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>ollieotc/Phaser-Snake_Game<file_sep>/assets/js/main.js window.onload = function(){ // 創建一個對象實例 var game = new Phaser.Game( 600 , 400 , Phaser.AUTO , 'gameDiv'); // 初始化 Menu state 對象 game.state.add('Menu', Menu); game.state.add('Game', Game); game.state.add('Game_Over', Game_Over); game.state.start('Menu'); } <file_sep>/README.md Phaser-Snake_Game ---- ### Snake_Game 貪吃蛇 ### 使用技術 ---- HTML5 + Phaser.js ### To start ---- HTML5 Game With Phaser.js.<file_sep>/assets/js/meun.js var Menu = { preload : function(){ this.load.image('menu','assets/img/menu.png'); }, create : function(){ // 添加一个按钮,點擊時調用 startGame() // button(x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame, group) this.add.button(0, 0, 'menu', this.startGame , this); }, startGame: function(){ this.state.start('Game'); }, }
62ac38b74974fb73df9ed73b3d37f1789c2d43af
[ "JavaScript", "Markdown" ]
3
JavaScript
ollieotc/Phaser-Snake_Game
62012d360cbdb0f6f5617260ccdfe8ddbbf19b17
61a132381eb49247d4403b45348ebcab9e554ace
refs/heads/main
<repo_name>HaneenKh88/RESTy<file_sep>/src/Form.js import { If, Then} from 'react-if'; import React from 'react'; const superagent = require('superagent'); class Form extends React.Component { constructor(props) { super(props); //initial state of the component this.state = { value: '', method: '', url: '', methodVal : '', Loading: false, }; // this line is needed if you create a function in the class without using arrow functions } handleclick = async (e) => { e.preventDefault(); await this.setState ({ url: e.target.url.value, methodVal: this.state.method }); try { console.log("state",this.state); let reqBody = e.target.body.value; this.setState({ Loading: true }) if (this.state.methodVal === 'POST' || this.state.methodVal === 'PUT' ) { const result = await superagent[this.state.methodVal.toLowerCase()]( e.target.url.value ).send(reqBody); console.log("this data" ,result ) this.props.handler( result, this.state); this.setState({ Loading: false }) } else { this.setState({ Loading: true }) const data= await superagent[this.state.methodVal.toLowerCase()](e.target.url.value); this.setState({ Loading: false }) this.props.handler(data, this.state) } } catch(error){ this.setState({ Loading: false }) console.error(error); this.props.handler(error.message , "Error in geting data") } }; componentDidMount () { let HomeData = JSON.parse(localStorage.getItem("data")) if(HomeData) { const inputURL = document.getElementById('url-input'); inputURL.value = HomeData.url; const inputMethod = document.getElementById(HomeData.method); inputMethod.click(); } } render() { return ( <main> <div className="Main-Class"> <form id= "form" onSubmit={this.handleclick}> <label>URL: </label> <input id="url-input" type="text" placeholder = "URL" name="url" /> <input id="GO" className = "GO" type="submit" value="GO!" /> <br></br> <br></br> <textarea type="text" name="body" placeholder="Request body..." rows="6" cols="40" /> <br></br> <br></br> <input id="GET" className={`method ${this.state.method === 'GET'}`} type="button"name= "method" value= "GET" onClick={() => this.setState({method: 'GET'})} /> <input id="POST" className={`method ${this.state.method === 'POST'}`} type="button" value= "POST" onClick={() => this.setState({method: 'POST'})} /> <input id="PUT" className={`method ${this.state.method === 'PUT'}`} type="button" value= "PUT" onClick={() => this.setState({method: 'PUT'})} /> <input id="DELETE" className={`method ${this.state.method === 'DELETE'}`} type="button" value= "DELETE" onClick={() => this.setState({method: 'DELETE'})} /> </form> <If condition={this.state.Loading === true}> <Then> <div id='loading'></div> <img id="loadingImg" src="https://media.istockphoto.com/videos/loading-circle-icon-on-white-background-animation-video-id1093418606?s=640x640" alt="loading"/> </Then> </If> </div> </main> ); } } export default Form;<file_sep>/src/home.js import React from 'react'; import Form from './Form'; import Result from './Result'; import History from './history'; let history = JSON.parse(localStorage.getItem('history')) || []; export class Home extends React.Component { constructor(props) { super(props); this.state = { result : [], count : 0, storageArray: history, }; } handleButton = (data, state) => { // this.setState({ result: data, count: number}); // console.log("state", state); console.log("data.body",data); if (data.headers && data.body) { let storageObj = { id: state.method+state.url, url: state.url, method: state.method, body: data.body, }; // console.log("storge" ,storageObj); this.state.storageArray.push(storageObj); console.log("storge" ,this.state.storageArray); const result = []; const map = new Map(); for (const item of this.state.storageArray) { if(!map.has(item.id)){ map.set(item.id, true); // set any value to Map result.push({ id: item.id, url: item.url, method: item.method, body: item.body, }); } } this.setState({ count: data.body.count || 0, result: data, storageArray: result, }); console.log("res",result); localStorage.setItem('history', JSON.stringify(result)); } else { this.setState({ // count: data.body.count || 0, result: data, }); } }; render() { return ( <> <Form handler={this.handleButton}/> <History result = {this.state.storageArray}/> <Result count= {this.state.count} result = {this.state.result}/> </> ); } } export default Home;<file_sep>/src/HistoryPage.js import React from 'react'; import ReactJson from 'react-json-view'; import { NavLink } from 'react-router-dom'; import { If, Then, Else } from '../src/if/index'; class HistoryPage extends React.Component { constructor(props) { super(props); this.state = { api: JSON.parse(localStorage.getItem('history')) || [], body: [], // trigger: false, // data:[], }; } dataHandling = (data) => { this.setState({ body: data }); console.log("data", data); localStorage.setItem('data', JSON.stringify(data)); }; // AutoHandler(e) { // let method = e.currentTarget.childNodes[0].innerHTML; // let url = e.currentTarget.childNodes[1].innerHTML; // console.log("target", e.currentTarget.childNodes[1].innerHTML); // console.log(e); // } render() { return ( <section id="history"> <h3 className="history"> History</h3> <table> <tbody> <If condition={this.state.api.length}> <Then> {this.state.api.map((val, i) => { return ( <tr key={i + val.method + val.url + val.body} data-testid="url" onClick={() => { this.dataHandling(val) }}> <td className="methodClass">{val.method}</td> <td>{val.url}</td> <NavLink to={{ pathname: '/', body: { method: this.state.body.method, url: this.state.body.url, data: this.state.body.data, }, }} > Re-Run </NavLink> </tr> ); })} </Then> </If> </tbody> </table> <div className="result"> <If condition={!this.state.body || this.state.body.length === 0}> <Then> <div>No data shown</div> </Then> <Else> {console.log(this.props.body)} <ReactJson src={this.state.headers} name="Headers" iconStyle={'circle'} collapsed={1} enableClipboard={false} displayDataTypes={false} IndentWidth={1} /> <ReactJson src={this.state} name="Response" iconStyle={'circle'} collapsed={1} enableClipboard={false} displayDataTypes={false} IndentWidth={1} /> </Else> </If> </div> </section> ); } } export default HistoryPage;<file_sep>/README.md # RESTy ### Deploy link on Netlify: [Netlify](https://609001320b164e9b26689a1e--rest-haneen88.netlify.app/) ### Pull Request Link [RESTy](https://github.com/HaneenKh88/RESTy/pull/6) **************************************************************************************************** ## UML Image: ![UML](https://github.com/HaneenKh88/RESTy/blob/main/assests/lab26.png) **************************************************************************************************** ## Setup: 1. Clone the repository. 2. install the react js library. 3. coding. 4. push the repo to the GitHub. <file_sep>/src/App.js import React from 'react'; import Header from './header'; import Main from './main'; import Footer from './footer'; import './style/header.scss'; import './style/Form.scss'; import './style/footer.scss'; import './style/Result.scss'; import './style/history.scss'; import './style/help.scss'; // let history = JSON.parse(localStorage.getItem('history')) || []; export class App extends React.Component { // constructor(props) { // super(props); // this.state = { // result : [], // count : 0, // storageArray: history, // }; // } // handleButton = (data, state) => { // // this.setState({ result: data, count: number}); // console.log("state", state); // // console.log("data.body",data.body); // if (data.headers && data.body) { // let storageObj = { // id: state.method+state.url, // url: state.url, // method: state.method, // body: state.body, // }; // console.log(storageObj); // this.state.storageArray.push(storageObj); // const result = []; // const map = new Map(); // for (const item of this.state.storageArray) { // if(!map.has(item.id)){ // map.set(item.id, true); // set any value to Map // result.push({ // id: item.id, // url: item.url, // method: item.method, // body: item.body, // }); // } // } // this.setState({ // count: data.body.count || 0, // result: data, // storageArray: result, // }); // console.log(this.state); // localStorage.setItem('history', JSON.stringify(result)); // } else { // this.setState({ // // count: data.body.count || 0, // result: data, // }); // } // }; render() { return ( <> <Header/> <Main /> <Footer/> </> ); } } export default App; <file_sep>/src/Help.js import React from 'react'; class Help extends React.Component { render() { return ( <div className="help"> <h1> Contact US ON: </h1> <br></br> <h3> 07978598200 </h3> <h3> <EMAIL> </h3> </div> ); }; } export default Help;<file_sep>/src/main.js import React from 'react'; import { Route, Switch } from 'react-router-dom'; import home from './home'; import HistoryPage from './HistoryPage'; import Help from './Help'; function Main() { return( <main> <Switch> <Route exact path="/" component={home}/> <Route path="/history" component={HistoryPage}/> <Route path="/help" component={Help}/> <Route> <div>404</div> </Route> </Switch> </main> ) } export default Main;
ba0a97ad9e1ba3afbec6434c748ebf1608e11396
[ "JavaScript", "Markdown" ]
7
JavaScript
HaneenKh88/RESTy
83b44bd6f9fbf997a42987add7d7fec9e5b82dcd
e3a4081970e88de50464a480fa68e910c90d17af
refs/heads/master
<file_sep>package com.caijia.download; /** * Created by cai.jia on 2018/7/5. */ public interface Schedule { void schedule(Runnable runnable); } <file_sep>package com.caijia.download; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by cai.jia on 2018/6/26. */ public class FileResponse { private InputStream byteStream; private Map<String, List<String>> headers; private String realDownloadUrl; private int httpCode; public InputStream getByteStream() { return byteStream; } public void setByteStream(InputStream byteStream) { this.byteStream = byteStream; } public Map<String, List<String>> getHeaders() { return headers; } public void setHeaders(Map<String, List<String>> headers) { this.headers = headers; } public String getRealDownloadUrl() { return realDownloadUrl; } public void setRealDownloadUrl(String realDownloadUrl) { this.realDownloadUrl = realDownloadUrl; } public boolean isSuccessful() { return httpCode >= 200 && httpCode < 300; } public long getContentLength() { String contentLength = Utils.getHeader("Content-Length", headers); long contentLengthLong = -1; try { contentLengthLong = Long.parseLong(contentLength); } catch (Exception e) { } return contentLengthLong; } public String getFileName() { String disposition = Utils.getHeader("Content-Disposition", headers); if (!Utils.isEmpty(disposition)) { Matcher m = Pattern.compile(".*filename=(.*)").matcher(disposition.toLowerCase()); if (m.find()) { try { return URLDecoder.decode(m.group(1), "utf-8"); } catch (Exception e) { return m.group(1); } } } else { int pathIndex = realDownloadUrl.lastIndexOf("\\"); if (pathIndex == -1) { pathIndex = realDownloadUrl.lastIndexOf("/"); } int whatIndex = realDownloadUrl.indexOf("?", pathIndex); return realDownloadUrl.substring(pathIndex + 1, whatIndex == -1 ? realDownloadUrl.length() : whatIndex); } return Utils.getMD5(realDownloadUrl) + ".temp";//默认取一个文件名; } public int getHttpCode() { return httpCode; } public void setHttpCode(int httpCode) { this.httpCode = httpCode; } } <file_sep>package com.caijia.download; public class DownloadState { public static final int IDLE = 0; public static final int START = 1; public static final int PREPARED = 2; public static final int DOWNLOADING = 3; public static final int PAUSING = 4; public static final int PAUSE = 5; public static final int COMPLETE = 6; public static String toName(int state) { String name = ""; switch (state) { case IDLE: name = "idle"; break; case PREPARED: name = "prepared"; break; case DOWNLOADING: name = "downloading"; break; case PAUSING: name = "pausing"; break; case PAUSE: name = "pause"; break; case COMPLETE: name = "complete"; break; } return name; } } <file_sep>package com.caijia.download; /** * Created by cai.jia on 2018/7/5. */ public interface DownloadListener { void onStart(CallbackInfo state); void onPrepared(CallbackInfo state); void onDownloading(CallbackInfo state); void onComplete(CallbackInfo state); void onPausing(CallbackInfo state); void onPause(CallbackInfo state); } <file_sep>#### 多线程断点下载,在极端网络下表现良好 ##### Android Studio添加 ``` allprojects { repositories { maven { url 'https://jitpack.io' } } } ``` ``` dependencies { implementation 'com.github.caijia:DownloadManager:0.23' } ``` ##### 使用 ``` FileRequest fileRequest = new FileRequest.Builder() .url("http://app.mi.com/download/656145") .build(); FileDownloader fileDownloader = new FileDownloader.Builder() .threadCount(threadCount) .saveFileDirPath(Environment.getExternalStorageDirectory().getAbsolutePath()) .fileRequest(fileRequest) .build(); ``` ##### 下载 ``` fileDownloader.download(downloadListener) ``` ##### 暂停 ``` fileDownloader.pause() ``` ##### 下载监听 ``` public interface DownloadListener { void onStart(CallbackInfo state); void onPrepared(CallbackInfo state); void onDownloading(CallbackInfo state); void onComplete(CallbackInfo state); void onPausing(CallbackInfo state); void onPause(CallbackInfo state); } ``` ##### 回调数据 CallbackInfo 方法 | 说明 --- | --- downloadPath | 文件下载路径 state | 下载状态{@link DownloadState} savePath | 保存的文件路径,只有当文件下载完后才有值 {@link DownloadState#COMPLETE} fileSize | 下载文件的总大小 downloadSize | 当前下载的总大小 speed | 下载的速度,单位是B/s,可以转换格式{@link Utils#formatSpeed(long)} ##### 回调方法 CallbackInfo 方法 | 说明 --- | --- onStart | 下载开始 onPrepared | 下载已准备好,此时知道下载文件的信息,包括大小等 onDownloading | 正在下载,进度条更新在这个方法里 onComplete | 下载完成 onPausing | 正在暂停中 onPause | 暂停了 <file_sep>package com.caijia.download; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * Created by cai.jia on 2018/6/26. */ public class FileRequest { private String url; private HttpMethod method; private Map<String, List<String>> headers; private Map<String, List<String>> queryParams; private Map<String, List<String>> fieldParams; private String bodyJsonString; private FileRequest() { } FileRequest(Builder builder) { this.url = builder.url; this.method = builder.method; this.headers = builder.headers; this.queryParams = builder.queryParams; this.fieldParams = builder.fieldParams; this.bodyJsonString = builder.bodyJsonString; if (Utils.isEmpty(url)) { throw new RuntimeException("url is null"); } if (this.method == null) { this.method = HttpMethod.GET; } } public static FileRequest toSampleRequest(String url) { return new Builder().method(HttpMethod.GET).url(url).build(); } public String getUrl() { return url; } public HttpMethod getMethod() { return method; } public Map<String, List<String>> getHeaders() { return headers; } public Map<String, List<String>> getQueryParams() { return queryParams; } public Map<String, List<String>> getFieldParams() { return fieldParams; } public String getBodyJsonString() { return bodyJsonString; } public Builder newBuilder() { return new Builder(this); } public static class Builder { private String url; private HttpMethod method; private Map<String, List<String>> headers; private Map<String, List<String>> queryParams; private Map<String, List<String>> fieldParams; private String bodyJsonString; public Builder() { } public Builder(FileRequest fileRequest) { this.url = fileRequest.url; this.method = fileRequest.method; this.headers = fileRequest.headers; this.queryParams = fileRequest.queryParams; this.fieldParams = fileRequest.fieldParams; this.bodyJsonString = fileRequest.bodyJsonString; } public Builder url(String url) { this.url = url; return this; } public Builder method(HttpMethod method) { this.method = method; return this; } public Builder bodyJsonString(String bodyString) { this.bodyJsonString = bodyString; return this; } public Builder header(String key, String value) { if (Utils.isEmpty(key) || Utils.isEmpty(value)) { return this; } headers = setValue(key, value, headers); return this; } public Builder header(String key, List<String> values) { if (!Utils.isEmpty(key) && values != null && !values.isEmpty()) { for (String value : values) { header(key, value); } } return this; } public Builder queryParams(String key, String value) { if (Utils.isEmpty(key) || Utils.isEmpty(value)) { return this; } queryParams = setValue(key, value, queryParams); return this; } public Builder queryParams(String key, List<String> values) { if (!Utils.isEmpty(key) && values != null && !values.isEmpty()) { for (String value : values) { queryParams(key, value); } } return this; } public Builder fieldParams(String key, String value) { if (Utils.isEmpty(key) || Utils.isEmpty(value)) { return this; } fieldParams = setValue(key, value, fieldParams); return this; } public Builder fieldParams(String key, List<String> values) { if (!Utils.isEmpty(key) && values != null && !values.isEmpty()) { for (String value : values) { fieldParams(key, value); } } return this; } private Map<String, List<String>> setValue(String key, String value, Map<String, List<String>> params) { if (params == null) { params = new HashMap<>(); } List<String> values = params.get(key); if (values == null) { values = new LinkedList<>(); params.put(key, values); } values.add(value); return params; } public FileRequest build() { return new FileRequest(this); } } } <file_sep>package com.caijia.download; import android.os.Handler; import android.os.Looper; /** * Created by cai.jia on 2018/7/5. */ public class AndroidSchedule implements Schedule { private Handler handler; public AndroidSchedule() { handler = new Handler(Looper.getMainLooper()); } @Override public void schedule(Runnable runnable) { handler.post(runnable); } } <file_sep>package com.caijia.download; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; /** * Created by cai.jia on 2018/6/26. */ public class FileDownloader { private static final float INTERVAL_DOWNLOAD = 1000f; private static final int MAX_THREAD_COUNT = 6; private Connection connection; private int threadCount = 3; private ExecutorService executorService; private FileRequest fileRequest; private String saveFileDirPath; private Schedule schedule; private boolean supportBreakPoint; private List<DownloadCallable> downloadCallableList; private List<FutureTask> downloadTasks; private BreakPointManager breakPointManager; private int pauseCount; private int completeCount; private long totalDownloadLength; private CallbackInfo callbackInfo; private DownloadListener downloadListener; private boolean isPausing; private long preComputeSpeedTime; private long preComputeSpeedLength; private float intervalDownload = INTERVAL_DOWNLOAD; private boolean debug; private FileDownloader() { } private FileDownloader(Builder builder) { callbackInfo = new CallbackInfo(); this.connection = builder.connection; this.debug = builder.debug; int maxThreadCount = builder.maxThreadCount; this.threadCount = builder.threadCount; this.saveFileDirPath = builder.saveFileDirPath; this.breakPointManager = builder.breakPointManager; this.supportBreakPoint = builder.supportBreakPoint; this.fileRequest = builder.fileRequest; this.schedule = builder.schedule; this.intervalDownload = builder.intervalDownload; if (this.connection == null) { this.connection = new OkHttpConnection(); } if (supportBreakPoint && this.breakPointManager == null) { this.breakPointManager = new FileBreakPointManager(); } if (maxThreadCount == 0 || maxThreadCount < 1) { maxThreadCount = MAX_THREAD_COUNT; } if (this.threadCount < 1) { this.threadCount = 1; } if (this.threadCount > maxThreadCount) { this.threadCount = maxThreadCount; } if (this.intervalDownload <= 0) { intervalDownload = INTERVAL_DOWNLOAD; } if (Utils.isAndroidPlatform()) { Utils.log(debug, "android platform"); this.schedule = new AndroidSchedule(); } if (Utils.isEmpty(saveFileDirPath)) { throw new RuntimeException("has not saveFileDirPath"); } downloadCallableList = new ArrayList<>(); downloadTasks = new ArrayList<>(); } public void download(DownloadListener downloadListener) { download(fileRequest, downloadListener); } public void download(FileRequest fileRequest, final DownloadListener downloadListener) { if (fileRequest == null || Utils.isEmpty(fileRequest.getUrl())) { throw new RuntimeException("please set " + FileRequest.class.getCanonicalName()); } if (!canDownload()) { return; } this.downloadListener = downloadListener; callbackInfo.setState(DownloadState.START); Runnable r = new Runnable() { @Override public void run() { downloadListener.onStart(callbackInfo); } }; schedule(r); this.fileRequest = fileRequest; reset(); requestDownFileInfo(); } private void reset() { isPausing = false; pauseCount = 0; completeCount = 0; preComputeSpeedTime = 0; preComputeSpeedLength = 0; totalDownloadLength = computePreviousLength(); downloadCallableList.clear(); downloadTasks.clear(); executorService = Executors.newCachedThreadPool(); } private long computePreviousLength() { long total = 0; for (int i = 0; i < threadCount; i++) { long length = breakPointManager != null ? breakPointManager.getDownloadLength(i, threadCount, saveFileDirPath, fileRequest) : 0; total += length; } return total; } public boolean canDownload() { int state = callbackInfo.getState(); return state == DownloadState.COMPLETE || state == DownloadState.PAUSE || state == DownloadState.IDLE; } private void requestDownFileInfo() { Callable<FileResponse> callable = new Callable<FileResponse>() { @Override public FileResponse call() throws Exception { FileRequest headRequest = fileRequest.newBuilder() .method(HttpMethod.GET) .build(); return connection.connect(headRequest); } }; FutureTask<FileResponse> task = new FutureTask<FileResponse>(callable) { @Override protected void done() { if (!isCancelled()) { try { FileResponse response = get(); if (response.isSuccessful()) { realDownload(response); } else { Utils.log(debug, "retry http code =" + response.getHttpCode()); retryRequestDownFileInfo(this); } } catch (Exception e) { Utils.log(debug, "retry error=" + e.getMessage()); retryRequestDownFileInfo(this); } } else { Utils.log(debug, "cancelled"); pauseCallback(); } } }; downloadTasks.add(task); executorService.submit(task); } private void retryRequestDownFileInfo(FutureTask<FileResponse> task) { if (isPausing) { pauseCallback(); return; } Utils.log(debug, "retry"); downloadTasks.remove(task); requestDownFileInfo(); } private void realDownload(FileResponse response) { if (response == null) { return; } long fileSize = response.getContentLength(); String fileName = response.getFileName(); String realDownloadUrl = response.getRealDownloadUrl(); fileRequest = fileRequest.newBuilder().url(realDownloadUrl).build(); if (fileSize < 0) { pauseCallback(); return; } if (Utils.isEmpty(fileName)) { pauseCallback(); return; } callbackInfo.setFileSize(fileSize); callbackInfo.setDownloadPath(realDownloadUrl); callbackInfo.setState(DownloadState.PREPARED); Runnable r = new Runnable() { @Override public void run() { downloadListener.onPrepared(callbackInfo); } }; schedule(r); File saveFileDir = new File(saveFileDirPath); saveFileDir.mkdirs(); if (fileSize < threadCount) { threadCount = (int) fileSize; } if (isPausing) { return; } for (int i = 0; i < threadCount; i++) { DownloadCallable callable = new DownloadCallable( saveFileDir, fileName, fileSize, connection, fileRequest, i, threadCount, breakPointManager, debug); downloadCallableList.add(callable); DownloadFutureTask task = new DownloadFutureTask(callable); downloadTasks.add(task); executorService.submit(task); } callbackInfo.setState(DownloadState.DOWNLOADING); Runnable r1 = new Runnable() { @Override public void run() { downloadListener.onDownloading(callbackInfo); } }; schedule(r1); } private void downloadLength(long downloadLength, long totalSize) { totalDownloadLength += downloadLength; long currTime = System.currentTimeMillis(); if (currTime - preComputeSpeedTime > intervalDownload || totalDownloadLength == totalSize) { if (preComputeSpeedTime != 0) { long deltaTime = currTime - preComputeSpeedTime; long deltaLength = totalDownloadLength - preComputeSpeedLength; long speed = (long) (deltaLength / (deltaTime / 1000f)); //(b/s) if (speed > 0) { long leftTime = (callbackInfo.getFileSize() - totalDownloadLength) / speed; callbackInfo.setLeftTime(leftTime); } callbackInfo.setSpeed(speed); callbackInfo.setDownloadSize(this.totalDownloadLength); Runnable r = new Runnable() { @Override public void run() { downloadListener.onDownloading(callbackInfo); } }; schedule(r); } preComputeSpeedTime = currTime; preComputeSpeedLength = totalDownloadLength; } } private synchronized void tryPauseCallback() { if (++pauseCount + completeCount == threadCount) { pauseCallback(); } } private void pauseCallback() { executorService.shutdown(); callbackInfo.setState(DownloadState.PAUSE); Runnable r = new Runnable() { @Override public void run() { downloadListener.onPause(callbackInfo); } }; schedule(r); } private synchronized void tryCompleteCallback(final String saveFilePath) { if (++completeCount + pauseCount == threadCount) { executorService.shutdown(); final boolean hasPause = pauseCount > 0; callbackInfo.setState(hasPause ? DownloadState.PAUSE : DownloadState.COMPLETE); Runnable r = new Runnable() { @Override public void run() { if (hasPause) { downloadListener.onPause(callbackInfo); } else { callbackInfo.setSavePath(saveFilePath); downloadListener.onComplete(callbackInfo); } } }; schedule(r); if (!hasPause && breakPointManager != null) { breakPointManager.release(); } } } private void schedule(Runnable r) { if (schedule != null) { schedule.schedule(r); } else { r.run(); } } public void pause() { int state = callbackInfo.getState(); if (state == DownloadState.PAUSE || state == DownloadState.COMPLETE || state == DownloadState.PAUSING) { return; } this.isPausing = true; callbackInfo.setState(DownloadState.PAUSING); Runnable r = new Runnable() { @Override public void run() { downloadListener.onPausing(callbackInfo); } }; schedule(r); for (DownloadCallable callable : downloadCallableList) { callable.exit(true); } for (FutureTask downloadTask : downloadTasks) { downloadTask.cancel(false); } } public static class Builder { private Connection connection; private int threadCount; private String saveFileDirPath; private BreakPointManager breakPointManager; private Schedule schedule; private FileRequest fileRequest; private float intervalDownload; private boolean debug; private int maxThreadCount; private boolean supportBreakPoint; public Builder connection(Connection connection) { this.connection = connection; return this; } public Builder supportBreakPoint(boolean supportBreakPoint) { this.supportBreakPoint = supportBreakPoint; return this; } public Builder maxThreadCount(int maxThreadCount) { this.maxThreadCount = maxThreadCount; return this; } public Builder threadCount(int threadCount) { this.threadCount = threadCount; return this; } public Builder debug(boolean debug) { this.debug = debug; return this; } public Builder intervalDownload(float intervalDownload) { this.intervalDownload = intervalDownload; return this; } public Builder saveFileDirPath(String saveFileDirPath) { this.saveFileDirPath = saveFileDirPath; return this; } public Builder breakPointManager(BreakPointManager breakPointManager) { this.breakPointManager = breakPointManager; return this; } public Builder schedule(Schedule schedule) { this.schedule = schedule; return this; } public Builder fileRequest(FileRequest fileRequest) { this.fileRequest = fileRequest; return this; } public FileDownloader build() { return new FileDownloader(this); } } private class DownloadFutureTask extends FutureTask<CallableResult> { private DownloadCallable callable; public DownloadFutureTask(DownloadCallable callable) { super(callable); this.callable = callable; callable.setDownloadProgressListener(new DownloadCallable.DownloadProgressListener() { @Override public void downloadProgress(int threadIndex, long downloadLength, long total) { downloadLength(downloadLength, total); } }); } @Override protected void done() { if (!isCancelled()) { try { CallableResult result = get(); int state = result.getState(); Utils.log(debug, callable.getThreadIndex(), DownloadCallable.stateToString(state)); switch (state) { case DownloadCallable.COMPLETE: tryCompleteCallback(result.getSaveFilePath()); break; case DownloadCallable.ERROR: retry(); break; case DownloadCallable.PAUSE: tryPauseCallback(); break; } } catch (Exception e) { Utils.log(debug, callable.getThreadIndex(), "error"); retry(); } } else { Utils.log(debug, callable.getThreadIndex(), "cancelled"); tryPauseCallback(); } } private void retry() { if (isPausing) { tryPauseCallback(); return; } //remove old downloadCallableList.remove(callable); downloadTasks.remove(this); //add new DownloadCallable newCallable = callable.newCallable(); DownloadFutureTask task = new DownloadFutureTask(newCallable); downloadCallableList.add(newCallable); downloadTasks.add(task); executorService.submit(task); Utils.log(debug, callable.getThreadIndex(), "retry"); } } } <file_sep>package com.caijia.download; /** * Created by cai.jia on 2018/7/4. */ public interface BreakPointManager { /** * 保存线程下载的长度 * * @param threadIndex 线程索引 * @param threadCount 线程个数 * @param downloadSize 线程下载的总长度 * @param saveFileDir 下载保存目录 * @param fileRequest 下载请求链接 */ void saveDownloadLength(int threadIndex, int threadCount, long downloadSize, String saveFileDir, FileRequest fileRequest); /** * 获取线程下载的长度 * * @param threadIndex 线程索引 * @param threadCount 线程个数 * @param saveFileDir 下载保存目录 * @param fileRequest 下载请求链接 * @return 线程下载的总长度 */ long getDownloadLength(int threadIndex, int threadCount, String saveFileDir, FileRequest fileRequest); /** * 资源释放 */ void release(); }
45996dee94815bbbd93b69a9df4a616837625f6c
[ "Markdown", "Java" ]
9
Java
caijia/DownloadManager
9e92832c4a50c05bff83d4962802394dfde60016
75b4942bfe5d66941d4d7f76b5cf4542dc67a2c2
refs/heads/master
<file_sep>// // NewPostViewController.swift // MyInstagram // // Created by <NAME> on 4/1/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class NewPostViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var postPhoto: UIImageView! @IBOutlet weak var captionTextField: UITextField! var photo: UIImage! var editedPhoto: UIImage! override func viewDidLoad() { super.viewDidLoad() captionTextField.delegate = self postPhoto.image = photo captionTextField.text = "Say something about your photo :)" // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func resize(image: UIImage, newSize: CGSize) -> UIImage { let resizeImageView = UIImageView(frame: CGRectMake(0, 0, newSize.width, newSize.height)) resizeImageView.contentMode = UIViewContentMode.ScaleAspectFill resizeImageView.image = image UIGraphicsBeginImageContext(resizeImageView.frame.size) resizeImageView.layer.renderInContext(UIGraphicsGetCurrentContext()!) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } @IBAction func onPost(sender: AnyObject) { // Post.postUserImage(resize(editedPhoto, newSize: CGSize(width: 100, height: 100)), withCaption: captionTextField.text!) { (success: Bool, error: NSError?) -> Void in Post.postUserImage(editedPhoto, withCaption: captionTextField.text!) { (success: Bool, error: NSError?) -> Void in if success { print("Posted") self.dismissViewControllerAnimated(true, completion: nil) } } } @IBAction func onCancel(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } func textFieldDidBeginEditing(textField: UITextField) { if (self.captionTextField.text == "Say something about your photo :)") { self.captionTextField.text = "" } } @IBAction func onTap(sender: AnyObject) { self.captionTextField.endEditing(true) } // func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { // // let currentCharacterCount = textField.text?.characters.count ?? 0 // if (range.length + range.location > currentCharacterCount){ // return false // } // let newLength = currentCharacterCount + string.characters.count - range.length // return newLength <= 25 // } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>// // HomeViewController.swift // MyInstagram // // Created by <NAME> on 4/1/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit import Parse import AFNetworking import MBProgressHUD class HomeViewController: UIViewController { var posts: [PFObject]? var refreshControl: UIRefreshControl! @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 120 // Initialize a UIRefreshControl refreshControl = UIRefreshControl() refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh") refreshControl.addTarget(self, action: "refreshControlAction:", forControlEvents: UIControlEvents.ValueChanged) tableView.insertSubview(refreshControl, atIndex: 0) refreshControlAction(refreshControl) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { refreshControlAction(refreshControl) } internal class Reachability { class func isConnectedToNetwork() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(&zeroAddress) { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) } var flags = SCNetworkReachabilityFlags() if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) { return false } let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0 let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 return (isReachable && !needsConnection) } } func refreshControlAction(refreshControl: UIRefreshControl) { if Reachability.isConnectedToNetwork() { dismissNetworkErr() requestPosts() } else { showNetworkErr() } refreshControl.endRefreshing() } func showNetworkErr(){ navigationItem.title = "Disconnected" } func dismissNetworkErr(){ navigationItem.title = "Linfinity Instagram" } func requestPosts() { let query = PFQuery(className: "Post") query.orderByDescending("createdAt") query.includeKey("author") query.limit = 20 // fetch data asynchronously if (refreshControl.refreshing) { refreshControl.beginRefreshing() } query.findObjectsInBackgroundWithBlock { (posts: [PFObject]?, error: NSError?) -> Void in if let posts = posts { print("successed to fetch posts") self.posts = posts for i in posts { print (i) } self.tableView.reloadData() self.refreshControl.endRefreshing() } else { print(error?.localizedDescription) } } } @IBAction func onNewPost(sender: AnyObject) { // 1 let optionMenu = UIAlertController(title: nil, message: "Choose Option", preferredStyle: .ActionSheet) // 2 let deleteAction = UIAlertAction(title: "Take Photo", style: .Default, handler: { (alert: UIAlertAction!) -> Void in print("Take photo") let vc = UIImagePickerController() vc.delegate = self vc.allowsEditing = true vc.sourceType = UIImagePickerControllerSourceType.Camera self.presentViewController(vc, animated: true, completion: nil) }) let saveAction = UIAlertAction(title: "Choose from Photos", style: .Default, handler: { (alert: UIAlertAction!) -> Void in print("Choose photos") let vc = UIImagePickerController() vc.delegate = self vc.allowsEditing = true vc.sourceType = UIImagePickerControllerSourceType.PhotoLibrary self.presentViewController(vc, animated: true, completion: nil) }) // let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: { (alert: UIAlertAction!) -> Void in print("Cancelled") }) // 4 optionMenu.addAction(deleteAction) optionMenu.addAction(saveAction) optionMenu.addAction(cancelAction) // 5 self.presentViewController(optionMenu, animated: true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } ////////// table \\\\\\\\\\ extension HomeViewController: UITableViewDataSource, UITableViewDelegate { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let count = self.posts?.count if let count = count { return count } else { return 0 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("PostCell", forIndexPath: indexPath) as! PostTableViewCell let query = PFQuery(className: "Post") query.orderByDescending("createdAt") query.includeKey("author") query.limit = 20 // fetch data asynchronously cell.post = self.posts![indexPath.row] return cell } } extension HomeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { // Get the image captured by the UIImagePickerController let originalImage = info[UIImagePickerControllerOriginalImage] as! UIImage let editedImage = info[UIImagePickerControllerEditedImage] as! UIImage // Dismiss UIImagePickerController to go back to your original view controller dismissViewControllerAnimated(true, completion: nil) let storyboard = UIStoryboard(name: "Main", bundle: nil) let navigation = storyboard.instantiateViewControllerWithIdentifier("NewPostNavigationController") as! UINavigationController let newPostViewController = navigation.topViewController as! NewPostViewController newPostViewController.photo = originalImage newPostViewController.editedPhoto = editedImage presentViewController(navigation, animated: false, completion: nil) } } <file_sep>// // PostTableViewCell.swift // MyInstagram // // Created by <NAME> on 4/1/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit import ParseUI class PostTableViewCell: UITableViewCell { @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var photoView: PFImageView! @IBOutlet weak var captionLabel: UILabel! var post: PFObject! { didSet { let user = post["author"] as? PFUser self.usernameLabel.text = user?.username // usernameLabel.sizeToFit() self.photoView.file = post["media"] as? PFFile self.photoView.loadInBackground() self.captionLabel.text = post["caption"] as? String // captionLabel.sizeToFit() } } override func awakeFromNib() { super.awakeFromNib() captionLabel.preferredMaxLayoutWidth = captionLabel.frame.size.width // Initialization code } override func layoutSubviews() { super.layoutSubviews() captionLabel.preferredMaxLayoutWidth = captionLabel.frame.size.width } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(false, animated: animated) // Configure the view for the selected state } }
3c8a77cfb693c8f475ee8502c3370b49d0b5c501
[ "Swift" ]
3
Swift
LinfinityLab/CodePath-iOS-App-MyInstagram
f5a3b6a7c113767291063667a24dfa61a97fcf64
eae88bab431bfccd606819ad9afe7c05a7910a02
refs/heads/master
<repo_name>marvinjude/pwa-react-workbox<file_sep>/src/App.js import React from "react"; import brandImg from "./hashtag.gif"; class App extends React.Component { constructor(props) { super(props); this.state = this.getInitialState(); } getInitialState = () => ({ online: navigator.onLine, users: [], fetching: true }); componentDidMount() { //Reister Listener for online/offline state window.addEventListener("online", () => { this.setState({ online: true }); }); window.addEventListener("offline", () => { this.setState({ online: false }); }); fetch("https://my-json-server.typicode.com/marvinjude/json-api/speakers/") .then(response => response.json()) .then(users => { this.setState({ users, fetching: false }); }) .catch(error => { console.log("An error occured"); this.setState({ fetching: false }); }); } componentWillUnmount() { window.removeEventListener("online"); window.removeEventListener("offline"); } render() { return ( <> <header style={styles.header}> <img alt="brand" src={brandImg} style={styles.logo} /> </header> {(!this.state.fetching && ( <> <div style={ this.state.online ? styles.networkStat__online : styles.networkStat__offline } > {this.state.online ? "Online" : "Offline"} </div> <div style={styles.container}> {!this.state.fetching && this.state.users.map(({ name, bio, talk }) => ( <div style={styles.card}> <div style={{ ...styles.circle, ...RandomColor() }} /> <div> <h3>{name}</h3> <p style={styles.smallText}>{bio}</p> <p>{talk}</p> </div> </div> ))} </div> </> )) || ( <div style={{ height: "calc(100% - 50px)", flex: "1 1 0", justifyContent: "center", alignItems: "center", display: "flex" }} > <div class="loader"> <svg class="circular" viewBox="25 25 50 50"> <circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="2" stroke-miterlimit="10" /> </svg> </div> </div> )} </> ); } } //Styles const networkStat = { padding: "10px", position: "absolute", bottom: "0", fontWeight: "bold", left: "0", width: "100%", color: "white" }; const styles = { logo: { height: "100%" }, header: { height: "50px", width: "100%", backgroundColor: "white", boxShadow: "0 3px 5px rgba(57, 63, 72, 0.3)", display: "flex", justifyContent: "center" }, networkStat__online: { ...networkStat, backgroundColor: "green" }, networkStat__offline: { ...networkStat, backgroundColor: "#db3236" }, circle: { width: "3rem", backgroundColor: RandomColor(), height: "3rem", borderRadius: "50%", marginRight: "10px", flexShrink: "0" }, smallText: { fontWeight: "200", color: "gray", fontSize: "0.85rem" }, container: { display: "flex", flexDirection: "column" }, card: { margin: "5px", backgroundColor: "white", padding: "10px", borderRadius: "5px", display: "flex" } }; export default App; function RandomColor() { const R = Math.round((Math.random() * 1000) % 255); const G = Math.round((Math.random() * 1000) % 255); const B = Math.round((Math.random() * 1000) % 255); return { backgroundColor: `rgb(${R}, ${G}, ${B})` }; } <file_sep>/src/sw.js importScripts("workbox-v4.3.1/workbox-sw.js"); workbox.setConfig({ modulePathPrefix: "workbox-v4.3.1/" }); const precacheManifest = []; workbox.precaching.precacheAndRoute(precacheManifest); //Cache fetch reqquest: const dataCacheConfig = { cacheName: "data" }; //Cache our speakers workbox.routing.registerRoute(/.*speakers/ , workbox.strategies.cacheFirst(dataCacheConfig), 'GET') <file_sep>/steps.md ## 1. Add Manifest.json to public directory yarn build ## 2. generate config workbox wizard ## 3 Generate workbox config <!-- CRA's `register()` stop here --> `workbox generateSW workbox-config.js` ## 4. Create Custom service worker in `src/sw.js` with boilerplate , while sourcing workbox locally ```js importScripts("workbox-v4.3.1/workbox-sw.js"); workbox.setConfig({ modulePathPrefix: "workbox-v4.3.1/" }); const precacheManifest = []; workbox.precaching.precacheAndRoute(precacheManifest); ``` ## 5. Modify workbox-config to point to custom sw and injectionPointRegexp ```json { "swSrc": "src/sw.js", "injectionPointRegexp": /(const precacheManifest = )\[\](;)/ } ``` ## 6. Load sw from index.html or index.js - (it doesn't make sense so do PWA thing when we aren't running build) ```js const isProduction = "%NODE_ENV%" === "production"; if (isProduction && "serviceWorker" in navigator) { navigator.serviceWorker.register("sw.js"); } ``` ## 7. Rebuild ## 8. Add start-sw to package.json `"start-sw": "workbox copyLibraries build/ && workbox injectManifest workbox-config.js && http-server build/ -c-1"` `yarn start-sw` ## 9. Cache data from API ```js const dataCacheConfig = { cacheName: "data" }; workbox.routing.registerRoute( /.\*speakers/, workbox.strategies.cacheFirst(dataCacheConfig), "GET" ); ```
08b2bf2bbd246be456ad9e797c712b04b386950e
[ "JavaScript", "Markdown" ]
3
JavaScript
marvinjude/pwa-react-workbox
f95f039a013d3aaa39d1cd032c6f4cd9313c3572
f2a81da20d151d64abdfba84eefc0db8fc1f15ae
refs/heads/master
<repo_name>black09bb/PayAngular<file_sep>/src/app/pages/users/users.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { environment } from '../../../environments/environment'; import { environmentLocalhost } from './../../../environments/environmentLocalhost'; @Injectable({ providedIn: 'root' }) export class UsersService { private url = `${environmentLocalhost.url}users`; constructor(private http: HttpClient) {} getList() { return this.http.get(this.url); } } <file_sep>/src/app/pages/users/users.module.ts import { MatTableModule } from '@angular/material/table'; import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { EditComponent } from './edit/edit.component'; import { ListComponent } from './list/list.component'; import { AddComponent } from './add/add.component'; import { Routes, RouterModule } from '@angular/router'; const routes: Routes = [ { path: 'list', component: ListComponent }, { path: 'add', component: AddComponent }, { path: 'edit', component: EditComponent }, { path: '', redirectTo: 'list', pathMatch: 'full' } ]; @NgModule({ imports: [ CommonModule, RouterModule.forChild(routes), MatTableModule ], declarations: [AddComponent, EditComponent, ListComponent] }) export class UsersModule { } <file_sep>/src/app/pages/users/list/list.component.ts import { UsersService } from './../users.service'; import { Component, OnInit } from '@angular/core'; const colums: string[] = ['ID', 'Imię', 'Nazwisko', 'Email', 'Ilość projektów', 'Edycja', 'Usuwanie']; @Component({ selector: 'app-list', templateUrl: './list.component.html', styleUrls: ['./list.component.css'] }) export class ListComponent implements OnInit { displayedColumns: string[] = ['ID', 'name', 'surname', 'email', 'numberOfProjects']; dataSource; constructor( private usersService: UsersService ) {} ngOnInit() { return this.usersService.getList().subscribe(res => { this.dataSource = res; this.dataSource = this.dataSource.users; console.log(this.dataSource); }); } }
eb11b23aa967163fac2c2052b88ee423cb7e47b6
[ "TypeScript" ]
3
TypeScript
black09bb/PayAngular
1b87af4ed4e6b57c1dc642407af1511d54a802fc
7f6c76ada1dd7ddf9b01ac916306fb0fd2518580
refs/heads/master
<file_sep>const { sayHello } = require("./lib/index"); console.log(sayHello("mjs")); <file_sep>"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.sayHello = sayHello; function sayHello(params) { return `Hello ${params}`; }<file_sep># node-mjs-transpilrr [![Build Status](https://travis-ci.org/rjoydip/node-mjs-transpilr.svg?branch=master)](https://travis-ci.org/rjoydip/node-mjs-transpilr) [![codecov](https://codecov.io/gh/rjoydip/node-mjs-transpilr/badge.svg?branch=master)](https://codecov.io/gh/rjoydip/node-mjs-transpilr?branch=master) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/xojs/xo) > Transpile node .mjs files using babel transpiler ## Install ``` $ git clone https://github.com/rjoydip/node-mjs-transpilr.git $ cd node-mjs-transpilr $ npm install $ npm start ``` ## Test ``` $ npm test ``` ## Usage ```js 'use strict'; const _ = require('./lib'); _.sayHello('unicorns'); //=> Hello unicorns ``` ## License MIT © [<NAME>](https://github.com/rjoydip) <file_sep>export function sayHello(params) { return `Hello ${params}`; } <file_sep>import test from 'ava'; test('Node Mjs Transpile sayHello', t => { t.is(require('./lib').sayHello('unicorns'), 'Hello unicorns'); });
13939019ef07bd7b83d1182992eca66efb267550
[ "JavaScript", "Markdown" ]
5
JavaScript
rjoydip-zz/node-mjs-transpiler
23d086e1aff3543a3ac4c61a205561e2005ecbaf
87be19a51867cb7e0dbf2dfbe7538c9adb9b66ed
refs/heads/main
<file_sep>import subprocess from pynput import keyboard notes = {} def run_process(command): return subprocess.Popen(command, shell = True) def stop_notes(key): global notes run_process("pkill sox") notes = {} def play_note(key): global notes try: note = int(key.char) except: stop_notes(None) exit() if not note in notes: command = f"sox --buffer 256 -c 1 -r 48000 -t alsa default -t alsa default pitch {note*100} &> /dev/null" notes[note] = run_process(command) # Collect events until released with keyboard.Listener( on_press=play_note, on_release=stop_notes) as listener: listener.join() <file_sep># Harmonizer Real time microphone harmonizer inspired on <NAME>'s keyboard. It relies on the great Sound eXchange (SoX) command line tool. [![IMAGE ALT TEXT HERE](https://i.ytimg.com/vi/DnpVAyPjxDA/hqdefault.jpg)](https://youtu.be/DnpVAyPjxDA?t=30) ## How it works This is a work in progress. The script waits for number keys to be pressed, then triggers a process that runs [sox](https://en.wikipedia.org/wiki/SoX) with a pitch shift. ## Requirements I tested it only in linux, help adding compatibility for other platforms is very welcomed :) - sox: (If you are in ubuntu it'd be like this `sudo apt install sox`) - python 3 - python libraries (Try something like: `pip3 install -r requirements.txt`) ## Usage Run the script and then press some numbers in the keyboard. ```bash python3 harmonizer.py ``` For example if you keep pressed 0, 4 and 7 it should make a major chord. But 0, 3 and 7 make a minor chord. It's because 0 is the root note here, the second semitone is 1 and so on. Press any letter key to exit, 'q' for example.
239981f1acc9b648c878c3369974d2a8485200d2
[ "Markdown", "Python" ]
2
Python
mathigatti/harmonizer
67f6d91165874187f67320b9aa03ef1e9dabeabf
b10cfac5d837005858fd5eea28912d08544c72f5
refs/heads/masterbranch
<file_sep>// // const mongoose = require('mongoose') // // const Schema = mongoose.Schema const mongoose = require('mongoose'); const Schema = mongoose.Schema; const photoSchema = new Schema({ path: { type: String }, caption: { type: String } }); module.exports = mongoose.model('image', photoSchema); // const ImageSchema = new Schema ({ // path: { type: String }, // caption: { type: String } // }); // const Image = mongoose.model('image',ImageSchema); // module.exports = Image // const mongoose = require('mongoose'); // const Schema = mongoose.Schema; // const ImageSchema = new Schema({ // path: { type: String }, // caption: { type: String } // }); // module.exports = mongoose.model('image', ImageSchema); // // const ImageSchema = new Schema({ // // user: { // // type: Schema.Types.ObjectId, // // ref: 'users' // // }, // // imageName:{ // // type: String, // // default: "none", // // // required: true // // }, // // imageData: { // // type: String, // // } // // }); // // const Image = mongoose.model('image',ImageSchema) // // module.exports = Image // // module.exports = Image = mongoose.model('Image',ImageSchema) <file_sep> import React, { Component } from 'react' import Moment from 'react-moment' import {deleteEducation} from '../../actions/profileActions' import {connect} from 'react-redux' class Education extends Component { onDelete(id){ this.props.deleteEducation(id) } render() { const education = this.props.education.map(edu => ( <tr key ={edu._id}> <td>{edu.school}</td> <td>{edu.degree}</td> <td>{edu.fieldofstudy}</td> <td>{edu.description}</td> <Moment format = "DD/MM/YYYY">{edu.from}</Moment> - {edu.to === null ? ' Now' : <Moment format = "DD/MM/YYYY">{edu.to}</Moment>} <td> <button onClick = {this.onDelete.bind(this,edu._id)} className ="btn btn-danger">Delete</button> </td> </tr> )) return ( <div> <h4 className= "mb-4"> Education Credentials </h4> <table className="table"> <thead> <tr> <th>School</th> <th>Degree</th> <th>Field of study</th> <th>Description</th> <th>Years DD/MM/YYYY</th> </tr> {education} </thead> </table> </div> ) } } export default connect(null,{deleteEducation})(Education)<file_sep>// const express = require('express'); // const Image = require('../../models/Image'); // const ImageRouter = express.Router(); // const multer = require ('multer'); // const router = express.Router() // const path = require('path') // const crypto = require('crypto') // const mongoose = require('mongoose') // const GridFsStorage = require('multer-gridfs-storage') // const Grid = require('gridfs-stream') // const methodOverride = require('method-override') // const bodyParser = require('body-parser') // // const fs = require('fs') // router.use(bodyParser.json()) // router.use(methodOverride('_method')) // const mongoURI = 'mongodb://localhost:27017/expartsforum' // const conn = mongoose.createConnection(mongoURI) // let gfs // conn.once('open', () => { // //ini Stream // debugger // gfs = Grid(conn.db, mongoose.mongo); // gfs.collection('uploads'); // }) // // set storage Engine // const storage = new GridFsStorage({ // url: mongoURI, // file:( req, file) => { // return new Promise(( resolve,reject) => { // crypto.randomBytes(16 ,(err,buf) =>{ // if(err) { // // return reject(err) // debugger // console.log(err,'error') // } // const filename = buf.toString('hex') + path.extname(file.originalname) // debugger // const fileInfo = { // filename: filename, // bucketName :'uploads' // }; // resolve(fileInfo); // }) // }) // } // }) // const image = multer({storage}) // // const Image = require('../../models/Image'); // router.route('/') // .post(image.single('file'), function(req, res) { // const new_img = new Image({ // path :req.body.path, // caption: req.body.caption // }); // // new_img.img.data = fs.readFileSync(req.file.path) // // new_img.img.contentType = 'image/jpeg'; // new_img.save(); // res.json({ message: 'New image added to the db!' }); // }) // // const storage = multer.diskStorage({ // // destination: './public/uploads/', // // filename: function(req,file, cb) { // // cb(null,file.fieldname + '-'+ Date.now() + path.extname(file.originalname)) // // } // // }); // // const upload = multer({ // // storage: stroage // // }).single('multerImage') // // storing image to db and creating a disck strage or relationship // // and also file fiter for the image to be uploaded // // const storage = multer.diskStorage({ // // destination: function(req,file,cb){ // // cb(null, './uploads/') // // }, // // filename: function(req,file,cb) { // // cb(null, Date.now() + file.originalname) // // } // // }); // // const fileFilter = (req, file,cd) => { // // if (file.mimetype ==='image/jpeg' || file.mimetype === 'image/png') { // // cb(null,true) // // } else { // // cb(null,false) // // } // // } // // const upload = multer ({ // // storage: storage, // // limits: { // // fileSize: 1024 * 1024 * 5 // // }, // // fileFilter: fileFilter // // }); // // // storing file and creating refrence to stored image // // //uploadmulter // // ImageRouter.route('/') // // .post(upload.single('imageData'), (req,res,next) => { // // console.log(req.body); // // const newImage = newImage({ // // imageName: req.body.imageName, // // imageData: req.file.path // // }); // // newImage.save // // .then((results) =>{ // // console.log(result) // // res.status(200).json({ // // success:true, // // document:result // // }) // // }) // // .catch((err) => next(err)) // // }); // // const path = require("path"); // // // const multer = require("multer"); // // const storage = multer.diskStorage({ // // destination: "./public/uploads/", // // filename: function(req, file, cb){ // // cb(null,"IMAGE-" + Date.now() + path.extname(file.originalname)); // // } // // }); // // const upload = multer({ // // storage: storage, // // limits:{fileSize: 1000000}, // // }).single("myImage"); // // // const router = express.Router(); // router.post('/', (req,res) => res.json({msg: 'profiles works'})) // module.exports = router; <file_sep> const Validator = require ('validator'); const isEmpty = require ('./is-empty'); module.exports = function employerRegValidation(info) { let errors = {}; info.name = !isEmpty(info.name) ? info.name : ''; info.email = !isEmpty(info.email) ? info.email : ''; info.password = !isEmpty(info.password) ? info.password : ''; info.password2 = !isEmpty(info.password2) ? info.password2 : ''; if (!Validator.isLength(info.name, {min: 2, max: 20})){ errors.name ='Name must be between 2 and 20 characters'; } if (Validator.isEmpty(info.name)) { errors.name = 'Please Enter empl Name'; } if (!Validator.isEmail(info.email)) { errors.email = 'Invalid emp Email'; } if (Validator.isEmpty(info.password)) { errors.password = '<PASSWORD> emp[ <PASSWORD>'; } if (Validator.isEmpty(info.password2)) { errors.password2 = '<PASSWORD>'; } if (!Validator.equals(info.password, info.password2)) { errors.password2 = '<PASSWORD>'; } if (!Validator.isLength(info.password, {min: 5, max : 10})) { errors.password = 'Password must be betwen 2 nd 20 characters'; } return { errors, isValid : isEmpty(errors) } } <file_sep> const Validator = require ('validator'); const isEmpty = require ('./is-empty'); module.exports = function validateExperienceInput(data) { let errors = {}; data.title = !isEmpty(data.title) ? data.title : ''; if (Validator.isEmpty(data.title)) { errors.title = 'Occupation Title is reqired'; } return { errors, isValid : isEmpty(errors) } } <file_sep> if(process.env.NODE_ENV === 'production') { module.exports = require('./keys_prod') } else { module.exports = require('./keys_dev') } // fix the login so the user know email is correct but password is wrong // fix reciver password <EMAIL> <PASSWORD> // fix router.delete post not yet done // fix retrieve password if password is lost // fix show password is incorrect. <file_sep> // const mongoose = require('mongoose'); // const Schema = mongoose.Schema; // // schemas // const UserrSchema = new Schema ({ // name:{ // type: String, // required: true // }, // email: { // type: String, // required: true // }, // password: { // type: String, // required: true // }, // date: { // type: String, // default: Date.now // } // }); // module.exports = Userr = mongoose.model('user',UserrSchema) // need to rechek schema for // const mongoose = require('mongoose'); // const Schema = mongoose.Schema; // const photoSchema = new Schema({ // path: { type: String }, // caption: { type: String } // }); // module.exports = mongoose.model('image', photoSchema); const mongoose = require('mongoose'); const Schema = mongoose.Schema; // schemas const EmployerSchema = new Schema ({ name:{ type: String, required: true }, email: { type: String, required: true }, password: { type: String, required: true }, avatar: { type: String, }, date: { type: String, default: Date.now }, }); module.exports = Employer = mongoose.model('employer',EmployerSchema)<file_sep>const Validator = require('validator') const isEmpty = require('./is-empty') module.exports = function validateskillinput(info){ let errors = {} info.empskillreq = !isEmpty(info.empskillreq)? info.empskillreq :""; info.minedureq = !isEmpty(info.minedureq) ? info.minedureq : ''; if(Validator.isEmpty(info.empskillreq)){ errors.empskillreq = " skills are required" } if(Validator.isEmpty(info.minedureq)){ errors.minedureq = " minimum Education is required" } return { errors, isValid: isEmpty(errors) } } // const Validator = require('validator'); // const isEmpty = require('./is-empty'); // module.exports = function validateskillinput(info) { // let errors = {}; // info.empskillreq = !isEmpty(info.empskillreq) ? info.empskillreq : ''; // info.minedureq = !isEmpty(info.minedureq) ? info.minedureq : ''; // if (Validator.isEmpty(info.empskillreq)) { // errors.empskillreq = 'full name is required'; // } // if (Validator.isEmpty(info.minedureq)) { // errors.minedureq = 'companybio field is required'; // } // // we need to check if the website and email fields // // are empty before checking if its a valid URL // return { // errors, // isValid: isEmpty(errors) // }; // }; <file_sep>import React, { Component } from 'react' import {connect} from 'react-redux' import {withRouter} from 'react-router-dom' import { uploadImage } from '../../actions/authActions'; class upload extends Component { state = { multerImage : null, errors: {} } handleSubmit = (e) => { e.preventDefault() const {multerImage} = this.state console.log('image submitted',multerImage) this.props.uploadImage(multerImage, this.props.history) } handleChange = (e)=> { // console.log(e.target.files[0]) console.log(e.target.files[0]) this.setState({ multerImage : e.target.files[0] }) } render() { // const{errors} = this.state return ( // <div className ="upload"> // <div> // <form action="#"/> // <div class="file-field input-field"> // <div class="btn"/> // <span>File here </span> // <input type="file"></input> // </div> // <div class="file-path-wrapper"> // <input class="file-path validate" type="text"/> // </div> // </div> // </div> <div className = "upload"> <div> <h4>IMAGE HERE</h4> <input type="file" className="process_upload-btn" onChange = {this.handleChange}/> <button className ="btn-btn-blue" onClick = {this.handleSubmit}> Submit photo</button> </div> {/* <img src ={this.state.multerImage} alt="upload-image" className ="process_image" /> */} {/* onChange = {(e) =>this.uploadImage(e,"multer")} */} {/* <form onSubmit = {this.onSubmit}/> */} </div> ) } } const mapStateToProps = state => ({ multerImage : state.multerImage, errors: state.errors }) export default connect (mapStateToProps,{uploadImage})(withRouter(upload)) // import React, { Component } from 'react' // import axios from 'axios' // // import { throws } from 'assert'; // class upload extends Component { // constructor(props){ // super(props) // // this.state = { // // multerImage: DefaultImg // // } // } // // setDefaultImage(uploadType) { // // if(uploadType === "multer") { // // this.setState({ // // multerImage:DefaultImg // // }) // // } // // } // render() { // // if (method ==="multer") { // // let imageObj ={} // // } // // if (method === "multer") { // // let imageFormObj = new FormData() // // imageFormObj.append('imageName', 'multer-image-' + Date.now()) // // imageFormObj.append('imageData', e.target.files[0]); // // this.setState({ // // multerImage: URL.createObjectURL(e.target.files[0]) // // }); // // axios.post(`${API_URL}/image/uploadmulter`, imageFormObj) // // .then((data) => { // // if (data.data.success) { // // alert("image uploaded done") // // this.setDefaultImage("multer") // // } // // }) // // .catch((err) => { // // alert("Error while uploading") // // this.setDefaultImage("multer") // // }) // // } // return ( // <div> // <h2> IMAGE HERE </h2> // {/* <div className = "process"> // <h4 className = "process_heading"> Process: Using Multer</h4> // <p className="process_details">upload image to node server</p> // <input type="file" className="process_upload-btn" onChange = {(e) =>this.uploadImage(e,"multer")}/> // <img src ={this.state.multerImage} alt="upload-image" className ="process_image" /> // </div> */} // </div> // ) // } // } // export default upload<file_sep> const Validator = require ('validator'); const isEmpty = require ('./is-empty'); module.exports = function validatePostInput(data) { let errors = {}; data.text = !isEmpty(data.text) ? data.text : ''; if (!Validator.isLength(data.text, {min: 5, max: 200})){ errors.text ='comments text must be between 5 and 200 characters'; } if (Validator.isEmpty(data.text)) { errors.text = 'text section is mandatory'; } return { errors, isValid : isEmpty(errors) } } <file_sep> import React, { Component } from 'react' import {Link,withRouter} from 'react-router-dom' import { connect } from 'react-redux'; // import InputGroup from '../common/InputGroup'; import TextFieldGroup from '../common/TextFieldGroup'; import TextAreaFieldGroup from '../common/TextAreaFieldGroup'; import { createExperience } from '../../actions/profileActions'; class AddExperience extends Component { constructor(props) { super(props) this.state = { company: '', title: '', location: '', from: '', to: '', current: false, description: '', errors: {}, disabled: false } } componentWillReceiveProps(newProps) { if(newProps.errors) { console.log('ther are errors') this.setState({errors:newProps.errors}) } } onSubmit = (e)=> { e.preventDefault(); const newExperience = { company: this.state.company, title: this.state.title, location: this.state.location, from: this.state.from, to: this.state.to, current: this.state.current, description: this.state.description }; this.props.createExperience(newExperience, this.props.history); } onChange = (e) => { this.setState({ [e.target.name]: e.target.value }); } onCheck = (e) => { this.setState({ disabled: !this.state.disabled, current: !this.state.current }); } render() { const {errors} = this.state return ( <div> <div className = "Add-Experiece"> <div className ="container"> <div className = "row"> <div className="col-md-8 m-auto"> <Link to = '/dashboard'><button className = 'btn btn-light'>Go back</button></Link> <h1> Add Current Experience</h1> <p>Add your recent Work Experience</p> <form onSubmit = {this.onSubmit}> <TextFieldGroup placeholder=" Current Company" name="company" value={this.state.company} onChange={this.onChange} error={errors.company} /> <TextFieldGroup placeholder = " Job title" name= "title" value={this.state.title} onChange={this.onChange} error = {errors.title} /> <TextFieldGroup placeholder = " Present location" name= "location" value={this.state.location} onChange ={this.onChange} error = {errors.location} /> <h6>From Date</h6> <TextFieldGroup name= "from" type="date" value={this.state.from} onChange ={this.onChange} error = {errors.from} /> <h6>to Date</h6> <TextFieldGroup name= "to" type ="date" value={this.state.to} onChange ={this.onChange} error = {errors.to} disabled = {this.state.disabled ? 'disabled' : ''} /> <h6>Current Date</h6> <div className ="form-check mb-4"> <input type="checkbox" className="form-check-input" name="current" value={this.state.current} checked={this.state.current} onChange={this.onCheck} id="current" /> <label htmlFor="current" className ="form-check-label"> Current Job </label> </div> <TextAreaFieldGroup placeholder = "Experence description" name= "description" value={this.state.description} error = {errors.description} onChange ={this.onChange} info ="tell us about your current and previoys experience" /> <input type="submit" value="Submit" className="btn btn-info btn-block mt4"/> </form> </div> </div> </div> </div> </div> ) } } const mapStateToProps = state => ({ profile:state.profile, errors:state.errors }) export default connect (mapStateToProps, {createExperience})(withRouter(AddExperience)) <file_sep># Expertsforum expartsform is a social media / Job app for exparts in the Netherlands. to start this back end nodemon run server npm run server entry route is index.js npm start react front end ### START APP npm start app for react front end npm run server for node back end "nodemon" npm start app "starts without nodemon" ### INSTALL DEPENDENCIES npm install ### client = React front end and expertsforum-backend = node.js back-end MERN Stack Application ### Still under construction ### Developer and experts job portal forum ### NODE VERSION Node version 11.10.0 <file_sep> ### TO START APP npm start app ### TO INSTALL DEPENDENCIES npm install ### Experts Forum client React Front end ### Still under construction ### Developer and Experts Job portal forum<file_sep> // import React, { Component } from 'react' // import { connect } from 'react-redux'; // import { withRouter, Link } from 'react-router-dom'; // import PropTypes from 'prop-types'; // import TextFieldGroup from '../common/TextFieldGroup'; // import TextAreaFieldGroup from '../common/TextAreaFieldGroup'; // import InputGroup from '../common/InputGroup'; // import SelectListGroup from '../common/SelectListGroup'; // import { createEmployerProfile } from '../../actions/profileActions'; // class CreateEmpProfile extends Component { // constructor(props){ // super(props); // this.state ={ // displaySocialField: false, // fullname :'', // companyname: '', // hiringlocation: '', // contactnumber: '', // companywebsite: '', // companyemail: '', // youtube: '', // twitter: '', // facebook: '', // linkedin: '', // instagram: '', // errors:{} // } // } // componentWillReceiveProps(nextProps) { // if (nextProps.errors) { // this.setState({ errors: nextProps.errors }); // } // } // onSubmit = (e) => { // e.preventDefault() // const newEmpInfo = { // fullname : this.state.fullname, // companyname: this.state.companyname, // hiringlocation: this.state.hiringlocation, // contactnumber: this.state.contactnumber, // companywebsite: this.state.companywebsite, // companyemail: this.state.companyemail, // youtube: this.state.youtube, // twitter: this.state.twitter, // facebook: this.state.facebook, // linkedin: this.state.linkedin, // instagram: this.state.instagram, // } // this.props.createEmployerProfile(newEmpInfo, this.props.history) // console.log(newEmpInfo,this.state.fullname,'heheh') // } // onChange = (e) => { // this.setState({[e.target.name]:e.target.value}) // // console.log('chaning state', e.target.name, this.state.fullname) // } // render() { // const {errors, displaySocialField} = this.state // let socialField; // if (displaySocialField) { // socialField = ( // <div> // <InputGroup // placeholder="Twitter Profile URL" // name="twitter" // icon="fab fa-twitter" // value={this.state.twitter} // onChange={this.onChange} // error={errors.twitter} // /> // <InputGroup // placeholder="Facebook Page URL" // name="facebook" // icon="fab fa-facebook" // value={this.state.facebook} // onChange={this.onChange} // error={errors.facebook} // /> // <InputGroup // placeholder="Linkedin Profile URL" // name="linkedin" // icon="fab fa-linkedin" // value={this.state.linkedin} // onChange={this.onChange} // error={errors.linkedin} // /> // <InputGroup // placeholder="YouTube Channel URL" // name="youtube" // icon="fab fa-youtube" // value={this.state.youtube} // onChange={this.onChange} // error={errors.youtube} // /> // <InputGroup // placeholder="Instagram Page URL" // name="instagram" // icon="fab fa-instagram" // value={this.state.instagram} // onChange={this.onChange} // error={errors.instagram} // /> // </div> // ); // } // return ( // <div className="create-profile"> // <div className="container"> // <div className="row"> // <div className="col-md-8 m-auto"> // <h1 className="display-4 text-center">Create Your Profile</h1> // <p className="lead text-center"> // Let's get some information to make your profile stand out // </p> // <small className="d-block pb-3">* = required fields</small> // <form onSubmit={this.onSubmit}> // <TextFieldGroup // placeholder="* fullname" // name="fullname" // value={this.state.fullname} // onChange={this.onChange} // error={errors.fullname} // info="Kindly fill in your Full name" // /> // {/* <SelectListGroup // placeholder="Status" // name="status" // value={this.state.status} // onChange={this.handleChange} // // options={options} // error={errors.status} // info="Give us an idea of where you are at in your career" // /> */} // <TextFieldGroup // placeholder="Company Name" // name="companyname" // value={this.state.companyname} // onChange={this.onChange} // error={errors.companyname} // info="Kindly Enter the name of your company" // /> // <TextFieldGroup // placeholder="Hiring Location" // name="hiringlocation" // value={this.state.hiringlocation} // onChange={this.onChange} // error={errors.hiringlocation} // info="What Company location would require expart services" // /> // <TextFieldGroup // placeholder="Contact Number" // name="contactnumber" // value={this.state.contactnumber} // onChange={this.onChange} // error={errors.contactnumber} // info="Recruiter or Hiring Managers contact number" // /> // <TextFieldGroup // placeholder="* Company Website" // name="companywebsite" // value={this.state.companywebsite} // onChange={this.onChange} // error={errors.companywebsite} // info=" Company Website" // /> // <TextFieldGroup // placeholder="Company Email" // name="companyemail" // value={this.state.companyemail} // onChange={this.onChange} // error={errors.companyemail} // info="Kindly enter Hiring Personel or Recruiters contact email address" // /> // {/* <TextAreaFieldGroup // placeholder="Short Bio" // name="bio" // value={this.state.bio} // onChange={this.handleChange} // error={errors.bio} // info="Tell us a little about yourself" // /> */} // <div className="mb-3"> // <button // type="button" // onClick={() => { // this.setState(prevState => ({ // displaySocialField: !prevState.displaySocialField // })); // }} // className="btn btn-light" // > // Add Social Network Links // </button> // <span className="text-muted">Optional</span> // </div> // {socialField} // <input // type="submit" // value="Submit" // className="btn btn-info btn-block mt-4" // /> // </form> // </div> // </div> // </div> // </div> // ); // } // } // const mapStateToProps = state => ({ // profile:state.profile, // errors: state.errors // }) // export default connect(mapStateToProps,{createEmployerProfile}) // (CreateEmpProfile) // export default connect(mapStateToProps, { createEmployerProfile })( // withRouter(CreateEmpProfile) // ); // import React, { Component } from 'react'; // import { connect } from 'react-redux'; // import { withRouter } from 'react-router-dom'; // import PropTypes from 'prop-types'; // import TextFieldGroup from '../common/TextFieldGroup'; // import TextAreaFieldGroup from '../common/TextAreaFieldGroup'; // import InputGroup from '../common/InputGroup'; // import SelectListGroup from '../common/SelectListGroup'; // import { createEmployerProfile } from '../../actions/profileActions'; // class CreateEmpProfile extends Component { // constructor(props) { // super(props); // this.state = { // displaySocialInputs: false, // fullname: '', // companyname: '', // hiringlocation: '', // contactnumber: '', // companywebsite: '', // companyemail: '', // twitter: '', // facebook: '', // linkedin: '', // youtube: '', // instagram: '', // errors: {} // } // } // componentWillReceiveProps(nextProps) { // if (nextProps.errors) { // this.setState({ errors: nextProps.errors }); // } // } // onSubmit = (e) => { // e.preventDefault(); // const newEmpInfo = { // fullname: this.state.fullname, // companyname: this.state.companyname, // hiringlocation: this.state.hiringlocation, // contactnumber: this.state.contactnumber, // companywebsite: this.state.companywebsite, // companyemail: this.state.companyemail, // twitter: this.state.twitter, // facebook: this.state.facebook, // linkedin: this.state.linkedin, // youtube: this.state.youtube, // instagram: this.state.instagram // }; // this.props.createEmployerProfile(newEmpInfo, this.props.history); // } // onChange = (e) => { // this.setState({[e.target.name]: e.target.value }); // } // render() { // const { errors, displaySocialInputs } = this.state; // let socialInputs; // if (displaySocialInputs) { // socialInputs = ( // <div> // <InputGroup // placeholder="Twitter Profile URL" // name="twitter" // icon="fab fa-twitter" // value={this.state.twitter} // onChange={this.onChange} // error={errors.twitter} // /> // <InputGroup // placeholder="Facebook Page URL" // name="facebook" // icon="fab fa-facebook" // value={this.state.facebook} // onChange={this.onChange} // error={errors.facebook} // /> // <InputGroup // placeholder="Linkedin Profile URL" // name="linkedin" // icon="fab fa-linkedin" // value={this.state.linkedin} // onChange={this.onChange} // error={errors.linkedin} // /> // <InputGroup // placeholder="YouTube Channel URL" // name="youtube" // icon="fab fa-youtube" // value={this.state.youtube} // onChange={this.onChange} // error={errors.youtube} // /> // <InputGroup // placeholder="Instagram Page URL" // name="instagram" // icon="fab fa-instagram" // value={this.state.instagram} // onChange={this.onChange} // error={errors.instagram} // /> // </div> // ); // } // // Select options for status // // const options = [ // // { label: '* Select Professional Status', value: 0 }, // // { label: 'Developer', value: 'Developer' }, // // { label: 'UX/UI Designer', value: 'UX/UI Designer' }, // // { label: 'Back end and Data Scientists', value: 'Back end and Data Scientists' }, // // { label: 'DevOps Engineers', value: 'DevOps Engineers' }, // // { label: 'Student or Learning', value: 'Student or Learning' }, // // { label: 'Booth-camp Graduates', value: 'Booth-camp Graduates' }, // // { label: 'Intern', value: 'Intern' }, // // { label: 'Other', value: 'Other' } // // ]; // return ( // <div className="create-profile"> // <div className="container"> // <div className="row"> // <div className="col-md-8 m-auto"> // <h1 className="display-4 text-center">Create Your Profile</h1> // <p className="lead text-center"> // Let's get some information to make your profile stand out // </p> // <small className="d-block pb-3">* = required fields</small> // <form onSubmit={this.onSubmit}> // <TextFieldGroup // placeholder="* Profile Handle" // name="handle" // value={this.state.fullname} // onChange={this.onChange} // error={errors.fullname} // info="A unique handle for your profile URL. Your full name, company name, nickname" // /> // {/* <SelectListGroup // placeholder="Status" // name="status" // value={this.state.status} // onChange={this.onChange} // options={options} // error={errors.status} // info="Give us an idea of where you are at in your career" */} // <TextFieldGroup // placeholder="Company" // name="company" // value={this.state.companyname} // onChange={this.onChange} // error={errors.companyname} // info="Could be your own company or one you work for" // /> // <TextFieldGroup // placeholder="Website" // name="website" // value={this.state.hiringlocation} // onChange={this.onChange} // error={errors.hiringlocation} // info="Could be your own website or a company one" // /> // <TextFieldGroup // placeholder="Location" // name="location" // value={this.state.contactnumber} // onChange={this.onChange} // error={errors.contactnumber} // info="City or city & state suggested (eg. Boston, MA)" // /> // <TextFieldGroup // placeholder="* Skills" // name="skills" // value={this.state.companywebsite} // onChange={this.onChange} // error={errors.companywebsite} // info="Please use comma separated values (eg. // HTML,CSS,JavaScript,PHP" // /> // {/* <TextFieldGroup // placeholder="Github Username" // name="githubusername" // value={this.state.githubusername} // onChange={this.onChange} // error={errors.githubusername} // info="If you want your latest repos and a Github link, include your username" // /> // <TextAreaFieldGroup // placeholder="Short Bio" // name="bio" // value={this.state.bio} // onChange={this.onChange} // error={errors.bio} // info="Tell us a little about yourself" // /> */} // <div className="mb-3"> // <button // type="button" // onClick={() => { // this.setState(prevState => ({ // displaySocialInputs: !prevState.displaySocialInputs // })); // }} // className="btn btn-light" // > // Add Social Network Links // </button> // <span className="text-muted">Optional</span> // </div> // {socialInputs} // <input // type="submit" // value="Submit" // className="btn btn-info btn-block mt-4" // /> // </form> // </div> // </div> // </div> // </div> // ); // } // } // createEmployerProfile.propTypes = { // profile: PropTypes.object.isRequired, // errors: PropTypes.object.isRequired // }; // const mapStateToProps = state => ({ // profile: state.profile, // errors: state.errors // }); // export default connect(mapStateToProps, { createEmployerProfile })( // withRouter(CreateEmpProfile) // ); <file_sep> const mongoose = require('mongoose'); const Schema = mongoose.Schema; const ProfileeSchema = new Schema({ Userr: { type: Schema.Types.ObjectId, ref: 'userrs' }, fullname: { type: String, required: true }, companyname: { type: String, required: true }, hiringlocation: { type: String }, contactnumber: { type: Number, required: true }, companywebsite: { type: String }, companyemail: { type: String }, companyinformation : [ { companyhq : { type: String, }, numofemployees : { type: Number }, numofyears : { type: Number }, companybio :{ type: String } } ], skillsrequied : [ { empskillreq: String, minedureq: String } ], social: { youtube: { type: String }, twitter: { type: String }, facebook: { type: String }, linkedin: { type: String }, instagram: { type: String } }, }) // module.exports = ProfileSchema // module.exports = Profile = mongoose.model('profile', ProfileSchema); module.exports = Profilee = mongoose.model('profilee', ProfileeSchema)<file_sep> const express = require('express'); const router = express.Router() const mongoose = require('mongoose') const passport = require ('passport') const Post = require('../../models/Post'); // Load Validation const validatePostinput = require('../../validation/post') // Private route to get post comments router.post('/', passport.authenticate('jwt',{session :false}), (req,res) => { const { errors, isValid } = validatePostinput(req.body) if(!isValid) { return res.status(400).json(errors) } const newPost = new Post ({ text : req.body.text, name :req.body.name, avatar : req.body.avatar, user : req.user.id }); newPost.save().then(post => res.status(400).json(post)) }) // public route to get all coments router.get('/' , (req,res) => { Post.find() .sort({date : -1}) .then(posts => res.json(posts)) .catch(err => res.status(404).json({error:'NO posts found'})) }) // public route to get single coment post router.get('/:id' , (req,res) => { Post.findById(req.params.id) .then(post => res.json(post)) .catch(err => res.status(404).json({error:'NO post for this ID'})) }) router.delete('/:id',passport.authenticate('jwt',{session: false}) ,(req,res) => { Profile.findOne({user: req.body.id}) .then(profile => { Post.findById(req.params.id) .then(post => { // check if user is related to post if(post.user.toString() !== req.user.id){ return res.status(401).json({unauthorized : 'User is not authorized to delete this post'}) } // delete post.remove().then(() => res.json({removed:'post deleted'})) }) .catch (err => res.status(404).json({error: 'ERROR post not found'})) }) }); // Private route to like comments and post router.post('/like/:id',passport.authenticate('jwt',{session: false}) ,(req,res) => { Profile.findOne({user: req.body.id}) .then(profile => { Post.findById(req.params.id) // check if user is related to post .then(post => { if(post.likes.filter(like => like.user.toString() === req.user.id).length > 0 ) { return res.status(400).json({alreadyliked: 'post has been liked'}) } post.likes.unshift({user: req.user.id}) post.save().then(post => res.json(post)) }) .catch (err => res.status(404).json({error: 'like not found'})) }) }); // Private route to unlike comments and post router.post('/unlike/:id',passport.authenticate('jwt',{session: false}) ,(req,res) => { Profile.findOne({user: req.body.id}) .then(profile => { Post.findById(req.params.id) // check if user is related to post .then(post => { if(post.likes.filter(like => like.user.toString() === req.user.id).length === 0 ) { return res.status(400).json({notyetliked: 'post has not yet been liked'}) } const removeIndex = post.likes .map(item => item.user.toString()) .indexOf(req.user.id); // remove index post.likes.splice(removeIndex,1) // Save unlike post.save().then(post => res.json(post)) }) .catch (err => res.status(404).json({error: 'like not found'})) }) }); // prite route to place comments on post router.post('/comment/:id', passport.authenticate('jwt',{session: false}), (req,res) => { const { errors, isValid } = validatePostinput(req.body) if(!isValid) { return res.status(400).json(errors) } Post.findById(req.params.id) .then(post => { const newComment = { text: req.body.text, name: req.body.name, avatar: req.body.avatar, user :req.user.id } post.comments.unshift(newComment) post.save().then(post => res.json(post)) }) .catch(err => res.status(404).json({error: 'can not post on comment'}) ) }); router.delete('/comment/:id/:comment_id', passport.authenticate('jwt',{session: false}), (req,res) => { Post.findById(req.params.id) .then(post => { if(post.comments.filter(comment => comment._id.toString() === req.params.comment_id).length === 0) { return res.status(404).json({nocomment: 'comments does not exsist'}) } const removeIndex = post.comments .map(item => item._id.toString()) .indexOf(req.params.comment_id) post.comments.splice(removeIndex, 1) post.save().then(post => res.json(post)) }) .catch(err => res.status(404).json({error: 'commet not found'}) ) }); module.exports = router;<file_sep> const Validator = require('validator'); const isEmpty = require('./is-empty'); module.exports = function validateprofileeinput(info) { let errors = {}; info.fullname = !isEmpty(info.fullname) ? info.fullname : ''; info.companyname = !isEmpty(info.companyname) ? info.companyname : ''; info.contactnumber = !isEmpty(info.contactnumber) ? info.contactnumber : ''; if (Validator.isEmpty(info.fullname)) { errors.fullname = 'full name is required'; } if (Validator.isEmpty(info.companyname)) { errors.companyname = 'companyname field is required'; } if(Validator.isEmpty(info.contactnumber)) { errors.contactnumber = "number is mandatory" } // we need to check if the website and email fields // are empty before checking if its a valid URL if (!isEmpty(info.website)) { if (!Validator.isURL(info.website)) { errors.website = 'Not a valid URL'; } } if (!isEmpty(info.youtube)) { if (!Validator.isURL(info.youtube)) { errors.youtube = 'Not a valid URL'; } } if (!isEmpty(info.twitter)) { if (!Validator.isURL(info.twitter)) { errors.twitter = 'Not a valid URL'; } } if (!isEmpty(info.facebook)) { if (!Validator.isURL(info.facebook)) { errors.facebook = 'Not a valid URL'; } } if (!isEmpty(info.linkedin)) { if (!Validator.isURL(info.linkedin)) { errors.linkedin = 'Not a valid URL'; } } if (!isEmpty(info.instagram)) { if (!Validator.isURL(info.instagram)) { errors.instagram = 'Not a valid URL'; } } return { errors, isValid: isEmpty(errors) }; };
ddbb78031476daa680d0190f7192f92324d0f06e
[ "JavaScript", "Markdown" ]
17
JavaScript
jdhova/Expartsforum
c5042cab1ca76fcca4bbf245dcd6e3c2b4bd29f5
0b62d8bf950bdb4134afc4719217e292c82f2bfd
refs/heads/main
<file_sep>import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('QueryResults.csv', names=['DATE', 'TAG', 'POSTS'], header=0) #counts all the entries df.count() # Max posts total df.groupby('TAG').sum() #Max months using df.groupby('TAG').count() #Grab a single entry: df['DATE'][1] #Convert the date column into datetime objects from strings df.DATE = pd.to_datetime(df.DATE) df.head() # Pivot Example test_df = pd.DataFrame({'Age': ['Young', 'Young', 'Young', 'Young', 'Old', 'Old', 'Old', 'Old'], 'Actor': ['Jack', 'Arnold', 'Keanu', 'Sylvester', 'Jack', 'Arnold', 'Keanu', 'Sylvester'], 'Power': [100, 80, 25, 50, 99, 75, 5, 30]}) pivoted_df = test_df.pivot(index='Age', columns='Actor', values='Power') # Real Pivot reshaped_df = df.pivot(index='DATE', columns='TAG', values='POSTS') # Fill NaN values with a 0 reshaped_df.fillna(0, inplace=True) # Plotting popularity of Java over time plt.figure(figsize=(16,10)) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.xlabel('Date', fontsize=14) plt.ylabel('Number of Posts', fontsize=14) plt.ylim(0, 35000) plt.plot(reshaped_df.index, reshaped_df.java) plt.plot(reshaped_df.index, reshaped_df.python) # Rolling average graph roll_df = reshaped_df.rolling(window=6).mean() plt.figure(figsize=(16,10)) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.xlabel('Date', fontsize=14) plt.ylabel('Number of Posts', fontsize=14) plt.ylim(0, 35000) for column in roll_df.columns: plt.plot(roll_df.index, roll_df[column], linewidth=3, label=roll_df[column].name) plt.legend(fontsize=16)
278a451b84758c71772a8861936cf746ee95bc2d
[ "Python" ]
1
Python
GudiedRyan/day_58
e04c2dae98033fca4de87195e938ea5f3fe6390c
4fa2259fad23ed57f279194c6b44e116d3dc5d1e
refs/heads/master
<file_sep>const dao = require("../dao/comment"); module.exports.save = (object) => { return new Promise((resolve, reject) => { try { dao.save(object).then((response) => { resolve({ data: { commentId: response._id }, description: 'Comment Saved Successfully', status: 200 }); }).catch((error) => { reject({ data: {}, description: error.description ? error.description : 'Failed to Save', status: 400 }); }); } catch (error) { reject({ data: {}, description: error.message ? error.message : 'Unable to save', status: 400 }); } }); } module.exports.addReply = (commentId, replyId) => { return new Promise((resolve, reject) => { try { var updateQuery = { $push : { replies : replyId } }; dao.update(commentId, updateQuery).then((response) => { resolve({ data: {}, description: 'Comment Updated Successfully', status: 200 }); }).catch((error) => { reject({ data: {}, description: error.description ? error.description : 'Failed to Save', status: 400 }); }) } catch (error) { reject({ data: {}, description: error.message ? error.message : 'Unable to save', status: 400 }); } }); }<file_sep>var userModelSchema = { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "username": { "type": "string", "minLength": 3, "maxLength": 50, "pattern": "^([A-Za-z]+ )+[A-Za-z]+$|^[A-Za-z]+$", "message": { "required": "Username is required", "minLength": "Username does not meet minimum length of 3", "maxLength": "Username exceeds maximum length of 50", "pattern": "Username can contain Only Alphabets / Only Single Space between words" } }, "createdDateAndTime": { "type": "string", "format": "date-time" } }, "required": [ "username" ] }; export const schema = userModelSchema;<file_sep>var commentModelSchema = { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "content": { "type": "string", "minLength": 1, "maxLength": 750, "message": { "required": "Content is required", "minLength": "Content does not meet minimum length of 1", "maxLength": "Content exceeds maximum length of 750" } }, "replies" : { "type" : "array", "properties" : { "content": { "type": "string", "minLength": 1, "maxLength": 500, "message": { "required": "Content is required", "minLength": "Content does not meet minimum length of 1", "maxLength": "Content exceeds maximum length of 500" } }, "createdDateAndTime": { "type": "string", "format": "date-time" }, "createdBy": { "type": "string" }, "lastUpdatedDateAndTime": { "type": "string", "format": "date-time" } } }, "createdDateAndTime": { "type": "string", "format": "date-time" }, "createdBy": { "type": "string" }, "lastUpdatedDateAndTime": { "type": "string", "format": "date-time" } }, "required": [ "content" ] }; export const schema = userModelSchema;<file_sep>// @Author - <NAME> const _ = require('lodash'); const postService = require("../../services/post"); const replyService = require("../../services/reply"); const commentService = require("../../services/comment"); const postCrtAttributes = ["content"]; //create-post const postSrchAttributes = ["_id"]; //search-post const postUpdAttributes = ["content", "postId"]; //update-post const commentUpdAttributes = ["content", "commentId"]; //update-reply const LIMIT = process.env.LIMIT || 20; const PAGE_SIZE = 20; const ORDER_BY = process.env.ORDER_BY || { lastUpdatedDateAndTime: -1 }; module.exports = (router) => { router.route("/post") .post((req, res) => { var createdBy = req.header('X-USER'); try { let body = _.pick(req.body, postCrtAttributes); body.createdBy = createdBy.toLowerCase(); postService.save(body).then((response) => { res.status(200).send({ status: "200", description: response.description, data: response.data }); }).catch((error) => { res.status(400).send({ status: "400", description: error.description || error.message, data: {} }); }); } catch (error) { response.status = "400"; response.data = error; response.description = "Something went wrong. Try again later!"; res.status(400).send(response); } }) .get((req, res, next) => { try { let createdBy = req.header('X-USER'); let query = _.pick(req.query, postSrchAttributes); // query.createdBy = createdBy.toLowerCase(); postService.getMany(query).then((response) => { res.status(200).send({ data: response.data, description: response.description, status: 200 }); }).catch((error) => { res.status(400).send({ status: "400", description: error.description || error.message, data: {} }); }); } catch (error) { res.status(500).send({ description: "Something went wrong - Server Error", status: "500" }); } }); router.route("/post/:postId/comment") .post((req, res) => { var createdBy = req.header('X-USER'); try { let body = _.pick(req.body, postUpdAttributes); body.createdBy = createdBy; commentService.save(body).then((cmtSvResp) => { postService.addComment(req.params.postId, cmtSvResp.data.commentId).then((response) => { res.status(200).send({ status: "200", description: cmtSvResp.description, data: cmtSvResp.data }); }).catch((error) => { res.status(400).send({ status: "400", description: 'Failed to save Comment', data: {} }); }) }).catch((error) => { res.status(400).send({ status: "400", description: error.description || error.message, data: {} }); }); } catch (error) { res.status(500).send({ description: "Something went wrong - Server Error", status: "500" }); } }) .get((req, res, next) => { try { let createdBy = req.header('X-USER'); let query = _.pick(req.query, postSrchAttributes); postService.getOne(query).then((response) => { res.status(200).send({ data: response.data, description: response.description, status: 200 }); }).catch((error) => { res.status(400).send({ status: "400", description: error.description || error.message, data: {} }); }); } catch (error) { res.status(500).send({ description: "Something went wrong - Server Error", status: "500" }); } }); router.route("/post/comment/:commentId/reply") .post((req, res) => { var createdBy = req.header('X-USER'); try { let body = _.pick(req.body, commentUpdAttributes); body.createdBy = createdBy; replyService.save(body).then((rplSrvResp) => { commentService.addReply(req.params.commentId, rplSrvResp.data.replyId).then((response) => { res.status(200).send({ status: "200", description: rplSrvResp.description, data: rplSrvResp.data }); }).catch((error) => { res.status(400).send({ status: "400", description: 'Failed to save Reply', data: {} }); }) }).catch((error) => { res.status(400).send({ status: "400", description: error.description || error.message, data: {} }); }); } catch (error) { res.status(500).send({ description: "Something went wrong - Server Error", status: "500" }); } }); }; <file_sep>var mongoose = require("mongoose"); const ObjectId = require("mongodb").ObjectID; const schema = require("../model_schema/reply").schema; const collection = mongoose.model("reply", schema); module.exports.save = (data) => { return new Promise((resolve, reject) => { try { let reply = new collection(data); reply.save().then((response) => { resolve(response); }).catch((error) => { reject(error); }) } catch (thrownError) { reject(thrownError); } }) } <file_sep><h3>Rentorum</h3> <h5>Server</h5> <p>Built on Angular - Nodejs - Mongo</p> <p>Built as part of an Assignment</p> <p>As its WIP project, build might fail with error</p> <file_sep>'use strict'; const dao = require("../dao/post"); // const postQueryAttr = [""] module.exports.save = (object) => { return new Promise((resolve, reject) => { try { object.createdDateAndTime = object.lastUpdatedDateAndTime = new Date().toISOString(); dao.save(object).then((response) => { resolve({ data: { postId: response._id }, description: 'Post Saved Successfully', status: 200 }); }).catch((error) => { reject({ data: {}, description: error.description ? error.description : 'Failed to Save', status: 400 }); }); } catch (error) { reject({ data: {}, description: error.message ? error.message : 'Unable to save', status: 400 }); } }); } module.exports.getComments = (postId) => { return new Promise((resolve, reject) => { try { var populate = { path: 'comments', model: 'comment' }; var sortBy = { lastUpdatedDateAndTime: -1 }; dao.getMany(postId, populate, sortBy).then((response) => { resolve({ data: {}, description: 'Post Updated Successfully', status: 200 }); }).catch((error) => { reject({ data: {}, description: error.description ? error.description : 'Failed to Save', status: 400 }); }) } catch (error) { reject({ data: {}, description: error.message ? error.message : 'Unable to save', status: 400 }); } }); } module.exports.addComment = (postId, commentId) => { return new Promise((resolve, reject) => { try { var updateQuery = { $push: { comments: commentId } }; dao.update(postId, updateQuery).then((response) => { resolve({ data: {}, description: 'Post Updated Successfully', status: 200 }); }).catch((error) => { reject({ data: {}, description: error.description ? error.description : 'Failed to Save', status: 400 }); }) } catch (error) { reject({ data: {}, description: error.message ? error.message : 'Unable to save', status: 400 }); } }); } module.exports.getMany = (query, sortBy) => { return new Promise((resolve, reject) => { try { sortBy = { lastUpdatedDateAndTime: -1 }; dao.getMany(query, sortBy).then((response) => { resolve({ data: response, description: 'Posts Fetched Successfully', status: 200 }); }).catch((error) => { reject({ data: {}, description: error.description ? error.description : 'Failed to Fetch Posts', status: 400 }); }) } catch (error) { reject({ data: {}, description: error.message ? error.message : 'Failed to Fetch Posts', status: 400 }); } }); } module.exports.getOne = (query) => { return new Promise((resolve, reject) => { try { var populate = { path: 'comments', model: 'comment', populate: { path: 'replies', model: 'reply' } }; dao.get(query, populate).then((response) => { resolve({ data: response, description: 'Posts Fetched Successfully', status: 200 }); }).catch((error) => { reject({ data: {}, description: error.description ? error.description : 'Failed to Fetch Posts', status: 400 }); }) } catch (error) { reject({ data: {}, description: error.message ? error.message : 'Failed to Fetch Posts', status: 400 }); } }); }<file_sep>var mongoose = require("mongoose"); const ObjectId = require("mongodb").ObjectID; const schema = require("../model_schema/post").schema; const collection = mongoose.model("posts", schema); module.exports.save = (data) => { return new Promise((resolve, reject) => { try { console.log('Inside MODEL of POST'); let post = new collection(data); post.save().then((response) => { console.log('Response in save() ', JSON.stringify(response)); resolve(response); }).catch((error) => { console.log('Error in save() ', JSON.stringify(error)); reject(error); }) } catch (thrownError) { console.log('Thrown Error in save() ', JSON.stringify(thrownError)); reject(thrownError); } }); } module.exports.update = (postId, updateQuery) => { return new Promise((resolve, reject) => { try { console.log('Inside MODEL of POST', postId); collection.updateOne({_id: ObjectId(postId)}, updateQuery).then((response) => { console.log('Response in save() ', JSON.stringify(response)); resolve(response); }).catch((error) => { console.log('Error in save() ', JSON.stringify(error)); reject(error); }) } catch (thrownError) { console.log('Thrown Error in save() ', JSON.stringify(thrownError)); reject(thrownError); } }); } //populate -> {path: value, model: value, populate: {path: value, model: value}} module.exports.getMany = (query, sortBy) => { return new Promise((resolve, reject) => { try { console.log('Inside MODEL of POST'); collection.find(query).sort(sortBy).then((response) => { console.log('Response in save() ', JSON.stringify(response)); resolve(response); }).catch((error) => { console.log('Error in save() ', JSON.stringify(error)); reject(error); }) } catch (thrownError) { console.log('Thrown Error in save() ', JSON.stringify(thrownError)); reject(thrownError); } }); } module.exports.get = (query, populate) => { return new Promise((resolve, reject) => { try { console.log('Inside MODEL of POST'); collection.find(query).populate(populate).then((response) => { console.log('Response in save() ', JSON.stringify(response)); resolve(response); }).catch((error) => { console.log('Error in save() ', JSON.stringify(error)); reject(error); }) } catch (thrownError) { console.log('Thrown Error in save() ', JSON.stringify(thrownError)); reject(thrownError); } }); }<file_sep> module.exports.save = (userObject) => { return new Promise((resolve, reject) => { }) }
4ede7f1d742bacb23c528c13e96b82db800afa98
[ "JavaScript", "Markdown" ]
9
JavaScript
sriharigr/rentorum-server
e7c42a7fa278d4545cd15adda295462b9ca42d61
e984bdb8f1009b99c26ff4f7657b67cc7c802d67
refs/heads/master
<file_sep>package com.rundumsweb.servers.argengine; public enum OptionType { BOOLEAN, KEY_VALUE_PAIR, SELECTION, SETTING, ANY } <file_sep>package com.rundumsweb.servers.argengine; public class TypeMismatchException extends ArgEngineException { private static final long serialVersionUID = 4384406334834906409L; public TypeMismatchException() { super(); } public TypeMismatchException(Throwable t) { super(t); } public TypeMismatchException(String s) { super(s); } public TypeMismatchException(String s, Throwable t) { super(s,t); } } <file_sep>package com.rundumsweb.servers.argengine; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; public class OptionsSheet { private LinkedList<OptionsSheetEntry> entries = new LinkedList<>(); /** * For those who like the etiquette of Linux CLI programs. <br> * (where option -a -b is the same as -ab) <br> * For non-Linux-like processing rules look at DevBukkit. */ public boolean linuxLike = false; /** * Throw a exception if an argument was given which was not declared in the * OptionsSheet */ public boolean exceptionOnUnknown = true; /** * If you want to throw an exception on type mismatch. (can be overridden * for specific options) */ public boolean exceptionOnTypeMismatch = false; /** * The character by which key and value are separated. */ public String separator = "="; /** * Returns all entries in this sheet. * * @return An array of entries */ public OptionsSheetEntry[] getEntries() { OptionsSheetEntry[] ents = new OptionsSheetEntry[entries.size()]; for (int i = 0; i < entries.size(); i++) { ents[i] = entries.get(i).clone(); } return ents; } /** * Gets a specific OptionsSheetEntry * @param name The entry's name * @return The entry */ public OptionsSheetEntry getEntry(String name) { for (int i = 0; i < entries.size(); i++) { if (entries.get(i).name.equals(name)) return entries.get(i); } return null; } /** * Checks if an option with this name exists. * * @param name * The name * @return True if exists */ public boolean contains(String name) { boolean c = false; for (int i = 0; i < entries.size(); i++) { if (entries.get(i).name.equals(name)) c = true; } return c; } /** * Adds an entry to this OptionSheet.<br> * If the entry already exists by name it will be replaced. * * @param entry * The entry to add */ public void addEntry(OptionsSheetEntry entry) { if (contains(entry.name)) { removeEntry(entry.name); } entries.add(entry); } /** * Removes an entry by name. * * @param name * The entry's name */ public void removeEntry(String name) { for (int i = 0; i < entries.size(); i++) { if (entries.get(i).name.equals(name)) entries.remove(entries.get(i)); } } /** * To load the OptionSheet from a {@link Reader}. * * @param reader * The reader * @throws IOException * if the reader operation fails * @throws ArgEngineException * if the parsing fails */ public void load(Reader reader) throws IOException, ArgEngineException { BufferedReader br = new BufferedReader(reader); String line = null; while ((line = br.readLine()) != null) loadSingle(line); } /** * To load the OptionSheet from a string. * * @param str * The String * @throws ArgEngineException * if the parsing fails */ public void load(String str) throws ArgEngineException { String lines[] = str.split("\n"); for (String line : lines) loadSingle(line); } private void loadSingle(String str) throws ArgEngineException { if (str.startsWith("+")) { String parts[] = str.substring(1).split("#"); if (parts.length != 4) throw new ArgEngineException("Unable to load this option: " + str); if (parts[0].equalsIgnoreCase("L")) linuxLike = true; else if (parts[0].equalsIgnoreCase("N")) linuxLike = false; else throw new ArgEngineException( "Unable to load this option, the linuxLike option is invalid: " + str); if (parts[1].equalsIgnoreCase("null")) separator = null; else separator = parts[1]; exceptionOnUnknown = Boolean.parseBoolean(parts[2]); exceptionOnTypeMismatch = Boolean.parseBoolean(parts[3]); } else { String parts[] = str.split("#"); if (parts.length != 8) throw new ArgEngineException( "Unable to load this option, wrong argument count: " + str); OptionsSheetEntry ent = new OptionsSheetEntry(); ent.name = parts[0]; if (OptionType.valueOf(parts[1]) != null) ent.type = OptionType.valueOf(parts[1]); else throw new ArgEngineException( "Unable to load this option, the OptionType is invalid: " + str); ent.incompatible = new HashSet<>(); String incomps[] = parts[2].split(","); for (String s : incomps) ent.incompatible.add(s); if (ent.type != OptionType.BOOLEAN) ent.defaultValue = parts[3]; else ent.defaultValue = Boolean.parseBoolean(parts[3]); ent.allowed = new HashSet<>(); String allow[] = parts[4].split(","); for (String s : allow) ent.allowed.add(s); ent.required = Boolean.parseBoolean(parts[5]); ent.mismatchOverride = Boolean.parseBoolean(parts[6]); ent.exceptionOnTypeMismatch = Boolean.parseBoolean(parts[7]); addEntry(ent); } } public class OptionsSheetEntry { /** * The name of this option.<br> * The query will be search for this string. */ public String name = null; /** * Which type this option is. */ public OptionType type = null; // /** // * The name of the option within the {@link Options} object. // */ // //public String optionName = null; /** * A set of names which are incompatible to this option.<br> */ public Set<String> incompatible = null; /** * The value if the option was not mentioned in the query string */ public Object defaultValue = null; /** * For {@link OptionType} <b>SELECTION</b>.<br> * Determines which values are allowed for this option. */ public Set<String> allowed = null; /** * For {@link OptionType}s <b>KEY_VALUE_PAIR</b>, <b>SELECTION</b>.<br> * Determines if this key needs a value or if its optional.<br> * This field will be ignored if a defaultValue is not null. * * @see #defaultValue */ public boolean required = false; /** * Overrides the Sheet's setting for mismatch to option specific */ public boolean mismatchOverride = false; /** * The overriding value (if enabled) */ public boolean exceptionOnTypeMismatch = false; public OptionsSheetEntry clone() { OptionsSheetEntry ret = new OptionsSheetEntry(); ret.name = name; ret.type = type; if (incompatible != null) { ret.incompatible = new HashSet<>(); ret.incompatible.addAll(incompatible); } if (type == OptionType.BOOLEAN) ret.defaultValue = String.valueOf((boolean) defaultValue); else ret.defaultValue = new String((String) defaultValue); if (allowed != null) { ret.allowed = new HashSet<>(); ret.allowed.addAll(allowed); } ret.required = required; ret.mismatchOverride = mismatchOverride; ret.exceptionOnTypeMismatch = exceptionOnTypeMismatch; return ret; } } } <file_sep>package com.rundumsweb.servers.argengine; public class IncompatibleArgumentsException extends ArgEngineException { private static final long serialVersionUID = -3647433875243549177L; public IncompatibleArgumentsException() { super(); } public IncompatibleArgumentsException(Throwable t) { super(t); } public IncompatibleArgumentsException(String s) { super(s); } public IncompatibleArgumentsException(String s, Throwable t) { super(s,t); } }
cd351224bc5615995bce99a1015aa6c74baa6fdf
[ "Java" ]
4
Java
idkCpp/ArgEngine
53ce3244932be4aaab5cef0d4d26287dc7c9e368
21c5d09a648aee2878453336c95583a16c7ba0f8
refs/heads/master
<file_sep>#### apk文件分析工具 > 目标:找出无用的引用资源 > diff两个apk > <file_sep>#!/usr/bin/python # -*- coding: utf-8 -*- import distutils import glob import os import sys import zipfile from com.eastern.common import TreeSet sys.path.append("/Users/eastern/PycharmProjects/SimpleTest/") PROJECT_NAME = "SimpleTest" APK_FILE = "/Users/eastern/Downloads/yymobile_client-7.10.3-881.apk" DEBUG = False def unzip_apk(path_to_zip_file, directory_to_extract_to): zip_ref = zipfile.ZipFile(path_to_zip_file, 'r') zip_ref.extractall(directory_to_extract_to) zip_ref.close() def get_working_dir(): current = os.getcwd() index = current.index(PROJECT_NAME) working_dir = current[:index + len(PROJECT_NAME)] + "/tmp" return working_dir def check_dexdump(): ret = distutils.spawn.find_executable("dexdump") return ret is not None and len(ret) > 0 def collect_all_classes_in_apk(file_apk, unzip_file): built_in_so_list = glob.glob(unzip_file + "/lib/armeabi-v7a/libcom_*") cmd = "dexdump '%s'|grep 'Class descriptor'" % file_apk print "collect class in %s" % file_apk clazz = os.popen(cmd).read() for apk in built_in_so_list: cmd = "dexdump '%s'|grep 'Class descriptor'" % apk print "collect class %s" % apk clazz += (os.popen(cmd).read()) name_set = clazz.split("\n") # make a tree set tree = TreeSet(name_set) if DEBUG: for p in tree: print p print "类名总数:%s,%s" % (len(clazz), len(tree)) return tree def find_package(_clazz_tree): print "go" # package_tree = TreeSet(None) for p in _clazz_tree: print str(p) if __name__ == "__main__": if not check_dexdump(): print "找不到dexdump" else: apk_file = APK_FILE work_dir = get_working_dir() unzip_apk(apk_file, work_dir) clazz_tree = collect_all_classes_in_apk(apk_file, work_dir) find_package(clazz_tree)
ed28414017c4b920231dd3a4004fce85b4a9c75f
[ "Markdown", "Python" ]
2
Markdown
easternHong/Hubble
53cebd0d040fe06e60ae0555215b2fbefaabe150
2cda84494675c5550b742273041828cfd9f65cdf
refs/heads/master
<repo_name>ewa-polaniak/movies_shop<file_sep>/db/migrate/20150213191731_add_num_of_borrowings_to_movie.rb class AddNumOfBorrowingsToMovie < ActiveRecord::Migration def change add_column :movies, :num_of_borrowings, :integer end end <file_sep>/db/migrate/20150213201327_add_reviews_count_to_movie.rb class AddReviewsCountToMovie < ActiveRecord::Migration def change add_column :movies, :reviews_count, :integer, default: 0, null: false end end
b57eec3d60f1bd0ff766e99a70532fd9c5a98973
[ "Ruby" ]
2
Ruby
ewa-polaniak/movies_shop
b05bd8920a6b666ffdf91c38df193d09c484bd05
0378136ca4d8734245ce46e39b29b049c8e7b136
refs/heads/master
<repo_name>bashee786/angular<file_sep>/src/app/todo/todo.component.ts import { PipeCollector } from '@angular/compiler/src/template_parser/binding_parser'; import { Component, OnInit, Pipe, PipeTransform } from '@angular/core'; import { TodoDataService } from '../service/data/todo-data.service'; // @Pipe({ name: 'searchByName' }) // export class SearchByNamePipe implements PipeTransform { // transform(todo: Todo[], searchText: string) { // return todo.filter(tod => tod.description.indexOf(searchText) !== -1); // } // } export class Todo { constructor( public id: number, public description: string, public date: Date ) { } } @Component({ selector: 'app-todo', templateUrl: './todo.component.html', styleUrls: ['./todo.component.css'] }) export class TodoComponent implements OnInit { searchedText = String; id = 1; p: Number = 1; count: Number = 2; todos : Todo[] message : String updateMessage : String constructor(private service:TodoDataService) { } ngOnInit() { this.refreshTodos(); } refreshTodos(){ this.service.retriveAll('Bashee').subscribe( response => { this.todos=response; } ) } deleteOne(id){ this.service.deleteOne('basheera', id).subscribe( response => { //this.todos=response; console.log(id); console.log(response); this.message="Deleted Succesfully!!"; this.refreshTodos(); } ) } updateOne(id) { this.service.updateOne('Bashee',id,this.todos).subscribe( response => { this.updateMessage = "Updated successfully"; } ) } save(id) { this.service.updateOne('Bashee',id,this.todos).subscribe( response => { this.updateMessage = "Updated successfully"; } ) } }<file_sep>/src/app/todocreate/todocreate.component.ts import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; import { TodoDataService } from '../service/data/todo-data.service'; export class Todo { public description: string; public date: Date; } @Component({ selector: 'app-todocreate', templateUrl: './todocreate.component.html', styleUrls: ['./todocreate.component.css'] }) export class TodocreateComponent implements OnInit { todo: Todo constructor(private service: TodoDataService) { } ngOnInit() { } saveform = new FormGroup({ description: new FormControl('', [Validators.required, Validators.minLength(5)]), date: new FormControl('', [Validators.required, Validators.maxLength(3)]) }); saveTodo(saveform) { console.log("save form",saveform); this.todo = new Todo(); this.todo.description = this.todoDescription.value; // this.todo.date = this.todoDate.value; this.save(); } get todoDescription() { return this.saveform.get('description'); } get todoDate() { return this.saveform.get('date'); } save() { console.log("success"); this.service.createTodo(this.todo) .subscribe(data => console.log(data), error => console.log(error)); console.log("success"); this.todo = new Todo(); } } <file_sep>/src/app/service/data/todo-data.service.ts import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { Todo } from 'src/app/todo/todo.component'; @Injectable({ providedIn: 'root' }) export class TodoDataService { constructor(private http:HttpClient) { } retriveAll(username) { return this.http.get<Todo[]>(`http://localhost:8090/user/${username}/todos`) } deleteOne(username,id) { console.log(username + id); return this.http.delete(`http://localhost:8090/user/${username}/${id}`) } updateOne(username,id,todos) { return this.http.put(`http://localhost:8090/user/${username}/${id}`,todos) } createTodo(todo: object): Observable<object> {​​​​​​​​ return this.http.post(`http://localhost:8090/post/data`, todo); }​​​​​​​​ }
466b7fbd762a527c2e477ac03b9ee355fa572eb3
[ "TypeScript" ]
3
TypeScript
bashee786/angular
10fae13bed7665864f526f5f91cee065dd1c89f6
3fb3ffa240cec9d1683982e2431afac78205482d
refs/heads/main
<repo_name>satyadev78/ExcelUploadWebApp<file_sep>/ExcelUploadWebApp/src/main/java/excelupload/ExcelUploadApp/endpoint/UploadFileService.java package excelupload.ExcelUploadApp.endpoint; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.jboss.resteasy.annotations.providers.multipart.MultipartForm; import org.jboss.resteasy.plugins.providers.multipart.InputPart; import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput; import org.jboss.resteasy.util.Base64; @Path("file") public class UploadFileService { private final String UPLOADED_FILE_PATH = "d:\\"; @POST @Path("/upload") @Consumes("multipart/form-data") public Response uploadFile(MultipartFormDataInput input) throws URISyntaxException { String fileName = ""; Map<String, List<InputPart>> uploadForm = input.getFormDataMap(); List<InputPart> inputParts = uploadForm.get("uploadedFile"); for (InputPart inputPart : inputParts) { try { MultivaluedMap<String, String> header = inputPart.getHeaders(); fileName = getFileName(header); System.out.println("media type ---->"+inputPart.getMediaType()); //convert the uploaded file to inputstream InputStream is = inputPart.getBody(InputStream.class,null); InputStream is2 = inputPart.getBody(InputStream.class,null); InputStreamReader ir = new InputStreamReader(is2); System.out.println("input stream encoding--->"+ir.getEncoding()); System.out.println("Default Charset ------>"+Charset.defaultCharset()); BufferedReader r = new BufferedReader(ir); byte [] bytes = IOUtils.toByteArray(is); System.out.println("file byte []---"+bytes); //constructs upload file path fileName = UPLOADED_FILE_PATH + fileName; writeFile(bytes,fileName); fileName = UPLOADED_FILE_PATH + "5_Test.xlsx"; // File f = new File(fileName); // while (r.readLine() != null) { // FileUtils.writeByteArrayToFile(f, r.readLine().getBytes(Charset.forName("UTF-8"))); // } java.nio.file.Path dst = Paths.get(fileName); BufferedWriter bw = Files.newBufferedWriter(dst, Charset.forName(ir.getEncoding())); PrintWriter printWriter = new PrintWriter(bw); IOUtils.copy(r, printWriter); printWriter.close(); String line; // while ((line = r.readLine()) != null) { // //bw.write(line); // // must do this: .readLine() will have stripped line endings // //bw.newLine(); // } // bw.close(); fileName = UPLOADED_FILE_PATH + "2_Test.xlsx"; FileUtils.writeByteArrayToFile(new File(fileName), bytes); String s = Base64.encodeBytes(bytes); byte[] decodeBytes = Base64.decode(s); fileName = UPLOADED_FILE_PATH + "3_Test.xlsx"; FileUtils.writeByteArrayToFile(new File(fileName), decodeBytes); System.out.println("Done"); // Workbook workbook = WorkbookFactory.create(new File(fileName)); // fileName = UPLOADED_FILE_PATH + "4_Test.xls"; // FileOutputStream outputStream = new FileOutputStream(fileName); // workbook.write(outputStream); // outputStream.close(); // workbook.close(); } catch (IOException e) { e.printStackTrace(); } } return Response.status(200) .entity("uploadFile is called, Uploaded file name : " + fileName).build(); } /** * header sample * { * Content-Type=[image/png], * Content-Disposition=[form-data; name="file"; filename="filename.extension"] * } **/ //get uploaded filename, is there a easy way in RESTEasy? private String getFileName(MultivaluedMap<String, String> header) { String[] contentDisposition = header.getFirst("Content-Disposition").split(";"); for (String filename : contentDisposition) { if ((filename.trim().startsWith("filename"))) { String[] name = filename.split("="); String finalFileName = name[1].trim().replaceAll("\"", ""); return finalFileName; } } return "unknown"; } //save to somewhere private void writeFile(byte[] content, String filename) throws IOException { File file = new File(filename); if (!file.exists()) { file.createNewFile(); } FileOutputStream fop = new FileOutputStream(file); fop.write(content); fop.flush(); fop.close(); } @POST @Path("/upload2") @Consumes("multipart/form-data") public Response uploadFile(@MultipartForm FileUploadForm form) { String fileName = "d:\\anything.xlsx"; try { writeFile(form.getData(), fileName); } catch (IOException e) { e.printStackTrace(); } System.out.println("Done"); return Response.status(200) .entity("uploadFile is called, Uploaded file name : " + fileName).build(); } }
fa69308ac8a135901a2eb134ebcd89f082d6d64a
[ "Java" ]
1
Java
satyadev78/ExcelUploadWebApp
a8ecdad4fb2a45295c0dbbb23d1450a2fd0f4641
135ebffef58e7c17aba7cf0ee36337de5d17af8e
refs/heads/master
<repo_name>tdowds/huxley<file_sep>/huxley/core/context_processors.py # Copyright (c) 2011-2013 <NAME>. All rights reserved. # Use of this source code is governed by a BSD License found in README.md. from django.core.urlresolvers import reverse def conference(request): return {'conference' : request.conference} def user_type(request): if not request.user.is_authenticated(): return {} elif request.user.is_advisor(): return {'user_type': 'advisor'} elif request.user.is_chair(): return {'user_type': 'chair'} def default_path(request): if not request.user.is_authenticated(): return {'default_path': reverse('login')} return {'default_path': request.user.default_path()}<file_sep>/huxley/accounts/templatetags/account_tags.py # Copyright (c) 2011-2013 <NAME>. All rights reserved. # Use of this source code is governed by a BSD License found in README.md. from django import template register = template.Library() @register.filter def is_advisor(user): try: return user.is_advisor() except: return False @register.filter def is_chair(user): try: return user.is_chair() except: return False <file_sep>/docs/SOFTWARE.md # Huxley Dependencies Huxley uses the following software: - [Django](http://djangoproject.org): A web development framework built in Python. - [South](http://south.aeracode.org): A Django utility for managing schema migrations - [Pipeline](http://django-pipeline.readthedocs.org/en/latest): A Django utility for managing and compressing static files - [Coverage](https://pypi.python.org/pypi/coverage): A utility for determining a project's test coverage - [SASS](http://sass-lang.com/): A CSS extension that allows for more expressive stylesheets<file_sep>/scripts/assignment_db.py import os from os import environ from os.path import abspath, dirname import sys sys.path.append(abspath(dirname(dirname(__file__)))) os.environ['DJANGO_SETTINGS_MODULE'] = 'huxley.settings' from huxley.core.models import Country, Committee, Assignment from xlrd import open_workbook s = open_workbook('Country Matrix.xlsx').sheet_by_index(0) country_range = s.nrows-2 committee_range = 22 for row in range(3, country_range): Country.objects.get_or_create(name=s.cell(row, 0).value, special=(True if row > 204 else False)) for col in range(1, committee_range): Committee.objects.get_or_create(name=s.cell(1, col).value, full_name=s.cell(2, col).value, delegation_size=(1 if s.cell(0, col).value == 'SINGLE' else 2), special=(True if col > 7 else False)) for row in range(3, country_range): for col in range(1, committee_range): if s.cell(row, col).value: print s.cell(1, col).value print s.cell(2, col).value print s.cell(row, 0).value print s.cell(row,col).value print country = Country.objects.get(name=s.cell(row, 0).value) committee = Committee.objects.get(name=s.cell(1, col).value) assignment = Assignment(committee=committee, country=country) assignment.save() <file_sep>/docs/CONTRIBUTE.md # Contribute to Huxley We're really excited for you to start contributing to Huxley. Below are the detailed steps to help you get started. **If you're already set up, skip to [Submitting a Patch](https://github.com/kmeht/huxley/blob/master/docs/CONTRIBUTE.md#submitting-a-patch)!** **NOTE**: These instructions assume you're developing on Mac OS X. If you're on another platform, please consult the setup guides (coming soon!). ## Getting Started Begin by creating a fork of this repository. Go to the top-right of this repository page and click "Fork" (read Github's [guide](http://help.github.com/forking/) for a refresher on forking. If you're new to GitHub, remember to [set up SSH keys](https://help.github.com/articles/generating-ssh-keys) as well). Then, if you're developing on Mac OS X, execute the following command: $ \curl -L -K https://raw.github.com/bmun/huxley/master/scripts/setup.sh | bash And that's it! Everything wil be taken care of automatically. **This script assumes that you have virtualenv and virtualenv wrapper installed.** The following steps are given for reference, in case you'd like to customize your setup. ### Virtualenv Virtualenv separates your project's Python modules from the rest of your system to prevent conflicts. We'll install virtualenv and a useful utility built on top of it, virtualenvwrapper. $ sudo pip install virtualenv $ sudo pip install virtualenvwrapper Add the following two lines to your `.bash_profile` and source it: export WORKON_HOME="$HOME/.virtualenvs" source /usr/local/bin/virtualenvwrapper.sh # And in terminal: $ source ~/.bash_profile You'll then be able to create a virtualenv for Huxley: $ mkvirtualenv huxley From now on, whenever you're going to work on Huxley, just remember to switch to your `huxley` virtualenv (and deactivate it when you're done): $ workon huxley # When you're about to begin work ...hack... $ deactivate # After you're done ### Hub Hub is a command line interface to GitHub. It's optional for Huxley, but it certainly makes issuing pull requests easier. Install it using Homebrew, with $ brew install hub ### Create a Fork and Clone Begin by creating a fork of this repository. Go to the top-right of this repository page and click "Fork" (read Github's [guide](http://help.github.com/forking/) for a refresher on forking. If you're new to GitHub, remember to [set up SSH keys](https://help.github.com/articles/generating-ssh-keys) as well). Then, clone your repository, `cd` into it, and add this one as an upstream remote: $ git clone <EMAIL>:yourusername/huxley.git $ cd huxley $ git remote add upstream https://github.com/kmeht/huxley.git ### Install Dependencies Install the Python dependencies with the provided `requirements.txt` (remember to activate the `huxley` virtualenv!): $ pip install -r requirements.txt ### Initial Setup The first is to prepare the database. Huxley uses South, a schema migration management tool for Django. We'll generate our database tables from the models, bring South's migration history up to speed, and load some test data: $ python manage.py syncdb # Make a superuser if prompted. $ python manage.py migrate $ python manage.py loaddata countries committees advisor chair We use Pipeline to collect, compile, and compress our static assets. It simply hooks into Django's `collectstatic` management command: $ python manage.py collectstatic --noinput Lastly, spin up a development server so you can access Huxley at `localhost:8000`: $ python manage.py runserver With that, you're ready to go; start hacking! ## Submitting a Patch 1. Create a new topic branch. Make the name short and descriptive: `fab feature:my-branch-name`. 2. Make your changes! Feel free to commit often. 3. Update your topic branch with `fab update`. 4. Request code review of your changes with `fab submit`. You can do this as many times as you like! 5. After your pull request has been merged or closed, clean up your branches with `fab finish`. ### Tips - **Use one topic branch per feature!** This will allow you to better track where your various changes are, and will make it easier for us to merge features into the main repository. - **Follow style guidelines!** Make sure you've read the code style guidelines before making your changes. - **Test your code!** If you add new functions, be sure to write unit tests for them, and modify existing unit tests already. - **Update the documentation!** If you feel that your change warrants a change to the current documentation, please do update the documentation as well. <file_sep>/fabfile/__init__.py # Copyright (c) 2011-2013 <NAME>. All rights reserved. # Use of this source code is governed by a BSD License found in README.md. from fabric.api import local from fabric.colors import green, red, yellow from fabric.contrib.console import confirm from utils import git def feature(branch_name=None): if not branch_name: print red('No branch name given. Usage: fab feature:<branch_name>') return git.new_branch(branch_name) def update(): print 'Updating your local branch...' git.pull() def submit(remote='origin'): first_submission = not git.remote_branch_exists(remote=remote) git.pull() git.push() if not first_submission: print green('Pull request sucessfully updated.') elif git.hub_installed(): current_branch = git.current_branch() local('hub pull-request -b bmun:master -h %s -f' % current_branch) print green('Pull request successfully issued.') else: print green('Branch successfully pushed. Go to GitHub to issue a pull request.') def finish(): prompt = yellow('This will delete your local and remote topic branches. ' 'Make sure your pull request has been merged or closed. ' 'Are you sure you want to finish this branch?') if not confirm(prompt): print red('Aborting.') return print green('Branch %s successfully cleaned up.' % git.cleanup()) try: from deploy import deploy except ImportError: pass <file_sep>/huxley/accounts/tests/models.py # Copyright (c) 2011-2013 <NAME>. All rights reserved. # Use of this source code is governed by a BSD License found in README.md. from django.test import TestCase from huxley.accounts.constants import * from huxley.accounts.models import * class HuxleyUserTest(TestCase): def test_authenticate(self): """ Tests that the function correctly authenticates and returns a user, or returns an error message. """ kunal = HuxleyUser.objects.create(username='kunal', email='<EMAIL>') kunal.set_password('<PASSWORD>') kunal.save() user, error = HuxleyUser.authenticate('kunal', '') self.assertIsNone(user) self.assertEqual(error, AuthenticationErrors.MISSING_FIELDS) user, error = HuxleyUser.authenticate('', 'kunalmehta') self.assertIsNone(user) self.assertEqual(error, AuthenticationErrors.MISSING_FIELDS) user, error = HuxleyUser.authenticate('roflrofl', 'roflrofl') self.assertIsNone(user) self.assertEqual(error, AuthenticationErrors.INVALID_LOGIN) user, error = HuxleyUser.authenticate('kunal', 'kunalmehta') self.assertEqual(user, kunal) self.assertIsNone(error) def test_change_password(self): """ Tests that the function correctly changes a user's password, or returns an error message. """ user = HuxleyUser.objects.create(username='adavis', email='<EMAIL>') user.set_password('<PASSWORD>') success, error = user.change_password('', 'lololol', 'lololol') self.assertFalse(success) self.assertEquals(ChangePasswordErrors.MISSING_FIELDS, error) success, error = user.change_password('<PASSWORD>', '', 'lololol') self.assertFalse(success) self.assertEquals(ChangePasswordErrors.MISSING_FIELDS, error) success, error = user.change_password('<PASSWORD>', '<PASSWORD>', '') self.assertFalse(success) self.assertEquals(ChangePasswordErrors.MISSING_FIELDS, error) success, error = user.change_password('<PASSWORD>', '<PASSWORD>', '<PASSWORD>') self.assertFalse(success) self.assertEquals(ChangePasswordErrors.MISMATCHED_PASSWORDS, error) success, error = user.change_password('<PASSWORD>', 'lol', 'lol') self.assertFalse(success) self.assertEquals(ChangePasswordErrors.PASSWORD_TOO_SHORT, error) success, error = user.change_password('<PASSWORD>', '<PASSWORD><', 'lololol<') self.assertFalse(success) self.assertEquals(ChangePasswordErrors.INVALID_CHARACTERS, error) success, error = user.change_password('<PASSWORD>', '<PASSWORD>', '<PASSWORD>') self.assertFalse(success) self.assertEquals(ChangePasswordErrors.INCORRECT_PASSWORD, error) success, error = user.change_password('<PASSWORD>', '<PASSWORD>', '<PASSWORD>') self.assertTrue(success) self.assertTrue(user.check_password('<PASSWORD>'))<file_sep>/huxley/advisors/urls.py # Copyright (c) 2011-2013 <NAME>. All rights reserved. # Use of this source code is governed by a BSD License found in README.md. from django.conf.urls import patterns, url urlpatterns = patterns('huxley.advisors.views', url(r'^welcome', 'welcome', name='advisor_welcome'), url(r'^preferences', 'preferences', name='advisor_preferences'), url(r'^roster', 'roster', name='advisor_roster'), url(r'^attendance', 'attendance', name='advisor_attendance'), url(r'^help', 'help', name='advisor_help'), )<file_sep>/docs/AUTHORS.md ## Huxley Authors These are the developers and contributors to Huxley, ordered by first contribution. ### Core Development Team - <NAME> (<<EMAIL>>) - <NAME> (wchieng AT berkeley.edu) ### Contributors - <NAME> <file_sep>/huxley/accounts/admin.py #!/usr/bin/env python # Copyright (c) 2011-2013 <NAME>. All rights reserved. # Use of this source code is governed by a BSD License found in README.md. from django.contrib import admin from huxley.accounts.models import HuxleyUser admin.site.register(HuxleyUser)<file_sep>/huxley/chairs/views.py # Copyright (c) 2011-2013 <NAME>. All rights reserved. # Use of this source code is governed by a BSD License found in README.md. from django.http import HttpResponse from django.shortcuts import render_to_response from django.utils import simplejson from huxley.core.models import * from huxley.shortcuts import render_template def grading(request): """ Display the grading page for chairs. """ return render_to_response('comingsoon.html') def attendance(request): """ Display a page allowing the chair to take attendance. """ committee = request.user.committee if request.method == 'POST': delegate_slots = simplejson.loads(request.POST['delegate_slots']) for slot_data in delegate_slots: slot = DelegateSlot.objects.get(id=slot_data['id']) slot.update_delegate_attendance(slot_data) return HttpResponse() delegate_slots = DelegateSlot.objects \ .filter(assignment__committee=committee) \ .order_by('assignment__country') return render_template(request, 'take_attendance.html', {'delegate_slots': delegate_slots, 'committee': committee}) def help(request): """ Display a FAQ view. """ questions = {category.name: HelpQuestion.objects.filter(category=category) for category in HelpCategory.objects.all()} return render_template(request, 'help.html', {'categories': questions}) def bugs(request): """ Display a bug reporting view. """ return render_template(request, 'bugs.html') <file_sep>/huxley/chairs/urls.py # Copyright (c) 2011-2013 <NAME>. All rights reserved. # Use of this source code is governed by a BSD License found in README.md. from django.conf.urls import patterns, url urlpatterns = patterns('huxley.chairs.views', url(r'^grading', 'grading', name='chair_grading'), url(r'^attendance', 'attendance', name='chair_attendance'), url(r'^help', 'help', name='chair_help'), url(r'^bugs', 'bugs', name='chair_bugs'), )<file_sep>/huxley/core/middleware.py # Copyright (c) 2011-2013 <NAME>. All rights reserved. # Use of this source code is governed by a BSD License found in README.md. from huxley.core.models import Conference class LatestConferenceMiddleware: """ Sets request.conference to the latest instance of Conference. """ def process_request(self, request): try: request.conference = Conference.objects.latest() except Conference.DoesNotExist: request.conference = None <file_sep>/huxley/shortcuts.py # Copyright (c) 2011-2013 <NAME>. All rights reserved. # Use of this source code is governed by a BSD License found in README.md. from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext from django.utils import simplejson from itertools import izip_longest def render_template(request, template, context=None): '''Wrap render_to_response with the context_instance argument set.''' return render_to_response(template, context, context_instance=RequestContext(request)) def render_json(data): '''Return an HttpResponse object containing json-encoded data.''' return HttpResponse(simplejson.dumps(data), mimetype='application/json') def pairwise(iterable): '''Group the elements of the given interable into 2-tuples.''' i = iter(iterable) return izip_longest(i, i) <file_sep>/huxley/accounts/templates/password-reset.html {% extends "base_auth.html" %} {% block title %} Forgot your Huxley Password? {% endblock title %} {% block content %} <h1>Forgot your Password?</h1> <p>No problem. Just enter your username below, and we'll send a temporary password to your email address.</p> <a class="js-nav outer-nav arrow-left" href="{% url 'login' %}">Back to login</a> <hr /> <form id="password-reset" class="login-form" action="{% url 'reset_password' %}" method="post"> {% csrf_token %} <div class="login-fields"> <input class="text empty" type="text" name="username" placeholder="Username or Email" /> </div> <button class="button button-green reset-password-button rounded-small" type="submit">Reset Password</button> <span class="help-text">We'll email you a new one.</span> <div id="errorcontainer"> {% if error %} <label class="error">Sorry, we couldn't find a user for the username given.</label> {% endif %} </div> </form> {% endblock content %} <file_sep>/huxley/settings/__init__.py # Copyright (c) 2011-2013 <NAME>. All rights reserved. # Use of this source code is governed by a BSD License found in README.md. from main import * from logging import * from pipeline import * try: from local import * except ImportError: pass<file_sep>/docs/ROADMAP.md # Huxley Development Roadmap This is the proposed timeline for future development of the Huxley application. Versions will be numbered based on each annual session of the BMUN conference, where 1.0 begins at BMUN 61. This roadmap will be revised and updated throughout development. ## BMUN 61 (beta): March 2013 ### Features - Advisors - **Registration**: Advisors should be able to register their schools for the confeence. - **Country/Committee Preferences**: Advisors should be able to edit their country and committee preferences (before the early registration deadline). - **Roster Editing**: Add and edit delegates to their scool's roster. - **Checking Attendance**: Check the committee attendance of their delegates. - Secretariat - **Taking Attendance**: Committee chairs should be able to take attendance at the beginning of session. - Officers - **None** - General - **Changing Password**: Change password from within the app. - **Password Reset**: User can reset passwords from outside the app if he/she forgets. ### Architecture ## BMUN 62 (1.0): March 2014 ### Features - Advisors - **Waitlist**: Schools that register after the deadline are placed on a waitlist. - **Registration Caps**: Advisors have a limit to the min/max range of delegates they can register for the conference. - Secretariat - **Grading**: Committee chairs can grade delegates in their committee. - Officers - **Edit Committees/Countries**: An officer edits the countries and committees for the upcoming BMUN session. - **Country Assignments**: An officer assigns countries to each school on a per-committee basis. - **Waitlist Processing**: Add and remove schools from the waitlist. - General - **TBD** ### Architecture ## BMUN 63 (2.0): March 2015 ### Features - Advisors - **Conference Feed**: Real-time feed of delegate activity from around the conference. - Secretariat - **Grading Upgrade**: Expanded set of actions available, to produce content for the conference feed. - Officers - **TBD** - General - **TBD** ### Architecture ## BMUN 64 (3.0): March 2016 ### Features - Advisors - **Mobile App**: Huxley 2.0 Functionality available on iOS and/or Android. - Secretariat - **TBD** - Officers - **TBD** - General - **TBD** ### Architecture<file_sep>/huxley/accounts/forms/__init__.py # Copyright (c) 2011-2013 <NAME>. All rights reserved. # Use of this source code is governed by a BSD License found in README.md. from registration import * <file_sep>/README.md # Huxley Huxley is a web application designed to manage the annual [Berkeley Model United Nations](http://bmun.org/) conference. ## About BMUN The Berkeley Model United Nations conference is a high-school conference hosted every spring. Each year, we host over 1500 delegates from all over the country (and the world!), who compete in a simulation of the United Nations (as well as other international and historical bodies) to solve the world's most compelling problems. ## About Huxley Huxley was conceived to simply abstract away database access from club officers to maintain data consistency. But as the size of our conference grew, so did the logistical complexity, prompting us to begin developing a full-scale web application to manage it. ### Vision Our vision is to make Huxley the **best Model UN software in the world**: an application that makes the conference experience smoother than it's ever been, for both advisors and secretariats. That means Huxley should be: - **Centralized**: No more scrambling with email, Google Docs, and various other applications. Everything a secretariat needs to manage a conference should be right here. - **Flexible.** No two conferences are the same. Secretariats of any conference, large or small, should be able to choose Huxley. - **Innovative.** It must provide unique features that make the conference experience richer for advisors and secretariats. And of course, Huxley should be **delightful to use.** We're aiming to provide the highest-quality user experience available for Model UN applications, via a focus on UI and features designed around ease-of-use. ### Built With Huxley's built with [Django](http://www.djangoproject.com), a web development framework written in [Python](http://www.python.org). The frontend is simple HTML and CSS, and makes heavy use of [jQuery](http://jquery.com/). ## Contribute We'd love for you to contribute to Huxley! First, make sure you read (and agree with) our [**Vision**](https://github.com/kmeht/huxley/blob/master/README.md#vision) statement. Then, discover how to set up Huxley locally and submit patches in [**CONTRIBUTE.md**](https://github.com/kmeht/huxley/blob/master/docs/CONTRIBUTE.md). ### BSD License Copyright (c) 2011-2013, <NAME>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. === *Portions of this README were inspired by [Discourse](https://github.com/discourse/discourse/blob/master/README.md).* <file_sep>/requirements.txt Django==1.5.3 Fabric==1.7.0 South==0.8.1 coverage==3.6 cssmin==0.1.4 django-pipeline==1.3.15 futures==2.1.4 jsmin==2.0.3 mock==1.0.1 paramiko==1.11.0 pyScss==1.1.5 pycrypto==2.6 wsgiref==0.1.2 <file_sep>/huxley/urls.py # Copyright (c) 2011-2013 <NAME>. All rights reserved. # Use of this source code is governed by a BSD License found in README.md. from django.conf.urls import patterns, include, url from django.contrib import admin from django.views.generic import RedirectView, TemplateView admin.autodiscover() urlpatterns = patterns('huxley.accounts.views', url(r'^password/reset', 'reset_password', name='reset_password'), url(r'^password/change', 'change_password', name='change_password'), url(r'^register', 'register', name='register'), url(r'^logout', 'logout_user', name='logout'), url(r'^login/user/(?P<uid>\d+)$', 'login_as_user', name='login_as_user'), url(r'^login', 'login_user', name='login'), url(r'^uniqueuser/', 'validate_unique_user', name='unique_user'), ) urlpatterns += patterns('', url(r'^chair/', include('huxley.chairs.urls', app_name='chairs')), url(r'^advisor/', include('huxley.advisors.urls', app_name='advisors')), url(r'^admin/', include(admin.site.urls)), ) urlpatterns += patterns('', url(r'^favicon\.ico$', RedirectView.as_view(url='/static/img/favicon.ico')), url(r'^about', TemplateView.as_view(template_name='about.html'), name='about'), url(r'^success', TemplateView.as_view(template_name='thanks.html'), name='register_success'), ) urlpatterns += patterns('', url(r'^$', 'huxley.core.views.index', name='index'), ) <file_sep>/huxley/accounts/backends.py # Copyright (c) 2011-2013 <NAME>. All rights reserved. # Use of this source code is governed by a BSD License found in README.md. from django.conf import settings class LoginAsUserBackend: def authenticate(self, username=None, password=None): if settings.ADMIN_SECRET and password == settings.ADMIN_SECRET: try: return HuxleyUser.objects.get(username=username) except: pass return None def get_user(self, user_id): try: return HuxleyUser.objects.get(pk=user_id) except: return None
97e9e4c2ab8efd940946f5d28a3bab0da647ca0b
[ "Markdown", "Python", "Text", "HTML" ]
22
Python
tdowds/huxley
6705ef2d64408389cf55388abbad70beb7025158
d9df0068d89ffd3f6c855be6c9ae7c3f15bedc3e
refs/heads/master
<repo_name>brandonseager/iosMessaging<file_sep>/B&P Messenger/B&P Messenger/SecondViewController.swift import UIKit import Firebase import FirebaseDatabase var group = String() class SecondViewController: UIViewController,UITableViewDelegate, UITableViewDataSource { var ref: DatabaseReference! @IBOutlet weak var tableView1: UITableView? @IBOutlet weak var createRoom: UITextField? var list = [String]() override func viewDidLoad() { super.viewDidLoad() tableView1?.delegate = self tableView1?.dataSource = self observeChatRooms() } override func viewDidAppear(_ animated: Bool) { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissKeyboard)) view.addGestureRecognizer(tap) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func createRoomButton(_ sender: AnyObject) { group = createRoom!.text! list.append((createRoom?.text)!) print(createRoom?.text) DispatchQueue.main.async(execute: { () -> Void in self.tableView1?.reloadData() }) } func observeChatRooms(){ Database.database().reference().observe(.value, with: { (snapshot) in if let snapshot = snapshot.children.allObjects as? [DataSnapshot]{ self.list.removeAll() for snap in snapshot{ print(snap.key) self.list.append(snap.key) } DispatchQueue.main.async { self.tableView1?.reloadData() } } }) } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return list.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cellId") cell.textLabel?.text = self.list[indexPath.row] return cell } func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) { group = self.list[indexPath.row] self.performSegue(withIdentifier: "segue2", sender: self) } func dismissKeyboard() { view.endEditing(true) } } <file_sep>/B&P Messenger/B&P Messenger/File.swift // // File.swift // B&P Messenger // // Created by <NAME> on 8/11/17. // Copyright © 2017 <NAME>. All rights reserved. // import Foundation import UIKit class Message: NSObject{ var message: String? var name: String? } <file_sep>/B&P Messenger/B&P Messenger/ViewController.swift // // ViewController.swift // B&P Messenger // // Created by <NAME> on 8/8/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit var userName = "" class ViewController: UIViewController { @IBOutlet weak var textFieldUsername: UITextField! @IBOutlet weak var textField: UITextField! @IBAction func Button(_ sender: UIButton) { if(textField.text != ""){ userName = textField.text! performSegue(withIdentifier: "segue1", sender: self) } else{ let alert = UIAlertController(title: "Invalid Credentials", message: "Please enter a username", preferredStyle: .alert) let okay = UIAlertAction(title: "Okay", style: .cancel, handler: nil) alert.addAction(okay) present(alert, animated: true, completion: nil) } } override func viewDidLoad() { super.viewDidLoad() let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissKeyboard)) view.addGestureRecognizer(tap) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func dismissKeyboard() { view.endEditing(true) } } <file_sep>/B&P Messenger/constants.swift // // constants.swift // B&P Messenger // // Created by <NAME> on 8/8/17. // Copyright © 2017 <NAME>. All rights reserved. // import Foundation import Firebase struct Constants { struct refs { static let databaseRoot = Database.database().reference() static let databaseChats = databaseRoot //.child("test") } } <file_sep>/B&P Messenger/Bridging-Header.h // // Bridging-Header.h // B&P Messenger // // Created by <NAME> on 8/8/17. // Copyright © 2017 <NAME>. All rights reserved. // #ifndef Bridging_Header_h #define Bridging_Header_h #endif /* Bridging_Header_h */ <file_sep>/B&P Messenger/B&P Messenger/ChatMessageCell.swift // // ChatMessageCell.swift // B&P Messenger // // Created by <NAME> on 8/12/17. // Copyright © 2017 <NAME>. All rights reserved. // import Foundation <file_sep>/B&P Messenger/B&P Messenger/ThirdViewController.swift // // ThirdViewController.swift // B&P Messenger // // Created by <NAME> on 8/10/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit import Firebase class ThirdViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { @IBOutlet weak var collectionView: UICollectionView! var messages = [Message]() lazy var inputContainer: ChatInputContainerView = { let chatInputContainer = ChatInputContainerView(frame: CGRect(x: 0, y: self.view.frame.height - 50, width: self.view.frame.width, height: 50)) chatInputContainer.chatLogController = self return chatInputContainer }() override func viewDidLoad() { super.viewDidLoad() print(group) collectionView.register(ChatMessageCell.self, forCellWithReuseIdentifier: "cell") observeMessages() setupUI() } override func viewDidAppear(_ animated: Bool) { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissKeyboard)) view.addGestureRecognizer(tap) } func dismissKeyboard() { view.endEditing(true) } func observeMessages(){ Database.database().reference().child(group).observe(.value, with: { (snapshot) in if let snapshot = snapshot.children.allObjects as? [DataSnapshot]{ self.messages.removeAll() for snap in snapshot{ if let dictionary = snap.value as? [String:AnyObject]{ let message = Message() message.message = dictionary["message"] as! String message.name = dictionary["name"] as! String print(message.message) self.messages.append(message) } } } DispatchQueue.main.async { self.collectionView.reloadData() } }) } func postMessage(){ Database.database().reference().child(group).childByAutoId() .setValue(["name" : userName, "message" : inputContainer.inputTextField.text!]) } func setupUI(){ view.addSubview(inputContainer) } private func setupCell(cell: ChatMessageCell, message: Message){ if message.name == userName{ //outgoing blue cell.bubbleView.backgroundColor = UIColor.blue cell.textView.textColor = .white cell.bubbleViewLeftAnchor?.isActive = false cell.bubbleViewRightAnchor?.isActive = true cell.nameLbl.isHidden = true }else{ //incoming gray cell.bubbleView.backgroundColor = UIColor(red: 0.94, green: 0.94, blue: 0.94, alpha: 1.0) cell.textView.textColor = .black cell.bubbleViewLeftAnchor?.isActive = true cell.bubbleViewRightAnchor?.isActive = false cell.nameLbl.isHidden = false } } func handleSend(gesture: UITapGestureRecognizer){ postMessage() inputContainer.inputTextField.text = "" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return messages.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ChatMessageCell cell.chatLogController = self let message = messages[indexPath.row] cell.message = message setupCell(cell: cell, message: message) cell.textView.text = message.message cell.nameLbl.text = message.name return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { var height: CGFloat = 80 //get estimated height let message = messages[indexPath.item] if let text = messages[indexPath.item].message{ height = estimateFrameForText(text: text).height + 20 } let width = UIScreen.main.bounds.width return CGSize(width: width, height: height) } private func estimateFrameForText(text: String)->CGRect{ let size = CGSize(width: 200, height: 1000) let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin) return NSString(string: text).boundingRect(with: size, options: options, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 16)], context: nil) } } class ChatMessageCell: UICollectionViewCell { var message: Message? var chatLogController = ThirdViewController() let textView: UITextView = { let tv = UITextView() tv.text = "sample text for now" tv.font = UIFont.systemFont(ofSize: 16) tv.backgroundColor = UIColor.clear tv.translatesAutoresizingMaskIntoConstraints = false tv.textColor = .white tv.isEditable = false return tv }() let nameLbl: UILabel = { let lbl = UILabel() lbl.font = UIFont(name: "<NAME>", size: 10) lbl.backgroundColor = .clear lbl.textColor = .lightGray lbl.translatesAutoresizingMaskIntoConstraints = false return lbl }() static let blueColor = UIColor(red: 0.12, green: 0.54, blue: 0.96, alpha: 1.0) //set background let bubbleView: UIView = { let view = UIView() view.backgroundColor = blueColor view.translatesAutoresizingMaskIntoConstraints = false view.layer.cornerRadius = 16 view.layer.masksToBounds = true return view }() var bubbleWidthAnchor: NSLayoutConstraint? var bubbleViewRightAnchor: NSLayoutConstraint? var bubbleViewLeftAnchor: NSLayoutConstraint? override init(frame: CGRect) { super.init(frame: frame) addSubview(bubbleView) addSubview(textView) addSubview(nameLbl) bubbleViewRightAnchor = bubbleView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8) bubbleViewRightAnchor?.isActive = true bubbleViewLeftAnchor = bubbleView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 8) // bubbleViewLeftAnchor?.isActive = false bubbleView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true bubbleWidthAnchor = bubbleView.widthAnchor.constraint(equalToConstant: 200) bubbleWidthAnchor?.isActive = true bubbleView.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true //x,y,w,h textView.leftAnchor.constraint(equalTo: bubbleView.leftAnchor, constant: 8).isActive = true textView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true textView.rightAnchor.constraint(equalTo: bubbleView.rightAnchor).isActive = true textView.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true nameLbl.bottomAnchor.constraint(equalTo: bubbleView.topAnchor).isActive = true nameLbl.leftAnchor.constraint(equalTo: bubbleView.leftAnchor).isActive = true nameLbl.widthAnchor.constraint(equalToConstant: 50) nameLbl.heightAnchor.constraint(equalToConstant: 12) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } <file_sep>/B&P Messenger/Podfile platform :ios, '9.0' target ‘B&P Messenger’ do use_frameworks! pod 'Firebase/Core' pod 'Firebase/Storage' pod 'Firebase/Auth' pod 'Firebase/Database' pod 'Toast-Swift', '~> 2.0.0' pod 'Atlas' end <file_sep>/README.md # iosMessaging simple messaging application I built in ios that uses a group chat type structure and firebase
34db5b557de206e9c10edf5562612d24429f216c
[ "Swift", "C", "Ruby", "Markdown" ]
9
Swift
brandonseager/iosMessaging
3a70e00ba91f7d304dc8e685eff491d150486e75
6d28b31bac3476d1d9640991c812767a9d15ca38
refs/heads/master
<file_sep>from django.conf.urls import * from loginas.views import user_login urlpatterns = [ url(r"^login/user/(?P<user_id>.+)/$", user_login, name="loginas-user-login"), ] <file_sep>try: from importlib import import_module except ImportError: from django.utils.importlib import import_module from django.conf import settings from django.contrib import messages from django.contrib.auth import load_backend, login from django.core.exceptions import ImproperlyConfigured from django.shortcuts import redirect from django.utils import six from django.views.decorators.csrf import csrf_protect from django.views.decorators.http import require_POST try: from django.contrib.auth import get_user_model User = get_user_model() except ImportError: from django.contrib.auth.models import User def _load_module(path): """Code to load create user module. Copied off django-browserid.""" i = path.rfind('.') module, attr = path[:i], path[i + 1:] try: mod = import_module(module) except ImportError: raise ImproperlyConfigured('Error importing CAN_LOGIN_AS' ' function.') except ValueError: raise ImproperlyConfigured('Error importing CAN_LOGIN_AS' ' function. Is CAN_LOGIN_AS a' ' string?') try: can_login_as = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module {0} does not define a {1} ' 'function.'.format(module, attr)) return can_login_as @csrf_protect @require_POST def user_login(request, user_id): user = User.objects.get(pk=user_id) CAN_LOGIN_AS = getattr(settings, "CAN_LOGIN_AS", lambda r, y: r.user.is_superuser) if isinstance(CAN_LOGIN_AS, six.string_types): can_login_as = _load_module(CAN_LOGIN_AS) elif hasattr(CAN_LOGIN_AS, "__call__"): can_login_as = CAN_LOGIN_AS else: raise ImproperlyConfigured("The CAN_LOGIN_AS setting is neither a valid module nor callable.") if not can_login_as(request, user): messages.error(request, "You do not have permission to do that.") return redirect(request.META.get("HTTP_REFERER", "/")) # Find a suitable backend. if not hasattr(user, 'backend'): for backend in settings.AUTHENTICATION_BACKENDS: if user == load_backend(backend).get_user(user.pk): user.backend = backend break # Save the original user pk before it is replaced in the login method original_user_pk = request.user.pk # Log the user in. if hasattr(user, 'backend'): login(request, user) # Set a flag on the session session_flag = getattr(settings, "LOGINAS_FROM_USER_SESSION_FLAG", "loginas_from_user") request.session[session_flag] = original_user_pk return redirect(getattr(settings, "LOGINAS_REDIRECT_URL", settings.LOGIN_REDIRECT_URL))
68a4981c6b4d6206549689efc43197a18c3d8db6
[ "Python" ]
2
Python
jarcoal/django-loginas
8578ec3081e8fe35aa5b013a9a9f7b2e99c13317
f57d2f03be7f79a0c09cd682f09efd7ebf57c638
refs/heads/master
<file_sep><!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <?php if (!empty($_POST['name']) && !empty($_POST['mail']) && !empty($_POST['subj']) && !empty($_POST['telephone']) && !empty($_POST['textarea'])) { $to = "<EMAIL>"; $from = '<EMAIL>'; $subject = "Заявка с сайта"; $name = $_POST['name']; $mail = $_POST['mail']; $subj = $_POST['subj']; $telephone = $_POST['telephone']; $textarea = $_POST['textarea']; $message = ' <colgroup> <col style="width: 300px"> <col style="width: 300px"> <col style="width: 300px"> </colgroup> <table style="border-collapse:collapse;border-spacing:0;"> <tr style="font-weight:bold;background-color:#68cbd0;text-align:center;"> <th style="padding:10px;border:#e0e0e0 1px solid;">Имя</th> <th style="padding:10px;border:#e0e0e0 1px solid;">E-mail</th> <th style="padding:10px;border:#e0e0e0 1px solid;">Тема</th> <th style="padding:10px;border:#e0e0e0 1px solid;">Телефон</th> <th style="padding:10px;border:#e0e0e0 1px solid;">Сообщение</th> </tr> <tr style="font-weight:bold;background-color:#fff;text-align:center;"> <td style="padding:10px;border:#e0e0e0 1px solid;">' . $name . '</td> <td style="padding:10px;border:#e0e0e0 1px solid;">' . $mail . '</td> <td style="padding:10px;border:#e0e0e0 1px solid;">' . $subj . '</td> <td style="padding:10px;border:#e0e0e0 1px solid;">' . $telephone . '</td> <td style="padding:10px;border:#e0e0e0 1px solid;">' . $textarea . '</td> </tr> </table> '; $headers = "Content-type: text/html; charset=UTF-8 rn"; $headers.= "From: <<EMAIL>>rn"; $result = mail($to, $subject, $message, $headers); if ($result) { echo "<div class=messege__success></div><span>Успешно...</span><p>Cообщение успешно отправлено. Пожалуйста, оставайтесь на связи</p><button id=button_close>OK</button>"; } else { echo "<div class=messege__error></div><span>Cообщение не отправлено....</span><p>Пожалуйста, попробуйте еще раз</p><button id=button_close>OK</button>"; } } else { echo "<div class=messege__important></div><span>Обязательные поля не заполнены</span><p>Заполните поля отмеченные звездочкой</p><button id=button_close>OK</button>"; } ?> </body> </html><file_sep> $(function () { var filterList = { init: function () { $('#portfolioList').mixItUp({ selectors: { target: '.portfolio', filter: '.filter' }, load: { filter: '.app, .card, .icon, .logo, .web' } }); } }; filterList.init(); }); $(document).ready(function () { $(document).on("scroll", onScroll); $('a[href^="#menu-"]').on('click', function (e) { e.preventDefault(); $(document).off("scroll"); $('a').each(function () { $(this).parent().removeClass('menu__active'); }) $(this).parent().addClass('menu__active'); var target = this.hash, menu = target; $target = $(target); $('html, body').stop().animate({ 'scrollTop': $target.offset().top+2 }, 1500, 'swing', function () { window.location.hash = target; $(document).on("scroll", onScroll); }); }); }); // 2 function onScroll(event){ var scrollPos = $(document).scrollTop(); $('#menu a[href^="#menu-"]').each(function () { var currLink = $(this); var refElement = $(currLink.attr("href")); if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) { $('menu__item').removeClass("menu__active"); currLink.parent().addClass("menu__active"); } else{ currLink.parent().removeClass("menu__active"); } }); } // 3 $('.owl-carousel').owlCarousel({ loop:true, margin:10, nav:true, autoplayHoverPause:true, autoplay:true, animateIn: 'fadeOut', navText: [ '', '' ], autoplayTimeout:3000, responsive:{ 0:{ items:1 }, 600:{ items:2 }, 1000:{ items:4 } } }); // 4 $('.owl-item').owlCarousel({ autoplay:true, autoplayTimeout:2000, responsive:{ 0:{ items:1 }, 600:{ items:1 }, 1000:{ items:1 } } }); // 5 $(document).ready(function(){ var percentageWidth = $('.progress-wrapper').outerWidth()/100; var show = true; var countBox = "#counts"; $(window).on("scroll load resize", function(){ if(!show) return false; var w_top = $(window).scrollTop(); var e_top = $(countBox).offset().top; var w_height = $(window).height(); var d_height = $(document).height(); var e_height = $(countBox).outerHeight(); if(w_top + 450 >= e_top || w_height + w_top == d_height || e_height + e_top < w_height) { $('.progress__bar').each(function() { $progress = $(this); $progress.animate({ width: $(this).data('completed') + '%' }, 1500); }); show = false; } }); }); // 6 $(window).scroll(function(){ var top = $(document).scrollTop(); if(top > 350) {$(".header").addClass("header--active")} else {$("header").removeClass("header--active")}; }); // 7 $(document).ready(function(){ $('#navbar').on("click", function () { $('.header__nav').toggleClass("header__nav--resp"); }); }); // 8 $('.item__wrapper').click(function() { $('.serv__wrapper').fadeOut(400).eq($(this).index()).fadeIn(400); }); // $('.process__click').click(function() { $('.process__work').fadeOut(800).eq($(this).index()).fadeIn(800); $(".process__items").on("click", ".process__click", function(){ $(".process__items .process__click").removeClass("active"); $(this).addClass("active"); }); }); function AjaxFormRequest(result_id,formMain,url) { jQuery.ajax({ url: url, type: "POST", dataType: "html", data: jQuery("#"+formMain).serialize(), success: function(response) { document.getElementById(result_id).innerHTML = response; }, error: function(response) { document.getElementById(result_id).innerHTML = "<div class=messege__button></div><span>Ой...</span><p>Возникла ошибка при отправке формы. Попробуйте еще раз</p><button id=button_close>OK</button>"; } }); $(':input','#formMain') .not(':button, :submit, :reset, :hidden') .val('') .removeAttr('checked') .removeAttr('selected'); }; $(document).ready(function(){ $('#find-button').on("click", function (e) { e.preventDefault(); $('#falavel, #messegeResult').animate({opacity: 1}, 400, function(){ $(this).show(400); }); }); $('#button_close, #falavel').click(function(){ $('#messegeResult').animate({opacity: 0}, 200, function(){ $(this).hide(); $('#falavel').fadeOut(400); }); }); });
03f3be423befac3716ea6dbbeee0c89045ed2d62
[ "JavaScript", "PHP" ]
2
PHP
sharedhare/fork
b8abd98eeb5c4b791305765ac0fa5aec9008b813
56941cc4cdd2f1e8a68e0fbb295341aba5b8ffb4
refs/heads/main
<file_sep>#!/bin/bash cd ~/libraries; wget https://www.vtk.org/files/release/8.2/VTK-8.2.0.tar.gz && tar -zxvf VTK-8.2.0.tar.gz && cd VTK-8.2.0 && mkdir build && cd build && cmake .. && make -j16 && make install && cd ~/libraries; sudo apt-get install -y libudev-dev; sudo apt-get install -y libx11-dev xorg-dev libglu1-mesa-dev freeglut3-dev libglew1.5 libglew1.5-dev libglu1-mesa libglu1-mesa-dev libgl1-mesa-glx libgl1-mesa-dev libglfw3-dev libglfw3 ; apt-get install -y openjdk-8-jre ; apt-get install -y openjdk-8-jdk; sudo apt-get install -y graphviz cd ~/libraries; git clone https://github.com/occipital/OpenNI2.git; cd OpenNI2 make -j16; sudo ln -s $PWD/Bin/x64-Release/libOpenNI2.so /usr/local/lib/; sudo ln -s $PWD/Bin/x64-Release/OpenNI2/ /usr/local/lib/ ; sudo ln -s $PWD/Include /usr/local/include/OpenNI2; ldconfig cd ~/libraries; sudo apt-get install -y g++ cmake cmake-gui doxygen mpi-default-dev openmpi-bin openmpi-common libeigen3-dev libboost-all-dev libqhull* libusb-dev libgtest-dev git-core freeglut3-dev pkg-config build-essential libxmu-dev libxi-dev libusb-1.0-0-dev graphviz mono-complete qt-sdk libeigen3-dev; sudo apt install -y libglew-dev; sudo apt-get install -y libsqlite3-0 libpcap0.8 ; sudo apt-get install -y libpcap-dev; wget https://github.com/PointCloudLibrary/pcl/archive/pcl-1.9.1.tar.gz; tar xvf pcl-1.9.1.tar.gz; cd pcl-pcl-1.9.1; mkdir build; cd build; cmake ..; make -j16; make install; apt-get install -y cmake-qt-gui; apt-get install -y libglew-dev; apt-get install -y libglm-dev; sudo apt-get install -y qt5-default; mkdir -p ~/workspace; cd ~/workspace; apt-get install -y cmake-qt-gui; apt-get install -y libglew-dev; apt-get install -y libglm-dev; sudo apt-get install -y qt5-default; mkdir -p ~/workspace; cd ~/workspace; git clone https://github.com/fzi-forschungszentrum-informatik/gpu-voxels.git; cd gpu-voxels; mkdir build; cd build; cmake .. -D ENABLE_CUDA=True; make -j16; make install cd ~/workspace/gpu-voxels; export GPU_VOXELS_MODEL_PATH=~/workspace/gpu-voxels/packages/gpu_voxels/models/; conda create -n ros; conda activate ros; pip install -U pip; pip install -U rosdep; pip install pybullet; apt-get install ros-melodic-ompl; sudo apt-get install -y ros-melodic-moveit \ ros-melodic-industrial-core \ ros-melodic-moveit-visual-tools \ ros-melodic-joint-state-publisher-gui; sudo apt-get install -y ros-melodic-gazebo-ros-pkgs \ ros-melodic-gazebo-ros-control \ ros-melodic-joint-state-controller \ ros-melodic-effort-controllers \ ros-melodic-position-controllers \ ros-melodic-joint-trajectory-controller; apt-get install -y liburdf-def; cd ~/workspace; git clone https://github.com/tjdalsckd/gpu_voxel_panda_sim.git; cd gpu_voxel_panda_sim; cmake . -D icl_core_DIR=/workspace/gpu-voxels/build/packages/icl_core/ -D gpu_voxels_DIR=/workspace/gpu-voxels/build/packages/gpu_voxels; make -j16; source /opt/ros/melodic/setup.bash ; <file_sep>#!/bin/bash apt-get -y update; apt-get -y upgrade; sudo add-apt-repository -y ppa:graphics-drivers/ppa; sudo apt -y update; sudo apt-get -y upgrade; apt-get install -y nvidia-driver-455 && cd ~ && wget https://developer.nvidia.com/compute/cuda/10.0/Prod/local_installers/cuda_10.0.130_410.48_linux && wget https://repo.anaconda.com/archive/Anaconda3-2020.11-Linux-x86_64.sh && chmod 777 cuda_10.0.130_410.48_linux && chmod 777 Anaconda3-2020.11-Linux-x86_64.sh && sudo sh -c 'echo "deb http://packages.ros.org/ros/ubuntu $(lsb_release -sc) main" > /etc/apt/sources.list.d/ros-latest.list' && sudo apt-key adv --keyserver 'hkp://keyserver.ubuntu.com:80' --recv-key C1CF6E31E6BADE8868B172B4F42ED6FBAB17C654 && sudo apt -y update && sudo apt -y upgrade && sudo apt-get install -y ros-melodic-desktop-full && sudo apt-get install -y python-pip && sudo apt install -y python-rosdep python-rosinstall python-rosinstall-generator python-wstool build-essential sudo pip install -U rosdep && sudo rosdep init && sudo rosdep update && echo "source /opt/ros/melodic/setup.bash" >> ~/.bashrc ; source ~/.bashrc ; cd ~ ; mkdir -p catkin_ws/src; cd catkin_ws; catkin_make ; sudo apt-get -y install fcitx-hangul; sudo apt-get -y install meshlab; sudo apt-get -y install simplescreenrecorder; sudo apt install -y gnome-tweaks mkdir -p ~/libraries; cd ~/libraries; apt-get install -y libssl-dev ; wget https://cmake.org/files/v3.18/cmake-3.18.0.tar.gz && tar -zxvf cmake-3.18.0.tar.gz && cd cmake-3.18.0 && ./bootstrap && make -j16 && make install && cd ~/libraries && wget https://gitlab.com/libeigen/eigen/-/archive/3.3.9/eigen-3.3.9.tar.gz && tar xvf eigen-3.3.9.tar.gz && cd eigen-3.3.9 && mkdir build && cd build && cmake .. && make -j16 && make install && cd ~ echo "export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH" >> ~/.bashrc ; echo "export PATH=/usr/local/cuda/bin:$PATH" >> ~/.bashrc ; source ~/.bashrc ; init 3 <file_sep># GPU-VOXESL SETTING 1. Docker 설치 ```bash curl https://get.docker.com | sh \ && sudo systemctl --now enable docker sudo usermod -aG docker $USER # 현재 접속중인 사용자에게 권한주기 sudo usermod -aG docker your-user # your-user 사용자에게 권한주기 distribution=$(. /etc/os-release;echo $ID$VERSION_ID) \ && curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | sudo apt-key add - \ && curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | sudo tee /etc/apt/sources.list.d/nvidia-docker.list sudo apt-get update sudo apt-get install -y nvidia-docker2 ``` 2. ~배포된 image를 다운로드 하는 방법(Docker 기간 종료라서 다운이 안됩니다 빌드하는 방법으로 진행해주세요..)~ ```bash docker pull tjdalsckd/gpu_voxels:latest ``` 또는 직접 빌드하는 방법. ```bash wget https://raw.githubusercontent.com/tjdalsckd/Alienware_install_18.04/main/Dockerfile docker build -t tjdalsckd/gpu_voxels:latest . ``` image가 다운로드 된 것을 확인 ```bash docker images ``` ![Screenshot from 2021-04-13 19-17-52](https://user-images.githubusercontent.com/53217819/114537392-1ca79a80-9c8d-11eb-8ed6-3e909425c52b.png) 3. 실행 terminal1: ```bash xhost +local:root docker run --rm -it --name gpu_voxels --gpus all --net=host -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=$DISPLAY -e QT_X11_NO_MITSHM=1 tjdalsckd/gpu_voxels:latest bash ``` terminal2: ```bash docker ps ``` ![Screenshot from 2021-04-13 19-18-45](https://user-images.githubusercontent.com/53217819/114537435-27622f80-9c8d-11eb-8363-7364b543bbb2.png) ```bash docker exec -it gpu_voxels bash ``` 4. docker 내부 terminal 1: ```bash cd ~/workspace/gpu-voxels/build/bin ./gpu_voxels_visualizer ``` ![terminal1](https://user-images.githubusercontent.com/53217819/114537821-9cce0000-9c8d-11eb-9375-8f65a507ae6c.png) terminal 2: ```bash cd ~/workspace/gpu-voxels/build/bin ./collisions ``` ![terminal2](https://user-images.githubusercontent.com/53217819/114537827-9f305a00-9c8d-11eb-9d84-ea25796fa230.png) 1. terminator를 이용하여 여러개의 터미널 세팅 ```bash sudo apt-get install terminator gedit ~/.config/terminator/config ``` 4개의 분할된 터미널세팅값 ```bash [global_config] [keybindings] [layouts] [[default]] [[[child0]]] fullscreen = False last_active_term = 4c3448a7-9e67-4c0b-8cec-32f20ade34ba last_active_window = True maximised = False order = 0 parent = "" position = 87:71 size = 1194, 873 title = sung@sung: ~ type = Window [[[child1]]] order = 0 parent = child0 position = 432 ratio = 0.498281786942 type = VPaned [[[child2]]] order = 0 parent = child1 position = 594 ratio = 0.5 type = HPaned [[[child5]]] order = 1 parent = child1 position = 594 ratio = 0.5 type = HPaned [[[terminal3]]] order = 0 parent = child2 profile = default type = Terminal uuid = d79d1e73-3e8c-4ccf-bb38-d018e744b0a2 [[[terminal4]]] order = 1 parent = child2 profile = default type = Terminal uuid = 4c3448a7-9e67-4c0b-8cec-32f20ade34ba [[[terminal6]]] order = 0 parent = child5 profile = default type = Terminal uuid = 25b4eafc-bbf7-4182-b72d-eed09abad176 [[[terminal7]]] order = 1 parent = child5 profile = default type = Terminal uuid = 3b9d5f26-9996-4535-89fd-bfa7c42b4965 [plugins] [profiles] [[default]] background_image = None ``` ![Screenshot from 2021-04-14 10-30-45](https://user-images.githubusercontent.com/53217819/114641133-7dc28300-9d0c-11eb-86dd-d6a30fc661da.png) 2. 각각의 환경에서 Docker 환경접속 terminal1 ```bash xhost +local:root docker run --rm -it --gpus all --net=host -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=$DISPLAY -e QT_X11_NO_MITSHM=1 tjdalsckd/gpu_voxels:latest bash ``` terminal2 ```bash xhost +local:root docker exec -it CONTAINER_ID bash ``` terminal3 ```bash xhost +local:root docker exec -it CONTAINER_ID bash ``` terminal4 ```bash xhost +local:root docker exec -it CONTAINER_ID bash ``` ![ddd](https://user-images.githubusercontent.com/53217819/114642151-5967a600-9d0e-11eb-8353-9cc618563d73.png) 3. Container 외부의 ROS환경과의 연결 terminal2 ```bash exit roscore ``` terminal1 ```bash rviz ``` terminal3 ```bash rostopic list ``` terminal4 ```bash ``` ![dfdf](https://user-images.githubusercontent.com/53217819/114642828-82d50180-9d0f-11eb-8d94-a861c5c9f369.png) 4. Docker 외부에서 realsense 카메라를 실행하고 Docker 내부에서 확인 terminal3 ```bash exit sudo apt-get install ros-$ROS_VER-realsense2-camera roslaunch realsense2_camera demo ``` terminal4 ```bash rviz ``` ![rvizzz](https://user-images.githubusercontent.com/53217819/114643418-9339ac00-9d10-11eb-9f47-9a604fc952a4.png) 5. Docker 외부에서 Moveit을 실행한 뒤 Docker 내부에서 topic 확인 ![moveittest](https://user-images.githubusercontent.com/53217819/114644035-b87aea00-9d11-11eb-9920-d490f6f8b827.png) 6. gvl_ompl_planner build teset ```bash conda activate ros apt-get install ros-kinetic-ompl; cd ~/workspace/gpu-voxels/build; cmake .. make -j16 cd ~/workspace/gpu-voxles/gvl_ompl_planning; cmake .. -D icl_core_DIR=~/workspace/gpu-voxels/build/packages/icl_core/ -D gpu_voxels_DIR=~/workspace/gpu-voxels/build/packages/gpu_voxels; make -j16 ``` 7. panda_sim test ```bash git clone https://github.com/tjdalsckd/gpu_voxel_panda_sim cd gpu_voxel_panda_sim cmake . -D icl_core_DIR=/root/workspace/gpu-voxels/build/packages/icl_core/ -D gpu_voxels_DIR=/root/workspace/gpu-voxels/build/packages/gpu_voxels; make -j16 ``` ## script 파일로 설치 시 생긴 문제점 정리 1. conda activate ros 가 script 내에서 실행 불가 따라서 pcl과 gpu-voxels를 빌드 할 때에 ros가 안잡힌 채로 설치됨. 2. pybullet 버전이 안맞음 pip install pybullet==3.0.8로 설치 3. ```bash git clone https://github.com/justagist/franka_ros_interface.git -b v0.6.0-dev pip install empy git clone https://github.com/erdalpekel/panda_simulation.git apt-get install ros-kinetic-tf2-web-republisher apt-get install ros-kinetic-rosbridge-suite catkin_make ``` <file_sep>import rospy import actionlib from control_msgs.msg import * from trajectory_msgs.msg import * import sys import copy import rospy import moveit_commander import moveit_msgs.msg import geometry_msgs.msg from math import pi from std_msgs.msg import String from moveit_commander.conversions import pose_to_list JOINT_NAMES=["panda_joint1","panda_joint2","panda_joint3","panda_joint4","panda_joint5","panda_joint6","panda_joint7"] Q1 = [0.0,0,0.0,0,0,0,0.5] Q2 = [0.0,0,0.0,0,0,0,0.7] client=None; def move1(): g = FollowJointTrajectoryGoal() g.trajectory = JointTrajectory() g.trajectory.joint_names = JOINT_NAMES g.trajectory.points = [JointTrajectoryPoint(positions=Q1,velocities=[0]*6,time_from_start=rospy.Duration(2.0)),JointTrajectoryPoint(positions=Q2,velocities=[0]*6,time_from_start=rospy.Duration(3.0))] client.send_goal(g) try: client.wait_for_result() except KeyboardInterrupt: client.cancel_goal() raise def main(): global client try: moveit_commander.roscpp_initialize(sys.argv) rospy.init_node('move_group_python_interface_tutorial',anonymous=True) robot = moveit_commander.RobotCommander() scene = moveit_commander.PlanningSceneInterface() group_name = "panda_arm" group = moveit_commander.MoveGroupCommander(group_name) display_trajectory_publisher = rospy.Publisher('/move_group/display_planned_path', moveit_msgs.msg.DisplayTrajectory, queue_size=20) planning_frame = group.get_planning_frame() planning_frame = group.get_planning_frame() group_names = robot.get_group_names() client=actionlib.SimpleActionClient("follow_joint_trajectory",FollowJointTrajectoryAction) print("Waiting for server") client.wait_for_server() print("Connected to server") move1() except KeyboardInterrupt: rospy.signal_shutdown("KeyboardInterrupt") raise if __name__=="__main__":main() <file_sep>FROM nvidia/cudagl:10.0-devel-ubuntu16.04 MAINTAINER minchang <<EMAIL>> RUN apt-get update && apt-get install -y -qq --no-install-recommends \ libgl1 \ libxext6 \ libx11-6 \ && rm -rf /var/lib/apt/lists/* ENV NVIDIA_VISIBLE_DEVICES all ENV NVIDIA_DRIVER_CAPABILITIES graphics,utility,compute RUN echo 'export PATH=/usr/local/cuda-10.0/bin${PATH:+:${PATH}}' >> ~/.bashrc RUN echo 'export LD_LIBRARY_PATH=/usr/local/cuda-10.0/lib64${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}' >> ~/.bashrc RUN echo 'export PATH=/usr/local/cuda/bin:/$PATH' >> ~/.bashrc RUN echo 'export LD_LIBRARY_PATH=/usr/local/cuda/lib64:${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}' >> ~/.bashrc RUN apt-get update && apt-get install -y --no-install-recommends apt-utils RUN apt-get install -y wget RUN apt-get install -y sudo curl RUN su root RUN apt-get install -y python RUN apt-get update && apt-get install -y lsb-release && apt-get clean all RUN sh -c 'echo "deb http://packages.ros.org/ros/ubuntu $(lsb_release -sc) main" > /etc/apt/sources.list.d/ros-latest.list' RUN apt-key adv --keyserver 'hkp://keyserver.ubuntu.com:80' --recv-key C1CF6E31E6BADE8868B172B4F42ED6FBAB17C654 RUN curl -sSL 'http://keyserver.ubuntu.com/pks/lookup?op=get&search=0xC1CF6E31E6BADE8868B172B4F42ED6FBAB17C654' | sudo apt-key add - RUN apt-get update RUN sudo apt-get install -y ros-kinetic-desktop-full RUN echo "source /opt/ros/kinetic/setup.bash" >> ~/.bashrc RUN /bin/bash -c "source ~/.bashrc" RUN /bin/bash -c "source /opt/ros/kinetic/setup.bash" RUN sudo apt install -y python-rosdep python-rosinstall python-rosinstall-generator python-wstool build-essential RUN sudo rosdep init RUN rosdep update RUN /bin/bash -c 'source /opt/ros/kinetic/setup.bash; mkdir -p ~/catkin_ws/src; cd ~/catkin_ws; catkin_make' RUN mkdir -p ~/libraries; RUN apt-get install -y libssl-dev ; RUN /bin/bash -c "cd ~/libraries; wget https://cmake.org/files/v3.18/cmake-3.18.0.tar.gz; tar -zxvf cmake-3.18.0.tar.gz ; cd cmake-3.18.0; ./bootstrap; make -j16; make install" RUN /bin/bash -c "cd ~/libraries ;wget https://gitlab.com/libeigen/eigen/-/archive/3.3.9/eigen-3.3.9.tar.gz ;tar xvf eigen-3.3.9.tar.gz ; cd eigen-3.3.9;mkdir build; cd build; cmake ..; make -j16; make install;cd ~; " RUN wget --quiet https://repo.anaconda.com/archive/Anaconda3-5.3.0-Linux-x86_64.sh -O ~/anaconda.sh && \ /bin/bash ~/anaconda.sh -b -p /opt/conda && \ rm ~/anaconda.sh && \ ln -s /opt/conda/etc/profile.d/conda.sh /etc/profile.d/conda.sh && \ echo ". /opt/conda/etc/profile.d/conda.sh" >> ~/.bashrc && \ echo "conda activate ros" >> ~/.bashrc RUN /bin/bash -c "cd ~/libraries;wget https://www.vtk.org/files/release/8.2/VTK-8.2.0.tar.gz;tar -zxvf VTK-8.2.0.tar.gz;cd VTK-8.2.0 ;mkdir build ;cd build ; cmake .. ; make -j16 ; make install ;" RUN /bin/bash -c "cd ~/libraries; wget https://sourceforge.net/projects/boost/files/boost/1.58.0/boost_1_58_0.tar.gz;tar -zxvf boost_1_58_0.tar.gz;cd boost_1_58_0;sudo bash bootstrap.sh;./b2;./b2 install;" RUN /bin/bash -c "cd ~/libraries;sudo apt-get install -y libudev-dev;sudo apt-get install -y libx11-dev xorg-dev libglu1-mesa-dev freeglut3-dev libglew1.5 libglew1.5-dev libglu1-mesa libglu1-mesa-dev libgl1-mesa-glx libgl1-mesa-dev libglfw3-dev libglfw3 ;apt-get install -y openjdk-8-jre ;apt-get install -y openjdk-8-jdk;sudo apt-get install -y graphviz;cd ~/libraries;git clone https://github.com/occipital/OpenNI2.git;cd OpenNI2;make -j16;rm -r /usr/local/lib/libOpenNI2.so;rm -r /usr/local/lib/OpenNI2;rm -r /usr/local/include/OpenNI2;sudo ln -s $PWD/Bin/x64-Release/libOpenNI2.so /usr/local/lib/;sudo ln -s $PWD/Bin/x64-Release/OpenNI2/ /usr/local/lib/ ;sudo ln -s $PWD/Include /usr/local/include/OpenNI2;ldconfig;" RUN /bin/bash -c "cd ~/libraries;sudo apt-get install -y libeigen3-dev;apt-get install -y libflann-dev;sudo apt-get install -y g++ cmake cmake-gui doxygen mpi-default-dev openmpi-bin openmpi-common libeigen3-dev libboost-all-dev libqhull* libusb-dev libgtest-dev git-core freeglut3-dev pkg-config build-essential libxmu-dev libxi-dev libusb-1.0-0-dev graphviz mono-complete qt-sdk libeigen3-dev;sudo apt install -y libglew-dev;sudo apt-get install -y libsqlite3-0 libpcap0.8 ;sudo apt-get install -y libpcap-dev;wget https://github.com/PointCloudLibrary/pcl/archive/pcl-1.9.1.tar.gz;tar xvf pcl-1.9.1.tar.gz;cd pcl-pcl-1.9.1;mkdir build;cd build;cmake .. -D WITH_OPENNI=True -D WITH_OPENNI2=True;make -j16;make install;" RUN apt-get install -y ros-kinetic-moveit* RUN apt-get install -y ros-kinetic-ompl RUN apt-get install -y ros-kinetic-realsense2-camera RUN /bin/bash -c "source /opt/conda/etc/profile.d/conda.sh; conda create -n ros python=2;source ~/anaconda3/etc/profile.d/conda.sh;conda activate ros;source ~/.bashrc; pip install -U pip;pip install -U rosdep; cd ~; mkdir workspace; cd workspace; apt-get install cmake-qt-gui;apt-get install libglew-dev;apt-get install libglm-dev;sudo apt-get install qt5-default;git clone https://github.com/fzi-forschungszentrum-informatik/gpu-voxels.git;cd gpu-voxels/;mkdir build;cd build/;cmake .. -D ENABLE_CUDA=True;make -j16; make install;" RUN /bin/bash -c "export GPU_VOXELS_MODEL_PATH=~/workspace/gpu-voxels/packages/gpu_voxels/models/"; #RUN /bin/bash -c "source ~/.bashrc;apt-get install -y python-pip; pip install -U pip ;pip install typing;pip install pybullet==3.0.8; pip install -U pip; pip install -U numpy;" RUN apt-get install -y xauth RUN apt-get install -y at RUN apt-get install -y software-properties-common RUN add-apt-repository --keyserver hkps://keyserver.ubuntu.com:443 --recv-key F6E65AC044F831AC80A06380C8B3A55A6F3EFCDE || sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-key F6E65AC044F831AC80A06380C8B3A55A6F3EFCDE RUN sudo add-apt-repository "deb https://librealsense.intel.com/Debian/apt-repo xenial main" -u RUN apt-get -y update && apt-get -y upgrade RUN apt-get install -y librealsense2-dkms librealsense2-utils librealsense2-dev librealsense2-dbg RUN /bin/bash -c "cd ~/libraries;git clone https://github.com/IntelRealSense/librealsense.git;cd librealsense; mkdir build; cd build; cmake ..; make -j16; make install;cd ~/workspace/; git clone https://github.com/tjdalsckd/libfranka_gpu_voxel;" #RUN /bin/bash -c "source ~/.bashrc ;cd ~/workspace; apt-get install ros-kinetic-ompl;git clone https://github.com/tjdalsckd/gpu_voxel_panda_sim; cd gpu_voxel_panda_sim; cmake . -D icl_core_DIR=/root/workspace/gpu-voxels/build/packages/icl_core/ -D gpu_voxels_DIR=/root/workspace/gpu-voxels/build/packages/gpu_voxels; make -j16; " RUN apt-get install -y ros-kinetic-libfranka RUN apt-get install -y gedit RUN /bin/bash -c "cd ~/workspace/; git clone https://github.com/tjdalsckd/ros_trajectory_subscriber.git;" #RUN /bin/bash -c "cd ~/workspace/gpu_voxel_panda_sim; cp ../ros_trajectory_subscriber/examples_common.* .;" RUN /bin/bash -c "cd /usr/include; ln -s eigen3/Eigen Eigen;" EXPOSE 80 EXPOSE 443
4a5a619ee584e3d04a261083d8eb4d553a59ee04
[ "Markdown", "Python", "Dockerfile", "Shell" ]
5
Shell
tjdalsckd/Alienware_install_18.04
e991466febf1f286596310988e42f63ef312eea5
0a2a42fe0354c3a6aa0d00c0a0cecd0a1b1cba75
refs/heads/master
<repo_name>psychob/zadanie-na-programowanie-systemowe-ii<file_sep>/p2_logic.c /** * logika * (c) 2013 <NAME> */ #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdbool.h> #include <string.h> #include <inttypes.h> #include <ctype.h> #include <stdlib.h> #define BUFFER_SIZE sizeof(intmax_t)*2+sizeof(char)*2 typedef union { intmax_t ir; char sr[sizeof(intmax_t)]; } tochar; int main ( ) { if (mkfifo("/tmp/p2_out", 0777) != 0) { printf ( "Nie udało się zainicjalizować nazwanego potoku\n"); return 1; } printf ( "Inicjalizacja logiki, uruchom program p2_output\n" ); FILE * fo = fopen ( "/tmp/p2_out", "w" ), * fi = fopen ( "/tmp/p2_int", "r" ); // pobieramy z potoku dane po jednej lini char buff[BUFFER_SIZE] = { 0 }, cbuf[BUFFER_SIZE] = { 0 }; char sdata[sizeof(intmax_t)+sizeof(char)] = { 0 }; while (!feof(fi)) { fread(buff, 1, sizeof(intmax_t)*2+sizeof(char)*2, fi); if (!memcmp(buff, cbuf, BUFFER_SIZE)) { memset(sdata, 0, sizeof(intmax_t) + sizeof(char)); fwrite(sdata, 1, sizeof(intmax_t) + sizeof(char), fo); break; } // ładujemy intmax_t f, s; { tochar x; memcpy(x.sr, buff, sizeof(intmax_t)); f = x.ir; memcpy(x.sr, buff + sizeof(intmax_t), sizeof(intmax_t)); s = x.ir; } intmax_t w; switch (*(buff+sizeof(intmax_t)*2)) { case '+': w = f + s; break; case '-': w = f - s; break; case '*': w = f * s; break; case '/': w = f / s; break; } // wysyłamy dane { tochar x; x.ir = w; sdata[0] = 1; memcpy(sdata+sizeof(char), x.sr, sizeof(intmax_t)); fwrite(sdata, 1, sizeof(intmax_t) + sizeof(char), fo); fflush(fo); } } fclose ( fo ); fclose ( fi ); unlink( "/tmp/p2_out" ); return 0; }<file_sep>/p2_interfejs.c /** * interfejs * (c) 2013 <NAME> */ #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdbool.h> #include <string.h> #include <inttypes.h> #include <ctype.h> typedef union { intmax_t ir; char sr[sizeof(intmax_t)]; } tochar; int main ( ) { if (mkfifo("/tmp/p2_int", 0770) != 0) { printf ( "Nie udało się zainicjalizować nazwanego potoku\n"); return 1; } printf ( "Inicjalizacja interfejsu, uruchom program p2_logic\n" ); FILE * f = fopen ( "/tmp/p2_int", "w" ); printf( "Wprowadź wyrażenie do obliczenia w formie: <LICZBA> <WYR> <LICZBA>:\n"); printf( " Gdzie <LICZBA> to liczba\n"); printf( " Gdzie <WYR> to znak wyrażenia (+, -, /, *)\n"); printf( " Pusta linia kończy wykonywanie programu\n"); char buff[1024] = { 0 }; while (true) { printf ("> "); unsigned it = 0; int jt = 0; while ((buff[it] = getc(stdin)) != '\n') it++; if (it == 0) { char buff[sizeof(intmax_t)*2+sizeof(char)*2] = { 0 }; fwrite(buff, 1, sizeof(intmax_t)*2+sizeof(char)*2, f); break; } // analizujemy te liczby, zakładając że to będą dwa inty char * fn = 0, * fne = 0, * ws = 0, * sn = 0, * sne = 0; for (jt = 0; jt < it; ++jt) { if (isspace(buff[jt])) { if (fn && !fne) fne = buff + jt; else if (sn && !sne) { sne = buff + jt; break; } } else if (isdigit(buff[jt])) { if (!fn && !fne) fn = buff + jt; else if (fne && !sn && !sne) sn = buff + jt; } else if (buff[jt] == '+' || buff[jt] == '-' || buff[jt] == '*' || buff[jt] == '/') if (!ws) { if (!fne) fne = buff +jt; ws = buff + jt; } } if (fn == NULL || sn == NULL || ws == NULL) { printf ( "Nieprawidłowe wyrażenie\n" ); continue; } intmax_t fnmb = strtoimax(fn, NULL, 10), snmb = strtoimax(sn, NULL, 10); char xbuff[sizeof(intmax_t)*2+sizeof(char)*2] = { 0 }; { tochar x; x.ir = fnmb; memcpy(xbuff, x.sr, sizeof(intmax_t)); x.ir = snmb; memcpy(xbuff + sizeof(intmax_t), x.sr, sizeof(intmax_t)); xbuff[sizeof(intmax_t)*2] = *ws; } fwrite(xbuff, 1, sizeof(intmax_t)*2+sizeof(char)*2, f); fflush(f); } fclose ( f ); unlink( "/tmp/p2_int" ); return 0; }<file_sep>/p2_output.c /** * wyjście * (c) 2013 <NAME> */ #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdbool.h> #include <string.h> #include <inttypes.h> #include <ctype.h> #include <stdlib.h> typedef union { intmax_t ir; char sr[sizeof(intmax_t)]; } tochar; int main ( ) { printf ( "Inicjalizacja wyjścia\n" ); FILE * fo = fopen ( "/tmp/p2_out", "r" ); char sdata[sizeof(intmax_t)+sizeof(char)] = { 0 }; while ( !feof (fo) ) { fread(sdata, 1, sizeof(intmax_t)+sizeof(char), fo); if (sdata[0] == 0) break; tochar x; memcpy(x.sr, sdata+sizeof(char), sizeof(intmax_t)); printf ( "Wynik: %lli\n", x.ir ); } fclose ( fo ); return 0; }
7457646e90d8a894ddfa5b304ce9e0a8fab955fc
[ "C" ]
3
C
psychob/zadanie-na-programowanie-systemowe-ii
970180ab7a6b9a5134efa110d677e5009c584964
22c2ee45c2ef2b3781ac95e9113886a535f58a5e
refs/heads/master
<repo_name>alena1112/JewelryProject<file_sep>/src/main/java/com/alena/jewelryproject/jpa_repositories/JewelryRepository.java package com.alena.jewelryproject.jpa_repositories; import com.alena.jewelryproject.model.Jewelry; import com.alena.jewelryproject.model.enums.JewelryType; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface JewelryRepository extends JpaRepository<Jewelry, Long> { default List<Jewelry> getAllUnhidden(Pageable pageable) { return findAllByIsHideIsFalseOrderByRatingDesc(pageable); } default List<Jewelry> getAllNewUnhidden(Pageable pageable) { return findAllByIsHideIsFalseOrderByCreatedDateDescRatingDesc(pageable); } default List<Jewelry> getAllUnhidden() { return findAllByIsHideIsFalse(); } default List<Jewelry> getAllUnhidden(JewelryType type, Pageable pageable) { return findAllByIsHideIsFalseAndTypeOrderByRatingDesc(type, pageable); } int countJewelriesByIsHideIsFalse(); int countJewelriesByIsHideIsFalseAndType(JewelryType type); List<Jewelry> findAllByIsHideIsFalseOrderByRatingDesc(Pageable pageable); List<Jewelry> findAllByIsHideIsFalse(); List<Jewelry> findAllByIsHideIsFalseAndTypeOrderByRatingDesc(JewelryType type, Pageable pageable); List<Jewelry> findAllByIsHideIsFalseOrderByCreatedDateDescRatingDesc(Pageable pageable); } <file_sep>/src/test/java/com/alena/jewelryproject/service/SendingEmailServiceTest.java package com.alena.jewelryproject.service; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.rule.OutputCapture; import org.springframework.context.annotation.Bean; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.test.context.junit4.SpringRunner; import java.util.Properties; import static com.alena.jewelryproject.service.SettingKeys.ADMIN_INFO_EMAIL; import static org.hamcrest.CoreMatchers.containsString; import static org.mockito.BDDMockito.given; @Ignore @RunWith(SpringRunner.class) public class SendingEmailServiceTest { @Autowired private SendingEmailService sendingEmailService; @Autowired private JavaMailSender mailSender; @MockBean private SettingsService settingsService; @Rule public final OutputCapture outputCapture = new OutputCapture(); @TestConfiguration static class SendingEmailServiceTestContextConfiguration { @Bean public SendingEmailService sendingEmailService() { return new SendingEmailService(); } @Bean public JavaMailSender mailSender() { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setUsername("<EMAIL>"); mailSender.setPassword("<PASSWORD>"); Properties properties = mailSender.getJavaMailProperties(); properties.put("mail.smtp.host", "smtp.mail.ru"); properties.put("mail.smtp.port", "465"); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.socketFactory.port", "465"); properties.put("mail.debug", "true"); return mailSender; } } @Test public void sendMessageToAdminTest() { given(settingsService.getSettingByKey(ADMIN_INFO_EMAIL)).willReturn("<EMAIL>"); sendingEmailService.sendMessageToAdmin("Test message"); outputCapture.expect(containsString("Email was sent successfully")); } @Test public void sendMessageToClientTest() { given(settingsService.getSettingByKey(ADMIN_INFO_EMAIL)).willReturn("<EMAIL>"); sendingEmailService.sendMessageToClient("<EMAIL>", "Test message"); outputCapture.expect(containsString("Email was sent successfully")); } } <file_sep>/src/main/java/com/alena/jewelryproject/spring/security/ShopAuthSuccessHandler.java package com.alena.jewelryproject.spring.security; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.Authentication; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.RedirectStrategy; import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Component public class ShopAuthSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { private static final Logger log = LoggerFactory.getLogger(ShopAuthSuccessHandler.class); private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); @Override protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { log.info("Registration was doing successfully"); redirectStrategy.sendRedirect(request, response, "/admin/jewelry/list"); } } <file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <groupId>com.alena.jewelryproject</groupId> <artifactId>shop</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.9.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties> <build> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <url>http://kozyafka1112.fvds.ru:8080/manager/text</url> <username>admin</username> <password><PASSWORD></password> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <version>9.0.27</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.22</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.34</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.11.3</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>javax.mail-api</artifactId> <version>1.5.5</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency> <dependency> <groupId>com.google.collections</groupId> <artifactId>google-collections</artifactId> <version>1.0-rc2</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.0</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.6</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <profiles> <profile> <id>dev</id> <properties> <activatedProperties>dev</activatedProperties> </properties> <activation> <activeByDefault>true</activeByDefault> </activation> </profile> <profile> <id>prod</id> <properties> <activatedProperties>prod</activatedProperties> </properties> </profile> </profiles> </project><file_sep>/src/main/java/com/alena/jewelryproject/service/sitemap/Urlset.java package com.alena.jewelryproject.service.sitemap; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; @XmlRootElement public class Urlset { private List<Url> url; @XmlAttribute private final String xmlns = "http://www.sitemaps.org/schemas/sitemap/0.9"; @XmlAttribute(name = "xmlns:xsi") private final String xsi = "http://www.w3.org/2001/XMLSchema-instance"; @XmlAttribute(name = "xsi:schemaLocation") private final String schemaLocation = "http://www.sitemaps.org/schemas/sitemap/0.9 " + "http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"; public Urlset() { } public Urlset(List<Url> url) { this.url = url; } public List<Url> getUrl() { return url; } @XmlElement public void setUrl(List<Url> url) { this.url = url; } } <file_sep>/src/main/java/com/alena/jewelryproject/FormatHelper.java package com.alena.jewelryproject; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.SimpleDateFormat; public class FormatHelper { public static DecimalFormatSymbols decimalFormatSymbols = DecimalFormatSymbols.getInstance(); public static SimpleDateFormat formatDate = new SimpleDateFormat("dd.MM.yyyy"); static { decimalFormatSymbols.setGroupingSeparator(' '); } public static DecimalFormat formatter = new DecimalFormat("###,###", decimalFormatSymbols); public enum Currency {RUB, USD} public static String getPriceFormat(Double price) { price = price == null ? 0 : price; StringBuilder sb = new StringBuilder(); sb.append(formatter.format(price)); return sb.toString(); } public static String getPriceFormat(Double price, Currency currency) { price = price == null ? 0 : price; StringBuilder sb = new StringBuilder(); sb.append(formatter.format(price)); sb.append(currency == Currency.RUB ? " \u20BD" : ""); return sb.toString(); } } <file_sep>/src/main/java/com/alena/jewelryproject/spring/MvcConfiguration.java package com.alena.jewelryproject.spring; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class MvcConfiguration implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/about").setViewName("shop/info/about"); registry.addViewController("/payment").setViewName("shop/info/payment"); registry.addViewController("/return").setViewName("shop/info/return"); registry.addViewController("/contacts").setViewName("shop/info/contacts"); } } <file_sep>/src/main/java/com/alena/jewelryproject/model/EmailsLog.java package com.alena.jewelryproject.model; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import java.util.Date; @NoArgsConstructor @Getter @Setter @Entity @Table(name = "emails_log") public class EmailsLog extends IdentifiableEntity { @Column(name = "message") private String message; @Column(name = "from_email") private String from; @Column(name = "to_email") private String to; @Column(name = "created_date") private Date createdDate = new Date(System.currentTimeMillis()); public EmailsLog(String message, String from, String to) { this.message = message; this.from = from; this.to = to; } } <file_sep>/src/main/java/com/alena/jewelryproject/controller/base/ImageHelper.java package com.alena.jewelryproject.controller.base; import com.alena.jewelryproject.model.Image; import com.alena.jewelryproject.model.Jewelry; public class ImageHelper { private Jewelry jewelry; private String contextPath; public ImageHelper(String contextPath) { this.contextPath = contextPath; } public ImageHelper(Jewelry jewelry, String contextPath) { this.jewelry = jewelry; this.contextPath = contextPath; } public static String getImageFullPath(String imageName, String contextPath) { return contextPath + "/image?name=" + imageName; } public String getMainImageFullPath(Jewelry jewelry) { Image mainImage = getMainImage(jewelry); return mainImage != null ? getImageFullPath(mainImage.getName(), contextPath) : ""; } public String getMainImageFullPath() { Image mainImage = getMainImage(jewelry); return mainImage != null ? getImageFullPath(mainImage.getName(), contextPath) : ""; } public String getMainImageFullPathOrDefault() { String path = getMainImageFullPath(); return path.equals("") ? getDefaultImage() : path; } public String getImageFullPath(int index) { Image image = jewelry.getImage(index); return image != null ? getImageFullPath(image.getName(), contextPath) : ""; } public String getImageFullPathOrDefault(int index) { String path = getImageFullPath(index); return path.equals("") ? getDefaultImage() : path; } public String getDefaultImage() { return contextPath + "/resources/images/icons-plus.png"; } private Image getMainImage(Jewelry jewelry) { return jewelry.getImage(0); } } <file_sep>/src/test/java/com/alena/jewelryproject/service/sitemap/SiteMapServiceTest.java package com.alena.jewelryproject.service.sitemap; import com.alena.jewelryproject.service.JewelryService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) public class SiteMapServiceTest { @Autowired private SiteMapService siteMapService; @MockBean private JewelryService jewelryService; @TestConfiguration static class SiteMapServiceTestContextConfiguration { @Bean public SiteMapService siteMapService() { return new SiteMapService(); } } //TODO починить sitemap @Test public void generateUrlsetTest() { // Urlset urlset = siteMapService.generateUrlset(); // assertTrue(urlset.getUrl().size() >= 7); // List<Url> urls = urlset.getUrl(); // assertTrue(urls.stream().anyMatch(url -> url.getLoc().contains("delivery"))); // assertTrue(urls.stream().anyMatch(url -> url.getLoc().contains("about"))); // assertTrue(urls.stream().anyMatch(url -> url.getLoc().contains("payment"))); // assertTrue(urls.stream().anyMatch(url -> url.getLoc().contains("return"))); // assertTrue(urls.stream().anyMatch(url -> url.getLoc().contains("contacts"))); } } <file_sep>/src/main/java/com/alena/jewelryproject/model/PromotionalCode.java package com.alena.jewelryproject.model; import com.alena.jewelryproject.model.enums.PromoCodeType; import lombok.NoArgsConstructor; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.*; import java.util.Date; @NoArgsConstructor @Entity @Table(name = "promotional_code") public class PromotionalCode extends IdentifiableEntity { @Column(name = "code") private String code; @Column(name = "is_active") private Boolean isActive = true; @Enumerated(EnumType.STRING) @Column(name = "promocode_type") private PromoCodeType promoCodeType; @Column(name = "value") private Double value; @Column(name = "max_uses_number") private Integer maxUsesNumber; @Column(name = "current_uses_number") private Integer currentUsesNumber = 0; @DateTimeFormat(pattern = "yyyy-MM-dd") @Column(name = "expiration_date") private Date expirationDate; @Column(name = "max_jewelries") private Integer maxJewelries; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Boolean getActive() { return isActive; } public void setActive(Boolean active) { isActive = active; } public PromoCodeType getPromoCodeType() { return promoCodeType; } public void setPromoCodeType(PromoCodeType promoCodeType) { this.promoCodeType = promoCodeType; } public Double getValue() { return value; } public void setValue(Double value) { this.value = value; } public Integer getMaxUsesNumber() { return maxUsesNumber; } public void setMaxUsesNumber(Integer maxUsesNumber) { this.maxUsesNumber = maxUsesNumber; } public Integer getCurrentUsesNumber() { return currentUsesNumber; } public void setCurrentUsesNumber(Integer currentUsesNumber) { this.currentUsesNumber = currentUsesNumber; } public Date getExpirationDate() { return expirationDate; } public void setExpirationDate(Date expirationDate) { this.expirationDate = expirationDate; } public Integer getMaxJewelries() { return maxJewelries; } public void setMaxJewelries(Integer maxJewelries) { this.maxJewelries = maxJewelries; } } <file_sep>/src/main/resources/db_scripts/schema_mysql.sql create table jewelry ( id int not null AUTO_INCREMENT, name varchar(100), original_price double, price double, description varchar(500), type varchar(50), material_description varchar(500), size varchar(500), weight varchar(500), is_sold tinyint(1) not null default 0, is_hide tinyint(1) not null default 0, created_date DATETIME not null default now(), rating int not null, PRIMARY KEY (id) ); create table image ( id int not null AUTO_INCREMENT, name varchar(100) UNIQUE, jewelry_id int not null, img_index int not null, PRIMARY KEY (id), FOREIGN KEY (jewelry_id) REFERENCES jewelry (id) ); create table promotional_code ( id int not null AUTO_INCREMENT, code varchar(20) not null, is_active tinyint(1) not null, promocode_type varchar(10) not null, value double not null, max_uses_number int, current_uses_number int not null default 0, expiration_date DATETIME, max_jewelries int, PRIMARY KEY (id) ); create table user_order ( id int not null AUTO_INCREMENT, created_date DATETIME not null default now(), promocode_id int, delivery_type varchar(20) not null, payment_type varchar(50) not null, delivery_cost double, discount double, total_cost double, first_name varchar(50), last_name varchar(50), patronymic varchar(50), phone varchar(50), email varchar(50), country varchar(50), city varchar(50), address varchar(100), post_index varchar(50), PRIMARY KEY (id), FOREIGN KEY (promocode_id) REFERENCES promotional_code (id) ); create table order_jewelry ( order_id int not null, jewelry_id int not null, FOREIGN KEY (order_id) REFERENCES user_order (id), FOREIGN KEY (jewelry_id) REFERENCES jewelry (id) ); create table settings ( id int not null AUTO_INCREMENT, s_key varchar(100) not null, s_value varchar(100) not null, description varchar(300), PRIMARY KEY (id) ); create table email_message ( id int not null AUTO_INCREMENT, message varchar(1000) not null, type varchar(10) not null, PRIMARY KEY (id) ); create table emails_log ( id int not null AUTO_INCREMENT, created_date DATETIME not null default now(), message varchar(1000), from_email varchar(50) not null, to_email varchar(50) not null, PRIMARY KEY (id) );<file_sep>/src/main/java/com/alena/jewelryproject/jpa_repositories/EmailsLogRepository.java package com.alena.jewelryproject.jpa_repositories; import com.alena.jewelryproject.model.EmailsLog; import org.springframework.data.jpa.repository.JpaRepository; public interface EmailsLogRepository extends JpaRepository<EmailsLog, Long> { } <file_sep>/src/main/java/com/alena/jewelryproject/model/enums/DeliveryType.java package com.alena.jewelryproject.model.enums; import org.apache.commons.lang3.StringUtils; import java.util.Arrays; import java.util.Optional; public enum DeliveryType { POST_OFFICE("postOffice", "Почта"), PICKUP("pickup", "Самовывоз"), BOXBERRY_MOSCOW("boxberryMoscow", "Boxberry"); private String id; private String name; DeliveryType(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public String getName() { return name; } public static DeliveryType fromId(String id) { if (StringUtils.isNotBlank(id)) { Optional<DeliveryType> optional = Arrays.stream(DeliveryType.values()) .filter(type -> type.getId().equals(id)) .findFirst(); if (optional.isPresent()) { return optional.get(); } } return null; } } <file_sep>/docker/Dockerfile FROM postgres ENV POSTGRES_PASSWORD admin ENV POSTGRES_DB jewelry_db COPY damp_02_02_2022.sql /docker-entrypoint-initdb.d/<file_sep>/src/main/java/com/alena/jewelryproject/controller/admin/EmailAdminController.java package com.alena.jewelryproject.controller.admin; import com.alena.jewelryproject.model.EmailMessage; import com.alena.jewelryproject.model.enums.EmailMessageToType; import com.alena.jewelryproject.service.EmailMessagesService; import com.alena.jewelryproject.service.OrderService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import java.util.HashMap; @Controller @SessionAttributes(value = "email") @RequestMapping("/admin/emails") public class EmailAdminController { private static final Logger log = LoggerFactory.getLogger(EmailAdminController.class); @Autowired private EmailMessagesService emailMessagesService; @Autowired private OrderService orderService; @GetMapping("/list") public ModelAndView getAllEmailMessages() { ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("emailsList", emailMessagesService.getAllEmailMessages()); modelAndView.addObject("orders", orderService.getAllOrders()); modelAndView.setViewName("admin/email_messages_list"); return modelAndView; } @GetMapping("/edit") public ModelAndView editEmailMessage(@RequestParam(value = "id", required = false) Long id) { ModelAndView modelAndView = new ModelAndView(); EmailMessage emailMessage = id != null ? emailMessagesService.getEmailMessage(id) : new EmailMessage(); modelAndView.addObject("emailMsg", emailMessage); modelAndView.addObject("toTypes", EmailMessageToType.values()); modelAndView.setViewName("admin/email_message_edit"); return modelAndView; } @PostMapping("/save") public ModelAndView saveEmailMessage(@RequestParam(value = "id") Long id, @ModelAttribute("emailMsg") EmailMessage emailMessage) { if (id == null) { emailMessagesService.save(emailMessage); } else { emailMessagesService.update(emailMessage); } return new ModelAndView("redirect:/admin/emails/list", new HashMap<>()); } @DeleteMapping("/delete") public @ResponseBody String deleteEmailMessage(@RequestParam(value = "id") Long id) { emailMessagesService.deleteEmailMessage(id); return "ok"; } @PutMapping("/sendEmail") public @ResponseBody String sendEmail(@RequestParam(value = "id") Long emailId, @RequestParam(value = "email") String email, @RequestParam(value = "orderId") Long orderId) { emailMessagesService.sendEmail(emailId, orderService.getOrder(orderId)); return "ok"; } } <file_sep>/src/main/java/com/alena/jewelryproject/spring/JewelrySessionListener.java package com.alena.jewelryproject.spring; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.security.web.session.HttpSessionEventPublisher; import org.springframework.web.context.support.WebApplicationContextUtils; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; public class JewelrySessionListener extends HttpSessionEventPublisher { private static final Logger log = LoggerFactory.getLogger(JewelrySessionListener.class); private static final int SESSION_TIME_SEC = 60 * 60; @Override public void sessionCreated(HttpSessionEvent event) { super.sessionCreated(event); log.info(String.format("Create new user session: id %s", event.getSession().getId())); //Установка таймаута сессии event.getSession().setMaxInactiveInterval(SESSION_TIME_SEC); } @Override public void sessionDestroyed(HttpSessionEvent event) { super.sessionDestroyed(event); } private Object getBean(HttpSessionEvent event, String name) { HttpSession session = event.getSession(); ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(session.getServletContext()); return ctx.getBean(name); } } <file_sep>/src/main/java/com/alena/jewelryproject/controller/admin/RegistrationController.java package com.alena.jewelryproject.controller.admin; import com.alena.jewelryproject.model.User; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller @RequestMapping() public class RegistrationController { private static final Logger log = LoggerFactory.getLogger(RegistrationController.class); @GetMapping("/registration") public String registration(Model model, @RequestParam(value = "msg", required = false) String errorMsg) { log.info("Need to login to admin page"); model.addAttribute("userForm", new User()); if (StringUtils.isNotBlank(errorMsg)) { model.addAttribute("errorMsg", errorMsg); } return "admin/registration"; } } <file_sep>/src/main/java/com/alena/jewelryproject/controller/shop/DeliveryController.java package com.alena.jewelryproject.controller.shop; import com.alena.jewelryproject.service.SettingsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import static com.alena.jewelryproject.service.SettingKeys.*; @Controller @RequestMapping("/delivery") public class DeliveryController { @Autowired private SettingsService settingsService; @GetMapping public ModelAndView getDeliveryInfo() { ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("deliveryPickupAvailableMoscow", settingsService.getSettingByKey(DELIVERY_PICKUP_AVAILABLE_MOSCOW)); modelAndView.addObject("deliveryPickupAvailableSamara", settingsService.getSettingByKey(DELIVERY_PICKUP_AVAILABLE_SAMARA)); String russiaPostOfficeDelivery = settingsService.getSettingByKey(DELIVERY_COST_RUSSIA_POST_OFFICE); modelAndView.addObject("deliveryCost", russiaPostOfficeDelivery); modelAndView.addObject("deliveryFree", SettingsService.isFree(russiaPostOfficeDelivery)); String boxberryMoscowDeliveryCost = settingsService.getSettingByKey(BOXBERRY_MOSCOW_DELIVERY_COST); modelAndView.addObject("boxberryCost", boxberryMoscowDeliveryCost); modelAndView.addObject("boxberryAvailable", settingsService.getSettingByKey(BOXBERRY_MOSCOW_DELIVERY_AVAILABLE)); modelAndView.addObject("boxberryFree", SettingsService.isFree(boxberryMoscowDeliveryCost)); modelAndView.addObject("ukraineDeliveryCost", settingsService.getSettingByKey(DELIVERY_COST_UKRAINE_POST_OFFICE)); modelAndView.addObject("kazakhstanDeliveryCost", settingsService.getSettingByKey(DELIVERY_COST_KAZAKHSTAN_POST_OFFICE)); modelAndView.setViewName("shop/info/delivery"); return modelAndView; } } <file_sep>/src/main/java/com/alena/jewelryproject/model/enums/JewelryType.java package com.alena.jewelryproject.model.enums; import org.apache.commons.lang3.StringUtils; import java.util.Arrays; import java.util.Optional; public enum JewelryType { EARRINGS("earrings", "Серьги"), BRACELET("bracelet", "Браслет"), NECKLACE("necklace", "Колье"), GLASSES_CHAIN("glasses_chain", "Цепи для очков"); private String id; private String name; JewelryType(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public String getName() { return name; } public static JewelryType fromId(String id) { if (StringUtils.isNotBlank(id)) { Optional<JewelryType> optional = Arrays.stream(JewelryType.values()) .filter(type -> type.getId().equals(id)) .findFirst(); if (optional.isPresent()) { return optional.get(); } } return null; } public static final String[] getIds() { return (String[]) Arrays.stream(JewelryType.values()) .map(jewelryType -> jewelryType.id) .toArray(); } } <file_sep>/src/main/java/com/alena/jewelryproject/model/Image.java package com.alena.jewelryproject.model; import com.google.gson.annotations.Expose; import lombok.NoArgsConstructor; import javax.persistence.*; @NoArgsConstructor @Entity @Table(name = "image") public class Image extends IdentifiableEntity { @Expose @Column(name = "name") private String name; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "jewelry_id") private Jewelry jewelry; /* * 0 - main image */ @Expose @Column(name = "img_index") private Integer index; public void setName(String name) { this.name = name; } public String getName() { return name; } public Jewelry getJewelry() { return jewelry; } public void setJewelry(Jewelry jewelry) { this.jewelry = jewelry; } public Integer getIndex() { return index; } public void setIndex(Integer index) { this.index = index; } } <file_sep>/src/main/java/com/alena/jewelryproject/controller/shop/MenuType.java package com.alena.jewelryproject.controller.shop; public enum MenuType { all, only_new, bracelet, earrings, necklace, glasses_chain } <file_sep>/src/main/java/com/alena/jewelryproject/model/enums/PromoCodeType.java package com.alena.jewelryproject.model.enums; import org.apache.commons.lang3.StringUtils; import java.util.Arrays; import java.util.Optional; public enum PromoCodeType { PERCENT("percent", "Процент"), SUM("sum", "Сумма"); private String id; private String name; PromoCodeType(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public String getName() { return name; } public static PromoCodeType fromId(String id) { if (StringUtils.isNotBlank(id)) { Optional<PromoCodeType> optional = Arrays.stream(PromoCodeType.values()) .filter(type -> type.getId().equals(id)) .findFirst(); if (optional.isPresent()) { return optional.get(); } } return null; } } <file_sep>/src/main/java/com/alena/jewelryproject/controller/base/ImageController.java package com.alena.jewelryproject.controller.base; import com.alena.jewelryproject.service.ImageFileService; import com.alena.jewelryproject.service.ImageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller @RequestMapping("/image") public class ImageController { @Autowired private ImageService imageService; @Autowired private ImageFileService imageFileService; @GetMapping public ResponseEntity<byte[]> getImage(@RequestParam(value = "name") String name) { HttpHeaders headers = new HttpHeaders(); byte[] media = imageFileService.loadImage(name); ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(media, headers, HttpStatus.OK); return responseEntity; } } <file_sep>/src/main/java/com/alena/jewelryproject/model/Jewelry.java package com.alena.jewelryproject.model; import com.alena.jewelryproject.FormatHelper; import com.alena.jewelryproject.model.enums.JewelryType; import com.google.gson.annotations.Expose; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import java.util.Date; import java.util.List; @NoArgsConstructor @Getter @Setter @Entity @Table(name = "jewelry") public class Jewelry extends IdentifiableEntity { @Expose @Column(name = "name") private String name; @Expose @Column(name = "original_price") private Double originalPrice; @Expose @Column(name = "price") private Double price; @Expose @Column(name = "description") private String description; @Expose @Enumerated(EnumType.STRING) @Column(name = "type") private JewelryType type; @Expose @OneToMany(mappedBy = "jewelry", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true) private List<Image> images; @Expose @Column(name = "material_description") private String materialDescription; @Expose @Column(name = "size") private String size; @Expose @Column(name = "weight") private String weight; @Expose @Column(name = "is_sold") private Boolean isSold = false; @Expose @Column(name = "is_hide") private Boolean isHide = false; @Column(name = "created_date") private Date createdDate = new Date(System.currentTimeMillis()); @Column(name = "rating") private Integer rating; public Image getImage(int index) { return images != null && !images.isEmpty() ? images.stream() .filter(image -> image.getIndex() == index) .findFirst() .orElse(null) : null; } public String getFormatPrice() { return FormatHelper.getPriceFormat(price, FormatHelper.Currency.RUB); } } <file_sep>/docker/docker-build.sh #!/bin/sh docker_image=docker-jewelry-db build_image() { echo build $1 docker build -t $1 . } push_image() { echo push $1 docker push $1 } #run_image() { # echo run $1 # docker run -d --name docker-jewelry-db -p 5432:5432 docker-jewelry-db #} # $1 - command # $2 - version case "$1" in build) build_image $docker_image:$2 ;; push) push_image $docker_image:$2 ;; *) echo "An error occurred. Build or push command expected" exit 1 ;; esac <file_sep>/src/main/java/com/alena/jewelryproject/controller/base/SiteMapController.java package com.alena.jewelryproject.controller.base; import com.alena.jewelryproject.service.sitemap.SiteMapService; import com.alena.jewelryproject.service.sitemap.Urlset; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/sitemap") public class SiteMapController { @Autowired private SiteMapService siteMapService; @GetMapping @ResponseBody public Urlset getSiteMap() { return siteMapService.generateUrlset(); } } <file_sep>/src/test/java/com/alena/jewelryproject/service/OrderServiceTest.java package com.alena.jewelryproject.service; import com.alena.jewelryproject.jpa_repositories.OrderRepository; import com.alena.jewelryproject.model.Jewelry; import com.alena.jewelryproject.model.Order; import com.alena.jewelryproject.model.PromotionalCode; import com.alena.jewelryproject.model.enums.DeliveryType; import com.alena.jewelryproject.model.enums.PromoCodeType; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.test.context.junit4.SpringRunner; import java.util.Arrays; import static com.alena.jewelryproject.service.SettingKeys.DELIVERY_COST_RUSSIA_POST_OFFICE; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; @RunWith(SpringRunner.class) public class OrderServiceTest { @Autowired private OrderService orderService; @MockBean private PromoCodeService promoCodeService; @MockBean private JewelryService jewelryService; @MockBean private SettingsService settingsService; @MockBean private EmailMessagesService emailMessagesService; @MockBean private OrderRepository orderRepository; @TestConfiguration static class OrderServiceTestContextConfiguration { @Bean public OrderService orderService(OrderRepository orderRepository, PromoCodeService promoCodeService, JewelryService jewelryService, SettingsService settingsService, EmailMessagesService emailMessagesService) { return new OrderService(orderRepository, promoCodeService, jewelryService, settingsService, emailMessagesService); } } @Test public void saveOrder() { Jewelry gracefulWhite = new Jewelry(); gracefulWhite.setId((long) 1); gracefulWhite.setName("Graceful White"); gracefulWhite.setPrice(1000.0); Jewelry gracefulGold = new Jewelry(); gracefulGold.setId((long) 2); gracefulGold.setName("<NAME>"); gracefulGold.setPrice(2500.0); PromotionalCode promotionalCode = new PromotionalCode(); promotionalCode.setCode("pc"); promotionalCode.setActive(true); promotionalCode.setPromoCodeType(PromoCodeType.PERCENT); promotionalCode.setMaxJewelries(1); promotionalCode.setMaxUsesNumber(1); promotionalCode.setCurrentUsesNumber(0); double deliveryCost = 200.0; Order order = new Order(); order.setJewelries(Arrays.asList(gracefulWhite, gracefulGold)); order.setDeliveryCost(deliveryCost); order.setDeliveryType(DeliveryType.POST_OFFICE); order.setPromocode(promotionalCode); given(jewelryService.getJewelry(gracefulWhite.getId())).willReturn(gracefulWhite); given(jewelryService.getJewelry(gracefulGold.getId())).willReturn(gracefulGold); given(settingsService.getSettingByKey(DELIVERY_COST_RUSSIA_POST_OFFICE, "50")).willReturn(String.valueOf(deliveryCost)); given(settingsService.getSettingByKey(SettingKeys.NEW_ORDER_ADMIN_EMAIL_ID)).willReturn(String.valueOf(1)); given(settingsService.getSettingByKey(SettingKeys.NEW_ORDER_CLIENT_EMAIL_ID)).willReturn(String.valueOf(2)); try { orderService.saveOrder(order); verify(promoCodeService).applyPromotionCode(promotionalCode); verify(jewelryService).sellJewelries(order.getJewelries()); verify(orderRepository).save(order); verify(emailMessagesService).sendEmail((long) 1, order); verify(emailMessagesService).sendEmail((long) 2, order); } catch (CreateOrderException e) { e.printStackTrace(); } } }
82612ec41a1ccf193d12147f3ae7665afd8e81e4
[ "SQL", "Maven POM", "Java", "Dockerfile", "Shell" ]
28
Java
alena1112/JewelryProject
276dd87a53bfc39fa33eb8a0281b9ccb9996737b
33a96bfed7d4448001c56da56e85d122fa9f7a0f
refs/heads/master
<file_sep>package com.example.luisito.notasapp.interfaces.reminder; /** * Created by luisito on 12/12/17. */ public interface ReminderPresenter { } <file_sep>package com.example.luisito.notasapp.services; import com.example.luisito.notasapp.models.Mensaje; import com.example.luisito.notasapp.models.Response; import com.example.luisito.notasapp.models.ResponseMensaje; import io.reactivex.Observable; import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.Header; import retrofit2.http.POST; /** * Created by luisito on 10/12/17. */ public interface LoginService { @FormUrlEncoded @POST("api/signIn") Call<Response> login(@Field("correo") String email, @Field("contrasena") String password,@Field("token")String token); @FormUrlEncoded @POST("api/signUp") Call<Response> signUp(@Field("correo") String email, @Field("contrasena") String password,@Field("token") String token); @POST("api/logout") Call<ResponseMensaje> logout(@Header("Authorization")String auth); } <file_sep>package com.example.luisito.notasapp.interfaces.reminder; /** * Created by luisito on 12/12/17. */ public interface ReminderView { } <file_sep>package com.example.luisito.notasapp.interfaces.settings; /** * Created by luisito on 10/12/17. */ public interface SettingsInteractor { void load(); void save(String name,String lastName,String email); } <file_sep>package com.example.luisito.notasapp.interactors; import android.util.Log; import com.example.luisito.notasapp.interfaces.reminder.ReminderInteractor; import com.example.luisito.notasapp.models.ResponseMensaje; import com.example.luisito.notasapp.services.ReminderService; import com.example.luisito.notasapp.utils.Util; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class ReminderInteractorImp implements ReminderInteractor { private Retrofit retrofit; private ReminderService service; public ReminderInteractorImp() { retrofit = new Retrofit .Builder() .baseUrl(Util.URL) .addConverterFactory(GsonConverterFactory.create()) .build(); service = retrofit.create(ReminderService.class); } @Override public void createReminder(String titulo, String fecha) { Call<ResponseMensaje> response = service.createReminder(Util.TOKEN,titulo,fecha); response.enqueue(new Callback<ResponseMensaje>() { @Override public void onResponse(Call<ResponseMensaje> call, Response<ResponseMensaje> response) { Log.e("Respuesta",response.body().getMensaje()); } @Override public void onFailure(Call<ResponseMensaje> call, Throwable t) { Log.e("Respuesta",t.toString()); } }); } @Override public void updateReminder(int id, String titulo, String fecha) { Call<ResponseMensaje> response = service.updateReminder(Util.TOKEN,id,titulo,fecha); response.enqueue(new Callback<ResponseMensaje>() { @Override public void onResponse(Call<ResponseMensaje> call, Response<ResponseMensaje> response) { } @Override public void onFailure(Call<ResponseMensaje> call, Throwable t) { } }); } @Override public void deleteReminder(int id) { Call<ResponseMensaje> response = service.deleteReminder(Util.TOKEN,id); response.enqueue(new Callback<ResponseMensaje>() { @Override public void onResponse(Call<ResponseMensaje> call, Response<ResponseMensaje> response) { } @Override public void onFailure(Call<ResponseMensaje> call, Throwable t) { } }); } } <file_sep>package com.example.luisito.notasapp.services; import com.example.luisito.notasapp.models.Response; import com.example.luisito.notasapp.models.ResponseMensaje; import com.example.luisito.notasapp.models.ResponseNota; import com.example.luisito.notasapp.models.ResponseNotas; import retrofit2.Call; import retrofit2.http.DELETE; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Path; /** * Created by luisito on 10/12/17. */ public interface NoteService { @GET("api/nota") Call<ResponseNotas> getNotas(@Header("Authorization")String auth); @FormUrlEncoded @POST("api/nota") Call<ResponseMensaje> saveNota(@Header("Authorization")String auth, @Field("titulo")String title, @Field("contenido") String content); @DELETE("api/nota/{id}") Call<ResponseMensaje> deleteNota(@Header("Authorization")String auth, @Path("id") int id); @FormUrlEncoded @PUT("api/nota/{id}") Call<ResponseMensaje> updateNota(@Header("Authorization")String auth,@Path("id") int id, @Field("titulo")String title, @Field("contenido") String content); //Note shared @FormUrlEncoded @POST("api/compartir") Call<ResponseMensaje> sharedNota(@Header("Authorization")String auth,@Field("id") int id,@Field("correo") String email); @GET("api/notas-compartidas") Call<ResponseNotas> getNotasCompartidas(@Header("Authorization")String auth); @DELETE("api/notas-compartidas/{id}") Call<ResponseMensaje> deleteCompartidas(@Header("Authorization")String auth,@Path("id") int id); } <file_sep>package com.example.luisito.notasapp.presenters; import com.example.luisito.notasapp.interactors.SettingsInteractorImp; import com.example.luisito.notasapp.interfaces.settings.SettingsInteractor; import com.example.luisito.notasapp.interfaces.settings.SettingsPresenter; import com.example.luisito.notasapp.interfaces.settings.SettingsView; /** * Created by luisito on 10/12/17. */ public class SettingsPresenterImp implements SettingsPresenter { private SettingsView view; private SettingsInteractor interactor; public SettingsPresenterImp(SettingsView view) { this.view = view; interactor = new SettingsInteractorImp(this); } @Override public void saveSettingsPresenter(String name, String lastName,String email) { if(view !=null) { view.showProgress(true); interactor.save(name,lastName,email); } } @Override public void showMessage(String message) { if(view !=null) { view.showProgress(false); view.showMessage(message); } } @Override public void loadSettingsPresenter(String name,String lastName,String email) { if(view !=null) { view.showProgress(false); view.loadInfo(name,lastName,email); } } @Override public void load() { if(view != null) { view.showProgress(true); interactor.load(); } } } <file_sep>package com.example.luisito.notasapp.interactors; import android.util.Log; import com.example.luisito.notasapp.interfaces.mynotes.MyNotesInteractor; import com.example.luisito.notasapp.interfaces.mynotes.MyNotesPresenter; import com.example.luisito.notasapp.models.ResponseMensaje; import com.example.luisito.notasapp.models.ResponseNota; import com.example.luisito.notasapp.models.ResponseNotas; import com.example.luisito.notasapp.services.NoteService; import com.example.luisito.notasapp.utils.Util; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by luisito on 10/12/17. */ public class MyNotesInteractorImp implements MyNotesInteractor { private MyNotesPresenter presenter; private Retrofit retrofit; private NoteService service; public MyNotesInteractorImp(MyNotesPresenter presenter) { this.presenter = presenter; retrofit = new Retrofit.Builder() .baseUrl(Util.URL) .addConverterFactory(GsonConverterFactory.create()) .build(); service = retrofit.create(NoteService.class); } @Override public void loadNotes() { Call<ResponseNotas> responseNotasCall = service.getNotas(Util.TOKEN); responseNotasCall.enqueue(new Callback<ResponseNotas>() { @Override public void onResponse(Call<ResponseNotas> call, Response<ResponseNotas> response) { if(response.body().getCode() == 200) presenter.loadSuccess(response.body().getNotas()); else presenter.showMessage(response.body().getMensaje()); } @Override public void onFailure(Call<ResponseNotas> call, Throwable t) { presenter.showMessage(t.getMessage()); } }); } @Override public void updateNote(int id, String title, String content) { Call<ResponseMensaje> response = service.updateNota(Util.TOKEN,id,title,content); response.enqueue(new Callback<ResponseMensaje>() { @Override public void onResponse(Call<ResponseMensaje> call, Response<ResponseMensaje> response) { presenter.showMessage(response.body().getMensaje()); } @Override public void onFailure(Call<ResponseMensaje> call, Throwable t) { presenter.showMessage(t.getMessage()); } }); } @Override public void deleteNote(int id) { Call<ResponseMensaje> response = service.deleteNota(Util.TOKEN,id); response.enqueue(new Callback<ResponseMensaje>() { @Override public void onResponse(Call<ResponseMensaje> call, Response<ResponseMensaje> response) { presenter.showMessage(response.body().getMensaje()); } @Override public void onFailure(Call<ResponseMensaje> call, Throwable t) { presenter.showMessage(t.getMessage()); } }); } @Override public void saveNote(String title, String content) { Call<ResponseMensaje> response = service.saveNota(Util.TOKEN,title,content); response.enqueue(new Callback<ResponseMensaje>() { @Override public void onResponse(Call<ResponseMensaje> call, Response<ResponseMensaje> response) { presenter.showMessage(response.body().getMensaje()); } @Override public void onFailure(Call<ResponseMensaje> call, Throwable t) { presenter.showMessage(t.getMessage()); } }); } @Override public void sharedNote(int idNote, String email) { final Call<ResponseMensaje> response = service.sharedNota(Util.TOKEN,idNote,email); response.enqueue(new Callback<ResponseMensaje>() { @Override public void onResponse(Call<ResponseMensaje> call, Response<ResponseMensaje> response) { presenter.showMessage(response.body().getMensaje()); } @Override public void onFailure(Call<ResponseMensaje> call, Throwable t) { presenter.showMessage(t.getMessage()); } }); } } <file_sep>package com.example.luisito.notasapp.views.activities; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Toast; import com.example.luisito.notasapp.R; import com.example.luisito.notasapp.interfaces.settings.SettingsPresenter; import com.example.luisito.notasapp.interfaces.settings.SettingsView; import com.example.luisito.notasapp.presenters.SettingsPresenterImp; public class SettingsActivity extends AppCompatActivity implements SettingsView, View.OnClickListener { private EditText name; private EditText lastName; private EditText email; private Button save; private ProgressBar progressBar; private SettingsPresenter presenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); progressBar = (ProgressBar) findViewById(R.id.settings_progress); name = (EditText) findViewById(R.id.settings_name); lastName = (EditText) findViewById(R.id.settings_last_name); email = (EditText) findViewById(R.id.settings_email); save = (Button) findViewById(R.id.settings_save); save.setOnClickListener(this); presenter = new SettingsPresenterImp(this); presenter.load(); } @Override public void showProgress(boolean option) { if(option) progressBar.setVisibility(View.VISIBLE); else progressBar.setVisibility(View.GONE); } @Override public void showMessage(String message) { Toast.makeText(this, message,Toast.LENGTH_SHORT).show(); } @Override public void loadInfo(String name, String lastName, String email) { this.name.setText(name); this.lastName.setText(lastName); this.email.setText(email); } @Override public void onClick(View v) { if(v.getId() == R.id.settings_save) { String name,lastName,email; name = this.name.getText().toString(); lastName = this.lastName.getText().toString(); email = this.email.getText().toString(); presenter.saveSettingsPresenter(name,lastName,email); } } } <file_sep>package com.example.luisito.notasapp.interactors; import android.widget.Toast; import com.example.luisito.notasapp.interfaces.settings.SettingsInteractor; import com.example.luisito.notasapp.interfaces.settings.SettingsPresenter; import com.example.luisito.notasapp.models.ResponseUsuario; import com.example.luisito.notasapp.models.Usuario; import com.example.luisito.notasapp.services.UsuarioService; import com.example.luisito.notasapp.utils.Interactor; import com.example.luisito.notasapp.utils.Util; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by luisito on 10/12/17. */ public class SettingsInteractorImp extends Interactor implements SettingsInteractor { private SettingsPresenter presenter; private UsuarioService service; public SettingsInteractorImp(SettingsPresenter presenter) { this.presenter = presenter; retrofit = new Retrofit.Builder() .baseUrl(Util.URL) .addConverterFactory(GsonConverterFactory.create()) .build(); service = retrofit.create(UsuarioService.class); } @Override public void load() { Call<ResponseUsuario> usuario = service.getUsuario(Util.TOKEN); usuario.enqueue(new Callback<ResponseUsuario>() { @Override public void onResponse(Call<ResponseUsuario> call, Response<ResponseUsuario> response) { if(response.body().getCode() == 200) { presenter.loadSettingsPresenter( response.body().getUsuario().getNombre(), response.body().getUsuario().getApaterno()+" "+response.body().getUsuario().getAmaterno(), response.body().getUsuario().getCorreo()); }else{ presenter.showMessage("No se encontro tu usuario"); } } @Override public void onFailure(Call<ResponseUsuario> call, Throwable t) { presenter.showMessage("No cargo"); } }); } @Override public void save(String name, String lastName, String email) { String []last = lastName.split(" "); Call<ResponseUsuario> save; if(last.length == 2) save = service.putUsuario(Util.TOKEN,name,last[0],last[1]); else save = service.putUsuario(Util.TOKEN,name,lastName,""); save.enqueue(new Callback<ResponseUsuario>() { @Override public void onResponse(Call<ResponseUsuario> call, Response<ResponseUsuario> response) { presenter.showMessage(response.body().getMensaje()); } @Override public void onFailure(Call<ResponseUsuario> call, Throwable t) { presenter.showMessage(t.toString()); } }); } } <file_sep>package com.example.luisito.notasapp.interfaces.login; /** * Created by luisito on 10/12/17. */ public interface LoginPresenter { void showErrorPresenter(String result); void showResultPresenter(Boolean success); void loginPresenter(String email,String password,String token); void signUp(String email,String password,String token); } <file_sep>package com.example.luisito.notasapp.interfaces.settings; /** * Created by luisito on 10/12/17. */ public interface SettingsPresenter { void saveSettingsPresenter(String name,String lastName,String email); void showMessage(String message); void loadSettingsPresenter(String name,String lastName,String email); void load(); } <file_sep>package com.example.luisito.notasapp.interfaces.sharednotes; import com.example.luisito.notasapp.models.Nota; import java.util.List; /** * Created by luisito on 12/12/17. */ public interface MyNotesSharedPresenter { void loadNotesPresenter(); void loadSuccess(List<Nota> notas); void loadFail(String message); void deleteNote(int id); void success(String message); } <file_sep>package com.example.luisito.notasapp.views.fragments; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.Toast; import com.example.luisito.notasapp.R; import com.example.luisito.notasapp.interfaces.sharednotes.MyNotesSharedPresenter; import com.example.luisito.notasapp.interfaces.sharednotes.MyNotesSharedView; import com.example.luisito.notasapp.models.Nota; import com.example.luisito.notasapp.presenters.MyNotesPresenterImp; import com.example.luisito.notasapp.presenters.MyNotesSharedPresenterImp; import com.example.luisito.notasapp.views.adapters.MyNotesAdapter; import com.example.luisito.notasapp.views.adapters.MyNotesSharedAdapter; import java.util.List; /** * A simple {@link Fragment} subclass. */ public class MyNotesSharedFragment extends Fragment implements MyNotesSharedView { private View rootView; private RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager mLayoutManager; private List<Nota> notas; private ProgressBar progress; private MyNotesSharedPresenter presenter; public MyNotesSharedFragment() {} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.fragment_my_notes_shared, container, false); progress = (ProgressBar) rootView.findViewById(R.id.myNotesShared_progress); presenter = new MyNotesSharedPresenterImp(this); //Para el recycler mRecyclerView = (RecyclerView) rootView.findViewById(R.id.myNotesShared_recycler); mRecyclerView.setHasFixedSize(true); mLayoutManager = new LinearLayoutManager(this.getContext()); mRecyclerView.setLayoutManager(mLayoutManager); presenter.loadNotesPresenter(); return rootView; } @Override public void showProgress(boolean option) { if(option) progress.setVisibility(View.VISIBLE); else progress.setVisibility(View.GONE); } @Override public void showMessage(String message) { Toast.makeText(this.getContext(),message,Toast.LENGTH_SHORT).show(); presenter.loadNotesPresenter(); } @Override public void loadMyNotesView(List<Nota> notas) { this.notas = notas; mAdapter = new MyNotesSharedAdapter(presenter,notas); mRecyclerView.setAdapter(mAdapter); } @Override public void refresh() { presenter.loadNotesPresenter(); } } <file_sep>package com.example.luisito.notasapp.interfaces.mynotes; /** * Created by luisito on 10/12/17. */ public interface MyNotesInteractor { void loadNotes(); void updateNote(int id,String title,String content); void deleteNote(int id); void saveNote(String title,String content); void sharedNote(int idNote,String email); }
e469b521566d691aa3810ee725a7449823d532e0
[ "Java" ]
15
Java
Altamira07/NotasApp
d17e15e4900dab423b74da7dc12360db038d3929
21b5b20417dd6537cc0052a5c51061595ca0f3ae
refs/heads/master
<file_sep>package tpjpa3; import entities.ElectronicDevice; import entities.Heater; import entities.Home; import entities.Person; public class JpaTest { /** * @param args */ public static void main(String[] args) { Heater heat1 = new Heater("Salon",1000); Heater heat2 = new Heater("Cuisine",750); ElectronicDevice ed = new ElectronicDevice("SecheLinge",5000); ElectronicDevice ed2 = new ElectronicDevice("Fraiseuse",10000); Home h1 = new Home("Chateau",250,7); Home h2 = new Home("La banque",1120,14); h1.addHeater(heat1); h1.addHeater(heat2); h1.addDevice(ed); h1.addDevice(ed2); PersonDAOImpl persDao = new PersonDAOImpl(); Person p = persDao.createPerson("Oncle","Picsou","<EMAIL>"); p.setNom("Donald"); p.addHome(h1); p.addHome(h2); persDao.update(p); } }
97986be5f9a72be677d3e775c20842c96865554a
[ "Java" ]
1
Java
jbrulez/TP3
c32835fb26974e1179f7d5fdafff3d103db82708
f5dd716da2bde5c705bb979607a792911018e8eb
refs/heads/main
<repo_name>ryanleviathan/react-practice<file_sep>/src/services/rickAndMortyApi.js export const getCharacters = () => { return fetch('https://rickandmortyapi.com/api/character') .then(res => res.json()) .then(json => json.results); }; export const getCharacter = (id) => { return fetch( `https://rickandmortyapi.com/api/character/${id}`) .then(res => res.json()) .then(json => json.results); }; <file_sep>/src/components/DetailPage.jsx import React, { Component } from 'react'; import { getCharacters } from '../services/rickAndMortyApi'; import Detail from './Detail'; export default class DetailPage extends Component { state = { character: [] } componentDidMount() { getCharacters(this.props.match.params.id); } render() { const { character } = this.state; return ( <Detail character={character} /> ); } } <file_sep>/src/components/app/App.jsx import React from 'react'; import AllCharacters from '../AllCharacters.jsx'; import Detail from '../Detail.jsx'; import { BrowserRouter as Router, Switch, Route, } from 'react-router-dom'; export default function App() { return ( <Router> <Switch> <Route path="/" exact render={(routerProps) => <AllCharacters {...routerProps} />} /> <Route path="/charcater/:id" exact render={(routerProps) => <Detail {...routerProps} />} /> </Switch> </Router> ); }
fc86daa2c01ea00b13b720475938b9f46412488d
[ "JavaScript" ]
3
JavaScript
ryanleviathan/react-practice
ea5222dbeff6f6561c0259020ded42a85f3cebec
0a1deff0e4daad5b95739312faf56e96ab779695
refs/heads/master
<file_sep>using UnityEngine; using System.Collections; public class tixScript : MonoBehaviour { void Start () { GetComponent<Renderer> ().enabled = false; } void Update () { if (Input.GetMouseButtonDown (2)) { GetComponent<Renderer> ().enabled = true; } } } <file_sep>using UnityEngine; using UnityEditor; using System.Collections; using System.Reflection; public class BuildTool { static string[] levels = new string[] { "Assets/Apartment Scene.unity" }; [MenuItem("Build Tools/Select Platform/WinPlayer")] static void SelectPlatform_WinPlayer() { EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTarget.StandaloneWindows); } [MenuItem("Build Tools/Select Platform/WinPlayer", true)] static bool ValidatePlatform_WinPlayer() { return EditorUserBuildSettings.activeBuildTarget != BuildTarget.StandaloneWindows; } private static void BuildPlayerImpl(string output, bool arch64 = false) { BuildTarget target = EditorUserBuildSettings.activeBuildTarget; SelectPlatform_WinPlayer(); UnityEditor.BuildOptions options = BuildOptions.None; BuildPipeline.BuildPlayer(levels, output, arch64?BuildTarget.StandaloneWindows64:BuildTarget.StandaloneWindows, options); EditorUserBuildSettings.SwitchActiveBuildTarget(target); } [MenuItem("Build Tools/Build/Build Mechdyne Cluster 32bit Player")] static void BuildMechdyneClusterPlayer() { BuildPlayerImpl("Build/Room_of_Shadows/Room_of_Shadows.exe"); } [MenuItem("Build Tools/Build/Build Mechdyne Cluster 64bit Player")] static void BuildMechdyneClusterPlayer64() { BuildPlayerImpl("Build/Room_of_Shadows_x64/Room_of_Shadows_x64.exe", true); } } <file_sep>var target : Transform; var edgeBorder = 0.1; var horizontalSpeed = 360.0; var verticalSpeed = 120.0; var minVertical = 20.0; var maxVertical = 85.0; private var x = 0.0; private var y = 0.0; private var distance = 0.0; function Start() { x = transform.eulerAngles.y; y = transform.eulerAngles.x; distance = (transform.position - target.position).magnitude; } function LateUpdate() { var dt = Time.deltaTime; x -= Input.GetAxis("Horizontal") * horizontalSpeed * dt; y += Input.GetAxis("Vertical") * verticalSpeed * dt; y = ClampAngle(y, minVertical, maxVertical); var rotation = Quaternion.Euler(y, x, 0); var position = rotation * Vector3(0.0, 0.0, -distance) + target.position; transform.rotation = rotation; transform.position = position; } static function ClampAngle (angle : float, min : float, max : float) { if (angle < -360) angle += 360; if (angle > 360) angle -= 360; return Mathf.Clamp (angle, min, max); } <file_sep>using UnityEngine; using System.Collections; public class Screenoon : MonoBehaviour { public MovieTexture movTexture; private bool started; private int counter; void Start () { GetComponent <Renderer>().material.mainTexture = movTexture; AudioSource audio = GetComponent <AudioSource>(); GetComponent<AudioSource>().Play(); movTexture.loop = true; GetComponent<Renderer> ().enabled = false; counter = 0; } void Update () { if (Input.GetMouseButtonDown (0)) { counter++; } if (counter == 2) { if (this.transform.name == "leftScreen") { startDisThang (); } if (this.transform.name == "rightScreen") { startDisThang (); } } else if (counter == 1) { if (this.transform.name == "midScreen") { startDisThang (); } } else if (counter == 3) { if (this.transform.name == "topScreen") { startDisThang (); } if (this.transform.name == "leftScreen" || this.transform.name == "rightScreen") { stopDisThang (); } counter++; } if (Input.GetMouseButtonDown (1)) { counter = 0; stopDisThang (); } } void startDisThang(){ movTexture.Play(); GetComponent<Renderer> ().enabled = true; } void stopDisThang(){ movTexture.Stop (); GetComponent<Renderer> ().enabled = false; } }
90f53b59004f0f1f4ad4f4854c5fe8f6fe7f3c0e
[ "JavaScript", "C#" ]
4
C#
kevinvle/Quackhack
c794c8f72458cad560992e4ab419e29d2af6136d
69fa8bc0b72ad252909f4b8fd2146215d4586e84
refs/heads/principal
<file_sep>package projeto_final; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.Select; public class RegistrationPage { @FindBy(css = "#menu-item-374 > a") private WebElement linkRegistration; @FindBy(id="name_3_firstname") private WebElement txtFirstName; @FindBy(id="name_3_lastname") private WebElement txtLastName; @FindBy(name="dropdown_7") private WebElement selectPais; @FindBy(id="mm_date_8") private WebElement selectMes; @FindBy(id="dd_date_8") private WebElement selectDia; @FindBy(id="yy_date_8") private WebElement selectAno; @FindBy(css="#pie_register > li:nth-child(2) > div > div > input:nth-child(2)") private WebElement checkSolteiro; @FindBy(css="#pie_register > li:nth-child(3) > div > div.radio_wrap > input:nth-child(2)") private WebElement checkDanca; @FindBy(id="phone_9") private WebElement txtCelular; @FindBy(id="username") private WebElement txtUsuario; @FindBy(id="email_1") private WebElement txtEmail; @FindBy(id="password_2") private WebElement txtSenha; @FindBy(id="confirm_password_password_2") private WebElement txtConfirmacao; @FindBy(name="pie_submit") private WebElement btnSubmit; @FindBy(className="piereg_message") private WebElement mensagemSucesso; @FindBy(css="#pie_register > li:nth-child(1) > div.fieldset.error > div.legend_txt > span") private WebElement mensagemObrigatoriedadeNome; @FindBy(css="#pie_register > li:nth-child(6) > div > div > span") private WebElement mensagemQtdeMinima; public RegistrationPage(WebDriver driver) { PageFactory.initElements(driver, this); } public void clicaEmRegistrationLink() { linkRegistration.click(); } public void preencheNome(String firstName, String lastName) { txtFirstName.sendKeys(firstName); txtLastName.sendKeys(lastName); } public void preencheEstadoCivilSolteiro() { checkSolteiro.click(); } public void escolheDance() { checkDanca.click(); } public void escolhePais(String pais) { Select select = new Select(selectPais); select.selectByVisibleText(pais); } public void preencheDataNascimento(String dia, String mes, String ano) { Select select = new Select(selectMes); select.selectByVisibleText(mes); select = new Select(selectDia); select.selectByVisibleText(dia); select = new Select(selectAno); select.selectByVisibleText(ano); } public void preencheDadosDeContato(String cellPhone, String domainName, String emailAddress) { txtCelular.sendKeys(cellPhone); txtUsuario.sendKeys(domainName); txtEmail.sendKeys(emailAddress); } public void digitaSenhaEConfirmacao(String senha, String confirmacao) { txtSenha.sendKeys(senha); txtConfirmacao.sendKeys(confirmacao); } public void enviaFormulario() { btnSubmit.click(); } public boolean mensagemSucessoRegistroApareceu() { return mensagemSucesso.isDisplayed(); } public boolean mensagemSucessoEstaCorreta() { return mensagemSucesso.getText().equals("Thank you for your registration"); } public boolean mensagemObrigatoriedadeNomeApareceu() { return mensagemObrigatoriedadeNome.isDisplayed(); } public boolean mensagemQtdeMinimaApareceu() { return mensagemQtdeMinima.isDisplayed(); } } <file_sep>package cap_08; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class CadastroFacebookPage { WebDriver driver; public CadastroFacebookPage(WebDriver driver) { this.driver = driver; } public CadastroFacebookPage preencheNome(String nome) { driver.findElement(By.name("firstname")).sendKeys(nome); return this; } public CadastroFacebookPage preencheSobrenome(String sobrenome) { driver.findElement(By.name("lastname")).sendKeys(sobrenome); return this; } public CadastroFacebookPage preencheUsuario(String usu) { driver.findElement(By.id("email")).sendKeys(usu); return this; } public CadastroFacebookPage preencheSenha(String senha) { driver.findElement(By.id("pass")).sendKeys(senha); return this; } public void clicaBotaoEntrar() { driver.findElement(By.id("u_0_2")).click(); } public void logarComo(String user, String pass) { preencheUsuario(user).preencheSenha(pass).clicaBotaoEntrar(); } }<file_sep>package cap_09; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; public class ExemploEsperaPersonalizada { static WebDriver driver; public static void aguardaAteQueValueMude(final WebElement element) { WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { String value = element.getAttribute("value"); if(!value.equals("")) { return true; } return false; } }); } } <file_sep>package cap_06; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; public class CadastroFacebookTest { WebDriver driver; @Before public void antes() { System.setProperty("webdriver.chrome.driver", "/Users/rafaelpeixotosilva/Downloads/chromedriver"); driver = new ChromeDriver(); driver.get("http://www.facebook.com"); } @Test public void cadastroFacebookComSucesso() throws InterruptedException { driver.findElement(By.name("firstname")).sendKeys("João"); driver.findElement(By.name("lastname")).sendKeys("<NAME>"); driver.findElement(By.name("reg_email__")).sendKeys("<EMAIL>"); driver.findElement(By.name("reg_email_confirmation__")).sendKeys("<EMAIL>"); driver.findElement(By.name("reg_passwd__")).sendKeys("<PASSWORD>."); WebElement comboDia = driver.findElement(By.id("day")); Select select = new Select(comboDia); select.selectByVisibleText("15"); WebElement comboMes = driver.findElement(By.id("month")); select = new Select(comboMes); select.selectByVisibleText("Jun"); WebElement comboAno = driver.findElement(By.id("year")); select = new Select(comboAno); select.selectByVisibleText("1980"); driver.findElement(By.id("u_0_7")).click(); driver.findElement(By.name("websubmit")).click(); } // @After public void depois() { driver.quit(); } } <file_sep>package projeto_final; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import com.github.javafaker.Faker; public class RegistrationTest { private WebDriver driver; private RegistrationPage page; @Before public void preCondicao() { System.setProperty("webdriver.chrome.driver", "/Users/rafaelpeixotosilva/Downloads/chromedriver"); driver = new ChromeDriver(); driver.manage().window().fullscreen(); driver.get("http://demoqa.com/"); page = new RegistrationPage(driver); page.clicaEmRegistrationLink(); } @Test public void deveCriarUmRegistro() { Faker faker = new Faker(); String primeiroNome = faker.name().firstName(); String ultimoNome = faker.name().lastName(); page.preencheNome(primeiroNome, ultimoNome); page.preencheEstadoCivilSolteiro(); page.escolheDance(); page.escolhePais("Brazil"); page.preencheDataNascimento("15", "5", "1990"); String user = primeiroNome + "_" + ultimoNome; page.preencheDadosDeContato("0123456789", user, user + "@gmail.com"); page.digitaSenhaEConfirmacao("<PASSWORD>", "<PASSWORD>"); page.enviaFormulario(); Assert.assertTrue(page.mensagemSucessoRegistroApareceu()); Assert.assertTrue(page.mensagemSucessoEstaCorreta()); } @Test public void deveAvisarObrigatoriedadeDeSobrenome() { page.preencheNome("Maria", ""); page.preencheEstadoCivilSolteiro(); Assert.assertTrue(page.mensagemObrigatoriedadeNomeApareceu()); } @Test public void deveValidarQuantidadeMinimaDeDigitosDeTelefone() { page.preencheDadosDeContato("123456789", "teste", "teste"); Assert.assertTrue(page.mensagemQtdeMinimaApareceu()); } @After public void posCondicao() { driver.quit(); } }<file_sep>package cap_08; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class TestaLoginFacebook { private CadastroFacebookPage facebook; private WebDriver driver; @Before public void preCondicao() { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); driver = new ChromeDriver(); driver.get("https://www.facebook.com/"); facebook = new CadastroFacebookPage(driver); } @Test public void deveLogarComSucesso() { // Passe seu usuário e senha corretos facebook.logarComo("Seu usuario", "Sua senha"); } @Test public void naoDeveLogarSemSenha() { // Deixei a senha em branco facebook.logarComo("Seu usuario", ""); } @Test public void naoDeveLogarComSenhaErrada() { // Passe uma senha errada facebook.logarComo("Seu usuario", "Sua senha"); } @After public void posCondicao() { driver.quit(); } } <file_sep># Selenium WebDriver - Descomplicando Testes com Java Aqui você encontrará exemplos do livro `Selenium WebDriver - Descomplicando Testes com Java`. Clique [aqui](src/test/java) para ver os exemplos de cada capítulo. *Em breve, mais exemplos.* Não tem o livro ainda? Você pode adquirir diretamente na [Casa do Código](https://www.casadocodigo.com.br/products/livro-selenium-webdriver) ou na [Amazon](https://www.amazon.com.br/Selenium-WebDriver-Descomplicando-testes-automatizados-ebook/dp/B07FMJXZ27) no formato físico ou digital. Dúvidas? Entre em contato comigo através do e-mail: <EMAIL><file_sep>package cap_07; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class UsandoAsserts { private static WebDriver driver; @BeforeClass public static void inicializa() { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); driver = new ChromeDriver(); driver.get("http://www.google.com"); } @Test public void verificaSeTituloEstaCorreto() { String titulo = driver.getTitle(); boolean tituloEstaCorreto = titulo.equals("Google"); Assert.assertTrue(tituloEstaCorreto); // aqui está nosso Assert } @AfterClass public static void finaliza() { driver.quit(); } }
350133e9e02e5b79dda24f7680e42e72343ed12c
[ "Markdown", "Java" ]
8
Java
rapesil/livro-selenium-webdriver
7f46d489cb107dd332908bccacaffec3c27e0933
ea490b9da4a418859f2b94f0d77de02b3e8748b5
refs/heads/master
<file_sep>package com.train.excel.utils; /** * * @author and04 * */ public interface FilePathConstants { String UPLOAD_SRC_FILE_PATH = "/upload/sourcefile"; // 源文件的路径 String UPLOAD_RESULT_FILE_PATH = "/upload/resultfile"; // 分析后的结果文件的路径 String FILE_EXTENSION_NAME_XLSX = ".xlsx"; } <file_sep>package com.train.excel.dao; import java.util.List; import com.train.excel.controller.dto.FileDto; import com.train.excel.domain.ResultFile; /** * * @author and04 * */ public interface ResultFileDao { /** * * @param rf */ void save(ResultFile rf); /** * * @param id */ void deleteById(Long id); /** * * @param condition * @return */ List<ResultFile> getWithCondition(FileDto condition); /** * * @param condition * @return */ int getCountWithCondition(FileDto condition); } <file_sep>/** * */ package com.train.excel.service.impl; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import com.train.excel.dao.StationTrainDao; import com.train.excel.domain.StationTrain; import com.train.excel.service.StationTrainService; /** * @author and04 * */ @Named public class StationTrainServiceImpl implements StationTrainService { @Inject private StationTrainDao dao; /* * (non-Javadoc) * * @see * com.train.excel.service.StationTrainService#save(com.train.excel.domain. * StationTrain) */ @Override public void save(StationTrain st) { dao.save(st); } /* * (non-Javadoc) * * @see * com.train.excel.service.StationTrainService#deleteByFileId(java.lang. * String) */ @Override public void deleteByFileId(String fileId) { dao.deleteByFileId(fileId); } /* * (non-Javadoc) * @see com.train.excel.service.StationTrainService#getByFileId(java.lang.String) */ @Override public List<StationTrain> getByFileId(String fileId) { return dao.getByFileId(fileId); } } <file_sep>package com.train.excel.utils; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import com.train.excel.domain.StationTrain; /** * Excel 工具类 * * @author and04 * */ public class ExcelUtil { public static List<StationTrain> excel2List(InputStream in, String fileId, Date upLoadTime) throws EncryptedDocumentException, InvalidFormatException, IOException { List<StationTrain> list = new ArrayList<>(); if (in == null) { return list; } try (Workbook wk = WorkbookFactory.create(in)) { if (wk == null) { return list; } for (Sheet sheet : wk) { for (Row row : sheet) { StationTrain st = new StationTrain(); if (row.getRowNum() == 0) { continue; } st.setSerialNum(getCellValue(row.getCell(0, Row.CREATE_NULL_AS_BLANK))); st.setTrainNum(getCellValue(row.getCell(1, Row.CREATE_NULL_AS_BLANK))); st.setTrainType(getCellValue(row.getCell(2, Row.CREATE_NULL_AS_BLANK))); st.setChangeLong(Double.parseDouble(getCellValue(row.getCell(3, Row.CREATE_NULL_AS_BLANK)))); st.setSelfWeight(Double.parseDouble(getCellValue(row.getCell(4, Row.CREATE_NULL_AS_BLANK)))); st.setLoadWeight(Double.parseDouble(getCellValue(row.getCell(5, Row.CREATE_NULL_AS_BLANK)))); st.setGoodsName(getCellValue(row.getCell(6, Row.CREATE_NULL_AS_BLANK))); st.setFromStation(getCellValue(row.getCell(7, Row.CREATE_NULL_AS_BLANK))); st.setFromBureau(getCellValue(row.getCell(8, Row.CREATE_NULL_AS_BLANK))); st.setToStation(getCellValue(row.getCell(9, Row.CREATE_NULL_AS_BLANK))); st.setToBureau(getCellValue(row.getCell(10, Row.CREATE_NULL_AS_BLANK))); st.setConsignee(getCellValue(row.getCell(11, Row.CREATE_NULL_AS_BLANK))); st.setFileId(fileId); st.setDate(upLoadTime); list.add(st); } } return list; } finally { in.close(); } } /* * 获取各种类型的单元格的值, 并转换成字符串 */ private static String getCellValue(Cell cell) { String value = null; int cellType = cell.getCellType(); switch (cellType) { case Cell.CELL_TYPE_NUMERIC: value = String.valueOf(cell.getNumericCellValue()); if (value.endsWith(".0")) { value = value.split("\\.")[0]; } break; case Cell.CELL_TYPE_BLANK: value = null; break; case Cell.CELL_TYPE_STRING: value = cell.getStringCellValue(); break; case Cell.CELL_TYPE_FORMULA: value = cell.getCellFormula(); break; default: break; } return value; } } <file_sep>/** * */ package com.train.excel.service.impl; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import com.train.excel.controller.dto.FileDto; import com.train.excel.dao.SourceFileDao; import com.train.excel.dao.StationTrainDao; import com.train.excel.domain.ResultFile; import com.train.excel.domain.SourceFile; import com.train.excel.service.SourceFileService; import com.train.excel.utils.FilePathConstants; /** * @author and04 * */ @Named public class SourceFileServiceImpl implements SourceFileService { @Inject private SourceFileDao dao; @Inject private StationTrainDao stDao; /* * (non-Javadoc) * * @see com.train.excel.service.SourceFileService#getByMd5(java.lang.String) */ @Override public SourceFile getByMd5(String md5) { return dao.getByMd5(md5); } /* * (non-Javadoc) * * @see * com.train.excel.service.SourceFileService#save(com.train.excel.domain. * SourceFile) */ @Override public void save(SourceFile sf) { dao.save(sf); } /* * (non-Javadoc) * * @see * com.train.excel.service.SourceFileService#deleteById(java.lang.String) */ @Override public void deleteById(Long id) { dao.deleteById(id); } /* * (non-Javadoc) * * @see * com.train.excel.service.SourceFileService#getWithCondition(com.train. * excel.controller.dto.SourceFileDto) */ @Override public List<SourceFile> getWithCondition(FileDto condition) { return dao.getWithCondition(condition); } /* * (non-Javadoc) * * @see * com.train.excel.service.SourceFileService#getCountWithCondition(com.train * .excel.controller.dto.SourceFileDto) */ @Override public int getCountWithCondition(FileDto condition) { return dao.getCountWithCondition(condition); } /* * (non-Javadoc) * * @see * com.train.excel.service.SourceFileService#deleteFileAndContent(java.lang. * String, java.lang.String, java.lang.String) */ @Override public void deleteFileAndContent(Long id, String fileId, String filePath) throws IOException { dao.deleteById(id); stDao.deleteByFileId(fileId); Files.deleteIfExists(Paths.get(filePath)); } /* * (non-Javadoc) * * @see com.train.excel.service.SourceFileService#analysis(java.lang.String, * java.lang.String) */ @Override public ResultFile analysis(String srcFileId, String srcFileName, String realPath) throws IOException { Path resultFilePath = Paths.get(realPath, srcFileName + FilePathConstants.FILE_EXTENSION_NAME_XLSX); Files.newOutputStream(resultFilePath); return null; } } <file_sep>package com.train.excel.controller; import java.io.IOException; import javax.inject.Inject; import javax.servlet.ServletContext; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.train.excel.domain.Status; import com.train.excel.service.FileUpLoadService; import com.train.excel.utils.FilePathConstants; @RestController @RequestMapping("/upload") public class FileUploadController { @Inject private FileUpLoadService service; @Inject private ServletContext sc; /** * 上传Excel * * @param name * @param file * @return8 * @throws IOException * @throws InvalidFormatException * @throws EncryptedDocumentException */ @RequestMapping(path = "/excel", method = RequestMethod.POST) public Status handleFormUpload(MultipartFile file) throws Exception { if (file != null && !file.isEmpty()) { String destPath = sc.getRealPath(FilePathConstants.UPLOAD_SRC_FILE_PATH); return service.saveContentAndfile(file, destPath); } return new Status(1, "file is empty"); } } <file_sep>jdbc.url=jdbc:mysql:///train jdbc.user=root jdbc.password=<PASSWORD><file_sep>package com.train.excel.service; import java.util.Date; import java.util.UUID; import javax.inject.Inject; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.train.excel.domain.SourceFile; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:beans.xml" }) public class SourceFileServiceTest { @Inject private SourceFileService service; @Test public void testGetByMd5() { String md5 = UUID.randomUUID().toString(); SourceFile file = service.getByMd5(md5); if (file != null) { Assert.assertEquals(md5, file.getMd5()); } } @Test public void testSave() { SourceFile sf = new SourceFile(); sf.setFileId("fdsfd"); sf.setFileName("fileName"); sf.setFilePath("fdsfsd"); sf.setMd5("md5"); sf.setUploadTime(new Date()); service.save(sf); Assert.assertTrue(sf.getId() != null); } } <file_sep>package com.train.excel.dao; import java.util.List; import com.train.excel.domain.StationTrain; /** * * @author and04 * */ public interface StationTrainDao { /** * save * * @param st */ void save(StationTrain st); /** * 根据文件Id删除 * * @param fileId */ void deleteByFileId(String fileId); /** * * @param fileId * @return */ List<StationTrain> getByFileId(String fileId); } <file_sep>use train; DROP TABLE IF EXISTS `t_station_train`; CREATE TABLE `t_station_train` ( `id_` int(11) NOT NULL auto_increment, `file_id_` varchar(255) default NULL, `date_` datetime default NULL, `serial_num_` varchar(255) default NULL, `train_num_` varchar(255) default NULL, `train_type_` varchar(255) default NULL, `change_long_` double default NULL, `self_weight_` double default NULL, `load_weight_` double default NULL, `goods_name_` varchar(255) default NULL, `from_station_` varchar(255) default NULL, `to_station_` varchar(255) default NULL, `from_bureau_` varchar(255) default NULL, `to_bureau_` varchar(255) default NULL, `consignee_` varchar(255) default NULL, PRIMARY KEY (`id_`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; DROP TABLE IF EXISTS `t_source_file`; CREATE TABLE `t_source_file` ( `id_` int(11) NOT NULL auto_increment, `file_id_` varchar(255) default NULL, `file_name_` varchar(255) default NULL, `file_path_` varchar(255) default NULL, `md5_` varchar(255) default NULL, `upload_time_` datetime default NULL, PRIMARY KEY (`id_`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; DROP TABLE IF EXISTS `t_result_file`; CREATE TABLE `t_result_file` ( `id_` int(11) NOT NULL auto_increment, `src_file_id_` varchar(255) default NULL, `file_path_` varchar(255) default NULL, `file_name_` varchar(255) default NULL, `create_time_` datetime default NULL, PRIMARY KEY (`id_`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
47bd88bf00a3b89a3795c347979c1d9468cc73f3
[ "Java", "SQL", "INI" ]
10
Java
and0429/train
c7db7d9e4662826468791a3bc78668a799737a40
8edbbbee82a52b75947186df4f375a9c87e66ecc
refs/heads/master
<repo_name>wjhzkf/steamsamll<file_sep>/src/test/DateTest.java package test; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import taobao.TaobaoController; public class DateTest { public static void main(String[] args) { // TODO Auto-generated method stub Date startDate = new Date(System.currentTimeMillis()); Date endDate = new Date(System.currentTimeMillis()-86400000); System.out.println(startDate); DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); System.out.println(format.format(startDate)); System.out.println(format.format(endDate)); } } <file_sep>/src/selenium/GameObj.java /* * Steam游戏发送到收货邮箱的类 */ package selenium; import java.io.File; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.Point; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.phantomjs.PhantomJSDriverService; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import script.SteamLog; import bean.Game; import bean.SteamGame; import frame.AutoSellerUI; import frame.BatchBuyUI; import frame.CheckValue; import frame.WalletAlertUI; public class GameObj{ private SeleniumMethods seleniumMethods; private BatchBuyUI batchFrame; private AutoSellerUI frame; private Game game; private SteamGame steamGame; private SteamGame uniSteamGame;//万能游戏 private String default_account = null; private String defaule_password = <PASSWORD>; private String default_email = null; private String game_name = null; private String driver_link = null; //账户购买游戏 public Map<String,SteamGame> buySteamGame=null; //是否刷新的变量 private boolean refresh = false; //记录循环购买游戏中更换账户的变量,如果当前账户余额不足或当前账户购买不成功,则使用下一个账号 private static boolean nextBuyGameAccount = false; //记录当前账户的余额 private String currentBalanceStr; private String finalBalanceStr; //记录浏览器的句柄,用于跳区购买游戏 private String handleStart = ""; private String handleEnd = ""; /* * 购买steam游戏需要保存的账户和密码,以及购买游戏的个数 */ public Map<String, String> buyGameAccounts; public List<String> buyGameAccountID; public int gameNum; //保存BuySteamGameXpath的哈希表 public Map<String, String> buySteamGameXpath; //日志 SteamLog log; //创建WebDriver实例 WebDriver driver; WebDriverWait wait; //Selenium模拟键盘 Actions action; public GameObj(){} public GameObj(BatchBuyUI batchFrame){ buySteamGame = new HashMap<String, SteamGame>(); //加载驱动 batchFrame.info_buy_process_Text.setText("!!!正在启动浏览器,请不要重复点击!!!"); this.frame = batchFrame.frame; // Define Chrome Option, create web Driver ChromeOptions options = new ChromeOptions(); options.addExtensions(new File("driver/Block-image_v1.1.crx"), new File("driver/StopFlash-Flash-Blocker_v0.1.5.crx")); System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe"); this.driver = new ChromeDriver(options); this.wait = new WebDriverWait(driver, 15); this.action = new Actions(driver); if(frame.showBrowserWhenRunning){ this.driver.manage().window().setPosition(new Point(0,0)); this.driver.manage().window().setSize(new Dimension(600, 400)); }else{ this.driver.manage().window().setPosition(new Point(-5000,0)); this.driver.manage().window().setSize(new Dimension(600, 400)); } //获取SeleniumMethods实例,并初始化driver和wait this.seleniumMethods = SeleniumMethods.getInstance(); this.seleniumMethods.setDriver(this.driver); this.seleniumMethods.setWait(this.wait); } public String getDefault_account() { return default_account; } public void setDefault_account(String default_account) { this.default_account = default_account; } public String getDefaule_password() { return defaule_password; } public void setDefaule_password(String defaule_password) { this.defaule_password = <PASSWORD>; } public String getDefault_email() { return default_email; } public void setDefault_email(String default_email) { this.default_email = default_email; } public String getGame_name() { return game_name; } public void setGame_name(String game_name) { this.game_name = game_name; }; public String getDriver_link() { return driver_link; } public void setDriver_link(String driver_link) { this.driver_link = driver_link; } public BatchBuyUI getBatchFrame() { return batchFrame; } public void setBatchFrame(BatchBuyUI batchFrame) { this.batchFrame = batchFrame; } public Game getGame() { return game; } public void setGame(Game game) { this.game = game; } public SteamGame getSteamGame() { return steamGame; } public void setSteamGame(SteamGame steamGame) { this.steamGame = steamGame; } public Map<String, String> getBuyGameAccounts() { return buyGameAccounts; } public void setBuyGameAccounts(Map<String, String> buyGameAccounts) { this.buyGameAccounts = buyGameAccounts; } public List<String> getBuyGameAccountID() { return buyGameAccountID; } public void setBuyGameAccountID(List<String> buyGameAccountID) { this.buyGameAccountID = buyGameAccountID; } public int getGameNum() { return gameNum; } public void setGameNum(int gameNum) { this.gameNum = gameNum; } public WebDriver getDriver() { return driver; } public void setDriver(WebDriver driver) { this.driver = driver; } public WebDriverWait getWait() { return wait; } public void setWait(WebDriverWait wait) { this.wait = wait; } public AutoSellerUI getFrame() { return frame; } public void setFrame(AutoSellerUI frame) { this.frame = frame; } public SteamLog getLog() { return log; } public void setLog(SteamLog log) { this.log = log; } public Map<String, String> getBuySteamGameXpath() { return buySteamGameXpath; } public void setBuySteamGameXpath(Map<String, String> buySteamGameXpath) { this.buySteamGameXpath = buySteamGameXpath; } public SteamGame getUniSteamGame() { return uniSteamGame; } public void setUniSteamGame(SteamGame uniSteamGame) { this.uniSteamGame = uniSteamGame; } /* * 调用是否关闭浏览器窗口的函数 */ public void exitBrowAfterRunning(){ if(frame.exitBrowserAfterRunning){ this.driver.quit(); } try { Runtime.getRuntime().exec("cmd /c start /B kill_chromedriver.bat"); }catch(Exception e){}; return; } /* * 取消程序的监听函数,如果 */ public boolean quitCharge(){ if(batchFrame.closeDriverTag){ this.driver.quit(); batchFrame.info_buy_process_Text.setText("!!!成功退出充值,请关闭窗口!!!"); try { Runtime.getRuntime().exec("cmd /c start /B kill_chromedriver.bat"); }catch(Exception e){}; return true; }else{ return false; } } /* * 获取当前账户余额的函数 */ public boolean getCurrentBalance(){ batchFrame.info_buy_process_Text.setText("!!!正在查询当前账户余额,请稍等!!!"); WebElement currentBalanceLink = null; try{ currentBalanceLink = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(this.buySteamGameXpath.get("currentBalanceA")))); }catch(Exception e){ batchFrame.info_buy_process_Text.setText("!!!账户余额查找失败,请检查xpath或重试!!!"); return false; } this.currentBalanceStr = currentBalanceLink.getText(); batchFrame.info_default_account_text.setText(this.default_account+"---账户余额"+this.currentBalanceStr); return true; } /* * 判断账户余额的程序 */ public boolean checkBalance(){ batchFrame.info_buy_process_Text.setText("!!!正在检查余额,请稍等!!!"); // WebElement currentBalanceLink = null; WebElement cartPriceDiv = null; try{ // currentBalanceLink = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(this.buySteamGameXpath.get("currentBalanceA")))); cartPriceDiv = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(this.buySteamGameXpath.get("cartPriceDiv")))); }catch(Exception e){ batchFrame.info_buy_process_Text.setText("!!!账户余额或购物车小计查找失败,请检查xpath或重试!!!"); this.refresh = true; return false; } currentBalanceStr =((JavascriptExecutor)driver).executeScript("var gift=document.getElementById('header_wallet_balance');" + "return gift.textContent;").toString(); String cartPriceStr = cartPriceDiv.getText(); System.out.println(currentBalanceStr+"---"+cartPriceStr); float currentBalance = balanceFormat(this.buySteamGameXpath.get("country"), currentBalanceStr); float cartPrice = balanceFormat(this.buySteamGameXpath.get("country"), cartPriceStr); System.out.println(currentBalance+"---"+cartPrice); finalBalanceStr = Float.toString(currentBalance-cartPrice); if(currentBalance<cartPrice){ this.refresh = false; this.nextBuyGameAccount = true; batchFrame.info_buy_process_Text.setText("!!!账户余额不够,请充值!!!"); //调用自动充值UI // WalletAlertUI walletAlertFrame = new WalletAlertUI(); // walletAlertFrame.setVisible(true); // walletAlertFrame.warningField.setText("账户"+this.default_account+"余额不足!"); return false; } else{ batchFrame.info_buy_process_Text.setText("!!!账户余额充足,继续购买!!!"); return true; } } /* * 针对不同国家地区处理账户余额 */ public float balanceFormat(String country, String balanceStr){ float balance = 0; String bs=""; switch(country){ case "ru": balance = Float.parseFloat((bs=balanceStr.replaceAll(" ", "").replaceAll(",", ".").replaceAll("pуб.", "")).equals("")?"0.0":bs); break; case "us": balance = Float.parseFloat((bs=balanceStr.replaceAll(" ", "").replace("$", "").replace("USD", "").replaceAll(",", "")).equals("")?"0.0":bs); break; case "hk": balance = Float.parseFloat((bs=balanceStr.replaceAll(" ", "").replace("$", "").replace("USD", "").replaceAll(",", "")).equals("")?"0.0":bs); break; case "cn": balance = Float.parseFloat((bs=balanceStr.replaceAll(" ", "").replace("¥", "").replace("USD", "").replaceAll(",", "")).equals("")?"0.0":bs); break; case "ua": balance = Float.parseFloat((bs=balanceStr.replaceAll(" ", "").replace("$", "").replace("USD", "").replaceAll(",", "")).equals("")?"0.0":bs); break; case "br": balance = Float.parseFloat((bs=balanceStr.replaceAll(" ", "").replace("R$", "").replaceAll(",", ".")).equals("")?"0.0":bs); break; case "jp": balance = Float.parseFloat((bs=balanceStr.replaceAll(" ", "").replace("¥", "").replaceAll(",", "")).equals("")?"0.0":bs); break; case "id": balance = Float.parseFloat((bs=balanceStr.replaceAll(" ", "").replace("Rp", "").replaceAll(",", "")).equals("")?"0.0":bs); break; case "my": balance = Float.parseFloat((bs=balanceStr.replaceAll(" ", "").replace("RM", "").replaceAll(",", "")).equals("")?"0.0":bs); break; } return balance; } /* * 针对不同国家地区处理游戏链接 */ public String changeGameLink(String country, String gameLink){ String newSteamGameLink = gameLink; switch(country){ case "ru": newSteamGameLink = gameLink.concat("?cc=ru"); break; case "us": newSteamGameLink = gameLink.concat("?cc=us"); break; case "hk": newSteamGameLink = gameLink.concat("?cc=hk"); break; case "cn": newSteamGameLink = gameLink.concat("?cc=cn"); break; case "ua": newSteamGameLink = gameLink.concat("?cc=ua"); break; case "br": newSteamGameLink = gameLink.concat("?cc=br"); break; case "jp": newSteamGameLink = gameLink.concat("?cc=jp"); break; case "id": newSteamGameLink = gameLink.concat("?cc=id"); break; case "my": newSteamGameLink = gameLink.concat("?cc=my"); break; } System.out.println("真实购买游戏的链接:"+newSteamGameLink); return newSteamGameLink; } /* * 加入到仓库的主函数 */ public boolean addToWare(){ //转到赠送礼物界面,点击“把礼物存放在我的仓库里” WebElement addToWareRadioButton = null; try{ addToWareRadioButton = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(this.buySteamGameXpath.get("addToWareRadioButton")))); }catch(Exception e){ batchFrame.info_buy_process_Text.setText("!!收货邮箱文本框的xpath出错,请更新程序!!"); this.refresh = true; return false; } if(quitCharge()){return false;}; if(!addToWareRadioButton.isSelected()){ addToWareRadioButton.click(); } //输入完邮箱以后,点击确认继续 // WebElement continue_button = null; // try{ // continue_button = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(this.buySteamGameXpath.get("EmailContinueButton")))); // }catch(Exception e){ // batchFrame.info_buy_process_Text.setText("!!收货邮箱处继续按钮的xpath出错,请更新程序!!"); // this.refresh = true; // return false; // } // if(quitCharge()){return false;}; // // try{ // continue_button.click(); // }catch(Exception e){ // this.refresh = true; // return false; // } //调用enter键 this.action.sendKeys(Keys.ENTER).perform(); //页面跳转,需要等待 try { Thread.sleep(6000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //确认购买页面,点击同意条款框,以及继续按钮 WebElement accept_box = null; try{ accept_box = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(this.buySteamGameXpath.get("agreeRadioButton")))); }catch(Exception e){ batchFrame.info_buy_process_Text.setText("!!同意条款选项的xpath出错,请更新程序!!"); this.refresh = true; return false; } if(quitCharge()){return false;}; if(!accept_box.isSelected()){ try{ accept_box.click(); }catch(Exception e){ this.refresh = true; return false; } } WebElement jump_to_WebMoney = null; try{ jump_to_WebMoney = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(this.buySteamGameXpath.get("agreeBuyButton")))); }catch(Exception e){ batchFrame.info_buy_process_Text.setText("!!同意条款出购买按钮的xpath出错,请更新程序!!"); this.refresh = true; return false; } if(quitCharge()){return false;}; try{ jump_to_WebMoney.click(); }catch(Exception e){ this.refresh = true; return false; } return true; } /* * purchase as a gift函数 */ public boolean purchaseAsGift(){ //检查账户余额是否正确,不正确的话则返回错误 if(!checkBalance()){ System.out.println("账户余额不足"); return false; } //转到购物车界面,点击以礼物的方式发给好友 WebElement send_gift_button = null; try{ // send_gift_button = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(this.buySteamGameXpath.get("cartAsPresentButton")))); String openGifts="var gift=document.getElementById('btn_purchase_self').parentElement.children[0];" +"gift.click();"; ((JavascriptExecutor)driver).executeScript(openGifts); }catch(Exception e){ this.refresh = true; System.out.println("错误的地方1~~"+this.buySteamGameXpath.get("cartAsPresentButton")); return false; } return true; } /* * 用于跳区购买游戏的purchase as a gift函数 */ public boolean jumpAreaPurchaseAsGift(){ //转到购物车界面,点击以礼物的方式发给好友 WebElement send_gift_button = null; try{ send_gift_button = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(this.buySteamGameXpath.get("cartAsPresentButton")))); }catch(Exception e){ this.refresh = true; System.out.println("错误的地方1~~"+this.buySteamGameXpath.get("cartAsPresentButton")); return false; } //不需要检查账户余额是否正确 // if(!checkBalance()){ // System.out.println("错误的地方2~~"); // return false; // } // try{ send_gift_button.click(); }catch(Exception e){ System.out.println("错误的地方3~~"); this.refresh = true; return false; } return true; } /* * purchase for myself函数 */ public boolean purchaseForMyself(){ //转到购物车界面,点击为自己购买按钮 WebElement buyForMyselfButton = null; try{ buyForMyselfButton = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(this.buySteamGameXpath.get("buyMyselfButton")))); }catch(Exception e){ this.refresh = true; System.out.println("错误的地方1~~"+this.buySteamGameXpath.get("buyMyselfButton")); return false; } //检查账户余额是否正确,不正确的话则返回错误 if(!checkBalance()){ System.out.println("错误的地方2~~"); return false; } try{ buyForMyselfButton.click(); }catch(Exception e){ System.out.println("错误的地方3~~"); this.refresh = true; return false; } try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //确认购买页面,点击同意条款框,以及继续按钮 WebElement accept_box = null; try{ accept_box = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(this.buySteamGameXpath.get("agreeRadioButton")))); }catch(Exception e){ batchFrame.info_buy_process_Text.setText("!!同意条款选项的xpath出错,请更新程序!!"); this.refresh = true; return false; } if(quitCharge()){return false;}; if(!accept_box.isSelected()){ try{ accept_box.click(); }catch(Exception e){ this.refresh = true; return false; } } WebElement jump_to_WebMoney = null; try{ jump_to_WebMoney = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(this.buySteamGameXpath.get("agreeBuyButton")))); }catch(Exception e){ batchFrame.info_buy_process_Text.setText("!!同意条款出购买按钮的xpath出错,请更新程序!!"); this.refresh = true; return false; } if(quitCharge()){return false;}; try{ jump_to_WebMoney.click(); }catch(Exception e){ this.refresh = true; return false; } return true; } /* * 用电子邮件发送礼物的主函数 */ public boolean sendPresent(){ if(quitCharge()){return false;}; //转到赠送礼物界面,填写相关收货邮箱信息 WebElement buyer_email = null; try{ buyer_email = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(this.buySteamGameXpath.get("sendEmailField")))); }catch(Exception e){ batchFrame.info_buy_process_Text.setText("!!收货邮箱文本框的xpath出错,请更新程序!!"); this.refresh = true; return false; } if(quitCharge()){return false;}; buyer_email.sendKeys(this.default_email); //输入完邮箱以后,点击确认继续 // WebElement continue_button = null; // try{ // continue_button = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(this.buySteamGameXpath.get("EmailContinueButton")))); // }catch(Exception e){ // batchFrame.info_buy_process_Text.setText("!!收货邮箱处继续按钮的xpath出错,请更新程序!!"); // this.refresh = true; // return false; // } // if(quitCharge()){return false;}; // // continue_button.click(); //调用enter键 this.action.sendKeys(Keys.ENTER).perform(); /* try{ continue_button.click(); }catch(Exception e){ this.refresh = true; return false; }*/ //这里的下一步需要等待几秒,设置等待时间 // try { // Thread.sleep(2000); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } if(quitCharge()){return false;}; WebElement buyer_name = null; WebElement gift_info = null; WebElement my_sign = null; try{ buyer_name = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(this.buySteamGameXpath.get("presentUserField")))); gift_info = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(this.buySteamGameXpath.get("presentMsgField")))); my_sign = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(this.buySteamGameXpath.get("mySignField")))); }catch(Exception e){ batchFrame.info_buy_process_Text.setText("!!填写留言信息处的xpath出错,请更新程序!!"); this.refresh = true; return false; } if(quitCharge()){return false;}; buyer_name.sendKeys("H"); gift_info.sendKeys("<PASSWORD>! Please provide us positive feedback!"); my_sign.sendKeys("xia<PASSWORD>"); // WebElement continue_button2 = null; // try{ // continue_button2 = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(this.buySteamGameXpath.get("presentContinueButton")))); // }catch(Exception e){ // batchFrame.info_buy_process_Text.setText("!!填写留言信息处继续按钮的xpath出错,请更新程序!!"); // this.refresh = true; // return false; // } // if(quitCharge()){return false;}; // try{ // continue_button2.click(); // }catch(Exception e){ // this.refresh = true; // return false; // } //调用enter键 this.action.sendKeys(Keys.ENTER).perform(); batchFrame.info_buy_process_Text.setText("!!正在跳转到最后的游戏购买页面!!"); //页面跳转,需要等待 try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(quitCharge()){return false;}; //确认购买页面,点击同意条款框,以及继续按钮 WebElement accept_box = null; try{ accept_box = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(this.buySteamGameXpath.get("agreeRadioButton")))); }catch(Exception e){ batchFrame.info_buy_process_Text.setText("!!同意条款选项的xpath出错,请更新程序!!"); this.refresh = true; return false; } if(quitCharge()){return false;}; if(!accept_box.isSelected()){ try{ accept_box.click(); }catch(Exception e){ this.refresh = true; return false; } } WebElement jump_to_WebMoney = null; try{ jump_to_WebMoney = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(this.buySteamGameXpath.get("agreeBuyButton")))); }catch(Exception e){ batchFrame.info_buy_process_Text.setText("!!同意条款出购买按钮的xpath出错,请更新程序!!"); this.refresh = true; return false; } if(quitCharge()){return false;}; try{ jump_to_WebMoney.click(); }catch(Exception e){ this.refresh = true; return false; } return true; } /* * Steam游戏发送到邮箱的最后一步,点击同意条框,点击继续即可 */ public boolean confirmPage(){ //此处正在确认购买,跳转到购买成功的页面 batchFrame.info_buy_process_Text.setText("!!正在跳转到购买成功页面,请稍等!!"); try { Thread.sleep(4000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(quitCharge()){return false;}; try{ WebElement printReceipt = driver.findElement(By.xpath("//*[@id='receipt_area']/a")); printReceipt.click(); }catch(Exception failed){ //查看error_display下的a标签是否存在,如果存在则出错 WebElement errorDisplaySpan = null; //a标签的父标签,判断xpath是否出错 try{ errorDisplaySpan = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(this.buySteamGameXpath.get("errorDisplaySpan")))); }catch(Exception e){ batchFrame.info_buy_process_Text.setText("!!!充值出错提醒元素的xpath出错,请重试!!!"); return false; } //捕获特殊异常,如果页面是需要选择支付方式,则出错 WebElement paymentMethodDIV = null; try{ paymentMethodDIV = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(this.buySteamGameXpath.get("paymentMethodDiv")))); //能找到支付方式的div块,说明发生错误,则返回false }catch(Exception e){ batchFrame.info_buy_process_Text.setText("!!账户禁用或余额不足!!"); return false; } WebElement errorDisplayA = null; try{ errorDisplayA = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(this.buySteamGameXpath.get("errorDisplayA")))); //特殊错误,记录标志,使用下一个账户 this.nextBuyGameAccount = true; batchFrame.info_buy_process_Text.setText("!!!最后充值发生错误,正在重试!!!"); }catch(Exception e){ batchFrame.info_buy_process_Text.setText("!!!最后充值发生错误,请重试!!!"); return true; } return true;} return true; } /* * 自动购买游戏的主要步骤 */ public synchronized boolean buyRun(){ this.log = new SteamLog(this.frame); this.seleniumMethods.setBuySteamGameXpath(this.buySteamGameXpath); //共有所烧个购买游戏 int selectgameNum=this.buySteamGame.size(); int gameNumTemp=0; //循环判断是否登录成功,不成功,则结束程序 // 这个循环应该放到 login 函数里面 String[] loginOrNot = new String[2]; for(int i=0;i<5;i++){ String account = this.default_account; String password = <PASSWORD>; loginOrNot = this.seleniumMethods.login(this.buySteamGameXpath.get("loginPageLink"), account, password, this.buySteamGameXpath.get("loginIdField"), this.buySteamGameXpath.get("loginPwField"), this.buySteamGameXpath.get("loginButton")); if(loginOrNot[0]=="true"){ break; }else if(i==4){ batchFrame.info_buy_process_Text.setText("!!!登陆5次错误,请检查登录元素xpath后再试!!!"); //记录日志 log.setMessage("购买失败!"+this.game_name+",购买账户为"+this.default_account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); // exitBrowAfterRunning(); return false; }else{ batchFrame.info_buy_process_Text.setText("!!!登陆异常,正在重试!!!"); } } batchFrame.info_buy_process_Text.setText("!!!正在登陆中!!!"); //查看当前账户余额 this.currentBalanceStr = loginOrNot[1]; System.out.println("当前余额:"+this.currentBalanceStr); Iterator iterator=this.buySteamGame.keySet().iterator(); //购买游戏 while (iterator.hasNext()) { for(int n=0;n<this.gameNum;n++){ String gamenameTemp=iterator.next().toString(); //设置当前steamgame this.setSteamGame(this.buySteamGame.get(gamenameTemp)); this.setGame_name(gamenameTemp); //设置显示游戏名 CheckValue value = null; for (int m = 0; m < frame.gamesComboBox.getItemCount(); m++) { value=(CheckValue) frame.gamesComboBox.getItemAt(m); if (this.game_name.equals(value.value)) { frame.gamesComboBox.setSelectedIndex(m); value.bolValue=true; } } batchFrame.setText(); if(quitCharge()){return true;}; batchFrame.hasBuyNumText.setText("已经购买"+gameNumTemp+"个游戏,正在购买第"+(gameNumTemp+1)+"个游戏!"); //跳转到游戏界面,查找加入购物车的按钮,循环查找 if(quitCharge()){return true;}; batchFrame.info_buy_process_Text.setText("!!!跳转到对应游戏界面并加入购物车!!!"); driver.get(this.steamGame.getLink()); for(int i=0;i<5;i++){ if(quitCharge()){return true;}; boolean addToCartOrNot = this.seleniumMethods.addToCart(this.steamGame.getLink(), this.steamGame.getXpath()); if(addToCartOrNot){ break; }else if(i==4){ batchFrame.info_buy_process_Text.setText("!!查找购物车按钮5次出错,请更新游戏xpath!!"); //记录日志 log.setMessage("购买失败!"+this.game_name+",购买账户为"+this.default_account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); // exitBrowAfterRunning(); return false; }else{ batchFrame.info_buy_process_Text.setText("!!加入购物车失败,正在重试!!"); driver.navigate().refresh(); } } if(quitCharge()){return true;}; //调用purchase as a gift函数,循环5次 for(int i=0;i<5;i++){ if(quitCharge()){return true;}; boolean purchaseOrNot = purchaseAsGift(); if(purchaseOrNot){ this.refresh = false; break; }else if(i==4||(!purchaseOrNot&&this.refresh==false)){ batchFrame.info_buy_process_Text.setText("!!查找购物车按钮5次出错或者账户余额不足,请更新游戏xpath或充值!!"); //记录日志 log.setMessage("购买失败!"+this.game_name+",购买账户为"+this.default_account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); // exitBrowAfterRunning(); this.refresh = false; return false; }else if(!purchaseOrNot&&this.refresh==true){ batchFrame.info_buy_process_Text.setText("!!加入购物车失败,正在重试!!"); driver.navigate().refresh(); } } //调用发送礼物的函数,循环5次 batchFrame.info_buy_process_Text.setText("!!!正在发送礼物,请稍等!!!"); for(int i=0;i<5;i++){ if(quitCharge()){return true;}; boolean sendPresentOrNot = sendPresent(); if(sendPresentOrNot){ this.refresh = false; break; }else if(i==4||(!sendPresentOrNot&&this.refresh==false)){ batchFrame.info_buy_process_Text.setText("!!发送礼物过程中出现xpath错误问题,请检查后重试!!"); //记录日志 log.setMessage("购买失败!"+this.game_name+",购买账户为"+this.default_account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); // exitBrowAfterRunning(); this.refresh = false; return false; }else if(!sendPresentOrNot&&this.refresh==true){ batchFrame.info_buy_process_Text.setText("!!发送礼物失败,正在重试!!"); driver.navigate().refresh(); } } if(quitCharge()){return true;}; //跳转到支付确认页面,选中同意条款,点击确认购买 batchFrame.info_buy_process_Text.setText("!!!最终的确认页面,请等待处理!!!"); if(!confirmPage()){ //记录日志 log.setMessage("购买失败!"+this.game_name+",购买账户为"+this.default_account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); // exitBrowAfterRunning(); return false; } batchFrame.hasBuyNumText.setText("已经购买"+(gameNumTemp+1)+"个游戏!"); // batchFrame.info_buy_process_Text.setText("!!!购买成功,请退出!!!"); //说明该游戏已经购买 ((CheckValue)frame.gamesComboBox.getItemAt(gameNumTemp)).bolValue=false; gameNumTemp++; //日志 log.setMessage("购买成功!"+this.game_name+",购买账户为"+this.default_account+",购买后余额为"+this.finalBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); // batchFrame.closeDriverTag = true; // exitBrowAfterRunning(); } } //判断该用户是否全部购买 if (gameNumTemp==selectgameNum) { return true; }else { return false; } } /* * 循环账户购买多个游戏 */ public synchronized void batchBuy(){ this.log = new SteamLog(this.frame); this.seleniumMethods.setBuySteamGameXpath(this.buySteamGameXpath); if(quitCharge()){return;}; batchFrame.info_buy_process_Text.setText("!!!正在登录中!!!"); //初始化i记录购买游戏的个数 int i = 0; //记录账户的个数 for(int j=0;j<this.buyGameAccountID.size()&&i<this.gameNum;j++){ this.nextBuyGameAccount = false; //登录对应账户 String account = this.buyGameAccountID.get(j); this.default_account = account; String password = this.buyGameAccounts.get(account); this.defaule_password = <PASSWORD>; batchFrame.info_default_account_text.setText(account); String[] loginOrNot = new String[2]; for(int x=0;x<5;x++){ loginOrNot = this.seleniumMethods.login(this.buySteamGameXpath.get("loginPageLink"), account, password, this.buySteamGameXpath.get("loginIdField"), this.buySteamGameXpath.get("loginPwField"), this.buySteamGameXpath.get("loginButton")); if(loginOrNot[0] == "true"){ batchFrame.info_buy_process_Text.setText("账户更换成功,即将购买游戏"); break; }else if(x==4){ batchFrame.info_buy_process_Text.setText("!!!登陆5次错误,请检查登录元素xpath后再试!!!"); //记录日志 log.setMessage("购买失败!"+this.game_name+",购买账户为"+account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); exitBrowAfterRunning(); return; }else{ batchFrame.info_buy_process_Text.setText("!!!登陆异常,正在重试!!!"); } } //查看当前账户余额 this.currentBalanceStr = loginOrNot[1]; //m记录5次循环 for(int m=0;m<5&&i<this.gameNum;m++){ batchFrame.hasBuyNumText.setText("已经购买"+i+"个游戏,正在购买第"+(i+1)+"个游戏!"); //跳转到游戏界面,查找加入购物车的按钮,循环查找 if(quitCharge()){return;}; batchFrame.info_buy_process_Text.setText("!!!跳转到对应游戏界面并加入购物车!!!"); driver.get(this.steamGame.getLink()); System.out.println("这里跳转了!!!!"+this.steamGame.getLink()); for(int x=0;x<5;x++){ if(quitCharge()){return;}; boolean addToCartOrNot = this.seleniumMethods.addToCart(this.steamGame.getLink(), this.steamGame.getXpath()); System.out.println("这里是不是true~!!!!"+addToCartOrNot); if(addToCartOrNot){ break; }else if(x==4){ batchFrame.info_buy_process_Text.setText("!!查找购物车按钮5次出错,请更新游戏xpath!!"); //记录日志 log.setMessage("购买失败!"+this.game_name+",购买账户为"+account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); exitBrowAfterRunning(); return; }else{ batchFrame.info_buy_process_Text.setText("!!加入购物车失败,正在重试!!"); driver.navigate().refresh(); } } if(quitCharge()){return;}; //调用purchase as a gift函数,循环5次 for(int x=0;x<5;x++){ if(quitCharge()){return;}; boolean purchaseOrNot = purchaseAsGift(); System.out.println("这里的purchase~~~"+purchaseOrNot); if(purchaseOrNot){ this.refresh = false; break; }else if(x==4){ batchFrame.info_buy_process_Text.setText("!!查找以礼物发送按钮5次出错,请更新游戏xpath!!"); //记录日志 log.setMessage("购买失败!"+this.game_name+",购买账户为"+this.default_account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); exitBrowAfterRunning(); this.refresh = false; return; }else if(!purchaseOrNot&&this.refresh==true){ batchFrame.info_buy_process_Text.setText("!!查找以礼物发送按钮失败,正在重试!!"); driver.navigate().refresh(); }else if(!purchaseOrNot&&this.refresh==false){ log.setMessage("购买失败!"+this.game_name+",购买账户为"+account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); break; //如果是由于账户余额不足造成购买失败,则使用下一个账户,如果是其他错误造成,则终止程序 // if(this.nextBuyGameAccount){ // batchFrame.info_buy_process_Text.setText("!!!当前账户余额不足,正在更换下一个账户!!!"); // break; // } // exitBrowAfterRunning(); // return; } } //如果是由于账户余额不足造成购买失败,则使用下一个账户,如果是其他错误造成,则终止程序 if(this.nextBuyGameAccount){ batchFrame.info_buy_process_Text.setText("!!!当前账户余额不足,正在更换下一个账户!!!"); continue; } //调用发送礼物的函数,循环5次 batchFrame.info_buy_process_Text.setText("!!!正在发送礼物,请稍等!!!"); for(int x=0;x<5;x++){ if(quitCharge()){return;}; boolean sendPresentOrNot = sendPresent(); if(sendPresentOrNot){ this.refresh = false; break; }else if(x==4||(!sendPresentOrNot&&this.refresh==false)){ batchFrame.info_buy_process_Text.setText("!!发送礼物过程中出现xpath错误问题,请检查后重试!!"); //记录日志 log.setMessage("购买失败!"+this.game_name+",购买账户为"+this.default_account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); exitBrowAfterRunning(); this.refresh = false; return; }else if(!sendPresentOrNot&&this.refresh==true){ batchFrame.info_buy_process_Text.setText("!!发送礼物失败,正在重试!!"); driver.navigate().refresh(); } } if(quitCharge()){return;}; //跳转到支付确认页面,选中同意条款,点击确认购买 batchFrame.info_buy_process_Text.setText("!!!最终的确认页面,请等待处理!!!"); if(!confirmPage()){ //首先记录日志,此次购买失败,其次要判断是否是由于账户问题造成购买失败 log.setMessage("购买失败!"+this.game_name+",购买账户为"+account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); //如果是由于账户问题造成购买失败,则使用下一个账户,如果是其他错误造成,则终止程序 if(this.nextBuyGameAccount){ batchFrame.info_buy_process_Text.setText("!!!当前账户充值有问题,正在更换下一个账户!!!"); break; } exitBrowAfterRunning(); return; } // //日志 log.setMessage("购买成功!"+this.game_name+",购买账户为"+account+",购买后余额为"+this.finalBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); batchFrame.info_buy_process_Text.setText("账户"+account+"购买一个游戏成功,还剩"+(this.gameNum-i-1)+"个游戏"); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } i++; } } //如果账户用完,则退出,剩下的游戏不再继续购买,并且记录购买个数 batchFrame.hasBuyNumText.setText("已经购买"+i+"个游戏!"); batchFrame.info_buy_process_Text.setText(i+"个游戏购买成功,还剩"+(this.gameNum-i)+"个游戏未购买!"); batchFrame.closeDriverTag = true; exitBrowAfterRunning(); return; } /* * 批量加入仓库的函数 */ public synchronized boolean batchBuyToWare(){ this.log = new SteamLog(this.frame); this.seleniumMethods.setBuySteamGameXpath(this.buySteamGameXpath); //共有所烧个购买游戏 int selectgameNum=this.buySteamGame.size(); int gameNumTemp=0; //循环判断是否登录成功,不成功,则结束程序 // 这个循环应该放到 login 函数里面 String[] loginOrNot = new String[2]; for(int i=0;i<5;i++){ String account = this.default_account; String password = <PASSWORD>; loginOrNot = this.seleniumMethods.login(this.buySteamGameXpath.get("loginPageLink"), account, password, this.buySteamGameXpath.get("loginIdField"), this.buySteamGameXpath.get("loginPwField"), this.buySteamGameXpath.get("loginButton")); if(loginOrNot[0]=="true"){ break; }else if(i==4){ batchFrame.info_buy_process_Text.setText("!!!登陆5次错误,请检查登录元素xpath后再试!!!"); //记录日志 log.setMessage("购买失败!"+this.game_name+",购买账户为"+this.default_account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); // exitBrowAfterRunning(); return false; }else{ batchFrame.info_buy_process_Text.setText("!!!登陆异常,正在重试!!!"); } } batchFrame.info_buy_process_Text.setText("!!!正在登陆中!!!"); //查看当前账户余额 this.currentBalanceStr = loginOrNot[1]; System.out.println("当前余额:"+this.currentBalanceStr); Iterator iterator=this.buySteamGame.keySet().iterator(); //购买游戏 while (iterator.hasNext()) { for(int n=0;n<this.gameNum;n++){ String gamenameTemp=iterator.next().toString(); //设置当前steamgame this.setSteamGame(this.buySteamGame.get(gamenameTemp)); this.setGame_name(gamenameTemp); //设置显示游戏名 CheckValue value; for (int m = 0; m < frame.gamesComboBox.getItemCount(); m++) { value=(CheckValue) frame.gamesComboBox.getItemAt(m); if (this.game_name.equals(value.value)) { frame.gamesComboBox.setSelectedIndex(m); value.bolValue=true; } } batchFrame.setText(); if(quitCharge()){return true;}; batchFrame.hasBuyNumText.setText("已经购买"+gameNumTemp+"个游戏,正在购买第"+(gameNumTemp+1)+"个游戏!"); //跳转到游戏界面,查找加入购物车的按钮,循环查找 if(quitCharge()){return true;}; batchFrame.info_buy_process_Text.setText("!!!跳转到对应游戏界面并加入购物车!!!"); driver.get(this.steamGame.getLink()); for(int i=0;i<5;i++){ if(quitCharge()){return true;}; boolean addToCartOrNot = this.seleniumMethods.addToCart(this.steamGame.getLink(), this.steamGame.getXpath()); if(addToCartOrNot){ break; }else if(i==4){ batchFrame.info_buy_process_Text.setText("!!查找购物车按钮5次出错,请更新游戏xpath!!"); //记录日志 log.setMessage("购买失败!"+this.game_name+",购买账户为"+this.default_account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); // exitBrowAfterRunning(); return false; }else{ batchFrame.info_buy_process_Text.setText("!!加入购物车失败,正在重试!!"); driver.navigate().refresh(); } } if(quitCharge()){return true;}; //调用purchase as a gift函数,循环5次 for(int i=0;i<5;i++){ if(quitCharge()){return true;}; boolean purchaseOrNot = purchaseAsGift(); if(purchaseOrNot){ this.refresh = false; break; }else if(i==4||(!purchaseOrNot&&this.refresh==false)){ batchFrame.info_buy_process_Text.setText("!!查找购物车按钮5次出错或者账户余额不足,请更新游戏xpath或充值!!"); //记录日志 log.setMessage("购买失败!"+this.game_name+",购买账户为"+this.default_account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); // exitBrowAfterRunning(); this.refresh = false; return false; }else if(!purchaseOrNot&&this.refresh==true){ batchFrame.info_buy_process_Text.setText("!!加入购物车失败,正在重试!!"); driver.navigate().refresh(); } } //调用发送礼物的函数,循环5次 batchFrame.info_buy_process_Text.setText("!!!正在加入仓库,请稍等!!!"); for(int i=0;i<5;i++){ if(quitCharge()){return true;}; boolean sendPresentOrNot = addToWare(); if(sendPresentOrNot){ this.refresh = false; break; }else if(i==4||(!sendPresentOrNot&&this.refresh==false)){ batchFrame.info_buy_process_Text.setText("!!发送礼物过程中出现xpath错误问题,请检查后重试!!"); //记录日志 log.setMessage("加入仓库失败!"+this.game_name+",购买账户为"+this.default_account+",账户余额为"+this.currentBalanceStr); log.insertLog(); // exitBrowAfterRunning(); this.refresh = false; return false; }else if(!sendPresentOrNot&&this.refresh==true){ batchFrame.info_buy_process_Text.setText("!!加入仓库失败,正在重试!!"); driver.navigate().refresh(); } } if(quitCharge()){return true;}; //跳转到支付确认页面,选中同意条款,点击确认购买 batchFrame.info_buy_process_Text.setText("!!!最终的确认页面,请等待处理!!!"); if(!confirmPage()){ //记录日志 log.setMessage("加入仓库失败!"+this.game_name+",购买账户为"+this.default_account+",账户余额为"+this.currentBalanceStr); log.insertLog(); // exitBrowAfterRunning(); return false; } batchFrame.hasBuyNumText.setText("已经加入"+(gameNumTemp+1)+"个游戏!"); // batchFrame.info_buy_process_Text.setText("!!!购买成功,请退出!!!"); //说明该游戏已经购买 ((CheckValue)frame.gamesComboBox.getItemAt(gameNumTemp)).bolValue=false; gameNumTemp++; //日志 log.setMessage("加入仓库成功!"+this.game_name+",购买账户为"+this.default_account+",购买后余额为"+this.finalBalanceStr); log.insertLog(); // batchFrame.closeDriverTag = true; // exitBrowAfterRunning(); } } //判断该用户是否全部购买 if (gameNumTemp==selectgameNum) { return true; }else { return false; } } /* * 为自己购买一个或多个游戏的函数 */ public synchronized boolean batchBuyMyself(){ this.log = new SteamLog(this.frame); this.seleniumMethods.setBuySteamGameXpath(this.buySteamGameXpath); //共有所烧个购买游戏 int selectgameNum=this.buySteamGame.size(); int gameNumTemp=0; //循环判断是否登录成功,不成功,则结束程序 // 这个循环应该放到 login 函数里面 String[] loginOrNot = new String[2]; for(int i=0;i<5;i++){ String account = this.default_account; String password = <PASSWORD>; loginOrNot = this.seleniumMethods.login(this.buySteamGameXpath.get("loginPageLink"), account, password, this.buySteamGameXpath.get("loginIdField"), this.buySteamGameXpath.get("loginPwField"), this.buySteamGameXpath.get("loginButton")); if(loginOrNot[0]=="true"){ break; }else if(i==4){ batchFrame.info_buy_process_Text.setText("!!!登陆5次错误,请检查登录元素xpath后再试!!!"); //记录日志 log.setMessage("购买失败!"+this.game_name+",购买账户为"+this.default_account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); // exitBrowAfterRunning(); return false; }else{ batchFrame.info_buy_process_Text.setText("!!!登陆异常,正在重试!!!"); } } batchFrame.info_buy_process_Text.setText("!!!正在登陆中!!!"); //查看当前账户余额 this.currentBalanceStr = loginOrNot[1]; System.out.println("当前余额:"+this.currentBalanceStr); Iterator iterator=this.buySteamGame.keySet().iterator(); //购买游戏 while (iterator.hasNext()) { for(int n=0;n<this.gameNum;n++){ String gamenameTemp=iterator.next().toString(); //设置当前steamgame this.setSteamGame(this.buySteamGame.get(gamenameTemp)); this.setGame_name(gamenameTemp); //设置显示游戏名 CheckValue value = null; for (int m = 0; m < frame.gamesComboBox.getItemCount(); m++) { value=(CheckValue) frame.gamesComboBox.getItemAt(m); if (this.game_name.equals(value.value)) { frame.gamesComboBox.setSelectedIndex(m); value.bolValue=true; } } batchFrame.setText(); if(quitCharge()){return true;}; batchFrame.hasBuyNumText.setText("已经购买"+gameNumTemp+"个游戏,正在购买第"+(gameNumTemp+1)+"个游戏!"); //跳转到游戏界面,查找加入购物车的按钮,循环查找 if(quitCharge()){return true;}; batchFrame.info_buy_process_Text.setText("!!!跳转到对应游戏界面并加入购物车!!!"); driver.get(this.steamGame.getLink()); for(int i=0;i<5;i++){ if(quitCharge()){return true;}; boolean addToCartOrNot = this.seleniumMethods.addToCart(this.steamGame.getLink(), this.steamGame.getXpath()); if(addToCartOrNot){ break; }else if(i==4){ batchFrame.info_buy_process_Text.setText("!!查找购物车按钮5次出错,请更新游戏xpath!!"); //记录日志 log.setMessage("购买失败!"+this.game_name+",购买账户为"+this.default_account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); // exitBrowAfterRunning(); return false; }else{ batchFrame.info_buy_process_Text.setText("!!加入购物车失败,正在重试!!"); driver.navigate().refresh(); } } if(quitCharge()){return true;}; //调用purchase as a gift函数,循环5次 for(int i=0;i<5;i++){ if(quitCharge()){return true;}; boolean purchaseOrNot = purchaseAsGift(); if(purchaseOrNot){ this.refresh = false; break; }else if(i==4||(!purchaseOrNot&&this.refresh==false)){ batchFrame.info_buy_process_Text.setText("!!查找购物车按钮5次出错或者账户余额不足,请更新游戏xpath或充值!!"); //记录日志 log.setMessage("购买失败!"+this.game_name+",购买账户为"+this.default_account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); // exitBrowAfterRunning(); this.refresh = false; return false; }else if(!purchaseOrNot&&this.refresh==true){ batchFrame.info_buy_process_Text.setText("!!加入购物车失败,正在重试!!"); driver.navigate().refresh(); } } //调用发送礼物的函数,循环5次 batchFrame.info_buy_process_Text.setText("!!!为自己购买,请稍等!!!"); for(int i=0;i<5;i++){ if(quitCharge()){return true;}; boolean sendPresentOrNot = purchaseForMyself(); if(sendPresentOrNot){ this.refresh = false; break; }else if(i==4||(!sendPresentOrNot&&this.refresh==false)){ batchFrame.info_buy_process_Text.setText("!!发送礼物过程中出现xpath错误问题,请检查后重试!!"); //记录日志 log.setMessage("为自己购买失败!"+this.game_name+",购买账户为"+this.default_account+",账户余额为"+this.currentBalanceStr); log.insertLog(); // exitBrowAfterRunning(); this.refresh = false; return false; }else if(!sendPresentOrNot&&this.refresh==true){ batchFrame.info_buy_process_Text.setText("!!为自己购买失败,正在重试!!"); driver.navigate().refresh(); } } if(quitCharge()){return true;}; //跳转到支付确认页面,选中同意条款,点击确认购买 batchFrame.info_buy_process_Text.setText("!!!最终的确认页面,请等待处理!!!"); if(!confirmPage()){ //记录日志 log.setMessage("为自己购买失败!"+this.game_name+",购买账户为"+this.default_account+",账户余额为"+this.currentBalanceStr); log.insertLog(); // exitBrowAfterRunning(); return false; } batchFrame.hasBuyNumText.setText("已经购买"+(gameNumTemp+1)+"个游戏!"); // batchFrame.info_buy_process_Text.setText("!!!购买成功,请退出!!!"); //说明该游戏已经购买 ((CheckValue)frame.gamesComboBox.getItemAt(gameNumTemp)).bolValue=false; gameNumTemp++; //日志 log.setMessage("购买成功!"+this.game_name+",购买账户为"+this.default_account+",购买后余额为"+this.finalBalanceStr); log.insertLog(); // batchFrame.closeDriverTag = true; // exitBrowAfterRunning(); } } //判断该用户是否全部购买 if (gameNumTemp==selectgameNum) { return true; }else { return false; } } /* * 跳区购买一个或多个游戏 */ public void jumpAreaBuy(){ this.log = new SteamLog(this.frame); this.seleniumMethods.setBuySteamGameXpath(this.buySteamGameXpath); if(quitCharge()){return;}; batchFrame.info_buy_process_Text.setText("!!!正在登录中!!!"); //初始化i记录购买游戏的个数 int i = 0; //记录账户的个数 for(int j=0;j<this.buyGameAccountID.size()&&i<this.gameNum;j++){ this.nextBuyGameAccount = false; String account = this.default_account; String password = <PASSWORD>; //如果购买个数为1,则使用默认的账户,否则登陆循环账户 if(this.gameNum>1){ //登录对应账户 account = this.buyGameAccountID.get(j); this.default_account = account; password = this.buyGameAccounts.get(account); this.defaule_password = <PASSWORD>; }else{ } batchFrame.info_default_account_text.setText(account); String[] loginOrNot = new String[2]; for(int x=0;x<5;x++){ loginOrNot = this.seleniumMethods.login("https://store.steampowered.com/login/?cc=ru", account, password, this.buySteamGameXpath.get("loginIdField"), this.buySteamGameXpath.get("loginPwField"), this.buySteamGameXpath.get("loginButton")); if(loginOrNot[0] == "true"){ batchFrame.info_buy_process_Text.setText("账户更换成功,即将购买游戏"); break; }else if(x==4){ batchFrame.info_buy_process_Text.setText("!!!登陆5次错误,请检查登录元素xpath后再试!!!"); //记录日志 log.setMessage("购买失败!"+this.game_name+",购买账户为"+account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); exitBrowAfterRunning(); return; }else{ batchFrame.info_buy_process_Text.setText("!!!登陆异常,正在重试!!!"); } } //查看当前账户余额 this.currentBalanceStr = loginOrNot[1]; //m记录5次循环 for(int m=0;m<5&&i<this.gameNum;m++){ //此处需要注意,避免只购买一个的情况下购买失败时i变量未变,而不停地循环账户造成的错误 if(this.gameNum==1){ this.gameNum = 0; } batchFrame.hasBuyNumText.setText("已经购买"+i+"个游戏,正在购买第"+(i+1)+"个游戏!"); //跳转到万能游戏界面,查找加入购物车的按钮,循环查找 if(quitCharge()){return;}; batchFrame.info_buy_process_Text.setText("!!!跳转到万能游戏界面并加入购物车!!!"); if(""!=this.handleStart){ System.out.println(this.handleStart); driver.switchTo().window(this.handleStart); } System.out.println("万能游戏网址:"+this.uniSteamGame.getLink()+"这边能输出"+i); driver.get(this.uniSteamGame.getLink()); System.out.println("这里跳转了!!!!"+this.uniSteamGame.getLink()); for(int x=0;x<5;x++){ if(quitCharge()){return;}; boolean addToCartOrNot = this.seleniumMethods.addToCart(this.uniSteamGame.getLink(), this.uniSteamGame.getXpath()); System.out.println("这里是不是true~!!!!"+addToCartOrNot); if(addToCartOrNot){ break; }else if(x==4){ batchFrame.info_buy_process_Text.setText("!!查找万能游戏购物车按钮5次出错,请更新游戏xpath!!"); //记录日志 log.setMessage("购买失败!"+this.game_name+",购买账户为"+account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); exitBrowAfterRunning(); return; }else{ batchFrame.info_buy_process_Text.setText("!!加入购物车失败,正在重试!!"); driver.navigate().refresh(); } } if(quitCharge()){return;}; //调用purchase as a gift函数,循环5次 for(int x=0;x<5;x++){ if(quitCharge()){return;}; boolean purchaseOrNot = jumpAreaPurchaseAsGift(); System.out.println("这里的purchase~~~"+purchaseOrNot); if(purchaseOrNot){ this.refresh = false; break; }else if(x==4){ batchFrame.info_buy_process_Text.setText("!!查找以礼物发送按钮5次出错,请更新游戏xpath!!"); //记录日志 log.setMessage("购买失败!"+this.game_name+",购买账户为"+this.default_account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); exitBrowAfterRunning(); this.refresh = false; return; }else if(!purchaseOrNot&&this.refresh==true){ batchFrame.info_buy_process_Text.setText("!!查找以礼物发送按钮失败,正在重试!!"); driver.navigate().refresh(); }else if(!purchaseOrNot&&this.refresh==false){ log.setMessage("购买失败!"+this.game_name+",购买账户为"+account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); //如果是由于账户余额不足造成购买失败,则使用下一个账户,如果是其他错误造成,则终止程序 if(this.nextBuyGameAccount){ batchFrame.info_buy_process_Text.setText("!!!当前账户余额不足,正在更换下一个账户!!!"); break; } exitBrowAfterRunning(); return; } } /* * !!!Important!!! * 打开一个新的标签,转到真正需要购买游戏的页面 */ if("".equals(this.handleEnd)&&"".equals(this.handleStart)){ JavascriptExecutor jse = (JavascriptExecutor)driver; jse.executeScript("function createDoc(){var w = window.open(); w.document.open(); w.document.write('<h1>Hello World!</h1>'); w.document.close();}; createDoc();"); this.handleStart = driver.getWindowHandle();//获取万能页面的句柄 System.out.println("当前页面句柄:"+this.handleStart); Set<String> handles = driver.getWindowHandles(); for(String handle : handles){ if(!handle.equals(this.handleStart)){ this.handleEnd = handle;//获取真正需要购买的游戏页面的句柄 } } } driver.switchTo().window(this.handleEnd);//将焦点移到真正购买的游戏页面 //跳转到真正购买的游戏界面,查找加入购物车的按钮,循环查找 if(quitCharge()){return;}; batchFrame.info_buy_process_Text.setText("!!!跳转到游戏界面并加入购物车!!!"); String newSteamGameLink = changeGameLink(this.buySteamGameXpath.get("country"), this.steamGame.getLink()); driver.get(newSteamGameLink); System.out.println("这里跳转了!!!!"+this.steamGame.getLink()); for(int x=0;x<5;x++){ if(quitCharge()){return;}; boolean addToCartOrNot = this.seleniumMethods.addToCart(newSteamGameLink, this.steamGame.getXpath()); System.out.println("这里是不是true~!!!!"+addToCartOrNot); if(addToCartOrNot){ break; }else if(x==4){ batchFrame.info_buy_process_Text.setText("!!查找游戏购物车按钮5次出错,请更新游戏xpath!!"); //记录日志 log.setMessage("购买失败!"+this.game_name+",购买账户为"+account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); exitBrowAfterRunning(); return; }else{ batchFrame.info_buy_process_Text.setText("!!加入购物车失败,正在重试!!"); driver.navigate().refresh(); } } try { Thread.sleep(3000); } catch (InterruptedException e1) { e1.printStackTrace(); } //此时需要移除购物车中的万能游戏,有待扩展。。循环五次执行 //由于remove的xpath会变,所以使用获取所有的remove,然后定位第二个的方法 List removeAS = null; try{ removeAS = driver.findElements(By.className("remove_link")); }catch(Exception e){ System.out.println(e); return; } String removeLinkText = this.frame.removeLinkTextField.getText(); int removeLink = Integer.parseInt(removeLinkText); System.out.println("删除的位置是:"+removeLink); WebElement removeA = (WebElement) removeAS.get(removeLink); removeA.click(); // WebElement removeA = null; // try{ // driver.findElement(By.xpath("//*[@id='cart_row_602689728667236399']/div/div[1]/a")).click();//*[@id="cart_row_602689728667236399"]/div/div[1]/a // }catch(Exception e){ // System.out.println(e); // } // removeA.click(); try { Thread.sleep(3000); } catch (InterruptedException e1) { e1.printStackTrace(); } //跳转到http://store.steampowered.com/cart/?cc=ru看按钮是否是disable的 driver.get("http://store.steampowered.com/cart/?cc=ru"); try{ driver.findElement(By.xpath("/html/body/div[2]/div[2]/div[3]/div[1]/div[2]/div[4]/span[1]")); }catch(Exception e){ //如果没有找到span元素,则说明按钮是可以点击的,能找到说明按钮已经disable System.out.println("作为礼物购买的按钮还能点击,请重试!"); return; } System.out.println("跳转到刚开始的页面句柄:"+this.handleStart); //重新将driver句柄定位到万能游戏的页面 driver.switchTo().window(this.handleStart); // driver.navigate().refresh(); System.out.println(driver.getTitle()); //调用发送礼物的函数,循环5次 batchFrame.info_buy_process_Text.setText("!!!正在发送礼物,请稍等!!!"); for(int x=0;x<5;x++){ if(quitCharge()){return;}; boolean sendPresentOrNot = sendPresent(); if(sendPresentOrNot){ this.refresh = false; break; }else if(x==4||(!sendPresentOrNot&&this.refresh==false)){ batchFrame.info_buy_process_Text.setText("!!发送礼物过程中出现xpath错误问题,请检查后重试!!"); //记录日志 log.setMessage("购买失败!"+this.game_name+",购买账户为"+this.default_account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); exitBrowAfterRunning(); this.refresh = false; return; }else if(!sendPresentOrNot&&this.refresh==true){ batchFrame.info_buy_process_Text.setText("!!发送礼物失败,正在重试!!"); driver.navigate().refresh(); } } // if(quitCharge()){return;}; // //跳转到支付确认页面,选中同意条款,点击确认购买 // batchFrame.info_buy_process_Text.setText("!!!最终的确认页面,请等待处理!!!"); // if(!confirmPage()){ // //首先记录日志,此次购买失败,其次要判断是否是由于账户问题造成购买失败 // log.setMessage("购买失败!"+this.game_name+",购买账户为"+account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); // log.insertLog(); // // //如果是由于账户问题造成购买失败,则使用下一个账户,如果是其他错误造成,则终止程序 // if(this.nextBuyGameAccount){ // batchFrame.info_buy_process_Text.setText("!!!当前账户充值有问题,正在更换下一个账户!!!"); // break; // } // exitBrowAfterRunning(); // return; // } // //日志 log.setMessage("购买成功!"+this.game_name+",购买账户为"+account+",账户余额为"+this.currentBalanceStr+",发送邮箱为"+this.default_email); log.insertLog(); batchFrame.info_buy_process_Text.setText("账户"+account+"购买一个游戏成功,还剩"+(this.gameNum-i-1)+"个游戏"); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } i++; } } //如果账户用完,则退出,剩下的游戏不再继续购买,并且记录购买个数 batchFrame.hasBuyNumText.setText("已经购买"+i+"个游戏!"); batchFrame.info_buy_process_Text.setText(i+"个游戏购买成功,还剩"+(this.gameNum-i)+"个游戏未购买!"); batchFrame.closeDriverTag = true; exitBrowAfterRunning(); return; } } <file_sep>/src/test/JUnitTest.java package test; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Iterator; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; public class JUnitTest { private WebDriver driver; @Test public void propertyTest() throws FileNotFoundException, IOException { Properties pros = new Properties(); pros.load(new FileInputStream("config/BuySteamGameXpath-hk.properties")); Iterator iter = pros.entrySet().iterator(); while(iter.hasNext()){ Entry entry = (Entry) iter.next(); System.out.println(entry.getKey()+"="+entry.getValue()); } } @Test public void balanceTest(){ String balancePY = "18230,02 pуб."; float py = Float.parseFloat(balancePY.replaceAll(" ", "").replaceAll(",", ".").replaceAll("pуб.", "")); System.out.println(py); String balanceUS = "$50.18 USD"; float us = Float.parseFloat(balanceUS.replaceAll(" ", "").replace("$", "").replace("USD", "").replaceAll(",", "")); System.out.println(us); String balanceBR = "R$ 15,99"; float br = Float.parseFloat(balanceBR.replaceAll(" ", "").replace("R$", "").replaceAll(",", ".")); System.out.println(br); String balanceJP = "¥ 5,509"; float jp = Float.parseFloat(balanceJP.replaceAll(" ", "").replace("¥", "").replaceAll(",", "")); System.out.println(jp); String balanceID = "Rp 115 999"; float id = Float.parseFloat(balanceID.replaceAll(" ", "").replace("Rp", "").replaceAll(",", "")); System.out.println(id); String balanceMY = "RM43.75"; float my = Float.parseFloat(balanceMY.replaceAll(" ", "").replace("RM", "").replaceAll(",", "")); System.out.println(my); } @Test public void KeyPressTest(){ System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe"); driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://store.steampowered.com/login/"); WebElement idField = driver.findElement(By.xpath("//*[@id='input_username']")); WebElement pwField = driver.findElement(By.xpath("//*[@id='input_password']")); idField.sendKeys("<PASSWORD>"); pwField.sendKeys("<PASSWORD>"); // WebElement submitButton = driver.findElement(By.xpath("//*[@id='login_btn_signin']/a")); // submitButton.click(); Actions action=new Actions(driver); action.sendKeys(Keys.ENTER).perform(); } @Test public void realChromeTest(){ System.setProperty("webdriver.chrome.driver", "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"); driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://store.steampowered.com/login/"); } @Test public void openNewTabTest(){ System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe"); driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://store.steampowered.com/login/"); // String selectLinkOpeninNewTab = Keys.chord(Keys.SHIFT,Keys.RETURN); // driver.findElement(By.linkText("http://www.baidu.com")).sendKeys(selectLinkOpeninNewTab); // String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,"t"); // driver.findElement(By.linkText("http://www.baidu.com")).sendKeys(selectLinkOpeninNewTab); // driver.findElement(By.tagName("body")).sendKeys(Keys.CONTROL +"t"); JavascriptExecutor jse = (JavascriptExecutor)driver; jse.executeScript("function createDoc(){var w = window.open(); w.document.open(); w.document.write('<h1>Hello World!</h1>'); w.document.close();}; createDoc();"); // System.out.println(driver.getWindowHandle()+"\n"); String start = driver.getWindowHandle(); String end = ""; Set<String> handles = driver.getWindowHandles(); for(String handle : handles){ if(!handle.equals(start)){ end = handle; } } System.out.println(start+"--"+end); driver.switchTo().window(end); System.out.println(driver.getTitle()); driver.get("http://www.baidu.com"); driver.switchTo().window(start); driver.get("http://www.163.com"); System.out.println("sdf"); } } <file_sep>/src/frame/ShowXpathListener.java package frame; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import org.jdom2.JDOMException; import script.ToDBC; import selenium.GameObj; import selenium.TaobaoAuto; import selenium.Wallet; import taobao.ShouquanController; import taobao.TaobaoController; import taobao.Tid; import bean.SteamGame; import com.taobao.api.ApiException; public class ShowXpathListener implements ActionListener, ItemListener{ private ShowXpathUI showXpathUI; // private Adder frame; TaobaoController tbc = TaobaoController.getInstance(); private int columnrow = 0; public ShowXpathListener(){} public ShowXpathListener(ShowXpathUI showXpathUI) { this.showXpathUI = showXpathUI; } @Override public void itemStateChanged(ItemEvent e) { if(showXpathUI.xpathComboBox.getSelectedItem()!=null){ String xpathName = showXpathUI.xpathComboBox.getSelectedItem().toString(); String xpath = null; if("SteamGameXpathú║".equals(this.showXpathUI.infoLabel.getText())){ xpath = showXpathUI.buySteamGameXpath.get(xpathName); }else if("WalletXpathú║".equals(this.showXpathUI.infoLabel.getText())){ xpath = showXpathUI.WalletXpath.get(xpathName); } showXpathUI.xpathTextField.setText(xpath); } } @Override public void actionPerformed(ActionEvent e) { if(e.getActionCommand()=="ÁŃ╗¸╗˝╚í╠ď▒Ž╩┌╚Ę"){ new Thread(){ public void run(){ TaobaoAuto tbAuto = new TaobaoAuto(); tbAuto.setAutoUrl("https://oauth.taobao.com/authorize?response_type=code&client_id=21784353&redirect_uri=urn:ietf:wg:oauth:2.0:oob&state=1212"); tbAuto.getTaobaoAuto(); } }.start(); } } } <file_sep>/src/bean/SteamGame.java package bean; public class SteamGame { private String name; private String link; private String xpath; private String fileName; public SteamGame(){} public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getXpath() { return xpath; } public void setXpath(String xpath) { this.xpath = xpath; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } } <file_sep>/src/bean/Game.java package bean; public class Game { private String id; private String name; private String remark; private String link; private String xpath; private String img; public Game(){} public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getXpath() { return xpath; } public void setXpath(String xpath) { this.xpath = xpath; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } } <file_sep>/src/taobao/GetTrade.java package taobao; import json.JsonParser; import com.taobao.api.ApiException; import com.taobao.api.DefaultTaobaoClient; import com.taobao.api.TaobaoClient; import com.taobao.api.request.TradeGetRequest; import com.taobao.api.response.TradeGetResponse; public class GetTrade { //orders.status, public Trade getInfo(long tid,String url, String appkey, String secret,String sessionKey,Trade trade){ TaobaoClient client=new DefaultTaobaoClient(url, appkey, secret); TradeGetRequest req=new TradeGetRequest(); req.setFields("orders.title,orders.price,orders.num,orders.status,created,buyer_nick, buyer_message"); // req.setTid(647717624038695L); req.setTid(tid); try { TradeGetResponse response = client.execute(req , sessionKey); JsonParser jp = new JsonParser(); trade = jp.getTrade(response.getBody(), trade); System.out.println("buyer_nick:"+trade.getBuyer_nick()+"//num:"+trade.getNum() +"//price:"+trade.getPrice()+"//status:"+trade.getStatus() +"//title:"+trade.getTitle()+"//created:"+trade.getCreated()+"//buyer_message"+trade.getBuyer_message()); // System.out.println(response.getBody()); return trade ; } catch (ApiException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } } <file_sep>/src/frame/CheckValue.java /** * */ package frame; /** * @author wjh * */ public class CheckValue { public boolean bolValue = false; public String value = null; public CheckValue() { } public CheckValue(boolean bolValue, String value) { this.bolValue = bolValue; this.value = value; } } <file_sep>/src/frame/ShowOrEditSteamGameUI.java package frame; import java.awt.Color; import java.awt.Font; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Map; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import org.jdom2.JDOMException; import bean.SteamGame; public class ShowOrEditSteamGameUI extends JFrame { public AutoSellerUI frame; private JPanel contentPane; public JTextField gameLinkText; public JTextField gameXPathText; public JTextField gameNameText; private JButton EditGameButton; private JButton clearButton; private JLabel infoLabel; public JTextField infoText; public Map<String, SteamGame> steamGames; public SteamGame steamGame; /** * Launch the application. */ public static void main(String[] args) { } /** * Create the frame. */ public ShowOrEditSteamGameUI(AutoSellerUI frame) { this.frame = frame; setResizable(false); setVisible(true); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); setBounds(100, 100, 610, 317); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel gameLinkLabel = new JLabel("游戏地址:"); gameLinkLabel.setBounds(10, 74, 103, 37); contentPane.add(gameLinkLabel); JLabel GameXPathLabel = new JLabel("加入购物车xpath:"); GameXPathLabel.setBounds(10, 126, 117, 37); contentPane.add(GameXPathLabel); JLabel GameNameLabel = new JLabel("淘宝商品名称:"); GameNameLabel.setBounds(10, 173, 103, 37); contentPane.add(GameNameLabel); gameLinkText = new JTextField(); gameLinkText.setBounds(137, 72, 463, 42); contentPane.add(gameLinkText); gameLinkText.setColumns(10); gameXPathText = new JTextField(); gameXPathText.setColumns(10); gameXPathText.setBounds(137, 124, 463, 42); contentPane.add(gameXPathText); gameNameText = new JTextField(); gameNameText.setColumns(10); gameNameText.setBounds(137, 176, 463, 42); contentPane.add(gameNameText); EditGameButton = new JButton("确认修改游戏"); EditGameButton.setBounds(166, 228, 126, 42); contentPane.add(EditGameButton); EditGameButton.addActionListener(new ShowOrEditSteamGameListener(this)); clearButton = new JButton("清空输入框"); clearButton.setBounds(404, 228, 126, 42); contentPane.add(clearButton); clearButton.addActionListener(new ShowOrEditSteamGameListener(this)); infoLabel = new JLabel("状态栏:"); infoLabel.setBounds(10, 20, 103, 37); contentPane.add(infoLabel); infoText = new JTextField(); infoText.setForeground(Color.ORANGE); infoText.setFont(new Font("微软雅黑", Font.BOLD, 18)); infoText.setEditable(false); infoText.setColumns(10); infoText.setBounds(137, 10, 463, 52); infoText.setText("!!查看或者修改游戏的对应信息!!"); contentPane.add(infoText); //添加关闭窗口的监听事件,即保存修改的信息 addWindowListener(new ShowOrEditSteamGameCloseListener(this)); //初始化界面 if("".equals(frame.editSteamGameName)||frame.editSteamGameName==null){ this.infoText.setText("!!请选择有效的游戏!!"); return; } this.steamGame = frame.steamGames.get(frame.editSteamGameName); this.gameLinkText.setText(this.steamGame.getLink()); this.gameNameText.setText(this.steamGame.getName()); this.gameXPathText.setText(this.steamGame.getXpath()); this.frame.setEnabled(false); } } <file_sep>/src/frame/AutoSellerUI.java package frame; import java.awt.BorderLayout; import java.awt.Checkbox; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Font; import java.awt.SystemColor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import javax.swing.border.TitledBorder; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; import org.jdom2.JDOMException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import bean.Game; import bean.SteamGame; public class AutoSellerUI extends JFrame { public List games; public Map<String, SteamGame> steamGames; public Game game; public SteamGame steamGame; //checkbox public MyComboBox gamesComboBox; public JPanel panel_8; //BuySteamGameXpath的文件地址 public String buySteamGameXpathFilePath; //保存BuySteamGameXpath的哈希表 public Map<String, String> buySteamGameXpath; //保存WalletXpath的哈希表 public Map<String, String> WalletXpath; //保存程序执行完成后是否关闭浏览器的变量 public boolean exitBrowserAfterRunning = true; //保存运行过程中是否显示浏览器的变量 public boolean showBrowserWhenRunning = true; /* * 购买steam游戏需要保存的账户和密码 */ public Map<String, String> buyGameAccounts; public List<String> buyGameAccountID; public String editSteamGameName = "请添加游戏"; String str[] = {"请选择游戏"}; String str2[] = {"请选择账户"}; public JPanel MainPanel; public JTabbedPane tabbedPane; //账户页面元素 public JTextField default_id_text_01; public JTextField default_pw_text_01; public JTextField default_id_text_02; public JTextField default_pw_text_02; public JTextField default_id_text_03; public JTextField default_pw_text_03; public JTextField default_id_text_04; public JTextField default_id_text_05; public JTextField default_id_text_06; public JTextField default_pw_text_04; public JTextField default_pw_text_05; public JTextField default_pw_text_06; public JTextField default_pw_text_sure; //授权页面元素 public JTextField Session_key_text; public JTextField Session_text; //单选按钮组 public ButtonGroup group; JRadioButton radioButton_1 = new JRadioButton("请添加游戏"); JRadioButton radioButton_2 = new JRadioButton("请添加游戏"); JRadioButton radioButton_3 = new JRadioButton("请添加游戏"); JRadioButton radioButton_4 = new JRadioButton("请添加游戏"); JRadioButton radioButton_5 = new JRadioButton("请添加游戏"); JRadioButton radioButton_6 = new JRadioButton("请添加游戏"); JRadioButton radioButton_7 = new JRadioButton("请添加游戏"); JRadioButton radioButton_8 = new JRadioButton("请添加游戏"); JRadioButton radioButton_9 = new JRadioButton("请添加游戏"); JRadioButton radioButton_10 = new JRadioButton("请添加游戏"); JRadioButton radioButton_11 = new JRadioButton("请添加游戏"); JRadioButton radioButton_12 = new JRadioButton("请添加游戏"); JRadioButton radioButton_13 = new JRadioButton("请添加游戏"); JRadioButton radioButton_14 = new JRadioButton("请添加游戏"); JRadioButton radioButton_15 = new JRadioButton("请添加游戏"); JRadioButton radioButton_16 = new JRadioButton("请添加游戏"); JRadioButton radioButton_17 = new JRadioButton("请添加游戏"); JRadioButton radioButton_18 = new JRadioButton("请添加游戏"); JRadioButton radioButton_19 = new JRadioButton("请添加游戏"); JRadioButton radioButton_20 = new JRadioButton("请添加游戏"); JRadioButton radioButton_21 = new JRadioButton("请添加游戏"); JRadioButton radioButton_22 = new JRadioButton("请添加游戏"); JRadioButton radioButton_23 = new JRadioButton("请添加游戏"); JRadioButton radioButton_24 = new JRadioButton("请添加游戏"); JRadioButton radioButton_25 = new JRadioButton("请添加游戏"); JRadioButton radioButton_26 = new JRadioButton("请添加游戏"); //订单页面元素 DefaultTableModel tableModel = new DefaultTableModel(0,9); JTable table; public JTextField table_gameName_text = new JTextField(37); public JTextField table_buyer_id_text = new JTextField(37); public JTextField table_buyer_email_text = new JTextField(37); public JTextField table_buyer_message_text = new JTextField(37); public JComboBox account_type_combo = new JComboBox(str2); public JTextField default_pw_text_sure2; public JTextField codeDefaultAccountText; public JTextField statusText; public JTextArea codesTextArea; public JTextArea codesStatusTextArea; public JTextArea steamLogTextArea; //三个下拉菜单 JComboBox accountsComboBox; // JComboBox gamesComboBox; public JComboBox codeAccountsComboBox; public JComboBox countrySelectBox; public JComboBox uniGamesComboBox; /* * Code验证充值需要保存的链表 */ public Map<String,String> accounts = new HashMap<String,String>(); public List<String> accountIDs = new ArrayList<String>(); public JTextField default_email_text_sure; public JTextField default_id_text_07; public JTextField default_id_text_08; public JTextField default_id_text_09; public JTextField default_id_text_10; public JTextField default_pw_text_07; public JTextField default_pw_text_08; public JTextField default_pw_text_09; public JTextField default_pw_text_10; //功能设置出的RadioButton public JRadioButton closeBroRadioButton; public JRadioButton dontCloseRadioButton; public JRadioButton showBroRadioButton; public JRadioButton dontShowRadioButton; public JRadioButton autoSendRadioButton; public JRadioButton manualSendRadioButton; public JTextField startTimeField; public JTextField endTimeField; public JTextField table_gameNum_text; public JTextField table_seller_message_text; public JTextField removeLinkTextField; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { AutoSellerUI frame = new AutoSellerUI(); frame.setLocation(0,0); frame.setResizable(false); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. * @throws IOException * @throws JDOMException * @throws JSONException */ public AutoSellerUI() throws JDOMException, IOException, JSONException { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 900, 650); MainPanel = new JPanel(); MainPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); MainPanel.setLayout(new BorderLayout(0, 0)); setContentPane(MainPanel); tabbedPane = new JTabbedPane(JTabbedPane.TOP); MainPanel.add(tabbedPane, BorderLayout.NORTH); /* * ***************授权获取SessionKey的Panel******************** */ /* * *************购买游戏************** */ JPanel panel_7 = new JPanel(); panel_7.setPreferredSize(new Dimension(850,580)); tabbedPane.addTab("购买游戏", null, panel_7, null); panel_7.setLayout(null); //确认信息 panel_8 = new JPanel(); panel_8.setBorder(new TitledBorder(null, "确认信息", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panel_8.setBounds(10, 21, 849, 225); panel_7.add(panel_8); panel_8.setLayout(null); //设置 JPanel panel_set = new JPanel(); panel_set.setBorder(new TitledBorder(null, "信息设置", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panel_set.setBounds(10, 280, 849, 100); panel_7.add(panel_set); panel_set.setLayout(null); //账户设置 JButton btnAccountSet = new JButton("账户设置"); btnAccountSet.setFont(new Font("微软雅黑", Font.BOLD, 14)); btnAccountSet.setBounds(200,31, 162, 47); panel_set.add(btnAccountSet); btnAccountSet.addActionListener(new MyListener(this)); //游戏设置 JButton btnGameSet = new JButton("游戏设置"); btnGameSet.setFont(new Font("微软雅黑", Font.BOLD, 14)); btnGameSet.setBounds(497,31, 162, 47); panel_set.add(btnGameSet); btnGameSet.addActionListener(new MyListener(this)); //测试 // JButton testbtn = new JButton("测试1"); // testbtn.setFont(new Font("微软雅黑", Font.BOLD, 14)); // testbtn.setBounds(50,31, 162, 47); // panel_set.add(testbtn); // testbtn.addActionListener(new MyListener(this)); JLabel lblNewLabel_1 = new JLabel("购买账户:"); lblNewLabel_1.setForeground(new Color(128, 0, 0)); lblNewLabel_1.setFont(new Font("微软雅黑", Font.PLAIN, 14)); lblNewLabel_1.setBounds(10, 25, 94, 36); panel_8.add(lblNewLabel_1); String str2[] = {"请选择账户"}; accountsComboBox = new JComboBox(); accountsComboBox.setForeground(Color.RED); accountsComboBox.setFont(new Font("微软雅黑", Font.PLAIN, 14)); accountsComboBox.setBounds(114, 24, 249, 41); panel_8.add(accountsComboBox); // accountsComboBox.addItemListener(new MyListener(this)); JLabel default_email_label = new JLabel("收货邮箱:"); default_email_label.setFont(new Font("微软雅黑", Font.PLAIN, 14)); default_email_label.setForeground(new Color(128, 0, 0)); default_email_label.setBounds(373, 25, 94, 36); panel_8.add(default_email_label); default_email_text_sure = new JTextField("<EMAIL>"); default_email_text_sure.setForeground(Color.RED); default_email_text_sure.setFont(new Font("微软雅黑", Font.PLAIN, 14)); default_email_text_sure.setBounds(477, 24, 185, 41); panel_8.add(default_email_text_sure); default_email_text_sure.setColumns(10); JLabel label_4 = new JLabel("购买游戏:"); label_4.setForeground(new Color(128, 0, 0)); label_4.setFont(new Font("微软雅黑", Font.PLAIN, 14)); label_4.setBounds(10, 92, 94, 36); panel_8.add(label_4); // gamesComboBox = new JComboBox(); // gamesComboBox.setForeground(Color.RED); // gamesComboBox.setFont(new Font("微软雅黑", Font.PLAIN, 16)); // gamesComboBox.setBounds(114, 88, 548, 47); // panel_8.add(gamesComboBox); // gamesComboBox.addItemListener(new MyListener(this)); //checkbox gamesComboBox=new MyComboBox(); gamesComboBox.setFont(new Font("微软雅黑", Font.BOLD, 14)); gamesComboBox.setBounds(114, 88, 548, 47); panel_8.add(gamesComboBox); gamesComboBox.setRenderer(new CheckListCellRenderer()); JButton btnNewButton_1 = new JButton("确认并购买"); btnNewButton_1.setFont(new Font("微软雅黑", Font.BOLD, 14)); btnNewButton_1.setBounds(677, 20, 162, 47); // panel_8.add(btnNewButton_1); btnNewButton_1.addActionListener(new MyListener(this)); JButton button = new JButton("批量采购"); button.setFont(new Font("微软雅黑", Font.BOLD, 14)); button.setBounds(677,38, 162, 47); panel_8.add(button); JLabel label_8 = new JLabel("选择国家:"); label_8.setForeground(new Color(128, 0, 0)); label_8.setFont(new Font("微软雅黑", Font.PLAIN, 14)); label_8.setBounds(10, 159, 94, 36); panel_8.add(label_8); String[] countries = {"俄罗斯", "乌克兰", "香港", "美国", "中国", "巴西", "日本", "印度尼西亚", "马来西亚"}; countrySelectBox = new JComboBox(countries); countrySelectBox.setForeground(Color.RED); countrySelectBox.setFont(new Font("微软雅黑", Font.PLAIN, 16)); countrySelectBox.setBounds(114, 154, 249, 47); panel_8.add(countrySelectBox); JButton buyMyselfButton = new JButton("为自己购买"); buyMyselfButton.setFont(new Font("微软雅黑", Font.BOLD, 14)); buyMyselfButton.setBounds(677, 154, 162, 47); panel_8.add(buyMyselfButton); JLabel label_9 = new JLabel("万能游戏:"); label_9.setForeground(new Color(128, 0, 0)); label_9.setFont(new Font("微软雅黑", Font.PLAIN, 14)); label_9.setBounds(10, 223, 94, 36); // panel_8.add(label_9); /////////////////////////////////////////////禁用万能游戏 uniGamesComboBox = new JComboBox(); uniGamesComboBox.setForeground(Color.RED); uniGamesComboBox.setFont(new Font("微软雅黑", Font.PLAIN, 16)); uniGamesComboBox.setBounds(114, 218, 249, 47); // panel_8.add(uniGamesComboBox); ////////////////////////////////////////////// uniGamesComboBox.addItemListener(new MyListener(this)); JButton jumpBuyButton = new JButton("跳区购买"); jumpBuyButton.setFont(new Font("微软雅黑", Font.BOLD, 14)); jumpBuyButton.setBounds(677, 218, 162, 47); // panel_8.add(jumpBuyButton); //////////////////////////////////////////////禁用跳区购买 JLabel label_10 = new JLabel("移除链接位置:"); label_10.setForeground(new Color(128, 0, 0)); label_10.setFont(new Font("微软雅黑", Font.PLAIN, 14)); label_10.setBounds(373, 223, 94, 36); // panel_8.add(label_10); ///////////////////////////////////////////// removeLinkTextField = new JTextField("2"); removeLinkTextField.setForeground(Color.RED); removeLinkTextField.setFont(new Font("微软雅黑", Font.PLAIN, 14)); removeLinkTextField.setColumns(10); removeLinkTextField.setBounds(477, 221, 185, 41); // panel_8.add(removeLinkTextField); ///////////////////////////////////////////////// jumpBuyButton.addActionListener(new MyListener(this)); buyMyselfButton.addActionListener(new MyListener(this)); countrySelectBox.addItemListener(new MyListener(this)); /* * ***************************账户设置***************************** */ JPanel AccountSet_Panel = new JPanel(); AccountSet_Panel.setPreferredSize(new Dimension(850,580)); // tabbedPane.addTab("账户设置", null, AccountSet_Panel, null); /////////////////////////////////禁用账户设置 AccountSet_Panel.setLayout(null); button.addActionListener(new MyListener(this)); default_pw_text_sure = new JTextField(); default_pw_text_sure.setBounds(332, 21, 186, 34); // panel_1.add(default_pw_text_sure); default_pw_text_sure.setVisible(false); default_pw_text_sure.setForeground(Color.RED); default_pw_text_sure.setFont(new Font("微软雅黑", Font.PLAIN, 14)); default_pw_text_sure.setEditable(false); default_pw_text_sure.setColumns(10); default_pw_text_sure.setText(""); JLabel default_pw_label_sure = new JLabel("密码:"); default_pw_label_sure.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_pw_label_sure.setForeground(new Color(128, 0, 0)); default_pw_label_sure.setBounds(281, 21, 86, 34); default_pw_label_sure.setVisible(false); JPanel accountSetPanel = new JPanel(); accountSetPanel.setBorder(new TitledBorder(null, "\u8D26\u6237\u8BBE\u7F6E", TitledBorder.LEADING, TitledBorder.TOP, null, null)); accountSetPanel.setBounds(0, 10, 859, 560); AccountSet_Panel.add(accountSetPanel); accountSetPanel.setLayout(null); JLabel default_id_label_01 = new JLabel("帐户 1:"); default_id_label_01.setBounds(84, 10, 86, 34); accountSetPanel.add(default_id_label_01); default_id_label_01.setFont(new Font("微软雅黑", Font.PLAIN, 12)); JLabel default_id_label_02 = new JLabel("账户 2:"); default_id_label_02.setBounds(84, 66, 86, 34); accountSetPanel.add(default_id_label_02); default_id_label_02.setFont(new Font("微软雅黑", Font.PLAIN, 12)); JLabel default_id_label_03 = new JLabel("账户 3:"); default_id_label_03.setBounds(84, 123, 86, 34); accountSetPanel.add(default_id_label_03); default_id_label_03.setFont(new Font("微软雅黑", Font.PLAIN, 12)); JLabel default_id_label_04 = new JLabel("账户 4:"); default_id_label_04.setBounds(84, 183, 86, 34); accountSetPanel.add(default_id_label_04); default_id_label_04.setFont(new Font("微软雅黑", Font.PLAIN, 12)); JLabel default_id_label_05 = new JLabel("账户 5:"); default_id_label_05.setBounds(84, 240, 86, 34); accountSetPanel.add(default_id_label_05); default_id_label_05.setFont(new Font("微软雅黑", Font.PLAIN, 12)); JLabel default_id_label_06 = new JLabel("账户 6:"); default_id_label_06.setBounds(84, 291, 86, 34); accountSetPanel.add(default_id_label_06); default_id_label_06.setFont(new Font("微软雅黑", Font.PLAIN, 12)); JLabel default_pw_label_01 = new JLabel("密码:"); default_pw_label_01.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_pw_label_01.setBounds(403, 10, 74, 34); accountSetPanel.add(default_pw_label_01); JLabel default_pw_label_02 = new JLabel("密码:"); default_pw_label_02.setBounds(403, 66, 74, 34); accountSetPanel.add(default_pw_label_02); default_pw_label_02.setFont(new Font("微软雅黑", Font.PLAIN, 12)); JLabel default_pw_label_03 = new JLabel("密码:"); default_pw_label_03.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_pw_label_03.setBounds(403, 123, 86, 34); accountSetPanel.add(default_pw_label_03); JLabel default_pw_label_04 = new JLabel("密码:"); default_pw_label_04.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_pw_label_04.setBounds(403, 183, 86, 34); accountSetPanel.add(default_pw_label_04); JLabel default_pw_label_05 = new JLabel("密码:"); default_pw_label_05.setBounds(403, 240, 86, 34); accountSetPanel.add(default_pw_label_05); default_pw_label_05.setFont(new Font("微软雅黑", Font.PLAIN, 12)); JLabel default_pw_label_06 = new JLabel("密码:"); default_pw_label_06.setBounds(403, 291, 86, 34); accountSetPanel.add(default_pw_label_06); default_pw_label_06.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_id_text_01 = new JTextField(""); default_id_text_01.setBounds(169, 11, 186, 34); accountSetPanel.add(default_id_text_01); default_id_text_01.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_id_text_01.setBackground(Color.WHITE); default_id_text_01.setColumns(10); default_id_text_02 = new JTextField(""); default_id_text_02.setBounds(169, 67, 186, 34); accountSetPanel.add(default_id_text_02); default_id_text_02.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_id_text_02.setColumns(10); default_id_text_03 = new JTextField(""); default_id_text_03.setBounds(169, 124, 186, 34); accountSetPanel.add(default_id_text_03); default_id_text_03.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_id_text_03.setColumns(10); default_id_text_04 = new JTextField(""); default_id_text_04.setBounds(169, 184, 186, 34); accountSetPanel.add(default_id_text_04); default_id_text_04.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_id_text_04.setText((String) null); default_id_text_04.setColumns(10); default_id_text_05 = new JTextField(""); default_id_text_05.setBounds(169, 241, 186, 34); accountSetPanel.add(default_id_text_05); default_id_text_05.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_id_text_05.setText((String) null); default_id_text_05.setColumns(10); default_id_text_06 = new JTextField(""); default_id_text_06.setBounds(169, 292, 186, 34); accountSetPanel.add(default_id_text_06); default_id_text_06.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_id_text_06.setText((String) null); default_id_text_06.setColumns(10); default_pw_text_01 = new JTextField(""); default_pw_text_01.setBounds(475, 11, 186, 34); accountSetPanel.add(default_pw_text_01); default_pw_text_01.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_pw_text_01.setColumns(10); default_pw_text_02 = new JTextField(""); default_pw_text_02.setBounds(475, 67, 186, 34); accountSetPanel.add(default_pw_text_02); default_pw_text_02.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_pw_text_02.setColumns(10); default_pw_text_03 = new JTextField(""); default_pw_text_03.setBounds(475, 124, 186, 34); accountSetPanel.add(default_pw_text_03); default_pw_text_03.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_pw_text_03.setColumns(10); default_pw_text_04 = new JTextField(""); default_pw_text_04.setBounds(475, 184, 186, 34); accountSetPanel.add(default_pw_text_04); default_pw_text_04.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_pw_text_04.setText((String) null); default_pw_text_04.setColumns(10); default_pw_text_05 = new JTextField(""); default_pw_text_05.setBounds(475, 241, 186, 34); accountSetPanel.add(default_pw_text_05); default_pw_text_05.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_pw_text_05.setText((String) null); default_pw_text_05.setColumns(10); default_pw_text_06 = new JTextField(""); default_pw_text_06.setBounds(475, 292, 186, 34); accountSetPanel.add(default_pw_text_06); default_pw_text_06.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_pw_text_06.setText((String) null); default_pw_text_06.setColumns(10); JLabel default_id_label_07 = new JLabel("账户 7:"); default_id_label_07.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_id_label_07.setBounds(84, 349, 86, 34); accountSetPanel.add(default_id_label_07); JLabel default_id_label_08 = new JLabel("账户 8:"); default_id_label_08.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_id_label_08.setBounds(84, 403, 86, 34); accountSetPanel.add(default_id_label_08); JLabel default_id_label_09 = new JLabel("账户 9:"); default_id_label_09.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_id_label_09.setBounds(84, 453, 86, 34); accountSetPanel.add(default_id_label_09); JLabel default_id_label_10 = new JLabel("账户 10:"); default_id_label_10.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_id_label_10.setBounds(84, 505, 86, 34); accountSetPanel.add(default_id_label_10); default_id_text_07 = new JTextField(""); default_id_text_07.setText((String) null); default_id_text_07.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_id_text_07.setColumns(10); default_id_text_07.setBounds(169, 350, 186, 34); accountSetPanel.add(default_id_text_07); default_id_text_08 = new JTextField(""); default_id_text_08.setText((String) null); default_id_text_08.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_id_text_08.setColumns(10); default_id_text_08.setBounds(169, 404, 186, 34); accountSetPanel.add(default_id_text_08); default_id_text_09 = new JTextField(""); default_id_text_09.setText((String) null); default_id_text_09.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_id_text_09.setColumns(10); default_id_text_09.setBounds(169, 454, 186, 34); accountSetPanel.add(default_id_text_09); default_id_text_10 = new JTextField(""); default_id_text_10.setText((String) null); default_id_text_10.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_id_text_10.setColumns(10); default_id_text_10.setBounds(169, 506, 186, 34); accountSetPanel.add(default_id_text_10); JLabel default_pw_label_07 = new JLabel("\u5BC6\u7801\uFF1A"); default_pw_label_07.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_pw_label_07.setBounds(403, 349, 86, 34); accountSetPanel.add(default_pw_label_07); JLabel default_pw_label_08 = new JLabel("\u5BC6\u7801\uFF1A"); default_pw_label_08.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_pw_label_08.setBounds(403, 403, 86, 34); accountSetPanel.add(default_pw_label_08); JLabel default_pw_label_09 = new JLabel("\u5BC6\u7801\uFF1A"); default_pw_label_09.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_pw_label_09.setBounds(403, 453, 86, 34); accountSetPanel.add(default_pw_label_09); JLabel default_pw_label_10 = new JLabel("\u5BC6\u7801\uFF1A"); default_pw_label_10.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_pw_label_10.setBounds(403, 505, 86, 34); accountSetPanel.add(default_pw_label_10); default_pw_text_07 = new JTextField(""); default_pw_text_07.setText((String) null); default_pw_text_07.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_pw_text_07.setColumns(10); default_pw_text_07.setBounds(475, 350, 186, 34); accountSetPanel.add(default_pw_text_07); default_pw_text_08 = new JTextField(""); default_pw_text_08.setText((String) null); default_pw_text_08.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_pw_text_08.setColumns(10); default_pw_text_08.setBounds(475, 404, 186, 34); accountSetPanel.add(default_pw_text_08); default_pw_text_09 = new JTextField(""); default_pw_text_09.setText((String) null); default_pw_text_09.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_pw_text_09.setColumns(10); default_pw_text_09.setBounds(475, 454, 186, 34); accountSetPanel.add(default_pw_text_09); default_pw_text_10 = new JTextField(""); default_pw_text_10.setText((String) null); default_pw_text_10.setFont(new Font("微软雅黑", Font.PLAIN, 12)); default_pw_text_10.setColumns(10); default_pw_text_10.setBounds(475, 506, 186, 34); accountSetPanel.add(default_pw_text_10); JButton changAccountsButton = new JButton("修改账户"); changAccountsButton.setFont(new Font("微软雅黑", Font.PLAIN, 14)); changAccountsButton.setBounds(706, 252, 123, 40); accountSetPanel.add(changAccountsButton); changAccountsButton.addActionListener(new MyListener(this)); /* * ****************游戏设置***************** */ JPanel AutoSell_Panel = new JPanel(); // tabbedPane.addTab("游戏设置", null, AutoSell_Panel, null); ////////////////////////////////禁用游戏设置 AutoSell_Panel.setLayout(null); JPanel panel = new JPanel(); panel.setBounds(10, 0, 849, 570); AutoSell_Panel.add(panel); panel.setLayout(null); radioButton_1.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_1.setBounds(9, 40, 421, 38); panel.add(radioButton_1); radioButton_2.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_2.setBounds(9, 80, 421, 38); panel.add(radioButton_2); radioButton_3.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_3.setBounds(9, 120, 421, 36); panel.add(radioButton_3); radioButton_4.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_4.setBounds(9, 158, 421, 38); panel.add(radioButton_4); radioButton_5.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_5.setBounds(9, 198, 421, 35); panel.add(radioButton_5); radioButton_6.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_6.setBounds(9, 235, 421, 38); panel.add(radioButton_6); radioButton_7.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_7.setBounds(9, 275, 421, 35); panel.add(radioButton_7); radioButton_8.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_8.setBounds(9, 312, 421, 35); panel.add(radioButton_8); radioButton_9.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_9.setBounds(9, 354, 421, 35); panel.add(radioButton_9); radioButton_10.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_10.setBounds(9, 391, 421, 35); panel.add(radioButton_10); radioButton_11.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_11.setBounds(9, 428, 411, 38); panel.add(radioButton_11); radioButton_12.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_12.setBounds(9, 468, 411, 38); panel.add(radioButton_12); radioButton_13.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_13.setBounds(9, 508, 411, 38); panel.add(radioButton_13); radioButton_14.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_14.setBounds(432, 40, 411, 38); panel.add(radioButton_14); radioButton_15.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_15.setBounds(432, 80, 411, 38); panel.add(radioButton_15); radioButton_16.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_16.setBounds(432, 119, 411, 38); panel.add(radioButton_16); radioButton_17.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_17.setBounds(432, 158, 411, 38); panel.add(radioButton_17); radioButton_18.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_18.setBounds(432, 196, 411, 38); panel.add(radioButton_18); radioButton_19.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_19.setBounds(432, 235, 411, 38); panel.add(radioButton_19); radioButton_20.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_20.setBounds(432, 273, 411, 38); panel.add(radioButton_20); group = new ButtonGroup(); group.add(radioButton_1); group.add(radioButton_2); group.add(radioButton_3); group.add(radioButton_4); group.add(radioButton_5); group.add(radioButton_6); group.add(radioButton_7); group.add(radioButton_8); group.add(radioButton_9); group.add(radioButton_10); group.add(radioButton_11); group.add(radioButton_12); group.add(radioButton_13); group.add(radioButton_14); group.add(radioButton_15); group.add(radioButton_16); group.add(radioButton_17); group.add(radioButton_18); group.add(radioButton_19); group.add(radioButton_20); group.add(radioButton_21); group.add(radioButton_22); group.add(radioButton_23); group.add(radioButton_24); group.add(radioButton_25); group.add(radioButton_26); JButton editGameButton = new JButton("查看或修改游戏信息"); editGameButton.setFont(new Font("微软雅黑", Font.PLAIN, 12)); editGameButton.setBounds(50, 5, 162, 33); panel.add(editGameButton); editGameButton.addActionListener(new MyListener(this)); JButton delGameButton = new JButton("删除此游戏"); delGameButton.setFont(new Font("微软雅黑", Font.PLAIN, 12)); delGameButton.setBounds(250, 5, 162, 34); panel.add(delGameButton); radioButton_21.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_21.setBounds(432, 309, 411, 38); panel.add(radioButton_21); radioButton_22.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_22.setBounds(432, 351, 411, 38); panel.add(radioButton_22); radioButton_23.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_23.setBounds(432, 388, 411, 38); panel.add(radioButton_23); radioButton_24.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_24.setBounds(432, 428, 411, 38); panel.add(radioButton_24); radioButton_25.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_25.setBounds(432, 468, 411, 38); panel.add(radioButton_25); radioButton_26.setFont(new Font("微软雅黑", Font.PLAIN, 14)); radioButton_26.setBounds(432, 508, 411, 38); panel.add(radioButton_26); default_pw_text_sure2 = new JTextField(); default_pw_text_sure2.setText(""); default_pw_text_sure2.setForeground(Color.RED); default_pw_text_sure2.setFont(new Font("微软雅黑", Font.PLAIN, 14)); default_pw_text_sure2.setEditable(false); default_pw_text_sure2.setColumns(10); default_pw_text_sure2.setBounds(356, 20, 186, 34); // panel_2.add(default_pw_text_sure2); default_pw_text_sure2.setVisible(false); JLabel label_1 = new JLabel("密码:"); label_1.setFont(new Font("微软雅黑", Font.PLAIN, 12)); label_1.setForeground(new Color(128, 0, 0)); label_1.setBounds(292, 17, 76, 34); // panel_2.add(label_1); label_1.setVisible(false); delGameButton.addActionListener(new MyListener(this)); radioButton_1.addActionListener(new MyListener(this)); radioButton_2.addActionListener(new MyListener(this)); radioButton_3.addActionListener(new MyListener(this)); radioButton_4.addActionListener(new MyListener(this)); radioButton_5.addActionListener(new MyListener(this)); radioButton_6.addActionListener(new MyListener(this)); radioButton_7.addActionListener(new MyListener(this)); radioButton_8.addActionListener(new MyListener(this)); radioButton_9.addActionListener(new MyListener(this)); radioButton_10.addActionListener(new MyListener(this)); radioButton_11.addActionListener(new MyListener(this)); radioButton_12.addActionListener(new MyListener(this)); radioButton_13.addActionListener(new MyListener(this)); radioButton_14.addActionListener(new MyListener(this)); radioButton_15.addActionListener(new MyListener(this)); radioButton_16.addActionListener(new MyListener(this)); radioButton_17.addActionListener(new MyListener(this)); radioButton_18.addActionListener(new MyListener(this)); radioButton_19.addActionListener(new MyListener(this)); radioButton_20.addActionListener(new MyListener(this)); radioButton_21.addActionListener(new MyListener(this)); radioButton_22.addActionListener(new MyListener(this)); radioButton_23.addActionListener(new MyListener(this)); radioButton_24.addActionListener(new MyListener(this)); radioButton_25.addActionListener(new MyListener(this)); radioButton_26.addActionListener(new MyListener(this)); /* * ***************淘宝订单查询的Panel************** */ JPanel panel_3 = new JPanel(); // tabbedPane.addTab("Steam充值", null, panel_3, null); ///////////////////////////////////// 禁用steam充值 panel_3.setLayout(null); JLabel codeDefaultAccountLabel = new JLabel("当前账户:"); codeDefaultAccountLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12)); codeDefaultAccountLabel.setBounds(358, 21, 83, 36); panel_3.add(codeDefaultAccountLabel); JLabel codesLabel = new JLabel("充值码:"); codesLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12)); codesLabel.setBounds(10, 70, 69, 36); panel_3.add(codesLabel); JLabel codesStatusLabel = new JLabel("充值码状态:"); codesStatusLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12)); codesStatusLabel.setBounds(358, 67, 96, 36); panel_3.add(codesStatusLabel); JLabel statusLabel = new JLabel("充值状态:"); statusLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12)); statusLabel.setBounds(10, 416, 69, 36); panel_3.add(statusLabel); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(73, 76, 264, 309); panel_3.add(scrollPane); codesTextArea = new JTextArea(); codesTextArea.setFont(new Font("微软雅黑", Font.PLAIN, 13)); scrollPane.setViewportView(codesTextArea); JScrollPane scrollPane_1 = new JScrollPane(); scrollPane_1.setBounds(451, 76, 396, 309); panel_3.add(scrollPane_1); codesStatusTextArea = new JTextArea(); codesStatusTextArea.setFont(new Font("微软雅黑", Font.PLAIN, 13)); codesStatusTextArea.setBackground(SystemColor.control); codesStatusTextArea.setEditable(false); scrollPane_1.setViewportView(codesStatusTextArea); codeDefaultAccountText = new JTextField(); codeDefaultAccountText.setEditable(false); codeDefaultAccountText.setBackground(new Color(72, 209, 204)); codeDefaultAccountText.setFont(new Font("微软雅黑", Font.PLAIN, 14)); codeDefaultAccountText.setBounds(451, 16, 396, 41); panel_3.add(codeDefaultAccountText); codeDefaultAccountText.setColumns(10); statusText = new JTextField(); statusText.setForeground(Color.RED); statusText.setFont(new Font("微软雅黑", Font.PLAIN, 16)); statusText.setEditable(false); statusText.setColumns(10); statusText.setBounds(73, 406, 774, 57); panel_3.add(statusText); JButton codeAutoButton = new JButton("Code自动充值"); codeAutoButton.setFont(new Font("微软雅黑", Font.PLAIN, 12)); codeAutoButton.setBounds(156, 487, 209, 48); panel_3.add(codeAutoButton); codeAutoButton.addActionListener(new MyListener(this)); JButton codeCheckButton = new JButton("Code批量验证"); codeCheckButton.setFont(new Font("微软雅黑", Font.PLAIN, 12)); codeCheckButton.setBounds(550, 487, 209, 48); panel_3.add(codeCheckButton); codeAccountsComboBox = new JComboBox(); codeAccountsComboBox.setForeground(Color.RED); codeAccountsComboBox.setFont(new Font("微软雅黑", Font.PLAIN, 14)); codeAccountsComboBox.setBounds(73, 16, 264, 41); panel_3.add(codeAccountsComboBox); codeAccountsComboBox.addItemListener(new MyListener(this)); JLabel label = new JLabel("选择账户:"); label.setFont(new Font("微软雅黑", Font.PLAIN, 12)); label.setBounds(10, 21, 83, 36); panel_3.add(label); codeCheckButton.addActionListener(new MyListener(this)); /* * 淘宝订单 */ JPanel Nid_Panel = new JPanel(); // tabbedPane.addTab("订单查询", null, Nid_Panel, null); /////////////////////////////////禁用淘宝订单 String[] columnNames = {"下单时间","订单编号","商品名称","买家旺旺","实收款","交易状态","买家留言","购买数量","卖家备注"}; String[][] column_01 = {}; tableModel = new DefaultTableModel(column_01,columnNames); JLabel table_nid_id_label = new JLabel("商品名称:"); //改成商品名称 table_nid_id_label.setFont(new Font("微软雅黑", Font.PLAIN, 14)); table_nid_id_label.setBounds(6, 18, 93, 40); JLabel table_buyer_id_label = new JLabel("买家用户名:"); table_buyer_id_label.setFont(new Font("微软雅黑", Font.PLAIN, 14)); table_buyer_id_label.setBounds(6, 114, 93, 40); JLabel table_buyer_email_label = new JLabel("买家邮箱:"); //改成可以输入或者从买家备注中读取 (之前做的邮箱处理函数) table_buyer_email_label.setFont(new Font("微软雅黑", Font.PLAIN, 14)); table_buyer_email_label.setBounds(434, 69, 93, 40); JLabel table_buyer_note_label = new JLabel("买家备注:"); table_buyer_note_label.setFont(new Font("微软雅黑", Font.PLAIN, 14)); table_buyer_note_label.setBounds(434, 115, 93, 40); JLabel table_buyer_game_lable = new JLabel("购买账户:"); table_buyer_game_lable.setFont(new Font("微软雅黑", Font.PLAIN, 14)); table_buyer_game_lable.setBounds(6, 214, 418, 40); account_type_combo.setFont(new Font("微软雅黑", Font.PLAIN, 14)); account_type_combo.setBounds(426, 214, 418, 40); account_type_combo.addItemListener(new MyListener(this)); JButton autoSeller_button2 = new JButton("手动充值"); autoSeller_button2.setFont(new Font("微软雅黑", Font.PLAIN, 14)); autoSeller_button2.setBounds(426, 264, 200, 40); JButton change_state_button1 = new JButton("发货"); change_state_button1.setFont(new Font("微软雅黑", Font.PLAIN, 14)); change_state_button1.setBounds(640, 264, 200, 40); autoSeller_button2.addActionListener(new MyListener(this)); change_state_button1.addActionListener(new MyListener(this)); JPanel sub_table_panel = new JPanel(); sub_table_panel.setBounds(9, 266, 850, 314); sub_table_panel.setPreferredSize(new Dimension(850, 350)); sub_table_panel.setBorder(BorderFactory.createTitledBorder("订单详情")); sub_table_panel.setLayout(null); sub_table_panel.add(table_nid_id_label); table_gameName_text.setEditable(false); table_gameName_text.setFont(new Font("微软雅黑", Font.PLAIN, 14)); table_gameName_text.setBounds(96, 19, 740, 40); sub_table_panel.add(table_gameName_text); sub_table_panel.add(table_buyer_id_label); table_buyer_id_text.setEditable(false); table_buyer_id_text.setFont(new Font("微软雅黑", Font.PLAIN, 14)); table_buyer_id_text.setBounds(96, 115, 317, 40); sub_table_panel.add(table_buyer_id_text); sub_table_panel.add(table_buyer_email_label); table_buyer_email_text.setFont(new Font("微软雅黑", Font.PLAIN, 14)); table_buyer_email_text.setBounds(525, 69, 311, 40); sub_table_panel.add(table_buyer_email_text); sub_table_panel.add(table_buyer_note_label); table_buyer_message_text.setEditable(false); table_buyer_message_text.setFont(new Font("微软雅黑", Font.PLAIN, 14)); table_buyer_message_text.setBounds(525, 115, 317, 40); sub_table_panel.add(table_buyer_message_text); sub_table_panel.add(table_buyer_game_lable); sub_table_panel.add(account_type_combo); sub_table_panel.add(autoSeller_button2); sub_table_panel.add(change_state_button1); Nid_Panel.add(sub_table_panel); JLabel label_3 = new JLabel("购买个数:"); label_3.setFont(new Font("微软雅黑", Font.PLAIN, 14)); label_3.setBounds(6, 64, 80, 40); sub_table_panel.add(label_3); table_gameNum_text = new JTextField(37); table_gameNum_text.setEditable(false); table_gameNum_text.setFont(new Font("微软雅黑", Font.PLAIN, 14)); table_gameNum_text.setBounds(96, 68, 317, 40); sub_table_panel.add(table_gameNum_text); JLabel label_7 = new JLabel("卖家备注:"); label_7.setFont(new Font("微软雅黑", Font.PLAIN, 14)); label_7.setBounds(6, 164, 93, 40); sub_table_panel.add(label_7); table_seller_message_text = new JTextField(37); table_seller_message_text.setEditable(false); table_seller_message_text.setFont(new Font("微软雅黑", Font.PLAIN, 14)); table_seller_message_text.setBounds(96, 164, 317, 40); sub_table_panel.add(table_seller_message_text); JScrollPane scrollPane_3 = new JScrollPane(); scrollPane_3.setBounds(9, 60, 850, 196); Nid_Panel.add(scrollPane_3); table = new JTable(tableModel); table.setFont(new Font("微软雅黑", Font.PLAIN, 12)); scrollPane_3.setViewportView(table); table.setRowHeight(35); //重新设置表格的宽度 TableColumn col_01 = table.getColumn("下单时间"); TableColumn col_02 = table.getColumn("订单编号"); TableColumn col_03 = table.getColumn("商品名称"); TableColumn col_04 = table.getColumn("买家旺旺"); TableColumn col_05 = table.getColumn("实收款"); TableColumn col_06 = table.getColumn("交易状态"); TableColumn col_07 = table.getColumn("买家留言"); TableColumn col_08 = table.getColumn("购买数量"); TableColumn col_09 = table.getColumn("卖家备注"); col_01.setPreferredWidth(125); col_02.setPreferredWidth(115); col_03.setPreferredWidth(350); col_04.setPreferredWidth(100); col_05.setPreferredWidth(50); col_06.setPreferredWidth(110); //不显示收货地址这一列,但是内容还在 col_07.setMaxWidth(0); col_07.setMinWidth(0); col_07.setPreferredWidth(0); col_08.setMaxWidth(0); col_08.setMinWidth(0); col_08.setPreferredWidth(0); col_09.setMaxWidth(0); col_09.setMinWidth(0); col_09.setPreferredWidth(0); Nid_Panel.setLayout(null); table.addMouseListener(new MyTableListener(this)); // JScrollPane orderListScrollPane = new JScrollPane(table); //支持滚动 Nid_Panel.add(table.getTableHeader()); JButton start_clash_button = new JButton("刷新"); start_clash_button.setFont(new Font("微软雅黑", Font.PLAIN, 14)); start_clash_button.setBounds(670, 10, 189, 40); Nid_Panel.add(start_clash_button); JLabel lblNewLabel = new JLabel("开始时间:"); lblNewLabel.setFont(new Font("微软雅黑", Font.BOLD, 14)); lblNewLabel.setBounds(9, 10, 94, 40); Nid_Panel.add(lblNewLabel); JLabel label_2 = new JLabel("结束时间:"); label_2.setFont(new Font("微软雅黑", Font.BOLD, 14)); label_2.setBounds(338, 10, 118, 40); Nid_Panel.add(label_2); startTimeField = new JTextField(); startTimeField.setFont(new Font("微软雅黑", Font.PLAIN, 14)); startTimeField.setBounds(86, 10, 242, 40); Nid_Panel.add(startTimeField); startTimeField.setColumns(10); endTimeField = new JTextField(); endTimeField.setFont(new Font("微软雅黑", Font.PLAIN, 14)); endTimeField.setColumns(10); endTimeField.setBounds(418, 10, 242, 40); Nid_Panel.add(endTimeField); start_clash_button.addActionListener(new MyListener(this)); /* * 淘宝授权 */ ButtonGroup group1 = new ButtonGroup(); ButtonGroup group2 = new ButtonGroup(); ButtonGroup group3 = new ButtonGroup(); JPanel Session_Panel = new JPanel(); // tabbedPane.addTab("淘宝授权", null, Session_Panel, null); /////////////////////////////////////禁用淘宝授权 Session_Panel.setLayout(null); JLabel Session_label = new JLabel("输入Session"); Session_label.setFont(new Font("微软雅黑", Font.PLAIN, 14)); Session_label.setBounds(38, 20, 111, 38); Session_Panel.add(Session_label); Session_text = new JTextField(); Session_text.setFont(new Font("微软雅黑", Font.PLAIN, 14)); Session_text.setBounds(182, 18, 634, 38); Session_Panel.add(Session_text); Session_text.setColumns(10); JLabel Session_key_label = new JLabel("获得的SessionKey"); Session_key_label.setFont(new Font("微软雅黑", Font.PLAIN, 14)); Session_key_label.setBounds(38, 78, 111, 38); Session_Panel.add(Session_key_label); Session_key_text = new JTextField(); Session_key_text.setFont(new Font("微软雅黑", Font.PLAIN, 14)); Session_key_text.setEditable(false); Session_key_text.setColumns(10); Session_key_text.setBounds(182, 78, 634, 38); Session_Panel.add(Session_key_text); JButton Seesion_key_button = new JButton("获取SessionKey"); Seesion_key_button.setFont(new Font("微软雅黑", Font.PLAIN, 14)); Seesion_key_button.setBounds(452, 153, 161, 43); Session_Panel.add(Seesion_key_button); JPanel panel_9 = new JPanel(); panel_9.setBorder(new TitledBorder(null, "功能设置", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panel_9.setBounds(10, 276, 849, 272); Session_Panel.add(panel_9); panel_9.setLayout(null); closeBroRadioButton = new JRadioButton("关闭",true); closeBroRadioButton.setFont(new Font("微软雅黑", Font.PLAIN, 14)); group1.add(closeBroRadioButton); closeBroRadioButton.setBounds(388, 56, 121, 23); panel_9.add(closeBroRadioButton); closeBroRadioButton.addActionListener(new MyListener(this)); dontCloseRadioButton = new JRadioButton("不关闭"); dontCloseRadioButton.setFont(new Font("微软雅黑", Font.PLAIN, 14)); group1.add(dontCloseRadioButton); dontCloseRadioButton.setBounds(579, 56, 121, 23); panel_9.add(dontCloseRadioButton); dontCloseRadioButton.addActionListener(new MyListener(this)); showBroRadioButton = new JRadioButton("显示",true); showBroRadioButton.setFont(new Font("微软雅黑", Font.PLAIN, 14)); group2.add(showBroRadioButton); showBroRadioButton.setBounds(388, 115, 121, 23); panel_9.add(showBroRadioButton); showBroRadioButton.addActionListener(new MyListener(this)); dontShowRadioButton = new JRadioButton("不显示"); dontShowRadioButton.setFont(new Font("微软雅黑", Font.PLAIN, 14)); group2.add(dontShowRadioButton); dontShowRadioButton.setBounds(579, 115, 121, 23); panel_9.add(dontShowRadioButton); dontShowRadioButton.addActionListener(new MyListener(this)); autoSendRadioButton = new JRadioButton("手动发货",true); autoSendRadioButton.setFont(new Font("微软雅黑", Font.PLAIN, 14)); group3.add(autoSendRadioButton); autoSendRadioButton.setBounds(388, 174, 121, 23); panel_9.add(autoSendRadioButton); autoSendRadioButton.addActionListener(new MyListener(this)); manualSendRadioButton = new JRadioButton("自动发货"); manualSendRadioButton.setFont(new Font("微软雅黑", Font.PLAIN, 14)); group3.add(manualSendRadioButton); manualSendRadioButton.setBounds(579, 174, 121, 23); panel_9.add(manualSendRadioButton); manualSendRadioButton.addActionListener(new MyListener(this)); JLabel lblNewLabel_2 = new JLabel("完成后是否关闭浏览器(默认关闭):"); lblNewLabel_2.setForeground(new Color(128, 0, 0)); lblNewLabel_2.setFont(new Font("微软雅黑", Font.PLAIN, 14)); lblNewLabel_2.setBounds(94, 48, 260, 38); panel_9.add(lblNewLabel_2); JLabel label_5 = new JLabel("运行是否需要显示浏览器(默认显示):"); label_5.setForeground(new Color(128, 0, 0)); label_5.setFont(new Font("微软雅黑", Font.PLAIN, 14)); label_5.setBounds(94, 106, 260, 38); panel_9.add(label_5); JLabel label_6 = new JLabel("符合条件的淘宝订单(默认手动发货):"); label_6.setForeground(new Color(128, 0, 0)); label_6.setFont(new Font("微软雅黑", Font.PLAIN, 14)); label_6.setBounds(94, 164, 260, 38); panel_9.add(label_6); JButton taobaoAutoButton = new JButton("点击获取淘宝授权"); taobaoAutoButton.setFont(new Font("微软雅黑", Font.PLAIN, 14)); taobaoAutoButton.setBounds(182, 153, 161, 43); Session_Panel.add(taobaoAutoButton); taobaoAutoButton.addActionListener(new MyListener(this)); Seesion_key_button.addActionListener(new MyListener(this)); JPanel panel_6 = new JPanel(); tabbedPane.addTab("运行日志", null, panel_6, null); panel_6.setLayout(null); JScrollPane scrollPane_2 = new JScrollPane(); scrollPane_2.setBounds(5,5, 870, 520); panel_6.add(scrollPane_2); steamLogTextArea = new JTextArea(); scrollPane_2.setViewportView(steamLogTextArea); steamLogTextArea.setForeground(new Color(0, 139, 139)); steamLogTextArea.setFont(new Font("微软雅黑", Font.PLAIN, 14)); JButton clearLogButton = new JButton("清空历史记录"); clearLogButton.setFont(new Font("微软雅黑", Font.PLAIN, 14)); clearLogButton.setBounds(730, 530, 143, 39); panel_6.add(clearLogButton); clearLogButton.addActionListener(new MyListener(this)); // **************调用账户页面初始化函数************** getDefaultAccount(); //调用游戏选择界面初始化函数 // setGames(); setJsonGames(); //Code验证与充值时初始化账户函数 getCodeAccounts(); //读取所有日志 getAllLog(); //读取BuySteamGameXpath的初始化程序 getBuySteamGameXpath(); //初始化时间 setStartEndTime(); //最后给TabPanel添加监听 // tabbedPane.addChangeListener(new MyChangeListener(this)); } /* * *****************账户界面初始化****************** */ public void getDefaultAccount() { BufferedReader br = null; this.buyGameAccounts = new HashMap<String, String>(); this.buyGameAccountID = new ArrayList<String>(); try { br = new BufferedReader(new FileReader(new File("config\\Accounts_Purchase.txt"))); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } String temp; //注意编码问题,这个程序不支持utf-8,所以所有的txt文件保存为ansi的 //读取默认账户文件 int i = 0; try { br.readLine(); // while((temp=br.readLine())!=null&&i++<10){ while((temp=br.readLine())!=null){ String default_id = temp.split("-")[0]; String default_pw = temp.split("-")[1]; this.buyGameAccountID.add(default_id); this.buyGameAccounts.put(default_id, default_pw); // switch(i){ // case 1: // this.default_id_text_01.setText(default_id); // this.default_pw_text_01.setText(default_pw); // break; // case 2: // this.default_id_text_02.setText(default_id); // this.default_pw_text_02.setText(default_pw); // break; // case 3: // this.default_id_text_03.setText(default_id); // this.default_pw_text_03.setText(default_pw); // break; // case 4: // this.default_id_text_04.setText(default_id); // this.default_pw_text_04.setText(default_pw); // break; // case 5: // this.default_id_text_05.setText(default_id); // this.default_pw_text_05.setText(default_pw); // break; // case 6: // this.default_id_text_06.setText(default_id); // this.default_pw_text_06.setText(default_pw); // break; // case 7: // this.default_id_text_07.setText(default_id); // this.default_pw_text_07.setText(default_pw); // break; // case 8: // this.default_id_text_08.setText(default_id); // this.default_pw_text_08.setText(default_pw); // break; // case 9: // this.default_id_text_09.setText(default_id); // this.default_pw_text_09.setText(default_pw); // break; // case 10: // this.default_id_text_10.setText(default_id); // this.default_pw_text_10.setText(default_pw); // break; // } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //先删除所有项目再添加 this.account_type_combo.removeAllItems(); this.accountsComboBox.removeAllItems(); this.codeAccountsComboBox.removeAllItems(); for(i=0;i<this.buyGameAccountID.size();i++){ this.accountsComboBox.addItem(this.buyGameAccountID.get(i)); this.account_type_combo.addItem(this.buyGameAccountID.get(i)); this.codeAccountsComboBox.addItem(this.buyGameAccountID.get(i)); } } /* * *******游戏选择界面初始化函数********** */ public void setGames() throws JDOMException, IOException{ File f = new File("games"); File[] fileLists = f.listFiles(); steamGames = new HashMap<String, SteamGame>(); games = new ArrayList<String>(); radioButton_1.setText("请添加游戏"); radioButton_2.setText("请添加游戏"); radioButton_3.setText("请添加游戏"); radioButton_4.setText("请添加游戏"); radioButton_5.setText("请添加游戏"); radioButton_6.setText("请添加游戏"); radioButton_7.setText("请添加游戏"); radioButton_8.setText("请添加游戏"); radioButton_9.setText("请添加游戏"); radioButton_10.setText("请添加游戏"); radioButton_11.setText("请添加游戏"); radioButton_12.setText("请添加游戏"); radioButton_13.setText("请添加游戏"); radioButton_14.setText("请添加游戏"); radioButton_15.setText("请添加游戏"); radioButton_16.setText("请添加游戏"); radioButton_17.setText("请添加游戏"); radioButton_18.setText("请添加游戏"); radioButton_19.setText("请添加游戏"); radioButton_20.setText("请添加游戏"); radioButton_21.setText("请添加游戏"); radioButton_22.setText("请添加游戏"); radioButton_23.setText("请添加游戏"); radioButton_24.setText("请添加游戏"); radioButton_25.setText("请添加游戏"); radioButton_26.setText("请添加游戏"); //按顺序读取文件并保存到Map for(int i=0;i<fileLists.length&&i<26;i++){ BufferedReader br = new BufferedReader(new FileReader(fileLists[i])); SteamGame steamGame = new SteamGame(); steamGame.setFileName(fileLists[i].getName()); steamGame.setLink(br.readLine()); steamGame.setXpath(br.readLine()); steamGame.setName(br.readLine()); steamGames.put(steamGame.getName(), steamGame); games.add(steamGame.getName()); switch(i+1){ case 1: radioButton_1.setText(steamGame.getName()); break; case 2: radioButton_2.setText(steamGame.getName()); break; case 3: radioButton_3.setText(steamGame.getName()); break; case 4: radioButton_4.setText(steamGame.getName()); break; case 5: radioButton_5.setText(steamGame.getName()); break; case 6: radioButton_6.setText(steamGame.getName()); break; case 7: radioButton_7.setText(steamGame.getName()); break; case 8: radioButton_8.setText(steamGame.getName()); break; case 9: radioButton_9.setText(steamGame.getName()); break; case 10: radioButton_10.setText(steamGame.getName()); break; case 11: radioButton_11.setText(steamGame.getName()); break; case 12: radioButton_12.setText(steamGame.getName()); break; case 13: radioButton_13.setText(steamGame.getName()); break; case 14: radioButton_14.setText(steamGame.getName()); break; case 15: radioButton_15.setText(steamGame.getName()); break; case 16: radioButton_16.setText(steamGame.getName()); break; case 17: radioButton_17.setText(steamGame.getName()); break; case 18: radioButton_18.setText(steamGame.getName()); break; case 19: radioButton_19.setText(steamGame.getName()); break; case 20: radioButton_20.setText(steamGame.getName()); break; case 21: radioButton_21.setText(steamGame.getName()); break; case 22: radioButton_22.setText(steamGame.getName()); break; case 23: radioButton_23.setText(steamGame.getName()); break; case 24: radioButton_24.setText(steamGame.getName()); break; case 25: radioButton_25.setText(steamGame.getName()); break; case 26: radioButton_26.setText(steamGame.getName()); break; } br.close(); } //先删除所有的项目,然后再添加 this.gamesComboBox.removeAllItems(); for(int i=0;i<games.size();i++){ this.gamesComboBox.addItem(games.get(i)); } this.uniGamesComboBox.removeAllItems(); for(int i=0;i<games.size();i++){ if("万能游戏".equals(games.get(i))){ this.uniGamesComboBox.addItem(games.get(i)); } } } /* * Code验证与充值初始化账户的函数 */ public void getCodeAccounts() throws IOException{ BufferedReader bf = null; try { bf = new BufferedReader(new FileReader(new File("config\\Accounts_Validate.txt"))); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } String temp; String defaultId = null; String defaultPassword = <PASSWORD>; while((temp=bf.readLine())!=null){ defaultId = temp.split("-")[0]; System.out.println(defaultId); defaultPassword = <PASSWORD>.split("-")[1]; System.out.println(defaultPassword); accounts.put(defaultId,defaultPassword); accountIDs.add(defaultId); } } /* * 日志页面初始化函数 */ public void getAllLog() throws IOException{ BufferedReader br = new BufferedReader(new FileReader(new File("steam.log"))); String temp; while((temp=br.readLine())!=null){ steamLogTextArea.setText(steamLogTextArea.getText()+temp+"\n"); } } /* * 读取BuySteamGameXpath的初始化函数 */ public void getBuySteamGameXpath() throws IOException{ // this.buySteamGameXpath = new HashMap<String,String>(); this.WalletXpath = new HashMap<String,String>(); // BufferedReader br = new BufferedReader(new FileReader(new File("config/BuySteamGameXpath.txt"))); String temp; // while((temp=br.readLine())!=null){ // String xpathName = temp.split("-")[0]; // String xpath = temp.split("-")[1]; // this.buySteamGameXpath.put(xpathName, xpath); // } BufferedReader br2 = new BufferedReader(new FileReader(new File("config/WalletXpath.txt"))); while((temp=br2.readLine())!=null){ String xpathName = temp.split("-")[0]; String xpath = temp.split("-")[1]; this.WalletXpath.put(xpathName, xpath); } } //时间初始化 public void setStartEndTime(){ Date startDate = new Date(System.currentTimeMillis()-86400000); Date endDate = new Date(); DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String startTime = format.format(startDate); String endTime = format.format(endDate); this.startTimeField.setText(startTime); this.endTimeField.setText(endTime); } //设置表格的函数 public void setAdder(final ArrayList arr,final int row){ setTableModel(arr,row); String buyer_nick = (String) arr.get(4); String title = (String)arr.get(3); String receiver_address = (String)arr.get(6); // String num = (String)arr.get(4); // auto_buyer_id_text.setText(diamond.getName()); // auto_buyer_pw_text.setText(diamond.getPw()); // auto_dia_type_text.setText(title); // auto_dia_num_text.setText(diamond.getAmount()); System.out.println("this is adder~~~~~~"); } public void setTableModel(ArrayList arr,int row){ String status = ""; switch((String)arr.get(5)){ case "BUYER_PAY": status = "等待买家付款"; break; case "WAIT_SELLER_SEND_GOODS": status = "等待卖家发货"; break; case "WAIT_BUYER_CONFIRM_GOODS": status = "等待买家确认收货"; break; case "TRADE_FINISHED": status = "交易成功"; break; } String tidTime = (String) arr.get(0); String nid = (String) arr.get(1); String gameName = (String) arr.get(2); String buyerWW = (String) arr.get(3); String payment = (String) arr.get(4); String tradeStatus = status; String message = (String) arr.get(6); String buyNum = (String) arr.get(7); String sellerMomo = (String) arr.get(8); String rowValue[] = {tidTime,nid,gameName,buyerWW,payment,tradeStatus,message,buyNum,sellerMomo}; System.out.println("!!!!!!!!用户留言!!!!!!!!!!"+message); tableModel.addRow(rowValue); System.out.println(tableModel.getValueAt(row, 0)); } public void setJsonGames() throws IOException, JSONException { steamGames = new HashMap<String, SteamGame>(); games = new ArrayList<String>(); StringBuffer stringBuffer = new StringBuffer(); String line = null ; BufferedReader br = new BufferedReader(new FileReader(new File("config\\gameConfig.txt"))); while( (line = br.readLine())!= null ){ stringBuffer.append(line); } //将Json文件数据形成JSONObject对象 JSONObject jsonObject = new JSONObject(stringBuffer.toString()); //获取JSONObject对象数据并打印 JSONArray gameArr= jsonObject.getJSONArray("games"); for (int i = 0; i < gameArr.length(); i++) { SteamGame steamGame = new SteamGame(); JSONObject game=gameArr.getJSONObject(i); steamGame.setLink(game.getString("address")); steamGame.setXpath(game.getString("xpath")); steamGame.setName(game.getString("name")); steamGames.put(steamGame.getName(), steamGame); games.add(steamGame.getName()); } //初始化游戏下拉框 gamesComboBox.removeActionListener(gamesComboBox.boxListener); gamesComboBox.removeAllItems(); // gamesComboBox.addItem(new CheckValue(true, "Select All")); CheckValue cValue; for(int i=0;i<games.size();i++){ // this.gamesComboBox.addItem(games.get(i)); cValue = new CheckValue(); cValue.value = games.get(i).toString(); gamesComboBox.addItem(cValue); } gamesComboBox.addActionListener(gamesComboBox.boxListener); } } <file_sep>/src/frame/AlertUI.java package frame; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JTextField; import javax.swing.JButton; import java.awt.Font; import java.awt.Color; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class AlertUI extends JFrame { private JPanel contentPane; private JTextField textField; private AlertUI alertUI; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { AlertUI frame = new AlertUI(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public AlertUI() { this.alertUI = this; setResizable(false); setVisible(true); setLocation(400,400); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 441, 212); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JPanel panel = new JPanel(); panel.setBounds(10, 10, 417, 170); contentPane.add(panel); panel.setLayout(null); textField = new JTextField(); textField.setForeground(Color.RED); textField.setFont(new Font("微软雅黑", Font.PLAIN, 18)); textField.setEditable(false); textField.setBounds(10, 10, 390, 46); panel.add(textField); textField.setColumns(10); textField.setText("!!!请选择有效的游戏、账户和邮箱!!!"); JButton btnNewButton = new JButton("关闭"); btnNewButton.addMouseListener(new MouseAdapter(){ @Override public void mouseClicked(MouseEvent arg0) { alertUI.dispose(); } }); btnNewButton.setFont(new Font("微软雅黑", Font.PLAIN, 16)); btnNewButton.setBounds(129, 89, 152, 46); panel.add(btnNewButton); } } <file_sep>/src/frame/BatchBuyListener.java package frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import script.ToDBC; import selenium.GameObj; import bean.SteamGame; public class BatchBuyListener implements ActionListener { private static final int DISPOSE_ON_CLOSE = 0; public BatchBuyUI batchFrame; public AutoSellerUI frame; GameObj gameObj; public BatchBuyListener(BatchBuyUI batchFrame, AutoSellerUI frame){ this.batchFrame = batchFrame; this.frame = frame; } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getActionCommand()=="确认并加入仓库"){ this.batchFrame.closeDriverTag = false; new Thread(new Runnable(){ @Override public void run(){ // String defaultAccountID = frame.accountsComboBox.getSelectedItem().toString(); // String defaultAccountPW = frame.buyGameAccounts.get(defaultAccountID); // String defaultEmail = frame.default_email_text_sure.getText(); // String steamGameName = frame.gamesComboBox.getSelectedItem().toString(); // SteamGame steamGame = frame.steamGames.get(steamGameName); // // GameObj gameObj = new GameObj(batchFrame); // gameObj.setDefault_account(defaultAccountID); // gameObj.setDefaule_password(<PASSWORD>); // gameObj.setDefault_email(ToDBC.ToDBC(defaultEmail)); // gameObj.setGame_name(steamGameName); // gameObj.setBatchFrame(batchFrame); // gameObj.setSteamGame(steamGame); // gameObj.setBuyGameAccountID(batchFrame.frame.buyGameAccountID); // gameObj.setBuyGameAccounts(batchFrame.frame.buyGameAccounts); // gameObj.setGameNum(Integer.parseInt(batchFrame.buyNumText.getText())); // gameObj.setFrame(frame); // gameObj.setBuySteamGameXpath(frame.buySteamGameXpath); // gameObj.batchBuyToWare(); //获取有多少个用户 int accountNum=frame.accountsComboBox.getItemCount(); //获取当前用户在第几个 int currentAcciunt=frame.accountsComboBox.getSelectedIndex(); //余额是否足够,true余额足够 boolean balanceHasEnough=false; //游戏名 String steamGameName = ((CheckValue)frame.gamesComboBox.getSelectedItem()).value; GameObj gameObj=null; //如果余额不够跳到下一个账户 while (!balanceHasEnough&&currentAcciunt<accountNum) { //将当前账户设为选中 frame.accountsComboBox.setSelectedIndex(currentAcciunt); batchFrame.setText(); String defaultAccountID = frame.accountsComboBox.getSelectedItem().toString(); String defaultAccountPW = frame.buyGameAccounts.get(defaultAccountID); String defaultEmail = frame.default_email_text_sure.getText(); gameObj = new GameObj(batchFrame); //查询该账户需要购买多少个游戏 CheckValue value; for (int i = 0; i < frame.gamesComboBox.getItemCount(); i++) { value=(CheckValue) frame.gamesComboBox.getItemAt(i); if (value.bolValue) { gameObj.buySteamGame.put(value.value,frame.steamGames.get(value.value)); } } gameObj.setDefault_account(defaultAccountID); gameObj.setDefaule_password(<PASSWORD>); gameObj.setDefault_email(ToDBC.ToDBC(defaultEmail)); gameObj.setBatchFrame(batchFrame); gameObj.setBuyGameAccountID(batchFrame.frame.buyGameAccountID); gameObj.setBuyGameAccounts(batchFrame.frame.buyGameAccounts); gameObj.setGameNum(Integer.parseInt(batchFrame.buyNumText.getText())); gameObj.setFrame(frame); gameObj.setBuySteamGameXpath(frame.buySteamGameXpath); balanceHasEnough=gameObj.batchBuyToWare(); currentAcciunt++; } //购买结束,退出 batchFrame.info_buy_process_Text.setText("购买结束!退出!"); gameObj.exitBrowAfterRunning(); } }).start(); } if(e.getActionCommand() == "确认并购买"){ this.batchFrame.closeDriverTag = false; new Thread(new Runnable(){ @Override public void run(){ // String defaultAccountID = frame.accountsComboBox.getSelectedItem().toString(); // String defaultAccountPW = frame.buyGameAccounts.get(defaultAccountID); // String defaultEmail = frame.default_email_text_sure.getText(); // String steamGameName = ((CheckValue)frame.gamesComboBox.getSelectedItem()).value; // SteamGame steamGame = frame.steamGames.get(steamGameName); // // GameObj gameObj = new GameObj(batchFrame); // gameObj.setDefault_account(defaultAccountID); // gameObj.setDefaule_password(<PASSWORD>); // gameObj.setDefault_email(ToDBC.ToDBC(defaultEmail)); // gameObj.setGame_name(steamGameName); // gameObj.setBatchFrame(batchFrame); // gameObj.setSteamGame(steamGame); // gameObj.setBuyGameAccountID(batchFrame.frame.buyGameAccountID); // gameObj.setBuyGameAccounts(batchFrame.frame.buyGameAccounts); // gameObj.setGameNum(Integer.parseInt(batchFrame.buyNumText.getText())); // gameObj.setFrame(frame); // gameObj.setBuySteamGameXpath(frame.buySteamGameXpath); // gameObj.batchBuy(); //获取有多少个用户 int accountNum=frame.accountsComboBox.getItemCount(); //获取当前用户在第几个 int currentAcciunt=frame.accountsComboBox.getSelectedIndex(); //余额是否足够,true余额足够 boolean balanceHasEnough=false; //游戏名 String steamGameName = ((CheckValue)frame.gamesComboBox.getSelectedItem()).value; GameObj gameObj=null; //如果余额不够跳到下一个账户 while (!balanceHasEnough&&currentAcciunt<accountNum) { //将当前账户设为选中 frame.accountsComboBox.setSelectedIndex(currentAcciunt); batchFrame.setText(); String defaultAccountID = frame.accountsComboBox.getSelectedItem().toString(); String defaultAccountPW = frame.buyGameAccounts.get(defaultAccountID); String defaultEmail = frame.default_email_text_sure.getText(); gameObj = new GameObj(batchFrame); //查询该账户需要购买多少个游戏 CheckValue value; for (int i = 0; i < frame.gamesComboBox.getItemCount(); i++) { value=(CheckValue) frame.gamesComboBox.getItemAt(i); if (value.bolValue) { gameObj.buySteamGame.put(value.value,frame.steamGames.get(value.value)); System.out.println(value.bolValue); System.out.println(value.value); } } gameObj.setDefault_account(defaultAccountID); gameObj.setDefaule_password(<PASSWORD>); gameObj.setDefault_email(ToDBC.ToDBC(defaultEmail)); gameObj.setBatchFrame(batchFrame); gameObj.setBuyGameAccountID(batchFrame.frame.buyGameAccountID); gameObj.setBuyGameAccounts(batchFrame.frame.buyGameAccounts); gameObj.setGameNum(Integer.parseInt(batchFrame.buyNumText.getText())); gameObj.setFrame(frame); gameObj.setBuySteamGameXpath(frame.buySteamGameXpath); balanceHasEnough=gameObj.buyRun(); currentAcciunt++; } //购买结束,退出 batchFrame.info_buy_process_Text.setText("购买结束!退出!"); gameObj.exitBrowAfterRunning(); } }).start(); } if(e.getActionCommand() == "为自己购买"){ this.batchFrame.closeDriverTag = false; new Thread(new Runnable(){ @Override public void run(){ // String defaultAccountID = frame.accountsComboBox.getSelectedItem().toString(); // String defaultAccountPW = frame.buyGameAccounts.get(defaultAccountID); // String defaultEmail = frame.default_email_text_sure.getText(); // String steamGameName = ((CheckValue)frame.gamesComboBox.getSelectedItem()).value; // SteamGame steamGame = frame.steamGames.get(steamGameName); // // GameObj gameObj = new GameObj(batchFrame); // gameObj.setDefault_account(defaultAccountID); // gameObj.setDefaule_password(<PASSWORD>); // gameObj.setDefault_email(ToDBC.ToDBC(defaultEmail)); // gameObj.setGame_name(steamGameName); // gameObj.setBatchFrame(batchFrame); // gameObj.setSteamGame(steamGame); // gameObj.setBuyGameAccountID(batchFrame.frame.buyGameAccountID); // gameObj.setBuyGameAccounts(batchFrame.frame.buyGameAccounts); // gameObj.setGameNum(Integer.parseInt(batchFrame.buyNumText.getText())); // gameObj.setFrame(frame); // gameObj.setBuySteamGameXpath(frame.buySteamGameXpath); // gameObj.batchBuyMyself(); //获取有多少个用户 int accountNum=frame.accountsComboBox.getItemCount(); //获取当前用户在第几个 int currentAcciunt=frame.accountsComboBox.getSelectedIndex(); //余额是否足够,true余额足够 boolean balanceHasEnough=false; //游戏名 String steamGameName = ((CheckValue)frame.gamesComboBox.getSelectedItem()).value; GameObj gameObj=null; //如果余额不够跳到下一个账户 while (!balanceHasEnough&&currentAcciunt<accountNum) { //将当前账户设为选中 frame.accountsComboBox.setSelectedIndex(currentAcciunt); batchFrame.setText(); String defaultAccountID = frame.accountsComboBox.getSelectedItem().toString(); String defaultAccountPW = frame.buyGameAccounts.get(defaultAccountID); String defaultEmail = frame.default_email_text_sure.getText(); gameObj = new GameObj(batchFrame); //查询该账户需要购买多少个游戏 CheckValue value; for (int i = 0; i < frame.gamesComboBox.getItemCount(); i++) { value=(CheckValue) frame.gamesComboBox.getItemAt(i); if (value.bolValue) { gameObj.buySteamGame.put(value.value,frame.steamGames.get(value.value)); System.out.println(value.bolValue); System.out.println(value.value); } } gameObj.setDefault_account(defaultAccountID); gameObj.setDefaule_password(<PASSWORD>); gameObj.setDefault_email(ToDBC.ToDBC(defaultEmail)); gameObj.setBatchFrame(batchFrame); gameObj.setBuyGameAccountID(batchFrame.frame.buyGameAccountID); gameObj.setBuyGameAccounts(batchFrame.frame.buyGameAccounts); gameObj.setGameNum(Integer.parseInt(batchFrame.buyNumText.getText())); gameObj.setFrame(frame); gameObj.setBuySteamGameXpath(frame.buySteamGameXpath); balanceHasEnough=gameObj.batchBuyMyself(); currentAcciunt++; } //购买结束,退出 batchFrame.info_buy_process_Text.setText("购买结束!退出!"); gameObj.exitBrowAfterRunning(); } }).start(); } if(e.getActionCommand() == "跳区购买"){ this.batchFrame.closeDriverTag = false; new Thread(new Runnable(){ @Override public void run(){ String defaultAccountID = frame.accountsComboBox.getSelectedItem().toString(); String defaultAccountPW = frame.buyGameAccounts.get(defaultAccountID); String defaultEmail = frame.default_email_text_sure.getText(); String steamGameName = frame.gamesComboBox.getSelectedItem().toString(); String uniSteamGameName = frame.uniGamesComboBox.getSelectedItem().toString(); SteamGame steamGame = frame.steamGames.get(steamGameName); SteamGame uniSteamGame = frame.steamGames.get(uniSteamGameName); GameObj gameObj = new GameObj(batchFrame); gameObj.setDefault_account(defaultAccountID); gameObj.setDefaule_password(<PASSWORD>); gameObj.setDefault_email(ToDBC.ToDBC(defaultEmail)); gameObj.setGame_name(steamGameName); gameObj.setBatchFrame(batchFrame); gameObj.setSteamGame(steamGame); gameObj.setUniSteamGame(uniSteamGame); gameObj.setBuyGameAccountID(batchFrame.frame.buyGameAccountID); gameObj.setBuyGameAccounts(batchFrame.frame.buyGameAccounts); gameObj.setGameNum(Integer.parseInt(batchFrame.buyNumText.getText())); gameObj.setFrame(frame); gameObj.setBuySteamGameXpath(frame.buySteamGameXpath); gameObj.jumpAreaBuy(); } }).start(); } if(e.getActionCommand() == "取消"){ System.out.println(batchFrame.closeDriverTag); if(!batchFrame.closeDriverTag){ batchFrame.closeDriverTag = true; batchFrame.info_buy_process_Text.setText("!!!!正在关闭浏览器,请稍等!!!!"); }else{ this.batchFrame.dispose(); this.frame.setEnabled(true); } // this.BpFrame.dispose(); } } } <file_sep>/src/frame/ShowXpathUI.java package frame; import java.awt.Font; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import java.awt.Color; public class ShowXpathUI extends JFrame { public JPanel contentPane; public JTextField xpathTextField; public AutoSellerUI frame; public Map<String, String> buySteamGameXpath; public Map<String, String> WalletXpath; public JComboBox xpathComboBox; public JLabel infoLabel; //标记要查看的是SteamGame的还是Wallet的Xpath public String tag; public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } /** * Launch the application. */ public static void main(String[] args) { } /** * Create the frame. */ public ShowXpathUI(AutoSellerUI frame, String tag) { this.tag = tag; this.frame = frame; // this.buySteamGameXpath = frame.buySteamGameXpath; // this.WalletXpath = frame.WalletXpath; setVisible(true); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setBounds(100, 100, 634, 174); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); xpathComboBox = new JComboBox(); xpathComboBox.setForeground(Color.RED); xpathComboBox.setFont(new Font("微软雅黑", Font.PLAIN, 14)); xpathComboBox.setBounds(139, 21, 299, 36); contentPane.add(xpathComboBox); xpathComboBox.addItemListener(new ShowXpathListener(this)); JButton deleteXpathButton = new JButton("删除xpath"); deleteXpathButton.setFont(new Font("微软雅黑", Font.PLAIN, 14)); deleteXpathButton.setBounds(448, 21, 150, 36); contentPane.add(deleteXpathButton); infoLabel = new JLabel("New label"); infoLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14)); infoLabel.setBounds(0, 21, 143, 36); contentPane.add(infoLabel); xpathTextField = new JTextField(); xpathTextField.setForeground(Color.RED); xpathTextField.setFont(new Font("微软雅黑", Font.PLAIN, 14)); xpathTextField.setBounds(139, 67, 459, 36); contentPane.add(xpathTextField); xpathTextField.setColumns(10); if("SteamGame".equals(this.tag)){ showBuySteamGameXpath(); }else if("Wallet".equals(this.tag)){ showWalletXpath(); } } /* * 初始化BuySteamGameXpath的下拉菜单 */ public void showBuySteamGameXpath(){ this.infoLabel.setText("SteamGameXpath:"); Iterator it = this.buySteamGameXpath.entrySet().iterator(); while(it.hasNext()){ Entry entry = (Entry)it.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); this.xpathComboBox.addItem(key); } } /* * 初始化WalletXpath的下拉菜单 */ public void showWalletXpath(){ this.infoLabel.setText("WalletXpath:"); Iterator it = this.WalletXpath.entrySet().iterator(); while(it.hasNext()){ Entry entry = (Entry)it.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); this.xpathComboBox.addItem(key); } } } <file_sep>/src/test/showFiles.java package test; import java.io.File; public class showFiles { public static void main(String[] args) { // TODO Auto-generated method stub File f = new File("games"); File[] fileLists = f.listFiles(); for(int i=0;i<fileLists.length;i++){ System.out.println(fileLists[i].getName()); } File file = new File("games\\中文.txt"); // BufferedWriter bw = new BufferedWriter(new FileWriter(new File("PC正版Dark Souls II Season Pass黑暗之魂2中文版季票DLC.txt"))) // file.delete(); // System.out.println(file.renameTo(new File("test.txt"))); } } <file_sep>/src/taobao/Tid.java package taobao; public class Tid { private long tid; private static Tid Tid = new Tid(); public static Tid getInstance(){ if(Tid==null){ Tid = new Tid(); } return Tid; } public long getTid() { return tid; } public void setTid(long tid) { this.tid = tid; } } <file_sep>/src/script/ToDBC.java /* * 全角转半角的函数测试 */ package script; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ToDBC { public static String ToDBC(String input) { char c[] = input.toCharArray(); for (int i = 0; i < c.length; i++) { if (c[i] == '\u3000') { c[i] = ' '; } else if (c[i] > '\uFF00' && c[i] < '\uFF5F') { c[i] = (char) (c[i] - 65248); } } String returnString = new String(c); return returnString.replaceAll(" ", ""); } /* * 提取邮箱的函数 */ public static String ExEmail(String str){ String email = ""; int atCount = 0; //记录@符号的变量,大于一则说明邮箱多余一个 int atLoc = 0; //记录@符号的位置 int beg = str.length()-1; //记录邮箱字符串的开始位置 int end = 0; //记录邮箱字符串的结束位置 for(int i=0;i<str.length();i++){ String atChar = str.substring(i, i+1); if("@".equals(atChar)){ atCount++; atLoc = i; } } if(atCount!=1){ return "error"; } //判断@符号之前的字符串是否由字母、数字和下滑线组成,注意首字符的判断 String pat = "\\w"; Pattern p = Pattern.compile(pat); Matcher m; for(int i=atLoc-1;i>=0;i--){ String atPre = str.substring(i, i+1); m = p.matcher(atPre); if(!m.matches()&&!".".equals(atPre)&&!"-".equals(atPre)){ beg = i+1; break; }else if(i==0&&m.matches()){ beg = 0; } } //判断@符号之后的字符串是否是由数字、字母和"."组成 pat = "[a-zA-Z0-9]"; p = Pattern.compile(pat); for(int i=atLoc+2;i<=str.length();i++){ String atSuf = str.substring(i-1,i); m = p.matcher(atSuf); if(!m.matches()&&!".".equals(atSuf)){ end = i-1; break; }else if(i==str.length()){ end = i; } } // for(int i=atLoc+2;i<=str.length();i++){ // String atSuf = str.substring(atLoc+1, i); // if(atSuf.contains(".com")||atSuf.contains(".cn")||atSuf.contains(".pro")){ // end = i; // break; // } // } if(end==0||beg==str.length()-1){ return "error"; } //判断@之后如果没有"."的话则错误 if(!str.substring(atLoc, end).contains(".")){ return "error"; } return str.substring(beg,end); } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new FileReader(new File("C:\\Users\\Black\\Desktop\\taobao\\另外一个自动购买流程\\买家留言邮箱.txt"))); String temp; while((temp=br.readLine())!=null){ String new_temp = ToDBC(temp); System.out.println(new_temp); System.out.println(ExEmail(new_temp)+"\n"); } // String email = ExEmail("邮箱:<EMAIL>,谢谢!"); // System.out.println(email); } } <file_sep>/src/test/StringTest.java package test; public class StringTest { public static void main(String[] args) { // TODO Auto-generated method stub String str = "2955,74 p§å§Ò."; System.out.println(str); System.out.println(str.replaceAll(" ", "")); System.out.println(str.replaceAll(" ", "").replaceAll(",", "")); System.out.println(str.replaceAll(" ", "").replaceAll(",", "").replaceAll("p§å§Ò.", "")); } }
cc8a5d247733f4964b4af4581e481e9635a35aae
[ "Java" ]
17
Java
wjhzkf/steamsamll
774303baf1afd9c5a23214fbc0ea53142beb6613
29f8e9659e2f0c09216048b8016bad4df80546bb
refs/heads/master
<repo_name>kinwei/DataStructure<file_sep>/LinkTree/LinkTree/Tree.hpp // // Tree.hpp // LinkTree // // Created by kinwei on 16/9/29. // Copyright © 2016年 kinwei. All rights reserved. // #ifndef Tree_hpp #define Tree_hpp #include <stdio.h> #include "Node.hpp" class Tree{ public: Tree(); ~Tree(); Node *SearchNode(int nodeIndex); bool AddNode(int nodeIndex,int direction,Node *pNode); bool DeteleNode(int nodeIndex,Node *pNode); void PreorderTraversal(); void InorderTraversal(); void PostorderTraversal(); private: Node *m_pRoot; }; #endif /* Tree_hpp */ <file_sep>/LinkTree/LinkTree/Node.hpp // // Node.hpp // LinkTree // // Created by kinwei on 16/9/29. // Copyright © 2016年 kinwei. All rights reserved. // #ifndef Node_hpp #define Node_hpp #include <stdio.h> class Node{ public: Node(); int index; int data; Node *pLChild; Node *pRChild; Node *pParent; Node *SearchNode(int nodeIndex); void DeteleNode(); void PreorderTraversal(); void InorderTraversal(); void PostorderTraversal(); }; #endif /* Node_hpp */ <file_sep>/LinkList/LinkList/Node.cpp // // Node.cpp // LinkList // // Created by kinwei on 16/9/21. // Copyright © 2016年 kinwei. All rights reserved. // #include <stdio.h> #include "Node.h" #include <iostream> using namespace std; void Node::printNode(){ cout << data <<endl; }<file_sep>/Map/Map/Node.cpp // // Node.cpp // Map // // Created by kinwei on 16/10/5. // Copyright © 2016年 kinwei. All rights reserved. // #include "Node.hpp" Node::Node(char data){ m_cData = data; m_bIsVisited = false; } <file_sep>/Map/Map/Map.hpp // // Map.hpp // Map // // Created by kinwei on 16/10/5. // Copyright © 2016年 kinwei. All rights reserved. // #ifndef Map_hpp #define Map_hpp #include <stdio.h> #include "Node.hpp" #include <iostream> #include <vector> using namespace std; class Map{ public: Map(int capacity); ~Map(); bool addNode(Node *pNode); void resetNode(); bool setValueToMatrixForDirectedGraph(int row,int col, int val=1);//为有向图设置邻接矩阵 bool setValueToMatrixForUndirectedGraph(int row,int col, int val=1);//为无向图设置邻接矩阵 void printMatrix(); void depthFirstTraverse(int nodeIndex); void breadthFirstTraverse(int nodeIndex); private: bool getValueFromMatrix(int row,int col,int &val); void breadthFirstTraverseImpl(vector<int> preVc); private: int m_iCapacity;//图中最多可以容纳的节点数 int m_iNodeCount;//已经添加的节点的个数 Node *m_pNodeArray;//用来存放顶点的数组 int *m_pMatrix;//用来存放邻接矩阵 }; #endif /* Map_hpp */ <file_sep>/stack/stack/MyStack.hpp // // MyStack.hpp // stack // // Created by kinwei on 16/9/23. // Copyright © 2016年 kinwei. All rights reserved. // #ifndef MyStack_hpp #define MyStack_hpp #include <stdio.h> class MyStack{ public: MyStack(int size); ~MyStack(); bool stackEmpty(); bool stackFull(); void clearStack(); int stackLength(); bool push(char elem); bool pop(char &elem); void stackTraverse(bool isFromBottom); private: char *m_pBuffer; int m_iSize; int m_iTop; }; #endif /* MyStack_hpp */ <file_sep>/LinkList/LinkList/main.cpp // // main.cpp // LinkList // // Created by kinwei on 16/9/21. // Copyright © 2016年 kinwei. All rights reserved. // #include <iostream> #include "LinkList.h" using namespace std; int main(int argc, const char * argv[]) { Node node1; node1.data = 3; Node node2; node2.data = 4; Node node3; node3.data = 5; Node node4; node4.data = 6; Node node5; node5.data = 7; LinkList *pList = new LinkList(); pList -> ListInsertHead(&node1); pList -> ListInsertHead(&node2); pList -> ListInsertHead(&node3); pList -> ListInsertHead(&node4); pList -> ListInsertHead(&node5); pList -> ListTraverse(); delete pList; return 0; } <file_sep>/LinkList/LinkList/LinkList.h // // LinkList.hpp // LinkList // // Created by kinwei on 16/9/21. // Copyright © 2016年 kinwei. All rights reserved. // #ifndef LinkList_hpp #define LinkList_hpp #include <stdio.h> #include "Node.h" class LinkList{ public: LinkList(); void ClearList(); bool ListEmpty(); int ListLength(); bool GetElem(int i, Node *pNode); int LocateElem(Node *pNode); bool PriorElem(Node *currentElem, Node *preElem); bool NextElem(Node *currentElem, Node *nextElem); void ListTraverse(); bool ListInsertHead(Node *pNode); bool ListInsertTail(Node *pNode); bool ListInsert(int i, Node *pNode); bool ListDelete(int i, Node *pNode); ~LinkList(); private: Node *m_pList; int m_iLength; }; #endif /* LinkList_hpp */ <file_sep>/LinkList/LinkList/Node.h // // Node.h // LinkList // // Created by kinwei on 16/9/21. // Copyright © 2016年 kinwei. All rights reserved. // #ifndef Node_h #define Node_h class Node{ public: int data; Node *next; void printNode(); }; #endif /* Node_h */ <file_sep>/ArrayTree/ArrayTree/main.cpp // // main.cpp // ArrayTree // // Created by kinwei on 16/9/29. // Copyright © 2016年 kinwei. All rights reserved. // #include <iostream> #include "Tree.hpp" using namespace std; int main(int argc, const char * argv[]) { int root = 3; Tree *pTree = new Tree(10,&root); int node1 = 5; int node2 = 8; pTree->AddNode(0,0, &node1); pTree->AddNode(0,1, &node2); int node3 = 2; int node4 = 6; pTree->AddNode(1,0, &node3); pTree->AddNode(1,1, &node4); int node5 = 9; int node6 = 7; pTree->AddNode(2,0, &node5); pTree->AddNode(2,1, &node6); pTree -> TreeTraverse(); int *p = pTree -> SearchNode(2); cout << "*p:"<<*p<<endl; delete pTree; } <file_sep>/stack/stack/MyStack.cpp // // MyStack.cpp // stack // // Created by kinwei on 16/9/23. // Copyright © 2016年 kinwei. All rights reserved. // #include "MyStack.hpp" #include <iostream> using namespace std; MyStack::MyStack(int size){ m_iSize = size; m_pBuffer = new char(m_iSize); m_iTop = 0; } MyStack::~MyStack(){ delete []m_pBuffer; } bool MyStack::stackEmpty(){ if (m_iTop == 0) { return true; } return false; } bool MyStack::stackFull(){ if (m_iTop >= m_iSize) { return true; } return false; } void MyStack::clearStack(){ m_iTop = 0; } int MyStack::stackLength(){ return m_iTop; } bool MyStack::push(char elem){ if (!stackFull()) { m_pBuffer[m_iTop] = elem; m_iTop++; return true; } return false; } bool MyStack::pop(char &elem){ if (stackEmpty()) { return false; } m_iTop--; elem = m_pBuffer[m_iTop]; return true; } void MyStack::stackTraverse(bool isFromBottom){ if(isFromBottom){ for (int i=0; i < stackLength(); i++) { cout <<m_pBuffer[i]<<endl; } }else{ for (int i=stackLength(); i >= 0; i--) { cout <<m_pBuffer[i]<<endl; } } } <file_sep>/LinkTree/LinkTree/Tree.cpp // // Tree.cpp // LinkTree // // Created by kinwei on 16/9/29. // Copyright © 2016年 kinwei. All rights reserved. // #include "Tree.hpp" Tree::Tree(){ m_pRoot = new Node(); } Node *Tree::SearchNode(int nodeIndex){ return m_pRoot -> SearchNode(nodeIndex); } bool Tree::AddNode(int nodeIndex, int direction, Node *pNode){ Node *temp = SearchNode(nodeIndex); if (temp == NULL) { return false; } Node *node = new Node(); if (node == NULL) { return false; } node->data = pNode -> data; node -> index = pNode -> index; node->pParent = temp; if (direction == 0) { temp -> pLChild = node; } if (direction == 1) { temp -> pRChild = node; } return true; } bool Tree::DeteleNode(int nodeIndex,Node *pNode){ Node *temp = SearchNode(nodeIndex); if (temp == NULL) { return false; } if (pNode != NULL) { pNode->data = temp->data; } temp -> DeteleNode(); return true; } Tree::~Tree(){ m_pRoot->DeteleNode(); } void Tree::PreorderTraversal(){ m_pRoot -> PreorderTraversal(); } void Tree::InorderTraversal(){ m_pRoot->InorderTraversal(); } void Tree::PostorderTraversal(){ m_pRoot->PostorderTraversal(); } <file_sep>/Map/Map/main.cpp // // main.cpp // Map // // Created by kinwei on 16/10/5. // Copyright © 2016年 kinwei. All rights reserved. // #include <iostream> #include "Map.hpp" int main(int argc, const char * argv[]) { // insert code here... Map *map = new Map(8); Node *pNodeA = new Node('A'); Node *pNodeB = new Node('B'); Node *pNodeC = new Node('C'); Node *pNodeD = new Node('D'); Node *pNodeE = new Node('E'); Node *pNodeF = new Node('F'); Node *pNodeG = new Node('G'); Node *pNodeH = new Node('H'); map -> addNode(pNodeA); map -> addNode(pNodeB); map -> addNode(pNodeC); map -> addNode(pNodeD); map -> addNode(pNodeE); map -> addNode(pNodeF); map -> addNode(pNodeG); map -> addNode(pNodeH); map -> setValueToMatrixForUndirectedGraph(0, 1); map -> setValueToMatrixForUndirectedGraph(0, 3); map -> setValueToMatrixForUndirectedGraph(1, 2); map -> setValueToMatrixForUndirectedGraph(1, 5); map -> setValueToMatrixForUndirectedGraph(3, 6); map -> setValueToMatrixForUndirectedGraph(3, 7); map -> setValueToMatrixForUndirectedGraph(6, 7); map -> setValueToMatrixForUndirectedGraph(2, 4); map -> setValueToMatrixForUndirectedGraph(4, 5); map -> printMatrix(); return 0; } <file_sep>/Map/Map/Map.cpp // // Map.cpp // Map // // Created by kinwei on 16/10/5. // Copyright © 2016年 kinwei. All rights reserved. // #include "Map.hpp" Map::Map(int capacity){ m_iCapacity = capacity; m_iNodeCount = 0; m_pNodeArray = new Node(m_iCapacity); m_pMatrix = new int[m_iCapacity*m_iCapacity]; for (int i=0; i<m_iCapacity*m_iCapacity; i++) { m_pMatrix[i] = 0; } } Map::~Map(){ delete []m_pNodeArray; delete []m_pMatrix; } bool Map::addNode(Node *pNode){ if (pNode == NULL) { return false; } m_pNodeArray[m_iNodeCount].m_cData = pNode -> m_cData; m_iNodeCount++; return true; } void Map::resetNode(){ for (int i=0; i<m_iNodeCount; i++) { m_pNodeArray[i].m_bIsVisited = false; } } bool Map::setValueToMatrixForDirectedGraph(int row, int col,int val){ if (row <0|| row >= m_iCapacity) { return false; } if (col <0|| col >= m_iCapacity) { return false; } m_pMatrix[row*m_iCapacity + col] = val; return true; } bool Map::setValueToMatrixForUndirectedGraph(int row, int col,int val){ if (row <0|| row >= m_iCapacity) { return false; } if (col <0|| col >= m_iCapacity) { return false; } m_pMatrix[row*m_iCapacity + col] = val; m_pMatrix[col*m_iCapacity + row] = val; return true; } bool Map::getValueFromMatrix(int row, int col, int &val){ if (row <0|| row >= m_iCapacity) { return false; } if (col <0|| col >= m_iCapacity) { return false; } val = m_pMatrix[row*m_iCapacity + col]; return true; } void Map::printMatrix(){ for (int i=0; i<m_iCapacity; i++) { for (int k=0; k<m_iCapacity; k++) { cout<<m_pMatrix[i * m_iCapacity + k]<<" "; } cout<<endl; } } void Map:: depthFirstTraverse(int nodeIndex){ int value = 0; cout<<m_pNodeArray[nodeIndex].m_cData<<" "; m_pNodeArray[nodeIndex].m_bIsVisited = true; for (int i=0; i<m_iCapacity; i++) { getValueFromMatrix(nodeIndex, i, value); if (value != 0) { if (m_pNodeArray[i].m_bIsVisited) { continue; }else{ depthFirstTraverse(i); } }else{ continue; } } } void Map::breadthFirstTraverse(int nodeIndex){ cout << m_pNodeArray[nodeIndex].m_cData << " "; m_pNodeArray[nodeIndex].m_bIsVisited = true; vector<int> curVer; curVer.push_back(nodeIndex); breadthFirstTraverseImpl(curVer); } void Map::breadthFirstTraverseImpl(vector<int> preVec){ int value = 0; vector<int> curVec; for (int j=0; j < preVec.size(); j++) { for (int i; i<m_iCapacity; i++) { getValueFromMatrix(preVec[j], i, value); if (value != 0) { if (m_pNodeArray[i].m_bIsVisited) { continue; }else{ cout<<m_pNodeArray[i].m_cData << " "; m_pNodeArray[i].m_bIsVisited = true; curVec.push_back(i); } } } } if (curVec.size() == 0) { return; }else{ breadthFirstTraverseImpl(curVec); } } <file_sep>/LinkTree/LinkTree/Node.cpp // // Node.cpp // LinkTree // // Created by kinwei on 16/9/29. // Copyright © 2016年 kinwei. All rights reserved. // #include <iostream> using namespace std; #include "Node.hpp" Node::Node(){ index = 0; data = 0; pLChild = NULL; pRChild = NULL; pParent = NULL; } Node *Node::SearchNode(int nodeIndex){ Node *temp = new Node(); if (this->index == nodeIndex) { return this; } if(this->pLChild != NULL){ if (this->pLChild->index == nodeIndex) { return this->pLChild; }else{ temp = this -> pLChild -> SearchNode(nodeIndex); if(temp !=NULL){ return temp; } } } if(this->pRChild != NULL){ if (this->pRChild->index == nodeIndex) { return this->pRChild; }else{ temp = this -> pRChild -> SearchNode(nodeIndex); if(temp !=NULL){ return temp; } } } return NULL; } void Node::DeteleNode(){ if (this->pLChild != NULL) { this->pLChild -> DeteleNode(); } if (this->pRChild != NULL) { this->pRChild -> DeteleNode(); } if (this->pParent != NULL) { if(this->pParent->pRChild == this){ this->pParent->pRChild = NULL; } if(this->pParent->pLChild == this){ this->pParent->pLChild = NULL; } } } void Node::PreorderTraversal(){ cout<<this->index<<" "<<this->data << endl; if (this->pLChild != NULL) { this->pLChild->PreorderTraversal(); } if (this->pRChild != NULL) { this->pRChild->PreorderTraversal(); } } void Node::InorderTraversal(){ if (this->pLChild != NULL) { this->pLChild->InorderTraversal(); } cout<<this->index<<" "<<this->data << endl; if (this->pRChild != NULL) { this->pRChild->InorderTraversal(); } } void Node::PostorderTraversal(){ if (this->pLChild != NULL) { this->pLChild->PostorderTraversal(); } if (this->pRChild != NULL) { this->pRChild->PostorderTraversal(); } cout<<this->index<<" "<<this->data << endl; } <file_sep>/ArrayTree/ArrayTree/Tree.hpp // // Tree.hpp // ArrayTree // // Created by kinwei on 16/9/29. // Copyright © 2016年 kinwei. All rights reserved. // #ifndef Tree_hpp #define Tree_hpp #include <stdio.h> class Tree{ public: Tree(int size,int *pRoot); ~Tree(); int *SearchNode(int nodeIndex); bool AddNode(int nodeIndex,int direction, int *pNode); bool DeleteNode(int nodeIndex,int *pNode); void TreeTraverse(); private: int *m_pTree; int m_Size; }; #endif /* Tree_hpp */ <file_sep>/LinkTree/LinkTree/main.cpp // // main.cpp // LinkTree // // Created by kinwei on 16/9/29. // Copyright © 2016年 kinwei. All rights reserved. // #include <iostream> using namespace std; #include "Tree.hpp" int main(int argc, const char * argv[]) { Tree *tree = new Tree(); Node *node1 = new Node(); node1 -> index = 1; node1 -> data = 5; Node *node2 = new Node(); node2 -> index = 2; node2 -> data = 8; Node *node3 = new Node(); node3 -> index = 3; node3 -> data = 2; Node *node4 = new Node(); node4 -> index = 4; node4 -> data = 6; Node *node5 = new Node(); node5 -> index = 5; node5 -> data = 9; Node *node6 = new Node(); node6 -> index = 6; node6 -> data = 7; tree->AddNode(0, 0, node1); tree -> AddNode(0, 1, node2); tree->AddNode(1, 0, node3); tree -> AddNode(1, 1, node4); tree->AddNode(2, 0, node5); tree -> AddNode(2, 1, node6); tree -> DeteleNode(6,NULL); tree -> DeteleNode(5,NULL); cout<<"前序遍历"<<endl; tree -> PreorderTraversal(); cout<<"中序遍历"<<endl; tree -> InorderTraversal(); cout<<"后序遍历"<<endl; tree -> PostorderTraversal(); delete tree; return 0; } <file_sep>/stack/stack/main.cpp // // main.cpp // stack // // Created by kinwei on 16/9/23. // Copyright © 2016年 kinwei. All rights reserved. // #include <iostream> #include "MyStack.hpp" int main(int argc, const char * argv[]) { MyStack *pStack = new MyStack(5); pStack -> push('h'); pStack -> push('e'); pStack -> push('l'); pStack -> push('l'); pStack -> push('o'); pStack -> stackTraverse(true); char elem = 0; pStack -> pop(elem); std::cout <<"pop后:" <<std::endl; pStack -> stackTraverse(false); delete pStack; return 0; } <file_sep>/LinkList/LinkList/LinkList.cpp // // LinkList.cpp // LinkList // // Created by kinwei on 16/9/21. // Copyright © 2016年 kinwei. All rights reserved. // #include "LinkList.h" #include <iostream> using namespace std; LinkList::LinkList() { m_pList = new Node; m_pList -> data = 0; m_pList -> next = NULL; m_iLength = 0; } bool LinkList::ListEmpty(){ if (m_iLength == 0) { return true; }else{ return false; } } void LinkList::ClearList(){ Node *currentNode = m_pList -> next; while (currentNode != NULL) { Node *temp = currentNode -> next; delete currentNode; currentNode = temp; } m_pList -> next = NULL; } LinkList::~LinkList(){ ClearList(); delete m_pList; m_pList = NULL; } bool LinkList::ListInsertHead(Node *pNode){ Node *temp = m_pList -> next; Node *newNode = new Node; if(newNode == NULL){ return false; } newNode->data = pNode -> data; m_pList -> next = newNode; newNode -> next = temp; m_iLength++; return true; } bool LinkList::ListInsertTail(Node *pNode){ Node *currentNode = m_pList; while (currentNode -> next != NULL) { currentNode = currentNode -> next; } Node *newNode = new Node; if (newNode == NULL) { return false; } newNode -> data = pNode -> data; newNode -> next = NULL; currentNode->next = newNode; m_iLength++; return true; } bool LinkList::ListInsert(int i, Node *pNode){ if(i < 0 || i > m_iLength){ return false; } Node *currentNode = m_pList; for (int k; k < i; k++) { currentNode = currentNode -> next; } Node *newNode = new Node; if (newNode == NULL) { return false; } newNode -> data = pNode -> data; newNode->next = currentNode -> next; currentNode -> next = newNode; return true; } bool LinkList::ListDelete(int i, Node *pNode){ if(i < 0 || i > m_iLength){ return false; } Node *currentNode = m_pList; Node *currentNodeBefore = m_pList; for (int k=0; k<=i; k++) { currentNodeBefore = currentNode; currentNode = currentNode -> next; } currentNodeBefore -> next = currentNode -> next; pNode -> data = currentNode -> data; delete currentNode; currentNode = NULL; m_iLength--; return true; } bool LinkList::GetElem(int i, Node *pNode){ if(i < 0 || i > m_iLength){ return false; } Node *currentNode = m_pList; for(int k = 0; k <= i; k++){ currentNode = currentNode -> next; } pNode -> data = currentNode -> data; return true; } int LinkList::LocateElem(Node *pNode){ Node *currentNode = m_pList; int count = 0; while (currentNode->next != NULL) { currentNode = currentNode -> next; if (currentNode->data == pNode->data) { return count; } count++; } return -1; } bool LinkList::PriorElem(Node *pCurrentNode, Node *pPreNode){ Node *currentNode = m_pList; Node *temp = NULL; while (currentNode -> next != NULL) { temp = currentNode; currentNode = currentNode -> next; if (currentNode ->data == pCurrentNode -> data) { if (temp == m_pList) { return false; } pPreNode -> data = temp -> data; return true; } } return false; } bool LinkList::NextElem(Node *pCurrentNode, Node *pNextNode){ Node *currentNode = m_pList; while (currentNode -> next != NULL) { currentNode = currentNode -> next; if (currentNode -> data == pNextNode -> data) { if (currentNode -> next == NULL) { return false; } pNextNode -> data = currentNode ->next -> data; return true; } } return false; } void LinkList::ListTraverse(){ Node *currentNode = m_pList; while (currentNode -> next != NULL) { currentNode = currentNode -> next; currentNode -> printNode(); } }
4cf03c7328d72ec25af177eb3b97eb2b5af51537
[ "C++" ]
19
C++
kinwei/DataStructure
0d6ed76118aac79bba4890205877617e164d4c7c
2adce579da68ccc40073beb7246472157eb13f92
refs/heads/master
<file_sep>#!/usr/bin/env bash set -Eeuo pipefail versions=( "$@" ) if [ "${#versions[@]}" -eq 0 ]; then versions=( */ ) fi versions=( "${versions[@]%/}" ) # see http://stackoverflow.com/a/2705678/433558 sed_escape_lhs() { echo "$@" | sed -e 's/[]\/$*.^|[]/\\&/g' } sed_escape_rhs() { echo "$@" | sed -e 's/[\/&]/\\&/g' | sed -e ':a;N;$!ba;s/\n/\\n/g' } alpine_versions=(3.10 "edge") declare -A boost_checksums boost_checksums=(["1.69.0"]="9a2c2819310839ea373f42d69e733c339b4e9a19deab6bfec448281554aa4dbb" ["1.70.0"]="882b48708d211a5f48e60b0124cf5863c1534cd544ecd0664bb534a4b5d506e9") for version in "${versions[@]}"; do echo "Generating Dockerfiles for Boost version ${version}." template=alpine boost_url_dir="boost_${version//./_}" checksum="${boost_checksums[$version]}" echo "Generating templates for ${template}" for alpine_version in "${alpine_versions[@]}"; do mkdir -p "${version}/${template}/${alpine_version}" sed -r \ -e 's!%%TAG%%!'"$alpine_version"'!g' \ -e 's!%%BOOST_VERSION%%!'"$version"'!g' \ -e 's!%%BOOST_CHECKSUM%%!'"$checksum"'!g' \ -e 's!%%BOOST_URL_DIR%%!'"$boost_url_dir"'!g' \ "Dockerfile-${template}.template" > "$version/$template/$alpine_version/Dockerfile" echo "Generated ${version}/${template}/${alpine_version}/Dockerfile" done done <file_sep>#!/usr/bin/env bash set -Eeuo pipefail versions=( "$@" ) if [ "${#versions[@]}" -eq 0 ]; then versions=( */ ) fi versions=( "${versions[@]%/}" ) # see http://stackoverflow.com/a/2705678/433558 sed_escape_lhs() { echo "$@" | sed -e 's/[]\/$*.^|[]/\\&/g' } sed_escape_rhs() { echo "$@" | sed -e 's/[\/&]/\\&/g' | sed -e ':a;N;$!ba;s/\n/\\n/g' } alpine_versions=(3.10 "edge") latest_alpine=3.10 latest_boost=1.70.0 imagebase="westonsteimel/boost" repos=("") for version in "${versions[@]}"; do echo "Building Dockerfiles for Boost version ${version}." template=alpine for alpine_version in "${alpine_versions[@]}"; do ( cd "${version}/${template}/${alpine_version}" build_tag="${imagebase}:${version}-${template}${alpine_version}" echo "Building ${build_tag}..." time docker build --build-arg "CONCURRENT_PROCESSES=4" -t "${build_tag}" . for repo in "${repos[@]}"; do repobase="${imagebase}" if [ "$repo" != "" ]; then repobase="${repo}/${imagebase}" fi docker tag "${build_tag}" "${repobase}:${version}-${template}${alpine_version}" if [ "${version}" = "${latest_boost}" ]; then docker tag "${build_tag}" "${repobase}:${template}${alpine_version}" fi if [ "${alpine_version}" = "${latest_alpine}" ]; then docker tag "${build_tag}" "${repobase}:${version}" docker tag "${build_tag}" "${repobase}:${version}-${template}" fi if [ "${version}" = "${latest_boost}" ] && [ "${alpine_version}" = "${latest_alpine}" ]; then docker tag "${build_tag}" "${repobase}:latest" docker tag "${build_tag}" "${repobase}:${template}" fi done ) done done <file_sep># Boost in Docker Dockerized environment with shared [Boost C++ Library](http://www.boost.org/) based on [Alpine Linux](https://alpinelinux.org). ## Build Info Excludes Boost.Python. ## Pull info `docker pull westonsteimel/boost` <file_sep>FROM alpine:3.10 LABEL Description="Boost C++ libraries on Alpine Linux" ARG BOOST_VERSION=1.69.0 ARG BOOST_CHECKSUM=9a2c2819310839ea373f42d69e733c339b4e9a19deab6bfec448281554aa4dbb ARG BOOST_DIR=boost ARG CONCURRENT_PROCESSES=1 ENV BOOST_VERSION ${BOOST_VERSION} RUN mkdir -p ${BOOST_DIR} \ && apk --no-cache add --virtual .build-dependencies \ build-base \ linux-headers \ curl \ tar \ && cd ${BOOST_DIR} \ && curl -L --retry 3 "https://dl.bintray.com/boostorg/release/${BOOST_VERSION}/source/boost_1_69_0.tar.gz" -o boost.tar.gz \ && echo "${BOOST_CHECKSUM} boost.tar.gz" | sha256sum -c \ && tar -xzf boost.tar.gz --strip 1 \ && ./bootstrap.sh \ && ./b2 --without-python --prefix=/usr -j ${CONCURRENT_PROCESSES} link=shared runtime-link=shared install \ && cd .. && rm -rf ${BOOST_DIR} \ && apk del .build-dependencies \ && rm -rf /var/cache/* CMD ["sh"] LABEL org.opencontainers.image.title="boost" \ org.opencontainers.image.description="Boost C++ libraries on Alpine Linux in Docker" \ org.opencontainers.image.url="https://github.com/westonsteimel/docker-boost" \ org.opencontainers.image.source="https://github.com/westonsteimel/docker-boost" \ org.opencontainers.image.version="${BOOST_VERSION}" <file_sep>.PHONY: build build: ## Builds all the dockerfiles in the repository. @$(CURDIR)/build.sh REGISTRY := westonsteimel .PHONY: image image: ## Build a Dockerfile (ex. DIR=telnet). @:$(call check_defined, DIR, directory of the Dockefile) docker build --rm --force-rm -t $(REGISTRY)/$(subst /,:,$(DIR)) ./$(DIR) .PHONY: test test: shellcheck ## Runs the tests on the repository. # if this session isn't interactive, then we don't want to allocate a # TTY, which would fail, but if it is interactive, we do want to attach # so that the user can send e.g. ^C through. INTERACTIVE := $(shell [ -t 0 ] && echo 1 || echo 0) ifeq ($(INTERACTIVE), 1) DOCKER_FLAGS += -t endif .PHONY: shellcheck shellcheck: ## Runs the shellcheck tests on the scripts. docker run --rm -i $(DOCKER_FLAGS) \ --name df-shellcheck \ -v $(CURDIR):/usr/src:ro \ --workdir "/usr/src" \ "westonsteimel/shellcheck:alpine" ./shellcheck.sh .PHONY: generate generate: @$(CURDIR)/generate.sh .PHONY: help help: @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
e348c052e067930801c3bd67e74fea2b3ddfccd0
[ "Markdown", "Makefile", "Dockerfile", "Shell" ]
5
Shell
westonsteimel/docker-boost
baa84c3c59502dda1a11f4df257c02eada5f8005
fc5c9ff97c415b668d6cae6061347786dad98be9
refs/heads/master
<repo_name>rahulguglani/Partial-dice<file_sep>/app/src/main/java/com/example/diceroller/MainActivity.kt package com.example.diceroller import android.content.Context import android.os.Build import android.os.Bundle import android.os.VibrationEffect import android.os.Vibrator import android.widget.Button import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity /** * This activity allows. the user to roll a dice and view the result * on the screen. */ @Suppress("DEPRECATION") class MainActivity : AppCompatActivity() { /** * This method is called when the Activity is created. */ val code = "AABBABA" var d1 = 1 var d2 = 2 private var poss: Int = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Find the Button in the layout val rollButton: Button = findViewById(R.id.button) val diceR : ImageView = findViewById(R.id.imageView2) val diceB : ImageView = findViewById(R.id.imageView3) diceR.setOnLongClickListener{ changeDice(1) } diceB.setOnLongClickListener { changeDice(2) } //when code is pressed dice should roll up 6 6 diceR.setOnClickListener { chkPoss(1) } diceB.setOnClickListener { chkPoss(2) } // Set a click listener on the button to roll the dice when the user taps the button rollButton.setOnClickListener { if(poss==7) { if(d1==1) diceR.setImageResource(R.drawable.dice_red_6) else diceR.setImageResource(R.drawable.dice_blue_6) if(d2==2) diceB.setImageResource(R.drawable.dice_blue_6) else diceB.setImageResource(R.drawable.dice_red_6) poss=0 // val tV : TextView = findViewById(R.id.textView) // tV.text = poss.toString() } else { rollDice() } } } fun chkPoss(d: Int) { vibratee(50) if(d==1) { when(poss) { 0->poss=1 1->poss=2 2->poss=0 3->poss=0 4->poss=5 5->poss=0 6->poss=7 } } if(d==2) { when(poss) { 0->poss=0 1->poss=0 2->poss=3 3->poss=4 4->poss=0 5->poss=6 6->poss=0 } } // val tV : TextView = findViewById(R.id.textView) // tV.text = poss.toString() } fun rollDice() { // val numSidesR: Int = findViewById(R.id.editTextNumber) // Create new Dice object with 6 sides and roll it val dice_red = Dice(6) val dice_blue = Dice(6) val diceRoll_red = dice_red.roll() val diceRoll_blue = dice_blue.roll() // Update the screen with the dice roll val diceImage_red : ImageView = findViewById(R.id.imageView2) val diceImage_blue : ImageView = findViewById(R.id.imageView3) if(d1==1){ when(diceRoll_red) { 1->diceImage_red.setImageResource(R.drawable.dice_red_1) 2->diceImage_red.setImageResource(R.drawable.dice_red_2) 3->diceImage_red.setImageResource(R.drawable.dice_red_3) 4->diceImage_red.setImageResource(R.drawable.dice_red_4) 5->diceImage_red.setImageResource(R.drawable.dice_red_5) 6->diceImage_red.setImageResource(R.drawable.dice_red_6) } } else{ when(diceRoll_red) { 1->diceImage_red.setImageResource(R.drawable.dice_blue_1) 2->diceImage_red.setImageResource(R.drawable.dice_blue_2) 3->diceImage_red.setImageResource(R.drawable.dice_blue_3) 4->diceImage_red.setImageResource(R.drawable.dice_blue_4) 5->diceImage_red.setImageResource(R.drawable.dice_blue_5) 6->diceImage_red.setImageResource(R.drawable.dice_blue_6) } } diceImage_red.contentDescription = diceRoll_red.toString() if(d2==2) { when (diceRoll_blue) { 1 -> diceImage_blue.setImageResource(R.drawable.dice_blue_1) 2 -> diceImage_blue.setImageResource(R.drawable.dice_blue_2) 3 -> diceImage_blue.setImageResource(R.drawable.dice_blue_3) 4 -> diceImage_blue.setImageResource(R.drawable.dice_blue_4) 5 -> diceImage_blue.setImageResource(R.drawable.dice_blue_5) 6 -> diceImage_blue.setImageResource(R.drawable.dice_blue_6) } } else { when (diceRoll_blue) { 1 -> diceImage_blue.setImageResource(R.drawable.dice_red_1) 2 -> diceImage_blue.setImageResource(R.drawable.dice_red_2) 3 -> diceImage_blue.setImageResource(R.drawable.dice_red_3) 4 -> diceImage_blue.setImageResource(R.drawable.dice_red_4) 5 -> diceImage_blue.setImageResource(R.drawable.dice_red_5) 6 -> diceImage_blue.setImageResource(R.drawable.dice_red_6) } } diceImage_blue.contentDescription = diceRoll_blue.toString() } private fun changeDice(d: Int): Boolean { vibratee(500) if(d==1){ if(d1==1) { d1=2 } else { d1=1 }} else { if(d2==1) { d2=2 } else { d2=1 } } return true } fun vibratee(t:Long) { val v = (getSystemService(Context.VIBRATOR_SERVICE) as Vibrator) // Vibrate for 500 milliseconds // Vibrate for 500 milliseconds if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { v.vibrate( VibrationEffect.createOneShot(t, VibrationEffect.DEFAULT_AMPLITUDE)) } else { v.vibrate(t) } } } /** * Dice with a fixed number of sides. */ class Dice(private val numSides: Int) { /** * Do a random dice roll and return the result. */ fun roll(): Int { return (1..numSides).random() } } <file_sep>/README.md # Partial-dice This is an Android application there are 2 dices and on tapping roll button dice rolls out randomly **`feature 1 `** on long pressing a dice, dice changes ![Screenshot_2021-09-07-19-38-15-661_com example diceroller](https://user-images.githubusercontent.com/60490438/132360105-a672676d-ae8a-4283-9fe0-5d0feea7b096.jpg) **`feature 2`** it has a cheat feature i.e. on pressing **`AABBABA`** where A is left dice and B is right dice both dice show 6 XD ![Screenshot_2021-09-07-19-38-25-727_com example diceroller](https://user-images.githubusercontent.com/60490438/132360144-34c8e426-c79b-4afa-a42d-6319288e38ae.jpg)
f75b6092d2694900b1a4a556c59b5d059e2b759d
[ "Markdown", "Kotlin" ]
2
Kotlin
rahulguglani/Partial-dice
8fe42c9e1090431baff3c326e23f448e84fffb73
07f96cc23376eb0eb49618409e42a2c188ec41fc
refs/heads/master
<repo_name>111milprogramadoresbaradero/DevelopmentEnvironment<file_sep>/eclipse-workspace/.metadata/version.ini #Tue Oct 24 19:43:04 UTC 2017 org.eclipse.core.runtime=2 org.eclipse.platform=4.7.1.v20171009-0410 <file_sep>/eclipse-workspace/EjercicioMaximos/ejercicio_maximos.py """Este codigo calcula el maximo de un listado de numeros.""" n = eval(input("¿Cantidad de valores? ")) valores = [] for i in range(0,n): v1 = eval(input()) valores.append(v1) maximo = -1000000 for valor in valores: if (valor > maximo): maximo = valor print(maximo)
1582eb28ba2005b61bdd2c18e83b4e09c6869210
[ "Python", "INI" ]
2
INI
111milprogramadoresbaradero/DevelopmentEnvironment
f0a13607c1fb8c02b065d521e253b996f30e90b0
e249b10d558ebc9436dc14989f3292dc29b92193
refs/heads/master
<file_sep>package co.grandcircus.Planets; import java.util.Arrays; import java.util.List; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import co.grandcircus.Planets.model.PlanetInfo; @Service public class PlanetApiService { private RestTemplate rest = new RestTemplate(); public List<PlanetInfo> planetInfoList() { String url = "https://grandcircusco.github.io/demo-apis/planets.json"; PlanetInfo[] planetsArray = rest.getForObject(url, PlanetInfo[].class); List<PlanetInfo> planets = Arrays.asList(planetsArray); return planets; } }
df5c7423c181863c9414d28ef3f4dbb6f2262cc9
[ "Java" ]
1
Java
msdottee/Planets
02383a18b12e0fb0ef196b7b26bada5c211cb302
0e8277e076b05cee14163b811b983f1211ec8961
refs/heads/master
<repo_name>JustinRoll/project1<file_sep>/classifier.py import random,operator,nltk import functools import rmse from nltk.corpus import udhr from nltk import bigrams, trigrams, ngrams from nltk.tokenize import word_tokenize, sent_tokenize from nltk.corpus import stopwords, wordnet from nltk.stem.snowball import SnowballStemmer from yelpQuery import YelpQuery from sentencePolarity import SentencePolarity class Classifier: def __init__(self, reviews): self.reviews = reviews self.yelpQuery = YelpQuery() self.yelpQuery.connect() self.polarity = SentencePolarity('twitter_sentiment_list.csv') def getBucket(self, count): if count <= 0: returnCount = None elif count >= 1 and count <= 5: returnCount = "low" elif count >= 6: returnCount = "high" return returnCount def getOverallFeatures(self, doc): featureDict = {} wordDict, topicWordDict, sents, stemmedWordDict = self.extractReviewWords(doc) wordList = sorted([word.lower() for word in set(stemmedWordDict.keys()) if word not in stopwords.words('English') and word not in ',-.;();$' and word not in '-' and word not in '.'], key = lambda x : stemmedWordDict[x], reverse=True) top10WordList = [wordList[i] for i in range(0, 10 if len(wordList) > 10 else len(wordList) - 1)] positiveSentenceCount = 0 negativeSentenceCount = 0 for sent in sents: tokenizedSent = [word for word in word_tokenize(sent) if ',' not in word and '.' not in word] negProb, posProb = self.polarity.classifySentiment(tokenizedSent) if posProb >= .6: positiveSentenceCount += 1 if negProb >= .6: negativeSentenceCount += 1 #for word in tokenizedSent: # posProb, negProb = self.polarity.classifyWord(word) # if negProb >= .8: # featureDict[word + " neg polarity"] = 1 # if posProb >= .8: # featureDict[word + " pos polarity"] = 1 #wordTrigrams = trigrams(tokenizedSent) #for trigram in wordTrigrams: # featureDict[trigram] = True for unigram in top10WordList: featureDict[unigram] = 1 #self.getBucket(stemmedWordDict[unigram]) featureDict["posSentences"] = self.getBucket(positiveSentenceCount) featureDict["negSentences"] = self.getBucket(negativeSentenceCount) #yelpFeatures = self.yelpQuery.getFeatures(doc.name, doc.city, 1) #featureDict.update(yelpFeatures) return featureDict def getAuthorshipFeatures(self, doc): featureDict = {} wordDict, topicWordDict, sents, stemmedWordDict = self.extractReviewWords(doc) wordList = sorted([word.lower() for word in set(stemmedWordDict.keys()) if word not in stopwords.words('English') and word not in ',-.;();$' and word not in '-' and word not in '.'], key = lambda x : stemmedWordDict[x], reverse=True) top10WordList = [wordList[i] for i in range(0, 10 if len(wordList) > 10 else len(wordList) - 1)] for sent in sents: tokenizedSent = [word for word in word_tokenize(sent) if ',' not in word and '.' not in word] wordTrigrams = trigrams(tokenizedSent) for trigram in wordTrigrams: featureDict[trigram] = True for unigram in top10WordList: featureDict[unigram] = 1#featureDict[unigram] = self.getBucket(stemmedWordDict[unigram]) return featureDict def getParagraphFeaturesExact(self, doc): featureDict = {} positiveSentenceCount = 0 negativeSentenceCount = 0 wordDict, topicWordDict, sents, stemmedWordDict = self.extractReviewWordsFromParagraph(doc) wordList = sorted([word.lower() for word in set(stemmedWordDict.keys()) if word.lower() not in stopwords.words('English') and word not in ',-.;();$' and word not in '-' and word not in '.'], key = lambda x : stemmedWordDict[x], reverse=True) topWordList = [wordList[i] for i in range(0, 10 if len(wordList) > 10 else len(wordList) - 1)] for sent in sents: tokenizedSent = [word for word in word_tokenize(sent) if ',' not in word and '.' not in word] posProb, negProb = self.polarity.classifySentiment(tokenizedSent) if posProb >= .6: positiveSentenceCount += 1 if negProb >= .6: negativeSentenceCount += 1 for word in tokenizedSent: negProb, posProb = self.polarity.classifyWord(word) if negProb >= .8: featureDict[word + " neg polarity"] = 1 if posProb >= .8: featureDict[word + " pos polarity"] = 1 #wordTrigrams = trigrams(tokenizedSent) #for trigram in wordTrigrams: # featureDict[trigram] = True #wordBigrams = bigrams(tokenizedSent) #for bigram in wordBigrams: # featureDict[bigram] = True #fourGrams = ngrams(tokenizedSent, 4) #for fourGram in fourGrams: # featureDict[fourGram] = True #for unigram in topWordList: # featureDict[unigram] = self.getBucket(stemmedWordDict[unigram]) featureDict["posSentences"] = self.getBucket(positiveSentenceCount) featureDict["negSentences"] = self.getBucket(negativeSentenceCount) return featureDict def getParagraphFeatures(self, doc): featureDict = {} wordDict, topicWordDict, sents, stemmedWordDict = self.extractReviewWordsFromParagraph(doc) wordList = sorted([word.lower() for word in set(stemmedWordDict.keys()) if word.lower() not in stopwords.words('English') and word not in ',-.;();$' and word not in '-' and word not in '.'], key = lambda x : stemmedWordDict[x], reverse=True) topWordList = [wordList[i] for i in range(0, 10 if len(wordList) > 10 else len(wordList) - 1)] #for sent in sents: # tokenizedSent = [word for word in word_tokenize(sent) if ',' not in word and '.' not in word] # wordTrigrams = trigrams(tokenizedSent) # for trigram in wordTrigrams: # featureDict[trigram] = True #wordBigrams = bigrams(tokenizedSent) #for bigram in wordBigrams: # featureDict[bigram] = True #fourGrams = ngrams(tokenizedSent, 4) #for fourGram in fourGrams: # featureDict[fourGram] = True for unigram in wordList: featureDict[unigram] = 1#self.getBucket(stemmedWordDict[unigram]) return featureDict #return a dictionary with words and a count of all the words in the review def extractReviewWords(self, doc): wordDict = {} topicWordDict = {} stemmedWordDict = {} stemmer = SnowballStemmer('english') sents = [] for paragraph in doc.paragraphs: #tokenize all words #to do: pos tag all words? wordTokens = word_tokenize(paragraph) for word in wordTokens: self.incrementDictCount(word, wordDict) self.incrementDictCount(stemmer.stem(word), stemmedWordDict) #self.incrementDictCount(key, topicWordDict) for sent in sent_tokenize(paragraph): sents.append(sent) return wordDict, topicWordDict, sents, stemmedWordDict def extractReviewWordsFromParagraph(self, paragraph): wordDict = {} topicWordDict = {} stemmedWordDict = {} stemmer = SnowballStemmer('english') sents = [] #tokenize all words #to do: pos tag all words? wordTokens = word_tokenize(paragraph) for word in wordTokens: self.incrementDictCount(word, wordDict) self.incrementDictCount(stemmer.stem(word), stemmedWordDict) #self.incrementDictCount(key, topicWordDict) for sent in sent_tokenize(paragraph): sents.append(sent) return wordDict, topicWordDict, sents, stemmedWordDict def incrementDictCount(self, item, incDict): if item in incDict: incDict[item] += 1 else: incDict[item] = 1 def classifyOverallReviews(self): docs = [(review, 1) for review in self.reviews if review.rating > 3] + [(review, 0) for review in self.reviews if review.rating <= 3] random.shuffle(docs) featureSets = [(self.getOverallFeatures(d),label) for (d, label) in docs] firstThird = int(len(featureSets)/3) train, test = featureSets[:firstThird], featureSets[firstThird:] classifier = nltk.NaiveBayesClassifier.train(train) print(classifier.show_most_informative_features(20)) return rmse.getError(classifier, test), nltk.classify.accuracy(classifier,test) def classifyOverallReviewsExact(self): docs = [(review, review.rating) for review in self.reviews] random.shuffle(docs) featureSets = [(self.getOverallFeatures(d),label) for (d, label) in docs] firstThird = int(len(featureSets)/3) train, test = featureSets[:firstThird], featureSets[firstThird:] classifier = nltk.NaiveBayesClassifier.train(train) print(classifier.show_most_informative_features(20)) return rmse.getError(classifier, test), nltk.classify.accuracy(classifier,test) def classifyParagraphReviewsExact(self): docs = [] for review in self.reviews: for score, paragraph in review.ratingParagraphMap.items(): docs.append((paragraph, score)) random.shuffle(docs) featureSets = [(self.getParagraphFeaturesExact(d),label) for (d, label) in docs] firstThird = int(len(featureSets)/3) train, test = featureSets[:firstThird], featureSets[firstThird:] classifier = nltk.NaiveBayesClassifier.train(train) print(classifier.show_most_informative_features(20)) return rmse.getError(classifier, test), nltk.classify.accuracy(classifier,test) def classifyAuthorshipReviews(self): docs = [] for review in self.reviews: docs.append((review, review.reviewer)) authors = set([review.reviewer for review in self.reviews]) print("%d Authors total, baseline is %f" %(len(authors), 1.0/len(authors))) random.shuffle(docs) featureSets = [(self.getAuthorshipFeatures(d),label) for (d, label) in docs] firstThird = int(len(featureSets)/3) train, test = featureSets[:firstThird], featureSets[firstThird:] classifier = nltk.NaiveBayesClassifier.train(train) print(classifier.show_most_informative_features(20)) return 0, nltk.classify.accuracy(classifier,test) def classifyParagraphReviews(self): docs = [] for review in self.reviews: for score, paragraph in review.ratingParagraphMap.items(): if score > 3: docs.append((paragraph, 1)) else: docs.append((paragraph, 0)) random.shuffle(docs) featureSets = [(self.getParagraphFeatures(d),label) for (d, label) in docs] firstThird = int(len(featureSets)/3) train, test = featureSets[:firstThird], featureSets[firstThird:] classifier = nltk.NaiveBayesClassifier.train(train) print(classifier.show_most_informative_features(20)) return rmse.getError(classifier, test), nltk.classify.accuracy(classifier,test) def getAverages(self, function): accuracyTotal = 0.0 rmseTotal = 0.0 accuracies = [] for i in range(0, 5): rmse, accuracy = function() accuracies.append(accuracy) accuracyTotal += accuracy rmseTotal += rmse print(accuracies) return rmseTotal / 5.0, accuracyTotal / 5.0 <file_sep>/review.py import re from bs4 import BeautifulSoup import glob, os class Review: def __init__(self): self.reviewer = "" self.name = "" self.address = "" self.city = "" self.food = 0 self.service = 0 self.venue = 0 self.rating = 0 self.paragraphs = list() self.ratingParagraphMap = {} def get_dict(self): return {"reviewer" : self.reviewer, "name" : self.name, "city" : self.city, "food" : self.food, "service" : self.service, "venue" : self.venue, "rating" : self.rating, "paragraphs" : self.paragraphs} #food service venue def make_paragraph_map(self): if len(self.paragraphs) >= 4: self.ratingParagraphMap[self.food] = self.paragraphs[0] self.ratingParagraphMap[self.service] = self.paragraphs[1] self.ratingParagraphMap[self.venue] = self.paragraphs[2] tagRegex = r'\<[^>]*\>' reviewerRegex = r'REVIEWER:\s*(.*)' nameRegex = r'NAME:\s*(.*)' addressRegex = r'ADDRESS:\s*(.*)' cityRegex = r'CITY:\s*(.*)' foodRegex = r'FOOD:\s*(\d)' serviceRegex = r'SERVICE:\s*(\d)' venueRegex = r'VENUE:\s*(\d)' ratingRegex = r'RATING:\s*(.*)' writtenReviewRegex = r'WRITTEN REVIEW:' def parseReview(html): html = re.sub(r"\<span[^>]*>", " ", html) html = re.sub(r"\<\/span>", " ", html) html = re.sub(r"<br \/>", "</p><p>", html) soup = BeautifulSoup(html) paragraphs = soup.find_all('p') reviews = [] review = None pMode = False metaMode = False for paragraph in paragraphs: contents = [x if isinstance(x, str) else "\n" for x in paragraph.contents] plaintext = "\n".join(contents) reviewer = re.search(reviewerRegex, plaintext, re.IGNORECASE) name = re.search(nameRegex, plaintext, re.IGNORECASE) address = re.search(addressRegex, plaintext, re.IGNORECASE) city = re.search(cityRegex, plaintext, re.IGNORECASE) food = re.search(foodRegex, plaintext, re.IGNORECASE) service = re.search(serviceRegex, plaintext, re.IGNORECASE) venue = re.search(venueRegex, plaintext, re.IGNORECASE) rating = re.search(ratingRegex, plaintext, re.IGNORECASE) writtenReview = re.search(writtenReviewRegex, plaintext, re.IGNORECASE) if reviewer and not metaMode: pMode = False if review: reviews.append(review) review = Review() metaMode =True review.reviewer = reviewer.group(1) if name: review.name = name.group(1) if address: review.address = address.group(1) if city: review.city = city.group(1) if food: review.food = int(food.group(1)) if service: review.service = int(service.group(1)) if venue: review.venue = int(venue.group(1)) if rating: review.rating = int(rating.group(1)) if writtenReview: pMode = True metaMode = False elif pMode and len(plaintext) > 4: review.paragraphs.append(plaintext) review.make_paragraph_map() reviews.append(review) return reviews def importReviews(directory): reviews = [] for filename in glob.glob(os.path.join(directory, '*.html')): f = open(filename, 'r', encoding='utf-8') content = f.read() f.close() newRevs = parseReview(content) reviews.extend(newRevs) for rev in newRevs: if len(rev.paragraphs) != 4: print(filename) print(len(rev.paragraphs)) #prints names of files that were not correctly parsed return reviews importReviews("./reviews") <file_sep>/yelpQuery.py import argparse import json import pprint import sys import urllib from yelpapi import YelpAPI class YelpQuery: def __init__(self): self.DEFAULT_TERM = 'dinner' self.DEFAULT_LOCATION = 'San Luis Obispo, CA' self.SEARCH_LIMIT = 3 self.SEARCH_PATH = '/v2/search/' self.BUSINESS_PATH = '/v2/business/' self.CONSUMER_KEY = "0Ji9mpDmiH0rub9AvjtRhQ" self.CONSUMER_SECRET = "<KEY>" self.TOKEN = "<KEY>" self.TOKEN_SECRET = "<KEY>" def connect(self): self.yelp_api = YelpAPI(self.CONSUMER_KEY, self.CONSUMER_SECRET, self.TOKEN, self.TOKEN_SECRET) def get_business(self, business_id, **kw_args): business_results = self.yelp_api.business_query(id=business_id, **kw_args) return businessResults def search(self, **kwargs): search_results = self.yelp_api.search_query(**kwargs) return search_results #get a valid restaurant def getValidRestaurant(self, **kwargs): response = self.search(**kwargs) nameMatch = False result = None i = 0 while not nameMatch and i < 3 and i < len(response["businesses"]): business = response["businesses"][i] if business["name"].lower() == kwargs["term"].lower(): nameMatch = True result = business i+=1 if len(response["businesses"]) > 0: result = response["businesses"][0] return result def getExactFeatures(self, restaurantName, location, weight): featureDict = {} if location == "Arnold": location = "Arnold, CA" elif restaurantName == "<NAME>": restaurantName = "<NAME>" elif location == "Shell Beach" and "intock" in restaurantName: restaurantName = "F. McLintocks Saloon & Dining House" location = "Shell Beach, CA" yelpRestaurant = self.getValidRestaurant(term = restaurantName, location = location, limit = 3) if yelpRestaurant: rating = self.getExactRating(yelpRestaurant) reviewCount = self.getReviews(yelpRestaurant) else: rating = self.getExactRating({"rating" : 3.0, "review_count" : 21}) reviewCount = self.getReviews({"rating": 3.0, "review_count" : 21}) #the only restaurant for which this failed is Alphys. Hardcoding the vals from #Alphys Chateau Basque at http://www.yelp.com/biz/alphys-chateau-basque-pismo-beach-2 print("No yelp info for %s in %s" % (restaurantName, location)) for i in range(1, weight + 1): featureDict["rating%d" %i] = rating featureDict["reviewCount%d" %i] = reviewCount return featureDict def getFeatures(self, restaurantName, location, weight): featureDict = {} if location == "Arnold": location = "Arnold, CA" elif restaurantName == "<NAME>": restaurantName = "<NAME>" elif location == "Shell Beach" and "intock" in restaurantName: restaurantName = "F. McLintocks Saloon & Dining House" location = "Shell Beach, CA" yelpRestaurant = self.getValidRestaurant(term = restaurantName, location = location, limit = 3) if yelpRestaurant: rating = self.getRating(yelpRestaurant) reviewCount = self.getReviews(yelpRestaurant) else: rating = self.getRating({"rating" : 3.0, "review_count" : 21}) reviewCount = self.getRating({"rating": 3.0, "review_count" : 21}) #the only restaurant for which this failed is Alphys. Hardcoding the vals from #Alphys Chateau Basque at http://www.yelp.com/biz/alphys-chateau-basque-pismo-beach-2 print("No yelp info for %s in %s" % (restaurantName, location)) for i in range(1, weight + 1): featureDict["rating%d" %i] = rating featureDict["reviewCount%d" %i] = reviewCount return featureDict def getReviews(self, restaurant): reviewCount = restaurant["review_count"] if reviewCount >= 500: reviewCountBucket = "above500" elif reviewCount >= 400: reviewCountBucket = "above400" elif reviewCount >= 300: reviewCountBucket = "above300" elif reviewCount >= 200: reviewCountBucket = "above200" elif reviewCount >= 100: reviewCountBucket = "above100" else: reviewCountBucket = "below100" return reviewCountBucket def getExactRating(self, restaurant): rating = restaurant["rating"] ratingBucket = None if rating >= 4.5: ratingBucket = "above45" elif rating >= 4.0: ratingBucket = "above4" elif rating >= 3.0: ratingBucket = "above3" elif rating >= 2.0: ratingBucket = "above2" elif ratingBucket >= 1.0: ratingBucket = "above1" else: ratingBucket = "above0" return ratingBucket def getRating(self, restaurant): rating = restaurant["rating"] ratingBucket = None if rating >= 4.0: ratingBucket = "positive" else: ratingBucket = "negative" return ratingBucket <file_sep>/confusionMatrix.py import nltk def printConfusion(classifier, testSet): gold = [] test = [] for document, label in testSet: gold.append(label) test.append(classifier.classify(document)) cm = nltk.ConfusionMatrix(gold, test) print(cm.pp()) <file_sep>/driver.py from yelpQuery import YelpQuery from classifier import Classifier from review import * def main(): reviews = importReviews("./reviews") classifier = Classifier(reviews) print("Overall Score Average accuracy: %f" % (classifier.getAverages(classifier.classifyOverallReviews)[1])) print("Overall Score Exact rmse: %f, accuracy: %f" % (classifier.getAverages(classifier.classifyOverallReviewsExact))) print("Paragraph accuracy: %f" % (classifier.getAverages(classifier.classifyParagraphReviews)[1])) print("Paragraph Exact Score rmse: %f, accuracy: %f" % (classifier.getAverages(classifier.classifyParagraphReviewsExact))) print("Authorship rmse: %f, accuracy: %f" % (classifier.getAverages(classifier.classifyAuthorshipReviews))) # print("Exact Score (0-5) Paragraph rmse: %f, accuracy: %f" % (classifier.classifyParagraphReviewsExact())) # print("Overall rmse: %f, accuracy: %f" % (classifier.classifyOverallReviews())) # print("Exact Overall rmse: %f, accuracy: %f" % (classifier.classifyOverallReviewsExact())) # print("Authorship score: %f" % classifier.classifyAuthorshipReviews()) main() <file_sep>/testYelpQuery.py from yelpQuery import YelpQuery def testQuery(): yelpQuery = YelpQuery() yelpQuery.connect() response = yelpQuery.search(term='Jaffa Cafe', location = "San Luis Obispo", limit = 3) print(response["businesses"][0]["rating"]) print(response["businesses"][0]["name"]) print(response["businesses"][0]) print(yelpQuery.getFeatures("Jaffa Cafe", "San Luis Obispo")) def main(): testQuery() main()
b920df64f6def2598b999b56f361babac4b03c2b
[ "Python" ]
6
Python
JustinRoll/project1
12a8ae32e40bf0e7d3d634f6609e284fe99d8bb1
6ae3f4ff10a900716ef0300464165ffbf3940aab
refs/heads/master
<repo_name>alex-b1/lesson3<file_sep>/dispatch.rb require_relative './train.rb' require_relative './route.rb' require_relative './station.rb' volgograd = Station.new(:volgograd) voronesh = Station.new(:voronesh) astrakhan = Station.new(:astrakhan) novgorod = Station.new(:novgorod) saint_petersburg = Station.new(:saint_petersburg) moscow_astrakhan = Route.new(:moscow, :astrakhan) moscow_astrakhan.add_station volgograd sapsan = Train.new('1', :passenger, 8) sapsan.route moscow_astrakhan sapsan.accelerate sapsan.accelerate sapsan.speed sapsan.slow_down sapsan.slow_down sapsan.number_carriage sapsan.attach_carriage sapsan.detach_carriage sapsan.detach_carriage lastochka = Train.new('2', :passenger, 12) express = Train.new('3', :passenger, 6) cargo1 = Train.new('4', :cargo, 4) cargo2 = Train.new('5', :cargo, 6) moscow = Station.new('moscow') moscow.arrival_train sapsan moscow.arrival_train express moscow.arrival_train cargo1 p moscow.arrival_train cargo2 p moscow.depart_train sapsan #moscow.depart_train express p moscow.get_trains_by_type #p moscow.trains # moscow_astrakhan.add_station :novgorod # moscow_astrakhan.add_station :voronesh # moscow_astrakhan.remove_station :novgorod # # p moscow_astrakhan.get_stations_list # moscow_saint_petersburg = Route.new(:moscow, :saint_petersburg) # moscow_saint_petersburg.add_station :novgorod # # sapsan.route moscow_astrakhan # sapsan.go_ahead # sapsan.route moscow_saint_petersburg # sapsan.go_ahead # sapsan.go_ahead # sapsan.go_ahead # sapsan.go_ahead # sapsan.go_back # # sapsan.next_station # sapsan.get_previous_station # sapsan.station <file_sep>/train.rb class Train attr_reader :number_carriage, :number, :type, :speed, :station, :is_move, :route def initialize(number, type, number_carriage) @number = number @type = type @number_carriage = number_carriage @speed = 0 end def accelerate(speed = 10) @speed += speed end def slow_down(speed = 10) @speed = @speed < speed ? 0 : @speed - speed end def attach_carriage(count = 1) if !validate_speed? @number_carriage += count else puts 'Поезд движется' @number_carriage end end def detach_carriage(count = 1) if !validate_speed? @number_carriage = @number_carriage < count ? 0 : @number_carriage - count else puts 'Поезд движется' @number_carriage end end def route(route) @route = route @station = @route.stations.first puts "Вы на станции: #{@station}" @route.get_stations_list end def go_ahead @station = next_station if next_station end def go_back @station = get_previous_station if get_previous_station end def next_station index = @route.stations.index @station length = @route.stations.length if index == length puts 'вы на последней станции' else @route.stations[index + 1] end end def get_previous_station index = @route.stations.index @station if index == 0 puts 'Вы на первой станции' else @route.stations[index - 1] end end private def validate_speed? @speed > 0 end end <file_sep>/route.rb class Route attr_reader :initial_station, :end_station, :stations def initialize(initial_station, end_station) @initial_station = initial_station @end_station = end_station @stations = [@initial_station, @end_station] end def add_station(station) if validate_station? station puts 'Ошибка, такая станция уже есть' else @stations.insert(-2, station) end end def remove_station(station) if validate_station? station @stations.delete(station) else puts 'Ошибка, такой станции нет' end end def get_stations_list @stations.each {|i| puts i} end private def validate_station?(station) @stations.include? station end end <file_sep>/station.rb class Station attr_accessor :trains attr_reader :name def initialize(name) @name = name @trains = [] end def arrival_train(train) @trains << train train.slow_down train.slow_down train.slow_down 100 end def depart_train(train) @trains.filter! {|i| i.number != train.number} train.next_station train.accelerate train.accelerate end def get_trains_by_type list = { cargo: (@trains.filter {|i| i.type == :cargo}).count , passenger: (@trains.filter {|i| i.type == :passenger}).count, } end end
8ac97defde12967c4cc286302e99d26f172bbed8
[ "Ruby" ]
4
Ruby
alex-b1/lesson3
b857171960886fb0fee1f1b7a326ad4e46578b00
71a5235257b45764645553607b40849fb5505c5d
refs/heads/master
<file_sep>$("form").on("submit", function(event) { var form = $(event.target), appId = form.find("#appId")[0].value; userEmail = form.find("#userEmail")[0].value, userPass = form.find("#userPassword")[0].value; $('#myModal').modal('toggle'); Parse.initialize(appId); Parse.serverURL = 'https://appdev.newyorker.de/newyorkerapitest'; loginUserToParseServer(userEmail, userPass); event.preventDefault(); }); function loginUserToParseServer(email, password) { var login = Parse.User.logIn(email, password); Parse.Promise.when(login).then( function() { $("#loginBtn").hide(); handleCustomerSexRatio(); }, function(error) { console.log(error[0].message); } ); } function handleCustomerSexRatio() { var CustomerProfile = Parse.Object.extend("CustomerProfile"), query_f = new Parse.Query(CustomerProfile), query_m = new Parse.Query(CustomerProfile), query_na = new Parse.Query(CustomerProfile), queriesCount; query_m.equalTo("sex", "MALE"); query_f.equalTo("sex", "FEMALE"); query_na.notEqualTo("sex", "MALE").notEqualTo("sex", "FEMALE"); queriesCount = [query_f.count(), query_m.count(), query_na.count()]; Parse.Promise.when(queriesCount).then(drawGraph); } function drawGraph(female, male, na) { var myPieChart = new Chart($("#myChart"), { type: 'pie', data: { labels: [ "Female", "Male", "N/A" ], datasets: [{ data: [female, male, na], backgroundColor: [ "#FF6384", "#36A2EB", "#EEEEEE" ], hoverBackgroundColor: [ "#FF6384", "#36A2EB", "#EEEEEE" ] }] }, options: { responsive: true } }); }
c9b7c4a832d7776196e89d0a24505cbe8108ffc7
[ "JavaScript" ]
1
JavaScript
lipina/ny-test-task
54d6b6c87bb93e50b88f00808eb2ed7fccf0d235
3d01cfa0d89d68d86ba3947ee5e9569140a7b1a4
refs/heads/master
<repo_name>rcsiit1/sails-searchUtility<file_sep>/api/controllers/CsvtodatabaseController.js const csv = require('fast-csv'); const NodeGeocoder = require('node-geocoder'); var insertData = async (req, res) => { function ran() { var results = []; csv.fromPath('./assets/mycsv.csv', { headers: true }) .on('data', (record) => { results.push(record); }).on('end', () => { console.log("Process Completed!"); googleGeocoding(results); }).on('error', () => { console.log('error'); }); }; function googleGeocoding(results) { const options = { provider: 'google', httpAdapter: 'https', apiKey: '<KEY> ', formatter: null }; var geocoder = NodeGeocoder(options); for (let i = 0; i < results.length; i++) { if (results[i].Locations !== undefined) { geocoder.geocode(results[i].Locations, async (err, res) => { try { if (res && res.length > 0 && res[0] !== undefined) { await Csvtodatabase.create({ title: results[i].Title, actor1: results[i].Actor1, actor2: results[i].Actor2, actor3: results[i].Actor3, production: results[i].ProductionCompany, release: results[i].ReleaseYear, locations: results[i].Locations, lat: res[0].latitude, long: res[0].longitude }); } } catch (err) { console.log(err); } }); } } }; ran(); }; module.exports = { insertData: insertData, }; <file_sep>/api/controllers/SearchController.js let searchUtility = async (req, res) => { res.view('pages/search', { layout: false }); }; let search = async (req, res) => { let q = req.param('search_query'); let category = req.param('category'); console.log(category); let query = {}; let subquery = {}; subquery['contains'] = q; query[category] = subquery; let results = await Csvtodatabase.find(query); console.log(results); res.json({ results: results}); }; module.exports = { searchUtility: searchUtility, search: search, }; <file_sep>/config/routes.js module.exports.routes = { '/': { view: 'pages/homepage' }, '/dataChange/': { controller: 'CsvtodatabaseController', action: 'insertData' }, '/searchUtility/': { controller: 'SearchController', action: 'searchUtility' }, '/search': { controller: 'SearchController', action: 'search' }, };
f517af7f9eae9b2a144ca3cc289d68f5c1ae9779
[ "JavaScript" ]
3
JavaScript
rcsiit1/sails-searchUtility
04fe5e0942350ac0ba1732befb4b4c110e885528
61d5f50507175e31223afd6f7fe75b06b9aacbc4
refs/heads/master
<repo_name>hbaker/wordpress-age-verification<file_sep>/age-verification.php <?php /** * Plugin Name: Simple Age Verification * Plugin URI: http://lauriliimatta.com * Description: This plugin adds a simple age verification check. * Version: 1.0.0 * Author: <NAME> * Author URI: http://lauriliimatta.com * License: GPL2 */ function age_verification_popup() { if(!isset($_COOKIE['age_verification'])) { ?> <div class="age-verification-overlay"> <div class="age-verification-popup"> <p class="age-verification-q"><?php _e('Are you 18 or older?', 'age-verification'); ?></p> <p> <a class="age-verification-btn age-verification-btn-no" href="https://google.com"><?php _e('No', 'age-verification'); ?></a> <a class="age-verification-btn age-verification-btn-yes" href="#"><?php _e('Yes', 'age-verification'); ?></a> </p> </div> </div> <?php } } add_action('wp_footer', 'age_verification_popup'); function age_verification_assets() { wp_enqueue_script( 'age-verification', plugins_url( '/age-verification.js', __FILE__ ), array('jquery')); wp_enqueue_style( 'age-verification', plugins_url( '/age-verification.css', __FILE__) ); $nonce = wp_create_nonce( 'age-verification' ); wp_localize_script( 'age-verification', 'my_ajax_obj', array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'nonce' => $nonce, ) ); } add_action('init', 'age_verification_assets'); function set_age_verification_cookie() { check_ajax_referer( 'age-verification' ); if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { setcookie('age_verification', true, time()+(3600*12), COOKIEPATH, COOKIE_DOMAIN ); } die(); } add_action('wp_ajax_set_age_verification_cookie', 'set_age_verification_cookie'); add_action('wp_ajax_nopriv_set_age_verification_cookie', 'set_age_verification_cookie'); ?><file_sep>/README.md # Simple age verification plugin for WordPress ## Installation 1. Upload the files to a folder called 'age-verification' inside of /wp-content/plugins/ directory 2. Activate the plugin through the ‘Plugins’ menu in WordPress
3dbe6b9361320a4066d889fb1c3df2a427c24109
[ "Markdown", "PHP" ]
2
PHP
hbaker/wordpress-age-verification
429f8d37be64cef263daad6224db23e9b58899a4
1697d74f1671b6ee3b35c77cea933e93997ad986
refs/heads/master
<file_sep>import os from setuptools import find_packages, setup version = '0.1.4' install_requires = ['six'] here = os.path.dirname(__file__) with open(os.path.join(here, 'README.rst')) as fp: longdesc = fp.read() with open(os.path.join(here, 'CHANGELOG.rst')) as fp: longdesc += "\n\n" + fp.read() setup( name='python-libxdo-ng', version=version, packages=find_packages(), url='https://github.com/user202729/python-libxdo', # 3-clause BSD, same as xdotool license='BSD License', author='<NAME>', author_email='<EMAIL>', description='Python bindings for libxdo', long_description='', install_requires=install_requires, # test_suite='tests', classifiers=[ "License :: OSI Approved :: BSD License", # 3-clause # "Development Status :: 1 - Planning", # "Development Status :: 2 - Pre-Alpha", "Development Status :: 3 - Alpha", # "Development Status :: 4 - Beta", # "Development Status :: 5 - Production/Stable", # "Development Status :: 6 - Mature", # "Development Status :: 7 - Inactive", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", # Only CPython is supported at the moment "Programming Language :: Python :: Implementation :: CPython", # "Programming Language :: Python :: Implementation :: PyPy", ], package_data={'': ['README.rst', 'LICENSE', 'CHANGELOG.rst']}) <file_sep>########################## Python bindings for libxdo ########################## libxdo is the library behind `xdotool <https://github.com/jordansissel/xdotool>`__, a tool to "fake keyboard/mouse input, window management, and more". This package aims to provide ctypes-based Python bindings (and a more pythonic way to use the C library, of course..) **WARNING** The project is still work in progress! Only a small part of the library is supported, and tests / documentation are missing. Use with care (and make sure to report any issue you should find!) Documentation ============= Documentation is hosted on Read The Docs: http://python-libxdo.readthedocs.org/ **Note:** there currently is a problem building the documentation on RTD due to missing libxdo library (which makes importing ``xdo.xdo`` fail). For this reason, a (locally-generated) copy of the documentation is hosted on github pages: https://rshk.github.io/python-libxdo Example usage ============= Ask the user to click a window with the mouse, then write "Python rocks!" to that window. .. code:: python from xdo import Xdo xdo = Xdo() win_id = xdo.select_window_with_click() xdo.enter_text_window(win_id, b'Python rocks!') Compatibility ============= The library is currently tested on: +---------------------------------------+----------------+--------------------+--------------+---------------+ | OS | Architecture | libxdo version | Date | Test result | +=======================================+================+====================+==============+===============+ | Debian GNU/Linux "jessie" (testing) | amd64 | 3.20130111.1-3.1 | | ✓ success | +---------------------------------------+----------------+--------------------+--------------+---------------+ | Archlinux | amd64 | 3.20150503.1 | 2015-11-16 | ✓ success | +---------------------------------------+----------------+--------------------+--------------+---------------+ Installation ============ The package is available on pypi https://pypi.python.org/pypi/python-libxdo/ Install via pip: :: pip install python-libxdo Install the tarball directly from github: :: pip install https://github.com/rshk/python-libxdo/tarball/master Install in development mode from git: :: pip install -e 'git+https://github.com/rshk/python-libxdo.git#egg=python-libxdo' <file_sep># -*- coding: utf-8 -*- """ Ctypes bindings for libxdo """ import ctypes from ctypes import ( POINTER, Structure, c_bool, c_char, c_char_p, c_int, c_long, c_uint, c_ulong, c_void_p, c_wchar, c_ubyte) from ctypes.util import find_library libxdo = ctypes.CDLL(find_library("xdo")) libX11 = ctypes.CDLL(find_library("X11")) # Import XFree XDO_ERROR = 1 XDO_SUCCESS = 0 # Window type is just defined as ``unsigned long`` window_t = c_ulong useconds_t = c_ulong # screen_t = c_ulong # warning! this is simply guessed! XID = c_ulong Colormap = XID GContext = XID Pixmap = XID Font = XID class XdoException(Exception): pass def _errcheck(result, func, arguments): """ Error checker for functions returning an integer indicating success (0) / failure (1). Raises a XdoException in case of error, otherwise just returns ``None`` (returning the original code, 0, would be useless anyways..) """ if result != 0: raise XdoException( 'Function {0} returned error code {1}' .format(func.__name__, result)) return None # be explicit :) # Keep reference of libraries from which stuff is taken.. # #include <sys/types.h> # #include <X11/Xlib.h> # #include <X11/X.h> # #include <unistd.h> # #include <wchar.h> # When issuing a window size change, giving this flag will make the size # change be relative to the size hints of the window. For terminals, this # generally means that the window size will be relative to the font size, # allowing you to change window sizes based on character rows and columns # instead of pixels. SIZE_USEHINTS = 1 << 0 SIZE_USEHINTS_X = 1 << 1 SIZE_USEHINTS_Y = 1 << 2 # CURRENTWINDOW is a special identify for xdo input faking (mouse and # keyboard) functions like xdo_send_keysequence_window that indicate # we should target the current window, not a specific window. # # Generally, this means we will use XTEST instead of XSendEvent when sending # events. CURRENTWINDOW = ctypes.c_ulong(0) KeyCode = c_char # unsinged char KeySym = c_ulong # XID -> unsigned long class charcodemap_t(Structure): """ Map character to whatever information we need to be able to send this key (keycode, modifiers, group, etc) """ _fields_ = [ # wchar_t key; // the letter for this key, like 'a' ('key', c_wchar), # KeyCode code; // the keycode that this key is on ('code', KeyCode), # KeySym symbol; // the symbol representing this key ('symbol', KeySym), # int group; // the keyboard group that has this key in it ('group', c_int), # int modmask; // the modifiers to apply when sending this key # // if this key need to be bound at runtime because # // it does not exist in the current keymap, this will # // be set to 1. ('modmask', c_int), # int needs_binding; ('needs_binding', c_int), ] # typedef enum { # XDO_FEATURE_XTEST, /** Is XTest available? */ # } XDO_FEATURES; XDO_FEATURE_XTEST = 0 class xdo_t(Structure): """The main context""" _fields_ = [ # The Display for Xlib # Display *xdpy; ('xdpy', c_void_p), # The display name, if any. NULL if not specified. # char *display_name; ('display_name', c_char_p), # @internal Array of known keys/characters # charcodemap_t *charcodes; ('charcodes', POINTER(charcodemap_t)), # @internal Lenth of charcodes array # int charcodes_len; ('charcodes_len', c_int), # @internal highest keycode value highest and lowest keycodes # int keycode_high; ('keycode_high', c_int), # @internal lowest keycode value used by this X server # int keycode_low; ('keycode_low', c_int), # @internal number of keysyms per keycode # int keysyms_per_keycode; ('keysyms_per_keycode', c_int), # Should we close the display when calling xdo_free? # int close_display_when_freed; ('close_display_when_freed', c_int), # Be extra quiet? (omits some error/message output) # int quiet; ('quiet', c_int), # Enable debug output? # int debug; ('debug', c_int), # Feature flags, such as XDO_FEATURE_XTEST, etc... # int features_mask; ('features_mask', c_int), ] class XErrorEvent(Structure): _fields = [ # int type; ('type', c_int), # Display *display; /* Display the event was read from */ ('display', c_void_p), # XID resourceid; /* resource id */ ('resourceid', XID), # unsigned long serial; /* serial number of failed request */ ('serial', c_ulong), # unsigned char error_code; /* error code of failed request */ ('error_code', c_ubyte), # unsigned char request_code; /* Major op-code of failed request */ ('request_code', c_ubyte), # unsigned char minor_code; /* Minor op-code of failed request */ ('minor_code', c_ubyte), ] # Search only window title. DEPRECATED - Use SEARCH_NAME SEARCH_TITLE = 1 << 0 # Search only window class. SEARCH_CLASS = 1 << 1 # Search only window name. SEARCH_NAME = 1 << 2 # Search only window pid. SEARCH_PID = 1 << 3 # Search only visible windows. SEARCH_ONLYVISIBLE = 1 << 4 # Search only a specific screen. SEARCH_SCREEN = 1 << 5 # Search only window class name. SEARCH_CLASSNAME = 1 << 6 # Search a specific desktop SEARCH_DESKTOP = 1 << 7 SEARCH_ANY = 0 SEARCH_ALL = 1 class xdo_search_t(Structure): """ The window search query structure. :see: xdo_search_windows """ _fields_ = [ # const char *title; pattern to test against a window title ('title', c_char_p), # const char *winclass; pattern to test against a window class ('winclass', c_char_p), # const char *winclassname; pattern to test against a window class ('winclassname', c_char_p), # const char *winname; pattern to test against a window name ('winname', c_char_p), # const char *winrole; pattern to test against a window role ('winrole', c_char_p), # int pid; window pid (From window atom _NET_WM_PID) ('pid', c_int), # long max_depth; depth of search. 1 means only toplevel windows ('max_depth', c_long), # int only_visible; boolean; set true to search only visible windows ('only_visible', c_int), # int screen; what screen to search, if any. If none given, # search all screens ('screen', c_int), # Should the tests be 'and' or 'or' ? If 'and', any failure # will skip the window. If 'or', any success will keep the window # in search results. # enum { SEARCH_ANY, SEARCH_ALL } require; ('require', c_int), # bitmask of things you are searching for, such as SEARCH_NAME, etc. # :see: SEARCH_NAME, SEARCH_CLASS, SEARCH_PID, SEARCH_CLASSNAME, etc # unsigned int searchmask; ('searchmask', c_uint), # What desktop to search, if any. If none given, search # all screens. # long desktop; ('desktop', c_long), # How many results to return? If 0, return all. # unsigned int limit; ('limit', c_uint), ] # Defined in X11/Xlib.h class XGCValues(Structure): _fields_ = [ ('function', c_int), # logical operation ('plane_mask', c_ulong), # plane mask ('foreground', c_ulong), # foreground pixel ('background', c_ulong), # background pixel ('line_width', c_int), # line width ('line_style', c_int), # LineSolid, LineOnOffDash, LineDoubleDash ('cap_style', c_int), # CapNotLast, CapButt, CapRound, CapProjecting ('join_style', c_int), # JoinMiter, JoinRound, JoinBevel ('fill_style', c_int), # FillSolid, FillTiled, FillStippled, FillOpaeueStippled # noqa ('fill_rule', c_int), # EvenOddRule, WindingRule ('arc_mode', c_int), # ArcChord, ArcPieSlice ('tile', Pixmap), # tile pixmap for tiling operations ('stipple', Pixmap), # stipple 1 plane pixmap for stipping ('ts_x_origin', c_int), # offset for tile or stipple operations ('ts_y_origin', c_int), ('font', Font), # default text font for text operations ('subwindow_mode', c_int), # ClipByChildren, IncludeInferiors ('graphics_exposures', c_bool), # boolean, should exposures be generated # noqa ('clip_x_origin', c_int), # origin for clipping ('clip_y_origin', c_int), ('clip_mask', Pixmap), # bitmap clipping; other calls for rects */ ('dash_offset', c_int), # patterned/dashed line information ('dashes', c_char), ] # Defined in X11/Xlibint.h as _XGC -> then typedef'd as "GC" class _XGC(Structure): _fields_ = [ ('ext_data', c_void_p), # (XExtData *) hook for extension to hang data ('gid', GContext), # protocol ID for graphics context ('reacts', c_bool), # boolean: TRUE if clipmask is list of rectangles ('dashes', c_bool), # boolean: TRUE if dash-list is really a list ('dirty', c_ulong), # cache dirty bits ('values', XGCValues), # shadow structure of values ] # Screen is defined in X11/Xlib.h class Screen(Structure): _fields_ = [ # XExtData *ext_data; /* hook for extension to hang data */ ('ext_data', c_void_p), # struct _XDisplay *display;/* back pointer to display structure */ ('display', c_void_p), # Window root; /* Root window id. */ ('root', window_t), # int width, height; /* width and height of screen */ ('width', c_int), ('height', c_int), # int mwidth, mheight; /* width and height of in millimeters */ ('mwidth', c_int), ('mheight', c_int), # int ndepths; /* number of depths possible */ ('ndepths', c_int), # Depth *depths; /* list of allowable depths on the screen */ ('depths', c_void_p), # int root_depth; /* bits per pixel */ ('root_depth', c_int), # Visual *root_visual; /* root visual */ ('root_visual', c_void_p), # GC default_gc; /* GC for the root root visual */ ('default_gc', _XGC), # Colormap cmap; /* default color map */ ('cmap', Colormap), # unsigned long white_pixel; ('white_pixel', c_ulong), # unsigned long black_pixel; /* White and Black pixel values */ ('black_pixel', c_ulong), # int max_maps, min_maps; /* max and min color maps */ ('max_maps', c_int), ('min_maps', c_int), # int backing_store; /* Never, WhenMapped, Always */ ('backing_store', c_int), # Bool save_unders; ('save_unders', c_bool), # long root_input_mask; /* initial root input mask */ ('root_input_mask', c_long), ] # From X11/Xdefs.h # typedef unsigned long Atom; Atom = atom_t = c_ulong # ============================================================================ # xdo_t* xdo_new(const char *display); libxdo.xdo_new.argtypes = (c_char_p,) libxdo.xdo_new.restype = POINTER(xdo_t) libxdo.xdo_new.__doc__ = """\ Create a new xdo_t instance. :param display: the string display name, such as ":0". If null, uses the environment variable DISPLAY just like XOpenDisplay(NULL). :return: Pointer to a new xdo_t or NULL on failure """ # ============================================================================ # xdo_t* xdo_new_with_opened_display(Display *xdpy, const char *display, # int close_display_when_freed); libxdo.xdo_new_with_opened_display.__doc__ = """\ Create a new xdo_t instance with an existing X11 Display instance. :param xdpy: the Display pointer given by a previous XOpenDisplay() :param display: the string display name :param close_display_when_freed: If true, we will close the display when xdo_free is called. Otherwise, we leave it open. """ # ============================================================================ # const char *xdo_version(void); libxdo.xdo_version.argtypes = () libxdo.xdo_version.restype = c_char_p libxdo.xdo_version.__doc__ = """\ Return a string representing the version of this library """ # ============================================================================ # void xdo_free(xdo_t *xdo); libxdo.xdo_free.argtypes = (POINTER(xdo_t),) libxdo.xdo_free.__doc__ = """\ Free and destroy an xdo_t instance. If close_display_when_freed is set, then we will also close the Display. """ # ============================================================================ # int xdo_move_mouse(const xdo_t *xdo, int x, int y, int screen); libxdo.xdo_move_mouse.argtypes = ( POINTER(xdo_t), c_int, c_int, c_int) libxdo.xdo_move_mouse.restype = c_int libxdo.xdo_move_mouse.errcheck = _errcheck libxdo.xdo_move_mouse.__doc__ = """ Move the mouse to a specific location. :param x: the target X coordinate on the screen in pixels. :param y: the target Y coordinate on the screen in pixels. :param screen: the screen (number) you want to move on. """ # ============================================================================ # int xdo_move_mouse_relative_to_window(const xdo_t *xdo, # Window window, int x, int y); libxdo.xdo_move_mouse_relative_to_window.argtypes = ( POINTER(xdo_t), POINTER(window_t), c_int, c_int) libxdo.xdo_move_mouse_relative_to_window.restype = c_int libxdo.xdo_move_mouse_relative_to_window.errcheck = _errcheck libxdo.xdo_move_mouse_relative_to_window.__doc__ = """\ Move the mouse to a specific location relative to the top-left corner of a window. :param x: the target X coordinate on the screen in pixels. :param y: the target Y coordinate on the screen in pixels. """ # ============================================================================ # int xdo_move_mouse_relative(const xdo_t *xdo, int x, int y); libxdo.xdo_move_mouse_relative.argtypes = (POINTER(xdo_t), c_int, c_int) libxdo.xdo_move_mouse_relative.restype = c_int libxdo.xdo_move_mouse_relative.errcheck = _errcheck libxdo.xdo_move_mouse_relative.__doc__ = """\ Move the mouse relative to it's current position. :param x: the distance in pixels to move on the X axis. :param y: the distance in pixels to move on the Y axis. """ # ============================================================================ # int xdo_mouse_down(const xdo_t *xdo, Window window, int button); libxdo.xdo_mouse_down.argtypes = (POINTER(xdo_t), window_t, c_int) libxdo.xdo_mouse_down.restype = c_int libxdo.xdo_mouse_down.errcheck = _errcheck libxdo.xdo_mouse_down.__doc__ = """\ Send a mouse press (aka mouse down) for a given button at the current mouse location. :param window: The window you want to send the event to or CURRENTWINDOW :param button: The mouse button. Generally, 1 is left, 2 is middle, 3 is right, 4 is wheel up, 5 is wheel down. """ # ============================================================================ # int xdo_mouse_up(const xdo_t *xdo, Window window, int button); libxdo.xdo_mouse_up.argtypes = (POINTER(xdo_t), window_t, c_int) libxdo.xdo_mouse_up.restype = c_int libxdo.xdo_mouse_up.errcheck = _errcheck libxdo.xdo_mouse_up.__doc__ = """\ Send a mouse release (aka mouse up) for a given button at the current mouse location. :param window: The window you want to send the event to or CURRENTWINDOW :param button: The mouse button. Generally, 1 is left, 2 is middle, 3 is right, 4 is wheel up, 5 is wheel down. """ # ============================================================================ # int xdo_get_mouse_location(const xdo_t *xdo, int *x, int *y, # int *screen_num); libxdo.xdo_get_mouse_location.argtypes = (POINTER(xdo_t), POINTER(c_int), POINTER(c_int), POINTER(c_int)) libxdo.xdo_get_mouse_location.restype = c_int libxdo.xdo_get_mouse_location.errcheck = _errcheck libxdo.xdo_get_mouse_location.__doc__ = """\ Get the current mouse location (coordinates and screen number). :param x: integer pointer where the X coordinate will be stored :param y: integer pointer where the Y coordinate will be stored :param screen_num: integer pointer where the screen number will be stored """ # ============================================================================ # int xdo_get_window_at_mouse(const xdo_t *xdo, Window *window_ret); libxdo.xdo_get_window_at_mouse.argtypes = (POINTER(xdo_t), POINTER(window_t)) libxdo.xdo_get_window_at_mouse.restype = c_int libxdo.xdo_get_window_at_mouse.errcheck = _errcheck libxdo.xdo_get_window_at_mouse.__doc__ = """\ Get the window the mouse is currently over :param window_ret: Winter pointer where the window will be stored. """ # ============================================================================ # int xdo_get_mouse_location2(const xdo_t *xdo, int *x_ret, int *y_ret, # int *screen_num_ret, Window *window_ret); libxdo.xdo_get_mouse_location2.argtypes = ( POINTER(xdo_t), POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(window_t)) libxdo.xdo_get_mouse_location2.restype = c_int libxdo.xdo_get_mouse_location2.errcheck = _errcheck libxdo.xdo_get_mouse_location2.__doc__ = """\ Get all mouse location-related data. If null is passed for any parameter, we simply do not store it. Useful if you only want the 'y' coordinate, for example. :param x: integer pointer where the X coordinate will be stored :param y: integer pointer where the Y coordinate will be stored :param screen_num: integer pointer where the screen number will be stored :param window: Window pointer where the window/client the mouse is over will be stored. """ # ============================================================================ # int xdo_wait_for_mouse_move_from(const xdo_t *xdo, int origin_x, # int origin_y); libxdo.xdo_wait_for_mouse_move_from.argtypes = (POINTER(xdo_t), c_int, c_int) libxdo.xdo_wait_for_mouse_move_from.restype = c_int libxdo.xdo_wait_for_mouse_move_from.errcheck = _errcheck libxdo.xdo_wait_for_mouse_move_from.__doc__ = """ Wait for the mouse to move from a location. This function will block until the condition has been satisified. :param origin_x: the X position you expect the mouse to move from :param origin_y: the Y position you expect the mouse to move from """ # ============================================================================ # int xdo_wait_for_mouse_move_to(const xdo_t *xdo, int dest_x, int dest_y); libxdo.xdo_wait_for_mouse_move_to.argtypes = (POINTER(xdo_t), c_int, c_int) libxdo.xdo_wait_for_mouse_move_to.restype = c_int libxdo.xdo_wait_for_mouse_move_to.errcheck = _errcheck libxdo.xdo_wait_for_mouse_move_to.__doc__ = """\ Wait for the mouse to move to a location. This function will block until the condition has been satisfied. :param dest_x: the X position you expect the mouse to move to :param dest_y: the Y position you expect the mouse to move to """ # ============================================================================ # int xdo_click_window(const xdo_t *xdo, Window window, int button); libxdo.xdo_click_window.argtypes = (POINTER(xdo_t), window_t, c_int) libxdo.xdo_click_window.restype = c_int libxdo.xdo_click_window.errcheck = _errcheck libxdo.xdo_click_window.__doc__ = """\ Send a click for a specific mouse button at the current mouse location. :param window: The window you want to send the event to or CURRENTWINDOW :param button: The mouse button. Generally, 1 is left, 2 is middle, 3 is right, 4 is wheel up, 5 is wheel down. """ # ============================================================================ # int xdo_click_window_multiple(const xdo_t *xdo, Window window, int button, # int repeat, useconds_t delay); libxdo.xdo_click_window_multiple.argtypes = ( POINTER(xdo_t), window_t, c_int, c_int, useconds_t) libxdo.xdo_click_window_multiple.restype = c_int libxdo.xdo_click_window_multiple.errcheck = _errcheck libxdo.xdo_click_window_multiple.__doc__ = """\ Send a one or more clicks for a specific mouse button at the current mouse location. :param window: The window you want to send the event to or CURRENTWINDOW :param button: The mouse button. Generally, 1 is left, 2 is middle, 3 is right, 4 is wheel up, 5 is wheel down. """ # ============================================================================ # int xdo_enter_text_window(const xdo_t *xdo, Window window, # const char *string, useconds_t delay); libxdo.xdo_enter_text_window.argtypes = ( POINTER(xdo_t), window_t, c_char_p, useconds_t) libxdo.xdo_enter_text_window.restype = c_int libxdo.xdo_enter_text_window.errcheck = _errcheck libxdo.xdo_enter_text_window.__doc__ = """ Type a string to the specified window. If you want to send a specific key or key sequence, such as "alt+l", you want instead xdo_send_keysequence_window(...). :param window: The window you want to send keystrokes to or CURRENTWINDOW :param string: The string to type, like "Hello world!" :param delay: The delay between keystrokes in microseconds. 12000 is a decent choice if you don't have other plans. """ # ============================================================================ # int xdo_send_keysequence_window(const xdo_t *xdo, Window window, # const char *keysequence, useconds_t delay); libxdo.xdo_send_keysequence_window.argtypes = ( POINTER(xdo_t), window_t, c_char_p, useconds_t) libxdo.xdo_send_keysequence_window.restype = c_int libxdo.xdo_send_keysequence_window.errcheck = _errcheck libxdo.xdo_send_keysequence_window.__doc__ = """\ Send a keysequence to the specified window. This allows you to send keysequences by symbol name. Any combination of X11 KeySym names separated by '+' are valid. Single KeySym names are valid, too. Examples: "l" "semicolon" "alt+Return" "Alt_L+Tab" If you want to type a string, such as "Hello world." you want to instead use xdo_enter_text_window. :param window: The window you want to send the keysequence to or CURRENTWINDOW :param keysequence: The string keysequence to send. :param delay: The delay between keystrokes in microseconds. """ # ============================================================================ # int xdo_send_keysequence_window_up(const xdo_t *xdo, Window window, # const char *keysequence, useconds_t delay); libxdo.xdo_send_keysequence_window_up.argtypes = ( POINTER(xdo_t), window_t, c_char_p, useconds_t) libxdo.xdo_send_keysequence_window_up.restype = c_int libxdo.xdo_send_keysequence_window_up.errcheck = _errcheck libxdo.xdo_send_keysequence_window_up.__doc__ = """\ Send key release (up) events for the given key sequence. :see: xdo_send_keysequence_window """ # ============================================================================ # int xdo_send_keysequence_window_down(const xdo_t *xdo, Window window, # const char *keysequence, useconds_t delay); libxdo.xdo_send_keysequence_window_down.argtypes = ( POINTER(xdo_t), window_t, c_char_p, useconds_t) libxdo.xdo_send_keysequence_window_down.restype = c_int libxdo.xdo_send_keysequence_window_down.errcheck = _errcheck libxdo.xdo_send_keysequence_window_down.__doc__ = """\ Send key press (down) events for the given key sequence. :see: xdo_send_keysequence_window """ # ============================================================================ # int xdo_send_keysequence_window_list_do(const xdo_t *xdo, Window window, # charcodemap_t *keys, int nkeys, # int pressed, int *modifier, useconds_t delay); libxdo.xdo_send_keysequence_window_list_do.argtypes = ( POINTER(xdo_t), window_t, POINTER(charcodemap_t), c_int, c_int, POINTER(c_int), useconds_t) libxdo.xdo_send_keysequence_window_list_do.restype = c_int libxdo.xdo_send_keysequence_window_list_do.errcheck = _errcheck libxdo.xdo_send_keysequence_window_list_do.__doc__ = """\ Send a series of keystrokes. :param window: The window to send events to or CURRENTWINDOW :param keys: The array of charcodemap_t entities to send. :param nkeys: The length of the keys parameter :param pressed: 1 for key press, 0 for key release. :param modifier: Pointer to integer to record the modifiers activated by the keys being pressed. If NULL, we don't save the modifiers. :param delay: The delay between keystrokes in microseconds. """ # ============================================================================ # int xdo_get_active_keys_to_keycode_list( # const xdo_t *xdo, charcodemap_t **keys, int *nkeys); # --- Note ------------------------------------------------------------- # This seems to be missing in version 3.20140213.1 (Debian Jessie) # but is there in current Git master. # Let's configure it only if it is available (meaning we are using # a recent version of the library) try: libxdo.xdo_get_active_keys_to_keycode_list.argtypes = ( POINTER(xdo_t), POINTER(POINTER(charcodemap_t)), POINTER(c_int)) libxdo.xdo_get_active_keys_to_keycode_list.restype = c_int libxdo.xdo_get_active_keys_to_keycode_list.errcheck = _errcheck libxdo.xdo_get_active_keys_to_keycode_list.__doc__ = """\ Get a list of active keys. Uses XQueryKeymap. :param keys: Pointer to the array of charcodemap_t that will be allocated by this function. :param nkeys: Pointer to integer where the number of keys will be stored. """ except AttributeError: pass # ============================================================================ # int xdo_wait_for_window_map_state(const xdo_t *xdo, Window wid, # int map_state); libxdo.xdo_wait_for_window_map_state.argtypes = ( POINTER(xdo_t), window_t, c_int) libxdo.xdo_wait_for_window_map_state.restype libxdo.xdo_wait_for_window_map_state.errcheck = _errcheck libxdo.xdo_wait_for_window_map_state.__doc__ = """\ Wait for a window to have a specific map state. State possibilities: IsUnmapped - window is not displayed. IsViewable - window is mapped and shown (though may be clipped by windows on top of it) IsUnviewable - window is mapped but a parent window is unmapped. :param wid: the window you want to wait for. :param map_state: the state to wait for. """ # ============================================================================ # Constants for xdo_wait_for_window_size() SIZE_TO = 0 SIZE_FROM = 1 # ============================================================================ # int xdo_wait_for_window_size( # const xdo_t *xdo, Window window, unsigned int width, # unsigned int height, int flags, int to_or_from); libxdo.xdo_wait_for_window_size.argtypes = ( POINTER(xdo_t), window_t, c_uint, c_uint, c_int, c_int) libxdo.xdo_wait_for_window_size.restype = c_int libxdo.xdo_wait_for_window_size.errcheck = _errcheck libxdo.xdo_wait_for_window_size.__doc__ = """\ """ # ============================================================================ # int xdo_move_window(const xdo_t *xdo, Window wid, int x, int y); libxdo.xdo_move_window.argtypes = ( POINTER(xdo_t), window_t, c_int, c_int) libxdo.xdo_move_window.restype = c_int libxdo.xdo_move_window.errcheck = _errcheck libxdo.xdo_move_window.__doc__ = """\ Move a window to a specific location. The top left corner of the window will be moved to the x,y coordinate. :param wid: the window to move :param x: the X coordinate to move to. :param y: the Y coordinate to move to. """ # ============================================================================ # int xdo_translate_window_with_sizehint( # const xdo_t *xdo, Window window, # unsigned int width, unsigned int height, # unsigned int *width_ret, unsigned int *height_ret); libxdo.xdo_translate_window_with_sizehint.argtypes = ( POINTER(xdo_t), window_t, c_uint, c_uint, POINTER(c_uint), POINTER(c_uint)) libxdo.xdo_translate_window_with_sizehint.restype = c_int libxdo.xdo_translate_window_with_sizehint.errcheck = _errcheck libxdo.xdo_translate_window_with_sizehint.__doc__ = """\ Apply a window's sizing hints (if any) to a given width and height. This function wraps XGetWMNormalHints() and applies any resize increment and base size to your given width and height values. :param window: the window to use :param width: the unit width you want to translate :param height: the unit height you want to translate :param width_ret: the return location of the translated width :param height_ret: the return locatino of the translated height """ # ============================================================================ # int xdo_set_window_size( # const xdo_t *xdo, Window wid, int w, int h, int flags); libxdo.xdo_set_window_size.argtypes = ( POINTER(xdo_t), window_t, c_int, c_int, c_int) libxdo.xdo_set_window_size.restype = c_int libxdo.xdo_set_window_size.errcheck = _errcheck libxdo.xdo_set_window_size.__doc__ = """\ Change the window size. :param wid: the window to resize :param w: the new desired width :param h: the new desired height :param flags: if 0, use pixels for units. If SIZE_USEHINTS, then the units will be relative to the window size hints. """ # ============================================================================ # int xdo_set_window_property(const xdo_t *xdo, Window wid, # const char *property, const char *value); libxdo.xdo_set_window_property.argtypes = ( POINTER(xdo_t), window_t, c_char_p, c_char_p) libxdo.xdo_set_window_property.restype = c_int libxdo.xdo_set_window_property.errcheck = _errcheck libxdo.xdo_set_window_property.__doc__ = """\ Change a window property. Example properties you can change are WM_NAME, WM_ICON_NAME, etc. :param wid: The window to change a property of. :param property: the string name of the property. :param value: the string value of the property. """ # ============================================================================ # int xdo_set_window_class(const xdo_t *xdo, Window wid, const char *name, # const char *_class); libxdo.xdo_set_window_class.argtypes = ( POINTER(xdo_t), window_t, c_char_p, c_char_p) libxdo.xdo_set_window_class.restype = c_int libxdo.xdo_set_window_class.errcheck = _errcheck libxdo.xdo_set_window_class.__doc__ = """\ Change the window's classname and or class. :param name: The new class name. If NULL, no change. :param _class: The new class. If NULL, no change. """ # ============================================================================ # int xdo_set_window_urgency (const xdo_t *xdo, Window wid, int urgency); libxdo.xdo_set_window_urgency.argtypes = ( POINTER(xdo_t), window_t, c_int) libxdo.xdo_set_window_urgency.restype = c_int libxdo.xdo_set_window_urgency.errcheck = _errcheck libxdo.xdo_set_window_urgency.__doc__ = """\ Sets the urgency hint for a window. """ # ============================================================================ # int xdo_set_window_override_redirect(const xdo_t *xdo, Window wid, # int override_redirect); libxdo.xdo_set_window_override_redirect.argtypes = ( POINTER(xdo_t), window_t, c_int) libxdo.xdo_set_window_override_redirect.restype = c_int libxdo.xdo_set_window_override_redirect.errcheck = _errcheck libxdo.xdo_set_window_override_redirect.__doc__ = """\ Set the override_redirect value for a window. This generally means whether or not a window manager will manage this window. If you set it to 1, the window manager will usually not draw borders on the window, etc. If you set it to 0, the window manager will see it like a normal application window. """ # ============================================================================ # int xdo_focus_window(const xdo_t *xdo, Window wid); libxdo.xdo_focus_window.argtypes = (POINTER(xdo_t), window_t) libxdo.xdo_focus_window.restype = c_int libxdo.xdo_focus_window.errcheck = _errcheck libxdo.xdo_focus_window.__doc__ = """\ Focus a window. :see: xdo_activate_window :param wid: the window to focus. """ # ============================================================================ # int xdo_raise_window(const xdo_t *xdo, Window wid); libxdo.xdo_raise_window.argtypes = (POINTER(xdo_t), window_t) libxdo.xdo_raise_window.restype = c_int libxdo.xdo_raise_window.errcheck = _errcheck libxdo.xdo_raise_window.__doc__ = """\ Raise a window to the top of the window stack. This is also sometimes termed as bringing the window forward. :param wid: The window to raise. """ # ============================================================================ # int xdo_get_focused_window(const xdo_t *xdo, Window *window_ret); libxdo.xdo_get_focused_window.argtypes = (POINTER(xdo_t), POINTER(window_t)) libxdo.xdo_get_focused_window.restype = c_int libxdo.xdo_get_focused_window.errcheck = _errcheck libxdo.xdo_get_focused_window.__doc__ = """\ Get the window currently having focus. :param window_ret: Pointer to a window where the currently-focused window will be stored. """ # ============================================================================ # int xdo_wait_for_window_focus(const xdo_t *xdo, Window window, # int want_focus); libxdo.xdo_wait_for_window_focus.argtypes = ( POINTER(xdo_t), window_t, c_int) libxdo.xdo_wait_for_window_focus.restype = c_int libxdo.xdo_wait_for_window_focus.errcheck = _errcheck libxdo.xdo_wait_for_window_focus.__doc__ = """\ Wait for a window to have or lose focus. :param window: The window to wait on :param want_focus: If 1, wait for focus. If 0, wait for loss of focus. """ # ============================================================================ # int xdo_get_pid_window(const xdo_t *xdo, Window window); libxdo.xdo_get_pid_window.argtypes = (POINTER(xdo_t), window_t) libxdo.xdo_get_pid_window.restype = c_int libxdo.xdo_get_pid_window.__doc__ = """\ Get the PID owning a window. Not all applications support this. It looks at the _NET_WM_PID property of the window. :param window: the window to query. :return: the process id or 0 if no pid found. """ # ============================================================================ # int xdo_get_focused_window_sane(const xdo_t *xdo, Window *window_ret); libxdo.xdo_get_focused_window_sane.argtypes = ( POINTER(xdo_t), POINTER(window_t)) libxdo.xdo_get_focused_window_sane.restype = c_int libxdo.xdo_get_focused_window_sane.errcheck = _errcheck libxdo.xdo_get_focused_window_sane.__doc__ = """\ Like xdo_get_focused_window, but return the first ancestor-or-self window * having a property of WM_CLASS. This allows you to get the "real" or top-level-ish window having focus rather than something you may not expect to be the window having focused. :param window_ret: Pointer to a window where the currently-focused window will be stored. """ # ============================================================================ # int xdo_activate_window(const xdo_t *xdo, Window wid); libxdo.xdo_activate_window.argtypes = ( POINTER(xdo_t), window_t) libxdo.xdo_activate_window.restype = c_int libxdo.xdo_activate_window.errcheck = _errcheck libxdo.xdo_activate_window.__doc__ = """\ Activate a window. This is generally a better choice than xdo_focus_window for a variety of reasons, but it requires window manager support: - If the window is on another desktop, that desktop is switched to. - It moves the window forward rather than simply focusing it Requires your window manager to support this. Uses _NET_ACTIVE_WINDOW from the EWMH spec. :param wid: the window to activate """ # ============================================================================ # int xdo_wait_for_window_active(const xdo_t *xdo, Window window, int active); libxdo.xdo_wait_for_window_active.argtypes = (POINTER(xdo_t), window_t, c_int) libxdo.xdo_wait_for_window_active.restype = c_int libxdo.xdo_wait_for_window_active.errcheck = _errcheck libxdo.xdo_wait_for_window_active.__doc__ = """\ Wait for a window to be active or not active. Requires your window manager to support this. Uses _NET_ACTIVE_WINDOW from the EWMH spec. :param window: the window to wait on :param active: If 1, wait for active. If 0, wait for inactive. """ # ============================================================================ # int xdo_map_window(const xdo_t *xdo, Window wid); libxdo.xdo_map_window.argtypes = (POINTER(xdo_t), window_t) libxdo.xdo_map_window.restype = c_int libxdo.xdo_map_window.errcheck = _errcheck libxdo.xdo_map_window.__doc__ = """\ Map a window. This mostly means to make the window visible if it is not currently mapped. :param wid: the window to map. """ # ============================================================================ # int xdo_unmap_window(const xdo_t *xdo, Window wid); libxdo.xdo_unmap_window.argtypes = (POINTER(xdo_t), window_t) libxdo.xdo_unmap_window.restype = c_int libxdo.xdo_unmap_window.errcheck = _errcheck libxdo.xdo_unmap_window.__doc__ = """\ Unmap a window :param wid: the window to unmap """ # ============================================================================ # int xdo_minimize_window(const xdo_t *xdo, Window wid); libxdo.xdo_minimize_window.argtypes = (POINTER(xdo_t), window_t) libxdo.xdo_minimize_window.restype = c_int libxdo.xdo_minimize_window.errcheck = _errcheck libxdo.xdo_minimize_window.__doc__ = """\ Minimize a window. """ # ============================================================================ # int xdo_reparent_window(const xdo_t *xdo, Window wid_source, # Window wid_target); libxdo.xdo_reparent_window.argtypes = (POINTER(xdo_t), window_t, window_t) libxdo.xdo_reparent_window.restype = c_int libxdo.xdo_reparent_window.errcheck = _errcheck libxdo.xdo_reparent_window.__doc__ = """\ Reparents a window :param wid_source: the window to reparent :param wid_target: the new parent window """ # ============================================================================ # int xdo_get_window_location(const xdo_t *xdo, Window wid, # int *x_ret, int *y_ret, Screen **screen_ret); libxdo.xdo_get_window_location.argtypes = ( POINTER(xdo_t), window_t, POINTER(c_int), POINTER(c_int), POINTER(Screen)) libxdo.xdo_get_window_location.restype = c_int libxdo.xdo_get_window_location.errcheck = _errcheck libxdo.xdo_get_window_location.__doc__ = """\ Get a window's location. :param wid: the window to query :param x_ret: pointer to int where the X location is stored. If NULL, X is ignored. :param y_ret: pointer to int where the Y location is stored. If NULL, X is ignored. :param screen_ret: Pointer to Screen* where the Screen* the window on is stored. If NULL, this parameter is ignored. """ # ============================================================================ # int xdo_get_window_size(const xdo_t *xdo, Window wid, # unsigned int *width_ret, unsigned int *height_ret); libxdo.xdo_get_window_size.argtypes = ( POINTER(xdo_t), window_t, POINTER(c_uint), POINTER(c_uint)) libxdo.xdo_get_window_size.restype = c_int libxdo.xdo_get_window_size.errcheck = _errcheck libxdo.xdo_get_window_size.__doc__ = """\ Get a window's size. :param wid: the window to query :param width_ret: pointer to unsigned int where the width is stored. :param height_ret: pointer to unsigned int where the height is stored. """ # ============================================================================ # int xdo_get_active_window(const xdo_t *xdo, Window *window_ret); libxdo.xdo_get_active_window.argtypes = (POINTER(xdo_t), POINTER(window_t)) libxdo.xdo_get_active_window.restype = c_int libxdo.xdo_get_active_window.errcheck = _errcheck libxdo.xdo_get_active_window.__doc__ = """\ Get the currently-active window. Requires your window manager to support this. Uses _NET_ACTIVE_WINDOW from the EWMH spec. :param window_ret: Pointer to Window where the active window is stored. """ # ============================================================================ # int xdo_select_window_with_click(const xdo_t *xdo, Window *window_ret); libxdo.xdo_select_window_with_click.argtypes = ( POINTER(xdo_t), POINTER(window_t)) libxdo.xdo_select_window_with_click.restype = c_int libxdo.xdo_select_window_with_click.errcheck = _errcheck libxdo.xdo_select_window_with_click.__doc__ = """\ Get a window ID by clicking on it. This function blocks until a selection is made. :param window_ret: Pointer to Window where the selected window is stored. """ # ============================================================================ # int xdo_set_number_of_desktops(const xdo_t *xdo, long ndesktops); libxdo.xdo_set_number_of_desktops.argtypes = (POINTER(xdo_t), c_long) libxdo.xdo_set_number_of_desktops.restype = c_int libxdo.xdo_set_number_of_desktops.errcheck = _errcheck libxdo.xdo_set_number_of_desktops.__doc__ = """\ Set the number of desktops. Uses _NET_NUMBER_OF_DESKTOPS of the EWMH spec. :param ndesktops: the new number of desktops to set. """ # ============================================================================ # int xdo_get_number_of_desktops(const xdo_t *xdo, long *ndesktops); libxdo.xdo_get_number_of_desktops.argtypes = (POINTER(xdo_t), POINTER(c_long)) libxdo.xdo_get_number_of_desktops.restype = c_int libxdo.xdo_get_number_of_desktops.errcheck = _errcheck libxdo.xdo_get_number_of_desktops.__doc__ = """\ Get the current number of desktops. Uses _NET_NUMBER_OF_DESKTOPS of the EWMH spec. :param ndesktops: pointer to long where the current number of desktops is stored """ # ============================================================================ # int xdo_set_current_desktop(const xdo_t *xdo, long desktop); libxdo.xdo_set_current_desktop.argtypes = (POINTER(xdo_t), c_long) libxdo.xdo_set_current_desktop.restype = c_int libxdo.xdo_set_current_desktop.errcheck = _errcheck libxdo.xdo_set_current_desktop.__doc__ = """\ Switch to another desktop. Uses _NET_CURRENT_DESKTOP of the EWMH spec. :param desktop: The desktop number to switch to. """ # ============================================================================ # int xdo_get_current_desktop(const xdo_t *xdo, long *desktop); libxdo.xdo_get_current_desktop.argtypes = (POINTER(xdo_t), POINTER(c_long)) libxdo.xdo_get_current_desktop.restype = c_int libxdo.xdo_get_current_desktop.errcheck = _errcheck libxdo.xdo_get_current_desktop.__doc__ = """\ Get the current desktop. Uses _NET_CURRENT_DESKTOP of the EWMH spec. :param desktop: pointer to long where the current desktop number is stored. """ # ============================================================================ # int xdo_set_desktop_for_window(const xdo_t *xdo, Window wid, long desktop); libxdo.xdo_set_desktop_for_window.argtypes = (POINTER(xdo_t), window_t, c_long) libxdo.xdo_set_desktop_for_window.restype = c_int libxdo.xdo_set_desktop_for_window.errcheck = _errcheck libxdo.xdo_set_desktop_for_window.__doc__ = """\ Move a window to another desktop Uses _NET_WM_DESKTOP of the EWMH spec. :param wid: the window to move :param desktop: the desktop destination for the window """ # ============================================================================ # int xdo_get_desktop_for_window(const xdo_t *xdo, Window wid, long *desktop); libxdo.xdo_get_desktop_for_window.argtypes = ( POINTER(xdo_t), window_t, POINTER(c_long)) libxdo.xdo_get_desktop_for_window.restype = c_int libxdo.xdo_get_desktop_for_window.errcheck = _errcheck libxdo.xdo_get_desktop_for_window.__doc__ = """\ Get the desktop a window is on. Uses _NET_WM_DESKTOP of the EWMH spec. If your desktop does not support _NET_WM_DESKTOP, then '*desktop' remains unmodified. :param wid: the window to query :param desktop: pointer to long where the desktop of the window is stored """ # ============================================================================ # int xdo_search_windows(const xdo_t *xdo, const xdo_search_t *search, # Window **windowlist_ret, unsigned int *nwindows_ret); libxdo.xdo_search_windows.argtypes = ( POINTER(xdo_t), POINTER(xdo_search_t), POINTER(POINTER(window_t)), POINTER(c_uint)) libxdo.xdo_search_windows.restype = c_int libxdo.xdo_search_windows.errcheck = _errcheck libxdo.xdo_search_windows.__doc__ = """\ Search for windows. :param search: the search query. :param windowlist_ret: the list of matching windows to return :param nwindows_ret: the number of windows (length of windowlist_ret) :see: xdo_search_t """ # ============================================================================ # unsigned char *xdo_get_window_property_by_atom( # const xdo_t *xdo, Window window, Atom atom, # long *nitems, Atom *type, int *size); # todo: fix the ``atom_t`` thing # todo: how to error check this function? NULL pointer return? libxdo.xdo_get_window_property_by_atom.argtypes = ( POINTER(xdo_t), window_t, atom_t, POINTER(c_long), POINTER(atom_t), POINTER(c_int)) libxdo.xdo_get_window_property_by_atom.restype = c_char_p libxdo.xdo_get_window_property_by_atom.__doc__ = """ Generic property fetch. :param window: the window to query :param atom: the Atom to request :param nitems: the number of items :param type: the type of the return :param size: the size of the type :return: data consisting of 'nitems' items of size 'size' and type 'type' will need to be cast to the type before using. """ # ============================================================================ # int xdo_get_window_property( # const xdo_t *xdo, Window window, const char *property, # unsigned char **value, long *nitems, Atom *type, int *size); libxdo.xdo_get_window_property.argtypes = ( POINTER(xdo_t), window_t, c_char_p, POINTER(POINTER(c_ubyte)), POINTER(c_long), POINTER(atom_t), POINTER(c_int)) libxdo.xdo_get_window_property.restype = c_int libxdo.xdo_get_window_property.errcheck = _errcheck libxdo.xdo_get_window_property.__doc__ = """\ Get property of window by name of atom. :param window: the window to query :param property: the name of the atom :param nitems: the number of items :param type: the type of the return :param size: the size of the type :return: data consisting of 'nitems' items of size 'size' and type 'type' will need to be cast to the type before using. """ # ============================================================================ # unsigned int xdo_get_input_state(const xdo_t *xdo); # todo: we need to define constants for the mask! libxdo.xdo_get_input_state.argtypes = (POINTER(xdo_t),) libxdo.xdo_get_input_state.restype = c_uint libxdo.xdo_get_input_state.__doc__ = """ Get the current input state. This is a mask value containing any of the following: ShiftMask, LockMask, ControlMask, Mod1Mask, Mod2Mask, Mod3Mask, Mod4Mask, or Mod5Mask. :return: the input mask """ # ============================================================================ # const char **xdo_get_symbol_map(void); libxdo.xdo_get_symbol_map.argtypes = () libxdo.xdo_get_symbol_map.restype = POINTER(c_char_p) libxdo.xdo_get_symbol_map.__doc__ = """ If you need the symbol map, use this method. The symbol map is an array of string pairs mapping common tokens to X Keysym strings, such as "alt" to "Alt_L" :return: array of strings. """ # ============================================================================ # int xdo_get_active_modifiers(const xdo_t *xdo, charcodemap_t **keys, # int *nkeys); libxdo.xdo_get_active_modifiers.argtypes = ( POINTER(xdo_t), POINTER(POINTER(charcodemap_t)), POINTER(c_int)) libxdo.xdo_get_active_modifiers.restype = c_int libxdo.xdo_get_active_modifiers.errcheck = _errcheck libxdo.xdo_get_active_modifiers.__doc__ = """\ Get a list of active keys. Uses XQueryKeymap. :param keys: Pointer to the array of charcodemap_t that will be allocated by this function. :param nkeys: Pointer to integer where the number of keys will be stored. """ # ============================================================================ # int xdo_clear_active_modifiers(const xdo_t *xdo, Window window, # charcodemap_t *active_mods, # int active_mods_n); libxdo.xdo_clear_active_modifiers.argtypes = ( POINTER(xdo_t), window_t, POINTER(charcodemap_t), c_int) libxdo.xdo_clear_active_modifiers.restype = c_int libxdo.xdo_clear_active_modifiers.errcheck = _errcheck libxdo.xdo_clear_active_modifiers.__doc__ = """\ Send any events necesary to clear the the active modifiers. For example, if you are holding 'alt' when xdo_get_active_modifiers is called, then this method will send a key-up for 'alt' """ # ============================================================================ # int xdo_set_active_modifiers(const xdo_t *xdo, Window window, # charcodemap_t *active_mods, # int active_mods_n); libxdo.xdo_set_active_modifiers.argtypes = ( POINTER(xdo_t), window_t, POINTER(charcodemap_t), c_int) libxdo.xdo_set_active_modifiers.restype = c_int libxdo.xdo_set_active_modifiers.errcheck = _errcheck libxdo.xdo_set_active_modifiers.__doc__ = """\ Send any events necessary to make these modifiers active. This is useful if you just cleared the active modifiers and then wish to restore them after. """ # ============================================================================ # int xdo_get_desktop_viewport(const xdo_t *xdo, int *x_ret, int *y_ret); libxdo.xdo_get_desktop_viewport.argtypes = ( POINTER(xdo_t), POINTER(c_int), POINTER(c_int)) libxdo.xdo_get_desktop_viewport.restype = c_int libxdo.xdo_get_desktop_viewport.errcheck = _errcheck libxdo.xdo_get_desktop_viewport.__doc__ = """\ Get the position of the current viewport. This is only relevant if your window manager supports ``_NET_DESKTOP_VIEWPORT`` """ # ============================================================================ # int xdo_set_desktop_viewport(const xdo_t *xdo, int x, int y); libxdo.xdo_set_desktop_viewport.argtypes = ( POINTER(xdo_t), c_int, c_int) libxdo.xdo_set_desktop_viewport.restype = c_int libxdo.xdo_set_desktop_viewport.errcheck = _errcheck libxdo.xdo_set_desktop_viewport.__doc__ = """\ Set the position of the current viewport. This is only relevant if your window manager supports ``_NET_DESKTOP_VIEWPORT`` """ # ============================================================================ # int xdo_kill_window(const xdo_t *xdo, Window window); libxdo.xdo_kill_window.argtypes = ( POINTER(xdo_t), window_t) libxdo.xdo_kill_window.restype = c_int libxdo.xdo_kill_window.errcheck = _errcheck libxdo.xdo_kill_window.__doc__ = """\ Kill a window and the client owning it. """ # ============================================================================ # Constants for xdo_find_window_client() # Find a client window that is a parent of the window given XDO_FIND_PARENTS = 0 # Find a client window that is a child of the window given XDO_FIND_CHILDREN = 1 # ============================================================================ # int xdo_find_window_client(const xdo_t *xdo, Window window, # Window *window_ret, int direction); libxdo.xdo_find_window_client.argtypes = ( POINTER(xdo_t), window_t, POINTER(window_t), c_int) libxdo.xdo_find_window_client.restype = c_int libxdo.xdo_find_window_client.errcheck = _errcheck libxdo.xdo_find_window_client.__doc__ = """\ Find a client window (child) in a given window. Useful if you get the window manager's decorator window rather than the client window. """ # ============================================================================ # int xdo_get_window_name(const xdo_t *xdo, Window window, # unsigned char **name_ret, int *name_len_ret, # int *name_type); libxdo.xdo_get_window_name.argtypes = ( POINTER(xdo_t), window_t, POINTER(c_char_p), POINTER(c_int), POINTER(c_int)) libxdo.xdo_get_window_name.restype = c_int libxdo.xdo_get_window_name.errcheck = _errcheck libxdo.xdo_get_window_name.__doc__ = """\ Get a window's name, if any. TODO(sissel): Document """ # ============================================================================ # void xdo_disable_feature(xdo_t *xdo, int feature); libxdo.xdo_disable_feature.argtypes = (POINTER(xdo_t), c_int) libxdo.xdo_disable_feature.restype = None libxdo.xdo_disable_feature.__doc__ = """\ Disable an xdo feature. This function is mainly used by libxdo itself, however, you may find it useful in your own applications. :see: XDO_FEATURES """ # ============================================================================ # void xdo_enable_feature(xdo_t *xdo, int feature); libxdo.xdo_enable_feature.argtypes = (POINTER(xdo_t), c_int) libxdo.xdo_enable_feature.restype = None libxdo.xdo_enable_feature.__doc__ = """\ Enable an xdo feature. This function is mainly used by libxdo itself, however, you may find it useful in your own applications. :see: XDO_FEATURES """ # ============================================================================ # int xdo_has_feature(xdo_t *xdo, int feature); libxdo.xdo_has_feature.argtypes = (POINTER(xdo_t), c_int) libxdo.xdo_has_feature.restype = c_int libxdo.xdo_has_feature.errcheck = _errcheck libxdo.xdo_has_feature.__doc__ = """\ Check if a feature is enabled. This function is mainly used by libxdo itself, however, you may find it useful in your own applications. :see: XDO_FEATURES """ # ============================================================================ # int xdo_get_viewport_dimensions(xdo_t *xdo, unsigned int *width, # unsigned int *height, int screen); libxdo.xdo_get_viewport_dimensions.argtypes = ( POINTER(xdo_t), POINTER(c_uint), POINTER(c_uint), c_int) libxdo.xdo_get_viewport_dimensions.restype = c_int libxdo.xdo_get_viewport_dimensions.errcheck = _errcheck libxdo.xdo_get_viewport_dimensions.__doc__ = """\ Query the viewport (your display) dimensions If Xinerama is active and supported, that api internally is used. If Xineram is disabled, we will report the root window's dimensions for the given screen. """ # ============================================================================ # void XFree(void *data); libX11.XFree.argtypes = (c_void_p,) libX11.XFree.restype = None libX11.XFree.__doc__ = """\ The XFree function is a general-purpose Xlib routine that frees the specified data. You must use it to free any objects that were allocated by Xlib, unless an alternate function is explicitly specified for the object. A NULL pointer cannot be passed to this function. :param data: Specifies the pointer to data that is to be freed """ # ============================================================================ # typedef int (*XErrorHandler) ( /* WARNING, this type not in Xlib spec */ # Display* /* display */, # XErrorEvent* /* error_event */ # ); XErrorHandler = ctypes.CFUNCTYPE(c_int, POINTER(XErrorEvent)) # ============================================================================ <file_sep># -*- coding: utf-8 -*- import ctypes import os from collections import namedtuple from ctypes import POINTER from six.moves import range from .xdo import libX11 as _libX11 from .xdo import libxdo as _libxdo from .xdo import ( # noqa CURRENTWINDOW, SEARCH_CLASS, SEARCH_CLASSNAME, SEARCH_DESKTOP, SEARCH_NAME, SEARCH_ONLYVISIBLE, SEARCH_PID, SEARCH_SCREEN, SEARCH_TITLE, Atom, Screen, XdoException, XErrorHandler, charcodemap_t, window_t, xdo_search_t) mouse_location = namedtuple('mouse_location', 'x,y,screen_num') mouse_location2 = namedtuple('mouse_location2', 'x,y,screen_num,window') window_location = namedtuple('window_location', 'x,y,screen') window_size = namedtuple('window_size', 'width,height') input_mask = namedtuple('input_mask', 'shift,lock,control,mod1,mod2,mod3,mod4,mod5') # noqa # Mouse button constants MOUSE_LEFT = 1 MOUSE_MIDDLE = 2 MOUSE_RIGHT = 3 MOUSE_WHEEL_UP = 4 MOUSE_WHEEL_DOWN = 5 # Keyboard modifiers MOD_Shift = 1 << 0 MOD_Lock = 1 << 1 MOD_Control = 1 << 2 MOD_Mod1 = 1 << 3 MOD_Mod2 = 1 << 4 MOD_Mod3 = 1 << 5 MOD_Mod4 = 1 << 6 MOD_Mod5 = 1 << 7 def _gen_input_mask(mask): """Generate input mask from bytemask""" return input_mask( shift=bool(mask & MOD_Shift), lock=bool(mask & MOD_Lock), control=bool(mask & MOD_Control), mod1=bool(mask & MOD_Mod1), mod2=bool(mask & MOD_Mod2), mod3=bool(mask & MOD_Mod3), mod4=bool(mask & MOD_Mod4), mod5=bool(mask & MOD_Mod5)) class XError(Exception): pass class Xdo(object): def __init__(self, display=None): if display is None: display = os.environ.get('DISPLAY', '') display = display.encode('utf-8') self._xdo = _libxdo.xdo_new(display) def _handle_x_error(evt): # todo: handle errors in a nicer way, eg. try getting error message raise XError('Event: {}'.format(evt)) self._error_handler = XErrorHandler(_handle_x_error) _libX11.XSetErrorHandler(self._error_handler) @classmethod def version(cls): return _libxdo.xdo_version() @classmethod def version_info(cls): return tuple(int(x) for x in cls.version().split(b'.')) def move_mouse(self, x, y, screen=0): """ Move the mouse to a specific location. :param x: the target X coordinate on the screen in pixels. :param y: the target Y coordinate on the screen in pixels. :param screen: the screen (number) you want to move on. """ # todo: apparently the "screen" argument is not behaving properly # and sometimes even making the interpreter crash.. # Figure out why (changed API / using wrong header?) # >>> xdo.move_mouse(3000,200,1) # X Error of failed request: BadWindow (invalid Window parameter) # Major opcode of failed request: 41 (X_WarpPointer) # Resource id in failed request: 0x2a4fca0 # Serial number of failed request: 25 # Current serial number in output stream: 26 # Just to be safe.. # screen = 0 x = ctypes.c_int(x) y = ctypes.c_int(y) screen = ctypes.c_int(screen) _libxdo.xdo_move_mouse(self._xdo, x, y, screen) def move_mouse_relative_to_window(self, window, x, y): """ Move the mouse to a specific location relative to the top-left corner of a window. :param x: the target X coordinate on the screen in pixels. :param y: the target Y coordinate on the screen in pixels. """ _libxdo.xdo_move_mouse_relative_to_window( self._xdo, ctypes.c_ulong(window), x, y) def move_mouse_relative(self, x, y): """ Move the mouse relative to it's current position. :param x: the distance in pixels to move on the X axis. :param y: the distance in pixels to move on the Y axis. """ _libxdo.xdo_move_mouse_relative(self._xdo, x, y) def mouse_down(self, window, button): """ Send a mouse press (aka mouse down) for a given button at the current mouse location. :param window: The window you want to send the event to or CURRENTWINDOW :param button: The mouse button. Generally, 1 is left, 2 is middle, 3 is right, 4 is wheel up, 5 is wheel down. """ _libxdo.xdo_mouse_down( self._xdo, ctypes.c_ulong(window), ctypes.c_int(button)) def mouse_up(self, window, button): """ Send a mouse release (aka mouse up) for a given button at the current mouse location. :param window: The window you want to send the event to or CURRENTWINDOW :param button: The mouse button. Generally, 1 is left, 2 is middle, 3 is right, 4 is wheel up, 5 is wheel down. """ _libxdo.xdo_mouse_up( self._xdo, ctypes.c_ulong(window), ctypes.c_int(button)) def get_mouse_location(self): """ Get the current mouse location (coordinates and screen number). :return: a namedtuple with ``x``, ``y`` and ``screen_num`` fields """ x = ctypes.c_int(0) y = ctypes.c_int(0) screen_num = ctypes.c_int(0) _libxdo.xdo_get_mouse_location( self._xdo, ctypes.byref(x), ctypes.byref(y), ctypes.byref(screen_num)) return mouse_location(x.value, y.value, screen_num.value) def get_window_at_mouse(self): """ Get the window the mouse is currently over """ window_ret = ctypes.c_ulong(0) _libxdo.xdo_get_window_at_mouse(self._xdo, ctypes.byref(window_ret)) return window_ret.value def get_mouse_location2(self): """ Get all mouse location-related data. :return: a namedtuple with ``x``, ``y``, ``screen_num`` and ``window`` fields """ x = ctypes.c_int(0) y = ctypes.c_int(0) screen_num_ret = ctypes.c_ulong(0) window_ret = ctypes.c_ulong(0) _libxdo.xdo_get_mouse_location2( self._xdo, ctypes.byref(x), ctypes.byref(y), ctypes.byref(screen_num_ret), ctypes.byref(window_ret)) return mouse_location2(x.value, y.value, screen_num_ret.value, window_ret.value) def wait_for_mouse_move_from(self, origin_x, origin_y): """ Wait for the mouse to move from a location. This function will block until the condition has been satisified. :param origin_x: the X position you expect the mouse to move from :param origin_y: the Y position you expect the mouse to move from """ _libxdo.xdo_wait_for_mouse_move_from(self._xdo, origin_x, origin_y) def wait_for_mouse_move_to(self, dest_x, dest_y): """ Wait for the mouse to move to a location. This function will block until the condition has been satisified. :param dest_x: the X position you expect the mouse to move to :param dest_y: the Y position you expect the mouse to move to """ _libxdo.xdo_wait_for_mouse_move_from(self._xdo, dest_x, dest_y) def click_window(self, window, button): """ Send a click for a specific mouse button at the current mouse location. :param window: The window you want to send the event to or CURRENTWINDOW :param button: The mouse button. Generally, 1 is left, 2 is middle, 3 is right, 4 is wheel up, 5 is wheel down. """ _libxdo.xdo_click_window(self._xdo, window, button) def click_window_multiple(self, window, button, repeat=2, delay=100000): """ Send a one or more clicks for a specific mouse button at the current mouse location. :param window: The window you want to send the event to or CURRENTWINDOW :param button: The mouse button. Generally, 1 is left, 2 is middle, 3 is right, 4 is wheel up, 5 is wheel down. :param repeat: number of repetitions (default: 2) :param delay: delay between clicks, in microseconds (default: 100k) """ _libxdo.xdo_click_window_multiple( self._xdo, window, button, repeat, delay) def enter_text_window(self, window, string, delay=12000): """ Type a string to the specified window. If you want to send a specific key or key sequence, such as "alt+l", you want instead ``send_keysequence_window(...)``. :param window: The window you want to send keystrokes to or CURRENTWINDOW :param string: The string to type, like "Hello world!" :param delay: The delay between keystrokes in microseconds. 12000 is a decent choice if you don't have other plans. """ return _libxdo.xdo_enter_text_window(self._xdo, window, string, delay) def send_keysequence_window(self, window, keysequence, delay=12000): """ Send a keysequence to the specified window. This allows you to send keysequences by symbol name. Any combination of X11 KeySym names separated by '+' are valid. Single KeySym names are valid, too. Examples: "l" "semicolon" "alt+Return" "Alt_L+Tab" If you want to type a string, such as "Hello world." you want to instead use xdo_enter_text_window. :param window: The window you want to send the keysequence to or CURRENTWINDOW :param keysequence: The string keysequence to send. :param delay: The delay between keystrokes in microseconds. """ _libxdo.xdo_send_keysequence_window( self._xdo, window, keysequence, delay) def send_keysequence_window_up(self, window, keysequence, delay=12000): """Send key release (up) events for the given key sequence""" _libxdo.xdo_send_keysequence_window_up( self._xdo, window, keysequence, ctypes.c_ulong(delay)) def send_keysequence_window_down(self, window, keysequence, delay=12000): """Send key press (down) events for the given key sequence""" _libxdo.xdo_send_keysequence_window_down( self._xdo, window, keysequence, ctypes.c_ulong(delay)) def send_keysequence_window_list_do( self, window, keys, pressed=1, modifier=None, delay=120000): """ Send a series of keystrokes. :param window: The window to send events to or CURRENTWINDOW :param keys: The array of charcodemap_t entities to send. :param pressed: 1 for key press, 0 for key release. :param modifier: Pointer to integer to record the modifiers activated by the keys being pressed. If NULL, we don't save the modifiers. :param delay: The delay between keystrokes in microseconds. """ # todo: how to properly use charcodes_t in a nice way? _libxdo.xdo_send_keysequence_window_list_do( self._xdo, window, keys, len(keys), pressed, modifier, delay) def get_active_keys_to_keycode_list(self): """Get a list of active keys. Uses XQueryKeymap""" try: _libxdo.xdo_get_active_keys_to_keycode_list except AttributeError: # Apparently, this was implemented in a later version.. raise NotImplementedError() keys = POINTER(charcodemap_t) nkeys = ctypes.c_int(0) _libxdo.xdo_get_active_keys_to_keycode_list( self._xdo, ctypes.byref(keys), ctypes.byref(nkeys)) # todo: make sure this returns a list of charcodemap_t! return keys.value def wait_for_window_map_state(self, window, state): """ Wait for a window to have a specific map state. State possibilities: IsUnmapped - window is not displayed. IsViewable - window is mapped and shown (though may be clipped by windows on top of it) IsUnviewable - window is mapped but a parent window is unmapped. :param window: the window you want to wait for. :param state: the state to wait for. """ _libxdo.xdo_wait_for_window_map_state(self._xdo, window, state) def wait_for_window_size(self, window, width, height, flags, to_or_from): _libxdo.xdo_wait_for_window_size(self._xdo) def wait_for_window_size_to(self, window, width, height, flags=0): return self.wait_for_window_size(window, width, height, flags, 0) def wait_for_window_size_from(self, window, width, height, flags=0): return self.wait_for_window_size(window, width, height, flags, 1) def move_window(self, window, x, y): """ Move a window to a specific location. The top left corner of the window will be moved to the x,y coordinate. :param wid: the window to move :param x: the X coordinate to move to. :param y: the Y coordinate to move to. """ _libxdo.xdo_move_window(self._xdo, window, x, y) def translate_window_with_sizehint(self, window, width, height): """ Apply a window's sizing hints (if any) to a given width and height. This function wraps XGetWMNormalHints() and applies any resize increment and base size to your given width and height values. :param window: the window to use :param width: the unit width you want to translate :param height: the unit height you want to translate :return: (width, height) """ width_ret = ctypes.c_uint(0) height_ret = ctypes.c_uint(0) _libxdo.xdo_translate_window_with_sizehint( self._xdo, window, width, height, ctypes.byref(width_ret), ctypes.byref(height_ret)) return width_ret.value, height_ret.value def set_window_size(self, window, w, h, flags=0): """ Change the window size. :param wid: the window to resize :param w: the new desired width :param h: the new desired height :param flags: if 0, use pixels for units. If SIZE_USEHINTS, then the units will be relative to the window size hints. """ _libxdo.xdo_set_window_size(self._xdo, window, w, h, flags) def set_window_property(self, window, name, value): """ Change a window property. Example properties you can change are WM_NAME, WM_ICON_NAME, etc. :param wid: The window to change a property of. :param name: the string name of the property. :param value: the string value of the property. """ _libxdo.xdo_set_window_property(self._xdo, window, name, value) def set_window_class(self, window, name, class_): """ Change the window's classname and or class. :param name: The new class name. If ``None``, no change. :param class_: The new class. If ``None``, no change. """ _libxdo.xdo_set_window_class(self._xdo, window, name, class_) def set_window_urgency(self, window, urgency): """Sets the urgency hint for a window""" _libxdo.xdo_set_window_urgency(self._xdo, window, urgency) def set_window_override_redirect(self, window, override_redirect): """ Set the override_redirect value for a window. This generally means whether or not a window manager will manage this window. If you set it to 1, the window manager will usually not draw borders on the window, etc. If you set it to 0, the window manager will see it like a normal application window. """ _libxdo.xdo_set_window_override_redirect( self._xdo, window, override_redirect) def focus_window(self, window): """ Focus a window. :see: xdo_activate_window :param wid: the window to focus. """ _libxdo.xdo_focus_window(self._xdo, window) def raise_window(self, window): """ Raise a window to the top of the window stack. This is also sometimes termed as bringing the window forward. :param wid: The window to raise. """ _libxdo.xdo_raise_window(self._xdo, window) def get_focused_window(self): """ Get the window currently having focus. :param window_ret: Pointer to a window where the currently-focused window will be stored. """ window_ret = window_t(0) _libxdo.xdo_get_focused_window(self._xdo, ctypes.byref(window_ret)) return window_ret.value def wait_for_window_focus(self, window, want_focus): """ Wait for a window to have or lose focus. :param window: The window to wait on :param want_focus: If 1, wait for focus. If 0, wait for loss of focus. """ _libxdo.xdo_wait_for_window_focus(self._xdo, window, want_focus) def get_pid_window(self, window): """ Get the PID owning a window. Not all applications support this. It looks at the ``_NET_WM_PID`` property of the window. :param window: the window to query. :return: the process id or 0 if no pid found. """ # todo: if the pid is 0, it means "not found" -> exception? return _libxdo.xdo_get_pid_window(self._xdo, window) def get_focused_window_sane(self): """ Like xdo_get_focused_window, but return the first ancestor-or-self window * having a property of WM_CLASS. This allows you to get the "real" or top-level-ish window having focus rather than something you may not expect to be the window having focused. :param window_ret: Pointer to a window where the currently-focused window will be stored. """ window_ret = window_t(0) _libxdo.xdo_get_focused_window_sane( self._xdo, ctypes.byref(window_ret)) return window_ret.value def activate_window(self, window): """ Activate a window. This is generally a better choice than xdo_focus_window for a variety of reasons, but it requires window manager support: - If the window is on another desktop, that desktop is switched to. - It moves the window forward rather than simply focusing it Requires your window manager to support this. Uses _NET_ACTIVE_WINDOW from the EWMH spec. :param wid: the window to activate """ _libxdo.xdo_activate_window(self._xdo, window) def wait_for_window_active(self, window, active=1): """ Wait for a window to be active or not active. Requires your window manager to support this. Uses _NET_ACTIVE_WINDOW from the EWMH spec. :param window: the window to wait on :param active: If 1, wait for active. If 0, wait for inactive. """ _libxdo.xdo_wait_for_window_active(self._xdo, window, active) def map_window(self, window): """ Map a window. This mostly means to make the window visible if it is not currently mapped. :param wid: the window to map. """ _libxdo.xdo_map_window(self._xdo, window) def unmap_window(self, window): """ Unmap a window :param wid: the window to unmap """ _libxdo.xdo_unmap_window(self._xdo, window) def minimize_window(self, window): """Minimize a window""" _libxdo.xdo_minimize_window(self._xdo, window) def reparent_window(self, window_source, window_target): """ Reparents a window :param wid_source: the window to reparent :param wid_target: the new parent window """ _libxdo.xdo_reparent_window(self._xdo, window_source, window_target) def get_window_location(self, window): """ Get a window's location. """ screen_ret = Screen() x_ret = ctypes.c_int(0) y_ret = ctypes.c_int(0) _libxdo.xdo_get_window_location( self._xdo, window, ctypes.byref(x_ret), ctypes.byref(y_ret), ctypes.byref(screen_ret)) return window_location(x_ret.value, y_ret.value, screen_ret) def get_window_size(self, window): """ Get a window's size. """ w_ret = ctypes.c_uint(0) h_ret = ctypes.c_uint(0) _libxdo.xdo_get_window_size(self._xdo, window, ctypes.byref(w_ret), ctypes.byref(h_ret)) return window_size(w_ret.value, h_ret.value) def get_active_window(self): """ Get the currently-active window. Requires your window manager to support this. Uses ``_NET_ACTIVE_WINDOW`` from the EWMH spec. """ window_ret = window_t(0) _libxdo.xdo_get_active_window(self._xdo, ctypes.byref(window_ret)) return window_ret.value def select_window_with_click(self): """ Get a window ID by clicking on it. This function blocks until a selection is made. """ window_ret = window_t(0) _libxdo.xdo_select_window_with_click( self._xdo, ctypes.byref(window_ret)) return window_ret.value def set_number_of_desktops(self, ndesktops): """ Set the number of desktops. Uses ``_NET_NUMBER_OF_DESKTOPS`` of the EWMH spec. :param ndesktops: the new number of desktops to set. """ _libxdo.xdo_set_number_of_desktops(self._xdo, ndesktops) def get_number_of_desktops(self): """ Get the current number of desktops. Uses ``_NET_NUMBER_OF_DESKTOPS`` of the EWMH spec. :param ndesktops: pointer to long where the current number of desktops is stored """ ndesktops = ctypes.c_long(0) _libxdo.xdo_get_number_of_desktops(self._xdo, ctypes.byref(ndesktops)) return ndesktops.value def set_current_desktop(self, desktop): """ Switch to another desktop. Uses ``_NET_CURRENT_DESKTOP`` of the EWMH spec. :param desktop: The desktop number to switch to. """ _libxdo.xdo_set_current_desktop(self._xdo, desktop) def get_current_desktop(self): """ Get the current desktop. Uses ``_NET_CURRENT_DESKTOP`` of the EWMH spec. """ desktop = ctypes.c_long(0) _libxdo.xdo_get_current_desktop(self._xdo, ctypes.byref(desktop)) return desktop.value def set_desktop_for_window(self, window, desktop): """ Move a window to another desktop Uses _NET_WM_DESKTOP of the EWMH spec. :param wid: the window to move :param desktop: the desktop destination for the window """ _libxdo.xdo_set_desktop_for_window(self._xdo, window, desktop) def get_desktop_for_window(self, window): """ Get the desktop a window is on. Uses _NET_WM_DESKTOP of the EWMH spec. If your desktop does not support ``_NET_WM_DESKTOP``, then '*desktop' remains unmodified. :param wid: the window to query """ desktop = ctypes.c_long(0) _libxdo.xdo_get_desktop_for_window( self._xdo, window, ctypes.byref(desktop)) return desktop.value def search_windows( self, winname=None, winclass=None, winclassname=None, pid=None, only_visible=False, screen=None, require=False, searchmask=0, desktop=None, limit=0, max_depth=-1): """ Search for windows. :param winname: Regexp to be matched against window name :param winclass: Regexp to be matched against window class :param winclassname: Regexp to be matched against window class name :param pid: Only return windows from this PID :param only_visible: If True, only return visible windows :param screen: Search only windows on this screen :param require: If True, will match ALL conditions. Otherwise, windows matching ANY condition will be returned. :param searchmask: Search mask, for advanced usage. Leave this alone if you don't kwnow what you are doing. :param limit: Maximum number of windows to list. Zero means no limit. :param max_depth: Maximum depth to return. Defaults to -1, meaning "no limit". :return: A list of window ids matching query. """ windowlist_ret = ctypes.pointer(window_t(0)) nwindows_ret = ctypes.c_uint(0) search = xdo_search_t(searchmask=searchmask) if winname is not None: search.winname = winname search.searchmask |= SEARCH_NAME if winclass is not None: search.winclass = winclass search.searchmask |= SEARCH_CLASS if winclassname is not None: search.winclassname = winclassname search.searchmask |= SEARCH_CLASSNAME if pid is not None: search.pid = pid search.searchmask |= SEARCH_PID if only_visible: search.only_visible = True search.searchmask |= SEARCH_ONLYVISIBLE if screen is not None: search.screen = screen search.searchmask |= SEARCH_SCREEN if screen is not None: search.screen = desktop search.searchmask |= SEARCH_DESKTOP search.limit = limit search.max_depth = max_depth _libxdo.xdo_search_windows( self._xdo, search, ctypes.byref(windowlist_ret), ctypes.byref(nwindows_ret)) return [windowlist_ret[i] for i in range(nwindows_ret.value)] def get_window_property_by_atom(self, window, atom): # todo: figure out what exactly this method does, and implement it raise NotImplemented( "get_window_property_by_atom() is not implemented (yet)") def get_window_property(self, window, name): value = ctypes.POINTER(ctypes.c_ubyte)() # unsigned char **value nitems = ctypes.c_long() type_ = Atom() size = ctypes.c_int(0) _libxdo.xdo_get_window_property( self._xdo, window, name, ctypes.byref(value), ctypes.byref(nitems), ctypes.byref(type_), ctypes.byref(size)) # todo: we need to convert atoms into their actual type.. values = [] for i in range(nitems.value): i_val = value[i] # i_type = type_[i] values.append(i_val) # todo: perform type conversion for "Atom"s of this type? # todo: how does the "Atom" thing work? _libX11.XFree(value) return values def get_input_state(self): """ Get the current input state. :return: a namedtuple with the following (boolean) fields: shift, lock, control, mod1, mod2, mod3, mod4, mod5 """ mask = _libxdo.xdo_get_input_state(self._xdo) return _gen_input_mask(mask) def get_symbol_map(self): """ If you need the symbol map, use this method. The symbol map is an array of string pairs mapping common tokens to X Keysym strings, such as "alt" to "Alt_L" :return: array of strings. """ # todo: make sure we return a list of strings! sm = _libxdo.xdo_get_symbol_map() # Return value is like: # ['alt', 'Alt_L', ..., None, None, None, ...] # We want to return only values up to the first None. # todo: any better solution than this? i = 0 ret = [] while True: c = sm[i] if c is None: return ret ret.append(c) i += 1 def get_active_modifiers(self): """ Get a list of active keys. Uses XQueryKeymap. :return: list of charcodemap_t instances """ keys = ctypes.pointer(charcodemap_t()) nkeys = ctypes.c_int(0) _libxdo.xdo_get_active_modifiers( self._xdo, ctypes.byref(keys), ctypes.byref(nkeys)) return [keys[i] for i in range(nkeys.value)] def clear_active_modifiers(self, window, mods=None): """ Send any events necesary to clear the the active modifiers. For example, if you are holding 'alt' when xdo_get_active_modifiers is called, then this method will send a key-up for 'alt' """ raise NotImplementedError() def set_active_modifiers(self, window, mods=None): """ Send any events necessary to make these modifiers active. This is useful if you just cleared the active modifiers and then wish to restore them after. """ raise NotImplementedError() def get_desktop_viewport(self): """ Get the position of the current viewport. This is only relevant if your window manager supports ``_NET_DESKTOP_VIEWPORT``. """ raise NotImplementedError() def set_desktop_viewport(self, x, y): """ Set the position of the current viewport. This is only relevant if your window manager supports ``_NET_DESKTOP_VIEWPORT`` """ raise NotImplementedError() def kill_window(self): """ Kill a window and the client owning it. """ raise NotImplementedError() XDO_FIND_PARENTS = 0 XDO_FIND_CHILDREN = 1 def find_window_client(self): """ Find a client window (child) in a given window. Useful if you get the window manager's decorator window rather than the client window. """ raise NotImplementedError() def get_window_name(self, win_id): """ Get a window's name, if any. """ window = window_t(win_id) name_ptr = ctypes.c_char_p() name_len = ctypes.c_int(0) name_type = ctypes.c_int(0) _libxdo.xdo_get_window_name( self._xdo, window, ctypes.byref(name_ptr), ctypes.byref(name_len), ctypes.byref(name_type)) name = name_ptr.value _libX11.XFree(name_ptr) # Free the string allocated by Xlib return name def enable_feature(self): """ Enable an xdo feature. This function is mainly used by libxdo itself, however, you may find it useful in your own applications. :see: XDO_FEATURES """ raise NotImplementedError() def has_feature(self): """ Check if a feature is enabled. This function is mainly used by libxdo itself, however, you may find it useful in your own applications. :see: XDO_FEATURES """ raise NotImplementedError() def get_viewport_dimensions(self): """ Query the viewport (your display) dimensions If Xinerama is active and supported, that api internally is used. If Xineram is disabled, we will report the root window's dimensions for the given screen. """ raise NotImplementedError() def __del__(self): _libxdo.xdo_free(self._xdo)
30e810a234021775e2107c5fa7b4e8bfb01ef732
[ "Python", "reStructuredText" ]
4
Python
user202729/python-libxdo-ng
80d4fc3977fdd9c8995bf08104dd7bab1be39807
b08174290b39b5d00aee1f2bcf7e54eabfde7f82
refs/heads/master
<repo_name>rlaneyjr/VimBox<file_sep>/uninstall-script.sh #!/usr/bin/env bash PWD=$(pwd) # Make sure that if we happen to be running in cygwin the symlinks will get setup correctly. # Make sure to enable develoepr more before installing export CYGWIN="$CYGWIN winsymlinks:nativestrict" if [[ -f "$PWD/dotVimRc" && ! -L "$PWD/dotVimRc" ]]; then if [[ -L "$HOME/.vim" && -d "$HOME/.vim_backup" ]]; then echo -e "Removing symlink ~/.vim" unlink ~/.vim elif [[ -d "$HOME/.vim" && -d "$HOME/.vim_backup" ]]; then echo -e "Backing up ~/.vim to ~/temp/vim_backup" mv ~/.vim ~/temp/vim_backup fi if [[ -d "$HOME/.vim_backup" && ! -d "$HOME/.vim" ]]; then echo -e "Moving ~/.vim_backup back to ~/.vim" mv ~/.vim_backup ~/.vim else echo "Not restoring $HOME/.vim - it has already been restored, or a backup does not exist" fi # This is where neovim likes its config to be stored. # Inside of our .vim directory, we already have a sym link from init.vim to # .vimrc, so all we have to do is setup the directory for neovim. if [[ -L "$HOME/.config/nvim" && -d "$HOME/.config/nvim_backup" ]]; then echo -e "Removing symlink ~/.config/nvim" unlink ~/.config/nvim elif [[ -d "$HOME/.config/nvim" && -d "$HOME/.config/nvim_backup" ]]; then echo -e "Backing up ~/.config/nvim to ~/temp/nvim_backup" mv ~/.config/nvim ~/temp/nvim_backup fi if [[ -d "$HOME/.config/nvim_backup" && ! -d "$HOME/.config/nvim" ]]; then echo -e "Moving ~/.config/nvim_backup back to ~/.config/nvim" mv ~/.config/nvim_backup ~/.config/nvim else echo "Not restoring $HOME/.config/nvim - it has already been restored, or a backup does not exist" fi # .vimrc is a file, use the -f flag if [[ -L "$HOME/.vimrc" && -f "$HOME/.dotfiles/vimrc" ]]; then echo -e "Removing symlink ~/.vimrc" unlink ~/.vimrc elif [[ -f "$HOME/.vimrc" && -f "$HOME/.vimrc_backup" ]]; then echo -e "Backing up ~/.vimrc to ~/temp/vimrc_backup" mv ~/.vimrc ~/temp/vimrc_backup fi if [[ -f "$HOME/.vimrc_backup" && ! -f "$HOME/.vimrc" ]]; then echo -e "Moving ~/.vimrc_backup back to ~/.vimrc" mv ~/.vimrc_backup ~/.vimrc elif [[ -f "$HOME/.dotfiles/vimrc" && ! -L "$HOME/.vimrc" ]]; then echo -e "Creating symlink ~/.vimrc from ~/.dotfiles/vimrc" ln -s ~/.dotfiles/vimrc ~/.vimrc else echo "Not restoring $HOME/.vimrc - it has already been restored, or a backup does not exist" fi # .gvimrc is a file, use the -f flag if [[ -L "$HOME/.gvimrc" && -f "$HOME/.dotfiles/gvimrc" ]]; then echo -e "Removing symlink ~/.gvimrc" unlink ~/.gvimrc elif [[ -f "$HOME/.gvimrc" && -f "$HOME/.gvimrc_backup" ]]; then echo -e "Backing up ~/.gvimrc to ~/temp/gvimrc_backup" mv ~/.gvimrc ~/temp/gvimrc_backup fi if [[ -f "$HOME/.gvimrc_backup" && ! -f "$HOME/.gvimrc" ]]; then echo -e "Moving ~/.gvimrc_backup back to ~/.gvimrc" mv ~/.gvimrc_backup ~/.gvimrc elif [[ -f "$HOME/.dotfiles/gvimrc" && ! -L "$HOME/.gvimrc" ]]; then echo -e "Creating symlink ~/.gvimrc from ~/.dotfiles/gvimrc" ln -s ~/.dotfiles/gvimrc ~/.gvimrc else echo "Not restoring $HOME/.gvimrc - it has already been restored, or a backup does not exist" fi if [[ -f "$HOME/.dotfiles/vimrc.bundles" && ! -L "$HOME/.vimrc.bundles" ]]; then echo -e "Creating symlink ~/.vimrc.bundles from ~/.dotfiles/vimrc.bundles" ln -s ~/.dotfiles/vimrc.bundles ~/.vimrc.bundles else echo -e "No vimrc.bundles or already linked" fi if [[ -f "$HOME/.dotfiles/vimrc_background" && ! -L "$HOME/.vimrc_background" ]]; then echo -e "Creating symlink ~/.vimrc_background from ~/.dotfiles/vimrc_background" ln -s ~/.dotfiles/vimrc_background ~/.vimrc_background else echo -e "No vimrc_background or already linked" fi # Leave the fonts #if [ -d "$HOME/Library/Fonts" ]; then # FONT_SOURCE="$PWD/dotVim/Fonts/Iosevka/iosevka-regular.ttf" # FONT_DEST="$HOME/Library/Fonts/iosevka-regular.ttf" # if [[ ! -f "$FONT_DEST" ]]; then # echo -e "Installing font $FONT_SOURCE into $FONT_DEST" # cp "$FONT_SOURCE" "$FONT_DEST" # else # echo -e "The font $FONT_DEST was already installed" # fi # FONT_SOURCE="$PWD/dotVim/Fonts/Iosevka/iosevka-bold.ttf" # FONT_DEST="$HOME/Library/Fonts/iosevka-bold.ttf" # if [[ ! -f "$FONT_DEST" ]]; then # echo -e "Installing font $FONT_SOURCE into $FONT_DEST" # cp "$FONT_SOURCE" "$FONT_DEST" # else # echo -e "The font $FONT_DEST was already installed" # fi # FONT_SOURCE="$PWD/dotVim/Fonts/Iosevka/iosevka-italic.ttf" # FONT_DEST="$HOME/Library/Fonts/iosevka-italic.ttf" # if [[ ! -f "$FONT_DEST" ]]; then # echo -e "Installing font $FONT_SOURCE into $FONT_DEST" # cp "$FONT_SOURCE" "$FONT_DEST" # else # echo -e "The font $FONT_DEST was already installed" # fi #fi else echo -e "It seems you are not running the installer from within the VimBox root" exit 1 fi
af94c23be19c9d88de89d2d07e0836d9a48665e7
[ "Shell" ]
1
Shell
rlaneyjr/VimBox
70903938bf793cf8047413967e353f893228afc1
a95352cae225d8aae2cb0a8a8402f5833e0a1f37
refs/heads/master
<file_sep>/* * The MIT License (MIT) * * Copyright (c) 2014 <NAME> * mailto:<EMAIL> */ package timetable.webapp; import timetable.webapp.kaffee.KaffeePage; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.markup.html.panel.Panel; /** * */ public class NavigationPanel extends Panel { public NavigationPanel(String id) { super(id); add(new Link("navigateHelloWorld") { @Override public void onClick() { setResponsePage(HelloWorldPage.class); } }); add(new Link("navigateKaffee") { @Override public void onClick() { setResponsePage(KaffeePage.class); } }); } }<file_sep>/* * The MIT License (MIT) * * Copyright (c) 2014 <NAME> * mailto:<EMAIL> */ package timetable.webapp; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.markup.html.basic.Label; /** * */ public class HelloWorldPage extends WebPage { public HelloWorldPage() { super(); add(new Label("<NAME>", "Spengergasse")); } } <file_sep>package timetable.domain; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import org.junit.After; import org.junit.Before; import org.junit.Test; public class TortenTest { private EntityManagerFactory entityManagerFactory; private EntityManager entityManager; @Before public void setup() { entityManagerFactory = Persistence .createEntityManagerFactory("spengergassePU"); entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); } @After public void teardown() { if (entityManager != null) entityManager.getTransaction().commit(); if (entityManager != null) entityManager.close(); if (entityManagerFactory != null) entityManagerFactory.close(); } @Test public void testMe() { Torte torte = new Torte("Sachertorte",5,1,20.0f,10.0f); entityManager.persist(torte); } } <file_sep>package timetable.domain; import java.util.ArrayList; import java.util.Date; import timetablee.Ensure; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Null; import javax.validation.constraints.Size; @Entity @Table(name = "kunde") public class Kunde extends BasePersistable { private static final long serialVersionUID = -6667520361999134030L; @Size(max = 255) @NotNull @Column(name = "name", nullable = false, length = 255) private String name; @Temporal(TemporalType.DATE) @NotNull @Column(name = "birth_date", nullable = false) private Date birthDate; @Size(max = 255) @NotNull @Column(name = "adresse", nullable = false, length = 255) private String adresse; @Size(max = 255) @NotNull @Column(name = "ort", nullable = false, length = 255) private String ort; @Size(max = 255) @NotNull @Column(name = "plz", nullable = false, length = 255) private String plz; protected Kunde() { // required for JPA } public Kunde(String name, Date birthDate, String adresse, String ort, String plz) { Ensure.notEmpty("name", name); Ensure.notNull("birthDate", birthDate); Ensure.notEmpty("adresse", adresse); Ensure.notEmpty("ort", ort); Ensure.notEmpty("plz", plz); this.name = name; this.birthDate = (Date)birthDate.clone(); this.adresse = adresse; this.ort = ort; this.plz = plz; } public String getName() { return name; } public Date getBirthDate() { return (Date)birthDate.clone(); } public String getOrt() { return ort; } public void setOrt(String ort) { this.ort = ort; } public String getPlz() { return plz; } public void setPlz(String plz) { this.plz = plz; } public void setName(String name) { this.name = name; } } <file_sep>/* * The MIT License (MIT) * * Copyright (c) 2013 <NAME> * mailto:<EMAIL> */ package timetable.service; import timetable.domain.Kaffee; import timetable.repository.KaffeeRepository; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * All uses cases for the timetable management. */ @Service public class KaffeeManagementService { @Autowired private KaffeeRepository kaffeeRepository; @Transactional public void createNewKaffee(String name, float preis, String menge, String herkunft, String art, float alterBohne) { // start transaction // write audit log Kaffee kaffee = new Kaffee(name,preis,menge,herkunft,art,alterBohne); kaffeeRepository.save(kaffee); // end (commit) transaction } } <file_sep> package timetable.domain; import java.util.Arrays; import java.util.Collection; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) public class TortenConstructorTest { private final String bezeichnung; private final Integer zutaten; private final Integer menge; private final Float groesse; private final Float preis; public TortenConstructorTest(String bezeichnung, Integer zutaten, Integer menge, Float groesse, Float preis) { this.bezeichnung = bezeichnung; this.zutaten = zutaten; this.menge = menge; this.groesse = groesse; this.preis = preis; } @Parameterized.Parameters public static Collection<Object[]> data() { Object[][] data = new Object[][]{ // {"Sachertorte",null,5,10.0f,3.0f}, // {null,3,5,10.0f,3.0f}, {"Sachertorte",3,5,null,3.0f}, {"Sachertorte",3,null,10.0f,3.0f}, {"Sachertorte",3,5,10.0f,null} }; return Arrays.asList(data); } @Test(expected = IllegalArgumentException.class) public void whenCreatingWithNullArguments() { new Torte( this.bezeichnung, this.zutaten, this.menge, this.groesse, this.preis); } } <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>spengergasse</groupId> <artifactId>fdisk</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2</version> </dependency> <!-- Hibernate --> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.0-api</artifactId> <version>1.0.1.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.2.6.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.2.6.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.0.1.Final</version> </dependency> <!-- connection pool & h2 database --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.3.175</version> </dependency> <!-- Logging --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.5</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>1.0.13</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.0.13</version> </dependency> <!-- Spring framework --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>1.5.0.RC1</version> </dependency> <dependency> <groupId>org.springframework.hateoas</groupId> <artifactId>spring-hateoas</artifactId> <version>0.9.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-commons</artifactId> <version>1.7.0.RC1</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2.2</version> </dependency> <!-- Spring web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring data --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-rest-core</artifactId> <version>2.0.0.RC1</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-rest-webmvc</artifactId> <version>2.0.0.RC1</version> </dependency> <!-- QueryDSL --> <dependency> <groupId>com.mysema.querydsl</groupId> <artifactId>querydsl-core</artifactId> <version>${querydsl.version}</version> </dependency> <dependency> <groupId>com.mysema.querydsl</groupId> <artifactId>querydsl-apt</artifactId> <version>${querydsl.version}</version> </dependency> <dependency> <groupId>com.mysema.querydsl</groupId> <artifactId>querydsl-jpa</artifactId> <version>${querydsl.version}</version> </dependency> <!-- Wicket --> <dependency> <groupId>org.apache.wicket</groupId> <artifactId>wicket-core</artifactId> <version>6.14.0</version> </dependency> <dependency> <groupId>org.apache.wicket</groupId> <artifactId>wicket-spring</artifactId> <version>6.14.0</version> </dependency> <dependency> <groupId>org.apache.wicket</groupId> <artifactId>wicket-bootstrap</artifactId> <version>0.16</version> </dependency> <!-- Web --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- Testing --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>1.8.4</version> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-library</artifactId> <version>1.3</version> </dependency> <dependency> <groupId>javassist</groupId> <artifactId>javassist</artifactId> <version>3.12.1.GA</version> </dependency> </dependencies> <properties> <jdk.version>1.7</jdk.version> <jacoco.version>0.6.4.201312101107</jacoco.version> <jacoco.ut.execution.data.file>${project.build.directory}/coverage-reports/jacoco-ut.exec </jacoco.ut.execution.data.file> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>3.2.7.RELEASE</spring.version> <querydsl.version>3.3.0</querydsl.version> </properties> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <verbose>true</verbose> <!-- <fork>true</fork> --> <compilerVersion>${jdk.version}</compilerVersion> <source>${jdk.version}</source> <target>${jdk.version}</target> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.6</version> <configuration> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>${jacoco.version}</version> <executions> <!-- Prepares the property pointing to the JaCoCo runtime agent which is passed as VM argument when Maven the Surefire plugin is executed. --> <execution> <id>pre-unit-test</id> <phase>pre-integration-test</phase> <goals> <goal>prepare-agent</goal> </goals> <configuration> <!-- Sets the path to the file which contains the execution data. --> <destFile>${jacoco.ut.execution.data.file}</destFile> <!-- Sets the name of the property containing the settings for JaCoCo runtime agent. --> <propertyName>surefireArgLine</propertyName> </configuration> </execution> </executions> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.16</version> <dependencies> <dependency> <groupId>org.apache.maven.surefire</groupId> <artifactId>surefire-junit47</artifactId> <version>2.16</version> </dependency> </dependencies> <configuration> <!-- Sets the VM argument line used when unit tests are run. --> <argLine>${surefireArgLine}</argLine> <includes> <include>**/*.java</include> </includes> <parallel>classes</parallel> <threadCount>1</threadCount> </configuration> </plugin> <plugin> <groupId>com.mysema.maven</groupId> <artifactId>maven-apt-plugin</artifactId> <version>1.0.4</version> <executions> <execution> <goals> <goal>process</goal> </goals> <configuration> <outputDirectory>target/generated-sources/java</outputDirectory> <processor>com.mysema.query.apt.jpa.JPAAnnotationProcessor</processor> </configuration> </execution> </executions> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>2.5</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.1</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.1</version> </plugin> <plugin> <artifactId>maven-jar-plugin</artifactId> <version>2.4</version> </plugin> <plugin> <artifactId>maven-site-plugin</artifactId> <version>3.3</version> </plugin> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.1.1.v20140108</version> </plugin> </plugins> </build> <reporting> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-report-plugin</artifactId> <version>2.16</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jxr-plugin</artifactId> <version>2.1</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.8</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.9.1</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-changes-plugin</artifactId> <version>2.9</version> </plugin> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.6.3.201306030806</version> <configuration> <!-- Sets the path to the file which contains the execution data. --> <dataFile>${jacoco.ut.execution.data.file}</dataFile> <!-- Sets the output directory for the code coverage report. --> <outputDirectory>${project.reporting.outputDirectory}/jacoco-ut</outputDirectory> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>2.10</version> <configuration> <configLocation>config/sun_checks.xml</configLocation> <!-- <configLocation>src/main/check/checkstyle.xml</configLocation> --> <!-- <packageNamesLocation>com/mycompany/checks/packagenames.xml</packageNamesLocation> --> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-pmd-plugin</artifactId> <version>3.0.1</version> <configuration> <sourceEncoding>${project.build.sourceEncoding}</sourceEncoding> <minimumTokens>100</minimumTokens> <targetJdk>1.7</targetJdk> <!-- <excludes> <exclude>**/*Bean.java</exclude> <exclude>**/generated/*.java</exclude> </excludes> <excludeRoots> <excludeRoot>target/generated-sources/stubs</excludeRoot> </excludeRoots> --> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>findbugs-maven-plugin</artifactId> <version>2.5.2</version> </plugin> </plugins> </reporting> <repositories> <repository> <id>spring-milestones</id> <url>http://repo.springsource.org/libs-milestone/</url> </repository> </repositories> </project><file_sep>package timetable.repository; import org.springframework.data.repository.CrudRepository; import timetable.domain.Kaffee; public interface KaffeeRepository extends CrudRepository<Kaffee, Long>{ Kaffee findByName(String name); } <file_sep>package timetable.service; public interface ServiceFactory { } <file_sep>/* * The MIT License (MIT) * * Copyright (c) 2013 <NAME> * mailto:<EMAIL> */ package timetable.webapp; import timetable.domain.DomainConfiguration; import timetable.repository.RepositoryConfiguration; import timetable.rest.RestPackage; import timetable.service.ServiceConfiguration; import javax.sql.DataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; @Import(value = {DomainConfiguration.class, RepositoryConfiguration.class, ServiceConfiguration.class}) @Configuration public class WebappApplicationConfig { @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build(); } } <file_sep>/* * Jumio Inc. * * Copyright (C) 2010 - 2011 * All rights reserved. */ package timetable.repositoryjpa; import timetable.domain.Torte; import java.util.List; import javax.persistence.EntityManager; import org.springframework.stereotype.Repository; @Repository public class TortenJpaRepository extends AbstractJpaRepository<Torte> { @Override public List<Torte> findAll() { return entityManager().createQuery("SELECT tt FROM Torte tt", Torte.class).getResultList(); } @Override public Torte findById(Long id) { return entityManager().find(Torte.class, id); } } //subject<file_sep>/* * Jumio Inc. * * Copyright (C) 2010 - 2011 * All rights reserved. */ package timetable.repositoryjpa; import timetable.domain.Kaffee; import java.util.List; import javax.persistence.EntityManager; import org.springframework.stereotype.Repository; @Repository public class KaffeeJpaRepository extends AbstractJpaRepository<Kaffee> { public List<Kaffee> findAll() { return entityManager().createQuery("SELECT kf FROM Kaffee kf", Kaffee.class).getResultList(); } public Kaffee findById(Long id) { return entityManager().find(Kaffee.class, id); } } //SchoolClass<file_sep>/* * The MIT License (MIT) * * Copyright (c) 2014 <NAME> * mailto:<EMAIL> */ package timetable.webapp.kaffee; import timetable.webapp.KaffeeManagementPage; import org.apache.wicket.Component; /** * */ public class KaffeePage extends KaffeeManagementPage { protected Component contentPanel() { return new KaffeePanel("kaffeePanel"); } }
5c6f1d755cc99492dc6648cd708b4bc13823e5c9
[ "Java", "Maven POM" ]
13
Java
sch14035/projectUpdate27032014
22454459b351386d35b43096c6de045bb8a75c1e
c91f5ef64ee826426cd6047133e32ad0e59ab29a
refs/heads/master
<file_sep>package TP2.ASD.Expr; import TP2.ASD.Int; import TP2.ASD.Program; import TP2.ASD.Type; import TP2.Llvm; import TP2.SymbolTable; import TP2.TypeException; import TP2.Utils; public class VarExpression extends Expression { Type type; String ident; public VarExpression(Type type, String ident) { this.ident = ident; this.type = type; } @Override public String pp() { return ident; } @Override public RetExpression toIR() throws TypeException { SymbolTable.Symbol var = Program.symbolTable.lookup(ident); if(var == null) { throw new TypeException("You must declare variable " + ident + " before using it !"); } String result = Utils.newtmp(); Llvm.IR ir = new Llvm.IR(Llvm.empty(), Llvm.empty()).appendCode(new Llvm.Load(type.toLlvmType(), ident, result)); return new RetExpression(ir, type, result); } } <file_sep>package TP2.ASD; import TP2.Llvm; import TP2.SymbolTable; import TP2.TypeException; import java.util.ArrayList; import java.util.List; public class Proto extends Function { String name; Type type; List<String> args; public Proto(String name, Type type, List<String> args) { this.name = name; this.type = type; this.args = args; } public String pp() { String s = "PROTO " + type.pp() + " " + name + "("; if (args.size() > 0) { for (String argument : args) { s += argument + ","; } s = s.substring(0, s.length() - 1); } return s + ")"; } public Llvm.IR toIR() throws TypeException { List<SymbolTable.VariableSymbol> a = new ArrayList<>(); for (String arg : args) { a.add(new SymbolTable.VariableSymbol(new Int(), arg)); } Program.symbolTable.add(new SymbolTable.FunctionSymbol(type, name, a, false)); return new Llvm.IR(Llvm.empty(), Llvm.empty()); } } <file_sep>package TP2; import java.util.List; import java.util.ArrayList; // This file contains a simple LLVM IR representation // and methods to generate its string representation public class Llvm { static public class IR { List<Instruction> header; // IR instructions to be placed before the code (global definitions) List<Instruction> code; // main code public List<Instruction> getCode() { return code; } public IR(List<Instruction> header, List<Instruction> code) { this.header = header; this.code = code; } // append an other IR public IR append(IR other) { header.addAll(other.header); code.addAll(other.code); return this; } // append a code instruction public IR appendCode(Instruction inst) { code.add(inst); return this; } // append a code header public IR appendHeader(Instruction inst) { header.add(inst); return this; } // Final string generation public String toString() { // This header describe to LLVM the target // and declare the external function printf StringBuilder r = new StringBuilder("; Target\n" + "target triple = \"x86_64-unknown-linux-gnu\"\n" + "; External declaration of the printf function\n" + "declare i32 @printf(i8* noalias nocapture, ...)\n" + "\n; Actual code begins\n\n"); for (Instruction inst : header) r.append(inst); r.append("\n\n"); // We create the function main for (Instruction inst : code) { r.append(inst); } return r.toString(); } } // Returns a new empty list of instruction, handy static public List<Instruction> empty() { return new ArrayList<>(); } // LLVM Types static public abstract class Type { public abstract String toString(); } static public class Int extends Type { public String toString() { return "i32"; } } static public class Void extends Type { public String toString() { return "void"; } } // LLVM IR Instructions static public abstract class Instruction { public abstract String toString(); } static public class Add extends Instruction { Type type; String left; String right; String lvalue; public Add(Type type, String left, String right, String lvalue) { this.type = type; this.left = left; this.right = right; this.lvalue = lvalue; } public String toString() { return lvalue + " = add " + type + " " + left + ", " + right + "\n"; } } static public class Return extends Instruction { Type type; String value; public Return(Type type, String value) { this.type = type; this.value = value; } public String toString() { if (type instanceof Int) { return "ret " + type + " " + value + "\n"; } else { return "ret " + type + "\n"; } } } static public class Sub extends Instruction { Type type; String left; String right; String lvalue; public Sub(Type type, String left, String right, String lvalue) { this.type = type; this.left = left; this.right = right; this.lvalue = lvalue; } public String toString() { return lvalue + " = sub " + type + " " + left + ", " + right + "\n"; } } static public class Mul extends Instruction { Type type; String left; String right; String lvalue; public Mul(Type type, String left, String right, String lvalue) { this.type = type; this.left = left; this.right = right; this.lvalue = lvalue; } public String toString() { return lvalue + " = mul " + type + " " + left + ", " + right + "\n"; } } static public class Div extends Instruction { Type type; String left; String right; String lvalue; public Div(Type type, String left, String right, String lvalue) { this.type = type; this.left = left; this.right = right; this.lvalue = lvalue; } public String toString() { return lvalue + " = div " + type + " " + left + ", " + right + "\n"; } } static public class Store extends Instruction { Type type; String var; String value; public Store(Type type, String var, String value) { this.type = type; this.var = var; this.value = value; } public String toString() { return "store " + type + " " + value + ", " + type + "* " + var + "\n"; } } static public class Alloca extends Instruction { Type type; String var; public Alloca(Type type, String var) { this.type = type; this.var = var; } @Override public String toString() { return "%" + var + "= alloca " + type + "\n"; } } static public class Load extends Instruction { Type type; String var; String lvalue; public Load(Type type, String var, String lvalue) { this.type = type; this.var = var; this.lvalue = lvalue; } @Override public String toString() { return lvalue + " = load " + type + ", " + type + "* %" + var + "\n"; } } static public class BrLabel extends Instruction { String name; public BrLabel(String name) { this.name = name; } @Override public String toString() { return "br label %" + name + "\n"; } } static public class BrIf extends Instruction { String condName; String trueLabel; String falseLabel; public BrIf(String condName, String trueLabel, String falseLabel) { this.condName = condName; this.trueLabel = trueLabel; this.falseLabel = falseLabel; } @Override public String toString() { return "br i1 " + condName + ", label %" + trueLabel + ", label %" + falseLabel + "\n"; } } static public class Label extends Instruction { String name; public Label(String name) { this.name = name; } @Override public String toString() { return "\n" + name + ":\n"; } } static public class Argument { Type type; String name; public Argument(Type type, String name) { this.type = type; this.name = name; } @Override public String toString() { return type + " " + name; } } static public class Function extends Instruction { String name; Type type; List<Argument> arguments; List<Instruction> block; public Function(String name, Type type, List<Argument> arguments, List<Instruction> block) { this.name = name; this.type = type; this.arguments = arguments; this.block = block; } @Override public String toString() { String s = "define " + type + " @" + name + "("; if (arguments.size() > 0) { for (Argument argument : arguments) { s += argument + ", "; } s = s.substring(0, s.length() - 2); } s += ") {\n"; block.add(new Return(type, "0")); for (Instruction instruction : block) { s += "\t" + instruction; } return s + "}"; } } static public class Call extends Instruction { Type type; String name; List<Argument> arguments; String lvalue; public Call(Type type, String name, List<Argument> arguments, String lvalue) { this.type = type; this.name = name; this.arguments = arguments; this.lvalue = lvalue; } @Override public String toString() { String s = lvalue + " = call " + type + " @" + name + "("; if (arguments.size() > 0) { for (Argument argument : arguments) { s += argument + ", "; } s = s.substring(0, s.length()-2); } return s + ")\n"; } } } <file_sep>package TP2.ASD.Expr; import TP2.ASD.Program; import TP2.ASD.Type; import TP2.Llvm; import TP2.SymbolTable; import TP2.TypeException; import TP2.Utils; import java.util.ArrayList; import java.util.List; public class FuncExpression extends Expression { Type type; String name; List<Expression> arguments; @Override public String pp() { String s = name + "("; if (arguments.size() > 0) { for (Expression argument : arguments) { s += argument.pp() + ", "; } s = s.substring(0, s.length()-2); } return s + ")"; } @Override public RetExpression toIR() throws TypeException { SymbolTable.Symbol var = Program.symbolTable.lookup(name); if(var == null) { throw new TypeException("You must declare variable " + name + " before using it !"); } List<Llvm.Argument> args = new ArrayList<>(); Llvm.IR ir = new Llvm.IR(Llvm.empty(), Llvm.empty()); RetExpression ret; for (Expression argument : arguments) { ret = argument.toIR(); ir.append(ret.ir); args.add(new Llvm.Argument(ret.type.toLlvmType(), ret.result)); } String result = Utils.newtmp(); ir.appendCode(new Llvm.Call(type.toLlvmType(), name, args, result)); return new RetExpression(ir, type, result); } } <file_sep>package TP2.ASD; import TP2.ASD.Expr.Expression.*; import TP2.ASD.Expr.Expression; import TP2.Llvm; import TP2.Llvm.*; import TP2.TypeException; public class Return extends Instruction { Expression expr; public Return(Expression expr) { this.expr = expr; } @Override public String pp() { return "RETURN " + expr.pp(); } @Override public Llvm.IR toIR() throws TypeException { RetExpression ret = expr.toIR(); ret.ir.appendCode(new Llvm.Return(ret.type.toLlvmType(), ret.result)); return ret.ir; } } <file_sep>package TP2.ASD; import TP2.Llvm; import TP2.TypeException; public class Print extends Instruction { @Override public String pp() { return "PRINT"; } @Override public Llvm.IR toIR() throws TypeException { return new Llvm.IR(Llvm.empty(), Llvm.empty()); } }
2f153a115df7125257bdb0d5eec4db12126f2d5a
[ "Java" ]
6
Java
Hamrod/PDS-TP2
f630e164258638022107ae2734f66671c1610f5b
0cd04a296788db73f87086447d94aa5c2e194ba0
refs/heads/master
<file_sep><?php $file_name = $_GET["q"]; if(!preg_match('/[a-z_]+/',$file_name)) { echo "Bad format"; return; } if(strlen($file_name) > 20) { echo "Bad format"; return; } if(file_exists($file_name)) { touch($file_name); echo "OK"; } else { echo "Not found"; } ?> <file_sep><?php function check_condition($name,$condition) { if(isset($condition->touched)) { $atime = fileatime($name); if($atime < time() - $condition->touched) { return false; } } return true; } function perform_action($action, $action_data) { switch($action) { case "mail": case "email": $recipient = $action_data->recipient; $subject = $action_data->subject; $message = $action_data->message; mail($recipient, $subject, $message); break; } } function process_rule($rule) { $name = $rule->name; $conditions = $rule->conditions; $ok = true; foreach($conditions as $condition) { if(!check_condition($name,$condition)) { $ok = false; } } if(!$ok) { perform_action($rule->action, $rule->action_data); } } function main() { if(!file_exists('rules.json')) { return; } $rules = json_decode(file_get_contents('rules.json')); foreach($rules as $rule) { process_rule($rule); } } main(); ?>
675d5afc496886551444536fbdaf62e69b5823ef
[ "PHP" ]
2
PHP
jittat/easy_noti
c0c3cbb47dd393e1bd0f7a9d3b7c477a0f921332
26c65ce80905ef2e47acfac9200e176e2b81781c
refs/heads/master
<repo_name>KenTsuRinn/rindexer<file_sep>/src/reader/node_reader.rs use crate::model::iprovider::IProvider; use crate::model::ireader::IReader; use crate::model::node::Node; fn line_process<'red>(num: usize, contents: String) -> Vec<Node<u8>> { let nodes = contents.split(' ').map(|x| { return Node::new(num, x.to_string()); }).collect(); nodes } pub struct U8ByteReader<'red> { provider: &'red dyn IProvider, line_hooks: Vec<&'red dyn Fn(usize, String) -> Vec<Node<u8>>>, } impl<'red> U8ByteReader<'red> { pub fn new(provider: &'red dyn IProvider) -> U8ByteReader<'red> { return U8ByteReader { provider, line_hooks: vec![ &line_process ], }; } } impl<'red> IReader<Node<u8>> for U8ByteReader<'red> { fn get_nodes(&self) -> Vec<Node<u8>> { let contents = self.provider.contents(); let mut line_counter: usize = 0; let mut nodes: Vec<Node<u8>> = vec![]; for line in contents.lines() { for hook in &self.line_hooks { let mut n = hook(line_counter, line.to_string()); line_counter += 1; nodes.append(&mut n); } } nodes } } <file_sep>/src/model/iprovider.rs pub trait IProvider { fn contents(&self) -> String; }<file_sep>/src/model/mod.rs pub mod iprovider; pub mod ireader; pub mod node;<file_sep>/src/test/physics_file_reader_test.rs #[cfg(test)] mod physics_file_reader_test { use crate::model::{iprovider, ireader}; use crate::model::node::Node; use crate::provider::physics_file_provider::PhysicsFileProvider; use crate::reader::node_reader::U8ByteReader; #[test] fn test_get_line_vec() { let provider: &dyn iprovider::IProvider = &PhysicsFileProvider::new("./data/health.txt"); let contents = provider.contents(); assert_eq!(contents.is_empty(), false); } #[test] fn test_get_nodes() { let provider: PhysicsFileProvider = PhysicsFileProvider::new("./data/health.txt"); let reader: &dyn ireader::IReader<Node<u8>> = &U8ByteReader::new(&provider); let nodes = reader.get_nodes(); assert_eq!(nodes.is_empty(), false); assert_eq!(nodes[0].line, 0); } } <file_sep>/src/model/ireader.rs pub trait IReader<T> { fn get_nodes(&self) -> Vec<T>; } <file_sep>/README.md # rindexer <hr/> * write indexer by rust, just for fun. <file_sep>/src/provider/physics_file_provider.rs use std::fs::File; use std::io::Read; use std::path::Path; use crate::model::iprovider::IProvider; pub struct PhysicsFileProvider<'pro> { path: &'pro Path, } impl<'pro> PhysicsFileProvider<'pro> { pub fn new(path: &'pro str) -> PhysicsFileProvider<'pro> { if path.is_empty() { panic!("invalid path.") } let p: &'pro Path = Path::new(path); return PhysicsFileProvider { path: p, }; } } impl<'pro> IProvider for PhysicsFileProvider<'pro> { fn contents(&self) -> String { if !self.path.exists() { panic!("file not found."); } let mut file = File::open(self.path).unwrap(); let mut contents = String::new(); file.read_to_string(&mut contents).unwrap(); contents } }<file_sep>/src/main.rs mod model; mod provider; mod reader; mod test; fn main() { println!("Hello, world!"); } <file_sep>/src/model/node.rs pub struct Node<T> { pub line: usize, pub bytes: Vec<T>, } impl Node<u8> { pub fn new(line: usize, contents: String) -> Node<u8> { return Node { line, bytes: contents.chars().map(|c| c as u8).collect::<Vec<u8>>(), }; } }
0184dfc6098dd855cacdc8c1270a255019f447d1
[ "Markdown", "Rust" ]
9
Rust
KenTsuRinn/rindexer
3863888c6140d4d57a6423f38e2e57d08e78f64d
3dfe5601f810320f7b261fc21e8d9c2ecf58951b
refs/heads/master
<file_sep>package com.fhqb.poi; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; /** * 第一个简单的POI编程 * @author zhangyu */ public class POITest01 { public static void main(String[] args) throws IOException { //①创建Excel文件对象:HSSFWorkbook HSSFWorkbook hssfWorkbook = new HSSFWorkbook(); //②创建工作区 HSSFSheet hssfSheet = hssfWorkbook.createSheet("工作区01"); //③创建行 HSSFRow hssfRow = hssfSheet.createRow(0); //④创建单元格 HSSFCell cell = hssfRow.createCell(5); cell.setCellValue("我的第一个单元格"); //⑤生成Excel文件 FileOutputStream fos = new FileOutputStream("good.xls"); hssfWorkbook.write(fos); } } <file_sep>package com.fbhq.poi; import java.io.FileOutputStream; import java.io.IOException; import java.util.Calendar; import java.util.Date; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFDataFormat; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; /** * 给单元格设置格式和列宽 */ public class POITest03 { public static void main(String[] args) throws IOException { HSSFWorkbook hssfWorkbook = new HSSFWorkbook(); HSSFSheet hssfSheet = hssfWorkbook.createSheet("工作区01"); HSSFRow hssfRow = hssfSheet.createRow(0); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ HSSFDataFormat hssfDataFormat = hssfWorkbook.createDataFormat(); //创建Excel格式对象 HSSFCellStyle dateCellStyle = hssfWorkbook.createCellStyle(); dateCellStyle.setDataFormat(hssfDataFormat.getFormat("yyyy-MM-dd HH:mm:ss")); //设置日期格式 HSSFCellStyle numberCellStyle = hssfWorkbook.createCellStyle(); numberCellStyle.setDataFormat(hssfDataFormat.getFormat("#,#.00000")); //设置数值格式 HSSFCellStyle wrapCellStyle = hssfWorkbook.createCellStyle(); wrapCellStyle.setWrapText(true);//设置回绕文本风格样式,自动换行 //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //--------------------------------------- HSSFCell cell00 = hssfRow.createCell(0); cell00.setCellValue("我的第一个单元格"); HSSFCell cell01 = hssfRow.createCell(1); cell01.setCellValue(false); HSSFCell cell02 = hssfRow.createCell(2); cell02.setCellValue(Calendar.getInstance()); cell02.setCellStyle(dateCellStyle); HSSFCell cell03 = hssfRow.createCell(3); cell03.setCellValue(new Date()); cell03.setCellStyle(dateCellStyle); HSSFCell cell04 = hssfRow.createCell(4); cell04.setCellValue(123456789.87654321); cell04.setCellStyle(numberCellStyle); HSSFCell cell05 = hssfRow.createCell(5); cell05.setCellValue(new HSSFRichTextString("Rich Text Goooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooods")); cell05.setCellStyle(wrapCellStyle); //--------------------------------------- //设置指定的列宽 //hssfSheet.setColumnWidth(3, 8000); //hssfSheet.setColumnWidth(4, 8000); hssfSheet.setColumnWidth(5, 10000); //设置自动的列宽 hssfSheet.autoSizeColumn(0); hssfSheet.autoSizeColumn(1); hssfSheet.autoSizeColumn(2); hssfSheet.autoSizeColumn(3); hssfSheet.autoSizeColumn(4); FileOutputStream fos = new FileOutputStream("good.xls"); hssfWorkbook.write(fos); } }
a082684f4415acb1303250112c9aefb56b0cbbc1
[ "Java" ]
2
Java
cdw0529/POI
b5bd89dff64f6a76d795c7524b6d9b9b7dabd425
e89783ecbcb6896a5214f7350973a0bb53a1c8cf
refs/heads/master
<repo_name>DzvezdanaV/PrvProekt<file_sep>/app/src/main/java/com/example/velkovska89/prvproekt/Main2Activity.java package com.example.velkovska89.prvproekt; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; public class Main2Activity extends AppCompatActivity { @BindView(R.id.userDetails) TextView userDetails; @BindView(R.id.name) EditText name; @BindView(R.id.lastName) EditText lastName; @BindView(R.id.username) EditText username; @BindView(R.id.textGender) TextView textGender; @BindView(R.id.radioGender) RadioGroup radioGender; @BindView(R.id.genderF) RadioButton genderF; @BindView(R.id.genderM) RadioButton genderM; @BindView(R.id.btnNext) Button btnNext; public User user; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.content_main2); ButterKnife.bind(this); user = new User(); if (getIntent().hasExtra("user")) { user = (User) getIntent().getSerializableExtra("user"); name.setText(user.getName()); lastName.setText(user.getLastname()); username.setText(user.getUserename()); if (user.getGender()) { genderF.setChecked(true); } else { genderM.setChecked(true); } } btnNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent next1 = new Intent(Main2Activity.this, Main3Activity.class); user.setName(name.getText().toString()); user.setLastname(lastName.getText().toString()); user.setUserename(username.getText().toString()); if (genderF.isChecked()) user.setGender(true); else user.setGender(false); next1.putExtra("user",user); if(getIntent().hasExtra("login")) startActivity(next1); else{ setResult(RESULT_OK, next1); finish(); } } }); } } <file_sep>/app/src/main/java/com/example/velkovska89/prvproekt/Main3Activity.java package com.example.velkovska89.prvproekt; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.TextView; import java.nio.file.attribute.UserPrincipalLookupService; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; public class Main3Activity extends AppCompatActivity { @BindView(R.id.spinnerGuest) Spinner spinner; @BindView(R.id.btnEdit) Button btnEdit; @BindView(R.id.viewInvisible) View viewInvisible; @BindView(R.id.btnUser) Button btnUser; @BindView(R.id.textGender1) TextView textGender1; @BindView(R.id.radioGender1) RadioGroup radioGender1; @BindView(R.id.btnF) RadioButton btnF; @BindView(R.id.btnM) RadioButton btnM; @BindView(R.id.female) ImageView image; @BindView(R.id.nameLastname) TextView nameLastname; @BindView(R.id.textNet) TextView textNet; @BindView(R.id.btnNet) Button btnNet; public User user; public ArrayList<User> usersList = new ArrayList<>(); public ArrayAdapter<User> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.content_main3); ButterKnife.bind(this); user = (User) getIntent().getSerializableExtra("user"); usersList.add(user); adapter = new ArrayAdapter<User>(this, android.R.layout.simple_spinner_item, usersList); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { user = usersList.get(i); updateData(); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); radioGender1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int i) { if (btnF.isChecked()) { image.setImageResource(R.drawable.mujer); } else { image.setImageResource(R.drawable.man); } } }); btnEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intendEdit = new Intent(Main3Activity.this, Main2Activity.class); intendEdit.putExtra("user", user); startActivityForResult(intendEdit, 1001); } }); btnUser.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent buttonUser = new Intent(Main3Activity.this, Main2Activity.class); startActivityForResult(buttonUser, 1000); } }); btnNet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent checkNet = new Intent(Main3Activity.this, Main4Activity.class); startActivity(checkNet); } }); updateData(); } public void updateData() { if (user.getGender()) { btnF.setChecked(true); image.setImageResource(R.drawable.mujer); } else { btnM.setChecked(true); image.setImageResource(R.drawable.man); } nameLastname.setText(user.getName() + "\n" + user.getLastname()); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1000 && resultCode == RESULT_OK) { user = (User) data.getSerializableExtra("user"); usersList.add(user); updateData(); } if (requestCode == 1001 && resultCode == RESULT_OK) { user = (User) data.getSerializableExtra("user"); User userPom = (User) spinner.getSelectedItem(); userPom.setUserename(user.getUserename()); userPom.setGender(user.getGender()); userPom.setName(user.getName()); userPom.setLastname(user.getLastname()); adapter.notifyDataSetChanged(); updateData(); } } } <file_sep>/app/src/main/java/com/example/velkovska89/prvproekt/Main4Activity.java package com.example.velkovska89.prvproekt; import android.content.DialogInterface; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; public class Main4Activity extends AppCompatActivity { @BindView(R.id.btnCheck) Button btnCheck; @BindView(R.id.internetChecked) TextView internetChecked; @BindView(R.id.btnBack) Button btnBack; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.content_main4); ButterKnife.bind(this); btnCheck.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showDialog(); } }); btnBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); } public void showDialog (){ final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); alertDialogBuilder.setTitle("ARE YOU CONNECTED"); alertDialogBuilder.setMessage("Now you are connected to the internet!"); AlertDialog dialog = alertDialogBuilder.create(); dialog.show(); } }
e29b852d3c062ce603930a970c03016bab1e468a
[ "Java" ]
3
Java
DzvezdanaV/PrvProekt
b6f2a2e1a99d4f6b849a4932676922b29659b833
efcb6b589f287292a05b1c003c14406c6100c0a6
refs/heads/master
<file_sep>// Code generated by ./hack/browserify.py // DO NOT EDIT! /* This is a RSVP based Ajax client for gRPC gateway JSON APIs. */ var _ = require('lodash'); var apis = _.merge({}, require('./apis/hello/v1alpha1/hello.gw.js'), require('./apis/status/status.gw.js') ); module.exports = apis.appscode.hello; <file_sep>#!/usr/bin/env bash set -o errexit set -o nounset set -o pipefail DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" ROOT=$DIR/.. rm -rf $ROOT/apis $ROOT/schemas pushd $GOPATH/src/github.com/appscode/hello-grpc/_proto # copy files mkdir -p $ROOT/apis $ROOT/schemas ./hack/make.sh js find . -name '*.gw.js' | cpio -pdm $ROOT/apis find . -name '*.schema.json' | cpio -pdm $ROOT/schemas (find . | grep gw.js | xargs rm) || true # regenerate index.js $DIR/browserify.py $ROOT popd <file_sep>## hello-grpc run Launch Hello GRPC server ### Synopsis Launch Hello GRPC server ``` hello-grpc run [flags] ``` ### Options ``` --api-domain string Domain used for apiserver (prod: api.appscode.com --cors-origin-allow-subdomain Allow CORS request from subdomains of origin (default true) --cors-origin-host string Allowed CORS origin host e.g, domain[:port] (default "*") --enable-cors Enable CORS support -h, --help help for run --log-rpc log RPC request and response --plaintext-addr string host:port used to serve http json apis (default ":8080") --secure-addr string host:port used to serve secure apis (default ":8443") --tls-ca-file string File containing CA certificate --tls-cert-file string File container server TLS certificate --tls-private-key-file string File containing server TLS private key ``` ### Options inherited from parent commands ``` --alsologtostderr log to standard error as well as files --log_backtrace_at traceLocation when logging hits line file:N, emit a stack trace (default :0) --log_dir string If non-empty, write log files in this directory --logtostderr log to standard error instead of files --stderrthreshold severity logs at or above this threshold go to stderr (default 2) -v, --v Level log level for V logs --vmodule moduleSpec comma-separated list of pattern=N settings for file-filtered logging ``` ### SEE ALSO * [hello-grpc](hello-grpc.md) - Hello gRPC by Appscode <file_sep># hello-grpc-js-client Hello GRPC JavaScript Client <file_sep>package hello import ( "fmt" "time" proto "github.com/appscode/hello-grpc/pkg/apis/hello/v1alpha1" "github.com/appscode/hello-grpc/pkg/cmds/server" "golang.org/x/net/context" ) func init() { server.GRPCEndpoints.Register(proto.RegisterHelloServiceServer, &Server{}) server.GatewayEndpoints.Register(proto.RegisterHelloServiceHandlerFromEndpoint) server.CorsPatterns.Register(proto.ExportHelloServiceCorsPatterns()) } type Server struct { } var _ proto.HelloServiceServer = &Server{} func (s *Server) Intro(ctx context.Context, req *proto.IntroRequest) (*proto.IntroResponse, error) { return &proto.IntroResponse{ Intro: fmt.Sprintf("hello, %s!", req.Name), }, nil } func (s *Server) Stream(req *proto.IntroRequest, stream proto.HelloService_StreamServer) error { for i := 0; i < 60; i++ { intro := fmt.Sprintf("%d: hello, %s!", i, req.Name) if err := stream.Send(&proto.IntroResponse{Intro: intro}); err != nil { return err } time.Sleep(1 * time.Second) } return nil } <file_sep>package server import ( "net/http" "strings" stringz "github.com/appscode/go/strings" utilerrors "github.com/appscode/go/util/errors" grpc_cors "github.com/appscode/grpc-go-addons/cors" "github.com/appscode/grpc-go-addons/endpoints" grpc_security "github.com/appscode/grpc-go-addons/security" "github.com/appscode/grpc-go-addons/server" "github.com/appscode/grpc-go-addons/server/options" grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware" grpc_glog "github.com/grpc-ecosystem/go-grpc-middleware/logging/glog" grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery" grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags" ctx_glog "github.com/grpc-ecosystem/go-grpc-middleware/tags/glog" grpc_opentracing "github.com/grpc-ecosystem/go-grpc-middleware/tracing/opentracing" grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus" gwrt "github.com/grpc-ecosystem/grpc-gateway/runtime" "golang.org/x/net/context" "google.golang.org/grpc" "google.golang.org/grpc/metadata" ) var ( GRPCEndpoints = endpoints.GRPCRegistry{} GatewayEndpoints = endpoints.ProxyRegistry{} CorsPatterns = grpc_cors.PatternRegistry{} ) type ServerOptions struct { RecommendedOptions *options.RecommendedOptions LogRPC bool } func NewServerOptions() *ServerOptions { o := &ServerOptions{ RecommendedOptions: options.NewRecommendedOptions(), } return o } func (o ServerOptions) Validate(args []string) error { var errors []error errors = append(errors, o.RecommendedOptions.Validate()...) return utilerrors.NewAggregate(errors) } func (o *ServerOptions) Complete() error { return nil } func (o ServerOptions) Config() (*server.Config, error) { config := server.NewConfig() if err := o.RecommendedOptions.ApplyTo(config); err != nil { return nil, err } config.SetGRPCRegistry(GRPCEndpoints) config.SetProxyRegistry(GatewayEndpoints) config.SetCORSRegistry(CorsPatterns) optsGLog := []grpc_glog.Option{ grpc_glog.WithDecider(func(methodFullName string, err error) bool { // will not log gRPC calls if it was a call to healthcheck and no error was raised if err == nil && methodFullName == "/github.com.appscode.hellogrpc.apis.status.StatusService/Status" { return false } // by default you will log all calls return o.LogRPC }), } payloadDecider := func(ctx context.Context, fullMethodName string, servingObject interface{}) bool { // will not log gRPC calls if it was a call to healthcheck and no error was raised if fullMethodName == "/github.com.appscode.hellogrpc.apis.status.StatusService/Status" { return false } // by default you will log all calls return o.LogRPC } glogEntry := ctx_glog.NewEntry(ctx_glog.Logger) grpc_glog.ReplaceGrpcLogger() config.GRPCServerOption( grpc.StreamInterceptor(grpc_middleware.ChainStreamServer( grpc_ctxtags.StreamServerInterceptor(), grpc_opentracing.StreamServerInterceptor(), grpc_prometheus.StreamServerInterceptor, grpc_glog.PayloadStreamServerInterceptor(glogEntry, payloadDecider), grpc_glog.StreamServerInterceptor(glogEntry, optsGLog...), grpc_cors.StreamServerInterceptor(grpc_cors.OriginHost(config.CORSOriginHost), grpc_cors.AllowSubdomain(config.CORSAllowSubdomain)), grpc_security.StreamServerInterceptor(), grpc_recovery.StreamServerInterceptor(), )), grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer( grpc_ctxtags.UnaryServerInterceptor(), grpc_opentracing.UnaryServerInterceptor(), grpc_prometheus.UnaryServerInterceptor, grpc_glog.PayloadUnaryServerInterceptor(glogEntry, payloadDecider), grpc_glog.UnaryServerInterceptor(glogEntry, optsGLog...), grpc_cors.UnaryServerInterceptor(grpc_cors.OriginHost(config.CORSOriginHost), grpc_cors.AllowSubdomain(config.CORSAllowSubdomain)), grpc_security.UnaryServerInterceptor(), grpc_recovery.UnaryServerInterceptor(), )), ) config.GatewayMuxOption(gwrt.WithIncomingHeaderMatcher(func(h string) (string, bool) { if stringz.PrefixFold(h, "access-control-request-") || stringz.PrefixFold(h, "k8s-") || strings.EqualFold(h, "Origin") || strings.EqualFold(h, "Cookie") || strings.EqualFold(h, "X-Phabricator-Csrf") { return h, true } return "", false }), gwrt.WithOutgoingHeaderMatcher(func(h string) (string, bool) { if stringz.PrefixFold(h, "access-control-allow-") || strings.EqualFold(h, "Set-Cookie") || strings.EqualFold(h, "vary") || strings.EqualFold(h, "x-content-type-options") || stringz.PrefixFold(h, "x-ratelimit-") { return h, true } return "", false }), gwrt.WithMetadata(func(c context.Context, req *http.Request) metadata.MD { return metadata.Pairs("x-forwarded-method", req.Method) }), gwrt.WithProtoErrorHandler(gwrt.DefaultHTTPProtoErrorHandler)) return config, nil } func (o ServerOptions) RunServer(stopCh <-chan struct{}) error { config, err := o.Config() if err != nil { return err } server, err := config.New() if err != nil { return err } return server.Run(stopCh) } <file_sep>package cmds import ( "context" "fmt" "io" "log" _ "net/http/pprof" "strings" hello "github.com/appscode/hello-grpc/pkg/apis/hello/v1alpha1" _ "github.com/appscode/hello-grpc/pkg/hello" _ "github.com/appscode/hello-grpc/pkg/status" "github.com/spf13/cobra" "google.golang.org/grpc" "google.golang.org/grpc/credentials" ) func NewCmdClient(stopCh <-chan struct{}) *cobra.Command { var address, certPath, name string var stream bool cmd := &cobra.Command{ Use: "client", Short: "Launch Hello GRPC client", Long: "Launch Hello GRPC client", RunE: func(c *cobra.Command, args []string) error { if stream { return doGRPCStream(address, certPath, name) } return doGRPC(address, certPath, name) }, } flags := cmd.Flags() flags.StringVar(&address, "address", "", "address of the server") flags.StringVar(&certPath, "crt", "", "path to cert file") flags.StringVar(&name, "name", "appscode", "name field of hello-request") flags.BoolVar(&stream, "stream", false, "use stream API") return cmd } func doGRPC(address, crtPath, name string) error { address = strings.TrimPrefix(address, "http://") address = strings.TrimPrefix(address, "https://") log.Println(address) option := grpc.WithInsecure() if len(crtPath) > 0 { creds, err := credentials.NewClientTLSFromFile(crtPath, "") if err != nil { return fmt.Errorf("failed to load TLS certificate") } option = grpc.WithTransportCredentials(creds) } conn, err := grpc.Dial(address, option) if err != nil { return fmt.Errorf("did not connect, %v", err) } defer conn.Close() client := hello.NewHelloServiceClient(conn) result, err := client.Intro(context.Background(), &hello.IntroRequest{Name: name}) if err != nil { return err } log.Println(result) return nil } func doGRPCStream(address, crtPath, name string) error { address = strings.TrimPrefix(address, "http://") address = strings.TrimPrefix(address, "https://") log.Println(address) option := grpc.WithInsecure() if len(crtPath) > 0 { creds, err := credentials.NewClientTLSFromFile(crtPath, "") if err != nil { return fmt.Errorf("failed to load TLS certificate") } option = grpc.WithTransportCredentials(creds) } conn, err := grpc.Dial(address, option) if err != nil { return fmt.Errorf("did not connect, %v", err) } defer conn.Close() streamClient, err := hello.NewHelloServiceClient(conn).Stream(context.Background(), &hello.IntroRequest{Name: name}) if err != nil { return err } for { result, err := streamClient.Recv() if err == io.EOF { break } if err != nil { return err } log.Println(result) } return nil } <file_sep>#!/usr/bin/python import os import sys def reindex(root): """root: path to the root of the git root.""" apis = [] for dir, _, files in os.walk(root + '/apis'): for file in files: rel = os.path.relpath(dir + '/' + file, root) # print rel apis.append(rel) content = """// Code generated by ./hack/browserify.py // DO NOT EDIT! /* This is a RSVP based Ajax client for gRPC gateway JSON APIs. */ var _ = require('lodash'); """ # module exports content += 'var apis = _.merge({},\n' for api in sorted(apis): content += " require('./{}'),\n".format(api) content = content[:-2] content += '\n);\n' content += 'module.exports = apis.appscode.hello;\n' with open(root + '/index.js', 'w') as f: return f.write(content) if __name__ == "__main__": if len(sys.argv) > 1: reindex(os.path.abspath(sys.argv[1])) else: reindex(os.path.expandvars('$GOPATH') + '/src/github.com/appscode/hello-grpc/client/js') <file_sep>#!/bin/bash # echo 'Setting up dependencies for compiling protos...' # "$(go env GOPATH)"/src/github.com/appscode/hello-grpc/_proto/hack/builddeps.sh echo '---' echo '--' echo '.' echo 'Setting up dependencies for compiling hello...' # https://github.com/ellisonbg/antipackage pip install git+https://github.com/ellisonbg/antipackage.git#egg=antipackage go get -u golang.org/x/tools/cmd/goimports go get github.com/Masterminds/glide go get github.com/sgotti/glide-vc go install github.com/progrium/go-extpoints <file_sep>// Code generated by protoc-gen-grpc-js-client // source: hello.proto // DO NOT EDIT! /* This is a RSVP based Ajax client for gRPC gateway JSON APIs. */ var xhr = require('grpc-xhr'); function helloServiceIntro(p, conf) { path = '/apis/hello/v1alpha1/intro/json' return xhr(path, 'GET', conf, p); } var services = { helloService: { intro: helloServiceIntro } }; module.exports = {github: {com: {appscode: {hellogrpc: {apis: {hello: {v1alpha1: services}}}}}}}; <file_sep>package status import ( v "github.com/appscode/go/version" proto "github.com/appscode/hello-grpc/pkg/apis/status" "github.com/appscode/hello-grpc/pkg/cmds/server" "golang.org/x/net/context" ) func init() { server.GRPCEndpoints.Register(proto.RegisterStatusServiceServer, &Server{}) server.GatewayEndpoints.Register(proto.RegisterStatusServiceHandlerFromEndpoint) server.CorsPatterns.Register(proto.ExportStatusServiceCorsPatterns()) } type Server struct { } var _ proto.StatusServiceServer = &Server{} func (s *Server) Status(ctx context.Context, req *proto.StatusRequest) (*proto.StatusResponse, error) { return &proto.StatusResponse{ Version: &proto.Version{ Version: v.Version.Version, VersionStrategy: v.Version.VersionStrategy, Os: v.Version.Os, Arch: v.Version.Arch, CommitHash: v.Version.CommitHash, GitBranch: v.Version.GitBranch, GitTag: v.Version.GitTag, CommitTimestamp: v.Version.CommitTimestamp, BuildTimestamp: v.Version.BuildTimestamp, BuildHost: v.Version.BuildHost, BuildHostOs: v.Version.BuildHostOs, BuildHostArch: v.Version.BuildHostArch, }, }, nil } <file_sep>package cmds import ( _ "net/http/pprof" "github.com/appscode/hello-grpc/pkg/cmds/server" _ "github.com/appscode/hello-grpc/pkg/hello" _ "github.com/appscode/hello-grpc/pkg/status" "github.com/spf13/cobra" ) func NewCmdRun(stopCh <-chan struct{}) *cobra.Command { o := server.NewServerOptions() cmd := &cobra.Command{ Use: "run", Short: "Launch Hello GRPC server", Long: "Launch Hello GRPC server", RunE: func(c *cobra.Command, args []string) error { if err := o.Complete(); err != nil { return err } if err := o.Validate(args); err != nil { return err } if err := o.RunServer(stopCh); err != nil { return err } return nil }, } flags := cmd.Flags() o.RecommendedOptions.AddFlags(flags) flags.BoolVar(&o.LogRPC, "log-rpc", o.LogRPC, "log RPC request and response") return cmd } <file_sep>package cmds import ( "flag" "log" "github.com/appscode/go/signals" v "github.com/appscode/go/version" "github.com/spf13/cobra" "github.com/spf13/pflag" ) func NewRootCmd(version string) *cobra.Command { rootCmd := &cobra.Command{ Use: "hello-grpc [command]", Short: `Hello gRPC by Appscode`, DisableAutoGenTag: true, PersistentPreRun: func(c *cobra.Command, args []string) { c.Flags().VisitAll(func(flag *pflag.Flag) { log.Printf("FLAG: --%s=%q", flag.Name, flag.Value) }) }, } rootCmd.PersistentFlags().AddGoFlagSet(flag.CommandLine) // ref: https://github.com/kubernetes/kubernetes/issues/17162#issuecomment-225596212 flag.CommandLine.Parse([]string{}) stopCh := signals.SetupSignalHandler() rootCmd.AddCommand(NewCmdRun(stopCh)) rootCmd.AddCommand(NewCmdClient(stopCh)) rootCmd.AddCommand(v.NewCmdVersion()) return rootCmd } <file_sep># hello-grpc Hello gRPC ! ## Run on Host Build binary: ```console $ ./hack/make.py ``` Run server: ```console $ hello-grpc run ``` Run client (Intro API): ``` $ hello-grpc client --address=127.0.0.1:8080 --name=appscode I0206 17:40:38.495948 4419 logs.go:19] intro:"hello, appscode!" ``` Run client (Stream API): ``` $ hello-grpc client --address=127.0.0.1:8080 --name=appscode --stream I0206 17:41:11.933033 4465 logs.go:19] intro:"0: hello, appscode!" I0206 17:41:12.933156 4465 logs.go:19] intro:"1: hello, appscode!" I0206 17:41:13.933201 4465 logs.go:19] intro:"2: hello, appscode!" I0206 17:41:14.933331 4465 logs.go:19] intro:"3: hello, appscode!" ... ``` JSON response: visit http://127.0.0.1:8080/apis/hello/v1alpha1/intro/json?name=tamal ## Run in a Kubernetes Cluster Tested against Minikube v0.25.0 (Kubernetes 1.9.0) ```console $ kubectl apply -f ./hack/deploy/deploy.yaml $ kubectl get pods,svc NAME READY STATUS RESTARTS AGE po/hello-grpc-66b9f67c46-bnd2l 1/1 Running 0 10s po/hello-grpc-66b9f67c46-wpw4b 1/1 Running 0 10s NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE svc/hello-grpc LoadBalancer 10.104.191.103 <pending> 80:30596/TCP,443:31816/TCP,56790:30206/TCP 10s svc/kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 34m $ minikube service list |-------------|----------------------|--------------------------------| | NAMESPACE | NAME | URL | |-------------|----------------------|--------------------------------| | default | hello-grpc | http://192.168.99.100:30596 | | | | http://192.168.99.100:31816 | | | | http://192.168.99.100:30206 | | default | kubernetes | No node port | | kube-system | kube-dns | No node port | | kube-system | kubernetes-dashboard | http://192.168.99.100:30000 | |-------------|----------------------|--------------------------------| ``` Now visit: http://192.168.99.100:30596/apis/hello/v1alpha1/intro/json?name=tamal ![hello-grpc](/docs/images/hello-grpc.png) ## Status Endpoint Hello GRPC server has a `/apis/status/json` endpoint which can be used to probe heatlh of the service. ![hello-grpc-status](/docs/images/hello-grpc-status.png)
73820515935b298163affcd8e02b9687582044a2
[ "JavaScript", "Markdown", "Python", "Go", "Shell" ]
14
JavaScript
appscode/hello-grpc
eea009cbf42e54d0a19cbf08dd1fdfa75502b69e
e524f23f6027744bfb0b8c69201dc430b4532012
refs/heads/master
<repo_name>uli-wizrd/GradDesc<file_sep>/GD_CN2.py from sympy import * from mpl_toolkits import mplot3d import matplotlib.pyplot as plt from numpy.random import randint import numpy as np import os import psutil as ps # Definicion de la condicion para imprimir la funcion de trabajo init_printing(use_unicode=True) x, y, z = symbols('x y z') # Definicion del tamaño del diferencial, conforme sea mas pequeño mas se asemejara a la derivada exacta evaluada h = 0.0000001 # Definicion de la derivada como un limite multivariable fxprim = ((2*(x+h)**2 + 7/5*y**2) - (2*x**2 + 7/5*y**2)) / h fyprim = ((2*x**2 + 7/5*(y+h)**2) - (2*x**2 + 7/5*y**2)) / h # Definicion de la funcion f = 2*x**2 + 7/5*y**2 print("\nLa función de trabajo es:", f) print("\nSe comenzará el descenso por gradiente con los siguientes valores aleatorios:") theta = randint(10) # valor de prueba inicial de x print("Theta 0 o (x) = ", theta) theta1 = randint(10) # valor de prueba inicial de y print("Theta 1 o (y) = ", theta1) alpha = float(input("Ingrese el valor de la tasa de aprendizaje con el que trabajará:\n")) # Tasa de aprendizaje # Definicion de constantes y espacios de almacenamiento iterations = 0 check = 0 precision = 1 / 1000000 printData = True maxIterations = 1000 ptheta = [] ptheta1 = [] ex = [] ey = [] itr = [] errx = 0 erry = 0 altura = [] while True: # Ok entonces empleando el lenguaje de sympy lo que haremos sera simplemente sustituir el valor de nuestra prueba # En las variables que resulten de nuestra derivada, al ser multivariables se agregara otro .subs # El es el comando en sympy para realizar la sustitucion, despues .evalf evalua la funcion como si los argumentos # En el tipo de dato float temptheta = theta - alpha * N(fxprim.subs(x, theta).subs(y, theta1)).evalf() temptheta1 = theta1 - alpha * N(fyprim.subs(y, theta1)).subs(x, theta).evalf() # si el numero de iteraciones es muy grande, quiza esta divergiendo entonces, se debe detener el bucle iterations += 1 itr.append(iterations) errx += pow(theta - temptheta, 2) erry += pow(theta1 - temptheta1, 2) Errx = 1 / iterations * errx Erry = 1 / iterations * erry ex.append(Errx) ey.append(Erry) alt = N(f.subs(x, theta).subs(y, theta1)).evalf() altura.append(alt) if iterations > maxIterations: print("Demasiadas iteraciones. Ajuste el valor de alpha y asegurese de que la función es convexa") printData = False break # Establecimiento de la condicion de paro. if abs(temptheta - theta) < precision and abs(temptheta1 - theta1) < precision: break # Actualizacion de valores theta = temptheta theta1 = temptheta1 # registro de valores ptheta.append(theta) ptheta1.append(theta1) # imprimir resultados if printData: print("La función " + str(f) + " converge a un mínimo") print("Número de iteraciones:", iterations, sep=" ") print("theta0 (x) final =", temptheta, sep=" ") print("theta1 (y) final =", temptheta1, sep=" ") print("Penultimo valor de theta0 (x) =", theta, sep=" ") print("penultimo valor de theta1 (y) =", theta1, sep=" ") print('Historial de valores de theta0 (x):\n ') for k in ptheta: print(k) print('Historial de valores de theta1 (y):\n ') for j in ptheta1: print(j) print('Historial de valores de la altura (z):\n ') for l in altura: print(l) # Gráficas de la función de trabajo x = np.linspace(-3, 3, 100) y = np.linspace(-3, 3, 100) X, Y = np.meshgrid(x, y) def fun(a, b): zx = pow(a, 2) + pow(b, 2) return zx Z = fun(X, Y) ax = plt.axes(projection='3d') ax.set_title('Gráfica de la función Z = 2X^2 + 7/5Y^2') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('z') ax.view_init(20, 30) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='viridis', edgecolor='none') plt.show() ax = plt.axes(projection='3d') ax.set_title('Gradiente descendente') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') ax.view_init(20, 20) ax.contour3D(X, Y, Z, 50, cmap='gray') pg = ax.scatter3D(ptheta, ptheta1, zs=0, zdir='y', c=ptheta1, cmap='seismic', label='Aproximación') plt.colorbar(pg) ax.legend() plt.show() # Graficas del error de calculo fig, ax = plt.subplots(facecolor='whitesmoke') ax.set_facecolor('floralwhite') ax.set_title('Comportamiento del error en X', color='k') ax.set_xlabel('Error en x', color='mediumseagreen') ax.set_ylabel('Iteraciones', color='brown') ax.plot(ex, itr, 'darkgray', linestyle='-') # Grafica principal plt.grid() ax.tick_params(labelcolor='k') plt.show() fig, ax = plt.subplots(facecolor=('whitesmoke')) ax.set_facecolor('floralwhite') ax.set_title('Comportamiento del error en Y', color='k') ax.set_xlabel('Error en y', color='mediumseagreen') ax.set_ylabel('Iteraciones', color='brown') ax.plot(ey, itr, 'royalblue', linestyle='-') # Grafica principal plt.grid() ax.tick_params(labelcolor='k') plt.show() # Ahora se imprimiran los resultados del uso de memoria def memoria_psutil(): # regresa el uso de memoria en MB process = ps.Process(os.getpid()) mem = process.memory_info().rss / float(2 ** 20) return mem print("La cantidad de memoria utilizada por este programa es:\n"+ str( memoria_psutil()))<file_sep>/README_EN.md # English version # Fuentes y recursos (sources and resources) Todo el codigo presentado ha sido desarrollado siguiendo lo presentado en el curso de <a href="http://personal.cimat.mx:8181/~mrivera/cursos/temas_aprendizaje.html" target="_blank"> Aprendizaje Automático <a> El curso mencionado es una herramienta invaluable para cualquiera interesado en el aprendizaje de máquina. Las definiciones de los métodos se obtuvieron de las páginas mencionadas en cada sección. # **Métodos de Gradiente (Gradient Methods)** Los ejemplos únicamente detallan el funcionamiento de los métodos expuestos en problemas de mínimizacion. La razón es porque el contenido de este repositorio va orientado más hacia el desarrollo de redes neuronales artificiales. En estos sistemas los optimizadores se utilizan para reducir el error del modelo a la hora de hacer predicciones (inferencia). ## Descenso por Gradiente de vainilla (Gradient Descent vanilla flavour) Imagen de la ecuacion la imagen fue creada utilizando word Definicion con cita ### Descenso por Gradiente 2D (Gradient Descent 2D) El ejemplo [Descenso por gradiente 2D](https://github.com/uli-wizrd/Gradient_Methods/blob/master/GD_CN2.py) Trata sobre del uso de descenso por gradiente de vanilla en la optimizacion de una funcion multivariable convexa. ### Descenso por gradiente 2D con derivada numerica (Gradient Descent 2D with numerical derivatives) El ejemplo [Descenso por gradiente 2D](https://github.com/uli-wizrd/Gradient_Methods/blob/master/GD_CN2.py) Trata sobre el descenso por gradiente en una funcion que vive en un espacio bidimensional (cuando solo necesitas dos variables para describir tu sistema). ### Descenso por Gradiente 3D (Gradient Descent 3D) El ejemplo [Descenso por gradiente 2D](https://github.com/uli-wizrd/Gradient_Methods/blob/master/GD_CN2.py) Trata sobre el uso del descenso por gradiente en una funcion que vive en un espacio tridimensional (Cada eje corresponde a una variable de interes) ## 2.- Descenso por Gradiente Estocastico (Stochastic Gradient Descent) El ejemplo trata sobre el uso del descenso por gradiente estocastico en funciones convexas y no convexas ## 3.- Sumthin El tercero es un ejemplo del metodo empleado en la optimizacion de una funcion no convexa ## 4.-Sumthin El cuarto es un ejemplo del metodo empleado en la optimizacion de una funcion no convexa ## 5.-ADAM Optimizador Adaptativo de Momento (Adaptative Moment optimizer) El Quinto es un ejemplo de la aplicacion del optimizador ADAM presentado en [cira] para una funcion no convexa # Comparaciones (Comparatives) El ejemplo [Descenso por gradiente 2D](https://github.com/uli-wizrd/Gradient_Methods/blob/master/GD_CN2.py). Es una simulacion de como se comparan el descenso por gradiente, el descenso por gradiente estocastico, x, y y ADAM. La tarea fue encontrar el minimo de la funcion 3D (funcion). La funcion de la cual se quiere encontrar el minimo en este caso se conoce como funcion de perdida (loss function). Esta funcion nos reporta el error de nuestro sistema a la hora de hacer predicciones. Tambien se le conoce a esta funcion como superficie de perdida (Loss surface).
4f34a479fe47f5557738797b76e7aed5469b1146
[ "Markdown", "Python" ]
2
Python
uli-wizrd/GradDesc
1b25d9ed4e83c97c6e5572b992c318ad0b90b775
68bc04aefed0250016c6c3e45fadf7f9d1e7fe60
refs/heads/master
<repo_name>tedchou12/ml_project3_ocr<file_sep>/pipeline1_splitting/ocr_3_image_crop.py from PIL import Image import glob # counter = 1 mode = 'training' for file in glob.glob('./' + mode + '/processed/*.jpg') : path_parts = file.split('/') name_parts = path_parts[-1].split('.') name = name_parts[0] window = 0 while window < 176 : window_size = 25 frame_x1 = window frame_x2 = window + window_size window_name = name + '_' + str(frame_x1) + '_' + str(frame_x2) + '.jpg' # print(window_name) im = Image.open(file) im_crop = im.crop((frame_x1, 0, frame_x2, 50)) im_crop.convert('L').save(mode + '/split/' + str(window_name), quality=95) window = window + 10 <file_sep>/pipeline1_splitting/ocr_1_collect.py import requests import random # digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] counter = 0 while counter < 100 : # random.shuffle(digits) # number = str(digits[0]) + str(digits[1]) + str(digits[2]) + str(digits[3]) + str(digits[4]) + str(digits[5]) with open('data/' + str(counter) + '.jpg', 'wb') as handle: response = requests.get('https://www.chief070.com.tw/verify_code.aspx', stream=True) if not response.ok: print(response) for block in response.iter_content(1024): if not block: break handle.write(block) counter += 1 <file_sep>/ml_1_sliding_window.py import requests import random from PIL import Image import os import numpy as np file = open('pipeline2_image_present/theta.txt', 'r') theta1 = file.readlines() file.close() theta_1 = [] for row in theta1 : row = row.replace('\n', '') theta_1.append(float(row)) file = open('pipeline3_digit_ocr/theta.txt', 'r') theta2 = file.readlines() file.close() theta_2 = [] for row in theta2 : row = row.replace('\n', '') row_vals = row.split(' ') row_processed = [] for row_val in row_vals : if row_val != '' : row_processed.append(float(row_val)) theta_2.append(row_processed) temp = 1 file_path = 'data/' + str(temp) + '.jpg' with open(file_path, 'wb') as handle : response = requests.get('https://www.chief070.com.tw/verify_code.aspx', stream=True) if not response.ok: print(response) for block in response.iter_content(1024): if not block: break handle.write(block) if os.path.exists(file_path) : im = Image.open(file_path) im.convert('L').save(file_path, quality=95) path_parts = file_path.split('/') name_parts = path_parts[-1].split('.') name = name_parts[0] window = 0 while window < 176 : window_size = 25 frame_x1 = window frame_x2 = window + window_size window_name = name + '_' + str(frame_x1) + '_' + str(frame_x2) + '.jpg' im = Image.open(file_path) im_crop = im.crop((frame_x1, 0, frame_x2, 50)) im_crop.convert('L').save('data/split/' + str(window_name), quality=95) window = window + 10 im = Image.open('data/split/' + str(window_name)) px = im.load() matrix = [0] i = 0 j = 0 for i in range(0, 25) : for j in range(0, 50) : hex = str(px[i, j]) matrix.append(int(hex)) # print(window_name) if np.dot(theta_1, matrix) > 0 : predict_matrix = list(np.dot(theta_2, matrix)) val = predict_matrix.index(max(predict_matrix)) print('predict:' + str(val + 1) + ', certainty: ' + str(max(predict_matrix)) + ', present: ' + str(np.dot(theta_1, matrix))) <file_sep>/pipeline3_digit_ocr/ocr_1_remove0.py file = open('training/matrix/data.txt', 'r') data_rows = file.readlines() file.close() file = open('training/window/data.txt', 'r') window_rows = file.readlines() file.close() valid_rows = [] valid_labels = [] counter = 0 for row in window_rows : if int(row) != 0 : row = row.replace('\n', '') valid_rows.append(data_rows[counter].replace('\n', '')) valid_labels.append(row) counter = counter + 1 # print(len(valid_rows)) file = open('training/matrix/data_processed.txt', 'w') file.write('\n'.join(valid_rows)) file.close() file = open('training/window/data_processed.txt', 'w') file.write('\n'.join(valid_labels)) file.close() # print(len(valid_labels)) <file_sep>/README.md # ml_project3_ocr Machine Learning classification (Logistic Regression) with Sliding Window Application written for Machine Learning OCR. App written to defeat Verification Codes on https://www.chief070.com.tw/member/apply/register.aspx. ![website](https://user-images.githubusercontent.com/10494709/110477460-87156a00-8126-11eb-820e-14a2bc4ede98.png) # Pipeline 1 Get Data 1. Collecting captcha from https://www.chief070.com.tw/verify_code.aspx and download all the codes. 2. Split 200 x 50 image into window frame size of 25 x 50 sizes, move window by 10. Greyscale 0-255. 3. Generated 18 images for each 200 x 50 image. ![greyscale splitted](https://user-images.githubusercontent.com/10494709/110477722-db204e80-8126-11eb-8f6b-92c7186ba314.jpg) # Pipeline 2 Using LR to determine if digit is in the center of the file or is recognizable. 1 if is recognizable or in the center, 0 if the digit is not present or unrecognizable. # Pipleline 3 Train digit in the frame from 0-9. (0 as 10) # Test `ml_1_sliding_window.py` will use theta1 and theta 2 from Pipeline 2 and Pipeline 3 to predict the digits. Because the digits are not as neat and can be at different places, the accuracy is lower, but there is about 2/10 to 3/10 of getting all the digits correct. ![result](https://user-images.githubusercontent.com/10494709/110478194-7285a180-8127-11eb-811f-9ca4b7451461.png) <file_sep>/pipeline1_splitting/ocr_2_image_process.py from PIL import Image import glob # counter = 1 mode = 'training' for file in glob.glob('./' + mode + '/unprocessed/*.jpg') : path_parts = file.split('/') # name = path_parts[-1].split('.') name = path_parts[-1] im = Image.open(file) # im_crop0 = im.crop((3, 0, 15, 25)) im.convert('L').save(mode + '/processed/' + str(name), quality=95) # counter = counter + 1 <file_sep>/pipeline1_splitting/ocr_4_matrix.py from PIL import Image import glob from natsort import natsorted mode = 'training' matrix = [] files = [] for file in glob.glob('./' + mode + '/split/*.jpg') : files.append(file) files = natsorted(files) for file in files : im = Image.open(file) px = im.load() row = [] i = 0 j = 0 for i in range(0, 25) : for j in range(0, 50) : hex = str(px[i, j]) # parts = hex.replace('(', '').replace(')', '').split(',') # hex = parts[0] row.append(hex) matrix.append(','.join(row)) matrix_string = '\n'.join(matrix) handle = open(mode + '/matrix/data.txt', 'w') handle.write(matrix_string) handle.close()
5c1b74988b740590bbc8165bce21d7366f985ad1
[ "Markdown", "Python" ]
7
Python
tedchou12/ml_project3_ocr
d8a08dbbb83f926cab6a27db2db8f3ba0709f8cf
189c4adaa0a5a2030419c88e9f28fb03d5ed4494
refs/heads/master
<repo_name>Fran-Fun/encrypt0r<file_sep>/main.js const { app, BrowserWindow, ipcMain, dialog, } = require('electron'); let mainWindow; const log = require('electron-log'); const path = require('path'); const Utils = require('./src/utils'); function createWindow() { mainWindow = new BrowserWindow({ width: 600, height: 600, webPreferences: { nodeIntegration: true, }, icon: path.join(__dirname, 'assets/icons/png/64x64.png'), }); mainWindow.loadFile('index.html'); log.info('created main window and loaded main page'); mainWindow.on('closed', () => { mainWindow = null; log.info('closed main window'); }); } app.on('ready', createWindow); app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } }); app.on('activate', () => { if (mainWindow === null) { createWindow(); } }); ipcMain.on('event:log', (e, arg) => { log.debug(arg); }); ipcMain.on('action:encrypt_decrypt', (e, arg) => { log.info('encrypting or decrypting...'); let popupFileName; if (arg.action === 'encrypt') { popupFileName = `${arg.filePath}.enc`; } else if (arg.action === 'decrypt') { popupFileName = arg.filePath.replace('.enc', ''); } let utils; dialog.showSaveDialog({ defaultPath: popupFileName, }, (filename) => { if (typeof filename !== 'undefined') { utils = new Utils(arg.filePath, filename, arg.passphrase); if (arg.action === 'encrypt') { log.info(`Encrypting ${filename} with password <redacted>`); utils.encrypt(); utils.on('progress', (progress) => { e.sender.send('notice-status', `Encrypting...${progress}%`); }); utils.on('finished', () => { log.info('File successfully encrypted!'); e.sender.send('notice-status', `Done! File has been saved to: ${filename}`); }); } else if (arg.action === 'decrypt') { log.info(`Decrypting ${filename} with password <redacted>`); utils.decrypt(); utils.on('progress', (progress) => { e.sender.send('notice-status', `Decrypting...${progress}%`); }); utils.on('finished', () => { log.info('File successfully decrypted!'); e.sender.send('notice-status', `Done! File has been saved to: ${filename}`); }); utils.on('error', (reason) => { if (reason === 'BAD_DECRYPT') { e.sender.send('notice-status', 'Oops. The passphrase is incorrect.'); } }); } } else { log.warn('Destination file location not selected'); e.sender.send('notice-status', 'Oops. Destination file location not selected. Please try again!'); } }); }); <file_sep>/README.md # encrypt0r [![Build Status](https://travis-ci.org/kunalnagar/encrypt0r.svg?branch=master)](https://travis-ci.org/kunalnagar/encrypt0r) [![Known Vulnerabilities](https://snyk.io/test/github/kunalnagar/encrypt0r/badge.svg?targetFile=package.json)](https://snyk.io/test/github/kunalnagar/encrypt0r?targetFile=package.json) Easily Encrypt and Decrypt files on Mac, Windows and Linux **Note:** Only single files supported for now. If you want to encrypt a folder, you need to zip it first and then drag it to encrypt0r ### Signing If you download the app on Mac/Windows, you will get an untrusted developer warning. This is because the app is not signed by the developer (aka me). Signing an app requires a Signing Certificate that costs hundreds of dollars per year. **Note:** It is absolutely safe to run the app on Mac/Windows. I'm not interested in your data or running malicious scripts. If you're worried about what the app is doing underneath, the code is all there, have at it :) Here's the warning on Windows: [![Watch the video](https://i.imgur.com/M3LQ1Wx.gif)](https://youtu.be/VIVz7MtNEO0) ### Download - [macOS](https://github.com/kunalnagar/encrypt0r/releases/latest/download/encrypt0r-mac.zip) - [Linux x64 Debian](https://github.com/kunalnagar/encrypt0r/releases/latest/download/encrypt0r-linux-deb.zip) - [Linux x64 Source](https://github.com/kunalnagar/encrypt0r/releases/latest/download/encrypt0r-linux-x64.zip) - [Windows x86](https://github.com/kunalnagar/encrypt0r/releases/latest/download/encrypt0r-windows-x86.zip) - [Windows x64](https://github.com/kunalnagar/encrypt0r/releases/latest/download/encrypt0r-windows-x64.zip) ### Screenshots ![](https://i.imgur.com/WQXyqsj.png) ### Demo Video Click on the GIF below to view the video on YouTube [![Watch the video](https://i.imgur.com/wdViVGA.gif)](https://youtu.be/WBf2bRMRFME) <file_sep>/src/utils.js const fs = require("fs"); const path = require("path"); const crypto = require("crypto"); const EventEmitter = require("events"); const zlib = require("zlib"); const { inherits } = require("util"); const Vector = require("./vector"); function calculateProgress(chunkSize, totalSize) { return Math.floor((chunkSize / totalSize) * 100); } class Utils { constructor(originalFile, destinationFile, password) { EventEmitter.call(this); this.originalFile = originalFile; this.destinationFile = destinationFile; this.password = <PASSWORD>; } getCipherKey() { return crypto .createHash("sha256") .update(this.password) .digest(); } encrypt() { const that = this; const initVector = crypto.randomBytes(16); const cipherKey = this.getCipherKey(); const readStream = fs.createReadStream(this.originalFile); const cipher = crypto.createCipheriv( "aes-256-cbc", cipherKey, initVector ); const initVectorStream = new Vector(initVector); const writeStream = fs.createWriteStream( path.join(this.destinationFile) ); const stat = fs.statSync(this.originalFile); const gzip = zlib.createGzip(); let size = 0; readStream .pipe(gzip) .pipe(cipher) .pipe(initVectorStream) .pipe(writeStream); readStream.on("data", chunk => { size += chunk.length; that.emit("progress", calculateProgress(size, stat.size)); }); writeStream.on("finish", () => { that.emit("finished"); }); } decrypt() { const that = this; const initVectorStream = fs.createReadStream(this.originalFile, { end: 15 }); const unzip = zlib.createGunzip(); let initVector; let size = 0; let cipherKey; let decipher; let readStream; let writeStream; initVectorStream.on("data", chunk => { initVector = chunk; }); initVectorStream.on("close", () => { cipherKey = this.getCipherKey(); decipher = crypto.createDecipheriv( "aes-256-cbc", cipherKey, initVector ); readStream = fs.createReadStream(this.originalFile, { start: 16 }); writeStream = fs.createWriteStream(path.join(this.destinationFile)); readStream .pipe(decipher) .pipe(unzip) .on("error", err => { that.emit("error", err.reason); }) .pipe(writeStream); }); initVectorStream.on("close", () => { const stat = fs.statSync(this.originalFile); readStream.on("data", chunk => { size += chunk.length; that.emit("progress", calculateProgress(size, stat.size)); }); writeStream.on("finish", () => { that.emit("finished"); }); }); } } inherits(Utils, EventEmitter); module.exports = Utils;
3b2656af9d1dc518b491462304ce6fb006e44e6c
[ "JavaScript", "Markdown" ]
3
JavaScript
Fran-Fun/encrypt0r
34ff2fb1b142987f3ea474bbd8701f42577fe91a
0a3b37104e19111b11573a7d0ac3cb65a692475b
refs/heads/master
<repo_name>WYMisShuaiGe/Cuckoo<file_sep>/src/utils/constant.js export const FOOTER_TYPE = { 0: 'boxoffice', 1: 'production', 2: 'news', 3: 'calendar', }; export const BOXOFFICE_TABLE_TITLE = [ '影片名称', '实时票房', '排片占比', '上座率', '累计票房', ]; export const PIE_COLORS = [ '#FF5937', '#FDAF29', '#1985CD', '#4D5E70', ]; <file_sep>/src/pages/home/Type.jsx import React from 'react'; const Type = props => { return ( <div className="type"> <ul> <li> <i className="film-screening" /> <p>实时排片</p> </li> <li> <i className="trend" /> <p>票房走势</p> </li> <li> <i className="vs" /> <p>影片对比</p> </li> <li> <i className="follow" /> <p>我的关注</p> </li> </ul> </div> ); }; export default Type; <file_sep>/src/app/selectors/home.js import { createSelector } from 'reselect'; const getBoxoffice = state => state.boxoffice; export default createSelector( getBoxoffice, (boxoffice) => { return { boxoffice, }; }, ); <file_sep>/src/components/Head/index.jsx import React from 'react'; import './head.scss'; class Head extends React.Component { constructor() { super(); } render() { const { title, } = this.props; return ( <div className="head"> <p className="head-title">{title}</p> </div> ); } } Head.propTypes = { title: React.PropTypes.string.isRequired, }; export default Head; <file_sep>/src/app/actions/home.js import * as types from '../constants/ActionTypes'; import request from 'utils/request'; import { API } from 'utils/api'; function receiveMovieRevenuesData(resp) { return { type: types.GET_MOVIE_REVENUES, boxoffice: resp, }; } export function GetMovieRevenues() { return (dispatch) => { const url = API.oneDayMovieRevenues; const data = { targetDate: 20161211, }; return request.GET(url, data) .then(function(resp) { return dispatch(receiveMovieRevenuesData(JSON.parse(resp))); }, function(err) { console.log(err); }); }; } function receiveCinemaRevenuesData(resp) { return { type: types.GET_MOVIE_REVENUES, boxoffice: resp, }; } export function GetCinemaRevenues() { return (dispatch) => { const url = API.oneDayCinemaRevenues; const data = { targetDate: 20161208, pageSize: 50, pageIdx: 0, }; return request.GET(url, data) .then(function(resp) { return dispatch(receiveCinemaRevenuesData(JSON.parse(resp))); }, function(err) { console.log(err); }); }; } function receiveCinemaLineRevenuesData(resp) { return { type: types.GET_MOVIE_REVENUES, boxoffice: resp, }; } export function GetCinemaLineRevenues() { return (dispatch) => { const url = API.oneDayCinemLineaRevenues; const data = { targetDate: 20161208, }; return request.GET(url, data) .then(function(resp) { return dispatch(receiveCinemaLineRevenuesData(JSON.parse(resp))); }, function(err) { console.log(err); }); }; } <file_sep>/src/pages/home/BoxofficeList.jsx import React from 'react'; import ReactEcharts from 'echarts-for-react'; import getOption from 'utils/chart_pie'; import { BOXOFFICE_TABLE_TITLE, PIE_COLORS } from 'utils/constant'; class BoxofficeList extends React.Component { constructor(props) { super(...props); } render() { const { upd, data, sumSCnt, aveSeat, sumRev, newMovieCnt } = this.props; const aveTicketPrice = (sumRev / sumSCnt / aveSeat / 100).toFixed(2); let todayBoxOffice = (sumRev / 1000000).toFixed(0) if (todayBoxOffice.length < 5) { todayBoxOffice = `${todayBoxOffice}万`; } else { todayBoxOffice = `${(todayBoxOffice / 10000).toFixed(2)}亿`; } const sortData = data.slice(0, 3); const pieData = []; let aa = 0; sortData.forEach((item) => { pieData.push(item.revRate); aa += item.revRate; }); pieData.push(1 - aa); const option = getOption(pieData, PIE_COLORS, todayBoxOffice); return ( <div className="box-office-data"> <div className="box-office-chart"> <div className="chart-data-warapper"> <ReactEcharts className="chart-boxofice-data" style={{ height: '170px' }} option={option} /> <span>{`北京时间${upd}更新`}</span> </div> <ul className="data-text"> { sortData.map((item, i) => <li key={i}> <i /> <p>{item.mTitle}</p> <p> <span className={`box-office-percent-${i} box-office-percent`}>{`${(item.revRate * 100).toFixed(2)}%`}</span> <span>{(item.rev / 1000000).toFixed(2)}万</span> </p> </li> ) } <li> <i /> <p>其他影片</p> </li> </ul> </div> <div className="box-office-list"> <ul className="box-office-overview"> <li> <p>{`${(sumSCnt / 10000).toFixed(2)}万`}</p> <p>总场次</p> </li> <li> <p>{`${newMovieCnt}部`}</p> <p>新上映影片</p> </li> <li> <p>{aveTicketPrice}</p> <p>平均票价</p> </li> </ul> <ul className="table-list"> <li className="table-list-title"> { BOXOFFICE_TABLE_TITLE.map((item, i) => <span key={i}>{item}</span> ) } </li> { data.map((item, i) => <li key={i}> <div> <i /> <span>{item.mTitle.length <= 5 ? item.mTitle : `${item.mTitle.slice(0, 5)}...`}</span> <span>{`已上映${item.days}天`}</span> </div> <div> <span>{(item.rev / 1000000).toFixed(2)}万</span> <span>{`${(item.revRate * 100).toFixed(2)}%`}</span> </div> <div> <span>{`${(item.sCntRate * 100).toFixed(2)}%`}</span> <span>{`${(item.sCnt / 10000).toFixed(2)}万场`}</span> </div> <div> <span>{(item.seat / 100000).toFixed(2)}%</span> </div> <div> <span>{(item.sumRev / 10000000000).toFixed(2)}亿</span> </div> </li> ) } </ul> </div> <div className="box-office-footer"> <p>{`注意:实时票房包含今日未开映场次已售出的票房,数据每30分钟更新一次,上次更新时间${upd}`}</p> </div> </div> ); } } BoxofficeList.propTypes = { upd: React.PropTypes.string.isRequired, data: React.PropTypes.array.isRequired, sumSCnt: React.PropTypes.number.isRequired, aveSeat: React.PropTypes.number.isRequired, sumRev: React.PropTypes.number.isRequired, newMovieCnt: React.PropTypes.number.isRequired, }; export default BoxofficeList; <file_sep>/src/pages/home/index.jsx import React from 'react'; import connect from 'utils/connect'; import { FOOTER_TYPE } from 'utils/constant'; import RoomSelector from 'app/selectors/home'; import Head from 'components/Head'; import Footer from 'components/Footer'; import Type from './Type'; import BoxofficeType from './BoxofficeType'; import BoxofficeList from './BoxofficeList'; import './index.scss'; class Home extends React.Component { constructor(props) { super(...props); } componentWillMount() { this.props.actions.GetMovieRevenues(); } render() { const { boxoffice } = this.props; const { upd, data, sumRev, sumSCnt, aveSeat, newMovieCnt } = boxoffice; if (!upd) { return null; } return ( <div className="home"> <Head title="Cuckoo" /> <div className="home-scroll"> <Type /> <BoxofficeType /> <BoxofficeList upd={upd} data={data} sumSCnt={sumSCnt} aveSeat={aveSeat} sumRev={sumRev} newMovieCnt={newMovieCnt} /> </div> <Footer type={FOOTER_TYPE[0]} /> </div> ); } } export default connect(Home, RoomSelector); <file_sep>/src/app/constants/ActionTypes.js // home export const GET_MOVIE_REVENUES = 'GET_MOVIE_REVENUES'; <file_sep>/src/pages/home/BoxofficeType.jsx import React from 'react'; class BoxofficeType extends React.Component { render() { return ( <div className="box-office"> <div className="box-office-title"> <span>实时票房|</span> <span>全国</span> <i /> </div> <div className="box-office-date"> <div> <i /> <span>前一日</span> </div> <div> <span>2016年12月05日</span> <i /> </div> <div> <span>后一日</span> <i /> </div> </div> <ul className="box-office-switchtype"> <li className="switchtype-movie">影片排行</li> <li className="switchtype-cinema">影院排行</li> <li className="switchtype-cinema-line">院线排行</li> </ul> </div> ); } } BoxofficeType.propTypes = { }; export default BoxofficeType;
a65cf39abe74676f60bbd3751252cb30a3cf728a
[ "JavaScript" ]
9
JavaScript
WYMisShuaiGe/Cuckoo
c5bdf96cdc3217ebce274f6295bc5587e1aa6748
88e289aad2365d16477926dbb07d73afb0a8d8ba
refs/heads/main
<repo_name>AkashKaranam/NBAShotCharts<file_sep>/python_files/aggregator.py from nba_api.stats.endpoints import shotchartdetail import json import requests import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt from tkinter import * # from tkinter import * # root = Tk() # # a = StringVar() # a.set("default") # # oc = StringVar(root) # oc.set("Select") # # def function(x): # # if x == "yes": # a.set("hello") # print(a.get()) # # else: # a.set("bye") # print(a.get()) # # o = OptionMenu(root, oc, "yes", "no", command=function) # o.pack() # # # z = a.get() # print(z) # # root.mainloop() players = json.loads(requests.get('https://raw.githubusercontent.com/bttmly/nba/master/data/players.json').text) def split_string(location): index = -1 for i in range(len(location)): if location[i] == ' ': index = i return location[:index], location[index+1:] def compute_league_averages(zone,x): area = zone[0] # print("The area is " + area) dict = {'(R)': 'Right Side(R)', '(C)': 'Center(C)', '(L)': 'Left Side(L)', '(RC)': 'Right Side Center(RC)', '(LC)': 'Left Side Center(LC)'} side = dict[zone[1]] filenames = {('Right Corner 3', 'Right Side(R)') : 'rightcorner3.txt', ('Left Corner 3', 'Left Side(L)') : 'leftcorner3.txt', ('Mid-Range', 'Left Side(L)') : 'midrangeleft.txt', ('Mid-Range', 'Left Side Center(LC)') : 'midrangeleftcenter.txt', ('Mid-Range', 'Center(C)') :'midrangecenter.txt', ('Mid-Range', 'Right Side Center(RC)') : 'midrangerightcenter.txt', ('Mid-Range', 'Right Side(R)'): 'midrangeright.txt', ('Above the Break 3', 'Left Side Center(LC)'): 'abovethebreak3leftcenter.txt', ('Above the Break 3', 'Center(C)') : 'abovethebreak3center.txt', ('Above the Break 3', 'Right Side Center(RC)'): 'abovethebreak3rightcenter.txt', ('Restricted Area', 'Center(C)') : 'restrictedareacenter.txt', ('In The Paint (Non-RA)', 'Right Side(R)') : 'inthepaintright.txt', ('In The Paint (Non-RA)', 'Center(C)') : 'inthepaintcenter.txt', ('In The Paint (Non-RA)', 'Left Side(L)') : 'inthepaintleft.txt' } input_list = [area, side] filename = filenames[tuple(input_list)] # print("The side is " + side) total_makes = 0 total_shots = 0 for player in players[x:x+1]: # print(player['']) team_id = player['teamId'] player_id = player['playerId'] context_measure_simple = 'FGA' season_nullable = '2020-21' season_type_all_start = 'Regular Season' # print("TEAM ID: " + str(team_id)) # print("PLAYER ID: " + str(player_id)) # print("CONTEXT MEASURE SIMPLE: " + context_measure_simple) # print("SEASON NUMBER: " + season_nullable) # print("SEASON TYPE: " + season_type_all_start) player_shot_json = shotchartdetail.ShotChartDetail( team_id=team_id, player_id=player_id, context_measure_simple=context_measure_simple, season_nullable=season_nullable, season_type_all_star=season_type_all_start) player_shot_data = json.loads(player_shot_json.get_json()) player_relevant_data = player_shot_data['resultSets'][0] headers = player_relevant_data['headers'] rows = player_relevant_data['rowSet'] player_data = pd.DataFrame(rows) # print(player_data.head()) # print(player_data.columns) if(player_data.shape[0] != 0): player_data.columns = headers # print(player_data.head()) # print(player_data.columns) #player_data.to_csv('lameloballbefore.csv', index=False) player_data = player_data.loc[(player_data['SHOT_ZONE_BASIC'] == area) & (player_data['SHOT_ZONE_AREA'] == side)] #player_data.to_csv('lameloball.csv', index=False) total_shots += player_data.shape[0] total_makes += player_data["SHOT_MADE_FLAG"].sum() file = open(filename, 'a') res = str(total_makes) + ' ' + str(total_shots) + '\n' file.write(res) file.close() # return total_makes, total_shots def driver(zone): made_shots = 0 total_shots = 0 for i in range(0, 100): block = compute_league_averages(zone, 5 * i) made_shots += block[0] total_shots += block[1] return made_shots, total_shots, made_shots / total_shots location = ["Right Corner 3 (R)", "Left Corner 3 (L)", "Mid-Range (L)", "Mid-Range (C)", "Mid-Range (R)", "Mid-Range (RC)", "Mid-Range (LC)", "Above the Break 3 (LC)", "Above the Break 3 (C)", "Above the Break 3 (RC)", "Restricted Area (C)", "In The Paint (Non-RA) (R)", "In The Paint (Non-RA) (C)", "In The Paint (Non-RA) (L)"] start = sys.argv[1] curr_loc = location[int(sys.argv[2])] print(compute_league_averages(split_string(curr_loc), int(start))) # print(driver(zone)) # def driver(zone): # made_shots = 0 # total_shots = 0 # for i in range(0,100): # block = compute_league_averages(zone, 5*i) # made_shots+=block[0] # total_shots+=block[1] # # return made_shots, total_shots, made_shots/total_shots <file_sep>/python_files/xogenerator.py from nba_api.stats.endpoints import shotchartdetail import json import requests import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt from tkinter import * teams = json.loads(requests.get('https://raw.githubusercontent.com/bttmly/nba/master/data/teams.json').text) players = json.loads(requests.get('https://raw.githubusercontent.com/bttmly/nba/master/data/players.json').text) # print(players) def list_first_names(): first_names = set() for player in players: first_names.add(player['firstName']) first_names_list = list(first_names) first_names_list.sort() return first_names_list def list_filtered_last_names(first_name): last_names = set() for player in players: if player['firstName'] == first_name: last_names.add(player['lastName']) last_names_list = list(last_names) last_names_list.sort() return last_names_list def list_last_names(): last_names = set() for player in players: last_names.add(player['lastName']) last_names_list = list(last_names) last_names_list.sort() return last_names_list def list_team_abrevs(): team_abrevs = [] for team in teams: team_abrevs.append(team['abbreviation']) return team_abrevs def list_team_names(): team_names = [] for team in teams: team_names.append(team['teamName']) return team_names def list_season_numbers(): seasons = [] seasons.append('2016-17') seasons.append('2017-18') seasons.append('2018-19') seasons.append('2019-20') seasons.append('2020-21') return seasons def list_season_types(): types = [] types.append('Regular Season') types.append('Playoffs') return types def get_team_id(teamName): for team in teams: if team['teamName'] == teamName: return team['teamId'] return -1 def get_player_id(first,last): for player in players: if player['firstName'] == first and player['lastName'] == last: return player['playerId'] return -1 def get_player_team(first,last): for player in players: if player['firstName'] == first and player['lastName'] == last: team_id = player['teamId'] for team in teams: if team_id == team['teamId']: return team['teamName'] return 'Nonexistent team' def get_team_name(teamAbr): for team in teams: if(team['abbreviation'] == teamAbr): return team['teamName'] return 'Nonexistent team' # def callback(input): # file = open('name.txt','w') # file.write(input) # file.close() # def update(): # print("First name selected") def user_interface(): root = Tk() root.title("Dropdown Menu for NBA Shot Chart") root.geometry("400x400") # first name block firstname_T = Text(root, height=2, width=30) firstname_T.pack() firstname_T.insert(END, "Choose Player's First Name") first_name_list = list_first_names() first_name_choice = StringVar(root) first_name_choice.set(first_name_list[0]) firstname_drop = OptionMenu(root, first_name_choice, *first_name_list) # print(first_name_choice.get()) firstname_drop.pack() # ----------------------------------------------------------------------------- # print(selection) # last name block # f = open('name.txt', 'r') # print("The contents of the file are " + f.read()) lastname_T = Text(root, height=2, width=30) lastname_T.pack() lastname_T.insert(END, "Choose Player's Last Name") last_name_list = list_last_names() last_name_choice = StringVar() last_name_choice.set(last_name_list[0]) lastname_drop = OptionMenu(root, last_name_choice, *last_name_list) lastname_drop.pack() # ----------------------------------------------------------------------------- # season block season_T = Text(root, height=2, width=30) season_T.pack() season_T.insert(END, "Choose a season") season_list = list_season_numbers() season_number_choice = StringVar() season_number_choice.set(season_list[0]) season_drop = OptionMenu(root, season_number_choice, *season_list) season_drop.pack() # ----------------------------------------------------------------------------- # team name(two cases) abbrev_T = Text(root, height=2, width=30) abbrev_T.pack() abbrev_T.insert(END, "Choose a team name") team_list = list_team_names() team_choice = StringVar() team_choice.set(team_list[0]) team_drop = OptionMenu(root, team_choice, *team_list) team_drop.pack() # ------------------------------------------------------------------------------- # team type block type_T = Text(root, height=2, width=30) type_T.pack() type_T.insert(END, "Choose a season type") type_list = list_season_types() type_choice = StringVar() type_choice.set(type_list[0]) type_drop = OptionMenu(root, type_choice, *type_list) type_drop.pack() exit_button = Button(root, text = "Submit", command = root.quit) exit_button.pack(pady=20) root.mainloop() return first_name_choice.get(), last_name_choice.get(), season_number_choice.get(), team_choice.get(), type_choice.get() def create_court(ax, color): ax.plot([-220, -220], [0, 140], linewidth=2, color=color) ax.plot([220, 220], [0, 140], linewidth=2, color=color) ax.add_artist(mpl.patches.Arc((0, 140), 440, 315, theta1 = 0, theta2 = 180, facecolor = 'none', edgecolor=color, lw=2)) ax.plot([-80,-80], [0, 190], linewidth=2, color=color) ax.plot([80, 80], [0, 190], linewidth=2, color=color) ax.plot([-60, -60], [0,190], linewidth=2, color=color) ax.plot([60,60], [0,190], linewidth=2, color=color) ax.plot([-80,80], [190,190], linewidth=2, color=color) ax.add_artist(mpl.patches.Circle((0,190), 60, facecolor='none', edgecolor=color, lw=2)) ax.add_artist(mpl.patches.Circle((0,60), 15, facecolor='none', edgecolor=color, lw=2)) ax.plot([-30,30], [40,40], linewidth=2, color=color) ax.set_xticks([]) ax.set_yticks([]) ax.set_xlim(-250,250) ax.set_ylim(0, 470) return ax # def split_string(location): # index = -1 # for i in range(len(location)): # if location[i] == ' ': # index = i # return location[:index], location[index+1:] # def compute_league_averages(zone): # area = zone[0] # dict = {'(R)':'Right Side(R)', '(C)':'Center(C)', '(L)':'Left Side(L)', '(RC)': 'Right Side Center(RC)', '(LC)': 'Left Side Center(LC)'} # side = dict[zone[1]] # total_makes = 0 # total_shots = 0 # for player in players: # team_id = player['teamId'] # player_id = player['playerId'] # context_measure_simple = 'FGA' # season_nullable = '2020-21' # season_type_all_start = 'Regular Season' # player_shot_json = shotchartdetail.ShotChartDetail( # team_id=team_id, # player_id=player_id, # context_measure_simple=context_measure_simple, # season_nullable=season_nullable, # season_type_all_star=season_type_all_start) # player_shot_data = json.loads(player_shot_json.get_json()) # player_relevant_data = player_shot_data['resultSets'][0] # headers = player_relevant_data['headers'] # rows = player_relevant_data['rowSet'] # # player_data = pd.DataFrame(rows) # player_data.columns = headers # # player_data = player_data.loc[(player_data['SHOT_ZONE_BASIC'] == area) & (player_data['SHOT_ZONE_AREA'] == side)] # total_shots += player_data.shape[0] # total_makes += player_data["SHOT_MADE_FLAG"].sum() # # return total_makes, total_shots inputs = user_interface() #print(inputs) player_first_name = inputs[0] player_last_name = inputs[1] season_nullable = inputs[2] player_team = inputs[3] context_measure_simple = 'FGA' season_type_all_start = inputs[4] team_id = get_team_id(player_team) player_id = get_player_id(player_first_name, player_last_name) note = player_first_name + " " + player_last_name + "\n" + season_nullable + " " + season_type_all_start filename = "../Images/MakesMisses_" + player_first_name + player_last_name + "_" + season_nullable + ".png" shot_json = shotchartdetail.ShotChartDetail( team_id = team_id, player_id = player_id, context_measure_simple = context_measure_simple, season_nullable = season_nullable, season_type_all_star = season_type_all_start) shot_data = json.loads(shot_json.get_json()) relevant_data = shot_data['resultSets'][0] headers = relevant_data['headers'] rows = relevant_data['rowSet'] player_data = pd.DataFrame(rows) player_data.columns = headers player_data.to_csv('../data.csv', index=False) player_makes = player_data.loc[player_data['SHOT_MADE_FLAG'] == 1] player_misses = player_data.loc[player_data['SHOT_MADE_FLAG'] == 0] mpl.rcParams['font.family'] = 'Avenir' mpl.rcParams['font.size'] = 18 mpl.rcParams['axes.linewidth'] = 2 fig = plt.figure(figsize=(4, 3.76)) ax = fig.add_axes([0, 0, 1, 1]) ax = create_court(ax, 'black') ax.plot(player_misses['LOC_X'], player_misses['LOC_Y'] + 60, 'ro') ax.plot(player_makes['LOC_X'], player_makes['LOC_Y'] + 60, 'go') ax.text(0, 1.05, note, transform=ax.transAxes, ha = 'left', va = 'baseline') plt.savefig(filename, dpi=300, orientation = 'landscape', bbox_inches='tight') plt.show() <file_sep>/python_files/ChartGenerator.py from nba_api.stats.endpoints import shotchartdetail import json import requests import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt # load team and player data from nba.com teams = json.loads(requests.get('https://raw.githubusercontent.com/bttmly/nba/master/data/teams.json').text) players = json.loads(requests.get('https://raw.githubusercontent.com/bttmly/nba/master/data/players.json').text) # print(teams) # print(players) def get_team_id(teamName): ''' Output team id from team name :param teamName: string representing a teamName :return: nba.com team id for the given teamName or -1 if the teamName is invalid ''' for team in teams: if team['teamName'] == teamName: return team['teamId'] return -1 def get_player_id(first,last): ''' Output the player id from their first and last name :param first: string representing the first name of the player :param last: string representing the last name of the player :return: the nba.com player id of the given player name ''' for player in players: if player['firstName'] == first and player['lastName'] == last: return player['playerId'] return -1 def create_court(ax, color): ''' Method to draw the court :param ax: axis object used to draw the court :param color: color of the lines and curves on the court :return: an axis object representing the court ''' ax.plot([-220, -220], [0, 140], linewidth=2, color=color) ax.plot([220,220], [0,140], linewidth=2, color=color) ax.add_artist(mpl.patches.Arc((0,140), 440, 315, theta1 = 0, theta2 = 180, facecolor = 'none', edgecolor=color, lw=2)) ax.plot([-80,-80], [0, 190], linewidth=2, color=color) ax.plot([80, 80], [0, 190], linewidth=2, color=color) ax.plot([-60, -60], [0,190], linewidth=2, color=color) ax.plot([60,60], [0,190], linewidth=2, color=color) ax.plot([-80,80], [190,190], linewidth=2, color=color) ax.add_artist(mpl.patches.Circle((0,190), 60, facecolor='none', edgecolor=color, lw=2)) ax.add_artist(mpl.patches.Circle((0,60), 15, facecolor='none', edgecolor=color, lw=2)) ax.plot([-30,30], [40,40], linewidth=2, color=color) ax.set_xticks([]) ax.set_yticks([]) ax.set_xlim(-250,250) ax.set_ylim(0, 470) return ax # def find_lebron(): # bin = [] # for player in players: # if player['lastName'] == 'James' or player['firstName'] == 'James': # bin.append(player) # return bin player_first_name = input("Enter the player's first name: ") player_last_name = input("Enter the player's last name: ") player_team = input("Enter the player's team's name: ") context_measure_simple = input("Enter either PTS or FGA: ") season_nullable = input("Enter the season: ") season_type_all_start = input("Enter the season type: ") team_id = get_team_id(player_team) player_id = get_player_id(player_first_name, player_last_name) note = player_first_name + " " + player_last_name + "\n" + season_nullable + " " + season_type_all_start filename = "ShortChart_" + player_first_name + player_last_name + "_" + season_nullable + ".png" shot_json = shotchartdetail.ShotChartDetail( team_id = team_id, player_id = player_id, context_measure_simple = context_measure_simple, season_nullable = season_nullable, season_type_all_star = season_type_all_start) # print(get_team_id('New <NAME>')) # print(find_lebron()) # print(get_player_id('LeBron', 'James')) shot_data = json.loads(shot_json.get_json()) relevant_data = shot_data['resultSets'][0] headers = relevant_data['headers'] rows = relevant_data['rowSet'] player_data = pd.DataFrame(rows) player_data.columns = headers # print(curry_data.columns) mpl.rcParams['font.family'] = 'Avenir' mpl.rcParams['font.size'] = 18 mpl.rcParams['axes.linewidth'] = 2 fig = plt.figure(figsize=(4, 3.76)) ax = fig.add_axes([0, 0, 1, 1]) ax = create_court(ax, 'black') ax.hexbin(player_data['LOC_X'], player_data['LOC_Y'] + 60, gridsize=(30,30), extent=(-300,300,0,940), bins = 'log', cmap='Blues') ax.text(0, 1.05, note, transform=ax.transAxes, ha = 'left', va = 'baseline') plt.savefig(filename, dpi=300, bbox_inches='tight') plt.show() <file_sep>/README.md # NBAShotCharts Goal: Map NBA players shots using a variety of data visualization techniques in order to better understand players shooting strengths and weaknesses. Completed: - Used the NBA_API to scrape nba shot data from stats.nba.com and generate a hexbin visualization that darkened hexagons if a comparatively large number of shots were made from that area - Generated the standard shot chart mapping made shots to green dots on an nba court and missed shots to red dots on an nba court. - Developed GUI to allow for dropdown selection of player and season to be charted - Implemented functions to aggregate league averages from 18 zones on the court and compare an individual player to the league average TODO: - Create a heat zone map to map a certain players efficiency in relation to league average in each zone - Create a frequency zone map to map a certain players shot attempts in relation to league average in each zone <file_sep>/python_files/dropdown.py from tkinter import * from PIL import ImageTk, Image root = Tk() root.title("Dropdown Menu For NBA Shot Chart") root.geometry("400x400") clicked = StringVar() clicked.set("Monday") clicked1 = StringVar() clicked1.set("March") drop = OptionMenu(root, clicked,"Monday", "Tuesday", "Wednesday", "Thursday", "Friday") drop.pack() drop1 = OptionMenu(root, clicked1, "January", "February", "March", "April") drop1.pack() # T = Text(root, height=2, width=30) # T.pack() # T.insert(END, "Choose Player's First Name") # listaEquipos = ['Equipos'] # menuEquipoText = StringVar(root) # menuEquipoText.set(listaEquipos[0]) # menuEquipo = OptionMenu(root, menuEquipoText, *'Hello') # menuEquipo.pack() # # T1 = Text(root, height=2, width=30) # T1.pack() # T1.insert(END, "Choose Player's Last Name") root.mainloop() # print("CLICKED") # day = clicked.get() # print(day) <file_sep>/python_files/visualization.py from nba_api.stats.endpoints import shotchartdetail import json import requests import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt teams = json.loads(requests.get('https://raw.githubusercontent.com/bttmly/nba/master/data/teams.json').text) players = json.loads(requests.get('https://raw.githubusercontent.com/bttmly/nba/master/data/players.json').text) print(type(players)) def read_data(filename): made = [] total = [] file = open(filename, 'r') for i in range(0,501): str = file.readline() # print(str) curr = [int(s) for s in str.split() if s.isdigit()] made.append(curr[0]) total.append(curr[1]) return made, total def compute_average(filename): made_sum = 0 total_sum = 0; made,total = filename for m in made: made_sum = made_sum + m for t in total: total_sum = total_sum + t def name_to_index(first, last): for i in range(len(players)): if(players[i]['firstName'] == first and players[i]['lastName'] == last): return i def draw(first, last, filename): made, total = read_data(filename) i = name_to_index(first,last) curr_player_makes = made[i] curr_player_total_shots = total[i] print(read_data('midrangeleft.txt')) print(name_to_index('Precious', 'Achiuwa'))
d9e27479aba4c814bf9d313f7adb2ba055c6a39a
[ "Markdown", "Python" ]
6
Python
AkashKaranam/NBAShotCharts
b14d9f3093a4bacade3b013b2917109ecdab125c
f37f45af6094e0482278fe67c617c18149c69ec6
refs/heads/main
<repo_name>LarsVeggeland/PAN20-Authorship-Verification<file_sep>/src/Data.py #---------- Imorted Libraries ---------- from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from nltk import ngrams import re from collections import defaultdict, Counter import datetime import json import timeit import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer #Not an imported library but the svm model from Svm import svm #---------- Variables ---------- #Words such as the, and, or, a, i.e, frequent words which are common for most texts. sw : set = set(stopwords.words("english")) #Tries to convert a word into its dictionary form, i.e, its lemma lemmatizer = WordNetLemmatizer() #---------- Clean Data ---------- def remove_stopwords(words : list): return [w for w in words if w not in sw] def normalize_data(data : list): for i in range(len(data)): #Simple step to normalize the data. Models are not aware that Hi and hi are the same word. data[i] = data[i].lower() #Reducing a word to its lemma data[i] = lemmatizer.lemmatize(data[i]) return data def remove_symbols(data : list): #A patter which will match any sequence of the included symbols pattern = re.compile(r"[\.,:;!?\"<>*-+`']+") for i in range(len(data)): #Removing symbol sequences matching the pattern data[i] = re.sub(pattern, r"", data[i]) return data def clean_data(data : list): cleaned_text_pair : list =[] for text in data: #Breaks the entire text into a list of words. words : list = word_tokenize(text) words = remove_symbols(words) words = normalize_data(words) words = remove_stopwords(words) cleaned_text_pair.append(" ".join(words)) return cleaned_text_pair #---------- Vectorize data ---------- def retrieve_vector_space_values(vector_space : list, vector_labels : list, vectorized_text_pair : np.array): vectors : list = [0]*len(vector_space) for vec in range(len(vector_space)): try: column_index : int = vector_labels.index(vector_space[vec]) column : np.array = vectorized_text_pair[:, column_index] vectors[vec] = abs(column[0] - column[1]) except ValueError as e: #The vector does not exist in the vectorized text pair, its value is already 0... pass return np.array(vectors) #TF-IDF def tf_ifd_transform(text_pair : list, analyzer : str, ngram_range : tuple): tf_idf = TfidfVectorizer(analyzer=analyzer, ngram_range=ngram_range) t = tf_idf.fit_transform(text_pair) a = t.toarray() return a, tf_idf.get_feature_names() #TF-IDF frequencies def tf_idf_vectorizer(text_pairs : list, vector_space : list, analyzer : str = "word", n_gram_range : tuple = (1, 1)): vectorized_text_pairs : list = [None]*len(text_pairs) c = 1 for i in range(len(text_pairs)): frequencies, features = tf_ifd_transform(text_pairs[i], analyzer=analyzer, ngram_range=n_gram_range) vectorized_text_pairs[i] = retrieve_vector_space_values(vector_space, features, frequencies) if (i == int((len(text_pairs)/10)*c)): print(f"{datetime.datetime.now()}: Vectorization at {c}0 %") c += 1 print(f"{datetime.datetime.now()}: Vectorization at 100 %") return vectorized_text_pairs #---------- Get data and related information ---------- def get_text_pairs(clean : bool, path : str, cutoff : int = None): id_and_texts : dict = {} with open(path, "r") as file: jsonlist = list(file)[:10] texts : list = [None]*len(jsonlist) for i in range(len(jsonlist)): entry = json.loads(jsonlist[i]) text_pair = entry["pair"] if (clean): text_pair = clean_data(text_pair) if (cutoff is not None): #Simply using the first and last n=cutoff number of words for each document text1 = word_tokenize(text_pair[0]) text2 = word_tokenize(text_pair[1]) del(text1[cutoff:-cutoff]) del(text2[cutoff:-cutoff]) text_pair = [" ".join(text1), " ".join(text2)] texts[i] = text_pair return texts def get_truth(path : str): #Boolean values are written with lower case... true = True false = False with open(path, "r") as file: jsonlist = list(file)[:10] truths : list = [None]*len(jsonlist) for i in range(len(jsonlist)): entry = json.loads(jsonlist[i]) truths[i] = entry["same"] return truths def get_training_data(shared_words : int = 0, ordered_words : int = 0, n_grams : tuple = None, funcwords : bool = False, largest_word_count : bool = False, cleaning : bool=True, cutoff : int = None, PATH : str): if (bool(shared_words) + bool(ordered_words) + bool(n_grams) > 1): print("ERROR! More than one dimension specified") raise Exception(print(f"shared_word : f{bool(shared_words)}\nordered_words : f{bool(ordered_words)}\nn_grams : f{bool(n_grams)}")) vectorized_data : list = [] labels : list = [] vector_space : list = [] vectorized_text_pairs : list = None print(f"\n{datetime.datetime.now()}: Collecting data...\n") #Two lists contaning text pairs and whether both texts weree written by the same author text_pairs = get_text_pairs(cleaning, PATH, cutoff) truths = get_truth(PATH) print(f"{datetime.datetime.now()}: Data collected, extracting vector space...\n") if (shared_words): vector_space = get_words_n_times_in_all_texts(text_pairs, shared_words) elif (ordered_words): vector_space = get_n_most_frequent_words(text_pairs, ordered_words) elif (n_grams): vector_space = get_n_most_frequent_ngrams(text_pairs, n_grams[0], n_grams[1]) #Requires a different TF-IDF vectorizer print(f"{datetime.datetime.now()}: vector space extracted, vectorizing data...\n") vectorized_text_pairs = tf_idf_vectorizer(text_pairs, vector_space, analyzer="char", n_gram_range=(n_grams[0], n_grams[0])) elif (largest_word_count): vector_space = get_wordcount_from_most_verbose_text(text_pairs) elif (funcwords): vector_space = get_function_words() if vectorized_text_pairs is None: print(f"{datetime.datetime.now()}: vector space extracted, vectorizing data...\n") vectorized_text_pairs = tf_idf_vectorizer(text_pairs, vector_space) print(f"{datetime.datetime.now()}: data collection and vectorization completed") X, Y = np.array(vectorized_text_pairs), np.array(truths) #vectorized_text_pairs = vectorized_text_pairs.reshape(vectorized_text_pairs.shape[1:]) print(len(X), len(Y)) return X, Y, np.array(vector_space) def get_function_words(): func_words : list = [] with open("Mosteller_Wallace_function_words.txt", 'r') as file: for word in file.readlines(): #Removes trailing newline character func_words.append(word[:-1]) return func_words def get_n_most_frequent_words(text_pairs : list, n: int): counter = defaultdict(int) for i in range(len(text_pairs)): #A list containing all words in both texts words = word_tokenize(text_pairs[i][0]) + word_tokenize(text_pairs[i][1]) for word in words: counter[word] += 1 #Sorts words by their frequency ordered = sorted(counter.items(), key=lambda kv : kv[1], reverse=True) if (n > len(ordered)): print(f"\nWARNING! n exceeds total number of distinct words\n") return ordered return [entry[0] for entry in ordered][:n] def get_words_n_times_in_all_texts(text_pairs : list, n : int = 1): words = set() for i in range(len(text_pairs)): #Getting all words and their frequncy for both texts text1_words = word_tokenize(text_pairs[i][0]) text2_words = word_tokenize(text_pairs[i][1]) text1_word_count = Counter(text1_words) text2_word_count = Counter(text2_words) #Removing all words whose frequency is less than n words_more_than_n_text1 = [kv[0] for kv in text1_word_count.items() if kv[1] >= n] words_more_than_n_text2 = [kv[0] for kv in text2_word_count.items() if kv[1] >= n] #Retrieving words with satisfactory frequency in both texts shared_words = set(words_more_than_n_text1).intersection(set(words_more_than_n_text2)) if len(words) == 0: words = shared_words else: #Updating the set of words satisfying the condition words = words.intersection(shared_words) return list(words) def get_n_most_frequent_ngrams(text_pairs : list, gram_size : int, n : int): #<NAME> and <NAME>inter n_grams : dict = defaultdict(int) #Matches all sequences of whitecase characters including \n, \t, \r, ... pattern = re.compile(r"\s+") for i in range(len(text_pairs)): #Removing whitespaces on the data itself as they are not deemed important text1 = re.sub(pattern, r"", text_pairs[i][0]) text2 = re.sub(pattern, r"", text_pairs[i][1]) text_pairs[i] = [text1, text2] for text in text_pairs[i]: for gram in ngrams(text, gram_size): n_grams["".join(gram)] += 1 #Sorts grams by their frequency in descending order ordered_grams = sorted([(gram, frequency) for gram, frequency in n_grams.items()], key=lambda kv : kv[1], reverse=True)[:n] #Returns the grams in sorted order return [x[0] for x in ordered_grams] if __name__ == '__main__': #Uncomment and specify feature set in get training data x, y, z = get_training_data(shared_words = 5000) svm(x, y, z) <file_sep>/README.md # PAN20-Authorship-Verification Determining whether two bodies of texts are written by the same author is the core of authorship verification. To accurately assess whether to texts share author, there exist a need for a feature set which catches the key stylometric features unique for all authors. The task undertaken in this project was to find a suitable feature set for determining whether two texts, from a collection of texts with unknown authors, were written by the same author. Four different feature sets are presented and evaluated on how well they enable a model to simply verify whether two unknown texts share authors. <br></br> <h2><b>Features</b></h2> Most of the feature sets consider words and their frequency in the texts for stylometric representation for different authors. <h3><b>n most frequent words in corpus</b></h3> One key aspect to consider with the task is that there are thousands of authors writing fictional texts within different fandoms. This combined with the fact that the model is tasked with determining whether two texts share author, there existed a need for representing every text, and thereby every text pair, in an equal manner. The initial approach was to extract the n most frequent words after the data was cleaned and return those words in a descending order. <br></br> <h3><b>Set of words shared by all texts</b></h3> Some of the more common words in the corpus may not exist in all texts or even all text pairs to be considered. Considering the difference in word frequency between two texts where the word does not exist is of little value. Solely considering the words appearing in all texts should avoid such scenarios. <br></br> <h3><b>Function words</b></h3> Function words are defined in the oxford dictionary as “a word that is important to the grammar of a sentence rather than its meaning, for example ‘do’ in ‘we do not live here’”. The rate at which different words are used will vary between authors. Thus, one can reveal differences in writing style through simply inspecting how the usage of function words differ between documents. This approach was originally introduced by <NAME> and <NAME> when attempting to attribute authorship for the 12 disputed essays from the famous Federalist papers. In this project 70 such function words were used. Every document is represented by a list containing the frequency for each function word <br></br> <h3><b>Most frequent n-grams</b></h3> Considering sequences of characters instead of words is a more fine-grained approach. This feature set would include the n most frequent 4-character ngrams from the entire corpus. <br></br> <h3><b>Dataset</b></h3> The dataset is provided by PAN for the PAN 2020 Authorship verification contest (PAN, 2021). PAN provided the data in two different sizes, a large and small version where the latter was used in this project. All data provided by PAN was collected from the website FanFiction.net. This website enables their users to submit and share their own fictional works. The dataset consists of several tens of thousands of entries holding containing the two texts both containing roughly 21,000 characters. Each such entity also containing a unique id for the author(s) of the two texts. In addition, as all texts are works of fiction, the appropriate fandom is provided for both texts. The dataset will not be found in this repository, but it may be obtained through requesting access at https://zenodo.org/record/3724096 <file_sep>/src/Svm.py #---------- Imported Libraries ---------- from sklearn.model_selection import train_test_split as tts from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity from sklearn.svm import SVC from collections import Counter from nltk.tokenize import word_tokenize import numpy as np import time #---------- Prepare Data ---------- def prep_data(X, Y, train_size : float = 0.9): #Splits the text pairs and truth values into seperate into training and test data return tts(X, Y, train_size=train_size) #---------- Train Model ---------- def svm(X, Y, vec_space): X_train, X_test, Y_train, Y_test = prep_data(X, Y) X_train, X_test = np.array(X_train), np.array(X_test) svm = SVC(kernel='linear') svm.fit(X_train, Y_train) print("Training completed, evaluating model...") Y_pred = svm.predict((X_test)) c = 0 for i in range(len(Y_test)): c += Y_pred[i] == Y_test[i] print(f"Accuracy: {round(c/len(Y_test) * 100, 2)} %")
a09656140e4e9d61ee7d979b81b1a76f315eaab4
[ "Markdown", "Python" ]
3
Python
LarsVeggeland/PAN20-Authorship-Verification
2d4bae35b88b5fb636475d23bbda1f00c2d0d80f
a34b1fa7d2a6ad20e0ea6834a029dd7c39f76147
refs/heads/master
<file_sep>import { Component } from '@angular/core'; import {ModalController} from '@ionic/angular'; import {ModalPage} from '../modal/modal.page'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], }) export class HomePage { constructor( private modalCtrl: ModalController, ) { console.log('page has loaded'); } async modalfunc() { const modal = await this.modalCtrl.create({ component: ModalPage, componentProps: { value: 'this is my modal' } }); return await modal.present(); } async modalfunc1() { const modal = await this.modalCtrl.create({ component: ModalPage, componentProps: { value: 'this is my modal' } }); return await modal.present(); } showHide() { let toggleDiv = document.getElementById('toggleDiv'); let toggleDiv1 = document.getElementById('toggleDiv1'); let toggleDiv2 = document.getElementById('toggleDiv2'); let div1 = document.getElementById('root'); if (toggleDiv.style.display = 'none') { toggleDiv.style.display = 'block' div1.style.display= 'none' } } showHide1() { let toggleDiv = document.getElementById('toggleDiv'); let toggleDiv1 = document.getElementById('toggleDiv1'); let toggleDiv2 = document.getElementById('toggleDiv2'); let div1 = document.getElementById('root'); if (toggleDiv1.style.display = 'none') { toggleDiv1.style.display = 'block' div1.style.display= 'none' } } showHide2() { let toggleDiv = document.getElementById('toggleDiv'); let toggleDiv1 = document.getElementById('toggleDiv1'); let toggleDiv2 = document.getElementById('toggleDiv2'); let div1 = document.getElementById('root'); if (toggleDiv2.style.display = 'none') { toggleDiv2.style.display = 'block' div1.style.display= 'none' } } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ModalController, NavParams, Input } from '@ionic/angular'; import {AlertController} from '@ionic/angular'; let newa = document.createElement('ion-card'); let num = 0; let elementids = 'card' @Component({ selector: 'app-modal', templateUrl: './modal.page.html', styleUrls: ['./modal.page.scss'], }) export class ModalPage implements OnInit { myElements: any = []; constructor(private modalCtrl: ModalController, private navParams: NavParams, private alertCtrl: AlertController,) { } ngOnInit() { let myValue = this.navParams.get("value"); console.log(myValue); } dismiss() { this.modalCtrl.dismiss(); } async presentAlert() { let add = document.getElementById('add'); let newa = document.createElement('ion-card'); const alert = await this.alertCtrl.create({ header: 'Add Homework', subHeader: 'Which homework are you working on?', inputs: [{ id: 'input1', type: 'text', placeholder: "Type Here", }], buttons: [{ text: 'Cancel', handler: data => { console.log('canceled') } }, { text: 'Add', handler: data =>{ let input1 = <HTMLInputElement>document.getElementById('input1'); let work = input1.value; console.log (work); newa.id = 'card' + num.toString(); //num="0" console.log(newa.id) console.log(typeof newa.id) this.myElements.push(newa.id) console.log(this.myElements) num ++; newa.innerText = work; add.appendChild(newa); newa.onclick = (async) => this.classFunction1(); } } ] }) alert.onDidDismiss().then( () => { console.log('stuff is dismissed'); }) await alert.present(); } classFunction() { console.log('test'); this.presentAlert(); } async presentAlert1() { const alert = await this.alertCtrl.create({ header: 'Move homework to doing.', message: 'Are you sure?', buttons: [ { text: 'Cancel', handler: data => { console.log('canceled') } }, { text: 'Yes', handler: data =>{ console.log ('YES'); document.getElementById('there').appendChild(document.getElementById('card0')) console.log(newa) } } ]}) alert.onDidDismiss().then( () => { console.log('stuff is dismissed'); }) await alert.present(); } async classFunction1() { console.log('test'); this.presentAlert1(); } // async func() { // document.getElementById('there').appendChild(newa) // console.log(newa) // } } <file_sep># Here-you-go-Phat<file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-doing', templateUrl: './doing.page.html', styleUrls: ['./doing.page.scss'], }) export class DOINGPage implements OnInit { constructor() { } ngOnInit() { } }
83ffa287f14f9ce02077a8304d7711349cb43ed1
[ "Markdown", "TypeScript" ]
4
TypeScript
priceless99/Here-you-go-Phat
2e87cfe5478de19e3a4e631fc0fa10a4abd263f6
0f6503ea9690b40b5a6b3111395c70f92a9e5b5f
refs/heads/main
<file_sep>function test(regExp, ...args) { let [result] = [args]; for (const i of result) { console.log(regExp.test(i)); } } // Lesson 1: An Introduction, and the ABCs /* let word1 = "abcdefg"; let word2 = "abcde"; let word3 = "abc"; let regEx = new RegExp("abc"); test(regEx, word1, word2, word3); */ // Lesson 1½: The 123s /* let num1 = `abc123xyZ`; let num2 = `define "123"`; let num3 = 123; let regEx = /\d/; test(regEx, num1, num2, num3); */ // Lesson 2: The Dot /* let dot1 = "cat."; let dot2 = "234."; let dot3 = "?$+=."; let dot4 = "abc1"; //skip let regEx = /\./; test(regEx, dot1, dot2, dot3, dot4); */ // Lesson 3: Matching specific characters /* let word1 = "can"; let word2 = "man"; let word3 = "fan"; let word4 = "ran"; //skip let regEx = /[cmf]/; test(regEx, word1, word2, word3, word4); */ // Lesson 4: Excluding specific characters /* let word1 = "hot"; let word2 = "dog"; let word3 = "bog"; let regEx = /[^bog]/; test(regEx, word1, word2, word3); */ // Lesson 5: Character ranges /* let word1 = "HOT"; let word2 = "hot"; let word3 = "DOG"; let regEx = /[A-Z]/; test(regEx, word1, word2, word3); */ // Lesson 6: Catching some zzz's /* let word1 = "wazzzzzup"; let word2 = "wazzzup"; let word3 = "wazap"; let regEx = /z{3,5}/; test(regEx, word1, word2, word3); */ // Lesson 7: Mr. Kleene, Mr. Kleene /* let word1 = "aaaabbcc"; let word2 = "aabbbcc"; let word3 = "a"; let regEx = /a.+/; test(regEx, word1, word2, word3); */ // Lesson 8: Characters optional /* let word1 = "1 file found?"; let word2 = "2 files found?"; let word3 = "24 files found?"; let word4 = "No files found"; let regEx = /\?/; test(regEx, word1, word2, word3, word4); */ // Lesson 9: All this whitespace /* let word1 = "1 abc"; let word2 = "2 abc"; let word3 = "3 abc"; let word4 = "4abc"; let regEx = /( )/; // \d\.\s+abc test(regEx, word1, word2, word3, word4); */ // Lesson 10: Starting and ending /* let match = "Mission: successful"; let skip1 = "Last Mission: unsuccessful"; let skip2 = "Next Mission: successful upon capture of target"; let regEx = /^Mission: successful$/; test(regEx, match, skip1, skip2); */ // Lesson 11: Match groups /* let match1 = "file_record_transcript.pdf"; let match2 = "file_07241999.pdf"; let skip1 = "testfile_fake.pdf.tmp"; let regEx = /^(file.+)\.pdf$/; test(regEx, match1, match2, skip1); */ // Lesson 12: Nested groups /* let match1 = "Jan 1987"; let match2 = "May 1969"; let match3 = "Aug 2011"; let regEx = /([A-z]+ (\d+))/; test(regEx, match1, match2, match3); */ // Lesson 13: More group work /* let match1 = "1280x720"; let match2 = "1920x1600"; let match3 = "1024x768"; let regEx = /(\d+)x(\d+)/; test(regEx, match1, match2, match3); */ // Lesson 14: It's all conditional /* let match1 = "I love cats"; let match2 = "I love dogs"; let match3 = "I love mouse"; let regEx = /I love *(cats|dogs)/; test(regEx, match1, match2, match3); */
9f876e2aee85829afe8a51fbbca5be1608c46675
[ "JavaScript" ]
1
JavaScript
haykbazoyan/Lesson014RegEx-Errors
7c268c11d6df26a1bb4635c238969cf164e09add
66c2fb58cf26f61f7b52bef174d0c714eb4cbc8f
refs/heads/main
<repo_name>soyangelaromero/Alimenmar<file_sep>/sistema/includes/footer.php <footer> <div> <p style="color: white; font-size: 16px; line-height: 25px; margin-left: 200px""><b>Correo Electrónico:</b> <EMAIL></p> <p style="color: white; font-size: 16px; line-height: 25px; margin-left: 200px""><b>Dirección:</b> Edificio CB-3. Porlamar, Estado Nueva Esparta</p> <p style="color: white; font-size: 16px; line-height: 25px; margin-left: 200px""><b>Teléfonos:</b> +58 (424) 8836001, +58 (414) 9806081, +58 (424) 8600550</p> <p style="color: white; font-size: 16px; line-height: 25px; margin-left: 200px""><b>Diseño y desarrollo por:</b> <NAME>., <NAME>, <NAME>.</p> </div> <div> <p style="color: white; font-size: 16px; line-height: 25px; margin-left: 200px"">© 2021 Alimentos Marinos de Nueva Esparta C.A. Derechos reservados.</p> </div> </footer> <file_sep>/sistema/index.php <?php session_start(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <?php include "includes/scripts.php"; ?> <link href="css/estilos.css" rel="stylesheet"> <title>Inicio</title> </head> <body> <?php include "includes/header.php"; ?> <section id="container"> <h1>¡Bienvenido de vuelta!</h1> <div class="gallery1"> <img src="../Images/barco1.jpg" width="260" height="260"> <img src="../Images/barco2.jpg" width="260" height="260"> <img src="../Images/barco3.jpg" width="260" height="260"> <img src="../Images/barco4.jpg" width="260" height="260"> <img src="../Images/barco5.jpg" width="260" height="260"> <img src="../Images/barco6.jpg" width="260" height="260"> <img src="../Images/barco7.jpg" width="260" height="260"> <img src="../Images/barco8.jpg" width="260" height="260"> </div> </section> <?php include "includes/footer.php"; ?> </body> </html><file_sep>/sistema/editar_barco.php <?php session_start(); if($_SESSION['rol'] != 1) { header("location: ./"); } include "../conexion.php"; if(!empty($_POST)) { $alert=''; if(empty($_POST['nombre']) || empty($_POST['tripulacion']) || empty($_POST['capacidad']) || empty($_POST['operador'])) { $alert='<p class="msg_error">Todos los campos son obligatorios.</p>'; }else{ $idbarco = $_POST['id']; $nombre = $_POST['nombre']; $operador = $_POST['operador']; $tripulacion = $_POST['tripulacion']; $capacidad = $_POST['capacidad']; $sql_update = mysqli_query($conection,"UPDATE barcos SET nombre = '$nombre', operador='$operador', tripulacion='$tripulacion',capacidad='$capacidad' WHERE codbarco= $idbarco "); if($sql_update){ $alert='<p class="msg_save">Barco actualizado correctamente.</p>'; }else{ $alert='<p class="msg_error">Error al actualizar el barco.</p>'; } } } //Mostrar Datos if(empty($_REQUEST['id'])) { header('Location: lista_barcos.php'); mysqli_close($conection); } $idbarco = $_REQUEST['id']; $sql= mysqli_query($conection,"SELECT * FROM barcos WHERE codbarco= $idbarco "); mysqli_close($conection); $result_sql = mysqli_num_rows($sql); if($result_sql == 0){ header('Location: lista_barcos.php'); }else{ while ($data = mysqli_fetch_array($sql)) { # code... $idbarco = $data['codbarco']; $nombre = $data['nombre']; $operador = $data['operador']; $tripulacion = $data['tripulacion']; $capacidad = $data['capacidad']; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <?php include "includes/scripts.php"; ?> <title>Actualizar Barco</title> </head> <body> <?php include "includes/header.php"; ?> <section id="container"> <div class="form_register"> <h1>Actualizar Barco</h1> <hr> <div class="alert"><?php echo isset($alert) ? $alert : ''; ?></div> <form action="" method="post"> <input type="hidden" name="id" value="<?php echo $idbarco;?>"> <label for="nombre">Nombre</label> <input type="text" name="nombre" id="nombre" placeholder="Nombre del Barco" value="<?php echo $nombre ?>"> <label for="operador">Operador</label> <input type="text" name="operador" id="operador" placeholder="Operador" value="<?php echo $operador ?>"> <label for="tripulacion">Tripulación</label> <input type="number" name="tripulacion" id="tripulacion" placeholder="Tripulación"value="<?php echo $tripulacion ?>"> <label for="capacidad">Capacidad (Kg)</label> <input type="number" name="capacidad" id="capacidad" placeholder="Capacidad (Kg)" value="<?php echo $capacidad ?>"> <input type="submit" value="Actualizar Barco " class="btn_save"> </form> </div> </section> </body> </html><file_sep>/BD/basededatos.sql -- phpMyAdmin SQL Dump -- version 4.8.5 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 20-06-2021 a las 05:45:34 -- Versión del servidor: 10.1.38-MariaDB -- Versión de PHP: 7.3.2 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; 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 */; -- -- Base de datos: `basededatos` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `barcos` -- CREATE TABLE `barcos` ( `codbarco` int(11) NOT NULL, `nombre` varchar(200) NOT NULL, `operador` varchar(200) NOT NULL, `tripulacion` int(11) NOT NULL, `capacidad` decimal(10,2) NOT NULL, `usuario_id` int(11) NOT NULL, `estatus` int(11) NOT NULL DEFAULT '1' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `barcos` -- INSERT INTO `barcos` (`codbarco`, `nombre`, `operador`, `tripulacion`, `capacidad`, `usuario_id`, `estatus`) VALUES (1, 'Sirena', 'Alejandro', 100, '2000.00', 1, 1), (2, 'Margarita Island', 'Angela', 200, '50000.00', 1, 1); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `detallefactura` -- CREATE TABLE `detallefactura` ( `correlativo` bigint(11) NOT NULL, `nofactura` bigint(11) DEFAULT NULL, `codproducto` int(11) DEFAULT NULL, `cantidad` int(11) DEFAULT NULL, `preciototal` decimal(10,2) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `entradas` -- CREATE TABLE `entradas` ( `correlativo` int(11) NOT NULL, `codproducto` int(11) NOT NULL, `fecha` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `cantidad` int(11) NOT NULL, `precio` decimal(10,2) NOT NULL, `usuario_id` int(11) NOT NULL DEFAULT '1' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `entradas` -- INSERT INTO `entradas` (`correlativo`, `codproducto`, `fecha`, `cantidad`, `precio`, `usuario_id`) VALUES (1, 1, '0000-00-00 00:00:00', 150, '110.00', 1), (2, 2, '2018-04-05 00:12:15', 100, '1500.00', 1), (3, 3, '2018-04-07 22:48:23', 200, '250.00', 9), (4, 4, '2018-09-08 22:28:50', 50, '10000.00', 1), (5, 5, '2018-09-08 22:34:38', 100, '500.00', 1), (6, 6, '2018-09-08 22:35:27', 8, '2000.00', 1), (7, 7, '2018-12-02 00:15:09', 75, '2200.00', 1), (8, 8, '2018-12-02 00:39:42', 75, '160.00', 1); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `facturas` -- CREATE TABLE `facturas` ( `codfac` int(20) NOT NULL, `fecha` date NOT NULL, `hora` char(50) NOT NULL, `mercancia` bigint(50) NOT NULL, `gananciab` bigint(20) NOT NULL, `gastos` bigint(50) NOT NULL, `ganancian` bigint(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `jornadas` -- CREATE TABLE `jornadas` ( `idjornada` int(11) NOT NULL, `nit` int(11) NOT NULL, `fecha` date DEFAULT NULL, `horai` time NOT NULL, `horac` time NOT NULL, `clima` varchar(500) NOT NULL, `precioc` decimal(10,2) NOT NULL, `usuario_id` int(11) NOT NULL, `estatus` int(11) NOT NULL DEFAULT '1' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `jornadas` -- INSERT INTO `jornadas` (`idjornada`, `nit`, `fecha`, `horai`, `horac`, `clima`, `precioc`, `usuario_id`, `estatus`) VALUES (1, 1, '2021-06-03', '04:00:00', '06:00:00', 'Soleado', '2000.00', 1, 1), (2, 2, '2016-07-20', '10:00:00', '09:00:00', 'Nublado', '300.00', 1, 1), (4, 7, '2021-06-21', '07:07:00', '05:55:00', 'Tormenta', '55555.00', 24, 1); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `producto` -- CREATE TABLE `producto` ( `codproducto` int(11) NOT NULL, `descripcion` varchar(100) DEFAULT NULL, `proveedor` int(11) DEFAULT NULL, `precio` decimal(10,2) DEFAULT NULL, `existencia` int(11) DEFAULT NULL, `date_add` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `usuario_id` int(11) NOT NULL, `estatus` int(11) NOT NULL DEFAULT '1', `foto` text ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `producto` -- INSERT INTO `producto` (`codproducto`, `descripcion`, `proveedor`, `precio`, `existencia`, `date_add`, `usuario_id`, `estatus`, `foto`) VALUES (1, 'Mouse USB', 11, '110.00', 150, '2018-04-05 00:09:34', 1, 1, 'img_producto.png'), (2, 'Monitor LCD', 3, '1500.00', 100, '2018-04-05 00:12:15', 1, 1, 'img_producto.png'), (3, 'Teclado USB', 9, '250.00', 200, '2018-04-07 22:48:23', 9, 1, 'img_producto.png'), (4, 'Cama', 5, '10000.00', 50, '2018-09-08 22:28:50', 1, 1, 'img_21084f55f7b61c8baa2726ad0b4a1dca.jpg'), (5, 'Plancha', 6, '500.00', 100, '2018-09-08 22:34:38', 1, 1, 'img_25c1e2ae283b99e83b387bf800052939.jpg'), (6, 'Monitor', 11, '2000.00', 8, '2018-09-08 22:35:27', 1, 1, 'img_producto.png'), (7, 'Monitor LCD 17', 9, '2200.00', 75, '2018-12-02 00:15:09', 1, 1, 'img_1328286905ecc9eec8e81b94fa1786b9.jpg'), (8, 'USG 32 GB', 11, '160.00', 75, '2018-12-02 00:39:42', 1, 1, 'img_cce86641de32660a29e0fa49f58a950c.jpg'); -- -- Disparadores `producto` -- DELIMITER $$ CREATE TRIGGER `entradas_A_I` AFTER INSERT ON `producto` FOR EACH ROW BEGIN INSERT INTO entradas(codproducto,cantidad,precio,usuario_id) VALUES(new.codproducto,new.existencia,new.precio,new.usuario_id); END $$ DELIMITER ; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `rol` -- CREATE TABLE `rol` ( `idrol` int(11) NOT NULL, `rol` varchar(20) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `rol` -- INSERT INTO `rol` (`idrol`, `rol`) VALUES (1, 'Administrador'), (2, 'Cajero'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `usuario` -- CREATE TABLE `usuario` ( `idusuario` int(11) NOT NULL, `nombre` varchar(100) NOT NULL, `apellido` varchar(100) NOT NULL, `cedula` int(8) NOT NULL, `direccion` varchar(500) NOT NULL, `telefono` varchar(11) NOT NULL, `correo` varchar(100) DEFAULT NULL, `usuario` varchar(15) DEFAULT NULL, `clave` varchar(100) DEFAULT NULL, `rol` int(11) DEFAULT NULL, `estatus` int(11) NOT NULL DEFAULT '1' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `usuario` -- INSERT INTO `usuario` (`idusuario`, `nombre`, `apellido`, `cedula`, `direccion`, `telefono`, `correo`, `usuario`, `clave`, `rol`, `estatus`) VALUES (1, 'Admin', 'Admin', 25555555, 'Sector 5', '04148763451', '<EMAIL>', 'admin', '123456', 1, 1), (2, 'Alejandro', 'Aleman', 27547084, 'Sector 3', '04246467821', '<EMAIL>', 'ale', '123', 2, 1), (3, 'Angela', 'Romero', 27650409, 'Sector 5', '04148763451', '<EMAIL>', 'angela', '123', 2, 1); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `barcos` -- ALTER TABLE `barcos` ADD PRIMARY KEY (`codbarco`), ADD KEY `usuario_id` (`usuario_id`); -- -- Indices de la tabla `detallefactura` -- ALTER TABLE `detallefactura` ADD PRIMARY KEY (`correlativo`), ADD KEY `codproducto` (`codproducto`), ADD KEY `nofactura` (`nofactura`); -- -- Indices de la tabla `entradas` -- ALTER TABLE `entradas` ADD PRIMARY KEY (`correlativo`), ADD KEY `codproducto` (`codproducto`); -- -- Indices de la tabla `facturas` -- ALTER TABLE `facturas` ADD PRIMARY KEY (`codfac`); -- -- Indices de la tabla `jornadas` -- ALTER TABLE `jornadas` ADD PRIMARY KEY (`idjornada`), ADD KEY `usuario_id` (`usuario_id`); -- -- Indices de la tabla `producto` -- ALTER TABLE `producto` ADD PRIMARY KEY (`codproducto`), ADD KEY `proveedor` (`proveedor`), ADD KEY `usuario_id` (`usuario_id`); -- -- Indices de la tabla `rol` -- ALTER TABLE `rol` ADD PRIMARY KEY (`idrol`); -- -- Indices de la tabla `usuario` -- ALTER TABLE `usuario` ADD PRIMARY KEY (`idusuario`), ADD UNIQUE KEY `cedula` (`cedula`), ADD KEY `rol` (`rol`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `barcos` -- ALTER TABLE `barcos` MODIFY `codbarco` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT de la tabla `detallefactura` -- ALTER TABLE `detallefactura` MODIFY `correlativo` bigint(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT de la tabla `entradas` -- ALTER TABLE `entradas` MODIFY `correlativo` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- AUTO_INCREMENT de la tabla `facturas` -- ALTER TABLE `facturas` MODIFY `codfac` int(20) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT de la tabla `jornadas` -- ALTER TABLE `jornadas` MODIFY `idjornada` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT de la tabla `producto` -- ALTER TABLE `producto` MODIFY `codproducto` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- AUTO_INCREMENT de la tabla `rol` -- ALTER TABLE `rol` MODIFY `idrol` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT de la tabla `usuario` -- ALTER TABLE `usuario` MODIFY `idusuario` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- Restricciones para tablas volcadas -- -- -- Filtros para la tabla `barcos` -- ALTER TABLE `barcos` ADD CONSTRAINT `barcos_ibfk_1` FOREIGN KEY (`usuario_id`) REFERENCES `usuario` (`idusuario`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Filtros para la tabla `detallefactura` -- ALTER TABLE `detallefactura` ADD CONSTRAINT `detallefactura_ibfk_2` FOREIGN KEY (`codproducto`) REFERENCES `producto` (`codproducto`), ADD CONSTRAINT `detallefactura_ibfk_3` FOREIGN KEY (`nofactura`) REFERENCES `factura` (`nofactura`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Filtros para la tabla `entradas` -- ALTER TABLE `entradas` ADD CONSTRAINT `entradas_ibfk_1` FOREIGN KEY (`codproducto`) REFERENCES `producto` (`codproducto`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Filtros para la tabla `jornadas` -- ALTER TABLE `jornadas` ADD CONSTRAINT `jornadas_ibfk_1` FOREIGN KEY (`usuario_id`) REFERENCES `usuario` (`idusuario`); -- -- Filtros para la tabla `usuario` -- ALTER TABLE `usuario` ADD CONSTRAINT `usuario_ibfk_1` FOREIGN KEY (`rol`) REFERENCES `rol` (`idrol`) ON DELETE CASCADE ON UPDATE CASCADE; COMMIT; /*!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>/sistema/includes/nav.php <nav> <ul> <li><a href="index.php">Inicio</a></li> <?php if($_SESSION['active']){ ?> <?php } ?> <?php if($_SESSION['rol'] == 1){ ?> <li class="principal"> <a href="#">Usuarios</a> <ul> <li><a href="registro_usuario.php">Nuevo Usuario</a></li> <li><a href="lista_usuarios.php">Lista de Usuarios</a></li> </ul> </li> <?php } ?> <li class="principal"> <a href="#">Jornadas</a> <ul> <li><a href="registro_jornada.php">Nueva Jornada</a></li> <li><a href="lista_jornadas.php">Lista de Jornadas</a></li> </ul> </li> <?php if($_SESSION['rol'] == 1 || $_SESSION['rol']==2){ ?> <li class="principal"> <a href="#">Barcos</a> <ul> <li><a href="registro_barco.php">Nuevo Barco</a></li> <li><a href="lista_barcos.php">Lista de Barcos</a></li> </ul> </li> <?php } ?> <li class="principal"> <a href="#">Facturas</a> <ul> <li><a href="registro_factura.php">Nueva Factura</a></li> <li><a href="lista_facturas.php">Lista de Facturas</a></li> </ul> </li> <?php if( $_SESSION['rol']==2){ ?> <li class="principal"> <a href="#">Mi cuenta</a> <ul> <li><a href="lista_usuarios2.php">Visualizar</a></li> </ul> </li> <?php } ?> </ul> </nav><file_sep>/sistema/editar_jornada.php <?php session_start(); if($_SESSION['rol'] != 1) { header("location: ./"); } include "../conexion.php"; if(!empty($_POST)) { $alert=''; if(empty($_POST['fecha']) || empty($_POST['horai']) || empty($_POST['horac']) || empty($_POST['clima']) || empty($_POST['precioc'])) { $alert='<p class="msg_error">Todos los campos son obligatorios.</p>'; }else{ $idjornada = $_POST['id']; $nit = $_POST['nit']; $fecha = $_POST['fecha']; $horai = $_POST['horai']; $horac = $_POST['horac']; $clima = $_POST['clima']; $precioc = $_POST['precioc']; $result= 0; if(is_numeric($nit) and $nit !=0) { $query = mysqli_query($conection,"SELECT * FROM jornadas WHERE (nit= '$nit' AND idjornada != idjornada)"); $result=mysqli_fetch_array($query); } if($result > 0){ $alert='<p class="msg_error">El numero de jornada ya existe.</p>'; }else{ if($nit=='') { $nit=0; } $sql_update = mysqli_query($conection,"UPDATE jornadas SET nit = $nit, fecha='$fecha',horai='$horai',horac='$horac' ,clima='$clima',precioc='$precioc' WHERE idjornada= $idjornada "); if($sql_update){ $alert='<p class="msg_save">Jornada actualizada correctamente.</p>'; }else{ $alert='<p class="msg_error">Error al actualizar la jornada.</p>'; } } } } //Mostrar Datos if(empty($_REQUEST['id'])) { header('Location: lista_jornadas.php'); mysqli_close($conection); } $idjornada = $_REQUEST['id']; $sql= mysqli_query($conection,"SELECT * FROM jornadas WHERE idjornada= $idjornada "); mysqli_close($conection); $result_sql = mysqli_num_rows($sql); if($result_sql == 0){ header('Location: lista_jornadas.php'); }else{ while ($data = mysqli_fetch_array($sql)) { # code... $idjornada = $data['idjornada']; $nit = $data['nit']; $fecha = $data['fecha']; $horai = $data['horai']; $horac = $data['horac']; $clima = $data['clima']; $precioc = $data['precioc']; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <?php include "includes/scripts.php"; ?> <title>Actualizar Jornada</title> </head> <body> <?php include "includes/header.php"; ?> <section id="container"> <div class="form_register"> <h1>Actualizar Jornada</h1> <hr> <div class="alert"><?php echo isset($alert) ? $alert : ''; ?></div> <form action="" method="post"> <input type="hidden" name="id" value="<?php echo $idjornada;?>"> <label for="nit">Número de Jornada</label> <input type="text" name="nit" id="nit" placeholder="Número de Jornada" value="<?php echo $nit;?>"> <label for="fecha">Fecha</label> <input type="date" name="fecha" id="fecha" placeholder="Fecha de jornada"value="<?php echo $fecha;?>"> <label for="horai">Hora de Inicio</label> <input type="time" name="horai" id="horai" placeholder="Hora de inicio"value="<?php echo $horai;?>"> <label for="horac">Hora de Cierre</label> <input type="text" name="horac" id="horac" placeholder="Hora de cierre"value="<?php echo $horac;?>"> <label for="clima">Estado del Clima</label> <input type="text" name="clima" id="clima" placeholder="Estado del clima"value="<?php echo $clima;?>"> <label for="precioc">Precio Compra</label> <input type="number" min="1" step="any" name="precioc" id="precioc" placeholder="Precio Compra"value="<?php echo $precioc;?>"> <input type="submit" value="Crear Jornada" class="btn_save"> </form> </div> </section> </body> </html><file_sep>/sistema/editar_factura.php <?php session_start(); if($_SESSION['rol'] != 1) { header("location: ./"); } include "../conexion.php"; if(!empty($_POST)) { $alert=''; if( empty($_POST['hora']) || empty($_POST['gananciab']) || empty($_POST['ganancian'])) { $alert='<p class="msg_error">Todos los campos son obligatorios.</p>'; }else{ $idfactura =$_POST['id']; $hora = $_POST['hora']; $mercancia = $_POST['mercancia']; $gananciab = $_POST['gananciab']; $gastos = $_POST['gastos']; $ganancian = $_POST['ganancian']; $sql_update = mysqli_query($conection,"UPDATE facturas SET hora='$hora', mercancia='$mercancia',gananciab='$gananciab, gastos='$gastos' ,ganancian='$ganancian' WHERE codfac= $idfactura"); if($sql_update){ $alert='<p class="msg_save">Factura actualizada correctamente.</p>'; }else{ $alert='<p class="msg_error">Error al actualizar la Factura.</p>'; } } } //Mostrar Datos if(empty($_REQUEST['id'])) { header('Location: lista_facturas.php'); mysqli_close($conection); } $codfac = $_REQUEST['id']; $sql= mysqli_query($conection,"SELECT * FROM facturas WHERE codfac= $codfac "); mysqli_close($conection); $result_sql = mysqli_num_rows($sql); if($result_sql == 0){ header('Location: lista_facturas.php'); }else{ while ($data = mysqli_fetch_array($sql)) { # code... $idfactura = $data['codfac']; $hora = $data['hora']; $mercancia = $data['mercancia']; $gananciab = $data['gananciab']; $gastos = $data['gastos']; $ganancian = $data['ganancian']; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <?php include "includes/scripts.php"; ?> <title>Actualizar Factura</title> </head> <body> <?php include "includes/header.php"; ?> <section id="container"> <div class="form_register"> <h1>Actualizar Factura</h1> <hr> <div class="alert"><?php echo isset($alert) ? $alert : ''; ?></div> <form action="" method="post"> <input type="hidden" name="id" value="<?php echo $idfactura;?>"> <label for="fecha">Fecha</label> <input type="date" name="fecha" id="fecha" placeholder="Fecha de Creacion" value="<?php echo $fecha ?>"> <label for="hora">Hora</label> <input type="text" name="hora" id="hora" placeholder="Hora" value="<?php echo $hora ?>"> <label for="mercancia">Mercancia</label> <input type="number" name="mercancia" id="mercancia" placeholder="Mercancia"value="<?php echo $mercancia ?>"> <label for="gananciab">Ganancia Bruta</label> <input type="number" name="gananciab" id="gananciab" placeholder="Ganancia Bruta" value="<?php echo $gananciab ?>"> <label for="gastos">Gastos Operativos</label> <input type="number" name="gastos" id="gastos" placeholder="gastos" value="<?php echo $gastos ?>"> <label for="ganancian">Ganancia Neta</label> <input type="number" name="ganancian" id="ganancian" placeholder="Ganancia Neta" value="<?php echo $ganancian ?>"> <input type="submit" value="Actualizar Factura " class="btn_save"> </form> </div> </section> </body> </html><file_sep>/sistema/buscar_jornada.php <?php session_start(); if($_SESSION['rol'] != 1) { header("location: ./"); } include "../conexion.php"; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <?php include "includes/scripts.php"; ?> <title>Lista de Jornadas</title> </head> <body> <?php include "includes/header.php"; ?> <section id="container"> <?php $busqueda = strtolower($_REQUEST['busqueda']); if(empty($busqueda)) { header("location: lista_jornadas.php"); mysqli_close($conection); } ?> <h1>Lista de Jornadas</h1> <a href="registro_jornada.php" class="btn_new">Crear Jornada</a> <form action="buscar_jornada.php" method="get" class="form_search"> <input type="text" name="busqueda" id="busqueda" placeholder="Buscar" value="<?php echo $busqueda; ?>"> <input type="submit" value="Buscar" class="btn_search"> </form> <table> <tr> <th>IDjornada</th> <th>Nro Jornada</th> <th>Fecha</th> <th>Hora de inicio</th> <th>Hora de cierre</th> <th>Estado del clima</th> <th>Precio Compra</th> </tr> <?php //Paginador $sql_registe = mysqli_query($conection,"SELECT COUNT(*) as total_registro FROM jornadas WHERE ( idjornada LIKE '%$busqueda%' OR nit LIKE '%$busqueda%' OR fecha LIKE '%$busqueda%' OR horai LIKE '%$busqueda%' OR horac LIKE '%$busqueda%' OR clima LIKE '%$busqueda%' OR precioc LIKE '%$busqueda%' ) AND estatus = 1 "); $result_register = mysqli_fetch_array($sql_registe); $total_registro = $result_register['total_registro']; $por_pagina = 5; if(empty($_GET['pagina'])) { $pagina = 1; }else{ $pagina = $_GET['pagina']; } $desde = ($pagina-1) * $por_pagina; $total_paginas = ceil($total_registro / $por_pagina); $query = mysqli_query($conection,"SELECT * FROM jornadas WHERE ( idjornada LIKE '%$busqueda%' OR nit LIKE '%$busqueda%' OR fecha LIKE '%$busqueda%' OR horai LIKE '%$busqueda%' OR horac LIKE '%$busqueda%' OR clima LIKE '%$busqueda%' OR precioc LIKE '%$busqueda%') AND estatus = 1 ORDER BY idjornada ASC LIMIT $desde,$por_pagina "); mysqli_close($conection); $result = mysqli_num_rows($query); if($result > 0){ while ($data = mysqli_fetch_array($query)) { ?> <tr> <td><?php echo $data["idjornada"]; ?></td> <td><?php echo $data["nit"]; ?></td> <td><?php echo $data["fecha"]; ?></td> <td><?php echo $data["horai"]; ?></td> <td><?php echo $data["horac"] ?></td> <td><?php echo $data["clima"] ?></td> <td><?php echo $data["precioc"] ?></td> <td> <a class="link_edit" href="editar_jornada.php?id=<?php echo $data["idjornada"]; ?>">Editar</a> <?php if($_SESSION['rol']==1 ||$_SESSION['rol']==2){ ?> | <a class="link_delete" href="eliminar_confirmar_jornada.php?id=<?php echo $data["idjornada"]; ?>">Eliminar</a> <?php } ?> </td> </tr> <?php } } ?> </table> <?php if($total_registro != 0) { ?> <div class="paginador"> <ul> <?php if($pagina != 1) { ?> <li><a href="?pagina=<?php echo 1; ?>&busqueda=<?php echo $busqueda; ?>">|<</a></li> <li><a href="?pagina=<?php echo $pagina-1; ?>&busqueda=<?php echo $busqueda; ?>"><<</a></li> <?php } for ($i=1; $i <= $total_paginas; $i++) { # code... if($i == $pagina) { echo '<li class="pageSelected">'.$i.'</li>'; }else{ echo '<li><a href="?pagina='.$i.'&busqueda='.$busqueda.'">'.$i.'</a></li>'; } } if($pagina != $total_paginas) { ?> <li><a href="?pagina=<?php echo $pagina + 1; ?>&busqueda=<?php echo $busqueda; ?>">>></a></li> <li><a href="?pagina=<?php echo $total_paginas; ?>&busqueda=<?php echo $busqueda; ?> ">>|</a></li> <?php } ?> </ul> </div> <?php } ?> </section> </body> </html><file_sep>/index.php <?php $alert = ''; session_start(); if(!empty($_SESSION['active'])) { header('location: sistema/'); }else{ if(!empty($_POST)) { if(empty($_POST['cedula']) || empty($_POST['clave'])) { $alert = 'Ingrese su cédula de identidad y su contraseña'; }else{ require_once "conexion.php"; $cedula = mysqli_real_escape_string($conection,$_POST['cedula']); $pass= $_POST['clave']; $query = mysqli_query($conection,"SELECT * FROM usuario WHERE cedula= '$cedula' AND clave = '$pass'"); mysqli_close($conection); $result = mysqli_num_rows($query); if($result > 0) { $data = mysqli_fetch_array($query); $_SESSION['active'] = true; $_SESSION['idUser'] = $data['idusuario']; $_SESSION['nombre'] = $data['nombre']; $_SESSION['cedula'] = $data['cedula']; $_SESSION['email'] = $data['email']; $_SESSION['user'] = $data['usuario']; $_SESSION['rol'] = $data['rol']; header('location: sistema/'); }else{ $alert = 'La cédula de identidad o la contraseña son incorrectos'; session_destroy(); } } } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Inicio de Sesión</title> <link rel="stylesheet" type="text/css" href="css/style.css"> </head> <body> <section id="container"> <form action="" method="post"> <img src="Images/logo.png" alt="Login" style="width: 250px; height: 250px"> <input type="integer" name="cedula" placeholder="Cédula de Identidad"> <input type="<PASSWORD>" name="<PASSWORD>" placeholder="<PASSWORD>"> <div class="alert"><?php echo isset($alert) ? $alert : ''; ?></div> <input type="submit" value="INGRESAR"> </form> </section> </body> </html>
0a46127b55e903b730ce29804581b893357578d0
[ "SQL", "PHP" ]
9
PHP
soyangelaromero/Alimenmar
f318e666614e18d6b9eaf89cb5f72aa2545d0d23
32ff26d158d8db7b372d75e29d64217a28cbdb0e
refs/heads/master
<file_sep>#!/usr/bin/node var sys = require('sys'), srv = require('http'); var host = "localhost", port = 8080; var calc_tab = { add: function(a,b){ return a+b }, sub: function(a,b){ return a-b }, mul: function(a,b){ return a*b }, div: function(a,b){ return a/b }, } srv.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); sys.puts(sys.inspect(req.url)); var expr = req.url.split("/"), operation = calc_tab[expr[1]], operand_a = parseInt(expr[2], 10), operand_b = parseInt(expr[3], 10); res.write("<i>Operator: </i>"); res.write(expr[1]); res.write("<br><i>Operand A: </i>"); res.write(expr[2]); res.write("<br><i>Operand A: </i>"); res.write(expr[3]); res.write("<br><b>Result: </b>"); res.end(); // result = operation ? operation(operand_a, operand_b) : "ERROR"; // res.end("" + result + ""); }).listen(port, host); sys.puts("Check http://localhost:8080/"); <file_sep>#!/usr/bin/node var sys = require('sys'), tty = require('tty'); fd = tty.open("/dev/pts/21", argc=[]); answer = tty.isatty(fd) ? "Yes" : "No"; fd.setRawMode( question = "Is it a tty?" sys.puts(question); sys.puts(answer);
5f6eddd4055ded3e22ae09364439ff7f39a3d477
[ "JavaScript" ]
2
JavaScript
errordeveloper/work-node
795d15cc696e06cb0669f3fe23aaa3471d953377
24197b5fc459c7fc7cc870eb0cba48b946897cbc
refs/heads/main
<repo_name>Rengkat/model-window<file_sep>/script.js "use strict"; const introBtn = document.getElementById("form--1"); const bioBtn = document.getElementById("form--2"); const locatioBtn = document.getElementById("form--3"); const overlay = document.querySelector(".overlay"); const closeBtn = document.querySelectorAll(".close"); //showing introduction page introBtn.addEventListener("click", () => { show(".section--1"); }); bioBtn.addEventListener("click", () => { show(".section--2"); }); locatioBtn.addEventListener("click", () => { show(".section--3"); }); closeBtn.forEach((closeBtns) => { closeBtns.addEventListener("click", () => { hide(".section--1"); hide(".section--2"); hide(".section--3"); }); }); //functio to call show section function show(section) { document.querySelector(section).classList.remove("hidden"); overlay.classList.remove("hidden"); } //hiding section by clicking overlay overlay.addEventListener("click", () => { hide(".section--1"); hide(".section--2"); hide(".section--3"); }); //hiding using escape key document.addEventListener("keyup", (e) => { if (e.key === "Escape") { hide(".section--1"); hide(".section--2"); hide(".section--3"); } }); //hide section function hide(section) { document.querySelector(section).classList.add("hidden"); document.querySelector(".overlay").classList.add("hidden"); }
f321e497c54716e0da144f10c3602df4dbed85e6
[ "JavaScript" ]
1
JavaScript
Rengkat/model-window
34ab7507c010276cd7aca4ed3219ad3985bf2f7e
6b6ea90c55b1327c9965810eace92ddfce116f08
refs/heads/master
<file_sep># Networked sensor script import dht import tsl2561 import json from time import sleep from machine import I2C, Pin, unique_id from umqtt.simple import MQTTClient if __name__ == "__main__": # Setup sensors d = dht.DHT22(Pin(2)) #D4 on NodeMCU board is GPIO 2 i2c = I2C(-1, Pin(5), Pin(4)) #D1 & D2 on NodeMCU board. l = tsl2561.TSL2561(i2c) l.integration_time(402) #Adjusts the length of exposure. l.gain(16) # Set to 1 or 16 but no values between. 16 is more sensitive. # Setup MQTT broker = "192.168.1.64" # ip address of computer running the broker. client_id = "multi_1" # client id. client = MQTTClient(client_id, broker) client.connect() print("Connected to {}".format(broker)) while True: try: # Take sensor measurement!s d.measure() try: lux = l.read(autogain=True) raw_l, infrared = l.read(autogain=True, raw=True) except: lux = 0.0 raw_l, infrared = 0.0, 0.0 fahrenheit = d.temperature()*9/5 + 32 # Build JSON data = {"lux": lux, "raw_light": raw_l, "infrared": infrared, "temperature": fahrenheit, "humidity": d.humidity()} json_data = json.dumps(data) # Publish to MQTT broker client.publish('home-assistant/multi_1/multi_data', bytes(str(json_data), 'utf-8')) # Print sensor data - enable for debugging and to see if the sensor is collecting information properly. print("\n *** Temperature ***") print("Farenheit: ", fahrenheit) print("Humidity: ", d.humidity()) print("\n *** Light ***") print("Lux: ", lux) print("Vis. Light: ", raw_l) print("Infrared: ", infrared) sleep(15) except: try: client.connect() except: pass <file_sep># This file is executed on every boot (including wake-boot from deepsleep) import esp esp.osdebug(None) import gc #import webrepl #webrepl.start() gc.collect() import network def do_connect(essid, pw): sta_if = network.WLAN(network.STA_IF); sta_if.active(True) if not sta_if.isconnected(): print('connecting to network...') sta_if.active(True) sta_if.connect(essid, pw) while not sta_if.isconnected(): print "Having trouble connecting..." pass print('network config:', sta_if.ifconfig()) do_connect("ATTFnI4dbA", "wfy65%=u?squ") # passes essid and pw to connect fuction.<file_sep># Home Assistant Configuraton This is an archive of my home assistant configuration from 2018. Home Assistant is open source home automation software that can be run on low resource linux devices such as the raspberry pi. <file_sep>__author__ = 'Scott' import time import paho.mqtt.client as mqtt from os import system def on_connect(mosq, obj, rc): client.subscribe('ir', 0) print "Connection Response Code: ", str(rc) def on_publish(mosq, obj, mid): print("mid: " + str(mid)) def on_subscribe(mosq, obj, mid, granted_qos): print("Subscribed: " + str(mid) + " " + str(granted_qos)) def on_log(mosq, obj, level, string): print(string) def on_message(mosq, obj, msg): global message print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload)) cmd = msg.payload system(cmd) if __name__ == "__main__": # Broker's ip/network address broker = '192.168.1.64' # Creating a client. client = mqtt.Client("tyr") # Assign event callbacks client.on_message = on_message client.on_connect = on_connect client.on_publish = on_publish client.on_subscribe = on_subscribe # Connect to broker. client.connect(broker) # Start the network loop. client.loop_forever()<file_sep>import paho.mqtt.client as mqtt import paho.mqtt.publish as publish import RPi.GPIO as GPIO from time import sleep if __name__ == "__main__": GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(4, GPIO.IN) # Read output from PIR motion sensor 1 GPIO.setup(14, GPIO.IN) # Read output from PIR motion sensor 2 # Broker's ip/network address broker = '192.168.1.115' state_topic = 'home-assistant/pir_1/presence' delay = .1 client = mqtt.Client("pir1-client") client.connect(broker) client.loop_start() prev_state = 0 while True: if GPIO.input(4) == 1 or GPIO.input(14) ==1: presence = 1 else: presence = 0 # When output from motion sensor is low. if presence == 0: print "No intruder: ", presence if presence != prev_state: client.publish(state_topic, presence) sleep(delay) #When output from motion sensor is HIGH elif presence == 1: print "Intruder: ", presence if presence != prev_state: client.publish(state_topic, presence) sleep(delay) prev_state = presence
361d36f382eac55394f37e83497dbb3767d52cc3
[ "Markdown", "Python" ]
5
Python
wscottsanders/Home-Assistant-Configuration-2nd-St
47713067af776d4cd3a91f0cd8664273f1841672
c9dca42cf6ead12df6c47a914608d853824fb562
refs/heads/master
<repo_name>VijRana/FCM-CLIENT<file_sep>/src/pages/home/user.ts import { Device } from '../models/device'; export class User{ private name:string; private token:string; private password:string; private mobile:number; private email:string; private role:string; private devices:Device[]; public getName():string{ return this.name; } public setName(name:string):void{ this.name= name; } public getToken():string{ return this.token; } public setToken(token:string):void{ this.token = token; } public getMobileNumber():number{ return this.mobile; } public setMobile(mob:number):void{ this.mobile= mob; } public setPassword(pass:string):void{ this.password= <PASSWORD>; } public setRole(role:string):void{ this.role=role; } public getRole():string{ return this.role; } public setEmail(email:string):void{ this.email= email; } public getEmail():string{ return this.email; } public setDevices(devices:Device[]):void{ this.devices= devices; } public getDevice():Device[]{ return this.devices; } }<file_sep>/src/pages/home/home.ts import { Component , NgZone} from '@angular/core'; import { NavController } from 'ionic-angular'; import { Platform } from 'ionic-angular'; import {Storage} from "@ionic/storage"; import { timeout } from 'rxjs/operators'; import {Firebase} from "@ionic-native/firebase"; import {HttpClient} from "@angular/common/http"; import { User } from './user'; import { TaskPage } from '../task/task'; import { UniqueDeviceID } from '@ionic-native/unique-device-id'; import { Device} from '../models/device'; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { private readonly TOPIC_NAME = "idp"; private readonly PLATFORM_ANDROID = "android"; private readonly PLATFORM_IOS = "ios"; allowPush: boolean; allowPersonal: boolean; items: { id: number, text: string }[] = []; token: string; user:User; isSucess:boolean = false; roles:string[]= ['PMO', 'DEV']; role:string; device:Device; constructor(private readonly http: HttpClient, private platform: Platform, private readonly ngZone: NgZone, private readonly firebase: Firebase, private readonly storage: Storage, private navCtrl:NavController, private deviceUniqueID:UniqueDeviceID ) { this.device = new Device(); this.platform.ready().then(() => { if(this.platform.is(this.PLATFORM_IOS)){ console.log('I am in IOS Device'); } if(this.platform.is(this.PLATFORM_ANDROID)){ console.log('I am in ANDROID Device'); this.device.setDeviceName('ANDROID'); this.firebase.getToken() .then(token => this.token = token) .catch(error => console.error('Error getting token', error)); this.firebase.onTokenRefresh() .subscribe((token: string) => { this.token = token; this.device.setdeviceToken(this.token); }); this.firebase.onNotificationOpen().subscribe(notification => this.handleNotification(notification)); this.deviceUniqueID.get() .then((uuid:any) => { console.log(uuid); this.device.setDeviceID(uuid); }) .catch((error:any) => console.log(error)) } // this.firebase.getToken() // .then(token => this.token = token) // .catch(error => console.error('Error getting token', error)); // this.firebase.onTokenRefresh() // .subscribe((token: string) => this.token = token); // this.firebase.onNotificationOpen().subscribe(notification => this.handleNotification(notification)); // this.deviceID.get() // .then((uuid:any) => console.log(uuid)) // .catch((error:any) => console.log(error)) }); storage.get("allowPush").then(flag => this.allowPush = !!flag); storage.get("allowPersonal").then(flag => this.allowPersonal = !!flag); } register() { const formData = new FormData(); formData.append('token', this.token); this.http.post(`http://localhost:8080/register`, formData) .pipe(timeout(10000)) .subscribe(() => this.storage.set("allowPersonal", this.allowPersonal), error => this.allowPersonal = !this.allowPersonal); } unregister() { const formData = new FormData(); formData.append('token', this.token); this.http.post(`http://localhost:8080/unregister`, formData) .pipe(timeout(10000)) .subscribe(() => this.storage.set("allowPersonal", this.allowPersonal), error => this.allowPersonal = !this.allowPersonal); } onChange() { this.storage.set("allowPush", this.allowPush); if (this.allowPush) { this.firebase.subscribe(this.TOPIC_NAME); } else { this.firebase.unsubscribe(this.TOPIC_NAME); } } onPmChange() { if (this.allowPersonal) { this.register(); } else { this.unregister(); } } handleNotification(data) { if (!data.text) { return; } this.ngZone.run(() => { this.items.splice(0, 0, {id: data.id, text: data.text}); //only keep the last 5 entries if (this.items.length > 5) { this.items.pop(); } }); } signUp(form:any):void{ console.log(form); console.log(this.token); let devices:Device[]=[]; devices.push(this.device); this.user = new User(); this.user.setName(form.value.uname); this.user.setToken(this.token); this.user.setMobile(form.value.mob); this.user.setPassword(<PASSWORD>); this.user.setEmail(form.value.email); this.user.setRole(form.value.role); this.user.setDevices(devices); this.http.put('https://idb-push.herokuapp.com/users/add',this.user) .subscribe((res) => { console.log(res) if(res){ this.isSucess =true; this.navCtrl.push(TaskPage); } }, error => console.log(error) ) } gotoTaskPage():void{ this.navCtrl.push(TaskPage); } } <file_sep>/src/pages/models/device.ts export class Device{ private deviceID:string; private deviceName:string; private deviceToken:string; public setDeviceID(deviceID):void{ this.deviceID= deviceID; } public getDeviceID():string{ return this.deviceID; } public setDeviceName(deviceName):void{ this.deviceName = deviceName; } public getDeviceName():string{ return this.deviceName; } public setdeviceToken(deviceToken):void{ this.deviceToken = deviceToken; } public getDeviceToken():string{ return this.deviceToken; } }<file_sep>/src/pages/task/task.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import {HttpClient} from "@angular/common/http"; import {Firebase} from "@ionic-native/firebase"; import { User } from '../home/user'; @IonicPage() @Component({ selector: 'page-task', templateUrl: 'task.html', }) export class TaskPage { email:string; message:any; public approvals =[]; public users:User[]=[]; public aUsers:string[]= [] constructor(public navCtrl: NavController, public navParams: NavParams,private readonly http: HttpClient,private readonly firebase: Firebase) { } ionViewDidLoad() { console.log('ionViewDidLoad TaskPage'); this.http.get('https://idb-push.herokuapp.com/users/all') .subscribe((res:User[]) =>{ // this.users = res; // console.log(this.users); // this.users.forEach((data) =>{ // console.log(data); // this.aUsers.push((<any> data).name); // }) }, error=> console.log(error)) } submitTask(form:any):void{ this.email= form.value.pmo; console.log(this.email); const formData = new FormData(); formData.append('email', this.email); this.http.post('https://idb-push.herokuapp.com/push/send',formData) .subscribe(((res) => { console.log(res); this.handleNotification(); }), error =>console.log(error)) } handleNotification(){ this.firebase.onNotificationOpen().subscribe((notification)=>{ this.message= notification.body; console.log(this.message); }) } }
178bbdb240aa2deb5b50b2f15341e8df6788433c
[ "TypeScript" ]
4
TypeScript
VijRana/FCM-CLIENT
2ef98381fba0430942e42ff78a38e756f3d7b882
7058d3593f75ce632f65588c1c5e406996605cc0
refs/heads/master
<repo_name>navp4l/bowling<file_sep>/src/main/java/com/techtest/entity/OFXBowlingClub.java package com.techtest.entity; import com.techtest.domain.Frame; import com.techtest.domain.Try; import java.util.ArrayList; import java.util.List; /** * This is the main bowling game entity. * Contains all the entity members and methods * for game process. */ public class OFXBowlingClub implements BowlingGame { private List<Frame> scoreboard = new ArrayList<>(); @Override public void roll(int pins) { Frame currentFrame, lastFrame; if (scoreboard.size() > 0) { lastFrame = (scoreboard.get(scoreboard.size() - 1)); if (lastFrame.isComplete()) { // Create new frame currentFrame = new Frame(); currentFrame.setNumber(scoreboard.size() + 1); scoreboard.add(currentFrame); } else { // Retrieve frame details currentFrame = lastFrame; } } else { // This is the first throw of the first frame currentFrame = new Frame(); currentFrame.setNumber(scoreboard.size() + 1); scoreboard.add(currentFrame); } // Retrieve list of tries List<Try> tries = currentFrame.getTries(); // Initialize a new try Try roll = new Try(); roll.setKnockedPins(pins); tries.add(roll); // determine and set frame type if not already set if (currentFrame.getType() == null) { currentFrame.determineType(); } currentFrame.checkFrameCompletion(); } @Override public int score() { int score = 0; for (int i = 0; i < this.scoreboard.size(); i++) { int frameScore = 0; Frame frame = this.scoreboard.get(i); Frame.Type type = frame.getType(); if (frame.isComplete()) { switch (type) { case OPEN_FRAME: { // scored by adding the pins knocked in 2 tries frameScore = (frame.getTries().get(0).getKnockedPins() + frame.getTries().get(1).getKnockedPins()); break; } case SPARE: { // scored by adding 10 + (pins knocked in the next throw) frameScore = 10; if (this.getScoreboard().size() >= (i + 2)) { // check if next frames are available Frame nextFrame = this.getScoreboard().get(i + 1); List<Try> nextFrameTries = nextFrame.getTries(); frameScore += nextFrameTries.get(0).getKnockedPins(); } break; } case STRIKE: { // scored by adding 10 + (pins knocked in the next 2 throws) frameScore = 10; if (this.getScoreboard().size() >= (i + 2)) { // check if next frames are available Frame nextFrame = this.getScoreboard().get(i + 1); List<Try> nextFrameTries = nextFrame.getTries(); // If this is the penultimate throw and the final throw // happens to be a strike followed by bonus throws, // we need to restrict score to consider - current throw + next 2 throws if (nextFrameTries.size() >= 1) { int count = 0; for (Try bowl : nextFrameTries) { if (count <= 1) { frameScore += bowl.getKnockedPins(); } count++; } } // If this is the penultimate throw and the final throw // happens to be a strike followed by another strike followed by bonus throws, // we need to restrict score to consider - current throw + next 2 throws if (nextFrame.getType() == Frame.Type.STRIKE && this.getScoreboard().size() >= (i + 3)) { Frame thirdFrame = this.getScoreboard().get(i + 2); List<Try> thirdFrameTries = thirdFrame.getTries(); frameScore += thirdFrameTries.get(0).getKnockedPins(); } } break; } case LAST_THROW_STRIKE: case LAST_THROW_SPARE: { List<Try> tries = frame.getTries(); for (Try roll : tries) { frameScore += roll.getKnockedPins(); } break; } } System.out.println("Frame score for frame number " + (i + 1) + " with type " + frame.getType().toString() + " is " + frameScore); frame.setScore(frameScore); } else { frameScore = frame.getTries().get(0).getKnockedPins(); } score += frameScore; } return score; } public List<Frame> getScoreboard() { return scoreboard; } } <file_sep>/src/main/java/com/techtest/entity/BowlingGame.java package com.techtest.entity; /** * Bowling Game interface provides * public API methods roll and score * * @author palanisn */ public interface BowlingGame { /** * Roll the ball * @param pins Number of pins knocked down */ void roll(int pins); /** * Calculate game score * @return Score */ int score(); } <file_sep>/README.md # Bowling Club Building a bowling club scoreboard application. ## Pre-requisites * Java 8 * Maven ## Steps to run * Download / Clone this repository `git clone https://github.com/palanisn/bowling.git` * Navigate to project folder `cd bowling` * Clean & Compile proj `mvn clean compile` * Run tests `mvn test` * Execute App `mvn exec:java` <file_sep>/src/main/java/com/techtest/domain/Try.java package com.techtest.domain; /** * The Try class is the domain class * which deals with all properties & operations * related to a Try in a Frame of a bowling game. * * 3 Tries = 1 Frame * * @author palanisn */ public class Try { private int knockedPins; public int getKnockedPins() { return knockedPins; } public void setKnockedPins(int knockedPins) { this.knockedPins = knockedPins; } }<file_sep>/src/main/java/com/techtest/GameController.java package com.techtest; import com.techtest.entity.BowlingGame; import com.techtest.entity.OFXBowlingClub; /** * Game Controller * @author palanisn */ public class GameController { public static void main(String[] args) { System.out.println("*********** Game 1 *****************"); BowlingGame game1 = new OFXBowlingClub(); game1.roll(10); game1.roll(10); game1.roll(10); game1.roll(10); game1.roll(10); game1.roll(10); game1.roll(10); game1.roll(10); game1.roll(10); game1.roll(10); // Bonus throws game1.roll(10); game1.roll(10); System.out.println("Game 1 Score is " + game1.score()); System.out.println("************************************"); System.out.println("*********** Game 2 *****************"); BowlingGame game2 = new OFXBowlingClub(); game2.roll(10); game2.roll(7); game2.roll(3); game2.roll(7); game2.roll(2); game2.roll(9); game2.roll(1); game2.roll(10); game2.roll(10); game2.roll(10); game2.roll(2); game2.roll(3); game2.roll(6); game2.roll(4); game2.roll(7); game2.roll(3); // Bonus throw game2.roll(3); System.out.println("Game 2 Score is " + game2.score()); System.out.println("************************************"); System.out.println("*********** Game 3 *****************"); BowlingGame game3 = new OFXBowlingClub(); game3.roll(9); game3.roll(0); game3.roll(9); game3.roll(0); game3.roll(9); game3.roll(0); game3.roll(9); game3.roll(0); game3.roll(9); game3.roll(0); game3.roll(9); game3.roll(0); game3.roll(9); game3.roll(0); game3.roll(9); game3.roll(0); game3.roll(9); game3.roll(0); game3.roll(9); game3.roll(0); System.out.println("Game 3 Score is " + game3.score()); System.out.println("************************************"); System.out.println("*********** Game 4 *****************"); BowlingGame game4 = new OFXBowlingClub(); game4.roll(5); game4.roll(5); game4.roll(5); game4.roll(5); game4.roll(5); game4.roll(5); game4.roll(5); game4.roll(5); game4.roll(5); game4.roll(5); game4.roll(5); game4.roll(5); game4.roll(5); game4.roll(5); game4.roll(5); game4.roll(5); game4.roll(5); game4.roll(5); game4.roll(5); game4.roll(5); // Bonus throw game4.roll(5); System.out.println("Game 4 Score is " + game4.score()); System.out.println("************************************"); } }
30930bb2a6ffb33c7d32b9bd9a259c27bf0e05b4
[ "Markdown", "Java" ]
5
Java
navp4l/bowling
6a8b2f4dd82db1f649c0598dd839f4236eb93059
d024b4cbbba478fe358324061962cb18b0787454
refs/heads/master
<file_sep>/* Load JavaScript only after document */ $(window).bind("load", function() { $("#submitBtn").click(function() { /* this function load all data from form to an modal table called before submit */ $("#mName").text($('#name').val()); }); $('#submit').click(function(){ /* when the submit button in the modal is clicked, submit the form */ $('#formfield').submit(); }); });<file_sep><?php use App\Http\Controllers\OrderController; use App\Neo4j\Neo4j; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', 'HomeController@index')->name('home'); Route::get("/produtos", "HomeController@produto")->name("produto"); Route::get("/produtos/{id}", "ProductController@filterCat")->name("produtoCategoria"); Route::get("/produtoDetalhe/{id}", "HomeController@produtoDetalhe")->name("produtoDetalhe"); Route::get("/sobre", "HomeController@about")->name("about"); Route::get("/contato","HomeController@contact")->name("contact"); Route::get("/carrinho/{id}", "HomeController@cart")->name("cartId"); Route::get("/carrinho","CartController@index")->name("cart"); Route::get("/carrinhoExcluir/{id}","CartController@excluir")->name("cartExcluir"); Route::get("/cliente","HomeController@client")->name("client"); Route::get("/finalizar", "OrderController@finalizar")->name("finalSale"); Route::get("/registrar","HomeController@register")->name("register"); Route::post("/registrarCliente","ClientController@register")->name("clientRegister"); // Rota Fornecedor Route::get("/registrarFornecedor","SupplierController@index")->name("supplier"); Route::post("/registrarFornecedorSubmit","SupplierController@register")->name("supplierRegister"); // Rota Categoria Route::get("/registrarCategoria","CategoryController@index")->name("category"); Route::post("/registrarCategoriaSubmit","CategoryController@register")->name("categoryRegister"); // Rota Produtos -> Informar dados para cadastrar. Route::get("/registrarProdutos","ProductController@product")->name("product"); // Rota Produtos -> Salvar no banco os dados cadastrados. Route::post("/registrarProductSubmit","ProductController@register")->name("productRegister"); // Rota Produtos -> Salvar no banco os dados cadastrados. Route::post("/registrarProductSubmitUpdate","ProductController@update")->name("productUpdate"); // Rota Produtos -> Selecionar produto pra edição. Route::get("/selecionarProdutoParaEdicao", "ProductController@selection")->name("productSelection"); // Rota Produto -> Modificar os dados desejados Route::get("/editarProdutos", "ProductController@edit")->name("productEdit"); // Rota Produto -> Selecionar os produtos através da Categoria Route::get("selecionarProdutoParaEdicao/categoria/{category}", "ProductController@filterProductCategory"); Route::get("selecionarProdutoParaEdicao/produto/{id_produto}","ProductController@findProduct"); // Rota Produtos -> Selecionar produto pra edição. Route::get("/selecionarCategoriaParaEdicao", "CategoryController@selection")->name("categorySelection"); // Rota Categoria -> Selecionar a Categoria Route::get("/selecionarCategoriaParaEdicao/categoria/{category}", "CategoryController@findCategory"); // Rota Category -> Modificar os dados desejados Route::post("/editarCategorias", "CategoryController@edit")->name("categoryUpdate"); // Rota Fornecedor -> Selecionar fornecedor Route::get(" /selecionarFornecedorParaEdicao/Fornecedor/{supplier}", "SupplierController@findSupplier"); // Rota Fornecedores -> Salvar no banco os dados cadastrados. Route::post("/alterarForncedor","SupplierController@updateSupplier")->name("supplierUpdate"); // Rota Fornecedor -> Selecionar Fornecedor pra edição. Route::get("/selecionarFornecedorParaEdicao", "SupplierController@selection")->name("supplierSelection"); // Rota Cliente Route::any("/alterarCliente","clientController@update")->name("clientUpdate"); Route::any("/editarCliente","clientController@consultaCliente")->name("updateClient"); Route::any("/principal","clientController@autenticar")->name("clienteLogin"); Route::get("/sairCliente","clientController@logout")->name("logoutCliente"); Route::get("/panelCliente","clientController@panelCliente")->name("clientPanel"); Route::get("/consultaVenda","clientController@consultSale")->name("consultSale"); Route::get("/consultaAjax/{id}", "clientController@consultAjax"); // Rota administrativa Route::get("/admin","AdminController@index")->name("admin"); Route::any("/painelAdmin","AdminController@autenticar")->name("adminPanel"); Route::get("/sairAdmin","AdminController@logout")->name("logout"); Route::get("/frete/{cep}", "CartController@frete"); // Rota Avaliação Route::get("/avaliacaoProduto/{id}", "ClientController@avaliacaoProduto")->name("avaliacaoProduto"); Route::post("/avaliacaoProduto", "ClientController@resultadoAvaliacao")->name("resultadoAvaliacao"); Route::get('/graph', function () { // $prop = ([ // 'infos' => ['name' => 'Geladeira', 'Price' => 4000.00] // ]); // $prop2 = ([ // 'infos' => ['first_name' => $request->get("first_name"), // 'last_name' => $request->get("last_name"), // 'cpf' => $request->get("cpf"), // 'rg' => $request->get("rg"), // 'sex' => $request->get("sex"), // 'telephone' => $request->get("telephone"), // 'phone_number' => $request->get("phone_numbere"), // 'birth_date' => $request->get("birth_date"), // 'state' => $request->get("state"), // 'city' => $request->get("city"), // 'postal_code' => $request->get("postal_code"), // 'street' => $request->get("street"), // 'street_number' => $request->get("street_number"), // 'complement' => $request->get("complement"), // 'email' => $request->get("email"), // ] // ]); // //name, cpf, rg, sex, telephone, phone_number,date_birth, address (o endereço deve conter: state, city, postal_code, street , street_number, complement), email. // $where = ([ // 'Node' => 'Cliente', // 'Id' => 'teste', // 'NodeTwo' => 'Produto', // 'IdTwo' => 'Iphone 7', // 'Rel' => 'COMPROU' // ]); // $recom = ([ // 'Node' => 'Cliente', // 'Id' => 'Elias', // ]); // $node = ([ // 'Node' => 'Cliente', // 'Id' => 'teste', // ]); // $rel = ([ // 'idOne' => '160', // 'idTwo' => '162', // ]); // //$r = Neo4j::createNodeProperty("Produto",$prop); // $s = Neo4j::createNodeProductProperty("Product",$prop,$rel); // //$c = Neo4j::createRelationship($where); // //$c = Neo4j::collaborativeFiltration($recom); // //$c = Neo4j::deleteNode($node,True); // // $neo4j = Neo4j::conectar(); // // $query = 'MATCH (m:Cliente) RETURN m,m.name as name'; // $c = $neo4j->run($query); // $data = Neo4j::matchNode("supplier"); // foreach ($data as $record) // { // $id[] = $record->value('id'). PHP_EOL; // $name[] = $record->value('name') . PHP_EOL; // echo"<br>"; // } // print_r($name); // echo"<br>"; // $arr = array( // 'id' => $id, // 'name' => $name // ); return null; }); <file_sep>$(document).ready(function($){ /* Money mask R$ */ $('.money').mask('#.##0,00', {reverse: true}); /* Only number on Dimensions Mask*/ $('.number').mask('0000000'); /* CEP Mask*/ $(".cep").mask("99.999-999"); $("#postal_code").focusout(function(){ //Início do Comando AJAX $.ajax({ //O campo URL diz o caminho de onde virá os dados //É importante concatenar o valor digitado no CEP url: 'https://viacep.com.br/ws/'+$(this).val().replace(/\.|\-/g, '')+'/json/unicode/', //Aqui você deve preencher o tipo de dados que será lido, //no caso, estamos lendo JSON. dataType: 'json', //SUCESS é referente a função que será executada caso //ele consiga ler a fonte de dados com sucesso. //O parâmetro dentro da função se refere ao nome da variável //que você vai dar para ler esse objeto. success: function(resposta){ //Agora basta definir os valores que você deseja preencher //automaticamente nos campos acima. $("#street").val(resposta.logradouro); $("#complement").val(resposta.complemento); $("#neighborhood").val(resposta.bairro); $("#city").val(resposta.localidade); $("#state").val(resposta.uf); //Vamos incluir para que o Número seja focado automaticamente //melhorando a experiência do usuário $("#street_number").focus(); } }); }); /* CNPJ Mask*/ $(".cnpj").on("keyup", function(e) { $(this).val( $(this).val() .replace(/\D/g, '') .replace(/^(\d{2})(\d{3})?(\d{3})?(\d{4})?(\d{2})?/, "$1 $2 $3/$4-$5")); }); /* New sp state phones Mask */ var SPMaskBehavior = function (val) { return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009'; }, spOptions = { onKeyPress: function(val, e, field, options) { field.mask(SPMaskBehavior.apply({}, arguments), options); } }; $('.sp_celphones').mask(SPMaskBehavior, spOptions); }); /* Load JavaScript only after document */ $(window).bind("load", function() { $("#submitBtn").click(function() { /* this function load all data from form to an modal table called before submit */ $("#mName").text($("#name").val()); $("#mCNPJ").text($("#cnpj").val()); $("#mPhoneNumber").text($("#phone_number").val()); $("#mTelephone").text($("#telephone").val()); $("#mEmail").text($("#email").val()); $("#mCEP").text($('#postal_code').val()); $("#mRua").text($("#street").val()); $("#mNumero").text($("#street_number").val()); $("#mBairro").text($("#neighborhood" ).val()); $("#mCidade").text($("#city").val()); $("#mEstado").text($("#state option:selected").text()); $("#mComplemento").text($("#complement").val()); }); $('#submit').click(function(){ /* when the submit button in the modal is clicked, submit the form */ $('#formfield').submit(); }); }); <file_sep>$(document).ready(function($){ /* Money mask R$ */ $('.money').mask('#.##0,00', {reverse: true}); /* Only number on Dimensions Mask*/ $('.number').mask('0000000'); /* New sp state phones Mask */ var SPMaskBehavior = function (val) { return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009'; }, spOptions = { onKeyPress: function(val, e, field, options) { field.mask(SPMaskBehavior.apply({}, arguments), options); } }; $('.sp_celphones').mask(SPMaskBehavior, spOptions); }); /* Load JavaScript only after document */ $(window).bind("load", function() { $("#submitBtn").click(function() { /* this function load all data from form to an modal table called before submit */ $("#mName").text($("#name").val()); $("#mCategory").text($("#category option:selected").text()); $("#mSupplier").text($("#supplier option:selected").text()); $("#mCostsPrice").text("R$ " + $("#costsprice").val()); $("#mSalesPrice").text("R$ " + $("#salesprice").val()); $("#mProductDesc").text($('#productdesc').val()); $("#mHeight").text($("#height").val() + " cm"); $("#mWidth").text($("#width").val() + " cm"); $("#mDepth").text($("#depth" ).val() + " cm"); $("#mWeight").text($("#weight").val() + " g"); $("#mSac").text($("#sac").val()); }); $('#submit').click(function(){ /* when the submit button in the modal is clicked, submit the form */ $('#formfield').submit(); }); });
1608a55c646da692319904c6909cb598e09e9f2d
[ "JavaScript", "PHP" ]
4
JavaScript
venezianluis/SysRec
810eaa6db2ccf678a1ad61c9f8c8f8a0705497f6
c0513a48d98b4fdc5e25e8769b4c553571bfeea4
refs/heads/master
<repo_name>xSAVIKx/nastya_web_site<file_sep>/nastya/urls.py from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.contrib import admin from nastya import settings from web_site import urls as web_site_urls from web_site.views import CustomContactView urlpatterns = patterns('', # Examples: # url(r'^$', 'nastya.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^$', include(web_site_urls)), url(r'^send_email$', CustomContactView.as_view(), name='send_email'), ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)<file_sep>/requirements.txt Django==1.7.2 django-envelope==1.0 django-honeypot==0.4.0 django-widget-tweaks==1.3 easy-thumbnails==2.2 Pillow==2.7.0 six==1.9.0 <file_sep>/web_site/admin.py from django.contrib import admin # Register your models here. from web_site.models import JumbotronImage, Project, ProjectImage class JumbotronImageAdmin(admin.ModelAdmin): fields = ['title', 'description', 'image_file'] list_display = ('title', 'image_file', 'admin_thumbnail', ) class ProjectImageInline(admin.TabularInline): model = ProjectImage class ProjectImageAdmin(admin.ModelAdmin): fields = ['title', 'project', 'image_file'] list_display = ['project', 'image_file', 'admin_thumbnail', ] class ProjectAdmin(admin.ModelAdmin): fields = ['title', 'description', 'logo_image'] list_display = ('title', 'logo_image', 'admin_thumbnail', ) inlines = [ProjectImageInline] admin.site.register(JumbotronImage, JumbotronImageAdmin) admin.site.register(Project, ProjectAdmin) admin.site.register(ProjectImage, ProjectImageAdmin)<file_sep>/static/web_site/js/nano_galery/jquery.nanogallery.min.js /* nanoGALLERY v5.2.3 Plugin for jQuery by <NAME> Demo: http://nanogallery.brisbois.fr Sources: https://github.com/Kris-B/nanoGALLERY License: For personal, non-profit organizations, or open source projects (without any kind of fee), you may use nanoGALLERY for jQuery for free. -------- ALL OTHER USES REQUIRE THE PURCHASE OF A PROFESSIONAL LICENSE. Components: - jQuery (http://www.jquery.com) - version >= 1.7.1 - jQuery Color plugin - is embedded - imagesloaded (https://github.com/desandro/imagesloaded) - is embebed - screenfull.js (https://github.com/sindresorhus/screenfull.js) - is embeded - webfont generated by http://fontello.com - based on Font Awesome Copyright (C) 2012 by <NAME> (http://fortawesome.github.com/Font-Awesome/) - http://closure-compiler.appspot.com/home - minifying javascript - http://gpbmike.github.io/refresh-sf/ - minifying css */ (function (s) { var J = null; jQuery.fn.nanoGallery = function (D) { var A = s.extend(!0, { userID: "", kind: "", album: "", photoset: "", blackList: "scrapbook|profil", whiteList: "", albumList: "", RTL: !1, picasaUseUrlCrossDomain: !0, galleryToolbarWidthAligned: !0, galleryToolbarHideIcons: !1, galleryFullpageButton: !1, galleryFullpageBgColor: "#111", galleryRenderStep: 10, breadcrumbAutoHideTopLevel: !1, displayBreadcrumb: !1, theme: "default", colorScheme: "none", colorSchemeViewer: "default", items: null, itemsBaseURL: "", paginationMaxLinesPerPage: 0, maxWidth: 0, viewer: "internal", fancyBoxOptions: null, viewerDisplayLogo: !1, imageTransition: "slide", viewerToolbar: { display: !0, position: "bottom", style: "innerImage", autoMinimize: 800, standard: "minimizeButton , previousButton, pageCounter ,nextButton,playPauseButton,fullscreenButton,infoButton,linkOriginalButton,closeButton,label", minimized: "minimizeButton,label" }, thumbnailAlignment: "center", thumbnailWidth: 230, thumbnailHeight: 154, thumbnailGutterWidth: 2, thumbnailGutterHeight: 2, thumbnailAdjustLastRowHeight: !0, thumbnailFeatured: !1, thumbnailHoverEffect: null, thumbnailLabel: { position: "overImageOnBottom", display: !0, displayDescription: !0, titleMaxLength: 0, descriptionMaxLength: 0, hideIcons: !1, title: "", itemsCount: "" }, thumbnailDisplayInterval: 30, thumbnailDisplayTransition: !0, thumbnailLazyLoad: !1, thumbnailLazyLoadTreshold: 100, thumbnailGlobalImageTitle: "", thumbnailGlobalAlbumTitle: "", thumbnailSizeSM: 480, thumbnailSizeME: 992, thumbnailSizeLA: 1200, thumbnailSizeXL: 1800, fnThumbnailInit: null, fnThumbnailHoverInit: null, fnThumbnailHoverResize: null, fnThumbnailHover: null, fnThumbnailHoverOut: null, fnThumbnailDisplayEffect: null, fnViewerInfo: null, fnImgToolbarCustInit: null, fnImgToolbarCustDisplay: null, fnImgToolbarCustClick: null, fnProcessData: null, touchAnimation: !0, touchAutoOpenDelay: 0, useTags: !1, preset: "none", locationHash: !1, slideshowDelay: 3E3, slideshowAutoStart: !1, photoSorting: "", albumSorting: "", dataSorting: "", lazyBuild: "none", lazyBuildTreshold: 150, flickrSkipOriginal: !0, i18n: { breadcrumbHome: "Galleries", breadcrumbHome_FR: "Galeries", paginationPrevious: "Previous", paginationPrevious_FR: "Pr&eacute;c&eacute;dent", paginationPrevious_DE: "Zur&uuml;ck", paginationPrevious_IT: "Indietro", paginationNext: "Next", paginationNext_FR: "Suivant", paginationNext_DE: "Weiter", paginationNext_IT: "Avanti", thumbnailLabelItemsCountPart1: "", thumbnailLabelItemsCountPart2: "", thumbnailImageTitle: "", thumbnailAlbumTitle: "", thumbnailImageDescription: "", thumbnailAlbumDescription: "", infoBoxPhoto: "Photo", infoBoxDate: "Date", infoBoxAlbum: "Album", infoBoxDimensions: "Dimensions", infoBoxFilename: "Filename", infoBoxFileSize: "File size", infoBoxCamera: "Camera", infoBoxFocalLength: "Focal length", infoBoxExposure: "Exposure", infoBoxFNumber: "F Number", infoBoxISO: "ISO", infoBoxMake: "Make", infoBoxFlash: "Flash", infoBoxViews: "Views", infoBoxComments: "Comments" } }, D); return this.each(function () { J = new nanoGALLERY; J.Initiate(this, A) }) }; jQuery.fn.nanoGallery.TEST = function () { console.dir(J) } })(jQuery); function nanoGALLERY() { function s() { return {animationEngine: F, t: "test"} } function J() { var b; b = 'Your browser version is not supported anymore. The image gallery cannot be displayed. <br><br>Please update to a more recent one. Download:<br>&nbsp;&nbsp;&nbsp; <a href="http://www.google.com/chrome/?hl=en-US)">Chrome</a><br>&nbsp;&nbsp;&nbsp; <a href="http://www.mozilla.com/firefox/)">Firefox</a><br>'; b += '&nbsp;&nbsp;&nbsp; <a href="http://www.microsoft.com/windows/internet-explorer/default.aspx">Internet Explorer</a><br>'; b += '&nbsp;&nbsp;&nbsp; <a href="http://www.apple.com/safari/download/">Safari</a>'; R(b, !1) } function D(b) { for (var c = document.createElement("div"), a = 0; a < b.length; ++a)if ("undefined" != typeof c.style[b[a]])return b[a]; return null } function A() { var b = Math.max(window.screen.width, window.screen.height); void 0 != window.devicePixelRatio && 1 < window.devicePixelRatio && (b *= window.devicePixelRatio); for (var c = 0; c < C.length; c++)switch (C[c].name) { case "imageScale150": case "imageScale150Outside": case "imageScaleIn80": case "imageSlide2Up": case "imageSlide2Down": case "imageSlide2Left": case "imageSlide2Right": case "imageSlide2UpRight": case "imageSlide2UpLeft": case "imageSlide2DownRight": case "imageSlide2DownLeft": case "imageSlide2Random": h.scale = Math.max(h.scale, 1.5); break; case "scale120": h.scale = Math.max(h.scale, 1.2) } 0 < f.itemsBaseURL.length && (f.itemsBaseURL += "/"); switch (f.kind) { case "": W(O.breadcrumbHome, "", "", "", "", "album", "", "0", "-1"); void 0 !== f.items && null !== f.items ? (Ub(), r(!1) || X(0, !1)) : (b = jQuery(e.base).children("a"), 0 < b.length ? (Vb(b), r(!1) || X(0, !1)) : R("error: no image to process.")); break; case "flickr": f.flickrSkipOriginal || (Q.photoAvailableSizes.push(1E4), Q.photoAvailableSizesStr.push("o")); for (i = 0; i < Q.photoAvailableSizes.length && !(Q.photoSize = i, b <= Q.photoAvailableSizes[i]); i++); W(O.breadcrumbHome, "", "", "", "", "album", "", 0 < f.photoset.length ? f.photoset : "0", "-1"); sb(0, !0, -1, !1); break; case "json": W(O.breadcrumbHome, "", "", "", "", "album", "", "0", "-1"); tb(0, !0, -1, !1); break; default: 0 < f.album.length ? (c = f.album.indexOf("&authkey="), 0 <= c ? (b = f.album.substring(0, c), c = f.album.substring(c), -1 == c.indexOf("Gv1sRg") && (c = "&authkey=Gv1sRg" + c.substring(9)), W(O.breadcrumbHome, "", "", "", "", "album", "", b, "-1").customData.authkey = c) : W(O.breadcrumbHome, "", "", "", "", "album", "", f.album, "-1")) : W(O.breadcrumbHome, "", "", "", "", "album", "", "0", "-1"), ub(0, !0, -1, !1) } jQuery(document).keyup(function (a) { if (S)switch (a.keyCode) { case 27: Da(!0); break; case 32: case 13: bb(); break; case 38: case 39: case 33: Ea(); break; case 40: case 37: case 34: Fa() } }); jQuery(window).bind("hashchange", function (a) { f.locationHash && r(!0) }); f.galleryFullpageButton && (e.conNavBFullpage = f.RTL ? jQuery('<div class="nanoGalleryFullpage setFullPageButton"></div>').prependTo(e.conNavB) : jQuery('<div class="nanoGalleryFullpage setFullPageButton"></div>').appendTo(e.conNavB), e.conNavBFullpage.on("click", function (a) { e.conNavBFullpage.hasClass("setFullPageButton") ? S || (0 < f.maxWidth && jQuery(e.base).css({maxWidth: ""}), e.conNavBFullpage.removeClass("setFullPageButton").addClass("removeFullPageButton"), L("", e.base), e.base.addClass("fullpage"), jQuery("body").css({overflow: "hidden"}), Ga()) : S || (e.conNavBFullpage.removeClass("removeFullPageButton").addClass("setFullPageButton"), 0 < f.maxWidth && jQuery(e.base).css({maxWidth: f.maxWidth}), e.base.removeClass("fullpage"), U(), Ga()) })) } function U() { jQuery("body").css({overflow: "visible"}) } function I(b) { function c(a) { void 0 != a && (null != Y && Ha(Y), Y = null, void 0 !== p[a].destinationURL && 0 < p[a].destinationURL.length ? window.location = p[a].destinationURL : (oa = !1, "album" == p[a].kind ? sa(a, !1, -1, !0) : ta(a, !1))) } function a() { ua = 0; h = Z = null; jQuery(e.conTn[0]).css({left: 0}); if (S)Y = null, oa = !1; else if (null != Y)if (10 < Math.abs(aa.t - M().t))Ha(Y), Y = null, oa = !1; else { var a = Y, b = a.data("index"); void 0 != b && (f.touchAnimation && !oa ? 0 < f.touchAutoOpenDelay ? (Ia(), cb(a), window.clearInterval(db), db = window.setInterval(function () { window.clearInterval(db); 10 < Math.abs(aa.t - M().t) ? (oa = !1, Y = null, Ha(a)) : c(b) }, f.touchAutoOpenDelay)) : p[b].hovered ? c(b) : (Ia(), cb(a)) : c(b)) } else oa = !1 } function d(a) { var b = {}; a.targetTouches ? (b.x = a.targetTouches[0].clientX, b.y = a.targetTouches[0].clientY) : (b.x = a.clientX, b.y = a.clientY); return b } function m() { if (E) { if (0 < T && "auto" != w() && "auto" != l()) { var a = ua - (Z.x - h.x); jQuery(u).css({left: a}) } E = !1 } } var u = b, E = !1, Z = null, h = null, ua = 0, g = !1, aa = 0; this.handleGestureStartNoDelay = function (a) { if (S)return a.stopPropagation(), a.eventDefault(), !1; 400 > (new Date).getTime() - eb || (oa = !0, this.handleGestureStart(a)) }.bind(this); this.handleGestureStart = function (a) { if (S)return a.stopPropagation(), a.eventDefault(), !1; if (!(400 > (new Date).getTime() - ga || 400 > (new Date).getTime() - eb)) { eb = (new Date).getTime(); for (var b = a.target || a.srcElement, c = !1; b != e.conTn[0];)"nanoGalleryThumbnailContainer" == b.getAttribute("class") && (null == Y || Y.is(jQuery(b)) || Ia(), Y = jQuery(b), c = !0), b = b.parentNode; c && (aa = M(), Z = d(a), initialOffsetTop = M().t, window.navigator.msPointerEnabled ? (document.addEventListener("MSPointerMove", this.handleGestureMove, !0), document.addEventListener("MSPointerUp", this.handleGestureEnd, !0)) : (document.addEventListener("touchmove", this.handleGestureMove, !0), document.addEventListener("touchend", this.handleGestureEnd, !0), document.addEventListener("touchcancel", this.handleGestureEnd, !0), document.addEventListener("mousemove", this.handleGestureMove, !0), document.addEventListener("mouseup", this.handleGestureEnd, !0)), e.base.addClass("unselectable").find("*").attr("draggable", "false").attr("unselectable", "on")) } }.bind(this); this.handleGestureMove = function (a) { h = d(a); !E && 0 < T && "auto" != w() && "auto" != l() && (15 < Math.abs(Z.x - h.x) || g) && (a.preventDefault(), E = g = !0, window.requestAnimationFrame(m)) }.bind(this); this.handleGestureEnd = function (b) { b.cancelable && b.preventDefault(); b.stopPropagation(); g = E = !1; window.navigator.msPointerEnabled ? (document.removeEventListener("MSPointerMove", this.handleGestureMove, !0), document.removeEventListener("MSPointerUp", this.handleGestureEnd, !0)) : (document.removeEventListener("touchmove", this.handleGestureMove, !0), document.removeEventListener("touchend", this.handleGestureEnd, !0), document.removeEventListener("touchcancel", this.handleGestureEnd, !0), document.removeEventListener("mousemove", this.handleGestureMove, !0), document.removeEventListener("mouseup", this.handleGestureEnd, !0)); e.base.addClass("unselectable").find("*").attr("draggable", "true").attr("unselectable", "off"); null == h || null == Z ? a() : (b = Z.x - h.x, ua -= b, 0 < T && "auto" != w() && "auto" != l() ? 30 < Math.abs(b) ? (Y = null, ua = 0, h = Z = null, Ia(), -30 > b ? vb() : wb()) : a() : a()); h = Z = null; ua = 0; g = !1 }.bind(this); window.navigator.msPointerEnabled ? u.addEventListener("MSPointerDown", this.handleGestureStartNoDelay, !0) : (u.addEventListener("touchstart", this.handleGestureStart, !0), Wb || u.addEventListener("mousedown", this.handleGestureStartNoDelay, !0)); u.addEventListener("mouseenter", function (a) { S || (a = a.target || a.srcElement, "nanoGalleryThumbnailContainer" == a.getAttribute("class") && cb(jQuery(a))) }, !0); u.addEventListener("mouseleave", function (a) { a = a.target || a.srcElement; "nanoGalleryThumbnailContainer" == a.getAttribute("class") && Ha(jQuery(a)) }, !0) } function q() { "fancybox" == f.viewer && "undefined" === typeof jQuery.fancybox && (f.viewer = "internal", ma("Fancybox could not be found. Fallback to internal viewer. Please check the file includes of the page.")); if ("<EMAIL>" == f.userID.toUpperCase() || "111186676244625461692" == f.userID)if ("" == f.blackList || "SCRAPBOOK|PROFIL" == f.blackList.toUpperCase())f.blackList = "profil|scrapbook|forhomepage"; "" != f.blackList && (Ma = f.blackList.toUpperCase().split("|")); "" != f.whiteList && (Na = f.whiteList.toUpperCase().split("|")); "" != f.albumList && (Ja = f.albumList.toUpperCase().split("|")); if ("picasa" == f.kind || "flickr" == f.kind)f.displayBreadcrumb = !0; void 0 !== f.photoset ? 0 < f.photoset.length && (f.displayBreadcrumb = !1) : f.photoset = ""; void 0 !== f.album ? 0 < f.album.length && (f.displayBreadcrumb = !1) : f.album = ""; 0 < f.maxWidth && (jQuery(e.base).css({maxWidth: f.maxWidth}), jQuery(e.base).css({"margin-left": "auto"}), jQuery(e.base).css({"margin-right": "auto"})); "number" == V(f.slideshowDelay) && 2E3 <= f.slideshowDelay ? Oa = f.slideshowDelay : ma('Parameter "slideshowDelay" must be an integer >= 2000 ms.'); "number" == V(f.thumbnailDisplayInterval) && 0 <= f.thumbnailDisplayInterval ? h.displayInterval = f.thumbnailDisplayInterval : ma('Parameter "thumbnailDisplayInterval" must be an integer.'); "number" == V(f.thumbnailLazyLoadTreshold) && 0 <= f.thumbnailLazyLoadTreshold ? h.lazyLoadTreshold = f.thumbnailLazyLoadTreshold : ma('Parameter "thumbnailLazyLoadTreshold" must be an integer.'); "number" == V(f.paginationMaxLinesPerPage) && 0 <= f.paginationMaxLinesPerPage ? T = f.paginationMaxLinesPerPage : ma('Parameter "paginationMaxLinesPerPage" must be an integer.'); var b = f.albumSorting.toUpperCase(); 0 == b.indexOf("RANDOM") && 6 < b.length && (n = parseInt(b.substring(6)), 0 < n && (Pa = n), f.albumSorting = "random"); b = f.photoSorting.toUpperCase(); 0 == b.indexOf("RANDOM") && 6 < b.length && (n = parseInt(b.substring(6)), 0 < n && (fb = n), f.photoSorting = "random"); switch (V(f.thumbnailHoverEffect)) { case "string": for (var c = f.thumbnailHoverEffect.split(","), b = 0; b < c.length; b++)if ("none" != c[b] && g(c[b])) { var a = v(); a.name = c[b]; C.push(a) } break; case "object": "none" != f.thumbnailHoverEffect.name && g(f.thumbnailHoverEffect.name) && (a = v(), C.push(jQuery.extend(a, f.thumbnailHoverEffect))); break; case "array": for (b = 0; b < f.thumbnailHoverEffect.length; b++)"none" != f.thumbnailHoverEffect[b].name && g(f.thumbnailHoverEffect[b].name) && (a = v(), C.push(jQuery.extend(a, f.thumbnailHoverEffect[b]))); break; case "null": break; default: R('incorrect parameter for "thumbnailHoverEffect".') } 0 == C.length && (f.touchAnimation = !1); ha = ca(); if ("number" == V(f.thumbnailWidth))k("width", "l1", f.thumbnailWidth, "u"), k("width", "lN", f.thumbnailWidth, "u"); else { c = f.thumbnailWidth.split(" "); a = "auto"; "auto" != c[0].substring(0, 4) && (a = parseInt(c[0])); var d = "u"; "C" == c[0].charAt(c[0].length - 1) && (d = "c"); k("width", "l1", a, d); k("width", "lN", a, d); for (b = 1; b < c.length; b++) { var m = c[b].substring(0, 2).toLowerCase(); if (/xs|sm|me|la|xl/i.test(m)) { var u = c[b].substring(2), a = "auto"; "auto" != u.substring(0, 4) && (a = parseInt(u)); d = "u"; "C" == u.charAt(u.length - 1) && (d = "c"); h.settings.width.l1[m] = a; h.settings.width.lN[m] = a; h.settings.width.l1[m + "c"] = d; h.settings.width.lN[m + "c"] = d } } } if (void 0 != f.thumbnailL1Width)if ("number" == V(f.thumbnailL1Width))k("width", "l1", f.thumbnailL1Width, "u"); else for (c = f.thumbnailL1Width.split(" "), a = "auto", "auto" != c[0].substring(0, 4) && (a = parseInt(c[0])), d = "u", "C" == c[0].charAt(c[0].length - 1) && (d = "c"), k("width", "l1", a, d), b = 1; b < c.length; b++)m = c[b].substring(0, 2).toLowerCase(), /xs|sm|me|la|xl/i.test(m) && (u = c[b].substring(2), a = "auto", "auto" != u.substring(0, 4) && (a = parseInt(u)), d = "u", "C" == u.charAt(u.length - 1) && (d = "c"), h.settings.width.l1[m] = a, h.settings.width.l1[m + "c"] = d); if ("number" == V(f.thumbnailHeight))k("height", "l1", f.thumbnailHeight, "u"), k("height", "lN", f.thumbnailHeight, "u"); else for (c = f.thumbnailHeight.split(" "), a = "auto", "auto" != c[0].substring(0, 4) && (a = parseInt(c[0])), d = "u", "C" == c[0].charAt(c[0].length - 1) && (d = "c"), k("height", "l1", a, d), k("height", "lN", a, d), b = 1; b < c.length; b++)m = c[b].substring(0, 2).toLowerCase(), /xs|sm|me|la|xl/i.test(m) && (u = c[b].substring(2), a = "auto", "auto" != u.substring(0, 4) && (a = parseInt(u)), d = "u", "C" == u.charAt(u.length - 1) && (d = "c"), h.settings.height.l1[m] = a, h.settings.height.lN[m] = a, h.settings.height.l1[m + "c"] = d, h.settings.height.lN[m + "c"] = d); if (void 0 != f.thumbnailL1Height)if ("number" == V(f.thumbnailL1Height))k("height", "l1", f.thumbnailL1Height, "u"); else for (c = f.thumbnailL1Height.split(" "), a = "auto", "auto" != c[0].substring(0, 4) && (a = parseInt(c[0])), d = "u", "C" == c[0].charAt(c[0].length - 1) && (d = "c"), k("height", "l1", a, d), b = 1; b < c.length; b++)m = c[b].substring(0, 2).toLowerCase(), /xs|sm|me|la|xl/i.test(m) && (u = c[b].substring(2), a = "auto", "auto" != u.substring(0, 4) && (a = parseInt(u)), d = "u", "C" == u.charAt(u.length - 1) && (d = "c"), h.settings.height.l1[m] = a, h.settings.height.l1[m + "c"] = d) } function k(b, c, a, d) { h.settings[b][c].xs = a; h.settings[b][c].sm = a; h.settings[b][c].me = a; h.settings[b][c].la = a; h.settings[b][c].xl = a; h.settings[b][c].xsc = d; h.settings[b][c].smc = d; h.settings[b][c].mec = d; h.settings[b][c].lac = d; h.settings[b][c].xlc = d } function l() { return h.settings.width[ba][ha] } function w() { return h.settings.height[ba][ha] } function H() { return h.outerWidth[ba][ha] } function da() { return h.outerHeight[ba][ha] } function ca() { var b = M().w; return 0 < f.thumbnailSizeSM && b < f.thumbnailSizeSM ? "xs" : 0 < f.thumbnailSizeME && b < f.thumbnailSizeME ? "sm" : 0 < f.thumbnailSizeLA && b < f.thumbnailSizeLA ? "me" : 0 < f.thumbnailSizeXL && b < f.thumbnailSizeXL ? "la" : "xl" } function v() { var b = { delay: 0, delayBack: 0, duration: 400, durationBack: 200, easing: "swing", easingBack: "swing", animParam: null }; "animate" != F && (b.easing = "ease", b.easingBack = "ease"); return b } function g(b) { var c = /labelOpacity50|borderLighter|borderDarker/i.test(b), a = /imageFlipVertical|imageFlipHorizontal|imageRotateCornerBR|imageRotateCornerBL|rotateCornerBL|rotateCornerBR|imageScale150|overScale|overScaleOutside|imageScaleIn80|imageScale150Outside|scale120|scaleLabelOverImage|slideUp|slideDown|slideLeft|slideRight|imageSlideUp|imageSlideDown|imageSlideLeft|imageSlideRight|labelAppear|labelAppear75|descriptionAppear|labelSlideDown|labelSlideUp|labelSlideUpTop|imageInvisible|imageOpacity50|descriptionSlideUp|labelSplitVert|labelSplit4|labelAppearSplitVert|labelAppearSplit4|imageSplitVert|imageSplit4/i.test(b), d = /imageExplode/i.test(b); f.touchAutoOpenDelay = parseInt(f.touchAutoOpenDelay); 0 == f.touchAutoOpenDelay && (f.touchAutoOpenDelay = 1E3); return c || a || d ? "onBottom" != f.thumbnailLabel.position || /borderLighter|borderDarker|imageOpacity50|imageScale150|imageScaleIn80|imageSlide2Up|imageSlide2Down|imageSlide2Left|imageSlide2Right|imageSlide2Random|imageSlide2UpRight|imageSlide2UpLeft|imageSlide2DownRight|imageSlide2DownLeft|imageScale150Outside|scale120/i.test(b) ? !d || "animate" != F && null != K ? !0 : (ma('Parameter thumbnailHoverEffect="' + b + '" requires one of the additionals jQuery plugins "Velocity" or "Transit".'), !1) : (R('The parameter combination thumbnailHoverEffect="' + b + '" and thumbnailLabel.position="onBottom" is not supported.'), !1) : (R('Unknow parameter value: thumbnailHoverEffect="' + b + '".'), !1) } function x() { ia = (navigator.language || navigator.userLanguage).toUpperCase(); "UNDEFINED" === ia && (ia = ""); var b = -("_" + ia).length; if ("object" == V(f.i18n))for (var c in f.i18n) { var a = c.substr(b); a == "_" + ia ? O[c.substr(0, c.length - a.length)] = f.i18n[c] : O[c] = f.i18n[c] } } function r(b) { if (!f.locationHash)return !1; var c = null, a = null, c = "#nanogallery/" + ja + "/", d = location.hash; if (d != va && ("" == d && -1 != gb && (va = "", sa(0, !1, -1, !1)), 0 == d.indexOf(c))) { var m = d.substring(c.length), u = m.indexOf("/"), E = d = -1, Z = p.length; if (0 < u)for (c = m.substring(0, u), a = m.substring(u + 1), m = 0; m < Z; m++) { if ("image" == p[m].kind && p[m].GetID() == a) { E = m; break } } else c = m; for (m = 0; m < Z; m++)if ("album" == p[m].kind && p[m].GetID() == c) { d = m; break } null !== a ? (b || (Qa = d), "" == f.kind ? ta(E) : -1 == E ? sa(d, !1, a, b) : ta(E)) : sa(d, !1, -1, b); return !0 } } function P() { p = []; var b = ""; f.thumbnailLabel.displayDescription && (b = "d"); b = W("dummydummydummy", "data:image/gif;base64,R0lGODlhEAAQAIAAAP///////yH5BAEKAAEALAAAAAAQABAAAAIOjI+py+0Po5y02ouzPgUAOw==", "data:image/gif;base64,R0lGODlhEAAQAIAAAP///////yH5BAEKAAEALAAAAAAQABAAAAIOjI+py+0Po5y02ouzPgUAOw==", b, "", "image", "", "1", "0"); b = xb(b, 0, !1).e$; h.borderWidth = b.outerWidth(!0) - b.width(); h.borderHeight = b.outerHeight(!0) - b.height(); h.imgcBorderWidth = b.find(".imgContainer").outerWidth(!0) - b.find(".imgContainer").width(); h.imgcBorderHeight = b.find(".imgContainer").outerHeight(!0) - b.find(".imgContainer").height(); h.labelBorderHeight = b.find(".labelImage").outerHeight(!0) - b.find(".labelImage").height(); h.labelBorderWidth = b.find(".labelImage").outerWidth(!0) - b.find(".labelImage").width(); "onBottom" == f.thumbnailLabel.position && (h.labelHeight = b.find(".labelImage").outerHeight(!0)); for (var c = ["xs", "sm", "me", "la", "xl"], a = 0; a < c.length; a++) { var d = h.settings.width.l1[c[a]]; h.outerWidth.l1[c[a]] = "auto" != d ? d + h.borderWidth + h.imgcBorderWidth : 0; d = h.settings.width.lN[c[a]]; h.outerWidth.lN[c[a]] = "auto" != d ? d + h.borderWidth + h.imgcBorderWidth : 0 } for (a = 0; a < c.length; a++)d = h.settings.height.l1[c[a]], h.outerHeight.l1[c[a]] = "auto" != d ? d + h.borderHeight + h.imgcBorderHeight + h.labelHeight : 0, d = h.settings.height.lN[c[a]], h.outerHeight.lN[c[a]] = "auto" != d ? d + h.borderHeight + h.imgcBorderHeight + h.labelHeight : 0; ka = wa(); G.oldBorderColor = b.css("border-color"); if ("" == G.oldBorderColor || null == G.oldBorderColor || void 0 == G.oldBorderColor)G.oldBorderColor = "#000"; G.oldLabelOpacity = b.find(".labelImage").css("opacity"); b = jQuery.Color(b.find(".labelImage"), "backgroundColor"); G.oldLabelRed = b.red(); G.oldLabelGreen = b.green(); G.oldLabelBlue = b.blue(); p = [] } function pa(b, c) { var a = ""; return "" != ia && void 0 !== b[c + "_" + ia] && 0 < b[c + "_" + ia].length ? a = b[c + "_" + ia] : a = b[c] } function N(b) { return "%filename" == f.thumbnailLabel.title ? b.split("/").pop().replace("_", " ") : "%filenameNoExt" == f.thumbnailLabel.title ? b.split("/").pop().split(".").shift().replace("_", " ") : b } function Ub() { var b = !1; "undefined" !== typeof f.dataSorting && ("random" == f.dataSorting ? f.items = Ka(f.items) : "reversed" == f.dataSorting && (f.items = f.items.reverse())); jQuery.each(f.items, function (a, c) { var d = "", d = pa(c, "title"); void 0 === d && (d = ""); var m = f.itemsBaseURL + c.src, u = "", u = void 0 !== c.srct && 0 < c.srct.length ? f.itemsBaseURL + c.srct : m, e = "", e = void 0 !== c.srct2x && 0 < c.srct2x.length ? f.itemsBaseURL + c.srct2x : "" != u ? u : m; "" != f.thumbnailLabel.title && (d = N(m)); var h = "", h = pa(c, "description"); void 0 === h && (h = ""); var g = ""; void 0 !== c.destURL && 0 < c.destURL.length && (g = c.destURL); var p = pa(c, "tags"); void 0 === p && (p = ""); var k = 0; void 0 !== c.albumID && (k = c.albumID, b = !0); var l = null; void 0 !== c.ID && (l = c.ID); var r = "image"; void 0 !== c.kind && 0 < c.kind.length && (r = c.kind); d = W(d, u, m, h, g, r, p, l, k); d.thumbX2src = e; e = 0; void 0 !== c.imgtWidth && 0 < c.imgtWidth && (e = c.imgtWidth, d.thumbImgWidth = e); m = 0; void 0 !== c.imgtHeight && 0 < c.imgtHeight && (m = c.imgtHeight, d.thumbImgHeight = m); d.thumbs = { url: {l1: {xs: u, sm: u, me: u, la: u, xl: u}, lN: {xs: u, sm: u, me: u, la: u, xl: u}}, width: { l1: {xs: e, sm: e, me: e, la: e, xl: e}, lN: { xs: e, sm: e, me: e, la: e, xl: e } }, height: {l1: {xs: m, sm: m, me: m, la: m, xl: m}, lN: {xs: m, sm: m, me: m, la: m, xl: m}} }; "function" == typeof f.fnProcessData && f.fnProcessData(d, "api", null) }); b && (f.displayBreadcrumb = !0); for (var c = p.length, a = 0, d = 0, m = 0; m < c; m++) { for (var u = d = a = 0; u < c; u++)m != u && p[m].GetID() == p[u].albumID && (a++, "image" == p[u].kind && (p[u].imageNumber = d++)); p[m].contentLength = a } } function Vb(b) { var c = !1; "undefined" !== typeof f.dataSorting && ("random" == f.dataSorting ? b = Ka(b) : "reversed" == f.dataSorting && (jQuery.fn.reverse = [].reverse, b = b.reverse())); jQuery.each(b, function (a, b) { var d = ""; void 0 !== jQuery(b).attr("data-ngthumb") && 0 < jQuery(b).attr("data-ngthumb").length && (d = f.itemsBaseURL + jQuery(b).attr("data-ngthumb")); void 0 !== jQuery(b).attr("data-ngThumb") && 0 < jQuery(b).attr("data-ngThumb").length && (d = f.itemsBaseURL + jQuery(b).attr("data-ngThumb")); var m = ""; void 0 !== jQuery(b).attr("data-ngthumb2x") && 0 < jQuery(b).attr("data-ngthumb2x").length && (m = f.itemsBaseURL + jQuery(b).attr("data-ngthumb2x")); void 0 !== jQuery(b).attr("data-ngThumb2x") && 0 < jQuery(b).attr("data-ngThumb2x").length && (m = f.itemsBaseURL + jQuery(b).attr("data-ngThumb2x")); src = f.itemsBaseURL + jQuery(b).attr("href"); var u = ""; void 0 !== jQuery(b).attr("data-ngdesc") && 0 < jQuery(b).attr("data-ngdesc").length && (u = jQuery(b).attr("data-ngdesc")); void 0 !== jQuery(b).attr("data-ngDesc") && 0 < jQuery(b).attr("data-ngDesc").length && (u = jQuery(b).attr("data-ngDesc")); var e = ""; void 0 !== jQuery(b).attr("data-ngdest") && 0 < jQuery(b).attr("data-ngdest").length && (e = jQuery(b).attr("data-ngdest")); void 0 !== jQuery(b).attr("data-ngDest") && 0 < jQuery(b).attr("data-ngDest").length && (e = jQuery(b).attr("data-ngDest")); var h = 0; void 0 !== jQuery(b).attr("data-ngalbumid") && (h = jQuery(b).attr("data-ngalbumid"), c = !0); void 0 !== jQuery(b).attr("data-ngAlbumID") && (h = jQuery(b).attr("data-ngAlbumID"), c = !0); var g = null; void 0 !== jQuery(b).attr("data-ngid") && (g = jQuery(b).attr("data-ngid")); void 0 !== jQuery(b).attr("data-ngID") && (g = jQuery(b).attr("data-ngID")); var p = "image"; void 0 !== jQuery(b).attr("data-ngkind") && 0 < jQuery(b).attr("data-ngkind").length && (p = jQuery(b).attr("data-ngkind")); void 0 !== jQuery(b).attr("data-ngKind") && 0 < jQuery(b).attr("data-ngKind").length && (p = jQuery(b).attr("data-ngKind")); var k = jQuery(b).text(); "" != f.thumbnailLabel.title && void 0 != f.thumbnailLabel.title && (k = N(src)); u = W(k, d, src, u, e, p, "", g, h); u.thumbX2src = m; m = 0; void 0 !== jQuery(b).attr("data-ngthumbImgWidth") && 0 < jQuery(b).attr("data-ngthumbImgWidth").length && (m = jQuery(b).attr("data-ngthumbImgWidth"), u.thumbImgWidth = m); e = 0; void 0 !== jQuery(b).attr("data-ngthumbImgHeight") && 0 < jQuery(b).attr("data-ngthumbImgHeight").length && (e = jQuery(b).attr("data-ngthumbImgHeight"), u.thumbImgHeight = e); u.thumbs = { url: {l1: {xs: d, sm: d, me: d, la: d, xl: d}, lN: {xs: d, sm: d, me: d, la: d, xl: d}}, width: {l1: {xs: m, sm: m, me: m, la: m, xl: m}, lN: {xs: m, sm: m, me: m, la: m, xl: m}}, height: {l1: {xs: e, sm: e, me: e, la: e, xl: e}, lN: {xs: e, sm: e, me: e, la: e, xl: e}} }; "function" == typeof f.fnProcessData && f.fnProcessData(u, "markup", null) }); jQuery.each(b, function (a, b) { jQuery(b).remove() }); c && (f.displayBreadcrumb = !0); b = p.length; for (var a = 0, d = 0, m = 0; m < b; m++) { for (var u = d = a = 0; u < b; u++)m != u && p[m].GetID() == p[u].albumID && (a++, "image" == p[u].kind && (p[u].imageNumber = d++)); p[m].contentLength = a } } function tb(b, c, a, d) { Ra(b); if (p[b].contentIsLoaded)X(b, d); else { var m = f.customSourceProvider + "?albumID=" + encodeURIComponent(p[b].GetID()); hb(); jQuery.ajaxSetup({cache: !1}); jQuery.support.cors = !0; var u = setTimeout(function () { ea(); R("Could not retrieve Custom data...") }, 6E4); jQuery.getJSON(m, function (m, f, e) { clearTimeout(u); ea(); Xb(b, m); if (c)r(!1) || X(b, d); else if (-1 != a) { m = -1; f = p.length; for (e = 0; e < f; e++)if ("image" == p[e].kind && p[e].GetID() == a) { m = e; break } ta(m, !0) } else X(b, d) }).fail(function (a, b, c) { clearTimeout(u); ea(); R("Could not retrieve Custom items list (jQuery): " + (b + ", " + c)) }) } } function Xb(b, c) { var a = !1, d = 0; jQuery.each(c, function (b, c) { var E = "", E = pa(c, "title"); void 0 === E && (E = ""); var e = f.itemsBaseURL + c.src, e = e.replaceAll("%2F", "/"), h = f.itemsBaseURL + c.srct, h = h.replaceAll("%2F", "/"); "" != f.thumbnailLabel.title && (E = N(e)); var g = "", g = pa(c, "description"); void 0 === g && (g = ""); var p = ""; void 0 !== c.destURL && 0 < c.destURL.length && (p = c.destURL); var k = 0; void 0 !== c.albumID && (k = c.albumID, a = !0); var l = null; void 0 !== c.ID && (l = c.ID); var r = "image"; void 0 !== c.kind && 0 < c.kind.length && (r = c.kind); E = W(E, h, e, g, p, r, "", l, k); e = c.imgtWidth; g = c.imgtHeight; E.thumbs = { url: {l1: {xs: h, sm: h, me: h, la: h, xl: h}, lN: {xs: h, sm: h, me: h, la: h, xl: h}}, width: {l1: {xs: e, sm: e, me: e, la: e, xl: e}, lN: {xs: e, sm: e, me: e, la: e, xl: e}}, height: {l1: {xs: g, sm: g, me: g, la: g, xl: g}, lN: {xs: g, sm: g, me: g, la: g, xl: g}} }; "function" == typeof f.fnProcessData && f.fnProcessData(E, "api", null); if ("image" == r && (E.imageNumber = d, d++, d >= Pa))return !1 }); a && (f.displayBreadcrumb = !0); p[b].contentIsLoaded = !0; p[b].contentLength = d } function sb(b, c, a, d) { Ra(b); if (p[b].contentIsLoaded)X(b, d); else { var m = "", u = "album"; 0 == p[b].GetID() ? m = Q.url() + "?&method=flickr.photosets.getList&api_key=" + Q.ApiKey + "&user_id=" + f.userID + "&per_page=500&primary_photo_extras=url_o,url_sq,url_t,url_q,url_s,url_m,url_z,url_b,url_h,url_k&format=json&jsoncallback=?" : (m = "none" == p[b].GetID() ? Q.url() + "?&method=flickr.people.getPublicPhotos&api_key=" + Q.ApiKey + "&user_id=" + f.userID + "&extras=description,views,url_o,url_sq,url_t,url_q,url_s,url_m,url_z,url_b,url_h,url_k&per_page=500&format=json&jsoncallback=?" : Q.url() + "?&method=flickr.photosets.getPhotos&api_key=" + Q.ApiKey + "&photoset_id=" + p[b].GetID() + "&extras=description,views,url_o,url_sq,url_t,url_q,url_s,url_m,url_z,url_b,url_h,url_k&format=json&jsoncallback=?", u = "image"); hb(); jQuery.ajaxSetup({cache: !1}); jQuery.support.cors = !0; var e = setTimeout(function () { ea(); R("Could not retrieve Flickr data...") }, 6E4); jQuery.getJSON(m, function (m, f, h) { clearTimeout(e); ea(); "album" == u ? Yb(b, m) : Zb(b, m); if (c)r(!1) || X(b, d); else if (-1 != a) { m = -1; f = p.length; for (h = 0; h < f; h++)if ("image" == p[h].kind && p[h].GetID() == a) { m = h; break } ta(m, !0) } else X(b, d) }).fail(function (a, b, c) { clearTimeout(e); ea(); R("Could not retrieve Flickr photoset list (jQuery): " + (b + ", " + c)) }) } } function Yb(b, c) { var a = !0; void 0 !== c.stat && "fail" === c.stat && (R("Could not retrieve Flickr photoset list: " + c.message + " (code: " + c.code + ")."), a = !1); if (a) { var d = 0, a = c.photosets.photoset; switch (f.albumSorting) { case "random": a = Ka(a); break; case "reversed": a = a.reverse(); break; case "titleAsc": a.sort(function (a, b) { var c = a.title._content.toUpperCase(), d = b.title._content.toUpperCase(); return c < d ? -1 : c > d ? 1 : 0 }); break; case "titleDesc": a.sort(function (a, b) { var c = a.title._content.toUpperCase(), d = b.title._content.toUpperCase(); return c > d ? -1 : c < d ? 1 : 0 }) } jQuery.each(a, function (a, c) { itemTitle = c.title._content; if (yb(itemTitle, c.id)) { itemID = c.id; itemDescription = ""; void 0 != c.description._content && (itemDescription = c.description._content); var f = {}, e; for (e in c.primary_photo_extras)f[e] = c.primary_photo_extras[e]; tags = ""; void 0 !== c.primary_photo_extras && void 0 !== c.primary_photo_extras.tags && (tags = c.primary_photo_extras.tags); e = W(itemTitle, "", "", itemDescription, "", "album", tags, itemID, p[b].GetID()); e.contentLength = c.photos; e.thumbSizes = f; f = { url: { l1: {xs: "", sm: "", me: "", la: "", xl: ""}, lN: {xs: "", sm: "", me: "", la: "", xl: ""} }, width: {l1: {xs: 0, sm: 0, me: 0, la: 0, xl: 0}, lN: {xs: 0, sm: 0, me: 0, la: 0, xl: 0}}, height: { l1: { xs: 0, sm: 0, me: 0, la: 0, xl: 0 }, lN: {xs: 0, sm: 0, me: 0, la: 0, xl: 0} } }; f = Sa(f, c.primary_photo_extras, "l1"); f = Sa(f, c.primary_photo_extras, "lN"); e.thumbs = f; d++; if (d >= Pa)return !1 } }); p[b].contentIsLoaded = !0; p[b].contentLength = d } } function Sa(b, c, a) { for (var d = ["xs", "sm", "me", "la", "xl"], m = 0; m < d.length; m++) { if ("auto" == h.settings.width[a][d[m]])var f = "height_", e = Math.ceil(h.settings.height[a][d[m]] * h.scale); else"auto" == h.settings.height[a][d[m]] ? (f = "width_", e = Math.ceil(h.settings.width[a][d[m]] * h.scale)) : (f = "height_", e = Math.ceil(h.settings.height[a][d[m]] * h.scale), h.settings.width[a][d[m]] > h.settings.height[a][d[m]] && (f = "width_", e = Math.ceil(h.settings.width[a][d[m]] * h.scale))); f = $b(f, e, c); b.url[a][d[m]] = f.url; b.width[a][d[m]] = f.width; b.height[a][d[m]] = f.height } return b } function $b(b, c, a) { for (var d = {url: "", width: 0, height: 0}, m = 0, f = 0; f < Q.thumbAvailableSizes.length; f++) { var e = a[b + Q.photoAvailableSizesStr[f]]; if (void 0 != e && (m = f, e >= c))break } b = Q.photoAvailableSizesStr[m]; d.url = a["url_" + b]; d.width = parseInt(a["width_" + b]); d.height = parseInt(a["height_" + b]); return d } function Zb(b, c) { var a = "", a = "none" == p[b].GetID() ? c.photos.photo : c.photoset.photo; switch (f.photoSorting) { case "random": a = Ka(a); break; case "reversed": a = a.reverse(); break; case "titleAsc": a.sort(function (a, b) { var c = "", d = ""; "" != f.thumbnailLabel.title ? (c = N(a.url_sq), d = N(b.url_sq)) : (c = a.title.toUpperCase(), d = b.title.toUpperCase()); return c < d ? -1 : c > d ? 1 : 0 }); break; case "titleDesc": a.sort(function (a, b) { var c = "", d = ""; "" != f.thumbnailLabel.title ? (c = N(a.url_sq), d = N(b.url_sq)) : (c = a.title.toUpperCase(), d = b.title.toUpperCase()); return c > d ? -1 : c < d ? 1 : 0 }) } var d = p[b].GetID(), m = 0; jQuery.each(a, function (a, b) { var c = b.title, e = b.id, h = b.description._content, g = b.url_sq; for (a = Q.photoSize; 0 <= a; a--)if (void 0 != b["url_" + Q.photoAvailableSizesStr[a]]) { g = b["url_" + Q.photoAvailableSizesStr[a]]; break } for (var p in b)0 == p.indexOf("height_") || 0 == p.indexOf("width_") || p.indexOf("url_"); "" != f.thumbnailLabel.title && (c = N(g)); c = W(c, "", g, h, "", "image", "", e, d); c.imageNumber = m; void 0 !== b.url_o ? (c.width = b.width_o, c.height = b.height_o) : (c.width = b.width_z, c.height = b.height_z); e = { url: {l1: {xs: "", sm: "", me: "", la: "", xl: ""}, lN: {xs: "", sm: "", me: "", la: "", xl: ""}}, width: {l1: {xs: 0, sm: 0, me: 0, la: 0, xl: 0}, lN: {xs: 0, sm: 0, me: 0, la: 0, xl: 0}}, height: {l1: {xs: 0, sm: 0, me: 0, la: 0, xl: 0}, lN: {xs: 0, sm: 0, me: 0, la: 0, xl: 0}} }; e = Sa(e, b, "l1"); e = Sa(e, b, "lN"); c.thumbs = e; m++; if (m >= fb)return !1 }); p[b].contentIsLoaded = !0; p[b].contentLength = m } function fa(b, c, a, d, m) { var f = Math.ceil(a * h.scale) + m; "auto" == c ? f = Math.ceil(a * h.scale) + m : "auto" == a ? f = Math.ceil(c * h.scale) + d : c > a && (f = Math.ceil(c * h.scale) + d); 0 < b.length && (b += ","); return b + f } function ub(b, c, a, d) { Ra(b); if (p[b].contentIsLoaded)X(b, d); else { var m = "", e = "album", E; E = fa("", h.settings.width.l1.xs, h.settings.height.l1.xs, h.settings.width.l1.xsc, h.settings.height.l1.xsc); E = fa(E, h.settings.width.l1.sm, h.settings.height.l1.sm, h.settings.width.l1.smc, h.settings.height.l1.smc); E = fa(E, h.settings.width.l1.me, h.settings.height.l1.me, h.settings.width.l1.mec, h.settings.height.l1.mec); E = fa(E, h.settings.width.l1.la, h.settings.height.l1.la, h.settings.width.l1.lac, h.settings.height.l1.lac); E = fa(E, h.settings.width.l1.xl, h.settings.height.l1.xl, h.settings.width.l1.xlc, h.settings.height.l1.xlc); E = fa(E, h.settings.width.lN.xs, h.settings.height.lN.xs, h.settings.width.lN.xsc, h.settings.height.lN.xsc); E = fa(E, h.settings.width.lN.sm, h.settings.height.lN.sm, h.settings.width.lN.smc, h.settings.height.lN.smc); E = fa(E, h.settings.width.lN.me, h.settings.height.lN.me, h.settings.width.lN.mec, h.settings.height.lN.mec); E = fa(E, h.settings.width.lN.la, h.settings.height.lN.la, h.settings.width.lN.lac, h.settings.height.lN.lac); E = fa(E, h.settings.width.lN.xl, h.settings.height.lN.xl, h.settings.width.lN.xlc, h.settings.height.lN.xlc); if (0 == p[b].GetID())m = zb.url() + "user/" + f.userID + "?alt=json&kind=album&thumbsize=" + E + "&rnd=" + (new Date).getTime(); else { var g = ""; "undefined" !== typeof p[b].customData.authkey && (g = p[b].customData.authkey); m = zb.url() + "user/" + f.userID + "/albumid/" + p[b].GetID() + "?alt=json&kind=photo" + g + "&thumbsize=" + E + "&imgmax=d"; e = "image" } hb(); jQuery.ajaxSetup({cache: !1}); jQuery.support.cors = !0; var k = setTimeout(function () { ea(); R("Could not retrieve Picasa/Google+ data...") }, 6E4); jQuery.getJSON(m, "callback=?", function (m) { clearTimeout(k); ea(); ac(b, m, e); if (c)r(!1) || X(b, d); else if (-1 != a) { m = -1; for (var f = p.length, h = 0; h < f; h++)if ("image" == p[h].kind && p[h].GetID() == a) { m = h; break } ta(m, !0) } else X(b, d) }).fail(function (a, b, c) { clearTimeout(k); ea(); var d = "", f; for (f in a)d += f + "=" + a[f] + "<br>"; R("Could not retrieve Picasa/Google+ data. Error: " + (b + ", " + c + " " + d + "<br><br>URL:" + m)) }) } } function ac(b, c, a) { var d = 0, m = p[b].GetID(); c = c.feed.entry; var e = f.albumSorting; "image" == a && (e = f.photoSorting); switch (e) { case "random": c = Ka(c); break; case "reversed": c = c.reverse(); break; case "titleAsc": c.sort(function (b, c) { var d = "", m = ""; "image" == a ? "" != f.thumbnailLabel.title ? (d = N(unescape(unescape(unescape(unescape(b.media$group.media$content[0].url))))), m = N(unescape(unescape(unescape(unescape(c.media$group.media$content[0].url)))))) : (d = b.media$group.media$description.$t.toUpperCase(), m = c.media$group.media$description.$t.toUpperCase()) : (d = b.media$group.media$title.$t.toUpperCase(), m = c.media$group.media$title.$t.toUpperCase()); return d < m ? -1 : d > m ? 1 : 0 }); break; case "titleDesc": c.sort(function (b, c) { var d = "", m = ""; "image" == a ? "" != f.thumbnailLabel.title ? (d = N(unescape(unescape(unescape(unescape(b.media$group.media$content[0].url))))), m = N(unescape(unescape(unescape(unescape(c.media$group.media$content[0].url)))))) : (d = b.media$group.media$description.$t.toUpperCase(), m = c.media$group.media$description.$t.toUpperCase()) : (d = b.media$group.media$title.$t.toUpperCase(), m = c.media$group.media$title.$t.toUpperCase()); return d > m ? -1 : d < m ? 1 : 0 }) } jQuery.each(c, function (b, c) { var e = c.media$group.media$title.$t, u = c.media$group.media$thumbnail[0].url, h = c.gphoto$id.$t, g = "", p = c.media$group.media$description.$t; "image" == a && (g = e, e = p, p = ""); var k = c.media$group.media$content[0].url; "image" == a && "" != f.thumbnailLabel.title && (e = N(unescape(unescape(unescape(unescape(k)))))); var r = !0; "album" == a && (yb(e, h) || (r = !1)); if (r && (r = "", "album" == a ? r = h : (k = k.substring(0, k.lastIndexOf("/")), k = k.substring(0, k.lastIndexOf("/")) + "/", r = window.screen.width > window.screen.height ? k + "w" + window.screen.width + "/" + g : k + "h" + window.screen.height + "/" + g), e = W(e, u, r, p, "", a, "", h, m), e.picasaThumbBaseURL = "", e.imageNumber = d, "album" == a && (e.author = c.author[0].name.$t, e.contentLength = c.gphoto$numphotos.$t), u = { url: { l1: { xs: "", sm: "", me: "", la: "", xl: "" }, lN: {xs: "", sm: "", me: "", la: "", xl: ""} }, width: {l1: {xs: 0, sm: 0, me: 0, la: 0, xl: 0}, lN: {xs: 0, sm: 0, me: 0, la: 0, xl: 0}}, height: {l1: {xs: 0, sm: 0, me: 0, la: 0, xl: 0}, lN: {xs: 0, sm: 0, me: 0, la: 0, xl: 0}} }, u = Ab("l1", 0, u, c, a), u = Ab("lN", 5, u, c, a), e.thumbs = u, "function" == typeof f.fnProcessData && f.fnProcessData(e, "picasa", c), d++, d >= ("album" == a ? Pa : fb)))return !1 }); p[b].contentIsLoaded = !0; p[b].contentLength = d } function Ab(b, c, a, d, m) { for (var f = ["xs", "sm", "me", "la", "xl"], e = 0; e < f.length; e++)if (a.url[b][f[e]] = d.media$group.media$thumbnail[c + e].url, "image" == m) { a.width[b][f[e]] = d.media$group.media$thumbnail[c + e].width; a.height[b][f[e]] = d.media$group.media$thumbnail[c + e].height; var g = d.media$group.media$thumbnail[c + e].width, p = d.media$group.media$thumbnail[c + e].height; if ("auto" == h.settings.width[b][f[e]] && p < h.settings.height[b][f[e]]) { var k = g / p; a.width[b][f[e]] = g * k; a.height[b][f[e]] = p * k; k = a.url[b][f[e]].substring(0, a.url[b][f[e]].lastIndexOf("/")); k = k.substring(0, k.lastIndexOf("/")) + "/"; a.url[b][f[e]] = k + "h" + h.settings.height[b][f[e]] + "/" } "auto" == h.settings.height[b][f[e]] && g < h.settings.width[b][f[e]] && (k = p / g, a.height[b][f[e]] = p * k, a.width[b][f[e]] = g * k, k = a.url[b][f[e]].substring(0, a.url[b][f[e]].lastIndexOf("/")), k = k.substring(0, k.lastIndexOf("/")) + "/", a.url[b][f[e]] = k + "w" + h.settings.width[b][f[e]] + "/") } else"auto" != h.settings.width[b][f[e]] ? a.width[b][f[e]] = d.media$group.media$thumbnail[c + e].width : (k = a.url[b][f[e]].substring(0, a.url[b][f[e]].lastIndexOf("/")), k = k.substring(0, k.lastIndexOf("/")) + "/", a.url[b][f[e]] = k + "h" + h.settings.height[b][f[e]] + "/"), "auto" != h.settings.height[b][f[e]] ? a.height[b][f[e]] = d.media$group.media$thumbnail[c + e].height : (k = a.url[b][f[e]].substring(0, a.url[b][f[e]].lastIndexOf("/")), k = k.substring(0, k.lastIndexOf("/")) + "/", a.url[b][f[e]] = k + "w" + h.settings.width[b][f[e]] + "/"); return a } function W(b, c, a, d, m, f, e, h, g) { b = new bc(b, h); b.thumbsrc = c; b.src = a; b.description = d; b.destinationURL = m; b.kind = f; b.albumID = g; b.tags = 0 == e.length ? null : e.split(" "); p.push(b); return b } function yb(b, c) { var a = b.toUpperCase(); if (null !== Ja)for (var d = 0; d < Ja.length; d++) { if (a == Ja[d].toUpperCase() || c == Ja[d])return !0 } else { var m = !1; if (null !== Na) { for (d = 0; d < Na.length; d++)-1 !== a.indexOf(Na[d]) && (m = !0); if (!m)return !1 } if (null !== Ma)for (d = 0; d < Ma.length; d++)if (-1 !== a.indexOf(Ma[d]))return !1; return !0 } } function X(b, c) { "display" == f.lazyBuild ? xa(e.conTnParent, f.lazyBuildTreshold) ? ib(b, c) : (Ta = b, Bb = c) : ib(b, c) } function ib(b, c) { f.lazyBuild = "none"; Qa = Ta = -1; S && Da(!1); if (b != gb) { if (f.locationHash && c) { var a = "nanogallery/" + ja + "/" + p[b].GetID(); va = "#" + a; top.location.hash = a } gb = p[b].GetID(); Ra(b); a = 0; 0 < p[b].paginationLastPage && p[b].paginationLastWidth == e.conTnParent.width() && (a = p[b].paginationLastPage); ya(b, a) } } function Cb(b) { var c = "folder"; 0 == b && (c = "folderHome"); c = jQuery('<div class="' + c + ' oneFolder">' + p[b].title + "</div>").appendTo(e.conBC); jQuery(c).data("albumIdx", b); c.click(function () { var a = jQuery(this).data("albumIdx"); jQuery(this).nextAll().remove(); sa(a, !1, -1, !0) }) } function Db(b) { var c = jQuery('<div class="separator' + (f.RTL ? "RTL" : "") + '"></div>').appendTo(e.conBC); jQuery(c).data("albumIdx", b); c.click(function () { var a = jQuery(this).data("albumIdx"); jQuery(this).nextAll().remove(); jQuery(this).remove(); sa(a, !1, -1, !0) }) } function Ra(b) { var c = !1; if (1 == f.displayBreadcrumb) { 0 == e.conBC.children().length && e.conNavBCon.css({opacity: 0, "max-height": "0px"}); c = !0; e.conBC.children().remove(); Cb(0); if (0 != b) { var a = p.length, d = []; for (d.push(b); 0 != p[b].albumID;)for (i = 1; i < a; i++)if (p[i].GetID() == p[b].albumID) { b = i; d.push(b); break } Db(0); for (i = d.length - 1; 0 <= i; i--)Cb(d[i]), 0 < i && Db(d[i - 1]) } a = e.conBC.children().length; 0 == a ? (ba = "l1", f.breadcrumbAutoHideTopLevel && (e.conNavBCon.css({ opacity: 0, "max-height": "0px" }), c = !1)) : (ba = 1 == a ? "l1" : "lN", 1 == a && f.breadcrumbAutoHideTopLevel ? e.conNavBCon.animate({opacity: "0", "max-height": "0px"}) : e.conNavBCon.animate({ opacity: "1", "max-height": "50px" })); ka = wa() } f.useTags && (c = !0, null == Eb && (Eb = jQuery('<div class="nanoGalleryTags"></div>').appendTo(e.conNavB))); f.galleryFullpageButton && (c = !0); !Fb && c && (Fb = !0, e.conNavBCon.show()) } function hb() { e.conLoadingB.css({visibility: "visible"}) } function ea() { e.conLoadingB.css({visibility: "hidden"}) } function sa(b, c, a, d) { switch (f.kind) { case "": X(b, d); break; case "flickr": sb(b, c, a, d); break; case "json": tb(b, c, a, d); break; default: ub(b, c, a, d) } } function Ga() { "auto" == w() ? cc() : "auto" == l() ? dc() : ec(); jb(); if (f.galleryToolbarWidthAligned && void 0 !== e.conNavBCon) { var b = e.conTn.outerWidth(!0); e.conNavBCon.width(); e.conNavBCon.width(b) } } function cc() { var b = e.conTnParent.width(), c = 0, a = 0, d = 0, m = [], h = wa(), g = 0, k = f.thumbnailGutterHeight, r = H(), l = e.conTn.find(".nanoGalleryThumbnailContainer"); "justified" == f.thumbnailAlignment ? (h = Math.min(h, l.length), g = 1 == h ? 0 : (b - h * r) / (h - 1)) : g = f.thumbnailGutterWidth; var x = 0; l.each(function () { var b = jQuery(this).data("index"); if (void 0 !== b) { if (0 == a)H(), m[c] = p[b].thumbFullHeight + k, c++, x++, c >= h && (c = 0, a++); else return !1; d++ } }); var aa = m.length * (r + g) - g, a = 0; l.each(function () { var b = jQuery(this), e = b.data("index"); if (void 0 !== e) { "onBottom" == f.thumbnailLabel.position && kb(b, p[e]); var r = 0, l = 0; if (0 == a)r = c * (H() + g), m[c] = p[e].thumbFullHeight + k, c++, c >= h && (c = 0, a++); else { var x = 0, r = m[0]; for (i = 1; i < h; i++)if (m[i] + 5 < r) { x = i; break } l = m[x]; r = x * (H() + g); m[x] = l + p[e].thumbFullHeight + k } x = r; f.RTL && (x = aa - r - H()); b.css({top: l, left: x}); lb(b, p[e], d); d++ } }); b = m[0]; for (i = 1; i < x; i++)b = Math.max(b, m[i]); e.conTn.width(aa).height(b) } function dc() { var b = e.conTnParent.width(), c = 0, a = 0, d = 0, m = [], u = 0, g = [], k = !1, r = 0, l = 0, x = 0, aa = 0, v = f.thumbnailGutterWidth, P = f.thumbnailGutterHeight, t = 0, q = 0, y = !1, z = !1, s = e.conTn.find(".nanoGalleryThumbnailContainer"); s.each(function () { var a = jQuery(this).data("index"); if (void 0 !== a && void 0 != p[a])if (0 < p[a].thumbImg().width) { var d = p[a], e = Math.floor(d.thumbImg().width / d.thumbImg().height * w()) + h.borderWidth + h.imgcBorderWidth; f.thumbnailFeatured && 0 == r && (x = e *= 2); k && (k = !1, u++, c = 0, z = y = !1, 1 == u && 0 < x && (c = x, x = 0)); d.thumbImg().height > d.thumbImg().width ? y = !0 : z = !0; c + e + v < b ? (c += e + v, g[u] = w(), d = Math.max(y ? t : 0, z ? q : 0), f.thumbnailAdjustLastRowHeight && 0 < d && (g[u] = Math.min(g[u], d)), m[u] = a) : (c += e, d = Math.floor(w() * b / c), g[u] = d, y && (t = Math.max(t, d)), z && (q = Math.max(q, d)), m[u] = a, k = !0); r++ } else return !1 }); r = a = d = u = 0; s.each(function () { var c = jQuery(this), e = c.data("index"); if (void 0 !== e && void 0 != p[e])if (0 < p[e].thumbImg().width) { var k = p[e], x = Math.floor(k.thumbImg().width / k.thumbImg().height * g[u]); 0 == r && f.thumbnailFeatured && (x *= 2, l = 1 == g.length ? 2 * parseInt(g[0]) : parseInt(g[0]) + parseInt(g[1]) + h.borderHeight + h.imgcBorderHeight); e == m[u] && (m.length != u + 1 ? x = b - a - h.borderWidth - h.imgcBorderWidth : a + x + h.borderWidth + h.imgcBorderWidth + v > b && (x = b - a - h.borderWidth - h.imgcBorderWidth)); var t = 0; 0 == r && f.thumbnailFeatured ? (t = l, aa = x + h.borderWidth + h.imgcBorderWidth, k.customData.featured = !0, c.find("img").attr("src", k.thumbX2src)) : t = g[u]; t = parseInt(t); x = parseInt(x); c.width(x + h.imgcBorderWidth).height(t + h.imgcBorderHeight + h.labelHeight); c.find(".imgContainer").height(t).width(x); c.find("img").css({"max-height": t + 2, "max-width": x + 2}); c.find(".subcontainer").width(x + h.imgcBorderWidth).height(t + h.imgcBorderHeight + h.labelHeight); var q = a; f.RTL && (q = b - a - (x + h.borderWidth + h.imgcBorderWidth)); c.css({top: d, left: q}); k.thumbFullWidth = x + h.borderWidth + h.imgcBorderWidth; k.thumbFullHeight = t + h.borderHeight + h.imgcBorderHeight + h.labelHeight; mb(c); lb(c, k, r); a += x + h.borderWidth + h.imgcBorderWidth + v; e == m[u] && (d += g[u] + h.labelHeight + P + h.imgcBorderHeight + h.borderHeight, u++, a = 0, 1 == u && 0 < aa && (a = aa, aa = 0)); r++ } else return !1 }); 0 < u && (d -= P); l = l + da() + h.labelHeight; e.conTn.width(b).height(d > l ? d : l) } function wa() { var b = l() + h.borderWidth + h.imgcBorderWidth, c = e.conTnParent.width(), a = 0, a = "justified" == f.thumbnailAlignment ? Math.floor(c / b) : Math.floor((c + f.thumbnailGutterWidth) / (b + f.thumbnailGutterWidth)); 0 < f.maxItemsPerLine && a > f.maxItemsPerLine && (a = f.maxItemsPerLine); 1 > a && (a = 1); return a } function ec() { var b = 0, c = 0, a = 0, d = f.thumbnailGutterHeight, m = e.conTnParent.width(), h = wa(), g = 0, k = 0, r = 0, x = [], l = 0; wa(); if (0 < T && 0 < H() && h != ka) { ka = h; var t = e.conPagin.data("galleryIdx"); ya(t, 0) } else { var t = e.conTn.find(".nanoGalleryThumbnailContainer"), v = t.length; "justified" == f.thumbnailAlignment ? (h = Math.min(h, v), a = 1 == h ? 0 : (m - h * H()) / (h - 1)) : a = f.thumbnailGutterWidth; f.RTL && (t.each(function () { if (void 0 !== jQuery(this).data("index")) { if (0 == c)b = l * (H() + a), r = x[l] = b; else return !1; l++; l >= h && (l = 0, c += da() + d) } }), m = r + H(), l = c = 0); t.each(function () { var e = jQuery(this), t = e.data("index"); if (void 0 !== t) { 0 == c ? (b = l * (H() + a), r = x[l] = b) : (b = x[l], k = c); var v = b; f.RTL && (v = parseInt(m) - b - H()); e.css({top: c, left: v}); lb(e, p[t], g); l++; l >= h && (l = 0, c += da() + d); g++ } }); e.conTn.width(r + H()).height(k + da()) } } function lb(b, c, a) { 0 == b.css("opacity") && (b.removeClass("nanogalleryHideElement"), f.thumbnailDisplayTransition ? "function" == typeof f.fnThumbnailDisplayEffect ? f.fnThumbnailDisplayEffect(b, c, 0) : b.delay(a * h.displayInterval).fadeTo(150, 1) : b.css({opacity: 1})) } function jb() { var b = e.conTn.find(".nanoGalleryThumbnailContainer").filter(function () { return Gb(jQuery(this), h.lazyLoadTreshold) }); jQuery(b).each(function () { var b = jQuery(this).find("img"); if ("data:image/gif;base64,R0lGODlhEAAQAIAAAP///////yH5BAEKAAEALAAAAAAQABAAAAIOjI+py+0Po5y02ouzPgUAOw==" == jQuery(b).attr("src")) { var a = jQuery(this).data("index"); void 0 != a && void 0 != p[a] && (jQuery(b).attr("src", ""), jQuery(b).attr("src", p[a].thumbImg().src)) } }) } function fc(b, c) { if (void 0 != e.conPagin)if (e.conPagin.children().remove(), 0 == T || "auto" == w() || "auto" == l())e.conPagin.hide(); else { e.conPagin.show(); e.conPagin.data("galleryIdx", b); e.conPagin.data("currentPageNumber", c); var a = 0, d = 0; if (0 < c) { var m = jQuery('<div class="paginationPrev">' + O.paginationPrevious + "</div>").appendTo(e.conPagin), d = d + jQuery(m).outerWidth(!0); m.click(function (a) { vb() }) } m = 0; 0 < T && "auto" != w() && "auto" != l() && (a = Math.ceil(p[b].contentLength / (T * ka))); 5 <= c ? (m = c - 5, a > c + 6 && (a = c + 6)) : 10 < a && (a = 10); if (1 == a)e.conPagin.hide(); else { for (; m < a; m++) { var f = ""; m == c && (f = " currentPage"); f = jQuery('<div class="paginationItem' + f + '">' + (m + 1) + "</div>").appendTo(e.conPagin); f.data("pageNumber", m); d += f.outerWidth(!0); f.click(function (a) { a = e.conPagin.data("galleryIdx"); var b = jQuery(this).data("pageNumber"); xa(e.base, 0) || $("html, body").animate({scrollTop: e.base.offset().top}, 200); ya(a, b) }) } c + 1 < a && (a = jQuery('<div class="paginationNext">' + O.paginationNext + "</div>").appendTo(e.conPagin), d += a.outerWidth(!0), a.click(function (a) { wb() })); e.conPagin.width(d) } } } function wb() { var b = e.conPagin.data("galleryIdx"), c = 0; 0 < T && (c = p[b].contentLength / (T * ka)); n2 = Math.ceil(c); c = e.conPagin.data("currentPageNumber"); c < n2 - 1 ? c++ : c = 0; xa(e.base, 0) || $("html, body").animate({scrollTop: e.base.offset().top}, 200); ya(b, c) } function vb() { var b = e.conPagin.data("galleryIdx"), c = 0; 0 < T && (c = p[b].contentLength / (T * ka)); n2 = Math.ceil(c); c = e.conPagin.data("currentPageNumber"); 0 < c ? c-- : c = n2 - 1; xa(e.base, 0) || $("html, body").animate({scrollTop: e.base.offset().top}, 250); ya(b, c) } function ya(b, c) { Ua = -1; e.conTn.parent().animate({opacity: 0}, 100).promise().done(function () { e.conTn.hide(0).off().show(0).html(""); for (var a = p.length, d = 0; d < a; d++)p[d].hovered = !1; e.conTnParent.css({left: 0, opacity: 1}); jQuery(e.conTn[0]).css({left: 0}); gc(b, c, hc) }) } function gc(b, c, a) { if (-1 != b && void 0 != p[b]) { p[b].paginationLastPage = c; p[b].paginationLastWidth = e.conTnParent.width(); var d = p.length, m = 0, g = 0, k = 0; 0 < T && "auto" != w() && "auto" != l() && (k = c * T * ka); ea(); var r = !1, x = !1, t = 0; (function () { for (var e = 0; e < f.galleryRenderStep; e++) { if (t >= d) { a(b, c); return } var v = p[t]; if (v.albumID == p[b].GetID()) { g++; if (0 < T && "auto" != w() && "auto" != l() && m + 1 > T * ka) { a(b, c); return } if (g > k) { m++; var q = xb(v, t, !1), P = q.e$; !f.thumbnailLazyLoad || q.cIS || r || (Gb(P, h.lazyLoadTreshold) ? (P.find("img").attr("src", ""), P.find("img").attr("src", v.thumbImg().src), x = !0) : x && (r = !0)) } } t++ } t < d ? setTimeout(arguments.callee, 2) : a(b, c) })() } } function hc(b, c) { Ga(); fc(b, c); Ua = b } function xb(b, c, a) { var d = [], m = 0, h = "", g = " nanogalleryHideElement"; f.thumbnailLazyLoad && "auto" == l() && (h = "top:0px;left:0px;", g = ""); d[m++] = '<div class="nanoGalleryThumbnailContainer' + g + '" style="display:block;opacity:0;' + h + '" ><div class="subcontainer" style="display:block;">'; h = !1; g = "data:image/gif;base64,R0lGODlhEAAQAIAAAP///////yH5BAEKAAEALAAAAAAQABAAAAIOjI+py+0Po5y02ouzPgUAOw=="; if ("auto" == w() && 0 == p[c].thumbImg().height || "auto" == l() && 0 == p[c].thumbImg().width)h = !0; if (!f.thumbnailLazyLoad || h)g = b.thumbImg().src; var k = ic(b), r = jc(b); "auto" == w() ? d[m++] = '<div class="imgContainer" style="width:' + l() + 'px;"><img class="image" src="' + g + '" alt=" " style="max-width:' + l() + 'px;"></div>' : "auto" == l() ? d[m++] = '<div class="imgContainer" style="height:' + w() + 'px;"><img class="image" src="' + g + '" alt=" " style="max-height:' + w() + 'px;" ></div>' : d[m++] = '<div class="imgContainer" style="width:' + l() + "px;height:" + w() + 'px;"><img class="image" src="' + g + '" alt=" " style="max-width:' + l() + "px;max-height:" + w() + 'px;" ></div>'; if ("album" == b.kind) { if (1 == f.thumbnailLabel.display) { if (0 < b.contentLength)switch (f.thumbnailLabel.itemsCount) { case "title": k += " " + O.thumbnailLabelItemsCountPart1 + "<span>" + b.contentLength + "</span>" + O.thumbnailLabelItemsCountPart2; break; case "description": r += " " + O.thumbnailLabelItemsCountPart1 + "<span>" + b.contentLength + "</span>" + O.thumbnailLabelItemsCountPart2 } d[m++] = '<div class="labelImage" style="width:' + l() + "px;" + (f.RTL ? "direction:RTL;" : "") + '"><div class="labelFolderTitle labelTitle" >' + k + '</div><div class="labelDescription" >' + r + "</div></div>" } } else 1 == f.thumbnailLabel.display && (a && 0 == r.length && "onBottom" == f.thumbnailLabel.position && (r = "&nbsp;"), d[m++] = '<div class="labelImage" style="width:' + l() + "px;" + (f.RTL ? "direction:RTL;" : "") + '"><div class="labelImageTitle labelTitle" >' + k + '</div><div class="labelDescription" >' + r + "</div></div>"); d[m++] = "</div></div>"; a = jQuery(d.join("")).appendTo(e.conTnHid); b.$elt = a; a.data("index", c); a.find("img").data("index", c); kc(a, b); a.detach().appendTo(e.conTn); Hb(a); if (h)ngimagesLoaded(a).on("always", function (a) { var b = p[jQuery(a.images[0].img).data("index")]; if (void 0 != b && "data:image/gif;base64,R0lGODlhEAAQAIAAAP///////yH5BAEKAAEALAAAAAAQABAAAAIOjI+py+0Po5y02ouzPgUAOw==" != a.images[0].img.src) { var c = !1; b.thumbImg().height != a.images[0].img.naturalHeight && (b.thumbSetImgHeight(a.images[0].img.naturalHeight), b.thumbSetImgWidth(a.images[0].img.naturalWidth), c = !0); b.thumbImg().width != a.images[0].img.naturalWidth && (b.thumbSetImgHeight(a.images[0].img.naturalHeight), b.thumbSetImgWidth(a.images[0].img.naturalWidth), c = !0); c && (kb(b.$elt, b), mb(b.$elt), Ga()) } }); else kb(a, b), mb(a); return {e$: a, cIS: h} } function ic(b) { b = b.title; if (1 == f.thumbnailLabel.display) { if (void 0 === b || 0 == b.length)b = "&nbsp;"; "" != O.thumbnailImageTitle && (b = O.thumbnailImageTitle); 3 < f.thumbnailLabel.titleMaxLength && b.length > f.thumbnailLabel.titleMaxLength && (b = b.substring(0, f.thumbnailLabel.titleMaxLength) + "...") } return b } function jc(b) { var c = ""; 1 == f.thumbnailLabel.displayDescription && (c = "album" == b.kind ? "" != O.thumbnailImageDescription ? O.thumbnailAlbumDescription : b.description : "" != O.thumbnailImageDescription ? O.thumbnailImageDescription : b.description, 3 < f.thumbnailLabel.descriptionMaxLength && c.length > f.thumbnailLabel.descriptionMaxLength && (c = c.substring(0, f.thumbnailLabel.descriptionMaxLength) + "...")); return c } function kb(b, c) { if ("auto" == w()) { if (0 < c.thumbImg().height) { var a = c.thumbImg().height / c.thumbImg().width; b.find(".imgContainer").height(l() * a); "onBottom" == f.thumbnailLabel.position ? (c.thumbLabelHeight = b.find(".labelImage").outerHeight(!0), c.thumbFullHeight = l() * a + c.thumbLabelHeight + h.borderHeight + h.imgcBorderHeight, b.width(H() - h.borderWidth).height(c.thumbFullHeight - h.borderHeight), b.find(".labelImage").css({ position: "absolute", top: "", bottom: "0px" })) : (c.thumbFullHeight = l() * a + c.thumbLabelHeight + h.borderHeight + h.imgcBorderHeight, b.width(H() - h.borderWidth).height(c.thumbFullHeight - h.borderHeight)) } c.thumbFullWidth = H(); b.find(".subcontainer").width(H() - h.borderWidth).height(c.thumbFullHeight - h.borderHeight) } else"auto" != l() && (c.thumbFullHeight = da(), c.thumbFullWidth = H(), b.width(c.thumbFullWidth - h.borderWidth).height(c.thumbFullHeight - h.borderHeight), b.find(".subcontainer").width(c.thumbFullWidth - h.borderWidth).height(c.thumbFullHeight - h.borderHeight)) } function kc(b, c) { if ("function" == typeof f.fnThumbnailInit)f.fnThumbnailInit(b, c, s()); else if (f.thumbnailLabel.display)switch (f.thumbnailLabel.position) { case "onBottom": b.find(".labelImage").css({ top: 0, position: "relative", left: 0, right: 0 }); "auto" == w() ? (b.find(".labelImageTitle").css({"white-space": "normal"}), b.find(".labelFolderTitle").css({"white-space": "normal"}), b.find(".labelDescription").css({"white-space": "normal"})) : (b.find(".labelImageTitle").css({"white-space": "nowrap"}), b.find(".labelFolderTitle").css({"white-space": "nowrap"}), b.find(".labelDescription").css({"white-space": "nowrap"})); break; case "overImageOnTop": b.find(".labelImage").css({top: 0, bottom: 0, left: 0, right: 0}); break; case "overImageOnMiddle": b.find(".labelImage").css({ top: 0, bottom: 0, left: 0, right: 0 }); b.find(".labelFolderTitle").css({left: 0, right: 0, position: "absolute", bottom: "50%"}); b.find(".labelImageTitle").css({left: 0, right: 0, position: "absolute", bottom: "50%"}); b.find(".labelDescription").css({left: 0, right: 0, position: "absolute", top: "50%"}); break; default: f.thumbnailLabel.position = "overImageOnBottom", b.find(".labelImage").css({ bottom: 0, left: 0, right: 0 }) } } function Ia() { for (var b = p.length, c = 0; c < b; c++)p[c].hovered && Ha(p[c].$elt) } function Hb(b) { var c = b.data("index"); if (void 0 != c) { var a = p[c]; "function" == typeof f.fnThumbnailHoverInit && f.fnThumbnailHoverInit(b, a, s()); for (var d in a.eltTransform)delete a.eltTransform[d]; for (j = 0; j < C.length; j++)switch (C[j].name) { case "imageSplit4": d = b.find(".subcontainer"); var c = b.find(".labelImage"), m = b.find(".imgContainer"); b.find(".imgContainer").css({position: "absolute"}); d.css({overflow: "hidden", position: "relative", width: "100%", height: "100%"}); d.prepend(m.clone()); d.prepend(b.find(".imgContainer").clone()); m = b.find(".imgContainer"); L("", m); B(a, "imgContainer0", m.eq(0)); y(a, "imgContainer0"); B(a, "imgContainer1", m.eq(1)); y(a, "imgContainer1"); B(a, "imgContainer2", m.eq(2)); y(a, "imgContainer2"); B(a, "imgContainer3", m.eq(3)); y(a, "imgContainer3"); break; case "imageSplitVert": d = b.find(".subcontainer"); m = b.find(".imgContainer"); m.css({position: "absolute"}); d.css({overflow: "hidden", position: "relative"}); d.prepend(m.clone()); m = b.find(".imgContainer"); L("", m); B(a, "imgContainer0", m.eq(0)); y(a, "imgContainer0"); B(a, "imgContainer1", m.eq(1)); y(a, "imgContainer1"); break; case "labelSplit4": d = b.find(".subcontainer"); c = b.find(".labelImage").css({top: 0, bottom: 0}); d.css({overflow: "hidden", position: "relative"}); c.clone().appendTo(d); b.find(".labelImage").clone().appendTo(d); c = b.find(".labelImage"); B(a, "labelImage0", c.eq(0)); y(a, "labelImage0"); B(a, "labelImage1", c.eq(1)); y(a, "labelImage1"); B(a, "labelImage2", c.eq(2)); y(a, "labelImage2"); B(a, "labelImage3", c.eq(3)); y(a, "labelImage3"); break; case "labelSplitVert": d = b.find(".subcontainer"); c = b.find(".labelImage"); d.css({ overflow: "hidden", position: "relative" }); c.clone().appendTo(d); c = b.find(".labelImage"); B(a, "labelImage0", c.eq(0)); y(a, "labelImage0"); B(a, "labelImage1", c.eq(1)); y(a, "labelImage1"); break; case "labelAppearSplit4": d = b.find(".subcontainer"); c = b.find(".labelImage"); c.css({left: 0, top: 0, right: 0, bottom: 0}); d.css({overflow: "hidden", position: "relative"}); c.clone().appendTo(d); b.find(".labelImage").clone().appendTo(d); c = b.find(".labelImage"); d = B(a, "labelImage0", c.eq(0)); d.translateX = -a.thumbFullWidth / 2; d.translateY = -a.thumbFullHeight / 2; y(a, "labelImage0"); d = B(a, "labelImage1", c.eq(1)); d.translateX = a.thumbFullWidth / 2; d.translateY = -a.thumbFullHeight / 2; y(a, "labelImage1"); d = B(a, "labelImage2", c.eq(2)); d.translateX = a.thumbFullWidth / 2; d.translateY = a.thumbFullHeight / 2; y(a, "labelImage2"); d = B(a, "labelImage3", c.eq(3)); d.translateX = -a.thumbFullWidth / 2; d.translateY = a.thumbFullHeight / 2; y(a, "labelImage3"); break; case "labelAppearSplitVert": d = b.find(".subcontainer"); c = b.find(".labelImage"); d.css({overflow: "hidden", position: "relative"}); c.clone().appendTo(d); c = b.find(".labelImage"); B(a, "labelImage0", c.eq(0)).translateX = -a.thumbFullWidth / 2; y(a, "labelImage0"); B(a, "labelImage1", c.eq(1)).translateX = a.thumbFullWidth / 2; y(a, "labelImage1"); break; case "imageScale150Outside": e.base.css({overflow: "visible"}); e.conTn.css({overflow: "visible"}); b.css({overflow: "visible"}); b.find(".subcontainer").css({overflow: "visible"}); b.find(".imgContainer").css({overflow: "visible"}); B(a, "img0", b.find("img")); y(a, "img0"); L(b.find(".imgContainer"), b.find(".labelImage")); break; case "scale120": e.base.css({overflow: "visible"}); e.conTn.css({overflow: "visible"}); B(a, "base", b); y(a, "base"); break; case "scaleLabelOverImage": d = b.find(".imgContainer"); c = b.find(".labelImage"); L(d, c); b.find(".labelImage").css({opacity: 0}); B(a, "labelImage0", c).scale = 50; y(a, "labelImage0"); B(a, "imgContainer0", d); y(a, "imgContainer0"); break; case "overScale": b.css({overflow: "hidden"}); d = b.find(".imgContainer"); c = b.find(".labelImage"); L("", c); c.css({opacity: 0}); d.css({opacity: 1}); B(a, "labelImage0", c).scale = 150; y(a, "labelImage0"); B(a, "imgContainer0", d); y(a, "imgContainer0"); break; case "overScaleOutside": e.base.css({overflow: "visible"}); e.conTn.css({overflow: "visible"}); b.css({overflow: "visible"}); d = b.find(".imgContainer"); c = b.find(".labelImage"); L("", c); c.css({opacity: 0}); d.css({opacity: 1}); B(a, "labelImage0", c).scale = 150; y(a, "labelImage0"); B(a, "imgContainer0", d); y(a, "imgContainer0"); break; case "rotateCornerBL": b.css({overflow: "hidden"}); d = b.find(".labelImage"); d.css({opacity: 1}); d[0].style[K + "Origin"] = "100% 100%"; B(a, "labelImage0", d).rotateZ = -90; y(a, "labelImage0"); d = b.find(".imgContainer"); d[0].style[K + "Origin"] = "100% 100%"; B(a, "imgContainer0", d); y(a, "imgContainer0"); break; case "rotateCornerBR": b.css({overflow: "hidden"}); d = b.find(".labelImage"); d.css({opacity: 1}); d[0].style[K + "Origin"] = "0% 100%"; B(a, "labelImage0", d).rotateZ = 90; y(a, "labelImage0"); d = b.find(".imgContainer"); d[0].style[K + "Origin"] = "0 100%"; B(a, "imgContainer0", d); y(a, "imgContainer0"); break; case "imageRotateCornerBL": d = b.find(".imgContainer"); L(b, d); b.css({overflow: "hidden"}); b.find(".labelImage").css({opacity: 1}); d[0].style[K + "Origin"] = "bottom right"; B(a, "imgContainer0", d); y(a, "imgContainer0"); break; case "imageRotateCornerBR": d = b.find(".imgContainer"); L(b, d); b.css({overflow: "hidden"}); b.find(".labelImage").css({opacity: 1}); d[0].style[K + "Origin"] = "0 100%"; B(a, "imgContainer0", d); y(a, "imgContainer0"); break; case "slideUp": b.css({overflow: "hidden"}); d = b.find(".labelImage"); d.css({opacity: 1, top: 0}); B(a, "labelImage0", d).translateY = a.thumbFullHeight; y(a, "labelImage0"); d = b.find(".imgContainer"); d.css({left: 0, top: 0}); B(a, "imgContainer0", d); y(a, "imgContainer0"); break; case "slideDown": b.css({overflow: "hidden"}); d = b.find(".labelImage"); d.css({opacity: 1, top: 0}); B(a, "labelImage0", d).translateY = -a.thumbFullHeight; y(a, "labelImage0"); d = b.find(".imgContainer"); d.css({left: 0, top: 0}); B(a, "imgContainer0", d); y(a, "imgContainer0"); break; case "slideRight": b.css({overflow: "hidden"}); d = b.find(".labelImage"); d.css({opacity: 1, top: 0}); B(a, "labelImage0", d).translateX = -a.thumbFullWidth; y(a, "labelImage0"); d = b.find(".imgContainer"); d.css({left: 0, top: 0}); B(a, "imgContainer0", d); y(a, "imgContainer0"); break; case "slideLeft": b.css({overflow: "hidden"}); d = b.find(".labelImage"); d.css({opacity: 1, top: 0}); B(a, "labelImage0", d).translateX = a.thumbFullWidth; y(a, "labelImage0"); d = b.find(".imgContainer"); d.css({left: 0, top: 0}); B(a, "imgContainer0", d); y(a, "imgContainer0"); break; case "imageSlideUp": case "imageSlideDown": case "imageSlideRight": case "imageSlideLeft": d = b.find(".imgContainer"); L(b, d); b.css({overflow: "visible"}); b.find(".labelImage").css({opacity: 1}); d.css({left: 0, top: 0}); B(a, "imgContainer0", d); y(a, "imgContainer0"); break; case "labelAppear": case "labelAppear75": var g = "rgb(" + G.oldLabelRed + "," + G.oldLabelGreen + "," + G.oldLabelBlue + ",0)"; b.find(".labelImage").css({backgroundColor: g}); b.find(".labelImageTitle").css({opacity: 0}); b.find(".labelFolderTitle").css({opacity: 0}); b.find(".labelDescription").css({opacity: 0}); break; case "descriptionAppear": b.find(".labelDescription").css({opacity: 0}); break; case "labelSlideUpTop": b.css({overflow: "hidden"}); b.find(".labelImage").css({ top: 0, bottom: 0 }); B(a, "labelImage0", b.find(".labelImage")).translateY = a.thumbFullHeight; y(a, "labelImage0"); break; case "labelSlideUp": b.css({overflow: "hidden"}); B(a, "labelImage0", b.find(".labelImage")).translateY = a.thumbFullHeight; y(a, "labelImage0"); break; case "labelSlideDown": b.css({overflow: "hidden"}); B(a, "labelImage0", b.find(".labelImage")).translateY = -a.thumbFullHeight; y(a, "labelImage0"); break; case "descriptionSlideUp": b.css({overflow: "hidden"}); c = "album" == a.kind ? b.find(".labelFolderTitle").outerHeight(!0) : b.find(".labelImageTitle").outerHeight(!0); b.find(".labelDescription").css({opacity: 0}); b.find(".labelImage").css({height: c}); B(a, "labelImage0", b.find(".labelImage")); y(a, "labelImage0"); break; case "imageExplode": L("", b); L(b.find(".labelImage"), b.find(".imgContainer")); d = b.find(".subcontainer"); for (var c = 7, m = b.find(".imgContainer"), k = m.outerWidth(!0) / c, r = m.outerHeight(!0), r = m.outerHeight(!0) / c, l = 0; l < c; l++)for (g = 0; g < c; g++) { var x = "rect(" + r * l + "px, " + k * (g + 1) + "px, " + r * (l + 1) + "px, " + k * g + "px)"; m.clone().appendTo(d).css({ top: 0, scale: 1, clip: x, left: 0, position: "absolute" }).data("ngScale", 1) } m.remove(); break; case "imageFlipHorizontal": switch (f.thumbnailLabel.position) { case "overImageOnTop": b.find(".labelImage").css({ top: -h.imgcBorderHeight / 2, bottom: h.imgcBorderWidth / 2, left: 0, right: 0 }); break; case "overImageOnMiddle": b.find(".labelImage").css({ top: -h.imgcBorderHeight / 2, bottom: h.imgcBorderWidth / 2, left: 0, right: 0 }); break; default: b.find(".labelImage").css({bottom: h.imgcBorderWidth / 2, left: 0, right: 0}) } e.base.css({overflow: "visible"}); e.conTn.css({overflow: "visible"}); b.css({overflow: "visible"}); L("", b); L(b.find(".labelImage"), b.find(".imgContainer")); d = b.find(".subcontainer"); d.css({overflow: "visible"}); d[0].style[Ib] = "preserve-3d"; c = Math.round(1.2 * a.thumbFullHeight) + "px"; d[0].style[Va] = c; d = b.find(".imgContainer"); d[0].style[za] = "hidden"; B(a, "imgContainer0", d); y(a, "imgContainer0"); b.find(".image")[0].style[za] = "hidden"; d = b.find(".labelImage"); d[0].style[za] = "hidden"; B(a, "labelImage0", d).rotateX = 180; y(a, "labelImage0"); break; case "imageFlipVertical": switch (f.thumbnailLabel.position) { case "overImageOnTop": b.find(".labelImage").css({ top: -h.imgcBorderHeight / 2, bottom: h.imgcBorderWidth / 2, left: 0, right: 0 }); break; case "overImageOnMiddle": b.find(".labelImage").css({ top: -h.imgcBorderHeight / 2, bottom: h.imgcBorderWidth / 2, left: 0, right: 0 }); break; default: b.find(".labelImage").css({bottom: h.imgcBorderWidth / 2, left: 0, right: 0}) } e.base.css({overflow: "visible"}); e.conTn.css({overflow: "visible"}); b.css({overflow: "visible"}); L("", b); L(b.find(".labelImage"), b.find(".imgContainer")); d = b.find(".subcontainer"); d.css({overflow: "visible"}); d[0].style[Ib] = "preserve-3d"; c = Math.round(1.2 * a.thumbFullWidth) + "px"; d[0].style[Va] = c; d = b.find(".imgContainer"); d[0].style[za] = "hidden"; B(a, "imgContainer0", d); y(a, "imgContainer0"); b.find(".image")[0].style[za] = "hidden"; d = b.find(".labelImage"); d[0].style[za] = "hidden"; B(a, "labelImage0", d).rotateY = 180; y(a, "labelImage0"); break; case "imageScale150": b.css({overflow: "hidden"}); B(a, "img0", b.find("img")); y(a, "img0"); break; case "imageScaleIn80": b.css({overflow: "hidden"}); B(a, "img0", b.find("img")).scale = 120; y(a, "img0"); break; case "imageSlide2Up": case "imageSlide2Down": case "imageSlide2Left": case "imageSlide2Right": case "imageSlide2UpRight": case "imageSlide2UpLeft": case "imageSlide2DownRight": case "imageSlide2DownLeft": b.css({overflow: "hidden"}); a.customData.hoverEffectRDir = C[j].name; nb(b, a); break; case "imageSlide2Random": b.css({overflow: "hidden"}), c = "imageSlide2Up imageSlide2Down imageSlide2Left imageSlide2Left imageSlide2UpRight imageSlide2UpLeft imageSlide2DownRight imageSlide2DownLeft".split(" "), a.customData.hoverEffectRDir = c[Math.floor(Math.random() * c.length)], nb(b, a) } a.hoverInitDone = !0 } } function nb(b, c) { var a = c.thumbFullWidth, d = c.thumbFullHeight, e = B(c, "img0", b.find("img")); e.scale = 140; switch (c.customData.hoverEffectRDir) { case "imageSlide2Up": e.translateY = c.thumbFullHeight < 1.4 * c.thumbImg().height ? (1.4 * c.thumbImg().height - c.thumbFullHeight) / 2 : 0; e.translateX = c.thumbFullWidth < 1.4 * c.thumbImg().width ? -(1.4 * c.thumbImg().width - c.thumbFullWidth) / 2 : 0; break; case "imageSlide2Down": d = c.thumbFullHeight < 1.4 * c.thumbImg().height ? Math.min((1.4 * c.thumbImg().height - c.thumbFullHeight) / 2 * .1, .1 * d) : 0; e.translateY = -d; a = c.thumbFullWidth < 1.4 * c.thumbImg().width ? Math.min((1.4 * c.thumbImg().width - c.thumbFullWidth) / 2 * .1, .1 * a) : 0; e.translateX = a; break; case "imageSlide2Left": e.translateY = .1 * -d; e.translateX = .1 * a; break; case "imageSlide2Right": e.translateY = .1 * -d; e.translateX = .1 * -a; break; case "imageSlide2UpRight": e.translateY = .05 * d; e.translateX = .05 * -a; break; case "imageSlide2UpLeft": e.translateY = .05 * d; e.translateX = .05 * a; break; case "imageSlide2DownRight": e.translateY = .05 * -d; e.translateX = .05 * -a; break; case "imageSlide2DownLeft": e.translateY = .05 * -d, e.translateX = .05 * a } y(c, "img0") } function mb(b) { var c = b.data("index"); if (void 0 != c) { var a = p[c]; if (a.hoverInitDone)for ("function" == typeof f.fnThumbnailHoverResize && f.fnThumbnailHoverResize(b, a, s()), j = 0; j < C.length; j++)switch (C[j].name) { case "imageSplit4": var c = a.thumbFullWidth - h.borderWidth - h.imgcBorderWidth, d = a.thumbFullHeight - h.borderHeight - h.imgcBorderHeight, e = b.find(".imgContainer"), g = "rect(0px, " + Math.ceil(c / 2) + "px, " + Math.ceil(d / 2) + "px, 0px)"; e.eq(0).css({clip: g}); g = "rect(0px, " + c + "px, " + Math.ceil(d / 2) + "px, " + Math.ceil(c / 2) + "px)"; e.eq(1).css({clip: g}); g = "rect(" + Math.ceil(d / 2) + "px, " + c + "px, " + d + "px, " + Math.ceil(c / 2) + "px)"; e.eq(2).css({clip: g}); g = "rect(" + Math.ceil(d / 2) + "px, " + Math.ceil(c / 2) + "px, " + d + "px, 0px)"; e.eq(3).css({clip: g}); break; case "imageSplitVert": e = b.find(".imgContainer"); c = a.thumbFullWidth - h.borderWidth - h.imgcBorderWidth; d = a.thumbFullHeight - h.borderHeight - h.imgcBorderHeight; g = "rect(0px, " + Math.ceil(c / 2) + "px, " + d + "px, 0px)"; e.eq(0).css({clip: g}); g = "rect(0px, " + c + "px, " + d + "px, " + Math.ceil(c / 2) + "px)"; e.eq(1).css({clip: g}); break; case "labelSplit4": c = a.thumbFullWidth - h.borderWidth - h.imgcBorderWidth; d = a.thumbFullHeight - h.borderHeight - h.imgcBorderHeight; e = b.find(".labelImage"); g = "rect(0px, " + Math.ceil(c / 2) + "px, " + Math.ceil(d / 2) + "px, 0px)"; e.eq(0).css({clip: g}); g = "rect(0px, " + c + "px, " + Math.ceil(d / 2) + "px, " + Math.ceil(c / 2) + "px)"; e.eq(1).css({clip: g}); g = "rect(" + Math.ceil(d / 2) + "px, " + c + "px, " + d + "px, " + Math.ceil(c / 2) + "px)"; e.eq(2).css({clip: g}); g = "rect(" + Math.ceil(d / 2) + "px, " + Math.ceil(c / 2) + "px, " + d + "px, 0px)"; e.eq(3).css({clip: g}); break; case "labelSplitVert": c = a.thumbFullWidth - h.borderWidth - h.imgcBorderWidth; d = a.thumbFullHeight - h.borderHeight - h.imgcBorderHeight; e = b.find(".labelImage"); g = "rect(0px, " + Math.ceil(c / 2) + "px, " + d + "px, 0px)"; e.eq(0).css({clip: g}); g = "rect(0px, " + c + "px, " + d + "px, " + Math.ceil(c / 2) + "px)"; e.eq(1).css({clip: g}); break; case "labelAppearSplit4": c = a.thumbFullWidth - h.borderWidth - h.imgcBorderWidth; d = a.thumbFullHeight - h.borderHeight - h.imgcBorderHeight; e = b.find(".labelImage"); g = "rect(0px, " + Math.ceil(c / 2) + "px, " + Math.ceil(d / 2) + "px, 0px)"; e.eq(0).css({clip: g}); g = "rect(0px, " + c + "px, " + Math.ceil(d / 2) + "px, " + Math.ceil(c / 2) + "px)"; e.eq(1).css({clip: g}); g = "rect(" + Math.ceil(d / 2) + "px, " + c + "px, " + d + "px, " + Math.ceil(c / 2) + "px)"; e.eq(2).css({clip: g}); g = "rect(" + Math.ceil(d / 2) + "px, " + Math.ceil(c / 2) + "px, " + d + "px, 0px)"; e.eq(3).css({clip: g}); a.eltTransform.labelImage0.translateX = -a.thumbFullWidth / 2; a.eltTransform.labelImage0.translateY = -a.thumbFullHeight / 2; y(a, "labelImage0"); a.eltTransform.labelImage1.translateX = a.thumbFullWidth / 2; a.eltTransform.labelImage1.translateY = -a.thumbFullHeight / 2; y(a, "labelImage1"); a.eltTransform.labelImage2.translateX = a.thumbFullWidth / 2; a.eltTransform.labelImage2.translateY = a.thumbFullHeight / 2; y(a, "labelImage2"); a.eltTransform.labelImage3.translateX = -a.thumbFullWidth / 2; a.eltTransform.labelImage3.translateY = a.thumbFullHeight / 2; y(a, "labelImage3"); break; case "labelAppearSplitVert": c = a.thumbFullWidth - h.borderWidth - h.imgcBorderWidth; d = a.thumbFullHeight - h.borderHeight - h.imgcBorderHeight; e = b.find(".labelImage"); g = "rect(0px, " + Math.ceil(c / 2) + "px, " + d + "px, 0px)"; e.eq(0).css({clip: g}); g = "rect(0px, " + c + "px, " + d + "px, " + Math.ceil(c / 2) + "px)"; e.eq(1).css({clip: g}); a.eltTransform.labelImage0.translateX = -a.thumbFullWidth / 2; y(a, "labelImage0"); a.eltTransform.labelImage1.translateX = a.thumbFullWidth / 2; y(a, "labelImage1"); break; case "slideUp": a.eltTransform.labelImage0.translateY = a.thumbFullHeight; y(a, "labelImage0"); break; case "slideDown": a.eltTransform.labelImage0.translateY = -a.thumbFullHeight; y(a, "labelImage0"); break; case "slideRight": a.eltTransform.labelImage0.translateX = -a.thumbFullWidth; y(a, "labelImage0"); break; case "slideLeft": a.eltTransform.labelImage0.translateX = a.thumbFullWidth; y(a, "labelImage0"); break; case "imageExplode": b.find(".subcontainer"); e = b.find(".imgContainer"); c = Math.sqrt(e.length); e.eq(0).outerWidth(!0); e.eq(0).outerHeight(!0); for (d = 0; d < c; d++)for (e = 0; e < c; e++); break; case "imageFlipHorizontal": d = b.find(".subcontainer"); c = Math.round(1.2 * a.thumbFullHeight) + "px"; d[0].style[Va] = c; break; case "imageFlipVertical": d = b.find(".subcontainer"); c = Math.round(1.2 * a.thumbFullWidth) + "px"; d[0].style[Va] = c; break; case "imageSlide2Up": case "imageSlide2Down": case "imageSlide2Left": case "imageSlide2Right": case "imageSlide2UpRight": case "imageSlide2UpLeft": case "imageSlide2DownRight": case "imageSlide2DownLeft": case "imageSlide2Random": nb(b, a); break; case "slideUp": a.eltTransform.labelImage0.translateY = a.thumbFullHeight; y(a, "labelImage0"); break; case "slideDown": a.eltTransform.labelImage0.translateY = -a.thumbFullHeight; y(a, "labelImage0"); break; case "slideRight": a.eltTransform.labelImage0.translateX = -a.thumbFullWidth; y(a, "labelImage0"); break; case "slideLeft": a.eltTransform.labelImage0.translateX = a.thumbFullWidth; y(a, "labelImage0"); break; case "labelSlideUpTop": case "labelSlideUp": a.eltTransform.labelImage0.translateY = a.thumbFullHeight; y(a, "labelImage0"); break; case "labelSlideDown": b.css({overflow: "hidden"}), a.eltTransform.labelImage0.translateY = -a.thumbFullHeight, y(a, "labelImage0") } else Hb(b) } } function B(b, c, a) { void 0 == b.eltTransform[c] && (b.eltTransform[c] = { translateX: 0, translateY: 0, rotateX: 0, rotateY: 0, rotateZ: 0, scale: 100 }, b.eltTransform[c].$elt = a); return b.eltTransform[c] } function y(b, c) { var a = b.eltTransform[c], d = "translateX(" + a.translateX + "px) translateY(" + a.translateY + "px) scale(" + a.scale / 100 + ")", d = 9 >= Jb || lc ? d + (" rotate(" + a.rotateZ + "deg)") : d + (" rotateX(" + a.rotateX + "deg) rotateY(" + a.rotateY + "deg) rotateZ(" + a.rotateZ + "deg)"); void 0 != a.$elt[0] && (a.$elt[0].style[K] = d) } function t(b, c, a, d, e) { var f = "translateX translateY scale rotateX rotateY rotateZ".split(" "); if ("animate" == F)for (var h = 0; h < f.length; h++) { var g = f[h]; if (void 0 !== a[g]) { var k = { v: parseInt(d.eltTransform[e][g]), item: d, tf: g, eltClass: e, to: parseInt(a[g]) }, p = {v: parseInt(a[g])}; 0 < C[c].delay ? jQuery(k).delay(C[c].delay).animate(p, { duration: C[c].duration, easing: C[c].easing, queue: !1, step: function (a) { this.item.hovered && (d.eltTransform[this.eltClass][this.tf] = a, y(this.item, this.eltClass)) }, complete: function () { this.item.hovered && (d.eltTransform[this.eltClass][this.tf] = this.to, y(this.item, this.eltClass)) } }) : jQuery(k).animate(p, { duration: C[c].duration, easing: C[c].easing, queue: !1, step: function (a) { this.item.hovered && (d.eltTransform[this.eltClass][this.tf] = a, y(this.item, this.eltClass)) }, complete: function () { this.item.hovered && (d.eltTransform[this.eltClass][this.tf] = this.to, y(this.item, this.eltClass)) } }); delete a[g] } } if (0 != a.length)if (0 < C[c].delay)if ("transition" == F)b.delay(C[c].delay)[F](a, C[c].duration, C[c].easing); else b.delay(C[c].delay)[F](a, { duration: C[c].duration, easing: C[c].easing, queue: !1 }); else if ("transition" == F)b[F](a, C[c].duration, C[c].easing); else b[F](a, { duration: C[c].duration, easing: C[c].easing, queue: !1 }) } function cb(b) { var c = b.data("index"); if (void 0 != c) { "velocity" == F ? b.find("*").velocity("stop", !0) : b.find("*").stop(!0, !1); var a = p[c]; a.hovered = !0; var d = "animate" == F ? 1 : 100; "function" == typeof f.fnThumbnailHover && f.fnThumbnailHover(b, a, s()); try { for (j = 0; j < C.length; j++)switch (C[j].name) { case "imageSplit4": var e = b.find(".imgContainer"); t(e.eq(0), j, { translateX: -a.thumbFullWidth / 2, translateY: -a.thumbFullHeight / 2 }, a, "imgContainer0"); t(e.eq(1), j, { translateX: a.thumbFullWidth / 2, translateY: -a.thumbFullHeight / 2 }, a, "imgContainer1"); t(e.eq(2), j, { translateX: a.thumbFullWidth / 2, translateY: a.thumbFullHeight / 2 }, a, "imgContainer2"); t(e.eq(3), j, { translateX: -a.thumbFullWidth / 2, translateY: a.thumbFullHeight / 2 }, a, "imgContainer3"); break; case "imageSplitVert": e = b.find(".imgContainer"); t(e.eq(0), j, {translateX: -a.thumbFullWidth / 2}, a, "imgContainer0"); t(e.eq(1), j, {translateX: a.thumbFullWidth / 2}, a, "imgContainer1"); break; case "labelSplit4": e = b.find(".labelImage"); t(e.eq(0), j, { translateX: -a.thumbFullWidth / 2, translateY: -a.thumbFullHeight / 2 }, a, "labelImage0"); t(e.eq(1), j, { translateX: a.thumbFullWidth / 2, translateY: -a.thumbFullHeight / 2 }, a, "labelImage1"); t(e.eq(2), j, { translateX: a.thumbFullWidth / 2, translateY: a.thumbFullHeight / 2 }, a, "labelImage2"); t(e.eq(3), j, { translateX: -a.thumbFullWidth / 2, translateY: a.thumbFullHeight / 2 }, a, "labelImage3"); break; case "labelSplitVert": e = b.find(".labelImage"); t(e.eq(0), j, {translateX: -a.thumbFullWidth / 2}, a, "labelImage0"); t(e.eq(1), j, {translateX: a.thumbFullWidth / 2}, a, "labelImage1"); break; case "labelAppearSplit4": e = b.find(".labelImage"); t(e.eq(0), j, {translateX: 0, translateY: 0}, a, "labelImage0"); t(e.eq(1), j, {translateX: 0, translateY: 0}, a, "labelImage1"); t(e.eq(2), j, {translateX: 0, translateY: 0}, a, "labelImage2"); t(e.eq(3), j, {translateX: 0, translateY: 0}, a, "labelImage3"); break; case "labelAppearSplitVert": e = b.find(".labelImage"); t(e.eq(0), j, {translateX: 0}, a, "labelImage0"); t(e.eq(1), j, {translateX: 0}, a, "labelImage1"); break; case "scaleLabelOverImage": t(b.find(".labelImage"), j, {scale: 100 / d, opacity: 1}, a, "labelImage0"); t(b.find(".imgContainer"), j, {scale: 50 / d}, a, "imgContainer0"); break; case "overScale": case "overScaleOutside": t(b.find(".labelImage"), j, {opacity: 1, scale: 100 / d}, a, "labelImage0"); t(b.find(".imgContainer"), j, {opacity: 0, scale: 50 / d}, a, "imgContainer0"); break; case "imageInvisible": t(b.find(".imgContainer"), j, {opacity: 0}, a); break; case "rotateCornerBL": var h = "transition" == F ? {rotate: "0deg"} : {rotateZ: "0"}; t(b.find(".labelImage"), j, h, a, "labelImage0"); h = "transition" == F ? {rotate: "90deg"} : {rotateZ: "90"}; t(b.find(".imgContainer"), j, h, a, "imgContainer0"); break; case "rotateCornerBR": h = "transition" == F ? {rotate: "0deg"} : {rotateZ: "0"}; t(b.find(".labelImage"), j, h, a, "labelImage0"); h = "transition" == F ? {rotate: "-90deg"} : {rotateZ: "-90"}; t(b.find(".imgContainer"), j, h, a, "imgContainer0"); break; case "imageRotateCornerBL": h = "transition" == F ? {rotate: "90deg"} : {rotateZ: "90"}; t(b.find(".imgContainer"), j, h, a, "imgContainer0"); break; case "imageRotateCornerBR": h = "transition" == F ? {rotate: "-90deg"} : {rotateZ: "-90"}; t(b.find(".imgContainer"), j, h, a, "imgContainer0"); break; case "slideUp": t(b.find(".imgContainer"), j, {translateY: -a.thumbFullHeight}, a, "imgContainer0"); t(b.find(".labelImage"), j, {translateY: 0}, a, "labelImage0"); break; case "slideDown": t(b.find(".imgContainer"), j, {translateY: a.thumbFullHeight}, a, "imgContainer0"); t(b.find(".labelImage"), j, {translateY: 0}, a, "labelImage0"); break; case "slideRight": t(b.find(".imgContainer"), j, {translateX: a.thumbFullWidth}, a, "imgContainer0"); t(b.find(".labelImage"), j, {translateX: 0}, a, "labelImage0"); break; case "slideLeft": t(b.find(".imgContainer"), j, {translateX: -a.thumbFullWidth}, a, "imgContainer0"); t(b.find(".labelImage"), j, {translateX: 0}, a, "labelImage0"); break; case "imageSlideUp": t(b.find(".imgContainer"), j, {translateY: -a.thumbFullHeight}, a, "imgContainer0"); break; case "imageSlideDown": t(b.find(".imgContainer"), j, {translateY: a.thumbFullHeight}, a, "imgContainer0"); break; case "imageSlideLeft": t(b.find(".imgContainer"), j, {translateX: -a.thumbFullWidth}, a, "imgContainer0"); break; case "imageSlideRight": t(b.find(".imgContainer"), j, {translateX: a.thumbFullWidth}, a, "imgContainer0"); break; case "labelAppear": if ("velocity" == F)t(b.find(".labelImage"), j, { backgroundColorRed: G.oldLabelRed, backgroundColorGreen: G.oldLabelGreen, backgroundColorBlue: G.oldLabelBlue, backgroundColorAlpha: 1 }, a); else { var g = "rgba(" + G.oldLabelRed + "," + G.oldLabelGreen + "," + G.oldLabelBlue + ",1)"; t(b.find(".labelImage"), j, {backgroundColor: g}, a) } t(b.find(".labelImageTitle"), j, {opacity: 1}, a); t(b.find(".labelFolderTitle"), j, {opacity: 1}, a); t(b.find(".labelDescription"), j, {opacity: 1}, a); break; case "labelAppear75": "velocity" == F ? t(b.find(".labelImage"), j, { backgroundColorRed: G.oldLabelRed, backgroundColorGreen: G.oldLabelGreen, backgroundColorBlue: G.oldLabelBlue, backgroundColorAlpha: .75 }, a) : (g = "rgba(" + G.oldLabelRed + "," + G.oldLabelGreen + "," + G.oldLabelBlue + ",0.75)", t(b.find(".labelImage"), j, {backgroundColor: g}, a)); t(b.find(".labelImageTitle"), j, {opacity: 1}, a); t(b.find(".labelFolderTitle"), j, {opacity: 1}, a); t(b.find(".labelDescription"), j, {opacity: 1}, a); break; case "descriptionAppear": t(b.find(".labelDescription"), j, {opacity: 1}, a); break; case "labelSlideDown": t(b.find(".labelImage"), j, {translateY: 0}, a, "labelImage0"); break; case "labelSlideUpTop": case "labelSlideUp": t(b.find(".labelImage"), j, {translateY: 0}, a, "labelImage0"); break; case "descriptionSlideUp": var k = "album" == a.kind ? b.find(".labelFolderTitle").outerHeight(!0) : b.find(".labelImageTitle").outerHeight(!0), r = b.find(".labelDescription").outerHeight(!0), l = a.thumbFullHeight - k - r; 0 > l && (l = 0); t(b.find(".labelImage"), j, {translateY: 0, height: k + r}, a, "labelImage0"); t(b.find(".labelDescription"), j, {opacity: 1}, a); break; case "labelOpacity50": t(b.find(".labelImage"), j, {opacity: .5}, a); break; case "imageOpacity50": t(b.find(".imgContainer"), j, {opacity: .5}, a); break; case "borderLighter": if ("velocity" == F) { var x = Wa(G.oldBorderColor, .5, !1), v = x.substring(x.indexOf("(") + 1, x.lastIndexOf(")")).split(/,\s*/); t(b, j, { borderColorRed: v[0], borderColorGreen: v[1], borderColorBlue: v[2], colorAlpha: v[3] }, a) } else t(b, j, {borderColor: Wa(G.oldBorderColor, .5, !1)}, a); break; case "borderDarker": "velocity" == F ? (x = Wa(G.oldBorderColor, .5, !0), v = x.substring(x.indexOf("(") + 1, x.lastIndexOf(")")).split(/,\s*/), t(b, j, { borderColorRed: v[0], borderColorGreen: v[1], borderColorBlue: v[2], colorAlpha: v[3] }, a)) : t(b, j, {borderColor: Wa(G.oldBorderColor, .5, !0)}, a); break; case "imageScale150": t(b.find("img"), j, {scale: 150 / d}, a, "img0"); break; case "imageScaleIn80": t(b.find("img"), j, {scale: 100 / d}, a, "img0"); break; case "imageSlide2Up": case "imageSlide2Down": case "imageSlide2Left": case "imageSlide2Right": case "imageSlide2UpRight": case "imageSlide2UpLeft": case "imageSlide2DownRight": case "imageSlide2DownLeft": case "imageSlide2Random": switch (a.customData.hoverEffectRDir) { case "imageSlide2Up": var q = a.thumbFullHeight < 1.4 * a.imgHeight ? (1.4 * a.imgHeight - a.thumbFullHeight) / 2 : 0; t(b.find("img"), j, {translateY: -q}, a, "img0"); break; case "imageSlide2Down": q = a.thumbFullHeight < 1.4 * a.imgHeight ? (1.4 * a.imgHeight - a.thumbFullHeight) / 2 : 0; t(b.find("img"), j, {translateY: q}, a, "img0"); break; case "imageSlide2Left": t(b.find("img"), j, {translateX: .1 * -a.thumbFullWidth}, a, "img0"); break; case "imageSlide2Right": t(b.find("img"), j, {translateX: .1 * a.thumbFullWidth}, a, "img0"); break; case "imageSlide2UpRight": t(b.find("img"), j, { translateY: .05 * -a.thumbFullHeight, translateX: .05 * a.thumbFullWidth }, a, "img0"); break; case "imageSlide2UpLeft": t(b.find("img"), j, { translateY: .05 * -a.thumbFullHeight, translateX: .05 * -a.thumbFullWidth }, a, "img0"); break; case "imageSlide2DownRight": t(b.find("img"), j, { translateY: .05 * a.thumbFullHeight, translateX: .05 * a.thumbFullWidth }, a, "img0"); break; case "imageSlide2DownLeft": t(b.find("img"), j, { translateY: .05 * a.thumbFullHeight, translateX: .05 * -a.thumbFullWidth }, a, "img0") } break; case "imageScale150Outside": L("", b); t(b.find("img"), j, {scale: 150 / d}, a, "img0"); break; case "scale120": L("", b); t(b, j, {scale: 120 / d}, a, "base"); break; case "imageExplode": L("", b); for (var P = b.find(".imgContainer"), c = Math.sqrt(P.length), y = [], z = 0; z <= Math.PI; z += Math.PI / (c - 1))y.push(Math.sin(z)); for (var w = P.outerWidth(!0) / c, N = P.outerHeight(!0) / c, h = z = 0; h < c; h++)for (g = 0; g < c; g++)t(P.eq(z++), j, { top: (-N * c / 3 + N * h - N) * y[g], left: (-w * c / 3 + w * g - w) * y[h], scale: 1.5, opacity: 0 }, a); break; case "imageFlipHorizontal": L("", b); t(b.find(".imgContainer"), j, {rotateX: 180}, a, "imgContainer0"); t(b.find(".labelImage"), j, {rotateX: 360}, a, "labelImage0"); break; case "imageFlipVertical": L("", b), t(b.find(".imgContainer"), j, {rotateY: 180}, a, "imgContainer0"), t(b.find(".labelImage"), j, {rotateY: 360}, a, "labelImage0") } } catch (pa) { R("error on hover " + pa.message) } } } function z(b, c, a, d, e) { var f = "translateX translateY scale rotateX rotateY rotateZ".split(" "); if ("animate" == F)for (var h = 0; h < f.length; h++) { var g = f[h]; if (void 0 !== a[g]) { var k = { v: parseInt(d.eltTransform[e][g]), item: d, tf: g, eltClass: e, to: parseInt(a[g]) }, p = {v: parseInt(a[g])}; 0 < C[c].delayBack ? jQuery(k).delay(C[c].delayBack).animate(p, { duration: C[c].durationBack, easing: C[c].easingBack, queue: !1, step: function (a) { d.eltTransform[this.eltClass][this.tf] = a; y(this.item, this.eltClass) }, complete: function () { d.eltTransform[this.eltClass][this.tf] = this.to; y(this.item, this.eltClass) } }) : jQuery(k).animate(p, { duration: C[c].durationBack, easing: C[c].easingBack, queue: !1, step: function (a) { d.eltTransform[this.eltClass][this.tf] = a; y(this.item, this.eltClass) }, complete: function () { d.eltTransform[this.eltClass][this.tf] = this.to; y(this.item, this.eltClass) } }); delete a[g] } } if (0 != a.length)if (0 < C[c].delay)if ("transition" == F)b.delay(C[c].delayBack)[F](a, C[c].durationBack, C[c].easingBack); else b.delay(C[c].delayBack)[F](a, { duration: C[c].durationBack, easing: C[c].easingBack, queue: !1 }); else if ("transition" == F)b[F](a, C[c].durationBack, C[c].easingBack); else b[F](a, { duration: C[c].durationBack, easing: C[c].easingBack, queue: !1 }) } function Ha(b) { if (!S) { var c = b.data("index"); if (void 0 != c) { "velocity" == F ? b.find("*").velocity("stop", !0) : b.find("*").filter(":animated").stop(!0, !1); var a = p[c]; a.hovered = !1; var d = "animate" == F ? 1 : 100; "function" == typeof f.fnThumbnailHoverOut && f.fnThumbnailHoverOut(b, a, s()); try { for (j = 0; j < C.length; j++)switch (C[j].name) { case "imageSplit4": var e = b.find(".imgContainer"); z(e.eq(0), j, {translateX: 0, translateY: 0}, a, "imgContainer0"); z(e.eq(1), j, {translateX: 0, translateY: 0}, a, "imgContainer1"); z(e.eq(2), j, {translateX: 0, translateY: 0}, a, "imgContainer2"); z(e.eq(3), j, {translateX: 0, translateY: 0}, a, "imgContainer3"); break; case "imageSplitVert": e = b.find(".imgContainer"); z(e.eq(0), j, {translateX: 0}, a, "imgContainer0"); z(e.eq(1), j, {translateX: 0}, a, "imgContainer1"); break; case "labelSplit4": e = b.find(".labelImage"); z(e.eq(0), j, {translateX: 0, translateY: 0}, a, "labelImage0"); z(e.eq(1), j, {translateX: 0, translateY: 0}, a, "labelImage1"); z(e.eq(2), j, {translateX: 0, translateY: 0}, a, "labelImage2"); z(e.eq(3), j, {translateX: 0, translateY: 0}, a, "labelImage3"); break; case "labelSplitVert": e = b.find(".labelImage"); z(e.eq(0), j, {translateX: 0}, a, "labelImage0"); z(e.eq(1), j, {translateX: 0}, a, "labelImage1"); break; case "labelAppearSplit4": e = b.find(".labelImage"); z(e.eq(0), j, { translateX: -a.thumbFullWidth / 2, translateY: -a.thumbFullHeight / 2 }, a, "labelImage0"); z(e.eq(1), j, { translateX: a.thumbFullWidth / 2, translateY: -a.thumbFullHeight / 2 }, a, "labelImage1"); z(e.eq(2), j, { translateX: a.thumbFullWidth / 2, translateY: a.thumbFullHeight / 2 }, a, "labelImage2"); z(e.eq(3), j, { translateX: -a.thumbFullWidth / 2, translateY: a.thumbFullHeight / 2 }, a, "labelImage3"); break; case "labelAppearSplitVert": e = b.find(".labelImage"); z(e.eq(0), j, {translateX: -a.thumbFullWidth / 2}, a, "labelImage0"); z(e.eq(1), j, {translateX: a.thumbFullWidth / 2}, a, "labelImage1"); break; case "scaleLabelOverImage": z(b.find(".labelImage"), j, {opacity: 0, scale: 50 / d}, a, "labelImage0"); z(b.find(".imgContainer"), j, {scale: 100 / d}, a, "imgContainer0"); break; case "overScale": case "overScaleOutside": z(b.find(".labelImage"), j, {opacity: 0, scale: 150 / d}, a, "labelImage0"); z(b.find(".imgContainer"), j, {opacity: 1, scale: 100 / d}, a, "imgContainer0"); break; case "imageInvisible": z(b.find(".imgContainer"), j, {opacity: 1}); break; case "rotateCornerBL": var h = "transition" == F ? {rotate: "-90deg"} : {rotateZ: "-90"}; z(b.find(".labelImage"), j, h, a, "labelImage0"); h = "transition" == F ? {rotate: "0deg"} : {rotateZ: "0"}; z(b.find(".imgContainer"), j, h, a, "imgContainer0"); break; case "rotateCornerBR": h = "transition" == F ? {rotate: "90deg"} : {rotateZ: "90"}; z(b.find(".labelImage"), j, h, a, "labelImage0"); h = "transition" == F ? {rotate: "0deg"} : {rotateZ: "0"}; z(b.find(".imgContainer"), j, h, a, "imgContainer0"); break; case "imageRotateCornerBL": case "imageRotateCornerBR": h = "transition" == F ? {rotate: "0deg"} : {rotateZ: "0"}; z(b.find(".imgContainer"), j, h, a, "imgContainer0"); break; case "slideUp": z(b.find(".imgContainer"), j, {translateY: 0}, a, "imgContainer0"); z(b.find(".labelImage"), j, {translateY: a.thumbFullHeight}, a, "labelImage0"); break; case "slideDown": z(b.find(".imgContainer"), j, {translateY: 0}, a, "imgContainer0"); z(b.find(".labelImage"), j, {translateY: -a.thumbFullHeight}, a, "labelImage0"); break; case "slideRight": z(b.find(".imgContainer"), j, {translateX: 0}, a, "imgContainer0"); z(b.find(".labelImage"), j, {translateX: -a.thumbFullWidth}, a, "labelImage0"); break; case "slideLeft": z(b.find(".imgContainer"), j, {translateX: 0}, a, "imgContainer0"); z(b.find(".labelImage"), j, {translateX: a.thumbFullWidth}, a, "labelImage0"); break; case "imageSlideUp": case "imageSlideDown": z(b.find(".imgContainer"), j, {translateY: 0}, a, "imgContainer0"); break; case "imageSlideLeft": case "imageSlideRight": z(b.find(".imgContainer"), j, {translateX: 0}, a, "imgContainer0"); break; case "labelAppear": case "labelAppear75": if ("velocity" == F)z(b.find(".labelImage"), j, { backgroundColorRed: G.oldLabelRed, backgroundColorGreen: G.oldLabelGreen, backgroundColorBlue: G.oldLabelBlue, backgroundColorAlpha: 0 }); else { var g = "rgb(" + G.oldLabelRed + "," + G.oldLabelGreen + "," + G.oldLabelBlue + ",0)"; z(b.find(".labelImage"), j, {backgroundColor: g}) } z(b.find(".labelImageTitle"), j, {opacity: 0}); z(b.find(".labelFolderTitle"), j, {opacity: 0}); z(b.find(".labelDescription"), j, {opacity: 0}); break; case "descriptionAppear": z(b.find(".labelDescription"), j, {opacity: 0}); break; case "labelSlideDown": z(b.find(".labelImage"), j, {translateY: -a.thumbFullHeight}, a, "labelImage0"); break; case "labelSlideUpTop": case "labelSlideUp": z(b.find(".labelImage"), j, {translateY: a.thumbFullHeight}, a, "labelImage0"); break; case "descriptionSlideUp": var k = "album" == a.kind ? b.find(".labelFolderTitle").outerHeight(!0) : b.find(".labelImageTitle").outerHeight(!0); z(b.find(".labelImage"), j, {translateY: 0, height: k}, a, "labelImage0"); break; case "labelOpacity50": z(b.find(".labelImage"), j, {opacity: G.oldLabelOpacity}); break; case "imageOpacity50": z(b.find(".imgContainer"), j, {opacity: 1}); break; case "borderLighter": case "borderDarker": if ("velocity" == F) { var r = G.oldBorderColor, x = r.substring(r.indexOf("(") + 1, r.lastIndexOf(")")).split(/,\s*/); z(b, j, { borderColorRed: x[0], borderColorGreen: x[1], borderColorBlue: x[2], colorAlpha: x[3] }) } else z(b, j, {borderColor: G.oldBorderColor}); break; case "imageScale150": case "imageScale150Outside": z(b.find("img"), j, {scale: 100 / d}, a, "img0"); break; case "imageScaleIn80": z(b.find("img"), j, {scale: 120 / d}, a, "img0"); break; case "imageSlide2Up": case "imageSlide2Down": case "imageSlide2Left": case "imageSlide2Right": case "imageSlide2UpRight": case "imageSlide2UpLeft": case "imageSlide2DownRight": case "imageSlide2DownLeft": case "imageSlide2Random": switch (a.customData.hoverEffectRDir) { case "imageSlide2Up": var l = a.thumbFullHeight < 1.4 * a.imgHeight ? (1.4 * a.imgHeight - a.thumbFullHeight) / 2 : 0; z(b.find("img"), j, {translateY: l}, a, "img0"); break; case "imageSlide2Down": l = a.thumbFullHeight < 1.4 * a.imgHeight ? (1.4 * a.imgHeight - a.thumbFullHeight) / 2 : 0; z(b.find("img"), j, {translateY: -l}, a, "img0"); break; case "imageSlide2Left": z(b.find("img"), j, {translateX: .1 * a.thumbFullWidth}, a, "img0"); break; case "imageSlide2Right": z(b.find("img"), j, {translateX: .1 * -a.thumbFullWidth}, a, "img0"); break; case "imageSlide2UpRight": z(b.find("img"), j, { translateY: .05 * a.thumbFullHeight, translateX: .05 * -a.thumbFullWidth }, a, "img0"); break; case "imageSlide2UpLeft": z(b.find("img"), j, { translateY: .05 * a.thumbFullHeight, translateX: .05 * a.thumbFullWidth }, a, "img0"); break; case "imageSlide2DownRight": z(b.find("img"), j, { translateY: .05 * -a.thumbFullHeight, translateX: .05 * -a.thumbFullWidth }, a, "img0"); break; case "imageSlide2DownLeft": z(b.find("img"), j, { translateY: .05 * -a.thumbFullHeight, translateX: .05 * a.thumbFullWidth }, a, "img0") } break; case "scale120": z(b, j, {scale: 100 / d}, a, "base"); break; case "imageExplode": for (var t = b.find(".imgContainer"), c = Math.sqrt(t.length), v = 0, h = 0; h < c; h++)for (g = 0; g < c; g++)z(t.eq(v++), j, { top: 0, left: 0, scale: 1, opacity: 1 }); break; case "imageFlipHorizontal": z(b.find(".imgContainer"), j, {rotateX: 0}, a, "imgContainer0"); z(b.find(".labelImage"), j, {rotateX: 180}, a, "labelImage0"); break; case "imageFlipVertical": z(b.find(".imgContainer"), j, {rotateY: 0}, a, "imgContainer0"), z(b.find(".labelImage"), j, {rotateY: 180}, a, "labelImage0") } } catch (q) { R("error on hoverOut " + q.message) } } } } function ta(b) { if ("fancybox" == f.viewer) { var c = [], a = 0; c[a] = {}; c[a].href = p[b].responsiveURL(); c[a].title = p[b].title; for (var d = p.length, e = b + 1; e < d; e++)"image" == p[e].kind && p[e].albumID == p[b].albumID && "" == p[e].destinationURL && (a++, c[a] = {}, c[a].href = p[e].responsiveURL(), c[a].title = p[e].title); for (e = 0; e < b; e++)"image" == p[e].kind && p[e].albumID == p[b].albumID && "" == p[e].destinationURL && (a++, c[a] = {}, c[a].href = p[e].responsiveURL(), c[a].title = p[e].title); null != f.fancyBoxOptions ? jQuery.fancybox(c, f.fancyBoxOptions) : jQuery.fancybox(c, { autoPlay: !1, nextEffect: "fade", prevEffect: "fade", scrolling: "no", helpers: {buttons: {position: "bottom"}} }) } else S ? Xa(b, "") : mc(b) } function mc(b) { jQuery("body").css({overflow: "hidden"}); S = !0; e.conVwCon = jQuery('<div class="nanoGalleryViewerContainer" style="visibility:visible"></div>').appendTo("body"); e.conVwCon.addClass("nanogallery_theme_" + f.theme); nc(e.conVwCon); e.conVw = jQuery('<div id="nanoGalleryViewer" class="nanoGalleryViewer" style="visibility:visible" itemscope itemtype="http://schema.org/ImageObject"></div>').appendTo(e.conVwCon); e.conVw.css({visibility: "visible", position: "fixed"}); var c; c = "" + ('<img class="image" src="' + p[b].responsiveURL() + '" alt=" " style="visibility:visible;opacity:0;position:absolute;top:0;bottom:0;left:0;right:0;margin:auto;zoom:1;" itemprop="contentURL">'); c += '<img class="image" src="' + p[b].responsiveURL() + '" alt=" " style="visibility:visible;opacity:0;position:absolute;top:0;bottom:0;left:0;right:0;margin:auto;zoom:1;" itemprop="contentURL">'; c += '<img class="image" src="' + p[b].responsiveURL() + '" alt=" " style="visibility:visible;opacity:0;position:absolute;top:0;bottom:0;left:0;right:0;margin:auto;zoom:1;" itemprop="contentURL">'; e.vwContent = jQuery('<div class="content">' + c + '<div class="contentAreaPrevious"></div><div class="contentAreaNext"></div></div>').appendTo(e.conVw); e.vwImgP = e.conVw.find(".image").eq(0); e.vwImgC = e.conVw.find(".image").eq(1); e.vwImgN = e.conVw.find(".image").eq(2); e.conVwCon.find("*").attr("draggable", "false").attr("unselectable", "on"); c = jQuery('<div class="closeButtonFloating"></div>').appendTo(e.conVw); c.on("touchstart click", function (a) { a.preventDefault(); a.stopPropagation(); if (!(400 > (new Date).getTime() - ga))return Da(!0), !1 }); for (var a = '<div class="toolbarContainer" style="visibility:' + (f.viewerToolbar.display ? "visible" : "hidden") + ';"><div class="toolbar">', d = f.viewerToolbar.standard.split(","), h = 0, g = d.length; h < g; h++)a += Kb(d[h]); d = f.viewerToolbar.minimized.split(","); h = 0; for (g = d.length; h < g; h++)-1 == f.viewerToolbar.standard.indexOf(d[h]) && (a += Kb(d[h])); e.conVwTb = jQuery(a + "</div></div>").appendTo(e.conVw); "min" == La || 0 < f.viewerToolbar.autoMinimize && f.viewerToolbar.autoMinimize >= M().w ? Lb() : Mb(); f.viewerDisplayLogo && (e.vwLogo = jQuery('<div class="nanoLogo"></div>').appendTo(e.conVw)); L("", e.conVw); L(e.conVw, c); qa(); ga = (new Date).getTime(); e.conVwTb.find(".closeButton").on("touchstart click", function (a) { a.preventDefault(); a.stopPropagation(); 400 > (new Date).getTime() - ga || Da(!0) }); e.conVwTb.find(".playPauseButton").on("touchstart click", function (a) { a.stopPropagation(); bb() }); e.conVwTb.find(".minimizeButton").on("touchstart click", function (a) { a.stopPropagation(); "std" == La ? Lb() : Mb() }); e.conVwTb.find(".fullscreenButton").on("touchstart click", function (a) { a.stopPropagation(); Nb() }); e.conVwTb.find(".infoButton").on("touchstart click", function (a) { a.stopPropagation(); "function" == typeof f.fnViewerInfo && f.fnViewerInfo(p[la], s()) }); e.conVwTb.find(".ngCustomBtn").on("touchstart click", function (a) { a.stopPropagation(); if ("function" == typeof f.fnImgToolbarCustClick) { for (a = a.target || a.srcElement; null == a || null == a.getAttribute("class") || -1 == a.getAttribute("class").indexOf("ngCustomBtn");)a = a.parentNode; var b = a.getAttribute("class"); if (0 <= b.indexOf("ngCustomBtn"))for (var b = b.split(" "), c = 0, d = b.length; c < d; c++)0 == b[c].indexOf("custom") && f.fnImgToolbarCustClick(b[c], jQuery(a), p[la], s()) } }); e.conVwTb.find(".linkOriginalButton").on("touchstart click", function (a) { a.stopPropagation(); "picasa" == f.kind && (a = "https://plus.google.com/photos/" + f.userID + "/albums/" + p[la].albumID + "/" + p[la].GetID(), window.open(a, "_blank")); "flickr" == f.kind && (a = "https://www.flickr.com/photos/" + f.userID + "/" + p[la].GetID(), window.open(a, "_blank")) }); e.conVwTb.find(".nextButton").on("touchstart click", function (a) { a.stopPropagation(); Ea() }); e.conVwTb.find(".previousButton").on("touchstart click", function (a) { a.stopPropagation(); Fa() }); e.vwContent.find(".contentAreaNext").on("touchstart click", function (a) { a.stopPropagation(); Ea() }); e.vwContent.find(".contentAreaPrevious").on("touchstart click", function (a) { a.stopPropagation(); Fa() }); e.vwContent.on("click", function (a) { if (!(400 > (new Date).getTime() - ga))return a.preventDefault(), a.stopPropagation(), Da(!0), !1 }); e.conVw.find(".image").attr("draggable", "false").attr("unselectable", "on").css({ "-moz-user-select": "none", "-khtml-user-select": "none", "-webkit-user-select": "none", "-o-user-select": "none", "user-select": "none" }); Xa(b, ""); null == Ya && (Ya = new oc(e.conVwCon[0])); f.slideshowAutoStart && (na = !0, e.conVwTb.find(".playPauseButton").removeClass("playButton").addClass("pauseButton"), Aa(), Ba = window.setInterval(function () { Aa() }, Oa)) } function Kb(b) { var c = ""; b = b.replace(/^\s+|\s+$/g, ""); switch (b) { case "minimizeButton": c = '<div class="ngbt minimizeButton hideToolbarButton"></div>'; break; case "previousButton": c = '<div class="ngbt previousButton"></div>'; break; case "pageCounter": c = '<div class="pageCounter"></div>'; break; case "nextButton": c = '<div class="ngbt nextButton"></div>'; break; case "playPauseButton": c = '<div class="ngbt playButton playPauseButton"></div>'; break; case "fullscreenButton": Ob && (c = '<div class="ngbt setFullscreenButton fullscreenButton"></div>'); break; case "infoButton": "function" == typeof f.fnViewerInfo && (c = '<div class="ngbt infoButton"></div>'); break; case "linkOriginalButton": if ("flickr" == f.kind || "picasa" == f.kind)c = '<div class="ngbt linkOriginalButton"></div>'; break; case "closeButton": c = '<div class="ngbt closeButton"></div>'; break; case "label": c = '<div class="label"><div class="title" itemprop="name"></div><div class="description" itemprop="description"></div></div>'; break; default: 0 == b.indexOf("custom") && (c = '<div class="ngbt ngCustomBtn ' + b + '">' + ("function" == typeof f.fnImgToolbarCustInit ? f.fnImgToolbarCustInit(b) : "") + "</div>") } return c } function oc(b) { function c(b) { S && (b.preventDefault(), b.touches && 1 < b.touches.length || (k = f(b), window.navigator.msPointerEnabled ? (document.addEventListener("MSPointerMove", a, !0), document.addEventListener("MSPointerUp", d, !0)) : (document.addEventListener("touchmove", a, !0), document.addEventListener("touchend", d, !0), document.addEventListener("touchcancel", d, !0), document.addEventListener("mousemove", a, !0), document.addEventListener("mouseup", d, !0)))) } function a(a) { a.preventDefault(); p = f(a); g || (g = !0, window.requestAnimationFrame(h)) } function d(b) { b.cancelable && b.preventDefault(); b.touches && 0 < b.touches.length || (g = !1, window.navigator.msPointerEnabled ? (document.removeEventListener("MSPointerMove", a, !0), document.removeEventListener("MSPointerUp", d, !0)) : (document.removeEventListener("touchmove", a, !0), document.removeEventListener("touchend", d, !0), document.removeEventListener("touchcancel", d, !0), document.removeEventListener("mousemove", a, !0), document.removeEventListener("mouseup", d, !0)), e()) } function e() { if (null == p)r = 0, k = null; else { var a = k.x - p.x; r -= a; -50 > a && Fa(); 50 < a && Ea(); r = 0; p = k = null; 50 > Math.abs(a) && ob(r) } } function f(a) { var b = {}; a.targetTouches ? (b.x = a.targetTouches[0].clientX, b.y = a.targetTouches[0].clientY) : (b.x = a.clientX, b.y = a.clientY); return b } function h() { g && (ob(r - (k.x - p.x)), g = !1) } var g = !1, k = null, p = null, r = 0; this.handleGestureStartOLD = function (a) { S && (a.preventDefault(), a.touches && 1 < a.touches.length || (k = f(a), window.navigator.msPointerEnabled ? (document.addEventListener("MSPointerMove", this.handleGestureMove, !0), document.addEventListener("MSPointerUp", this.handleGestureEnd, !0)) : (document.addEventListener("touchmove", this.handleGestureMove, !0), document.addEventListener("touchend", this.handleGestureEnd, !0), document.addEventListener("touchcancel", this.handleGestureEnd, !0), document.addEventListener("mousemove", this.handleGestureMove, !0), document.addEventListener("mouseup", this.handleGestureEnd, !0)))) }.bind(this); this.handleGestureMoveOLD = function (a) { a.preventDefault(); p = f(a); g || (g = !0, window.requestAnimationFrame(h)) }.bind(this); this.handleGestureEndOLD = function (a) { a.cancelable && a.preventDefault(); a.touches && 0 < a.touches.length || (g = !1, window.navigator.msPointerEnabled ? (document.removeEventListener("MSPointerMove", this.handleGestureMove, !0), document.removeEventListener("MSPointerUp", this.handleGestureEnd, !0)) : (document.removeEventListener("touchmove", this.handleGestureMove, !0), document.removeEventListener("touchend", this.handleGestureEnd, !0), document.removeEventListener("touchcancel", this.handleGestureEnd, !0), document.removeEventListener("mousemove", this.handleGestureMove, !0), document.removeEventListener("mouseup", this.handleGestureEnd, !0)), e(this)) }.bind(this); this.removeEventListeners = function () { window.navigator.msPointerEnabled ? (b.removeEventListener("MSPointerDown", c, !0), document.removeEventListener("MSPointerMove", a, !0), document.removeEventListener("MSPointerUp", d, !0)) : (b.removeEventListener("touchstart", c, !0), document.removeEventListener("touchmove", a, !0), document.removeEventListener("touchend", d, !0), document.removeEventListener("touchcancel", d, !0), document.removeEventListener("mousemove", a, !0), document.removeEventListener("mouseup", d, !0)) }; window.navigator.msPointerEnabled ? b.addEventListener("MSPointerDown", c, !0) : b.addEventListener("touchstart", c, !0) } function ob(b) { Za = b; if (null == K)e.vwImgC.css({left: b}); else if (e.vwImgC[0].style[K] = "translateX(" + b + "px)", "slide" == f.imageTransition)if (0 < b) { var c = M().w; e.vwImgP.css({visibility: "visible", left: 0, opacity: 1}); e.vwImgP[0].style[K] = "translateX(" + (-c + b) + "px) "; e.vwImgN[0].style[K] = "translateX(" + -c + "px) " } else c = -M().w, e.vwImgN.css({ visibility: "visible", left: 0, opacity: 1 }), e.vwImgN[0].style[K] = "translateX(" + (-c + b) + "px) ", e.vwImgP[0].style[K] = "translateX(" + -c + "px) " } function Nb() { ngscreenfull.enabled && (ngscreenfull.toggle(), $a ? ($a = !1, e.conVwTb.find(".fullscreenButton").removeClass("removeFullscreenButton").addClass("setFullscreenButton")) : ($a = !0, e.conVwTb.find(".fullscreenButton").removeClass("setFullscreenButton").addClass("removeFullscreenButton"))) } function bb() { na ? (window.clearInterval(Ba), na = !1, e.conVwTb.find(".playPauseButton").removeClass("pauseButton").addClass("playButton")) : (na = !0, e.conVwTb.find(".playPauseButton").removeClass("playButton").addClass("pauseButton"), Aa(), Ba = window.setInterval(function () { Aa() }, Oa)) } function Mb() { La = "std"; e.conVwTb.find(".minimizeButton").removeClass("viewToolbarButton").addClass("hideToolbarButton"); Pb("std"); qa() } function Lb() { La = "min"; e.conVwTb.find(".minimizeButton").removeClass("hideToolbarButton").addClass("viewToolbarButton"); Pb("min"); qa() } function Pb(b) { var c = f.viewerToolbar, c = "std" == b ? f.viewerToolbar.standard : f.viewerToolbar.minimized, a = "minimizeButton previousButton pageCounter nextButton playPauseButton fullscreenButton infoButton linkOriginalButton closeButton label".split(" "); b = 0; for (var d = a.length; b < d; b++)"label" == a[b] ? "" == e.conVwTb.find(".title").text() && "" == e.conVwTb.find(".description").text() ? e.conVwTb.find("." + a[b]).css({display: "none"}) : e.conVwTb.find("." + a[b]).css({display: 0 <= c.indexOf(a[b]) ? "table-cell" : "none"}) : e.conVwTb.find("." + a[b]).css({display: 0 <= c.indexOf(a[b]) ? "table-cell" : "none"}); e.conVwTb.find(".ngCustomBtn").css({display: "none"}); c = c.split(","); b = 0; for (d = c.length; b < d; b++)a = c[b].replace(/^\s+|\s+$/g, ""), 0 == a.indexOf("custom") && e.conVwTb.find("." + a).css({display: "table-cell"}) } function Ea() { na && (window.clearInterval(Ba), Ba = window.setInterval(function () { Aa() }, Oa)); Aa() } function Aa() { if (!(Ca || 300 > (new Date).getTime() - ga)) { var b = Qb(la); Xa(b, "nextImage") } } function Fa() { if (!(Ca || 300 > (new Date).getTime() - ga)) { na && bb(); var b = Rb(la); Xa(b, "previousImage") } } function Xa(b, c) { ga = (new Date).getTime(); Ca = !0; if (f.locationHash) { var a = "nanogallery/" + ja + "/" + p[b].albumID + "/" + p[b].GetID(); "#" + a != location.hash ? (va = "#" + a, top.location.hash = a) : va = top.location.hash } qa(); window.cancelAnimationFrame(ab); la = b; if ("" == c)e.vwImgC.css({ opacity: 0, left: 0, visibility: "visible" }).attr("src", "data:image/gif;base64,R0lGODlhEAAQAIAAAP///////yH5BAEKAAEALAAAAAAQABAAAAIOjI+py+0Po5y02ouzPgUAOw==").attr("src", p[b].responsiveURL()), jQuery.when(e.vwImgC.animate({opacity: 1}, 300)).done(function () { ra(b, c) }); else switch (f.imageTransition) { case "fade": var d = "nextImage" == c ? e.vwImgN : e.vwImgP; d.css({opacity: 0, left: 0, visibility: "visible"}); jQuery.when(e.vwImgC.animate({opacity: 0}, 500), d.animate({opacity: 1}, 300)).done(function () { ra(b, c) }); break; case "slideBETA": d = "nextImage" == c ? e.vwImgN : e.vwImgP; d.css({opacity: 1, left: 0, visibility: "visible"}); if (null == K)jQuery.when(e.vwImgC.animate({ left: ("nextImage" == c ? -M().w : M().w) + "px", opacity: 0 }, 500), d.animate({opacity: 1}, 300)).done(function () { ra(b, c) }); else { var h = "nextImage" == c ? -M().w : M().w; d[0].style[K] = "translateX(" + -h + "px) "; var a = {v: Za}, g = {v: "nextImage" == c ? -M().w : M().w}; jQuery(a).animate(g, { duration: 500, step: function (a) { e.vwImgC[0].style[K] = "translateX(" + a + "px)"; e.vwImgC.css({ opacity: 1 - Math.abs(a / h) }); d[0].style[K] = "translateX(" + (-h + a) + "px) " }, complete: function () { e.vwImgC[0].style[K] = ""; e.vwImgC.css({opacity: 0}); ra(b, c) } }) } break; case "slide": d = "nextImage" == c ? e.vwImgN : e.vwImgP; null == K ? (d.css({ opacity: 0, left: 0, visibility: "visible" }), jQuery.when(e.vwImgC.animate({left: ("nextImage" == c ? -M().w : M().w) + "px"}, 500), d.animate({opacity: 1}, 300)).done(function () { ra(b, c) })) : (d.css({ opacity: 1, left: 0, visibility: "visible" }), h = "nextImage" == c ? -M().w : M().w, d[0].style[K] = "translateX(" + -h + "px) ", a = {v: Za}, g = {v: "nextImage" == c ? -M().w : M().w}, jQuery(a).animate(g, { duration: 400, easing: "linear", step: function (a) { window.requestAnimationFrame(function () { e.vwImgC[0].style[K] = "translateX(" + a + "px)"; d[0].style[K] = "translateX(" + (-h + a) + "px) " }) }, complete: function () { window.requestAnimationFrame(function () { e.vwImgC[0].style[K] = ""; ra(b, c) }) } })); break; default: h = M().w + "px", d = e.vwImgP, "nextImage" == c && (h = "-" + h, d = e.vwImgN), d.css({ opacity: 0, left: 0, visibility: "visible" }), jQuery.when(e.vwImgC.animate({left: h, opacity: 0}, 500), d.animate({opacity: 1}, 300)).done(function () { ob(0); ra(b, c) }) } } function ra(b, c) { pc(b); Za = 0; e.vwImgC.off("click"); e.vwImgC.removeClass("imgCurrent"); var a = e.vwImgC; switch (c) { case "nextImage": e.vwImgC = e.vwImgN; e.vwImgN = a; break; case "previousImage": e.vwImgC = e.vwImgP, e.vwImgP = a } e.vwImgC.addClass("imgCurrent"); e.vwImgN.css({ opacity: 0, left: 0, visibility: "hidden" }).attr("src", "data:image/gif;base64,R0lGODlhEAAQAIAAAP///////yH5BAEKAAEALAAAAAAQABAAAAIOjI+py+0Po5y02ouzPgUAOw==").attr("src", p[Qb(b)].responsiveURL()); e.vwImgP.css({ opacity: 0, left: 0, visibility: "hidden" }).attr("src", "data:image/gif;base64,R0lGODlhEAAQAIAAAP///////yH5BAEKAAEALAAAAAAQABAAAAIOjI+py+0Po5y02ouzPgUAOw==").attr("src", p[Rb(b)].responsiveURL()); e.vwImgC.on("click", function (a) { a.stopPropagation(); a.pageX < jQuery(window).width() / 2 ? Fa() : Ea() }); qa(); Ca = !1 } function Qb(b) { for (var c = p.length, a = -1, d = b + 1; d < c; d++)if (p[d].albumID == p[b].albumID && "image" == p[d].kind) { a = d; break } if (-1 == a)for (d = 0; d <= b; d++)if (p[d].albumID == p[b].albumID && "image" == p[d].kind) { a = d; break } return a } function Rb(b) { for (var c = -1, a = b - 1; 0 <= a; a--)if (p[a].albumID == p[b].albumID && "image" == p[a].kind) { c = a; break } if (-1 == c)for (a = p.length - 1; a >= b; a--)if (p[a].albumID == p[b].albumID && "image" == p[a].kind) { c = a; break } return c } function pc(b) { if (f.viewerToolbar.display) { e.conVwTb.css({visibility: "visible"}); var c = !1; void 0 !== p[b].title && "" != p[b].title ? (e.conVwTb.find(".title").html(p[b].title), c = !0) : e.conVwTb.find(".title").html(""); void 0 !== p[b].description && "" != p[b].description ? (e.conVwTb.find(".description").html(p[b].description), c = !0) : e.conVwTb.find(".description").html(""); var a = e.conVwTb.find(".ngCustomBtn"); 0 < a.length && "function" == typeof f.fnImgToolbarCustDisplay && f.fnImgToolbarCustDisplay(a, p[b], s()); c && 0 <= ("std" == La ? f.viewerToolbar.standard : f.viewerToolbar.minimized).indexOf("label") ? e.conVwTb.find(".label").show() : e.conVwTb.find(".label").hide(); for (var c = 0, a = p.length, d = 0; d < a; d++)p[d].albumID == p[b].albumID && "image" == p[d].kind && c++; 0 < c && e.conVwTb.find(".pageCounter").html(p[b].imageNumber + 1 + "/" + c) } } function Da(b) { Ca && e.vwContent.find("*").stop(!0, !0); Ca = !1; S && (Ya.removeEventListeners(), Ya = null, window.cancelAnimationFrame(ab), na && (window.clearInterval(Ba), na = !1), f.galleryFullpageButton && e.base.hasClass("fullpage") || U(), $a && Nb(), e.conVwCon.hide(0).off().show(0).html("").remove(), -1 != Qa ? X(Qa, !0) : (f.locationHash && b && (b = "nanogallery/" + ja + "/" + p[la].albumID, va = "#" + b, top.location.hash = b), Ia()), ga = (new Date).getTime(), S = !1) } function qa() { window.cancelAnimationFrame(ab); ab = window.requestAnimationFrame(qa); var b = e.conVw.width(), c = e.conVw.height(), a = e.vwImgC, d = a.height(), h = a.width(), g = a.outerHeight(!0), k = a.outerHeight(!1), p = e.conVwTb.find(".toolbar"), r = p.outerHeight(!0); 40 >= d || !f.viewerToolbar.display ? e.conVwTb.css({visibility: "hidden"}) : e.conVwTb.css({visibility: "visible"}); var x = Math.abs(e.vwContent.outerHeight(!0) - e.vwContent.height()), l = Math.abs(e.vwContent.outerWidth(!0) - e.vwContent.width()), t = k - a.innerHeight(), k = Math.abs(a.outerWidth(!1) - a.innerWidth()), v = Math.abs(a.innerHeight() - d), q = Math.abs(a.innerWidth() - h), a = t + v, k = k + q, t = 0; "innerImage" != f.viewerToolbar.style && (t = r); c = c - t - x; b -= l; switch (f.viewerToolbar.position) { case "top": e.vwContent.css({height: c, width: b, top: t}); l = 0; "innerImage" == f.viewerToolbar.style && (l = Math.abs(g - d) / 2 + 5); "stuckImage" == f.viewerToolbar.style && (l = Math.abs(g - d) / 2 - a); e.conVwTb.css({top: l}); break; default: e.vwContent.css({ height: c, width: b }), l = 0, "innerImage" == f.viewerToolbar.style && (l = Math.abs(g - d) / 2 + 5), "stuckImage" == f.viewerToolbar.style && (l = Math.abs(g - d) / 2 - a), e.conVwTb.css({bottom: l}) } "innerImage" == f.viewerToolbar.style && p.css({"max-width": h}); "fullWidth" == f.viewerToolbar.style && p.css({width: b}); e.conVwTb.css({height: r}); e.vwContent.children("img").css({"max-width": b - k, "max-height": c - a}) } function qc(b) { var c = null; switch (V(f.colorScheme)) { case "object": c = Sb; jQuery.extend(!0, c, f.colorScheme); g_colorSchemeLabel = "nanogallery_colorscheme_custom_" + ja; break; case "string": switch (f.colorScheme) { case "none": return; case "light": c = rc; g_colorSchemeLabel = "nanogallery_colorscheme_light"; break; case "lightBackground": c = sc; g_colorSchemeLabel = "nanogallery_colorscheme_lightBackground"; break; case "darkRed": c = tc; g_colorSchemeLabel = "nanogallery_colorscheme_darkred"; break; case "darkGreen": c = uc; g_colorSchemeLabel = "nanogallery_colorscheme_darkgreen"; break; case "darkBlue": c = vc; g_colorSchemeLabel = "nanogallery_colorscheme_darkblue"; break; case "darkOrange": c = wc; g_colorSchemeLabel = "nanogallery_colorscheme_darkorange"; break; default: c = Sb, g_colorSchemeLabel = "nanogallery_colorscheme_default" } break; default: R("Error in colorScheme parameter."); return } var a = "." + g_colorSchemeLabel + " ", d = a + ".nanoGalleryNavigationbar { background:" + c.navigationbar.background + " !important; }\n"; void 0 !== c.navigationbar.border && (d += a + ".nanoGalleryNavigationbar { border:" + c.navigationbar.border + " !important; }\n"); void 0 !== c.navigationbar.borderTop && (d += a + ".nanoGalleryNavigationbar { border-top:" + c.navigationbar.borderTop + " !important; }\n"); void 0 !== c.navigationbar.borderBottom && (d += a + ".nanoGalleryNavigationbar { border-bottom:" + c.navigationbar.borderBottom + " !important; }\n"); void 0 !== c.navigationbar.borderRight && (d += a + ".nanoGalleryNavigationbar { border-right:" + c.navigationbar.borderRight + " !important; }\n"); void 0 !== c.navigationbar.borderLeft && (d += a + ".nanoGalleryNavigationbar { border-left:" + c.navigationbar.borderLeft + " !important; }\n"); var d = d + (a + ".nanoGalleryNavigationbar .oneFolder { color:" + c.navigationbar.color + " !important; }\n"), d = d + (a + ".nanoGalleryNavigationbar .separator { color:" + c.navigationbar.color + " !important; }\n"), d = d + (a + ".nanoGalleryNavigationbar .separatorRTL { color:" + c.navigationbar.color + " !important; }\n"), d = d + (a + ".nanoGalleryNavigationbar .nanoGalleryTags { color:" + c.navigationbar.color + " !important; }\n"), d = d + (a + ".nanoGalleryNavigationbar .setFullPageButton { color:" + c.navigationbar.color + " !important; }\n"), d = d + (a + ".nanoGalleryNavigationbar .removeFullPageButton { color:" + c.navigationbar.color + " !important; }\n"), d = d + (a + ".nanoGalleryNavigationbar .oneFolder:hover { color:" + c.navigationbar.colorHover + " !important; }\n"), d = d + (a + ".nanoGalleryNavigationbar .separatorRTL:hover { color:" + c.navigationbar.colorHover + " !important; }\n"), d = d + (a + ".nanoGalleryNavigationbar .nanoGalleryTags:hover { color:" + c.navigationbar.colorHover + " !important; }\n"), d = d + (a + ".nanoGalleryNavigationbar .setFullPageButton:hover { color:" + c.navigationbar.colorHover + " !important; }\n"), d = d + (a + ".nanoGalleryNavigationbar .removeFullPageButton:hover { color:" + c.navigationbar.colorHover + " !important; }\n"), d = d + (a + ".nanoGalleryContainer > .nanoGalleryThumbnailContainer { background:" + c.thumbnail.background + " !important; border:" + c.thumbnail.border + " !important; }\n"), d = d + (a + ".nanoGalleryContainer > .nanoGalleryThumbnailContainer .imgContainer { background:" + c.thumbnail.background + " !important; }\n"), d = d + (a + ".nanoGalleryContainer > .nanoGalleryThumbnailContainer .labelImage{ background:" + c.thumbnail.labelBackground + " ; }\n"), d = d + (a + ".nanoGalleryContainer > .nanoGalleryThumbnailContainer .labelImageTitle { color:" + c.thumbnail.titleColor + " !important; Text-Shadow:" + c.thumbnail.titleShadow + " !important; }\n"), d = d + (a + ".nanoGalleryContainer > .nanoGalleryThumbnailContainer .labelImageTitle:before { color:" + c.thumbnail.titleColor + " !important; Text-Shadow:" + c.thumbnail.titleShadow + " !important; }\n"), d = d + (a + ".nanoGalleryContainer > .nanoGalleryThumbnailContainer .labelFolderTitle { color:" + c.thumbnail.titleColor + " !important; Text-Shadow:" + c.thumbnail.titleShadow + " !important; }\n"), e = c.thumbnail.labelBackground; "transparent" == e && (e = ""); d += a + ".nanoGalleryContainer > .nanoGalleryThumbnailContainer .labelFolderTitle > span { background-color:" + c.thumbnail.titleColor + " !important; color:" + e + " !important; }\n"; d += a + ".nanoGalleryContainer > .nanoGalleryThumbnailContainer .labelFolderTitle:before { color:" + c.thumbnail.titleColor + " !important; Text-Shadow:" + c.thumbnail.titleShadow + " !important; }\n"; d += a + ".nanoGalleryContainer > .nanoGalleryThumbnailContainer .labelDescription { color:" + c.thumbnail.descriptionColor + " !important; Text-Shadow:" + c.thumbnail.descriptionShadow + " !important; }\n"; d += a + ".nanoGalleryContainer > .nanoGalleryThumbnailContainer .labelDescription > span { background-color:" + c.thumbnail.titleColor + " !important; color:" + e + " !important; }\n"; c = "nanogallery_galleryfullpage_bgcolor_" + ja; d += "." + c + ".fullpage { background:" + f.galleryFullpageBgColor + " !important; }\n"; jQuery("head").append("<style>" + d + "</style>"); jQuery(b).addClass(g_colorSchemeLabel); jQuery(b).addClass(c) } function nc(b) { var c = null; switch (V(f.colorSchemeViewer)) { case "object": c = Tb; jQuery.extend(!0, c, f.colorSchemeViewer); g_colorSchemeLabel = "nanogallery_colorschemeviewer_custom"; break; case "string": switch (f.colorSchemeViewer) { case "none": return; case "light": c = xc; g_colorSchemeLabel = "nanogallery_colorschemeviewer_light"; break; case "darkRed": c = yc; g_colorSchemeLabel = "nanogallery_colorschemeviewer_darkred"; break; case "darkGreen": c = zc; g_colorSchemeLabel = "nanogallery_colorschemeviewer_darkgreen"; break; case "darkBlue": c = Ac; g_colorSchemeLabel = "nanogallery_colorschemeviewer_darkblue"; break; case "darkOrange": c = Bc; g_colorSchemeLabel = "nanogallery_colorschemeviewer_darkorange"; break; case "dark": c = Cc; g_colorSchemeLabel = "nanogallery_colorschemeviewer_dark"; break; default: c = Tb, g_colorSchemeLabel = "nanogallery_colorschemeviewer_default" } break; default: R("Error in colorSchemeViewer parameter."); return } var a = "." + g_colorSchemeLabel + " ", d = a + ".nanoGalleryViewer { background:" + c.background + " !important; }\n", d = d + (a + ".nanoGalleryViewer .content img { border:" + c.imageBorder + " !important; box-shadow:" + c.imageBoxShadow + " !important; }\n"), d = d + (a + ".nanoGalleryViewer .toolbar { background:" + c.barBackground + " !important; border:" + c.barBorder + " !important; color:" + c.barColor + " !important; }\n"), d = d + (a + ".nanoGalleryViewer .toolbar .previousButton:after { color:" + c.barColor + " !important; }\n"), d = d + (a + ".nanoGalleryViewer .toolbar .nextButton:after { color:" + c.barColor + " !important; }\n"), d = d + (a + ".nanoGalleryViewer .toolbar .closeButton:after { color:" + c.barColor + " !important; }\n"), d = d + (a + ".nanoGalleryViewer .toolbar .label .title { color:" + c.barColor + " !important; }\n"), d = d + (a + ".nanoGalleryViewer .toolbar .label .description { color:" + c.barDescriptionColor + " !important; }\n"); jQuery("head").append("<style>" + d + "</style>"); jQuery(b).addClass(g_colorSchemeLabel) } function R(b, c) { ma(b); null != e.conConsole && (e.conConsole.css({ visibility: "visible", height: "auto" }), 0 == c ? e.conConsole.append("<p>" + b + "</p>") : e.conConsole.append("<p>nanoGALLERY: " + b + " [" + ja + "]</p>")) } function ma(b) { window.console && console.log("nanoGALLERY: " + b + " [" + ja + "]") } function M() { var b = jQuery(window); return {l: b.scrollLeft(), t: b.scrollTop(), w: b.width(), h: b.height()} } function Gb(b, c) { var a = M(), d = b.offset(), e = b.outerHeight(!0), f = b.outerWidth(!0); return d.top >= a.t - c && d.top + e <= a.t + a.h + c && d.left >= a.l - c && d.left + f <= a.l + a.w + c ? !0 : !1 } function xa(b, c) { var a = M(), d = b.offset(), e = b.outerHeight(!0); b.outerWidth(!0); return 0 == a.t && d.top <= a.t + a.h ? !0 : d.top >= a.t && d.top + e <= a.t + a.h - c ? !0 : !1 } function L(b, c) { var a = 0; "" == b && (b = "*"); jQuery(b).each(function () { var b = parseInt(jQuery(this).css("z-index")); a = b > a ? b : a }); a++; jQuery(c).css("z-index", a) } function Ka(b) { for (var c, a, d = b.length; d; c = Math.floor(Math.random() * d), a = b[--d], b[d] = b[c], b[c] = a); return b } this.N = {v: 1}; var O = { paginationPrevious: "Previous", paginationNext: "Next", breadcrumbHome: "List of Albums", thumbnailImageTitle: "", thumbnailAlbumTitle: "", thumbnailImageDescription: "", thumbnailAlbumDescription: "" }, f = null, p = [], e = { base: null, conTnParent: null, conLoadingB: null, conConsole: null, conTn: null, conTnHid: null, conPagin: null, conBC: null, conNavB: null, conNavBCon: null, conNavBFullpage: null, conVwCon: null, conVw: null, conVwTb: null, vwImgP: null, vwImgN: null, vwImgC: null, vwContent: null, vwLogo: null }, Y = null, ja = null, Eb = null, Fb = !1, S = !1, h = { displayInterval: 30, lazyLoadTreshold: 100, scale: 1, borderWidth: 0, borderHeight: 0, imgcBorderHeight: 0, imgcBorderWidth: 0, labelHeight: 0, outerWidth: {l1: {xs: 0, sm: 0, me: 0, la: 0, xl: 0}, lN: {xs: 0, sm: 0, me: 0, la: 0, xl: 0}}, outerHeight: {l1: {xs: 0, sm: 0, me: 0, la: 0, xl: 0}, lN: {xs: 0, sm: 0, me: 0, la: 0, xl: 0}}, settings: { width: { l1: {xs: 0, sm: 0, me: 0, la: 0, xl: 0, xsc: "u", smc: "u", mec: "u", lac: "u", xlc: "u"}, lN: {xs: 0, sm: 0, me: 0, la: 0, xl: 0, xsc: "u", smc: "u", mec: "u", lac: "u", xlc: "u"} }, height: { l1: { xs: 0, sm: 0, me: 0, la: 0, xl: 0, xsc: "u", smc: "u", mec: "u", lac: "u", xlc: "u" }, lN: {xs: 0, sm: 0, me: 0, la: 0, xl: 0, xsc: "u", smc: "u", mec: "u", lac: "u", xlc: "u"} } } }, C = [], Ma = null, Na = null, Ja = null, La = "std", na = !1, Ba = 0, Oa = 3E3, db = 0, Ob = !1, $a = !1, ia = "", ga = 0, eb = 0, ka = 1, T = 0, gb = -1, va = "", Ca = !1, ab = -1, la = -1, Za = 0, Qa = -1, G = {}, Ta = -1, Ua = -1, Bb = !1, Ya = null, F = "animate", pb = 0, qb = 0, Pa = 1E6, fb = 1E6, ba = "l1", ha = "me", K = D(["transform", "msTransform", "MozTransform", "WebkitTransform", "OTransform"]), Ib = D(["transformStyle", "msTransformStyle", "MozTransformStyle", "WebkitTransformStyle", "OTransformStyle"]), Va = D(["perspective", "msPerspective", "MozPerspective", "WebkitPerspective", "OPerspective"]), za = D(["backfaceVisibility", "msBackfaceVisibility", "MozBackfaceVisibility", "WebkitBackfaceVisibility", "OBackfaceVisibility"]); D(["transition", "msTransition", "MozTransition", "WebkitTransition", "OTransition"]); D(["animation", "msAnimation", "MozAnimation", "WebkitAnimation", "OAnimation"]); var Jb = function () { if (document.documentMode)return document.documentMode; for (var b = 7; 4 < b; b--) { var c = document.createElement("div"); c.innerHTML = "\x3c!--[if IE " + b + "]><span></span><![endif]--\x3e"; if (c.getElementsByTagName("span").length)return b } }(); (function () { if (/iP(hone|od|ad)/.test(navigator.platform)) { var b = navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/); return [parseInt(b[1], 10), parseInt(b[2], 10), parseInt(b[3] || 0, 10)] } })(); var Wb = /(iPad|iPhone|iPod)/g.test(navigator.userAgent), lc = /Android 2\.3\.[3-7]/i.test(navigator.userAgent), oa = !1, zb = { url: function () { return f.picasaUseUrlCrossDomain ? "https://photos.googleapis.com/data/feed/api/" : "https://picasaweb.google.com/data/feed/api/" }, thumbSize: 64, thumbAvailableSizes: [32, 48, 64, 72, 94, 104, 110, 128, 144, 150, 160, 200, 220, 288, 320, 400, 512, 576, 640, 720, 800, 912, 1024, 1152, 1280, 1440, 1600], thumbAvailableSizesCropped: " 32 48 64 72 104 144 150 160 " }, Q = { url: function () { return "https://api.flickr.com/services/rest/" }, thumbSize: "sq", thumbSizeX2: "sq", thumbAvailableSizes: [75, 100, 150, 240, 500, 640], thumbAvailableSizesStr: "sq t q s m z".split(" "), photoSize: "sq", photoAvailableSizes: [75, 100, 150, 240, 500, 640, 1024, 1024, 1600, 2048], photoAvailableSizesStr: "sq t q s m z b l h k".split(" "), ApiKey: "<KEY>" }, Sb = { navigationbar: { background: "none", borderTop: "1px solid #555", borderBottom: "1px solid #555", borderRight: "", borderLeft: "", color: "#ccc", colorHover: "#fff" }, thumbnail: { background: "#000", border: "1px solid #000", labelBackground: "rgba(34, 34, 34, 0.75)", titleColor: "#eee", titleShadow: "", descriptionColor: "#ccc", descriptionShadow: "" } }, tc = { navigationbar: { background: "#a60000", border: "1px dotted #ff0000", color: "#ccc", colorHover: "#fff" }, thumbnail: { background: "#a60000", border: "1px solid #ff0000", labelBackground: "rgba(134, 0, 0, 0.75)", titleColor: "#eee", titleShadow: "", descriptionColor: "#ccc", descriptionShadow: "" } }, uc = { navigationbar: { background: "#008500", border: "1px dotted #00cc00", color: "#ccc", colorHover: "#fff" }, thumbnail: { background: "#008500", border: "1px solid #00cc00", labelBackground: "rgba(0, 105, 0, 0.75)", titleColor: "#eee", titleShadow: "", descriptionColor: "#ccc", descriptionShadow: "" } }, vc = { navigationbar: { background: "#071871", border: "1px dotted #162ea2", color: "#ccc", colorHover: "#fff" }, thumbnail: { background: "#071871", border: "1px solid #162ea2", labelBackground: "rgba(7, 8, 81, 0.75)", titleColor: "#eee", titleShadow: "", descriptionColor: "#ccc", descriptionShadow: "" } }, wc = { navigationbar: { background: "#a67600", border: "1px dotted #ffb600", color: "#ccc", colorHover: "#fff" }, thumbnail: { background: "#a67600", border: "1px solid #ffb600", labelBackground: "rgba(134, 86, 0, 0.75)", titleColor: "#eee", titleShadow: "", descriptionColor: "#ccc", descriptionShadow: "" } }, rc = { navigationbar: { background: "none", borderTop: "1px solid #ddd", borderBottom: "1px solid #ddd", borderRight: "", borderLeft: "", color: "#777", colorHover: "#eee" }, thumbnail: { background: "#fff", border: "1px solid #fff", labelBackground: "rgba(60, 60, 60, 0.75)", titleColor: "#fff", titleShadow: "none", descriptionColor: "#eee", descriptionShadow: "none" } }, sc = { navigationbar: {background: "none", border: "", color: "#000", colorHover: "#444"}, thumbnail: { background: "#000", border: "1px solid #000", labelBackground: "rgba(34, 34, 34, 0.85)", titleColor: "#fff", titleShadow: "", descriptionColor: "#eee", descriptionShadow: "" } }, Tb = { background: "#000", imageBorder: "4px solid #000", imageBoxShadow: "#888 0px 0px 0px", barBackground: "rgba(4, 4, 4, 0.7)", barBorder: "0px solid #111", barColor: "#eee", barDescriptionColor: "#aaa" }, Cc = { background: "rgba(1, 1, 1, 0.75)", imageBorder: "4px solid #f8f8f8", imageBoxShadow: "#888 0px 0px 20px", barBackground: "rgba(4, 4, 4, 0.7)", barBorder: "0px solid #111", barColor: "#eee", barDescriptionColor: "#aaa" }, yc = { background: "rgba(1, 1, 1, 0.75)", imageBorder: "4px solid #ffa3a3", imageBoxShadow: "#ff0000 0px 0px 20px", barBackground: "#a60000", barBorder: "2px solid #111", barColor: "#eee", barDescriptionColor: "#aaa" }, zc = { background: "rgba(1, 1, 1, 0.75)", imageBorder: "4px solid #97e697", imageBoxShadow: "#00cc00 0px 0px 20px", barBackground: "#008500", barBorder: "2px solid #111", barColor: "#eee", barDescriptionColor: "#aaa" }, Ac = { background: "rgba(1, 1, 1, 0.75)", imageBorder: "4px solid #a0b0d7", imageBoxShadow: "#162ea2 0px 0px 20px", barBackground: "#071871", barBorder: "2px solid #111", barColor: "#eee", barDescriptionColor: "#aaa" }, Bc = { background: "rgba(1, 1, 1, 0.75)", imageBorder: "4px solid #ffd7b7", imageBoxShadow: "#ffb600 0px 0px 20px", barBackground: "#a67600", barBorder: "2px solid #111", barColor: "#eee", barDescriptionColor: "#aaa" }, xc = { background: "rgba(187, 187, 187, 0.75)", imageBorder: "none", imageBoxShadow: "#888 0px 0px 0px", barBackground: "rgba(4, 4, 4, 0.7)", barBorder: "0px solid #111", barColor: "#eee", barDescriptionColor: "#aaa" }, bc = function () { function b(a, b) { var e = 0, e = void 0 === b || null === b ? c++ : b; this.GetID = function () { return e }; this.title = a; this.src = this.description = ""; this.height = this.width = 0; this.thumbX2src = this.thumbsrc = this.author = this.kind = this.destinationURL = ""; this.thumbLabelHeight = this.thumbLabelWidth = this.thumbFullHeight = this.thumbFullWidth = this.thumbImgHeight = this.thumbImgWidth = 0; this.thumbSizes = {}; this.thumbs = { url: {l1: {xs: "", sm: "", me: "", la: "", xl: ""}, lN: {xs: "", sm: "", me: "", la: "", xl: ""}}, width: {l1: {xs: 0, sm: 0, me: 0, la: 0, xl: 0}, lN: {xs: 0, sm: 0, me: 0, la: 0, xl: 0}}, height: { l1: { xs: 0, sm: 0, me: 0, la: 0, xl: 0 }, lN: {xs: 0, sm: 0, me: 0, la: 0, xl: 0} } }; this.picasaThumbs = null; this.hoverInitDone = this.hovered = !1; this.$elt = null; this.contentIsLoaded = !1; this.imageNumber = this.contentLength = 0; this.eltTransform = {}; this.paginationLastWidth = this.paginationLastPage = this.albumID = 0; this.customData = {} } var c = 1; b.get_nextId = function () { return c }; b.prototype = { thumbSetImgHeight: function (a) { for (var b = ["xs", "sm", "me", "la", "xl"], c = 0; c < b.length; c++)h.settings.height.l1[b[c]] == w() && h.settings.width.l1[b[c]] == l() && (this.thumbs.height.l1[b[c]] = a); for (c = 0; c < b.length; c++)h.settings.height.lN[b[c]] == w() && h.settings.width.l1[b[c]] == l() && (this.thumbs.height.lN[b[c]] = a) }, thumbSetImgWidth: function (a) { for (var b = ["xs", "sm", "me", "la", "xl"], c = 0; c < b.length; c++)h.settings.height.l1[b[c]] == w() && h.settings.width.l1[b[c]] == l() && (this.thumbs.width.l1[b[c]] = a); for (c = 0; c < b.length; c++)h.settings.height.lN[b[c]] == w() && h.settings.width.l1[b[c]] == l() && (this.thumbs.width.lN[b[c]] = a) }, thumbImg: function () { var a = {src: "", width: 0, height: 0}; if ("dummydummydummy" == this.title)return a.src = "data:image/gif;base64,R0lGODlhEAAQAIAAAP///////yH5BAEKAAEALAAAAAAQABAAAAIOjI+py+0Po5y02ouzPgUAOw==", a; a.src = this.thumbs.url[ba][ha]; a.width = this.thumbs.width[ba][ha]; a.height = this.thumbs.height[ba][ha]; return a }, responsiveURL: function () { var a = ""; switch (f.kind) { case "": a = this.src; break; case "flickr": a = this.src; break; default: a = this.src } return a } }; return b }(); this.Initiate = function (b, c) { f = c; e.base = jQuery(b); ja = e.base.attr("id"); jQuery("body").css("overflow"); Function.prototype.bind || (Function.prototype.bind = function (a) { if ("function" !== typeof this)throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); var b = Array.prototype.slice.call(arguments, 1), c = this, d = function () { }, e = function () { return c.apply(this instanceof d && a ? this : a, b.concat(Array.prototype.slice.call(arguments))) }; d.prototype = this.prototype; e.prototype = new d; return e }); String.prototype.replaceAll = function (a, b) { return void 0 === b ? this.toString() : this.split(a).join(b) }; "object" == V(jQuery.velocity) ? F = "velocity" : "object" == V(jQuery.transit) && (F = "transition"); jQuery(b).addClass("nanogallery_theme_" + f.theme); qc(b); if (f.thumbnailLabel.hideIcons) { var a = ".nanogallery_thumbnails_icons_off ", a = a + ".nanoGalleryContainer .nanoGalleryThumbnailContainer .labelImageTitle:before { display:none !important; }\n" + (a + ".nanoGalleryContainer .nanoGalleryThumbnailContainer .labelFolderTitle:before { display:none !important; }\n"); jQuery("head").append("<style>" + a + "</style>"); jQuery(b).addClass("nanogallery_thumbnails_icons_off") } f.galleryToolbarHideIcons && (a = ".nanogallery_breadcrumb_icons_off ", a = a + ".nanoGalleryNavigationbar .folderHome:before { display:none !important; }\n" + (a + ".nanoGalleryNavigationbar .folder:before { display:none !important; }\n"), jQuery("head").append("<style>" + a + "</style>"), jQuery(b).addClass("nanogallery_breadcrumb_icons_off")); "right" == f.thumbnailLabel.align && (a = ".nanogallery_thumbnails_label_align_right .nanoGalleryContainer .nanoGalleryThumbnailContainer .labelImage { text-align : right !important; }\n", jQuery("head").append("<style>" + a + "</style>"), jQuery(b).addClass("nanogallery_thumbnails_label_align_right")); "center" == f.thumbnailLabel.align && (a = ".nanogallery_thumbnails_label_align_center .nanoGalleryContainer .nanoGalleryThumbnailContainer .labelImage { text-align : center !important; }\n", jQuery("head").append("<style>" + a + "</style>"), jQuery(b).addClass("nanogallery_thumbnails_label_align_center")); "left" == f.thumbnailLabel.align && (a = ".nanogallery_thumbnails_label_align_left .nanoGalleryContainer .nanoGalleryThumbnailContainer .labelImage { text-align : left !important; }\n", jQuery("head").append("<style>" + a + "</style>"), jQuery(b).addClass("nanogallery_thumbnails_label_align_left")); e.conNavBCon = jQuery('<div class="nanoGalleryNavigationbarContainer"></div>').appendTo(b); e.conNavBCon.hide(); e.conNavB = jQuery('<div class="nanoGalleryNavigationbar"></div>').appendTo(e.conNavBCon); a = ""; f.RTL && (a = 'style="text-align:right;direction:rtl;"'); e.conBC = jQuery('<div class="nanoGalleryBreadcrumb" ' + a + "></div>").appendTo(e.conNavB); e.conLoadingB = jQuery('<div class="nanoGalleryLBar" style="visibility:hidden;"><div></div><div></div><div></div><div></div><div></div></div>').appendTo(b); e.conTnParent = jQuery('<div class="nanoGalleryContainerParent"></div>').appendTo(b); e.conTn = jQuery('<div class="nanoGalleryContainer"></div>').appendTo(e.conTnParent); e.conConsole = jQuery('<div class="nanoGalleryConsoleParent"></div>').appendTo(b); switch (f.thumbnailAlignment) { case "left": e.conTnParent.css({"text-align": "left"}); e.conNavBCon.css({"margin-left": 0}); break; case "right": e.conTnParent.css({"text-align": "right"}), e.conNavBCon.css({"margin-right": 0}) } jQuery("head").append("<style>.nanogalleryHideElement {position: absolute !important; top: -9999px !important; left: -9999px !important;}</style>"); a = jQuery('<div class="nanogalleryHideElement ' + jQuery(b).attr("class") + '"></div>').appendTo("body"); a = jQuery('<div class="nanoGalleryContainerParent"></div>').appendTo(a); e.conTnHid = jQuery('<div class="nanoGalleryContainer"></div>').appendTo(a); if (f.supportIE8)try { !window.addEventListener && function (a, b, c, d, e, f, h) { a[d] = b[d] = c[d] = function (a, b) { var c = this; h.unshift([c, a, b, function (a) { a.currentTarget = c; a.preventDefault = function () { a.returnValue = !1 }; a.stopPropagation = function () { a.cancelBubble = !0 }; a.target = a.srcElement || c; b.call(c, a) }]); this.attachEvent("on" + a, h[0][3]) }; a[e] = b[e] = c[e] = function (a, b) { for (var c = 0, d; d = h[c]; ++c)if (d[0] == this && d[1] == a && d[2] == b)return this.detachEvent("on" + a, h.splice(c, 1)[0][3]) }; a[f] = b[f] = c[f] = function (a) { return this.fireEvent("on" + a.type, a) } }(Window.prototype, HTMLDocument.prototype, Element.prototype, "addEventListener", "removeEventListener", "dispatchEvent", []) } catch (d) { return J(), !1 } else if (8 >= Jb)return J(), !1; q(); a = ""; f.RTL && (a = 'style="direction:rtl;"'); e.conPagin = jQuery('<div class="nanoGalleryPagination" ' + a + "></div>").appendTo(e.conTnParent); e.conPagin.hide(); new I(e.conTn[0]); x(); document.fullscreenEnabled || document.webkitFullscreenEnabled || document.msFullscreenEnabled || document.mozFullScreenEnabled ? Ob = !0 : ma("Your browser does not support the fullscreen API. Fullscreen button will not be displayed."); P(); wa(); "loadData" != f.lazyBuild && A(); var g = 0; jQuery(window).resize(function () { g && clearTimeout(g); S ? qa() : g = setTimeout(function () { var a = ca(); -1 == Ua || w() == h.settings.height[ba][a] && l() == h.settings.width[ba][a] ? Ga() : (ha = a, ya(Ua, 0)) }, 50) }); jQuery(window).on("scroll", function () { pb && clearTimeout(pb); pb = setTimeout(function () { "loadData" == f.lazyBuild && xa(e.conTnParent, f.lazyBuildTreshold) && (f.lazyBuild = "none", A()); -1 != Ta && xa(e.conTnParent, f.lazyBuildTreshold) && ib(Ta, Bb); jb() }, 200) }); e.base.on("scroll", function () { qb && clearTimeout(qb); qb = setTimeout(function () { jb() }, 200) }) }; (function () { for (var b = 0, c = ["ms", "moz", "webkit", "o"], a = 0; a < c.length && !window.requestAnimationFrame; ++a)window.requestAnimationFrame = window[c[a] + "RequestAnimationFrame"], window.cancelAnimationFrame = window[c[a] + "CancelAnimationFrame"] || window[c[a] + "CancelRequestAnimationFrame"]; window.requestAnimationFrame || (window.requestAnimationFrame = function (a, c) { var e = (new Date).getTime(), f = Math.max(0, 16 - (e - b)), h = window.setTimeout(function () { a(e + f) }, f); b = e + f; return h }); window.cancelAnimationFrame || (window.cancelAnimationFrame = function (a) { clearTimeout(a) }) })(); var V = function (b) { return {}.toString.call(b).match(/\s([a-zA-Z]+)/)[1].toLowerCase() }, Wa = function (b, c, a) { b = b.replace(/^\s*|\s*$/, ""); b = b.replace(/^#?([a-f0-9])([a-f0-9])([a-f0-9])$/i, "#$1$1$2$2$3$3"); c = Math.round(256 * c) * (a ? -1 : 1); var d = b.match(/^rgba?\(\s*(\d|[1-9]\d|1\d{2}|2[0-4][0-9]|25[0-5])\s*,\s*(\d|[1-9]\d|1\d{2}|2[0-4][0-9]|25[0-5])\s*,\s*(\d|[1-9]\d|1\d{2}|2[0-4][0-9]|25[0-5])(?:\s*,\s*(0|1|0?\.\d+))?\s*\)$/i), e = d && null != d[4] ? d[4] : null; b = d ? [d[1], d[2], d[3]] : b.replace(/^#?([a-f0-9][a-f0-9])([a-f0-9][a-f0-9])([a-f0-9][a-f0-9])/i, function (a, b, c, d) { return parseInt(b, 16) + "," + parseInt(c, 16) + "," + parseInt(d, 16) }).split(/,/); return d ? "rgb" + (null !== e ? "a" : "") + "(" + Math[a ? "max" : "min"](parseInt(b[0], 10) + c, a ? 0 : 255) + ", " + Math[a ? "max" : "min"](parseInt(b[1], 10) + c, a ? 0 : 255) + ", " + Math[a ? "max" : "min"](parseInt(b[2], 10) + c, a ? 0 : 255) + (null !== e ? ", " + e : "") + ")" : ["#", rb(Math[a ? "max" : "min"](parseInt(b[0], 10) + c, a ? 0 : 255).toString(16), 2), rb(Math[a ? "max" : "min"](parseInt(b[1], 10) + c, a ? 0 : 255).toString(16), 2), rb(Math[a ? "max" : "min"](parseInt(b[2], 10) + c, a ? 0 : 255).toString(16), 2)].join("") }, rb = function (b, c) { for (b += ""; b.length < c;)b = "0" + b; return b } } (function (s, J) { function D(g, k, r) { var l = w[k.type] || {}; if (null == g)return r || !k.def ? null : k.def; g = l.floor ? ~~g : parseFloat(g); return isNaN(g) ? k.def : l.mod ? (g + l.mod) % l.mod : 0 > g ? 0 : l.max < g ? l.max : g } function A(g) { var x = k(), r = x._rgba = []; g = g.toLowerCase(); v(q, function (k, v) { var q, w = v.re.exec(g); q = w && v.parse(w); w = v.space || "rgba"; if (q)return q = x[w](q), x[l[w].cache] = q[l[w].cache], r = x._rgba = q._rgba, !1 }); return r.length ? ("0,0,0,0" === r.join() && s.extend(r, ca.transparent), x) : ca[g] } function U(g, k, r) { r = (r + 1) % 1; return 1 > 6 * r ? g + (k - g) * r * 6 : 1 > 2 * r ? k : 2 > 3 * r ? g + (k - g) * (2 / 3 - r) * 6 : g } var I = /^([\-+])=\s*(\d+\.?\d*)/, q = [{ re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, parse: function (g) { return [g[1], g[2], g[3], g[4]] } }, { re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, parse: function (g) { return [2.55 * g[1], 2.55 * g[2], 2.55 * g[3], g[4]] } }, { re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/, parse: function (g) { return [parseInt(g[1], 16), parseInt(g[2], 16), parseInt(g[3], 16)] } }, { re: /#([a-f0-9])([a-f0-9])([a-f0-9])/, parse: function (g) { return [parseInt(g[1] + g[1], 16), parseInt(g[2] + g[2], 16), parseInt(g[3] + g[3], 16)] } }, { re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, space: "hsla", parse: function (g) { return [g[1], g[2] / 100, g[3] / 100, g[4]] } }], k = s.Color = function (g, k, r, l) { return new s.Color.fn.parse(g, k, r, l) }, l = { rgba: {props: {red: {idx: 0, type: "byte"}, green: {idx: 1, type: "byte"}, blue: {idx: 2, type: "byte"}}}, hsla: { props: { hue: {idx: 0, type: "degrees"}, saturation: {idx: 1, type: "percent"}, lightness: {idx: 2, type: "percent"} } } }, w = { "byte": {floor: !0, max: 255}, percent: {max: 1}, degrees: {mod: 360, floor: !0} }, H = k.support = {}, da = s("<p>")[0], ca, v = s.each; da.style.cssText = "background-color:rgba(1,1,1,.5)"; H.rgba = -1 < da.style.backgroundColor.indexOf("rgba"); v(l, function (g, k) { k.cache = "_" + g; k.props.alpha = {idx: 3, type: "percent", def: 1} }); k.fn = s.extend(k.prototype, { parse: function (g, x, r, q) { if (g === J)return this._rgba = [null, null, null, null], this; if (g.jquery || g.nodeType)g = s(g).css(x), x = J; var w = this, N = s.type(g), I = this._rgba = []; x !== J && (g = [g, x, r, q], N = "array"); if ("string" === N)return this.parse(A(g) || ca._default); if ("array" === N)return v(l.rgba.props, function (k, r) { I[r.idx] = D(g[r.idx], r) }), this; if ("object" === N)return g instanceof k ? v(l, function (k, r) { g[r.cache] && (w[r.cache] = g[r.cache].slice()) }) : v(l, function (k, r) { var l = r.cache; v(r.props, function (k, x) { if (!w[l] && r.to) { if ("alpha" === k || null == g[k])return; w[l] = r.to(w._rgba) } w[l][x.idx] = D(g[k], x, !0) }); w[l] && 0 > s.inArray(null, w[l].slice(0, 3)) && (w[l][3] = 1, r.from && (w._rgba = r.from(w[l]))) }), this }, is: function (g) { var x = k(g), r = !0, q = this; v(l, function (g, k) { var l, w = x[k.cache]; w && (l = q[k.cache] || k.to && k.to(q._rgba) || [], v(k.props, function (g, k) { if (null != w[k.idx])return r = w[k.idx] === l[k.idx] })); return r }); return r }, _space: function () { var g = [], k = this; v(l, function (r, l) { k[l.cache] && g.push(r) }); return g.pop() }, transition: function (g, x) { var r = k(g), q = r._space(), s = l[q], A = 0 === this.alpha() ? k("transparent") : this, I = A[s.cache] || s.to(A._rgba), H = I.slice(), r = r[s.cache]; v(s.props, function (g, k) { var l = k.idx, v = I[l], q = r[l], P = w[k.type] || {}; null !== q && (null === v ? H[l] = q : (P.mod && (q - v > P.mod / 2 ? v += P.mod : v - q > P.mod / 2 && (v -= P.mod)), H[l] = D((q - v) * x + v, k))) }); return this[q](H) }, blend: function (g) { if (1 === this._rgba[3])return this; var l = this._rgba.slice(), r = l.pop(), v = k(g)._rgba; return k(s.map(l, function (g, k) { return (1 - r) * v[k] + r * g })) }, toRgbaString: function () { var g = "rgba(", k = s.map(this._rgba, function (g, k) { return null == g ? 2 < k ? 1 : 0 : g }); 1 === k[3] && (k.pop(), g = "rgb("); return g + k.join() + ")" }, toHslaString: function () { var g = "hsla(", k = s.map(this.hsla(), function (g, k) { null == g && (g = 2 < k ? 1 : 0); k && 3 > k && (g = Math.round(100 * g) + "%"); return g }); 1 === k[3] && (k.pop(), g = "hsl("); return g + k.join() + ")" }, toHexString: function (g) { var k = this._rgba.slice(), l = k.pop(); g && k.push(~~(255 * l)); return "#" + s.map(k, function (g) { g = (g || 0).toString(16); return 1 === g.length ? "0" + g : g }).join("") }, toString: function () { return 0 === this._rgba[3] ? "transparent" : this.toRgbaString() } }); k.fn.parse.prototype = k.fn; l.hsla.to = function (g) { if (null == g[0] || null == g[1] || null == g[2])return [null, null, null, g[3]]; var k = g[0] / 255, l = g[1] / 255, v = g[2] / 255; g = g[3]; var q = Math.max(k, l, v), w = Math.min(k, l, v), s = q - w, A = q + w, I = .5 * A, A = 0 === s ? 0 : .5 >= I ? s / A : s / (2 - A); return [Math.round(w === q ? 0 : k === q ? 60 * (l - v) / s + 360 : l === q ? 60 * (v - k) / s + 120 : 60 * (k - l) / s + 240) % 360, A, I, null == g ? 1 : g] }; l.hsla.from = function (g) { if (null == g[0] || null == g[1] || null == g[2])return [null, null, null, g[3]]; var k = g[0] / 360, l = g[1], v = g[2]; g = g[3]; l = .5 >= v ? v * (1 + l) : v + l - v * l; v = 2 * v - l; return [Math.round(255 * U(v, l, k + 1 / 3)), Math.round(255 * U(v, l, k)), Math.round(255 * U(v, l, k - 1 / 3)), g] }; v(l, function (g, l) { var r = l.props, q = l.cache, w = l.to, A = l.from; k.fn[g] = function (g) { w && !this[q] && (this[q] = w(this._rgba)); if (g === J)return this[q].slice(); var l, x = s.type(g), I = "array" === x || "object" === x ? g : arguments, H = this[q].slice(); v(r, function (g, k) { var l = I["object" === x ? g : k.idx]; null == l && (l = H[k.idx]); H[k.idx] = D(l, k) }); return A ? (l = k(A(H)), l[q] = H, l) : k(H) }; v(r, function (l, r) { k.fn[l] || (k.fn[l] = function (k) { var v = s.type(k), q = "alpha" === l ? this._hsla ? "hsla" : "rgba" : g, x = this[q](), w = x[r.idx]; if ("undefined" === v)return w; "function" === v && (k = k.call(this, w), v = s.type(k)); if (null == k && r.empty)return this; "string" === v && (v = I.exec(k)) && (k = w + parseFloat(v[2]) * ("+" === v[1] ? 1 : -1)); x[r.idx] = k; return this[q](x) }) }) }); k.hook = function (g) { g = g.split(" "); v(g, function (g, l) { s.cssHooks[l] = { set: function (g, v) { var q, x = ""; if ("transparent" !== v && ("string" !== s.type(v) || (q = A(v)))) { v = k(q || v); if (!H.rgba && 1 !== v._rgba[3]) { for (q = "backgroundColor" === l ? g.parentNode : g; ("" === x || "transparent" === x) && q && q.style;)try { x = s.css(q, "backgroundColor"), q = q.parentNode } catch (w) { } v = v.blend(x && "transparent" !== x ? x : "_default") } v = v.toRgbaString() } try { g.style[l] = v } catch (I) { } } }; s.fx.step[l] = function (g) { g.colorInit || (g.start = k(g.elem, l), g.end = k(g.end), g.colorInit = !0); s.cssHooks[l].set(g.elem, g.start.transition(g.end, g.pos)) } }) }; k.hook("backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor"); s.cssHooks.borderColor = { expand: function (g) { var k = {}; v(["Top", "Right", "Bottom", "Left"], function (l, v) { k["border" + v + "Color"] = g }); return k } }; ca = s.Color.names = { aqua: "#00ffff", black: "#000000", blue: "#0000ff", fuchsia: "#ff00ff", gray: "#808080", green: "#008000", lime: "#00ff00", maroon: "#800000", navy: "#000080", olive: "#808000", purple: "#800080", red: "#ff0000", silver: "#c0c0c0", teal: "#008080", white: "#ffffff", yellow: "#ffff00", transparent: [null, null, null, 0], _default: "#ffffff" } })(jQuery); (function () { function s() { } function J(q, k) { for (var l = q.length; l--;)if (q[l].listener === k)return l; return -1 } function D(q) { return function () { return this[q].apply(this, arguments) } } var A = s.prototype, U = this, I = U.ngEventEmitter; A.getListeners = function (q) { var k = this._getEvents(), l, w; if ("object" === typeof q)for (w in l = {}, k)k.hasOwnProperty(w) && q.test(w) && (l[w] = k[w]); else l = k[q] || (k[q] = []); return l }; A.flattenListeners = function (q) { var k = [], l; for (l = 0; l < q.length; l += 1)k.push(q[l].listener); return k }; A.getListenersAsObject = function (q) { var k = this.getListeners(q), l; k instanceof Array && (l = {}, l[q] = k); return l || k }; A.addListener = function (q, k) { var l = this.getListenersAsObject(q), w = "object" === typeof k, s; for (s in l)l.hasOwnProperty(s) && -1 === J(l[s], k) && l[s].push(w ? k : {listener: k, once: !1}); return this }; A.on = D("addListener"); A.addOnceListener = function (q, k) { return this.addListener(q, {listener: k, once: !0}) }; A.once = D("addOnceListener"); A.defineEvent = function (q) { this.getListeners(q); return this }; A.defineEvents = function (q) { for (var k = 0; k < q.length; k += 1)this.defineEvent(q[k]); return this }; A.removeListener = function (q, k) { var l = this.getListenersAsObject(q), w, s; for (s in l)l.hasOwnProperty(s) && (w = J(l[s], k), -1 !== w && l[s].splice(w, 1)); return this }; A.off = D("removeListener"); A.addListeners = function (q, k) { return this.manipulateListeners(!1, q, k) }; A.removeListeners = function (q, k) { return this.manipulateListeners(!0, q, k) }; A.manipulateListeners = function (q, k, l) { var w, s, A = q ? this.removeListener : this.addListener; q = q ? this.removeListeners : this.addListeners; if ("object" !== typeof k || k instanceof RegExp)for (w = l.length; w--;)A.call(this, k, l[w]); else for (w in k)k.hasOwnProperty(w) && (s = k[w]) && ("function" === typeof s ? A.call(this, w, s) : q.call(this, w, s)); return this }; A.removeEvent = function (q) { var k = typeof q, l = this._getEvents(), w; if ("string" === k)delete l[q]; else if ("object" === k)for (w in l)l.hasOwnProperty(w) && q.test(w) && delete l[w]; else delete this._events; return this }; A.removeAllListeners = D("removeEvent"); A.emitEvent = function (q, k) { var l = this.getListenersAsObject(q), w, s, A, I; for (A in l)if (l.hasOwnProperty(A))for (s = l[A].length; s--;)w = l[A][s], !0 === w.once && this.removeListener(q, w.listener), I = w.listener.apply(this, k || []), I === this._getOnceReturnValue() && this.removeListener(q, w.listener); return this }; A.trigger = D("emitEvent"); A.emit = function (q) { var k = Array.prototype.slice.call(arguments, 1); return this.emitEvent(q, k) }; A.setOnceReturnValue = function (q) { this._onceReturnValue = q; return this }; A._getOnceReturnValue = function () { return this.hasOwnProperty("_onceReturnValue") ? this._onceReturnValue : !0 }; A._getEvents = function () { return this._events || (this._events = {}) }; s.noConflict = function () { U.ngEventEmitter = I; return s }; "function" === typeof define && define.amd ? define("ngEventEmitter/ngEventEmitter", [], function () { return s }) : "object" === typeof module && module.exports ? module.exports = s : this.ngEventEmitter = s }).call(this); (function (s) { function J(A) { var q = s.event; q.target = q.target || q.srcElement || A; return q } var D = document.documentElement, A = function () { }; D.addEventListener ? A = function (s, q, k) { s.addEventListener(q, k, !1) } : D.attachEvent && (A = function (s, q, k) { s[q + k] = k.handleEvent ? function () { var l = J(s); k.handleEvent.call(k, l) } : function () { var l = J(s); k.call(s, l) }; s.attachEvent("on" + q, s[q + k]) }); var U = function () { }; D.removeEventListener ? U = function (s, q, k) { s.removeEventListener(q, k, !1) } : D.detachEvent && (U = function (s, q, k) { s.detachEvent("on" + q, s[q + k]); try { delete s[q + k] } catch (l) { s[q + k] = void 0 } }); D = {bind: A, unbind: U}; "function" === typeof define && define.amd ? define("eventie/eventie", D) : s.eventie = D })(this); (function (s, J) { "function" === typeof define && define.amd ? define(["ngEventEmitter/ngEventEmitter", "eventie/eventie"], function (D, A) { return J(s, D, A) }) : "object" === typeof exports ? module.exports = J(s, require("wolfy87-eventemitter"), require("eventie")) : s.ngimagesLoaded = J(s, s.ngEventEmitter, s.eventie) })(window, function (s, J, D) { function A(k, g) { for (var l in g)k[l] = g[l]; return k } function U(k) { var g = []; if ("[object Array]" === da.call(k))g = k; else if ("number" === typeof k.length)for (var l = 0, r = k.length; l < r; l++)g.push(k[l]); else g.push(k); return g } function I(k, g, q) { if (!(this instanceof I))return new I(k, g); "string" === typeof k && (k = document.querySelectorAll(k)); this.elements = U(k); this.options = A({}, this.options); "function" === typeof g ? q = g : A(this.options, g); if (q)this.on("always", q); this.getImages(); l && (this.jqDeferred = new l.Deferred); var r = this; setTimeout(function () { r.check() }) } function q(k) { this.img = k } function k(k) { this.src = k; ca[k] = this } var l = s.jQuery, w = s.console, H = "undefined" !== typeof w, da = Object.prototype.toString; I.prototype = new J; I.prototype.options = {}; I.prototype.getImages = function () { this.images = []; for (var k = 0, g = this.elements.length; k < g; k++) { var l = this.elements[k]; "IMG" === l.nodeName && this.addImage(l); var r = l.nodeType; if (r && (1 === r || 9 === r || 11 === r))for (var l = l.querySelectorAll("img"), r = 0, q = l.length; r < q; r++)this.addImage(l[r]) } }; I.prototype.addImage = function (k) { k = new q(k); this.images.push(k) }; I.prototype.check = function () { function k(q, v) { g.options.debug && H && w.log("confirm", q, v); g.progress(q); l++; l === r && g.complete(); return !0 } var g = this, l = 0, r = this.images.length; this.hasAnyBroken = !1; if (r)for (var q = 0; q < r; q++) { var s = this.images[q]; s.on("confirm", k); s.check() } else this.complete() }; I.prototype.progress = function (k) { this.hasAnyBroken = this.hasAnyBroken || !k.isLoaded; var g = this; setTimeout(function () { g.emit("progress", g, k); g.jqDeferred && g.jqDeferred.notify && g.jqDeferred.notify(g, k) }) }; I.prototype.complete = function () { var k = this.hasAnyBroken ? "fail" : "done"; this.isComplete = !0; var g = this; setTimeout(function () { g.emit(k, g); g.emit("always", g); if (g.jqDeferred)g.jqDeferred[g.hasAnyBroken ? "reject" : "resolve"](g) }) }; l && (l.fn.ngimagesLoaded = function (k, g) { return (new I(this, k, g)).jqDeferred.promise(l(this)) }); q.prototype = new J; q.prototype.check = function () { var l = ca[this.img.src] || new k(this.img.src); if (l.isConfirmed)this.confirm(l.isLoaded, "cached was confirmed"); else if (this.img.complete && void 0 !== this.img.naturalWidth)this.confirm(0 !== this.img.naturalWidth, "naturalWidth"); else { var g = this; l.on("confirm", function (k, l) { g.confirm(k.isLoaded, l); return !0 }); l.check() } }; q.prototype.confirm = function (k, g) { this.isLoaded = k; this.emit("confirm", this, g) }; var ca = {}; k.prototype = new J; k.prototype.check = function () { if (!this.isChecked) { var k = new Image; D.bind(k, "load", this); D.bind(k, "error", this); k.src = this.src; this.isChecked = !0 } }; k.prototype.handleEvent = function (k) { var g = "on" + k.type; if (this[g])this[g](k) }; k.prototype.onload = function (k) { this.confirm(!0, "onload"); this.unbindProxyEvents(k) }; k.prototype.onerror = function (k) { this.confirm(!1, "onerror"); this.unbindProxyEvents(k) }; k.prototype.confirm = function (k, g) { this.isConfirmed = !0; this.isLoaded = k; this.emit("confirm", this, g) }; k.prototype.unbindProxyEvents = function (k) { D.unbind(k.target, "load", this); D.unbind(k.target, "error", this) }; return I }); (function () { var s = "undefined" !== typeof module && module.exports, J = "undefined" !== typeof Element && "ALLOW_KEYBOARD_INPUT"in Element, D = function () { var s, A, q = ["requestFullscreen exitFullscreen fullscreenElement fullscreenEnabled fullscreenchange fullscreenerror".split(" "), "webkitRequestFullscreen webkitExitFullscreen webkitFullscreenElement webkitFullscreenEnabled webkitfullscreenchange webkitfullscreenerror".split(" "), "webkitRequestFullScreen webkitCancelFullScreen webkitCurrentFullScreenElement webkitCancelFullScreen webkitfullscreenchange webkitfullscreenerror".split(" "), "mozRequestFullScreen mozCancelFullScreen mozFullScreenElement mozFullScreenEnabled mozfullscreenchange mozfullscreenerror".split(" "), "msRequestFullscreen msExitFullscreen msFullscreenElement msFullscreenEnabled MSFullscreenChange MSFullscreenError".split(" ")], k = 0; A = q.length; for (var l = {}; k < A; k++)if ((s = q[k]) && s[1]in document) { k = 0; for (A = s.length; k < A; k++)l[q[0][k]] = s[k]; return l } return !1 }(), A = { request: function (s) { var A = D.requestFullscreen; s = s || document.documentElement; if (/5\.1[\.\d]* Safari/.test(navigator.userAgent))s[A](); else s[A](J && Element.ALLOW_KEYBOARD_INPUT) }, exit: function () { document[D.exitFullscreen]() }, toggle: function (s) { this.isFullscreen ? this.exit() : this.request(s) }, onchange: function () { }, onerror: function () { }, raw: D }; D ? (Object.defineProperties(A, { isFullscreen: { get: function () { return !!document[D.fullscreenElement] } }, element: { enumerable: !0, get: function () { return document[D.fullscreenElement] } }, enabled: { enumerable: !0, get: function () { return !!document[D.fullscreenEnabled] } } }), document.addEventListener(D.fullscreenchange, function (s) { A.onchange.call(A, s) }), document.addEventListener(D.fullscreenerror, function (s) { A.onerror.call(A, s) }), s ? module.exports = A : window.ngscreenfull = A) : s ? module.exports = !1 : window.ngscreenfull = !1 })();<file_sep>/web_site/models.py from django.db import models # Create your models here. from easy_thumbnails.fields import ThumbnailerImageField from easy_thumbnails.signal_handlers import generate_aliases_global from easy_thumbnails.signals import saved_file from web_site.util.upload_util import UploadTo, UploadToProjectImage saved_file.connect(generate_aliases_global) class ThumbnailAdminMixin(object): admin_thumbnail_field = 'admin_thumbnail_field_name' def admin_thumbnail(self): admin_thumbnail_field = getattr(self, getattr(self, self.admin_thumbnail_field)) if admin_thumbnail_field: thumbnail = admin_thumbnail_field['thumbnail'] if thumbnail: return u'<a href="%s" target="_blank"><img src="%s" style="width: 250px;"/></a>' % ( admin_thumbnail_field.url, admin_thumbnail_field['thumbnail'].url) else: return u'<a href="%s" target="_blank"><img src="%s" style="width: 250px;"/></a>' % ( admin_thumbnail_field.url, admin_thumbnail_field.url) else: return '(none)' admin_thumbnail.short_description = 'Thumbnail' admin_thumbnail.allow_tags = True class JumbotronImage(models.Model, ThumbnailAdminMixin): image_file = ThumbnailerImageField(upload_to='jumbotron_images/') title = models.CharField(max_length=40, blank=True) description = models.TextField(max_length=200, blank=True) admin_thumbnail_field_name = 'image_file' class Project(models.Model, ThumbnailAdminMixin): upload_dir = 'project_images' title = models.CharField(max_length=40) description = models.TextField(max_length=200, blank=True) logo_image = ThumbnailerImageField(upload_to=UploadTo(upload_dir)) admin_thumbnail_field_name = 'logo_image' def __unicode__(self): return self.title class ProjectImage(models.Model, ThumbnailAdminMixin): project = models.ForeignKey('Project', related_name='ProjectImages', default=1) title = models.CharField(max_length=50, blank=True) image_file = ThumbnailerImageField(upload_to=UploadToProjectImage(sub_path='images/')) admin_thumbnail_field_name = 'image_file' def __unicode__(self): return self.project.title + "_" + self.image_file.name # # # # These two auto-delete files from filesystem when they are unneeded: # @receiver(models.signals.post_delete) # def auto_delete_file_on_delete(sender, instance, **kwargs): # """Deletes file from filesystem # when corresponding `MediaFile` object is deleted. # """ # if issubclass(sender, ThumbnailAdminMixin): # image_field = getattr(instance, getattr(instance, ThumbnailAdminMixin.admin_thumbnail_field)) # if image_field: # if os.path.isfile(image_field.path): # os.remove(image_field.path) # # # @receiver(models.signals.pre_save) # def auto_delete_file_on_change(sender, instance, **kwargs): # """Deletes file from filesystem # when corresponding `MediaFile` object is changed. # """ # if not instance.pk: # return False # if issubclass(sender, ThumbnailAdminMixin): # try: # old_file = instance.objects.get(pk=instance.pk).getattr( # getattr(instance, ThumbnailAdminMixin.admin_thumbnail_field)) # except instance.DoesNotExist: # return False # new_file = image_field = getattr(instance, getattr(instance, ThumbnailAdminMixin.admin_thumbnail_field)) # if not old_file == new_file: # if os.path.isfile(old_file.path): # os.remove(old_file.path)<file_sep>/web_site/forms.py from envelope.forms import ContactForm __author__ = '<NAME>' class CustomContactForm(ContactForm): pass<file_sep>/web_site/views.py # Create your views here. from django.views.generic.base import TemplateView from envelope.views import ContactView from web_site.forms import CustomContactForm from web_site.models import JumbotronImage, Project, ProjectImage class IndexView(TemplateView): template_name = 'web_site/index.html' http_method_names = ['get'] def get_context_data(self, **kwargs): kwargs = super(IndexView, self).get_context_data(**kwargs) kwargs['jumbotron_image_objects'] = self.get_jumbotron_image_objects() kwargs['projects_and_images'] = self.get_projects_with_its_images() kwargs['contact_form'] = self.get_contact_form() return kwargs def get_jumbotron_image_objects(self): return JumbotronImage.objects.all() def get_projects_with_its_images(self): project_with_images_list = [] project_id = 1 projects = Project.objects.all() for project in projects: project_images = ProjectImage.objects.filter(project=project) project_with_images_list.append((project, project_id, project_images)) project_id += len(project_images) + 1 return sorted(project_with_images_list, key=lambda prjct: len(prjct[2]), reverse=True) def get_contact_form(self): contact_form = CustomContactForm() return contact_form class CustomContactView(ContactView): template_name = 'web_site/index.html' success_url = 'index'
9e89bbebbcaef6ea011cb025f1d09b55e45e97c6
[ "JavaScript", "Python", "Text" ]
7
Python
xSAVIKx/nastya_web_site
2e982a56fcdfd3ea5e76ab93d0be2cc32495efb9
3f6aef21085bec5ad83ee28e1cb153fdfff479d7
refs/heads/master
<file_sep>using System; using System.Windows; using OrganizationGUI.Classes; using System.Collections.ObjectModel; using System.Diagnostics; using Microsoft.Win32; using System.Windows.Controls; using OrganizationGUI_2.DialogWindows; using OrganizationGUI_2.DialogWindows.WorkerDialogs; using System.Collections.Generic; using System.Linq; namespace OrganizationGUI_2 { /// <summary> /// Программа реализует структуру Организации и представляет ее /// в графическом интерфейсе с использованием WPF. /// В директории с программой находится файл organization.xml с данными об /// организации "Организация", который можно загрузить, /// выполнив Файл -> Загрузить, и выбрав данный xml-файл. /// Также можно произвести выгрузку данных организации в xml-файл, выполнив /// Файл -> Выгрузить. /// Сортировка сотрудников по различным полям проискходит через меню Сортировать работников. /// Редактирование департаментов и работников происходит через контекстные меню /// соответствующих элементов окна (TreeView, ListView). /// Управленцев (директор организации, его заместитель и начальники департаментов) /// можно только редактировать (перемещать запрещено). /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); #region Наполнение структуры организации из кода //ObservableCollection<Organization> orgs; //orgs = returnAnyOrganizationCollection(); //organizationTree.ItemsSource = orgs; //DataContext = orgs[0]; #endregion // Наполнение структуры организации из кода } #region Меню "Файл" /// <summary> /// Выгрузка (сериализация) структуры организации (обработчик на нажатие меню "Выгрузить") /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MenuItemUnload_Click(object sender, RoutedEventArgs e) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Xml file (*.xml)|*.xml"; saveFileDialog.InitialDirectory = Environment.CurrentDirectory; if (saveFileDialog.ShowDialog() == true) { // Если организация существует, то выгружаем данные if (organizationTree.ItemsSource != null) { (organizationTree.ItemsSource as ObservableCollection<Organization>)[0] .xmlOrganizationSerializer(saveFileDialog.FileName); } } } /// <summary> /// Загрузка (десериализация) структуры организации (обработчик на нажатие меню "Загрузить") /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MenuItemLoad_Click(object sender, RoutedEventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Xml file (*.xml)|*.xml"; openFileDialog.InitialDirectory = @"c:\temp\"; if (openFileDialog.ShowDialog() == true) { // Если организация существует, то спрашиваем о дальнейшей загрузке новой if (!organizationTree.Items.IsEmpty) { var answer = MessageBox.Show("Структура организации не пуста! Вы уверены, что хотите перезаписать данные?", "Загрузка", MessageBoxButton.YesNo, MessageBoxImage.Warning); if (answer == MessageBoxResult.No) { return; } else if (answer == MessageBoxResult.Yes) { Debug.WriteLine("ПЕРЕЗАПИСЬ ТЕКУЩЕЙ СТРУКТУРЫ!"); // Очищаем структуру (organizationTree.ItemsSource as ObservableCollection<Organization>).Clear(); } } Organization org = Organization.xmlOrganizationDeserializer(openFileDialog.FileName); ObservableCollection<Organization> orgs = new ObservableCollection<Organization>(); orgs.Add(org); organizationTree.ItemsSource = orgs; DataContext = orgs[0]; } } /// <summary> /// Выход из программы /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MenuItemExit_Click(object sender, RoutedEventArgs e) { this.Close(); } #endregion #region Меню "Сортировать работников" /// <summary> /// Сортировка по возрасту работника /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MenuSortByAge_Click(object sender, RoutedEventArgs e) { (organizationTree.SelectedItem as Department)?.sortedWorkers(Department.FIELDSORT.AGE); } /// <summary> /// Сортировка по Id работника /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MenuSortById_Click(object sender, RoutedEventArgs e) { (organizationTree.SelectedItem as Department)?.sortedWorkers(); } /// <summary> /// Сортировка по имени работника /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MenuSortByName_Click(object sender, RoutedEventArgs e) { (organizationTree.SelectedItem as Department)?.sortedWorkers(Department.FIELDSORT.NAME); } /// <summary> /// Сортировка по фамилии работника /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MenuSortByLName_Click(object sender, RoutedEventArgs e) { (organizationTree.SelectedItem as Department)?.sortedWorkers(Department.FIELDSORT.LNAME); } /// <summary> /// Сортировка сначала по имени потом по фамилии работника /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MenuSortByNameAndLName_Click(object sender, RoutedEventArgs e) { (organizationTree.SelectedItem as Department)?.sortedWorkers(Department.FIELDSORT.NAME_LNAME); } /// <summary> /// Сортировка сначала по фамилии потом по имени работника /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MenuSortByLNameAndName_Click(object sender, RoutedEventArgs e) { (organizationTree.SelectedItem as Department)?.sortedWorkers(Department.FIELDSORT.LNAME_NAME); } #endregion // Обработчики меню сортировки #region Контекстные меню /// <summary> /// Обработчик контекстного меню дерева организации /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MenuItemTreeView_Click(object sender, RoutedEventArgs e) { // Выбрано меню "Добавить" if ((sender as MenuItem).Header.ToString() == "Новый") { if (organizationTree.SelectedItem != null) { DialogNewDepartment dlgNewDep = new DialogNewDepartment(); if (dlgNewDep.ShowDialog() == true) { if (organizationTree.SelectedItem is Organization) { (organizationTree.SelectedItem as Organization)? .addDepartment(new Department(dlgNewDep.tboxDepName.Text, DataContext as Organization)); } else { (organizationTree.SelectedItem as Department)? .addDepartment(new Department(dlgNewDep.tboxDepName.Text, DataContext as Organization)); } } } } // Выбрано меню "Переместить" if ((sender as MenuItem).Header.ToString() == "Переместить") { if (organizationTree.SelectedItem is Department) { // Создаем словарь Идентификатор - Наименование департамента Dictionary<int, string> dicIdNameDeparts = new Dictionary<int, string>(); // Вспомогательная коллекция без вложенных департаментов (разность коллекций) // чтобы в дальнейшем нельзя было переместить департамент в своего "потомка" IEnumerable<Department> depsExcept = (DataContext as Organization).AllDepartments .Except((organizationTree.SelectedItem as Department).AllSubDepartments.ToList()); // Заполняем словарь foreach (Department dep in depsExcept) { dicIdNameDeparts.Add(dep.Id, dep.Name); } if (organizationTree.SelectedItem is Department) { DialogTransferDepartment dlgTransferDep = new DialogTransferDepartment((organizationTree.SelectedItem as Department).Id, (organizationTree.SelectedItem as Department).Name, dicIdNameDeparts, (DataContext as Organization).Name); if (dlgTransferDep.ShowDialog() == true) { Department currentDep = organizationTree.SelectedItem as Department; Department tmpDep = new Department(currentDep.Name, currentDep.LocalBoss, currentDep.Departments, currentDep.Workers, DataContext as Organization); // Удаляем текущий департамент (DataContext as Organization).removeDepartment(currentDep); // Если переместить департамент необходимо в корень организации if (dlgTransferDep.ToDepID == 0) { // Добавляем департамент в коллекцию департаментов организации (DataContext as Organization).addDepartment(tmpDep); } else { // Добавляем департамент в нужную коллекцию (DataContext as Organization).getDepartmentFromId(dlgTransferDep.ToDepID) .addDepartment(tmpDep); } } } } } // Выбрано меню "Редактировать" if ((sender as MenuItem).Header.ToString() == "Редактировать") { if (organizationTree.SelectedItem is Department) { DialogEditDepartment dlgEditDep = new DialogEditDepartment((organizationTree.SelectedItem as Department).Name); if (dlgEditDep.ShowDialog() == true) { (organizationTree.SelectedItem as Department).Name = dlgEditDep.tboxDepName.Text; } } } // Выбрано меню "Удалить" if ((sender as MenuItem).Header.ToString() == "Удалить") { if (organizationTree.SelectedItem is Department) { var answer1 = MessageBox.Show("Вы уверены, что хотите удалить департамент и всех его сотрудников?", "Удаление департамента", MessageBoxButton.YesNo, MessageBoxImage.Question); if (answer1 == MessageBoxResult.Yes) { var answer2 = MessageBox.Show("Возможно у сотрудников ипотека! Вы хорошо подумали?", "Удаление департамента", MessageBoxButton.YesNo, MessageBoxImage.Question); if (answer2 == MessageBoxResult.Yes) { MessageBox.Show("Удаляем..."); (DataContext as Organization)?.removeDepartment(organizationTree.SelectedItem as Department); } } } } } /// <summary> /// Обработчик контекстного меню списков сотрудников и интернов /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MenuItemWorkList_Click(object sender, RoutedEventArgs e) { // Выбрано меню "Добавить" if ((sender as MenuItem).Header.ToString() == "Добавить") { if (organizationTree.SelectedItem is Department) { // Работаем со списком сотрудников if (employeesList.SelectedItem != null) { Employee employee = new Employee(); DialogNewWorker dlgNewEmployee = new DialogNewWorker(employee); if (dlgNewEmployee.ShowDialog() == true) { (organizationTree.SelectedItem as Department)? .addWorker(employee); // добавляем сотрудника } } // Работаем со списком интернов if (internsList.SelectedItem != null) { Intern intern = new Intern(); DialogNewWorker dlgNewIntern = new DialogNewWorker(intern); if (dlgNewIntern.ShowDialog() == true) { (organizationTree.SelectedItem as Department)? .addWorker(intern); // добавляем интерна } } } } // Выбрано меню "Переместить" if ((sender as MenuItem).Header.ToString() == "Переместить") { if (organizationTree.SelectedItem is Department) { DialogTransferWorker dlgTransferWorker = new DialogTransferWorker(DataContext as Organization); if (dlgTransferWorker.ShowDialog() == true) { // Был выделен сотрудник if (employeesList.SelectedItem != null) { Employee currentEmployee = employeesList.SelectedItem as Employee; // Создаем временного сотрудника для перемещения Employee tmpEmployee = new Employee(currentEmployee.Name, currentEmployee.LastName, currentEmployee.BirthDate, currentEmployee.NamePost, currentEmployee.Salary / 168); (DataContext as Organization).getDepartmentFromId(dlgTransferWorker.ToDepID) .addWorker(tmpEmployee); // Удаляем сотрудника по Id (organizationTree.SelectedItem as Department).removeWorker(currentEmployee.Id); } // Был выделен интерн if (internsList.SelectedItem != null) { Intern currentIntern = internsList.SelectedItem as Intern; // Создаем временного сотрудника для перемещения Intern tmpIntern = new Intern(currentIntern.Name, currentIntern.LastName, currentIntern.BirthDate, currentIntern.Salary); (DataContext as Organization).getDepartmentFromId(dlgTransferWorker.ToDepID) .addWorker(tmpIntern); // Удаляем сотрудника по Id (organizationTree.SelectedItem as Department).removeWorker(currentIntern.Id); } } } } // Выбрано меню "Редактировать" if ((sender as MenuItem).Header.ToString() == "Редактировать") { if (organizationTree.SelectedItem is Department) { // Работаем со списком сотрудников if (employeesList.SelectedItem != null) { Employee employee = employeesList.SelectedItem as Employee; DialogEditWorker dlgEditEmployee = new DialogEditWorker(employee); dlgEditEmployee.ShowDialog(); employee.OnPropertyChanged("Age"); // обновляем отображение возраста } // Работаем со списком интернов if (internsList.SelectedItem != null) { Intern intern = internsList.SelectedItem as Intern; DialogEditWorker dlgEditIntern = new DialogEditWorker(intern); dlgEditIntern.ShowDialog(); intern.OnPropertyChanged("Age"); // обновляем отображение возраста } } // Обновляем интерфейс (organizationTree.SelectedItem as Department).refreshBigBossSalary(); (organizationTree.SelectedItem as Department).refreshLocalBossSalary(); } // Выбрано меню "Удалить" if ((sender as MenuItem).Header.ToString() == "Удалить") { // Работаем со списком сотрудников if (employeesList.SelectedItem != null) { (organizationTree.SelectedItem as Department)? .removeWorker((employeesList.SelectedItem as Worker).Id); // удаление сотрудника с переданным Id } // Работаем со списком интернов if (internsList.SelectedItem != null) { (organizationTree.SelectedItem as Department)? .removeWorker((internsList.SelectedItem as Worker).Id); // удаление интерна с переданным Id } } } /// <summary> /// При потере фокуса снимаем выделение элемента /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void employeesList_LostFocus(object sender, RoutedEventArgs e) { employeesList.UnselectAll(); } /// <summary> /// При потере фокуса снимаем выделение элемента /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void internsList_LostFocus(object sender, RoutedEventArgs e) { internsList.UnselectAll(); } #endregion // Контекстные меню /// <summary> /// Наполняет структуру организации /// </summary> /// <returns>Организация</returns> private ObservableCollection<Organization> returnAnyOrganizationCollection() { Director director = Director.getInstance("Олег", "Важный", new DateTime(1961, 1, 1)); AssociateDirector assDirector = AssociateDirector.getInstance("Игорь", "Чутьменееважный", new DateTime(1962, 2, 2)); // Создание организации Organization organization = new Organization("Организация", director, assDirector); #region Департамент 1 DepBoss depBoss1 = new DepBoss("Михаил", "Руководящий", new DateTime(1959, 7, 8)); ObservableCollection<Worker> workers1 = new ObservableCollection<Worker>(); workers1.Add(depBoss1); workers1.Add(new Employee("Шарап", "Сишарпов", new DateTime(1974, 6, 17), "Главный программист", 1_000)); workers1.Add(new Employee("Иван", "Иванов", new DateTime(1975, 7, 18), "Программист", 800)); workers1.Add(new Employee("Василий", "Васильев", new DateTime(1976, 8, 19), "Программист", 800)); workers1.Add(new Employee("Петр", "Петров", new DateTime(1977, 9, 22), "Программист", 800)); workers1.Add(new Employee("Игорь", "Федоров", new DateTime(1978, 10, 24), "Системный администратор", 600)); workers1.Add(new Employee("Матвей", "Павлов", new DateTime(1979, 11, 26), "Инженер", 650)); workers1.Add(new Employee("Марина", "Маринина", new DateTime(1980, 12, 27), "Инженер", 650)); workers1.Add(new Intern("Игорь", "Новичков", new DateTime(1999, 10, 12), 50_000)); workers1.Add(new Intern("Иван", "Непонимающий", new DateTime(1996, 8, 16), 50_000)); // Создание департамента 1 Department departament1 = new Department("Департамент 1", depBoss1, workers1, organization); #region Департамент 11 DepBoss depBoss11 = new DepBoss("Августина", "Анитсугва", new DateTime(1977, 7, 7)); ObservableCollection<Worker> workers11 = new ObservableCollection<Worker>(); workers11.Add(depBoss11); workers11.Add(new Employee("Иван", "Иванов", new DateTime(1973, 5, 6), "Программист", 750)); workers11.Add(new Employee("Вячеслав", "Васильев", new DateTime(1974, 5, 7), "Системный администратор", 550)); workers11.Add(new Employee("Федор", "Федоров", new DateTime(1975, 5, 8), "Инженер", 600)); // Создание департамента 11 Department departament11 = new Department("Департамент 11", depBoss11, workers11, organization); #endregion // Департамент 11 #region Департамент 12 DepBoss depBoss12 = new DepBoss("Сократ", "Платонов", new DateTime(1988, 8, 7)); ObservableCollection<Worker> workers12 = new ObservableCollection<Worker>(); workers12.Add(depBoss12); workers12.Add(new Employee("Павел", "Плюсплюсов", new DateTime(1971, 1, 3), "Главный программист", 900)); workers12.Add(new Employee("Иван", "Иванов", new DateTime(1971, 1, 3), "Программист", 750)); workers12.Add(new Employee("Василий", "Васильев", new DateTime(1972, 4, 3), "Программист", 750)); workers12.Add(new Employee("Петр", "Петров", new DateTime(1973, 2, 3), "Системный администратор", 550)); workers12.Add(new Employee("Федор", "Федоров", new DateTime(1974, 3, 3), "Инженер", 600)); workers12.Add(new Intern("Василий", "Ябсделал", new DateTime(2000, 2, 26), 40_000)); // Создание департамента 12 Department departament12 = new Department("Департамент 12", depBoss12, workers12, organization); #region Департамент 121 DepBoss depBoss121 = new DepBoss("Платон", "Сократов", new DateTime(1980, 3, 15)); ObservableCollection<Worker> workers121 = new ObservableCollection<Worker>(); workers121.Add(depBoss121); workers121.Add(new Employee("Кирилл", "Иванов", new DateTime(1972, 2, 25), "Программист", 750)); workers121.Add(new Employee("Павел", "Петров", new DateTime(1972, 4, 28), "Системный администратор", 550)); workers121.Add(new Employee("Евгений", "Федоров", new DateTime(1972, 3, 30), "Инженер", 600)); // Создание департамента 121 Department departament121 = new Department("Департамент 121", depBoss121, workers121, organization); #endregion // Департамент 121 #endregion // Департамент 12 // Добавление поддепартаментов в департаменты departament12.addDepartment(departament121); departament1.addDepartment(departament11); departament1.addDepartment(departament12); #endregion // Департамент 1 #region Департамент 2 DepBoss depBoss2 = new DepBoss("Юрий", "Возглавляющий", new DateTime(1959, 7, 8)); ObservableCollection<Worker> workers2 = new ObservableCollection<Worker>(); workers2.Add(depBoss2); workers2.Add(new Employee("Платон", "Питонов", new DateTime(1977, 09, 09), "Главный программист", 1_000)); workers2.Add(new Employee("Сергей", "Иванов", new DateTime(1978, 10, 09), "Программист", 800)); workers2.Add(new Employee("Евлампий", "Васильев", new DateTime(1979, 11, 09), "Программист", 800)); workers2.Add(new Employee("Галина", "Петрова", new DateTime(1980, 12, 15), "Программист", 800)); workers2.Add(new Employee("Юлия", "Юлина", new DateTime(1981, 09, 10), "Программист", 800)); workers2.Add(new Employee("Евгений", "Евгеньев", new DateTime(1982, 09, 18), "Программист", 800)); workers2.Add(new Employee("Федор", "Федоров", new DateTime(1983, 05, 12), "Системный администратор", 600)); workers2.Add(new Employee("Иван", "Сисадминский", new DateTime(1984, 06, 30), "Системный администратор", 600)); workers2.Add(new Employee("Владимир", "Владимиров", new DateTime(1985, 11, 21), "Инженер", 650)); workers2.Add(new Employee("Галина", "Галинина", new DateTime(1986, 10, 15), "Инженер", 650)); workers2.Add(new Intern("Егор", "Этокаковый", new DateTime(1995, 6, 5), 50_000)); workers2.Add(new Intern("Анна", "Немогущая", new DateTime(1994, 11, 2), 50_000)); workers2.Add(new Intern("Платон", "Почемучин", new DateTime(1994, 11, 2), 50_000)); // Создание департамента 2 Department departament2 = new Department("Департамент 2", depBoss2, workers2, organization); #region Департамент 21 DepBoss depBoss21 = new DepBoss("Павел", "Павлов", new DateTime(1991, 2, 14)); ObservableCollection<Worker> workers21 = new ObservableCollection<Worker>(); workers21.Add(depBoss21); workers21.Add(new Employee("Джон", "Джавин", new DateTime(1971, 01, 03), "Главный программист", 900)); workers21.Add(new Employee("Константин", "Иванов", new DateTime(1975, 07, 07), "Программист", 750)); workers21.Add(new Employee("Алексей", "Васильев", new DateTime(1976, 07, 08), "Программист", 750)); workers21.Add(new Employee("Петр", "Петров", new DateTime(1977, 07, 09), "Программист", 750)); workers21.Add(new Employee("Федор", "Федоров", new DateTime(1978, 07, 10), "Системный администратор", 550)); workers21.Add(new Employee("Евгения", "Евгенина", new DateTime(1968, 07, 11), "Инженер", 600)); workers21.Add(new Employee("Илона", "Давыдная", new DateTime(1975, 01, 16), "Инженер", 600)); workers21.Add(new Intern("Василиса", "Немудрая", new DateTime(1997, 09, 12), 40_000)); // Создание департамента 21 Department departament21 = new Department("Департамент 21", depBoss21, workers21, organization); #region Департамент 211 DepBoss depBoss211 = new DepBoss("Иван", "Иванов", new DateTime(1995, 8, 11)); ObservableCollection<Worker> workers211 = new ObservableCollection<Worker>(); workers211.Add(depBoss211); workers211.Add(new Employee("Иван", "Иванов", new DateTime(1975, 01, 02), "Главный программист", 900)); workers211.Add(new Employee("Иван", "Иванов", new DateTime(1979, 08, 10), "Программист", 750)); workers211.Add(new Employee("Василий", "Васильев", new DateTime(1976, 02, 11), "Программист", 750)); workers211.Add(new Employee("Федор", "Петров", new DateTime(1977, 08, 12), "Системный администратор", 550)); workers211.Add(new Employee("Федор", "Федоров", new DateTime(1978, 09, 13), "Инженер", 600)); workers211.Add(new Employee("Петр", "Петров", new DateTime(1985, 12, 20), "Инженер", 600)); workers211.Add(new Intern("Акакий", "Акаконов", new DateTime(1993, 11, 07), 40_000)); // Создание департамента 211 Department departament211 = new Department("Департамент 211", depBoss211, workers211, organization); #region Департамент 2111 DepBoss depBoss2111 = new DepBoss("Сергей", "Сергеев", new DateTime(1986, 1, 2)); ObservableCollection<Worker> workers2111 = new ObservableCollection<Worker>(); workers2111.Add(depBoss2111); workers2111.Add(new Employee("Кирилл", "Иванов", new DateTime(1972, 02, 25), "Программист", 750)); workers2111.Add(new Employee("Павел", "Петров", new DateTime(1972, 04, 28), "Системный администратор", 550)); workers2111.Add(new Intern("Юлия", "Июльская", new DateTime(1995, 11, 17), 40_000)); //Создание департамента 2111 Department departament2111 = new Department("Департамент 2111", depBoss2111, workers2111, organization); #endregion // Департамент 2111 #endregion // Департамент 211 #region Департамент 212 DepBoss depBoss212 = new DepBoss("Артем", "Артемов", new DateTime(1993, 4, 15)); ObservableCollection<Worker> workers212 = new ObservableCollection<Worker>(); workers212.Add(depBoss212); workers212.Add(new Employee("Кирилл", "Иванов", new DateTime(1972, 02, 25), "Программист", 750)); workers212.Add(new Employee("Павел", "Петров", new DateTime(1972, 04, 28), "Системный администратор", 550)); workers212.Add(new Employee("Евгений", "Федоров", new DateTime(1972, 03, 30), "Инженер", 600)); // Создание департамента 212 Department departament212 = new Department("Департамент 212", depBoss212, workers212, organization); #endregion // Департамент 212 #endregion // Департамент 21 #region Департамент 22 DepBoss depBoss22 = new DepBoss("Ада", "Байрон", new DateTime(1972, 12, 10)); ObservableCollection<Worker> workers22 = new ObservableCollection<Worker>(); workers22.Add(depBoss22); workers22.Add(new Employee("Иван", "Иванов", new DateTime(1979, 08, 10), "Программист", 750)); workers22.Add(new Employee("Василий", "Васильев", new DateTime(1976, 02, 11), "Программист", 750)); workers22.Add(new Employee("Федор", "Петров", new DateTime(1977, 08, 12), "Системный администратор", 550)); workers22.Add(new Employee("Федор", "Федоров", new DateTime(1978, 09, 13), "Инженер", 600)); workers22.Add(new Intern("Николай", "Недумающий", new DateTime(1998, 07, 02), 40_000)); // Создание департамента 22 Department departament22 = new Department("Департамент 22", depBoss22, workers22, organization); #endregion // Департамент 22 #region Департамент 23 DepBoss depBoss23 = new DepBoss("Людмила", "Нелюдимая", new DateTime(1989, 5, 24)); ObservableCollection<Worker> workers23 = new ObservableCollection<Worker>(); workers23.Add(depBoss23); workers23.Add(new Employee("Иван", "Иванов", new DateTime(1971, 01, 03), "Программист", 750)); workers23.Add(new Intern("Роман", "Ждущий", new DateTime(1995, 10, 27), 40_000)); // Создание департамента 23 Department departament23 = new Department("Департамент 23", depBoss23, workers23, organization); #region Департамента 231 DepBoss depBoss231 = new DepBoss("Ираклий", "Икаров", new DateTime(1995, 8, 11)); ObservableCollection<Worker> workers231 = new ObservableCollection<Worker>(); workers231.Add(depBoss231); workers231.Add(new Employee("Евстигней", "Старорусский", new DateTime(1958, 01, 01), "Программист", 750)); workers231.Add(new Employee("Артур", "Молодой", new DateTime(1957, 12, 31), "Системный администратор", 550)); // Создание департамента 231 Department departament231 = new Department("Департамент 231", depBoss231, workers231, organization); #endregion // Департамента 231 #region Департамент 232 DepBoss depBoss232 = new DepBoss("Аида", "Шестьдесятчетырная", new DateTime(1979, 10, 6)); ObservableCollection<Worker> workers232 = new ObservableCollection<Worker>(); workers232.Add(depBoss232); workers232.Add(new Employee("Анатолий", "Шарящий", new DateTime(1975, 01, 01), "Программист", 750)); workers232.Add(new Employee("Петр", "Вопрошающий", new DateTime(1969, 02, 02), "Программист", 750)); workers232.Add(new Employee("Иван", "Иванов", new DateTime(1995, 10, 19), "Системный администратор", 550)); // Создание департамента 232 Department departament232 = new Department("Департамент 232", depBoss232, workers232, organization); #endregion #endregion // Департамент 23 // Добавление поддепартаментов в департаменты departament211.addDepartment(departament2111); departament21.addDepartment(departament211); departament21.addDepartment(departament212); departament23.addDepartment(departament231); departament23.addDepartment(departament232); departament2.addDepartment(departament21); departament2.addDepartment(departament22); departament2.addDepartment(departament23); #endregion // Департамент 2 // Добавление в организацию департаментов с их поддепартаментами organization.addDepartment(departament1); organization.addDepartment(departament2); ObservableCollection<Organization> orgs = new ObservableCollection<Organization>(); orgs.Add(organization); return orgs; } /// <summary> /// Перемещение главного окна за любую его часть /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainWindow_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e) { DragMove(); } } } <file_sep>using System; using System.Windows; namespace OrganizationGUI_2.DialogWindows { /// <summary> /// Interaction logic for DialogEditDepartment.xaml /// </summary> public partial class DialogEditDepartment : Window { public DialogEditDepartment(string depName) { InitializeComponent(); tboxDepName.Text = depName; tboxDepName.Focus(); tboxDepName.SelectAll(); } /// <summary> /// Обработчик нажатия кнопки подтверждения /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Accept_Click(object sender, RoutedEventArgs e) { // Если в текстовом поле есть непробельные символы if (tboxDepName.Text.Trim() != String.Empty) DialogResult = true; } } } <file_sep>using System; namespace OrganizationGUI.Classes { /// <summary> /// Класс директора (синглтон, т.к. директор в организации один) /// </summary> public class Director : Worker { #region Constructors /// <summary> /// Конструктор по умолчанию /// </summary> protected Director() { } /// <summary> /// Конструктор /// </summary> /// <param name="name">Имя</param> /// <param name="lastName">Фамилия</param> /// <param name="birthDate">Дата рождения</param> /// <param name="salary">Зарплата</param> protected Director(string name, string lastName, DateTime birthDate) { Name = name; LastName = lastName; BirthDate = birthDate; Id = 1; } #endregion // Constructors #region Properties /// <summary> /// Имя директора /// </summary> public override string Name { get { return name; } set { name = value; OnPropertyChanged("Name"); } } /// <summary> /// Фамилия директора /// </summary> public override string LastName { get { return lastName; } set { lastName = value; OnPropertyChanged("LastName"); } } /// <summary> /// Дата рождения директора /// </summary> public override DateTime BirthDate { get { return birthDate; } set { birthDate = value; OnPropertyChanged("BirthDate"); } } /// <summary> /// Идентификатор директора /// </summary> public override int Id { get; } #endregion // Properties #region Methods public static Director getInstance(string name, string lastName, DateTime birthDate) { if (instance == null) instance = new Director(name, lastName, birthDate); return instance; } /// <summary> /// Информация о директоре /// </summary> /// <returns>String: Id, Name, LastName, BirthDate, Salary</returns> public override string ToString() { return $"| Идентификатор директора: { Id } | " + $"Имя директора: { Name } | " + $"Фамилия директора: { LastName } | " + $"Дата рождения директора: { BirthDate } | "; } #endregion // Methods #region Fields private string name; // имя директора private string lastName; // фамилия директора private DateTime birthDate; // дата рождения директора private static Director instance; // поле (инстанс) для синглтона #endregion } } <file_sep>using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Diagnostics; using System.Linq; using System.Collections.Generic; namespace OrganizationGUI.Classes { /// <summary> /// Департамент /// </summary> public class Department : INotifyPropertyChanged { #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged([CallerMemberName] string prop = "") { if (PropertyChanged != null) PropertyChanged.Invoke(this, new PropertyChangedEventArgs(prop)); } #endregion // INotifyPropertyChanged /// <summary> /// Поля для сортировки /// </summary> public enum FIELDSORT { ID = 1, // для сортировки по идентификатору сотрудника AGE, // для сортировки по возрасту NAME, // для сортировки по имени LNAME, // для сортировки по фамилии NAME_LNAME, // для сортировки сначала по имени, потом по фамилии LNAME_NAME, // для сортировки сначала по фамилии, потом по имени } #region Constructors /// <summary> /// Конструктор по умолчанию /// </summary> public Department() { Id = ++countDep; workers = new ObservableCollection<Worker>(); departments = new ObservableCollection<Department>(); Org = new Organization(); } /// <summary> /// Конструктор 1 /// </summary> /// <param name="name">Наименование департамента</param> /// <param name="org">Организация включающая департамент</param> public Department(string name, Organization org) { Id = ++countDep; Name = name; LocalBoss = new DepBoss(); workers = new ObservableCollection<Worker>(); departments = new ObservableCollection<Department>(); Org = org; } /// <summary> /// Конструктор 2 /// </summary> /// <param name="name">Наименование департамента</param> /// <param name="localBoss">Начальник департамента</param> /// <param name="org">Организация включающая департамент</param> public Department(string name, DepBoss localBoss, Organization org) { Id = ++countDep; Name = name; LocalBoss = localBoss; workers = new ObservableCollection<Worker>(); departments = new ObservableCollection<Department>(); Org = org; } /// <summary> /// Конструктор 3.1 /// </summary> /// <param name="name">Наименование департамента</param> /// <param name="localBoss">Начальник департамента</param> /// <param name="departments">Коллекция поддепартаментов</param> /// <param name="workers">Коллекция работников департамента</param> /// <param name="org">Организация включающая департамент</param> public Department(string name, DepBoss localBoss, ObservableCollection<Department> departments, ObservableCollection<Worker> workers, Organization org) { Id = ++countDep; Name = name; LocalBoss = localBoss; this.workers = workers; this.departments = departments; Org = org; } /// <summary> /// Конструктор 3.2 /// </summary> /// <param name="name">Наименование департамента</param> /// <param name="localBoss">Начальник департамента</param> /// <param name="workers">Коллекция работников департамента</param> /// <param name="org">Организация включающая департамент</param> public Department(string name, DepBoss localBoss, ObservableCollection<Worker> workers, Organization org) : this(name, localBoss, new ObservableCollection<Department>(), workers, org) { } /// <summary> /// Конструктор 4 /// </summary> /// <param name="name">Наименование департамента</param> /// <param name="departments">Департаменты в текущем департаменте</param> public Department(string name, DepBoss localBoss, ObservableCollection<Department> departments) { Id = ++countDep; Name = name; LocalBoss = localBoss; this.workers = new ObservableCollection<Worker>(); this.departments = departments; Org = new Organization(this); } /// <summary> /// Конструктор 5 /// </summary> /// <param name="name"></param> /// <param name="workers"></param> public Department(string name, DepBoss localBoss, ObservableCollection<Worker> workers) { Id = ++countDep; Name = name; LocalBoss = localBoss; this.workers = workers; this.departments = new ObservableCollection<Department>(); Org = new Organization(this); } #endregion // Constructors #region Properties /// <summary> /// Идентификатор департамента /// </summary> public int Id { get; } /// <summary> /// Название департамента /// </summary> public string Name { get { return name; } set { name = value; OnPropertyChanged("Name"); } } /// <summary> /// Начальник департамента /// </summary> public DepBoss LocalBoss { get; set; } /// <summary> /// Организация в которую входит департамент /// </summary> public Organization Org { get; private set; } /// <summary> /// Возвращает коллекцию поддепартаментов /// </summary> public ObservableCollection<Department> Departments { get { return departments ?? new ObservableCollection<Department>(); } } /// <summary> /// Все поддепартаменты /// </summary> public List<Department> AllSubDepartments { get { // Все поддепартаменты текущего департамента allSubDepartments = new List<Department>(); makeAllSubDepartments(Departments.ToList()); return allSubDepartments; } } /// <summary> /// Возвращает коллекцию работников в текущем департаменте /// </summary> public ObservableCollection<Worker> Workers { get { return workers ?? new ObservableCollection<Worker>(); } } /// <summary> /// Возвращает коллекцию сотрудников в текущем департаменте /// </summary> public ObservableCollection<Employee> Employees { get { ObservableCollection<Employee> emps = new ObservableCollection<Employee>(); foreach (var emp in workers) { if (emp is Employee) emps.Add(emp as Employee); } return emps ?? new ObservableCollection<Employee>(); } } /// <summary> /// Возвращает коллекцию интернов в текущем департаменте /// </summary> public ObservableCollection<Intern> Interns { get { ObservableCollection<Intern> interns = new ObservableCollection<Intern>(); foreach (var intern in workers) { if (intern is Intern) interns.Add(intern as Intern); } return interns ?? new ObservableCollection<Intern>(); } } /// <summary> /// Количество работников в департаменте /// </summary> public int CountEmployees { get { int count = 0; foreach (var worker in workers) { if (worker is Employee) ++count; // подсчет рабочих } return count; } } /// <summary> /// Количество интернов в департаменте /// </summary> public int CountInterns { get { int count = 0; foreach (var worker in workers) { if (worker is Intern) ++count; // подсчет интернов } return count; } } /// <summary> /// Зарплата начальника департамента (15% от суммы зарплат всех подчиненных, /// но не менее 160000 р.) /// </summary> public double LocalBossSalary { get { if (LocalBoss.Name != null) { double salary = salaryDepWorkers() * 0.15; salary = Math.Round(salary); // округляем до целых return (salary < 160_000) ? 160_000 : salary; } else { return 0; } } } /// <summary> /// Количество поддепартаментов в департаменте /// </summary> public int CountDepartments { get { return Departments.Count; } } #endregion // Properties #region Methods /// <summary> /// Добавление департамента в коллекцию поддепартаментов /// </summary> /// <param name="dep">Департамент</param> public void addDepartment(Department dep) { departments.Add(dep); refreshView(); refreshLocalBossSalary(); refreshBigBossSalary(); } /// <summary> /// Добавление работника в коллекцию работников /// </summary> /// <param name="worker">Работник</param> public void addWorker(Worker worker) { workers.Add(worker); refreshView(); refreshLocalBossSalary(); refreshBigBossSalary(); } /// <summary> /// Удаляет работника из департамента по идентификатору /// </summary> /// <param name="id">Идентификатор работника</param> public void removeWorker(int id) { workers.Remove(returnWorkerDepById(id)); refreshView(); refreshLocalBossSalary(); refreshBigBossSalary(); } /// <summary> /// Вспомогательный метод, возвращает работника департамента по идентификатору /// </summary> /// <param name="id">Идентификатор работника</param> /// <returns>Работник</returns> private Worker returnWorkerDepById(int id) { return workers.Where(item => item.Id == id).First<Worker>(); } /// <summary> /// Вспомогательный метод. Создаем коллекцию всех поддепартаментов /// </summary> /// <param name="deps">Коллекция департаментов</param> private static void makeAllSubDepartments(List<Department> deps) { for (int i = 0; i < deps.Count; ++i) { allSubDepartments.Add(deps[i]); makeAllSubDepartments(deps[i].Departments.ToList()); } } /// <summary> /// Обновление интерфейса для свойств Employees и CountEmployees /// Interns и CountInterns /// </summary> public void refreshView() { OnPropertyChanged("Interns"); OnPropertyChanged("CountInterns"); OnPropertyChanged("Employees"); OnPropertyChanged("CountEmployees"); } /// <summary> /// Обновление интерфейса для свойства LocalBossSalary /// </summary> public void refreshLocalBossSalary() { OnPropertyChanged("LocalBossSalary"); } /// <summary> /// Обновление интерфейса для свойств в организации DirSalary и AssociateDirSalary /// </summary> public void refreshBigBossSalary() { Org.OnPropertyChanged("DirSalary"); Org.OnPropertyChanged("AssociateDirSalary"); } /// <summary> /// Рекурсивный метод, расчет суммы зарплат всех работников департамента (и его поддепартаментов) /// </summary> /// <returns>Сумма зарплат</returns> public double salaryDepWorkers() { int indexDepartment = CountDepartments; // количество поддепартаментов double sum = salarySumWorkers(); for (int i = 0; i < indexDepartment; ++i) { // Зарплаты начальников поддепартаментов и остальных работников поддепартамента (рекурсия) sum += Departments[i].LocalBossSalary + Departments[i].salaryDepWorkers(); } return sum; } /// <summary> /// Сумма зарплат всех работников текущего департамента /// (вспомогательный метод для метода salaryDepWorkers()) /// </summary> /// <returns>Сумма</returns> private int salarySumWorkers() { int salarySum = 0; foreach (var worker in workers) { salarySum += (worker as ISalary)?.Salary ?? 0; } return salarySum; } #region Sorting /// <summary> /// Сортирует работников в организации по различным критериям (6 критериев) /// </summary> /// <param name="critSort">Критерии сортировки: FIELDSORT.ID - по идентификатору работника (по умолчанию), /// FIELDSORT.AGE - по возрасту, /// FIELDSORT.NAME - по имени, /// FIELDSORT.LNAME - по фамилии, /// FIELDSORT.NAME_LNAME - сначала по имени, потом по фамилии, /// FIELDSORT.LNAME_NAME - сначала по фамилии, потом по имени</param> /// <returns>Коллекция работников, отсортированных по выбранному критерию</returns> public void sortedWorkers(FIELDSORT critSort = FIELDSORT.ID) { switch (critSort) { case FIELDSORT.ID: // Сортируем всех работников по идентификатору workers = new ObservableCollection<Worker>(workers.OrderBy(item => item.Id).ToList()); break; case FIELDSORT.AGE: // Сортируем всех работников по возрасту workers = new ObservableCollection<Worker>(workers.OrderBy(item => item.Age).ToList()); break; case FIELDSORT.NAME: // Сортируем всех работников по имени workers = new ObservableCollection<Worker>(workers.OrderBy(item => item.Name).ToList()); break; case FIELDSORT.LNAME: // Сортируем всех работников по фамилии workers = new ObservableCollection<Worker>(workers.OrderBy(item => item.LastName).ToList()); break; case FIELDSORT.NAME_LNAME: // Сортируем всех работников по имени и фамилии workers = new ObservableCollection<Worker>(workers.OrderBy(item => item.Name).ThenBy(item => item.LastName).ToList()); break; case FIELDSORT.LNAME_NAME: // Сортируем всех работников по фамилии и имени workers = new ObservableCollection<Worker>(workers.OrderBy(item => item.LastName).ThenBy(item => item.Name).ToList()); break; } refreshView(); // обновляем интерфейс после сортировки } #endregion // Sorting /// <summary> /// Информация о департаменте /// </summary> /// <returns>String: Id, Name, CountEmployees, CountDirectors</returns> public override string ToString() { return $"| Идентификатор отдела: { Id } | " + $"Название отдела: { Name } | " + $"Количество сотрудников: { CountEmployees } | " + $"Количество поддепартаментов: { CountDepartments } |"; } #endregion // Methods #region Fields private string name; // наименование департамента private ObservableCollection<Worker> workers; // работники департамента private ObservableCollection<Department> departments; // поддепартаменты private static List<Department> allSubDepartments; // ВСЕ поддепартаменты private static int countDep = 0; // счетчик для идентификатора департамента #endregion // Fields } } <file_sep>using OrganizationGUI.Classes; using System; using System.Windows; namespace OrganizationGUI_2.DialogWindows.WorkerDialogs { /// <summary> /// Interaction logic for DialogNewWorker.xaml /// </summary> public partial class DialogNewWorker : Window { /// <summary> /// Создаваемый работник /// </summary> public Worker NewWorker { get; set; } public DialogNewWorker(Worker worker) { InitializeComponent(); // Размер окна по контенту this.SizeToContent = SizeToContent.WidthAndHeight; tboxWorkerName.Focus(); NewWorker = worker; if (NewWorker is Employee) { tblockWorkerSalry.Text = "Зарплата (рубли, в час): "; gridPostWorker.Visibility = Visibility.Visible; } if (NewWorker is Intern) { tblockWorkerSalry.Text = "Зарплата (рубли, в месяц): "; gridPostWorker.Visibility = Visibility.Collapsed; } } /// <summary> /// Обработчик нажатия кнопки подтверждения /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Accept_Click(object sender, RoutedEventArgs e) { // Если в текстовом поле есть непробельные символы if (tboxWorkerName.Text.Trim() != String.Empty && tboxWorkerSirname.Text.Trim() != String.Empty && tboxWorkerBirthDate.Text.Trim() != String.Empty && tboxWorkerSalary.Text.Trim() != String.Empty) { if (DateTime.TryParse(tboxWorkerBirthDate.Text, out DateTime birth)) { NewWorker.Name = tboxWorkerName.Text; NewWorker.LastName = tboxWorkerSirname.Text; NewWorker.BirthDate = DateTime.Parse(tboxWorkerBirthDate.Text); if (int.TryParse(tboxWorkerSalary.Text, out int salary) && NewWorker.BirthDate < DateTime.Now && salary > 0) { (NewWorker as ISalary).Salary = salary; if (NewWorker is Employee) { if (tboxWorkerPost.Text.Trim() != String.Empty) { (NewWorker as Employee).NamePost = tboxWorkerPost.Text; DialogResult = true; } } if (NewWorker is Intern) { DialogResult = true; } } } } // Если ответ некорректен if (!DialogResult ?? true) MessageBox.Show("Введите корректные данные!"); } } } <file_sep>using System; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Xml.Linq; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Collections.Generic; using System.Diagnostics; namespace OrganizationGUI.Classes { /// <summary> /// Организация /// </summary> public class Organization : INotifyPropertyChanged { #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged([CallerMemberName] string prop = "") { if (PropertyChanged != null) PropertyChanged.Invoke(this, new PropertyChangedEventArgs(prop)); } #endregion // INotifyPropertyChanged #region Constructors /// <summary> /// Конструктор по умолчанию /// </summary> public Organization() { departments = new ObservableCollection<Department>(); } /// <summary> /// Конструктор 1 /// </summary> /// <param name="dep">Департамент</param> public Organization(Department dep) { departments = new ObservableCollection<Department>(); departments.Add(dep); } /// <summary> /// Конструктор 2.1 /// </summary> /// <param name="name">Наименование организации</param> /// <param name="director">Директор организации</param> /// <param name="associateDirector">Зам. директора</param> /// <param name="departments">Департаменты в организации</param> public Organization(string name, Director director, AssociateDirector associateDirector, ObservableCollection<Department> departments) { this.Name = name; this.Dir = director; this.AssociateDir = associateDirector; this.departments = departments; } /// <summary> /// Конструктор 2.2 /// </summary> /// <param name="name">Наименование организации</param> /// <param name="director">Директор организации</param> /// <param name="associateDirector">Зам. директора</param> public Organization(string name, Director director, AssociateDirector associateDirector) : this(name, director, associateDirector, new ObservableCollection<Department>()) { } #endregion #region Properties /// <summary> /// Название организации /// </summary> public string Name { get; set; } /// <summary> /// Директор /// </summary> public Director Dir { get; set; } /// <summary> /// Заместитель директора /// </summary> public AssociateDirector AssociateDir { get; set; } /// <summary> /// Возвращает коллекцию департаментов верхнего уровня в организации /// </summary> public ObservableCollection<Department> Departments { get { return departments ?? new ObservableCollection<Department>(); } } /// <summary> /// Все департаменты и поддепартаменты /// </summary> public List<Department> AllDepartments { get { // Заполняем коллекцию всех департаментов allDepartments = new List<Department>(); makeAllDepartments(Departments.ToList()); return allDepartments; } } /// <summary> /// Количество департаментов верхнего уровня /// </summary> public int CountDepartments { get { return departments?.Count ?? 0; // если департаментов в организации нет (null), то возвр. 0 } } /// <summary> /// Зарплата начальника организации (15% от суммы зарплат всех подчиненных, /// но не менее 2000000 р.) /// </summary> public double DirSalary { get { // Зарплата начальника = (Зарплата всех сотрудников + Зарплата зам. начальника) * 0,15, double sum = (sumSalaryAllWorkers() + AssociateDirSalary) * 0.15; sum = Math.Round(sum); // округляем до целых return (sum < 2_000_000) ? 2_000_000 : sum; } } /// <summary> /// Зарплата зам. начальника организации (15% от суммы зарплат всех подчиненных, /// но не менее 1000000 р.) /// </summary> public double AssociateDirSalary { get { double sum = sumSalaryAllWorkers() * 0.15; sum = Math.Round(sum); // округляем до целых return (sum < 1_000_000) ? 1_000_000 : sum; } } #region Заглушка для исключения ошибок при Bindings public DepBoss LocalBoss { get; } public double LocalBossSalary { get; } public int CountEmployees { get; } public int CountInterns { get; } public IEnumerable<Employee> Employees { get; } public IEnumerable<Intern> Interns { get; } #endregion // Заглушка для исключения ошибок при Bindings #endregion // Properties #region Methods /// <summary> /// Сумма зарплат всех работников (включая начальников департаментов) /// </summary> /// <returns>Сумма зарплат</returns> private double sumSalaryAllWorkers() { double sum = 0; foreach (var dep in Departments) { sum += dep.salaryDepWorkers() + dep.LocalBossSalary; } return sum; } /// <summary> /// Добавление департамента в коллекцию департаментов /// </summary> /// <param name="dep">Департамент</param> public void addDepartment(Department dep) { departments.Add(dep); // Обновляем интерфейс (зарплаты главных начальников) OnPropertyChanged("DirSalary"); OnPropertyChanged("AssociateDirSalary"); } /// <summary> /// Возвращает департамент по его id /// </summary> /// <param name="id">Идентификатор департамента</param> /// <returns>Департамент</returns> public Department getDepartmentFromId(int id) { foreach (Department dep in AllDepartments) { if (dep.Id == id) return dep; } return new Department(); } /// <summary> /// Вспомогательный метод. Создаем коллекцию всех департаментов и поддепартаментов /// </summary> /// <param name="deps">Коллекция департаментов</param> private static void makeAllDepartments(List<Department> deps) { for (int i = 0; i < deps.Count; ++i) { allDepartments.Add(deps[i]); makeAllDepartments(deps[i].Departments.ToList()); } } /// <summary> /// Удаление департамента /// </summary> /// <param name="dep">Департамент</param> public void removeDepartment(Department dep) { Organization.returnIncludeDepCollection(Departments, dep).Remove(dep); // Обновляем интерфейс (зарплаты главных начальников) OnPropertyChanged("DirSalary"); OnPropertyChanged("AssociateDirSalary"); } /// <summary> /// Вспомогательный метод. Возвращает коллекцию в которой находится департамент /// </summary> /// <param name="deps">Коллекция в которой ищем департамент</param> /// <param name="dep">Искомый департамент</param> /// <returns></returns> private static ObservableCollection<Department> returnIncludeDepCollection(ObservableCollection<Department> deps, Department dep) { // Вспомогательная коллекция ObservableCollection<Department> departs = new ObservableCollection<Department>(); // Если департамент есть в коллекции, то возвращаем эту коллекцию if (deps.Contains(dep)) { return deps; } for (int i = 0; i < deps.Count; ++i) { // Если departs не содержит элементов, то "ищем" дальше if (departs.Count == 0) departs = returnIncludeDepCollection(deps[i].Departments, dep); } return departs; } /// <summary> /// Информация об организации /// </summary> /// <returns>String: Name, CountEmployees, CountDirectors</returns> public override string ToString() { return $"Название организации: { Name } | " + $"Имя директора: {Dir?.Name ?? String.Empty} {Dir?.LastName ?? String.Empty} | " + $"Имя зама: {AssociateDir?.Name ?? String.Empty} {AssociateDir?.LastName ?? String.Empty} | " + $"Количество департаментов верхнего уровня: {CountDepartments} | "; } #region XML Serialization /// <summary> /// Сериализует организацию (xml) /// </summary> /// /// <param name="path">Путь к файлу экспорта (xml)</param> public void xmlOrganizationSerializer(string path) { XElement xeORGANIZATION = new XElement("ORGANIZATION"); XAttribute xaNAME_ORG = new XAttribute("orgname", this.Name); XAttribute xaNAME_DIR = new XAttribute("dirname", this.Dir.Name); XAttribute xaLASTNAME_DIR = new XAttribute("dirlastname", this.Dir.LastName); XAttribute xaBIRTHDATE_DIR = new XAttribute("dirbirth", this.Dir.BirthDate); XAttribute xaNAME_ASSDIR = new XAttribute("assdirname", this.AssociateDir.Name); XAttribute xaLASTNAME_ASSDIR = new XAttribute("assdirlastname", this.AssociateDir.LastName); XAttribute xaBIRTHDATE_ASSDIR = new XAttribute("assdirbirth", this.AssociateDir.BirthDate); // ДЕПАРТАМЕНТЫ ОРГАНИЗАЦИИ XElement xeDEPARTMENTS = new XElement("DEPARTMENTS"); foreach (Department dep in departments) { XElement xeDEPARTMENT = serializerSubDeps(dep); xeDEPARTMENTS.Add(xeDEPARTMENT); } xeORGANIZATION.Add(xeDEPARTMENTS, xaNAME_ORG, xaNAME_DIR, xaLASTNAME_DIR, xaBIRTHDATE_DIR, xaNAME_ASSDIR, xaLASTNAME_ASSDIR, xaBIRTHDATE_ASSDIR); xeORGANIZATION.Save(path); } /// <summary> /// Вспомогательный рекурсивный метод для сереализации департамента и его поддепартаментов /// </summary> /// <param name="dep">Департамент</param> /// <param name="org">Организация</param> /// <returns>XML-узел</returns> private static XElement serializerSubDeps(Department dep) { XElement xeDEPARTMENT = new XElement("DEPARTMENT"); XAttribute xaNAME_DEP = new XAttribute("depname", dep.Name); XAttribute xaNAME_DEPBOSS = new XAttribute("depbossname", dep.LocalBoss.Name); XAttribute xaLASTNAME_DEPBOSS = new XAttribute("depbosslastname", dep.LocalBoss.LastName); XAttribute xaBIRTHDATE_DEPBOSS = new XAttribute("depbossbirth", dep.LocalBoss.BirthDate); // СОТРУДНИКИ ОРГАНИЗАЦИИ XElement xeEMPLOYEES = new XElement("EMPLOYEES"); foreach (Employee emp in dep.Employees) { XElement xeEMPLOYEE = new XElement("EMPLOYEE"); XAttribute xaNAME_EMP = new XAttribute("empname", emp.Name); XAttribute xaLASTNAME_EMP = new XAttribute("emplastname", emp.LastName); XAttribute xaBIRTHDATE_EMP = new XAttribute("empbirth", emp.BirthDate); XAttribute xaPOST_EMP = new XAttribute("empnamepost", emp.NamePost); XAttribute xaSALARY_EMP = new XAttribute("empsalary", emp.Salary / 168); xeEMPLOYEE.Add(xaNAME_EMP, xaLASTNAME_EMP, xaBIRTHDATE_EMP, xaPOST_EMP, xaSALARY_EMP); xeEMPLOYEES.Add(xeEMPLOYEE); } // ИНТЕРНЫ ОРГАНИЗАЦИИ XElement xeINTERNS = new XElement("INTERNS"); foreach (Intern intern in dep.Interns) { XElement xeINTERN = new XElement("INTERN"); XAttribute xaNAME_INTERN = new XAttribute("internname", intern.Name); XAttribute xaLASTNAME_INTERN = new XAttribute("internlastname", intern.LastName); XAttribute xaBIRTHDATE_INTERN = new XAttribute("internbirth", intern.BirthDate); XAttribute xaSALARY_INTERN = new XAttribute("internsalary", intern.Salary); xeINTERN.Add(xaNAME_INTERN, xaLASTNAME_INTERN, xaBIRTHDATE_INTERN, xaSALARY_INTERN); xeINTERNS.Add(xeINTERN); } xeDEPARTMENT.Add(xaNAME_DEP, xaNAME_DEPBOSS, xaLASTNAME_DEPBOSS, xaBIRTHDATE_DEPBOSS); xeDEPARTMENT.Add(xeEMPLOYEES); xeDEPARTMENT.Add(xeINTERNS); if (dep.CountDepartments > 0) { // ПОДДЕПАРТАМЕНТЫ ДЕПАРТАМЕНТА XElement xeSUBDEPARTMENTS = new XElement("DEPARTMENTS"); foreach (Department department in dep.Departments) { XElement xeDEP = serializerSubDeps(department); // рекурсия xeSUBDEPARTMENTS.Add(xeDEP); } xeDEPARTMENT.Add(xeSUBDEPARTMENTS); } return xeDEPARTMENT; } #endregion // XML Serialization #region XML Deserialization /// <summary> /// Десериализует организацию (xml) /// </summary> /// <param name="path">Путь к файлу импорта (xml)</param> /// <returns>Организация</returns> public static Organization xmlOrganizationDeserializer(string path) { string xml = File.ReadAllText(path); Director dir = Director .getInstance(XDocument.Parse(xml).Element("ORGANIZATION").Attribute("dirname").Value, XDocument.Parse(xml).Element("ORGANIZATION").Attribute("dirlastname").Value, DateTime.Parse(XDocument.Parse(xml).Element("ORGANIZATION").Attribute("dirbirth").Value)); dir.Name = XDocument.Parse(xml).Element("ORGANIZATION").Attribute("dirname").Value; // если директор (синглтон) уже был dir.LastName = XDocument.Parse(xml).Element("ORGANIZATION").Attribute("dirlastname").Value; dir.BirthDate = DateTime.Parse(XDocument.Parse(xml).Element("ORGANIZATION").Attribute("dirbirth").Value); AssociateDirector assDir = AssociateDirector .getInstance(XDocument.Parse(xml).Element("ORGANIZATION").Attribute("assdirname").Value, XDocument.Parse(xml).Element("ORGANIZATION").Attribute("assdirlastname").Value, DateTime.Parse(XDocument.Parse(xml).Element("ORGANIZATION").Attribute("assdirbirth").Value)); assDir.Name = XDocument.Parse(xml).Element("ORGANIZATION").Attribute("assdirname").Value; // если зам. (синглтон) уже был assDir.LastName = XDocument.Parse(xml).Element("ORGANIZATION").Attribute("assdirlastname").Value; assDir.BirthDate = DateTime.Parse(XDocument.Parse(xml).Element("ORGANIZATION").Attribute("assdirbirth").Value); Organization org = new Organization(XDocument.Parse(xml).Element("ORGANIZATION").Attribute("orgname").Value, dir, assDir); var colDepsXml = XDocument.Parse(xml) .Element("ORGANIZATION") .Element("DEPARTMENTS") .Elements("DEPARTMENT") .ToList(); // Цикл по департаментам в организации foreach (var itemDepXml in colDepsXml) { Department dep = deserializerSubDeps(itemDepXml, org); org.addDepartment(dep); // добавляем созданный отдел в организацию } return org; } /// <summary> /// Вспомогательный рекурсивный метод для десереализации департамента и его поддепартаментов /// </summary> /// <param name="xeDep">XML-узел</param> /// <returns>Департамент с поддепартаментами</returns> private static Department deserializerSubDeps(XElement xeDep, Organization org) { DepBoss depBoss = new DepBoss(xeDep.Attribute("depbossname").Value, xeDep.Attribute("depbosslastname").Value, DateTime.Parse(xeDep.Attribute("depbossbirth").Value)); ObservableCollection<Worker> workers = new ObservableCollection<Worker>(); // Перебираем сотрудников и добавляем их в коллекцию workers foreach (var itemEmpXml in xeDep.Element("EMPLOYEES").Elements()) { workers.Add(new Employee(itemEmpXml.Attribute("empname").Value, itemEmpXml.Attribute("emplastname").Value, DateTime.Parse(itemEmpXml.Attribute("empbirth").Value), itemEmpXml.Attribute("empnamepost").Value, int.Parse(itemEmpXml.Attribute("empsalary").Value))); } // Перебираем интернов и добавляем их в коллекцию workers foreach (var itemEmpXml in xeDep.Element("INTERNS").Elements()) { workers.Add(new Intern(itemEmpXml.Attribute("internname").Value, itemEmpXml.Attribute("internlastname").Value, DateTime.Parse(itemEmpXml.Attribute("internbirth").Value), int.Parse(itemEmpXml.Attribute("internsalary").Value))); } Department dep = new Department(xeDep.Attribute("depname").Value, depBoss, workers, org); if (xeDep.Element("DEPARTMENTS") != null) { foreach (var itemSubdepXml in xeDep.Element("DEPARTMENTS").Elements("DEPARTMENT").ToList()) { // ПОДДЕПАРТАМЕНТЫ ДЕПАРТАМЕНТА dep.addDepartment(deserializerSubDeps(itemSubdepXml, org)); // рекурсия } } return dep; } #endregion // XML Deserialization #endregion // Methods private ObservableCollection<Department> departments; // департаменты в организации private static List<Department> allDepartments; // все департаменты в организации } } <file_sep>namespace OrganizationGUI.Classes { /// <summary> /// Зарплата /// </summary> interface ISalary { /// <summary> /// Размер зарплаты /// </summary> public int Salary { get; set; } } } <file_sep>using System; using System.Windows; namespace OrganizationGUI_2 { /// <summary> /// Interaction logic for DialogNewDepartment.xaml /// </summary> public partial class DialogNewDepartment : Window { public DialogNewDepartment() { InitializeComponent(); tboxDepName.Focus(); } /// <summary> /// Обработчик нажатия кнопки подтверждения /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Accept_Click(object sender, RoutedEventArgs e) { // Если в текстовом поле есть непробельные символы if (tboxDepName.Text.Trim() != String.Empty) DialogResult = true; } } } <file_sep>namespace OrganizationGUI.Classes { /// <summary> /// Должность /// </summary> interface IPost { /// <summary> /// Наименование должности /// </summary> public string NamePost { get; set; } } } <file_sep>using System; using System.ComponentModel; using System.Runtime.CompilerServices; namespace OrganizationGUI.Classes { /// <summary> /// Абстрактный класс работника /// </summary> public abstract class Worker : INotifyPropertyChanged { #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged([CallerMemberName] string prop = "") { if (PropertyChanged != null) PropertyChanged.Invoke(this, new PropertyChangedEventArgs(prop)); } #endregion // INotifyPropertyChanged #region Properties /// <summary> /// Имя работника /// </summary> public abstract string Name { get; set; } /// <summary> /// Фамилия работника /// </summary> public abstract string LastName { get; set; } /// <summary> /// Дата рождения работника /// </summary> public abstract DateTime BirthDate { get; set; } /// <summary> /// Идентификатор работника /// </summary> public abstract int Id { get; } /// <summary> /// Возраст работника в годах /// </summary> public int Age { get { int age = DateTime.Now.Year - BirthDate.Year; if (BirthDate > DateTime.Now.AddYears(-age)) --age; // для корректного вычисления полных лет return age; } } #endregion // Property #region Fields protected static int countWorker = 0; // количество созданных работников (нач. деп., сотрудники, интерны) #endregion } } <file_sep>using OrganizationGUI.Classes; using System; using System.Windows; namespace OrganizationGUI_2.DialogWindows.WorkerDialogs { /// <summary> /// Interaction logic for DialogTransferWorker.xaml /// </summary> public partial class DialogTransferWorker : Window { public DialogTransferWorker(Organization organization) { InitializeComponent(); foreach (Department department in organization.AllDepartments) { cboxDepNames.Items.Add(new String($"{department.Name} (Id: {department.Id})")); } } /// <summary> /// Идентификатор департамента в который необходимо переместить /// </summary> public int ToDepID { get; private set; } /// <summary> /// Обработчик нажатия кнопки подтверждения /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Accept_Click(object sender, RoutedEventArgs e) { // Если выбран элемент if (cboxDepNames.SelectedItem != null) { string selectedString = cboxDepNames.SelectedItem.ToString(); // выбранный item int posId = selectedString.IndexOf("Id:") + 4; // позиция id int lenId = selectedString.Length - posId - 1; // длина id string selectedId = selectedString.Substring(posId, lenId); // "вырезаем" id if (int.TryParse(selectedId, out int id)) { ToDepID = id; DialogResult = true; } } else { MessageBox.Show("Не выбран департамент в который перемещаем текущий!"); } } } } <file_sep>using System; namespace OrganizationGUI.Classes { /// <summary> /// Интерн /// </summary> public class Intern : Worker, ISalary { #region Constructors /// <summary> /// Конструктор по умолчанию /// </summary> public Intern() { Id = ++countWorker; } /// <summary> /// Конструктор /// </summary> /// <param name="name">Имя</param> /// <param name="lastName">Фамилия</param> /// <param name="birthDate">Дата рождения</param> /// <param name="salary">Зарплата в месяц</param> public Intern(string name, string lastName, DateTime birthDate, int salary) { Name = name; LastName = lastName; BirthDate = birthDate; Salary = salary; Id = ++countWorker; } #endregion // Constructors #region Properties /// <summary> /// Имя интерна /// </summary> public override string Name { get { return name; } set { name = value; OnPropertyChanged("Name"); } } /// <summary> /// Фамилия интерна /// </summary> public override string LastName { get { return lastName; } set { lastName = value; OnPropertyChanged("LastName"); } } /// <summary> /// Дата рождения интерна /// </summary> public override DateTime BirthDate { get { return birthDate; } set { birthDate = value; OnPropertyChanged("BirthDate"); } } /// <summary> /// Идентификатор интерна /// </summary> public override int Id { get; } /// <summary> /// Зарплата интерна /// </summary> public int Salary { get { return salary; } set { salary = value; OnPropertyChanged("Salary"); } } #endregion // Properties #region Methods /// <summary> /// Информация об интерне /// </summary> /// <returns>String: Id, Name, LastName, BirthDate, NamePost, Salary</returns> public override string ToString() { return $"| Идентификатор интерна: { Id } | " + $"Имя интерна: { Name } | " + $"Фамилия интерна: { LastName } | " + $"Дата рождения интерна: { BirthDate } | " + $"Зарплата интерна: { Salary } |"; } #endregion // Methods private string name; // <NAME> private string lastName; // фамилия интерна private DateTime birthDate; // дата рождения интерна private int salary; // зарплата интерна } } <file_sep>using System; using System.Collections.Generic; using System.Windows; namespace OrganizationGUI_2.DialogWindows { /// <summary> /// Interaction logic for DialogTransferDepartment.xaml /// </summary> public partial class DialogTransferDepartment : Window { public DialogTransferDepartment(int id, string depName, Dictionary<int, string> dicIdName, string nameOrg) { InitializeComponent(); tblockDepIn.Text = depName; cboxDepNames.Items.Add(nameOrg); foreach (var pair in dicIdName) { // Добавляем в список ComboBox все наименования и id департаментов кроме перемещаемого if (pair.Key != id) cboxDepNames.Items.Add($"{pair.Value} (Id: {pair.Key})"); } cboxDepNames.Focus(); } /// <summary> /// Идентификатор департамента в который необходимо переместить /// </summary> public int ToDepID { get; private set; } /// <summary> /// Обработчик нажатия кнопки подтверждения /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Accept_Click(object sender, RoutedEventArgs e) { // Если выбран элемент if (cboxDepNames.SelectedItem != null) { // Если выбрана организация, то выходим и присваиваем ToDepID ноль if (cboxDepNames.SelectedIndex == 0) { ToDepID = 0; DialogResult = true; } string selectedString = cboxDepNames.SelectedItem.ToString(); // выбранный item int posId = selectedString.IndexOf("Id:") + 4; // позиция id int lenId = selectedString.Length - posId - 1; // длина id string selectedId = selectedString.Substring(posId, lenId); // "вырезаем" id if (int.TryParse(selectedId, out int id)) { ToDepID = id; DialogResult = true; } } else { MessageBox.Show("Не выбран департамент в который перемещаем текущий!"); } } } } <file_sep>using System; namespace OrganizationGUI.Classes { /// <summary> /// Заместитель директора организации (синглтон, т.к. зам один в организации) /// </summary> public class AssociateDirector : Worker { #region Constructors /// <summary> /// Конструктор по умолчанию /// </summary> protected AssociateDirector() { } /// <summary> /// Конструктор /// </summary> /// <param name="name">Имя</param> /// <param name="lastName">Фамилия</param> /// <param name="birthDate">Дата рождения</param> /// <param name="salary">Зарплата</param> protected AssociateDirector(string name, string lastName, DateTime birthDate) { Name = name; LastName = lastName; BirthDate = birthDate; Id = 1; } #endregion // Constructors #region Properties /// <summary> /// Имя заместителя директора /// </summary> public override string Name { get { return name; } set { name = value; OnPropertyChanged("Name"); } } /// <summary> /// Фамилия заместителя директора /// </summary> public override string LastName { get { return lastName; } set { lastName = value; OnPropertyChanged("LastName"); } } /// <summary> /// Дата рождения заместителя директора /// </summary> public override DateTime BirthDate { get { return birthDate; } set { birthDate = value; OnPropertyChanged("BirthDate"); } } /// <summary> /// Идентификатор заместителя директора /// </summary> public override int Id { get; } #endregion // Properties #region Methods /// <summary> /// Возвращает инстанс зам. директора /// </summary> /// <param name="name"></param> /// <param name="lastName"></param> /// <param name="salary"></param> /// <returns></returns> public static AssociateDirector getInstance(string name, string lastName, DateTime birthDate) { if (instance == null) instance = new AssociateDirector(name, lastName, birthDate); return instance; } /// <summary> /// Информация о заместителе директора /// </summary> /// <returns>String: Id, Name, LastName, BirthDate, Salary</returns> public override string ToString() { return $"| Идентификатор заместителя директора: { Id } | " + $"Имя заместителя директора: { Name } | " + $"Фамилия заместителя директора: { LastName } | " + $"Дата рождения заместителя директора: { BirthDate } | "; } #endregion // Methods #region Fields private string name; // имя заместителя директора private string lastName; // фамилия заместителя директора private DateTime birthDate; // дата рождения заместителя директора private static AssociateDirector instance; // поле (инстанс) для синглтона #endregion } } <file_sep>using System; namespace OrganizationGUI.Classes { /// <summary> /// Рабочий (сотрудник) /// </summary> public class Employee : Worker, IPost, ISalary { #region Constructors /// <summary> /// Конструктор по умолчанию /// </summary> public Employee() { Id = ++countWorker; } /// <summary> /// Конструктор 1 /// </summary> /// <param name="name">Имя сотрудника</param> /// <param name="lastName">Фами<NAME>дника</param> /// <param name="birthDate">Дата рождения</param> /// <param name="namePost">Наименование должности</param> /// <param name="salary">Зарплата в час</param> public Employee(string name, string lastName, DateTime birthDate, string namePost, int salary) { Name = name; LastName = lastName; BirthDate = birthDate; NamePost = namePost; Salary = salary; // умножаем на 168 рабочих часов в месяце Id = ++countWorker; } #endregion // Constructors #region Properties /// <summary> /// Имя сотрудника /// </summary> public override string Name { get { return name; } set { name = value; OnPropertyChanged("Name"); } } /// <summary> /// Фамилия сотрудника /// </summary> public override string LastName { get { return lastName; } set { lastName = value; OnPropertyChanged("LastName"); } } /// <summary> /// Дата рождения сотрудника /// </summary> public override DateTime BirthDate { get { return birthDate; } set { birthDate = value; OnPropertyChanged("BirthDate"); } } /// <summary> /// Идентификатор сотрудника /// </summary> public override int Id { get; } /// <summary> /// Наименование должности /// </summary> public string NamePost { get { return namePost; } set { namePost = value; OnPropertyChanged("NamePost"); } } /// <summary> /// Зарплата сотрудника /// </summary> public int Salary { get { return salary * 168; } set { salary = value; OnPropertyChanged("Salary"); } } #endregion // Properties #region Methods /// <summary> /// Информация о рабочем /// </summary> /// <returns>String: Id, Name, LastName, BirthDate, NamePost, Salary</returns> public override string ToString() { return $"| Идентификатор рабочего: { Id } | " + $"Имя рабочего: { Name } | " + $"Фамилия рабочего: { LastName } | " + $"Дата рождения рабочего: { BirthDate } | " + $"Должность рабочего: { NamePost } | " + $"Зарплата рабочего: { Salary } |"; } #endregion // Methods #region Fields private string name; // имя сотрудника private string lastName; // фамилия сотрудника private DateTime birthDate; // дата рождения сотрудника private string namePost; // наименование должности сотрудника private int salary; // зарплата сотрудника #endregion // Fields } } <file_sep>using System; namespace OrganizationGUI.Classes { /// <summary> /// Начальник департамента /// </summary> public class DepBoss : Worker { #region Constructors /// <summary> /// Конструктор по умолчанию /// </summary> public DepBoss() { Id = ++countWorker; BirthDate = DateTime.Now; // для корректного отображения возраста (костыль) } /// <summary> /// Конструктор /// </summary> /// <param name="name">Имя</param> /// <param name="lastName">Фамилия</param> /// <param name="birthDate">Дата рождения</param> public DepBoss(string name, string lastName, DateTime birthDate) { Name = name; LastName = lastName; BirthDate = birthDate; Id = ++countWorker; } #endregion // Constructors #region Properties /// <summary> /// Имя начальника департамента /// </summary> public override string Name { get { return name; } set { name = value; OnPropertyChanged("Name"); } } /// <summary> /// Фамилия начальника департамента /// </summary> public override string LastName { get { return lastName; } set { lastName = value; OnPropertyChanged("LastName"); } } /// <summary> /// Дата рождения начальника департамента /// </summary> public override DateTime BirthDate { get { return birthDate; } set { birthDate = value; OnPropertyChanged("BirthDate"); } } /// <summary> /// Идентификатор рабочего /// </summary> public override int Id { get; } #endregion // Properties #region Methods /// <summary> /// Информация о рабочем /// </summary> /// <returns>String: Id, Name, CountPositions</returns> public override string ToString() { return $"| Идентификатор рабочего: { Id } | " + $"Имя рабочего: { Name } | " + $"Фамилия рабочего: { LastName } | " + $"Дата рождения рабочего: { BirthDate } | " + $"Должность сотрудника: начальник департамента | "; } #endregion // Methods #region Fields private string name; // имя на<NAME>артамента private string lastName; // фамили<NAME>артамента private DateTime birthDate; // дата рождения начальника департамента #endregion } }
575ee617ed925101826ba2bf6fae3537a785f86d
[ "C#" ]
16
C#
VyachTur/OrganizationGUI_2
2d8500e300e95fc1977b874ff611e9d7bfb20435
e2c9f36a738308210415b3b027286790d59b4ed9
refs/heads/master
<file_sep># ros2 wrapper for CenterTrack This repo is forked from the official implementation of CenterTrack and add ROS2 wrapper to receive images over ros topics. I am using Ubuntu 20.04 + ros2 foxy. ### ros2 + conda It seems ros2 is not officially supporting conda currently. The error message is something like no module named ```rclpy._rclpy```. I have a dirty work-around of this problem. Under a particular conda env, I clone the source code of several ros2 packages (rclpy, rcl_interfaces, common_interfaces) into a workspace and build it. Then I can run or launch without problem. ### run demo I use Intel Realsense D435i in this project. You can simply change the topic name in ```src/ros2_demo.py``` to work with your own camera. In one terminal, launch your camera node. You can also use ros2 bag... In another terminal, run the demo ``` python ros2_demo.py tracking,dd --load_model ../models/coco_tracking.pth --demo webcam ``` <file_sep>import sys CENTERTRACK_PATH = "/home/tony/CenterTrack/src/lib" sys.path.insert(0, CENTERTRACK_PATH) from detector import Detector from opts import opts import rclpy from rclpy.node import Node from sensor_msgs.msg import Image import cv2 import numpy as np MODEL_PATH = "../models/coco_pose.pth" TASK = 'tracking' # or 'tracking,multi_pose' for pose tracking and 'tracking,ddd' for monocular 3d tracking opt = opts().init('{} --load_model {}'.format(TASK, MODEL_PATH).split(' ')) opt.debug = max(opt.debug, 1) detector = Detector(opt) class MinimalSubscriber(Node): def __init__(self): super().__init__('minimal_subscriber') self.subscription = self.create_subscription( Image, '/realsense/camera/color/image_raw', self.callback, 30) def callback(self, msg): img = np.array(msg.data) img = img.reshape((480, 640, 3)) img = np.flip(img, 2) #print(ret) cv2.imshow("img", img) ret = detector.run(img) if cv2.waitKey(1) == 27: return rclpy.init(args = None) subs = MinimalSubscriber() print("start spining node...") rclpy.spin(subs) subs.destroy_node() rclpy.shutdown() # for img in images: # ret = detector.run(img)['results']
2900a694d9479289a40be4e8f00380cdc7c1d6fa
[ "Markdown", "Python" ]
2
Markdown
tony23545/CenterTrack
7d516e2b5bd5e20140531f55f5e6a67c6f91cb92
eff694f687fd42cd2f76fd01d6fcd02f38014f07
refs/heads/master
<file_sep>#include <linux/init.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/mutex.h> #include <linux/errno.h> #include <linux/err.h> #include <linux/init.h> #include <linux/elf.h> #include <mach/scm.h> #include <asm/cacheflush.h> MODULE_LICENSE("Dual BSD/GPL"); struct elf_info_s { Elf32_Ehdr *elf_hdr; Elf32_Phdr *prog_hdr; u32 prog_hdr_num; u8* hash_seg; u32 hash_seg_sz; u8* sig_ptr; u32 sig_sz; u8* cert_ptr; u32 cert_sz; }; typedef u32 tz_mutex_t; struct pil_info_s { struct elf_info_s elf_info; u32 proc; tz_mutex_t lock; u32 state; void *ssd; }; #ifndef __MSM_SCM_PAS_H enum pas_id { PAS_MODEM, PAS_Q6, PAS_DSPS, PAS_TZAPPS, PAS_MODEM_SW, PAS_MODEM_FW, PAS_WCNSS, PAS_SECAPP, PAS_GSS, PAS_VIDC, }; #endif #define SONY_XPERIA_SP //#define SAMSUNG_ACE_3 /* symbols */ #ifdef SAMSUNG_ACE_3 /* samsung galaxy ace 3 */ #define BLIST_ADDR 0x2A025158 #define BLIST_INDEX 4 /* #define CLOBBER_ADDR (BLIST_ADDR + 4*16 + 4) */ #define FEATURE_LIST 0x2A02500C #define TZ_SECTION_2 0x2A025CBC #define TZ_SECTION_2_ORIG {0x2A02749C, 0x2A0279C4} #define TZ_MEMCPY (0x2A019558|1) #define TZ_MMU_MAP (0x2A003AB8|1) #define TZ_SIGN_ADDR 0x2A02514B #elif defined (SONY_XPERIA_SP) /* as seen in sony xperia sp Boot partition */ #define BLIST_ADDR 0x2A02C1E0 #define BLIST_INDEX 8 #define FEATURE_LIST 0x2A02C15C #define TZ_SECTION_2 0x2A02CDDC #define TZ_SECTION_2_ORIG {0x2A02E89C, 0x2A02EE38} #define TZ_MEMCPY (0x2A0208D0|1) #define TZ_MMU_MAP (0x2A001F12|1) /* needed for manual image loading */ #define TZ_DCACHE_INVAL (0x2A020FC8) #define TZ_MUTEX_LOCK (0x2A0237FC) #define TZ_MUTEX_UNLOCK (0x2A023848) #define TZ_CLEAN_PIL (0x2A002E12|1) #define TZ_IS_ELF (0x2A002E2C|1) #define TZ_POPULATE_ELF (0x2A00299C|1) #define TZ_VIDC_CONFIG (0x2A008DFA|1) #define TZ_DSPS_CONFIG (0x2A008C4A|1) #define MANUAL_INIT_IMAGE #define PIL_INFO_ADDR 0x2A02F480 #define pil_info ((struct pil_info_s*)(PIL_INFO_ADDR)) #else #error "no target selected" #endif /* commons */ #define TZ_PIL_LOCK(id) tz_mutex_lock(&pil_info[id].lock) #define TZ_PIL_UNLOCK(id) tz_mutex_unlock(&pil_info[id].lock) #define CLOBBER_ADDR (BLIST_ADDR + 16*BLIST_INDEX+4) #define BLIST_ORIG {2, 0x28420000, 0x2A03F000} #define TZ_LOG(fmt, ...) printk(KERN_ALERT "tzexec: " fmt "\n", ##__VA_ARGS__) // #define TZ_DEBUG(fmt, ...) TZ_LOG(fmt, ##__VA_ARGS__) #define TZ_DEBUG(fmt, ...) {} /** scm utils */ #define TZ_SID(svc,cmd) (((svc&0x3f)<<10)|(cmd&0x3f)) struct scm_command { u32 len; u32 buf_offset; u32 resp_hdr_offset; u32 id; u32 buf[0]; }; struct scm_sc_s { u32 id; u32 name; u32 flags; u32 func; u32 nargs; u32 args[4]; }; struct mmu_block_s { u32 p_addr; u32 v_addr; u32 n_pages; u32 flags; }; #define SCM_INTERRUPTED 1 static u32 smc(u32 cmd_addr) { int context_id; register u32 r0 asm("r0") = 1; register u32 r1 asm("r1") = (u32)&context_id; register u32 r2 asm("r2") = cmd_addr; do { asm volatile( __asmeq("%0", "r0") __asmeq("%1", "r0") __asmeq("%2", "r1") __asmeq("%3", "r2") #ifdef REQUIRES_SEC ".arch_extension sec\n" #endif "smc #0 @ switch to secure world\n" : "=r" (r0) : "r" (r0), "r" (r1), "r" (r2) : "r3"); } while (r0 == SCM_INTERRUPTED); return r0; } /* writes {0xc, 0xc, 0x1} at paddr */ static int clobber_it(u32 paddr) { int ret; struct scm_command *scm_buf; u32 cmd_addr; scm_buf = kzalloc(PAGE_ALIGN(0x40), GFP_KERNEL); if (!scm_buf){ TZ_LOG("no mem"); return -ENOMEM; } cmd_addr = virt_to_phys(scm_buf); scm_buf->id = TZ_SID(1, 3); scm_buf->len = 0xfffff000; scm_buf->buf_offset = 0xffffe000; scm_buf->resp_hdr_offset = paddr - cmd_addr; if (scm_buf->len <= 16){ TZ_LOG( "invalid buf len %08x", scm_buf->len); } if (scm_buf->buf_offset > scm_buf->len || scm_buf->buf_offset < 16){ TZ_LOG( "invalid buf offset %08x", scm_buf->buf_offset); } flush_cache_all(); ret = smc(cmd_addr); TZ_LOG( "scm_call(1,3, len %x, bof %x, rof %x (raddr %x)) -> %d ", scm_buf->len, scm_buf->buf_offset, scm_buf->resp_hdr_offset, scm_buf->resp_hdr_offset + cmd_addr, ret); kfree(scm_buf); return ret; } /* check wether a scm call is available */ static int scm_call_usable(u32 sid) { u32 *buf; int ret; buf = kzalloc(PAGE_ALIGN(sizeof(*buf)), GFP_KERNEL); if (!buf){ return -ENOMEM; } flush_cache_all(); ret = scm_call_atomic3(6, 1, sid, virt_to_phys(buf), 4); if (ret == 0) ret = (int)*buf; else TZ_LOG( "call_usable: error %x", (unsigned)ret); kfree(buf); return ret; } /* Reads version[id]*/ static int get_version(u32 id, u32 paddr) { int ret; flush_cache_all(); ret = scm_call_atomic3(6, 3, id, paddr, 4 ); flush_cache_all(); return ret; } /* Writes size bytes of random in paddr */ static int do_prng(u32 paddr, u32 size) { int ret; flush_cache_all(); ret = scm_call_atomic2(10, 1, paddr, size ); return ret; } /* Use prng to write 4 bytes in version[id]*/ static int write_version(u32 id, u32 val) { int rc; u32 waddr, raddr, i; u8 *buf, *vb = (u8*)&val; rc = 0; buf = kzalloc(PAGE_ALIGN(4), GFP_KERNEL); if (!buf){ TZ_LOG( "no mem"); return -ENOMEM; } waddr = FEATURE_LIST + 4 + id*8; raddr = virt_to_phys(buf); for (i=0;i<4;i++){ while(1){ if ((rc = get_version(id, raddr))!= 0){ TZ_LOG("get_version failed"); goto ret; } if (buf[i] == vb[i]) break; if ((rc = do_prng(waddr+i, 1))!=0){ TZ_LOG("do_pring(0x%08x, 1) failed", waddr+i); goto ret; } } } ret: kfree(buf); return rc; } /* write 4 bytes */ static int write4(u32 paddr, u32 val) { int rc; /* set version[0] to write val */ if ((rc = write_version(0, val))) return rc; /* write version[0] to target addr */ return get_version(0, paddr); } int tz_mmu_map( u32 p_addr, u32 v_addr, u32 n_pages, u32 flags ) { TZ_LOG("mmu_map"); return scm_call_atomic4_3(30, 32, p_addr, v_addr, n_pages, flags, NULL, NULL); } EXPORT_SYMBOL(tz_mmu_map); int tz_memcpy(u32 dst, u32 src, u32 size) { int rc; flush_cache_all(); rc = scm_call_atomic3(30, 33, dst, src, size); return rc; } EXPORT_SYMBOL(tz_memcpy); /* wrapper to copy data to trustzone secure memory */ int copy_to_tz(u32 dst, const void* src, u32 size) { u8 *buf; buf = kzalloc(PAGE_ALIGN(size), GFP_KERNEL); if (!buf){ TZ_LOG( "no mem"); return -ENOMEM; } memcpy(buf, src, size); tz_memcpy(dst, virt_to_phys(buf), size); kfree(buf); return 0; } EXPORT_SYMBOL(copy_to_tz); int copy_from_tz(void* dst, u32 src, u32 size) { u8 *buf; buf = kzalloc(PAGE_ALIGN(size), GFP_KERNEL); if (!buf) return -ENOMEM; tz_memcpy(virt_to_phys(buf), src, size); memcpy(dst, buf, size); kfree(buf); return 0; } EXPORT_SYMBOL(copy_from_tz); #ifdef MANUAL_INIT_IMAGE void tz_dcache_inval (void *addr, u32 size) { TZ_DEBUG("dcache_inval"); scm_call_atomic2(30, 34, (u32) addr, size); } void tz_mutex_lock (tz_mutex_t *lock) { TZ_DEBUG("mutex_lock"); scm_call_atomic1(30, 35, (u32)lock); } void tz_mutex_unlock (tz_mutex_t *lock) { TZ_DEBUG("mutex_unlock"); scm_call_atomic1(30, 36, (u32) lock); } void tz_clean_pil (struct pil_info_s *pil) { TZ_DEBUG("clean_pil"); scm_call_atomic1(30, 37, (u32)pil); } int tz_is_elf (Elf32_Ehdr * ehdr) { TZ_DEBUG("is_elf"); return scm_call_atomic1(30, 38, (u32)ehdr); } int tz_populate_elf (u32 proc, Elf32_Ehdr *ehdr) { TZ_DEBUG("populate elf"); return scm_call_atomic3(30, 39, proc, (u32)ehdr, (u32)&pil_info[proc].elf_info); } void tz_dsps_config (void) { TZ_DEBUG("dsps_config"); scm_call_atomic1 (30, 40, 0); } void tz_vidc_config (void) { TZ_DEBUG("vidc_config"); scm_call_atomic1 (30, 41, (u32) &pil_info[PAS_VIDC].elf_info); } int tz_manual_init_image(u32 proc, u32 elf_paddr) { const u32 st_reset = 2, dsps_entry = 0x12000000; Elf32_Ehdr *dsps_elf, *elf = (Elf32_Ehdr*) elf_paddr; int rc = 0; TZ_LOG("init_image(%d, 0x%x)", proc, elf_paddr); tz_dcache_inval(elf, sizeof(*elf)); do { TZ_PIL_LOCK(4); tz_clean_pil(&pil_info[proc]); if (!tz_is_elf(elf)){ TZ_LOG("not an elf ?!"); rc = -1; break; } if ((rc = tz_populate_elf(proc, elf))){ TZ_LOG("populo failed: %d", rc); break; } switch(proc){ case PAS_DSPS: tz_dsps_config(); copy_from_tz(&dsps_elf, (u32)&pil_info[proc].elf_info.elf_hdr, 4); TZ_LOG("dsps elf_ptr : %x", (u32)dsps_elf); copy_to_tz((u32)&dsps_elf->e_entry, &dsps_entry, 4); break; case PAS_VIDC: tz_vidc_config(); break; default: break; } } while (0); if (!rc){ copy_to_tz((u32)&pil_info[proc].state, &st_reset, 4); } else{ tz_clean_pil(&pil_info[proc]); } TZ_PIL_UNLOCK(4); TZ_LOG("all done, rc = %d", rc); return rc; } EXPORT_SYMBOL(tz_manual_init_image); #endif static struct scm_sc_s *scm_sc = NULL; static struct scm_sc_s scm_sc_def[] = { {TZ_SID(30, 32), 0, 0xd, TZ_MMU_MAP, 4, {4, 4, 4, 4}}, {TZ_SID(30, 33), 0, 0xd, TZ_MEMCPY, 3, {4, 4, 4}}, #ifdef MANUAL_INIT_IMAGE {TZ_SID(30, 34), 0, 0xd, TZ_DCACHE_INVAL, 2, {4, 4}}, {TZ_SID(30, 35), 0, 0xd, TZ_MUTEX_LOCK, 1, {4}}, {TZ_SID(30, 36), 0, 0xd, TZ_MUTEX_UNLOCK, 1, {4}}, {TZ_SID(30, 37), 0, 0xd, TZ_CLEAN_PIL, 1, {4}}, {TZ_SID(30, 38), 0, 0xd, TZ_IS_ELF, 1, {4}}, {TZ_SID(30, 39), 0, 0xd, TZ_POPULATE_ELF, 3, {4}}, {TZ_SID(30, 40), 0, 0xd, TZ_DSPS_CONFIG, 1, {4}}, {TZ_SID(30, 41), 0, 0xd, TZ_VIDC_CONFIG, 1, {4}}, #endif }; /* Remove custom handlers */ static void free_handlers(void) { static const u32 orig_sec2[] = TZ_SECTION_2_ORIG; if (!scm_sc) return; /* restore section */ copy_to_tz(TZ_SECTION_2, orig_sec2, sizeof(orig_sec2)); /* free mem */ kfree(scm_sc); scm_sc = NULL; } /* Add custom handlers */ static int init_handlers(void) { static const u32 orig_map[] = BLIST_ORIG; u32 index, i, paddr, rc; struct scm_sc_s *h; /* Get new section size, check sanity of tzsids */ for (h=scm_sc_def, index=0, i=0; i<ARRAY_SIZE(scm_sc_def); i++,h++) { if (scm_call_usable(h->id) == 1){ TZ_LOG( "error: scm call %x already usable", h->id); return -EINVAL; } index += offsetof(struct scm_sc_s, args) + 4 *h->nargs; TZ_LOG( "%4x | of %d | idx %d", h->id, offsetof(struct scm_sc_s, args), index); } TZ_LOG("total size: %d", index); if (scm_sc){ TZ_LOG( "handlers already init"); return -1; } /* Clear secure_memory blacklist. */ if ((rc=clobber_it(CLOBBER_ADDR))){ TZ_LOG( "clobber failed"); return rc; } /* Alloc mem for section */ if (!(scm_sc = kzalloc(PAGE_ALIGN(index), GFP_KERNEL))) return -ENOMEM; /* copy handlers */ for (h=scm_sc_def, index=0, i=0; i<ARRAY_SIZE(scm_sc_def); i++,h++) { memcpy((u8*)scm_sc + index, (u8*)h, offsetof(struct scm_sc_s, args)+4*h->nargs); TZ_LOG( "scm_hdlr[%d] = %x %x", i, h->id, h->func); index += offsetof(struct scm_sc_s, args) + 4 *h->nargs; } /* write section */ paddr = virt_to_phys(scm_sc); write4(TZ_SECTION_2 + 4, paddr + index); write4(TZ_SECTION_2, paddr); /* check all ready */ for (h=scm_sc_def, i=0 ; i<ARRAY_SIZE(scm_sc_def); i++,h++) { if (scm_call_usable(h->id)!=1){ TZ_LOG( "call %x not usable", h->id); free_handlers(); return -1; } } /* Restore secure_memory blacklist. */ copy_to_tz(CLOBBER_ADDR, orig_map, 12); return 0; } int __init tzexec_init(void) { int rc = 0; TZ_LOG("tzexec starting"); /* Add custom smc handlers */ if ((rc=init_handlers())){ TZ_LOG( "init failed"); return 0; } #ifdef TZ_SIGN_ADDR /* generic signing disabling */ copy_to_tz(TZ_SIGN_ADDR, "\x00\x01", 2); TZ_LOG("signing gone ?!"); #endif return 0; } void __exit tzexec_exit(void) { free_handlers(); TZ_LOG("ciao bella"); } module_init(tzexec_init); module_exit(tzexec_exit); <file_sep>#ifndef DEF_TZEXEC_H #define DEF_TZEXEC_H #include <linux/types.h> int tz_memcpy(u32 dst, u32 src, u32 size); int tz_mmu_map( u32 p_addr, u32 v_addr, u32 n_pages, u32 flags ); int copy_to_tz(u32 dst, const void *src, u32 size); int copy_from_tz(void *dst, u32 src, u32 size); int tz_manual_init_image(u32 proc, u32 elf); #endif <file_sep># Disable baseband signature check in trustzone I wanted to patch the baseband firmware running on my phone (based on Qualcomm MSM8960). (ie. /etc/firmware/modem.\*). This is normally not possible, as these firmware images must be properly signed to be allowed to run. If you patch those images and try to run it, pas\_init\_image will just fail and return -2. The signature checking is enforced in the TrustZone code (partition TZ or Aboot dependign on vendor). This project provides a way to bypass this signature checking, by abusing a bug documented by <NAME> in 2014 (see docs/\*.pdf). # Compiling To use this, you will need to add this module to your android kernel (I just set it to run first when my kernel boots). It contains symbols for the Sony Xperia SP (huashan) and the Samsung Galaxy Ace 3 (s7275r). To build it, I assume you already know how to compile the kernel for your platform. I encourage you to read tzexec.c to understand a bit about what is going on. ## Samsung Galaxy Ace 3 You just need tzexec module. It will patch two bytes in tz memory and that's all you need. Copy/symlink tzexec.{c,h} in arch/arm/mach-msm/ In tzexec.c, define SAMSUNG\_ACE\_3, and undefine SONY\_XPERIA\_SP In arch/arm/mach-msm/Makefile, add the line "obj-y += tzexec.o" before scm.o Compile and run, cross your fingers, check kernel messages to ensure it worked. ## Sony Xperia SP The trustzone implementation is a bit different, and the method of patching two bytes is not enought there. I used a different method, and re-implemented the image loading in non-secure world. So you'll also need to apply the patch mach-msm.patch to call it instead of the trustzone version. Next, just follow the same steps as for Samsung (just define SONY\_XPERIA\_SP instead of SAMSUNG\_ACE\_3). Same-same: check kernel logs for success. ## Running This exploit disables the signature checking only, bute the image still need to contain the proper segment's hashes. To run arbitrary firmware images, just patch the things you want, correct the hash segment, and there you are. You can use [pymdt](https://github.com/eti1/pymdt) to do this.
602c7bcbf35debcea291a1d4114bfbb343e7773c
[ "Markdown", "C" ]
3
C
Manouchehri/tzexec
45d322ecda9f7031c016c4af7647b148fd21ab92
510a7af3d29a14b6711dbfb1f95a34b9d7a46836
refs/heads/master
<repo_name>sofa-fatuk/tonejs<file_sep>/js/main.js var piano = new Tone.Sampler({ 'c1' : './sounds/piano/c1.mp3' }, function () { piano.triggerAttackRelease('C4', '4n'); var arpeggio = new Tone.Sequence(function (time, note) { piano.triggerAttackRelease(note, '4n'); }, ['F1', 'A1', 'C2', 'D2', 'F1', 'D2', 'C2', 'A1'], '4n'); var bass = new Tone.Sequence(function (time, note) { piano.triggerAttackRelease(note, '2n'); }, ['F0', '0', '0', 'E0', 'D0', '0', 'F1', 'E1'], '4n'); Tone.Transport.start(); arpeggio.start(); bass.start(); }).toMaster(); var drums = new Tone.Sampler({ 'd1': './sounds/drums/closedhat.mp3', 'd2': './sounds/drums/cowbell1.mp3', 'd3': './sounds/drums/cowbell2.mp3', 'd4': './sounds/drums/crash1.mp3', 'd5': './sounds/drums/floor.mp3', 'd6': './sounds/drums/kick.mp3', 'd7': './sounds/drums/openhat.mp3', 'd8': './sounds/drums/ridebell.mp3', 'd9': './sounds/drums/ridecymbal2.mp3', 'd10': './sounds/drums/rim.mp3', 'd11': './sounds/drums/shaker1.mp3', 'd12': './sounds/drums/snare2.mp3', 'd13': './sounds/drums/tamb.mp3', 'd14': './sounds/drums/tom.mp3' }, function () { var main = new Tone.Sequence(function (time, note) { drums.triggerAttackRelease(note, '5n'); }, ['d6', 'd1', 'd12', 'd1', 'd6', 'd1', 'd12', ['d1', 'd1']], '4n'); var second = new Tone.Sequence(function (time, note) { drums.triggerAttack(note); }, [], '8n'); Tone.Transport.start(); main.start(); second.start(); }).toMaster(); var guitar = new Tone.Sampler({ 'c4': './sounds/guitar/Guitar_C4.mp3' }, function() { var solo = new Tone.Sequence(function (time, note) { guitar.triggerAttackRelease(note, '3n'); }, [['C5', 'E5'], ['D5', ['A4', 'G4']], 'F4', ['C4', 'E4']], '2n'); // Tone.Transport.start(); // solo.start(); }).toMaster(); var soloNotes = ['C5', 'E5', 'D5', 'A4', 'G4', 'F4', 'C4', 'E4']; var factor = 30; $(document).on('scroll', debounce(soloPlayer, 40)); function soloPlayer(e) { var position = $(this).scrollTop(); var stepSize = $(window).height(); var steps = soloNotes.length; for (var i = 0; i <= steps; i++) { if (position > stepSize * (i - 1) && position < stepSize * i) { guitar.triggerAttackRelease(soloNotes[i], '3n'); } } // if (position >= 0 && position < step) { // console.log(soloNotes[0]); // guitar.triggerAttackRelease(soloNotes[0], '3n'); // } // if (position >= step && position < step * 2) { // console.log(soloNotes[1]); // guitar.triggerAttackRelease(soloNotes[1], '3n'); // } // if (position >= step * 2 && position > step * 3) { // console.log(soloNotes[2]); // guitar.triggerAttackRelease(soloNotes[2], '3n'); // } } function debounce(func, wait, immediate) { var timeout; return function() { var context = this; var args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }<file_sep>/README.md # Учебный проект на [tone.js](https://tonejs.github.io) Здесь будут лежать, написанные мною, приложения на tone.js Посмотреть можно [здесь](https://sofa-fatuk.github.io/tonejs)
c08830af921a2775f38cb2e85313ac5d6e07523d
[ "JavaScript", "Markdown" ]
2
JavaScript
sofa-fatuk/tonejs
dd6df8ccd011ed3a1a48507a23eae3988b3b3163
9c7433c9df5627c41bc06591ea7559eef0bf6be1
refs/heads/master
<file_sep># Team Express-25 Teamwork project for TelerikAcademy season 2017, course Web Apps with NodeJS ## Description Web application for party events. A user can organize party events and join to them via reservation. ## Functionality - Creating a event - Creating a reservation - View all events - View all reservations - Update user profile settings (firstname, lastname, email) - Register - Login - Logout - Admin panel - Make reservations - Organize events ## Team members | Name | [Student system](https://telerikacademy.com) username | [Github](https://github.com) username| |:----|:-----------------------|:-----------------------------| | <NAME> | MonikaTzenova | MonikaTzenova | | <NAME> | Dankattaa | Dankatta | <file_sep>module.exports = function(data, models, validation) { function isAuth(req, result){ if (req.isAuthenticated()) { result.user = req.user; } return result; } return { getHome(req, res) { const result = isAuth(req, {}); res.render('home/home.pug', { result }); }, }; };<file_sep>module.exports = function(repository, models) { return { getEvents() { return repository.find('events', {}); }, createEvent(event) { return repository.add('events', event); }, }; }; <file_sep>module.exports = function(data, models, validation) { function isAuth(req, result){ if (req.isAuthenticated()) { result.user = req.user; } return result; } return { createReservation(req, res) { const result = isAuth(req, {}); const reservation = models.getReservation( req.body.people, req.body.place, req.body.time, req.body.name, req.body.number, req.body.date ); global.io.emit('new-reservation', reservation); data.createReservation(reservation) .then(() => { res.json({ success: 'Reservation successfull' }); }) .catch(() => { // TODO: redirect to another page res.json({ error: 'Add reservation failed' }); res.status(500).end(); }); res.redirect('/reservation'); }, getReservation(req, res) { const result = isAuth(req, {}); data.getReservations() .then((reservations)=>{ res.render('home/reservation.pug',{ reservations,result }); }) }, }; };<file_sep>const express = require('express') ,toastr = require('express-toastr'); const session = require('express-session'); const cookieParser = require('cookie-parser'); const bodyParser = require('body-parser'); module.exports = function(data) { const app = express(); app.use(require('connect-flash')()); app.use((req, res, next) => { res.locals.messages = require('express-messages')(req, res); next(); }); app.set('view engine', 'pug'); app.use('/static', express.static('public')); app.use('/libs', express.static('node_modules')); app.use(cookieParser()); app.use(bodyParser.urlencoded({ extended: true })); app.use(session({ secret: 'secret1', resave: true, saveUninitialized: true, })); require('./passport/index')(app, data); // require('passport/local-strategy')(app, data); return app; };<file_sep>module.exports = function() { class Event { constructor(title, place, time, description,date) { this.title = title; this.place = place; this.time = time; this.description = description; this.date=date; } get title() { return this._title; } set title(value) { this._title = value; } get date() { return this._date; } set date(value) { this._date = value; } get place() { return this._place; } set place(value) { this._place = value; } get time() { return this._time; } set time(value) { this._time = value; } get description() { return this._description; } set description(value) { this._description = value; } } return { getEvent(title, place, time, description,date) { return new Event(title, place, time, description,date); }, }; }; <file_sep>module.exports = function() { class Reservation { constructor(people, place, time,name,number,date) { this.date=date; this.people = people; this.place = place; this.time = time; this.number= number; this.name=name; } get date() { return this._date; } set date(value) { this._date = value; } get people() { return this._people; } set people(value) { this._people = value; } get number() { return this._number; } set number(value) { this._number = value; } get name() { return this._name; } set name(value) { this._name = value; } get place() { return this._place; } set place(value) { this._place = value; } get time() { return this._time; } set time(value) { this._time = value; } } return { getReservation(people, place, time,name,number,date) { return new Reservation(people, place, time,name,number,date); }, }; }; <file_sep>const {SHA256} = require('crypto-js'); module.exports = function(data, models, validation) { function isAuth(req, result){ if (req.isAuthenticated()) { result.user = req.user; } return result; } return { loadRegisterPage(req, res) { const result = isAuth(req, {}); return res.status(200).render('auth/register-view', { result }); }, loadLoginPage(req, res) { const result = isAuth(req, {}); return res.status(200).render('auth/login-view', { result }); }, register(req, res) { const user = models.takeUser( req.body.username, SHA256(req.body.password).toString(), req.body.firstname, req.body.lastname, req.body.email ); data.createUser(user) .then(() => { res.json({ success: 'Registration successfull' }); }) .catch(() => { // TODO: redirect to another page res.json({ error: 'Registration failed' }); res.status(500).end(); }); res.redirect('/login'); }, getProfile(req, res) { if (!req.isAuthenticated()) { //res.redirect('/unauthorized'); res.redirect('/'); } const result = isAuth(req, {}); result.title = 'Profile'; data.getUsers({ username: result.user.username }) .then((users) => { const user = users[0]; result.firstname = user._firstname; result.lastname = user._lastname; result.email = user._email; res.render('auth/profile-view', { result }); }); }, getModifyProfilePage(req, res) { const result = isAuth(req, {}); return res.status(200).render('auth/change-profile-view', { result }); }, changeProfilePage(req, res) { if (!req.isAuthenticated()) { res.redirect('/'); //res.redirect('/unauthorized'); } const result = isAuth(req, {}); const firstname = req.body.firstname; const lastname = req.body.lastname; const email = req.body.email; data.getUsers({ username: result.user.username }) .then((users) => { const user = users[0]; user._firstname = firstname; user._lastname = lastname; user._email = email; data.updateUser(user); res.redirect('/'); }) .catch((err) => { req.flash('error', err); return res.redirect('/'); }); }, logout(req, res) { req.logout(); res.status(200).redirect('/'); req.toastr.success('Successfully logged in.', "You're in!"); }, }; };<file_sep>module.exports = function(data, models, validation) { function isAuth(req, result){ if (req.isAuthenticated()) { result.user = req.user; } return result; } return { createEvent(req, res) { const result = isAuth(req, {}); const event = models.getEvent( req.body.title, req.body.place, req.body.time, req.body.description, req.body.date ); data.createEvent(event) .then(() => { res.json({ success: 'successfull' }); }) .catch(() => { // TODO: redirect to another page res.json({ error: 'Add event failed' }); res.status(500).end(); }); res.redirect('/'); }, getEvents(req,res){ const result = isAuth(req, {}); data.getEvents() .then((events)=>{ res.render('home/events.pug',{ events,result }); }) }, }; };<file_sep>const express = require('express'); const passport = require('passport'); module.exports = function(app, data, models, validation) { const controller = require('../controllers/auth-controller')(data, models, validation); const router = new express.Router(); router .get('/login', controller.loadLoginPage) .get('/register', controller.loadRegisterPage) .post('/login', passport.authenticate('local', { failureRedirect: '/error' }), function(req, res) { res.redirect('/'); }) .post('/register', controller.register) .get('/profile', controller.getProfile) .get('/profile', controller.getProfile) .post('/profile', (req, res) => res.redirect('/profile-change')) .get('/profile-change', controller.getModifyProfilePage) .post('/profile-change', controller.changeProfilePage) .get('/logout', controller.logout) app.use('/', router); }; <file_sep>module.exports = { validateStringLength(value, minLength, maxLength) { if (!value || typeof value !== 'string' || value.length < minLength || value.length > maxLength) { throw new Error('Invalid input length!'); } }, validatePasswordsMatch(pass, passConfirm) { if (pass !== passConfirm) { throw new Error('Password does not match password confirmation!'); } }, }; <file_sep>module.exports = function(repository, models) { return { getReservations() { return repository.find('reservations', {}); }, createReservation(reservation) { return repository.add('reservations', reservation); }, }; }; <file_sep>module.exports = function(repository, models) { return { findUserById(id) { return repository.findOne('users', id); }, findUserByCredentials(username, password) { const searchedUser = models.getBaseUser(username, password); return repository.findOne('users', searchedUser); }, createUser(user) { return repository.add('users', user); }, getUsers(filter) { return repository.find('users', filter); }, updateUser(filter) { return repository.update('users', filter); } }; }; <file_sep>module.exports = function(data, models, validation) { function isAuth(req, result){ if (req.isAuthenticated()) { result.user = req.user; } return result; } return { getUserbyId(req, res) { const result = isAuth(req, {}); const id=req.params.id; data.findUserById(id) .then((user)=> res.render('user/user.pug', { user , result})); }, getUsers(req,res) { const result = isAuth(req, {}); data.getUsers() .then((users)=> res.render('user/users.pug',{users, result})); }, }; };<file_sep>module.exports = { PORT: 3001, DB_URL: 'mongodb://localhost:27017/expressDB', }; <file_sep>const express = require('express'); module.exports = function(app, data, models, validation) { const controller = require('../controllers/event-controller')(data, models, validation); const router = new express.Router(); router .post('/add-event', controller.createEvent) .get('/events', controller.getEvents) app.use('/', router); };<file_sep>const {SHA256} = require('crypto-js'); module.exports = function(constants, validator) { class BaseUser { constructor(user, pass) { this.user = user; this.pass = pass; } get user() { return this.username; } set user(value) { validator.validateStringLength(value, constants.MIN_USERNAME_LENGTH, constants.MAX_USERNAME_LENGTH); this.username = value.trim(); } get pass() { return this.password; } set pass(value) { validator.validateStringLength(value, constants.MIN_PASSWORD_LENGTH, constants.MAX_PASSWORD_LENGTH); this.password = value.trim().toString(); } } class User extends BaseUser { constructor(user, pass, firstname, lastname, email) { super(user, pass); this.firstname = firstname; this.lastname = lastname; this.email = email; } get firstname() { return this._firstname; } set firstname(value) { this._firstname = value; } get lastname() { return this._lastname; } set lastname(value) { this._lastname = value; } get email() { return this._email; } set email(value) { this._email = value; } } return { getBaseUser(user, pass) { return new BaseUser(user, SHA256(pass).toString()); }, takeUser(user, pass, firstname, lastname, email) { return new User(user, pass, firstname, lastname, email); }, }; };
0119aa83ab7205d148ec935635aff9c503e9043d
[ "Markdown", "JavaScript" ]
17
Markdown
MonikaTzenova/Express-25
8c53eaf57d03409533d4c0456d4e54444cc0cea4
377109b9a0b0246df34e469a2ee82c1b61ef3826
refs/heads/master
<file_sep> sea = {} local waves = { backWave = { image = love.graphics.newImage("graphics/sea/back.png"), x1 = -1280, x2 = 0, y = 0, speed = 6, --3.5 up = true, upSpeed = 3, --2.5 startPos = 0, delta = 5 }, middleWave = { image = love.graphics.newImage("graphics/sea/middle.png"), x1 = -1280, x2 = 0, y = 0, speed = 7.5, --6.5 up = true, upSpeed = 2.5, --2 startPos = 0, delta = 8 }, frontWave = { image = love.graphics.newImage("graphics/sea/front.png"), x1 = -1280, x2 = 0, y = 0, speed = 9.5, --8.5 up = true, upSpeed = 1.5, --1.5 startPos = 0, delta = 5 } } function sea.update(dt) for k,v in pairs(waves) do -- Vertical wave moving v.x1 = v.x1 + v.speed * dt v.x2 = v.x2 + v.speed * dt if v.x1 > love.window.getWidth() then v.x1 = -love.window.getWidth() end if v.x2 > love.window.getWidth() then v.x2 = -love.window.getWidth() end -- Horizontal wave moving if v.up then v.y = v.y - v.upSpeed * dt else v.y = v.y + v.upSpeed * dt end if v.y < v.startPos then v.up = false end if v.y > v.startPos + v.delta then v.up = true end end end function sea.draw() love.graphics.draw(waves.backWave.image, waves.backWave.x1, waves.backWave.y) love.graphics.draw(waves.backWave.image, waves.backWave.x2, waves.backWave.y) love.graphics.draw(waves.middleWave.image, waves.middleWave.x1, waves.middleWave.y) love.graphics.draw(waves.middleWave.image, waves.middleWave.x2, waves.middleWave.y) love.graphics.draw(waves.frontWave.image, waves.frontWave.x1, waves.frontWave.y) love.graphics.draw(waves.frontWave.image, waves.frontWave.x2, waves.frontWave.y) end <file_sep> --[[ ~ ~ ~ TOOL KIT ~ ~ ~ Used to add own custom functions ]]-- function math.clamp(val, lower, upper) assert(val and lower and upper, "not very useful error message here") if lower > upper then lower, upper = upper, lower end -- swap if boundaries supplied the wrong way return math.max(lower, math.min(upper, val)) end function isColliding(a,b) return not ((a.X > b.x + b.width) or (b.x > a.X + a.width) or (a.Y > b.y + b.height) or (b.y > a.Y + a.height)) end function playerIsHit() if player.isHit then love.graphics.setColor(255, 0, 0, 100) love.graphics.rectangle("fill", 0, 0, love.window.getWidth(),love.window.getHeight()) love.graphics.setColor(255, 255, 255, 255) end end function reSpawn() objects.player.body:setX(640) objects.player.body:setY(360) player.X = objects.player.body:getX() player.Y = objects.player.body:getY() end <file_sep>fish = class() fish.image = love.graphics.newImage("graphics/npcs/fish.png") local heigh = fish.image:getHeight()*0.3 local width = fish.image:getWidth()*0.3 --fish.grid = anim8.newGrid(width,height,width,height) function fish:init() --spawn rett utenfor window self.decider = math.random(0,1) self.moveSpeed = math.random(1,2)*100 self.height = fish.image:getHeight()*0.3 self.width = fish.image:getWidth()*0.3 self.isHooked = false if self.decider < 0.5 then self.x = 0 - self.width --starter på venstre side else self.x = love.window.getWidth() --starter på høyre side end --410 is the the y under raft self.y = math.random(410 + self.height, love.window.getHeight() - self.height) end function fish:update(dt) if (hook.x < self.x+5 and hook.x > self.x-5) and (hook.y < self.y+5 and hook.y > self.y-10) and not hook.fishOnHook then self.isHooked = true hook.fishOnHook = true end if self.isHooked then if self.decider < 0.5 then self.x = (hook.x - self.width/1.5) self.y = (hook.y + hook.height/2) else self.x = (hook.x) self.y = (hook.y + hook.height/2) end else if self.decider < 0.5 then self.x = self.x + self.moveSpeed * dt else self.x = self.x - self.moveSpeed * dt end end end function fish:draw() if self.decider < 0.5 then --love.graphics.rectangle("fill", self.x, self.y, self.width, self.height) love.graphics.draw(fish.image, self.x+self.width, self.y, 0, -0.3, 0.3) else --love.graphics.rectangle("fill", self.x, self.y, self.width, self.height) love.graphics.draw(fish.image, self.x, self.y, 0, 0.3, 0.3) --speil langs y-aksen? end end <file_sep>spawn = {} function spawn.load() -- Load for fishes fishes = {} fishes.counter = 0 fishes.timer = 0 fishes.table = {} maxFish = 3 --Load for sharks sharks = {} sharks.counter = 0 sharks.timer = 0 sharks.table = {} end function spawn.update(dt) updateFish(dt) updateSharks(dt) end function spawn.draw() -- Fishes for i,v in ipairs(fishes.table) do v:draw() end for i,v in ipairs(sharks.table) do v:draw() end --love.graphics.printf("Fishes: "..#fishes.table, 200, 30, 100, 'left') --love.graphics.printf("Sharks: "..#sharks.table, 300, 30, 100, 'left') --love.graphics.printf("hook.y:"..hook.y, 400, 30, 100, 'left') end function spawn.setMaxFish(max) maxFish = max end -- Updating the fishes function updateFish(dt) fishes.timer = (fishes.timer + dt) if fishes.timer > maxFish then fishes.timer = (fishes.timer - 3) if fishes.counter < 3 then local f = fish:new() table.insert(fishes.table, f) fishes.counter = (fishes.counter + 1) end end for i,v in ipairs(fishes.table) do v:update(dt) if v.x < 0-v.width and v.decider > 0.5 or v.x > love.window.getWidth() and v.decider < 0.5 then table.remove(fishes.table, i) fishes.counter = (fishes.counter - 1) end if hook.y == 350 and v.isHooked then table.remove(fishes.table, i) fishes.counter = (fishes.counter - 1) hook.fishOnHook = false HUD.increaseFood() HUD.increaseFood() HUD.addFishEaten() end end end --Updating the sharks function updateSharks(dt) sharks.timer = (sharks.timer + dt) if sharks.timer > 3 then sharks.timer = (sharks.timer - 3) if sharks.counter < 5 then local s = shark:new() table.insert(sharks.table, s) sharks.counter = (sharks.counter + 1) end end for i,v in ipairs(sharks.table) do v:update(dt) if v.x < 0-v.width and v.decider >= 0.5 or v.x > love.window.getWidth() and v.decider <= 0.5 then table.remove(sharks.table, i) sharks.counter = (sharks.counter - 1) end end end <file_sep> player = {} function player.load() --PLAYER IMAGES --player.standImg = love.graphics.newImage() player.walkImage = love.graphics.newImage("graphics/player/walking.png") player.jumpImage = love.graphics.newImage("graphics/player/jump.png") --PLAYER ANIMATIONS player.image = love.graphics.newImage("graphics/player/stand.png") player.X = 640 player.Y = 360 player.baseY = 360 player.scale = 4 player.width = player.image:getWidth()/player.scale player.height = player.image:getHeight()/player.scale local grid = anim8.newGrid(player.image:getWidth(), player.image:getHeight(), player.walkImage:getWidth(), player.walkImage:getHeight()) player.walkAnimation = anim8.newAnimation(grid('1-4',1), 0.1) player.diretion = "right" player.status = "stand" player.lives = 10.0 player.isHit = false player.wasHit = player.isHit player.alive = true player.startPos = 0 player.jumpings = false -- Creating physics object of the player objects.player = {} objects.player.body = love.physics.newBody(world, player.X, player.Y, "dynamic") objects.player.shape = love.physics.newRectangleShape(player.width, player.height) objects.player.fixture = love.physics.newFixture(objects.player.body, objects.player.shape, 0.45) objects.player.fixture:setRestitution(0.4) objects.player.body:setFixedRotation(true) -- Create map boundries objects.leftBox = {} objects.leftBox.body = love.physics.newBody(world, -1, -1, "static") objects.leftBox.shape = love.physics.newRectangleShape(1,love.window.getHeight()*2) objects.leftBox.fixture = love.physics.newFixture(objects.leftBox.body, objects.leftBox.shape) objects.rightBox = {} objects.rightBox.body = love.physics.newBody(world, love.window.getWidth(), 0, "static") objects.rightBox.shape = love.physics.newRectangleShape(1,love.window.getHeight()*2) objects.rightBox.fixture = love.physics.newFixture(objects.rightBox.body, objects.rightBox.shape) objects.bottomBox = {} objects.bottomBox.body = love.physics.newBody(world, 0, love.window.getHeight(), "static") objects.bottomBox.shape = love.physics.newRectangleShape(love.window.getWidth()*2,0) objects.bottomBox.fixture = love.physics.newFixture(objects.bottomBox.body, objects.bottomBox.shape) end function player.update(dt) player.X = objects.player.body:getX() player.Y = objects.player.body:getY() player.status = "stand" xVel,yVel = objects.player.body:getLinearVelocity() xVelMax = 150 yVelMax = 100 -- Keyboard Events if not (xVel < -xVelMax) then if love.keyboard.isDown("left") then player.status = "walk" player.walkAnimation:update(dt) if objects.player.body:getY() > raft.Y - 25 then objects.player.body:applyForce(-200,0) end end end if not (xVel > xVelMax) then if love.keyboard.isDown("right") then player.status = "walk" player.walkAnimation:update(dt) if objects.player.body:getY() > raft.Y - 25 then objects.player.body:applyForce(200,0) end end end player.jumping() if love.keyboard.isDown("down") then objects.player.body:applyForce(0, 200) end -- Set player shape if under water or not if (objects.player.body:getY() > raft.Y + raft.delta) then objects.player.body:applyForce(0, -220) --objects.player.shape = love.physics.newRectangleShape(40,25) else --objects.player.body:applyForce(0, -300) --objects.player.shape = love.physics.newRectangleShape(25,40) end -- Force control if high up if (objects.player.body:getY() > raft.Y + raft.delta + 300) then objects.player.body:applyForce(0, -300) end if ((objects.player.body:getY() < raft.Y + raft.delta) and ((objects.player.body:getX() < raft.X - 300) or (objects.player.body:getX() > raft.X + 300))) then if(yVel < 0) then objects.player.body:setLinearVelocity(xVel, 0.1 * yVel) end end player.isHit = false for i,v in ipairs(sharks.table) do if isColliding(player,v) then player.isHit = true end end if player.wasHit == false and player.isHit == true then audio.hit:play() HUD.reduceHealth() HUD.reduceHealth() --reSpawn() end player.wasHit = player.isHit end function player.draw() if player.status == "stand" then --love.graphics.rectangle("fill",player.X - player.width/2, player.Y - player.height/2, player.width, player.height) love.graphics.draw(player.image, objects.player.body:getX(), objects.player.body:getY(), 0, (1/player.scale), (1/player.scale), player.image:getWidth()/2, player.image:getHeight()/2) elseif player.status == "walk" then player.walkAnimation:draw(player.walkImage, objects.player.body:getX(), objects.player.body:getY(), 0, (1/player.scale), (1/player.scale), player.image:getWidth()/2, player.image:getHeight()/2) elseif player.status == "jumping" or player.status == "falling" then love.graphics.draw(player.jumpImage, objects.player.body:getX(), objects.player.body:getY(), 0, (1/player.scale), (1/player.scale), player.image:getWidth()/2, player.image:getHeight()/2) end --love.graphics.printf("X:"..player.X, 10, 100, 100, 'left') --love.graphics.printf("Y:"..player.Y, 10, 150, 100, 'left') end function player.jumping() if player.Y <= player.startPos - 10 then player.jumpings = false player.status = "falling" elseif player.jumpings == true then objects.player.body:applyForce(0,-500) player.status = "jumping" elseif player.Y >= player.startPos then end --[[if player.Y >= player.startPos then player.jumpings = false end]]-- end function player.jump() if player.jumpings == false then if player.Y < raft.Y + raft.delta then audio.jump:play() end player.status = "jumping" player.startPos = player.Y player.jumpings = true end end <file_sep>shark = class() shark.image = love.graphics.newImage("graphics/npcs/shark.png") --local height = fish.image:getHeight()*0.2 --local width = fish.image:getWidth()*0.2 --fish.grid = anim8.newGrid(width,height,width,height) function shark:init() --spawn rett utenfor window self.scale = 0.7 self.decider = math.random(0,1) self.moveSpeed = math.random(1,2)*100 self.height = shark.image:getHeight()*self.scale self.width = shark.image:getWidth()*self.scale self.isHooked = false if self.decider < 0.5 then self.x = 0 - self.width --starter på venstre side else self.x = love.window.getWidth() --starter på høyre side end --410 is the the y under raft self.y = math.random(410 + self.height, love.window.getHeight() - self.height) end function shark:update(dt) if self.decider < 0.5 then self.x = self.x + self.moveSpeed * dt else self.x = self.x - self.moveSpeed * dt end end function shark:draw() if self.decider < 0.5 then --love.graphics.rectangle("fill", self.x, self.y, self.width, self.height) love.graphics.draw(shark.image, self.x+self.width, self.y-self.height, 0, -self.scale, self.scale) else --love.graphics.rectangle("fill", self.x, self.y, self.width, self.height) love.graphics.draw(shark.image, self.x, self.y-self.height, 0, self.scale, self.scale) --speil langs y-aksen? end end <file_sep> shaders = {} function shaders.load() shader = love.graphics.newShader[[ extern number intensity; vec4 effect(vec4 color, Image texture, vec2 texture_coords, vec2 screen_coords){ vec4 pixel = Texel(texture, texture_coords); pixel.r = pixel.r * intensity; pixel.g = pixel.g * intensity; pixel.b = pixel.b * intensity; return pixel; } ]] updown = false intensity = 0.5 end function shaders.update(dt) intensity = math.clamp(skies.getTime(), 0.5, 1) end<file_sep># Gamejam Game made at Sonen Gamejam. 48 hours to create a game with theme "Float" # Credits ###Development and Graphics: - Daniel (Blt950) - <NAME> - <NAME> ###Assisting Graphics: - Flaticon.com ###Font: - Seagull Wine by <NAME> at DaFont.com ### Music: - "Ondina", The Blessed Islands Album by Ton at Jamendo.com - "Watery", The Blessed Islands Album by Ton at Jamendo.com ### Sounds: - Jump by LloydEvans09 at Freesound.org - Hit by Under7dude at Freesound.org - Splash by HQSFX at Youtube.com <file_sep> HUD = {} HUD.showMenu = 0 font = love.graphics.newFont("graphics/fonts/seagull_wine.ttf", 42) function HUD.load() love.graphics.setBackgroundColor(80,219,255) love.window.setMode(1280,720) --font = love.graphics.newFont(24) love.graphics.setFont(font) --FoodF img_food_empty = love.graphics.newImage("graphics/hud/chicken bone/chicken-bone-empty.png") img_food_half = love.graphics.newImage("graphics/hud/chicken bone/chicken-bone-half.png") img_food_full = love.graphics.newImage("graphics/hud/chicken bone/chicken-bone-full.png") foodXpos = love.window.getWidth() - 240 foodYpos = 80 foodTimerReset = 200 foodTimer = foodTimerReset foodTimer2Reset = foodTimerReset foodTimer2 = foodTimer2Reset food = 6 foodTable = {2,2,2} --alle tre er fulle --2 = draw full --1 == draw half --0 == draw empty --Food end hungerTimerReset = 300 hungerTimer = hungerTimerReset fishEaten = 0 --Health img_health_empty = love.graphics.newImage("graphics/hud/heart/heart-empty.png") img_health_half = love.graphics.newImage("graphics/hud/heart/heart-half.png") img_health_full = love.graphics.newImage("graphics/hud/heart/heart-full.png") healthXpos = love.window.getWidth() - 240 healthYpos = 20 health = 6 healthTable = {2,2,2} --Health end started = false end local function drawChickenBone(i, index) if i == 0 then love.graphics.draw(img_food_empty, foodXpos + (index * img_food_empty:getWidth() * 0.1), foodYpos, 0, 0.1, 0.1) elseif i == 1 then love.graphics.draw(img_food_half, foodXpos + (index * img_food_half:getWidth() * 0.1), foodYpos, 0, 0.1, 0.1) elseif i == 2 then love.graphics.draw(img_food_full, foodXpos + (index * img_food_full:getWidth() * 0.1), foodYpos, 0, 0.1, 0.1) end end local function drawFood() for i = 1, 3 do drawChickenBone(foodTable[i], i) end end local function drawHeart(i, index) if i == 0 then love.graphics.draw(img_health_empty, healthXpos + (index * img_health_empty:getWidth() * 0.1), healthYpos, 0, 0.1, 0.1) elseif i == 1 then love.graphics.draw(img_health_half, healthXpos + (index * img_health_half:getWidth() * 0.1), healthYpos, 0, 0.1, 0.1) elseif i == 2 then love.graphics.draw(img_health_full, healthXpos + (index * img_health_full:getWidth() * 0.1), healthYpos, 0, 0.1, 0.1) end end local function drawHealth() for i = 1, 3 do drawHeart(healthTable[i], i) end end local function reduceTable(table) for i = #table, 1, -1 do if table[i] > 0 then table[i] = table[i] - 1 break end end end local function increaseTable(table) for i = 1, #table do if table[i] < 2 then table[i] = table[i] + 1 break end end end function HUD.draw() if HUD.showMenu == 1 then love.graphics.setColor(50, 50, 50, 200) love.graphics.rectangle("fill", 0, 0, love.window.getWidth(),love.window.getHeight()) love.graphics.setColor(255, 255, 255, 255) local titleFont = love.graphics.newFont("graphics/fonts/seagull_wine.ttf", 128) love.graphics.setFont(titleFont) love.graphics.printf("Survival Float", 1280/2-(200/2), 720/2-150, 200, "center") love.graphics.setFont(font) love.graphics.printf("Press 'space' to start the game", (1280/2)-(1000/2), (720/2)+300, 1000, "center") local creditsFont = love.graphics.newFont("graphics/fonts/seagull_wine.ttf", 14) love.graphics.setFont(creditsFont) love.graphics.printf("Development and Graphics: Daniel, <NAME>, <NAME>", 10, 10, 1000, "left") love.graphics.printf("Music by: Ton at jamendo.com", 10, 30, 1000, "left") love.graphics.setFont(font) elseif player.alive then love.graphics.setColor(255,255,255) drawFood() drawHealth() love.graphics.print("Days: "..skies.getDay(), 10, 30) love.graphics.print("Score: "..fishEaten, 10, 70) end if not player.alive then love.graphics.setColor(50, 50, 50, 200) love.graphics.rectangle("fill", 0, 0, love.window.getWidth(),love.window.getHeight()) love.graphics.setColor(255, 255, 255, 255) local titleFont = love.graphics.newFont("graphics/fonts/seagull_wine.ttf", 128) love.graphics.setFont(titleFont) love.graphics.printf("You died!", 1280/2-(200/2), 720/2-150, 200, "center") love.graphics.setFont(font) love.graphics.printf("Score: "..fishEaten*skies.getDay(), (1280/2)-(1000/2), (720/2)+100, 1000, "center") love.graphics.printf("Press 'space' to start new game", (1280/2)-(1000/2), (720/2)+300, 1000, "center") end --love.graphics.printf("FPS: "..love.timer.getFPS(), 0, 0, 100, 'left') end function HUD.update(dt) if love.keyboard.isDown(" ") and HUD.showMenu > 0 then HUD.showMenu = 0 started = true audio.menuMusic:stop() audio.music:play() end if love.keyboard.isDown(" ") and not player.alive then audio.menuMusic:stop() audio.music:stop() HUD.showMenu = 0 love.load() end --[[if (skies.getTime() < 0) then HUD.reduceFood() elseif (skies.getTime() > 1) then HUD.reduceFood() end]]-- hungerTimer = hungerTimer - 50*dt if hungerTimer < 0 then HUD.reduceFood() hungerTimer = hungerTimerReset end if food == 6 then foodTimer = foodTimer - 100*dt if foodTimer < 0 then HUD.increaseHealth() foodTimer = foodTimerReset end else foodTimer = foodTimerReset end if food == 0 then foodTimer2 = foodTimer2 -1 if foodTimer2 == 0 then HUD.reduceHealth() foodTimer2 = foodTimer2Reset end else foodTimer2 = foodTimer2Reset end -- Kill the player if health == 0 then player.alive = false end end function HUD.addFishEaten() fishEaten = fishEaten + 1 end function HUD.reduceFood() reduceTable(foodTable) if food > 0 then food = food - 1 end end function HUD.increaseFood() increaseTable(foodTable) hungerTimer = hungerTimerReset if food < 6 then food = food + 1 end end function HUD.reduceHealth() reduceTable(healthTable) if health > 0 then health = health - 1 end end function HUD.increaseHealth() increaseTable(healthTable) if health < 6 then health = health + 1 end end <file_sep>--[[ ~ ~ ~ SURVIVAL FLOAT ~ ~ ~ by: Daniel, <NAME> and <NAME> ]]-- local created = false function love.load(arg) -- Window configuration love.window.setMode(1280,720) love.window.setTitle("Survival Float") if not created then -- Import the physics init require("physics") physics.load() -- Import the required libaries anim8 = require("assets/anim8") require("assets/class") require("assets/toolkit") require("assets/shaders") shaders.load() -- Import our classes require("classes/player") player.load() require("classes/environment/skies") skies.load() require("classes/environment/sunmoon") skyObjs.load() require("classes/environment/clouds") clouds.load() require("classes/environment/sea") require("classes/raft/rod") rod.load() require("classes/raft/raft") raft.load() require("classes/hud") HUD.load() require("classes/npcs/fish") require("classes/npcs/shark") require("classes/spawn") spawn.load() require("classes/audio") audio.load() HUD.showMenu = 1 created = true else physics.load() shaders.load() player.load() skies.load() skyObjs.load() clouds.load() rod.load() raft.load() HUD.load() spawn.load() audio.load() end audio.music:stop() audio.menuMusic:play() end function love.update(dt) if HUD.showMenu == 0 and player.alive then physics.update(dt) shaders.update(dt) skies.update(dt) clouds.update(dt) sea.update(dt) raft.update(dt) player.update(dt) spawn.update(dt) rod.update(dt) end HUD.update(dt) end function love.draw() skies.draw() shader:send("intensity", intensity) love.graphics.setShader(shader) sea.draw() raft.draw() player.draw() clouds.draw() rod.draw() spawn.draw() love.graphics.setShader() physics.draw() playerIsHit() HUD.draw() --love.graphics.rectangle("fill",player.X - player.width/2, player.Y - player.height/2, player.width, player.height) end function love.keypressed(key) if key == "escape" then love.event.push("quit") end if key == "up" then player.jump(key) end end <file_sep> raft = {} local raftImage = love.graphics.newImage("graphics/raft/raft.png") function raft.load() raft.X = 640 raft.Y = 320 raft.delta = 88 -- Crafting the raft floor objects.raft = {} objects.raft.body = love.physics.newBody(world, raft.X, raft.Y + raft.delta, "static") objects.raft.shape = love.physics.newRectangleShape(300,20) objects.raft.fixture = love.physics.newFixture(objects.raft.body, objects.raft.shape) -- Crafting the raft left side objects.raftLeft = {} objects.raftLeft.body = love.physics.newBody(world, raft.X - 140, raft.Y + raft.delta - 20, "static") objects.raftLeft.shape = love.physics.newRectangleShape(15, 20) objects.raftLeft.fixture = love.physics.newFixture(objects.raftLeft.body, objects.raftLeft.shape) -- Crafting the raft right side objects.raftRight = {} objects.raftRight.body = love.physics.newBody(world, raft.X + 140, raft.Y + raft.delta - 20, "static") objects.raftRight.shape = love.physics.newRectangleShape(15, 20) objects.raftRight.fixture = love.physics.newFixture(objects.raftRight.body, objects.raftLeft.shape) end function raft.update(dt) end function raft.draw() love.graphics.draw(raftImage, 640, 320, 0, 1, 1, raftImage:getWidth()/2, raftImage:getHeight()/2) end<file_sep>rod = {} function rod.load() --ROD rod.image = love.graphics.newImage("graphics/raft/rod.png") rod.x = 780 rod.y = 300 rod.width = rod.image:getWidth()*0.5 rod.hight = rod.image:getHeight()*0.5 rod.inUse = false --HOOK hook = {} hook.image = love.graphics.newImage("graphics/raft/hook.png") hook.x = rod.x+rod.width-14 hook.y = 350 hook.width = hook.image:getWidth()*0.5 hook.height = hook.image:getHeight()*0.5 hook.speed = 200 hook.fishOnHook = false end function rod.update(dt) playerAtRod() if rod.inUse then if love.keyboard.isDown("a") and not love.keyboard.isDown("d") and rod.inUse then hook.y = hook.y + (hook.speed * dt) if hook.y > (love.window.getHeight()-hook.height) then hook.y = (love.window.getHeight()-hook.height) end end if love.keyboard.isDown("d") and not love.keyboard.isDown("a") and rod.inUse then hook.y = hook.y - (hook.speed * dt) if hook.y < 350 then hook.y = 350 end end end end function rod.draw() love.graphics.draw(rod.image, rod.x, rod.y, 0, 0.5, 0.5) love.graphics.draw(hook.image, hook.x, hook.y, 0, 0.5, 0.5) love.graphics.line(rod.x+rod.width, rod.y, hook.x+hook.width-4, hook.y) end function playerAtRod() if (player.X >= (753-10) and player.X <= 756) and (player.Y >= 364 and player.Y <= 367) then rod.inUse = true else rod.inUse = false end end<file_sep> physics = {} objects = {} function physics.load() love.physics.setMeter(64) world = love.physics.newWorld(0, 9.81*64, true) end function physics.update(dt) world:update(dt) end function physics.draw() --love.graphics.polygon("fill", objects.raftRight.body:getWorldPoints(objects.raftRight.shape:getPoints())) end<file_sep> audio = {} function audio.load() audio.music = love.audio.newSource("sounds/music/ondina.mp3") audio.music:setLooping(true) audio.menuMusic = love.audio.newSource("sounds/music/watery.mp3") audio.menuMusic:setLooping(true) audio.splash = love.audio.newSource("sounds/splash.mp3") audio.hit = love.audio.newSource("sounds/hit.wav") audio.jump = love.audio.newSource("sounds/jump.wav") end --brukes: --splash:play()<file_sep> skies = {} local time = 1.0 local speed = 0.025 local day = true local cycle = 0 local starImage = love.graphics.newImage("graphics/skies/stars.png") local starSpeed = 2 local starX = -1280 local starAlpha = 0 function skies.load() starAlpha = 0 time = 1.0 end function skies.update(dt) if day then time = time + speed * dt if time > 1 then day = false starX = -1280 end else time = time - speed * dt if time < 0 then day = true cycle=cycle+1 end end starX = starX + starSpeed * dt skyObjs.update(dt, skies.getTime(), skies.getSpeed()) --spawn.setMaxFish(3) if cycle == 2 then spawn.setMaxFish(2) elseif cycle == 5 then spawn.setMaxFish(1) end end function skies.draw() love.graphics.setColor(178,232,255,255*time) love.graphics.rectangle("fill", 0, 0, love.window.getWidth(), love.window.getHeight()) love.graphics.setColor(255,255,255, 255) local starAlpha = (255)*(-1*time*2+1) love.graphics.setColor(255,255,255, math.clamp(starAlpha, 0, 255)) love.graphics.draw(starImage, starX, 0) love.graphics.setColor(255,255,255,255) --love.graphics.printf("Day:"..cycle, 10, 10, 100, 'left') --love.graphics.printf("Time:"..time, 150, 0, 100, 'left') skyObjs.draw() end function skies.getDay() return cycle end function skies.getTime() return time end function skies.getSpeed() return speed end <file_sep> clouds = {} function clouds.load() love.window.setMode(1280,720) love.graphics.setBackgroundColor(80,219,255) img_cloud = love.graphics.newImage("graphics/skies/cloud/cloud.png") img_rain_cloud = love.graphics.newImage("graphics/skies/cloud/raincloud.png") cloudScale = 0.4 img_width = img_cloud:getWidth() cloudXpos = {-img_width,-img_width, -img_width,-img_width, -img_width} cloudYpos = {25,25,25,25,25} cloudSpeed = {1,1,1,1,1} --raining = {false, false, false, false, false} cloudTable = {0,0,0,0,0} --up to 5 clouds --0 = no cloud --1 = cloud --2 = rain cloud waitTimer = 15 waitReset = 15 + math.random(0, 15) cloudCount = 0 --rainChance = 10 end local function deleteCloud(i) cloudTable[i] = 0 cloudXpos[i] = -img_width cloudYpos[i] = 50 cloudCount = cloudCount -1 --raining[i] = false end local function updateCloud(i) if cloudTable[i] > 0 then cloudXpos[i] = cloudXpos[i] + cloudSpeed[i] if cloudXpos[i] > love.window.getWidth() + img_width then deleteCloud(i) end end end local function spawnCloud() for i = 1, #cloudTable do if cloudTable[i] == 0 then cloudTable[i] = math.random(1,2) --if cloudTable[i] == 2 then -- if math.random(0,100) < rainChance then -- raining[i] = true -- end --end cloudYpos[i] = math.random(25, 100) cloudSpeed[i] = 1 + math.random(0, 1) break end end end function clouds.update(dt) waitTimer = waitTimer - 0.1 if waitTimer < 0 then if cloudCount < 5 then spawnCloud() cloudCount = cloudCount + 1 end waitTimer = waitReset end for i = 1, #cloudTable do updateCloud(i) end end function clouds.draw() for i = 1, #cloudTable do if cloudSpeed[i] < 2 then cloudScale = -0.3 else cloudScale = 0.4 end if cloudTable[i] == 1 then love.graphics.draw(img_cloud, cloudXpos[i], cloudYpos[i], 0, cloudScale, cloudScale) elseif cloudTable[i] == 2 then love.graphics.draw(img_rain_cloud, cloudXpos[i], cloudYpos[i], 0, cloudScale, cloudScale) --if (raining[i]) then -- love.graphics.setColor(255,255,255) -- love.graphics.print("RAIN CLOUD", cloudXpos[i], cloudYpos[i]) --end end end end <file_sep>skyObjs = {} sun = {} moon = {} curve = {} sunImage = love.graphics.newImage("graphics/skies/sun.png") moonImage = love.graphics.newImage("graphics/skies/moon.png") function skyObjs.load() curve.a = 0.0 curve.r = 680 curve.speed = 0.3141592/(0.1/skies.getSpeed()) curve.x = 1280/2 curve.y = 720 moon.r = 50 moon.x = -500 moon.y = -500 sun.r = 50 sun.x = -500 sun.y = -500 end function skyObjs.update(dt, time, speed) if curve.r <= 400 then curve.r = curve.r + 15 if curve.r >= 680 then curve.r = 680 curve.mid = true end elseif curve.r >= 680 then curve.r = curve.r - 15 if curve.r <= 400 then curve.r = 400 curve.mid = true end end curve.a = curve.a + curve.speed * dt sun.x = curve.x - curve.r * math.sin(curve.a) sun.y = curve.y - curve.r * math.cos(curve.a) moon.x = curve.y + curve.r * math.sin(curve.a) moon.y = curve.y + curve.r * math.cos(curve.a) if curve.a == 1 then curve.a = 0 end end function skyObjs.draw() love.graphics.draw(sunImage, sun.x, sun.y, 0, 0.20, 0.20, sunImage:getWidth()/2, sunImage:getHeight()/2) love.graphics.draw(moonImage, moon.x, moon.y, 0, 0.18, 0.18, moonImage:getWidth(), moonImage:getHeight()/2) end
93b02beb013bf2688517ff35751036fa0a3330fd
[ "Markdown", "Lua" ]
17
Lua
blt950/gamejam
d6dfadb3f8374b7cda1c36fa8accea5fcf2fd585
9f85d517947d953cc8352f15c16db66ea27eb6b1
refs/heads/main
<repo_name>Swaroog23/Netguru-recruitment-task<file_sep>/task_api/conftest.py from task_api.models import Car, CarRating import pytest @pytest.fixture def create_objects(): car1 = Car.objects.create(make="HONDA", model="Civic") car2 = Car.objects.create(make="HONDA", model="CR-V") car3 = Car.objects.create(make="HONDA", model="Accord") CarRating.objects.create(car_id=car1.id, rating=3) CarRating.objects.create(car_id=car2.id, rating=3) CarRating.objects.create(car_id=car3.id, rating=3)<file_sep>/task_api/serializers.py from django.db.models import fields from task_api.models import Car, CarRating from rest_framework import serializers class CarSerializerWithAvgRating(serializers.ModelSerializer): avg_rating = serializers.FloatField() class Meta: model = Car fields = "__all__" class CarSerializerWithRatingCount(serializers.ModelSerializer): rates_number = serializers.IntegerField() class Meta: model = Car fields = "__all__" class CarRatingSerializer(serializers.ModelSerializer): class Meta: model = CarRating fields = "__all__"<file_sep>/task_api/migrations/0004_alter_car_model.py # Generated by Django 3.2.7 on 2021-09-10 17:30 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('task_api', '0003_alter_carrating_rating'), ] operations = [ migrations.AlterField( model_name='car', name='model', field=models.CharField(max_length=100, unique=True), ), ] <file_sep>/task_api/views.py from task_api.validators import ( validate_list_of_models_exists, validate_post_rate_request_data, validate_post_car_request_data, ) from django.core.exceptions import ObjectDoesNotExist from django.db.models.aggregates import Avg, Count from task_api.serializers import ( CarRatingSerializer, CarSerializerWithAvgRating, CarSerializerWithRatingCount, ) from task_api.services import get_models_for_make from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.renderers import ParseError from .models import Car from django.db import IntegrityError from rest_framework.exceptions import NotFound from rest_framework.decorators import api_view class CarViews(APIView): def get(self, request): cars = Car.objects.annotate(avg_rating=Avg("rating__rating")) serialized_cars_with_avg_rating = CarSerializerWithAvgRating( cars.values(), many=True ).data return Response(data=serialized_cars_with_avg_rating, status=200) def post(self, request): validate_post_car_request_data(request.data) models_for_make_response = get_models_for_make(request.data["make"]) validate_list_of_models_exists(models_for_make_response) for model in models_for_make_response["Results"]: if request.data["model"].upper() == model["Model_Name"].upper(): try: Car.objects.create( make=model["Make_Name"], model=model["Model_Name"] ) return Response(data="Car created", status=201) except IntegrityError: raise ParseError( detail="Object with given name already exists", code=400 ) raise NotFound(detail="Model does not exists") @api_view(["DELETE"]) def delete_car_view(request, id): try: car_to_delete = Car.objects.get(id=id) car_to_delete.delete() return Response(data="Car deleted", status=200) except ObjectDoesNotExist: raise NotFound(detail="Model does not exists") @api_view(["POST"]) def post_car_rating_view(request): validate_post_rate_request_data(request.data) serialized_car_rating = CarRatingSerializer( data={ "rating": request.data["rating"], "car": request.data["car_id"], } ) if serialized_car_rating.is_valid(): try: serialized_car_rating.save() return Response(data="Rating added", status=201) except IntegrityError: raise NotFound(detail="Car model does not exists") @api_view(["GET"]) def get_cars_by_popularity(request): ordered_cars_by_rating = Car.objects.annotate( rates_number=Count("rating") ).order_by("-rates_number") ordered_serialized_cars_by_rating = CarSerializerWithRatingCount( ordered_cars_by_rating, many=True ).data return Response(data=ordered_serialized_cars_by_rating, status=200) <file_sep>/task_api/models.py from django.db import models class Car(models.Model): make = models.CharField(max_length=100) model = models.CharField(max_length=100, unique=True) class CarRating(models.Model): rating = models.IntegerField(null=True) car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name="rating")<file_sep>/static/index.js // Empty file for collectstatic<file_sep>/task_api/tests.py from task_api.conftest import create_objects from django.test import Client from task_api.models import Car, CarRating from jsonschema import validate from task_api.response_schemas import car_view_schema, popular_view_schema import json import pytest @pytest.mark.django_db def test_get_cars_view(client: Client, create_objects: create_objects): response = client.get("/cars/") assert response.status_code == 200 assert response.headers["Content-Type"] == "application/json" response_body = response.json() validate(instance=response_body, schema=car_view_schema) @pytest.mark.django_db def test_get_popular_view(client: Client, create_objects: create_objects): response = client.get("/popular/") assert response.status_code == 200 assert response.headers["Content-Type"] == "application/json" response_body = response.json() validate(instance=response_body, schema=popular_view_schema) @pytest.mark.django_db def test_post_cars_view(client: Client): response = client.post( "/cars/", data=json.dumps({"make": "Honda", "model": "Civic"}), content_type="application/json;charset=UTF-8", ) assert response.status_code == 201 assert Car.objects.count() == 1 car = Car.objects.get(model="Civic") assert car.make == "HONDA" assert car.model == "Civic" @pytest.mark.django_db def test_post_car_rating_view(client: Client): car = Car.objects.create(make="HONDA", model="Civic") response = client.post( "/rate/", data=json.dumps({"car_id": car.id, "rating": 4}), content_type="application/json;charset=UTF-8", ) assert response.status_code == 201 assert CarRating.objects.count() == 1 rate = CarRating.objects.get(car_id=car.id) assert rate.car_id == car.id assert rate.rating == 4 @pytest.mark.django_db def test_delete_car_view(client: Client): car = Car.objects.create(make="HONDA", model="Civic") assert Car.objects.count() == 1 response = client.delete(f"/cars/{car.id}") assert response.status_code == 200 assert Car.objects.count() == 0 <file_sep>/Dockerfile # syntax=docker/dockerfile:1 FROM python:3.9.7 ENV PYTHONUNBUFFERED=1 WORKDIR /Netguru-recruitment-task COPY . /Netguru-recruitment-task/ RUN ls . RUN pip install -r requirements.txt CMD python manage.py makemigrations && python manage.py migrate && python manage.py seed && python manage.py runserver 0.0.0.0:$PORT<file_sep>/task_api/response_schemas.py car_view_schema = { "type": "array", "properties": { "id": {"type": "number"}, "avg_rating": {"type": "number"}, "make": {"type": "string"}, "model": {"type": "string"}, }, "required": ["id", "avg_rating", "make", "model"], } popular_view_schema = { "type": "array", "properties": { "id": {"type": "number"}, "rates_number": {"type": "number"}, "make": {"type": "string"}, "model": {"type": "string"}, }, "required": ["id", "rates_number", "make", "model"], } <file_sep>/task_api/migrations/0003_alter_carrating_rating.py # Generated by Django 3.2.7 on 2021-09-10 08:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('task_api', '0002_auto_20210908_1830'), ] operations = [ migrations.AlterField( model_name='carrating', name='rating', field=models.IntegerField(null=True), ), ] <file_sep>/task_api/services.py import requests def get_all_makes(): makes = requests.get( "https://vpic.nhtsa.dot.gov/api/vehicles/getallmakes?format=json" ).json() return makes def get_models_for_make(requested_make): all_makes_response = get_all_makes() for make in all_makes_response["Results"]: if requested_make.upper() in make["Make_Name"]: models = requests.get( f"https://vpic.nhtsa.dot.gov/api/vehicles/getmodelsformake/{requested_make}?format=json" ).json() return models<file_sep>/task_api/migrations/0001_initial.py # Generated by Django 3.2.7 on 2021-09-08 18:28 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Car', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('make', models.CharField(max_length=100)), ('model', models.CharField(max_length=100)), ], ), migrations.CreateModel( name='CarRating', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('rating', models.IntegerField()), ('car_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='task_api.car')), ], ), ] <file_sep>/task_api/management/commands/seed.py from django.core.management.base import BaseCommand from task_api.models import Car, CarRating import random import logging class Command(BaseCommand): help = "seed database for testing and development." def handle(self, *args, **options): self.stdout.write("seeding data...") run_seed(self) self.stdout.write("done.") def create_car_and_car_rating(): logging.info("Creating cars") makes = [ ["HONDA", "Accord"], ["<NAME>", "DBS"], ["TESLA", "Model X"], ["JAGUAR", "F-Type"], ] if Car.objects.count() == 0 and CarRating.objects.count == 0: for make in makes: car = Car.objects.create( make=make[0], model=make[1], ) for _ in range(5): CarRating.objects.create(car_id=car.id, rating=random.randint(1, 5)) logging.info(f"{car} created.") return car logging.info("Database seeded!") def run_seed(self): create_car_and_car_rating()<file_sep>/task_api/migrations/0002_auto_20210908_1830.py # Generated by Django 3.2.7 on 2021-09-08 18:30 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('task_api', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='carrating', name='car_id', ), migrations.AddField( model_name='carrating', name='car', field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, related_name='rating', to='task_api.car'), preserve_default=False, ), ] <file_sep>/task_api/validators.py from rest_framework.renderers import ParseError def validate_post_car_request_data(request_data): if "make" not in request_data.keys() and "model" not in request_data.keys(): raise ParseError(detail="Wrong body data provided", code=400) validate_request_data_is_not_null(request_data) validate_request_make_is_not_numeric(request_data["make"]) def validate_list_of_models_exists(list_of_models): if not list_of_models: raise ParseError(detail="Wrong body data provided", code=400) def validate_request_make_is_not_numeric(request_make): if request_make.isnumeric(): raise ParseError(detail="Wrong body data provided", code=400) def validate_request_rating_is_number(request_rating): if not isinstance(request_rating, int): raise ParseError(detail="Wrong body data provided", code=400) def validate_request_rating(request_rating): validate_request_rating_is_number(request_rating) if not 5 >= request_rating >= 1: raise ParseError(detail="Wrong body data provided", code=400) def validate_post_rate_request_data(request_data): if not "rating" in request_data.keys() and not "car_id" in request_data.keys(): raise ParseError(detail="Wrong body data provided", code=400) validate_request_rating(request_data["rating"]) def validate_request_data_is_not_null(request_data): if request_data["make"] is None and request_data["model"] is None: raise ParseError(detail="Request data cannot be null", code=400) <file_sep>/requirements.txt asgiref==3.4.1 attrs==21.2.0 certifi==2021.5.30 charset-normalizer==2.0.4 Django==3.2.7 djangorestframework==3.12.4 idna==3.2 iniconfig==1.1.1 jsonschema==3.2.0 packaging==21.0 pluggy==1.0.0 psycopg2-binary==2.9.1 py==1.10.0 pyparsing==2.4.7 pyrsistent==0.18.0 pytest==6.2.5 pytest-django==4.4.0 pytz==2021.1 requests==2.26.0 six==1.16.0 sqlparse==0.4.1 toml==0.10.2 urllib3==1.26.6 whitenoise==5.3.0 dj-database-url==0.5.0 python-decouple==3.5 <file_sep>/README.md # Netguru-recruitment-task ## Task for recruitment at Netguru ### Used packages: __Django-rest-framework__: For building API, mainly for ability to use serializers </br> __requests__: For fetching data from seperate api, mainly for checking if POST values for cars are valid</br> __pytest, pytest-django__: Unit testing</br> __jsonschema__: To further check if response returned wanted values during testing</br> __whitenoise__: collecting and serving static files for development server</br> __python-decouple__: Used for importing data from .env files</br> App is dockerized using docker-compose ### Development setup: .env: ``` DEBUG=1 SECRET_KEY={{django-app secret key}} ALLOWED_HOSTS={{Allowed hosts}} DB_ENGINE=django.db.backends.postgresql DB_TYPE=postgres DB_DATABASE_NAME={{db name}} DB_USERNAME={{db user}} DB_PASSWORD={{<PASSWORD>}} DB_HOST=db DB_PORT=5432 PORT=8000 ``` .env-db: ``` POSTGRES_DB={{same as DB_DATABASE_NAME}} POSTGRES_USER={{same as DB_USERNAME}} POSTGRES_PASSWORD={{same as DB_PASSWORD}} ``` ``docker-compose -f docker-compose.development.yml up --build`` </br></br> This command runs development version of docker-compose, building api and a postgres db containers with migrations and seeds. ### Used database: PostgreSql You should provide username, password and db name to .env files for app to work properly ### JSON request Endpoints accept these arguments over request: #### POST: - __/cars/__ : "model" - model of the car, string; "make" - manufacturer of the car, string; Validity of maker and model of cars is taken from this API: https://vpic.nhtsa.dot.gov/api/ - __/rate/__: "car_id" - id of the car in the database, int; "rating" - value from 1 to 5, int; #### DELETE: - __/cars/:id__ : "id" - id of a car in db to delete, int; The two __GET__ requests are: - __/cars/__ - returns all cars with their ratings - __/popular/__ - returns all cars based on their popularit, from the highest to lowest rating Example of the /cars/ GET response: ``` { "id" : 1, "make" : "Volkswagen", "model" : "Golf", "avg_rating" : 5.0, } ``` ### Heroku: This api is avaiable over Heroku under this link: https://api-netguru-task.herokuapp.com/
933e0544e94bc6cc861737d77c6912ebecf1685f
[ "JavaScript", "Markdown", "Python", "Text", "Dockerfile" ]
17
Python
Swaroog23/Netguru-recruitment-task
84a2c09985f849c136856010d6b32e4c4b6969d5
f8f4b915e210401bf95d4286df8d69da43147f47
refs/heads/master
<file_sep># frozen_string_literal: true class ProjectStat < ActiveRecord::Base STAT_VALUES = %w(0 25 50 75 90 100).freeze before_create :stamp # Stamp (fill in) the current values into a ProjectStat. Uses database. # rubocop:disable Metrics/AbcSize def stamp # Use a transaction to get values from a single consistent point in time. Project.transaction do # Count projects at different levels of completion STAT_VALUES.each do |completion| send "percent_ge_#{completion}=", Project.gteq(completion).count end # These use 1.day.ago, so a create or updates in 24 hours + fractional # seconds won't be counted today, and *might* not be counted previously. # This isn't important enough to solve. self.created_since_yesterday = Project.created_since(1.day.ago).count # Exclude newly-created records from updated_since count self.updated_since_yesterday = Project.updated_since(1.day.ago).count - created_since_yesterday end self # Return self to support method chaining end # rubocop:enable Metrics/AbcSize end <file_sep># frozen_string_literal: true # rubocop:disable Metrics/ClassLength class Project < ActiveRecord::Base using StringRefinements using SymbolRefinements include PgSearch # PostgreSQL-specific text search BADGE_STATUSES = [ ['All', nil], ['Passing (100%)', 100], ['In Progress (25% or more)', 25], ['In Progress (50% or more)', 50], ['In Progress (75% or more)', 75], ['In Progress (90% or more)', 90] ].freeze STATUS_CHOICE = %w(? Met Unmet).freeze STATUS_CHOICE_NA = (STATUS_CHOICE + %w(N/A)).freeze MIN_SHOULD_LENGTH = 5 MAX_TEXT_LENGTH = 8192 # Arbitrary maximum to reduce abuse MAX_SHORT_STRING_LENGTH = 254 # Arbitrary maximum to reduce abuse PROJECT_OTHER_FIELDS = %i( name description homepage_url cpe license general_comments user_id ).freeze ALL_CRITERIA_STATUS = Criteria.map { |c| c.name.status }.freeze ALL_CRITERIA_JUSTIFICATION = Criteria.map { |c| c.name.justification }.freeze PROJECT_PERMITTED_FIELDS = (PROJECT_OTHER_FIELDS + ALL_CRITERIA_STATUS + ALL_CRITERIA_JUSTIFICATION).freeze default_scope { order(:created_at) } scope :created_since, ( lambda do |time| where(Project.arel_table[:created_at].gteq(time)) end ) scope :gteq, ( lambda do |floor| where(Project.arel_table[:badge_percentage].gteq(floor.to_i)) end ) scope :in_progress, -> { lteq(99) } scope :lteq, ( lambda do |ceiling| where(Project.arel_table[:badge_percentage].lteq(ceiling.to_i)) end ) scope :passing, -> { gteq(100) } scope :recently_updated, ( lambda do unscoped.limit(50).order(updated_at: :desc, id: :asc).eager_load(:user) end ) # prefix query (old search system) scope :text_search, ( lambda do |text| start_text = "#{sanitize_sql_like(text)}%" where( Project.arel_table[:name].matches(start_text).or( Project.arel_table[:homepage_url].matches(start_text) ).or( Project.arel_table[:repo_url].matches(start_text) ) ) end ) # Use PostgreSQL-specific text search mechanism # There are many options we aren't currently using; for more info, see: # https://github.com/Casecommons/pg_search pg_search_scope( :search_for, against: %i(name homepage_url repo_url description) # using: { tsearch: { any_word: true } } ) scope :updated_since, ( lambda do |time| where(Project.arel_table[:updated_at].gteq(time)) end ) # Record information about a project. # We'll also record previous versions of information: has_paper_trail before_save :update_badge_percentage # A project is associated with a user belongs_to :user delegate :name, to: :user, prefix: true # For these fields we'll have just simple validation rules. # We'll rely on Rails' HTML escaping system to counter XSS. validates :name, length: { maximum: MAX_SHORT_STRING_LENGTH } validates :description, length: { maximum: MAX_TEXT_LENGTH } validates :license, length: { maximum: MAX_SHORT_STRING_LENGTH } # We'll do automated analysis on these URLs, which means we will *download* # from URLs provided by untrusted users. Thus we'll add additional # URL restrictions to counter tricks like http://ACCOUNT:PASSWORD@host... # and http://something/?arbitrary_parameters validates :repo_url, url: true, length: { maximum: MAX_SHORT_STRING_LENGTH }, uniqueness: { allow_blank: true } validates :homepage_url, url: true, length: { maximum: MAX_SHORT_STRING_LENGTH } validate :need_a_base_url validates :cpe, length: { maximum: MAX_SHORT_STRING_LENGTH }, format: { with: /\A(cpe:.*)?\Z/, message: 'Must begin with cpe:' } validates :user_id, presence: true # Validate all of the criteria-related inputs Criteria.each do |criterion| if criterion.na_allowed? validates criterion.name.status, inclusion: { in: STATUS_CHOICE_NA } else validates criterion.name.status, inclusion: { in: STATUS_CHOICE } end validates criterion.name.justification, length: { maximum: MAX_TEXT_LENGTH } end def badge_level return 'passing' if all_active_criteria_passing? 'in_progress' end def calculate_badge_percentage met = Criteria.active.count { |criterion| passing? criterion } to_percentage met, Criteria.active.length end # Does this contain a URL *anywhere* in the (justification) text? # Note: This regex needs to be logically the same as the one used in the # client-side badge calculation, or it may confuse some users. # See app/assets/javascripts/*.js function "containsURL". # # Note that we do NOT need to validate these URLs, because the BadgeApp # 1. escapes these (as part of normal processing) against XSS attacks, and # 2. does not traverse these URLs in its automated processing. # Thus, this rule is intentionally *not* strict at all. Contrast this # with the intentionally strict validation of the project and repo URLs, # which *are* traversed by BadgeApp and thus need to be much more strict. # def contains_url?(text) text =~ %r{https?://[^ ]{5}} end # Update the badge percentage, and update relevant event datetime if needed. # This code will need to changed if there are multiple badge levels, or # if there are more than 100 criteria. (If > 100 criteria, switch # percentage to something like millipercentage.) def update_badge_percentage old_badge_percentage = badge_percentage self.badge_percentage = calculate_badge_percentage if badge_percentage == 100 && old_badge_percentage < 100 self.achieved_passing_at = Time.now.utc elsif badge_percentage < 100 && old_badge_percentage == 100 self.lost_passing_at = Time.now.utc end end private def all_active_criteria_passing? Criteria.active.all? { |criterion| passing? criterion } end def need_a_base_url return unless repo_url.blank? && homepage_url.blank? errors.add :base, 'Need at least a home page or repository URL' end # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity # rubocop:disable Metrics/PerceivedComplexity def passing?(criterion) status = self[criterion.name.status] justification = self[criterion.name.justification] return true if status.na? return true if status.met? && !criterion.met_url_required? return true if status.met? && contains_url?(justification) return true if criterion.should? && status.unmet? && justification.length >= MIN_SHOULD_LENGTH return true if criterion.suggested? && !status.unknown? false end # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity # rubocop:enable Metrics/PerceivedComplexity def to_percentage(portion, total) return 0 if portion.zero? ((portion * 100.0) / total).round end end
7c431ab3e19f40e7be0722676d693a5e3e71d560
[ "Ruby" ]
2
Ruby
pombredanne/cii-best-practices-badge
3079d7e6dd8714a86c09eb5c43ccc5445dfc8ea9
8c7fc57732dbca6638290eeb70a926dc8e78959f
refs/heads/master
<repo_name>zekiko/mebscraper<file_sep>/data_scraper.py import pandas as pd import requests from bs4 import BeautifulSoup import re schoolList = [] addressList = [] def getSchoolList(ilkodu): url = "https://www.meb.gov.tr/baglantilar/okullar/index.php?ILKODU=" + ilkodu df = pd.read_html(url)[0] response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') table = soup.find('table') for tr in table.findAll("tr"): trs = tr.findAll("td") i = 0 ar = [] for each in trs: try: if(i == 0): name = each.find('a').text if("lise" in name.lower() or "LİSE" in name.upper()): ar.append(name) else: break elif(i == 1): link = each.find('a')['href'] ar.append(link) i = i + 1 except: pass if(len(ar) != 0): schoolList.append(ar) #df['Link'] = schoolList def getPhyscalAddress(URL, index): try: html_doc = requests.get(URL) soup = BeautifulSoup(html_doc.text, 'html.parser') laka = soup.text for line in laka.split("\n"): keywords = re.findall(r'[^-/,\s.]+', line) for i in keywords: if ("sk" == i.lower() or "sok" == i.lower() or "sokak" == i.lower() or "sokağı" in i.lower() or "cd" == i.lower() or "cad" == i.lower() or "cadde" == i.lower() or "caddesi" in i.lower() or "mh" == i.lower() or "mah" == i.lower() or "mah " == i.lower() or " mahalle" == i.lower() or "mahallesi" in i.lower())\ or "köyü" == i.lower() or "km" == i.lower() or "bulvar" == i.lower() or "bulvarı" in i.lower()\ or "kısım" == i.lower(): str = " ".join(keywords) addressList.append(str) print(index, keywords) return addressList.append("-") print("BULAMADI") return except: pass def appendAddressToSchoolList(): for i in range(len(schoolList)): schoolList[i].append(addressList[i]) def application(): getSchoolList("2") for i in range(len(schoolList)): getPhyscalAddress(schoolList[i][1], i) print("lengths: ", len(schoolList), len(addressList)) appendAddressToSchoolList() for i in schoolList: print(i) df = pd.DataFrame(schoolList) csv_data = df.to_csv("lise.csv", header=['LİSE', 'WEB', 'ADRES'], mode='w') application()<file_sep>/deneme.py import re import numpy def findWholeWord(w): return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search #print(findWholeWord('seek')('those who seek shall find')) a = numpy.asarray([ [1,2,3], [4,5,6], [7,8,9] ]) #numpy.savetxt("foo.csv", a, delimiter=",") a = "Bağlar Cad. Cad Cd cd cd. Ethem Köslü Sok. No13 Seyranbağları / ANKARA" kom = re.split('. |\ ', a) print(kom) #out = map(lambda x:x.lower(), kom) #print ("Cad." in list(out)) e = "12.Cadde No 3 Emek Çankaya/ANKARA" kom = re.split('. |\s+ |, ', e) #print (kom) s = "İSTANBUL Türkiye" print("istanbul türkiye" in s.lower())
b3421656a5af40cb80ea38d18c3a158d7c6e20ea
[ "Python" ]
2
Python
zekiko/mebscraper
b586dd28467c533599a8b1e047f22ea6f2696d97
7fd7b5a65ce214480a27e24b90e0cd3dbc64dacf
refs/heads/master
<file_sep>function Entry(title, body) { this.title = title; this.body = body; } Entry.prototype.wordCount = function() { var words = []; words = this.body.split(" "); return words.length; }; Entry.prototype.vowelCount = function() { var vowels = []; vowels = this.body.match(/[AEIOU]/gi); return vowels.length; }; Entry.prototype.consonantCount = function() { var vowels = []; vowels = this.body.match(/[b-df-hj-np-tv-z]/gi); return vowels.length; }; Entry.prototype.getTeaser = function() { var teaser = []; teaser = this.body.split(/([\.\!\?])/); var sentence = teaser[0].split(" "); if (sentence.length <= 8) { return teaser[0] + teaser[1]; } else if (sentence.length > 8) { var output = ""; for (i=0; i < 8; i++){ output = output.concat(sentence[i] + " "); } return output + "..."; } }; exports.entryModule = Entry; <file_sep>(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ function Entry(title, body) { this.title = title; this.body = body; } Entry.prototype.wordCount = function() { var words = []; words = this.body.split(" "); return words.length; }; Entry.prototype.vowelCount = function() { var vowels = []; vowels = this.body.match(/[AEIOU]/gi); return vowels.length; }; Entry.prototype.consonantCount = function() { var vowels = []; vowels = this.body.match(/[b-df-hj-np-tv-z]/gi); return vowels.length; }; Entry.prototype.getTeaser = function() { var teaser = []; teaser = this.body.split(/([\.\!\?])/); var sentence = teaser[0].split(" "); if (sentence.length <= 8) { return teaser[0] + teaser[1]; } else if (sentence.length > 8) { var output = ""; for (i=0; i < 8; i++){ output = output.concat(sentence[i] + " "); } return output + "..."; } }; exports.entryModule = Entry; },{}],2:[function(require,module,exports){ var Entry = require('./../js/journal.js').entryModule; $(document).ready(function() { $('#journal-form').submit(function(event) { event.preventDefault(); var title = $('#title').val(); var body = $('#body').val(); var newEntry = new Entry(title, body); var wordCount = newEntry.wordCount(); var vowelCount = newEntry.vowelCount(); var consonantCount = newEntry.consonantCount(); var teaser = newEntry.getTeaser(); $('#wordCount').text(wordCount); $('#vowelCount').text(vowelCount); $('#consonantCount').text(consonantCount); $('#teaserText').text(teaser); $('#title-display').text(title); $('#body-display').text(body); $('#entry-display').show(); $('#entry-form').hide(); }); }); },{"./../js/journal.js":1}]},{},[2]); <file_sep>var Entry = require('./../js/journal.js').entryModule; $(document).ready(function() { $('#journal-form').submit(function(event) { event.preventDefault(); var title = $('#title').val(); var body = $('#body').val(); var newEntry = new Entry(title, body); var wordCount = newEntry.wordCount(); var vowelCount = newEntry.vowelCount(); var consonantCount = newEntry.consonantCount(); var teaser = newEntry.getTeaser(); $('#wordCount').text(wordCount); $('#vowelCount').text(vowelCount); $('#consonantCount').text(consonantCount); $('#teaserText').text(teaser); $('#title-display').text(title); $('#body-display').text(body); $('#entry-display').show(); $('#entry-form').hide(); }); });
e0c60c74cfdeb8d1c3a2e973cd0db78992d82763
[ "JavaScript" ]
3
JavaScript
bradcopenhaver/JS-journal
2f760704d4c04da2053e538aab6de51e51b6174c
8741fbc6f0c147b183886af5fee7f9c562f1d6ab
refs/heads/main
<file_sep># **************************************************************************** # # # # ::: :::::::: # # Dockerfile :+: :+: :+: # # +:+ +:+ +:+ # # By: ealexa <<EMAIL>> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2021/02/03 15:09:58 by ealexa #+# #+# # # Updated: 2021/02/03 15:11:01 by ealexa ### ########.fr # # # # **************************************************************************** # FROM alpine:latest RUN apk add wget php7 php7-fpm php7-mysqli php7-mbstring php7-json php7-session && \ apk add telegraf --repository http://dl-cdn.alpinelinux.org/alpine/edge/community/ --allow-untrusted --no-cache && \ wget https://files.phpmyadmin.net/phpMyAdmin/4.9.2/phpMyAdmin-4.9.2-all-languages.tar.gz && \ tar -xzvf phpMyAdmin-4.9.2-all-languages.tar.gz && \ rm -rf phpMyAdmin-4.9.2-all-languages.tar.gz && \ mkdir -p /www /etc/telegraf && mv phpMyAdmin-4.9.2-all-languages /www/phpmyadmin COPY /srcs/telegraf.conf /etc/telegraf/ COPY /srcs/config.inc.php /www/phpmyadmin/ COPY /srcs/start.sh / EXPOSE 5000 ENTRYPOINT sh start.sh <file_sep>FROM alpine RUN apk update && apk add vsftpd openssl && \ apk add telegraf --repository http://dl-cdn.alpinelinux.org/alpine/edge/community/ --allow-untrusted --no-cache && \ echo "root:toor" | chpasswd && \ openssl req -x509 -nodes -days 365 \ -newkey rsa:2048 -subj "/C=RU/ST=Rus/L=Cheliabinsk/O=21/CN=ealexa" \ -keyout /etc/ssl/private/vsftpd.key \ -out /etc/ssl/certs/vsftpd.crt COPY /srcs/telegraf.conf /etc/telegraf/ COPY /srcs/vsftpd.conf /etc/vsftpd COPY /srcs/start.sh / #Port 21 works in active and passive mode. Port 30021 only passive mode works. EXPOSE 21 30021 ENTRYPOINT sh start.sh <file_sep># **************************************************************************** # # # # ::: :::::::: # # Dockerfile :+: :+: :+: # # +:+ +:+ +:+ # # By: ealexa <<EMAIL>> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2021/02/03 15:10:03 by ealexa #+# #+# # # Updated: 2021/02/03 15:11:09 by ealexa ### ########.fr # # # # **************************************************************************** # FROM alpine:latest RUN apk add wget php7 php7-fpm php7-mysqli php7-mbstring php7-json php7-session && \ apk add telegraf --repository http://dl-cdn.alpinelinux.org/alpine/edge/community/ --allow-untrusted --no-cache RUN mkdir -p /usr/share/webapps/ && cd /usr/share/webapps/ ADD https://wordpress.org/wordpress-5.6.tar.gz . RUN tar -xzvf wordpress-5.6.tar.gz && rm wordpress-5.6.tar.gz RUN mkdir -p /var/www && mv /wordpress /var/www/ COPY /srcs/telegraf.conf /etc/telegraf/ COPY /srcs/wp-config.php /var/www/wordpress/ COPY /srcs/start.sh / EXPOSE 5050 ENTRYPOINT sh start.sh <file_sep>FROM alpine RUN apk update && \ apk add nginx && \ mkdir -p /var/run/nginx && \ apk add openssl && \ rm -rf /var/cache/apk/* RUN mkdir /www COPY ./index.html /www RUN apk update && apk add nginx tar openssl telegraf --repository http://dl-cdn.alpinelinux.org/alpine/edge/community/ \ && mkdir -p /run/nginx && mkdir -p /etc/telegraf COPY ./telegraf.conf /etc/telegraf/telegraf.conf RUN apk add openrc RUN mkdir /lib64 && ln -s /lib/libc.musl-x86_64.so.1 /lib64/ld-linux-x86-64.so.2 RUN yes "" | openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/certs/localhost.key -out /etc/ssl/certs/localhost.crt RUN rm /etc/nginx/conf.d/default.conf COPY ./nginx.conf /etc/nginx/conf.d/default.conf COPY ./start.sh . RUN chmod +x ./start.sh EXPOSE 80 443 CMD ./start.sh<file_sep>minikube delete minikube start --vm-driver=docker eval $(minikube docker-env) minikube addons enable metrics-server minikube addons enable dashboard minikube addons enable metallb # minikube addons enable ingress # kubectl get configmap kube-proxy -n kube-system -o yaml | sed -e "s/strictARP: false/strictARP: true/" | kubectl diff -f - -n kube-system # kubectl apply -f https://raw.githubusercontent.com/google/metallb/v0.7.3/manifests/metallb.yaml kubectl apply -f https://raw.githubusercontent.com/google/metallb/v0.8.1/manifests/metallb.yaml kubectl apply -f https://raw.githubusercontent.com/metallb/metallb/v0.9.5/manifests/namespace.yaml # export DOCKER_HOST="tcp://127.0.0.1:32782" cd ./srcs kubectl apply -f ./metallb.yaml docker build -t mysql ./mysql docker build -t influxdb ./influxdb docker build -t nginx ./nginx docker build -t wordpress ./wordpress docker build -t phpmyadmin ./phpmyadmin docker build -t ftps ./ftps docker build -t grafana ./grafana kubectl create -f ./mysql/mysql.yaml kubectl create -f ./influxdb/influxdb.yaml sleep 30 kubectl create -f ./nginx/nginx.yaml kubectl create -f ./wordpress/wordpress.yaml kubectl create -f ./phpmyadmin/phpmyadmin.yaml kubectl create -f ./ftps/ftps.yaml kubectl create -f ./grafana/grafana.yaml minikube dashboard<file_sep>FROM alpine RUN apk add mariadb mariadb-client && \ apk add telegraf --repository http://dl-cdn.alpinelinux.org/alpine/edge/community/ --allow-untrusted --no-cache && \ mkdir -p /run/mysqld/ COPY /srcs/telegraf.conf /etc/telegraf/ COPY /srcs/my.cnf /etc/ # COPY /srcs/wordpress.sql / COPY /srcs/start.sh / EXPOSE 3306 ENTRYPOINT sh start.sh
d64ddc9c54e13920842e4dbf29ecfb7d403f9841
[ "Dockerfile", "Shell" ]
6
Dockerfile
Diavolos88/services
b64e8a1a156278ddfd853b2c66f01257056cdcaf
19b732896b56389c016b4c70367ea8cb979cb2dc
refs/heads/master
<file_sep><?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/11/9 * Time: 18:52 */ echo 1212343434;
46bf1d5cb05162950e46d9c2b2e9e14f8bfbed1f
[ "PHP" ]
1
PHP
243773041/dg
b51773e0aee3b4cbc6634a03282279e7c04873e3
9646f7f506e155ab84e9e8756a985b0a00f354b9
refs/heads/master
<repo_name>wcggit/zhixun<file_sep>/src/main/java/com/imbo/myseek/login/dao/UserRepository.java package com.imbo.myseek.login.dao; import com.imbo.myseek.login.entities.User; import org.springframework.data.jpa.repository.JpaRepository; /** * Created by wcg on 16/3/2. */ public interface UserRepository extends JpaRepository<User,Long>{ } <file_sep>/src/main/java/com/imbo/myseek/login/service/UserService.java package com.imbo.myseek.login.service; import com.imbo.myseek.login.entities.User; import com.imbo.myseek.login.dao.UserRepository; import org.springframework.stereotype.Service; import java.util.List; import javax.inject.Inject; /** * Created by wcg on 16/3/2. */ @Service public class UserService { @Inject private UserRepository userDao; public List<User> findAllUser(){ return userDao.findAll(); } } <file_sep>/src/main/java/com/imbo/myseek/test/test.java package com.imbo.myseek.test; import com.imbo.myseek.login.service.UserService; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.inject.Inject; /** * Created by wcg on 16/2/20. */ @RestController @RequestMapping("/api") public class test { @Inject private UserService userService; @RequestMapping("/test") public void test(){ System.out.println("test"); } } <file_sep>/Dockerfile FROM ubuntu:v3 MAINTAINER wcg EXPOSE 8080 CMD cd /app && mvn spring-boot:run <file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.weseek</groupId> <artifactId>zhixun</artifactId> <version>1.0-SNAPSHOT</version> </parent> <groupId>com.weseek</groupId> <artifactId>weseek-home</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>weseek-home</name> <dependencies> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>1.0.0.Final</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-hibernate4</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-hppc</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-json-org</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${springfox.version}</version> <exclusions> <exclusion> <groupId>org.mapstruct</groupId> <artifactId>mapstruct</artifactId> </exclusion> </exclusions> </dependency> <!--<dependency>--> <!--<groupId>com.mattbertolini</groupId>--> <!--<artifactId>liquibase-slf4j</artifactId>--> <!--<version>${liquibase-slf4j.version}</version>--> <!--</dependency>--> <dependency> <groupId>com.ryantenney.metrics</groupId> <artifactId>metrics-spring</artifactId> <version>${metrics-spring.version}</version> <exclusions> <exclusion> <groupId>com.codahale.metrics</groupId> <artifactId>metrics-annotation</artifactId> </exclusion> <exclusion> <groupId>com.codahale.metrics</groupId> <artifactId>metrics-core</artifactId> </exclusion> <exclusion> <groupId>com.codahale.metrics</groupId> <artifactId>metrics-healthchecks</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <exclusions> <exclusion> <artifactId>tools</artifactId> <groupId>com.sun</groupId> </exclusion> </exclusions> </dependency> <!-- The HikariCP Java Agent is disabled by default, as it is experimental <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP-agent</artifactId> <version>${HikariCP.version}</version> </dependency> --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>${commons-io.version}</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>${commons-lang.version}</version> </dependency> <dependency> <groupId>io.gatling.highcharts</groupId> <artifactId>gatling-charts-highcharts</artifactId> <version>${gatling.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>${javax.inject.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <version>${assertj-core.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-envers</artifactId> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> </dependency> <!--<dependency>--> <!--<groupId>org.liquibase</groupId>--> <!--<artifactId>liquibase-core</artifactId>--> <!--<exclusions>--> <!--<exclusion>--> <!--<artifactId>jetty-servlet</artifactId>--> <!--<groupId>org.eclipse.jetty</groupId>--> <!--</exclusion>--> <!--</exclusions>--> <!--</dependency>--> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-jdk8</artifactId> <version>${mapstruct.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-actuator</artifactId> </dependency> <!--<dependency>--> <!--<groupId>org.springframework.boot</groupId>--> <!--<artifactId>spring-boot-autoconfigure</artifactId>--> <!--</dependency>--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-loader-tools</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </dependency> <!--<dependency>--> <!--<groupId>org.springframework.boot</groupId>--> <!--<artifactId>spring-boot-starter-mail</artifactId>--> <!--</dependency>--> <!--<dependency>--> <!--<groupId>org.springframework.boot</groupId>--> <!--<artifactId>spring-boot-starter-security</artifactId>--> <!--</dependency>--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <!-- reporting --> <dependency> <groupId>fr.ippon.spark.metrics</groupId> <artifactId>metrics-spark-reporter</artifactId> <version>${metrics-spark-reporter.version}</version> </dependency> <!-- jhipster-needle-maven-add-dependency --> </dependencies> <build> <defaultGoal>spring-boot:run</defaultGoal> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> <includes> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <filtering>false</filtering> <excludes> <exclude>**/*.xml</exclude> </excludes> </resource> </resources> <plugins> <plugin> <groupId>com.google.code.sortpom</groupId> <artifactId>maven-sortpom-plugin</artifactId> <version>${maven-sortpom-plugin.version}</version> <executions> <execution> <phase>verify</phase> <goals> <goal>sort</goal> </goals> </execution> </executions> <configuration> <sortProperties>true</sortProperties> <nrOfIndentSpace>4</nrOfIndentSpace> <sortDependencies>groupId,artifactId</sortDependencies> <sortPlugins>groupId,artifactId</sortPlugins> <keepBlankLines>true</keepBlankLines> <expandEmptyElements>false</expandEmptyElements> </configuration> </plugin> <plugin> <groupId>io.gatling</groupId> <artifactId>gatling-maven-plugin</artifactId> <version>${gatling-maven-plugin.version}</version> <configuration> <configFolder>src/test/gatling/conf</configFolder> <dataFolder>src/test/gatling/data</dataFolder> <resultsFolder>target/gatling/results</resultsFolder> <bodiesFolder>src/test/gatling/bodies</bodiesFolder> <simulationsFolder>src/test/gatling/simulations</simulationsFolder> <!-- This will force Gatling to ask which simulation to run This is useful when you have multiple simulations --> <simulationClass>*</simulationClass> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-eclipse-plugin</artifactId> <configuration> <downloadSources>true</downloadSources> <downloadJavadocs>true</downloadJavadocs> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-enforcer-plugin</artifactId> <version>${maven-enforcer-plugin.version}</version> <executions> <execution> <id>enforce-versions</id> <goals> <goal>enforce</goal> </goals> </execution> </executions> <configuration> <rules> <requireMavenVersion> <message>You are running an older version of Maven. JHipster requires at least Maven 3.0</message> <version>[3.0.0,)</version> </requireMavenVersion> <requireJavaVersion> <message>You are running an older version of Java. JHipster requires at least JDK ${java.version}</message> <version>[${java.version}.0,)</version> </requireJavaVersion> </rules> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <configuration> <packagingExcludes>WEB-INF/lib/tomcat-*.jar</packagingExcludes> </configuration> </plugin> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>${jacoco-maven-plugin.version}</version> <executions> <execution> <id>pre-unit-tests</id> <goals> <goal>prepare-agent</goal> </goals> <configuration> <!-- Sets the path to the file which contains the execution data. --> <destFile>${project.testresult.directory}/coverage/jacoco/jacoco.exec</destFile> <!-- Sets the name of the property containing the settings for JaCoCo runtime agent. --> <propertyName>surefireArgLine</propertyName> </configuration> </execution> <!-- Ensures that the code coverage report for unit tests is created after unit tests have been run --> <execution> <id>post-unit-test</id> <phase>test</phase> <goals> <goal>report</goal> </goals> <configuration> <dataFile>${project.testresult.directory}/coverage/jacoco/jacoco.exec</dataFile> <outputDirectory>${project.testresult.directory}/coverage/jacoco</outputDirectory> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>sonar-maven-plugin</artifactId> <version>${sonar-maven-plugin.version}</version> </plugin> <plugin> <groupId>org.bsc.maven</groupId> <artifactId>maven-processor-plugin</artifactId> <version>2.2.4</version> <configuration> <defaultOutputDirectory> ${project.build.directory}/generated-sources </defaultOutputDirectory> <processors> <processor>org.mapstruct.ap.MappingProcessor</processor> </processors> <options> <mapstruct.suppressGeneratorTimestamp>true</mapstruct.suppressGeneratorTimestamp> <mapstruct.defaultComponentModel>spring</mapstruct.defaultComponentModel> </options> </configuration> <executions> <execution> <id>process</id> <phase>generate-sources</phase> <goals> <goal>process</goal> </goals> </execution> </executions> <dependencies> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>${mapstruct.version}</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <executable>true</executable> <jvmArguments>-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005</jvmArguments> <arguments> <argument>--spring.profiles.active=dev</argument> </arguments> </configuration> </plugin> <!-- jhipster-needle-maven-add-plugin --> </plugins> </build> <profiles> <profile> <id>dev</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <!-- log configuration --> <logback.loglevel>DEBUG</logback.loglevel> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>com.github.trecloux</groupId> <artifactId>yeoman-maven-plugin</artifactId> <version>0.4</version> <executions> <execution> <id>run-grunt</id> <phase>generate-resources</phase> <goals> <goal>build</goal> </goals> <configuration> <skipTests>true</skipTests> <buildTool>grunt</buildTool> <buildArgs>sass:server --force</buildArgs> </configuration> </execution> </executions> <configuration> <yeomanProjectDirectory>${project.basedir}</yeomanProjectDirectory> </configuration> </plugin> </plugins> </build> </profile> </profiles> </project>
214851b382db71ee0b833a40793245625530df84
[ "Java", "Maven POM", "Dockerfile" ]
5
Java
wcggit/zhixun
ef82fc7bcfe1058a0ed67114149b0233760c1e48
b13b9bf53ca383aae3808fd6e06e286367b517ed
refs/heads/master
<repo_name>rheinwein/docker-api<file_sep>/Rakefile $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), 'lib')) require 'rake' require 'docker' require 'rspec/core/rake_task' require 'cane/rake_task' task :default => [:spec, :quality] RSpec::Core::RakeTask.new do |t| t.pattern = 'spec/**/*_spec.rb' end Cane::RakeTask.new(:quality) do |cane| cane.canefile = '.cane' end desc 'Pull an Ubuntu image' image 'ubuntu:13.10' do puts "Pulling ubuntu:13.10" image = Docker::Image.create('fromImage' => 'ubuntu', 'tag' => '13.10') puts "Pulled ubuntu:13.10, image id: #{image.id}" end
9a784583fdd73e433359a7f9565f7a85c2c551ed
[ "Ruby" ]
1
Ruby
rheinwein/docker-api
103f36c91e205d0bef8da7a1871c2c56f83a7f6a
8712feb5a569cc062515586457cef4573027438c
refs/heads/master
<repo_name>JDubendorf/mongo-exercises<file_sep>/exercises/two.js module.exports = function(mongoose, Checkout, Movie) { // Which users checked out any of the Lord of the Rings trilogy? Movie.find( { title : { $regex: /lord of the rings/, $options: "$i" } }, function(err, movieTitleResult) { Checkout.distinct("userId", { $or : [ { movieId : movieTitleResult[0]._id}, { movieId : movieTitleResult[1]._id}, { movieId : movieTitleResult[2]._id} ]}, function (err, result) { console.log(result.length + " users checked out any of the Lord of the Rings trilogy. Here are their user ID's: " + result + "."); } ); } ); }; <file_sep>/exercises/three.js module.exports = function(mongoose, Checkout, Movie) { //What is the title of the movie(s) that was the most checked out? Checkout.aggregate( [ { $group: { _id: "$movieId", movieCount: { $sum: 1 } }}, { $sort: {"movieCount": -1} }, { $limit: 1 } ], function(err, result) { var movieId = result[0]._id; Movie.aggregate( [ { $match : { _id : movieId } } ], function(err, result) { console.log("The most checked out movie is " + result[0].title + "."); } ); } ); }; // in Movie, <file_sep>/exercises/one.js module.exports = function(mongoose, Checkout, Movie) { // What user(s) had the most checkouts? Checkout.aggregate( [ { $group: { _id: "$userId", checkoutCount: { $sum: 1 } }}, { $sort: {"checkoutCount": -1} }, { $limit: 1 } ], function(err, result) { console.log("The user with the most checkouts has userId " + result[0]._id + "."); } ); };
0fcb4f49da8fb70a615fe8f4c863e39bcb8f8a76
[ "JavaScript" ]
3
JavaScript
JDubendorf/mongo-exercises
5134b0da09679d67b6412e710990c0eb348f369a
022e20e42928c8bff1319f02c9d53117312c22fa
refs/heads/master
<file_sep>package com.db.chartviewdemo; import java.util.Random; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.Paint; import com.db.chart.Tools; import com.db.chart.view.animation.Animation; import com.db.chart.view.animation.easing.bounce.BounceEaseOut; import com.db.chart.view.animation.easing.elastic.ElasticEaseOut; import com.db.chart.view.animation.easing.quint.QuintEaseOut; public class DataRetriever { private final static String[] mColors = {"#f36c60","#7986cb", "#4db6ac", "#aed581", "#ffb74d"}; public static boolean randBoolean(){ return Math.random() < 0.5; } public static int randNumber(int min, int max) { return new Random().nextInt((max - min) + 1) + min; } public static float randValue(float min, float max) { return (new Random().nextFloat() * (max - min)) + min; } public static float randDimen(float min, float max){ float ya = (new Random().nextFloat() * (max - min)) + min; return Tools.fromDpToPx(ya); } public static Paint randPaint() { if(randBoolean()){ Paint paint = new Paint(); paint.setColor(Color.parseColor("#b0bec5")); paint.setStyle(Paint.Style.STROKE); paint.setAntiAlias(true); paint.setStrokeWidth(Tools.fromDpToPx(1)); if(randBoolean()) paint.setPathEffect(new DashPathEffect(new float[] {10,10}, 0)); return paint; } return null; } public static boolean hasFill(int index){ return (index == 2) ? true : false; } public static Animation randAnimation(Runnable endAction){ switch (new Random().nextInt(3)){ case 0: return new Animation() .setEasing(new QuintEaseOut()) .setOverlap(randValue(0.5f, 1f)) .setAlpha(randNumber(3,6)) .setEndAction(endAction); case 1: return new Animation() .setEasing(new QuintEaseOut()) .setStartPoint(0f, 0f) .setAlpha(randNumber(3,6)) .setEndAction(endAction); case 2: return new Animation() .setEasing(new BounceEaseOut()) .setOverlap(randValue(0.5f, 1f)) .setEndAction(endAction); default: return new Animation() .setOverlap(randValue(0.5f, 1f)) .setEasing(new ElasticEaseOut()) .setEndAction(endAction); } } public static String getColor(int index){ switch (index){ case 0: return mColors[0]; case 1: return mColors[1]; case 2: return mColors[2]; case 3: return mColors[0]; case 4: return mColors[1]; default: return mColors[2]; } } }
2af7f47f109d7dcb7e3499c1a54eb14ace39784e
[ "Java" ]
1
Java
7katana/WilliamChart
b76bc367439df8478b5ca85217a3602ad37585b3
8f63bbdebe5e601d6b8b61184e5b82a058a7ed26
refs/heads/master
<repo_name>bobiOneBG/JS_Fundamentals_Exersice<file_sep>/StringAndRegex_Lab/js/main.js function printLetters(str) { for (const key in str) { console.log(`str[${key}] -> ${str[key]}`); } } function concatenateAndReverse(arr) { let str = arr.join('') .split('') .reverse() .join(''); console.log(str); } function countOccurences(target, str) { let counter = 0; while (true) { let startIndex = str.indexOf(target); if (startIndex < 0) { break; } counter++; str = str.substr(startIndex + 1); } console.log(counter); } function extractText(input) { let result = []; while (true) { let start = input.indexOf('('); if (start < 0) break; let end = input.indexOf(')'); if (end < 0 || end < start) break; let sss = input.substring(start + 1, end); result.push(input.substring(start + 1, end)); input = input.substring(end + 1); } console.log(result.join(', ')); } function aggregateTable(input) { let arr = []; sum = 0; for (let str of input) { let data = str.split('|') .filter(e => e !== '') .map(e => { return e.trim(); }); arr.push(data[0]); sum += +data[1]; } console.log(arr.join(', ')); console.log(sum); } function restaurantBill(arr) { let purchases = arr.filter((p, i) => i % 2 === 0); let sum = arr .filter((p, i) => i % 2 !== 0) .map(p => +p) .reduce((acc, cur) => acc + cur); console.log(`You purchased ${purchases.join(', ')} for a total sum of ${sum}`) } function usernames(arr) { let arrResult = []; for (let i = 0; i < arr.length; i++) { let token = arr[i].split('@'); let domains = token[1].split('.'); let result = token[0] + '.'; for (let str of domains) { result += str[0]; } arrResult.push(result) } console.log(arrResult.join(', ')); } function censorship(text, arr) { for (let censStr of arr) { let regex = new RegExp(censStr, 'g'); text = text.replace(regex, '-'.repeat(censStr.length)) }; console.log(text); } function matchAllWords(str) { let regex = /[a-zA-Z0-9_]+/g; console.log(str.match(regex).join('|')); } function emailValidation(str) { let regex = /^[a-zA-Z0-9]+@[a-z]+\.[a-z]+$/; if (regex.test(str)) { console.log("Valid"); } else { console.log("Invalid"); } } function expressionSplit(str) { let re = /[,;()\. ]+/; str.split(re).forEach(s => console.log(s)); } function matchTheDates(text) { let re = /\b([\d]{1,2})-([A-Z][a-z]{2})-([\d]{4})/gm; // ensure atleast one match let expRe = re.exec(text); while (expRe) { console.log(`${expRe[0]} (Day: ${expRe[1]}, Month: ${expRe[2]}, Year: ${expRe[3]})`) expRe = re.exec(text); } } function parseTheEmployeData(arr) { let re = /^([A-Z][a-zA-Z]*) - ([1-9][0-9]*) - ([a-zA-Z0-9 -]+)$/; for (let data of input) { let match = re.exec(data); if (match) { console.log(`Name: ${match[1]}`); console.log(`Position: ${match[3]}`); console.log(`Salary: ${match[2]}`); } } } function formFiller(username, email, phone, arr) { arr.forEach(l => { l = l.replace(/<![a-zA-Z]+!>/g, username); l = l.replace(/<@[a-zA-Z]+@>/g, email); l = l.replace(/<\+[a-zA-Z]+\+>/g, phone); console.log(l); }); } function performMultiplications(text) { text = text.replace(/(-?\d+)\s*\*\s*(-?\d+(\.\d+)?)/g, (match, num1, num2) => +(num1) * +(num2)); console.log(text); } function matchMult(str) { let re = /(\-?\d+)\s*\*\s*(\-?\d+(?:\.\d+)?)/g; str = str.replace(re, (match, num1, num2) => +num1 * +num2); console.log(str); }<file_sep>/ArrayAndMatrix_Exercise/js/main.js function printArrayiWithGivenDelimiter(arr) { let delimeter = arr.pop(); console.log(arr.join(delimeter)); } function printEveryNthElementFromAnArray(arr) { let step = +arr.pop(); arr = arr.filter((v, i) => { return i % step === 0; }); console.log(arr.join('\n')) } function addAndRemoveElements(arr) { let temp = 1; let rslt = []; for (let str of arr) { if (str === 'add') { rslt.push(temp++); } else if (str === 'remove') { rslt.pop(0); temp++; } } console.log(rslt.length > 0 ? rslt.join('\n') : ('Empty')); } function rotateArray(arr) { let step = +arr.pop(); step %= arr.length; step = Math.abs(step - arr.length) let tempArr = arr.splice(0, step); arr = arr.concat(tempArr); console.log(arr.join(' ')); } function extractIncreasingSubsequenceFromArray(arr) { let rslt = arr.filter((x, i) => x >= Math.max(...arr.slice(0, i + 1))); console.log(rslt.join('\n')); } function sortArray(arr) { console.log(arr.sort().sort((a, b) => a.length - b.length).join('\n')); } function magicMatrices(matrix) { let sum = matrix[0].reduce((a, b) => a + b, 0); for (let row = 0; row < matrix.length; row++) { let rowSum = matrix[row].reduce((a, b) => a + b, 0); if (rowSum != sum) return false; for (let col = 0; col < matrix[row].length; col++) { let sumCol = 0; for (let row = 0; row < matrix.length; row++) { sumCol += matrix[row][col]; } if (sumCol != sum) return false; } } return true; } function spiralMatrix(rows, cols) { let matrix = []; for (let i = 0; i < rows; i++) { matrix.push([]); } let startRow = 0, startCol = 0, endRow = rows - 1, endCol = cols - 1; let number = 1; while (startRow <= endRow || startCol <= endCol) { for (let i = startCol; i <= endCol; i++) { matrix[startRow][i] = number++; } for (let i = startRow + 1; i <= endRow; i++) { matrix[i][endCol] = number++; } for (let i = endCol - 1; i >= startCol; i--) { matrix[endRow][i] = number++; } for (let i = endRow - 1; i > startRow; i--) { matrix[i][startCol] = number++; } startRow++; startCol++; endRow--; endCol--; } console.log(matrix.map(row => row.join(" ")).join("\n")); } function diagonalAttack(arr) { let matrix = arr.map(row => row.split(' ').map(x => +x)); let primaryDiagonalSum = 0; let secondaryDiagonalSum = 0; for (let row = 0; row < matrix.length; row++) { for (let col = 0; col < matrix[row].length; col++) { if (row == col) { primaryDiagonalSum += matrix[row][col]; } if (col === matrix[row].length - row - 1) { secondaryDiagonalSum += matrix[row][col]; } } } if (primaryDiagonalSum === secondaryDiagonalSum) { for (let row = 0; row < matrix.length; row++) { for (let col = 0; col < matrix[row].length; col++) { if (row !== col && col !== matrix[row].length - row - 1) { matrix[row][col] = primaryDiagonalSum; } } } } let result = matrix.map(row => row.join(' ')).join('\n'); console.log(result); } function orbitMatrix(numArr) { let [rows, cols, x, y] = numArr; let matrix = []; for (let i = 0; i < rows; i++) { matrix.push(('0').repeat(cols).split('').map(Number)); } let num = 1; matrix[x][y] = 1; let counter = 1; let currentRow = x; let currentCol = y; while (true) { let isFilled = false; num++; let startRow = Math.max(0, currentRow - counter); let endRow = Math.min(matrix.length - 1, currentRow + counter); let startCol = Math.max(0, currentCol - counter); let endCol = Math.min(matrix[0].length - 1, currentCol + counter); for (let row = startRow; row <= endRow; row++) { for (let col = startCol; col <= endCol; col++) { if (matrix[row][col] == 0) { matrix[row][col] = num; isFilled = true; } } } counter++; if (!isFilled) { break; } } let result = matrix.map(row => row.join(' ')).join('\n'); console.log(result); } <file_sep>/WarehouseMachine/app.js function warehouseMashine(strArr) { let warehouse = {}; let commandExecutor = { 'IN': (str) => inFnctn(str), 'OUT': (str) => out(str), 'REPORT': () => report(), 'INSPECTION': () => inspection() }; strArr.forEach(info => { let command = info.split(', ')[0]; commandExecutor[command](info); }); function inFnctn(str) { let [brand, coffeeName, expDate, quantity] = str.split(', ').slice(1); if (warehouse[brand] && warehouse[brand][coffeeName]) { let inCoffeeDate = expDate.split('-').join(''); let existCoffeeDate = warehouse[brand][coffeeName].expDate.split('-').join(''); if (inCoffeeDate > existCoffeeDate) { warehouse[brand][coffeeName].expDate = expDate; warehouse[brand][coffeeName].quantity = +quantity; } else if (inCoffeeDate === existCoffeeDate) { warehouse[brand][coffeeName].quantity += +quantity; } } if (!warehouse[brand]) { warehouse[brand] = {}; warehouse[brand][coffeeName] = { 'expDate': expDate, 'quantity': +quantity }; } if (!warehouse[brand][coffeeName]) { warehouse[brand][coffeeName] = { 'expDate': expDate, 'quantity': +quantity }; } } function out(str) { let [brand, coffeeName, expDate, quantity] = str.split(', ').slice(1); if (warehouse[brand] && warehouse[brand][coffeeName]) { let outCoffeeDate = expDate.split('-').join(''); let existCoffeeDate = warehouse[brand][coffeeName].expDate.split('-').join(''); if (existCoffeeDate > outCoffeeDate && warehouse[brand][coffeeName].quantity >= quantity) { warehouse[brand][coffeeName].quantity -= quantity; } } } function report() { console.log('>>>>> REPORT! <<<<<'); Object.keys(warehouse).forEach((brand) => { console.log(`Brand: ${brand}:`); Object.keys(warehouse[brand]) .forEach((coffee) => { console.log(`-> ${coffee} -> ${warehouse[brand][coffee].expDate} -> ${warehouse[brand][coffee].quantity}.`); }); }); } function inspection() { console.log('>>>>> INSPECTION! <<<<<'); Object.keys(warehouse).sort((a, b) => { return a.localeCompare(b); }).forEach((brand) => { console.log(`Brand: ${brand}:`); Object.keys(warehouse[brand]).sort((a, b) => { return warehouse[brand][b].quantity - warehouse[brand][a].quantity; }) .forEach((coffee) => { console.log(`-> ${coffee} -> ${warehouse[brand][coffee].expDate} -> ${warehouse[brand][coffee].quantity}.`); }); }); } } warehouseMashine([ 'IN, Folgers, Black Silk, 2023-03-01, 14', 'IN, Lavazza, Crema e Gusto, 2023-05-01, 5', 'IN, Lavazza, Crema, 2005-05-01, 5', 'IN, Lavazza, Crema, 2006-05-01, 50', 'IN, Batdorf & Bronson, Es, 2025-05-25, 20', 'IN, Batdorf & Bronson, Espresso, 2035-05-25, 70', 'IN, Batdorf & Bronson, Es, 2035-05-25, 60', 'IN, Lavazza, Crema e Gusto, 2023-05-02, 5', 'IN, Folgers, Black Silk, 2022-01-01, 10', 'IN, Lavazza, Intenso, 2022-07-19, 20', 'OUT, Dallmayr, Espresso, 2022-07-19, 5', 'OUT, Dallmayr, Crema, 2022-07-19, 5', 'OUT, Lavazza, Crema, 2020-01-28, 2', 'IN, Batdorf & Bronson, Es, 2025-05-25, 10 ', 'INSPECTION', ]);<file_sep>/ArraysAndMatrices_Lab/js/main.js function sumFirstLast(arr) { let sum = [arr[0], arr[arr.length - 1]] .map((v, i) => { return +v }) .reduce((acc, cur) => { return acc + cur; }, 0); console.log(sum); } function evenPositionElements(arr) { let evenArr = arr .filter((v, i) => { return (i % 2) === 0; }); console.log(evenArr.join(' ')); } function negativePositiveNumbers(arr) { let result = []; for (num of arr) if (num < 0) result.unshift(num); else result.push(num); console.log(result.join('\n')); } function firstAndLastKNumbers(arr) { let k = arr.shift(); console.log(arr.slice(0, k).join(' ')); console.log(arr.slice(arr.length - k, arr.length).join(' ')); } function lastKNumbersSequence(n, k) { let seq = [1]; for (let current = 1; current < n; current++) { let start = Math.max(0, current - k); let end = current - 1; let sum = seq.slice(start, end + 1).reduce((acc, cur) => { return acc + cur; }, 0); seq[current] = sum; } console.log(seq.join(' ')); } function processOddNumbers(arr) { let rslt = arr .filter((v, i) => { return i % 2 !== 0 }) .map((v) => { return v * 2 }) .reverse(); console.log(rslt.join(' ')); } function smallestTwoNumbers(arr) { let rslt = arr.sort((a, b) => a - b) .slice(0, 2) .join(' '); console.log(rslt); } function biggestElement(matrix) { let biggestNum = Number.NEGATIVE_INFINITY; matrix.forEach( row => biggestNum = Math.max(biggestNum, row.reduce((a, b) => Math.max(a, b)))); console.log(biggestNum); } function diagonalSums(matrix) { let arr = [0, 0]; matrix.forEach((row, indx) => { row.forEach((item, innerIndx) => { if (innerIndx === indx) { arr[0] += item; } if (innerIndx + indx === row.length - 1) { arr[1] += item; } }) }); console.log(arr.join(' ')) } function equalNeighbors(matrix) { let neighbors = 0; for (let row = 0; row < matrix.length; row++) { for (let col = 0; col < matrix[row].length; col++) { if (row < matrix.length - 1) { if (matrix[row][col] == matrix[row + 1][col]) { neighbors++; } } if (col < matrix[row].length) { if (matrix[row][col] == matrix[row][col + 1]) { neighbors++; } } } } return neighbors; }<file_sep>/ATMMashine/js/main.js function atmMashine(matrix) { let atm = {}; let atmBalance = 0; matrix.forEach(arr => { if (arr.length > 2) { insert(arr); } else if (arr.length === 2) { let currBalance = arr[0]; let toWithdraw = arr[1]; if (currBalance < toWithdraw) { console.log(`Not enough money in your account. Account balance: ${currBalance}$.`); } else if (atmBalance < toWithdraw) { console.log('ATM machine is out of order!'); } else { let sortedAtm = Object.keys(atm).sort((a, b) => { // string array return b - a; }).map(el => +el); let i = 0; let count = 0; let curSum = toWithdraw; while (curSum >0) { count = parseInt(curSum / sortedAtm[i]); atm[sortedAtm[i]] -= count; if (count>0) { curSum = toWithdraw % sortedAtm[i]; } count = 0; i++; } currBalance -= toWithdraw; atmBalance -= toWithdraw; console.log(`You get ${toWithdraw}$. Account balance: ${currBalance}$. Thank you!`); } } else if (arr.length === 1) { let nominal = arr[0]; let cnt = atm[nominal] ? atm[nominal] : 0; console.log(`Service Report: Banknotes from ${nominal}$: ${cnt}.`); } }); function insert(arr) { let insert = 0; arr.forEach(el => { if (!atm[el]) { atm[el] = 0; } insert += el; atm[el] += 1; }); atmBalance += insert; console.log(`Service Report: ${insert}$ inserted. Current balance: ${atmBalance}$.`); } } atmMashine([ [10, 20, 10, 50, 5, 10], [100, 30], [20], [20, 10, 10], [5, 10], [150, 150] ]); <file_sep>/DataTypesExpressionStatements/js/main.js // Your code here! function helloJS(name) { console.log(`Hello, ${name}, I am JavaScript!`) } function areaAndPerimeter(a, b) { console.log(a * b); console.log(2 * a + 2 * b) } function distanceOverTime(input) { v1 = input[0]; v2 = input[1]; t = input[2] / 3600; let diff = (Math.abs(v1 - v2) * t) * 1000; console.log(diff); } function distanceIn3D(input) { x0 = input[0]; y0 = input[1]; z0 = input[2]; x1 = input[3]; y1 = input[4]; z1 = input[5]; let distance = Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2) + Math.pow(z0 - z1, 2)); console.log(distance); } function gradsToRadians(grad) { let degrees = 0.9 * grad; degrees %= 360; if (degrees < 0) { degrees = 360 + degrees; } console.log(degrees); } function compoundInterest(input) { let P = input[0]; let i = input[1]; let n = input[2]; let t = input[3]; let F = P * Math.pow((1 + (i / 100) / (12 / n)), (12 / n) * t); console.log(Math.round(F * 100) / 100); } function rounding(input) { let nmbr = +input[0]; let precision = +input[1]; if (precision > 15) { precision = 15; } console.log(+nmbr.toFixed(precision)); } function imperialUnits(a) { let feet = parseInt(a / 12); let inches = a % 12; console.log(feet + "\'-" + inches + "\""); } function nowPlaying([songName, name, time]) { console.log(`Now Playing: ${name} - ${songName} [${time}]`); } function composeTag([name, tag]) { console.log(`<img src="${name}" alt="${tag}">`); } function binaryToDecimal(binary) { var digit = parseInt(+binary, 2); console.log(digit) } function assignProperties(input) { let a = input[0]; let b = input[1]; let c = input[2]; let d = input[3]; let e = input[4]; let f = input[5]; let objct = { [a]: b, [c]: d, [e]: f } console.log(objct); } function lastMonth([day, month, year]) { let date = new Date(year, month-1, 0); let days = date.getDate(); console.log(days); } function biggestOfThreeNumbers([a, b, c]) { let maxNum = Math.max(a, b, c); console.log(maxNum); } function pointInRectangle([x, y, xMin, xMax, yMin, yMax]) { if (x >= xMin && x <= xMax && y >= yMin && y <= yMax) { console.log('inside'); } else { console.log('outside'); } } function oddNumbersOneToN(n) { for (let i = 1; i <= n; i += 2) { console.log(i); } } function triangleOfDollars(n) { for (let i = 1; i <= n; i++) { let line = ''; for (let j = 0; j < i; j++) { line += '$'; } console.log(line); } } function moviePrices([movieTitle, dayOfWeek]) { let title = movieTitle.toString().toLowerCase(); let day = dayOfWeek.toString().toLowerCase(); let price = ''; switch (title) { case 'the godfather': switch (day) { case 'monday': price = 12; break; case 'tuesday': price = 10; break; case 'wednesday': price = 15; break; case 'thursday': price = 12.50; break; case 'friday': price = 15; break; case 'saturday': price = 25; break; case 'sunday': price = 30; break; default: console.log('error'); break; } break; case 'schindler\'s list': switch (day) { case 'monday': price = 8.50; break; case 'tuesday': price = 8.50; break; case 'wednesday': price = 8.50; break; case 'thursday': price = 8.50; break; case 'friday': price = 8.50; break; case 'saturday': price = 15; break; case 'sunday': price = 15; break; default: console.log('error'); break; } break; case 'casablanca': switch (day) { case 'monday': price = 8; break; case 'tuesday': price = 8; break; case 'wednesday': price = 8; break; case 'thursday': price = 8; break; case 'friday': price = 8; break; case 'saturday': price = 10; break; case 'sunday': price = 10; break; default: console.log('error'); break; } break; case 'the wizard of oz': switch (day) { case 'monday': price = 10; break; case 'tuesday': price = 10; break; case 'wednesday': price = 10; break; case 'thursday': price = 10; break; case 'friday': price = 10; break; case 'saturday': price = 15; break; case 'sunday': price = 15; break; default: console.log('error'); break; } break; default: console.log('error'); break; } console.log(price); } function quadraticequation(a, b, c) { let d = b * b - 4 * a * c; if (d < 0) { console.log('No'); } else if (d === 0) { console.log(-b / (2 * a)); } else { console.log(-b / 2 / a - Math.pow(Math.pow(b, 2) - 4 * a * c, 0.5) / 2 / a); console.log(-b / 2 / a + Math.pow(Math.pow(b, 2) - 4 * a * c, 0.5) / 2 / a); } } <file_sep>/FunctionsAndArrowFunctions/js/main.js // Your code here! function isInVolume(input) { for (let i = 0; i < input.length; i += 3) { let x = input[i]; let y = input[i + 1]; let z = input[i + 2]; if (isInside(x, y, z)) { console.log("inside"); } else { console.log("outside"); } } function isInside(x, y, z) { let x1 = 10; let x2 = 50; let y1 = 20; let y2 = 80; let z1 = 15; let z2 = 50; if (x >= x1 && x <= x2) { if (y >= y1 && y <= y2) { if (z >= z1 && z <= z2) { return true; } } } return false; } } function roadRadar(input) { let zone = input[1]; function getLimit(zone) { switch (zone) { case 'city': return 50; case 'residential': return 20; case 'interstate': return 90; case 'motorway': return 130; default: break; } } let speed = +input[0]; let limit = getLimit(zone); function getInfraction(speed, limit) { let overSpeed = speed - limit; if (overSpeed <= 0) { return ''; } else { if (overSpeed <= 20) { return 'speeding'; } else if (overSpeed <= 40) { return 'excessive speeding'; } else { return 'reckless driving'; } } } console.log(getInfraction(speed, limit)) } function templateFormat(input) { console.log(`<?xml version="1.0" encoding="UTF-8"?> <quiz>`) for (let i = 0; i < input.length; i += 2) { let question = input[i]; let answer = input[i + 1]; console.log(`<question> ${question} </question>`); console.log(`<answer> ${answer} </answer>`); } console.log(`</quiz>`); } function cookingByNumbers(input) { let chop = () => inpurNumber / 2; let dice = () => Math.sqrt(inpurNumber); let spice = () => inpurNumber + 1; let bake = () => inpurNumber * 3; let fillet = () => inpurNumber * 0.8; let inpurNumber = +input[0]; for (let i = 1; i < input.length; i++) { let operation = input[i]; switch (operation) { case 'chop': inpurNumber = chop(); break; case 'dice': inpurNumber = dice(inpurNumber); break; case 'spice': inpurNumber = spice(inpurNumber); break; case 'bake': inpurNumber = bake(inpurNumber); break; case 'fillet': inpurNumber = fillet(inpurNumber); break; default: break; } console.log(inpurNumber); } } function modifyAverage(input) { let nmbrs = input.toString(); let avrg = (nmbrs) => { let sum = 0; for (let nmbr of nmbrs) { sum += +nmbr; } return sum / nmbrs.length; } while (avrg(nmbrs) <= 5) { nmbrs += '9'; } console.log(nmbrs); } function validityChecker(input) { let x1 = input[0]; let y1 = input[1]; let x2 = input[2]; let y2 = input[3]; /* d=√(x2−x1) ^ 2+(y2−y1) ^ 2 */ let d = Math.sqrt((x1 - 0) ** 2 + (y1 - 0) ** 2); if (isInteger(d)) { console.log(`{${x1}, ${y1}} to {0, 0} is valid`) } else { console.log(`{${x1}, ${y1}} to {0, 0} is invalid`) } d = Math.sqrt((x2 - 0) ** 2 + (y2 - 0) ** 2); if (isInteger(d)) { console.log(`{${x2}, ${y2}} to {0, 0} is valid`) } else { console.log(`{${x2}, ${y2}} to {0, 0} is invalid`) } d = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2); if (isInteger(d)) { console.log(`{${x1}, ${y1}} to {${x2}, ${y2}} is valid`) } else { console.log(`{${x1}, ${y1}} to {${x2}, ${y2}} is invalid`) } function isInteger(x) { return parseInt(x, 10) === x; } } function treasureLocator(input) { let tuvalu = (x, y) => { return x >= 1 && x <= 3 && y >= 1 && y <= 3; } let tokelau = (x, y) => { return x >= 8 && x <= 9 && y >= 0 && y <= 1; } let samoa = (x, y) => { return x >= 5 && x <= 7 && y >= 3 && y <= 6; } let tonga = (x, y) => { return x >= 0 && x <= 2 && y >= 6 && y <= 8; } let cook = (x, y) => { return x >= 4 && x <= 9 && y >= 7 && y <= 8; } let str = ''; for (let i = 0; i < input.length; i += 2) { let x = input[i]; let y = input[i + 1]; if (tuvalu(x, y)) { str = 'Tuvalu'; } else if (tokelau(x, y)) { str = 'Tokelau'; } else if (samoa(x, y)) { str = 'Samoa'; } else if (tonga(x, y)) { str = 'Tonga'; } else if (cook(x, y)) { str = 'Cook'; } else { str = 'On the bottom of the ocean'; } console.log(str); } } function tripLength(input) { let x1 = input[0]; let y1 = input[1]; let x2 = input[2]; let y2 = input[3]; let x3 = input[4]; let y3 = input[5]; let dist = (xf, yf, xs, ys) => Math.sqrt(Math.pow(xf - xs, 2) + Math.pow(yf - ys, 2)); let d123 = dist(x1, y1, x2, y2) + dist(x2, y2, x3, y3); let d132 = dist(x1, y1, x3, y3) + dist(x3, y3, x2, y2); let d213 = dist(x2, y2, x1, y1) + dist(x1, y1, x3, y3); let shortD = Math.min(d123, d132, d213); if (shortD == d123) { console.log(`1->2->3: ${shortD}`); return; } if (shortD == d132) { console.log(`1->3->2: ${shortD}`); return; } if (shortD == d213) { console.log(`2->1->3: ${shortD}`); return; } } function DNAHelix(num) { let arr = ['AT', 'CG', 'TT', 'AG', 'GG']; let starArr = [2, 1, 0, 1]; let dashArr = [0, 2, 4, 2]; let s = '*'; let d = '-'; for (let i = 0; i < num; i++) { let starCnt = i % 4; let dnaIndx = i % 5; let dashCnt = i % 4; console.log(`${s.repeat(starArr[starCnt])}${arr[dnaIndx][0]}${d.repeat(dashArr[dashCnt])}${arr[dnaIndx][1]}${s.repeat(starArr[starCnt])}`); } } <file_sep>/Crossword/app.js function crossword(matrix) { let str = ''; let commandExecutor = { 'filterUPPERCASE': (line) => filterUPPERCASE(line), 'filterLOWERCASE': (line) => filterLOWERCASE(line), 'filterNUMS': (line) => filterNUMS(line), 'sortA': (line) => sortA(line), 'sortZ': (line) => sortZ(line), 'rotate': (line) => rotate(line), 'get': (line) => get(line) }; matrix.forEach(line => { let command = line[0] + line[1]; if (line[0] === 'rotate' || line[0] === 'get') { command = line[0]; } commandExecutor[command](line); }); function filterUPPERCASE(line) { let matches = line[3].match(/[A-Z]/g); str += matches[+line[2] - 1]; } function filterLOWERCASE(line) { let matches = line[3].match(/[a-z]/g); str += matches[+line[2] - 1]; } function filterNUMS(line) { let matches = line[3].match(/[0-9]/g); str += matches[+line[2] - 1]; } function sortA(line) { let sorted = line[3].split('').sort(); str += sorted[+line[2] - 1]; } function sortZ(line) { let sorted = line[3].split('').sort((a, b) => { return b.localeCompare(a); }); str += sorted[+line[2] - 1]; } function rotate(line) { let stringi = line[3].split(''); for (let i = 0; i < +line[1] % stringi.length; i++) { stringi.unshift(stringi.pop()); } str += stringi[+line[2] - 1]; } function get(line) { str += line[2].split('')[+line[1]-1]; } console.log(str); } crossword([ ["filter", "UPPERCASE", 4, "AkIoRpSwOzFdT"], ["sort", "A", 3, "AOB"], ["sort", "A", 3, "FAILCL"], ["sort", "Z", 2, "OUTAGN"], ["filter", "UPPERCASE", 2, "01S345U7N"], ["rotate", 2, 2, "DAN"], ["get", 2, "PING"], ["get", 3, "?- 654"] ]); <file_sep>/ObjectsAndAssocArrays/js/main.js function townsToJSON(townData) { townData = townData.slice(1).filter(str => str !== ''); let towns = []; for (let town of townData) { town = town.split(/\s*\|\s*/).filter(str => str !== ''); let townObj = { Town: town[0], Latitude: +town[1], Longitude: +town[2] }; towns.push(townObj); } console.log(JSON.stringify(towns)); } function scoreToHTML(jsonStr) { let parsedArr = JSON.parse(jsonStr); let rslt = `<table> <tr><th>name</th><th>score</th></tr>\n`; for (let obj of parsedArr) { rslt += `\t<tr><td>${escapeChars(obj.name + '')}</td><td>${escapeChars(obj.score + '')}</td></tr>\n`; } rslt += `</table>`; console.log(rslt); function escapeChars(str) { return str.replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;'); } } function jsonToHtml(jsonStr) { let parsedArr = JSON.parse(jsonStr); let str = `<table>\n\t<tr>`; let keys = Object.keys(parsedArr[0]); for (const key of keys) { str += `<th>${key}</th>`; } str += `</tr>\n`; for (let obj of parsedArr) { str += `\t<tr>`; for (const [k, v] of Object.entries(obj)) { str += `<td>${escapeChars(v + '')}</td>`; } str += '</tr>\n'; } str += '</table>'; console.log(str); function escapeChars(str) { return str.replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;'); } } function sumByTown(arr) { let towns = {}; for (let i = 0; i < arr.length; i += 2) { if (towns.hasOwnProperty(arr[i])) { towns[arr[i]] += +arr[i + 1]; } else { towns[arr[i]] = +arr[i + 1]; } } console.log(JSON.stringify(towns)); } function countWordsInText(strArr) { let words = {}; let arr = strArr[0].split(/[^a-zA-Z0-9]+/).filter(s => s !== ''); for (const word of arr) { if (!words.hasOwnProperty(word)) { words[word] = 1; } else { words[word] += 1; } } console.log(JSON.stringify(words)); } function countWordsWithMap(arr) { let myMap = new Map(); for (let str of arr) { let currentWord = str.split(/[^0-9a-zA-Z_]+/) .filter(w => w != ''); for (let word of currentWord) { word = word.toLowerCase(); if (myMap.has(word)) { myMap.set(word, (myMap.get(word) + 1)); } else { myMap.set(word, 1); } } } let sortedKeys = Array.from(myMap.keys()).sort((a, b) => a.localeCompare(b)); for (let key of sortedKeys) { console.log("'" + key + "'" + ' -> ' + myMap.get(key) + ' times'); } } function populationInTowns(arr) { let towns = {}; for (const townData of arr) { let town = townData.split(' <-> ')[0]; let population = townData.split(' <-> ')[1]; if (!towns.hasOwnProperty(town)) { towns[town] = +population; } else { towns[town] += +population; } } for (let obj in towns) { console.log(obj + ' : ' + towns[obj]); } } function cictyMarkets(arr) { let towns = {}; for (let line of arr) { let data = line.split(/\s->\s|\s:\s/).filter(l => l !== ''); let product = {}; let town = data[0]; let prdctName = data[1]; product[prdctName] = { income: +data[2] * +data[3] }; if (!towns.hasOwnProperty(town)) { towns[town] = product; } else { if (!towns[town].hasOwnProperty(prdctName)) { towns[town][prdctName] = product[prdctName]; } else { towns[town][prdctName].income += product[prdctName].income; } } } for (let key in towns) { console.log(`Town - ${key}`); for (const town in towns[key]) { console.log(`$$$${town} : ${towns[key][town].income}`); } } } function lowestPricesInCities(arr) { let products = {}; for (let line of arr) { let data = line.split(' | '); let townName = data[0]; let productName = data[1]; let price = +data[2]; let town = {}; town[townName] = { price: price }; if (!products.hasOwnProperty(productName)) { products[productName] = town; } else { if (!products[productName].hasOwnProperty(townName)) { products[productName][townName] = town[townName]; } else { products[productName][townName].price = Math.min(products[productName][townName].price, town.price); } } } for (const key in products) { if (products.hasOwnProperty(key)) { let sortedObj = sortObject(products[key]); let v = sortedObj[0]; console.log(`${key} -> ${sortedObj[0].value.price} (${sortedObj[0].key})`); } } function sortObject(obj) { var arr = []; var prop; for (prop in obj) { if (obj.hasOwnProperty(prop)) { arr.push({ 'key': prop, 'value': obj[prop] }); } } arr.sort(function (a, b) { return a.value - b.value; }); return arr; // returns array } }<file_sep>/WarehouseMachine/README.md # WarehouseMachine <file_sep>/Stadium/app.js function stadium(arr) { let numberOfSeats = +arr.splice(0, 1)[0]; let totalMoney = 0; let countOfFans = 0; let ticketPrice = 0; let stadium = { 'A': { 'LITEX': [], 'LEVSKI': [], 'VIP': [] }, 'B': { 'LITEX': [], 'LEVSKI': [], 'VIP': [] }, 'C': { 'LITEX': [], 'LEVSKI': [], 'VIP': [] } }; arr.forEach(line => { let zone = line.split('*')[0]; let seat = line.split('*')[1]; let sector = line.split('*')[2]; if (sector === 'A') { if (zone === 'VIP') { ticketPrice = 25; } else { ticketPrice = 10; } } else if (sector === 'B') { if (zone === 'VIP') { ticketPrice = 15; } else { ticketPrice = 7; } } else if (sector === 'C') { if (zone === 'VIP') { ticketPrice = 10; } else { ticketPrice = 5; } } if (stadium[sector][zone].length === 0) { stadium[sector][zone] = Array(numberOfSeats).fill(0); stadium[sector][zone][seat - 1] = 1; totalMoney += ticketPrice; countOfFans += 1; } else { if (stadium[sector][zone][seat - 1] === 0) { totalMoney += ticketPrice; countOfFans += 1; } else { console.log(`Seat ${seat} in zone ${zone} sector ${sector} is unavailable`); } } }); console.log(`${totalMoney} lv.`); console.log(`${countOfFans} fans`); } stadium(["5","LITEX*5*A", "LEVSKI*2*A", "LEVSKI*3*B", "VIP*4*C", "LITEX*3*B", "LEVSKI*2*A", "LITEX*5*B", "LITEX*5*A", "VIP*1*A"]);//42 lv. <file_sep>/CofeeMashine/js/main.js function coffeeMachine(strArr) { let totalMoney = 0; strArr.forEach(line => { let orderPrice = 0.8; let order = line.split(', '); let insertedCoins = order[0]; let drinkType = order[1]; if (drinkType === 'coffee' && order[2] === 'decaf') { orderPrice = 0.9; } if (order[order.length - 2] === 'milk') { orderPrice += 0.1; } let sugarPrice = +order.slice(-1)[0]; if (sugarPrice > 0) { orderPrice += 0.1; } if (insertedCoins >= orderPrice) { totalMoney += orderPrice; let change = insertedCoins - orderPrice; console.log(`You ordered ${drinkType}. Price: ${orderPrice.toFixed(2)}$ Change: ${change.toFixed(2)}$`); } else { let lack = orderPrice - insertedCoins; console.log(`Not enough money for ${drinkType}. Need ${lack.toFixed(2)}$ more.`); } }); console.log(`Income Report: ${totalMoney.toFixed(2)}$`); } <file_sep>/JS_MyTools/js/myTools.js function escapeChars(str) { return str.replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;'); } // Sort object function sortObject(obj) { var arr = []; var prop; for (prop in obj) { if (obj.hasOwnProperty(prop)) { arr.push({ 'key': prop, 'value': obj[prop] }); } } arr.sort(function (a, b) { return a.value - b.value; }); return arr; // returns array } function sortByTwoCriteria(a,b){ let sorted = obj.sort((a, b) => { if (countA > countB) return -1; //descending order if (countA < countB) return 1; if (a < b) return -1; //ascending order if (a > b) return 1; return 0; }); } function compareArrays(array, arr) { let hasEquals = array.length === arr.length && array.every((value, index) => value === arr[index]); } function executeCommand(commands) { let commandExecuter = { //obj of annonimous functions breeze: (value) => breeze(value), gale: (value) => gale(value), smog: (value) => smog(value) };//command for (let row of commands) { let [command, value] = row.split(' '); commandExecuter[command](value); } } function regexExec(str){ let exec; while ((exec = regex.exec(str)) != null) { result = result.replace(exec[0], ""); } }<file_sep>/Stadium/README.md # Stadium <file_sep>/TicketScan/README.md # TicketScan <file_sep>/Trucks/README.md # Trucks <file_sep>/ObjectAndJSON/js/main.js // Your code here! function heroicInventory(input) { let heroes = []; for (let line of input) { let heroData = line.split(' / '); let heroName = heroData[0]; let heroLevel = +heroData[1]; let heroItems = []; if (heroData.length > 2) { heroItems = heroData[2].split(', '); } let hero = { name: heroName, level: heroLevel, items: heroItems }; heroes.push(hero); } console.log(JSON.stringify(heroes)); } function JSONsTable(input) { let rslt = `<table>\n`; for (let line of input) { let obj = JSON.parse(line); rslt += `\t<tr>\n`; rslt += `\t\t<td>${escapeChars(obj.name)}</td>\n`; rslt += `\t\t<td>${escapeChars(obj.position)}</td>\n`; rslt += `\t\t<td>${obj.salary}</td>\n`; rslt += `\t</tr>\n`; } rslt += `</table>`; console.log(rslt); function escapeChars(str) { return str .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;'); } } function cappyJuice(input) { let juices = {}; let bottles = {}; for (let line of input) { line = line.split(' => '); let juiceName = line[0]; let quantity = +line[1]; if (!juices.hasOwnProperty(juiceName)) { juices[juiceName] = 0; } juices[juiceName] += quantity; if (juices[juiceName] >= 1000) { bottles[juiceName] = parseInt(juices[juiceName] / 1000); } } for (const key of Object.keys(bottles)) { console.log(`${key} => ${bottles[key]}`); } } function storeCatalog(input) { let store = {}; for (const line of input) { let ch = line[0]; let data = line.split(' : '); let prdctName = data[0]; let prdctPrice = +data[1]; if (!store.hasOwnProperty(ch)) { store[ch] = {}; } store[ch][prdctName] = prdctPrice; } let storeKeys = Object.keys(store).sort((a, b) => a.localeCompare(b)); for (const key of storeKeys) { if (store.hasOwnProperty(key)) { const element = store[key]; let sortedKeys = Object.keys(element).sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' })); console.log(key); for (const el of sortedKeys) { console.log(` ${el}: ${store[key][el]}`); } } } } function autoEngineeringCompany(input) { let cars = {}; for (let carData of input) { carData = carData.split(' | '); let carBrand = carData[0]; let carModel = carData[1]; let producedCars = +carData[2]; if (!cars.hasOwnProperty(carBrand)) { cars[carBrand] = {}; } if (!cars[carBrand].hasOwnProperty(carModel)) { cars[carBrand][carModel] = 0; } cars[carBrand][carModel] += producedCars; } for (const key in cars) { console.log(key); const element = cars[key]; for (const mdl in element) { const count = element[mdl]; console.log(`###${mdl} -> ${count}`); } } } function systemComponents(input) { let components = {}; for (let data of input) { data = data.split(' | '); let systemName = data[0]; let componentName = data[1]; let subcomponentName = data[2]; if (!components.hasOwnProperty(systemName)) { components[systemName] = {}; } if (!components[systemName].hasOwnProperty(componentName)) { components[systemName][componentName] = []; } components[systemName][componentName].push(subcomponentName); } let sortedSystems = Object.keys(components).sort((a, b) => { let countA = Object.keys(components[a]).length; let countB = Object.keys(components[b]).length; if (countA > countB) return -1; //descending order if (countA < countB) return 1; if (a < b) return -1; //ascending order if (a > b) return 1; return 0; }); for (const key of sortedSystems) { console.log(key); let ssss = components[key]; let dddd = Object.keys(ssss).sort((a, b) => { let fr = Object.keys(ssss[a]).length; let sc = Object.keys(ssss[b]).length; if (fr > sc) return -1; //descending order if (fr < sc) return 1; return 0; }); for (const it of dddd) { let sdsd = components[key][it]; console.log(`|||${it}`); for (let i = 0; i < sdsd.length; i++) { console.log(`||||||${sdsd[i]}`); } } } } function usernames(input) { let usernames = {}; for (let username of input) { if (!usernames.hasOwnProperty(username)) { usernames[username] = null; } } let sortedUsernames = Object.keys(usernames).sort((a, b) => { if (a.length < b.length) return -1; //ascending order if (a.length > b.length) return 1; if (a < b) return -1; //ascending order if (a > b) return 1; return 0; }); console.log(sortedUsernames.join('\n')); } function uniqueSequences(input) { let arrays = []; for (let arr of input) { arr = JSON.parse(arr).sort((a, b) => { return b - a; }); let isUnique = true; for (let i = 0; i < arrays.length; i++) { let hasEquals = arrays[i].length === arr.length && arrays[i].every((value, index) => value === arr[index]); if (hasEquals) { isUnique = false; } } if (isUnique) { arrays.push(arr); } } arrays .sort((a, b) => a.length - b.length) .forEach(arr => { console.log(`[${arr.join(', ')}]`); }); } function arenaTier(input) { let gldData = input .map((info) => { return info.split(/\s+->\s+/); }) .filter((ln) => ln.length === 3) .reduce((acc, cur) => { const gldName = cur[0]; const technique = cur[1]; const skill = +cur[2]; let ssss = acc[gldName]; if (!acc[gldName]) { acc[gldName] = {}; if (!acc[gldName][technique]) { acc[gldName][technique] = skill; acc[gldName].overalSkill = skill; } } else if (!acc[gldName][technique]) { acc[gldName][technique] = skill; acc[gldName].overalSkill += skill; } else if (acc[gldName][technique]) { if (acc[gldName][technique] < skill) { acc[gldName].overalSkill += skill - acc[gldName][technique]; } acc[gldName][technique] = skill; } return acc; }, {}); let battleData = input .map((line) => { return line.split(/\svs\s/); }) .filter(ln => ln.length === 2) .forEach((arr) => { if (gldData[arr[0]] && gldData[arr[1]] && gldData[arr[0]] !== null && gldData[arr[1]] !== null) { let frst = Object.keys(gldData[arr[0]]).filter(p => p !== 'overalSkill'); let scnd = Object.keys(gldData[arr[1]]).filter(p => p !== 'overalSkill'); let hasCommonTechnique = frst .some(r => scnd.indexOf(r) >= 0); if (hasCommonTechnique) { const looser = gldData[arr[0]].overalSkill < gldData[arr[1]].overalSkill ? arr[0] : arr[1]; gldData[looser] = null; } } }); Object.keys(gldData) .filter(gl => gldData[gl] !== null) .sort((a, b) => { return gldData[b].overalSkill - gldData[a].overalSkill || a - b; }) .forEach((name) => { console.log(`${name}: ${gldData[name].overalSkill} skill`); Object.keys(gldData[name]) .filter((tech) => tech !== 'overalSkill') .sort((a, b) => { return gldData[name][b] - gldData[name][a] || a > b; }) .forEach(technique => { console.log(`- ${technique} <!> ${gldData[name][technique]}`); }); }); }
b02e6fdc1764147ed6b5fb34ea954069ce96ede0
[ "JavaScript", "Markdown" ]
17
JavaScript
bobiOneBG/JS_Fundamentals_Exersice
f0709e42c060d5bd089a0fadde97a2e88894ffa7
f4e62107cb301e2413c8a9022a780aba92af2c36
refs/heads/main
<repo_name>danielsalazar86/delegacion<file_sep>/funcionesTeatro.php <?php class Funciones{ //atributos private $nombreFuncion; private $horaInicio; private $duracionObra; private $precio; public function __construct($nombreFuncion, $horaInicio, $duracionObra, $precio){ $this->nombreFuncion = $nombreFuncion; $this->horaInicio = $horaInicio; $this->duracionObra = $duracionObra; $this->precio = $precio; } //Sets. public function setNombreFuncion($nombre){ $this->nombreFuncion = $nombre; } public function setHoraInicio($hora){ $this->horaInicio = $hora; } public function setDuracionObra($duracion){ $this->duracionObra = $duracion; } public function setPrecio($valor){ $this->precio = $valor; } //Gets. public function getNombreFuncion(){ return $this->nombreFuncion; } public function getHoraInicio(){ return $this->horaInicio; } public function getDuracionObra(){ return $this->duracionObra; } public function getPrecio(){ return $this->precio; } public function __toString(){ $cadena = "- Nombre de la funcion: ".$this->getNombreFuncion()." - Hora de inicio: ".$this->getHoraInicio(). " - Duracion de la obra: ".$this->getDuracionObra()." - Precio: ".$this->getPrecio()."\n"; return $cadena; } } //Cierre class. ?><file_sep>/testTeatroFunciones.php <?php include_once 'teatroMod.php'; include_once 'funcionesTeatro.php'; function menuOpciones(){ echo "Menu de opciones\n"; echo "1 = Cargar datos\n"; echo "2 = Cambiar nombre y direccion del teatro\n"; echo "3 = Cambiar los datos de una funcion\n"; echo "4 = Corroborar horarios de funciones\n"; echo "5 = Visualizar toda la informacion\n"; echo "0 = Salir\n"; $opc = trim(fgets(STDIN)); return $opc; } function main(){ $cargarDatos = false; do{ $resp = menuOpciones(); if($resp == 1){ $arregloFuncionesT = array(); echo "Ingrese nombre del teatro\n"; $nombreT = trim(fgets(STDIN)); echo "Ingrese direccion de teatro\n"; $direccionT = trim(fgets(STDIN)); echo "Ingrese el total de funciones\n"; $totalFunciones = trim(fgets(STDIN)); for($i=0; $i<$totalFunciones; $i++){ echo "Ingrese nombre de la funcion\n"; $nombreFuncion = trim(fgets(STDIN)); echo "Ingrese hora de inicio\n"; $horaInicio = trim(fgets(STDIN)); echo "Ingrese duración de la obra\n"; $duracionObra = trim(fgets(STDIN)); echo "Ingrese precio de la funcion\n"; $precio = trim(fgets(STDIN)); $funciones = new Funciones($nombreFuncion, $horaInicio, $duracionObra, $precio); $arregloFuncionesT[$i] = $funciones; } $teatro = new Teatro($nombreT, $direccionT, $arregloFuncionesT); $cargarDatos = true; } elseif($resp == 2){ if($cargarDatos == true){ echo "Ingrese nuevo nombre del teatro\n"; $nombre = trim(fgets(STDIN)); echo "Ingrese nueva dirección del teatro\n"; $direccion = trim(fgets(STDIN)); $teatro->cambiarTeatro($nombre, $direccion); } else{ echo "ERROR, aun no se han cargado los datos\n"; } } elseif($resp == 3){ if($cargarDatos == true){ echo "Ingrese el nombre de la nueva funcion\n"; $nuevaFuncion = trim(fgets(STDIN)); echo "Ingrese hora de inicio\n"; $horaInicio = trim(fgets(STDIN)); echo "Ingrese la duracion\n"; $duracionObra = trim(fgets(STDIN)); echo "Ingrese precio de la nueva funcion\n"; $precioNuevo = trim(fgets(STDIN)); echo "Ingrese el numero de la funcion a reemplazar\n"; $posicion = trim(fgets(STDIN)); $teatro->cambiarFunciones($nuevaFuncion, $horaInicio, $duracionObra, $precioNuevo, $posicion); } else{ echo "ERROR, aun no se han cargado los datos\n"; } } elseif($resp == 4){ if($cargarDatos == true){ if($teatro->corroboraHorariosFunciones()){ echo "Atencion, hay funciones que poseen el mismo horario, revisar!!!\n"; } else{ echo "Todas las funciones tienen distintos horarios\n"; } } else{ echo "ERROR, aun no se han cargado los datos\n"; } } elseif($resp == 5){ if($cargarDatos == true){ echo $teatro; } else{ echo "ERROR, aun no se han cargado los datos\n"; } } }while($resp != 0); } main(); ?><file_sep>/teatroMod.php <?php class Teatro{ //atributos private $nombreTeatro; private $direccionTeatro; private $funciones; public function __construct($nombreT, $direccionT, $funcionesT){ $this->nombreTeatro = $nombreT; $this->direccionTeatro = $direccionT; $this->funciones = $funcionesT; } //Sets. public function setNombre($nombre){ $this->nombreTeatro = $nombre; } public function setDireccion($direccion){ $this->direccionTeatro = $direccion; } public function setFunciones($arrayFunciones){ $this->funciones = $arrayFunciones; } //Gets. public function getNombre(){ return $this->nombreTeatro; } public function getDireccion(){ return $this->direccionTeatro; } public function getFunciones(){ return $this->funciones; } public function cambiarTeatro($nombre, $direccion){ $this->setNombre($nombre); $this->setDireccion($direccion); } public function cambiarFunciones($nuevaFuncion, $horaInicio, $duracion, $precioNuevo, $posicion){ $arregloFunciones = $this->getFunciones(); $esta = false; $i = 0; $j = count($arregloFunciones); while($i< $j && !$esta){ if($i == $posicion){ $arregloFunciones[$i]->setNombreFuncion($nuevaFuncion); $arregloFunciones[$i]->setHoraInicio($horaInicio); $arregloFunciones[$i]->setDuracionObra($duracion); $arregloFunciones[$i]->setPrecio($precioNuevo); $this->setFunciones($arregloFunciones); $esta = true; } $i++; } } public function corroboraHorariosFunciones(){ $arregloFunciones2 = $this->getFunciones(); $sale = false; $i = 0; $j = count($arregloFunciones2); $arregloHoras = array(); while($i< $j){ $arregloHoras[$i] = $arregloFunciones2[$i]->getHoraInicio(); $i++; } if(count($arregloHoras) > count(array_unique ($arregloHoras))){ $sale = true; } return $sale; } public function __toString(){ $cadena = "El teatro ".$this->getNombre(). " esta ubicado en la direccion ".$this->getDireccion()."\n". "Presenta las siguientes funciones: \n"; $arregloFunciones3 = $this->getFunciones(); foreach ($arregloFunciones3 as $valor){ $cadena.= $valor; } return $cadena; } } //cierre class.
6ac6c2e0d0d1d687e08587b98d3e647b31ff5bb2
[ "PHP" ]
3
PHP
danielsalazar86/delegacion
ad5b2697e9da21de5d2b9c360f3de1982a0cf922
864d504be87fcd138357d333459956c57a15fd1a
refs/heads/master
<file_sep># == Schema Information # # Table name: pieces # # id :integer not null, primary key # created_at :datetime not null # updated_at :datetime not null # user_id :integer # class Piece < ActiveRecord::Base belongs_to :user, inverse_of: :pieces validates :user, presence: true has_many :versions, dependent: :destroy, inverse_of: :piece, order: "created_at ASC" has_many :drafts, through: :versions scope :last_modified_first, order("updated_at DESC") default_scope last_modified_first def current_version versions.last end def title current_version.title if !!current_version end def content current_version.content if !!current_version end def blurb current_version.blurb if !!current_version end def short_title current_version.short_title if !!current_version end end <file_sep>tinder ====== Get feedback from others on creative pieces. Setting up a development environment ==================================== The easy way ------------ There is no easy way just yet! Sorry! The hard way ------------ Install PostgreSQL 9.2.x, git, Ruby 2.0.0-p0, and bundler Ubuntu > apt-get install postgresql git Fedora > yum install postgresql-server git Gentoo/Sabayon > emerge dev-db/postgresql-server # Latest binary PostgreSQL is currently 9.1.9 on Sabayon > emerge git > equo install git MacOS See http://www.postgresql.org/download/macosx/ Install Ruby 2.0.0-p0 http://www.ruby-lang.org It's recommended to use one of the following methods to help manage/install Ruby: chruby: https://github.com/postmodern/chruby RVM: https://rvm.io/rvm/install/ rbenv: https://github.com/sstephenson/rbenv/ Install bundler > gem install bundler Clone the repository - git://github.com/nullsix/tinder.git > git clone git://github.com/nullsix/tinder.git > cd tinder > bundle install Create a Postgres user/role > psql -U postgres > CREATE ROLE tinder CREATEDB LOGIN ENCRYPTED PASSWORD '<PASSWORD>'; > \q Or you can use the following tool and set the username to 'tinder' and the password to '<PASSWORD>': > createuser -P Then create the database and load the schema: > rake db:create > rake db:schema:load To test simply run RSpec: > rake spec <file_sep># == Schema Information # # Table name: drafts # # id :integer not null, primary key # number :integer # created_at :datetime not null # updated_at :datetime not null # version_id :integer # require 'spec_helper' describe Draft do it "has a valid factory" do FactoryGirl.build_stubbed(:draft).should be_valid end describe "instance methods" do methods = [ :version, :piece, :number ] methods.each do |m| it "responds to #{m}" do should respond_to m end end context "with a draft" do subject { FactoryGirl.build_stubbed :draft } specify do subject.version.should be_a Version end specify do subject.number.should be_an Integer end specify do subject.piece.should be_a Piece end end end end <file_sep>FactoryGirl.define do factory :piece do ignore do versions_count 1 end user { FactoryGirl.build_stubbed :user } before :stub do |piece, evaluator| FactoryGirl.stub_list :version, evaluator.versions_count, piece: piece end before :build, :create do |piece, evaluator| FactoryGirl.create_list :version, evaluator.versions_count, piece: piece end end end <file_sep># == Schema Information # # Table name: versions # # id :integer not null, primary key # title :string(255) # content :text # created_at :datetime not null # updated_at :datetime not null # piece_id :integer # number :integer # class Version < ActiveRecord::Base belongs_to :piece, inverse_of: :versions has_one :draft, dependent: :destroy validates :title, length: { maximum: 255 } validates :number, numericality: { greater_than: 0 } validates :piece, presence: true def blurb content_length = 50 if content.length > content_length "#{content[0..(content_length-4)]}..." else content end end def short_title title_length = 30 if title.length > title_length "#{title[0..(title_length-4)]}..." else title end end end <file_sep>require 'spec_helper' describe PagesController do context "with no user logged in" do describe "GET index" do before :each do get :index end it "renders the #index view" do should render_template :index end it "does not assign @piece" do assigns(:piece).should be_nil end it "does not assign @version" do assigns(:version).should be_nil end end end context "with a logged in user" do before :each do @user = FactoryGirl.create :user, pieces_count: 0 end describe "GET index" do before :each do session[:user_id] = @user.id get :index end it "renders the #index view" do should render_template :index end describe "@piece" do subject { assigns :piece } it "is a Piece" do should be_a Piece end it "is a new Piece" do should be_a_new_record end it "belongs to the logged in user" do subject.user.should eq @user end end describe "@version" do subject { assigns :version } it "is a Version" do should be_a Version end it "is a new Version" do should be_a_new_record end it "belongs to the piece being created" do subject.piece.should eq assigns(:piece) end end end end end <file_sep>feature "Versions Management" do before :each do login_with_oauth @piece = FactoryGirl.create :piece, user_id: User.last.id, versions_count: 0 @versions = [] 5.times do |i| @versions << FactoryGirl.create(:version, piece_id: @piece.id, title: i.to_s, content: i.to_s, number: (i+1).to_s) end end subject { page } context "view a piece's versions" do scenario "redirects to history" do version = @versions.last visit piece_versions_path @piece.id current_path.should == history_piece_path(id: @piece.id) end end context "view a piece's version" do before :each do @version_wanted = @versions.last visit piece_version_path @piece.id, @version_wanted.number end it_behaves_like "piece bar for history" do let(:piece) { @piece } end scenario "displays a version's data" do within ".version" do should have_content @version_wanted.title should have_content @version_wanted.content end end end end <file_sep># == Schema Information # # Table name: pieces # # id :integer not null, primary key # created_at :datetime not null # updated_at :datetime not null # user_id :integer # require 'spec_helper' describe Piece do it "has a valid factory" do FactoryGirl.build_stubbed(:piece).should be_valid end context "with a piece" do before :each do @versions_count = 2 @piece = FactoryGirl.build_stubbed :piece, versions_count: @versions_count end describe "instance methods" do subject { @piece } methods = [ :versions, :current_version, :title, :content, :blurb, :short_title, :drafts ] methods.each do |m| it "responds to ##{m}" do should respond_to m end end context "with a saved piece" do before :each do @piece = FactoryGirl.create :piece, versions_count: @versions_count end subject { @piece } it "has the correct number of versions" do subject.versions.length.should == @versions_count end it "has a #current_version is the last item in #versions" do subject.current_version.should == subject.versions.last end specify "#title gives the current version's title" do subject.title.should == subject.current_version.title end specify "#content gives the current version's content" do subject.content.should == subject.current_version.content end specify "#blurb gives the current version's content" do subject.blurb.should == subject.current_version.blurb end specify "#short_title gives the current version's short title" do subject.short_title == subject.current_version.short_title end context "with a draft" do before :each do @version = @piece.versions.first @draft = FactoryGirl.create :draft, version: @version end subject { @piece } it "has one draft" do subject.drafts == [@draft] end end end context "with a piece with no versions" do before :each do @no_versions_piece = FactoryGirl.create :piece, versions_count: 0 end subject { @no_versions_piece } specify "#versions is empty" do subject.versions.should be_empty end specify "#drafts is empty" do subject.drafts.should be_empty end specify "#title is nil" do subject.title.should be_nil end specify "#content is nil" do subject.content.should be_nil end specify "#blurb is nil" do subject.blurb.should be_nil end specify "#short_title is nil" do subject.short_title.should be_nil end end end it "has a user" do @piece.user.should_not be_nil end it "is not valid without a user" do no_user_piece = FactoryGirl.build_stubbed :piece, user: nil no_user_piece.should_not be_valid end describe "creating a new version" do it "increases the size of the versions collection by 1" do piece = FactoryGirl.create :piece expect do FactoryGirl.create :version, piece: piece piece.reload end.to change{ piece.versions.length }.by 1 end end describe "a new version" do before :each do @piece = FactoryGirl.create :piece @new_version = FactoryGirl.create :version, piece: @piece end it "saves the new version" do @new_version.should_not be_a_new_record end it "has piece as its piece" do @new_version.piece.should == @piece end it "adds the new version to the versions collection" do @piece.versions.should include @new_version end it "sets the new version as the current version" do piece = FactoryGirl.create :piece new_version = FactoryGirl.create :version, piece: piece piece.current_version.should == new_version end end end describe "scopes" do shared_context "with pieces" do let(:pieces) do pieces = [] 5.times do pieces << FactoryGirl.create(:piece) end pieces.reverse! end end context "default" do include_context "with pieces" it "returns last modified pieces" do pieces Piece.all.should == pieces end end context "last_modified_first" do include_context "with pieces" it "returns last modified pieces" do pieces Piece.last_modified_first.should == pieces end end end end <file_sep>class PagesController < ApplicationController def index if current_user @piece = current_user.pieces.build @version = @piece.versions.build end end end
b6d119b5c9108c1eb0dbd9252f2ad5f4c06ee5a2
[ "Markdown", "Ruby" ]
9
Ruby
aedorn/tinder
d2a46cc96ba3d29f7ae69b37139ea278b30c6f96
0c7a6fc5756cbcb23b914658f1acc9a7a5de3287
refs/heads/master
<repo_name>BhuwanUpadhyay/cv<file_sep>/Makefile install: sudo gem install bundler && bundle install run: bundle exec jekyll serve --drafts --watch build: bundle exec jekyll build upgrade: bundle update help: bundle exec jekyll help <file_sep>/index.markdown --- layout: page --- <NAME> Software Engineer 123-456-78900 <EMAIL> linkedin.com/in/thirvanen600 Summary Enthusiastic software engineer with 4+ years experience participating in the complete product development lifecycle of successfully launched applications. Eager to join XYZ Inc. to deliver mission-critical technology and business solutions to Fortune 500 companies and some of the most recognized brands on the planet. In previous roles, reduced downtime by 15% and warranty costs by 25%; identified and resolved a process bottleneck that reduced coding efficiency by up to 30%. Experience Software Engineer Cloud Nin9 August 2017–present Built modern applications with JAVA, Spring, Spring Boot, SQL Server, No SQL. Developed microservices and Web Services (incl. REST/SOAP/WSDL/XML/SOA). Built on Pivotal Cloud Foundry Platform (Gradle, GitHub). Continuously integrated and deployed developed software. Updated the continuous integration/deployment scripts as necessary to improve continuous integration practices. Consulted with Product Manager to identify minimal viable product and decomposed feature set into small scoped user stories. Key achievement: Ensured the uninterrupted flow of business-critical operations. On-time error analysis reduced downtime by 15% and costs of warranty by up to 25%. Software Engineer Intern CodEX September 2016–May 2017 Supported CodEX software development and testing processes. Verified that software met requirements. Maintained existing applications. Collaborated on future projects and innovations. Continuously identified, measured, and improved processes. Key achievement: Identified and resolved a process bottleneck that reduced coding efficiency by up to 30%. Education B.Sc., Software Engineering University of Washington Bothell 2013–2016 Heavy concentration in data structures, Java, SQL. Organized the university hackathon in two consecutive years. Built a mock customer service web app for a Senior Scholar project. Skills Adaptability Agile processes Excellent communication skills JAVA, Spring, Spring Boot, SQL Server, No SQL Microservices development Pivotal Cloud Foundry Platform (Gradle, GitHub) Status tracking tools (Jira and Rally) Strong collaboration skills Practical knowledge of SQL and database concepts Certifications Oracle Certified Associate (OCA) Java SE Programmer CIW Web Development Professional Languages Spanish (Advanced) Interests Alpine skiing Guitar playing<file_sep>/_includes/cv-right-sidebar.html {% assign cv = site.data.cv %} <div class="cv-right-sidebar"> <div class="cv-skills"> <h5>Professional Skills</h5> {% for skill in cv.skills %} <div class="mb-2"> <div> <h6 class="m-0">{{ skill.title }}</h6> </div> {% for category in skill.categories %} <span class="cv-skill"> <span class="cv-skill-o">{{ category.name }}</span> </span> {% endfor %} </div> {% endfor %} </div> <div class="cv-projects mt-2"> <h5>Personal Projects</h5> {% for project in cv.projects %} <div> <h6>{{ project.title }}</h6> <ul> {% for link in project.links %} <li><a href="{{link.href}}">{{link.title}}</a></li> {% endfor %} </ul> </div> {% endfor %} </div> <div class="cv-github-status mt-2"> <h5>Commit on Github</h5> <br/> <a href="https://github.com/BhuwanUpadhyay"> <img align="center" style="width: 100%;" src="https://github-readme-stats.vercel.app/api?username=BhuwanUpadhyay&count_private=true&show_icons=true&custom_title=Github%20Status&hide=issues" /> </a> <br/> <br/> </div> <div class="cv-github-status mt-2"> <h5>Rate on Github</h5> <br/> <a href="https://github.com/BhuwanUpadhyay"> <img align="center" style="width: 100%;" src="https://github-readme-stats.vercel.app/api/top-langs/?username=BhuwanUpadhyay&layout=compact" /> </a> <br/> <br/> </div> <div class="cv-experiences mt-2"> <h5>Educations</h5> {% for education in cv.educations %} <div> <div class="d-flex justify-content-between"> <div> <h6>{{ education.title }}</h6> <span class="font-italic">{{ education.years }}</span> </div> <div> <h6>{{ education.school }}</h6> <span class="font-italic">{{ education.grade }}</span> </div> </div> </div> {% endfor %} </div> <div class="cv-languages mt-2"> <h5>Languages</h5> <ul> {% for language in cv.languages %} <li> <span class="cv-language-name"> {{ language.name }}</span> <br> <span class="cv-language-level">{{ language.level }}</span> </li> {% endfor %} </ul> </div> <div class="cv-achievements mt-2"> <h5>Achievements</h5> <ul> {% for achievement in cv.achievements %} <li>{{ achievement.title }}</li> {% endfor %} </ul> </div> <div class="cv-interests mt-2"> <h5>Interests</h5> {% for interest in cv.interests %} <span class="cv-interest"> <span class="cv-interest-o">{{ interest }}</span> </span> {% endfor %} </div> </div> <file_sep>/README.md # CV | <NAME> Web: <https://bhuwanupadhyay.github.io/cv/> ## How to use ?? - Fork this repo. - Install dependencies. ```shell script make install ``` - Change cv detail in data file `_data/cv.yml`. - If you want to change colors modify `assets/css/theme.scss`. ```scss ... $primary: red; $secondary: blue; ... ``` - Run ``` make run ```<file_sep>/Gemfile source "https://rubygems.org" group :jekyll_plugins do gem 'jekyll-seo-tag' gem 'bootstrap', '~> 4.4.1' gem 'kramdown', '>= 2.3.0' gem 'rouge' end
31637938a64c977cb6eede57af5164df5d76eff5
[ "Markdown", "Makefile", "HTML", "Ruby" ]
5
Makefile
BhuwanUpadhyay/cv
46d99c5b236bed9374d85ee2029e20170c2c73b9
ad2f6ae3af1cdd7bc48c974035e16507f96b6914
refs/heads/master
<repo_name>weight-lifting/backend<file_sep>/users/user-model.spec.js const db = require("../data/config") const Users = require("./users-model.js"); describe('users-model.js',() => { describe('add', () => { afterEach(async () => { //clean up await db('users').truncate(); }) it("should insert a user into the db", async () => { //using our model method await Users.add({ username: "Ashley", password: "<PASSWORD>" }) await Users.add({ username: "Mandy", password: '<PASSWORD>'}) //confirm with knex const users = await db('users'); expect(users).toHaveLength(2); expect(users[0].username).toBe("Ashley") }) it("should return new user on insert", async () => { const user = await Users.add({ username: 'Ashley', password: "<PASSWORD>"}) expect(user).toEqual({ id: 1, username: 'Ashley'}) }) }) describe('findById', () => { afterEach(async () => { //clean up await db('users').truncate(); }) it('finds a user by id', async () => { //set up await db('users').insert([ {username: 'Ashley', password: 'abc' }, {username: 'Mandy', password: 'abc' } ]); const user = await Users.findById(2); expect (user.username).toBe('Mandy') }) it('returns undefined on invalid id', async () => { const user = await Users.findById(2); expect(user).toBeUndefined(); }) }) describe('find',() => { afterEach(async () => { //clean up await db('users').truncate(); }) it("should return all users", async () => { //using our model method await Users.add({ username: "Ashley", password: "<PASSWORD>"}) await Users.add({ username: "Mandy", password: "<PASSWORD>"}) //confirm with knex const users = await Users.find(); expect(users).toHaveLength(2); }) }) })<file_sep>/auth/restricted-middleware.js const jwt = require("jsonwebtoken"); const secrets = require("../config/secret"); // const Users = require('../users/users-model.js'); module.exports = (req, res, next) => { const token = req.headers.authorization; console.log(token); if (token) { jwt.verify(token, secrets.jwt, (err, payload) => { if (err) { res.status(403).json({ message: "you are not authorized" }); } else { req.subject = payload.subject; next(); } }); } else { res.status(400).json({ message: "No credentials provided" }); } }; <file_sep>/auth/auth-router.spec.js const request = require("supertest"); const server = require("../api/server"); describe("the auth-router",() => { describe("POST /register", () => { it("responds with json", () => { request(server) .post("/api/auth/register") .send({ username:"admin", password:"<PASSWORD>"}) .set("Accept","application/json") .expect("Content-Type", /json/) .expect(200) .end((err,res) =>{ if(err) return document(err); else(done()) }) }) }) describe('/login',() => { it("responds with json", () => { request(server) .post("/api/auth/register") .send({ username:"admin", password:"<PASSWORD>"}) .set("Accept","application/json") .expect("Content-Type", /json/) .expect(200) .end((err,res) =>{ if(err) return (err); else(done()) }) }) }) })<file_sep>/README.md # Weight Lifting Journal https://weight-lift-1.herokuapp.com/api/ ## API Endpoints ### Auth Endpoints https://weight-lift-1.herokuapp.com/api/auth | **Method** | **Endpoint** | **Description** | | ---------- | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------- | | POST | /register | Creates a `user` sent inside the `body` of the request. **Hashes** password before saving onto the database. | | POST | /login | Uses the credentials sent inside the `body` to authenticate the user. On successful login, creates a JWT token to be used to access restricted endpoints. | ### User https://weight-lift-1.herokuapp.com/api/ | **Method** | **Endpoint** | **Description** | | ---------- | ------------ | -------------------------------------------------------------------------------------------------------------- | | GET | /users | Retrieves a list of all `users` in the databases. | | GET | /users/:id | Retrieves a `user` specified by the `id` provided. | ### Exercise https://weight-lift-1.herokuapp.com/api/ | **Method** | **Endpoint** | **Description** | | ---------- | -------------- | -------------------------------------------------------------------------- | | GET | /exercises | Retrieves a list of all `exercises` for the specific user in the database. | | GET | /exercises/:id | Retrieves an `exercise` specified by the `id` provided for a specific user | | POST | /exercises | If all required fields are met, creates an `exercise` for a specific user. | | DELETE | /exercises/:id | Deletes the `exercise` with the specified `id` for a specific user. | | PUT | /exercises/:id | Updates the `exercise` with the specified `id` for a specific user. | ## Data Models ### Exercise Data Model | **Field** | **Type** | **Description** | | --------------------- | -------- | -------------------------------------------------- | | id | Integer | ID of the newly created exercise | | title | String | Title of the newly created exercise | | targeted area | String | Body part targeted for the newly created exercise | | repetitions completed | Integer | Number of reps of the newly created exercise | | date | Integer | Date of newly created exercise | | user id | Integer | User ID that the newly created exercise belongs to | ### User Data Model | Field | Type | Description | | -------- | ---------- | ------------------------------------ | | username | String | A unique username chosen by the user | | password | <PASSWORD> | <PASSWORD> | <file_sep>/api/server.spec.js const request = require("supertest"); const server = require("./server.js"); describe("server.js", () => { it('should set the test env', () => { expect(process.env.DB_ENV).toBe('testing'); }) describe('Get /', () => { it('should return 200', async () => { const res = await request(server).get("/"); expect(res.status).toBe(200); }) }) })
e8a0630718955059488ffd0d54542538ce94cef0
[ "JavaScript", "Markdown" ]
5
JavaScript
weight-lifting/backend
9175dc7feda341c5c6fb52e3ef634cfc3938b040
749e806029ba43c223bed8a35b190fd924536c99
refs/heads/master
<file_sep><?php class HtmlHelper { public static $_Title; public static $_ViewData; function __construct() { $this->m_title = ""; HtmlHelper::$_ViewData = array(); //Start an output buffer for html to be written to. ob_start(); } //Helper to create a dropdown list for an array, with the ability to specify value and text fields and html classes public function DropDownList(array $model, array $htmlAttributes = null, string $value = 'id', string $text = 'value', string $selected = null) { if(count($model) > 0) { //Make sure the provided text and value fields exisit for the object type $propNames = get_object_vars($model[0]); if(!array_key_exists($value, $propNames) && $value !== null) { throw new InvalidArgumentException('$value argument ' . $value . ' does not correspond with a field in the provided model'); } if(!array_key_exists($text, $propNames)) { throw new InvalidArgumentException('$text argument ' . $text . ' does not correspond with a field in the provided model'); } echo '<select '. $this->GetHtmlAttribStr($htmlAttributes) .'>'; for($index = 0; $index < count($model); $index++) { $selectedAttrib = $selected != null ? ($model[$index]->$value == $selected ? ' selected="selected"' : '') : ''; echo '<option value="' . ($value != null ? $model[$index]->$value : $model[$index]->$text) . '"' . $selectedAttrib . '>' . $model[$index]->$text . '</option>'; } echo '</select>'; } else { echo '<select '. $this->GetHtmlAttribStr($htmlAttributes) . ' />'; } } public function Input($model, array $htmlAttributes = null, $type = "text") { if($htmlAttributes != null && array_key_exists('type', $htmlAttributes)) { echo '<input ' . $this->GetHtmlAttribStr($htmlAttributes) . ' value="' . $model . '" />'; } else { echo '<input type="'. $type .'" ' . $this->GetHtmlAttribStr($htmlAttributes) . ' value="' . $model . '" />'; } } //Renders the buffered output, configurable as to whether to use layout file, and which file to use. public function Render(bool $useLayout = true, string $layoutFile = "_layout.php", string $layoutDir = __DIR__ . "/../Views/") { if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' ) { $useLayout = false; } if(isset(HtmlHelper::$_Title)) { HtmlHelper::$_ViewData['Title'] = HtmlHelper::$_Title; } else { HtmlHelper::$_ViewData['Title'] = ''; } HtmlHelper::$_ViewData['Body'] = ob_get_clean(); if($useLayout === true && $layoutFile != null) { if(file_exists($layoutDir . $layoutFile)) { ob_start(); include $layoutDir . $layoutFile; echo ob_get_clean(); } } else { echo HtmlHelper::$_ViewData['Body']; } } private function GetHtmlAttribStr(array $htmlAttributes) { if($htmlAttributes == null) return ""; $htmlAttribStr = ""; if(!array_key_exists("name", $htmlAttributes) && array_key_exists("id", $htmlAttributes)) { //Copies ID to name if name is empty $htmlAttributes["name"] = $htmlAttributes["id"]; } foreach($htmlAttributes as $name => $value) { if($value != "") { $htmlAttribStr .= $name . '="' . $value . '" '; } else { $htmlAttribStr .= $name . " "; } } return $htmlAttribStr; } } $HTML = new HtmlHelper(); //Push the helper to the globals array, in case, for some reason, it isn't accessible. $GLOBALS["HTML"] = $HTML; ?><file_sep><?php require_once '../Model/User.php'; require_once '../Model/UserAccessLevel.php'; require_once '../core/html.php'; HtmlHelper::$_Title = 'Admin: Users'; StartSession(); RequireAuth(); $user = SafeGetValue($_SESSION, 'User'); if($user->AccessLevel->Name != 'Admin') { ErrorResponse(401); } $users = $Users->Select([], [new DbCondition("Active", true)]); $accessLevels = $UserAccessLevels->Select([]); $userCount = count($users); ?> <h3>Users</h3> <hr /> <table class="table table-light table-striped"> <thead> <tr> <th>Email</th> <th>Firstname</th> <th>Lastname</th> <th>Job Title</th> <th>Accesslevel</th> <th></th> <th></th> </tr> </thead> <tbody id="UserTableBody"> <?php foreach($users as $curr): ?> <tr> <td><?php echo htmlspecialchars($curr->Email) ?></td> <td><?php echo htmlspecialchars($curr->FirstName) ?></td> <td><?php echo htmlspecialchars($curr->LastName) ?></td> <td><?php echo htmlspecialchars($curr->JobTitle) ?></td> <td><?php echo $curr->AccessLevel->Name ?></td> <td><a class="btn btn-info" href="./User/Edit.php?Id=<?php echo $curr->Id ?>">Edit</a></td> <td> <?php if($curr->Id != $user->Id): ?> <form action="./User/Delete.php" method="POST" onsubmit="return confirm('Are you sure you wish to delete this user?')"> <?php echo $HTML->Input($curr->Id, ["id" => "Id"], "hidden") ?> <button type="submit" class="btn btn-danger">Delete</button></form> <?php endif; ?> </td> </tr> <?php endforeach ?> </tbody> </table> <div> <a class="btn btn-success" href="./User/Add.php">Add</a> </div> <?php $HTML->Render() ?> <file_sep>[database] driver = 'mysql' host = 'server1.logicalview.co.uk' port = '' database = 'c540ws311470dev' username = 'c540ws311470sa' password = <PASSWORD>'<file_sep># webapp-development This was done for a level 6 apprenticeship univerity course, for second year module Web App Development <file_sep><?php require_once '../Model/Course.php'; require_once '../Model/Booking.php'; require_once '../core/utils.php'; require_once '../core/html.php'; HtmlHelper::$_Title = 'Admin: Courses'; StartSession(); RequireAuth(); $user = SafeGetValue($_SESSION, 'User'); if($user->AccessLevel->Name != 'Admin') { ErrorResponse(401); } $Now = CurrentDateTime(); $UpcomingCourses = $Courses->Select([], [new DbCondition("StartDate", $Now, "ge"), new DbCondition("Active", true)]); $HistoricalCourses = $Courses->Select([], [new DbCondition("StartDate", $Now, "lt"), new DbCondition("Active", true)]); ?> <h3>Courses</h3> <p>Click a row to see it's bookings</p> <hr /> <div class="row"> <h4>Upcoming Courses</h4> <table class="table table-light table-hover table-striped"> <thead> <tr> <th>Title</th> <th>Start Date</th> <th>Description</th> <th>Duration</th> <th>Capacity</th> <th>Currently Booked</th> <th></th> <th></th> </tr> </thead> <tbody id="CourseTableBody"> <?php foreach($UpcomingCourses as $CurrCourse): ?> <?php $CourseBookings = $Bookings->Select(["Id"], [new DbCondition("CourseId", $CurrCourse->Id)]); $NumBookings = count($CourseBookings); $CurrPercentage = ($NumBookings / $CurrCourse->Capacity) * 100; ?> <tr data-toggle="collapse" data-target="#Details<?php echo $CurrCourse->Id ?>" role="button" aria-expanded="false" aria-controls="#Details<?php echo $CurrCourse->Id ?>" data-parent="#CourseTableBody"> <td><?php echo htmlspecialchars($CurrCourse->Name) ?></td> <td><?php echo (new DateTime($CurrCourse->StartDate))->format("d/m/Y") ?></td> <td><?php echo htmlspecialchars($CurrCourse->Description) ?></td> <td><?php echo $CurrCourse->Duration ?> Days</td> <td><?php echo $CurrCourse->Capacity ?></td> <td> <div class="progress"> <div class="progress-bar bg-success" role="progressbar" style="width: <?php echo $CurrPercentage ?>%" aria-valuenow="<?php echo $CurrPercentage ?>" aria-valuemin="0" aria-valuemax="<?php echo $CurrCourse->Capacity ?>"> <?php echo $NumBookings ?></div> </div> </td> <td><a class="btn btn-info" href="./Course/Edit.php?Id=<?php echo $CurrCourse->Id ?>">Edit</a></td> <td> <form action="./Course/Delete.php" method="POST" onsubmit="return confirm('Are you sure you wish to delete this course?')"> <?php echo $HTML->Input($CurrCourse->Id, ["id" => "Id"], "hidden") ?> <button type="submit" class="btn btn-danger">Delete</button></form> </td> </tr> <tr> <td class="unpadded" colspan="8"> <div id="Details<?php echo $CurrCourse->Id ?>" class="collapse td-collapse async-panel" data-target="./Course/CourseBookings.php" data-id='{"CourseId":<?php echo $CurrCourse->Id ?>}'> </div> </td> </tr> <?php endforeach ?> </tbody> </table> <div> <a class="btn btn-success" href="./Course/Add.php">Add</a> </div> </div> <div class="row"> <h4>Historical Courses</h4> <table class="table table-light"> <thead> <tr> <th>Title</th> <th>Start Date</th> <th>Description</th> <th>Duration</th> <th>Capacity</th> <th>Attendance</th> </tr> </thead> <tbody id="CourseTableBody"> <?php foreach($HistoricalCourses as $CurrCourse): ?> <?php $CourseBookings = $Bookings->Select(["Id"], [new DbCondition("CourseId", $CurrCourse->Id)]); $NumBookings = count($CourseBookings); ?> <tr data-toggle="collapse" data-target="#Details<?php echo $CurrCourse->Id ?>" role="button" aria-expanded="false" aria-controls="#Details<?php echo $CurrCourse->Id ?>" data-parent="#CourseTableBody"> <td><?php echo htmlspecialchars($CurrCourse->Name) ?></td> <td><?php echo (new DateTime($CurrCourse->StartDate))->format("d/m/Y") ?></td> <td><?php echo htmlspecialchars($CurrCourse->Description) ?></td> <td><?php echo $CurrCourse->Duration ?> Days</td> <td><?php echo $CurrCourse->Capacity ?></td> <td><?php echo $NumBookings ?></td> </tr> <?php endforeach ?> </tbody> </table> </div> <?php $HTML->Render() ?> <file_sep><?php require_once '../../Model/User.php'; require_once '../../Model/UserAccessLevel.php'; require_once '../../core/utils.php'; require_once '../../core/html.php'; StartSession(); RequireAuth(); $user = SafeGetValue($_SESSION, 'User'); if($user->AccessLevel->Name != 'Admin') { ErrorResponse(401); } if($_SERVER['REQUEST_METHOD'] === 'POST') { $Email = ValidatePOSTValue('Email'); $PasswordSalt = hash('sha512', GenerateRandomString(128), false); $PasswordHash = hash('sha512', ValidatePOSTValue('Password') . $PasswordSalt, false); $FirstName = ValidatePOSTValue('FirstName'); $LastName = ValidatePOSTValue('LastName'); $AccessLevel = ValidatePOSTValue('AccessLevel'); $JobTitle = ValidatePOSTValue('JobTitle'); $Timestamp = CurrentDateTime(); $UniqueCheck = $Users->Select(['Id'], [new DbCondition('Email', $Email, 'like')]); if(count($UniqueCheck) > 0) { header('Location: ./Add.php?err=NotUnique'); exit(); } $NewUser = new User(); $NewUser->Email = $Email; $NewUser->PassHash = $<PASSWORD>; $NewUser->PassSalt = $PasswordSalt; $NewUser->FirstName = $FirstName; $NewUser->LastName = $LastName;; $NewUser->AccessLevelId = $AccessLevel; $NewUser->JobTitle = $JobTitle; $NewUser->Active = true; $NewUser->Timestamp = $Timestamp; $Users->InsertObj($NewUser); header('Location: ../Users.php'); exit(); } $accessLevels = array(); $Err = ""; if($_SERVER['REQUEST_METHOD'] === 'GET') { $accessLevels = $UserAccessLevels->Select([]); $Err = SafeGetValue($_GET, "err"); } HtmlHelper::$_Title = 'Admin: Add User'; ?> <?php if($Err == "NotUnique"): ?> <script> $(document).ready(function(){ CM.Alert("Email not unique!", "A user already exists with the provided email address!", "danger"); }); </script> <?php endif; ?> <h3>New User</h3> <hr /> <form action="./Add.php" method="POST"> <div class="form-row"> <div class="form-group col-6"> <label>Email</label> <?php $HTML->Input("", ['id' => 'Email', 'class' => 'form-control', 'type' => 'email', 'maxlength' => 255, "required" => ""]); ?> </div> <div class="form-group col-6"> <label>Password</label> <?php $HTML->Input("", ['id' => 'Password', 'class' => 'form-control', 'type' => 'password', "required" => ""]); ?> </div> <div class="form-group col-md-6"> <label>Firstname</label> <?php $HTML->Input("", ['id' => 'FirstName', 'class' => 'form-control', 'maxlength' => 255, "required" => ""]); ?> </div> <div class="form-group col-md-6"> <label>Lastname</label> <?php $HTML->Input("", ['id' => 'LastName', 'class' => 'form-control', 'maxlength' => 255, "required" => ""]); ?> </div> <div class="form-group col-12"> <label>Job Title</label> <?php $HTML->Input("", ['id' => 'JobTitle', 'class' => 'form-control', 'maxlength' => 255, "required" => ""]); ?> </div> <div class="form-group col-12"> <label>Access Level</label> <?php $HTML->DropDownList($accessLevels, ['id' => 'AccessLevel', 'class' => 'form-control', "required" => ""], 'Id', 'Name'); ?> </div> <hr /> </div> <button class="btn btn-success" type="submit">Save</button> <a class="btn btn-warning" href="../Users.php">Cancel</a> </form> <?php $HTML->Render() ?><file_sep><?php require_once './Model/User.php'; require_once './Model/Course.php'; require_once './Model/Booking.php'; require_once './core/utils.php'; StartSession(); RequireAuth(); if(GetRequestMethod() != "POST") { ErrorResponse(404); } $UserId = ValidatePOSTValue("UserId", true); $CourseId = ValidatePOSTValue("CourseId", true); $Now = CurrentDateTime(); $NewBooking = new Booking(); $NewBooking->UserId = $UserId; $NewBooking->CourseId = $CourseId; $NewBooking->Timestamp = $Now; $Bookings->InsertObj($NewBooking); header('Location: /Courses.php'); exit(); ?> <file_sep><?php require_once './core/utils.php'; require_once './core/html.php'; HtmlHelper::$_Title = 'Login'; if(!$_SERVER['REQUEST_METHOD'] === 'GET') { header('HTTP/1.0 405 Method Not Allowed', 405); die(); } $location = SafeGetValue($_GET, "location"); StartSession(); if(SafeGetValue($_SESSION, "auth") == true) { if($location != null) { header("Location: " . urldecode($location)); } else { header("Location: /index.php"); } exit(); } $err = SafeGetValue($_GET, 'err'); if($err !== null) { } HtmlHelper::$_Title = "Login"; ?> <?php if($err === 'e01'): ?> <script> CM.Alert("Username Or Password!", "The provided username or password was incorrect!", ) </script> <?php endif; ?> <div class="login-container"> <div class="row"> <div class="col"></div> <div class="col"> <div class="card login-card text-dark"> <div class="card-body form-row"> <form class="form-signin async no-validate" action="auth.php" method="POST" onsuccess="window.location = data.Location;" onfail="CM.Alert(data.Heading, data.Content, data.Type);"> <input type="hidden" name="location" value="<?php echo $location ?>"> <img class="mb-4" src="/content/Mortarboard.svg" alt="CourseMan" width="144" height="72"> <h1 class="h3 mb-3 font-weight-normal">Please sign in</h1> <div class="form-group col-12"> <label for="inputEmail" class="sr-only">Email address</label> <input type="email" id="Email" name="Email" class="form-control" placeholder="Email address" required autofocus> </div> <div class="form-group col-12"> <label for="inputPassword" class="sr-only">Password</label> <input type="<PASSWORD>" id="Password" name="Password" class="form-control" placeholder="<PASSWORD>" required> </div> <div class="form-group col-12"> <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> </div> <p class="mt-5 mb-3 text-dark"><NAME>© 2019</p> </form> </div> </div> </div> <div class="col"></div> </div> </div> <?php $HTML->Render(true, "_layout_login.php") ?><file_sep><?php require_once './core/utils.php'; require_once './Model/User.php'; require_once './Model/Booking.php'; require_once './Model/Course.php'; StartSession(); RequireAuth(); include_once "./core/html.php"; $CurrUser = $_SESSION["User"]; $UserBookings = $Bookings->Select([],[new DbCondition("UserId", $CurrUser->Id)]); $UpcomingCourses = Where($UserBookings, function($Booking){ return (new DateTime($Booking->Course->StartDate))->modify("+ " . $Booking->Course->Duration . " days")->getTimestamp() > (new DateTime('now'))->getTimestamp();}); $PastCourses = Where($UserBookings, function($Booking){ return (new DateTime('now'))->getTimestamp() > (new DateTime($Booking->Course->StartDate))->modify("+ " . $Booking->Course->Duration . " days")->getTimestamp();}); HtmlHelper::$_Title = "CourseMan"; ?> <div class="row"> <div class="col-sm-6"> <div class="card text-dark"> <div class="card-header"> Upcoming Bookings <a class="btn btn-sm btn-dark float-right" href="/Courses.php">Manage</a> </div> <div class="card-body"> <?php foreach($UpcomingCourses as $UpcomingCourse): ?> <div class="row"> <div class="col-lg-4"> <?php echo htmlspecialchars($UpcomingCourse->Course->Name) ?> </div> <div class="col-lg-4"> <?php if(!$UpcomingCourse->Course->Active): ?> <p class="text text-danger">Cancelled</p> <?php else: ?> <?php echo "(" . (new DateTime($UpcomingCourse->Course->StartDate))->format("d/m/Y") . " - " . (new DateTime($UpcomingCourse->Course->StartDate))->modify("+ " . $UpcomingCourse->Course->Duration . " days")->format("d/m/Y") . ")"; ?> <?php endif; ?> </div> </div> <hr/> <?php endforeach; ?> </div> </div> </div> <div class="col-sm-6"> <div class="card text-dark"> <div class="card-header"> Course History </div> <div class="card-body"> <?php foreach($PastCourses as $PastCourse): ?> <div class="row"> <div class="col-lg-4"> <?php echo htmlspecialchars($PastCourse->Course->Name) ?> </div> <div class="col-lg-4"> <?php echo "(" . (new DateTime($PastCourse->Course->StartDate))->format("d/m/Y") . " - " . (new DateTime($PastCourse->Course->StartDate))->modify("+ " . $PastCourse->Course->Duration . " days")->format("d/m/Y") . ")"; ?> </div> </div> <hr/> <?php endforeach; ?> </div> </div> </div> </div> <?php $HTML->Render() ?><file_sep><?php require_once __DIR__ .'/../core/database.php'; class Course extends DbData { /** @var integer */ public $Id; public $Name; public $Description; public $StartDate; public $Duration; /** @var integer */ public $Capacity; /** @var boolean */ public $Active; } $Courses = new DbHelper("Course"); ?><file_sep><?php require_once __DIR__ .'/../core/database.php'; require_once __DIR__ .'/../Model/User.php'; require_once __DIR__ .'/../Model/Course.php'; class Booking extends DbData { public $Id; /** @var integer * @fkey-alias User * @fkey-table Users */ public $UserId; /** @var integer * @fkey-alias Course * @fkey-table Courses */ public $CourseId; public $Timestamp; } $Bookings = new DbHelper("Booking"); ?><file_sep><?php require_once __DIR__ .'/../core/database.php'; class UserAccessLevel extends DbData { /** @var integer */ public $Id; public $Name; } $UserAccessLevels = new DbHelper('UserAccessLevel'); ?><file_sep><?php require_once __DIR__ . '/../core/html.php'; $viewData = HtmlHelper::$_ViewData; ?> <!DOCTYPE html> <html lang="en"> <head> <Title><?php echo $viewData['Title'] ?></Title> <script type="text/javascript" src="/js/jquery-3.4.1.min.js"></script> <script type="text/javascript" src="/js/jquery.validate.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <link rel="stylesheet" href="/css/bootstrap.min.css" /> <script type="text/javascript" src="/js/bootstrap.min.js"></script> <link rel="stylesheet" type="text/css" href="/css/courseman.css" /> <script type="text/javascript" src="/js/courseman.js"></script> </head> <body class="login-body"> <?php echo $viewData['Body'] ?> <div id="MasterAlerts"></div> </body> </html><file_sep><?php require_once './Model/Course.php'; require_once './Model/Booking.php'; require_once './core/utils.php'; require_once './core/html.php'; HtmlHelper::$_Title = 'Courses'; StartSession(); RequireAuth(); $user = SafeGetValue($_SESSION, 'User'); $Now = CurrentDateTime(); $UpcomingCourses = $Courses->Select([], [new DbCondition("StartDate", $Now, "gt"), new DbCondition("Active", true)]); ?> <h3>Courses</h3> <hr /> <table class="table table-light table-striped"> <thead> <tr> <th>Title</th> <th>Start Date</th> <th>Duration</th> <th>Capacity</th> <th></th> <th></th> </tr> </thead> <tbody id="CourseTableBody"> <?php foreach($UpcomingCourses as $CurrCourse): ?> <?php $CourseBookings = $Bookings->Select(["Id", "UserId"], [new DbCondition("CourseId", $CurrCourse->Id)]); $UserBooking = Find($CourseBookings, function ($Value) use ($user) { return $Value->UserId == $user->Id; }); $UserBooked = ($UserBooking != null); $NumBookings = count($CourseBookings); $IsFull = ($CurrCourse->Capacity - $NumBookings == 0) ?> <tr> <td><?php echo htmlspecialchars($CurrCourse->Name) ?></td> <td><?php echo (new DateTime($CurrCourse->StartDate))->format("d/m/yy") ?></td> <td><?php echo $CurrCourse->Duration ?> Days</td> <td> <?php echo $CurrCourse->Capacity ?> </td> <td> <?php if($UserBooked): ?> <p class="text text-success">Booked!</p> <?php elseif($IsFull): ?> <p class="text text-danger">Course Full!</p> <?php else: ?> <form action="Enroll.php" method="POST"> <input type="hidden" name="UserId" value="<?php echo $user->Id ?>"> <input type="hidden" name="CourseId" value="<?php echo $CurrCourse->Id ?>"> <button class="btn btn-success" type="submit">Enroll</button> </form> <?php endif; ?> </td> <td> <?php if($UserBooked): ?> <form action="/Admin/Booking/Delete.php" method="POST" onsubmit="return confirm('Are you sure you wish to cancel this booking?')"> <input type="hidden" name="Id" value="<?php echo $UserBooking->Id ?>"> <input type="hidden" name="Location" value="<?php echo urlencode($_SERVER['REQUEST_URI']) ?>"> <button class="btn btn-danger" type="submit">Cancel</button> </form> <?php endif; ?> </td> </tr> <tr> <td collspan="6"> <?php echo htmlspecialchars($CurrCourse->Description) ?> </td> </tr> <?php endforeach ?> </tbody> </table> <?php $HTML->Render() ?> <file_sep><?php ini_set('display_errors', 1); ini_set('display_startup_errors', 1); require_once '../../core/utils.php'; require_once '../../Model/User.php'; if(!(GetRequestMethod() == 'POST')) { ErrorResponse(404); exit(); } StartSession(); RequireAuth(); $User = SafeGetValue($_SESSION, "User"); if(!$User->AccessLevel->Name == "Admin") { ErrorResponse(401); die(); } $UserId = ValidatePOSTValue("Id", true); $DeleteUser = $Users->Find($UserId); $DeleteUser->Active = false; $Users->UpdateObj($DeleteUser); header("Location: ../Users.php"); exit(); ?><file_sep><?php require_once __DIR__ . '/core/html.php'; HtmlHelper::$_Title = "404"; ?> <div class="row"> <h1 class="text-light">Page Not Found</h1> </div> <?php $GLOBALS["HTML"]->Render() ?><file_sep><?php require_once '../../core/utils.php'; require_once '../../Model/User.php'; require_once '../../Model/UserAccessLevel.php'; require_once '../../core/html.php'; StartSession(); RequireAuth(); $user = SafeGetValue($_SESSION, 'User'); if ($user->AccessLevel->Name != 'Admin') { ErrorResponse(401); exit(); } $gUser = null; $accessLevels = null; if ($_SERVER['REQUEST_METHOD'] === 'GET') { $uid = SafeGetValue($_GET, 'Id'); if ($uid === null) { ErrorResponse(404); exit(); } $gUser = $Users->Find($uid); if ($gUser === null) { ErrorResponse(404); exit(); } $accessLevels = $UserAccessLevels->Select([]); } else if ($_SERVER['REQUEST_METHOD'] === 'POST') { $Id = ValidatePOSTValue('Id'); $Email = ValidatePOSTValue('Email'); $FirstName = ValidatePOSTValue('FirstName'); $LastName = ValidatePOSTValue('LastName'); $JobTitle = ValidatePOSTValue('JobTitle'); $AccessLevel = ValidatePOSTValue('AccessLevel'); $updateUser = $Users->Find($Id); if($updateUser != null) { $updateUser->Email = $Email; $updateUser->FirstName = $FirstName; $updateUser->LastName = $LastName;; $updateUser->AccessLevelId = $AccessLevel; $updateUser->JobTitle = $JobTitle; $Users->UpdateObj($updateUser); } header('Location: ../Users.php'); exit(); } HtmlHelper::$_Title = 'Admin: Edit User'; ?> <h3>Edit User: <?php echo htmlspecialchars($gUser->LastName) ?>, <?php echo htmlspecialchars($gUser->FirstName) ?></h3> <hr /> <form action="./Edit.php" method="POST"> <div class="form-row"> <input name="Id" type="hidden" value="<?php echo $gUser->Id ?>" /> <div class="form-group col-12"> <label>Email</label> <?php $HTML->Input($gUser->Email, ['id' => 'Email', 'class' => 'form-control', 'type' => 'email', 'maxlength' => 255, "required" => ""]); ?> </div> <div class="form-group col-md-6"> <label>Firstname</label> <?php $HTML->Input($gUser->FirstName, ['id' => 'FirstName', 'class' => 'form-control', 'maxlength' => 255, "required" => ""]); ?> </div> <div class="form-group col-md-6"> <label>Lastname</label> <?php $HTML->Input($gUser->LastName, ['id' => 'LastName', 'class' => 'form-control', 'maxlength' => 255, "required" => ""]); ?> </div> <div class="form-group col-12"> <label>Job Title</label> <?php $HTML->Input($gUser->JobTitle, ['id' => 'JobTitle', 'class' => 'form-control', 'maxlength' => 255, "required" => ""]); ?> </div> <div class="form-group col-12"> <label>Access Level</label> <?php $HTML->DropDownList($accessLevels, ['id' => 'AccessLevel', 'class' => 'form-control', "required" => ""], 'Id', 'Name', $gUser->AccessLevelId); ?> </div> <hr /> </div> <button class="btn btn-success" type="submit">Update</button> <a class="btn btn-warning" href="../Users.php">Cancel</a> </form> <?php $HTML->Render() ?><file_sep>//CourseMan app object that contains CourseMan functions CM = {}; CM.Alert = function(Heading, Content, Type) { if ($('#MasterAlerts').length > 0) { var alert = $('<div class="alert alert-' + Type + ' alert-dismissable" role="alert">') .append('<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>') .append($('<strong>').text(Heading)) .append($('<p class="text-' + Type + ' small">').text(Content)); $('#MasterAlerts').append(alert); } } CM.ReloadAsyncPanel = function(Id, Target, Data) { if($('#' + Id).length > 0) { $.get(Target, Data) .done(function(data) { $('#' + Id).empty(); $('#' + Id).append(data); ApplyHandlers('#' + Id); }); } } //All the default handlers that should be applied to all content, static or dynamic //Scope defines th scope to which this should be applied function ApplyHandlers(scope) { $(scope).find('collapse-trigger').click(function(){ var target = $(this).data('target'); $(target).collapse('toggle'); }); $(scope).find('div.async-panel').each(function(index){ var curr = $(this); CM.ReloadAsyncPanel(curr.attr('id'), curr.data('target'), curr.data('id')); }); $(scope).find('form').not('.no-validate').validate(); $(scope).find('form.async').data('prevent', true); $(scope).find('form.async').submit(function(e){ var DoPrevent = $('form.async').data('prevent'); var CurrForm = $(this) var Confirm = CurrForm.data('confirm'); if(Confirm != undefined) { var isConfirmed = confirm(Confirm); if(!isConfirmed) { e.preventDefault(); return; } } var Method = CurrForm.attr('method'); var Endpoint = CurrForm.attr('action'); var OnSuccessStr = CurrForm.attr('onsuccess'); var OnFailStr = CurrForm.attr('onfail'); var OnSuccess = new Function(['data', 'form'], OnSuccessStr); var OnFail = new Function(['data', 'form'], OnFailStr); var FormData = CurrForm.serialize(); var AjaxOptions = { url: Endpoint, data: FormData, method: Method }; $.ajax(AjaxOptions) .done(function(data, textStatus, jqXHR){ var jsData = $.parseJSON(data); if(jsData.success == true) { if(typeof OnSuccess === 'function') { OnSuccess(jsData.data, CurrForm); } } else { if(typeof OnFail === 'function') { OnFail(jsData.data); } } }) .fail(function( jqXHR, textStatus, errorThrown) { //Fall back to synchronous submission if submission fails CurrForm.data('prevent', false); CurrForm.submit(); }); if(DoPrevent) e.preventDefault(); }); $(scope).find('tr[data-toggle="collapse"] > td > button').click(function(e){ e.stopPropagation(); }); $(scope).find('tr[data-toggle="collapse"] > td > a').click(function(e){ e.stopPropagation(); }); }; function ReloadContainingPanel(jqThis) { var curr = jqThis.parents('div.async-panel'); CM.ReloadAsyncPanel(curr.attr('id'), curr.data('target'), curr.data('id')); } $(document).ready(function(){ ApplyHandlers('body'); });<file_sep><?php require_once __DIR__ .'/../core/database.php'; require_once __DIR__ .'/../Model/UserAccessLevel.php'; class User extends DbData { /** @var integer */ public $Id; public $Email; public $PassHash; public $PassSalt; public $FirstName; public $LastName; public $JobTitle; /** @var integer * @fkey-alias AccessLevel * @fkey-table UserAccessLevels */ public $AccessLevelId; public $Timestamp; /** @var boolean */ public $Active; } $Users = new DbHelper("User"); ?><file_sep><?php ini_set('display_errors', 1); require_once '../../core/utils.php'; require_once '../../Model/User.php'; require_once '../../Model/Course.php'; require_once '../../Model/Booking.php'; require_once '../../core/html.php'; StartSession(); RequireAuth(); $user = SafeGetValue($_SESSION, 'User'); if ($user->AccessLevel->Name != 'Admin') { ErrorResponse(401); exit(); } $gCourse = null; $NumBookings = 0; if ($_SERVER['REQUEST_METHOD'] === 'GET') { $Id = SafeGetValue($_GET, 'Id'); if ($Id === null) { ErrorResponse(404); exit(); } $gCourse = $Courses->Find($Id); if ($gCourse === null) { ErrorResponse(404); exit(); } $CourseBookings = $Bookings->Select(["Id"], [new DbCondition("CourseId", $gCourse->Id)]); $NumBookings = count($CourseBookings); } else if ($_SERVER['REQUEST_METHOD'] === 'POST') { $Id = ValidatePOSTValue('Id', true); $Title = ValidatePOSTValue('Title'); $StartDate = ValidatePOSTValue('StartDate'); $Description = ValidatePOSTValue('Description'); $Duration = ValidatePOSTValue('Duration'); $Capacity = ValidatePOSTValue('Capacity'); $updateCourse = $Courses->Find($Id); if($updateCourse != null) { $updateCourse->Name = $Title; $updateCourse->StartDate = $StartDate; $updateCourse->Description = $Description; $updateCourse->Duration = $Duration; $updateCourse->Capacity = $Capacity; $Courses->UpdateObj($updateCourse); } header('Location: ../Courses.php'); exit(); } HtmlHelper::$_Title = 'Admin: Edit Course'; ?> <h3>Edit Course</h3> <hr /> <form action="./Edit.php" method="POST"> <div class="form-row"> <input type="hidden" name="Id" value="<?php echo $gCourse->Id ?>" > <div class="form-group col-6"> <label>Title</label> <?php $HTML->Input($gCourse->Name, ['id' => 'Title', 'placeholder' => 'Course Title', 'class' => 'form-control', 'maxlength' => 255, "required" => ""]); ?> </div> <div class="form-group col-6"> <label>Start Date</label> <?php $HTML->Input($gCourse->StartDate, ['id' => 'StartDate', 'placeholder' => 'Course Start Date', 'class' => 'form-control', "required" => "", "min" => (new DateTime('now', new DateTimeZone('Europe/London')))->format('Y-m-d')], 'date'); ?> </div> <div class="form-group col-12"> <label>Description</label> <?php $HTML->Input($gCourse->Description, ['id' => 'Description', 'placeholder' => 'Course Description', 'class' => 'form-control', 'maxlength' => 255, "required" => ""]); ?> </div> <div class="form-group col-md-6"> <label>Duration</label> <?php $HTML->Input($gCourse->Duration, ['id' => 'Duration', 'placeholder' => 'Course Duration (Days)', 'class' => 'form-control', "required" => "", "min" => "1"], 'number'); ?> </div> <div class="form-group col-md-6"> <label>Capacity</label> <?php $HTML->Input($gCourse->Capacity, ['id' => 'Capacity', 'placeholder' => 'Course Capacity', 'class' => 'form-control', 'min' => $NumBookings, "required" => "", "min" => "1"], 'number'); ?> </div> <hr /> </div> <button class="btn btn-success" type="submit">Update</button> <a class="btn btn-warning" href="../Courses.php">Cancel</a> </form> <?php $HTML->Render() ?><file_sep><?php require_once '../../core/utils.php'; require_once '../../Model/User.php'; require_once '../../Model/Course.php'; if(!(GetRequestMethod() == 'POST')) { ErrorResponse(404); exit(); } StartSession(); RequireAuth(); $User = SafeGetValue($_SESSION, "User"); if(!$User->AccessLevel->Name == "Admin") { ErrorResponse(401); die(); } $CourseId = ValidatePOSTValue("Id", true); $DeleteCourse = $Courses->Find($CourseId); $DeleteCourse->Active = false; $Courses->UpdateObj($DeleteCourse); header("Location: ../Courses.php"); exit(); ?><file_sep><?php require_once "../../core/utils.php"; require_once "../../Model/User.php"; require_once "../../Model/Course.php"; require_once "../../Model/Booking.php"; StartSession(); RequireAuth(); if(!IsAjax() || GetRequestMethod() != "GET") { ErrorResponse(404); } $user = $_SESSION["User"]; if($user->AccessLevel->Name != 'Admin') { ErrorResponse(401); } $CourseId = SafeGetValue($_GET, "CourseId"); if($CourseId == null) { ErrorResponse(404); } $CourseBookings = $Bookings->Select([], [new DbCondition("CourseId", $CourseId)]); ?> <?php if(count($CourseBookings) > 0): ?> <?php foreach($CourseBookings as $Booking): ?> <div class="row"> <div class="col-3"> <?php echo htmlspecialchars($Booking->User->FirstName) . " " . htmlspecialchars($Booking->User->LastName) ?> </div> <div class="col-3"> Date Booked: <?php echo (new DateTime($Booking->Timestamp, new DateTimeZone('UTC')))->format('H:i d/m/Y') ?> </div> <div class="col-3"> <form class="async" action="./Booking/Delete.php" method="POST" data-confirm="Are you sure you wish to delete this booking?" onsuccess="CM.Alert(data.Heading, data.Content, data.Type);ReloadContainingPanel(form);" onfail="CM.Alert(data.Heading, data.Content, data.Type);"> <input type="hidden" name="Id" value="<?php echo $Booking->Id ?>"> <button class="btn btn-danger float-right" type="submit">Delete</button> </form> </div> </div> <hr /> <?php endforeach; ?> <?php else: ?> <p>No Bookings Found</p> <?php endif; ?><file_sep><?php //polyfill for fastcgi instances that lack getallheaders() if (!function_exists('getallheaders')) { function getallheaders() { $headers = []; foreach ($_SERVER as $name => $value) { if (substr($name, 0, 5) == 'HTTP_') { $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value; } } return $headers; } } function GenerateRandomString($length = 10) : string { $Chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $NumChars = strlen($Chars); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $Chars[rand(0, $NumChars - 1)]; } return $randomString; } //Gets the current date and time in UTC function CurrentDateTime() : string { $dt = new DateTime('now', new DateTimezone('UTC')); $currTime = $dt->format('Y-m-d H:i:s.u'); return $currTime; } //Safeley gets a value from an array if it exists, or null if it doesn't function SafeGetValue(array $dataArray, string $valName) { if(array_key_exists($valName, $dataArray)) { return $dataArray[$valName]; } else { return null; } } //Safely gets a value from $_POST, can be made to respond with err 400 function ValidatePOSTValue(string $name, bool $required = false) { if(empty($name) && $required) { ErrorResponse(400); die($response->json()); } if(empty($_POST[$name])) { if($required) { ErrorResponse(400); die($response->json()); } else { return null; } } return $_POST[$name]; } //Gets an assoc array of annotations on a class property, parsed from documentation comments function GetPropertyAnnotations(string $ClassName, string $Property) : array { $propReflection = new ReflectionProperty($ClassName, $Property); $docComment = $propReflection->getDocComment(); $Annotations = array(); if($docComment != false) { $docComment = str_replace("*", "", $docComment); $docComment = str_replace("/", "", $docComment); $docDataAnnots = explode("@", $docComment); foreach($docDataAnnots as $value) { $value = trim($value); $keyVal = explode(" ", $value); if(count($keyVal) == 2) { $Annotations[$keyVal[0]] = $keyVal[1]; } } } return $Annotations; } //Returns a collection of items from the passed in collection that meet the requirements of the predicate function Where(array $Collection, $Predicate) { $output = array(); foreach($Collection as $Value) { if($Predicate($Value)) { $output[] = $Value; } } return $output; } //Returns the first item from the passed in collection that meet the requirements of the predicate function Find(array $Collection, $Predicate) { foreach($Collection as $Value) { if($Predicate($Value)) return $Value; } return null; } //Safely verifies that the session is available function StartSession() : void { if(!isset($_SESSION)) { ini_set('session.cookie_httponly', 1); ini_set('session.use_only_cookies', 1); //Allows insecure cookie for localhost non https connections if($_SERVER['HTTP_HOST'] != "localhost") ini_set('session.cookie_secure', 1); session_start(); } } //Checks if the user is authenticated, and if not, redirects to the login page function RequireAuth() { if(isset($_SESSION)) { if(SafeGetValue($_SESSION, 'auth') == null || $_SESSION['auth'] != true) { header('Location: /login.php?location=' . urlencode($_SERVER['REQUEST_URI'])); exit(); } } else { header('Location: /login.php?location=' . urlencode($_SERVER['REQUEST_URI'])); exit(); } } //Gets the method of the current request function GetRequestMethod() { if(!array_key_exists("REQUEST_METHOD", $_SERVER)) { return ""; } return $_SERVER["REQUEST_METHOD"]; } //Sets the response code, and if available, outputs a custom Error page function ErrorResponse(int $ResponseCode) { http_response_code($ResponseCode); $responsePage = __DIR__ . '/../' . $ResponseCode . '.php'; if(file_exists($responsePage) && !IsAjax()); { include_once $responsePage; } die(); } //Returns true if the current request was made asynchronously function IsAjax() { return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'); } class ResponseData extends ResponseMessage { public $data; public function __construct(bool $success, string $message, array $data) { $this->success = $success; $this->message = $message; $this->data = $data; } public function __toString() { return $this->json(); } public function json() { return json_encode(array( 'success' => $this->success, 'message' =>$this->message, 'data' => $this->data )); } } class ResponseMessage { public $success; public $message; public function __construct(bool $success, string $message) { $this->success = $success; $this->message = $message; } public function json() { return json_encode(array( 'success' => $this->success, 'message' => $this->message )); } } ?><file_sep><?php include_once 'utils.php'; class Db extends PDO { //Basic cache for storing navigation values within a single request //Very naiive implemetation, will probably opt for proper ctx management in later version public static $Cache = array(); public function __construct($file = __DIR__ . "/../settings.ini", string $section = "database") { if(!$settings = parse_ini_file($file, TRUE)) throw new exception("Cannot open settings file " . $file); $connString = $settings[$section]['driver'] . ':host=' . $settings[$section]['host'] . ((!empty($settings[$section]['port'])) ? (';port=' . $settings[$section]['port']):''). ';dbname=' . $settings[$section]['database']; parent::__construct($connString, $settings[$section]['username'], $settings[$section]['password']); } } //Class to derive DB Data models from class DbData { //Uses data in assoc array from DB to construct the properties, setting correct types where necessary public function __construct(array $dbObject = null) { if($dbObject != null) { $class = get_class($this); $props = get_object_vars($this); foreach($props as $key => $value) { $annotations = GetPropertyAnnotations($class, $key); $type = SafeGetValue($annotations, "var"); $this->$key = SafeGetValue($dbObject, $key); if($type != null) { if(!settype($this->$key, $type)) throw new Exception("Invalid conversion from string to " . $type); } } } } //Using __get magic function to create virtual navigation properties to other DbData classes public function __get($Name) { $ClassName = get_class($this); $Props = get_object_vars($this); foreach($Props as $Prop => $Val) { $annotations = GetPropertyAnnotations($ClassName, $Prop); $ForeignAlias = SafeGetValue($annotations, "fkey-alias"); if($ForeignAlias == $Name) { $ForeignTable = SafeGetValue($annotations, "fkey-table"); if($ForeignTable != null) { $ForeignType = substr($ForeignTable, 0 , -1); $CacheName = $ForeignTable . "_" . $Val; //Checks the cache to see if this object already exists if(!array_key_exists($CacheName, Db::$Cache)) { //If not, makes a database request to get it Db::$Cache[$CacheName] = (new DbHelper($ForeignType))->Find($Val); } //Returns requested object from the DB Cache return Db::$Cache[$CacheName]; } } } throw new Exception("Invalid navigation property: " . $Name . "!"); } //Coerces any properties with a var type set in annotations to specified type public function CoerceTypes() { $class = get_class($this); $props = get_object_vars($this); foreach($props as $key => $value) { $annotations = GetPropertyAnnotations($class, $key); $type = SafeGetValue($annotations, "var"); if($type != null) { if(!settype($this->$key, $type)) throw new Exception("Invalid conversion from string to " . $type); } } } //Gets a partially full copy of the object public function GetPartial(array $propNames) { $props = get_object_vars($this); $output = array(); foreach($propNames as $index => $value) { $propVal = SafeGetValue($props, $value); if($propVal != null) { $output[$value] = $propVal; } } return $output; } public static function FromJson(string $jsonString, string $typeName) { if(!class_exists($typename)) return null; $outObj = new $typeName(); $jsobj = json_decode($jsonString, true); $props = get_object_vars($outObj); foreach($props as $key => $value) { $outObj->$key = SafeGetValue($jsobj, $key); } return $outObj; } public function AsJson() { return json_encode($this); } } class DbCondition { public $Column; private $Operation; public $Value; public function __construct(string $Column, $Value, string $Operation = "eq") { $this->Column = $Column; $this->Value = $Value; $this->Operation = $Operation; } public function GetOperation() : string { $opText = ""; if($this->Operation == "like") { $opText = " LIKE "; } else if($this->Operation == "gt") { $opText = " > "; } else if($this->Operation == "lt") { $opText = " < "; } else if($this->Operation == "ge") { $opText = " >= "; } else if($this->Operation == "le") { $opText = " <= "; } else { $opText = " = "; } return $opText; } } //Helper class for easily constructing basic SQL requests and retuning serialized results class DbHelper { private $TypeName; private $TableName; public function __construct(string $TypeName, string $TableName = '') { if(!class_exists($TypeName)) throw new Exception("Invalid type name proveded"); if(!in_array("DbData", class_parents($TypeName))) throw new Exception($TypeName . " is not a valid DbData object"); $this->TypeName = $TypeName; if($TableName == '') { $this->TableName = $TypeName . 's'; } else { $this->TableName = $TableName; } } //Inserts a new object of the type that this DbHelper is configured for public function InsertObj($object) { //Make sure that the if(get_class($object) != $this->TypeName) throw new Exception("Invalid object type for this helper!"); $object->CoerceTypes(); $objVals = get_object_vars($object); $columnVals = array(); foreach($objVals as $Var => $Val) { if($Val != null && $Var != "Id") { $columnVals[$Var] = $Val; } } $this->Insert($columnVals); } //Inserts new row into the table with specified values public function Insert(array $ColumnVals) { $insertString = "INSERT INTO " . $this->TableName . " (" . $this->BuildInsertColsString($ColumnVals) . ") VALUES (" . $this->BuildInsertValuesString($ColumnVals) . ");"; $db = new Db(); $stmt = $db->prepare($insertString); $count = 0; foreach($ColumnVals as $Column => $Val) { $paramStr = ":v" . $count; if(!$stmt->bindValue($paramStr, $Val, $this->GetPdoParam($Val))) { var_dump($stmt); throw new Exception("Failed to bind parameter " . $paramStr . " Value: " . $Val); } $count++; } if(!$stmt->execute()) { throw new Exception("An error occured updating the database. Error info: " . $stmt->errorInfo()[2]); } } //Selectts data from the database public function Select(array $Columns, array $Conditions = [], string $OrderColumn = "", string $OrderDir = "ASC") { $colsString = ""; $conditionString = ""; $selectString = "SELECT "; $colsString = $this->BuildSelectString($Columns); $selectString .= $colsString . ' FROM ' . $this->TableName; if($Conditions != []) { $selectString .= $this->BuildConditionString($Conditions); } if($OrderColumn != "") { $selectString .= " ORDER BY " . $OrderColumn . " " . $OrderDir; } $selectString .= ";"; $db = new Db(); $stmt = $db->prepare($selectString); if($Conditions != []) { $count = 0; foreach($Conditions as $Condition) { if(get_class($Condition) == "DbCondition") { $paramStr = ":c" . $count; $stmt->bindValue($paramStr, $Condition->Value, $this->GetPdoParam($Condition->Value)); $count++; } } } if(!$stmt->execute()) { throw new Exception("An error occured retrieving data from the database. Error info: " . $stmt->errorInfo()[2]); } $data = $stmt->fetchAll(); $numRows = count($data); $outData = array(); for($index = 0; $index < $numRows; $index++) { $outData[$index] = new $this->TypeName($data[$index]); } return $outData; } //Finds the record with the requested Id public function Find(string $Id, array $Columns = []) { $colsString = $this->BuildSelectString($Columns); $selectString = "SELECT " . $colsString . " FROM " . $this->TableName . " WHERE Id = :id;"; $db = new Db(); $stmt = $db->prepare($selectString); $stmt->bindValue(":id", $Id, $this->GetPdoParam($Id)); if(!$stmt->execute()) { throw new Exception("An error occured retrieving data from the database. Error info: " . $stmt->errorInfo()[2]); } $data = $stmt->fetchAll(); $numRows = count($data); $outVal = null; if($numRows > 1) { throw new Exception("A primary key search yeilded multiple results. This should not be possible."); } if($numRows == 1) { $outVal = new $this->TypeName($data[0]); } return $outVal; } //Updates an object of the type that this DbHelper is configured for public function UpdateObj($object) { if(get_class($object) != $this->TypeName) throw new Exception("Invalid object type for this helper!"); $object->CoerceTypes(); $objVals = get_object_vars($object); $columnVals = array(); foreach($objVals as $Var => $Val) { $columnVals[$Var] = $Val; } $this->Update($columnVals, [new DbCondition("Id", $object->Id)]); } //Updates an object in teh database public function Update(array $ColumnVals, array $Conditions = []) { $updateString = "UPDATE " . $this->TableName . " SET " . $this->BuildPreparedValuesString($ColumnVals) . $this->BuildConditionString($Conditions) . ";"; $db = new Db(); $stmt = $db->prepare($updateString); $count = 0; foreach($ColumnVals as $Column => $Val) { $paramStr = ":v" . $count; if(!$stmt->bindValue($paramStr, $Val, $this->GetPdoParam($Val))) { throw new Exception("Failed to bind parameter " . $paramStr . " Value: " . $Val); } $count++; } if($Conditions != []) { $count = 0; foreach($Conditions as $Condition) { if(get_class($Condition) == "DbCondition") { $paramStr = ":c" . $count; if(!$stmt->bindValue($paramStr, $Condition->Value, $this->GetPdoParam($Condition->Value))) { throw new Exception("Failed to bind parameter " . $paramStr . " Value: " . $Condition->Value); } $count++; } } } if(!$stmt->execute()) { throw new Exception("An error occured updating the database. Error info: " . $stmt->errorInfo()[2]); } } public function Delete($Id) { $deleteString = "DELETE FROM " . $this->TableName . " WHERE Id = :v0"; $db = new Db(); $stmt = $db->prepare($deleteString); $stmt->bindValue(":v0", $Id, $this->GetPdoParam($Id)); if(!$stmt->execute()) { throw new Exception("An error occured updating the database. Error info: " . $stmt->errorInfo()[2]); } } private function BuildSelectString(array $Columns) : string { $colsString = ""; if($Columns != []) { $numColumns = count($Columns); for($index = 0; $index < $numColumns; $index++) { if($index != 0) { $colsString .= ", "; } $colsString .= $Columns[$index]; } } else { $colsString = '*'; } return $colsString; } private function BuildInsertColsString(array $Columns) : string { $colsString = ""; if($Columns != []) { $count = 0; foreach($Columns as $Key => $Val) { if($count != 0) { $colsString .= ", "; } $colsString .= $Key; $count++; } } else { $colsString = '*'; } return $colsString; } private function BuildPreparedValuesString(array $Values) : string { $valuesString = ""; if($Values != []) { $count = 0; foreach($Values as $Column => $Value) { if($count > 0) { $valuesString .= ", "; } $valuesString .= $Column . " = :v" . $count; $count++; } } return $valuesString; } private function BuildInsertValuesString(array $Values) : string { $valuesString = ""; if($Values != []) { $count = 0; foreach($Values as $Column => $Value) { if($Value != null) { if($count > 0) { $valuesString .= ", "; } $valuesString .= ":v" . $count; $count++; } } } return $valuesString; } private function BuildConditionString(array $Conditions) : string { $conditionString = ""; if($Conditions != []) { $conditionString .= ' WHERE '; $count = 0; foreach($Conditions as $Condition) { if(get_class($Condition) == "DbCondition") { if($count > 0) { $conditionString .= " AND "; } $isInt = gettype($Condition->Value) == "integer"; $conditionString .= $Condition->Column . $Condition->GetOperation() . ":c" . $count; $count++; } } } return $conditionString; } private function GetPdoParam($value) { $typeString = gettype($value); $ParamType = PDO::PARAM_STR; if($typeString == "integer") { $ParamType = PDO::PARAM_INT; } else if($typeString == "boolean") { $ParamType = PDO::PARAM_BOOL; } return $ParamType; } } ?><file_sep><?php require_once './core/utils.php'; StartSession(); if (SafeGetValue($_SESSION, 'auth') == null || $_SESSION['auth'] != true) { header('Location: /login.php'); exit(); } if($_SERVER['REQUEST_METHOD'] === 'GET') { session_destroy(); header('Location: /login.php'); exit(); } ?><file_sep><?php require_once '../../core/utils.php'; require_once '../../Model/User.php'; require_once '../../Model/Booking.php'; if(!(GetRequestMethod() == 'POST')) { ErrorResponse(404); exit(); } StartSession(); RequireAuth(); $BookingId = ValidatePOSTValue("Id", true); $Location = ValidatePOSTValue("Location"); $User = SafeGetValue($_SESSION, "User"); $Booking = $Bookings->Find($BookingId); if($User->AccessLevel->Name != "Admin" && $Booking->User->Id != $User->Id) { if(IsAjax()) { echo new ResponseData(false, "", ["Heading" => "Booking Not Deleted!", "Content" => "Something went wrong, so the booking was not deleted!", "Type" => "danger"]); exit(); } else { ErrorResponse(401); die(); } } $Bookings->Delete($Booking->Id); if(IsAjax()) { echo new ResponseData(true, "", ["Heading" => "Booking Deleted!", "Content" => "Booking deleted successfully", "Type" => "success"]); exit(); } else { if($Location != null) { header("Location: " . urldecode($Location)); } else { header("Location: /index.php"); } } exit(); ?><file_sep><?php ini_set('display_errors', 1); ini_set('display_startup_errors', 1); require_once __DIR__ . "/../core/utils.php"; require_once __DIR__ . "/../Model/User.php"; StartSession(); $loggedIn = false; $User = null; $isAdmin = false; $auth = SafeGetValue($_SESSION, 'auth'); if ($auth != null && $auth == true) { $loggedIn = true; $User = SafeGetValue($_SESSION, 'User'); $isAdmin = $User->AccessLevel->Name == "Admin"; } ?> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="/"><img src="/content/Mortarboard.svg" alt="CourseMan" width="72" height="36"></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="/">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="/Courses.php">Courses</a> </li> <?php if($isAdmin): ?> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Admin </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="/Admin/Users.php">Users</a> <a class="dropdown-item" href="/Admin/Courses.php">Courses</a> </div> </li> <?php endif; ?> </ul> <?php if($loggedIn): ?> <a class="text text-light" href="/logout.php">Logout</a> <?php endif; ?> </div> </nav><file_sep><?php require_once './core/utils.php'; require_once './core/database.php'; require_once './Model/User.php'; if(!$_SERVER['REQUEST_METHOD'] === 'POST') { ErrorResponse(404); die(); } $email = $_POST['Email']; $password = $_POST['<PASSWORD>']; $location = SafeGetValue($_POST, 'location'); $FoundUsers = $Users->Select([], [new DbCondition("Email", $email)]); if(count($FoundUsers) !== 1) { //Allows the response to either be JSON or a redirect if(IsAjax()) { $Response = new ResponseData(false, '', ['Heading' => 'Username or Password!', 'Content' => 'The username or password was incorrect!', 'Type' => 'danger']); echo $Response->json(); exit(); } else { header("Location: /login.php?err=e01" . ($location != null ? "&location=" . $location : "")); exit(); } } $User = $FoundUsers[0]; $inputPassHash = hash('<PASSWORD>', $password . $User->PassSalt, FALSE); if($User->PassHash != $inputPassHash) { //Allows the response to either be JSON or a redirect if(IsAjax()) { $Response = new ResponseData(false, '', ['Heading' => 'Username or Password!', 'Content' => 'The username or password was incorrect!', 'Type' => 'danger']); echo $Response->json(); exit(); } else { header("Location: /login.php?err=e01" . ($location != null ? "&location=" . $location : "")); exit(); } } StartSession(); $_SESSION['auth'] = true; $_SESSION['User'] = $User; if($location != null) { if(IsAjax()) { $Response = new ResponseData(true, '', ['Location' => urldecode($location)]); echo $Response->json(); } else { header("Location: " . urldecode($location)); } exit(); } if(IsAjax()) { $Response = new ResponseData(true, '', ['Location' => '/index.php']); echo $Response->json(); } else { header("Location: /index.php"); } exit(); ?><file_sep><?php ini_set('display_errors', 1); ini_set('display_startup_errors', 1); require_once __DIR__ . '/core/html.php'; HtmlHelper::$_Title = "403"; ?> <div class="row"> <h1 class="text-light">Forbidden</h1> </div> <?php $GLOBALS["HTML"]->Render() ?>
d7536d79a5d8ce10ea43fd07e2db029a88ec679b
[ "Markdown", "JavaScript", "PHP", "INI" ]
29
PHP
hwoodiwiss/webapp-development
7ceee1ea5bcab5eb8ccbfec50b8a5e7c9e8af0df
039780686fc1d218f0f2b63ce9e7080526eb66be
refs/heads/master
<repo_name>creekpld/sort-native<file_sep>/build.gradle.kts plugins { kotlin("multiplatform") version "1.3.61" } repositories { mavenCentral() } kotlin { macosX64("sort-native") { sourceSets["sort-nativeMain"].kotlin.srcDir("src") sourceSets["sort-nativeTest"].kotlin.srcDir("test") binaries { executable(buildTypes = setOf(DEBUG)) { entryPoint = "main" } } val main by compilations.getting val interop by main.cinterops.creating { defFile(project.file("ncurses.def")) packageName("ncurses") includeDirs( "/usr/local/Cellar/ncurses/6.2/include/", "/usr/local/Cellar/ncurses/6.2/include/ncursesw" ) } } }<file_sep>/settings.gradle rootProject.name = 'sort-native' <file_sep>/README.md # This is not the Repo you are looking for! :alien: New development is taking place in [gitlab.com/pdylong/sort-native](https://gitlab.com/pdylong/sort-native) :ok_hand:. # bubblesort visualization in Kotlin/Native and ncurses ## :construction: a work in progress <file_sep>/src/main.kt @file:Suppress("EXPERIMENTAL_UNSIGNED_LITERALS") import ncurses.* import platform.posix.* import kotlin.random.Random /** ▀ ▁ ▂ ▃ ▄ ▅ ▆ ▇ █ ▉ ▊ ▋ ▌ ▍ ▎ ▏ ▐ ░ ▒ ▓ ▔ ▕ ▖ ▗ ▘ ▙ ▚ ▛ ▜ ▝ ▞ ▟ {4,2,1,1,1,2,6,4,3,2} ▐ ▐ ▐ ▐▐ ▐ ▐▐▐ ▐▐ ▐▐▐▐▐ ▐▐▐▐▐▐▐▐▐▐ {4,2,1,1,1,2,6,4,3,2} */ fun main(args: Array<String>) { val items = 30 // items/values in the array to sort, aka. the columns in the graph val delay = 100000U // delay per sort step in microsecond (μs) val rng = Random(123) // random number generator for shuffling the array values // use random values //val values = Array(items) { rng.nextInt(1, items) } // use shuffled values var values = Array(items) { it + 1 } .toList() .shuffled(rng) .toTypedArray() // Set locale for ncurses wide character (UTF-8) support. // setlocale, Passing "" results in getting the configured/system locale, // which should be UTF-8 based on any modern system. // Note: The call to setlocale must precede initscr(). setlocale(LC_ALL, "") initscr() val window = newwin(34, 96, 0, 0) box(window, 0, 0) fun drawDummyGraphBox(array: Array<Int>) { // Title mvwprintw(window, 1, 1, "Title of graph!") // Lines for (i in 0..(array.max()!!)) { var line = "" var column = 0 // columns for (j in array.indices) { column = j line += "█░" } // draw line mvwprintw(window, (i + 2), 2, line) wrefresh(window) } } fun drawGraph(array: Array<Int>, activeValue: Int, title: String = "") { // Title mvwprintw(window, 1, 1, title) // Lines for (i in 0..(array.max()!!)) { var line = "" var column = 0 // columns for (j in array.indices) { column = j line += if (array[j] >= i) { if (activeValue == j) { "░ " } else { "█ " } } else { " " } } // draw line mvwprintw(window, (array.max()!! - (i - 2)), 2, line) wrefresh(window) } } fun bubblesort(array: Array<Int>, stateCallback: (array: Array<Int>, activeValue: Int) -> Unit) { for (pass in 0 until (array.size - 1)) { for (currentPosition in 0 until (array.size - pass - 1)) { if (array[currentPosition] > array[currentPosition + 1]) { val tmp = array[currentPosition] array[currentPosition] = array[currentPosition + 1] array[currentPosition + 1] = tmp stateCallback(array, currentPosition + 1) } } } } fun cocktailsort(array: Array<Int>, stateCallback: (array: Array<Int>, activeValue: Int) -> Unit) { fun swap(i: Int, j: Int) { val temp = array[i] array[i] = array[j] array[j] = temp } do { var swapped = false for (i in 0 until array.size - 1) if (array[i] > array[i + 1]) { swap(i, i + 1) swapped = true stateCallback(array, i + 1) } if (!swapped) break swapped = false for (i in array.size - 2 downTo 0) if (array[i] > array[i + 1]) { swap(i, i + 1) swapped = true stateCallback(array, i + 1) } } while (swapped) } bubblesort(values) { array, activeVAlue -> drawGraph(array, activeVAlue, "Bubble sort") usleep(delay) } values = values.toList() .shuffled(rng) .toTypedArray() cocktailsort(values) { array, activeVAlue -> drawGraph(array, activeVAlue, "Cocktail sort") usleep(delay) } // Dummy box // drawDummyGraphBox(values) wrefresh(window) wgetch(window) // wait for input, for now. // end delwin(window) endwin() }
fcc225a804b7d79ae0775e2b089144176bd71bbc
[ "Markdown", "Kotlin", "Gradle" ]
4
Kotlin
creekpld/sort-native
6fd14edacc4394f3d5a3ed74125eb856e8517850
2c1416135a678d45baf8e145a4db6bd43cba9fd1
refs/heads/master
<file_sep>#include "Evento.h" Evento::Evento(int n) { /*srand((unsigned)time(NULL)); this->nEvento = 1 + (rand() % 4);*/ this->nEvento = n; } Evento::Evento() { } Evento::~Evento() { } int Evento::getEvento() { return this->nEvento; } <file_sep>#pragma once #include "Nave.h" #include <iostream> #include "Configuracao.h" #include "Propulsor.h" #include "Sala_Maquinas.h" #include "Controlo_Escudo.h" #include "Ponte.h" #include "Suporte_Vida.h" #include "MembroDaTripulacao.h" #include "Robot.h" #include "Capitao.h" #include "Unidade.h" using namespace std; void DesenhaSalasFixas(); //void Configuracao(); Nave* ConfiguraNave(); Unidade* ListaTripulantes(int i); int Dificuldade(Nave *n);<file_sep>#pragma once #include <iostream> #include<string> #include <sstream> #include <vector> #include "Sala.h" #include "Caracteristicas.h" class Sala; class Caracteristicas; using namespace std; static int numeroIm = 0; class Unidade { string id; int saude; string nome; vector<Caracteristicas*>caracteristicas; Sala* sala; int n = numeroIm++; bool combate; public: Unidade(string n); Unidade(string n, Sala *sala); Unidade(); void SetSala(Sala *s); ~Unidade(); Sala* getSala(); string getNome()const; int getSaude() const; void diminuiSaude(int n); void MudarDeSala(Sala *s); void aumentaSaude(int n); bool getCombate(); const vector<Caracteristicas*>& getCaracteristicas(); void setCaracteristica(Caracteristicas *p); void Unidade::AplicaEfeitoCaracteristicaFinal(); }; <file_sep>#include "SSInterno.h" SSInterno::SSInterno() : Sala("SSINTERNO") {} SSInterno::~SSInterno(){}<file_sep>#include "CampoCosmisco.h" CampoCosmico::CampoCosmico() : Evento() { for (int i = 0; i < 12; i++) { this->SalasAfetadas[i] = 0; } } CampoCosmico::~CampoCosmico() { } int CampoCosmico::NumeroSalasAfetadas() { int i; srand((unsigned)time(NULL)); //Funcao Para gerar Numero aleatoricos de 3 a 5; i = 3 + (rand() % (5 - 3 + 1)); return i; } void CampoCosmico::EscolheSalas() { int sala; srand((unsigned)time(NULL)); for (int i = 0; i < this->NumeroSalasAfetadas(); i++) { sala = rand() % 12; if (this->SalasAfetadas[sala] == 0) this->SalasAfetadas[sala] = 1; else i--; } } void CampoCosmico::AplicaEvento(Nave *n){ this->NumeroSalasAfetadas(); this->EscolheSalas(); Consola c; c.gotoxy(50, 1); cout << "Chuva de Po Cosmico"; for (int i = 0; i < 12; i++) { if (SalasAfetadas[i] == 1) { n->getSala(i)->AplicaDano(DANO); } } } <file_sep>#pragma once #include "Sala.h" class SSInterno:public Sala { public: SSInterno(); ~SSInterno(); };<file_sep>#include "Sala_Maquinas.h" Sala_Maquinas::Sala_Maquinas() : Sala("SALA DAS MAQUINAS") { setOxigenio(100); setNumero(5); } <file_sep>#pragma once #include "Caracteristicas.h" class Respira : public Caracteristicas { public: Respira(Unidade *p, int n); ~Respira(); void AplicaCaracteristicaIniciais(Sala *p); void AplicaCaracteristicaFinais(Sala *s); private: }; <file_sep>#pragma once #include "Unidade.h" #include "Operador.h" #include "Reparador.h" class Capitao : public Unidade { public: Capitao(Sala *s); Capitao(); ~Capitao(); private: };<file_sep>#pragma once #include "Unidade.h" #include "Sala.h" class Unidade; class Sala; class Caracteristicas{ Unidade *unidade; public: Caracteristicas(Unidade *p); ~Caracteristicas(); Unidade* getUnidade(); // virtual void reparaSala(int n) =0; // virtual void Operasala() = 0; //Aplica Caracteristica virtual void AplicaCaracteristicaFinais(Sala *p) = 0; virtual void AplicaCaracteristicaIniciais(Sala *p) = 0; };<file_sep>#pragma once #include "Sala.h" class Beliches : public Sala { public: Beliches(); ~Beliches(); void aumenta_tripulantes(); };<file_sep>#pragma once #include "Unidade.h" #include "Operador.h" #include "Reparador.h" class MembroDaTripulacao : public Unidade{ public: /*MembroDaTripulacao(Sala *s);*/ MembroDaTripulacao(); ~MembroDaTripulacao(); private: }; <file_sep>#include <iostream> #include "consola.h" #include "Nave.h" #include "Configuracao.h" #include "Jogo.h" using namespace std; int main() { Consola c; c.setTextSize(15, 15); c.setScreenSize(200, 200); c.setBackgroundColor(c.BRANCO_CLARO); c.setTextColor(c.PRETO); c.clrscr(); c.gotoxy(40, 10); c.setTextColor(c.VERMELHO); cout << "PROGRAMACAO ORIENTADA A OBJETOS"; cout << ""; c.gotoxy(40, 12); c.setTextColor(c.PRETO); cout << "<NAME> & <NAME>"; c.gotoxy(40, 15); cout << "Precione ENTER para comecar"; char tecla; while (1) { tecla = c.getch(); if ((int)tecla ==13) break; } c.clrscr(); c.gotoxy(20, 10); c.setTextSize(15, 15); //nave->DesenhaNave(); //nave->DesenhaSalasOpcionais(); //Jogo(); Jogo j; j.IniciaJogo(); j.jogar(); }<file_sep>#pragma once #include "Evento.h" #include "Nave.h" class ChuvaMeteoritos : public Evento { public: ChuvaMeteoritos(); ~ChuvaMeteoritos(); void AplicaEvento(Nave *n); private: }; <file_sep>#pragma once #include "Sala.h" class Enfermaria :public Sala { public: Enfermaria(); ~Enfermaria(); };<file_sep>#include "Operador.h" Operador::Operador(Unidade *p) : Caracteristicas(p) { } Operador::~Operador() { } void Operador::AplicaCaracteristicaIniciais(Sala *p) { } void Operador::AplicaCaracteristicaFinais(Sala *s) { if (this->getUnidade()->getCombate() == false) { if (s->getIntegridade() == 100) s->setOperada(true); else s->setOperada(false); } } <file_sep>#pragma once #include "Unidade.h" #include "Operador.h" #include "Reparador.h" class Robot :public Unidade { public: Robot(); Robot(Sala *s); ~Robot(); private: };<file_sep>#pragma once #include "Caracteristicas.h" #include "Sala.h" class Operador : public Caracteristicas { public: Operador(Unidade *p); ~Operador(); void AplicaCaracteristicaIniciais(Sala *p); void AplicaCaracteristicaFinais(Sala *s); private: }; <file_sep> /* Funcoes da consola. Dez 2010 */ /* Pequenas correcoes + função main nova. Nov. 2013 */ /* Comentarios melhorados. Dez. 2015 */ /* --> ver comentários em Consola.h */ /* -----> Ler os comentários todos antes de fazer perguntas */ #include <iostream> #include "consola.h" // Isto é uma biblioteca desenvolvida para POO // Não é standard e não pretende ser // // Em última análise, isto é tudo o que é preciso saber: // // * Para que serve? // . Serve para controlar a consola e imprimir // caracteres onde se quiser, com as cores que se quiser // // * Requisitos: Sistema Windows NT ou superior // . Isto usa funções do sistema Windows (NT) // . Mac -> Não dá. Esquece isso. // . Linux -> Não dá. Esquece isso. // . "Mas eu tenho um Mac ou Linux e quero mesmo usar isto" // -> usar numa máquina virtual com o windows // ou // -> Linux ou Mac são unixes. Portanto pode usar a // biblioteca ncurses (que até tem mais coisas) // // * Isto constituído pelo quê, afinal? // . Uma classe, com funções que são o que interesa // // * Quais são os ficheiros envolvidos // . Um ficheiro .h que tem as declarações das funções // . Um ficheiro .cpp que tem as definições das funções e classe // . Um exemplo (este ficheiro) para ver como se usa // // * Como é que se usa // . Pegar no consola.h e no consola.h e juntá-los ao projecto // . Declarar um objecto Consola e usar as suas funções // . Basta ter um objecto Consola. Não são precisos mais using namespace std; // exemplo. serve de explicacao int main() { Consola c; // Este objecto dá acesso à funcionalidade da consola. Basta um por programa c.setTextColor(c.VERDE_CLARO); c.gotoxy(10, 10); cout << "Este programa serve para demonstrar o que se pode fazer com"; c.gotoxy(10, 11); cout << "a biblioteca \"consola\" de POO"; c.gotoxy(10, 13); cout << "Convem ver o codigo disto antes de colocar questoes"; c.gotoxy(10, 15); cout << "Primeiro passo: redimensionar o ecran"; c.gotoxy(10, 17); cout << "Carrega numa tecla para continuar"; c.getch(); c.setTextSize(8, 8); c.setScreenSize(50, 80); // linhas colunas. valores grandes pode nao dar c.setBackgroundColor(c.AZUL); // favor consultar o .h para ver as constantes c.setTextColor(c.AMARELO_CLARO); c.clrscr(); // reparar no c.xx - trata-se de funções da biblioteca de Consolda (para POO) // e não das funções com o mesmo nome da cionio.h do antigo turbo-c cout << "\n\n\nEsta parte do programa demostra que se pode ler uma tecla sem esperar pelo enter\n"; cout << "Cada tecla tem um codigo associado.\n"; cout << "Teclas especiais (Fxx) tem uma sequencia de dois codigos\n"; cout << "Carrega em teclas. \"Espaco\" para sair\n"; char tecla; while (1) { tecla = c.getch(); // reparar em c. -> getch da biblioteca de POO, não é a do conio.h cout << (char)tecla << " = " << (int)tecla << "\n"; if (tecla == ' ') break; } c.setTextColor(c.BRANCO_CLARO); cout << "\nAgora experimenta teclas de direccao."; cout << "\nRepara no asterisco no centro do ecran - fa-lo mexer."; cout << "\n(quem sabe se nao daria para implementar o pacman)"; cout << "\n\"escape\" para sair e depois carrega numa tecla"; int x = 39, y = 24; c.gotoxy(x, y); cout << '*'; while (1) { tecla = c.getch(); if (tecla == c.ESCAPE) break; if ((tecla != c.ESQUERDA) && (tecla != c.DIREITA) && (tecla != c.CIMA) && (tecla != c.BAIXO)) continue; //c.setTextColor(c.AZUL); c.gotoxy(x, y); cout << ' '; if (tecla == c.ESQUERDA) x--; if (tecla == c.DIREITA) x++; if (tecla == c.CIMA) y--; if (tecla == c.BAIXO) y++; c.gotoxy(x, y); cout << '*'; // TPC: validar os limites da consola } // RGB -> macro. valores entre 0 e 255 c.drawLine(0, 0, 300, 200, RGB(255, 0, 0)); c.drawCircle(150, 130, 105, RGB(0, 0, 255), 1); c.drawCircle(200, 130, 75, RGB(50, 255, 50), 0); c.gotoxy(0, 34); c.setTextColor(c.AMARELO_CLARO); cout << "Desenho de pixels e possivel mas nao e suportado\n"; cout << "Sao disponibilizadas algumas funcoes para esse efeito"; cout << "\nmas o resultado nao fica \"memorizado\" na janela\n"; cout << "(depois em SO2 resove-se isso)\n"; cout << "\n\nEscolhendo com cuidado as coordenadas pode-se fazer os desenhos coincidir\n"; cout << "com os limites dos caracteres\n"; cout << "mas realmente, nao se aconselha o uso de pixeis na consola de caracteres\n"; cout << "\nCaracteres com a mesma altura que a largura melhoram a apresentacao\n"; cout << "\n\ncarrega numa tecla qualquer"; c.getch(); c.setBackgroundColor(c.CINZENTO); c.setTextColor(c.BRANCO_CLARO); c.clrscr(); // reparar no c. trata-se de funções da biblioteca de Consolda (para POO) c.gotoxy(10, 4); cout << "Tabela com caracteres."; c.gotoxy(10, 5); cout << "Reparar que muitos podem ser usados para desenhar molduras e afins"; c.gotoxy(10, 6); cout << "Outros podem ser como tonalidades"; for (int i = 0; i< 16; i++) { for (int j = 0; j<16; j++) { c.gotoxy(20 + j * 3, 9 + i * 2); cout << (char)(i * 16 + j); } } c.setTextColor(c.VERMELHO); c.gotoxy(10, 40); cout << "\n\tNotar os seguintes\n\n"; cout << "\t" << (char)176 << ' ' << (char)177 << ' ' << (char)178 << '\n'; cout << "\n\t"; cout << (char)179 << ' ' << (char)180 << ' '; for (int i = 192; i<198; i++) cout << (char)i << ' '; for (int i = 200; i<207; i++) cout << (char)i << ' '; cout << "\n\n\tcarrega numa tecla qualquer para ver exemplos"; c.getch(); c.setTextColor(c.PRETO); c.setBackgroundColor(c.BRANCO_CLARO); c.clrscr(); c.gotoxy(20, 20); cout << (char)218 << (char)196 << (char)196 << (char)196 << (char)191 << '\n'; c.gotoxy(20, 21); cout << (char)179 << (char)176 << (char)176 << (char)176 << (char)179 << '\n'; c.gotoxy(20, 22); cout << (char)179 << (char)176 << (char)176 << (char)176 << (char)179 << '\n'; c.gotoxy(20, 23); cout << (char)179 << (char)176 << (char)176 << (char)176 << (char)179 << '\n'; c.gotoxy(20, 24); cout << (char)192 << (char)196 << (char)196 << (char)196 << (char)217 << '\n'; c.gotoxy(25, 20); cout << (char)218 << (char)196 << (char)196 << (char)196 << (char)191 << '\n'; c.gotoxy(25, 21); cout << (char)179 << (char)177 << (char)177 << (char)177 << (char)179 << '\n'; c.gotoxy(25, 22); cout << (char)179 << (char)177 << (char)177 << (char)177 << (char)179 << '\n'; c.gotoxy(25, 23); cout << (char)179 << (char)177 << (char)177 << (char)177 << (char)179 << '\n'; c.gotoxy(25, 24); cout << (char)192 << (char)196 << (char)196 << (char)196 << (char)217 << '\n'; c.gotoxy(30, 20); cout << (char)218 << (char)196 << (char)196 << (char)196 << (char)191 << '\n'; c.gotoxy(30, 21); cout << (char)179 << (char)178 << (char)178 << (char)178 << (char)179 << '\n'; c.gotoxy(30, 22); cout << (char)179 << (char)178 << (char)178 << (char)178 << (char)179 << '\n'; c.gotoxy(30, 23); cout << (char)179 << (char)178 << (char)178 << (char)178 << (char)179 << '\n'; c.gotoxy(30, 24); cout << (char)192 << (char)196 << (char)196 << (char)196 << (char)217 << '\n'; c.gotoxy(35, 20); cout << (char)218 << (char)196 << (char)196 << (char)196 << (char)191 << '\n'; c.gotoxy(35, 21); cout << (char)179 << (char)219 << (char)219 << (char)219 << (char)179 << '\n'; c.gotoxy(35, 22); cout << (char)179 << (char)219 << (char)219 << (char)219 << (char)179 << '\n'; c.gotoxy(35, 23); cout << (char)179 << (char)219 << (char)219 << (char)219 << (char)179 << '\n'; c.gotoxy(35, 24); cout << (char)192 << (char)196 << (char)196 << (char)196 << (char)217 << '\n'; c.setTextColor(c.VERDE); cout << "\n\n\t\tAgora e uma questao de criatividade"; c.setTextColor(c.PRETO); cout << "\n\n\t\tCarrega numa tecla qualquer"; c.getch(); return 0; } <file_sep>#include "Nave.h" Nave::Nave() { this->numeroPropulsores = 2; } Nave::~Nave() { } void Nave::setSala(Sala *n) { Salas.push_back(n); } void Nave::addMilhas(int m) { this->milhaspercorridas = this->milhaspercorridas +m ; } int Nave::getMilhas()const { return this->milhaspercorridas; } Sala* Nave::getSala(int i) { return Salas[i]; } Sala* Nave::listaSalas(int i) { if (i == 1) return new Propulsor(); if (i == 2) return new Beliches(); if (i== 3) return new RaioLaser(); if (i == 4) return new AutoReparador(); if (i == 5) return new SSInterno(); if(i==6) return new Enfermaria(); if(i==7) return new SalaArmas(); if(i==8) return new AlojamentosCapitao(); if(i==9) return new OficinaRobotica(); } void Nave::DesenhaNave() { Consola c; c.gotoxy(10, 15); cout << (char)218; c.gotoxy(10, 16); cout << (char)179; c.gotoxy(10, 17); cout << (char)179; c.gotoxy(10, 18); cout << (char)179; c.gotoxy(10, 19); cout << (char)179; c.gotoxy(10, 20); cout << (char)192; for (int i = 10; i <= 90; i++) { c.gotoxy(i, 15); switch (i) { case 10:c.gotoxy(i, 15); cout << (char)201; //218 c.gotoxy(i, 16); cout << (char)186; //179 c.gotoxy(i, 17); cout << (char)186; c.gotoxy(i, 18); cout << (char)186; c.gotoxy(i, 19); cout << (char)186; c.gotoxy(i, 20); cout << (char)186; c.gotoxy(i, 21); cout << (char)186; c.gotoxy(i, 22); cout << (char)186; c.gotoxy(i, 23); cout << (char)186; c.gotoxy(i, 24); cout << (char)186; c.gotoxy(i, 25); cout << (char)200; break; //192 case 30: c.gotoxy(i, 15); cout << (char)203; //194 c.gotoxy(i, 16); cout << (char)186; //179 c.gotoxy(i, 17); cout << (char)186; c.gotoxy(i, 18); cout << (char)186; c.gotoxy(i, 19); cout << (char)186; c.gotoxy(i, 20); cout << (char)186; c.gotoxy(i, 21); cout << (char)186; c.gotoxy(i, 22); cout << (char)186; c.gotoxy(i, 23); cout << (char)186; c.gotoxy(i, 24); cout << (char)186; break; case 50:c.gotoxy(i, 15); cout << (char)203; //194 c.gotoxy(i, 16); cout << (char)186; //179 c.gotoxy(i, 17); cout << (char)186; c.gotoxy(i, 18); cout << (char)186; c.gotoxy(i, 19); cout << (char)186; c.gotoxy(i, 20); cout << (char)186; c.gotoxy(i, 21); cout << (char)186; c.gotoxy(i, 22); cout << (char)186; c.gotoxy(i, 23); cout << (char)186; c.gotoxy(i, 24); cout << (char)186; break; case 70: c.gotoxy(i, 15); cout << (char)203; //194 c.gotoxy(i, 16); cout << (char)186; //179 c.gotoxy(i, 17); cout << (char)186; c.gotoxy(i, 18); cout << (char)186; c.gotoxy(i, 19); cout << (char)186; c.gotoxy(i, 20); cout << (char)186; c.gotoxy(i, 21); cout << (char)186; c.gotoxy(i, 22); cout << (char)186; c.gotoxy(i, 23); cout << (char)186; c.gotoxy(i, 24); cout << (char)186; break; case 90: c.gotoxy(i, 15); cout << (char)203; //194 c.gotoxy(i, 16); cout << (char)186; //179 c.gotoxy(i, 17); cout << (char)186; c.gotoxy(i, 18); cout << (char)186; c.gotoxy(i, 19); cout << (char)186; c.gotoxy(i, 20); cout << (char)186; c.gotoxy(i, 21); cout << (char)186; c.gotoxy(i, 22); cout << (char)186; c.gotoxy(i, 23); cout << (char)186; c.gotoxy(i, 24); cout << (char)186; break; default:cout << (char)205; break; } } for (int i = 11; i <= 110; i++) { c.gotoxy(i, 25); switch (i) { case 30:c.gotoxy(i, 25); cout << (char)206; //197 c.gotoxy(i, 26); cout << (char)186; c.gotoxy(i, 27); cout << (char)186; c.gotoxy(i, 28); cout << (char)186; c.gotoxy(i, 29); cout << (char)186; c.gotoxy(i, 30); cout << (char)186; c.gotoxy(i, 31); cout << (char)186; c.gotoxy(i, 32); cout << (char)186; c.gotoxy(i, 33); cout << (char)186; c.gotoxy(i, 34); cout << (char)186; break; case 50: c.gotoxy(i, 25); cout << (char)206; //197 c.gotoxy(i, 26); cout << (char)186; c.gotoxy(i, 27); cout << (char)186; c.gotoxy(i, 28); cout << (char)186; c.gotoxy(i, 29); cout << (char)186; c.gotoxy(i, 30); cout << (char)186; c.gotoxy(i, 31); cout << (char)186; c.gotoxy(i, 32); cout << (char)186; c.gotoxy(i, 33); cout << (char)186; c.gotoxy(i, 34); cout << (char)186; break; case 70: c.gotoxy(i, 25); cout << (char)206; //197 c.gotoxy(i, 26); cout << (char)186; c.gotoxy(i, 27); cout << (char)186; c.gotoxy(i, 28); cout << (char)186; c.gotoxy(i, 29); cout << (char)186; c.gotoxy(i, 30); cout << (char)186; c.gotoxy(i, 31); cout << (char)186; c.gotoxy(i, 32); cout << (char)186; c.gotoxy(i, 33); cout << (char)186; c.gotoxy(i, 34); cout << (char)186; break; case 90: c.gotoxy(i, 25); cout << (char)206; //197 c.gotoxy(i, 26); cout << (char)186; c.gotoxy(i, 27); cout << (char)186; c.gotoxy(i, 28); cout << (char)186; c.gotoxy(i, 29); cout << (char)186; c.gotoxy(i, 30); cout << (char)186; c.gotoxy(i, 31); cout << (char)186; c.gotoxy(i, 32); cout << (char)186; c.gotoxy(i, 33); cout << (char)186; c.gotoxy(i, 34); cout << (char)186; break; case 110: c.gotoxy(i, 25); cout << (char)206; //197 c.gotoxy(i, 26); cout << (char)186; c.gotoxy(i, 27); cout << (char)186; c.gotoxy(i, 28); cout << (char)186; c.gotoxy(i, 29); cout << (char)186; c.gotoxy(i, 30); cout << (char)186; c.gotoxy(i, 31); cout << (char)186; c.gotoxy(i, 32); cout << (char)186; c.gotoxy(i, 33); cout << (char)186; c.gotoxy(i, 34); cout << (char)186; break; default:cout << (char)205; break; } } for (int i = 10; i <= 110; i++) { c.gotoxy(i, 35); switch (i) { case 10:c.gotoxy(i, 35); cout << (char)201; //218 c.gotoxy(i, 36); cout << (char)186; c.gotoxy(i, 37); cout << (char)186; c.gotoxy(i, 38); cout << (char)186; c.gotoxy(i, 39); cout << (char)186; c.gotoxy(i, 40); cout << (char)186; c.gotoxy(i, 41); cout << (char)186; c.gotoxy(i, 42); cout << (char)186; c.gotoxy(i, 43); cout << (char)186; c.gotoxy(i, 44); cout << (char)186; c.gotoxy(i, 45); cout << (char)192; break; case 30:c.gotoxy(i, 35); cout << (char)206; c.gotoxy(i, 36); cout << (char)186; c.gotoxy(i, 37); cout << (char)186; c.gotoxy(i, 38); cout << (char)186; c.gotoxy(i, 39); cout << (char)186; c.gotoxy(i, 40); cout << (char)186; c.gotoxy(i, 41); cout << (char)186; c.gotoxy(i, 42); cout << (char)186; c.gotoxy(i, 43); cout << (char)186; c.gotoxy(i, 44); cout << (char)186; break; case 50: c.gotoxy(i, 35); cout << (char)206; c.gotoxy(i, 36); cout << (char)186; c.gotoxy(i, 37); cout << (char)186; c.gotoxy(i, 38); cout << (char)186; c.gotoxy(i, 39); cout << (char)186; c.gotoxy(i, 40); cout << (char)186; c.gotoxy(i, 41); cout << (char)186; c.gotoxy(i, 42); cout << (char)186; c.gotoxy(i, 43); cout << (char)186; c.gotoxy(i, 44); cout << (char)186; break; case 70: c.gotoxy(i, 35); cout << (char)206; c.gotoxy(i, 36); cout << (char)186; c.gotoxy(i, 37); cout << (char)186; c.gotoxy(i, 38); cout << (char)186; c.gotoxy(i, 39); cout << (char)186; c.gotoxy(i, 40); cout << (char)186; c.gotoxy(i, 41); cout << (char)186; c.gotoxy(i, 42); cout << (char)186; c.gotoxy(i, 43); cout << (char)186; c.gotoxy(i, 44); cout << (char)186; break; case 90: c.gotoxy(i, 35); cout << (char)206; c.gotoxy(i, 36); cout << (char)186; c.gotoxy(i, 37); cout << (char)186; c.gotoxy(i, 38); cout << (char)186; c.gotoxy(i, 39); cout << (char)186; c.gotoxy(i, 40); cout << (char)186; c.gotoxy(i, 41); cout << (char)186; c.gotoxy(i, 42); cout << (char)186; c.gotoxy(i, 43); cout << (char)186; c.gotoxy(i, 44); cout << (char)186; break; case 110: c.gotoxy(i, 35); cout << (char)188; //217 default:cout << (char)205; break; } } for (int i = 10; i <= 90; i++) { c.gotoxy(i, 45); switch (i) { case 10:cout << (char)200; break; //192 case 30:cout << (char)202; break; //202 case 50:cout << (char)202; break; case 70:cout << (char)202; break; case 90:cout << (char)188; break;//217 default:cout << (char)205;//196 break; } } } //Salas opcionais void Nave::DesenhaSalasOpcionais() { Consola c; int sala,posicao=0; string nome; /*c.gotoxy(125, 18); cout << "Indique o NUMERO da sala que pretende adicionar a nave e a POSICAO:"; c.gotoxy(130, 19); cout << "1: Propulsor Adicional"; c.gotoxy(130, 20); cout << "2: Beliches"; c.gotoxy(130, 21); cout << "3: <NAME>"; c.gotoxy(130, 22); cout << "4: Auto-Reparador"; c.gotoxy(130, 23); cout << "5: Sistema de Seguranca Interno "<<endl; c.gotoxy(125, 24); cout << "SALA NUMERO: "; cin >> sala; c.gotoxy(125, 25); cout << "POSICAO: "; cin >> posicao;*/ for (unsigned int i = 0; i <= Salas.size(); i++) { if (i == 0) { c.setTextColor(c.VERMELHO); c.gotoxy(16, 16); cout << Salas[i]->getNomeSala(); c.setTextColor(c.PRETO); c.gotoxy(11, 17); cout << "Integridade: "; cout << Salas[i]->getIntegridade(); c.gotoxy(11, 18); cout << "Oxigenio: "; cout << Salas[i]->getOxigenio(); c.gotoxy(11, 19); cout<<"Tripulacao: "; cout << Salas[i]->mostraUnidadesnaSala(); } if (i == 1) { c.setTextColor(c.AZUL); c.gotoxy(32, 16); cout << Salas[i]->getNomeSala(); c.setTextColor(c.PRETO); c.setTextColor(c.PRETO); c.gotoxy(32, 17); cout << "Integridade: "; cout << Salas[i]->getIntegridade(); c.gotoxy(32, 18); cout << "Oxigenio: "; cout << Salas[i]->getOxigenio(); c.gotoxy(32, 19); cout << "Tripulacao: "; cout << Salas[i]->mostraUnidadesnaSala(); } else if (i == 2) { c.setTextColor(c.AZUL); c.gotoxy(51, 16); cout << Salas[i]->getNomeSala(); c.setTextColor(c.PRETO); c.setTextColor(c.PRETO); c.gotoxy(51, 17); cout << "Integridade: "; cout << Salas[i]->getIntegridade(); c.gotoxy(51, 18); cout << "Oxigenio: "; cout << Salas[i]->getOxigenio(); c.gotoxy(51, 19); cout << "Tripulacao: "; cout << Salas[i]->mostraUnidadesnaSala(); } else if (i == 3) { c.setTextColor(c.AZUL); c.gotoxy(71, 16); cout << Salas[i]->getNomeSala(); c.setTextColor(c.PRETO); c.setTextColor(c.PRETO); c.gotoxy(71, 17); cout << "Integridade: "; cout << Salas[i]->getIntegridade(); c.gotoxy(71, 18); cout << "Oxigenio: "; cout << Salas[i]->getOxigenio(); c.gotoxy(71, 19); cout << "Tripulacao: "; cout << Salas[i]->mostraUnidadesnaSala(); } else if (i == 4) { c.setTextColor(c.VERMELHO); c.gotoxy(33, 26); cout << Salas[i]->getNomeSala(); c.setTextColor(c.PRETO); c.gotoxy(31, 27); cout << "Integridade: "; cout << Salas[i]->getIntegridade(); c.gotoxy(31, 28); cout << "Oxigenio: "; cout << Salas[i]->getOxigenio(); c.gotoxy(31, 29); cout << "Tripulacao: "; cout << Salas[i]->mostraUnidadesnaSala(); } else if (i == 5) { c.setTextColor(c.VERMELHO); c.gotoxy(53, 26); cout << Salas[i]->getNomeSala(); c.setTextColor(c.PRETO); c.gotoxy(51, 27); cout << "Integridade: "; cout << Salas[i]->getIntegridade(); c.gotoxy(51, 28); cout << "Oxigenio: "; cout << Salas[i]->getOxigenio(); c.gotoxy(51, 29); cout << "Tripulacao: "; cout << Salas[i]->mostraUnidadesnaSala(); } else if (i == 6) { c.setTextColor(c.VERMELHO); c.gotoxy(71, 26); cout << Salas[i]->getNomeSala(); c.setTextColor(c.PRETO); c.gotoxy(71, 27); cout << "Integridade: "; cout << Salas[i]->getIntegridade(); c.gotoxy(71, 28); cout << "Oxigenio: "; cout << Salas[i]->getOxigenio(); c.gotoxy(71, 29); cout << "Tripulacao: "; cout << Salas[i]->mostraUnidadesnaSala(); } else if (i == 7) { c.setTextColor(c.VERMELHO); c.gotoxy(98, 26); cout << Salas[i]->getNomeSala(); c.setTextColor(c.PRETO); c.gotoxy(91, 27); cout << "Integridade: "; cout << Salas[i]->getIntegridade(); c.gotoxy(91, 28); cout << "Oxigenio: "; cout << Salas[i]->getOxigenio(); c.gotoxy(91, 29); cout << "Tripulacao: "; cout << Salas[i]->mostraUnidadesnaSala(); } else if (i == 8) { c.setTextColor(c.VERMELHO); c.gotoxy(16, 36); cout << Salas[i]->getNomeSala(); c.setTextColor(c.PRETO); c.gotoxy(11, 37); cout << "Integridade: "; cout << Salas[i]->getIntegridade(); c.gotoxy(11, 38); cout << "Oxigenio: "; cout << Salas[i]->getOxigenio(); c.gotoxy(11, 39); cout << "Tripulacao: "; cout << Salas[i]->mostraUnidadesnaSala(); } else if (i == 9) { c.setTextColor(c.AZUL); c.gotoxy(31, 36); cout << Salas[i]->getNomeSala(); c.setTextColor(c.PRETO); c.setTextColor(c.PRETO); c.gotoxy(31, 37); cout << "Integridade: "; cout << Salas[i]->getIntegridade(); c.gotoxy(31, 38); cout << "Oxigenio: "; cout << Salas[i]->getOxigenio(); c.gotoxy(31, 39); cout << "Tripulacao: "; cout << Salas[i]->mostraUnidadesnaSala(); } else if (i == 10) { c.setTextColor(c.AZUL); c.gotoxy(51, 36); cout << Salas[i]->getNomeSala(); c.setTextColor(c.PRETO); c.setTextColor(c.PRETO); c.gotoxy(51, 37); cout << "Integridade: "; cout << Salas[i]->getIntegridade(); c.gotoxy(51, 38); cout << "Oxigenio: "; cout << Salas[i]->getOxigenio(); c.gotoxy(51, 39); cout << "Tripulacao: "; cout << Salas[i]->mostraUnidadesnaSala(); } else if (i == 11) { c.setTextColor(c.AZUL); c.gotoxy(71, 36); cout << Salas[i]->getNomeSala(); c.setTextColor(c.PRETO); c.setTextColor(c.PRETO); c.gotoxy(71, 37); cout << "Integridade: "; cout << Salas[i]->getIntegridade(); c.gotoxy(71, 38); cout << "Oxigenio: "; cout << Salas[i]->getOxigenio(); c.gotoxy(71, 39); cout << "Tripulacao: "; cout << Salas[i]->mostraUnidadesnaSala(); } } } void Nave::AvancaNave() { int propulsao=0; bool operada=false; for (unsigned int i = 0; i < this->Salas.size(); i++) { if (this->getSala(i)->getNomeSala() == "PROPULSOR") propulsao += this->getSala(i)->getIntegridade(); else { if (this->getSala(i)->getNomeSala() == "PONTE") { if (this->getSala(i)->getOperada() == true) operada = true; } } } if(operada==true) this->addMilhas(propulsao); } //void Nave::UnidadesaOperar() { // for (unsigned int i = 0; i < this->Salas.size(); i++) // for (unsigned j = 0; j < this->Salas[i]->getUnidades().size(); j++) // for (unsigned z = 0; z < this->Salas[i]->getUnidades()[j]->getCaracteristicas().size(); z++) // this->Salas[i]->getUnidades()[j]->getCaracteristicas()[z]->AplicaCaracteristica(): //} const vector<Sala*>& Nave::getSalas() { return this->Salas; } bool Nave::verificaSalasDestruidas() { for (unsigned int i = 0; i < Salas.size(); i++) { if ((Salas[i]->getIntegridade()) <= 0) return true; else return false; } } void Nave::setNumeroPropulsores(int numero) { this->numeroPropulsores = numero; } int Nave::getNumeroPropulsores() const { return numeroPropulsores; } <file_sep> #include "Beliches.h" Beliches::Beliches() : Sala("BELICHES") { setOxigenio(100); setNumero(20); // as salas opcionais iniciam no id 20 } void Beliches::aumenta_tripulantes() { } Beliches::~Beliches() {}<file_sep>#pragma once #include <iostream> #include <random> #include <time.h> #include "Nave.h" #define CHUVAMETEORITOS 1 #define ATAQUEPIRATAS 2 #define ATAQUEXENOMORFO 3 #define CAMPOCOSMICO 4 using namespace std; class Evento { public: Evento(int n); Evento(); ~Evento(); virtual void AplicaEvento(Nave *n) = 0; int getEvento(); private: int nEvento; }; <file_sep>#pragma once #include <string> #include<vector> #include "Unidade.h" #include <sstream> #include "consola.h" class Unidade; using namespace std; class Sala { vector<Unidade*>tripulantes; int integridade; int oxigenio; int numero; string nome; bool operada; bool fogo; bool brecha; bool CurtoCircuito; int id; public: Sala(string nome); Sala(); ~Sala(); void setTripulantes(Unidade *t); Unidade* getUnidade(int i); int getOxigenio()const; int getNumero()const; int getIntegridade()const; bool getFogo(); bool getBrecha(); bool getCurtoCircuito(); // bool operada(); /* bool fogo(); bool brecha(); bool CurtoCircuito();*/ bool getOperada(); void setOperada(bool a); void setIntegridade(int n); void setOxigenio(int o); void setNumero(int id) { numero = id; } void setFogo(bool f); void setBrecha(bool b); void setCurtoCircuito(bool cc); string getNomeSala()const; const vector<Unidade*>& getUnidades(); string mostraUnidadesnaSala()const; void AplicaDano(); void AplicaDano(int dano); void verificaOperada(); void RemoveElemento(Unidade* p); }; <file_sep>#include "Enfermaria.h" Enfermaria::Enfermaria() : Sala("ENFERMARIA") {} Enfermaria::~Enfermaria(){}<file_sep>#pragma once #include "Sala.h" class AutoReparador :public Sala { public: AutoReparador(); ~AutoReparador(); };<file_sep>#include "Reparador.h" Reparador::Reparador(Unidade *p, int n) : Caracteristicas(p) { this->reparador = n; } Reparador::~Reparador() { } void Reparador::AplicaCaracteristicaIniciais(Sala *p) { } void Reparador::AplicaCaracteristicaFinais(Sala *s) { Consola c; s->setIntegridade(reparador); c.gotoxy(60, 3); cout << "A Repararar Sala" << s->getNomeSala(); } <file_sep>#pragma once #include <iostream> #include <vector> #include "consola.h" #include "Sala.h" #include "Unidade.h" #include "Sala_Maquinas.h" #include "Controlo_Escudo.h" #include "Ponte.h" #include "RaioLaser.h" #include "AutoReparador.h" #include "SSInterno.h" #include "Propulsor.h" #include "Enfermaria.h" #include "Beliches.h" #include "Suporte_Vida.h" #include "SalaArmas.h" #include "AlojamentosCapitao.h" #include "OficinaRobotica.h" #include <string> class Sala; class Unidade; using namespace std; class Nave { private: vector <Sala*> Salas; vector<Unidade*>Tripulantes; int milhaspercorridas; int numeroPropulsores; public: Nave(); ~Nave(); void DesenhaNave(); //void DesenhaSalasFixas(); void DesenhaSalasOpcionais(); void setSala(Sala* n); const vector<Sala*>& getSalas(); void AvancaNave(); Sala* getSala(int i); Sala* listaSalas(int i); void addMilhas(int m); int getMilhas()const; bool verificaSalasDestruidas(); int getNumeroPropulsores()const; void setNumeroPropulsores(int numero); //void UnidadesaOperar(); //void UnidadesReparar(); }; <file_sep>#include "AlojamentosCapitao.h" AlojamentosCapitao::AlojamentosCapitao() : Sala("ALOJAMENTO CAPITAO") {} AlojamentosCapitao::~AlojamentosCapitao(){}<file_sep>#pragma once #include"Nave.h" #include "Nave.h" #include "consola.h" #include "Configuracao.h" #include "Evento.h" #include "CampoCosmisco.h" #include <time.h> #include <random> class Jogo { Nave *nave; int dificuldade; int DistanciaObj; int nRondas; int RondaProxEvento; Evento *evento; public: Jogo(); ~Jogo(); void mostraJogo(); void IniciaJogo(); bool fimJogo(); void jogar(); void estado(); bool detetaVitoria(); bool detetaDerrota(); int getNumeroRondas()const; void setNumeroRondas(); void primeiraFase(); void segundaFase(); void terceiraFase(); void quartaFase(); Evento* CriaEvento(); void ControlaEventos(); void EscolheRondaProxEvento(); void UnidadeAplicamCaracteristicasFinais(); }; //void Jogo();<file_sep>#include "Configuracao.h" void MapeiaNava() { Consola c; c.gotoxy(10, 15); cout << (char)218; c.gotoxy(10, 16); cout << (char)179; c.gotoxy(10, 17); cout << (char)179; c.gotoxy(10, 18); cout << (char)179; c.gotoxy(10, 19); cout << (char)179; c.gotoxy(10, 20); cout << (char)192; for (int i = 10; i <= 90; i++) { c.gotoxy(i, 15); switch (i) { case 10:c.gotoxy(i, 15); cout << (char)201; //218 c.gotoxy(i, 16); cout << (char)186; //179 c.gotoxy(i, 17); cout << (char)186; c.gotoxy(i, 18); cout << (char)186; c.gotoxy(i, 19); cout << (char)186; c.gotoxy(i, 20); cout << (char)186; c.gotoxy(i, 21); cout << (char)186; c.gotoxy(i, 22); cout << (char)186; c.gotoxy(i, 23); cout << (char)186; c.gotoxy(i, 24); cout << (char)186; c.gotoxy(i, 25); cout << (char)200; break; //192 case 30: c.gotoxy(i, 15); cout << (char)203; //194 c.gotoxy(i, 16); cout << (char)186; //179 c.gotoxy(i, 17); cout << (char)186; c.gotoxy(i, 18); cout << (char)186; c.gotoxy(i, 19); cout << (char)186; c.gotoxy(i, 20); cout << (char)186; c.gotoxy(i, 21); cout << (char)186; c.gotoxy(i, 22); cout << (char)186; c.gotoxy(i, 23); cout << (char)186; c.gotoxy(i, 24); cout << (char)186; break; case 50:c.gotoxy(i, 15); cout << (char)203; //194 c.gotoxy(i, 16); cout << (char)186; //179 c.gotoxy(i, 17); cout << (char)186; c.gotoxy(i, 18); cout << (char)186; c.gotoxy(i, 19); cout << (char)186; c.gotoxy(i, 20); cout << (char)186; c.gotoxy(i, 21); cout << (char)186; c.gotoxy(i, 22); cout << (char)186; c.gotoxy(i, 23); cout << (char)186; c.gotoxy(i, 24); cout << (char)186; break; case 70: c.gotoxy(i, 15); cout << (char)203; //194 c.gotoxy(i, 16); cout << (char)186; //179 c.gotoxy(i, 17); cout << (char)186; c.gotoxy(i, 18); cout << (char)186; c.gotoxy(i, 19); cout << (char)186; c.gotoxy(i, 20); cout << (char)186; c.gotoxy(i, 21); cout << (char)186; c.gotoxy(i, 22); cout << (char)186; c.gotoxy(i, 23); cout << (char)186; c.gotoxy(i, 24); cout << (char)186; break; case 90: c.gotoxy(i, 15); cout << (char)203; //194 c.gotoxy(i, 16); cout << (char)186; //179 c.gotoxy(i, 17); cout << (char)186; c.gotoxy(i, 18); cout << (char)186; c.gotoxy(i, 19); cout << (char)186; c.gotoxy(i, 20); cout << (char)186; c.gotoxy(i, 21); cout << (char)186; c.gotoxy(i, 22); cout << (char)186; c.gotoxy(i, 23); cout << (char)186; c.gotoxy(i, 24); cout << (char)186; break; default:cout << (char)205; break; } } for (int i = 11; i <= 110; i++) { c.gotoxy(i, 25); switch (i) { case 30:c.gotoxy(i, 25); cout << (char)206; //197 c.gotoxy(i, 26); cout << (char)186; c.gotoxy(i, 27); cout << (char)186; c.gotoxy(i, 28); cout << (char)186; c.gotoxy(i, 29); cout << (char)186; c.gotoxy(i, 30); cout << (char)186; c.gotoxy(i, 31); cout << (char)186; c.gotoxy(i, 32); cout << (char)186; c.gotoxy(i, 33); cout << (char)186; c.gotoxy(i, 34); cout << (char)186; break; case 50: c.gotoxy(i, 25); cout << (char)206; //197 c.gotoxy(i, 26); cout << (char)186; c.gotoxy(i, 27); cout << (char)186; c.gotoxy(i, 28); cout << (char)186; c.gotoxy(i, 29); cout << (char)186; c.gotoxy(i, 30); cout << (char)186; c.gotoxy(i, 31); cout << (char)186; c.gotoxy(i, 32); cout << (char)186; c.gotoxy(i, 33); cout << (char)186; c.gotoxy(i, 34); cout << (char)186; break; case 70: c.gotoxy(i, 25); cout << (char)206; //197 c.gotoxy(i, 26); cout << (char)186; c.gotoxy(i, 27); cout << (char)186; c.gotoxy(i, 28); cout << (char)186; c.gotoxy(i, 29); cout << (char)186; c.gotoxy(i, 30); cout << (char)186; c.gotoxy(i, 31); cout << (char)186; c.gotoxy(i, 32); cout << (char)186; c.gotoxy(i, 33); cout << (char)186; c.gotoxy(i, 34); cout << (char)186; break; case 90: c.gotoxy(i, 25); cout << (char)206; //197 c.gotoxy(i, 26); cout << (char)186; c.gotoxy(i, 27); cout << (char)186; c.gotoxy(i, 28); cout << (char)186; c.gotoxy(i, 29); cout << (char)186; c.gotoxy(i, 30); cout << (char)186; c.gotoxy(i, 31); cout << (char)186; c.gotoxy(i, 32); cout << (char)186; c.gotoxy(i, 33); cout << (char)186; c.gotoxy(i, 34); cout << (char)186; break; case 110: c.gotoxy(i, 25); cout << (char)206; //197 c.gotoxy(i, 26); cout << (char)186; c.gotoxy(i, 27); cout << (char)186; c.gotoxy(i, 28); cout << (char)186; c.gotoxy(i, 29); cout << (char)186; c.gotoxy(i, 30); cout << (char)186; c.gotoxy(i, 31); cout << (char)186; c.gotoxy(i, 32); cout << (char)186; c.gotoxy(i, 33); cout << (char)186; c.gotoxy(i, 34); cout << (char)186; break; default:cout << (char)205; break; } } for (int i = 10; i <= 110; i++) { c.gotoxy(i, 35); switch (i) { case 10:c.gotoxy(i, 35); cout << (char)201; //218 c.gotoxy(i, 36); cout << (char)186; c.gotoxy(i, 37); cout << (char)186; c.gotoxy(i, 38); cout << (char)186; c.gotoxy(i, 39); cout << (char)186; c.gotoxy(i, 40); cout << (char)186; c.gotoxy(i, 41); cout << (char)186; c.gotoxy(i, 42); cout << (char)186; c.gotoxy(i, 43); cout << (char)186; c.gotoxy(i, 44); cout << (char)186; c.gotoxy(i, 45); cout << (char)192; break; case 30:c.gotoxy(i, 35); cout << (char)206; c.gotoxy(i, 36); cout << (char)186; c.gotoxy(i, 37); cout << (char)186; c.gotoxy(i, 38); cout << (char)186; c.gotoxy(i, 39); cout << (char)186; c.gotoxy(i, 40); cout << (char)186; c.gotoxy(i, 41); cout << (char)186; c.gotoxy(i, 42); cout << (char)186; c.gotoxy(i, 43); cout << (char)186; c.gotoxy(i, 44); cout << (char)186; break; case 50: c.gotoxy(i, 35); cout << (char)206; c.gotoxy(i, 36); cout << (char)186; c.gotoxy(i, 37); cout << (char)186; c.gotoxy(i, 38); cout << (char)186; c.gotoxy(i, 39); cout << (char)186; c.gotoxy(i, 40); cout << (char)186; c.gotoxy(i, 41); cout << (char)186; c.gotoxy(i, 42); cout << (char)186; c.gotoxy(i, 43); cout << (char)186; c.gotoxy(i, 44); cout << (char)186; break; case 70: c.gotoxy(i, 35); cout << (char)206; c.gotoxy(i, 36); cout << (char)186; c.gotoxy(i, 37); cout << (char)186; c.gotoxy(i, 38); cout << (char)186; c.gotoxy(i, 39); cout << (char)186; c.gotoxy(i, 40); cout << (char)186; c.gotoxy(i, 41); cout << (char)186; c.gotoxy(i, 42); cout << (char)186; c.gotoxy(i, 43); cout << (char)186; c.gotoxy(i, 44); cout << (char)186; break; case 90: c.gotoxy(i, 35); cout << (char)206; c.gotoxy(i, 36); cout << (char)186; c.gotoxy(i, 37); cout << (char)186; c.gotoxy(i, 38); cout << (char)186; c.gotoxy(i, 39); cout << (char)186; c.gotoxy(i, 40); cout << (char)186; c.gotoxy(i, 41); cout << (char)186; c.gotoxy(i, 42); cout << (char)186; c.gotoxy(i, 43); cout << (char)186; c.gotoxy(i, 44); cout << (char)186; break; case 110: c.gotoxy(i, 35); cout << (char)188; //217 default:cout << (char)205; break; } } for (int i = 10; i <= 90; i++) { c.gotoxy(i, 45); switch (i) { case 10:cout << (char)200; break; //192 case 30:cout << (char)202; break; //202 case 50:cout << (char)202; break; case 70:cout << (char)202; break; case 90:cout << (char)188; break;//217 default:cout << (char)205;//196 break; } } } //Salas fixas void DesenhaSalasFixas() { Consola c; c.setTextColor(c.VERMELHO); c.gotoxy(16, 16); cout << "PROPULSOR"; c.setTextColor(c.PRETO); c.gotoxy(11, 17); cout << "Integridade: "; c.gotoxy(11, 18); cout << "Oxigenio: "; c.setTextColor(c.VERMELHO); c.gotoxy(33, 26); cout << "SALA MAQUINAS"; c.setTextColor(c.PRETO); c.gotoxy(31, 27); cout << "Integridade: "; c.gotoxy(31, 28); cout << "Oxigenio: "; c.setTextColor(c.VERMELHO); c.gotoxy(53, 26); cout << "SUPORTE DE VIDA"; c.setTextColor(c.PRETO); c.gotoxy(51, 27); cout << "Integridade: "; c.gotoxy(51, 28); cout << "Oxigenio: "; c.setTextColor(c.VERMELHO); c.gotoxy(71, 26); cout << "CONTROLO DE ESCUDO"; c.setTextColor(c.PRETO); c.gotoxy(71, 27); cout << "Integridade: "; c.gotoxy(71, 28); cout << "Oxigenio: "; c.setTextColor(c.VERMELHO); c.gotoxy(98, 26); cout << "PONTE"; c.setTextColor(c.PRETO); c.gotoxy(91, 27); cout << "Integridade: "; c.gotoxy(91, 28); cout << "Oxigenio: "; c.setTextColor(c.VERMELHO); c.gotoxy(16, 36); cout << "PROPULSOR"; c.setTextColor(c.PRETO); c.gotoxy(11, 37); cout << "Integridade: "; c.gotoxy(11, 38); cout << "Oxigenio: "; } Nave* ConfiguraNave(){ Consola c; int sala, posicao = 0; string nome; int ntripulantes = 3; Nave *nave= new Nave(); MapeiaNava(); cout << endl; DesenhaSalasFixas(); for (int i = 0; i < 12; i++) { c.gotoxy(125, 18); cout << "Indique as salas que pretende adicionar no seguinte formato:"; c.gotoxy(125, 19); cout << "Numero das salas separadas por espaco e ordenadas"; c.gotoxy(130, 20); cout << "1: Propulsor Adicional"; c.gotoxy(130, 21); cout << "2: Beliches"; c.gotoxy(130, 22); cout << "3: <NAME>"; c.gotoxy(130, 23); cout << "4: Auto-Reparador"; c.gotoxy(130, 24); cout << "5: Sistema de Seguranca Interno "; c.gotoxy(130, 25); cout << "6: Enfermaria "; c.gotoxy(130, 26); cout << "7: Sala de Armas "; c.gotoxy(130, 27); cout << "8: Alojamentos do Capitao "; c.gotoxy(130, 28); cout << "9: Oficina Robotica " << endl; c.gotoxy(125, 30); cout << "SALA NUMERO: " << " "; c.gotoxy(125, 30); cout << "SALA NUMERO: "; switch (i) { case 0: nave->setSala(new Propulsor()); nave->setNumeroPropulsores(nave->getNumeroPropulsores() + 1); break; case 1:do { cin >> sala; if (sala < 0 || sala>9) { cin.clear(); c.gotoxy(125, 30); cout << "SALA NUMERO: "<<" "; c.gotoxy(125, 30); cout << "SALA NUMERO: "; c.gotoxy(125, 31); cout << "Nao existe essa sala! "; c.gotoxy(125, 30); cout << "SALA NUMERO: "<<" "; c.gotoxy(125, 30); cout << "SALA NUMERO: "; } } while (sala < 0 || sala>9); nave->setSala(nave->listaSalas(sala)); if (sala == 2) ntripulantes++; break; case 2:do { cin >> sala; if (sala < 0 || sala>9) { cin.clear(); c.gotoxy(125, 30); cout << "SALA NUMERO: " << " "; c.gotoxy(125, 30); cout << "SALA NUMERO: "; c.gotoxy(125, 31); cout << "Nao existe essa sala! "; c.gotoxy(125, 30); cout << "SALA NUMERO: " << " "; c.gotoxy(125, 30); cout << "SALA NUMERO: "; } } while (sala < 0 || sala>9); nave->setSala(nave->listaSalas(sala)); if (sala == 2) ntripulantes++; break; case 3:do { cin >> sala; if (sala < 0 || sala>9) { cin.clear(); c.gotoxy(125, 30); cout << "SALA NUMERO: " << " "; c.gotoxy(125, 30); cout << "SALA NUMERO: "; c.gotoxy(125, 31); cout << "Nao existe essa sala! "; c.gotoxy(125, 30); cout << "SALA NUMERO: " << " "; c.gotoxy(125, 30); cout << "SALA NUMERO: "; } } while (sala < 0 || sala>9); nave->setSala(nave->listaSalas(sala)); if (sala == 2) ntripulantes++; break; case 4: nave->setSala(new Sala_Maquinas()); break; case 5: nave->setSala(new Suporte_Vida()); break; case 6:nave->setSala(new Controlo_Escudo()); break; case 7:nave->setSala(new Ponte()); break; case 8:nave->setSala(new Propulsor()); break; case 9:do { cin >> sala; if (sala < 0 || sala>9) { cin.clear(); c.gotoxy(125, 30); cout << "SALA NUMERO: " << " "; c.gotoxy(125, 30); cout << "SALA NUMERO: "; c.gotoxy(125, 31); cout << "Nao existe essa sala! "; c.gotoxy(125, 30); cout << "SALA NUMERO: " << " "; c.gotoxy(125, 30); cout << "SALA NUMERO: "; } } while (sala < 0 || sala>9); nave->setSala(nave->listaSalas(sala)); if (sala == 2) ntripulantes++; break; case 10:do { cin >> sala; if (sala < 0 || sala>9) { cin.clear(); c.gotoxy(125, 30); cout << "SALA NUMERO: " << " "; c.gotoxy(125, 30); cout << "SALA NUMERO: "; c.gotoxy(125, 31); cout << "Nao existe essa sala! "; c.gotoxy(125, 30); cout << "SALA NUMERO: " << " "; c.gotoxy(125, 30); cout << "SALA NUMERO: "; } } while (sala < 0 || sala>9); nave->setSala(nave->listaSalas(sala)); if (sala == 2) ntripulantes++; break; case 11:do { cin >> sala; if (sala < 0 || sala>9) { cin.clear(); c.gotoxy(125, 30); cout << "SALA NUMERO: " << " "; c.gotoxy(125, 30); cout << "SALA NUMERO: "; c.gotoxy(125, 31); cout << "Nao existe essa sala! "; c.gotoxy(125, 30); cout << "SALA NUMERO: " << " "; c.gotoxy(125, 30); cout << "SALA NUMERO: "; } } while (sala < 0 || sala>9); nave->setSala(nave->listaSalas(sala)); if (sala == 2) ntripulantes++; break; } } c.clrscr(); //MapeiaNava(); nave->DesenhaNave(); nave->DesenhaSalasOpcionais(); int numero; for (int i = 0; i < ntripulantes; i++) { c.gotoxy(125, 19); cout << "Indique os tripulantes que pretende adicionar:"; c.gotoxy(130, 20); cout << "1: Membro da Tripulacao"; c.gotoxy(130, 21); cout << "2: Capitao"; c.gotoxy(130, 22); cout << "3: Robot"; c.gotoxy(125, 23); cout << "Tripulante Numero: "<<" "; c.gotoxy(125, 23); cout << "Tripulante Numero: "; cin >> numero; c.gotoxy(125, 24); cout << "Posicao: "; cin >> posicao; do { if (numero < 0 || numero>3) { c.gotoxy(125, 24); cout << "Posicao: " << " "; c.gotoxy(125, 24); cout << "Posicao: "; cin >> numero; c.gotoxy(125, 31); cout << "Nao existe essa sala! "; c.gotoxy(125, 24); cout << "Posicao: " << " "; c.gotoxy(125, 24); cout << "Posicao: "; } } while (numero < 0 || numero>3); /// nave->setTripulantes(ListaTripulantes(sala,nave->getSala(posicao))); ListaTripulantes(numero)->SetSala(nave->getSala(posicao-1)); //c.gotoxy(125, 24); cout << "Trip: "; cout << nave->getSala(posicao)->getUnidades()[0]->getNome(); } return nave; } Unidade* ListaTripulantes(int i) { if (i == 1) return new MembroDaTripulacao(); if (i == 2) return new Capitao(); if (i == 3) return new Robot(); } int Dificuldade(Nave *n) { Consola c; int dificuldade; c.clrscr(); n->DesenhaNave(); n->DesenhaSalasOpcionais(); c.gotoxy(130, 20); cout << "Introduza a Dificuldade do jogo"; c.gotoxy(130, 21); cin >> dificuldade; c.clrscr(); n->DesenhaNave(); n->DesenhaSalasOpcionais(); c.gotoxy(130, 20); cout << "O jogo ira comecar com dificuldade "<<dificuldade; c.gotoxy(130, 25); cout << "Precione ENTER para comecar"; c.gotoxy(130, 26); char tecla; do { tecla = c.getch(); } while ((int)tecla != 13); return dificuldade; } <file_sep>#include "Capitao.h" Capitao::Capitao(Sala *s) :Unidade("C", s) { this->setCaracteristica(new Operador(this)); // this->setCaracteristica(new Reparador(this)); } Capitao::Capitao() : Unidade("C") { } Capitao::~Capitao() { } <file_sep>#pragma once #include "Sala.h" class Sala_Maquinas : public Sala { public: Sala_Maquinas(); ~Sala_Maquinas(); };<file_sep>#include "ChuvaMeteoritos.h" ChuvaMeteoritos::ChuvaMeteoritos() { } ChuvaMeteoritos::~ChuvaMeteoritos() { } void ChuvaMeteoritos::AplicaEvento(Nave *n) { }<file_sep>#pragma once #include "Unidade.h" class Geigermorfo :public Unidade { Geigermorfo(); ~Geigermorfo(); };<file_sep>#include "Controlo_Escudo.h" Controlo_Escudo::Controlo_Escudo():Sala("CONTROLO ESCUDO") { setNumero(7); } Controlo_Escudo::~Controlo_Escudo() {} <file_sep>#include "AutoReparador.h" AutoReparador::AutoReparador() : Sala("AUTOREAPARADOR") {} AutoReparador::~AutoReparador(){}<file_sep>#include "RaioLaser.h" RaioLaser::RaioLaser() : Sala("RAIO LASER") {} RaioLaser::~RaioLaser(){}<file_sep>#pragma once #include "Sala.h" class OficinaRobotica :public Sala { public: OficinaRobotica(); ~OficinaRobotica(); };<file_sep>#include "SalaArmas.h" SalaArmas::SalaArmas() : Sala("SALA DE ARMAS") {} SalaArmas::~SalaArmas(){}<file_sep>#include "Propulsor.h" Propulsor::Propulsor() : Sala("PROPULSOR"){ setOxigenio(100); setNumero(1); } Propulsor::~Propulsor() {} int Propulsor::getPropulsao() { return this->getIntegridade(); } <file_sep>#pragma once #include "Sala.h" class Propulsor : public Sala { public: Propulsor(); ~Propulsor(); int getPropulsao(); };<file_sep>#pragma once #include "Sala.h" class AlojamentosCapitao :public Sala { public: AlojamentosCapitao(); ~AlojamentosCapitao(); };<file_sep>#pragma once #include "Sala.h" class SalaArmas :public Sala { public: SalaArmas(); ~SalaArmas(); };<file_sep>#include "Ponte.h" Ponte::Ponte() : Sala("PONTE") { setOxigenio(100); setNumero(8); } Ponte::~Ponte() {}<file_sep>#pragma once #include "Evento.h" #include "Nave.h" #include <random> #include <time.h> #define DANO 10 class CampoCosmico : public Evento { private: int SalasAfetadas[12]; int NumeroSalasAfetadas(); void EscolheSalas(); public: CampoCosmico(); ~CampoCosmico(); void AplicaEvento(Nave *n); }; <file_sep>#include "OficinaRobotica.h" OficinaRobotica::OficinaRobotica() : Sala("OFICINA") {} OficinaRobotica::~OficinaRobotica(){}<file_sep>#include "Suporte_Vida.h" Suporte_Vida::Suporte_Vida() : Sala("SUPORTE DE VIDA") { setOxigenio(100); setNumero(6); } Suporte_Vida::~Suporte_Vida() {} <file_sep>#include "Respira.h" Respira::Respira(Unidade *p, int n) : Caracteristicas(p) { } Respira::~Respira() { } void Respira::AplicaCaracteristicaIniciais(Sala *p) { } void Respira::AplicaCaracteristicaFinais(Sala *s) { }<file_sep>#pragma once #include "Sala.h" class RaioLaser :public Sala { public: RaioLaser(); ~RaioLaser(); };<file_sep>#include "Robot.h" Robot::Robot(Sala *s) :Unidade("R", s) { this->setCaracteristica(new Operador(this)); //this->setCaracteristica(new Reparador(this)); } Robot::Robot() : Unidade("R") { } Robot::~Robot() { }<file_sep>#pragma once #include "Sala.h" class Ponte : public Sala { public: Ponte(); ~Ponte(); };<file_sep>#include "Jogo.h" Jogo::Jogo() { } Jogo::~Jogo(){} //Função que Trata de Confgurar as caracteristicas do jogo, nave, dificuldade, rondas, distancia void Jogo::IniciaJogo() { this->nave = ConfiguraNave(); this->dificuldade = Dificuldade(this->nave); this->nRondas =1; this->DistanciaObj = 4000 + 1000 * this->dificuldade; this->RondaProxEvento = 1; } //Funcao que deteta o fim do jogo bool Jogo::fimJogo() { if(nave->verificaSalasDestruidas()==true) return false; if (this->DistanciaObj - this->nave->getMilhas() <= 0) return false; return true; } //Ciclo onde decorre o jogo void Jogo::jogar() { while (fimJogo()) { this->primeiraFase(); this->segundaFase(); this->terceiraFase(); this->quartaFase(); this->nRondas++; } } void Jogo::estado() { } //Primeira Fase do turno void Jogo::primeiraFase() { Consola c; char tecla; c.clrscr(); this->mostraJogo(); this->ControlaEventos(); //verificar integridade das salas //this->nave->UnidadesaOperar(); c.gotoxy(122, 39); cout << "pressione ENTER para avançar para a fase 2:"; do { tecla = c.getch(); } while ((int)tecla != 13); } //Segunda Fase do turno void Jogo::segundaFase() { Consola c; string nome; int pos; char tecla; do { c.clrscr(); this->mostraJogo(); c.gotoxy(122, 35); // this->nave->UnidadesReparar(); cout << "E<NAME>? (ESC para avançar para 3 fase)"; tecla = c.getch(); if ((int)tecla != 27) { c.gotoxy(122, 37); cout << "Jogador>>>"; cin >> nome; c.gotoxy(122, 39); cout << "Sala>>>"; cin >> pos; for (unsigned int i = 0; i < nave->getSalas().size(); i++) { for (unsigned int j = 0; j < nave->getSalas()[i]->getUnidades().size(); j++) { if (nave->getSalas()[i]->getUnidades()[j]->getNome() == nome) nave->getSalas()[i]->getUnidades()[j]->MudarDeSala(nave->getSalas()[pos-1]); } } } } while ((int)tecla != 27); } //Terceira Fase do turno, onde se pode aplicar comandos void Jogo::terceiraFase() { Consola c; char tecla; c.clrscr(); this->mostraJogo(); UnidadeAplicamCaracteristicasFinais(); c.gotoxy(122, 39); cout << "pressione ENTER para avançar para a fase 4:"; do { tecla = c.getch(); } while ((int)tecla != 13); this->nave->AvancaNave(); } //Quarta fase do jogo void Jogo::quartaFase() { Consola c; char tecla; c.clrscr(); this->mostraJogo(); c.gotoxy(122, 39); cout << "pressione ENTER para avançar no turno:"; do { tecla = c.getch(); } while ((int)tecla != 13); } //Deteção de vitoria bool Jogo::detetaVitoria() { return false; } //deteção de derrota bool Jogo::detetaDerrota() { return false; } //Metodo que devolve o numero de rondas int Jogo::getNumeroRondas()const { return this->nRondas; } //Metodo que incrementa o numero de rondas void Jogo::setNumeroRondas() { this->nRondas++; } //Mostra o tabuleiro de jogo void Jogo::mostraJogo() { Consola c; c.clrscr(); for (int i = 120; i <= 180; i++) { switch (i) { case 120:c.gotoxy(i, 15); cout << (char)218; for (int j = 16; j < 40; j++) { c.gotoxy(120, j); cout << (char)179; } break; case 180:c.gotoxy(i, 15); cout << (char)191; for (int j = 16; j < 40; j++) { c.gotoxy(i, j); cout << (char)179; }break; default:c.gotoxy(i, 15); cout << (char)196; break; } } for (int i = 120; i <= 180; i++) { switch (i) { case 120:c.gotoxy(i, 40); cout << (char)192; break; case 180:c.gotoxy(i, 40); cout << (char)217; break; default:c.gotoxy(i, 40); cout << (char)196; break; break; } } this->nave->DesenhaNave(); this->nave->DesenhaSalasOpcionais(); c.gotoxy(130, 20); cout << "Distancia Objetivo: " << this->DistanciaObj; c.gotoxy(130, 21); cout << "Distancia a Percorrer: " << this->DistanciaObj - (this->nave->getMilhas()); c.gotoxy(130, 22); cout << "Turno Numero:" << this->nRondas; } void Jogo::UnidadeAplicamCaracteristicasFinais() { for (int i = 0; i < this->nave->getSalas().size(); i++) { for (int j = 0; j < this->nave->getSala(i)->getUnidades().size(); j++) { this->nave->getSala(i)->getUnidade(j)->AplicaEfeitoCaracteristicaFinal(); } } } //funcao que faz o sorteio dos enventos Evento* Jogo:: CriaEvento() { srand((unsigned)time(NULL)); int numeroEvento; numeroEvento = 1 + (rand() % 4); if (numeroEvento == CHUVAMETEORITOS) { return new CampoCosmico(); } else if (numeroEvento == ATAQUEPIRATAS) { return new CampoCosmico(); } else if (numeroEvento == ATAQUEXENOMORFO) { return new CampoCosmico(); } else if (numeroEvento == CAMPOCOSMICO) { return new CampoCosmico(); } } //Metodo que controla os Eventos do jogo void Jogo::ControlaEventos() { if (this->nRondas == this->RondaProxEvento) { this->evento = this->CriaEvento(); this->evento->AplicaEvento(this->nave); delete this->evento; this->EscolheRondaProxEvento(); } } //Escolhe a proxima Ronda onde ira ocorrer o proximo envento. //Soma a Ronda actual um numero entre 10 e 5 void Jogo::EscolheRondaProxEvento() { srand((unsigned)time(NULL)); this->RondaProxEvento = this->nRondas + (5 + (rand() % (10 - 5 + 1))); Consola c; c.gotoxy(1, 1); cout << "Proximo Evento na Ronda " << RondaProxEvento; } <file_sep>#include "Sala.h" Sala::Sala(string nome){ this->nome = nome; this->integridade = 100; this->oxigenio = 100; this->operada = false; this->fogo = false; this->brecha = false; this->CurtoCircuito = false; this->operada = true; } Sala::Sala(){} Sala::~Sala(){} void Sala::setTripulantes(Unidade *t) { tripulantes.push_back(t); } void Sala::setOxigenio(int o) { this->oxigenio = o; } bool Sala::getOperada() { return this->operada; } void Sala::setOperada(bool a) { this->operada = a; } void Sala::RemoveElemento(Unidade* p) { for (unsigned int i = 0; i < tripulantes.size(); i++) if (tripulantes[i]->getNome() == p->getNome()) tripulantes.erase(tripulantes.begin()+i); } void Sala::setIntegridade(int n) { Consola c; if (this->integridade + n > 100) { this->integridade = 100; c.gotoxy(122, 14); cout << "Sala sem danos"; } else this->integridade = this->integridade + n; } void Sala::setFogo(bool f) { this->fogo = f; } void Sala::setBrecha(bool b) { this->brecha = b; } void Sala::setCurtoCircuito(bool cc) { this->CurtoCircuito = cc; } int Sala::getOxigenio()const { return oxigenio; } string Sala::getNomeSala()const { return nome; } int Sala::getNumero()const { return numero; } int Sala::getIntegridade()const { return this->integridade; } bool Sala::getBrecha() { return brecha; } bool Sala::getCurtoCircuito() { return CurtoCircuito; } bool Sala::getFogo() { return fogo; } const vector<Unidade*>& Sala::getUnidades() { return tripulantes; } void Sala::AplicaDano() { this->integridade = (100 - this->integridade); } void Sala::AplicaDano(int dano) { this->integridade = (this->integridade - dano); } string Sala::mostraUnidadesnaSala()const { ostringstream oss; for (unsigned i = 0; i < tripulantes.size(); i++) { oss << tripulantes[i]->getNome() << " "; } return oss.str(); } void Sala::verificaOperada() { if ((this->integridade) == 100) { for (int j = 0; j < this->tripulantes.size(); j++) { if ((tripulantes[j]->getCombate()) == false) this->operada = true; } } else this->operada=false; } Unidade* Sala::getUnidade(int i) { return this->tripulantes[i]; }<file_sep>#include "Caracteristicas.h" Caracteristicas::Caracteristicas(Unidade *p) { this->unidade = p; } Caracteristicas::~Caracteristicas() { } Unidade* Caracteristicas::getUnidade(){ return this->unidade; }<file_sep>#pragma once #include "Sala.h" class Controlo_Escudo : public Sala { public: Controlo_Escudo(); ~Controlo_Escudo(); }; <file_sep>#include "MembroDaTripulacao.h" //MembroDaTripulacao::MembroDaTripulacao(Sala *s) :Unidade("MT",s) //{ // this->setCaracteristica(new Operador(this)); // this->setCaracteristica(new Reparador(this,2)); //} MembroDaTripulacao::MembroDaTripulacao() : Unidade("M") { this->setCaracteristica(new Operador(this)); this->setCaracteristica(new Reparador(this, 2)); } MembroDaTripulacao::~MembroDaTripulacao() { } <file_sep>#include "Unidade.h" Unidade::Unidade(string n) { ostringstream convert; convert << numeroIm; this->id = n; this->nome = n+convert.str(); this->saude = 100; this->combate = false; } Unidade::Unidade(string n, Sala *s){ this->nome = n; this->sala = s; this ->saude = 100; } void Unidade::SetSala(Sala *s) { this->sala = s; s->setTripulantes(this); } Unidade::Unidade() { } Unidade::~Unidade(){} string Unidade::getNome() const{ return this->nome; } int Unidade::getSaude() const { return this->saude; } void Unidade::aumentaSaude(int n) { if ((this->saude + n) <= 100) { this->saude = this->saude + n; } else { this->saude = 100; } } void Unidade::diminuiSaude(int n) { if ((this->saude - n) > 0) { this->saude = this->saude - n; } else { this->saude = 0;//morrer } } void Unidade::MudarDeSala(Sala *s) { this->sala->RemoveElemento(this); this->sala = s; s->setTripulantes(this); } bool Unidade::getCombate() { return this->combate; } Sala* Unidade::getSala() { return this->sala; } const vector<Caracteristicas*>& Unidade::getCaracteristicas() { return this->caracteristicas; } void Unidade::setCaracteristica(Caracteristicas *p) { this->caracteristicas.push_back(p); } void Unidade::AplicaEfeitoCaracteristicaFinal() { Consola c; c.gotoxy(60, 2); cout << "Estou aqui " << caracteristicas.size(); for (int i = 0; i < caracteristicas.size(); i++) { caracteristicas[i]->AplicaCaracteristicaFinais(this->sala); } }<file_sep>#pragma once #include "Sala.h" class Reparador : public Caracteristicas { public: Reparador(Unidade *p, int n); ~Reparador(); void AplicaCaracteristicaIniciais(Sala *p); void AplicaCaracteristicaFinais(Sala *s); private: int reparador; }; <file_sep>#pragma once #include "Sala.h" class Suporte_Vida : public Sala { public: Suporte_Vida( ); ~Suporte_Vida(); };
2aaaf66415554b47b0b6c921d5f3f34a8e2d8aee
[ "C++" ]
59
C++
JonathanMaga/TrabalhoEXP
589a9bb4e2a47a57ce1f29e0b72210f0c209bdb0
632c80dc65df6d8aa660de0ed910761e18608398
refs/heads/master
<file_sep>// Quiz $(document).ready(function(){ // When someone clicks an answer... $(".answer").click(function() { // if it hasn't been clicked before and the right answer hasn't already been picked.... if ( !$(this).hasClass("clicked") && !$(this).siblings('.right').hasClass("clicked") ) { // show that it's been clicked. $(this).addClass("clicked"); if ( $(this).hasClass( "wrong" ) && $( this ).hasClass( "clicked" ) ) { // If it's wrong, show this message. $(this).parent().siblings('.message').html('Close, try again.'); } if ( $(this).hasClass( "right" ) && $( this ).hasClass( "clicked" ) ) { // If it's right, show this message and disable the other buttons. $(this).parent().siblings('.message').html('You got it!'); $(this).siblings('.wrong').addClass("disable"); } // Set this number to how many correct answers there are (must be same number for all). if ($(".right.clicked").length >= 3) { // If all correct answers are selected, show this. $("div#winner").fadeIn( "fast" ); } } }); });<file_sep>// Modified from "How to Display Random News or Content with JavaScript" by Extreme Design Studio @ http://www.extremestudio.ro/blog/?p=4273 // Change this to the number of different quizzes you have (3+1 for 3 quizzes, 2+1 for 2 quizzes, etc.) randomNumber = Math.floor(Math.random()*3+1); window.onload = function() { // Add this section for each quiz that you have and change the number so there is one for each option. if (randomNumber == 1) { // Change ID to ID of the section you want to show. document.getElementById("quiz1").style.display = "block"; } if (randomNumber == 2) { document.getElementById("quiz2").style.display = "block"; } if (randomNumber == 3) { document.getElementById("quiz3").style.display = "block"; } }<file_sep># Randomized Quiz Sets Randomize sets of quiz questions with answer confirmation and completion message. This does three things: 1. **Displays a random set of quiz questions on screen** by hiding all sections with class "quiz" and then showing one based on a random number generated. I have also included a loading animation if this takes too long. 2. **Provides feedback on quiz answers** in a few different ways. - When an answer is clicked, color of the item changes to indicate if it is correct or incorrect. - When an answer is clicked, a message shows indicating if the answer is correct or incorrect. - When an incorrect answer is clicked, that answer appears 'disabled' and no longer changes the mouse cursor, changes color when clicked, displays hover effects, or updates the message when clicked. - When the correct answer is clicked, all answers appear disabled as described above. 3. **Displays congratulatory message when all answers are marked correct** by calculating the number of correct answers possible. This number must be the same for all quizzes. If all answers are correct a modal overlay window is shown. See a sample at http://thekristin.github.io/randomized-quiz-sets/ ## Usage You will need to include: - **index.html** - Includes quiz questions and modal window content, page structure. - **quiz.css** - Includes the very very basic code you need to make this work, seperate from all other markup so you can use this with your own styling if you like. - **js/check-quiz-answers.js** - Check if answers are correct, feedback as answers are clicked, message if all correct answers are selected. - **js/display-random-content.js** - Display a random set of questions on each page load. I've also included these files for styling, but the code with work without them (it just won't look as nice): - **style.css** - All styling as seen on the sample. - **js/modernizr.custom.62055.js** - Uses modernizr to check for flexbox support. ### Randomly show/hide section or element This will allow random sections of content to show on the page at one time. The ID of an element is used decide what content to show and hide. In the sample html these are divs labelled "quiz1", "quiz2", and "quiz3". The important thing here is the ID name, but this can be modified to whatever you need and additional elements can be added with new names. Each section must also be set to `display: hide` by default - in the sample this is set for all elements with class "quiz". If you want to modify the IDs in any way, you will need to update the IDs in **js/display-random-content.js** to whatever content you want to show/hide randomly. Replace "quiz1", "quiz2", "quiz3" with your new ID names in both **js/display-random-content.js** and **index.html**. To add content: 1. Add an element with your ID(s) to **index.html**. 2. Go to **js/display-random-content.js** and replicate this section as many times as needed: ``` if (randomNumber == 1) { // Change ID to ID of the section you want to show. document.getElementById("YourID").style.display = "block"; } ``` 3. Replace *1* with a different number for each, incrementing by one each time. 4. Replace *YourID* with your ID from **index.html**. 5. Update this section `randomNumber = Math.floor(Math.random()*3+1);` in **js/display-random-content.js** with the highest number in randomNumber from the code above - replace *3* in this snippet. This is modified from "How to Display Random News or Content with JavaScript" by Extreme Design Studio @ http://www.extremestudio.ro/blog/?p=4273 ### Check quiz answers Quiz answers must be given the class "answer". They must have the class "right" or "wrong". Suggested HTML markup (in **index.html**) is: ``` <div class="answer wrong">Wrong Answer</div> <div class="answer right">Right Answer</div> ``` To allow answers to change color on click, the suggested styles are (see samples in **styles.css**): ``` .answer { background-color: gray; /* set a default color for quiz answers before clicking */ } .answer:hover { background-color: orange; /* set a hover color for quiz answers */ } .answer.disable:hover, .disable.wrong:hover { background-color: gray; /* hide hover effect when correct answer has already been selected - keep same as .answer color */ } .clicked.wrong, .clicked.disable.wrong:hover { background-color: red; /* change color when wrong */ } .clicked.right, .disable.right:hover { background-color: green; /* change color when right */ } ``` #### Show correct/incorrect message After clicking an answer, show the user a message below the questions that varies if answer is right or wrong. You must include `<div class="message"> &nbsp; </div>` in an area with the same parent as the answers group. Suggested HTML markup in **index.html**: ``` <div class="questions"> <div class="options"> <div class="answer wrong">Wrong</div> <div class="answer wrong">Wrong</div> <div class="answer right">Right</div> </div> <div class="message"> &nbsp; </div> </div> ``` The message can be modified in **js/check-quiz-answers.js**. ``` // If it's wrong, show this message. $(this).parent().siblings('.message').html('Close, try again.'); ``` ``` // If it's right, show this message. $(this).parent().siblings('.message').html('You got it!'); ``` #### Display message if all answers are correct. Display a modal message if all questions shown are answered correctly. This must be the same number of correct answersfor all quizzes. To modify the number of correct possible answers, change the number (here *3* in **js/check-quiz-answers.js** to whatever you need: `if ($(".right.clicked").length >= 3)`.
558d1799de8cbea72203e92f6e287bc0209b0924
[ "JavaScript", "Markdown" ]
3
JavaScript
thekristin/randomized-quiz-sets
45c1796f2068b43644a304d4b6da268af165700d
3b0c13cd958f8488e126db42e132bc57c1de3d2b
refs/heads/master
<repo_name>gdg-el-paso/github-workshop-1<file_sep>/project-1-sorting/Runner1.java /* * <NAME> Github Workshop * Purpose: To practice insertion sort and merge sort using arrays * Last Modified: 17 April 2019 */ import java.util.Random; public class Runner1 { public static void main(String[] args) { // Demonstrate the code works by generating a random list of 20 boxes, printing // the list before AND sorting using via insertion and merge sort. int numOfBoxes = 20; Box firstArray[] = arrayOfBoxes(numOfBoxes); // Create the array printArrayOfBoxen(firstArray); // Print the list Box copy[] = copyArray(firstArray); // Copy the array Box iSort[] = insertionSort(copy); // Sort via insertion sort // Verify insetionSort is working int i = 0; System.out.println(); System.out.println("After Insertion Sort:"); while (i < numOfBoxes) { System.out.println("The length, width, & height of Box #" + (i + 1) + " are " + (int) iSort[i].length + ", " + (int) iSort[i].width + ", " + (int) iSort[i].height + ", with a volume of " + (int) iSort[i].calculateVolume()); i++; } printArrayOfBoxen(firstArray); // Print the list again Box mSort[] = mergeSort(copy); // Implement merge sort // Verify mergeSort is working int j = 0; // You're in main; int i was already used System.out.println(); System.out.println("After Megre Sort:"); while (j < numOfBoxes) { System.out.println("The length, width, & height of Box #" + (j + 1) + " are " + (int) mSort[j].length + ", " + (int) mSort[j].width + ", " + (int) mSort[j].height + ", with a volume of " + (int) mSort[j].calculateVolume()); j++; } } /** * Generate a random list of boxes for testing. Method should take in (20) the * size of the list and return an array of that many boxes */ public static Box[] arrayOfBoxes(int numOfBoxes) { // Your Code here Box[] boxes = new Box[numOfBoxes]; Random rand = new Random(); for (int i = 0; i < numOfBoxes; i++) { double L = 1 + (10 - 1) * rand.nextDouble(); double W = 1 + (10 - 1) * rand.nextDouble(); double H = 1 + (10 - 1) * rand.nextDouble(); boxes[i] = new Box(L, W, H); } return boxes; } /** * Print the array of boxes. Each line should be the l,w,h && v of a specific * box */ public static void printArrayOfBoxen(Box[] firstArray) { // Your Code here for (int i = 0; i < firstArray.length; i++) { System.out.println("Box " + i); firstArray[i].print(); System.out.println(); } } /** Create a new array of boxes with identical values of the given one */ public static Box[] copyArray(Box[] firstArray) { Box[] boxCopy = new Box[firstArray.length]; int i = 0; while (i < boxCopy.length) { /// Only less than, NOT EQUALS; otherwise nullPointerException error boxCopy[i] = new Box(); // Iniatiate the boxes boxCopy[i].length = (int) (firstArray[i].length); // set them equal to ints boxCopy[i].width = (int) (firstArray[i].width); boxCopy[i].height = (int) (firstArray[i].height); i++; // increment/traverse as you go along } return boxCopy; } /** Sort the boxes using the insertion sort algorithm */ public static Box[] insertionSort(Box[] copy) { // Your Code Here return copy; } /** Sort the boxes using the merge sort algorithm */ /** 1st half of the merge sort algorithm */ public static Box[] mergeSort(Box[] arrayCopy) { if (arrayCopy.length <= 1) // Base case; if 1, array is sorted by default return arrayCopy; Box[] leftHalf = new Box[arrayCopy.length / 2]; // left side will be 1st (1/2) of array |\/ 1/2 via each iteration // |\/ use center as random split Box[] rightHalf = new Box[arrayCopy.length - leftHalf.length]; // right side will be 2nd (1/2) of array |\/ 1/2 via // each iteration System.arraycopy(arrayCopy, 0, leftHalf, 0, leftHalf.length); // copies leftHalf.length-elements of arrayCopy to the // new leftHalf array System.arraycopy(arrayCopy, leftHalf.length, rightHalf, 0, rightHalf.length); // copies rightHalf.length-elements of // arrayCopy to the leftHalf array mergeSort(leftHalf); // recursive calls mergeSort(rightHalf); merge(leftHalf, rightHalf, arrayCopy); // call a second merge method to combine everything togetheer return arrayCopy; } /** 2nd half of the merge-sort algorithm */ private static Box[] merge(Box[] leftHalf, Box[] rightHalf, Box[] modifiedCopy) { int leftCounter = 0, rightCounter = 0; // to traverse through each array int i = 0; // genral counter while (leftCounter < leftHalf.length && rightCounter < rightHalf.length) { // positional; e.g. if i<n |\/ minus the // "i" and ALL ACTUAL NUMBERS!! -_- if (leftHalf[leftCounter].calculateVolume() < rightHalf[rightCounter].calculateVolume()) { modifiedCopy[i] = leftHalf[leftCounter]; // lesser volume boxes to the left leftCounter++; } else { modifiedCopy[i] = rightHalf[rightCounter]; // greater volume boxes to the right rightCounter++; // keep traversing } i++; } return modifiedCopy; } } <file_sep>/README.md ![alt text](https://raw.githubusercontent.com/gdg-el-paso/github-workshop-1/master/img/readme_image.png) # GDG El Paso GitHub Workshop 1 <br /> ## Overview The objective of this workshop is to introduce Git / Github to our local student developers. <br /> Note that this repository contians sample project work where mentors will demo how git works, as well as two projects for students to complete in teams of 3. <br /> ### Project Contributions: 1. <NAME> (github.com/GigaMatt)<br /> 2. <NAME> (github.com/ihuds577)<br /> 3. <NAME> (github.com/nicholasvenecia)<br /> 4. <NAME> (github.com/HiramRios)
90560f67db657f7c859c1e5d0c627901cdbb75ce
[ "Markdown", "Java" ]
2
Java
gdg-el-paso/github-workshop-1
4d80139e649ff3e2cb25e9a133bee18816beb504
5265ca5d6484c42c6d0bea351d94692bc508b2f2
refs/heads/master
<file_sep># -*- coding: utf-8 -*- import threading, serial, time class ComMonitorThread(threading.Thread): def __init__( self, data_q, port_num, port_baud, port_stopbits = serial.STOPBITS_ONE, port_parity = serial.PARITY_NONE, port_timeout = 0.01): threading.Thread.__init__(self) self.serial_port = None self.serial_arg = dict( port = port_num, baudrate = port_baud, stopbits = port_stopbits, parity = port_parity, timeout = port_timeout) self.data_q = data_q self.alive = threading.Event() self.alive.set() def run(self): try: if self.serial_port: self.serial_port.close() self.serial_port = serial.Serial(**self.serial_arg) except serial.SerialException, e: print(e.message) return startTime = time.time() while self.alive.isSet(): Line = self.serial_port.readline() timeStamp = time.time()-startTime self.data_q.put((Line,timeStamp)) if self.serial_port: self.serial_port.close() def join(self,timeout=None): self.alive.clear() self.serial_port.close() threading.Thread.join(self,timeout) <file_sep># -*- coding: utf-8 -*- ''' Serial plotting program - USER INTERFACE By: <NAME> 19/1/2016 This program is written to plot a multiple values sent to PC via serial protocol. The main purpose was to plot values from an MPU6050 IMU. It was used to analyze motion sensing data in order to gain deeper understanding: -raw values from the accelerometer and gyroscope -data from DMP digital motion processor of the MPU6050 -filtered spacial orientation data ''' #Import required libraries import sys from PyQt4 import QtGui, QtCore import pyqtgraph as pg import Queue from globals import LiveDataFeed, get_all_from_queue from comMonitor import ComMonitorThread #Set up a class for drawing the user interface class DataMonitor(QtGui.QMainWindow): #define the contstucotr method def __init__(self): super(DataMonitor,self).__init__() #call initUI method self.initUI() self.livefeed = LiveDataFeed() #declare data variables for plotting self.timeV=0 self.value1=0 self.value2=0 self.value3=0 self.samples = [] self.maxSamples = 550 #here was a ; #define initUI method def initUI(self): #initUI initializes the user interface self.createMainFrame() #declare variables for serial communication self.comPort = "COM4" self.baudRate = "9600" #initialize QTimer self.timer = QtCore.QTimer() #signals and slots for pushbuttons #self.start_btn.clicked.connect(self.onStart) #self.stop_btn.clicked.connect(self.onStop) #self.stop_btn.setEnabled(False) def createMainFrame(self): #createMainFrame creates the user interface layout #LAYOUT CONTROL======================================================= self.resize(840,840) self.setWindowTitle("Serial Monitor") grid = QtGui.QGridLayout() self.setLayout(grid) #START/STOP BUTTON #self.start_btn = QtGui.QPushButton("Start") #self.stop_btn = QtGui.QPushButton("Stop") #GRAPH self.graph = pg.PlotWidget(title="Serial Data Plot") self.graph.setBackground('k') self.graph.plotItem.showGrid(1,1,1) self.curve1 = self.graph.plotItem.plot() self.curve1.setPen(color='g',width=2) self.curve2 = self.graph.plotItem.plot() self.curve2.setPen(color='c',width=2) self.curve3 = self.graph.plotItem.plot() self.curve3.setPen(color='y',width=2) #STATUS BAR self.status_text = QtGui.QLabel("Monitor Idle") self.statusBar().addWidget(self.status_text,1) self.status_text.setStyleSheet("QLabel {color: rgb(200,200,200); font-weight: bold;}") #INSERT WIDGETS INTO THE MAIN FRAME #grid.addWidget(self.start_btn,0,0,1,3) #grid.addWidget(self.stop_btn,1,0,1,3) grid.addWidget(self.graph,2,0,1,3) self.mainFrame = QtGui.QWidget() self.mainFrame.setLayout(grid) self.setCentralWidget(self.mainFrame) #ADD MENU self.createToolbar() #STYLESHEET ''' self.start_btn.setStyleSheet("QPushButton {background-color: rgb(170,170,180);" "border-radius: 4px;" "border-style: solid;" "border-color: black;" "border-width: 1px;" "font-size:20px;}") self.stop_btn.setStyleSheet("QPushButton {background-color: rgb(170,170,180);" "border-radius: 4px;" "border-style: solid;" "border-color: black;" "border-width: 1px;" "font-size:20px;}") ''' self.setStyleSheet("QMainWindow {background-color: rgb(60,60,70)}") self.setWindowIcon(QtGui.QIcon('SP_logo.png')) def createToolbar(self): #Create the toolbar first! toolbar = self.addToolBar('Config') self.startFeed = QtGui.QAction(QtGui.QIcon('START.png'), 'Start', self) self.startFeed.triggered.connect(self.onStart) self.stopFeed = QtGui.QAction(QtGui.QIcon('STOP.png'), 'Stop', self) self.stopFeed.triggered.connect(self.onStop) self.changeComPort = QtGui.QAction(QtGui.QIcon('COMPORT.png'), 'Set Com Port', self) self.changeComPort.triggered.connect(self.showPortDialog) self.changeBaud = QtGui.QAction(QtGui.QIcon('BAUDRATE.png'), 'Set Baud Rate', self) self.changeBaud.triggered.connect(self.showBaudDialog) toolbar.addAction(self.startFeed) toolbar.addAction(self.stopFeed) toolbar.addSeparator() toolbar.addAction(self.changeComPort) toolbar.addAction(self.changeBaud) toolbar.addSeparator() toolbar.setIconSize(QtCore.QSize(70,70)) toolbar.setStyleSheet("QToolBar {background-color: rgb(60,60,70);}") toolbar.setMovable(False) self.stopFeed.setEnabled(False) def showPortDialog(self): text, ok = QtGui.QInputDialog.getText(self, 'Set COM Port', 'Enter COM port:') if ok: self.comPort = str(text) def showBaudDialog(self): text, ok = QtGui.QInputDialog.getText(self, 'Set Baud Rate', 'Enter baud rate:') if ok: self.baudRate = str(text) def onStart(self): self.startFeed.setEnabled(False) self.stopFeed.setEnabled(True) #self.start_btn.setEnabled(False) #self.stop_btn.setEnabled(True) self.isReceiving = True self.data_q = Queue.Queue() self.com_monitor = ComMonitorThread(self.data_q,self.comPort,self.baudRate) self.com_monitor.start() self.timer.timeout.connect(self.onTimer) self.timer.start(10) def onStop(self): self.startFeed.setEnabled(True) self.stopFeed.setEnabled(False) self.status_text.setText("Monitor idle") #self.start_btn.setEnabled(True) #self.stop_btn.setEnabled(False) self.isReceiving = False self.timer.stop() self.com_monitor.join(0.01) def onTimer(self): self.read_serial_data() self.update_monitor() def read_serial_data(self): qdata = list(get_all_from_queue(self.data_q)) if len(qdata) > 0: self.data = qdata self.livefeed.add_data(self.data) def update_monitor(self): if self.livefeed.has_new_data: self.data = self.livefeed.read_data() readings = self.data[0][0] readings = readings.split() readings_size = len(readings) try: self.timeV = float(self.data[0][1]) if (readings_size==1): self.value1=float(readings[0]) elif (readings_size==2): self.value1=float(readings[0]) self.value2=float(readings[1]) elif (readings_size==3): self.value1=float(readings[0]) self.value2=float(readings[1]) self.value3=float(readings[2]) self.status_text.setText("Receiving data") except ValueError: self.status_text.setText("Waiting for the data") self.timeV = 0 self.value1 = 0 self.value2 = 0 self.value3 = 0 self.samples.append((self.timeV,self.value1,self.value2,self.value3)) if len(self.samples) > self.maxSamples: self.samples.pop(0) self.status_text.setText("Receiving data") tdata = [s[0] for s in self.samples] self.graph.setXRange(self.timeV-5,self.timeV) if (readings_size==1): sensorData1 = [s[1] for s in self.samples] self.curve1.setData(tdata,sensorData1) elif (readings_size==2): sensorData1 = [s[1] for s in self.samples] self.curve1.setData(tdata,sensorData1) sensorData2 = [s[2] for s in self.samples] self.curve2.setData(tdata,sensorData2) elif (readings_size==3): sensorData1 = [s[1] for s in self.samples] self.curve1.setData(tdata,sensorData1) sensorData2 = [s[2] for s in self.samples] self.curve2.setData(tdata,sensorData2) sensorData3 = [s[3] for s in self.samples] self.curve3.setData(tdata,sensorData3) ''' def showDialog(self): CPR = QtGui.QDialog(self) CPR.setWindowTitle('Com Port Setting') CPR.resize(150,80) gridCP = QtGui.QGridLayout(CPR) okBtn = QtGui.QPushButton('OK') CP_label = QtGui.QLabel(CPR) CP_label.setText('Enter COM port:') CP_le = QtGui.QLineEdit(CPR) gridCP.addWidget(okBtn,2,0,1,2) gridCP.addWidget(CP_label,0,0,1,1) gridCP.addWidget(CP_le,1,0,1,2) #STYLESHEETS ========================================================= CPR.setStyleSheet("QDialog {background-color: rgb(60,60,70)}") CP_label.setStyleSheet("QLabel {color: rgb(200,200,200);" "font-size: 20px;}") okBtn.setStyleSheet("QPushButton {background-color: rgb(170,170,180);" "border-radius: 4px;" "border-style: solid;" "border-color: black;" "border-width: 1px;" "font-size:20px;}") # ==================================================================== CPR.exec_() ''' #define main() function def main(): #start the QT application app = QtGui.QApplication(sys.argv) #construct an object from interface class dataMonitor = DataMonitor() dataMonitor.show() #exit system sys.exit(app.exec_()) #call the main function if __name__ == '__main__': main()<file_sep># -*- coding: utf-8 -*- import Queue class LiveDataFeed(object): """ A simple "live data feed" abstraction that allows a reader to read the most recent data and find out whether it was updated since the last read. Interface to data writer: add_data(data): Add new data to the feed. Interface to reader: read_data(): Returns the most recent data. has_new_data: A boolean attribute telling the reader whether the data was updated since the last read. """ def __init__(self): self.cur_data = None self.has_new_data = False def add_data(self, data): self.cur_data = data self.has_new_data = True def read_data(self): self.has_new_data = False return self.cur_data def get_all_from_queue(Q): """ Generator to yield one after the others all items currently in the queue Q, without any waiting. """ try: while True: yield Q.get_nowait() except Queue.Empty: raise StopIteration <file_sep># Serial-Graphing-Monitor-Python Serial Graphing Monitor - Python 2.7</b> is used to visualize the data sent via serial communication. I use it to analyze the data sent from the MPU6050 IMU connected to Arduino. Current code is written for Python 2.7. If you want to run it on Python 3 you need to change a couple of things (For example: -Py 2: from Queue import Queue -Py 3: from queue import queue). <div align="center"> <img src="Monitor.jpg" height="500"> </div> In order to run the code you need to install the following libraries: <ul> <li>PyQtGraph</li> <li>PyQt 4.8+ or PySide</li> <li>NumPy</li> <li>PySerial</li> </ul> Place the following files in a folder: <ul> <li>DataMonitor.py</li> <li>globals.py</li> <li>ComMonitor.py</li> <li>SP_logo.png</li> <li>COMPORT.png</li> <li>BAUDRATE.png</li> </ul> To start the program run DataMonitor.py. The program is written to receive maximum three separate values at a time from serial. For now it is programmed so all three values need to be packed in a single line, for example, if you want to plot readings from all X, Y, and Z accelerometer axis you should write them to serial like this "AccX AccY AccZ\n". If only one or two values are written to serial, then only one or two data sets will be plotted. Code was inspired by <a href="https://github.com/mba7/SerialPort-RealTime-Data-Plotter"> MBA7's SerialPort-RealTime-Data-Plotter </a> and <a href="http://eli.thegreenplace.net/2009/08/07/a-live-data-monitor-with-python-pyqt-and-pyserial/"> Eli Bendersky work</a>.
55034b505b6114e4a1f2837c21e0d8dfc6a70741
[ "Markdown", "Python" ]
4
Python
axkralj990/Serial-Graphing-Monitor-Python
ea21746a9877b725339fb8c13d39e2b365ef2355
0b953b548f77238d287351f1c6d877e9556f06f9
refs/heads/master
<file_sep>// // ViewController.swift // WordGame // // Created by <NAME> on 2/27/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit /** * Delegate for swipe actions */ protocol SwipeDelegate { func determineSwipePosition(sender: UIView, location: CGPoint) func swipeEnded(sender: UIView) } /** * Delegate for determining the validity of a submitted word */ protocol ValidWordDelegate { func validWord(_ isTrue: Bool) } /** * Controller that delgates between the HighlightCollectionView and the GameModel * comprised of Letter Cells */ class GameViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, SwipeDelegate { var validDelegate: ValidWordDelegate? private var word: [String] = [] private var wordCells: [LetterCell] = [] private var lastWordAdded: String = "" private var highlightedIndexs: [Int] = [] private var firstLayout: Bool = false override func viewDidLoad() { /* On load register every cell and generate the highlighted numbers */ super.viewDidLoad() let layout = UICollectionViewFlowLayout() let highlightView = HighlightCollectionView(frame: view.frame, collectionViewLayout: layout) self.generateHighlitedIndexes() validDelegate = highlightView highlightView.swipeDelegate = self collectionView = highlightView collectionView?.allowsMultipleSelection = true collectionView?.register(LetterCell.self, forCellWithReuseIdentifier: "letterCell") navigationItem.rightBarButtonItem = UIBarButtonItem(title: "New", style: .plain, target: self, action: #selector(newGame)) } func determineSwipePosition(sender: UIView, location: CGPoint) { /* Determines what letter is being played based on 'location' */ /* Each block is about 35px away on Iphone 8, which is roughly its height(568) / 16.0 and its width(320) / 9 */ let row: Int = Int(location.y) / Int(view.frame.height / 16) let col: Int = Int(location.x) / Int(view.frame.width / 9) if (row < 12 && col < 9) { let index = row * 9 + col let indexP = IndexPath(row: index, section: 0) let letterCell = collectionView?.cellForItem(at: indexP) as! LetterCell // Removes Duplicates if(letterCell.charPreviouslyAdded == false && self.lastWordAdded != letterCell.letterLabel.text!) { letterCell.letterLabel.textColor = UIColor.orange self.word.append(letterCell.letterLabel.text!) wordCells.append(letterCell) letterCell.charPreviouslyAdded = true self.lastWordAdded = letterCell.letterLabel.text! } // BackSwipe Logic else if (self.lastWordAdded != letterCell.letterLabel.text!) { letterCell.charPreviouslyAdded = false letterCell.letterLabel.textColor = UIColor.black let _ = self.word.popLast() let _ = self.wordCells.popLast() if (self.word.count > 0) { self.lastWordAdded = self.word[self.word.count - 1] } else { self.word = [] } print(self.word) } } let str: String = self.word.joined() if(GameModel.checkValidWord(str)) { self.validDelegate?.validWord(true) } else { self.validDelegate?.validWord(false) } } func swipeEnded(sender: UIView) { /* When swipe has ended, submit the word to the GameModel and reset */ // Check Word accuracy, delete and then reset let str: String = self.word.joined() if (GameModel.checkValidWord(str)) { self.validDelegate?.validWord(true) // Sort by row (needed for removal) self.wordCells.sort(by: {$0.row! < $1.row!}) for i in wordCells { print("row: \(i.row!) col: \(i.column!)") GameModel.removeLetter(row: i.row!, column: i.column!, isHighlighted: i.highlightedLetter) } } else { self.validDelegate?.validWord(false) } print(self.word) self.word = [] self.wordCells = [] // Reset all cells back to default values for i in 0...107 { let indexP = IndexPath(row: i, section: 0) let letterCell = collectionView?.cellForItem(at: indexP) as! LetterCell letterCell.letterLabel.textColor = UIColor.black letterCell.charPreviouslyAdded = false self.lastWordAdded = "" } collectionView?.reloadData() } private func generateHighlitedIndexes(){ /* Generate Random Indexes that are the highlighted letters*/ var previousNumber: UInt32 = 0 var randomNumber: UInt32 = 0 for _ in 0...3 { randomNumber = arc4random_uniform(UInt32(GameModel.getLetterCount())) if (randomNumber != previousNumber) { self.highlightedIndexs.append(Int(randomNumber)) } previousNumber = randomNumber } } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { /* Amount of cells = 108 */ return GameModel.getLetterCount() } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { /* Each cell should be this size */ return CGSize(width: view.frame.width / 13.5 , height: view.frame.height / 22.0) } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { /* Each cell is a new LetterCell with its label corresponding to GameModel */ let letterCell = collectionView.dequeueReusableCell(withReuseIdentifier: "letterCell", for: indexPath) as! LetterCell //TODO: Probably have to move this to the controller. if (highlightedIndexs.contains(indexPath.row)) { letterCell.highlightedLetter = true letterCell.letterLabel.textColor = UIColor(red:1.00, green:0.87, blue:0.15, alpha:1.0) } letterCell.column = indexPath.row % 9 letterCell.row = (indexPath.row - letterCell.column!) / 9 letterCell.letterLabel.text = GameModel.get(at: indexPath.row).rawValue letterCell.scoreLabel.text = "\(GameModel.getLetterScore(letterCell.letterLabel.text!))" return letterCell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @objc func newGame() { /* On a new game, remove highlighted indexes, reset all game defaults and rebuild board */ for i in highlightedIndexs { let indexP = IndexPath(row: i, section: 0) let letterCell = collectionView?.cellForItem(at: indexP) as! LetterCell letterCell.letterLabel.textColor = UIColor.black letterCell.highlightedLetter = false } firstLayout = false self.highlightedIndexs.removeAll() self.generateHighlitedIndexes() GameModel.buildBoard() collectionView?.reloadData() } } <file_sep>// // HighlightCollectionView.swift // WordGame // // Created by <NAME> on 3/5/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit /** * Represents the top layer of the collection view that is transparent * and sends drag information through the swipe delegate */ class HighlightCollectionView: UICollectionView, ValidWordDelegate{ var swipeDelegate: SwipeDelegate? private var lineStart: CGPoint? private var lines: [CGPoint] = [] var lineColor: CGColor = UIColor.yellow.cgColor override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) self.backgroundColor = UIColor(red:0.91, green:0.95, blue:0.96, alpha:1.0) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func validWord(_ isTrue: Bool) { /* Checks if the word is valid and adjusts the line color */ if(isTrue) { lineColor = UIColor(red:1.00, green:0.87, blue:0.15, alpha:1.0).cgColor } else { lineColor = UIColor(red:0.10, green:0.54, blue:0.67, alpha:1.0).cgColor } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) let touch: UITouch = touches.first! lineStart = touch.location(in: self) swipeDelegate?.determineSwipePosition(sender: self, location: lineStart!) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) let touch: UITouch = touches.first! let touchPoint = touch.location(in: self) let row: Int = Int(touchPoint.y) / Int(frame.height / 16) let col: Int = Int(touchPoint.x) / Int(frame.width / 9) print(touchPoint) print("Row: \(row) col \(col)") //lines.append(touchPoint) lines.append(CGPoint(x: CGFloat(col) * frame.height / 16.0 + frame.height / 32.0, y: CGFloat(row) * frame.width / 9.0 + frame.width / 18.0)) self.setNeedsDisplay() swipeDelegate?.determineSwipePosition(sender: self, location: touchPoint) } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { lines = [] self.setNeedsDisplay() swipeDelegate?.swipeEnded(sender: self) } override func draw(_ rect: CGRect) { super.draw(rect) let context = UIGraphicsGetCurrentContext()! context.setLineJoin(.round) context.setLineCap(.round) context.setStrokeColor(UIColor(red:0.10, green:0.54, blue:0.67, alpha:1.0).cgColor) context.setFillColor(UIColor(red:0.10, green:0.54, blue:0.67, alpha:1.0).cgColor) context.setLineWidth(3) // Draw the vertical lines for i in 0...10 { let num: CGFloat = CGFloat(i); context.move(to: CGPoint(x: num * bounds.width / 9.0, y: 0.0)) context.addLine(to: CGPoint(x: num * bounds.width / 9.0, y: 12 * bounds.height / 16.0)) context.strokePath() } // Draw the horizontal for i in 0...12 { let num: CGFloat = CGFloat(i); context.move(to: CGPoint(x: 0.0, y: num * bounds.height / 16.0)) context.addLine(to: CGPoint(x: bounds.width, y: num * bounds.height / 16.0)) context.strokePath() } /* context.setFillColor(UIColor.black.cgColor) for i in 0...10 { context.fillEllipse(in: CGRect(x: bounds.width / 9.0 + bounds.width / 108.0, y: bounds.height / 16.0 + bounds.height / 160.0, width: bounds.width / 10.5, height: bounds.width / 10.5)) } */ // Draw Score and Longest Word Elements let lowerBounds = 14 * bounds.height / 16.0 let scoreString: NSString = NSString(string: "Score:") scoreString.draw(at: CGPoint(x: bounds.width / 10.0 , y: lowerBounds - bounds.height / 26.0), withAttributes: [:]) let score: NSString = NSString(string: "\(GameModel.score)") score.draw(at: CGPoint(x: 3 * bounds.width / 10.0 , y: lowerBounds - bounds.height / 26.0), withAttributes: [:]) context.strokePath() let longestWordString: NSString = NSString(string: "Longest Word:") longestWordString.draw(at: CGPoint(x: 4 * bounds.width / 10.0 , y: lowerBounds - bounds.height / 26.0), withAttributes: [:]) let longestWord: NSString = NSString(string: "\(GameModel.longestWord)") longestWord.draw(at: CGPoint(x: 7 * bounds.width / 10.0 , y: lowerBounds - bounds.height / 26.0), withAttributes: [:]) // Draw line that traces the current swipe if let point = lineStart { context.move(to: point) context.setStrokeColor(lineColor) context.setLineWidth(10) for i in lines { context.addLine(to: i) context.strokePath() context.move(to: i) } } } } <file_sep>// // LetterCell.swift // WordGame // // Created by <NAME> on 3/5/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit /** * Reperesents a Cell in a collection view that has one unique element * in its letter label */ class LetterCell: UICollectionViewCell { var row: Int? var column: Int? var charPreviouslyAdded: Bool = false var highlightedLetter: Bool = false override init(frame: CGRect) { super.init(frame: frame) self.isUserInteractionEnabled = true setupViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } let letterLabel: UILabel = { let letterLabel = UILabel() letterLabel.text = "A" letterLabel.font = UIFont(name: "HelveticaNeue", size: 18) letterLabel.textColor = UIColor(red:0.16, green:0.24, blue:0.34, alpha:1.0) letterLabel.adjustsFontSizeToFitWidth = true; letterLabel.translatesAutoresizingMaskIntoConstraints = false return letterLabel }() let scoreLabel: UILabel = { let scoreLabel = UILabel() scoreLabel.text = "0" scoreLabel.font = UIFont(name: "HelveticaNeue", size: 8) scoreLabel.textColor = UIColor(red:0.16, green:0.24, blue:0.34, alpha:1.0) scoreLabel.adjustsFontSizeToFitWidth = true; scoreLabel.translatesAutoresizingMaskIntoConstraints = false return scoreLabel }() func setupViews() { addSubview(letterLabel) addSubview(scoreLabel) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-1-[v0]-1-[v1]-1-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": letterLabel, "v1": scoreLabel])) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-1-[v1]-1-[v0]-1-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": letterLabel, "v1": scoreLabel])) } } <file_sep>// // Game.swift // WordGame // // Created by <NAME> on 2/27/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation /* Represents All Letters String representations */ enum Letters: String { case Blank = "-" case Clear = "" case A = "A" case B = "B" case C = "C" case D = "D" case E = "E" case F = "F" case G = "G" case H = "H" case I = "I" case J = "J" case K = "K" case L = "L" case M = "M" case N = "N" case O = "O" case P = "P" case Q = "Q" case R = "R" case S = "S" case T = "T" case U = "U" case V = "V" case W = "W" case X = "X" case Y = "Y" case Z = "Z" } class GameModel { // Letters available to be placed public static let letterBank: [Letters] = [.Blank, .A, .B, .C, .D, .E, .F, .G, .H, .I, .J, .K, .L, .M, .N, .O, .P, .Q, .R, .S, .T, .U, .V, .W, .X, .Y, .Z] // Each letters score value (scrabble rules) private static let wordScore: [String: Int] = ["": 0, "_": 0, "A": 1, "B": 3, "C": 3, "D": 2, "E": 1, "F": 4, "G": 2, "H": 4, "I": 1, "J": 8, "K": 5, "L": 1, "M": 3, "N": 1, "O": 1, "P": 3, "Q": 10, "R": 1, "S": 1, "T": 1, "U": 1, "V": 4, "W": 4, "X": 8, "Y": 4, "Z": 10] private static var board: [Letters] = [] static var wordsOnBoard: [String] = [] private static var wordsInDict: [String] = [] private static let letterCount = 98 static var score: Int = 0 static var longestWord: String = "" private static var selectedLetters: [String] = [] static func insert(char: Letters, x: Int, y: Int) { board.insert(char, at: (y * 12) + x) } static func get(at indexPath: Int) -> Letters { return board[indexPath] } static func getLetterCount() -> Int { return board.count } static func buildBoard() { longestWord = "" wordsOnBoard = [] getWordsFromDictFile() score = 0 board = [] /* for _ in 0...107 { board.append(Letters.Clear) } var blankCounter = 0 while(blankCounter < 10) { let index = randomIndex() if board[index] == Letters.Clear { board[index] = Letters.Blank blankCounter += 1 } } var index = 0 // Actual Index var previousIndex = 0 // Index of last placed letter var attempts = 0 while(index < 98) { while(board[index] != Letters.Clear && index < 98) { index += 1 } for word in wordsOnBoard { let strWord = String(word).uppercased() var wordIndex = 0 previousIndex = index for letter in strWord { print("Index: \(index) Letter: \(letter) Word: \(strWord)") // Place the first letter of the word @ the actual index if (wordIndex == 0) { board[index] = Letters(rawValue: "\(letter)")! index += 1 wordIndex += 1 continue } var letterHasBeenPlaced = false let indexColumn = previousIndex % 9 let indexRow = (previousIndex - indexColumn) / 9 while(letterHasBeenPlaced == false) { let direction = self.randomDirection() switch direction { /* case 0: if(indexRow > 0 && indexColumn > 1 && board[previousIndex - 10] == Letters.Clear) { board[previousIndex - 10] = Letters(rawValue: "\(letter)")! letterHasBeenPlaced = true previousIndex += -10 }*/ /* case 1: if(indexRow > 0 && board[previousIndex - 9] == Letters.Clear) { board[previousIndex - 9] = Letters(rawValue: "\(letter)")! letterHasBeenPlaced = true previousIndex += -9 } */ /* case 2: if(indexRow > 0 && indexColumn < 9 && board[previousIndex - 8] == Letters.Clear) { board[previousIndex - 8] = Letters(rawValue: "\(letter)")! letterHasBeenPlaced = true previousIndex += -8 } */ /* case 3: if(indexColumn > 0 && board[previousIndex - 1] == Letters.Clear) { board[previousIndex - 1] = Letters(rawValue: "\(letter)")! letterHasBeenPlaced = true previousIndex += -1 } */ case 4: if(indexColumn < 8 && board[previousIndex + 1] == Letters.Clear) { board[previousIndex + 1] = Letters(rawValue: "\(letter)")! letterHasBeenPlaced = true previousIndex += 1 index += 1 } /* case 5: if(indexRow < 11 && indexColumn > 0 && board[previousIndex + 8] == Letters.Clear) { board[previousIndex + 8] = Letters(rawValue: "\(letter)")! letterHasBeenPlaced = true previousIndex += 8 } */ case 6: if(indexRow < 11 && board[previousIndex + 9] == Letters.Clear) { board[previousIndex + 9] = Letters(rawValue: "\(letter)")! letterHasBeenPlaced = true previousIndex += 9 } /* case 7: if(indexRow < 11 && indexColumn < 8 && board[previousIndex + 10] == Letters.Clear) { board[previousIndex + 10] = Letters(rawValue: "\(letter)")! letterHasBeenPlaced = true previousIndex += 10 } */ default: if(1 != 1) { print("") } } } wordIndex += 1 } index += 1 } } */ for word in wordsOnBoard { let strWord = String(word) for i in strWord.uppercased() { board.append(Letters(rawValue: "\(i)")!) } } for i in 0...9 { board.append(Letters.B) } /* for i in 0...107 { board.append() } */ } static func removeLetter(row: Int, column: Int, isHighlighted: Bool) { var currentRow: Int = row var currrentColumn: Int = 9 var currentIndex = row * 9 + column let scoreLetter = self.board[currentIndex] if let letterScore = self.wordScore[scoreLetter.rawValue] { self.score += letterScore } self.board[currentIndex] = Letters.Clear self.clearBanks(row: currentRow, col: column) if(isHighlighted) { while(currrentColumn > 0) { while(currentRow > 0) { currentIndex = currentRow * 9 + currrentColumn self.board[currentIndex] = self.board[currentIndex - 9] currentRow -= 1 } currentRow = row self.board[currrentColumn] = Letters.Clear currrentColumn -= 1 } self.score += 10 } else { while(currentRow > 0) { currentIndex = currentRow * 9 + column self.board[currentIndex] = self.board[currentIndex - 9] currentRow -= 1 } self.board[column] = Letters.Clear } } private static func clearBanks(row: Int, col: Int) { let currentIndex = row * 9 + col if (col == 8) { if(self.board[currentIndex - 1] == Letters.Blank) { self.board[currentIndex - 1] = Letters.Clear } } else if (col == 0) { if (self.board[currentIndex + 1] == Letters.Blank) { self.board[currentIndex - 1] = Letters.Clear } } else { if(self.board[currentIndex - 1] == Letters.Blank) { self.board[currentIndex - 1] = Letters.Clear } else if (self.board[currentIndex + 1] == Letters.Blank) { self.board[currentIndex - 1] = Letters.Clear } } if (row == 11) { if(self.board[currentIndex - 9] == Letters.Blank) { self.board[currentIndex - 9] = Letters.Clear } } else if (row == 0) { if (self.board[currentIndex + 9] == Letters.Blank) { self.board[currentIndex + 9] = Letters.Clear } } else { if (self.board[currentIndex - 9] == Letters.Blank) { self.board[currentIndex - 9] = Letters.Clear } else if (self.board[currentIndex + 9] == Letters.Blank) { self.board[currentIndex + 9] = Letters.Clear } } } static func getWordsFromDictFile() { //TODO: ADD RELATIVE PATH let path = "/Users/bennagel/Documents/S18/cs4530/WordGame/WordGame/dict.txt" do { let contents = try? String(contentsOfFile: path, encoding: .ascii) if contents != nil { wordsInDict = (contents?.components(separatedBy: "\n"))! } } var currentLetterCount: Int = 0 while(currentLetterCount < self.letterCount) { let randomIndex = Int(arc4random_uniform(UInt32(wordsInDict.count))) //print("Trying: \(wordsInDict[randomIndex].count)") print("CLC: \(currentLetterCount) + \(wordsInDict[randomIndex].count) =\(self.letterCount)") if(currentLetterCount + wordsInDict[randomIndex].count <= self.letterCount && currentLetterCount + wordsInDict[randomIndex].count != self.letterCount - 1) { //print("Count: \(currentLetterCount)") wordsOnBoard.append(wordsInDict[randomIndex]) currentLetterCount += wordsInDict[randomIndex].count } } } static func checkValidWord(_ word: String) -> Bool { let lowerCaseWord = word.lowercased() if(wordsInDict.contains("_") || wordsInDict.contains("''")) { return false } for i in wordsInDict { if (i == lowerCaseWord) { if(lowerCaseWord.count > self.longestWord.count) { self.longestWord = lowerCaseWord.uppercased() } return true } } return false } static func randomLetter() -> Letters { // pick and return a new value let rand = arc4random_uniform(UInt32(letterBank.count)) return letterBank[Int(rand)] } static func randomIndex() -> Int { let rand = arc4random_uniform(UInt32(108)) return Int(rand) } static func randomDirection() -> Int { let rand = arc4random_uniform(UInt32(8)) return Int(rand) } static func getLetterScore(_ letter: String) -> Int { return self.wordScore[letter]! } static func insertSelected(letter: String) { selectedLetters.append(letter) } static func checkWordsSelected() { print(selectedLetters) selectedLetters = [] } } <file_sep>// // GameView.swift // WordGame // // Created by <NAME> on 2/27/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class GameView: UIView { private var score: NSString = "0" private var letters: [String: [Int]] = [:] private var context: CGContext? private var lineStart: CGPoint? private var lines: [CGPoint] = [] override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.white } required init?(coder aDecoder: NSCoder) { fatalError() } func setScore(_ score:Int) { self.score = NSString(string: "\(score)") } func setLineStart(row: Int, col: Int) { lineStart = CGPoint(x: CGFloat(col + 1) * bounds.width / 9.0 - bounds.width / 18.0, y: CGFloat(row + 1) * bounds.height / 16.0 + bounds.height / 19.0 + bounds.height / 32.0) } func startIsSet() -> Bool { if lineStart != nil { return true } return false } func appendtoLines(row: Int, col: Int) { let line = CGPoint(x: CGFloat(col + 1) * bounds.width / 9.0 - bounds.width / 18.0, y: CGFloat(row + 1) * bounds.height / 16.0 + bounds.height / 19.0 + bounds.height / 32.0) lines.append(line) } override func draw(_ rect: CGRect) { super.draw(rect) context = UIGraphicsGetCurrentContext()! context!.setStrokeColor(UIColor.lightGray.cgColor) context?.setLineWidth(3) // 9x12 grid for i in 1...10 { let num: CGFloat = CGFloat(i * 1); context!.move(to: CGPoint(x: num * bounds.width / 9.0, y: bounds.height / 16.0)) context!.addLine(to: CGPoint(x: num * bounds.width / 9.0, y: 13 * bounds.height / 16.0 + bounds.height / 19.0)) context!.strokePath() } for i in 1...13 { let num: CGFloat = CGFloat(i * 1); context!.move(to: CGPoint(x: 0.0, y: num * bounds.height / 16.0 + bounds.height / 19.0)) context!.addLine(to: CGPoint(x: bounds.width, y: num * bounds.height / 16.0 + bounds.height / 19.0)) context!.strokePath() } // Draw Score and Score String let lowerBounds = 12 * bounds.height / 12.0 let scoreString: NSString = NSString(string: "Score:") scoreString.draw(at: CGPoint(x: bounds.width / 10.0 , y: lowerBounds - bounds.height / 26.0), withAttributes: [:]) score.draw(at: CGPoint(x: bounds.width / 3.0 , y: lowerBounds - bounds.height / 26.0), withAttributes: [:]) context?.strokePath() // Draw Line //let lineEnd: CGPoint = CGPoint(x: CGFloat(5 + 1) * bounds.width / 9.0 - bounds.width / 18.0, y: CGFloat(5 + 1) * bounds.height / 16.0 + bounds.height / 19.0 + bounds.height / 32.0) if let point = lineStart { context!.move(to: point) context?.setStrokeColor(UIColor.yellow.cgColor) context?.setLineWidth(10) for i in lines { context?.addLine(to: i) context?.strokePath() context?.move(to: i) } } /* for i in self.letters.keys { let letter: NSString = NSString(string: i) if let arr = self.letters[i] { for j in 0...arr.count - 1 { let x: CGFloat = CGFloat(self.letters[i]![j] % 12) let y: CGFloat = (CGFloat(self.letters[i]![j]) - CGFloat(x)) / 12 let attrs = [NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Thin", size: 24)!] letter.draw(at: CGPoint(x: x * bounds.width / 9.0 + bounds.width / 27.0 , y: y * bounds.height / 16.0), withAttributes: attrs) } } } */ } }
550ba077b990c064d43f7861f4abebd21cce7cf6
[ "Swift" ]
5
Swift
Bnagel25/WordGame
2766e8568bf18d40c284b1bcbb2ccba18b394390
720a141f34f9ffc661da9e565ec196551dac4d45
refs/heads/master
<repo_name>Carrotsssw/nestjs-boilerplate<file_sep>/src/api.modules/order/order.service.ts import { Injectable } from '@nestjs/common'; import { IOrder } from './interfaces/order.interface'; @Injectable() export class OrderService { async getOrder(query): Promise<IOrder[]> { let result = new Promise<IOrder[]>((resolve) => { resolve([{ id: 'test001', net: '677.00', order_item: [{ id: '12033', product_sku_id: '9123', product_sku_name: 'Blue Shirt', product_sku_amount: '1.00' }], status: 1, create_time: "2019-01-10T10:36:21.000Z", update_time: "2019-01-10T10:36:21.000Z", }]) }) return result } async createOrder(payload): Promise<Object> { return { code: 200, success: true }; } }<file_sep>/src/server.ts import 'dotenv/config'; import { NestFactory } from '@nestjs/core'; import { AppModule } from './main.module/main.module'; import { Logger } from '@nestjs/common'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.enableCors(); await app.listen(process.env.HTTP_PORT || 5555); Logger.log(`Server running on http://localhost:${process.env.HTTP_PORT}`, 'Bootstrap'); } bootstrap(); <file_sep>/src/main.module/main.module.ts import { Module } from '@nestjs/common'; import { AppController } from './main.controller'; import { AppService } from './main.service'; import { APP_INTERCEPTOR } from '@nestjs/core'; import { MorganModule, MorganInterceptor } from 'nest-morgan'; import { ConfigModule } from '../config/config.module'; import { ApiModule } from '../api.modules/api.module'; let morganMode: string; switch (process.env.NODE_ENV) { case 'dev': case 'staging': morganMode = 'dev'; break; default: morganMode = 'common'; } @Module({ imports: [ MorganModule.forRoot(), ConfigModule, ApiModule, ], controllers: [AppController], providers: [ AppService, { provide: APP_INTERCEPTOR, // morgan minimal output(tiny) // :method :url :status :res[content-length] - :response-time ms useClass: MorganInterceptor(morganMode) }, ], }) export class AppModule { constructor() { } } <file_sep>/src/api.modules/shared/api.interface.ts export abstract class IApi { prefix: string; // abstract test(): void; // test2():number { // return 123123; // } }<file_sep>/src/api.modules/api.module.ts import { APP_FILTER, APP_INTERCEPTOR } from '@nestjs/core'; import { Module } from '@nestjs/common'; import { HttpExceptionFilter } from './shared/http-exception.filter'; import { UserModule } from './user/user.module'; import { OrderModule } from './order/order.module'; const importExport = [ UserModule, OrderModule, ]; @Module({ imports: [ ...importExport ], providers: [ { provide: APP_FILTER, useClass: HttpExceptionFilter }, ], exports: [ ...importExport ], }) export class ApiModule {}<file_sep>/src/api.modules/order/order.controller.ts import { Controller, Get, Post, Query, Param, Headers, Body } from '@nestjs/common'; import { OrderService } from './order.service'; import { IApi } from '../shared/api.interface'; import { IOrder } from './interfaces/order.interface'; @Controller('order') export class OrderController extends IApi { constructor(private readonly orderService: OrderService) { super() this.prefix = 'hello' } @Get() getOrder(@Query() query): Promise<IOrder[]> { return this.orderService.getOrder(query); } @Post() createOrder(@Body() order: IOrder): Promise<Object> { return this.orderService.createOrder(order); } } <file_sep>/src/api.modules/order/test/order.controller.spec.ts import { Test, TestingModule } from '@nestjs/testing'; import { OrderController } from '../order.controller'; import { OrderService } from '../order.service'; describe('Order Controller', () => { let controller: OrderController; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ components: [OrderService], controllers: [OrderController], }).compile(); controller = module.get<OrderController>(OrderController); }); describe('test getOrder', () => { test('getOrder should be defined', () => { expect(controller.getOrder).toBeDefined(); }); // TODO: check query value if-else test('getOrder call return value', async () => { const result = [{ id: 'O0119M8OJWI00028', url: 'WPQD7T8', net: '677.00', order_item: [{ id: '16009938', product_sku_id: '2108339', product_sku_name: 'retestJa', product_sku_amount: '1.00' }], status: 1, create_time: "2019-01-10T10:36:21.000Z", update_time: "2019-01-10T10:36:21.000Z", }]; expect.assertions(1); expect(await controller.getOrder({current_state: 'pending'})).toEqual(result); }); }); }); <file_sep>/src/api.modules/order/interfaces/order.interface.ts export interface IOrderItem { id: string; product_sku_id: string; product_sku_name: string; product_sku_amount: string; } export interface IOrder { id: string; net: string; order_item: Array<IOrderItem> status: number; create_time: string; update_time: string; }
0971d04cbdda7e942128e8d673b4a4da2a84dac8
[ "TypeScript" ]
8
TypeScript
Carrotsssw/nestjs-boilerplate
9efd5f7dd67dad465c3efaad501ae0669920dbf3
ce520316c2df7f624dbf32c2422a6390f921a366
refs/heads/master
<repo_name>WilliamsOhworuka/Tic-tac-toe<file_sep>/src/Components/Container/Container.js import React, { useContext } from 'react'; import Board from '../Board/Board'; import { BoardSearchContext } from '../Context/BoardContext'; import Dropdown from '../Dropdown/Dropdown'; import Result from '../Result/Result'; import './Container.scss'; const Container = () => { let result; const dificulty = [{ text: 'Easy', value: 2 }, { text: 'Medium', value: 4 }, { text: 'Hard', value: -1 }]; const starting = [{ text: 'Human', value: 1 }, { text: 'Computer', value: 0 }]; const { setOptions, handleReset, winner, } = useContext(BoardSearchContext); if (winner) { result = winner === 1 ? <Result exclamation="Horray" emoji="https://img.icons8.com/color/70/000000/confetti.png" text="You win" /> : <Result exclamation="Well played" emoji="https://img.icons8.com/cute-clipart/70/000000/facebook-like.png" text="Its a DRAW" />; } else { result = winner === 0 ? <Result exclamation="Sorry" emoji="https://img.icons8.com/dusk/70/000000/sad.png" text="You Lose" /> : null; } return ( <div className="gameContainer"> <div className="controls"> <Dropdown type="Starting Player" defaultValue={starting[0].text} options={starting} setState={setOptions} id="turns" /> <Dropdown type="Difficulty" defaultValue={dificulty[0].text} options={dificulty} setState={setOptions} id="depth" /> <button type="button" onClick={handleReset} data-testid="New Game"> New Game </button> </div> <Board /> {result} </div> ); }; export default Container; <file_sep>/src/Utils/Player.js import Board from './Board'; class Player { constructor(maxDepth = -1) { this.max_depth = maxDepth; this.nodes_map = new Map(); } getBestMove(board, maximizing = true, callback = () => {}, depth = 0) { if (depth === 0) this.nodes_map.clear(); if (board.isTerminal() || depth === this.max_depth) { if (board.isTerminal().winner === 'x') { return 100 - depth; } if (board.isTerminal().winner === 'o') { return -100 + depth; } return 0; } // Current player is maximizing if (maximizing) { let best = -100; board.getAvailableMoves().forEach((index) => { const child = new Board([...board.state]); child.insert('x', index); const nodeValue = this.getBestMove(child, false, callback, depth + 1); best = Math.max(best, nodeValue); if (depth === 0) { const moves = this.nodes_map.has(nodeValue) ? `${this.nodes_map.get(nodeValue)},${index}` : index; this.nodes_map.set(nodeValue, moves); } }); if (depth === 0) { let ret; if (typeof this.nodes_map.get(best) === 'string') { const arr = this.nodes_map.get(best).split(','); const rand = Math.floor(Math.random() * arr.length); ret = arr[rand]; } else { ret = this.nodes_map.get(best); } callback(ret); return ret; } return best; } if (!maximizing) { let best = 100; board.getAvailableMoves().forEach((index) => { const child = new Board([...board.state]); child.insert('o', index); const nodeValue = this.getBestMove(child, true, callback, depth + 1); best = Math.min(best, nodeValue); if (depth === 0) { const moves = this.nodes_map.has(nodeValue) ? `${this.nodes_map.get(nodeValue)},${index}` : index; this.nodes_map.set(nodeValue, moves); } }); if (depth === 0) { let ret; if (typeof this.nodes_map.get(best) === 'string') { const arr = this.nodes_map.get(best).split(','); const rand = Math.floor(Math.random() * arr.length); ret = arr[rand]; } else { ret = this.nodes_map.get(best); } callback(ret); return ret; } return best; } return undefined; } } export default Player; <file_sep>/src/Components/Board/Cell/Cell.jsx /* eslint-disable jsx-a11y/no-static-element-interactions */ /* eslint-disable jsx-a11y/click-events-have-key-events */ import React from 'react'; const Cell = ({ className, id, onClick, children, testId, }) => ( <div data-testid={testId} className={className} id={id} key={`${id}#`} onClick={onClick}>{children}</div> ); export default Cell; <file_sep>/src/Components/Context/BoardContext.js import React, { useState, createContext } from 'react'; import PropType from 'prop-types'; import controls from '../../Utils/Controls'; export const BoardSearchContext = createContext(); const BoardContextProvider = ({ children }) => { const initialBoard = ['', '', '', '', '', '', '', '', '']; const [clicked, setClicked] = useState([false, false, false, false, false, false, false, false, false]); const [board, setBoard] = useState(initialBoard); const [winCoords, setWinCoords] = useState(null); const [depth, setDepth] = useState(2); const [starting, setStarting] = useState(1); const [winner, setWinner] = useState(null); const setOptions = (type, value) => { if (type === 'Starting Player') { setStarting(value); } else { setDepth(value); } }; const addSymbol = (position, symbol) => { setBoard((prevBoard) => { const tempBoard = [...prevBoard]; tempBoard[position] = symbol; return tempBoard; }); }; const showWinner = (win, direction) => { if (win !== 'draw') { setWinCoords(direction); } switch (win) { case 'x': if (starting === 1) { setWinner(1); } else { setWinner(0); } break; case 'o': if (starting === 1) { setWinner(0); } else { setWinner(1); } break; default: setWinner(-1); } }; const checkClicked = (index) => { if (clicked[index]) { return true; } return false; }; const handleReset = () => { setWinner(null); setWinCoords(null); setBoard((prevState) => prevState.map(() => '')); setClicked((prevState) => prevState.map(() => false)); controls.newGame(depth, starting, addSymbol); }; const handleClick = (index) => { if (!checkClicked(index)) { setClicked((prevState) => { const temp = [...prevState]; temp[index] = true; return temp; }); controls.play(index, showWinner, addSymbol); } }; return ( <BoardSearchContext.Provider value={{ handleClick, handleReset, winCoords, board, setOptions, winner, }} > {children} </BoardSearchContext.Provider> ); }; BoardContextProvider.propTypes = { children: PropType.node.isRequired, }; export default BoardContextProvider; <file_sep>/src/Components/Board/Board.jsx import React, { useContext, useEffect } from 'react'; import { BoardSearchContext } from '../Context/BoardContext'; import Cell from './Cell/Cell'; import './Board.scss'; const Board = () => { const { handleClick, board, handleReset, winCoords, } = useContext(BoardSearchContext); useEffect(() => { handleReset(); }, []); return ( <div id="board"> {board.map((cell, index) => { const win = winCoords ? winCoords.includes(index) : null; return ( <Cell className={win ? `cell-${index} win` : `cell-${index}`} testId={`cell-${index}`} onClick={() => handleClick(index)} > <p>{cell}</p> </Cell> ); })} </div> ); }; export default Board; <file_sep>/src/Components/App.jsx import React from 'react'; import Container from './Container/Container'; import BoardContextProvider from './Context/BoardContext'; import './app.scss'; const App = () => ( <BoardContextProvider> <Container /> </BoardContextProvider> ); export default App; <file_sep>/src/Utils/Board.js class Board { constructor(state = ['', '', '', '', '', '', '', '', '']) { this.state = state; } isEmpty() { return this.state.every((cell) => cell === !cell); } isFull() { return this.state.every((cell) => cell); } isTerminal() { if (this.isEmpty()) return false; const lines = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ]; let row = 1; for (let i = 0; i < lines.length; i += 1) { row = row > 3 ? 1 : row; const [a, b, c] = lines[i]; if (this.state[a] === this.state[b] && this.state[a] === this.state[c] && this.state[a]) { return { winner: this.state[a], direction: [a, b, c] }; } row += 1; } if (this.isFull()) { return { winner: 'draw' }; } // return false otherwise return false; } insert(symbol, position) { // Cell is either occupied or does not exist if (position > 8 || this.state[position]) return false; this.state[position] = symbol; return true; } getAvailableMoves() { const moves = []; for (let i = 0; i < this.state.length; i += 1) { if (!this.state[i]) moves.push(i); } return moves; } } export default Board;
01bccceb80c7afb4c3fc421f88dff062d70276f1
[ "JavaScript" ]
7
JavaScript
WilliamsOhworuka/Tic-tac-toe
13ae0a7f6a5ec109d8678b5c6bbefdc4fa4e61d9
9905f0cf47a95ed09b3373a5d1aab6d0b2e4b523
refs/heads/master
<repo_name>Agontuk/vuejs-webpack-boilerplate<file_sep>/README.md # vuejs-webpack-boilerplate > Simple webpack boilerplate for Vue JS which uses Vuex for state management. ## Features * Hot Reloading * Eslint support * Sample counter app example * Single State Tree with Vuex > Initial directory structure is generated using the awesome `vue-cli` tool. ## Setup ``` bash $ git clone <EMAIL>:Agontuk/vuejs-webpack-boilerplate.git $ cd vuejs-webpack-boilerplate # install dependencies $ npm install # serve with hot reload at localhost:8080 $ npm run dev # build for production with minification $ npm run build ``` > NOTE: This project is for personal use. So no future support is guaranteed. ## License [MIT](http://opensource.org/licenses/MIT) <file_sep>/src/mutators/lib/counter.js export function increment (state, action) { state.count += action.data; } export function decrement (state, action) { state.count -= action.data; } <file_sep>/src/store/index.js import Vuex from 'vuex'; import Vue from 'vue'; import mutations from '../mutators'; // important, teaches Vue components how to // handle Vuex-related options Vue.use(Vuex); const state = { count: 0 }; export default new Vuex.Store({ state, mutations }); <file_sep>/src/main.js import Vue from 'vue'; import store from './store'; import App from './App'; import { remarks } from './filters'; // Register Vue filters globally Vue.filter('remarks', remarks); new Vue({ el: 'body', components: { App }, // provide the store using the "store" option. // this will inject the store instance to all child components. store }); <file_sep>/src/mutators/index.js import * as type from 'constants'; import { increment, decrement } from './lib/counter'; const mutations = { [type.INCREMENT]: (state, action) => { increment(state, action); }, [type.DECREMENT]: (state, action) => { decrement(state, action); } }; export default mutations;
9526697443beeaa26c9a1e1e03705098d126e382
[ "Markdown", "JavaScript" ]
5
Markdown
Agontuk/vuejs-webpack-boilerplate
64bd4a8327db229710ad8f593cffeec68d47e219
f0ba1b4d7c9d906f901fd53a633bd586b91b8998
refs/heads/master
<repo_name>dheeraj-coding/budget-tracker<file_sep>/server.go package main import ( "encoding/json" "log" "net/http" "os" "strconv" "strings" "github.com/gorilla/mux" ) // StartServer starts the HTTP server and configures all necessary routes. func StartServer() { // TODO ML Refactor into multiple files / restructure this file. r := mux.NewRouter() r.HandleFunc("/api/transaction/{year}/{month}", listHandler) r.HandleFunc("/api/transaction/{year}/{month}/budget", budgetHandler) r.HandleFunc("/api/transaction", postHandler). Methods("POST") r.PathPrefix("/").HandlerFunc(fileHandler) port := ":8080" log.Println("Starting to listen on port", port) http.ListenAndServe(port, r) } func fileHandler(w http.ResponseWriter, r *http.Request) { _, err := os.Stat("static/") localMode := true if err != nil { localMode = false } log.Println("localMode", localMode) if localMode { f := http.FileServer(http.Dir("./static/")) f.ServeHTTP(w, r) return } for _, n := range AssetNames() { log.Println("Asset:", n) } // Serving from files in go-bindata only. upath := r.URL.Path if !strings.HasPrefix(upath, "/") { upath = "/" + upath r.URL.Path = upath } if upath == "/" { upath = "/index.html" } bytes, err := Asset("static" + upath) if err != nil { log.Println("File not found", upath) w.WriteHeader(http.StatusNotFound) return } w.Write(bytes) } func listHandler(w http.ResponseWriter, r *http.Request) { log.Println("List transactions handler called. vars=", mux.Vars(r)) year, month, err := parseStandardFields(w, r) if err != nil { return } w.Header()["Content-Type"] = []string{"application/json"} ts := Load(year, month) enc := json.NewEncoder(w) enc.Encode(ts) } func budgetHandler(w http.ResponseWriter, r *http.Request) { log.Println("Budget transactions handler called. vars=", mux.Vars(r)) year, month, err := parseStandardFields(w, r) if err != nil { return } w.Header()["Content-Type"] = []string{"application/json"} ts := Load(year, month) budget := ComputeBudget(ts) enc := json.NewEncoder(w) enc.Encode(budget) } func postHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) log.Println("Post transaction handler called. vars=", vars) dec := json.NewDecoder(r.Body) var t Transaction dec.Decode(&t) w.WriteHeader(http.StatusOK) trans := NewTransaction(t.Description, t.Amount.StringFixed(2)) Save(trans) } func parseStandardFields(w http.ResponseWriter, r *http.Request) (int, int, error) { vars := mux.Vars(r) year, err := strconv.Atoi(vars["year"]) if err != nil { log.Println("Unable to parse year", err) w.WriteHeader(http.StatusBadRequest) return 0, 0, err } month, err := strconv.Atoi(vars["month"]) if err != nil { log.Println("Unable to parse month", err) w.WriteHeader(http.StatusBadRequest) return 0, 0, err } return year, month, nil } <file_sep>/README.md [![Build Status](https://travis-ci.org/mlesniak/budget-tracker.svg?branch=master)](https://travis-ci.org/mlesniak/budget-tracker) [![Go Report Card](https://goreportcard.com/badge/github.com/mlesniak/budget-tracker)](https://goreportcard.com/report/github.com/mlesniak/budget-tracker) # Overview A budget tracker. # Guiding Principles I will be guided by the following principles - Open Source everything - Be open to suggestions - Write idiomatic go code - Be pragmatic about testing, but try to test everything - Do not overengineer # Project Organization The project is organized in a [Trello board](https://trello.com/b/l6MnCUzv/budget-tracker). <file_sep>/Makefile all: pack go build ./... pack: go-bindata static/ clean: rm -f budget-tracker <file_sep>/static/index.html <html> <head> <link rel="stylesheet" type="text/css" href="/main.css"> </head> <body> <div id="app"> <h1>Budget</h1> <ul v-cloak> <li>Balance: {{budget.balance}}</li> <li>Daily budget: {{budget.daily}}</li> <li>Remaining days: {{budget.remainingDays}}</li> </ul> <h1>Input</h1> <form v-on:submit.prevent=""> Description <input v-model="description"> <br/> <input v-on:click="add()" type="submit" value="+"> Amount <input v-model="amount" placeholder="0.00"> <input v-on:click="sub()" type="submit" value="-"> </form> <h1>List of transactions</h1> <ul v-cloak> <li v-for="t in transactions"> {{t.description}} {{t.amount}} </li> </ul> </div> </body> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script src="/main.js"></script> </html><file_sep>/main.go package main func main() { InitalizeStorage("./data.db") StartServer() }
2521ef782954b7a0bca3f9846e7367e8cc682354
[ "Markdown", "Go", "HTML", "Makefile" ]
5
Go
dheeraj-coding/budget-tracker
bffb5490401d2c6faf87e51e3b007f576722ec22
843d5be85bcc1dd8f670ce16c3c2086625377da1
refs/heads/master
<repo_name>yehuda81/FlightProject<file_sep>/DB_Generator/AirLinesCompanies.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DB_Generator { class AirLinesCompanies { public static List<AirLineCompany> companies = new List<AirLineCompany> { new AirLineCompany("ABSA Cargo Airline","TUS","323",1), new AirLineCompany("Adria Airways","ADR","165",2), new AirLineCompany("Aegean Airlines","AEE","390",3), new AirLineCompany("Aer Lingus","EIN","053",4), new AirLineCompany("Aero República","RBP","845",5), new AirLineCompany("Aeroflot","AFL","555",6), new AirLineCompany("Aerolineas Argentinas","ARG","044",7), new AirLineCompany("Aerolineas Galapagos S.A. Aerogal","547","547",8), new AirLineCompany("Aeromexico","AMX","139",9), new AirLineCompany("Afriqiyah Airways","AAW","546",10), new AirLineCompany("Aigle Azur","AAF","439",11), new AirLineCompany("Air Algérie","DAH","124",12), new AirLineCompany("Air Arabia","ABY","514",13), new AirLineCompany("Air Astana","KZR","465",14), new AirLineCompany("Air Austral","REU","760",15), new AirLineCompany("Air Baltic","BTI","657",16), new AirLineCompany("Air Berlin","BER","745",17), new AirLineCompany("Air Botswana","BOT","636",18), new AirLineCompany("Air Caledonie","TPC","190",19), new AirLineCompany("Air Canada","ACA","014",20), new AirLineCompany("Air China Limited","CCA","999",21), new AirLineCompany("Air Corsica","CCM","146",22), new AirLineCompany("Air Europa","AEA","996",23), new AirLineCompany("Air France","AFR","057",24), new AirLineCompany("Air India","AIC","098",25), new AirLineCompany("Air Koryo","KOR","120",26), new AirLineCompany("Air Macau","AMU","675",27), new AirLineCompany("Air Madagascar","MDG","258",28), new AirLineCompany("Air Malta","AMC","643",29), new AirLineCompany("Air Mauritius","MAU","239",30), new AirLineCompany("Air Moldova","MLD","572",31), new AirLineCompany("Air Namibia","NMB","186",32), new AirLineCompany("Air New Zealand","ANZ","086",33), new AirLineCompany("Air Niugini","ANG","656",34), new AirLineCompany("Air Nostrum","ANE","694",35), new AirLineCompany("Air One S.p.A.","ADH","867",36), new AirLineCompany("Air SERBIA a.d. Beograd","JAT","115",37), new AirLineCompany("Air Seychelles","SEY","061",38), new AirLineCompany("Air Tahiti","VTA","135",39), new AirLineCompany("Air Tahiti Nui","THT","244",40), new AirLineCompany("Air Transat","TSC","649",41), new AirLineCompany("Air Uganda","UGA","926",42), new AirLineCompany("Air Vanuatu","AVN","218",43), new AirLineCompany("AirBridgeCargo Airlines","ABW","580",44), new AirLineCompany("Aircalin","ACI","063",45), new AirLineCompany("Airlink","SOA","749",46), new AirLineCompany("Alaska Airlines","ASA","027",47), new AirLineCompany("Alitalia","AZA","055",48), new AirLineCompany("All Nippon Airways","ANA","205",49), new AirLineCompany("AlMasria Universal Airlines","LMU","110",50), new AirLineCompany("ALS","KNYA","656",51), new AirLineCompany("American Airlines","AAL","001",52), new AirLineCompany("Arik Air","ARA","725",53), new AirLineCompany("Arkia Israeli Airlines","AIZ","238",54), new AirLineCompany("Asia Pacific Airlines","MGE","046",55), new AirLineCompany("Asiana","AAR","988",56), new AirLineCompany("Atlas Air","GTI","369",57), new AirLineCompany("Atlasjet Airlines","KKK","610",58), new AirLineCompany("Austral","AUT","143",59), new AirLineCompany("Austrian","AUA","257",60), new AirLineCompany("AVIANCA","AVA","134",61), new AirLineCompany("Avianca Brasil","ONE","247",62), new AirLineCompany("Azerbaijan Airlines","AHY","771",63), new AirLineCompany("B&H Airlines","BON","995",64), new AirLineCompany("Bangkok Air","BKP","829",65), new AirLineCompany("Belavia - Belarusian Airlines","BRU","628",66), new AirLineCompany("BH AIR","BGH","366",67), new AirLineCompany("Biman","BBC","997",68), new AirLineCompany("Binter Canarias","IBB","474",69), new AirLineCompany("Blue Panorama","BPA","004",70), new AirLineCompany("Blue1","BLF","142",71), new AirLineCompany("bmi Regional","BMR","480",72), new AirLineCompany("Boliviana de Aviación - BoA","BOV","930",73), new AirLineCompany("British Airways","BAW","125",74), new AirLineCompany("Brussels Airlines","BEL","082",75), new AirLineCompany("Bulgaria air","LZB","623",76), new AirLineCompany("C.A.L. Cargo Airlines","ICL","700",77), new AirLineCompany("Cargojet Airways","CJT","489",78), new AirLineCompany("Cargolux S.A.","CLX","172",79), new AirLineCompany("Caribbean Airlines","BWA","106",80), new AirLineCompany("Carpatair","KRP","021",81), new AirLineCompany("Cathay Pacific","CPA","160",82), new AirLineCompany("China Airlines","CAL","297",83), new AirLineCompany("China Cargo Airlines","CHN","112",84), new AirLineCompany("China Eastern","CES","781",85), new AirLineCompany("China Postal Airlines","CYZ","804",86), new AirLineCompany("China Southern Airlines","CSN","784",87), new AirLineCompany("CityJet","BCY","689",88), new AirLineCompany("Comair","CAW","161",89), new AirLineCompany("Condor","CFG","881",90), new AirLineCompany("COPA Airlines","CMP","230",91), new AirLineCompany("Corendon Airlines","CAI","395",92), new AirLineCompany("Corsair International","CRL","923",93), new AirLineCompany("Croatia Airlines","CTN","831",94), new AirLineCompany("Cubana","CUB","136",95), new AirLineCompany("Cyprus Airways","CYP","048",96), new AirLineCompany("Czech Airlines j.s.c","CSA","064",97), new AirLineCompany("Delta Air Lines","DAL","006",98), new AirLineCompany("DHL Air","DHK","936",99), new AirLineCompany("DHL Aviation EEMEA B.S.C.(c)","DHX","155",100), new AirLineCompany("Donavia","DNV","733",101), new AirLineCompany("Dragonair","HDA","043",102), new AirLineCompany("Egyptair","MSR","077",103), new AirLineCompany("EL AL","ELY","114",104), new AirLineCompany("Emirates","UAE","176",105), new AirLineCompany("Estonian Air","ELL","960",106), new AirLineCompany("Ethiopian Airlines","ETH","071",107), new AirLineCompany("Etihad Airways","ETD","607",108), new AirLineCompany("Euroatlantic Airways","MMZ","551",109), new AirLineCompany("European Air Transport","BCS","615",110), new AirLineCompany("Eurowings","EWG","104",111), new AirLineCompany("EVA Air","EVA","695",112), new AirLineCompany("Federal Express","FDX","023",113), new AirLineCompany("Fiji Airways","FJI","260",114), new AirLineCompany("Finnair","FIN","105",115), new AirLineCompany("flybe","BEE","267",116), new AirLineCompany("Freebird Airlines","FHY","324",117), new AirLineCompany("Garuda","GIA","126",118), new AirLineCompany("Georgian Airways","TGZ","606",119), new AirLineCompany("Germania","GMI","246",120), new AirLineCompany("Gulf Air","GFA","072",121), new AirLineCompany("Hahn Air","HHN","169",122), new AirLineCompany("Hainan Airlines","CHH","880",123), new AirLineCompany("Hawaiian Airlines","HAL","173",124), new AirLineCompany("Hi Fly","HFY","234",125), new AirLineCompany("Hong Kong Airlines","CRK","851",126), new AirLineCompany("Hong Kong Express Airways","HKE","128",127), new AirLineCompany("IBERIA","IBE","075",128), new AirLineCompany("Icelandair","ICE","108",129), new AirLineCompany("InselAir","INC","958",130), new AirLineCompany("Interair","ILN","625",131), new AirLineCompany("InterSky","AUS","222",132), new AirLineCompany("Iran Air","IRA","096",133), new AirLineCompany("Iran Aseman Airlines","IRC","815",134), new AirLineCompany("Israir","ISR","818",135), new AirLineCompany("Japan Airlines","JAL","131",136), new AirLineCompany("Jazeera Airways","JZR","486",137), new AirLineCompany("Jet Airways","JAI","589",138), new AirLineCompany("Jet Lite (India) Limited","IND","705",139), new AirLineCompany("JetBlue","JBU","279",140), new AirLineCompany("Jordan Aviation","JAV","151",141), new AirLineCompany("JSC Aircompany Yakutia","SYL","849",142), new AirLineCompany("JSC Nordavia-RA","AUL","316",143), new AirLineCompany("Juneyao Airlines","DKH","018",144), new AirLineCompany("Kenya Airways","KQA","706",145), new AirLineCompany("Kish Air","IRK","780",146), new AirLineCompany("KLM","KLM","074",147), new AirLineCompany("Korean Air","KAL","180",148), new AirLineCompany("Kuwait Airways","KAC","229",149), new AirLineCompany("LACSA","LRC","133",150), new AirLineCompany("LAM","LAM","068",151), new AirLineCompany("Lan Airlines","LAN","045",152), new AirLineCompany("Lan Argentina","DSM","469",153), new AirLineCompany("Lan Cargo","LCO","145",154), new AirLineCompany("Lan Perú","LPE","544",155), new AirLineCompany("LanEcuador","LNE","462",156), new AirLineCompany("LIAT Airlines","LIA","140",157), new AirLineCompany("Libyan Airlines","LAA","148",158), new AirLineCompany("LLC","NWS","216",159), new AirLineCompany("LOT Polish Airlines","LOT","080",160), new AirLineCompany("Lufthansa","DLH","220",161), new AirLineCompany("Lufthansa Cargo","GEC","020",162), new AirLineCompany("Lufthansa CityLine","CLH","683",163), new AirLineCompany("Luxair","LGL","149",164), new AirLineCompany("Mahan Air","IRM","537",165), new AirLineCompany("Malaysia Airlines","MAS","232",166), new AirLineCompany("Malmö Aviation","SCW","276",167), new AirLineCompany("Martinair Cargo","MPH","129",168), new AirLineCompany("MAS AIR","MAA","865",169), new AirLineCompany("MEA","MEA","076",170), new AirLineCompany("Meridiana fly","ISS","191",171), new AirLineCompany("MIAT","MGL","289",172), new AirLineCompany("Montenegro Airlines","MGX","409",173), new AirLineCompany("Nesma Airlines","NMA","477",174), new AirLineCompany("NIKI","AUS","545",175), new AirLineCompany("Nile Air","NIA","325",176), new AirLineCompany("Nippon Cargo Airlines (NCA)","NCA","933",177), new AirLineCompany("Nouvelair","LBT","796",178), new AirLineCompany("Olympic Air","OAL","050",179), new AirLineCompany("Oman Air","OAS","910",180), new AirLineCompany("Onur Air","OHY","066",181), new AirLineCompany("PAL","PAL","079",182), new AirLineCompany("Pegasus Airlines","PGT","624",183), new AirLineCompany("PGA-Portugália Airlines","PGA","685",184), new AirLineCompany("PIA","PIA","214",185), new AirLineCompany("Precision Air","PRF","031",186), new AirLineCompany("PrivatAir","PTI","656",187), new AirLineCompany("Qantas","QFA","081",188), new AirLineCompany("Qatar Airways","QTR","157",189), new AirLineCompany("Rossiya Airlines","SDM","195",190), new AirLineCompany("Royal Air Maroc","RAM","147",191), new AirLineCompany("Royal Brunei","RBA","672",192), new AirLineCompany("Royal Jordanian","RJA","512",193), new AirLineCompany("SAA","SAA","083",194), new AirLineCompany("Safair","SFR","640",195), new AirLineCompany("Safi Airways","SFW","741",196), new AirLineCompany("SAS","SAS","117",197), new AirLineCompany("SATA Air Açores","SAT","737",198), new AirLineCompany("SATA Internacional","RZO","331",199), new AirLineCompany("Saudi Arabian Airlines","SVA","065",200), new AirLineCompany("Shandong Airlines","CDG","324",201), new AirLineCompany("Shanghai Airlines","CHI","774",202), new AirLineCompany("Shenzhen Airlines","CSZ","479",203), new AirLineCompany("SIA","SIA","618",204), new AirLineCompany("SIA Cargo","SIA","343",205), new AirLineCompany("Siberia Airlines","SBI","421",206), new AirLineCompany("Sichuan Airlines","CHI","876",207), new AirLineCompany("Silkair","SLK","629",208), new AirLineCompany("South African Express Airways","EXY","234",209), new AirLineCompany("SriLankan","ALK","603",210), new AirLineCompany("Sudan Airways","SUD","200",211), new AirLineCompany("SunExpress","SXS","564",212), new AirLineCompany("Surinam Airways","SLM","192",213), new AirLineCompany("SWISS","SWR","724",214), new AirLineCompany("SYPHAX AIRLINES","SYA","393",215), new AirLineCompany("Syrianair","SYR","070",216), new AirLineCompany("TAAG - Angola Airlines","DTA","118",217), new AirLineCompany("TACA","TAI","202",218), new AirLineCompany("TACA Peru","TPU","530",219), new AirLineCompany("TACV Cabo Verde Airlines","TCV","696",220), new AirLineCompany("TAM - Transportes Aéreos del Mercosur Sociedad Anónima","LAP","692",221), new AirLineCompany("TAM Linhas Aéreas","TAM","957",222), new AirLineCompany("TAME - Linea Aérea del Ecuador","TAE","269",223), new AirLineCompany("TAP Portugal","TAP","047",224), new AirLineCompany("TAROM","ROT","281",225), new AirLineCompany("Tassili Airlines","ALG","515",226), new AirLineCompany("Thai Airways International","THA","217",227), new AirLineCompany("THY - Turkish Airlines","THY","235",228), new AirLineCompany("Tianjin Airlines","GCR","826",229), new AirLineCompany("TNT Airways S.A.","TAY","756",230), new AirLineCompany("Transaero","TSO","670",231), new AirLineCompany("TransAsia Airways","TNA","170",232), new AirLineCompany("TUIfly","TUI","617",233), new AirLineCompany("Tunisair","TAR","199",234), new AirLineCompany("Ukraine International Airlines","AUI","566",235), new AirLineCompany("United Airlines","UAL","016",236), new AirLineCompany("UPS Airlines","UPS","406",237), new AirLineCompany("US Airways","USA","037",238), new AirLineCompany("UTair","UTA","298",239), new AirLineCompany("Uzbekistan Airways","UZB","250",240), new AirLineCompany("Vietnam Airlines","HVN","738",241), new AirLineCompany("Virgin Atlantic","VIR","932",242), new AirLineCompany("Virgin Australia","VAU","795",243), new AirLineCompany("VLM Airlines","VLM","532",244), new AirLineCompany("Volaris","VOI","036",245), new AirLineCompany("Volga-Dnepr Airlines","VDA","412",246), new AirLineCompany("VRG <NAME>.A. - Grupo GOL","GLO","127",247), new AirLineCompany("White coloured by you","WHT","097",248), new AirLineCompany("Wideroe","WIF","701",249), new AirLineCompany("Xiamen Airlines","CXA","731",250), new AirLineCompany("Yemenia","IYE","635",251), new AirLineCompany("Silk Way Airlines","AZQ","463",252), new AirLineCompany("Silk Way West Airlines Limited","AZE","501",253) }; } } <file_sep>/FlightsManagementSystem/CustomerDAOMSSQL.cs using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FlightsManagementSystem { public class CustomerDAOMSSQL : ICustomerDAO { public void Add(Customer t) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); using (con) { SqlCommand cmd = new SqlCommand("ADD_CUSTOMER", con); cmd.Parameters.Add(new SqlParameter("@FIRST_NAME", t.FirstName)); cmd.Parameters.Add(new SqlParameter("@LAST_NAME", t.LastName)); cmd.Parameters.Add(new SqlParameter("@USER_NAME", t.UserName)); cmd.Parameters.Add(new SqlParameter("@PASSWORD", t.Password)); cmd.Parameters.Add(new SqlParameter("@ADDRESS", t.Address)); cmd.Parameters.Add(new SqlParameter("@PHONE_NO", t.PhoneNo)); cmd.Parameters.Add(new SqlParameter("@CREDIT_CARD_NUMBER", t.CreditCardNumber)); con.Open(); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); con.Close(); } } public Customer Get(int id) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); Customer t = new Customer(); using (con) { SqlCommand cmd = new SqlCommand("SELECT_CUSTOMER_BY_ID", con); cmd.Parameters.Add(new SqlParameter("@id", id)); con.Open(); cmd.CommandType = CommandType.StoredProcedure; SqlDataReader reader = cmd.ExecuteReader(); { while (reader.Read()) { t.Id = (long)reader["ID"]; t.FirstName = (string)reader["FIRST_NAME"]; t.UserName = (string)reader["USER_NAME"]; t.LastName = (string)reader["LAST_NAME"]; t.Password = (string)reader["<PASSWORD>"]; t.Address = (string)reader["ADDRESS"]; t.PhoneNo = (string)reader["PHONE_NO"]; t.CreditCardNumber = (string)reader["CREDIT_CARD_NUMBER"]; } con.Close(); return t; } } } public IList<Customer> GetAll() { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); List<Customer> customers = new List<Customer>(); using (con) { con.Open(); SqlCommand cmd = new SqlCommand($"SELECT_ALL_CUSTOMERS", con); SqlDataReader reader = cmd.ExecuteReader(); { while (reader.Read()) { Customer t = new Customer(); t.Id = (long)reader["ID"]; t.FirstName = (string)reader["FIRST_NAME"]; t.UserName = (string)reader["USER_NAME"]; t.LastName = (string)reader["LAST_NAME"]; t.Password = (string)reader["<PASSWORD>"]; t.Address = (string)reader["ADDRESS"]; t.PhoneNo = (string)reader["PHONE_NO"]; t.CreditCardNumber = (string)reader["CREDIT_CARD_NUMBER"]; customers.Add(t); } con.Close(); return customers; } } } public Customer GetCustomerByUserame(string username) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); Customer t = new Customer(); using (con) { SqlCommand cmd = new SqlCommand("SELECT_CUSTOMER_BY_USERNAME", con); cmd.Parameters.Add(new SqlParameter("@username", username)); con.Open(); cmd.CommandType = CommandType.StoredProcedure; SqlDataReader reader = cmd.ExecuteReader(); { while (reader.Read()) { t.Id = (long)reader["ID"]; t.FirstName = (string)reader["FIRST_NAME"]; t.UserName = (string)reader["USER_NAME"]; t.LastName = (string)reader["LAST_NAME"]; t.Password = (string)reader["<PASSWORD>"]; t.Address = (string)reader["ADDRESS"]; t.PhoneNo = (string)reader["PHONE_NO"]; t.CreditCardNumber = (string)reader["CREDIT_CARD_NUMBER"]; } con.Close(); return t; } } } public void RemoveAll() { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); using (con) { con.Open(); SqlCommand cmd = new SqlCommand($"DELETE_ALL_CUSTOMERS", con); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); con.Close(); } } public void Remove(Customer t) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); using (con) { con.Open(); SqlCommand cmd = new SqlCommand($"DELETE_CUSTOMER", con); cmd.Parameters.Add(new SqlParameter("@id", t.Id)); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); con.Close(); } } public void Update(Customer t) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); using (con) { con.Open(); SqlCommand cmd = new SqlCommand($"UPDATE_CUSTOMER", con); cmd.Parameters.Add(new SqlParameter("@ID", t.Id)); cmd.Parameters.Add(new SqlParameter("@FIRST_NAME", t.FirstName)); cmd.Parameters.Add(new SqlParameter("@LAST_NAME", t.LastName)); cmd.Parameters.Add(new SqlParameter("@USER_NAME", t.UserName)); cmd.Parameters.Add(new SqlParameter("@PASSWORD", <PASSWORD>)); cmd.Parameters.Add(new SqlParameter("@ADDRESS", t.Address)); cmd.Parameters.Add(new SqlParameter("@PHONE_NO", t.PhoneNo)); cmd.Parameters.Add(new SqlParameter("@CREDIT_CARD_NUMBER", t.CreditCardNumber)); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); con.Close(); } } } } <file_sep>/Controllers/AdministratorFacdeController.cs using FlightsManagementSystem; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; namespace FlightsWebApplication.Controllers { [BasicAuthenticationAdministrator] public class AdministratorFacdeController : ApiController { LoggedInAdministratorFacade facade = new LoggedInAdministratorFacade(); LoginToken<Administrator> AdminLogin = new LoginToken<Administrator>(); [ResponseType(typeof(AirlineCompany))] [HttpGet] [Route("api/AdministratorFacade/airlines/byname/{text}")] public IEnumerable<AirlineCompany> GetByTextAndSender([FromUri] string text) { IEnumerable<AirlineCompany> result_text = facade.GetAllAirlineCompanies().Where(m => m.AirlineName.ToUpper().Contains(text.ToUpper())); return result_text; } [ResponseType(typeof(AirlineCompany))] [HttpPost] [Route("api/AdministratorFacade/CreateNewAirline")] public IHttpActionResult CreateNewAirline([FromBody] AirlineCompany airline) { GetLoginToken(); try { facade.CreateNewAirline(AdminLogin,airline); AirlineCompany company = facade.GetAllAirlineCompanies().Last(); airline.Id = company.Id; if (company == airline) { return Ok(airline); } return BadRequest(); } catch (Exception) { return BadRequest(); } } [ResponseType(typeof(AirlineCompany))] [HttpPost] [Route("api/AdministratorFacade/UpdateAirlineDetails/{id}")] public IHttpActionResult UpdateAirlineDetails([FromUri] int id, [FromBody] AirlineCompany company) { GetLoginToken(); try { company.Id = id; facade.UpdateAirlineDetails(AdminLogin, company); if (company == facade.GetAirlineCompanyById(AdminLogin, id)) { return Ok(company); } return BadRequest(); } catch (Exception) { return NotFound(); } } [ResponseType(typeof(AirlineCompany))] [HttpPost] [Route("api/AdministratorFacade/RemoveAirline/{id}")] public IHttpActionResult RemoveAirline([FromUri] int id) { GetLoginToken(); AirlineCompany airline = facade.GetAirlineCompanyById(AdminLogin, id); if (airline.Id == id) { facade.RemoveAirline(AdminLogin, airline); return Ok(); } return NotFound(); } [ResponseType(typeof(Customer))] [HttpPost] [Route("api/AdministratorFacade/CreateNewCustomer")] public IHttpActionResult CreateNewCustomer([FromBody] Customer customer) { GetLoginToken(); try { facade.CreateNewCustomer(AdminLogin, customer); Customer c = facade.GetCustomerByUserName(AdminLogin, customer.UserName); c.Id = customer.Id; if (c == customer) { return Ok(customer); } return BadRequest(); } catch (Exception) { return NotFound(); } } [ResponseType(typeof(Customer))] [HttpPost] [Route("api/AdministratorFacade/UpdateCustomerDetails/{id}")] public IHttpActionResult UpdateCustomerDetails([FromUri] int id, [FromBody] Customer customer) { GetLoginToken(); try { customer.Id = id; facade.UpdateCustomerDetails(AdminLogin, customer); if (customer == facade.GetCustomerById(AdminLogin, id)) { return Ok(customer); } return BadRequest(); } catch (Exception) { return NotFound(); } } [ResponseType(typeof(Customer))] [HttpPost] [Route("api/AdministratorFacade/RemoveCustomer/{id}")] public IHttpActionResult RemoveCustomer([FromUri] int id) { GetLoginToken(); try { Customer customer = facade.GetCustomerById(AdminLogin, id); facade.RemoveCustomer(AdminLogin, customer); Customer c = facade.GetCustomerById(AdminLogin, id); if (c.Id == id) { facade.RemoveCustomer(AdminLogin, customer); return Ok(); } return BadRequest(); } catch (Exception) { return NotFound(); } } private void GetLoginToken() { Request.Properties.TryGetValue("token", out object Token); Administrator administrator = (Administrator)Token; AdminLogin.User = administrator; } } } <file_sep>/TestFlightProject/TestCenter.cs using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using FlightsManagementSystem; namespace TestFlightProject { public class TestCenter { public LoginToken<AirlineCompany> AirLineToken = new LoginToken<AirlineCompany>(); public void DeleteAllData() { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); using (con) { SqlCommand cmd = new SqlCommand("DELETE_ALL_DB", con); con.Open(); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); con.Close(); } } public void FillData() { //LoggedInAirlineFacade AirlineFacade = new LoggedInAirlineFacade(); //AirlineFacade.GetAllFlights(); } } } <file_sep>/FlightsManagementSystem/Ticket.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FlightsManagementSystem { public class Ticket : IPoco { public long Id { get; set; } public long FlightId { get; set; } public long CustomerId { get; set; } public Ticket() { } public Ticket(long flightId, long customerId) { FlightId = flightId; CustomerId = customerId; } public static bool operator ==(Ticket a, Ticket b) { if (ReferenceEquals(a, null) && ReferenceEquals(b, null)) { return true; } if (ReferenceEquals(a, null) || ReferenceEquals(b, null)) { return false; } return a.Id == b.Id; } public static bool operator !=(Ticket a, Ticket b) { return !(a == b); } public override string ToString() { return $"Id: {Id} FlightId: {FlightId} CustomerId: {CustomerId}"; } public override bool Equals(object obj) { Ticket other = obj as Ticket; return this == other; } public override int GetHashCode() { return Id.GetHashCode(); } } }<file_sep>/FlightsManagementSystem/LoginService.cs using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FlightsManagementSystem { public class LoginService : ILoginService { private IAirlineDAO _airlineDAO; private ICustomerDAO _customerDAO; public LoginService() { _airlineDAO = new AirlineDAOMSSQL(); _customerDAO = new CustomerDAOMSSQL(); } public bool TryAdminLogin(string userName, string password, out LoginToken<Administrator> token) { Administrator administrator = new Administrator(userName,password); if (userName == AppConfig.ADMIN_USER && password == AppConfig.ADMIN_PASSWORD) { token = new LoginToken<Administrator>(); token.User = new Administrator(userName,password); return true; } token = null; return false; } public bool TryAirlineLogin(string userName, string password, out LoginToken<AirlineCompany> token) { AirlineCompany company = _airlineDAO.GetAirlineByUsername(userName); if (company != null) { if (company.UserName == userName) { if (company.Password == <PASSWORD>) { token = new LoginToken<AirlineCompany>(); token.User = company; return true; } else { throw new WrongPasswordException("Wrong Password"); } } } token = null; return false; } public bool TryCustomerLogin(string userName, string password, out LoginToken<Customer> token) { Customer customer = _customerDAO.GetCustomerByUserame(userName); if (customer != null) { if (customer.UserName == userName) { if (customer.Password == <PASSWORD>) { token = new LoginToken<Customer>(); token.User = customer; return true; } else { throw new WrongPasswordException("Wrong Password"); } } } token = null; return false; } } } <file_sep>/UnitTestWebApi/AnonymousTest.cs using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Net.Http; using System.Net.Http.Headers; using FlightsManagementSystem; using System.Collections.Generic; namespace UnitTestWebApi { [TestClass] public class AnonymousTest { [TestMethod] public void TestAnonymousController_GetAllFlights() { using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(""); string ss = Convert.ToBase64String(plainTextBytes); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); using (HttpResponseMessage response = client.GetAsync("http://localhost:50946/api/AnonymousFacade/GetAllFlights").Result) { using (HttpContent content = response.Content) { IList<Flight> flights = content.ReadAsAsync<IList<Flight>>().Result; Assert.AreNotEqual(null, flights); Assert.AreEqual(TestResource.flight.AirlineCompanyId, flights[8].AirlineCompanyId); Assert.AreEqual(TestResource.flight.DepartureTime, flights[8].DepartureTime); Assert.AreEqual(TestResource.flight.DestinationCountryCode, flights[8].DestinationCountryCode); Assert.AreEqual(TestResource.flight.OriginCountryCode, flights[8].OriginCountryCode); Assert.AreEqual(TestResource.flight.LandingTime, flights[8].LandingTime); } } } } [TestMethod] public void TestAdministratorFacade_CreateNewCustomer() { using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); var plainTextBytes = System.Text.Encoding.UTF8.GetBytes("admin:9999"); string ss = Convert.ToBase64String(plainTextBytes); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(plainTextBytes)); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); Customer customer = TestResource.newCustomer; using (HttpResponseMessage response = client.PostAsJsonAsync("http://localhost:50946/api/AdministratorFacade/CreateNewCustomer",customer).Result) { using (HttpContent content = response.Content) { Customer testCustomer = content.ReadAsAsync<Customer>().Result; Assert.AreNotEqual(null, testCustomer); Assert.AreEqual(customer.FirstName, testCustomer.FirstName); Assert.AreEqual(customer.LastName, testCustomer.LastName); Assert.AreEqual(customer.UserName, testCustomer.UserName); Assert.AreEqual(customer.Password, testCustomer.Password); Assert.AreEqual(customer.Address, testCustomer.Address); Assert.AreEqual(customer.PhoneNo, testCustomer.PhoneNo); Assert.AreEqual(customer.CreditCardNumber, testCustomer.CreditCardNumber); } } } } [TestMethod] public void TestAirlineFacade_ChangeMyPassword() { using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); var plainTextBytes = System.Text.Encoding.UTF8.GetBytes("TUS:323"); string ss = Convert.ToBase64String(plainTextBytes); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(plainTextBytes)); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); AirlineCompany airline = new AirlineCompany(); airline.UserName = "TUS"; airline.Password = "323"; using (HttpResponseMessage response = client.PostAsJsonAsync("http://localhost:50946/api/airlineFacade/ChangeMyPassword/323/323",airline).Result) { using (HttpContent content = response.Content) { Assert.AreEqual("OK", response.ReasonPhrase.ToString()); } } } } [TestMethod] public void TestCustomerFacade_CancelTicket() { using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); var plainTextBytes = System.Text.Encoding.UTF8.GetBytes("Anthony  Mansir :1e!Ck"); string ss = Convert.ToBase64String(plainTextBytes); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(plainTextBytes)); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); Customer customer = new Customer(); customer.UserName = "Anthony  Mansir"; customer.Password = "<PASSWORD>"; using (HttpResponseMessage response = client.PostAsJsonAsync("http://localhost:50946/api/CustomerFacade/CancelTicket/20846", customer).Result) { using (HttpContent content = response.Content) { Assert.AreEqual("OK", response.ReasonPhrase.ToString()); } } } } } } <file_sep>/DB_Generator/AirLineCompany.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DB_Generator { class AirLineCompany { public long Id { get; set; } public string AirlineName { get; set; } public string UserName { get; set; } public string Password { get; set; } public long CountryCode { get; set; } public AirLineCompany(string airlineName, string userName, string password, long countryCode) { AirlineName = airlineName; UserName = userName; Password = <PASSWORD>; CountryCode = countryCode; } } } <file_sep>/FlightsManagementSystem/LoggedInCustomerFacade.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FlightsManagementSystem { public class LoggedInCustomerFacade : AnonymousUserFacade, ILoggedInCustomerFacade { public void CancelTicket(LoginToken<Customer> token, Ticket ticket) { if (token.User != null) { _ticketDAO.Remove(ticket); } } public IList<Flight> GetAllMyFlights(LoginToken<Customer> token) { if (token.User != null) { Customer customer = new Customer(); customer.Id = token.User.Id; customer.UserName = token.User.UserName; customer.Password = <PASSWORD>; return _flightDAO.GetFlightsByCustomer(customer); } return null; } public Ticket PurchaseTicket(LoginToken<Customer> token, Ticket ticket) { if (token.User != null) { _ticketDAO.Add(ticket); Flight flight = _flightDAO.GetFlightById((int)ticket.FlightId); flight.RemainingTickets = flight.RemainingTickets - 1; _flightDAO.Update(flight); return ticket; } return null; } public Ticket GetMyLastTicket(LoginToken<Customer> token) { if (token.User != null) { return _ticketDAO.GetAll().Last(); } return null; } public Ticket GetMyTicket(LoginToken<Customer> token,int Id) { if (token.User != null) { return _ticketDAO.Get(Id); } return null; } } } <file_sep>/Controllers/CustomerFacdeController.cs using FlightsManagementSystem; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; namespace FlightsWebApplication.Controllers { [BasicAuthenticationCustomer] public class CustomerFacdeController : ApiController { LoggedInCustomerFacade customerFacade = new LoggedInCustomerFacade(); LoginToken<Customer> loginToken = new LoginToken<Customer>(); [ResponseType(typeof(Flight))] [HttpGet] [Route("api/CustomerFacade/GetAllMyFlights")] public IHttpActionResult GetAllMyFlights() { GetLoginToken(); try { IList<Flight> flights = customerFacade.GetAllMyFlights(loginToken); if (flights.Count == 0) { return NotFound(); } return Ok(flights); } catch (Exception) { return BadRequest(); } } private void GetLoginToken() { Request.Properties.TryGetValue("token", out object Token); Customer customer = (Customer)Token; loginToken.User = customer; } [ResponseType(typeof(Ticket))] [HttpPost] [Route("api/CustomerFacade/PurchaseTicket/{id}")] public IHttpActionResult PurchaseTicket([FromUri] long Id) { GetLoginToken(); try { Ticket ticket = new Ticket(Id, loginToken.User.Id); customerFacade.PurchaseTicket(loginToken, ticket); return Ok(customerFacade.GetMyLastTicket(loginToken)); } catch (Exception) { return BadRequest(); } } [ResponseType(typeof(Ticket))] [HttpPost] [Route("api/CustomerFacade/CancelTicket/{id}")] public IHttpActionResult CancelTicket([FromUri] int Id) { GetLoginToken(); try { Ticket ticket = customerFacade.GetMyTicket(loginToken, Id); if (ticket.Id != 0) { customerFacade.CancelTicket(loginToken, ticket); return Ok($"Ticket {Id} canceld"); } return NotFound(); } catch (Exception) { return BadRequest(); } } } } <file_sep>/FlightsManagementSystem/CountryDAOMSSQL.cs using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FlightsManagementSystem { public class CountryDAOMSSQL : ICountryDAO { public void Add(Country t) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); using (con) { SqlCommand cmd = new SqlCommand("ADD_COUNTRY", con); cmd.Parameters.Add(new SqlParameter("@COUNTRY_NAME", t.CountryName)); con.Open(); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); con.Close(); } } public Country GetByName(string name) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); Country t = new Country(); using (con) { SqlCommand cmd = new SqlCommand("SELECT_COUNTRY_BY_NAME", con); cmd.Parameters.Add(new SqlParameter("@name", name)); con.Open(); cmd.CommandType = CommandType.StoredProcedure; SqlDataReader reader = cmd.ExecuteReader(); { while (reader.Read()) { t.Id = (long)reader["ID"]; t.CountryName = (string)reader["COUNTRY_NAME"]; } con.Close(); return t; } } } public Country Get(int id) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); using (con) { SqlCommand cmd = new SqlCommand("SELECT_COUNTRY_BY_ID", con); Country t = new Country(); cmd.Parameters.Add(new SqlParameter("@id", id)); con.Open(); cmd.CommandType = CommandType.StoredProcedure; SqlDataReader reader = cmd.ExecuteReader(); { while (reader.Read()) { t.Id = (long)reader["ID"]; t.CountryName = (string)reader["COUNTRY_NAME"]; } con.Close(); return t; } } } public IList<Country> GetAll() { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); List<Country> countries = new List<Country>(); using (con) { con.Open(); SqlCommand cmd = new SqlCommand($"SELECT_ALL_COUNTRIES", con); SqlDataReader reader = cmd.ExecuteReader(); { while (reader.Read()) { Country t = new Country(); t.Id = (long)reader["ID"]; t.CountryName = (string)reader["COUNTRY_NAME"]; countries.Add(t); } con.Close(); return countries; } } } public void Remove(Country t) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); using (con) { SqlCommand cmd = new SqlCommand($"DELETE_COUNTRY", con); cmd.Parameters.Add(new SqlParameter("@id", t.Id)); con.Open(); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); con.Close(); } } public void Update(Country t) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); using (con) { con.Open(); SqlCommand cmd = new SqlCommand($"UPDATE_COUNTRY", con); cmd.Parameters.Add(new SqlParameter("@id", t.Id)); cmd.Parameters.Add(new SqlParameter("@COUNTRY_NAME", t.CountryName)); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); con.Close(); } } public void RemoveAll() { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); using (con) { con.Open(); SqlCommand cmd = new SqlCommand($"DELETE_ALL_COUNTRIES", con); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); con.Close(); } } } } <file_sep>/TestFlightProject/AirLineTest.cs using System; using System.Collections.Generic; using FlightsManagementSystem; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace TestFlightProject { [TestClass] public class AirLineTest { LoggedInAirlineFacade facade = FlyingCenterSystem.GetInstance().GetFacade("LLL", "111", out ILoginToken token) as LoggedInAirlineFacade; LoginToken<AirlineCompany> AirLineLogin = new LoginToken<AirlineCompany>(); Flight flight = new Flight(10079,13,14,new DateTime (2019, 08, 09, 10, 00, 00),new DateTime (2019, 08, 09, 12, 00, 00), 30); [TestMethod] public void Login() { Assert.AreEqual(facade.GetType(), facade.GetType()); } [TestMethod] public void CreateFlight() { IList<AirlineCompany> airlines = facade.GetAllAirlineCompanies(); flight.AirlineCompanyId = airlines[0].Id; facade.CreateFlight(AirLineLogin, flight); } [TestMethod] public void GetAllFlights() { facade.GetAllFlights(AirLineLogin); } [TestMethod] public void UpdateFlight() { IList<AirlineCompany> airlines = facade.GetAllAirlineCompanies(); flight.AirlineCompanyId = airlines[0].Id; flight.LandingTime = new DateTime(2019, 11, 11, 10, 00, 00); facade.UpdateFlight(AirLineLogin, flight); } [TestMethod] public void ModifyAirlineDetails() { IList<AirlineCompany> airlines = facade.GetAllAirlineCompanies(); airlines[0].UserName = "LLL"; facade.ModifyAirlineDetails(AirLineLogin, airlines[0]); } [TestMethod] public void CancelFlight() { IList<AirlineCompany> airlines = facade.GetAllAirlineCompanies(); flight.AirlineCompanyId = airlines[0].Id; facade.CancelFlight(AirLineLogin, flight); } [TestMethod] public void GetAllTickets() { IList<Ticket> tickets = facade.GetAllTickets(AirLineLogin); } [TestMethod] public void ChangeMyPassword() { LoginToken<AirlineCompany> AirLineLogin = new LoginToken<AirlineCompany> { User = facade.GetAllAirlineCompanies()[0] }; facade.ChangeMyPassword(AirLineLogin, "111", "222"); } } } <file_sep>/Controllers/BasicAuthenticationAirLineAttribute.cs using FlightsManagementSystem; using System; using System.Net; using System.Net.Http; using System.Text; using System.Web.Http.Controllers; using System.Web.Http.Filters; namespace FlightsWebApplication.Controllers { internal class BasicAuthenticationAirLineAttribute : AuthorizationFilterAttribute { LoggedInAirlineFacade facade = new LoggedInAirlineFacade(); LoginToken<AirlineCompany> loginToken = new LoginToken<AirlineCompany>(); AirlineCompany airline = new AirlineCompany(); public override void OnAuthorization(HttpActionContext actionContext) { string authenticationToken = actionContext.Request.Headers.Authorization.Parameter; if (actionContext.Request.Headers.Authorization == null) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden, "You must send user name and password in basic authentication"); return; } string decodedAuthenticationToken = Encoding.UTF8.GetString( Convert.FromBase64String(authenticationToken)); string[] usernamePasswordArray = decodedAuthenticationToken.Split(':'); string username = usernamePasswordArray[0]; string password = <PASSWORD>[1]; try { foreach (var company in facade.GetAllAirlineCompanies()) { if (company.UserName == username && company.Password == <PASSWORD> ) { airline = company; actionContext.Request.Properties["token"] = airline; return; } } actionContext.Response = actionContext.Request .CreateResponse(HttpStatusCode.Unauthorized, "incorrect user or password"); } catch (Exception) { } } } }<file_sep>/Controllers/AirlineCompanyFacdeController.cs using FlightsManagementSystem; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; namespace FlightsWebApplication.Controllers { [BasicAuthenticationAirLine] public class AirlineCompanyFacdeController : ApiController { LoggedInAirlineFacade airlineFacade = new LoggedInAirlineFacade(); LoginToken<AirlineCompany> loginToken = new LoginToken<AirlineCompany>(); [ResponseType(typeof(Ticket))] [HttpGet] [Route("api/airlineFacade/GetAllTickets")] public IHttpActionResult GetAllTickets() { GetLoginToken(); try { IList<Ticket> tickets = airlineFacade.GetAllTickets(loginToken); if (tickets.Count == 0) { return NotFound(); } return Ok(tickets); } catch (Exception) { return BadRequest(); } } [ResponseType(typeof(Flight))] [HttpGet] [Route("api/airlineFacade/GetAllFlights")] public IHttpActionResult GetAllFlights() { GetLoginToken(); try { IList<Flight> flights = airlineFacade.GetAllFlights(loginToken); if (flights.Count == 0) { return NotFound(); } return Ok(flights); } catch (Exception) { return BadRequest(); } } [ResponseType(typeof(Flight))] [HttpPost] [Route("api/airlineFacade/CancelFlight/{id}")] public IHttpActionResult CancelFlight(int id) { GetLoginToken(); try { Flight flight = airlineFacade.GetFlightById(id); airlineFacade.CancelFlight(loginToken, flight); if (airlineFacade.GetFlightById(id).Id == 0 && flight.Id !=0) { return Ok(); } return NotFound(); } catch (Exception) { return BadRequest(); } } [ResponseType(typeof(Flight))] [HttpPost] [Route("api/airlineFacade/CreateFlight")] public IHttpActionResult CreateFlight([FromBody]Flight flight) { GetLoginToken(); try { airlineFacade.CreateFlight(loginToken, flight); Flight f = airlineFacade.GetAllFlights(loginToken).Last(); flight.Id = f.Id; if (f == flight) { return Ok(flight); } return NotFound(); } catch (Exception) { return BadRequest(); } } [ResponseType(typeof(Flight))] [HttpPost] [Route("api/airlineFacade/UpdateFlight/{id}")] public IHttpActionResult UpdateFlight([FromBody]Flight flight, int id) { GetLoginToken(); try { flight.Id = id; airlineFacade.UpdateFlight(loginToken, flight); if (airlineFacade.GetFlightById(id).Id == id && id != 0) { return Ok(flight); } return NotFound(); } catch (Exception) { return BadRequest(); } } [ResponseType(typeof(AirlineCompany))] [HttpPost] [Route("api/airlineFacade/ChangeMyPassword/{oldPassword}/{newPassword}")] public IHttpActionResult ChangeMyPassword(string oldPassword, string newPassword) { GetLoginToken(); try { //if (oldPassword == <PASSWORD>) //{ airlineFacade.ChangeMyPassword(loginToken, oldPassword, newPassword); return Ok("Password changed successfully"); // } //return BadRequest("incorrect password"); } catch (Exception) { return BadRequest(); } } [ResponseType(typeof(AirlineCompany))] [HttpPost] [Route("api/airlineFacade/MofidyAirlineDetails")] public IHttpActionResult MofidyAirlineDetails([FromBody]AirlineCompany airline) { GetLoginToken(); try { if (airline.Id == loginToken.User.Id) { airlineFacade.ModifyAirlineDetails(loginToken, airline); return Ok(); } return BadRequest(); } catch (Exception) { return BadRequest(); } } private void GetLoginToken() { Request.Properties.TryGetValue("token", out object Token); AirlineCompany airline = (AirlineCompany)Token; loginToken.User = airline; } } } <file_sep>/DB_Generator/Country.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DB_Generator { class Country { public long id; public string name; public Country(long id, string name) { this.id = id; this.name = name; } } } <file_sep>/DB_Generator/Countries.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DB_Generator { class Countries { public static List<Country> countries = new List<Country> { new Country(1,"Brazil"), new Country(2,"Slovenia"), new Country(3,"Greece"), new Country(4,"Ireland"), new Country(5,"Colombia"), new Country(6,"Russian Federation"), new Country(7,"Argentina"), new Country(8,"Ecuador"), new Country(9,"Mexico"), new Country(10,"Libya"), new Country(11,"France"), new Country(12,"Algeria"), new Country(13,"United Arab Emirates"), new Country(14,"Kazakhstan"), new Country(15,"France"), new Country(16,"Latvia"), new Country(17,"Germany"), new Country(18,"Botswana"), new Country(19,"New Caledonia"), new Country(20,"Canada"), new Country(21,"China (People's Republic of)"), new Country(22,"France"), new Country(23,"Spain"), new Country(24,"France"), new Country(25,"India"), new Country(26,"Korea, Democratic People's Republic of"), new Country(27,"Macao SAR, China"), new Country(28,"Madagascar"), new Country(29,"Malta"), new Country(30,"Mauritius"), new Country(31,"Moldova, Republic of"), new Country(32,"Namibia"), new Country(33,"New Zealand"), new Country(34,"Independent State of Papua New Guinea"), new Country(35,"Spain"), new Country(36,"Italy"), new Country(37,"Serbia"), new Country(38,"Seychelles"), new Country(39,"French Polynesia"), new Country(40,"French Polynesia"), new Country(41,"Canada"), new Country(42,"Uganda"), new Country(43,"Vanuatu"), new Country(44,"Russian Federation"), new Country(45,"New Caledonia"), new Country(46,"South Africa"), new Country(47,"United States"), new Country(48,"Italy"), new Country(49,"Japan"), new Country(50,"Egypt"), new Country(51,"Kenya"), new Country(52,"United States"), new Country(53,"Nigeria"), new Country(54,"Israel"), new Country(55,"United States"), new Country(56,"Korea"), new Country(57,"United States"), new Country(58,"Turkey"), new Country(59,"Argentina"), new Country(60,"Austria"), new Country(61,"Colombia"), new Country(62,"Brazil"), new Country(63,"Azerbaijan"), new Country(64,"Bosnia and Herzegovina"), new Country(65,"Thailand"), new Country(66,"Belarus"), new Country(67,"Bulgaria"), new Country(68,"Bangladesh"), new Country(69,"Spain"), new Country(70,"Italy"), new Country(71,"Finland"), new Country(72,"United Kingdom"), new Country(73,"Bolivia"), new Country(74,"United Kingdom"), new Country(75,"Belgium"), new Country(76,"Bulgaria"), new Country(77,"Israel"), new Country(78,"Canada"), new Country(79,"Luxembourg"), new Country(80,"Jamaica"), new Country(81,"Romania"), new Country(82,"Hong Kong SAR, China"), new Country(83,"Chinese Taipei"), new Country(84,"China (People's Republic of)"), new Country(85,"China (People's Republic of)"), new Country(86,"China (People's Republic of)"), new Country(87,"China (People's Republic of)"), new Country(88,"Ireland"), new Country(89,"South Africa"), new Country(90,"Germany"), new Country(91,"Panama"), new Country(92,"Turkey"), new Country(93,"France"), new Country(94,"Croatia"), new Country(95,"Cuba"), new Country(96,"Cyprus"), new Country(97,"Czech Republic"), new Country(98,"United States"), new Country(99,"United Kingdom"), new Country(100,"Bahrain"), new Country(101,"Russian Federation"), new Country(102,"Hong Kong SAR, China"), new Country(103,"Egypt"), new Country(104,"Israel"), new Country(105,"United Arab Emirates"), new Country(106,"Estonia"), new Country(107,"Ethiopia"), new Country(108,"United Arab Emirates"), new Country(109,"Portugal"), new Country(110,"Germany"), new Country(111,"Germany"), new Country(112,"Chinese Taipei"), new Country(113,"United States"), new Country(114,"Fiji"), new Country(115,"Finland"), new Country(116,"United Kingdom"), new Country(117,"Turkey"), new Country(118,"Indonesia"), new Country(119,"Georgia"), new Country(120,"Germany"), new Country(121,"Bahrain"), new Country(122,"Germany"), new Country(123,"China (People's Republic of)"), new Country(124,"United States"), new Country(125,"Portugal"), new Country(126,"Hong Kong SAR, China"), new Country(127,"Hong Kong SAR, China"), new Country(128,"Spain"), new Country(129,"Iceland"), new Country(130,"Curaçao"), new Country(131,"South Africa"), new Country(132,"Austria"), new Country(133,"Iran, Islamic Republic of"), new Country(134,"Iran, Islamic Republic of"), new Country(135,"Israel"), new Country(136,"Japan"), new Country(137,"Kuwait"), new Country(138,"India"), new Country(139,"India"), new Country(140,"United States"), new Country(141,"Jordan"), new Country(142,"Russian Federation"), new Country(143,"Russian Federation"), new Country(144,"China (People's Republic of)"), new Country(145,"Kenya"), new Country(146,"Iran, Islamic Republic of"), new Country(147,"Netherlands"), new Country(148,"Korea"), new Country(149,"Kuwait"), new Country(150,"Costa Rica"), new Country(151,"Mozambique"), new Country(152,"Chile"), new Country(153,"Argentina"), new Country(154,"Chile"), new Country(155,"Peru"), new Country(156,"Ecuador"), new Country(157,"Antigua and Barbuda"), new Country(158,"Libya"), new Country(159,"Russian Federation"), new Country(160,"Poland"), new Country(161,"Germany"), new Country(162,"Germany"), new Country(163,"Germany"), new Country(164,"Luxembourg"), new Country(165,"Iran, Islamic Republic of"), new Country(166,"Malaysia"), new Country(167,"Sweden"), new Country(168,"Netherlands"), new Country(169,"Mexico"), new Country(170,"Lebanon"), new Country(171,"Italy"), new Country(172,"Mongolia"), new Country(173,"Montenegro"), new Country(174,"Egypt"), new Country(175,"Austria"), new Country(176,"Egypt"), new Country(177,"Japan"), new Country(178,"Tunisia"), new Country(179,"Greece"), new Country(180,"Oman"), new Country(181,"Turkey"), new Country(182,"Philippines"), new Country(183,"Turkey"), new Country(184,"Portugal"), new Country(185,"Pakistan"), new Country(186,"Tanzania, United Republic of"), new Country(187,"Switzerland"), new Country(188,"Australia"), new Country(189,"Qatar"), new Country(190,"Russian Federation"), new Country(191,"Morocco"), new Country(192,"Brunei Darussalam"), new Country(193,"Jordan"), new Country(194,"South Africa"), new Country(195,"South Africa"), new Country(196,"Afghanistan"), new Country(197,"Sweden"), new Country(198,"Portugal"), new Country(199,"Portugal"), new Country(200,"Saudi Arabia"), new Country(201,"China (People's Republic of)"), new Country(202,"China (People's Republic of)"), new Country(203,"China (People's Republic of)"), new Country(204,"Singapore"), new Country(205,"Singapore"), new Country(206,"Russian Federation"), new Country(207,"China (People's Republic of)"), new Country(208,"Singapore"), new Country(209,"South Africa"), new Country(210,"Sri Lanka"), new Country(211,"Sudan"), new Country(212,"Turkey"), new Country(213,"Suriname"), new Country(214,"Switzerland"), new Country(215,"Tunisia"), new Country(216,"Syrian Arab Republic"), new Country(217,"Angola"), new Country(218,"El Salvador"), new Country(219,"Peru"), new Country(220,"Cape Verde"), new Country(221,"Paraguay"), new Country(222,"Brazil"), new Country(223,"Ecuador"), new Country(224,"Portugal"), new Country(225,"Romania"), new Country(226,"Algeria"), new Country(227,"Thailand"), new Country(228,"Turkey"), new Country(229,"China (People's Republic of)"), new Country(230,"Belgium"), new Country(231,"Russian Federation"), new Country(232,"Chinese Taipei"), new Country(233,"Germany"), new Country(234,"Tunisia"), new Country(235,"Ukraine"), new Country(236,"United States"), new Country(237,"United States"), new Country(238,"United States"), new Country(239,"Russian Federation"), new Country(240,"Uzbekistan"), new Country(241,"Vietnam"), new Country(242,"United Kingdom"), new Country(243,"Australia"), new Country(244,"Belgium"), new Country(245,"Mexico"), new Country(246,"Russian Federation"), new Country(247,"Brazil"), new Country(248,"Portugal"), new Country(249,"Norway"), new Country(250,"China (People's Republic of)"), new Country(251,"Yemen"), new Country(252,"Azerbaijan"), new Country(253,"Azerbaijan") }; } } <file_sep>/FlightsManagementSystem/LoggedInAirlineFacade.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FlightsManagementSystem { public class LoggedInAirlineFacade : AnonymousUserFacade, ILoggedInAirlineFacade { public void CancelFlight(LoginToken<AirlineCompany> token, Flight flight) { if (token.User.Id == flight.AirlineCompanyId) { _flightDAO.Remove(flight); } } public void ChangeMyPassword(LoginToken<AirlineCompany> token, string oldPassword, string newPassword) { if (token.User != null) { AirlineCompany company = _airlineDAO.GetAirlineByUsername(token.User.UserName); if (company.Password.ToString() == oldPassword) { company.Password = <PASSWORD>; _airlineDAO.Update(company); } else { throw new WrongPasswordException("Wrong Password"); } } } public void CreateFlight(LoginToken<AirlineCompany> token, Flight flight) { if (token.User.Id == flight.AirlineCompanyId) { _flightDAO.Add(flight); } } public IList<Flight> GetAllFlights(LoginToken<AirlineCompany> token) { if (token.User != null) { return _flightDAO.GetAll(); } return null; } public IList<Ticket> GetAllTickets(LoginToken<AirlineCompany> token) { if (token.User != null) { return _ticketDAO.GetAll(); } return null; } public void ModifyAirlineDetails(LoginToken<AirlineCompany> token, AirlineCompany airline) { if (token.User.Id == airline.Id) { _airlineDAO.Update(airline); } } public void UpdateFlight(LoginToken<AirlineCompany> token, Flight flight) { if (token.User.Id == flight.AirlineCompanyId) { _flightDAO.Update(flight); } } } } <file_sep>/FlightsManagementSystem/Administrator.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FlightsManagementSystem { public class Administrator : IUser { public string UserName; public string Password; public Administrator(string userName, string password) { UserName = userName; Password = <PASSWORD>; } } } <file_sep>/FlightsManagementSystem/IAirlineDAO.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FlightsManagementSystem { public interface IAirlineDAO :IBasicDB<AirlineCompany> { AirlineCompany GetAirlineByUsername(string name); IList<AirlineCompany> GetAllAirlinesByCountry(int countryId); } } <file_sep>/Controllers/AnonymousFacadeController.cs using FlightsManagementSystem; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; namespace FlightsWebApplication.Controllers { public class AnonymousFacadeController : ApiController { AnonymousUserFacade facade = new AnonymousUserFacade(); [ResponseType(typeof(Flight))] [HttpGet] [Route("api/AnonymousFacade/GetAllFlights")] public IHttpActionResult GetAllFlights() { IList<Flight> flights = facade.GetAllFlights(); if (flights.Count > 0) { return Ok(flights); } return NotFound(); } [ResponseType(typeof(AirlineCompany))] [HttpGet] [Route("api/AnonymousFacade/GetAllAirlineCompanies")] public IHttpActionResult GetAllAirlineCompanies() { IList<AirlineCompany> airlines = facade.GetAllAirlineCompanies(); if (airlines.Count > 0) { return Ok(airlines); } return NotFound(); } [ResponseType(typeof(Flight))] [HttpGet] [Route("api/AnonymousFacade/GetAllFlightsVacancy")] public IHttpActionResult GetAllFlightsVacancy() { Dictionary<Flight, int> flights = facade.GetAllFlightsVacancy(); if (flights.Count > 0) { return Ok(flights); } return NotFound(); } [ResponseType(typeof(Flight))] [HttpGet] [Route("api/AnonymousFacade/GetFlightById/{id}")] public IHttpActionResult GetFlightById(int id) { Flight flight = facade.GetFlightById(id); if (flight.Id != 0) { return Ok(flight); } return NotFound(); } [ResponseType(typeof(Flight))] [HttpGet] [Route("api/AnonymousFacade/GetFlightsByOriginCountry/{countryCode}")] public IHttpActionResult GetFlightsByOriginCountry(int countryCode) { IList<Flight> flights = facade.GetFlightsByOriginCountry(countryCode); if (flights.Count > 0) { return Ok(flights); } return NotFound(); } [ResponseType(typeof(Flight))] [HttpGet] [Route("api/AnonymousFacade/GetFlightsByDestinationCountry/{countryCode}")] public IHttpActionResult GetFlightsByDestinationCountry(int countryCode) { IList<Flight> flights = facade.GetFlightsByDestinationCountry(countryCode); if (flights.Count > 0) { return Ok(flights); } return NotFound(); } [ResponseType(typeof(Flight))] [HttpGet] [Route("api/AnonymousFacade/GetFlightsByDepatrureDate/{departureDate}")] public IHttpActionResult GetFlightsByDepatrureDate(DateTime departureDate) { IList<Flight> flights = facade.GetFlightsByDepatrureDate(departureDate); if (flights.Count > 0) { return Ok(flights); } return NotFound(); } [ResponseType(typeof(Flight))] [HttpGet] [Route("api/AnonymousFacade/GetFlightsByLandingDate/{landingDate}")] public IHttpActionResult GetFlightsByLandingDate(DateTime landingDate) { IList<Flight> flights = facade.GetFlightsByLandingDate(landingDate); if (flights.Count > 0) { return Ok(flights); } return NotFound(); } // query string // ...api/flights/search ? airlineCompanyId = d & originCountryCode = o // ...api/flights/search ? originCountryCode = o & airlineCompanyId = d [Route("api/flights/search")] [HttpGet] public IEnumerable<Flight> GetByFilter(string airlineCompanyId = "", string originCountryCode = "") { if (airlineCompanyId == "" && originCountryCode != "") return facade.GetAllFlights().Where(m => m.OriginCountryCode.ToString().ToUpper().Contains(originCountryCode.ToUpper())); if (airlineCompanyId != "" && originCountryCode == "") return facade.GetAllFlights().Where(m => m.AirlineCompanyId.ToString().ToUpper().Contains(airlineCompanyId.ToUpper())); ; return facade.GetAllFlights().Where(m => m.AirlineCompanyId.ToString().ToUpper().Contains(airlineCompanyId.ToUpper()) && m.OriginCountryCode.ToString().ToUpper().Contains(originCountryCode.ToUpper())); } } } <file_sep>/FlightsManagementSystem/FlyingCenterSystem.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace FlightsManagementSystem { public class FlyingCenterSystem { private static FlyingCenterSystem _instance = null; LoginToken<Administrator> administratorToken = new LoginToken<Administrator>(); static object key = new object(); bool moveToHistoryToday = false; Thread moveToHistory = new Thread(()=> { new TicketDAOMSSQL().MoveTicketsToTicketHistory(); new FlightDAOMSSQL().MoveFlightsToFlightstHistory(); }); public FlyingCenterSystem() { if (DateTime.Now.Hour >= AppConfig.TIMETOMOVETOHISTORY) { if (moveToHistoryToday == false) { moveToHistory.Start(); moveToHistoryToday = true; } } else { moveToHistoryToday = false; } } public static FlyingCenterSystem GetInstance() { if (_instance == null) { lock (key) { if (_instance == null) { _instance = new FlyingCenterSystem(); } } } return _instance; } public FacadeBase GetFacade(string user, string password, out ILoginToken token) { LoginService loginService = new LoginService(); if (loginService.TryAdminLogin(user, password, out LoginToken<Administrator> AdminToken)) { token = AdminToken; return new LoggedInAdministratorFacade(); } else if (loginService.TryAirlineLogin(user, password, out LoginToken<AirlineCompany> AirLineToken)) { token = AirLineToken; return new LoggedInAirlineFacade(); } else if (loginService.TryCustomerLogin(user, password, out LoginToken<Customer> CustomerToken)) { token = CustomerToken; return new LoggedInCustomerFacade(); } token = null; return new AnonymousUserFacade(); } } } <file_sep>/TestFlightProject/CustomerTest.cs using System; using System.Collections.Generic; using FlightsManagementSystem; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace TestFlightProject { [TestClass] public class CustomerTest { LoggedInCustomerFacade facade = FlyingCenterSystem.GetInstance().GetFacade("YR","1234", out ILoginToken token) as LoggedInCustomerFacade; LoginToken<Customer> CustomerLogin = new LoginToken<Customer>(); [TestMethod] public void Login() { Assert.AreEqual(facade.GetType(), facade.GetType()); } [TestMethod] public void CancelTicket() { Ticket ticket = new Ticket(facade.GetAllFlights()[0].Id, 10113); facade.CancelTicket(CustomerLogin, ticket); } [TestMethod] public void GetAllMyFlights() { facade.GetAllMyFlights(CustomerLogin); } [TestMethod] public void PurchaseTicket() { AdministratorTest AT = new AdministratorTest(); LoginToken<Administrator> AdminLogin = new LoginToken<Administrator>(); Ticket ticket = new Ticket(facade.GetAllFlights()[0].Id, AT.GetCustomerByUserName("YR")); facade.PurchaseTicket(CustomerLogin,ticket); } } } <file_sep>/UnitTestWebApi/TestResource.cs using FlightsManagementSystem; using System; namespace UnitTestWebApi { internal class TestResource { public static Flight flight = new Flight() { AirlineCompanyId = 31192, DepartureTime = new DateTime(2020, 01, 19, 21, 01, 000), LandingTime = new DateTime(2020, 01, 20, 20, 57, 000), DestinationCountryCode = 21962, OriginCountryCode = 21958 }; public static Customer newCustomer = new Customer() { FirstName = "israel", LastName = "israeli", UserName = "ils", Password = "<PASSWORD>", Address = "Tel Aviv", PhoneNo = "054-5207871", CreditCardNumber = "4580 1010 2020 4040" }; } }<file_sep>/Controllers/BasicAuthenticationCustomerAttribute.cs using FlightsManagementSystem; using System; using System.Net; using System.Net.Http; using System.Security.Principal; using System.Text; using System.Threading; using System.Web.Http.Controllers; using System.Web.Http.Filters; namespace FlightsWebApplication.Controllers { internal class BasicAuthenticationCustomerAttribute : AuthorizationFilterAttribute { LoggedInAdministratorFacade facade = new LoggedInAdministratorFacade(); Administrator admin = new Administrator("admin","9999"); LoginToken<Administrator> AdminLogin = new LoginToken<Administrator>(); Customer customer = new Customer(); public override void OnAuthorization(HttpActionContext actionContext) { string authenticationToken = actionContext.Request.Headers.Authorization.Parameter; string decodedAuthenticationToken = Encoding.UTF8.GetString( Convert.FromBase64String(authenticationToken)); string[] usernamePasswordArray = decodedAuthenticationToken.Split(':'); string username = usernamePasswordArray[0]; string password = <PASSWORD>[1]; try { AdminLogin.User = admin; customer = facade.GetCustomerByUserName(AdminLogin, username); if (username == customer.UserName && password == <PASSWORD>) { actionContext.Request.Properties["token"] = customer; } else { actionContext.Response = actionContext.Request .CreateResponse(HttpStatusCode.Unauthorized, "incorrect user or password"); } } catch (Exception) { } } } }<file_sep>/DB_Generator/DataDB.cs using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; namespace DB_Generator { class DataDB { private const string URL = "https://restcountries.eu/rest/v2"; private const string URL1 = "https://randomuser.me/api"; //private const string URL = "http://webapichat110919.azurewebsites.net/api/messages"; FlightsManagementSystem.CountryDAOMSSQL countryDAOMSSQL = new FlightsManagementSystem.CountryDAOMSSQL(); FlightsManagementSystem.FlightDAOMSSQL flightDAOMSSQL = new FlightsManagementSystem.FlightDAOMSSQL(); FlightsManagementSystem.AirlineDAOMSSQL airlineDAOMSSQL = new FlightsManagementSystem.AirlineDAOMSSQL(); FlightsManagementSystem.CustomerDAOMSSQL customerDAOMSSQL = new FlightsManagementSystem.CustomerDAOMSSQL(); FlightsManagementSystem.TicketDAOMSSQL ticketDAOMSSQL = new FlightsManagementSystem.TicketDAOMSSQL(); private static List<string> companiesList = new List<string>(); private static List<string> countriesList = new List<string>(); int counter; int countriesCounter = 0; int companiesCounter = 0; int customersCounter = 0; int ticketsCounter = 0; int flightsCounter = 0; int index = 0; int index2 = 0; Random r = new Random(); static async Task<Uri> CreateAsync(FlightsManagementSystem.Country country, HttpClient client) { HttpResponseMessage response = await client.PostAsJsonAsync( "api/countries", country); response.EnsureSuccessStatusCode(); // return URI of the created resource. return response.Headers.Location; } // GET REQUEST public void AddCountriesToDB(int countries) { int range = countries; HttpClient client = new HttpClient(); client.BaseAddress = new Uri(URL); // Add an Accept header for JSON format. client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); // List data response. HttpResponseMessage response = client.GetAsync("").Result; // Blocking call! Program will wait here until a response is received or a timeout occurs. if (response.IsSuccessStatusCode) { // Parse the response body. var dataObjects = response.Content.ReadAsAsync<IEnumerable<Country>>().Result; foreach (var d in dataObjects) { if (countriesCounter < range) { FlightsManagementSystem.Country country = new FlightsManagementSystem.Country(); countriesList.Add(d.name); country.CountryName = d.name; countryDAOMSSQL.Add(country); countriesCounter++; counter++; Thread.Sleep(20); } } } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } //Make any other calls using HttpClient here. //Dispose once all HttpClient calls are complete. This is not necessary if the containing object will be disposed of; for example in this case the HttpClient instance will be disposed automatically when the application terminates so the following call is superfluous. client.Dispose(); } internal void DeleteDB() { customerDAOMSSQL.RemoveAll(); flightDAOMSSQL.RemoveAll(); airlineDAOMSSQL.RemoveAll(); countryDAOMSSQL.RemoveAll(); } internal int GetCounter() { return counter; } internal void AddCompaniesToDB(int companies) { int range = companies; for (int i = 0; i < range; i++) { index = r.Next(countriesList.Count); companiesList.Add(AirLinesCompanies.companies[i].UserName); FlightsManagementSystem.AirlineCompany company = new FlightsManagementSystem.AirlineCompany(); company.AirlineName = AirLinesCompanies.companies[i].AirlineName; company.UserName = AirLinesCompanies.companies[i].UserName; company.Password = AirLinesCompanies.companies[i].Password; //company.CountryCode = AirLinesCompanies.companies[i].CountryCode; company.CountryCode = countryDAOMSSQL.GetByName(countriesList[index]).Id; airlineDAOMSSQL.Add(company); counter++; companiesCounter++; Thread.Sleep(20); } } internal string getMessegeCountries(int countries) { if (countriesCounter < countries) { return $"- Creating Countries ({countriesCounter}/{countries})"; } else { return $"- {countries} Countries created "; } } internal string getMessegeCompanies(int companies) { if (companiesCounter < companies) { return $"- Creating Companies ({companiesCounter}/{companies})"; } else { return $"- {companies} Companies created "; } } internal string getMessegeCustomers(int customers) { if (customersCounter < customers) { return $"- Creating Customers ({customersCounter}/{customers})"; } else { return $"- {customers} Customers created "; } } internal string getMessegeFlights(int flights) { if (flightsCounter < flights) { return $"- Creating Flights ({flightsCounter}/{flights})"; } else { return $"- {flights} Flights created "; } } internal string getMessegeTickets(int tickets) { if (ticketsCounter < tickets) { return $"- Creating Tickets ({ticketsCounter}/{tickets})"; } else { return $"- {tickets} Tickets created "; } } internal void AddTicketsToDB(int tickets) { int range = tickets; IList<FlightsManagementSystem.Customer> customers = customerDAOMSSQL.GetAll(); IList<FlightsManagementSystem.Flight> flights = flightDAOMSSQL.GetAll(); FlightsManagementSystem.Ticket ticket = new FlightsManagementSystem.Ticket(); for (int i = 0; i < range; i++) { index = r.Next(flights.Count); index2 = r.Next(customers.Count); ticket.FlightId = flights[index].Id; ticket.CustomerId = customers[index2].Id; ticketDAOMSSQL.Add(ticket); flights[index].RemainingTickets--; flightDAOMSSQL.Update(flights[index]); customers.RemoveAt(index2); counter++; ticketsCounter++; Thread.Sleep(20); } } internal void AddFlightsToDB(int flights) { int range = flights; foreach (var company in companiesList) { for (int i = 0; i < range; i++) { int countryA = r.Next(countriesList.Count); int countryB; do { countryB = r.Next(countriesList.Count); } while (countryB == countryA); index = r.Next(companiesList.Count); FlightsManagementSystem.Flight flight = new FlightsManagementSystem.Flight(); flight.AirlineCompanyId = airlineDAOMSSQL.GetAirlineByUsername(companiesList[index]).Id; flight.OriginCountryCode = countryDAOMSSQL.GetByName(countriesList[countryA]).Id; flight.DestinationCountryCode = countryDAOMSSQL.GetByName(countriesList[countryB]).Id; DateTime start = new DateTime(DateTime.Today.Year, DateTime.Today.Month,DateTime.Today.Day); flight.DepartureTime = start.AddHours(r.Next(120)).AddMinutes(r.Next(60)); flight.LandingTime = flight.DepartureTime.AddHours(r.Next(24)).AddMinutes(r.Next(60)); flight.RemainingTickets = 30; flightDAOMSSQL.Add(flight); counter++; flightsCounter++; Thread.Sleep(2); } } } internal void AddCustomersToDB(int customers) { int range = customers; FlightsManagementSystem.Customer customer = new FlightsManagementSystem.Customer(); for (int i = 0; i < range; i++) { index = r.Next(Customers.firstNames.Count); customer.FirstName = Customers.firstNames[index]; customer.LastName = Customers.lastNames[index]; customer.UserName = customer.FirstName + customer.LastName; customer.Password = <PASSWORD>[index]; customer.Address = Customers.adresses[index]; customer.PhoneNo = Customers.phoneNumbers[index]; customer.CreditCardNumber = r.Next(100000000, 999999999).ToString(); customerDAOMSSQL.Add(customer); Customers.firstNames.RemoveAt(index); Customers.lastNames.RemoveAt(index); Customers.passwords.RemoveAt(index); Customers.adresses.RemoveAt(index); Customers.phoneNumbers.RemoveAt(index); counter++; customersCounter++; } } } } <file_sep>/FlightsManagementSystem/AirlineCompany.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FlightsManagementSystem { public class AirlineCompany : IPoco, IUser { public long Id { get; set; } public string AirlineName { get; set; } public string UserName { get; set; } public string Password { get; set; } public long CountryCode { get; set; } public AirlineCompany() { } public AirlineCompany(string airlineName, string userName, string password, long countryCode) { AirlineName = airlineName; UserName = userName; Password = <PASSWORD>; CountryCode = countryCode; } public static bool operator ==(AirlineCompany a, AirlineCompany b) { if (ReferenceEquals(a, null) && ReferenceEquals( b, null)) { return true; } if (ReferenceEquals(a, null) || ReferenceEquals(b, null)) { return false; } return a.Id == b.Id; } public static bool operator !=(AirlineCompany a, AirlineCompany b) { return !(a == b); } public override string ToString() { return $"AirlineName: {AirlineName} UserName: {UserName}" + $" Password:{<PASSWORD>} CountryCode: {CountryCode}"; } public override bool Equals(object obj) { AirlineCompany other = obj as AirlineCompany; return this == other; } public override int GetHashCode() { return Id.GetHashCode(); } } } <file_sep>/DB_Generator/MainWIndowViewModel.cs using Prism.Commands; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; namespace DB_Generator { class MainWIndowViewModel : INotifyPropertyChanged { public DelegateCommand AddCommand { get; set; } public DelegateCommand ReplaceCommand { get; set; } public event PropertyChangedEventHandler PropertyChanged; private bool isEnable; public bool doWork = true; private string countriesmessage; private string companiesmessage; private string customersmessage; private string flightsmessage; private string ticketsmessage; private string companies; private string customers; private string administrators; private string flights; private string tickets; private string countries; private int barValue; private int maxPb = 100; public bool IsEnable { get { return isEnable; } set { isEnable = value; OnPropertyChanged("IsEnable"); } } public int MaxPb { get { return maxPb; } set { maxPb = value; OnPropertyChanged("MaxPb"); } } public int BarValue { get { return barValue; } set { barValue = value; OnPropertyChanged("BarValue"); } } public string Countriesmessage { get { return countriesmessage; } set { countriesmessage = value; OnPropertyChanged("Countriesmessage"); } } public string Companiesmessage { get { return companiesmessage; } set { companiesmessage = value; OnPropertyChanged("Companiesmessage"); } } public string Customersmessage { get { return customersmessage; } set { customersmessage = value; OnPropertyChanged("Customersmessage"); } } public string Flightsmessage { get { return flightsmessage; } set { flightsmessage = value; OnPropertyChanged("Flightsmessage"); } } public string Ticketsmessage { get { return ticketsmessage; } set { ticketsmessage = value; OnPropertyChanged("Ticketsmessage"); } } public string Companies { get { return companies; } set { companies = value; OnPropertyChanged("Companies"); } } public string Customers { get { return customers; } set { customers = value; OnPropertyChanged("Customers"); } } public string Administrators { get { return administrators; } set { administrators = value; OnPropertyChanged("Administrators"); } } public string Flights { get { return flights; } set { flights = value; OnPropertyChanged("Flights"); } } public string Tickets { get { return tickets; } set { tickets = value; OnPropertyChanged("Tickets"); } } public string Countries { get { return countries; } set { countries = value; OnPropertyChanged("Countries"); } } public MainWIndowViewModel() { AddCommand = new DelegateCommand(ExecuteAddCommand, CanExecute); ReplaceCommand = new DelegateCommand(ExecuteReplaceCommand, CanExecute); isEnable = true; } private void ExecuteReplaceCommand() { doWork = false; IsEnable = false; DataDB data = new DataDB(); data.DeleteDB(); IsEnable = true; BarValue = 0; Countriesmessage = "Data has been deleted!"; Customersmessage = ""; Companiesmessage = ""; Ticketsmessage = ""; Flightsmessage = ""; } private bool CanExecute() { return true; } private void ExecuteAddCommand() { doWork = true; IsEnable = false; int total = 0; int _Companies = 0; int _Customers = 0; int _Flights = 0; int _Tickets = 0; int _Countries = 0; try { _Companies = Convert.ToInt32(Companies); _Customers = Convert.ToInt32(Customers); _Flights = Convert.ToInt32(Flights); _Tickets = Convert.ToInt32(Tickets); _Countries = Convert.ToInt32(Countries); total = _Companies + _Customers + _Flights*_Companies + _Tickets + _Countries; } catch (Exception) { } DataDB data = new DataDB(); Task t = Task.Run(() => { do { BarValue = data.GetCounter() * 100 / total; Countriesmessage = data.getMessegeCountries(_Countries); Companiesmessage = data.getMessegeCompanies(_Companies); Customersmessage = data.getMessegeCustomers(_Customers); Flightsmessage = data.getMessegeFlights(_Flights * _Companies); Ticketsmessage = data.getMessegeTickets(_Tickets); Thread.Sleep(1); } while (data.GetCounter() <= total && doWork); }); AddDB(data,_Companies,_Customers,_Flights,_Tickets,_Countries, total); } private async void AddDB(DataDB data, int companies,int customers,int flights,int tickets, int countries, int total) { await Task.Run(() => { data.AddCountriesToDB(countries); data.AddCompaniesToDB(companies); data.AddCustomersToDB(customers); data.AddFlightsToDB(flights); data.AddTicketsToDB(tickets); doWork = false; IsEnable = true; }); } public void OnPropertyChanged(string property) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(property)); } } } } <file_sep>/FlightsManagementSystem/TicketDAOMSSQL.cs using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FlightsManagementSystem { public class TicketDAOMSSQL : ITicketDAO { public void Add(Ticket t) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); using (con) { SqlCommand cmd = new SqlCommand("ADD_TICKET", con); cmd.Parameters.Add(new SqlParameter("@FLIGHT_ID", t.FlightId)); cmd.Parameters.Add(new SqlParameter("@CUSTOMER_ID", t.CustomerId)); con.Open(); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); con.Close(); } } internal void MoveTicketsToTicketHistory() { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); using (con) { SqlCommand cmd = new SqlCommand("MOVE_TICKETS_TO_HISTORY", con); cmd.Parameters.Add(new SqlParameter("@Trheehoursago", DateTime.Now.AddHours(-3))); con.Open(); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); con.Close(); } } public Ticket Get(int id) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); Ticket t = new Ticket(); using (con) { SqlCommand cmd = new SqlCommand("SELECT_TICKETS_BY_ID", con); cmd.Parameters.Add(new SqlParameter("@id", id)); con.Open(); cmd.CommandType = CommandType.StoredProcedure; SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default); while (reader.Read()) { t.Id = (long)reader["ID"]; t.FlightId = (long)reader["FLIGHT_ID"]; t.CustomerId = (long)reader["CUSTOMER_ID"]; } con.Close(); return t; } } public IList<Ticket> GetAll() { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); List<Ticket> tickets = new List<Ticket>(); using (con) { SqlCommand cmd = new SqlCommand($"SELECT_ALL_TICKETS", con); con.Open(); cmd.CommandType = CommandType.StoredProcedure; SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default); { while (reader.Read()) { Ticket t = new Ticket(); t.Id = (long)reader["ID"]; t.FlightId = (long)reader["FLIGHT_ID"]; t.CustomerId = (long)reader["CUSTOMER_ID"]; tickets.Add(t); } con.Close(); return tickets; } } } public void Remove(Ticket t) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); using (con) { SqlCommand cmd = new SqlCommand($"DELETE_TICKET", con); cmd.Parameters.Add(new SqlParameter("@id", t.Id)); con.Open(); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); con.Close(); } } public void Update(Ticket t) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); using (con) { SqlCommand cmd = new SqlCommand($"UPDATE_TICKET", con); cmd.Parameters.Add(new SqlParameter("@id", t.Id)); cmd.Parameters.Add(new SqlParameter("@FLIGHT_ID", t.FlightId)); cmd.Parameters.Add(new SqlParameter("@CUSTOMER_ID", t.CustomerId)); con.Open(); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); con.Close(); } } } } <file_sep>/TestFlightProject/AdministratorTest.cs using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using FlightsManagementSystem; using System.Collections.Generic; namespace TestFlightProject { [TestClass] public class AdministratorTest { TestCenter Test = new TestCenter(); LoggedInAdministratorFacade Admin = new LoggedInAdministratorFacade(); LoginToken<Administrator> AdminLogin = new LoginToken<Administrator>(); FacadeBase facade = FlyingCenterSystem.GetInstance().GetFacade(AppConfig.ADMIN_USER, AppConfig.ADMIN_PASSWORD,out ILoginToken token); Customer c = new Customer("Yehuda", "Reisner", "Yuda", "1234", "<NAME>", "0545207871", "4580"); Country country = new Country("Israel"); AirlineCompany airline = new AirlineCompany("ELAL", "eee", "111", 13); [TestMethod] public void Login() { Assert.AreEqual(facade.GetType(), Admin.GetType()); } [TestMethod] public void DeleteData() { Test.DeleteAllData(); } [TestMethod] public void CreateNewCountry() { Admin.CreateNewCountry(AdminLogin, country); } [TestMethod] public void CreateNewAirline() { Admin.CreateNewAirline(AdminLogin, airline); } [TestMethod] public void CreateNewCustomer() { Admin.CreateNewCustomer(AdminLogin, c); } [TestMethod] public void RemoveAirline() { IList<AirlineCompany> airlines = Admin.GetAllAirlineCompanies(); Admin.RemoveAirline(AdminLogin, airlines[0]); } [TestMethod] public void RemoveCustomer() { Admin.RemoveCustomer(AdminLogin,c); } [TestMethod] public void UpdateAirlineDetails() { CreateNewAirline(); IList<AirlineCompany> airlines = Admin.GetAllAirlineCompanies(); airlines[0].UserName = "LLL"; Admin.UpdateAirlineDetails(AdminLogin, airlines[0]); } [TestMethod] public void UpdateCustomerDetails() { Customer customer = Admin.GetCustomerByUserName(AdminLogin, c.UserName); customer.UserName = "YR"; Admin.UpdateCustomerDetails(AdminLogin, customer); } [TestMethod] public long GetCustomerByUserName(string user) { return Admin.GetCustomerByUserName(AdminLogin, user).Id; } } } <file_sep>/FlightsManagementSystem/FlightDAOMSSQL.cs using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FlightsManagementSystem { public class FlightDAOMSSQL : IFlightDAO { public void Add(Flight t) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); using (con) { SqlCommand cmd = new SqlCommand("ADD_FLIGHT", con); cmd.Parameters.Add(new SqlParameter("@AIRLINECOMPANY_ID", t.AirlineCompanyId)); cmd.Parameters.Add(new SqlParameter("@ORIGIN_COUNTRY_CODE", t.OriginCountryCode)); cmd.Parameters.Add(new SqlParameter("@DESTINATION_COUNTRY_CODE", t.DestinationCountryCode)); cmd.Parameters.Add(new SqlParameter("@DEPARTURE_TIME", t.DepartureTime)); cmd.Parameters.Add(new SqlParameter("@LANDING_TIME", t.LandingTime)); cmd.Parameters.Add(new SqlParameter("@REMAINING_TICKETS", t.RemainingTickets)); con.Open(); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); con.Close(); } } internal void MoveFlightsToFlightstHistory() { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); using (con) { SqlCommand cmd = new SqlCommand("MOVE_FLIGHTS_TO_HISTORY", con); cmd.Parameters.Add(new SqlParameter("@Trheehoursago", DateTime.Now.AddHours(-3))); con.Open(); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); con.Close(); } } public Flight Get(int id) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); Flight t = new Flight(); using (con) { SqlCommand cmd = new SqlCommand("SELECT_FLIGHT_BY_ID", con); cmd.Parameters.Add(new SqlParameter("@id", id)); con.Open(); cmd.CommandType = CommandType.StoredProcedure; SqlDataReader reader = cmd.ExecuteReader(); { while (reader.Read()) { t.Id = (long)reader["ID"]; t.AirlineCompanyId = (long)reader["AIRLINECOMPANY_ID"]; t.OriginCountryCode = (long)reader["ORIGIN_COUNTRY_CODE"]; t.DestinationCountryCode = (long)reader["DESTINATION_COUNTRY_CODE"]; t.DepartureTime = (DateTime)reader["DEPARTURE_TIME"]; t.LandingTime = (DateTime)reader["LANDING_TIME"]; t.RemainingTickets = (int)reader["REMAINING_TICKETS"]; } con.Close(); return t; } } } public IList<Flight> GetAll() { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); List<Flight> flights = new List<Flight>(); using (con) { SqlCommand cmd = new SqlCommand("SELECT_ALL_FLIGHT", con); con.Open(); cmd.CommandType = CommandType.StoredProcedure; SqlDataReader reader = cmd.ExecuteReader(); { while (reader.Read()) { Flight t = new Flight(); t.Id = (long)reader["ID"]; t.AirlineCompanyId = (long)reader["AIRLINECOMPANY_ID"]; t.OriginCountryCode = (long)reader["ORIGIN_COUNTRY_CODE"]; t.DestinationCountryCode = (long)reader["DESTINATION_COUNTRY_CODE"]; t.DepartureTime = (DateTime)reader["DEPARTURE_TIME"]; t.LandingTime = (DateTime)reader["LANDING_TIME"]; t.RemainingTickets = (int)reader["REMAINING_TICKETS"]; flights.Add(t); } con.Close(); return flights; } } } public void RemoveAll() { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); using (con) { con.Open(); SqlCommand cmd = new SqlCommand($"DELETE_ALL_FLIGHTS", con); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); con.Close(); } } public Dictionary<Flight, int> GetAllFlightsVacancy() { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); Dictionary<Flight,int> vacancyFlights = new Dictionary<Flight,int>(); Flight t = new Flight(); using (con) { SqlCommand cmd = new SqlCommand("SELECT_ALL_FLIGHTS_VACANCY", con); con.Open(); cmd.CommandType = CommandType.StoredProcedure; SqlDataReader reader = cmd.ExecuteReader(); { while (reader.Read()) { t.Id = (long)reader["ID"]; t.AirlineCompanyId = (long)reader["AIRLINECOMPANY_ID"]; t.OriginCountryCode = (long)reader["ORIGIN_COUNTRY_CODE"]; t.DestinationCountryCode = (long)reader["DESTINATION_COUNTRY_CODE"]; t.DepartureTime = (DateTime)reader["DEPARTURE_TIME"]; t.LandingTime = (DateTime)reader["LANDING_TIME"]; t.RemainingTickets = (int)reader["REMAINING_TICKETS"]; vacancyFlights.Add(t,t.RemainingTickets); } con.Close(); return vacancyFlights; } } } public Flight GetFlightById(int id) { return Get(id); } public IList<Flight> GetFlightsByCustomer(Customer customer) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); List<Flight> flights = new List<Flight>(); Flight t = new Flight(); using (con) { SqlCommand cmd = new SqlCommand("SELECT_FLIGHTS_BY_CUSTOMER", con); cmd.Parameters.Add(new SqlParameter("@id", customer.Id)); con.Open(); cmd.CommandType = CommandType.StoredProcedure; SqlDataReader reader = cmd.ExecuteReader(); { while (reader.Read()) { t.Id = (long)reader["ID"]; t.AirlineCompanyId = (long)reader["AIRLINECOMPANY_ID"]; t.OriginCountryCode = (long)reader["ORIGIN_COUNTRY_CODE"]; t.DestinationCountryCode = (long)reader["DESTINATION_COUNTRY_CODE"]; t.DepartureTime = (DateTime)reader["DEPARTURE_TIME"]; t.LandingTime = (DateTime)reader["LANDING_TIME"]; t.RemainingTickets = (int)reader["REMAINING_TICKETS"]; flights.Add(t); } con.Close(); return flights; } } } public IList<Flight> GetFlightsByDepatrureDate(DateTime departureDate) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); List<Flight> flights = new List<Flight>(); Flight t = new Flight(); using (con) { SqlCommand cmd = new SqlCommand("SELECT_FLIGHT_BY_DEPERTURE_DATE", con); cmd.Parameters.Add(new SqlParameter("@departureDate", departureDate)); con.Open(); cmd.CommandType = CommandType.StoredProcedure; SqlDataReader reader = cmd.ExecuteReader(); { while (reader.Read()) { t.Id = (long)reader["ID"]; t.AirlineCompanyId = (long)reader["AIRLINECOMPANY_ID"]; t.OriginCountryCode = (long)reader["ORIGIN_COUNTRY_CODE"]; t.DestinationCountryCode = (long)reader["DESTINATION_COUNTRY_CODE"]; t.DepartureTime = (DateTime)reader["DEPARTURE_TIME"]; t.LandingTime = (DateTime)reader["LANDING_TIME"]; t.RemainingTickets = (int)reader["REMAINING_TICKETS"]; flights.Add(t); } con.Close(); return flights; } } } public IList<Flight> GetFlightsByDestinationCountry(int countryCode) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); List<Flight> flights = new List<Flight>(); Flight t = new Flight(); using (con) { SqlCommand cmd = new SqlCommand("SELECT_FLIGHT_BY_COUNTRY_CODE", con); cmd.Parameters.Add(new SqlParameter("@countryCode", countryCode)); con.Open(); cmd.CommandType = CommandType.StoredProcedure; SqlDataReader reader = cmd.ExecuteReader(); { while (reader.Read()) { t.Id = (long)reader["ID"]; t.AirlineCompanyId = (long)reader["AIRLINECOMPANY_ID"]; t.OriginCountryCode = (long)reader["ORIGIN_COUNTRY_CODE"]; t.DestinationCountryCode = (long)reader["DESTINATION_COUNTRY_CODE"]; t.DepartureTime = (DateTime)reader["DEPARTURE_TIME"]; t.LandingTime = (DateTime)reader["LANDING_TIME"]; t.RemainingTickets = (int)reader["REMAINING_TICKETS"]; flights.Add(t); } con.Close(); return flights; } } } public IList<Flight> GetFlightsByLandingDate(DateTime landingDate) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); List<Flight> flights = new List<Flight>(); Flight t = new Flight(); using (con) { SqlCommand cmd = new SqlCommand("SELECT_FLIGHT_BY_LANDING_DATE", con); cmd.Parameters.Add(new SqlParameter("@landingDate", landingDate)); con.Open(); cmd.CommandType = CommandType.StoredProcedure; SqlDataReader reader = cmd.ExecuteReader(); { while (reader.Read()) { t.Id = (long)reader["ID"]; t.AirlineCompanyId = (long)reader["AIRLINECOMPANY_ID"]; t.OriginCountryCode = (long)reader["ORIGIN_COUNTRY_CODE"]; t.DestinationCountryCode = (long)reader["DESTINATION_COUNTRY_CODE"]; t.DepartureTime = (DateTime)reader["DEPARTURE_TIME"]; t.LandingTime = (DateTime)reader["LANDING_TIME"]; t.RemainingTickets = (int)reader["REMAINING_TICKETS"]; flights.Add(t); } con.Close(); return flights; } } } public IList<Flight> GetFlightsByOriginCountry(int countryCode) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); List<Flight> flights = new List<Flight>(); Flight t = new Flight(); using (con) { SqlCommand cmd = new SqlCommand("SELECT_FLIGHT_BY_ORIGIN_COUNTRY", con); cmd.Parameters.Add(new SqlParameter("@countryCode", countryCode)); con.Open(); cmd.CommandType = CommandType.StoredProcedure; SqlDataReader reader = cmd.ExecuteReader(); { while (reader.Read()) { t.Id = (long)reader["ID"]; t.AirlineCompanyId = (long)reader["AIRLINECOMPANY_ID"]; t.OriginCountryCode = (long)reader["ORIGIN_COUNTRY_CODE"]; t.DestinationCountryCode = (long)reader["DESTINATION_COUNTRY_CODE"]; t.DepartureTime = (DateTime)reader["DEPARTURE_TIME"]; t.LandingTime = (DateTime)reader["LANDING_TIME"]; t.RemainingTickets = (int)reader["REMAINING_TICKETS"]; flights.Add(t); } con.Close(); return flights; } } } public void Remove(Flight t) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); using (con) { con.Open(); SqlCommand cmd = new SqlCommand($"DELETE_FLIGHT", con); cmd.Parameters.Add(new SqlParameter("@Id", t.Id)); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); con.Close(); } } public void Update(Flight t) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); using (con) { con.Open(); SqlCommand cmd = new SqlCommand($"UPDATE_FLIGHT", con); cmd.Parameters.Add(new SqlParameter("@ID", t.Id)); cmd.Parameters.Add(new SqlParameter("@AIRLINECOMPANY_ID", t.AirlineCompanyId)); cmd.Parameters.Add(new SqlParameter("@ORIGIN_COUNTRY_CODE", t.OriginCountryCode)); cmd.Parameters.Add(new SqlParameter("@DESTINATION_COUNTRY_CODE", t.DestinationCountryCode)); cmd.Parameters.Add(new SqlParameter("@DEPARTURE_TIME", t.DepartureTime)); cmd.Parameters.Add(new SqlParameter("@LANDING_TIME", t.LandingTime)); cmd.Parameters.Add(new SqlParameter("@REMAINING_TICKETS", t.RemainingTickets)); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); con.Close(); } } } } <file_sep>/Controllers/BasicAuthenticationAdministratorAttribute.cs using FlightsManagementSystem; using System; using System.Net; using System.Net.Http; using System.Text; using System.Web.Http.Controllers; using System.Web.Http.Filters; namespace FlightsWebApplication.Controllers { internal class BasicAuthenticationAdministratorAttribute : AuthorizationFilterAttribute { Administrator administrator = new Administrator(null,null); public override void OnAuthorization(HttpActionContext actionContext) { string authenticationToken = actionContext.Request.Headers.Authorization.Parameter; string decodedAuthenticationToken = Encoding.UTF8.GetString( Convert.FromBase64String(authenticationToken)); string[] usernamePasswordArray = decodedAuthenticationToken.Split(':'); string username = usernamePasswordArray[0]; string password = <PASSWORD>[1]; try { administrator.UserName = username; administrator.Password = <PASSWORD>; } catch (Exception) { } if (username == AppConfig.ADMIN_USER && password == <PASSWORD>) { actionContext.Request.Properties["token"] = administrator; } else { actionContext.Response = actionContext.Request .CreateResponse(HttpStatusCode.Unauthorized, "incorrect user or password"); } } } }<file_sep>/FlightsManagementSystem/AirlineDAOMSSQL.cs using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FlightsManagementSystem { public class AirlineDAOMSSQL : IAirlineDAO { public void Add(AirlineCompany t) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); using (con) { SqlCommand cmd = new SqlCommand("ADD_COMPANY", con); cmd.Parameters.Add(new SqlParameter("@AIRLINE_NAME", t.AirlineName)); cmd.Parameters.Add(new SqlParameter("@USER_NAME", t.UserName)); cmd.Parameters.Add(new SqlParameter("@PASSWORD", t.Password)); cmd.Parameters.Add(new SqlParameter("@COUNTRY_CODE", t.CountryCode)); con.Open(); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); con.Close(); } } public AirlineCompany Get(int id) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); AirlineCompany t = new AirlineCompany(); using (con) { SqlCommand cmd = new SqlCommand("SELECT_AIRLINECOMPANY_BY_ID", con); cmd.Parameters.Add(new SqlParameter("@id", id)); con.Open(); cmd.CommandType = CommandType.StoredProcedure; SqlDataReader reader = cmd.ExecuteReader(); { while (reader.Read()) { t.Id = (long)reader["ID"]; t.AirlineName = (string)reader["AIRLINE_NAME"]; t.UserName = (string)reader["USER_NAME"]; t.Password = (string)reader["PASSWORD"]; t.CountryCode = (long)reader["COUNTRY_CODE"]; } con.Close(); return t; } } } public AirlineCompany GetAirlineByUsername(string username) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); AirlineCompany t = new AirlineCompany(); using (con) { SqlCommand cmd = new SqlCommand("SELECT_AIRLINECOMPANY_BY_USERNAME", con); cmd.Parameters.Add(new SqlParameter("@username", username)); con.Open(); cmd.CommandType = CommandType.StoredProcedure; SqlDataReader reader = cmd.ExecuteReader(); { while (reader.Read()) { t.Id = (long)reader["ID"]; t.AirlineName = (string)reader["AIRLINE_NAME"]; t.UserName = (string)reader["USER_NAME"]; t.Password = (string)reader["<PASSWORD>"]; t.CountryCode = (long)reader["COUNTRY_CODE"]; } con.Close(); return t; } } } public IList<AirlineCompany> GetAll() { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); IList<AirlineCompany> companies = new List<AirlineCompany>(); using (con) { SqlCommand cmd = new SqlCommand("SELECT_ALL_AIRLINECOMPANIES", con); con.Open(); cmd.CommandType = CommandType.StoredProcedure; SqlDataReader reader = cmd.ExecuteReader(); { while (reader.Read()) { AirlineCompany t = new AirlineCompany(); t.Id = (long)reader["ID"]; t.AirlineName = (string)reader["AIRLINE_NAME"]; t.UserName = (string)reader["USER_NAME"]; t.Password = (string)reader["<PASSWORD>"]; t.CountryCode = (long)reader["COUNTRY_CODE"]; companies.Add(t); } con.Close(); return companies; } } } public void RemoveAll() { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); using (con) { con.Open(); SqlCommand cmd = new SqlCommand($"DELETE_ALL_AIRLINESCOMPANIES", con); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); con.Close(); } } public IList<AirlineCompany> GetAllAirlinesByCountry(int countryCode) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); IList<AirlineCompany> airlines = new List<AirlineCompany>(); using (con) { con.Open(); SqlCommand cmd = new SqlCommand($"SELECT_AIRLINECOMPANIES_BY_COUNTRY_CODE", con); cmd.Parameters.Add(new SqlParameter("@COUNTRY_CODE", countryCode)); SqlDataReader reader = cmd.ExecuteReader(); { while (reader.Read()) { AirlineCompany t = new AirlineCompany(); t.Id = (long)reader["ID"]; t.AirlineName = (string)reader["AIRLINE_NAME"]; t.UserName = (string)reader["USER_NAME"]; t.Password = (string)reader["PASSWORD"]; t.CountryCode = (long)reader["COUNTRY_CODE"]; airlines.Add(t); } con.Close(); return airlines; } } } public void Remove(AirlineCompany t) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); using (con) { SqlCommand cmd = new SqlCommand($"DELETE_AirlineCompanie", con); cmd.Parameters.Add(new SqlParameter("@id", t.Id)); con.Open(); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); con.Close(); } } public void Update(AirlineCompany t) { SqlConnection con = new SqlConnection(AppConfig.CONNECTION_STRING); using (con) { con.Open(); SqlCommand cmd = new SqlCommand($"UPDATE_AirlineCompanie",con); cmd.Parameters.Add(new SqlParameter("@Id", t.Id)); cmd.Parameters.Add(new SqlParameter("@AIRLINE_NAME", t.AirlineName)); cmd.Parameters.Add(new SqlParameter("@USER_NAME", t.UserName)); cmd.Parameters.Add(new SqlParameter("@PASSWORD", t.Password)); cmd.Parameters.Add(new SqlParameter("@COUNTRY_CODE", t.CountryCode)); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); con.Close(); } } } } <file_sep>/FlightsManagementSystem/Country.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FlightsManagementSystem { public class Country : IPoco { public long Id { get; set; } public string CountryName { get; set; } public Country() { } public Country(string countryName) { CountryName = countryName; } public static bool operator ==(Country a, Country b) { if (ReferenceEquals(a, null) && ReferenceEquals(b, null)) { return true; } if (ReferenceEquals(a, null) || ReferenceEquals(b, null)) { return false; } return a.Id == b.Id; } public static bool operator !=(Country a, Country b) { return !(a == b); } public override bool Equals(object obj) { Country other = obj as Country; return this == other; } public override int GetHashCode() { return Id.GetHashCode(); } } } <file_sep>/FlightsManagementSystem/LoggedInAdministratorFacade.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FlightsManagementSystem { public class LoggedInAdministratorFacade : AnonymousUserFacade, ILoggedInAdministratorFacade { //AirlineDAOMSSQL Airline = new AirlineDAOMSSQL(); //CustomerDAOMSSQL Customer = new CustomerDAOMSSQL(); public void CreateNewAirline(LoginToken<Administrator> token, AirlineCompany airline) { if (token.User != null) { _airlineDAO.Add(airline); } } public void CreateNewCustomer(LoginToken<Administrator> token, Customer customer) { if (token.User != null) { _customerDAO.Add(customer); } } public Customer GetCustomerByUserName(LoginToken<Administrator> token, string user) { if (token.User != null) { return _customerDAO.GetCustomerByUserame(user); } return null; } public void CreateNewCountry(LoginToken<Administrator> token, Country country) { if (token.User != null) { _countryDAO.Add(country); } } public void RemoveAirline(LoginToken<Administrator> token, AirlineCompany airline) { if (token.User != null) { _airlineDAO.Remove(airline); } } public void RemoveCustomer(LoginToken<Administrator> token, Customer customer) { if (token.User != null) { _customerDAO.Remove(customer); } } public void UpdateAirlineDetails(LoginToken<Administrator> token, AirlineCompany airline) { if (token.User != null) { _airlineDAO.Update(airline); } } public void UpdateCustomerDetails(LoginToken<Administrator> token, Customer customer) { if (token.User != null) { _customerDAO.Update(customer); } } public AirlineCompany GetAirlineCompanyById(LoginToken<Administrator> token, int id) { if (token.User != null) { return _airlineDAO.Get(id); } return null; } public Customer GetCustomerById(LoginToken<Administrator> token, int id) { if (token.User != null) { return _customerDAO.Get(id); } return null; } } } <file_sep>/FlightsManagementSystem/AppConfig.cs using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FlightsManagementSystem { public class AppConfig { public const string CONNECTION_STRING = @"Data Source=.;Initial Catalog=YehudaReisner;Integrated Security=True"; public const string ADMIN_USER = "admin"; public const string ADMIN_PASSWORD = "<PASSWORD>"; public const int TIMETOMOVETOHISTORY = 12; } }
ca84654baea9177b4f3a6d6314e8687a5e2498e5
[ "C#" ]
35
C#
yehuda81/FlightProject
66fe80b606027aa9682a8d7a8f752ef3ab4ea494
4ac50ab0557154bb0685441c10dc9b3ef1f9a48a
refs/heads/master
<file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <artifactId>web2-gwt</artifactId> <groupId>masterjava.web2</groupId> <packaging>pom</packaging> <version>1.0</version> <name>web2-gwt</name> <url>http://www.masterjava.ru</url> <modules> <module>common</module> <module>common-test</module> <module>shared</module> <module>client</module> <module>server</module> </modules> <properties> <smartgwt.version>2.4</smartgwt.version> <gwt.version>2.1.1</gwt.version> <spring.version>2.5.5</spring.version> <hibernate.version>3.3.1.GA</hibernate.version> </properties> <repositories> <repository> <id>Apache</id> <url>http://ftp.cica.es/mirrors/maven2/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> <repository> <id>JBoss</id> <url>http://repository.jboss.org/maven2/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> <repository> <id>JavaNet</id> <url>http://download.java.net/maven/2/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> <!--repository> <id>google-maven-release-repository</id> <name>Google Maven Release Repository</name> <url>https://oss.sonatype.org/content/repositories/google-releases</url> <snapshots> <enabled>false</enabled> </snapshots> </repository--> <repository> <id>Smartgwt</id> <url>http://www.smartclient.com/maven2</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> <!--<repository>--> <!--<id>appfuse</id>--> <!--<url>http://static.appfuse.org/repository</url>--> <!--</repository>--> </repositories> <build> <finalName>Web2 GWT</finalName> <defaultGoal>install</defaultGoal> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.6</source> <target>1.6</target> <encoding>UTF-8</encoding> </configuration> </plugin> <!--<plugin>--> <!--<groupId>org.codehaus.mojo</groupId>--> <!--<artifactId>hibernate3-maven-plugin</artifactId>--> <!--<configuration>--> <!--<components>--> <!--<component>--> <!--<name>hbm2ddl</name>--> <!--<implementation>annotationconfiguration</implementation>--> <!--&lt;!&ndash; Use 'jpaconfiguration' if you're using JPA. &ndash;&gt;--> <!--&lt;!&ndash;<implementation>jpaconfiguration</implementation>&ndash;&gt;--> <!--</component>--> <!--</components>--> <!--<componentProperties>--> <!--<drop>true</drop>--> <!--<jdk5>true</jdk5>--> <!--<propertyfile>target/classes/jdbc.properties</propertyfile>--> <!--<skip>${maven.masterjava.skip}</skip>--> <!--</componentProperties>--> <!--</configuration>--> <!--<executions>--> <!--<execution>--> <!--<phase>process-masterjava-resources</phase>--> <!--<goals>--> <!--<goal>hbm2ddl</goal>--> <!--</goals>--> <!--</execution>--> <!--</executions>--> <!--&lt;!&ndash;<dependencies>&ndash;&gt;--> <!--&lt;!&ndash;<dependency>&ndash;&gt;--> <!--&lt;!&ndash;<groupId>${jdbc.groupId}</groupId>&ndash;&gt;--> <!--&lt;!&ndash;<artifactId>${jdbc.artifactId}</artifactId>&ndash;&gt;--> <!--&lt;!&ndash;<version>${jdbc.version}</version>&ndash;&gt;--> <!--&lt;!&ndash;</dependency>&ndash;&gt;--> <!--&lt;!&ndash;</dependencies>&ndash;&gt;--> <!--</plugin>--> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.4.3</version> <configuration> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> <dependencies> <!--<dependency>--> <!--<groupId>${jdbc.groupId}</groupId>--> <!--<artifactId>${jdbc.artifactId}</artifactId>--> <!--<version>${jdbc.version}</version>--> <!--</dependency>--> <!--Hibernate--> <!-- See http://community.jboss.org/wiki/HibernateCompatibilityMatrix --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId> <version>3.4.0.GA</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <!--<dependency>--> <!--<groupId>org.hibernate</groupId>--> <!--<artifactId>hibernate-tools</artifactId>--> <!--<version>3.2.3.GA</version>--> <!--</dependency>--> <!--Spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- Logging --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.4.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.14</version> </dependency> <!-- Commons --> <dependency> <groupId>javaee</groupId> <artifactId>javaee-api</artifactId> <version>5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javassist</groupId> <artifactId>javassist</artifactId> <version>3.4.GA</version> </dependency> </dependencies> </project> <file_sep>package masterjava.web2.webapp.controller; import masterjava.web2.common.dao.GenericDao; import masterjava.web2.common.spring.XmlDataEditor; import masterjava.web2.model.SimpleTableEntity; import masterjava.web2.util.ConvertUtil; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Required; import org.springframework.stereotype.Controller; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.sql.Timestamp; import java.util.Date; import java.util.List; /** * User: GKislin * Date: 13.12.2010 */ @Controller @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}) public class TableController { private static final Logger LOGGER = Logger.getLogger(TableController.class); private GenericDao<SimpleTableEntity, Long> simpleTableDao; public TableController() { LOGGER.info("\n\n\n--------- START APP ----------"); } @InitBinder protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { binder.registerCustomEditor(Date.class, new XmlDataEditor()); } @Autowired @Required public void setSimpleTableDao(GenericDao<SimpleTableEntity, Long> simpleTableDao) { this.simpleTableDao = simpleTableDao; } @RequestMapping("/fetch.do") public ModelAndView handleFetch(HttpServletRequest request, HttpServletResponse response) throws Exception { List<SimpleTableEntity> list = simpleTableDao.loadAll(); LOGGER.info("fetch table"); response.getWriter().write(ConvertUtil.toJson(list)); response.getWriter().close(); return null; } // @RequestMapping("/update.do") // public ModelAndView handleUpdate( // @RequestParam("id") long id, // @RequestParam("ttext") String ttext, // @RequestParam("tint") int tint, // @RequestParam("tdate") Date tdate) throws Exception { // SimpleTableEntity entity = simpleTableDao.get(id); // entity.setTtext(ttext); // entity.setTint(tint); // entity.setTdate(new Timestamp(tdate.getTime())); // simpleTableDao.save(entity); // LOGGER.info("update table: " + entity.toJson()); // // ModelAndView mv = new ModelAndView("update"); // mv.addObject("data", entity); // return null; // } // // @RequestMapping("/add.do") // public ModelAndView handleAdd( // @RequestParam("ttext") String ttext, // @RequestParam("tint") int tint, // @RequestParam("tdate") Date tdate) throws Exception { // // SimpleTableEntity entity = new SimpleTableEntity(ttext, tint, tdate); // entity.setId(simpleTableDao.save(entity)); // LOGGER.info("add to table: " + entity.toJson()); // // ModelAndView mv = new ModelAndView("update"); // mv.addObject("data", entity); // return null; // } // // @RequestMapping("/remove.do") // public ModelAndView handleRemove(@RequestParam("id") long id) throws Exception { // simpleTableDao.delete(id); // LOGGER.info("remove from table: " + id); // // ModelAndView mv = new ModelAndView("remove"); // mv.addObject("data", id); // return null; // } } <file_sep>jdbc.driverClassName=org.hsqldb.jdbcDriver hibernate.dialect=org.hibernate.dialect.HSQLDialect jdbc.url=jdbc:hsqldb:mem:TEST jdbc.username=sa jdbc.password= <file_sep>package masterjava.web2.common.spring; import masterjava.web2.common.util.DateTimeUtil; import org.springframework.util.StringUtils; import java.beans.PropertyEditorSupport; import java.text.ParseException; import java.util.Date; /** * User: GKislin * Date: 22.12.2010 */ public class XmlDataEditor extends PropertyEditorSupport { public void setAsText(String text) throws IllegalArgumentException { if (StringUtils.hasText(text)) { try { setValue(DateTimeUtil.parse(text)); } catch (ParseException ex) { throw new IllegalArgumentException("Could not parse XML date: " + ex.getMessage()); } } else { setValue(new Date()); } } public String getAsText() { Date value = (Date) getValue(); return (value != null ? DateTimeUtil.format(value) : ""); } }<file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <artifactId>client</artifactId> <groupId>masterjava.web2</groupId> <version>1.0</version> </parent> <groupId>masterjava.web2</groupId> <artifactId>smartgwt</artifactId> <packaging>war</packaging> <version>1.0</version> <profiles> <profile> <id>javaee</id> </profile> <profile> <id>develop</id> <activation> <activeByDefault>true</activeByDefault> </activation> <dependencies> <!--<dependency>--> <!--<groupId>ojdbc</groupId>--> <!--<artifactId>ojdbc</artifactId>--> <!--<version>1.4</version>--> <!--</dependency>--> <dependency> <groupId>hsqldb</groupId> <artifactId>hsqldb</artifactId> <version>1.8.0.10</version> </dependency> </dependencies> </profile> </profiles> <build> <finalName>smartgwt-masterjava</finalName> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>gwt-maven-plugin</artifactId> <version>2.1.0-1</version> <executions> <execution> <!--<configuration>--> <!--<module>masterjava.client.SmartGwtEntryPoint</module>--> <!--</configuration>--> <goals> <goal>compile</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <!--SmartGwt--> <dependencies> <dependency> <groupId>masterjava.web2</groupId> <artifactId>common</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>masterjava.web2</groupId> <artifactId>common-test</artifactId> <version>1.0</version> <scope>test</scope> </dependency> <dependency> <groupId>masterjava.web2</groupId> <artifactId>shared</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>com.smartgwt</groupId> <artifactId>smartgwt</artifactId> <version>${smartgwt.version}</version> </dependency> <dependency> <groupId>com.google.gwt</groupId> <artifactId>gwt-servlet</artifactId> <version>${gwt.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>com.google.gwt</groupId> <artifactId>gwt-user</artifactId> <version>${gwt.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.google.gwt</groupId> <artifactId>gwt-dev</artifactId> <version>${gwt.version}</version> <scope>runtime</scope> </dependency> <!--<dependency>--> <!--<groupId>com.smartgwt</groupId>--> <!--<artifactId>smartgwtee</artifactId>--> <!--<version>${smartgwt.version}</version>--> <!--</dependency>--> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.1.2</version> </dependency> </dependencies> </project> <file_sep>package masterjava.web2.common.dao; import java.io.Serializable; import java.util.Collection; import java.util.List; /** * @author <NAME> */ public interface GenericDao<T, PK extends Serializable> { T create(); T get(PK id); T load(PK id); List<T> loadAll(); <M> M narrow(T entity, Class<M> targetClass); void refresh(T entity); PK save(T entity); void update(T entity); void saveOrUpdate(T entity); void saveOrUpdateAll(Collection<T> entities); void delete(T entity); void delete(PK id); void deleteAll(Collection<T> entities); void deleteAll(); List<T> findByNamedQuery(final String queryName); List<T> findByNamedQuery(final String queryName, Object value); List<T> findByNamedQuery(final String queryName, final Object[] values); List<T> findByNamedQueryAndNamedParam(String queryName, String paramName, Object value); List<T> findByNamedQueryAndNamedParam(String queryName, String[] paramNames, Object[] values); } <file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>web2-gwt</artifactId> <groupId>masterjava.web2</groupId> <version>1.0</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>server</artifactId> <dependencies> <dependency> <groupId>masterjava.web2</groupId> <artifactId>shared</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>net.sf.beanlib</groupId> <artifactId>beanlib-hibernate</artifactId> <version>5.0.2beta</version> <exclusions> <exclusion> <groupId>org.hibernate</groupId> <artifactId>hibernate</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> </exclusion> <exclusion> <groupId>log4j</groupId> <artifactId>log4j</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.2.2</version> <classifier>jdk15</classifier> </dependency> </dependencies> </project><file_sep>package masterjava.web2.common.dao; import masterjava.web2.common.dao.GenericDao; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import java.io.Serializable; import java.util.Collection; import java.util.List; /** * @author <NAME> * Typesafe delegate request to HibernateTemplate * <p/> * Constructor: Entity class */ public class GenericDaoHibernate<T, PK extends Serializable> extends HibernateDaoSupport implements GenericDao<T, PK> { protected Class<T> type; public GenericDaoHibernate(Class<T> type) { this.type = type; } // return T or null @Override public T create() { try { return type.newInstance(); } catch (Exception e) { throw new IllegalStateException(e); } } @SuppressWarnings("unchecked") public T get(PK id) { return (T) getHibernateTemplate().get(type, id); } // return T or Exception @SuppressWarnings("unchecked") public T load(PK id) { return (T) getHibernateTemplate().load(type, id); } @SuppressWarnings("unchecked") public List<T> loadAll() { return getHibernateTemplate().loadAll(type); } @SuppressWarnings("unchecked") public PK save(T newInstance) { return (PK) getHibernateTemplate().save(newInstance); } public void saveOrUpdate(T entity) { getHibernateTemplate().saveOrUpdate(entity); } public void saveOrUpdateAll(Collection<T> entities) { getHibernateTemplate().saveOrUpdateAll(entities); } public void update(T entity) { getHibernateTemplate().update(entity); } public void delete(T entity) { getHibernateTemplate().delete(entity); } public void delete(PK key) { getHibernateTemplate().delete(get(key)); } public void deleteAll(Collection<T> entities) { getHibernateTemplate().deleteAll(entities); } public void deleteAll() { getHibernateTemplate().deleteAll(loadAll()); } public void refresh(T entity) { getHibernateTemplate().refresh(entity); } @SuppressWarnings("unchecked") public List<T> findByNamedQuery(String queryName) { return (List<T>) getHibernateTemplate().findByNamedQuery(queryName); } @SuppressWarnings("unchecked") public List<T> findByNamedQuery(String queryName, Object value) { return (List<T>) getHibernateTemplate().findByNamedQuery(queryName, value); } @SuppressWarnings("unchecked") public List<T> findByNamedQuery(String queryName, Object[] values) { return (List<T>) getHibernateTemplate().findByNamedQuery(queryName, values); } @SuppressWarnings("unchecked") public List<T> findByNamedQueryAndNamedParam(String queryName, String paramName, Object value) { return (List<T>) getHibernateTemplate().findByNamedQueryAndNamedParam(queryName, paramName, value); } @SuppressWarnings("unchecked") public List<T> findByNamedQueryAndNamedParam(String queryName, String[] paramNames, Object[] values) { return (List<T>) getHibernateTemplate().findByNamedQueryAndNamedParam(queryName, paramNames, values); } @SuppressWarnings("unchecked") public <M> M narrow(T entity, Class<M> targetClass) { getHibernateTemplate().initialize(entity); if (!targetClass.isAssignableFrom(entity.getClass())) { throw new ClassCastException("Target class " + targetClass.getName() + "is not assignable from " + entity.getClass().getName()); } return (M) entity; } } <file_sep>package masterjava.web2.dao; import masterjava.common.web2.dao.GenericDao; import masterjava.common.web2.test.DaoHsqlDbInFileTest; import masterjava.web2.model.SimpleTableEntity; import org.junit.Test; import javax.annotation.Resource; import java.sql.Date; import static org.junit.Assert.assertEquals; /** * User: GKislin * Date: 10.12.2010 */ public class SimpleTableDaoTest extends DaoHsqlDbInFileTest { @Resource GenericDao<SimpleTableEntity, Long> simpleTableDao; @Test public void testSave() { SimpleTableEntity entity = new SimpleTableEntity("Sample text", 1, new Date(System.currentTimeMillis())); long pk = simpleTableDao.save(entity); assertEquals(entity, simpleTableDao.load(pk)); } } <file_sep>CREATE TABLE SIMPLE_TABLE (ID INTEGER NOT NULL, TTEXT VARCHAR(256), TINT INTEGER, TDATE TIMESTAMP, PRIMARY KEY (ID)); CREATE SEQUENCE SEQ_SIMPLE_TABLE; INSERT INTO SIMPLE_TABLE (ID, TTEXT, TINT, TDATE) values (1, 'Text', 555, NOW()); <file_sep>jdbc.driverClassName=oracle.jdbc.OracleDriver hibernate.dialect=org.hibernate.dialect.Oracle10gDialect jdbc.url=jdbc:oracle:thin:@127.0.0.1:1521:TEST jdbc.username=sa jdbc.password=<PASSWORD> <file_sep>package masterjava.web2.common.util; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import java.text.ParseException; import java.util.Date; import java.util.GregorianCalendar; /** * User: GKislin * Date: 24.06.2009 * <p/> * * @link http://www.w3.org/TR/xmlschema-2/#dateTime * for example: 2000-03-04T23:00:00.00+03:00 */ public class DateTimeUtil { private static final DatatypeFactory DATATYPE_FACTORY; static { try { DATATYPE_FACTORY = DatatypeFactory.newInstance(); } catch (DatatypeConfigurationException e) { throw new IllegalStateException(e); } } private DateTimeUtil() { } public static String format(Date date) { if (date == null) { return null; } final GregorianCalendar gc = new GregorianCalendar(); gc.setTime(date); return DATATYPE_FACTORY.newXMLGregorianCalendar(gc).toXMLFormat(); } public static Date parse(String w3cDateTime) throws ParseException { if (w3cDateTime == null) { return null; } return DATATYPE_FACTORY.newXMLGregorianCalendar(w3cDateTime).toGregorianCalendar().getTime(); } }
a075aae0464f1736c764ea846c3c0594558f1916
[ "Java", "Maven POM", "SQL", "INI" ]
12
Maven POM
liseryang/web2-smart-ext-gwt
8464733baecddf6733da345e88bd35ccd2664a06
7afa1965fd960531f199c6a1f6e1b853ed4de631
refs/heads/master
<file_sep>// // ViewController.swift // AsyncDisplayKit-Issue-4 // // Created by <NAME> on 15/11/28. // Copyright © 2015年 Pony.Cui. All rights reserved. // import UIKit class ViewController: UIViewController, ASTableViewDataSource, ASTableViewDelegate { let tableView = ASTableView() deinit { tableView.asyncDelegate = nil // 记得在这里将 delegate 设为 nil,否则有可能崩溃 tableView.asyncDataSource = nil // dataSource 也是一样 } override func viewDidLoad() { super.viewDidLoad() tableView.asyncDataSource = self tableView.asyncDelegate = self self.view.addSubview(tableView) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() tableView.frame = view.bounds } func numberOfSectionsInTableView(tableView: UITableView!) -> Int { return 1 } func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return 100 } func tableView(tableView: ASTableView!, nodeForRowAtIndexPath indexPath: NSIndexPath!) -> ASCellNode! { let cellNode = CustomCellNode() cellNode.startAnimating() return cellNode } func tableView(tableView: ASTableView!, willDisplayNodeForRowAtIndexPath indexPath: NSIndexPath!) { if let cellNode = tableView.nodeForRowAtIndexPath(indexPath) as? CustomCellNode { cellNode.resume() } } } class CustomCellNode: ASCellNode { let activityIndicator = ASDisplayNode { () -> UIView! in let view = UIActivityIndicatorView(activityIndicatorStyle: .Gray) view.backgroundColor = UIColor.clearColor() view.hidesWhenStopped = true return view } override init!() { super.init() addSubnode(activityIndicator) } func resume() { startAnimating() } func startAnimating() { if let activityIndicatorView = activityIndicator.view as? UIActivityIndicatorView { activityIndicatorView.startAnimating() } } override func calculateSizeThatFits(constrainedSize: CGSize) -> CGSize { return CGSize(width: constrainedSize.width, height: 44) } override func layout() { activityIndicator.frame = CGRect(x: self.calculatedSize.width / 2.0 - 22.0, y: 11, width: 44, height: 44) } }<file_sep>platform :ios, '7.0' target 'AsyncDisplayKit-Issue-4' do pod "AsyncDisplayKit" end
050f1b77904edd49989df5b551d8e7a8799232ab
[ "Swift", "Ruby" ]
2
Swift
PonyCui/AsyncDisplayKit-Issue-4
acacdc0743ba846a4c7eb610d9c496f89cf9e2a5
5a15d82ab2834985407877cb5dd206f3ad695271