branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>sebjf/GPULatencyMeasurement<file_sep>/src/GPULatencyMeasurement.cpp
//============================================================================
// Name : GPULatencyMeasurement.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <GL/gl.h>
#include <GL/glut.h>
#include <GL/glx.h>
#include <GL/glext.h>
#include "Mouse.hpp"
/*
* xorg.conf section for the Asus VG248QE showing modeline settings for driving it at 144Hz. Note that nvidia-settings
* must be used to specify these timings before they are used.
*/
/*
Section "Monitor"
Identifier "Monitor1"
VendorName "Unknown"
ModelName "Ancor Communications Inc VG248"
# HorizSync 30.0 - 160.0
# VertRefresh 50.0 - 150.0
#http://ubuntuforums.org/showthread.php?t=1994729&page=2
Option "ModeValidation" "NoEdidModes"
Option "ExactModeTimingsDVI" "TRUE"
Modeline "1280x720x144" 143.5 1280 1304 1336 1360 720 723 728 733 +HSync -VSync
EndSection
*/
using namespace std;
Mouse* mouse;
float mousex;
float mousey;
class Texture
{
public:
Texture(uint32_t colour)
{
glGenTextures(1, &m_texName);
Initialise(colour);
}
GLuint m_texName;
GLsizei m_width, m_height;
void* m_data;
void Initialise(uint32_t colour)
{
Bind();
m_width = 1024;
m_height = 1024;
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
m_data = malloc(sizeof(uint32_t) * m_width * m_height);
for(int i = 0; i < m_width * m_height; i++){
((uint32_t*)m_data)[i] = colour;
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width, m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_data);
}
void Bind()
{
glBindTexture(GL_TEXTURE_2D, m_texName);
}
};
class TexturedSquare
{
public:
TexturedSquare(float size, uint32_t colour)
{
m_texture = new Texture(colour);
m_size = size;
}
Texture* m_texture;
float m_size;
void Render()
{
Render(0.0f,0.0f);
}
void Render(float x, float y)
{
glEnable(GL_TEXTURE_2D);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
m_texture->Bind();
glBegin(GL_QUADS);
float size = m_size/2;
glTexCoord2f(0.0, 0.0); glVertex3f(x-size, y-size, 0.0f); // The bottom left corner
glTexCoord2f(0.0, 1.0); glVertex3f(x-size, y+size, 0.0f); // The top left corner
glTexCoord2f(1.0, 1.0); glVertex3f(x+size, y+size, 0.0f); // The top right corner
glTexCoord2f(1.0, 0.0); glVertex3f(x+size, y-size, 0.0f); // The bottom right corner
glEnd();
glFlush();
glDisable(GL_TEXTURE_2D);
}
};
TexturedSquare* background;
TexturedSquare* cursor;
TexturedSquare* target;
void draw()
{
//clear the background
glClearColor(0.0f,0.0f,0.0f,1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//code for rendering here
//render the background map and target
background->Render();
target->Render(-1.0f, -1.0f);
//render the cursor
MouseState s = mouse->readDevice();
cursor->Render(s.x,s.y);
glutSwapBuffers(); // swapping image buffer for double buffering
glutPostRedisplay(); // redrawing. Omit this line if you don't want constant redraw
glFinish();
}
int main(int argc, char** argv)
{
mouse = new Mouse(false);
mouse->Scale = 0.010f;
/* Prepare the conditions for this measurement */
bool b_vsyncenabled = true;
bool b_doublebuffered = true;
if (argc > 0)
{
switch(atoi(argv[1]))
{
case 1:
b_vsyncenabled = true;
b_doublebuffered = true;
break;
case 2:
b_vsyncenabled = false;
b_doublebuffered = true;
break;
case 3:
b_vsyncenabled = true;
b_doublebuffered = false;
break;
case 4:
b_vsyncenabled = true;
b_doublebuffered = false;
break;
}
}
unsigned int displayModeFlags = GLUT_RGBA;
if(b_doublebuffered){
displayModeFlags |= GLUT_DOUBLE;
}else{
displayModeFlags |= GLUT_SINGLE;
}
unsigned int swap_interval = 0;
if(b_vsyncenabled > 0)
{
swap_interval = 1;
}
/* Initialise the device and display */
glutInit(&argc, argv);
glutInitDisplayMode(displayModeFlags); // enabling double buffering and RGBA
glutInitWindowSize(1280, 720);
glutCreateWindow("OpenGL"); // creating the window
glutFullScreen(); // making the window full screen
PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC)glXGetProcAddress( (const GLubyte*)"glXSwapIntervalSGI");
glXSwapIntervalSGI(swap_interval);
glDisable(GL_LIGHTING);
/* Configure texture mapping */
background = new TexturedSquare(2, 0xFF000020);
target = new TexturedSquare(0.4, 0xFF200000);
cursor = new TexturedSquare(0.25f, 0xFFFFFFFF);
/* Start the main loop */
glutDisplayFunc(draw); // draw is your function for redrawing the screen
glutMainLoop();
return 0;
}
| 7cad0248f59d5f76793862cd5372549f20cfbdea | [
"C++"
] | 1 | C++ | sebjf/GPULatencyMeasurement | 53a0206d692670c8f4c546a769b1fd3bb80f5c20 | 0be4fa85b1b144710967685d22f519d15af0eec2 |
refs/heads/main | <file_sep>module.exports = () => {
console.log("DaBabyBot is online!");
}<file_sep>const Discord = require('discord.js');
require('dotenv').config();
const client = new Discord.Client();
const fs = require('fs');
const message = require('./events/guild/message');
client.commands = new Discord.Collection();
client.events = new Discord.Collection();
['command_handler', 'event_handler'].forEach(handler => {
require(`./handlers/${handler}`)(client, Discord);
});
client.on('ready', () => {
var facts = ['yea yea', 'i pull up', 'https://youtu.be/U2JyeciEwSI', 'huh', 'https://youtu.be/KvuQNNVrbtM', 'less go']
setInterval(function () {
var fact = Math.floor(Math.random() * facts.length)
const channel = client.channels.cache.get('849328935992426527')
channel.send(`${facts[fact]}`);
console.log(facts[fact]);
}, 3600000)
});
client.on('ready', () => {
client.user.setPresence({
status: 'available', //sets status button to green
activity: {
name: `Fortnite`, //This is the custom text
type: 'PLAYING' //this is the type (duh). 'watching' would also be an option
}
});
});
client.login(process.env.DISCORD_TOKEN); | a00c6e5f1d0eabd6abb064bd32a08b12da9d1617 | [
"JavaScript"
] | 2 | JavaScript | Bumiii/dababy | 1ccfc98304a1cf0673349795415cb69c8d819451 | be686379593dd2868642f4e85452f486ef6d88f2 |
refs/heads/main | <repo_name>x-jokay/docker-ccu-historian<file_sep>/CHANGELOG.md
# Changelog
## [2.6.0](https://github.com/jokay/docker-ccu-historian/releases/tag/2.6.0) (2021-03-19)
This release contains CCU-Historian [2.6.0](https://github.com/mdzio/ccu-historian/releases/tag/2.6.0).
## [2.5.3](https://github.com/jokay/docker-ccu-historian/releases/tag/2.5.3) (2021-01-21)
This release contains CCU-Historian [2.5.3](https://github.com/mdzio/ccu-historian/releases/tag/2.5.3).
## 2.5.2 (2021-01-10)
This release contained CCU-Historian [2.5.2](https://github.com/mdzio/ccu-historian/releases/tag/2.5.2).
### Features
- Added support for multi-platform images. ([#29])
## 2.5.1 (2020-10-12)
This release contained CCU-Historian [2.5.1](https://github.com/mdzio/ccu-historian/releases/tag/2.5.1).
### Features
- Added new environment variable `CONFIG_KEEP_MONTHS` to be able to cleanup old
data. ([#10])
### Improvements
- Exposed additional ports `8082` (Database Web-GUI Port), `9092` (Database TCP
Port) and `5435` (Database PostgreSQL Port). ([#13])
## 2.4.0 (2020-06-11)
This release contained CCU-Historian [2.4.0](https://github.com/mdzio/ccu-historian/releases/tag/2.4.0).
### Improvements
- Added Support for username and password environment variables. ([#7])
## 2.3.0 (2019-11-09)
This release contained CCU-Historian [2.3.0](https://github.com/mdzio/ccu-historian/releases/tag/2.3.0).
## 2.2.2 (2019-10-06)
This release contained CCU-Historian [2.2.2](https://github.com/mdzio/ccu-historian/releases/tag/2.2.2).
## 2.2.1 (2019-09-27)
This release contained CCU-Historian [2.2.1](https://github.com/mdzio/ccu-historian/releases/tag/2.2.1).
## 2.2.0 (2019-09-03)
This release contained CCU-Historian [2.2.0](https://github.com/mdzio/ccu-historian/releases/tag/2.2.0).
### Improvements
- Added multi-stage build. (thx to [@zsisamci](https://github.com/zsisamci))
- Added healthcheck.
### Bug fixes
- Fixed config file generation. ([#3])
[#3]: https://github.com/jokay/docker-ccu-historian/issues/3
[#7]: https://github.com/jokay/docker-ccu-historian/issues/7
[#10]: https://github.com/jokay/docker-ccu-historian/issues/10
[#13]: https://github.com/jokay/docker-ccu-historian/issues/13
[#29]: https://github.com/jokay/docker-ccu-historian/issues/29
<file_sep>/src/docker-entrypoint.sh
#!/bin/bash
PATH_BASE=/opt/ccu-historian
PATH_CONFIG=${PATH_BASE}/config
FILE_CONFIG=${PATH_CONFIG}/ccu-historian.config
log () {
echo "$(date +"%Y-%m-%d %T")|INFO |${1}"
}
log_sub () {
echo " |${1}"
}
add_cfg () {
echo "${1}" >> ${FILE_CONFIG}
}
log "jokay/ccu-historian ${VERSION}"
if [[ ! -d "${PATH_CONFIG}" ]]; then
log "Creating config directory ..."
mkdir -p "${PATH_CONFIG}"
fi
if [[ ! -f "${FILE_CONFIG}" ]]; then
log "Creating config file ..."
if [[ -z "${CONFIG_HOST_IP}" || -z "${CONFIG_CCU_TYPE}" || -z "${CONFIG_CCU_IP}" ]]; then
log "Required environment variables are missing!"
log_sub "Please specify CONFIG_HOST_IP, CONFIG_CCU_TYPE and CONFIG_CCU_IP."
exit 1
fi
touch "${FILE_CONFIG}"
add_cfg "database.dir='/database'"
add_cfg "database.webAllowOthers=true"
add_cfg "devices.device1.address='${CONFIG_CCU_IP}'"
add_cfg "devices.device1.type=${CONFIG_CCU_TYPE}"
if [ -n "${CONFIG_CCU_PLUGIN1_TYPE}" ]; then
add_cfg "devices.device1.plugin1.type=${CONFIG_CCU_PLUGIN1_TYPE}"
fi
if [ -n "${CONFIG_CCU_PLUGIN2_TYPE}" ]; then
add_cfg "devices.device1.plugin2.type=${CONFIG_CCU_PLUGIN2_TYPE}"
fi
if [ -n "${CONFIG_CCU_USERNAME}" ]; then
add_cfg "devices.device1.username='${CONFIG_CCU_USERNAME}'"
fi
if [ -n "${CONFIG_CCU_PASSWORD}" ]; then
add_cfg "devices.device1.password='${CONFIG_CCU_PASSWORD}'"
fi
add_cfg "devices.historianAddress='${CONFIG_HOST_IP}'"
if [ -n "${CONFIG_HOST_BINRPCPORT}" ]; then
add_cfg "devices.historianBinRpcPort=${CONFIG_HOST_BINRPCPORT}"
fi
if [ -n "${CONFIG_HOST_XMLRPCPORT}" ]; then
add_cfg "devices.historianXmlRpcPort=${CONFIG_HOST_XMLRPCPORT}"
fi
add_cfg "webServer.historianAddress='${CONFIG_HOST_IP}'"
fi
if [ -n "${CONFIG_KEEP_MONTHS}" ]; then
REF_DATE=$(date -d "-${CONFIG_KEEP_MONTHS} month" +%Y-%m-%d)
log "Running database maintenance 'clean' (removes all data before ${REF_DATE}) ..."
java -jar ${PATH_BASE}/ccu-historian.jar -config "${FILE_CONFIG}" -clean "${REF_DATE}"
log "Running database maintenance 'recalc' ..."
java -jar ${PATH_BASE}/ccu-historian.jar -config "${FILE_CONFIG}" -recalc
log "Running database maintenance 'compact' ..."
java -jar ${PATH_BASE}/ccu-historian.jar -config "${FILE_CONFIG}" -compact
fi
log "Starting CCU-Historian using the following config:"
log_sub "---"
while IFS="" read -r cfg || [ -n "$cfg" ]
do
log_sub "${cfg}"
done < "${FILE_CONFIG}"
log_sub "---"
java -jar ${PATH_BASE}/ccu-historian.jar -config ${FILE_CONFIG}<file_sep>/README.md
# Docker CCU-Historian
Docker image for [CCU-Historian](https://github.com/mdzio/ccu-historian).
## Information
| Service | Stats |
|---------|-------|
| [GitHub](https://github.com/jokay/docker-ccu-historian) |    |
| [Docker Hub](https://hub.docker.com/r/xjokay/ccu-historian) |   |
## Usage
```sh
docker pull docker.io/xjokay/ccu-historian:latest
```
### Supported tags
| Tag | Description |
|-----------|------------------------------------------------------------------------------------------------------------|
| latest | [Latest](https://github.com/jokay/docker-ccu-historian/releases/latest) release |
| {release} | Specific release version, see available [releases](https://github.com/jokay/docker-ccu-historian/releases) |
### Exposed Ports
| Port | Protocol | Description |
|------|----------|--------------------------|
| 80 | TCP | Web-GUI Port |
| 2098 | TCP | Xml RPC Port |
| 2099 | TCP | Bin RPC Port |
| 8082 | TCP | Database Web-GUI Port |
| 9092 | TCP | Database TCP Port |
| 5435 | TCP | Database PostgreSQL Port |
### Volumes
| Directory | Description |
|---------------------------|-----------------------------|
| /database | Location of the database |
| /opt/ccu-historian/config | Location of the config file |
### Configuration
These environment variables must be set for the first start:
| ENV field | Req. / Opt. | Description |
|-------------------------|--------------|----------------------------------------------------------|
| CONFIG_CCU_TYPE | **Required** | Type of the CCU hardware, e.g. `CCU1`, `CCU2` or `CCU3`. |
| CONFIG_CCU_IP | **Required** | IP of the CCU. |
| CONFIG_HOST_IP | **Required** | IP of the Docker host. |
| CONFIG_HOST_XMLRPCPORT | *Optional* | XML port of the RPC-port, e.g. `2098`. |
| CONFIG_HOST_BINRPCPORT | *Optional* | Bin port of the RPC-port, e.g. `2099`. |
| CONFIG_CCU_PLUGIN1_TYPE | *Optional* | Additional plugins, e.g. `CUXD` or `HMWLGW`. |
| CONFIG_CCU_PLUGIN2_TYPE | *Optional* | Additional plugins, e.g. `CUXD` or `HMWLGW`. |
| CONFIG_CCU_USERNAME | *Optional* | Username for authentication. |
| CONFIG_CCU_PASSWORD | *Optional* | Password for authentication. |
| CONFIG_KEEP_MONTHS | *Optional* | Cleanup of values older than x months. Maintenance is performed before the CCU-Historian is actually started. One after the other the CCU-Historian is called with the options -clean, -recalc and -compact. |
Additional config settings should be made by changing the config file `ccu-historian.config`
within the docker container.
It is easier to export the config folder out of the docker container and edit
the file there.
## Samples
### docker-compose
```yml
services:
app:
image: docker.io/xjokay/ccu-historian:latest
volumes:
- ./data/database:/database
- ./data/config:/opt/ccu-historian/config
ports:
- 80:80
- 2098:2098
- 2099:2099
environment:
- TZ=Europe/Zurich
- CONFIG_CCU_TYPE=CCU3
- CONFIG_CCU_IP=192.168.1.10
- CONFIG_HOST_IP=192.168.1.100
- CONFIG_HOST_BINRPCPORT=2099
- CONFIG_HOST_XMLRPCPORT=2098
- CONFIG_CCU_PLUGIN1_TYPE=CUXD
- CONFIG_KEEP_MONTHS=12
networks:
- default
```
### docker run
```sh
docker run -d \
-v $PWD/data/database:/database \
-v $PWD/data/config:/opt/ccu-historian/config \
-p 80:80 \
-p 2098:2098 \
-p 2099:2099 \
-e TZ=Europe/Zurich \
-e CONFIG_CCU_TYPE=CCU3 \
-e CONFIG_CCU_IP=192.168.1.10 \
-e CONFIG_HOST_IP=192.168.1.100 \
-e CONFIG_HOST_BINRPCPORT=2099 \
-e CONFIG_HOST_XMLRPCPORT=2098 \
-e CONFIG_CCU_PLUGIN1_TYPE=CUXD \
-e CONFIG_KEEP_MONTHS=12 \
docker.io/xjokay/ccu-historian:latest
```
<file_sep>/src/Dockerfile
ARG VERSION=2.6.0
ARG CHECKSUM=f7c9250746616b0f590e52b6864d67bcf2fdb0e665f7c1279bbb36cd669205288a4844684aaa06ba45ce2281ecab5307b95b0d70d211c4a99b6b431f9b8dd3b0
FROM docker.io/alpine:3.14.0 AS build
ARG VERSION
ARG CHECKSUM
WORKDIR /tmp
ADD https://github.com/mdzio/ccu-historian/releases/download/${VERSION}/ccu-historian-${VERSION}-bin.zip .
# hadolint ignore=DL4006
RUN printf "%s ccu-historian-%s-bin.zip" "${CHECKSUM}" "${VERSION}" | sha512sum -c - && \
mkdir /tmp/ccu-historian && \
unzip "ccu-historian-${VERSION}-bin.zip" -d /tmp/ccu-historian
FROM docker.io/adoptopenjdk:11.0.10_9-jre-hotspot
ARG VERSION
ENV VERSION "${VERSION}"
ENV TZ "UTC"
WORKDIR /opt/ccu-historian
RUN mkdir -p /database && \
printf "%s" "${TZ}" > /etc/timezone
COPY --from=build /tmp/ccu-historian /opt/ccu-historian
VOLUME ["/opt/ccu-historian/config", "/database"]
COPY docker-entrypoint.sh /usr/local/bin/
ENTRYPOINT ["docker-entrypoint.sh"]
EXPOSE 80 2098 2099 8082 9092 5435
HEALTHCHECK --interval=1m --timeout=3s \
CMD curl -f http://localhost/historian || exit 1 | 2613c1968ebfdd0fba47c28cd4ac904213dcc15f | [
"Markdown",
"Dockerfile",
"Shell"
] | 4 | Markdown | x-jokay/docker-ccu-historian | b4924141fb2c2d81a560cb83b320462a3cb4a925 | a3587ba4769260b520f6e03f228c1ef77f20a6db |
refs/heads/master | <file_sep>package fr.eni.ihm;
import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GestionListeFrame extends JFrame {
private JPanel panneauPrincipal;
private JLabel label;
private JTextField textField;
private List liste;
private JButton bAjout;
private JButton bVider;
public GestionListeFrame() {
super("Gestion de String ");
gestionComposants();//On initialise les différents paramètres
this.setSize(800,200);//Autre maniere de faire une fenêtre rectangulaire en interface graphique
this.setLocationRelativeTo(null);//position la fenêtre dans l'écran mettre null la positionne au centre
this.setResizable(false);//Interdire le redimensionnement de la fenêtre par l'utilisateur
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);//On supprime l'instance de la fenêtre
}
private void gestionComposants() {
//Création des différents éléments dont le panneau dans lequel tout les autres éléments seront intégré
panneauPrincipal = new JPanel();
label = new JLabel("Texte à ajouter : ");
textField = new JTextField(10);//Champ de saisie avec longueur de 10
liste = new List(5);
bAjout = new JButton("Ajouter");
bVider = new JButton("Vider");
this.getContentPane().add(panneauPrincipal);//Renvoyer le panneau courant pour ensuite rajouter dessus le panneau créé
//ajout des différents éléments au panneau
panneauPrincipal.add(label);
panneauPrincipal.add(textField);
panneauPrincipal.add(bAjout);
panneauPrincipal.add(liste);
panneauPrincipal.add(bVider);
bAjout.addActionListener(new BoutonAjouterActionListener());//détecte un clique sur le bouton
bVider.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
liste.removeAll();//On vide entièrement la liste
}
});
}
class BoutonAjouterActionListener implements ActionListener{//Permet de définir les action à effectueur en fonction de l'action sur le bouton
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String chaine= textField.getText();//récupérer le contenu du champ de saisie lorsque l'on appuie sur le bouton ajouter
if(chaine.trim().length() > 0) {//on vérifie qu'il y a au moins un caractère hors espace
liste.add(chaine);//on ajoute la saisie récupérer à la liste
//La liste étant affichée sur le côté
}
textField.setText("");//On met un texte vide à la place de la saise dans le champs de saisie une fois que le texte est ajouté dans la liste
System.out.println("Bouton ajouter clique");
}
}
}
| 2c0822e953a3e54c6a7ce26a1527b354384d2667 | [
"Java"
] | 1 | Java | Razold/module06-03-action-bouton_couleur | 4beba476ed93eaca2b80c642f50a3a47f3467749 | 77eca25cb8e2d17d7789aede9aef18f92b728323 |
refs/heads/master | <file_sep><?php
return array(
'title' => 'タイトル',
'A' => 'A',
'B' => 'B',
'Text' => 'テキスト',
'Clicks / Views' => 'クリック数 / 表示数',
'conversion' => 'クリック率',
'Image' => '画像',
);<file_sep><?php
/**
* NOVIUS OS - Web OS for digital communication
*
* @copyright 2011 Novius
* @license GNU Affero General Public License v3 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0.html
* @link http://www.novius-os.org
*/
Nos\I18n::current_dictionary('ab_test::common');
?>
<div style="overflow: hidden">
<?= $title;?>
<table style="text-align: center">
<tr><td></td><td><img src="<?= $imga; ?>"></td><td><img src="<?= $imgb; ?>"></td></tr>
<tr><td><?= __('Clicks / Views');?></td><td><?= $conversiona;?> / <?= $inta;?></td><td><?= $conversionb;?> / <?= $intb;?></td></tr>
<tr><td><?= __('conversion');?></td><td><?= $ratioa;?>%</td><td><?= $ratiob;?>%</td></tr>
<tr><td></td><td></td></tr>
</table>
</div><file_sep><h3>Options</h3>
<p style="margin-bottom: 0.5em;">
<label><?= __('Select a form:') ?>
<?php
$options = array();
$forms = \Arr::pluck(\ABTEST\Model_Abtest::find('all', $options), 'abte_title', 'abte_id');
echo \Fuel\Core\Form::select('abte_id', \Arr::get($enhancer_args, 'abte_id', ''), $forms);
?>
</label>
</p>
<p style="margin-bottom: 0.5em;">
<?= __('Link Page:') ?>
</p>
<div class="enhancer_confirmation_page_id">
<?= \Nos\Page\Renderer_Selector::renderer(array(
'input_name' => 'confirmation_page_id',
'selected' => array(
'id' => \Arr::get($enhancer_args, 'confirmation_page_id', null),
),
'treeOptions' => array(
'context' => \Arr::get($enhancer_args, 'nosContext', \Nos\Tools_Context::defaultContext()),
),
)); ?>
</div><file_sep>CREATE TABLE IF NOT EXISTS `abtests` (
`abte_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`abte_title` varchar(255) NOT NULL,
`abte_texta` varchar(255) NOT NULL,
`abte_textb` varchar(255) NOT NULL,
`abte_inta` int(11),
`abte_intb` int(11),
`abte_conversiona` int(11),
`abte_conversionb` int(11),
`abte_created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`abte_updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`abte_id`),
KEY `abte_created_at` (`abte_created_at`),
KEY `abte_updated_at` (`abte_updated_at`)
) DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
<file_sep><?php
/**
* NOVIUS OS - Web OS for digital communication
*
* @copyright 2011 Novius
* @license GNU Affero General Public License v3 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0.html
* @link http://www.novius-os.org
*/
namespace ABTEST;
use Nos\Controller_Front_Application;
use View;
class Controller_Front extends Controller_Front_Application
{
protected $enhancer_args = array();
public function action_main($enhancer_args = array())
{
$this->main_controller->disableCaching();
$abte_id = $enhancer_args['abte_id'];
$item = \ABTEST\Model_Abtest::find($abte_id);
// when link is clicked
$page_id = $enhancer_args['confirmation_page_id'];
if (\Input::post('_go') == 'abtest' && !empty($page_id)) {
if (ctype_alpha(\Session::get('abtest'.$abte_id))) {
// add conversion count
$num = 'abte_conversion'.\Session::get('abtest'.$abte_id);
$item->$num++;
$item->save();
}
$page = \Nos\Page\Model_Page::find($page_id);
if (!empty($page)) {
\Response::redirect($page->url());
}
return $num;
}
// select a value and save into session
$ab = array('a','b');
$rand_key = array_rand($ab);
$abdata = $ab[$rand_key];
\Session::set('abtest'.$abte_id, $abdata);
// add view count
$abte_view = 'abte_int' . $abdata;
$item->$abte_view++;
$item->save();
// create link img/txt
$img = 'img' . $abdata;
$text = 'text' . $abdata;
$textdata = $item->{$text};
$thumbnail = $item->medias->{$img}->get_public_path_resized(400, 300);
// link format
$format = '<form method="post"><input type="hidden" name="_go" value="abtest"><input type="image" src="%s" alt="%s"></form>';
$data = sprintf($format,$thumbnail,$textdata);
return $data ;
}
}
<file_sep><?php
namespace ABTEST;
class Controller_Admin_Abtest_Crud extends \Nos\Controller_Admin_Crud
{
}
<file_sep><?php
Nos\I18n::current_dictionary('ab_test::common');
return array(
'controller_url' => 'admin/ab_test/abtest/crud',
'model' => 'ABTEST\Model_Abtest',
'layout' => array(
'large' => true,
'save' => 'save',
'title' => 'abte_title',
'medias' => array(),
'content' => array(
'a' => array(
'view' => 'nos::form/expander',
'params' => array(
'title' => __('A'),
'nomargin' => true,
'options' => array(
'allowExpand' => false,
),
'content' => array(
'view' => 'nos::form/fields',
'params' => array(
'fields' => array(
'abte_texta',
'medias->imga->medil_media_id'
),
),
),
),
),
'b' => array(
'view' => 'nos::form/expander',
'params' => array(
'title' => __('B'),
'nomargin' => true,
'options' => array(
'allowExpand' => false,
),
'content' => array(
'view' => 'nos::form/fields',
'params' => array(
'fields' => array(
'abte_textb',
'medias->imgb->medil_media_id'
),
),
),
),
),
),
),
'fields' => array(
'abte__id' => array (
'label' => 'ID: ',
'form' => array(
'type' => 'hidden',
),
'dont_save' => true,
),
'abte_inta' => array (
'label' => 'inta: ',
'form' => array(
'type' => 'hidden',
),
'dont_save' => true,
),
'abte_intb' => array (
'label' => 'intb: ',
'form' => array(
'type' => 'hidden',
),
'dont_save' => true,
),
'abte_title' => array(
'label' => __('title'),
'form' => array(
'type' => 'text',
),
),
'medias->imga->medil_media_id' => array(
'label' => '',
'renderer' => 'Nos\Media\Renderer_Media',
'form' => array(
'title' => __('Image') . __('A'),
),
'validation' => array(
'required',
),
),
'abte_texta' => array(
'label' => __('Text') . __('A'),
'form' => array(
'type' => 'text',
),
),
'medias->imgb->medil_media_id' => array(
'label' => '',
'renderer' => 'Nos\Media\Renderer_Media',
'form' => array(
'title' => __('Image') . __('B'),
),
'validation' => array(
'required',
),
),
'abte_textb' => array(
'label' => __('Text') . __('B'),
'form' => array(
'type' => 'text',
),
),
'save' => array(
'label' => '',
'form' => array(
'type' => 'submit',
'tag' => 'button',
// Note to translator: This is a submit button
'value' => __('Save'),
'class' => 'primary',
'data-icon' => 'check',
),
),
)
/* UI texts sample
'messages' => array(
'successfully added' => __('Item successfully added.'),
'successfully saved' => __('Item successfully saved.'),
'successfully deleted' => __('Item has successfully been deleted!'),
'you are about to delete, confim' => __('You are about to delete item <span style="font-weight: bold;">":title"</span>. Are you sure you want to continue?'),
'you are about to delete' => __('You are about to delete item <span style="font-weight: bold;">":title"</span>.'),
'exists in multiple context' => __('This item exists in <strong>{count} contexts</strong>.'),
'delete in the following contexts' => __('Delete this item in the following contexts:'),
'item deleted' => __('This item has been deleted.'),
'not found' => __('Item not found'),
'error added in context' => __('This item cannot be added {context}.'),
'item inexistent in context yet' => __('This item has not been added in {context} yet.'),
'add an item in context' => __('Add a new item in {context}'),
'delete an item' => __('Delete a item'),
),
*/
/*
Tab configuration sample
'tab' => array(
'iconUrl' => 'static/apps/{{application_name}}/img/16/icon.png',
'labels' => array(
'insert' => __('Add a item'),
'blankSlate' => __('Translate a item'),
),
),
*/
);<file_sep><?php
return array(
'model' => 'ABTEST\Model_Abtest',
//'thumbnails' => true,
/*
'appdesk' => array(
'appdesk' => array(
'defaultView' => 'thumbnails',
),
),
*/
'search_text' => 'abte_title',
/*
'inspectors' => array(
'author',
'tag',
'category',
'date'
),
*/
/*
'query' => array(
'model' => '{{namespace}}\Model_Post',
'order_by' => array('post_created_at' => 'DESC'),
'limit' => 20,
),
*/
);
<file_sep><?php
namespace ABTEST\Migrations;
class Install extends \Nos\Migration
{
}<file_sep><?php
/**
* NOVIUS OS - Web OS for digital communication
*
* @copyright 2011 Novius
* @license GNU Affero General Public License v3 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0.html
* @link http://www.novius-os.org
*/
namespace ABTEST;
class Controller_Admin_Enhancer extends \Nos\Controller_Admin_Enhancer
{
public function action_save(array $args = null)
{
if (empty($args)) {
$args = $_POST;
}
$abtestdata = \ABTEST\Model_Abtest::find($args['abte_id']);
$params['title'] = $abtestdata->abte_title;
$params['imga'] = $abtestdata->medias->imga->get_public_path_resized(200, 200);
$params['imgb'] = $abtestdata->medias->imgb->get_public_path_resized(200, 200);
$params['conversiona'] = $abtestdata->conversiona;
$params['conversionb'] = $abtestdata->conversionb;
$params['inta'] = $abtestdata->inta;
$params['intb'] = $abtestdata->intb;
if ($abtestdata->inta) {
$ratio = 100 * $abtestdata->conversiona / $abtestdata->inta;
$params['ratioa'] = round($ratio,2);
}
else
{
$params['ratioa'] =0;
};
if ($abtestdata->intb) {
$ratio = 100 * $abtestdata->conversionb / $abtestdata->intb;
$params['ratiob'] = round($ratio,2);
}
else
{
$params['ratiob'] =0;
};
$body = array(
'config' => $args,
'preview' => \View::forge($this->config['preview']['view'], $params)->render(),
);
\Response::json($body);
}
}
<file_sep><?php
/**
* NOVIUS OS - Web OS for digital communication
*
* @copyright 2011 Novius
* @license GNU Affero General Public License v3 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0.html
* @link http://www.novius-os.org
*/
return array(
'popup' => array(
'layout' => array(
'view' => 'ab_test::enhancer/popup',
),
),
'preview' => array(
'view' => 'ab_test::enhancer/preview',
),
/*
'preview' => array(
'params' => array(
'title' => function($enhancer_args) {
$output = '';
if (!empty($enhancer_args['abte_id'])) {
$abtestdata = \ABTEST\Model_Abtest::find($enhancer_args['abte_id']);
}
if (!empty($abtestdata->abte_title)) {
$output .= $abtestdata->abte_title;
$output .= '<br>';
}
if (!empty($abtestdata->medias->imga)) {
$output .= '<img src="' . $abtestdata->medias->imga->get_public_path_resized(100, 100) . '">';
$output .= $abtestdata->conversiona . '/' . $abtestdata->inta;
$output .= '<br>';
}
if (!empty($abtestdata->medias->imgb)) {
$output .= '<img src="' . $abtestdata->medias->imgb->get_public_path_resized(100, 100) . '">';
$output .= $abtestdata->conversionb . '/' . $abtestdata->intb;
$output .= '<br>';
}
return $output;
},
),
),
*/
);
<file_sep><?php
namespace ABTEST;
class Model_Abtest extends \Nos\Orm\Model
{
protected static $_primary_key = array('abte_id');
protected static $_table_name = 'abtests';
protected static $_properties = array(
'abte_id',
'abte_title',
'abte_texta',
'abte_textb',
'abte_inta',
'abte_intb',
'abte_conversiona',
'abte_conversionb',
'abte_created_at',
'abte_updated_at',
);
protected static $_title_property = 'abte_title';
protected static $_observers = array(
'Orm\Observer_CreatedAt' => array(
'events' => array('before_insert'),
'mysql_timestamp' => true,
'property'=>'abte_created_at'
),
'Orm\Observer_UpdatedAt' => array(
'events' => array('before_save'),
'mysql_timestamp' => true,
'property'=>'abte_updated_at'
)
);
protected static $_behaviours = array(
/*
'Nos\Orm_Behaviour_Publishable' => array(
'publication_state_property' => 'abte__publication_status',
'publication_start_property' => 'abte__publication_start',
'publication_endproperty' => 'abte__publication_end',
),
*/
/*
'Nos\Orm_Behaviour_Urlenhancer' => array(
'enhancers' => array('ab_test_abtest'),
),
*/
/*
'Nos\Orm_Behaviour_Virtualname' => array(
'events' => array('before_save', 'after_save'),
'virtual_name_property' => 'abte_virtual_name',
),
*/
/*
'Nos\Orm_Behaviour_Twinnable' => array(
'events' => array('before_insert', 'after_insert', 'before_save', 'after_delete', 'change_parent'),
'context_property' => 'abte__context',
'common_id_property' => 'abte__context_common_id',
'is_main_property' => 'abte__context_is_main',
'invariant_fields' => array(),
),
*/
);
protected static $_belongs_to = array(
/*
'key' => array( // key must be defined, relation will be loaded via $abtest->key
'key_from' => 'abte_...', // Column on this model
'model_to' => 'ABTEST\Model_...', // Model to be defined
'key_to' => '...', // column on the other model
'cascade_save' => false,
'cascade_delete' => false,
//'conditions' => array('where' => ...)
),
*/
);
protected static $_has_many = array(
/*
'key' => array( // key must be defined, relation will be loaded via $abtest->key
'key_from' => 'abte_...', // Column on this model
'model_to' => 'ABTEST\Model_...', // Model to be defined
'key_to' => '...', // column on the other model
'cascade_save' => false,
'cascade_delete' => false,
//'conditions' => array('where' => ...)
),
*/
);
protected static $_many_many = array(
/*
'key' => array( // key must be defined, relation will be loaded via $abtest->key
'table_through' => '...', // intermediary table must be defined
'key_from' => 'abte_...', // Column on this model
'key_through_from' => '...', // Column "from" on the intermediary table
'key_through_to' => '...', // Column "to" on the intermediary table
'key_to' => '...', // Column on the other model
'cascade_save' => false,
'cascade_delete' => false,
'model_to' => 'ABTEST\Model_...', // Model to be defined
),
*/
);
}
<file_sep><?php
namespace ABTEST;
class Controller_Admin_Abtest_Appdesk extends \Nos\Controller_Admin_Appdesk
{
}
| 0ea94699891d68ef704dda30b7536f32865ca96d | [
"SQL",
"PHP"
] | 13 | PHP | ounziw/abtest | 75f30290c9aaca736f9ed7c3a50f56d795dbffa5 | 054a639b856c3e2699a4c0a43d264edda7bbfa82 |
refs/heads/master | <file_sep>package com.example.demo.Service;
public interface UserService {
//method to add a person as a new User on the database
void addUser(long id ,String name,String surname);
//method to remove a person as a User on the database
void removeUser(long id);
//method to search for a person on the database
String getUser(long id);
}
| f77fef11d6ddbb5edf982b7ef4bf8cec0db212ee | [
"Java"
] | 1 | Java | FeliKanenga/SpringBoot-Part2 | 9836cecd63361d74c7fad1df80f0d025d5ac6cf4 | 7b1a88cce2a6b3b29db32153f0d29a822d1900c4 |
refs/heads/master | <repo_name>richgieg/TournamentResults<file_sep>/README.md
# Tournament Results
This is the second project in my pursuit of my Full-Stack Web Developer
Nanodegree from Udacity. Following is Udacity's description for this project:
"In this project, you’ll be writing a Python module that uses the PostgreSQL
database to keep track of players and matches in a game tournament. The game
tournament will use the Swiss system for pairing up players in each round:
players are not eliminated, and each player should be paired with another player
with the same number of wins, or as close as possible. This project has two
parts: defining the database schema (SQL table definitions), and writing the
code that will use it."
To execute this project, please follow the steps in the sections below.
----
## Install VirtualBox 4.3
VirtualBox 4.3 is required for Vagrant to function. The steps for installing it
vary depending on your operating system. You can find the installer for many
operating systems [here](https://www.virtualbox.org/wiki/Download_Old_Builds_4_3).
If you happen to be using Ubuntu 15.04 (as I did for this project), you can try
this terminal command:
```
sudo apt-get install virtualbox-4.3
```
*This command will probably work for other versions of Ubuntu as well.*
----
## Install Vagrant
Vagrant is required to manage the virtual machine (VM) used for executing this
project. The VM image is automatically fetched by Vagrant when the VM is
powered up the first time. The VM comes preconfigured with Python and
PostgreSQL. The steps for installing Vagrant vary depending on your operating
system. You can find the installer for many operating systems
[here](https://www.vagrantup.com/downloads.html).
If you happen to be using Ubuntu 15.04 (as I did for this project), you can try
this terminal command:
```
sudo apt-get install vagrant
```
*This command will probably work for other versions of Ubuntu as well.*
----
## Run the Test Suite
Use a command line terminal for the following steps.
**Clone the repository to your local system, then launch the VM:**
```
git clone https://github.com/richgieg/TournamentResults.git
cd TournamentResults/vagrant
vagrant up
```
*It may take several minutes for the VM to spin up when you're launching it for
the first time, since the VM image is being fetched and the one-time
configuration must take place. Please be patient. Once the process is complete,
your terminal prompt will be returned, thus allowing you to execute the next
steps.*
**Connect to the VM via SSH, create the database, then run the test suite:**
```
vagrant ssh
cd /vagrant/tournament
psql -f tournament.sql
python tournament_test.py
```
*If all tests were successfully executed, the last line of output should be
"Success! All tests pass!" If that is not the case, then the output can be
examined in order to determine which unit test failed. With this vital
information, one should be able to easily track down the problem in the code
(if a problem happened to be present).*
Example of the expected output:
```
1. Old matches can be deleted.
2. Player records can be deleted.
3. After deleting, countPlayers() returns zero.
4. After registering a player, countPlayers() returns 1.
5. Players can be registered and deleted.
6. Newly registered players appear in the standings with no matches.
7. After a match, players have updated standings.
8. After one match, players with one win are paired.
Success! All tests pass!
```
**Exit the SSH session and shutdown the VM:**
```
exit
vagrant halt
```
<file_sep>/vagrant/tournament/tournament.py
#!/usr/bin/env python
#
# tournament.py -- implementation of a Swiss-system tournament
#
import psycopg2
# Define internal constants for table and view names.
_PLAYER_TABLE = "players"
_MATCH_TABLE = "matches"
_PLAYER_STANDINGS_VIEW = "player_standings"
_NEXT_PAIRING_VIEW = "next_pairing"
def connect():
"""Connect to the PostgreSQL database. Returns a database connection."""
return psycopg2.connect("dbname=tournament")
def _query(query, values=(), commit=False):
"""Executes a query against the PostgreSQL database.
This is an internal helper function that will execute a query against the
PostgreSQL database. If the commit argument is False, then the function will
return the results. Otherwise, the function will commit the changes to the
database and return an empty list.
Args:
query: The query string to execute against the database.
values: A tuple containing the values to substitute into the query
string (OPTIONAL, default is an empty tuple).
commit: If true, changes are committed (OPTIONAL, default is False).
Returns:
If the commit argument is False (default), then the function returns a
list containing the resulting rows from the execution of the query.
Otherwise, the function returns an empty list.
"""
results = []
db = connect()
cursor = db.cursor()
cursor.execute(query, values)
if commit:
db.commit()
else:
results = cursor.fetchall()
db.close()
return results
def _clearTable(table):
"""Remove all the records from a table.
This is an internal helper function that will remove all the records from
the table specified in the table argument.
Args:
table: The name of the table from which to remove all records.
"""
_query("DELETE FROM " + table, commit=True)
def deleteMatches():
"""Remove all the match records from the database."""
_clearTable(_MATCH_TABLE)
def deletePlayers():
"""Remove all the player records from the database."""
_clearTable(_PLAYER_TABLE)
def countPlayers():
"""Returns the number of players currently registered."""
result = _query("SELECT COUNT(*) FROM " + _PLAYER_TABLE)
return int(result[0][0])
def registerPlayer(name):
"""Adds a player to the tournament database.
The database assigns a unique serial id number for the player. (This
should be handled by your SQL database schema, not in your Python code.)
Args:
name: The player's full name (need not be unique).
"""
_query("INSERT INTO players (name) VALUES (%s)", (name,), True)
def playerStandings():
"""Returns a list of the players and their win records, sorted by wins.
The first entry in the list should be the player in first place, or a player
tied for first place if there is currently a tie.
Returns:
A list of tuples, each of which contains (id, name, wins, matches):
id: The player's unique id (assigned by the database).
name: The player's full name (as registered).
wins: The number of matches the player has won.
matches: The number of matches the player has played.
"""
return _query("SELECT * FROM " + _PLAYER_STANDINGS_VIEW)
def reportMatch(winner, loser):
"""Records the outcome of a single match between two players.
Args:
winner: The id number of the player who won.
loser: The id number of the player who lost.
"""
query = "INSERT INTO " + _MATCH_TABLE + " (winner, loser) VALUES (%s, %s)"
values = (winner, loser)
_query(query, values, True)
def swissPairings():
"""Returns a list of pairs of players for the next round of a match.
Assuming that there are an even number of players registered, each player
appears exactly once in the pairings. Each player is paired with another
player with an equal or nearly-equal win record, that is, a player adjacent
to him or her in the standings.
Returns:
A list of tuples, each of which contains (id1, name1, id2, name2).
id1: The first player's unique id.
name1: The first player's name.
id2: The second player's unique id.
name2: The second player's name.
"""
return _query("SELECT * FROM " + _NEXT_PAIRING_VIEW)
<file_sep>/vagrant/tournament/tournament.sql
-- Create tournament database and connect to it.
DROP DATABASE IF EXISTS tournament;
CREATE DATABASE tournament;
\c tournament
-- Create players table.
CREATE TABLE players (
id serial primary key,
name text
);
-- Create matches table.
CREATE TABLE matches (
id serial primary key,
winner integer references players(id),
loser integer references players(id)
);
-- Create view for finding number of wins per player.
CREATE VIEW player_wins AS
SELECT players.id, COUNT(matches.winner) AS wins
FROM players LEFT JOIN matches
ON players.id = matches.winner
GROUP BY players.id;
-- Create view for finding number of matches per player.
CREATE VIEW player_matches AS
SELECT players.id, COUNT(matches.winner) AS matches
FROM players LEFT JOIN matches
ON players.id = matches.winner OR players.id = matches.loser
GROUP BY players.id;
-- Create view for player standings.
CREATE VIEW player_standings AS
SELECT players.id, players.name, player_wins.wins, player_matches.matches
FROM players, player_wins, player_matches
WHERE players.id = player_wins.id AND players.id = player_matches.id
ORDER BY player_wins.wins DESC;
-- Create view for player standings with row numbers.
-- This view is a helper view for the "next pairing" view below.
CREATE VIEW player_standings_row_numbers AS
SELECT row_number() over() AS row, id, name
FROM player_standings;
-- Create view for next pairing.
-- This code performs a self join on the player_standings_row_numbers view,
-- utilizing the row numbers as a guide to form records containing info for the
-- players from each pair of adjacent records in the player_standings view.
CREATE VIEW next_pairing AS
SELECT a.id AS id1, a.name AS name1, b.id AS id2, b.name AS name2
FROM player_standings_row_numbers AS a, player_standings_row_numbers AS b
WHERE (a.row % 2 = 1) AND (b.row = a.row + 1);
| 449e0bf51e51a58af1bc5f08eaf4f70df5fdb2b1 | [
"Markdown",
"SQL",
"Python"
] | 3 | Markdown | richgieg/TournamentResults | d3336d9eeee431d204717f098b068a421b154bce | 4765441398d83dc6523a11929b75a616b50c9888 |
refs/heads/master | <file_sep># ColorPicker
ColorPicker was inspired websites such as Coolors.co.
# Build status
Current Build: 2.4
Edit History:
1.0 - Randomizer Feature Built and Working
1.1 - Added Lock feature
1.2 - CSS changes
2.0 - Scheme Gen Feature Built and Working
2.1 - CSS Updates
2.2 - Code Optimizations/Refactors
2.3 - Randomizer to Scheme Feature pushed (breaks app)
2.4 - Bug Fixes
# Languages Used:
React.js, Next.js, JS, CSS
# Provide Feedback
Please give me feedback so I can fine tune the game: https://forms.gle/QuXB5xRNcpi62Ler7
# Credits
Shout out General Assembly for teaching me this stuff.
Shout out <NAME>, Carlos, Kenny and Nathaniel for helping.
-- A SVK Snip
<file_sep>import React, {Component} from "react";
class Lock extends Component {
constructor(props) {
super(props);
}
render() {
if (this.props.locked === false) {
return (
<div>
<button onClick={() => this.props.updateLock(this.props.column)} className="lock-button" type="button">
LOCK
</button>
<style jsx>{`
@import url("https://fonts.googleapis.com/css?family=Sulphur+Point&display=swap");
.lock-button {
display: block;
text-align: center;
height: 3vh;
width: 5vw;
background-color: white;
border: 1px solid black;
border-radius: 3px;
font-family: "Sulphur Point", sans-serif;
color: black;
font-size: 14px;
cursor: pointer;
margin: auto;
}
`}</style>
</div>
);
} else {
return (
<div>
<button
onClick={() => this.props.updateLock(this.props.column)}
className="unlock-button"
type="button"
>
UNLOCK
</button>
<style jsx>{`
@import url("https://fonts.googleapis.com/css?family=Sulphur+Point&display=swap");
.unlock-button {
display: block;
text-align: center;
height: 3vh;
width: 5vw;
background-color: black;
border: 1px solid white;
border-radius: 3px;
font-family: "Sulphur Point", sans-serif;
color: white;
font-size: 14px;
cursor: pointer;
margin: auto;
}
`}</style>
</div>
);
}
}
}
export default Lock;
<file_sep>import React, { Component } from "react";
import Link from "next/link";
class GenerateScheme extends Component {
constructor(props) {
super(props);
}
render() {
console.log(this.props.colorInfo)
return (
<div>
<button className="scheme-button" type="button">
<Link href={"/Scheme/" + this.props.colorInfo}>
<a>Generate Scheme</a>
</Link>
</button>
<style jsx>{`
@import url("https://fonts.googleapis.com/css?family=Sulphur+Point&display=swap");
.scheme-button {
display: block;
text-align: center;
height: 3vh;
width: 7.5vw;
background-color: white;
border: 1px solid black;
border-radius: 3px;
font-family: "Sulphur Point", sans-serif;
color: black;
font-size: 14px;
cursor: pointer;
margin: 5px auto;
}
a{
text-decoration: none;
}
`}</style>
</div>
);
}
}
export default GenerateScheme;
<file_sep>import React from "react";
import Head from "next/head";
import Layout from "../components/Layout";
import SchemeGen from "../components/SchemeGen/SchemeGen"
const Scheme = () => (
<div>
<Head>
<title>Iro - Color Scheme Generator</title>
<link rel="icon" href="/responsive.png" />
</Head>
<Layout>
<SchemeGen />
</Layout>
</div>
);
export default Scheme;<file_sep>import React, { Component } from "react";
class ColorSection extends Component {
constructor(props) {
super(props);
}
render() {
const column = {
gridColumn: `${this.props.idx + 1}`,
backgroundColor: `${this.props.info.hex.value}`,
border: "1px solid black"
};
return (
<div style={column} className="color-block">
<div className="color-info">
<h4>{this.props.info.name.value}</h4>
<p>{this.props.info.hex.value}</p>
</div>
<style jsx>{`
.color-info {
background: rgba(255, 255, 255, 0.3);
width: 10vw;
height: 7vh;
margin: auto;
color: black;
text-align: center;
}
`}</style>
</div>
);
}
}
export default ColorSection;
<file_sep>import React, { Component } from "react";
import SchemeOptions from "./SchemeHeader/SchemeOptions";
import ColorContainer from "./ColorSection/ColorContainer";
import ColorSearch from "./ColorSection/ColorSearch";
import SchemeInfo from "./SchemeHeader/SchemeInfo";
class SchemeGen extends Component {
constructor(props) {
super(props);
this.state = {
colorsNeeded: 3,
mode: "monochrome",
hex: "",
colors: []
};
}
getColorsNeeded = num => {
this.setState({ colorsNeeded: num });
};
getMode = style => {
this.setState({ mode: style });
};
getHex = color => {
let adjustedColor = color.split("#").join("");
this.setState({ hex: adjustedColor });
};
updateLock = idx => {
let updatedArray = this.state.colors.slice(0);
updatedArray[idx].locked = !this.state.colors[idx].locked;
this.setState({ colors: updatedArray });
};
fetchColors = () => {
let colorsToFetch =
"https://www.thecolorapi.com/scheme?hex=" +
this.state.hex +
"&mode=" +
this.state.mode +
"&count=" +
this.state.colorsNeeded;
fetch(colorsToFetch)
.then(res => res.json())
.then(res =>
this.setState({
colors: res
})
)
.catch(err => console.log(err));
};
render() {
return (
<div>
<div className="scheme-info">
<SchemeInfo />
<SchemeOptions
getNumbers={this.getColorsNeeded}
clickFunction={this.fetchColors}
updateMode={this.getMode}
updateHex={this.getHex}
/>
</div>
<ColorSearch color={this.state.hex} />
<ColorContainer hex={this.state.hex} columns={this.state.colorsNeeded} colorData={this.state.colors} height={"70.7vh"} />
<style jsx>{`
@import url("https://fonts.googleapis.com/css?family=Sulphur+Point&display=swap");
.scheme-info {
background: rgba(0, 0, 0, 0.95);
color: white;
height: 10vh;
width: 100vw;
display: grid;
grid-template-columns: 1fr 1fr;
}
`}</style>
</div>
);
}
}
export default SchemeGen;
<file_sep>import React, { Component } from "react";
import RandomizerOptions from "./RandomizerHeader/RandomizerOptions/RandomizerOptions";
import ColorContainer from "./ColorSection/ColorContainer";
import RandomizerInfo from "./RandomizerHeader/RandomizerInfo/RandomizerInfo"
class RandomGen extends Component {
constructor(props) {
super(props);
this.state = {
colorsNeeded: 3,
colors: []
};
}
getColorsNeeded = num => {
this.setState({ colorsNeeded: num });
};
updateLock = (idx) => {
let updatedArray = this.state.colors.slice(0)
updatedArray[idx].locked = !(this.state.colors[idx].locked)
this.setState({ colors: updatedArray });
}
fetchColors = () => {
this.setState({
colors: this.state.colors.filter(color => (color.locked === true))
}, () => {
let colorsToFetch = this.buildColorArray(this.state.colorsNeeded);
for (let i = 0; i < (colorsToFetch.length - this.state.colors.length); i++) {
fetch(colorsToFetch[i])
.then(res => res.json())
.then(res =>
this.setState({
colors: [...this.state.colors, { data: res, locked: false }]
})
)
.catch(err => console.log(err));
}
});
};
buildColorArray = num => {
let colors = [];
for (let i = 0; i < num; i++) {
let hexPoss = [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
"A",
"B",
"C",
"D",
"E",
"F"
];
let val1 = hexPoss[Math.floor(Math.random() * 16)];
let val2 = hexPoss[Math.floor(Math.random() * 16)];
let val3 = hexPoss[Math.floor(Math.random() * 16)];
let val4 = hexPoss[Math.floor(Math.random() * 16)];
let val5 = hexPoss[Math.floor(Math.random() * 16)];
let val6 = hexPoss[Math.floor(Math.random() * 16)];
let functionArray = [val1, val2, val3, val4, val5, val6];
let colorSet = this.shuffleArray(functionArray);
colors.push("https://www.thecolorapi.com/id?hex=" + colorSet.join(""));
}
return colors;
};
shuffleArray = arr => {
let idx = arr.length;
let hold;
let ridx;
while (idx) {
ridx = Math.floor(Math.random() * idx);
idx -= 1;
hold = arr[idx];
arr[idx] = arr[ridx];
arr[ridx] = hold;
}
return arr;
};
render() {
return (
<div>
<div className="randomizer-info">
<RandomizerInfo />
<RandomizerOptions
getNumbers={this.getColorsNeeded}
clickFunction={this.fetchColors}
/>
</div>
<ColorContainer
columns={this.state.colors.length}
colorData={this.state.colors}
updateLock={this.updateLock}
height={"80.7vh"}
/>
<style jsx>{`
@import url("https://fonts.googleapis.com/css?family=Sulphur+Point&display=swap");
.randomizer-info {
background: rgba(0, 0, 0, 0.95);
color: white;
height: 10vh;
width: 100vw;
display: grid;
grid-template-columns: 1fr 1fr;
}
`}</style>
</div>
);
}
}
export default RandomGen;
<file_sep>import React, {Component} from "react";
import ColorSection from "./ColorSection"
// const grid = props => {
// display: grid,
// gridTemplateColumns: {props.columns}
// }
class ColorContainer extends Component {
constructor(props) {
super(props);
}
render() {
let colors = this.props.colorData.map((color, i) => {
return <ColorSection info={color} column={i} updateLock={this.props.updateLock}/>;
});
const container = {
display: "grid",
gridTemplateColumns: `repeat(${this.props.columns}}, 1fr)`,
height: `${this.props.height}`
};
return (
<div style={container} className="color-container">
{colors}
<style jsx>{`
`}</style>
</div>
);
}
}
export default ColorContainer;
<file_sep>import React, { Component } from "react";
class ColorSearch extends Component {
constructor(props) {
super(props);
}
render() {
const column = {
backgroundColor: `#${this.props.color}`,
height: "10vh",
width: "100vw",
border: "2px solid black",
margin: "auto",
textAlign: "center"
};
const other = {
backgroundColor: "white",
height: "1vh",
width: "100vw"
};
if (this.props.color.length >= 3) {
return <div style={column} className="color-block">#{this.props.color}</div>;
} else {
return <div style={other} className="color-block"></div>;
}
}
}
export default ColorSearch;
<file_sep>import React, { Component } from "react";
import ColorSection from "./ColorSection";
const ColorContainer = props => {
if (props.hex.length < 3 || props.hex.length > 6) {
return (
<div>
Please enter a valid HexCode above and press the "Generate" button.
</div>
);
} else {
if (props.colorData.colors === undefined) {
return <div>Click "Generate" to generate your scheme.</div>;
} else {
let colors = props.colorData.colors.map((color, i) => {
return <ColorSection info={color} idx={i}/>;
});
const container = {
display: "grid",
gridTemplateColumns: `repeat(${props.columns}}, 1fr)`,
height: `${props.height}`
};
return (
<div style={container}>
{colors}
</div>
);
}
}
};
export default ColorContainer;<file_sep>import Header from "./Header/Header";
const Layout = props => (
<div>
<Header />
{props.children}
<style jsx global>{`
body {
margin: 0;
}
`}</style>
</div>
);
export default Layout;<file_sep>import React, { Component } from "react";
import Lock from "./Lock"
import GenerateScheme from "./GenerateScheme"
class ColorSection extends Component {
constructor(props) {
super(props);
}
render() {
const column = {
gridColumn: `${this.props.column + 1}`,
backgroundColor: `${this.props.info.data.hex.value}`,
border: "1px solid black"
};
return (
<div style={column} className="color-block">
<div className="color-info">
<h4>{this.props.info.data.name.value}</h4>
<p>{this.props.info.data.hex.value}</p>
<Lock
locked={this.props.info.locked}
updateLock={this.props.updateLock}
column={this.props.column}
/>
<GenerateScheme colorInfo={this.props.info.data.hex.value}/>
</div>
<style jsx>{`
.color-info {
background: rgba(255, 255, 255, 0.3);
width: 10vw;
height: 15vh;
margin: auto;
color: black;
text-align: center;
}
`}</style>
</div>
);
}
}
export default ColorSection;
<file_sep>import React from "react";
const RandomizerInfo = () => (
<div className="randomizer-info">
<h1 className="randomizer-title">Random Color Generator</h1>
<p className="randomizer-desc">
Iro can generate a random set of colors (up to 7). To change the amount of
colors, use the dropdown. To generate the colors, click the button. After generating, you can lock colors you want to keep before re-generating!
</p>
<style jsx>{`
@import url("https://fonts.googleapis.com/css?family=Sulphur+Point&display=swap");
.randomizer-info {
margin: 1.5vh 0;
}
.randomizer-title {
font-family: "Sulphur Point", sans-serif;
font-size: 1.25em;
margin: 0;
height: 2vh;
width: 40vw;
padding: 0 0 0 2.5vw;
}
.randomizer-desc {
font-family: "Sulphur Point", sans-serif;
font-size: 0.9em;
height: 2vh;
margin: .5vh 0 0 0;
width: 40vw;
padding: 0 0 0 2.5vw;
}
`}</style>
</div>
);
export default RandomizerInfo;
<file_sep>import React, {Component} from "react";
class RandomizerOptions extends Component {
render() {
return (
<div className="buttons-grid">
<select
id="dropdown"
ref={input => (this.menu = input)}
onChange={() => this.props.getNumbers(parseInt(this.menu.value))}
>
<option value="3">Three (3)</option>
<option value="4">Four (4)</option>
<option value="5">Five (5)</option>
<option value="6">Six (6)</option>
<option value="7">Seven (7)</option>
</select>
<button className="fetch-button" type="button" onClick={() => this.props.clickFunction()}>Generate</button>
<style jsx>{`
@import url("https://fonts.googleapis.com/css?family=Sulphur+Point&display=swap");
button {
display: block;
margin: 0px auto;
text-align: center;
max-width: 150px;
max-height: 7vh;
padding: 14px 10px;
background-color: black;
border-radius: 3px;
font-family: "Sulphur Point", sans-serif;
color: white;
font-size: 14px;
cursor: pointer;
margin: 1.5vh 0;
}
.fetch-button {
grid-column: 4;
}
#dropdown {
grid-column: 3;
display: block;
heigh: 1vh;
width: 10vw;
margin: 4.5vh 0;
}
.buttons-grid {
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
}
`}</style>
</div>
);
}
}
export default RandomizerOptions;
| aec770ed81f733d8c94cc84be7ef663988017ff8 | [
"Markdown",
"JavaScript"
] | 14 | Markdown | svkalvakolanu/ColorPicker | 48effca2cb43be6e87a3770a34c25b0f3ecc910f | 8e6699bbbe2aa3b9b4c16e9d6297bb551647fc11 |
refs/heads/master | <repo_name>mikk5394/Hovedopgave<file_sep>/auctions/views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .forms import GetAuctions
from .api_call import get_auctions
@login_required
def about(request):
return render(request, 'auctions/about.html')
@login_required
def home(request):
if request.method == 'POST':
form = GetAuctions(request.POST)
if form.is_valid():
region = form.cleaned_data['region']
server = form.cleaned_data['server']
amount = form.cleaned_data['amount']
auctions = get_auctions(region, server, amount)
context = {
'form': form,
'auctions': auctions,
'total_auctions': get_auctions.number_of_auctions
}
return render(request, 'auctions/home.html', context)
form = GetAuctions()
return render(request, 'auctions/home.html', {'form': form})
| 93afe97cb5f5c5cf09d2dbcda6607193edf47ecf | [
"Python"
] | 1 | Python | mikk5394/Hovedopgave | 376c2337cd6409b33e40af189ca64be7f77eb1fa | 23f58d93d28a38ccdef213992dd98bbfef937b87 |
refs/heads/master | <file_sep># TriviaGame
Come test your knowledge on the NBA!
This program utilizes jquery concepts as well as html and css to develop this webpage.
<file_sep>const timeLeft = 10;
const timeBetweenQuestions = 4;
$(document).ready(function(){
function Question(question, options, answer, imageUrl){
this.question = question;
this.options = options;
this.answer = answer;
this.imageUrl = imageUrl;
}
var triviaGame = {
timerTimeOut: null,
timeOutCounter: timeLeft,
questions : [],
questionIndex : 0,
currentQuestionObj: null,
winsCount: 0,
wrongCount: 0,
// blankQuestion:0, attempted to create a property called blankQuestion and setting it with a value of 0.
initialize: function(){
var question1 = new Question("1. What team was <NAME> on?",
["Chicago Bulls", "LA Lakers", "Orlando Magic",
"Atlanta Hawks"], "LA Lakers", "lakers.jpg");
var question2 = new Question("2. What team was <NAME> on?",
["Chicago Bulls", "Oklahoma City Thunder", "Miami Heat",
"Atlanta Hawks"], "Chicago Bulls","bulls.jpg");
var question3 = new Question("3. What team is <NAME> on?",
["New York Knicks", "Portland Trailblazers", "Cleveland Cavaliers",
"Dallas Mavericks"], "Cleveland Cavaliers","cavs.png");
var question4 = new Question("4. What team is <NAME> on?",
["Brooklyn Nets", "Houston Rockets", "Golden State Warriors",
"San Antonio Spurs"], "Golden State Warriors","warriors.png");
var question5 = new Question("5. Which team won a championship in 2005?",
["La Lakers", "Chicago Bulls", "Golden State Warriors",
"San Antonio Spurs"], "San Antonio Spurs","spurs.png");
triviaGame.questions.push(question1, question2, question3, question4, question5);
},
reset: function(){
triviaGame.questionIndex = 0;
triviaGame.winsCount = 0;
},
resetTimeOut: function(){
triviaGame.timeOutCounter = timeLeft;
},
start: function(){
triviaGame.reset();
$("#start-div").hide();
$("#final-div").hide();
$("#timer-div").show();
$("#trivia-div").show();
triviaGame.nextQuestion();
},
nextQuestion: function(){
if(triviaGame.questionIndex === triviaGame.questions.length){
triviaGame.stop();
}
else{
triviaGame.currentQuestionObj = triviaGame.questions[triviaGame.questionIndex];
triviaGame.timerTimeOut = setInterval(triviaGame.updateTimer, 1000);
triviaGame.displayTimeOut();
triviaGame.displayQuestion();
triviaGame.questionIndex++;
}
},
displayQuestion: function(question){
$("#trivia-div").show();
$("#answer-div").hide();
$("#question-div").text(triviaGame.currentQuestionObj.question);
var newDiv = $('<div>');
var optionsArray = triviaGame.currentQuestionObj.options;
optionsArray.forEach(function(option){
newDiv.append( $('<p><input type="radio" name="option" value="' + option +
'"></input><label class="option-label">' + option + '</label></p>'));
});
$("#options-div").html(newDiv);
},
evaluateAnswer: function(){
triviaGame.clearTimer();
var selectedAnswer = $(this).val();
if( selectedAnswer === triviaGame.currentQuestionObj.answer){
triviaGame.winsCount++;
triviaGame.displayAnswer(true, "You got the answer right!");
}
else{
triviaGame.displayAnswer(false, "Oh no! Your answer was wrong!");
triviaGame.wrongCount++;
}
},
displayAnswer: function(isCorrectAnswer, message){
$("#trivia-div").hide();
$("#answer-div").show();
$("#result-div").html(message);
var pAnswer = $('<p>');
if(!isCorrectAnswer){
pAnswer.html("The right answer was: " + triviaGame.currentQuestionObj.answer);
}
else{
pAnswer.html( triviaGame.currentQuestionObj.answer);
}
$("#answer-img-div").html(pAnswer);
var answerImage = $("<img>");
var url = "assets/images/" + triviaGame.currentQuestionObj.imageUrl;
answerImage.attr("src", url);
answerImage.addClass("answer-image");
$("#answer-img-div").append(answerImage);
setTimeout(triviaGame.nextQuestion, timeBetweenQuestions* 1000);
},
displayTimeOut: function(){
$("#timeout").text("Time Remaining: " + triviaGame.timeOutCounter + " seconds");
},
updateTimer: function(){
triviaGame.timeOutCounter--;
triviaGame.displayTimeOut();
if(triviaGame.timeOutCounter === 0){
// triviaGame.blankQuestion++; attempted to answer display unanswered questions by inputting counter within my if statement for the timeer runs out.
triviaGame.clearTimer();
triviaGame.displayAnswer(false, "Out of Time!");
}
},
clearTimer: function(){
clearInterval(triviaGame.timerTimeOut);
triviaGame.resetTimeOut();
},
stop: function(){
$("#final-result-div").text("Correct answers: " + triviaGame.winsCount);
$("#final").text("Wrong answers: " + triviaGame.wrongCount);
// $("#blank").text("Questions left blank: " + triviaGame.blankQuestion); attempted to display unanswered questions.
$("#timer-div").hide();
$("#answer-div").hide();
$("#final-div").show();
$("#final").show();
//$("#blank").show(); Attempted to display unanswered questions. The end result displayed all 5 questions as blank so I have coded this aspect of the code out of the my program.
}
}
triviaGame.initialize();
$("#start-btn").click(triviaGame.start);
$("#restart-btn").click(triviaGame.start);
$('#options-div').on('change', 'input[name="option"]', triviaGame.evaluateAnswer);
});
| b05c0b5c02e0a09e2b2a009d3c552f9d36d149eb | [
"Markdown",
"JavaScript"
] | 2 | Markdown | aditp928/TriviaGame | 5d3e4e3650d995df31f03ee35526f0f907376443 | 71857dba075dd5628708db8bdb8ac90ce78e4a07 |
refs/heads/master | <file_sep># voc2coco
Make COCO annotation format .json file from Pascal VOC annotation xml file
# How to use
1. Use txtwriter.py to make xmllist.txt
xmllist.txt contain xml file names like this
2007_000027.xml
2007_000032.xml
2007_000033.xml
2007_000039.xml
2007_000042.xml
2007_000061.xml
2007_000063.xml
2007_000068.xml
2007_000121.xml
2. Use voc2coco.py to make .json file
Example command:
<pre><code>
$ python voc2coco.py xmllist.txt path/of/VOCdevkit/VOC2012/Annotations output.json
</code></pre>
# Acknowledgement
https://github.com/shiyemin/voc2coco
<file_sep>import os
import sys
path = "Path/of/VOCdevkit/VOC2012/Annotations"
file_list = os.listdir(path)
file_list_xml = [file for file in file_list if file.endswith(".xml")]
f = open('xmllist.txt', "a")
for i in range(len(file_list_xml)):
f.write(file_list_xml[i] + "\n")
| dbb0def0db31121c44b819a4a8dd2b6caa6cf067 | [
"Markdown",
"Python"
] | 2 | Markdown | cbpark-nota/voc2coco | 912ab37e7ec377ae949460cb804cd73d53513cff | f5005674636e048e60772d9797f406c5b3d51ccb |
refs/heads/main | <file_sep>#!/usr/bin/env bash
## Toggles xdebug on|off.
##
## Usage: fin php/xdebug on|off
## Prior to using you must enable Xdebug in your local settings and restart the
## container:
##
## fin config set --env=local XDEBUG_ENABLED=1
## fin restart
##
#: exec_target = cli
set -e
$(dirname $0)/ext xdebug $1
<file_sep>#!/usr/bin/env bash
## Runs npm commands within the build container.
##
## Usage: fin npm [command]
# This runs within the CLI container, so all tools are available.
#: exec_target = cli
set -e
npm "$@"
| 759b9e09054e42b1c9bbb998c8a3ef872a0bf683 | [
"Shell"
] | 2 | Shell | Jwaxo/jwax-portfolio | 4430fe1d9b870e43ceeff8a1834dd86011ff68d0 | 443fbbabdbbe200f582018ecdea482c5fe52e995 |
refs/heads/master | <file_sep>//
// ViewController.swift
// QuickPlayer-Example
//
// Created by Shvier on 31/03/2017.
// Copyright © 2017 Shvier. All rights reserved.
//
import UIKit
import QuickPlayer
import AVFoundation
class ViewController: UIViewController {
var player: QuickPlayer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
player = QuickPlayer(frame: view.frame)
view.addSubview(player.playerView)
player.startPlay(videoUrl: URL(fileURLWithPath: Bundle.main.path(forResource: "test", ofType: "m4v")!))
DispatchQueue.main.asyncAfter(deadline: .now() + 10) { [unowned self] in
self.player.replaceCurrentItem(coverUrl: nil, videoUrl: URL(fileURLWithPath: Bundle.main.path(forResource: "test", ofType: "m4v")!))
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: QuickPlayerDelegate {
}
<file_sep>//
// QuickSessionTaskProtocol.swift
// QuickPlayer
//
// Created by Shvier on 14/04/2017.
// Copyright © 2017 Shvier. All rights reserved.
//
import Foundation
@objc public protocol QuickSessionTaskDelegate {
@objc func requestTaskDidUpdateCache()
@objc optional func requestTaskDidReceivedResponse()
@objc optional func requestTaskDidFinishedLoading()
@objc optional func requestTaskDidFailed(error: Error)
}
<file_sep>//
// Array+Extension.swift
// QuickPlayer
//
// Created by Shvier on 14/04/2017.
// Copyright © 2017 Shvier. All rights reserved.
//
import Foundation
extension Array where Element: Equatable {
mutating func remove(object: Element) {
if let index = index(of: object) {
remove(at: index)
}
}
}
<file_sep>//
// QuickSessionTask.swift
// QuickPlayer
//
// Created by Shvier on 12/04/2017.
// Copyright © 2017 Shvier. All rights reserved.
//
import UIKit
public class QuickSessionTask: NSObject {
let RequestTimeOut: TimeInterval = 10
public weak var delegate: QuickSessionTaskDelegate?
var requestURL: URL?
var requestOffset: Int64 = 0
var fileLength: Int64 = 0
var cacheLength: Int = 0
var allowCache: Bool = true
var cancel: Bool {
get {
return self.cancel
}
set {
self.cancel = newValue
if newValue {
sessionTask?.cancel()
session?.invalidateAndCancel()
}
}
}
var filename: String!
var session: URLSession?
var sessionTask: URLSessionDataTask?
public init(filename: String) {
super.init()
self.filename = filename
let _ = QuickCacheHandle.createTempFile(filename: filename)
}
public func resume() {
let request = NSMutableURLRequest(url: (requestURL?.originalSchemeURL())!, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: RequestTimeOut)
if requestOffset > 0 {
request.addValue("bytes=\(requestOffset)-\(fileLength-1)", forHTTPHeaderField: "Range")
}
session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue.main)
sessionTask = session?.dataTask(with: request as URLRequest)
sessionTask?.resume()
}
}
extension QuickSessionTask: URLSessionDataDelegate {
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
if cancel {
return
}
print("response: \(response)")
completionHandler(.allow)
let httpResponse = response as! HTTPURLResponse
let contentRange = httpResponse.allHeaderFields["Content-Rage"] as! String
let fileLength = contentRange.components(separatedBy: "/").last
self.fileLength = Int64.init(fileLength!)! > 0 ? Int64.init(fileLength!)! : Int64.init(response.expectedContentLength)
delegate?.requestTaskDidReceivedResponse!()
}
}
extension QuickSessionTask: NSURLConnectionDataDelegate {
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if cancel {
return
}
QuickCacheHandle.writeTempFile(data: data, filename: filename)
cacheLength += NSData.init(data: data).length
delegate?.requestTaskDidUpdateCache()
}
public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if cancel {
print("download cancel")
} else {
if let e = error {
delegate?.requestTaskDidFailed!(error: e)
} else {
if allowCache {
QuickCacheHandle.cacheTempFile(filename: filename)
}
delegate?.requestTaskDidFinishedLoading!()
}
}
}
}
<file_sep>//
// QuickPlayer.swift
// QuickPlayer
//
// Created by Shvier on 31/03/2017.
// Copyright © 2017 Shvier. All rights reserved.
//
import UIKit
import AVFoundation
open class QuickPlayer: NSObject {
// AVPlayer
private(set) public var player: AVPlayer?
// video current play time
private(set) public var currentTime: CGFloat = 0.0
// view rendering video
private(set) public var playerView: UIView!
// current video item
private(set) public var currentItem: AVPlayerItem?
// current player status
private(set) public var status: PlayerStatus = .Stopped
// cover view url
private(set) public var coverUrl: URL!
// video url
private(set) public var videoUrl: URL!
// current time callback frequency
public var timeFrequency: Float64 = 1.0
// player delegate, jump to QuickPlayerDelegate.Swift
public weak var delegate: QuickPlayerDelegate?
// frame of player view
var frame: CGRect = CGRect.zero
// current time observer
var playbackTimeObserver: Any?
// cover image
var coverView: UIImageView?
// AVPlayer layer
var playerLayer: AVPlayerLayer?
// cache resource manager
var resourceManager: QuickResourceManager?
// cache filename
var filename: String?
/// if you like to fix a brief black screen before playing for video, just set a cover image
///
/// - Parameter coverUrl: cover image url
public func preparePlay(coverUrl: URL) {
self.coverUrl = coverUrl
if coverView == nil {
self.configCoverView()
} else {
if (coverView?.isHidden)! {
coverView?.isHidden = false
}
}
}
/// set a url for video
///
/// - Parameter videoUrl: video url
public func startPlay(videoUrl: URL) {
self.videoUrl = videoUrl
self.filename = videoUrl.path.components(separatedBy: "/").last
if videoUrl.absoluteString.hasPrefix("http") {
let cacheFilePath = QuickCacheHandle.cacheFileExists(filename: filename!)
if cacheFilePath != nil {
let url = URL(fileURLWithPath: cacheFilePath!)
currentItem = AVPlayerItem(url: url)
} else {
resourceManager = QuickResourceManager(filename: filename!)
resourceManager?.delegate = self
let asset = AVURLAsset(url: videoUrl)
currentItem = AVPlayerItem(asset: asset)
}
} else {
currentItem = AVPlayerItem(url: videoUrl)
}
if player == nil {
self.videoUrl = videoUrl
currentItem = AVPlayerItem(url: videoUrl)
self.configPlayer()
}
self.play()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
if self.currentTime <= 0 {
// play waiting indicator
}
}
}
/// pause player
public func pause() {
delegate?.playerChangedStatus!(status: .Paused)
status = .Paused
player?.pause()
}
/// resume Paused status
public func resume() {
delegate?.playerChangedStatus!(status: .Playing)
status = .Playing
player?.play()
}
/// play again from beginning time
public func play() {
delegate?.playerChangedStatus!(status: .Playing)
status = .Playing
player?.seek(to: kCMTimeZero)
player?.play()
}
/// stop playing, the observer will be released when this object deinit
public func stop() {
delegate?.playerChangedStatus!(status: .Stopped)
status = .Stopped
coverView?.removeFromSuperview()
playerLayer?.removeFromSuperlayer()
player?.pause()
player?.replaceCurrentItem(with: nil)
resourceManager?.stopLoading()
}
/// replace current item with another video
///
/// - Parameters:
/// - coverUrl: if you don't like a cover image, leave it alone
/// - videoUrl: video url
public func replaceCurrentItem(coverUrl: URL?, videoUrl: URL?) {
if coverUrl != nil {
self.coverUrl = coverUrl!
self.preparePlay(coverUrl: self.coverUrl)
}
if videoUrl != nil {
self.videoUrl = videoUrl
currentItem = AVPlayerItem(url: videoUrl!)
if self.player == nil {
self.configPlayer()
} else {
self.playerLayer = AVPlayerLayer(player: player)
self.playerLayer?.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
player?.replaceCurrentItem(with: currentItem)
}
self.play()
}
}
/// init
///
/// - Parameter frame: frame of player view
public init(frame: CGRect) {
super.init()
self.frame = frame
self.initialize()
}
deinit {
destoryPlayer()
}
func initialize() {
playerView = ({
let view = UIView(frame: frame)
return view
}())
}
func addObserverForPlayer() {
addObserver(self, forKeyPath: #keyPath(player.currentItem.loadedTimeRanges), options: [.initial, .old, .new], context: nil)
addObserver(self, forKeyPath: #keyPath(player.status), options: [.initial, .old, .new], context: nil)
NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil, queue: OperationQueue.current) { [unowned self] (notification) in
if notification.object as? AVPlayerItem == self.player?.currentItem {
self.delegate?.playerFinished!(player: self)
self.delegate?.playerChangedStatus!(status: .Stopped)
}
}
}
func configCoverView() {
coverView = ({
let view = UIImageView(frame: frame)
view.contentMode = .scaleAspectFit
return view
}())
playerView.addSubview(coverView!)
}
func configPlayer() {
player = ({
let player = AVPlayer(playerItem: self.currentItem)
player.volume = 0
return player
}())
playerLayer = ({
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
return playerLayer
}())
playerView.layer.insertSublayer(playerLayer!, above: playerView.layer)
addObserverForPlayer()
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if player == nil {
return
}
if keyPath == "player.status" {
let status: AVPlayerStatus = AVPlayerStatus(rawValue: ((change![NSKeyValueChangeKey.kindKey] as! NSNumber).intValue))!
switch status {
case .readyToPlay:
self.delegate?.playerChangedStatus!(status: .ReadyToPlay)
self.playbackTimeObserver = self.player?.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(timeFrequency, Int32(NSEC_PER_SEC)), queue: nil, using: { [unowned self] (time) in
let currentSecond = CGFloat((self.player?.currentItem?.currentTime().value)!)/CGFloat((self.player?.currentItem?.currentTime().timescale)!)
self.currentTime = currentSecond
if currentSecond > 0 {
if self.coverView != nil && !((self.coverView?.isHidden)!) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: {
self.coverView?.isHidden = true
})
}
self.delegate?.playerChangedStatus!(status: .Playing)
}
self.delegate?.playerPlayingVideo!(player: self, currentTime: currentSecond)
})
break
case .unknown:
self.delegate?.playerChangedStatus!(status: .Unknown)
break
case .failed:
self.delegate?.playerChangedStatus!(status: .Failed)
break
}
}
}
func destoryObserver() {
NotificationCenter.default.removeObserver(self, forKeyPath: #keyPath(player.currentItem.loadedTimeRanges))
NotificationCenter.default.removeObserver(self, forKeyPath: #keyPath(player.status))
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
if let observer = playbackTimeObserver {
player?.removeTimeObserver(observer)
}
}
func destoryPlayer() {
destoryObserver()
player?.pause()
player = nil
playerLayer?.removeFromSuperlayer()
playerLayer = nil
}
}
extension QuickPlayer: QuickResourceManagerDelegate {
}
<file_sep>//
// QuickResourceManager.swift
// QuickPlayer
//
// Created by Shvier on 12/04/2017.
// Copyright © 2017 Shvier. All rights reserved.
//
import UIKit
import AVFoundation
import MobileCoreServices
open class QuickResourceManager: NSObject {
let MimeType = "video/mp4"
public weak var delegate: QuickResourceManagerDelegate?
lazy var requestList: [AVAssetResourceLoadingRequest] = {
return Array<AVAssetResourceLoadingRequest>()
}()
public var seekRequired: Bool = false
public var filename: String!
var requestTask: QuickSessionTask?
public init(filename: String) {
super.init()
self.filename = filename
}
public func stopLoading() {
requestTask?.cancel = true
}
func addLoadingRequest(loadingRequest: AVAssetResourceLoadingRequest) {
requestList.append(loadingRequest)
objc_sync_enter(self)
if requestTask != nil {
if (loadingRequest.dataRequest?.requestedOffset)! >= Int64((requestTask?.requestOffset)!) &&
(loadingRequest.dataRequest?.requestedOffset)! <= Int64((requestTask?.requestOffset)!) + Int64((requestTask?.cacheLength)!) {
processLoadingRequest()
} else {
if seekRequired {
newTask(loadingRequest: loadingRequest, allowCache: false)
}
}
} else {
newTask(loadingRequest: loadingRequest, allowCache: true)
}
objc_sync_exit(self)
}
func removeLoadingRequest(loadingRequest: AVAssetResourceLoadingRequest) {
requestList.remove(object: loadingRequest)
}
func finishLoading(loadingRequest: AVAssetResourceLoadingRequest) -> Bool {
// fill request information
let contentType = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, MimeType as CFString, String() as CFString)
loadingRequest.contentInformationRequest?.contentType = String.init(describing: contentType)
loadingRequest.contentInformationRequest?.isByteRangeAccessSupported = true
loadingRequest.contentInformationRequest?.contentLength = (requestTask?.fileLength)!
// read cache file
let cacheLength: UInt64 = UInt64((requestTask?.cacheLength)!)
var requestedOffset: UInt64 = UInt64((loadingRequest.dataRequest?.requestedOffset)!)
if loadingRequest.dataRequest?.currentOffset != 0 {
requestedOffset = UInt64((loadingRequest.dataRequest?.currentOffset)!)
}
let canReadLength = cacheLength - (requestedOffset - UInt64((requestTask?.requestOffset)!))
let responseLength = min(canReadLength, UInt64(Int64((loadingRequest.dataRequest?.requestedLength)!)))
loadingRequest.dataRequest?.respond(with: QuickCacheHandle.readTempFileData(offset: requestedOffset - UInt64((requestTask?.requestOffset)!), length: responseLength, filename: filename))
// if cached offset > expected offset, return true
let currentEndOffset: UInt64 = requestedOffset + canReadLength
let requestEndOffset: UInt64 = UInt64((loadingRequest.dataRequest?.requestedOffset)!) + UInt64((loadingRequest.dataRequest?.requestedLength)!)
if currentEndOffset > requestEndOffset {
loadingRequest.finishLoading()
return true
}
return false
}
func newTask(loadingRequest: AVAssetResourceLoadingRequest, allowCache: Bool) {
var fileLength: Int64 = 0
if requestTask != nil {
fileLength += (requestTask?.fileLength)!
requestTask?.cancel = true
}
requestTask = QuickSessionTask(filename: filename)
requestTask?.requestURL = loadingRequest.request.url
requestTask?.requestOffset = (loadingRequest.dataRequest?.requestedOffset)!
requestTask?.allowCache = allowCache
if fileLength > 0 {
requestTask?.fileLength = fileLength
}
requestTask?.delegate = self
requestTask?.resume()
seekRequired = false
}
func processLoadingRequest() {
let finishRequestList = requestList
for loadingRequest in finishRequestList {
if finishLoading(loadingRequest: loadingRequest) {
requestList.remove(object: loadingRequest)
}
}
}
func synchronized(lock: AnyObject, closure: () -> ()) {
objc_sync_enter(lock)
closure()
objc_sync_exit(lock)
}
}
extension QuickResourceManager: AVAssetResourceLoaderDelegate {
public func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool {
addLoadingRequest(loadingRequest: loadingRequest)
return true
}
public func resourceLoader(_ resourceLoader: AVAssetResourceLoader, didCancel loadingRequest: AVAssetResourceLoadingRequest) {
removeLoadingRequest(loadingRequest: loadingRequest)
}
}
extension QuickResourceManager: QuickSessionTaskDelegate {
public func requestTaskDidUpdateCache() {
processLoadingRequest()
let cacheProgress = CGFloat.init((requestTask?.cacheLength)!)/CGFloat.init((requestTask?.fileLength)! - (requestTask?.requestOffset)!)
delegate?.resourceManagerCacheProgress!(manager: self, progress: cacheProgress)
}
public func requestTaskDidFinishedLoading() {
delegate?.resourceManagerFinishLoading!(manager: self)
}
}
<file_sep>
//
// QuickPlayerManager.swift
// QuickPlayer
//
// Created by Shvier on 24/04/2017.
// Copyright © 2017 Shvier. All rights reserved.
//
import UIKit
open class QuickPlayerManager: NSObject {
static let sharedInstance = QuickPlayerManager()
lazy var httpsMode: Bool = {
return false
}()
lazy var cachePath: String = {
return NSHomeDirectory().appending("/Library/Caches/\(Bundle.main.bundleIdentifier!)")
}()
}
<file_sep>//
// QuickCacheHandle.swift
// QuickPlayer
//
// Created by Shvier on 12/04/2017.
// Copyright © 2017 Shvier. All rights reserved.
//
import UIKit
// default cache path: /Library/Caches/com.Shvier.QuickPlayer/xxx.mp4
// default temp file path: /Library/Caches/com.Shvier.QuickPlayer/xxx
public class QuickCacheHandle: NSObject {
static let fileManager = FileManager.default
static var cachePath: String = QuickPlayerManager.sharedInstance.cachePath
static open func createTempFile(filename: String) -> Bool {
let filePath = QuickCacheHandle.tempFilePath(filename: filename)
if fileManager.fileExists(atPath: filePath) {
do {
try fileManager.removeItem(atPath: filePath)
} catch let error {
print("remove temp file error: \(error)")
}
}
return fileManager.createFile(atPath: filePath, contents: nil, attributes: nil)
}
static open func writeTempFile(data: Data, filename: String) {
let fileHandle = FileHandle(forWritingAtPath: QuickCacheHandle.tempFilePath(filename: filename))
fileHandle?.seekToEndOfFile()
fileHandle?.write(data)
}
static open func readTempFileData(offset: UInt64, length: UInt64, filename: String) -> Data {
let fileHandle = FileHandle(forReadingAtPath: QuickCacheHandle.tempFilePath(filename: filename))
fileHandle?.seek(toFileOffset: offset)
return (fileHandle?.readData(ofLength: Int(length)))!
}
static open func cacheTempFile(filename: String) {
do {
let cacheFilePath = "\(cacheFolderPath)/\(filename)"
try fileManager.copyItem(atPath: QuickCacheHandle.tempFilePath(filename: filename), toPath: cacheFilePath)
print("cache file success")
} catch let error {
print("cache file error: \(error)")
}
}
static open func cacheFileExists(filename: String) -> String? {
let cacheFilePath = "\(QuickCacheHandle.cacheFolderPath())/\(filename).mp4"
if fileManager.fileExists(atPath: cacheFilePath) {
print("cache found: \(cacheFilePath)")
return cacheFilePath
}
return nil
}
static open func clearCache() {
do {
try fileManager.removeItem(atPath: QuickCacheHandle.cacheFolderPath())
} catch let error {
print("clear cache error: \(error)")
}
}
static private func tempFilePath(filename: String) -> String {
return "\(QuickCacheHandle.cacheFolderPath())/\(filename).tmp"
}
static open func cacheFolderPath() -> String {
let isDirectory = UnsafeMutablePointer<ObjCBool>.allocate(capacity: 1)
if !fileManager.fileExists(atPath: cachePath, isDirectory: isDirectory) {
do {
try fileManager.createDirectory(atPath: cachePath, withIntermediateDirectories: true, attributes: nil)
} catch let error {
print("create cache folder error: \(error)")
}
}
return cachePath
}
}
<file_sep>//
// QuickPlayerProtocol.swift
// QuickPlayer
//
// Created by Shvier on 01/04/2017.
// Copyright © 2017 Shvier. All rights reserved.
//
@objc public enum PlayerStatus: Int {
case ReadyToPlay
case Paused
case Failed
case Playing
case Stopped
case Finished
case Unknown
}
@objc public protocol QuickPlayerDelegate: class {
@objc optional func playerPlayingVideo(player: QuickPlayer, currentTime: CGFloat)
@objc optional func playerChangedStatus(status: PlayerStatus)
@objc optional func playerFinished(player: QuickPlayer)
@objc optional func playerCached(player: QuickPlayer, cahceProgress: CGFloat)
@objc optional func playerCacheFailed(player: QuickPlayer, error: Error)
}
<file_sep>//
// QuickResourceManagerProtocol.swift
// QuickPlayer
//
// Created by Shvier on 13/04/2017.
// Copyright © 2017 Shvier. All rights reserved.
//
import Foundation
@objc public protocol QuickResourceManagerDelegate: class {
@objc optional func resourceManagerCacheProgress(manager: QuickResourceManager, progress: CGFloat)
@objc optional func resourceManagerFailLoading(manager: QuickResourceManager, error: Error)
@objc optional func resourceManagerFinishLoading(manager: QuickResourceManager)
}
<file_sep>//
// URL+Extension.swift
// QuickPlayer
//
// Created by Shvier on 12/04/2017.
// Copyright © 2017 Shvier. All rights reserved.
//
import Foundation
let customScheme = "streaming"
let httpScheme = "http"
let httpsScheme = "https"
extension URL {
func customSchemeURL() -> URL {
var components = URLComponents(url: self, resolvingAgainstBaseURL: false)
components?.scheme = customScheme
return (components?.url)!
}
func originalSchemeURL() -> URL {
var components = URLComponents(url: self, resolvingAgainstBaseURL: false)
if QuickPlayerManager.sharedInstance.httpsMode {
components?.scheme = httpsScheme
} else {
components?.scheme = httpScheme
}
return (components?.url)!
}
}
| ae57829b731f9b3cd353150b1994cf8b7f177c1a | [
"Swift"
] | 11 | Swift | ZikeX/QuickPlayer-Swift | 914c667b0b0c7304663b09110a3ae7b6f179b8a1 | c701c95423ee13dbd9f997c3ce8283c39e45a736 |
refs/heads/master | <repo_name>kirillDanshin/avrs-desktop<file_sep>/src/main/window/Window.js
import { BrowserWindow } from 'electron'
class Window {
options = {}
constructor() {
this.protocol = process.env.NODE_ENV === 'development' ? 'http://localhost:3030/dist/' : 'aversis://aversis/'
}
getOptions() {
if (process.env.NODE_ENV === 'development') {
return {
...this.options,
show: false,
width: this.options.width ? this.options.width + 400 : this.options.width,
}
}
return {
...this.options,
show: false,
}
}
open(pathname) {
this.browserWindow = new BrowserWindow(this.getOptions())
this.browserWindow.loadURL(`${this.protocol}${pathname}`)
this.browserWindow.once('closed', this.onClosed)
return new Promise((resolve) => {
this.browserWindow.webContents.once('did-finish-load', () => {
this.browserWindow.show()
this.browserWindow.focus()
if (process.env.NODE_ENV === 'development') {
this.browserWindow.openDevTools()
}
resolve()
})
})
}
hide() {
this.browserWindow.hide()
}
close() {
this.browserWindow.close()
}
send(...args) {
this.browserWindow.webContents.send(...args)
}
isMinimized() {
return this.browserWindow && this.browserWindow.isMinimized()
}
isClosed() {
return !this.browserWindow
}
restore() {
return this.browserWindow.restore()
}
onClosed = () => {
this.browserWindow = null
}
}
export default Window
<file_sep>/src/app/pages/statistics/routes/index.js
import { load } from '../actions/sessions'
import Statistics from '../containers/Statistics'
export default ({ dispatch }) => ({
path: 'statistics',
component: Statistics,
onEnter() {
dispatch(load())
},
})
<file_sep>/src/app/pages/statistics/reducers/sessions/chart.js
import moment from 'moment'
import { createReducer } from '../../../../utils'
import * as actions from '../../constants/sessions'
const initialState = []
const colors = ['#00BB27', '#0288D1']
export default createReducer(initialState, {
[actions.load]: (state, { sessions, from, to, activations }) => {
const colorsByActivation = activations.reduce((result, id, index) => ({
...result,
[id]: colors[index],
}), {})
const getColor = id => colorsByActivation[parseInt(id, 10)] || '#00BB27'
const sessionsByDays = sessions.reduce((result, session) => {
const date = moment(session.startAt).startOf('day').toDate()
if (!result[date]) {
result[date] = [] // eslint-disable-line no-param-reassign
}
result[date].push({
...session,
date: session.startAt,
value: session.time,
color: getColor(session.activation.id),
})
return result
}, {})
const startAt = moment(new Date(from)).subtract(1, 'day')
const period = moment(new Date(to)).diff(startAt, 'days') + 1
return Array.from(Array(period).keys()).reduce((result, day) => {
const date = moment(startAt).add(day, 'day').startOf('day').toDate()
if (!sessionsByDays[date]) {
return [
...result,
{ date, value: 0 },
]
}
return [
...result,
...sessionsByDays[date],
]
}, [])
},
})
<file_sep>/src/app/pages/statistics/components/filters/Expander.js
import React from 'react'
import { StyleSheet } from 'elementum'
import Icon from 'avrs-ui/src/icons/Icon'
import { rotate } from 'avrs-ui/src/icons/utils'
const styles = StyleSheet.create({
self: {
position: 'absolute',
border: '1px solid #0288d1',
borderRadius: '50%',
padding: '6px 8px 4px 8px',
cursor: 'pointer',
top: '15px',
right: '20px',
zIndex: 3,
background: '#ffffff',
'& svg': {
fill: '#0288d1',
},
'&:hover': {
opacity: 0.9,
},
},
})
const ArrowIcon = ({ right, down, left, ...props }) => (
<Icon originalWidth={24} originalHeight={24} {...props}>
<g transform={rotate({ right, down, left }, 24, 24)}>
<path
d='M12 2q0.422 0 0.711 0.289l7 7q0.289 0.289 0.289 0.711
0 0.43-0.285 0.715t-0.715 0.285q-0.422 0-0.711-0.289l-5.289-5.297v15.586q0
0.414-0.293 0.707t-0.707 0.293-0.707-0.293-0.293-0.707v-15.586l-5.289
5.297q-0.289 0.289-0.711 0.289-0.43 0-0.715-0.285t-0.285-0.715q0-0.422
0.289-0.711l7-7q0.289-0.289 0.711-0.289z'
/>
</g>
</Icon>
)
const Expander = ({ inverse, onClick }) => (
<div
className={styles()}
onClick={onClick}
>
<ArrowIcon
height={12}
down={!inverse}
/>
</div>
)
export default Expander
<file_sep>/src/app/routes/main.js
import App from '../containers/App'
import init from '../pages/init/routes'
import beginning from '../pages/beginning/routes'
import dashboard from '../pages/dashboard/routes'
import profile from '../pages/profile/routes'
import statistics from '../pages/statistics/routes'
export default function getRoutes(store) {
return {
path: '/',
indexRoute: init(),
childRoutes: [{
component: App,
childRoutes: [
beginning(store),
dashboard(store),
statistics(store),
profile(store),
],
}],
}
}
<file_sep>/src/app/pages/init/routes/index.js
import Saver from '../components/Saver'
export default function getRoutes() {
return {
component: Saver,
}
}
<file_sep>/src/main/scheduler/Scheduler.js
import { EventEmitter } from 'events'
import moment from 'moment'
import { powerSaveBlocker } from 'electron'
import Session from './Session'
import { formatSchedules, searchMatchedSchedule, searchNextMatchedSchedule, random } from './utils'
class Scheduler extends EventEmitter {
checkTimeout = 1000
onCheck = async () => {
if (this.session) {
if (this.session.endAt <= (new Date()).getTime()) {
this.refresh()
return null
}
const currentTime = Math.floor(((new Date()).getTime() - this.session.startAt) / 1000)
if ((currentTime % 4) === 0) {
const data = {
c: random(4, 10),
m: random(400, 1000),
}
if (this.session.started) {
this.emit('stat', data)
}
}
}
if (this.nextStartAt && this.nextStartAt <= (new Date()).getTime()) {
this.startSession()
}
this.emit('tick')
return null
}
onStart = (data) => {
this.emit('started', data)
}
setSchedules(schedules) {
this.schedules = schedules
}
setToken(token) {
this.token = token
}
setMachineId(machineId) {
this.machineId = machineId
}
searchCurrent() {
const today = moment().format('ddd').toLowerCase()
const now = (new Date()).getTime()
const [matched] = searchMatchedSchedule(formatSchedules(this.schedules), today, now)
return matched
}
searchNext() {
const today = moment().format('ddd').toLowerCase()
const now = (new Date()).getTime()
const [matched] = searchNextMatchedSchedule(formatSchedules(this.schedules), today, now)
return matched
}
async start() {
this.interval = setInterval(this.onCheck, this.checkTimeout)
this.powerSaveBlockerId = powerSaveBlocker.start('prevent-app-suspension')
this.startSession()
}
async refresh() {
this.closeSession()
this.startSession()
}
async stop() {
this.closeSession()
if (this.interval) {
clearInterval(this.interval)
}
if (this.powerSaveBlockerId) {
powerSaveBlocker.stop(this.powerSaveBlockerId)
}
this.emit('stopped')
}
async startSession() {
const current = this.searchCurrent()
this.nextStartAt = null
if (current) {
this.activation = current.id
this.endTime = current.to
this.session = new Session(this.token, this.machineId, current.id, current.from, current.to)
this.session.start()
this.session.on('started', this.onStart)
} else {
const next = this.searchNext()
if (next) {
this.nextStartAt = next.from
this.emit('wait', { activation: next.id, nextStartAt: next.from })
}
}
}
async closeSession() {
if (this.session) {
this.session.removeListener('started', this.onStart)
this.session.close()
this.session = null
}
}
}
export default Scheduler
<file_sep>/src/app/components/header/controls/Control.js
import React from 'react'
import { StyleSheet } from 'elementum'
const styles = StyleSheet.create({
self: {
padding: '9px 12px 8px 12px',
display: 'flex',
cursor: 'pointer',
WebkitAppRegion: 'no-drag',
'&:hover': {
background: '#f2f2f2',
},
},
red: {
'&:hover': {
background: '#ff0000',
'& .control-element': {
fill: '#ffffff',
},
},
},
'align=bottom': {
paddingTop: '12px',
},
})
const Control = ({ children, align, red, onClick }) => (
<div
className={styles({ align, red })}
onClick={onClick}
>
{children}
</div>
)
export default Control
<file_sep>/src/app/components/header/controls/Controls.js
import React from 'react'
import { StyleSheet } from 'elementum'
import Hide from './Hide'
import FullScreen from './FullScreen'
import Close from './Close'
const styles = StyleSheet.create({
self: {
display: 'flex',
flexDirection: 'row',
marginTop: '0px',
},
})
const Controls = ({ onMinimize, onMaximize, onClose }) => (
<div className={styles()}>
<Hide onClick={onMinimize} />
<FullScreen onClick={onMaximize} />
<Close onClick={onClose} />
</div>
)
export default Controls
<file_sep>/src/app/pages/schedule/actions/index.js
import { send } from '../../../actions/remote'
import * as actions from '../constants'
export function changeActive(id) {
return {
type: actions.changeActive,
id,
}
}
export function change(value) {
return {
type: actions.change,
value,
}
}
export function reset() {
return {
type: actions.reset,
}
}
export function save() {
return async (dispatch, getState) => {
const schedules = getState().schedule.schedules.reduce((result, schedule) => ({
...result,
[schedule.id]: {
schedule: schedule.values,
},
}), {})
dispatch(send('schedule:save', schedules))
}
}
export function saved() {
return {
type: actions.saved,
}
}
<file_sep>/src/app/containers/Root.prod.js
import React from 'react'
import { Provider } from 'react-redux'
import storeShape from 'react-redux/lib/utils/storeShape'
import ReduxRouter from './ReduxRouter'
import getMainRoutes from '../routes/main'
import getAuthRoutes from '../routes/auth'
const Root = ({ main, store }) => (
<Provider store={store}>
<ReduxRouter routes={main ? getMainRoutes(store) : getAuthRoutes(store)} />
</Provider>
)
Root.propTypes = {
store: storeShape,
}
export default Root
<file_sep>/src/app/pages/beginning/containers/Beginning.js
import { connect } from 'react-redux'
import { open } from '../actions'
import { changePeriod, changeTime, changeCPU, changeMemory } from '../../ServicePlans/actions'
import Beginning from '../components/Beginning'
export default connect(
state => ({
plan: state.servicePlans.active || {},
}),
dispatch => ({
onOpen: () => dispatch(open()),
onChangePeriod: period => dispatch(changePeriod(period)),
onChangeTime: time => dispatch(changeTime(time)),
onChangeCPU: cpu => dispatch(changeCPU(cpu)),
onChangeMemory: memory => dispatch(changeMemory(memory)),
}),
)(Beginning)
<file_sep>/src/app/pages/statistics/components/sessions/list/Cell.js
import React from 'react'
import { StyleSheet } from 'elementum'
const styles = StyleSheet.create({
self: {
display: 'flex',
padding: '10px',
boxSizing: 'border-box',
fontSize: '12px',
color: '#505458',
fontFamily: '"Ubuntu", sans-serif',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
},
borderTop: {
borderTop: '1px solid #E5E5E5',
},
borderRight: {
borderRight: '1px solid #E5E5E5',
},
borderBottom: {
borderBottom: '1px solid #E5E5E5',
},
borderLeft: {
borderLeft: '1px solid #E5E5E5',
},
'align=center': {
justifyContent: 'center',
},
})
const Cell = ({ children, borderTop, borderRight, borderBottom, borderLeft, basis, align }) => (
<div
style={{ flex: `0 0 ${basis}` }}
className={styles({ borderTop, borderRight, borderBottom, borderLeft, align })}
>
{children}
</div>
)
export default Cell
<file_sep>/src/app/pages/statistics/components/filters/Filters.js
import React from 'react'
import { StyleSheet } from 'elementum'
import { Column, Row, Layout } from 'flex-layouts'
import { GhostButton } from 'avrs-ui/src/button'
import { Divider } from 'avrs-ui/src/divider'
import { Text } from 'avrs-ui/src/text'
import RangeCalendar from 'avrs-ui/src/datepicker/RangeCalendar'
import Container from './Container'
import Activation from './Activation'
import ContentDivider from './Divider'
import Expander from './Expander'
const styles = StyleSheet.create({
self: {
position: 'relative',
width: '100%',
},
})
const Filters = ({ show, activations = [], period = {}, onChangePeriod, onChangeActivation, onToggle, onLoad }) => (
<div className={styles()}>
<Expander
inverse={show}
onClick={onToggle}
/>
<Container show={show}>
<div style={{ background: '#ffffff' }}>
<Row>
<Layout basis='18px' />
<Layout>
<Column>
<Layout basis='35px' />
<Layout>
<Row>
<Layout>
<Text size='small'>
Период
</Text>
</Layout>
<Layout basis='20px' />
<Layout>
<RangeCalendar
locale='ru'
from={period.from}
to={period.to}
numberOfMonths={2}
onChange={onChangePeriod}
/>
</Layout>
</Row>
</Layout>
<Layout basis='40px' />
<Layout>
<Row>
<Layout basis='30px' />
<Layout grow={1}>
<Divider vertical />
</Layout>
</Row>
</Layout>
<Layout basis='35px' />
<Layout grow={1}>
<Row>
<Layout>
<Text size='small'>
Тариф
</Text>
</Layout>
<Layout basis='20px' />
<Layout>
<Row>
{activations.map((activation, index) => (
<Activation
key={index}
{...activation}
onChange={onChangeActivation}
/>
))}
</Row>
</Layout>
</Row>
</Layout>
<Layout basis='35px' />
</Column>
</Layout>
<Layout basis='30px' />
<Layout>
<Divider />
</Layout>
<Layout basis='15px' />
<Layout>
<Column align='center'>
<Layout grow={1} />
<Layout>
<GhostButton
color='blue'
size='small'
onClick={onLoad}
>
Показать
</GhostButton>
</Layout>
<Layout basis='20px' />
</Column>
</Layout>
<Layout basis='15px' />
</Row>
</div>
<ContentDivider show={show} />
</Container>
</div>
)
export default Filters
<file_sep>/src/app/components/header/Header.js
import React from 'react'
import { StyleSheet } from 'elementum'
import { Column, Row, Layout } from 'flex-layouts'
import { Condition } from 'avrs-ui/src/condition'
import { LogoWithText } from 'avrs-ui/src/logo'
import { Divider } from 'avrs-ui/src/divider'
import { NavLink } from 'avrs-ui/src/link'
import { AccountIcon } from 'avrs-ui/src/icons'
import { Controls } from './controls'
const styles = StyleSheet.create({
self: {
width: '100%',
display: 'flex',
'-webkit-user-select': 'none',
'-webkit-app-region': 'drag',
},
})
const Header = ({ isNew, firstName, lastName, onMinimize, onMaximize, onClose }) => (
<div className={styles()}>
<Row>
<Layout basis='56px'>
<Column align='center'>
<Layout basis='30px' />
<Layout>
<LogoWithText height={15} />
</Layout>
<Layout basis='40px' />
<Layout shrink={1} basis='100%'>
<Row>
<Layout basis='3px' />
<Layout>
<Column align='center'>
<Condition match={isNew}>
<Layout>
<NavLink to='/beginning'>
Начало работы
</NavLink>
</Layout>
</Condition>
<Condition match={!isNew}>
<Layout>
<NavLink to='/dashboard'>
Сессия
</NavLink>
</Layout>
</Condition>
<Layout basis='30px' />
<Condition match={!isNew}>
<Layout>
<NavLink to='/statistics'>
Статистика
</NavLink>
</Layout>
</Condition>
<Layout grow={1} />
<Layout align='center'>
<span style={{ position: 'relative', width: 32, height: 26 }}>
<span style={{ position: 'absolute', top: 0 }}>
<AccountIcon height={24} />
</span>
</span>
<NavLink to='/profile'>
{firstName} {lastName}
</NavLink>
</Layout>
</Column>
</Layout>
</Row>
</Layout>
<Layout basis='60px' />
<Layout>
<Controls
onMinimize={onMinimize}
onMaximize={onMaximize}
onClose={onClose}
/>
</Layout>
<Layout basis='10px' />
</Column>
</Layout>
<Layout>
<Divider />
</Layout>
</Row>
</div>
)
export default Header
<file_sep>/src/app/constants/session.js
export const started = '@@avrs-desktop/session/STARTED'
export const stopped = '@@avrs-desktop/session/STOPPED'
export const wait = '@@avrs-desktop/session/WAIT'
<file_sep>/config/webpack/app/build.js
import path from 'path'
import webpack from 'webpack'
import nested from 'jss-nested'
import camelCase from 'jss-camel-case'
import autoprefixer from 'autoprefixer'
import CopyWebpackPlugin from 'copy-webpack-plugin'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
import CssResolvePlugin from 'elementum-tools/lib/webpack/css-resolve-plugin'
export const target = 'electron-renderer'
export const entry = {
auth: [
'babel-polyfill',
'./src/app/auth.js',
],
main: [
'babel-polyfill',
'./src/app/main.js',
],
}
export const output = {
filename: '[name].js',
path: './build/public/',
publicPath: 'aversis://aversis/',
}
export const module = {
rules: [
{
test: /\.js?$/,
exclude: /node_modules\/(?!avrs-ui)/,
loader: 'babel-loader',
options: {
babelrc: false,
presets: [
['es2015', { modules: false }],
'stage-0',
'react',
],
plugins: [
['elementum-tools/lib/babel/plugin', {
alias: {
AvrsDesktop: 'src/app',
AvrsUI: 'node_modules/avrs-ui/src',
},
extract: true,
}],
],
},
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
fallbackLoader: 'style-loader',
loader: [
'css-loader',
'postcss-loader',
],
}),
},
{
test: /\.jss$/,
loader: ExtractTextPlugin.extract({
fallbackLoader: 'style-loader',
loader: [
'css-loader',
'postcss-loader',
'jss-loader',
],
}),
},
{
test: /\.(png|jpg|svg|ttf|eot|woff|woff2)$/,
loader: 'file-loader?name=[path][name].[ext]',
},
],
}
export const resolve = {
plugins: [
new CssResolvePlugin(),
],
}
export const plugins = [
new ExtractTextPlugin('[name].css'),
new HtmlWebpackPlugin({
chunks: ['auth'],
filename: 'auth.html',
template: path.resolve(__dirname, 'index.ejs'),
}),
new HtmlWebpackPlugin({
chunks: ['main'],
filename: 'main.html',
template: path.resolve(__dirname, 'index.ejs'),
}),
new webpack.DefinePlugin({
'process.env.CABINET_URL': JSON.stringify('http://cabinet.stage.aversis.net/'),
'process.env.API_URL': JSON.stringify('http://api.stage.aversis.net/'),
'process.env.NODE_ENV': JSON.stringify('production'),
}),
new webpack.LoaderOptionsPlugin({
options: {
jssLoader: {
plugins: [
nested(),
camelCase(),
],
},
postcss: {
plugins: autoprefixer({
browsers: [
'>2%',
'last 2 versions',
],
}),
},
},
}),
new webpack.optimize.UglifyJsPlugin(),
new CopyWebpackPlugin([{
from: path.join(__dirname, '..', '..', '..', 'resources', 'fonts'),
to: 'fonts',
}]),
]
<file_sep>/src/app/containers/App.js
import React from 'react'
import { connect } from 'react-redux'
import { Row, Layout } from 'flex-layouts'
import { Condition } from 'avrs-ui/src/condition'
import Header from './Header'
import Controls from './Controls'
import Schedule from '../pages/schedule/containers/Schedule'
const App = ({ children, isNew, showSchedule }) => (
<Row fill>
<Layout>
<Header />
</Layout>
<Layout shrink={1} grow={1}>
<div style={{ position: 'relative', width: '100%' }}>
<Row fill>
<Layout grow={1}>
{children}
</Layout>
<Layout>
<Schedule show={showSchedule} />
</Layout>
</Row>
</div>
</Layout>
<Condition match={!isNew}>
<Layout>
<Controls />
</Layout>
</Condition>
</Row>
)
export default connect(
(state, { router }) => ({
isNew: state.user.isNew,
showSchedule: router.getCurrentLocation().query.schedule,
}),
)(App)
<file_sep>/src/main/debug.js
import path from 'path'
import debug from 'debug'
import { app } from 'electron'
import { Logger, transports } from 'winston'
if (process.env.NODE_ENV !== 'development') {
const logger = new (Logger)({
transports: [
new (transports.File)({ filename: path.join(path.dirname(app.getPath('exe')), 'aversis.log') }),
],
})
debug.log = logger.info
}
debug.enable('*')
export const exception = debug('avrs:exception')
export const application = debug('avrs:application')
export const protocol = debug('avrs:protocol')
export const settings = debug('avrs:settings')
export const updateManager = debug('avrs:update-manager')
export const api = debug('avrs:api')
export const squirrel = debug('avrs:squirrel')
export const tray = debug('avrs:tray')
<file_sep>/bin/release/installer.js
/* eslint-disable no-console */
import path from 'path'
import fs from 'fs-extra-promise'
import { createWindowsInstaller } from 'electron-winstaller'
import { metadata, protectedDir, outputDir, loadingGif, iconPath } from './config'
const replaceTemplate = async () => {
const templatePath = path.join(__dirname, 'nuspec', 'template.nuspectemplate')
const replacePath = path.join(__dirname, '..', '..', 'node_modules', 'electron-winstaller', 'template.nuspectemplate')
await fs.copyAsync(templatePath, replacePath)
}
const createInstaler = async (arch) => {
try {
await replaceTemplate()
await createWindowsInstaller({
...metadata,
loadingGif,
iconUrl: iconPath,
usePackageJson: false,
title: metadata.productName || metadata.name,
appDirectory: protectedDir(arch),
outputDirectory: outputDir(arch),
setupExe: `AversisSetup-${metadata.version}.exe`,
exe: 'Aversis.exe',
noMsi: true,
})
console.log(`Release created in ${outputDir(arch)}`)
} catch (error) {
console.error(error)
}
}
createInstaler('x64')
<file_sep>/src/app/pages/auth/actions/login.js
import gql from 'graphql-tag'
import { shell } from 'electron'
import { send } from '../../../actions/remote'
import * as actions from '../constants/login'
export function change(field, value) {
return {
type: actions.change,
field,
value,
}
}
export function login() {
return async (dispatch, getState, client) => {
const { email, password } = getState().auth.login
const { data } = await client.mutate({
mutation: gql`
mutation loginUser($email: String!, $password: String!) {
loginUser(email: $email, password: $password) {
token { id, email, token }
errors {
key
message
}
}
}
`,
variables: {
email,
password,
},
})
if (data.loginUser.errors.length > 0) {
dispatch({
type: actions.setErrors,
errors: data.loginUser.errors,
})
} else {
dispatch(send('auth:login', data.loginUser.token))
}
}
}
export function openRegistration() {
return async () => {
shell.openExternal(`${process.env.CABINET_URL}#/auth/registration`)
}
}
export function openResetPassword() {
return async () => {
shell.openExternal(`${process.env.CABINET_URL}#/auth/reset_password`)
}
}
<file_sep>/src/app/pages/dashboard/routes/index.js
import Dashboard from '../components/Dashboard'
export default function getRoutes() {
return {
path: 'dashboard',
component: Dashboard,
}
}
<file_sep>/config/webpack/app/dev.js
import path from 'path'
import webpack from 'webpack'
import nested from 'jss-nested'
import camelCase from 'jss-camel-case'
import autoprefixer from 'autoprefixer'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import CssResolvePlugin from 'elementum-tools/lib/webpack/css-resolve-plugin'
export const target = 'electron-renderer'
export const entry = {
auth: [
'babel-polyfill',
'webpack-hot-middleware/client?path=http://localhost:3030/__webpack_hmr',
'react-hot-loader/patch',
'./src/app/auth.js',
],
main: [
'babel-polyfill',
'webpack-hot-middleware/client?path=http://localhost:3030/__webpack_hmr',
'react-hot-loader/patch',
'./src/app/main.js',
],
}
export const output = {
filename: '[name].js',
publicPath: 'http://localhost:3030/dist/',
}
export const module = {
rules: [
{
test: /\.js?$/,
exclude: /node_modules\/(?!avrs-ui)/,
use: [
{
loader: 'react-hot-loader/webpack',
},
{
loader: 'babel-loader',
query: {
babelrc: false,
presets: [
['es2015', { modules: false }],
'stage-0',
'react',
],
plugins: [
['elementum-tools/lib/babel/plugin', {
alias: {
AvrsDesktop: 'src/app',
AvrsUI: 'node_modules/avrs-ui/src',
},
extract: true,
}],
],
},
},
],
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
'postcss-loader',
],
},
{
test: /\.jss$/,
use: [
'style-loader',
'css-loader',
'postcss-loader',
'jss-loader',
],
},
{
test: /\.(png|jpg|svg|ttf|eot|woff|woff2)$/,
loader: 'file-loader?name=[path][name].[ext]',
},
],
}
export const resolve = {
plugins: [
new CssResolvePlugin(),
],
}
export const plugins = [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
chunks: ['auth'],
filename: 'auth.html',
template: path.resolve(__dirname, 'index.ejs'),
}),
new HtmlWebpackPlugin({
chunks: ['main'],
filename: 'main.html',
template: path.resolve(__dirname, 'index.ejs'),
}),
new webpack.DefinePlugin({
'process.env.CABINET_URL': JSON.stringify('http://cabinet.stage.aversis.net/'),
'process.env.API_URL': JSON.stringify(process.env.API_URL || 'http://api.stage.aversis.net/'),
}),
new webpack.LoaderOptionsPlugin({
options: {
jssLoader: {
plugins: [
nested(),
camelCase(),
],
},
postcss: {
plugins: autoprefixer({
browsers: [
'>2%',
'last 2 versions',
],
}),
},
},
}),
]
<file_sep>/src/app/pages/statistics/components/sessions/list/Container.js
import React from 'react'
import { StyleSheet } from 'elementum'
const styles = StyleSheet.create({
self: {},
container: {
width: '100%',
minHeight: '100%',
maxHeight: '100%',
overflowY: 'auto',
position: 'relative',
},
wrapper: {
position: 'absolute',
top: 0,
right: 0,
bottom: 0,
left: 0,
overflowY: 'auto',
overflowX: 'hidden',
borderTop: '1px solid #e5e5e5',
borderBottom: '1px solid #e5e5e5',
boxSizing: 'border-box',
},
})
const Container = ({ children }) => (
<div className={styles({ container: true })}>
<div className={styles({ wrapper: true })}>
{children}
</div>
</div>
)
export default Container
<file_sep>/src/app/reducers/main.js
import { combineReducers } from 'redux'
import { routerStateReducer as router } from 'redux-router'
import client from '../api/client'
import user from './user'
import session from './session'
import security from './security'
import auth from '../pages/auth/reducers'
import servicePlans from '../pages/ServicePlans/reducers'
import statistics from '../pages/statistics/reducers'
import schedule from '../pages/schedule/reducers'
export default combineReducers({
apollo: client.reducer(),
router,
user,
session,
security,
auth,
servicePlans,
statistics,
schedule,
})
<file_sep>/src/app/pages/ServicePlans/constants/index.js
export const sync = '@@avrs-desktop/servicePlans/SYNC'
export const select = '@@avrs-desktop/servicePlans/SELECT'
export const changePlan = '@@avrs-desktop/servicePlans/CHANGE_PLAN'
export const changePeriod = '@@avrs-desktop/servicePlans/CHANGE_PERIOD'
export const changeTime = '@@avrs-desktop/servicePlans/CHANGE_TIME'
export const changeCPU = '@@avrs-desktop/servicePlans/CHANGE_CPU'
export const changeMemory = '@@avrs-desktop/servicePlans/CHANGE_MEMORY'
<file_sep>/src/app/pages/ServicePlans/actions/index.js
import * as actions from '../constants'
export function select(plan, period) {
return {
type: actions.select,
plan,
period,
}
}
export function changePeriod(period) {
return {
type: actions.changePeriod,
period,
}
}
export function changeTime(time) {
return {
type: actions.changeTime,
time,
}
}
export function changeCPU(cpu) {
return {
type: actions.changeCPU,
cpu,
}
}
export function changeMemory(memory) {
return {
type: actions.changeMemory,
memory,
}
}
<file_sep>/src/app/actions/window.js
import { remote } from 'electron'
export function minimize() {
return async () => remote.BrowserWindow.getFocusedWindow().minimize()
}
export function maximize() {
return async () => {
const win = remote.BrowserWindow.getFocusedWindow()
if (win.isMaximized()) {
win.unmaximize()
} else {
win.maximize()
}
}
}
export function close() {
return async () => remote.BrowserWindow.getFocusedWindow().close()
}
<file_sep>/src/app/pages/statistics/actions/sessions.js
import gql from 'graphql-tag'
import * as actions from '../constants/sessions'
export function load() {
return async (dispatch, getState, client) => {
const filters = getState().statistics.filters
const { from, to } = filters.period
const activations = filters.activations
.filter(({ selected }) => selected)
.map(({ id }) => id)
const { data } = await client.query({
forceFetch: true,
query: gql`
query sessions ($from: String, $to: String, $activations: [ID!]) {
sessions (from: $from, to: $to, activations: $activations) {
id
time
startAt
activation {
id
servicePlan {
type
}
}
}
}
`,
variables: {
from,
to,
activations,
},
})
dispatch({
type: actions.load,
sessions: data.sessions,
activations,
from,
to,
})
}
}
<file_sep>/src/app/pages/statistics/constants/filters.js
export const sync = '@@avrs-desktop/statistics/filters/SYNC'
export const toggle = '@@avrs-desktop/statistics/filters/TOGGLE'
export const changePeriod = '@@avrs-desktop/statistics/filters/CHANGE_PERIOD'
export const changeActivation = '@@avrs-desktop/statistics/filters/CHANGE_ACTIVATION'
<file_sep>/src/app/api/client.js
/* eslint-disable no-param-reassign */
import ApolloClient, { createNetworkInterface } from 'apollo-client'
import { ipcRenderer } from 'electron'
const networkInterface = createNetworkInterface({ uri: process.env.API_URL })
const client = new ApolloClient({
networkInterface,
})
networkInterface.use([{
applyMiddleware(req, next) {
const security = client.store.getState().security
if (!req.options.headers) {
req.options.headers = {}
}
if (security && security.token) {
req.options.headers.authorization = security.token
}
next()
},
}])
networkInterface.useAfter([{
applyAfterware({ response }, next) {
if (response.status === 401) {
ipcRenderer.send('auth:logout')
}
next()
},
}])
export default client
<file_sep>/src/app/reducers/user.js
import { createReducer } from '../utils'
import * as actions from '../constants/user'
const initialState = {}
export default createReducer(initialState, {
[actions.sync]: (state, { user }) => ({
...state,
...user,
isNew: user.status === 'NEW',
}),
[actions.update]: (state, { user }) => ({ ...state, ...user }),
[actions.setServicePlan]: (state, { plan }) => ({ ...state, plan }),
})
<file_sep>/src/app/containers/Controls.js
import { connect } from 'react-redux'
import { withRouter } from 'react-router'
import { start, stop } from '../actions/session'
import Controls from '../components/controls/Controls'
export default withRouter(connect(
state => ({
started: state.session.started,
startAt: state.session.startAt,
endAt: state.session.endAt,
nextStartAt: state.session.nextStartAt,
activation: state.session.activation,
}),
(dispatch, { router }) => ({
onToggleShedule: () => {
const location = router.getCurrentLocation()
const { schedule, ...query } = location.query
if (schedule) {
router.replace({ ...location, query })
} else {
router.replace({ ...location, query: { ...query, schedule: true } })
}
},
onStart: () => dispatch(start()),
onStop: () => dispatch(stop()),
}),
)(Controls))
<file_sep>/config/webpack/main/build.js
import path from 'path'
import webpack from 'webpack'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import { version } from '../../../package.json'
export const target = 'electron-main'
export const entry = [
'babel-polyfill',
'./src/main/index.js',
]
export const output = {
filename: 'index.js',
path: './build/',
}
export const module = {
rules: [
{
test: /\.js?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
babelrc: false,
presets: [
'es2015',
'stage-0',
],
},
},
{
test: /\.json?$/,
loader: 'json-loader',
},
{
test: /\.(png|jpg|svg|ttf|eot|woff|woff2)$/,
loader: 'file-loader?name=[name].[ext]',
},
],
}
export const plugins = [
new webpack.DefinePlugin({
'process.env.API_URL': JSON.stringify('http://api.stage.aversis.net/'),
'process.env.NODE_ENV': JSON.stringify('production'),
}),
new HtmlWebpackPlugin({
inject: false,
filename: 'package.json',
template: path.resolve(__dirname, 'package.ejs'),
version,
}),
new webpack.optimize.UglifyJsPlugin(),
]
<file_sep>/bin/release/config.js
/* eslint-disable max-len */
/* eslint-disable import/no-unresolved */
import path from 'path'
import appPackage from '../../build/package.json'
const version = appPackage.version
export const metadata = appPackage
export const iconPath = path.join(__dirname, '..', '..', 'resources', 'logo.ico')
export const loadingGif = path.join(__dirname, '..', '..', 'resources', 'install.gif')
export const releasesDir = path.join(__dirname, '..', '..', 'releases')
export const distDir = path.join(__dirname, '..', '..', 'build')
export const packagedBaseDir = path.join(releasesDir, version, 'packaged')
export function packagedDir(arch) {
return path.join(packagedBaseDir, `win32-${arch}`)
}
export const protectedBaseDir = path.join(releasesDir, version, 'protected')
export function protectedDir(arch) {
return path.join(protectedBaseDir, `win32-${arch}`)
}
export const outputBaseDir = path.join(releasesDir, 'output')
export function outputDir(arch) {
return path.join(outputBaseDir, `win32-${arch}`)
}
export const virtualBox = {
secure1: '<KEY>',
secure2: '<KEY>',
privateKey: '<KEY>',
publicKey: '<KEY>',
}
export const enigmaExe = {
x64: 'C:\\Program Files (x86)\\The Enigma Protector\\Enigma64g.exe',
}
<file_sep>/src/app/actions/init.js
import { sync as syncUser } from '../constants/user'
import { sync as syncToken } from '../constants/security'
import { sync as syncServicePlans } from '../pages/ServicePlans/constants'
import { sync as syncSchedule } from '../pages/schedule/constants'
import { sync as syncFilters } from '../pages/statistics/constants/filters'
export function init(data) {
return async (dispatch, getState) => {
const { user, token, servicePlans, schedules } = JSON.parse(data)
dispatch({
type: syncToken,
token,
})
dispatch({
type: syncUser,
user,
})
dispatch({
type: syncServicePlans,
servicePlans,
})
dispatch({
type: syncSchedule,
schedules,
})
dispatch({
type: syncFilters,
activations: user.activations,
})
setTimeout(() => {
if (getState().user.isNew) {
window.location.hash = '/beginning'
} else {
window.location.hash = '/dashboard'
}
}, 1500)
}
}
<file_sep>/src/app/constants/user.js
export const sync = '@@avrs-desktop/user/SYNC'
export const update = '@@avrs-desktop/user/UPDATE'
export const setServicePlan = '@@avrs-desktop/user/SET_SERVICE_PLAN'
<file_sep>/src/main/startCrashReporter.js
export default (extra) => {
const { crashReporter } = require('electron') // eslint-disable-line global-require
crashReporter.start({
productName: 'Aversis',
companyName: 'Aversis',
submitURL: 'https://crashreporter.aversis.net',
autoSubmit: false,
extra,
})
}
<file_sep>/src/app/components/controls/Controls.js
import React from 'react'
import { Column, Row, Layout } from 'flex-layouts'
import { Condition } from 'avrs-ui/src/condition'
import { GhostButton } from 'avrs-ui/src/button'
import { Text, Space } from 'avrs-ui/src/text'
import Icon from 'avrs-ui/src/icons/Icon'
import SessionStopped from './SessionStopped'
import SessionTimer from './SessionTimer'
import SessionWait from './SessionWait'
import Activation from './Activation'
import Divider from './Divider'
const ScheduleIcon = props => (
<Icon originalWidth={24} originalHeight={24} {...props}>
<g>
<path
d='M12.516 6.984v5.25l4.5 2.672-0.75 1.266-5.25-3.188v-6h1.5zM12
20.016c4.406 0 8.016-3.609 8.016-8.016s-3.609-8.016-8.016-8.016-8.016
3.609-8.016 8.016 3.609 8.016 8.016 8.016zM12 2.016c5.531 0 9.984 4.453
9.984 9.984s-4.453 9.984-9.984 9.984-9.984-4.453-9.984-9.984 4.453-9.984 9.984-9.984z'
/>
</g>
</Icon>
)
const Controls = ({ started, startAt, endAt, nextStartAt, activation, onToggleShedule, onStart, onStop }) => (
<Row>
<Layout>
<Divider />
</Layout>
<Layout basis='15px' />
<Layout basis='42px'>
<Column align='center'>
<Layout basis='45px' />
<Layout basis='235px'>
<Condition match={started && startAt}>
<SessionTimer
startAt={startAt}
endAt={endAt}
/>
</Condition>
<Condition match={started && nextStartAt}>
<SessionWait nextStartAt={nextStartAt} />
</Condition>
<Condition match={!started}>
<SessionStopped />
</Condition>
</Layout>
<Layout>
<div
style={{ cursor: 'pointer', marginTop: 6 }}
onClick={onToggleShedule}
>
<ScheduleIcon
height={18}
fill='#0288d1'
/>
<Space />
<span style={{ position: 'relative', top: -4 }}>
<Text size='xsmall' color='blue400'>
Расписание
</Text>
</span>
</div>
</Layout>
<Layout grow={1} />
<Layout>
<Condition match={activation}>
<Activation {...activation} />
</Condition>
</Layout>
<Layout basis='40px' />
<Layout>
<Condition match={started}>
<GhostButton color='blue' size='small' onClick={onStop}>
Остановить
</GhostButton>
</Condition>
<Condition match={!started}>
<GhostButton color='blue' size='small' onClick={onStart}>
Запустить
</GhostButton>
</Condition>
</Layout>
<Layout basis='45px' />
</Column>
</Layout>
<Layout basis='15px' />
</Row>
)
export default Controls
<file_sep>/src/app/actions/remote.js
import { ipcRenderer } from 'electron'
export function send(event, ...args) {
return async () => ipcRenderer.send(event, ...args)
}
<file_sep>/src/app/pages/auth/reducers/login.js
import { createReducer, formatErrors } from '../../../utils'
import * as actions from '../constants/login'
const initialState = {
email: '',
password: '',
errors: {},
}
export default createReducer(initialState, {
[actions.change]: (state, { field, value }) => ({ ...state, [field]: value }),
[actions.setErrors]: (state, { errors }) => ({ ...state, errors: formatErrors(errors) }),
})
<file_sep>/src/main/window/MainWindow.js
import Window from './Window'
class MainWindow extends Window {
options = {
width: 900,
height: 600,
minWidth: 900,
minHeight: 550,
frame: false,
}
open() {
return super.open('main.html')
}
}
export default MainWindow
<file_sep>/src/app/store/auth/configureStore.prod.js
import { createStore, compose, applyMiddleware } from 'redux'
import { reduxReactRouter } from 'redux-router'
import { createHashHistory as createHistory } from 'history'
import api from '../middleware/api'
import rootReducer from '../../reducers/auth'
import client from '../../api/client'
const enhancer = compose(
reduxReactRouter({ createHistory }),
applyMiddleware(api(client)),
)
export default function configureStore(initialState) {
const store = createStore(rootReducer, initialState, enhancer)
return store
}
<file_sep>/src/app/pages/schedule/components/activation/Activation.js
import React from 'react'
import { StyleSheet } from 'elementum'
import Color from './Color'
const names = {
basis: 'Базис',
standart: 'Стандарт',
premium: 'Премиум',
business: 'Бизнес',
}
const styles = StyleSheet.create({
self: {
fontSize: '14px',
fontWeight: 300,
fontFamily: '"Ubuntu", sans-serif',
lineHeight: '12px',
cursor: 'pointer',
padding: '7px 20px',
background: 'transparent',
textDecoration: 'none',
outline: 0,
color: 'black',
opacity: 0.7,
'&:hover': {
opacity: 0.9,
'& span': {
opacity: 0.9,
},
},
'& span': {
fontSize: '12px',
},
},
active: {
opacity: 1,
},
})
const Activation = ({ id, type, active, color, onClick }) => (
<div
className={styles({ active })}
onClick={onClick}
>
<Color
color={color}
active={active}
/>
{names[type]} <span>(#{id})</span>
</div>
)
export default Activation
<file_sep>/src/main/main.js
import { app } from 'electron'
import { exception as debug } from './debug'
import startCrashReporter from './startCrashReporter'
import { handleStartupEventWithSquirrel } from './squirrelUpdate'
app.commandLine.appendSwitch('ignore-certificate-errors', 'true')
export default function run() {
if (handleStartupEventWithSquirrel()) {
return
}
process.on('uncaughtException', ({ message, stack } = {}) => {
if (message !== null) {
debug(message)
}
if (stack !== null) {
debug(stack)
}
})
app.on('will-finish-launching', startCrashReporter)
app.on('ready', () => {
const AversisApplication = require('./Application').default // eslint-disable-line global-require
const aversis = new AversisApplication()
aversis.start()
})
}
<file_sep>/src/app/auth.js
import React from 'react'
import { render } from 'react-dom'
import 'flex-layouts/lib/flex-layouts.css'
import 'reset.css'
import configureStore from './store/configureAuthStore'
import Root from './containers/Root'
import './index.css'
const store = configureStore(JSON.parse(process.env.INITIAL_STATE || '{}'))
render(
<Root store={store} />,
document.getElementById('container'),
)
if (module.hot) {
module.hot.accept('./containers/Root', () => {
render(
<Root store={store} />,
document.getElementById('container'),
)
})
}
<file_sep>/src/app/pages/statistics/containers/Filters.js
import { connect } from 'react-redux'
import { toggle, changePeriod, changeActivation, load } from '../actions/filters'
import Filters from '../components/filters/Filters'
export default connect(
state => ({
show: state.statistics.filters.show,
period: state.statistics.filters.period,
activations: state.statistics.filters.activations,
}),
dispatch => ({
onLoad: () => dispatch(load()),
onToggle: () => dispatch(toggle()),
onChangePeriod: value => dispatch(changePeriod(value)),
onChangeActivation: (id, value) => dispatch(changeActivation(id, value)),
}),
)(Filters)
<file_sep>/src/app/pages/profile/components/Profile.js
import React from 'react'
import { Column, Row, Layout } from 'flex-layouts'
import { Text, Space } from 'avrs-ui/src/text'
import { LogOutIcon } from 'avrs-ui/src/icons'
import { Link } from 'avrs-ui/src/link'
const Profile = ({ firstName, lastName, onLogout }) => (
<Column>
<Layout basis='45px' />
<Layout grow={1}>
<Row>
<Layout basis='30px' />
<Layout>
<Column align='center'>
<Layout>
<Text size='xlarge' weight='light'>
{firstName}
<Space />
{lastName}
</Text>
</Layout>
<Layout grow={1} />
<Layout align='center'>
<LogOutIcon fill='#0288d1' />
<Space />
<Link onClick={onLogout}>
<Text color='blue400' weight='light' lineHeight='large'>
Выйти
</Text>
</Link>
</Layout>
<Layout basis='10px' />
</Column>
</Layout>
<Layout basis='20px' />
</Row>
</Layout>
<Layout basis='45px' />
</Column>
)
export default Profile
<file_sep>/src/app/pages/profile/containers/Profile.js
import { connect } from 'react-redux'
import { send } from '../../../actions/remote'
import Profile from '../components/Profile'
export default connect(
state => ({
firstName: state.user.firstName,
lastName: state.user.lastName,
}),
dispatch => ({
onLogout: () => dispatch(send('auth:logout')),
}),
)(Profile)
<file_sep>/src/app/reducers/session.js
import { createReducer } from '../utils'
import * as actions from '../constants/session'
const initialState = {
started: false,
activation: null,
startAt: null,
endAt: null,
nextStartAt: null,
}
export default createReducer(initialState, {
[actions.started]: (state, { data }) => ({
...state,
started: true,
...data,
nextStartAt: null,
}),
[actions.stopped]: () => initialState,
[actions.wait]: (state, { data }) => ({
...state,
started: true,
...data,
startAt: null,
endAt: null,
}),
})
<file_sep>/src/app/pages/init/components/Saver.js
import React from 'react'
import { Column, Row, Layout } from 'flex-layouts'
import { LogoWithText } from 'avrs-ui/src/logo'
const Icon = () => (
<svg viewBox='0 14 32 18' width='192' height='24' fill='#0288d1' preserveAspectRatio='none'>
<path
opacity='0.8'
d='M2 14 V18 H6 V14z'
transform='translate(0 0)'
>
<animateTransform
dur='2s'
begin='0'
type='translate'
calcMode='spline'
values='0 0; 24 0; 0 0'
repeatCount='indefinite'
attributeName='transform'
keySplines='0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8'
/>
</path>
<path
opacity='0.5'
d='M0 14 V18 H8 V14z'
transform='translate(0 0)'
>
<animateTransform
dur='2s'
begin='0.1s'
type='translate'
calcMode='spline'
values='0 0; 24 0; 0 0'
repeatCount='indefinite'
attributeName='transform'
keySplines='0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8'
/>
</path>
<path
opacity='0.25'
d='M0 14 V18 H8 V14z'
transform='translate(0 0)'
>
<animateTransform
dur='2s'
begin='0.2s'
type='translate'
calcMode='spline'
values='0 0; 24 0; 0 0'
repeatCount='indefinite'
attributeName='transform'
keySplines='0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8'
/>
</path>
</svg>
)
const Saver = () => (
<Column fill>
<Layout grow={1} />
<Layout>
<Row>
<Layout grow={1} />
<Layout basis='15px' />
<Layout>
<LogoWithText height={45} />
</Layout>
<Layout basis='25px' />
<Layout justify='center'>
<Icon />
</Layout>
<Layout grow={1} />
</Row>
</Layout>
<Layout grow={1} />
</Column>
)
export default Saver
<file_sep>/docker-compose.yml
version: "2"
services:
ide:
image: monstrs/cloud9
volumes:
- ./:/workspace
ports:
- "8516:80"
install:
image: node
working_dir: /workspace
volumes:
- ./:/workspace
- ./.netrc:/root/.netrc
entrypoint: npm install
build:
image: node
working_dir: /workspace
volumes:
- ./:/workspace
entrypoint: npm run build
<file_sep>/src/app/containers/Header.js
import { connect } from 'react-redux'
import { minimize, maximize, close } from '../actions/window'
import Header from '../components/header/Header'
export default connect(
state => ({
isNew: state.user.isNew,
firstName: state.user.firstName,
lastName: state.user.lastName,
}),
dispatch => ({
onMinimize: () => dispatch(minimize()),
onMaximize: () => dispatch(maximize()),
onClose: () => dispatch(close()),
}),
)(Header)
<file_sep>/src/app/components/header/controls/Hide.js
import React from 'react'
import Icon from 'avrs-ui/src/icons/Icon'
import Control from './Control'
const Hide = ({ onClick }) => (
<Control
align='bottom'
onClick={onClick}
>
<Icon originalWidth={16} originalHeight={2}>
<g stroke='none' strokeWidth='1' fill='none' fillRule='evenodd'>
<g transform='translate(-1003.000000, -296.000000)' fill='#9B9B9B'>
<g transform='translate(115.000000, 265.000000)'>
<g transform='translate(310.000000, 9.000000)'>
<g transform='translate(578.000000, 10.000000)'>
<rect id='Hide' x='0' y='12' width='16' height='2' />
</g>
</g>
</g>
</g>
</g>
</Icon>
</Control>
)
export default Hide
<file_sep>/src/app/pages/auth/components/Login.js
import React, { PropTypes } from 'react'
import { Column, Row, Layout } from 'flex-layouts'
import { Text, Space } from 'avrs-ui/src/text'
import { Input } from 'avrs-ui/src/input'
import { Link } from 'avrs-ui/src/link'
import { Button } from 'avrs-ui/src/button'
import Container from './Container'
import Info from './Info'
const Login = ({
email, password, errors, onChangeEmail, onChangePassword,
onLogin, onOpenRegistration, onOpenResetPassword,
}) => (
<Container>
<Row>
<Layout>
<Column>
<Layout basis='35px' />
<Layout shrink={1} basis='100%'>
<Row>
<Layout basis='30px' />
<Layout justify='center'>
<Text size='large'>
Вход
</Text>
</Layout>
<Layout basis='4px' />
<Layout basis='25px' />
<Layout>
<Input
value={email}
placeholder='Email адрес'
onChange={onChangeEmail}
/>
</Layout>
<Layout basis='15px' />
<Layout>
<Input
type='password'
value={password}
placeholder='Пароль'
onChange={onChangePassword}
/>
</Layout>
<Layout basis='8px' />
<Layout justify='center'>
<Text color='red400' size='xsmall'>
{errors.email || <Space />}
</Text>
</Layout>
<Layout basis='10px' />
<Layout>
<Column>
<Layout align='center'>
<Link onClick={onOpenResetPassword}>
<Text size='xsmall' color='blue400'>
Забыли пароль?
</Text>
</Link>
</Layout>
<Layout grow={1} />
<Layout>
<Button onClick={onLogin}>
Войти
</Button>
</Layout>
</Column>
</Layout>
<Layout basis='30px' />
</Row>
</Layout>
<Layout basis='35px' />
</Column>
</Layout>
<Layout grow={1} />
<Layout>
<Info>
<Text size='xsmall' lineHeight='extended'>
Впервые на Aversis?
</Text>
<Space />
<Link onClick={onOpenRegistration}>
<Text color='blue400' size='xsmall' lineHeight='extended'>
Стать участником
</Text>
</Link>
</Info>
</Layout>
</Row>
</Container>
)
Login.propTypes = {
email: PropTypes.string,
password: PropTypes.string,
onChangeEmail: PropTypes.func,
onChangePassword: PropTypes.func,
onLogin: PropTypes.func,
}
export default Login
<file_sep>/bin/release/package.js
/* eslint-disable no-console */
import fs from 'fs-extra-promise'
import packager from 'electron-packager'
import { metadata, distDir, packagedBaseDir, packagedDir, iconPath } from './config'
const defaults = {
dir: distDir,
out: packagedBaseDir,
platform: process.platform,
asar: true,
prune: true,
overwrite: true,
icon: iconPath,
name: 'Aversis',
win32metadata: {
CompanyName: 'Aversis',
FileDescription: 'Aversis',
ProductName: 'Aversis',
},
'version-string': {
CompanyName: 'Aversis',
FileDescription: 'Aversis',
ProductName: 'Aversis',
},
'app-bundle-id': 'net.aversis',
'app-copyright': `Copyright © ${(new Date()).getFullYear()} Aversis. All rights reserved.`,
'app-version': metadata.version,
'build-version': metadata.version,
}
const run = arch =>
new Promise((resolve, reject) => {
packager({ ...defaults, arch }, (error, result) => {
if (error) {
reject(error)
} else {
resolve(result)
}
})
})
const pack = async (arch) => {
try {
const [target] = await run(arch)
await fs.rename(target, packagedDir(arch))
} catch (error) {
console.error(error)
}
}
pack('x64')
<file_sep>/src/app/utils/index.js
import { lensPath, set } from 'ramda'
export function formatErrors(errors = []) {
return errors.reduce((result, error) => set(lensPath(error.key), error.message, result), {})
}
export function createReducer(initialState, reducers = {}, nested) {
return (state = initialState, { type, ...payload }) => {
const handler = reducers[type]
const newState = handler ? handler(state, payload) : state
if (nested) {
const nestedState = Object.keys(nested).reduce((result, key) => ({
...result,
[key]: nested[key](newState[key], { type, ...payload }),
}), {})
return { ...newState, ...nestedState }
}
return newState
}
}
<file_sep>/src/app/pages/statistics/components/filters/Activation.js
import React from 'react'
import moment from 'moment'
import { StyleSheet } from 'elementum'
import { Checkbox } from 'avrs-ui/src/checkbox'
const names = {
basis: 'Базис',
standart: 'Стандарт',
premium: 'Премиум',
business: 'Бизнес',
}
const styles = StyleSheet.create({
self: {
fontSize: '14px',
fontWeight: 300,
fontFamily: '"Ubuntu", sans-serif',
lineHeight: '12px',
cursor: 'pointer',
padding: '0px 0px 12px 0px',
background: 'transparent',
textDecoration: 'none',
outline: 0,
color: 'black',
'& span': {
fontSize: '12px',
},
'& div': {
marginRight: '8px',
},
},
})
const formatCreatedAt = createdAt => moment(new Date(createdAt)).format('LL')
const Activation = ({ selected, id, createdAt, servicePlan, onChange }) => (
<div
className={styles()}
onClick={() => onChange(id, !selected)}
>
<Checkbox
type='desktop'
value={selected}
onChange={f => f}
/>
{names[servicePlan.type]} #{id}, {formatCreatedAt(createdAt)}
</div>
)
export default Activation
<file_sep>/bin/release/protect.js
/* eslint-disable no-use-before-define */
/* eslint-disable no-console */
import path from 'path'
import { spawn } from 'child_process'
import fs from 'fs-extra-promise'
import enigma from './enigma'
import { metadata, packagedDir, protectedDir, virtualBox, enigmaExe } from './config'
const processFile = async (target, file) => {
const stat = await fs.statAsync(path.join(target, file))
if (stat.isDirectory()) {
const files = await getFiles(path.join(target, file))
return { name: file, target, files }
}
return { name: file, target }
}
const getFiles = async (target) => {
const files = await fs.readdirAsync(target)
const filtered = files.filter(file => !['Aversis.exe'].includes(file))
return await Promise.all(filtered.map(file => processFile(target, file)))
}
const createConfig = async (arch) => {
const files = await getFiles(packagedDir(arch))
const configPath = path.join(protectedDir(arch), '..', 'aversis.enigma64')
const template = enigma({
...metadata,
inputFileName: path.join(packagedDir(arch), 'Aversis.exe'),
outputFileName: path.join(protectedDir(arch), 'Aversis.exe'),
virtualBox: {
...virtualBox,
files,
},
})
await fs.writeFileAsync(configPath, template)
return configPath
}
const run = async (arch, configPath) =>
new Promise((resolve, reject) => {
const proc = spawn(enigmaExe[arch], [configPath], { stdio: 'inherit' })
proc.on('close', (code) => {
if (code === 0) {
resolve()
} else {
reject(new Error(`Failed with exit code: ${code}`))
}
})
})
const protect = async (arch) => {
try {
await fs.mkdirsAsync(protectedDir(arch))
const configPath = await createConfig(arch)
await run(arch, configPath)
} catch (error) {
console.error(error)
}
}
protect('x64')
<file_sep>/src/main/squirrelUpdate.js
import { app } from 'electron'
import { spawn } from 'child_process'
import path from 'path'
import { squirrel as debug } from './debug'
const spawnUpdate = (args, callback) => {
const updateExe = path.resolve(path.dirname(process.execPath), '..', 'Update.exe')
debug('Spawning `%s` with args `%s`', updateExe, args)
spawn(updateExe, args, { detached: true }).on('close', callback)
}
const onCompleteSpawn = (error, stdout) => {
if (error) {
debug(error)
}
debug(stdout)
app.quit()
}
export function handleStartupEventWithSquirrel() {
if (process.platform === 'win32') {
const cmd = process.argv[1]
debug('processing squirrel command `%s`', cmd)
const target = path.basename(process.execPath)
if (cmd === '--squirrel-install' || cmd === '--squirrel-updated') {
spawnUpdate([`--createShortcut=${target}`], onCompleteSpawn)
return true
}
if (cmd === '--squirrel-uninstall') {
spawnUpdate([`--removeShortcut=${target}`], onCompleteSpawn)
return true
}
if (cmd === '--squirrel-obsolete') {
app.quit()
return true
}
}
return false
}
<file_sep>/src/app/pages/schedule/constants/index.js
export const sync = '@@avrs-ui/schedule/SYNC'
export const change = '@@avrs-ui/schedule/CHANGE'
export const reset = '@@avrs-ui/schedule/RESET'
export const changeActive = '@@avrs-ui/schedule/CHANGE_ACTIVE'
export const saved = '@@avrs-ui/schedule/SAVED'
<file_sep>/src/app/pages/statistics/components/filters/Divider.js
import React from 'react'
import { StyleSheet } from 'elementum'
const styles = StyleSheet.create({
self: {
width: '110%',
height: '20px',
boxShadow: 'inset 0 1px 2px 0px rgba(0, 0, 0, 0.15)',
borderTop: '1px solid #E1E4E6',
transition: 'opacity 2s',
opacity: 0,
},
show: {
opacity: 1,
},
})
const Divider = ({ show }) => (
<div className={styles({ show })} />
)
export default Divider
<file_sep>/src/app/pages/schedule/components/activation/Color.js
import React from 'react'
import { StyleSheet } from 'elementum'
const styles = StyleSheet.create({
self: {
display: 'inline-block',
width: '9px',
height: '9px',
borderRadius: '50%',
marginRight: '6px',
opacity: 0.5,
},
active: {
opacity: 1,
},
})
const Color = ({ color, active }) => (
<span
style={{ background: color }}
className={styles({ active })}
/>
)
export default Color
<file_sep>/src/app/pages/dashboard/components/MemoryChart.js
import React, { Component } from 'react'
import { LineLiveChart } from 'avrs-ui/src/chart'
import { AutoSizer } from 'avrs-ui/src/content'
import { ipcRenderer } from 'electron'
class MemoryChart extends Component {
constructor(props, context) {
super(props, context)
this.state = {
value: null,
}
}
componentDidMount() {
ipcRenderer.on('session:stat', this.onStat)
}
componentWillUnmount() {
ipcRenderer.removeListener('session:stat', this.onStat)
}
onStat = (event, data) => {
this.setState({ value: data.m })
}
render() {
const { value } = this.state
return (
<AutoSizer>
<LineLiveChart
value={value}
/>
</AutoSizer>
)
}
}
export default MemoryChart
<file_sep>/src/app/pages/profile/routes/index.js
import Profile from '../containers/Profile'
export default function getRoutes() {
return {
path: 'profile',
component: Profile,
}
}
<file_sep>/src/main/window/AuthWindow.js
import Window from './Window'
class AuthWindow extends Window {
options = {
width: 400,
height: 500,
resizable: false,
}
open() {
return super.open('auth.html')
}
}
export default AuthWindow
<file_sep>/src/app/pages/statistics/components/sessions/list/index.js
import Container from './Container'
import Row from './Row'
import Cell from './Cell'
export {
Container,
Row,
Cell,
}
<file_sep>/src/app/routes/auth.js
import auth from '../pages/auth/routes'
export default function getRoutes() {
return {
path: '/',
indexRoute: auth(),
}
}
<file_sep>/src/main/Application.js
import { app } from 'electron'
import ProtocolHandler from './ProtocolHandler'
import IpcManager from './IpcManager'
import Settings from './Settings'
import ApiClient from './ApiClient'
import Tray from './Tray'
import Scheduler from './scheduler/Scheduler'
import { AuthWindow, MainWindow } from './window'
class Application {
constructor() {
this.protocolHandler = new ProtocolHandler()
this.ipcManager = new IpcManager()
this.apiClient = new ApiClient()
this.settings = new Settings()
this.tray = new Tray()
this.scheduler = new Scheduler()
this.windows = {
auth: new AuthWindow(),
main: new MainWindow(),
}
this.ipcManager.on('login', this.onLogin)
this.ipcManager.on('logout', this.onLogout)
this.ipcManager.on('schedule:save', this.onScheduleSave)
this.ipcManager.on('session:start', this.onSessionStart)
this.ipcManager.on('session:stop', this.onSessionStop)
this.apiClient.on('logout', this.onLogout)
this.tray.on('open', this.onOpenPage)
this.tray.on('quit', this.quit)
this.scheduler.on('stat', this.onSessionStat)
this.scheduler.on('started', this.onSessionStarted)
this.scheduler.on('stopped', this.onSessionStoped)
this.scheduler.on('tick', this.onSessionTick)
this.scheduler.on('wait', this.onSessionWait)
app.on('window-all-closed', this.onWindowAllClosed)
}
async start() {
this.protocolHandler.register()
this.ipcManager.init()
await this.settings.load()
await this.launch()
}
async launch() {
if (!this.settings.getToken()) {
await this.windows.auth.open()
return null
}
await this.windows.main.open()
this.apiClient.setToken(this.settings.getToken())
const { user, servicePlans } = await this.apiClient.load()
this.settings.setUser(user)
this.settings.setServicePlans(servicePlans)
await this.settings.loadMachineId()
if (this.settings.isActivated()) {
await this.settings.sync()
}
this.windows.main.send('init', this.settings.toJSON())
if (this.settings.isActivated()) {
this.tray.add()
if (this.settings.isStarted()) {
this.scheduler.setSchedules(this.settings.getSchedules())
this.scheduler.setMachineId(this.settings.getMachineId())
this.scheduler.setToken(this.settings.getToken())
await this.scheduler.start()
}
}
return null
}
quit() {
app.quit()
}
onWindowAllClosed = () => {
if (!this.settings.isActivated()) {
this.quit()
}
}
onLogin = async (token) => {
this.settings.setToken(token)
await this.settings.save()
await this.windows.auth.hide()
await this.launch()
await this.windows.auth.close()
}
onLogout = async () => {
this.settings.setToken(null)
await this.settings.save()
await this.windows.main.hide()
await this.launch()
await this.windows.main.close()
this.scheduler.stop()
this.tray.destroy()
}
onOpenPage = async (target) => {
if (this.windows.main.isClosed()) {
await this.windows.main.open()
this.windows.main.send('init', this.settings.toJSON())
}
if (this.windows.main.isMinimized()) {
this.windows.main.restore()
}
this.windows.main.send('location:change', target)
}
onScheduleSave = async (schedules) => {
this.settings.setSchedules(schedules)
await this.settings.save()
if (this.settings.isStarted()) {
this.scheduler.setSchedules(schedules)
this.scheduler.setMachineId(this.settings.getMachineId())
this.scheduler.setToken(this.settings.getToken())
this.scheduler.refresh()
}
this.windows.main.send('schedule:saved')
}
onSessionStart = async () => {
this.settings.setStarted(true)
await this.settings.save()
this.scheduler.setSchedules(this.settings.getSchedules())
this.scheduler.setMachineId(this.settings.getMachineId())
this.scheduler.setToken(this.settings.getToken())
await this.scheduler.start()
}
onSessionStop = async () => {
this.settings.setStarted(false)
await this.settings.save()
this.scheduler.stop()
}
onSessionStat = (data) => {
this.windows.main.send('session:stat', data)
}
onSessionStarted = (data) => {
this.windows.main.send('session:started', data)
}
onSessionStoped = () => {
this.windows.main.send('session:stopped')
}
onSessionTick = (data) => {
this.windows.main.send('session:tick', data)
}
onSessionWait = (data) => {
this.windows.main.send('session:wait', data)
}
}
export default Application
<file_sep>/src/main/Settings.js
import storage from 'electron-storage'
import { machineId } from 'node-machine-id'
import { generateSchedule, generateEmptySchedule } from './utils'
import { settings as debug } from './debug'
class Settings {
settings = {
started: false,
schedules: {},
}
user = {}
servicePlans = []
setStarted(started) {
this.settings.started = started
}
getToken() {
return this.settings.token
}
setToken(token) {
this.settings.token = token
}
getUser() {
return this.user
}
setUser(user) {
this.user = user
}
setServicePlans(servicePlans) {
this.servicePlans = servicePlans
}
setSchedules(schedules) {
this.settings.schedules = schedules
}
getSchedules() {
return this.settings.schedules
}
getMachineId() {
return this.machineId
}
isStarted() {
return this.settings.started
}
isActivated() {
if (!(this.user && this.user.status)) {
return false
}
return this.user.status !== 'NEW' && this.user.status !== 'NOT_ACTIVATED'
}
toJSON() {
const { activationId, schedules, started, token } = this.settings
return JSON.stringify({
servicePlans: this.servicePlans,
user: this.user,
schedules,
schedule: schedules[activationId],
activationId,
started,
token,
})
}
async sync() {
const updates = {
...this.fillSchedules(),
...this.setActication(),
...this.clearActivation(),
}
if (Object.keys(updates).length > 0) {
this.settings = {
...this.settings,
...updates,
}
await this.save()
}
}
fillSchedules() {
const { activations } = this.user
const activationsIds = activations.map(({ id }) => id, [])
const schedules = Object.keys(this.settings.schedules).reduce((result, id) => {
if (!activationsIds.includes(id)) {
return result
}
return { ...result, [id]: this.settings.schedules[id] }
}, {})
const newSchedules = this.user.activations.reduce((result, { id, servicePlan }, index) => {
if (!(schedules && schedules[id])) {
return {
...result,
[id]: {
schedule: index === 0 ? generateSchedule(servicePlan.time) : generateEmptySchedule(),
},
}
}
return result
}, {})
if (Object.keys(newSchedules).length > 0) {
return { schedules: newSchedules }
}
return {}
}
setActication() {
const { activationId } = this.settings
if (!activationId && this.user.activations.length > 0) {
return { activationId: this.user.activations[0].id }
}
return {}
}
clearActivation() {
const { activationId } = this.settings
if (activationId && !this.user.activations.some(({ id }) => id === activationId)) {
return { activationId: null }
}
return {}
}
async load() {
try {
this.settings = await storage.get('settings')
} catch (error) {
debug(error)
}
}
async save() {
try {
await storage.set('settings', this.settings)
} catch (error) {
debug(error)
}
}
async clear() {
try {
await storage.set('settings', {})
} catch (error) {
debug(error)
}
}
async loadMachineId() {
this.machineId = await machineId()
}
}
export default Settings
<file_sep>/src/app/pages/statistics/reducers/sessions/index.js
import { combineReducers } from 'redux'
import list from './list'
import chart from './chart'
export default combineReducers({
list,
chart,
})
<file_sep>/src/app/pages/statistics/components/sessions/list/Row.js
import React from 'react'
import { StyleSheet } from 'elementum'
const styles = StyleSheet.create({
self: {
display: 'flex',
flexDirection: 'row',
width: '100%',
maxWidth: '100%',
},
})
const Row = ({ children }) => (
<div className={styles({ })}>
{children}
</div>
)
export default Row
<file_sep>/src/app/reducers/auth.js
import { combineReducers } from 'redux'
import { routerStateReducer as router } from 'redux-router'
import user from './user'
import auth from '../pages/auth/reducers'
export default combineReducers({
router,
user,
auth,
})
<file_sep>/src/app/pages/auth/components/Info.js
import React, { PropTypes } from 'react'
import { StyleSheet } from 'elementum'
const styles = StyleSheet.create({
self: {
background: '#f6f7fa',
borderTop: '1px solid #f2f2f2',
boxSizing: 'border-box',
padding: '14px',
width: '100%',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
},
})
const Info = ({ children }) => (
<div className={styles()}>
{children}
</div>
)
Info.propTypes = {
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.element),
PropTypes.element,
]),
}
export default Info
<file_sep>/src/main/IpcManager.js
import { EventEmitter } from 'events'
import { ipcMain } from 'electron'
class IpcManager extends EventEmitter {
init() {
ipcMain.on('auth:login', this.onLogin)
ipcMain.on('auth:logout', this.onLogout)
ipcMain.on('schedule:save', this.onScheduleSave)
ipcMain.on('session:start', this.onStart)
ipcMain.on('session:stop', this.onStop)
}
onLogin = (event, { token }) => {
this.emit('login', token)
}
onLogout = () => {
this.emit('logout')
}
onScheduleSave = (event, data) => {
this.emit('schedule:save', data)
}
onStart = () => {
this.emit('session:start')
}
onStop = () => {
this.emit('session:stop')
}
}
export default IpcManager
<file_sep>/src/app/pages/statistics/reducers/index.js
import { combineReducers } from 'redux'
import filters from './filters'
import sessions from './sessions'
export default combineReducers({
filters,
sessions,
})
<file_sep>/src/app/pages/auth/components/Container.js
import React, { PropTypes } from 'react'
import { StyleSheet } from 'elementum'
import { Row, Layout } from 'flex-layouts'
import { LogoWithText } from 'avrs-ui/src/logo'
const styles = StyleSheet.create({
self: {
width: '100%',
height: '100%',
background: '#ffffff',
},
})
const Container = ({ children }) => (
<div className={styles()}>
<Row fill>
<Layout basis='50px' />
<Layout justify='center'>
<LogoWithText height={30} />
</Layout>
<Layout basis='20px' />
<Layout grow={1}>
{children}
</Layout>
</Row>
</div>
)
Container.propTypes = {
children: PropTypes.element,
}
export default Container
<file_sep>/src/app/components/controls/Divider.js
import React from 'react'
import { StyleSheet } from 'elementum'
const styles = StyleSheet.create({
self: {
position: 'relative',
width: '100%',
height: '5px',
'& div': {
position: 'absolute',
bottom: 0,
height: '10px',
width: '110%',
boxShadow: 'inset 0 -1px 2px 0px rgba(0, 0, 0, 0.05)',
borderBottom: '1px solid #E1E4E6',
},
},
})
const Divider = () => (
<div className={styles()}>
<div />
</div>
)
export default Divider
<file_sep>/src/app/pages/statistics/components/filters/Container.js
import React from 'react'
import { StyleSheet } from 'elementum'
const styles = StyleSheet.create({
self: {
position: 'absolute',
zIndex: 2,
width: '100%',
top: '-400px',
transition: 'all 0.5s ease-in-out',
background: 'transparent',
},
show: {
top: '0px',
},
})
const Container = ({ children, show }) => (
<div className={styles({ show })}>
{children}
</div>
)
export default Container
| c7ca55ff2bb0a9a87718768b3db00f65680a48cd | [
"JavaScript",
"YAML"
] | 79 | JavaScript | kirillDanshin/avrs-desktop | 9a24875d63887d6a0464ec0bc14040016b2af66d | 650dad1065ee1783307e8d905b1b33416bf7af41 |
refs/heads/master | <repo_name>StanislavTomilov/Design-patterns<file_sep>/Decorator/src/Conditment/Soy.java
package Conditment;
import Benerages.Benerage;
/**
* Created by sbt-tomilov-si on 29/03/2018.
*/
public class Soy extends ConditmentDecorator {
Benerage benerage;
public Soy(Benerage benerage) {
this.benerage = benerage;
}
@Override
public String getDescription() {
return benerage.getDescription() + ", Soy";
}
@Override
public double cost() {
return .15 + benerage.cost();
}
}
<file_sep>/FactoryMethod/src/Products/test.java
package Products;
/**
* Created by sbt-tomilov-si on 06/04/2018.
*/
public class test {
}
<file_sep>/Decorator/src/Benerages/HouseBlend.java
package Benerages;
import Benerages.Benerage;
/**
* Created by sbt-tomilov-si on 29/03/2018.
*/
public class HouseBlend extends Benerage {
public HouseBlend() {
description = "House Blend Coffe";
}
@Override
public double cost() {
return .89;
}
}
<file_sep>/Decorator/src/Conditment/ConditmentDecorator.java
package Conditment;
import Benerages.Benerage;
/**
* Created by sbt-tomilov-si on 29/03/2018.
*/
public abstract class ConditmentDecorator extends Benerage {
public abstract String getDescription();
}
<file_sep>/Decorator/src/Benerages/Espresso.java
package Benerages;
import Benerages.Benerage;
/**
* Created by sbt-tomilov-si on 29/03/2018.
*/
public class Espresso extends Benerage {
public Espresso() {
description = "Espresso";
}
@Override
public double cost() {
return 1.99;
}
}
<file_sep>/FactoryMethod/src/Fuctories/ChicagoPizzaStore.java
package Fuctories;
import Products.ChicagoPizza;
import Products.Pizza;
/**
* Created by sbt-tomilov-si on 03/04/2018.
*/
public class ChicagoPizzaStore extends PizzaStore{
@Override
public Pizza createPizza(String type) {
if (type.equals("cheese")) {
return new ChicagoPizza();
} else if (type.equals("veggie")) {
//return new ChicagoVeggiePizza();
return null;
} else if (type.equals("clam")) {
//return new ChicagoClamPizza;
return null;
} else {
return null;
}
}
}
<file_sep>/Decorator/src/Benerages/Decaf.java
package Benerages;
import Benerages.Benerage;
/**
* Created by sbt-tomilov-si on 29/03/2018.
*/
public class Decaf extends Benerage {
public Decaf() {
description = "Decaf";
}
@Override
public double cost() {
return 1.05;
}
}
<file_sep>/Simpe Factory/SimplePizzaFactory2/src/Fuctories/NYPizzaStore.java
package Fuctories;
import Products.NYCheesePizza;
import Products.Pizza;
/**
* Created by sbt-tomilov-si on 03/04/2018.
*/
public class NYPizzaStore extends PizzaStore {
@Override
public Pizza createPizza(String type) {
if (type.equals("cheese")) {
return new NYCheesePizza();
} else if (type.equals("veggie")) {
//return new NYVeggiePizza();
return null;
} else if(type.equals("clam")) {
//return new NYClamPizza();
return null;
} else if (type.equals("pepperoni")) {
//return new NYPeperoniPizza();
return null;
} else {
return null;
}
}
}
| 3e1da0b6726f808476c04f970625394680a4dda2 | [
"Java"
] | 8 | Java | StanislavTomilov/Design-patterns | 5656d9f467413c8ff86ab3df189efd618ef631bc | 32de705b28bfb05cfdf2c403bcbcc1f7dbfb0fd3 |
refs/heads/main | <file_sep>FROM anapsix/alpine-java:8_server-jre_unlimited
MAINTAINER <EMAIL>
RUN mkdir -p /blade
WORKDIR /blade
EXPOSE 8800
ADD ./target/SpringBlade.jar ./app.jar
ENTRYPOINT ["java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "app.jar"]
CMD ["--spring.profiles.active=test"]
| 42523b0c349e39aea61c1e8b549d667fe6a5415c | [
"Dockerfile"
] | 1 | Dockerfile | 1335907208/myblog | b0a8dbd5ea0466cb285b833847cd79b9aed7f1c3 | 8bedcdb3810869dc45d1c9fc92cb305b93031150 |
refs/heads/master | <file_sep># yofio_backend
YoFio - Backend Golang
## Configuration
1 Import the sql that is located on schema/schema.sql
```sql
mysql -u username -p database_name < schema/schema.sql
```
2 Edit the config file `.env`
```
DB_TYPE=mysql
USER=username
PASSWORD=<PASSWORD>
DB_NAME=database_name
```
3 Build and run the project
```
GO111MODULE=on go build
./yofio_backend
```
Tests
For testing you should have the backend run to rull unit tests
```
cd tests
go test
```
Endpoints
POST → /credit-assignment
```
curl -X POST -d '{"investment": 1500}' http://localhost:9090/api/statistics
```
POST → /statistics
```
curl -X POST -d '{}' http://localhost:9090/api/statistics
```
<file_sep>package models
import "time"
type InvestmentRequest struct {
Investment int32 `json:"investment"`
}
type CreditType struct {
Id int64 `json:"-" gorm:"primary_key"`
CreditType300 int32 `json:"credit_type_300" gorm:"column:credit_type_300"`
CreditType500 int32 `json:"credit_type_500" gorm:"column:credit_type_500"`
CreditType700 int32 `json:"credit_type_700" gorm:"column:credit_type_700"`
Investment int32 `json:"-" gorm:"column:investment"`
Success int32 `json:"-" gorm:"column:success"`
DateCreated time.Time `json:"-" gorm:"column:date_created;default:'current_timestamp'"`
}
func (CreditType) TableName() string {
return "credit_Type"
}
type CreditTypeStatistics struct {
AssignmentsDone int32 `json:"assignments_done"`
AssignmentsSuccess int32 `json:"assignments_success"`
AssignmentsUnSuccess int32 `json:"assignments_unsuccess"`
InvestmentAverageSuccess int32 `json:"investment_average_success"`
InvestmentAverageUnSuccess int32 `json:"investment_average_unsuccess"`
}
<file_sep>package repository
import (
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
)
func GetConnection(DB_TYPE, MYSQL_CONNECT string) (*gorm.DB, error) {
connection, err := gorm.Open(DB_TYPE, MYSQL_CONNECT)
if err != nil {
return nil, err
}
connection.SingularTable(true)
connection.LogMode(true)
connection.DB().SetConnMaxLifetime(0)
return connection, nil
}
<file_sep>package controllers
import (
"encoding/json"
"fmt"
"net/http"
"github.com/hendry19901990/yofio_backend/models"
"github.com/hendry19901990/yofio_backend/repository"
"github.com/hendry19901990/yofio_backend/services"
)
// success
// curl -X POST -d '{"investment": 1500}' http://localhost:9090/api/statistics
// unsuccess
//curl -X POST -d '{"investment": 1600}' http://localhost:9090/api/credit-assignment
func (cont *Controller) CreditAssignment(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
req := models.InvestmentRequest{}
if err := decoder.Decode(&req); err != nil {
http.Error(w, http.StatusText(400), 400)
cont.WriteResponse(w, []byte(http.StatusText(400)), 400)
return
}
conn, connErr := cont.GetConnection()
if connErr != nil {
cont.WriteResponse(w, []byte(connErr.Error()), 500)
return
}
creditStore := repository.CreditStore{conn}
c := services.GetCreditAssigner()
creditType300, creditType500, creditType700, err := c.Assign(req.Investment)
resp := models.CreditType{
CreditType300: creditType300,
CreditType500: creditType500,
CreditType700: creditType700,
Investment: req.Investment,
}
if err != nil {
creditStore.Save(&resp)
fmt.Println(err)
cont.WriteResponse(w, []byte(err.Error()), 400)
return
}
resp.Success = 1
creditStore.Save(&resp)
bytesResp, err := json.Marshal(&resp)
if err != nil {
fmt.Println(err)
cont.WriteResponse(w, []byte(err.Error()), 500)
return
}
cont.WriteResponse(w, bytesResp, 200)
}
//curl -X POST -d '{}' http://localhost:9090/api/statistics
func (cont *Controller) Statistics(w http.ResponseWriter, r *http.Request) {
conn, connErr := cont.GetConnection()
if connErr != nil {
http.Error(w, connErr.Error(), 500)
return
}
creditStore := repository.CreditStore{conn}
statistics, err := creditStore.GetCreditTypeStatistics()
if err != nil {
fmt.Println(err)
http.Error(w, err.Error(), 500)
return
}
bytesResp, err := json.Marshal(statistics)
if err != nil {
fmt.Println(err)
cont.WriteResponse(w, []byte(err.Error()), 500)
return
}
cont.WriteResponse(w, bytesResp, 200)
}
<file_sep>package repository
import (
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
"github.com/hendry19901990/yofio_backend/models"
)
type CreditStore struct {
Connection *gorm.DB
}
func (creditStore *CreditStore) Save(creditType *models.CreditType) {
creditStore.Connection.NewRecord(creditType)
creditStore.Connection.Create(creditType)
}
type CreditTypeStatisticsResult struct {
Count int32
Average float32
Success int32
}
func (creditStore *CreditStore) GetCreditTypeStatistics() (*models.CreditTypeStatistics, error) {
var result []CreditTypeStatisticsResult
creditStore.Connection.Raw("select count(*) as count, avg(investment) as average, success from credit_Type group by success").Scan(&result)
statistics := models.CreditTypeStatistics{}
assignmentsDone := int32(0)
for _, res := range result {
if res.Success == 1 {
statistics.AssignmentsSuccess = res.Count
statistics.InvestmentAverageSuccess = int32(res.Average)
assignmentsDone += res.Count
} else if res.Success == 0 {
statistics.AssignmentsUnSuccess = res.Count
statistics.InvestmentAverageUnSuccess = int32(res.Average)
assignmentsDone += res.Count
}
}
statistics.AssignmentsDone = assignmentsDone
return &statistics, nil
}
<file_sep>-- MySQL dump 10.13 Distrib 8.0.22, for Linux (x86_64)
--
-- Host: 127.0.0.1 Database: test_db
-- ------------------------------------------------------
-- Server version 5.7.32
--
-- Table structure for table `credit_Type`
--
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE IF NOT EXISTS `credit_Type` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`credit_type_300` int(11) NOT NULL,
`credit_type_500` int(11) NOT NULL,
`credit_type_700` int(11) NOT NULL,
`investment` int(11) NOT NULL,
`success` tinyint(1) NOT NULL,
`date_created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
<file_sep>package tests
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"github.com/hendry19901990/yofio_backend/models"
"github.com/hendry19901990/yofio_backend/services"
)
func TestCreditAssigner(t *testing.T) {
c := services.GetCreditAssigner()
creditType300, creditType500, creditType700, _ := c.Assign(3000)
resultSuccess := creditType300*300 + creditType500*500 + creditType700*700
assert.Equal(t, int32(3000), resultSuccess, "The three values should be the same.")
creditType300, creditType500, creditType700, _ = c.Assign(1600)
resultUnSuccess := creditType300*300 + creditType500*500 + creditType700*700
assert.Equal(t, int32(0), resultUnSuccess, "The result should be zero.")
}
func TestSuccessCreditAssignment(t *testing.T) {
investOk := `{"investment": 3000}`
credit, err := MakeRequest("http://localhost:9090/api/credit-assignment", []byte(investOk))
if err != nil {
t.Errorf("%v", err)
return
}
resultSuccess := credit.CreditType300*300 + credit.CreditType500*500 + credit.CreditType700*700
assert.Equal(t, int32(3000), resultSuccess, "The three values should be the same.")
}
func TestUnSuccessCreditAssignment(t *testing.T) {
investOk := `{"investment": 1600}`
credit, err := MakeRequest("http://localhost:9090/api/credit-assignment", []byte(investOk))
if err != nil {
t.Errorf("%v", err)
return
}
resultUnSuccess := credit.CreditType300*300 + credit.CreditType500*500 + credit.CreditType700*700
assert.Equal(t, int32(0), resultUnSuccess, "The result should be zero.")
}
func TestStatistics(t *testing.T) {
statisticsTest, err := MakeRequest("http://localhost:9090/api/statistics", []byte("{}"))
if err != nil {
t.Errorf("%v", err)
return
}
assert.NotNil(t, statisticsTest, "The result shouldn't be empty.")
}
func MakeRequest(url string, jsonStr []byte) (*models.CreditType, error) {
fmt.Println("URL:> ", url)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
credit := models.CreditType{}
if resp.StatusCode == 200 {
if errParse := json.Unmarshal(body, &credit); errParse != nil {
return nil, errParse
}
}
return &credit, nil
}
<file_sep>package controllers
import (
"errors"
"net/http"
"github.com/hendry19901990/yofio_backend/repository"
"github.com/jinzhu/gorm"
)
type Controller struct {
DBType string
URLConnection string
connection *gorm.DB
}
func (cont *Controller) Init() error {
conn, err := repository.GetConnection(cont.DBType, cont.URLConnection)
if err != nil {
return err
}
cont.connection = conn
return nil
}
func (cont *Controller) GetConnection() (*gorm.DB, error) {
if d := cont.connection.DB(); d != nil {
if err := d.Ping(); err != nil {
d.Close()
if err := cont.Init(); err != nil {
return nil, err
}
}
return cont.connection, nil
}
return nil, errors.New("Error parsing sql.DB")
}
func (cont *Controller) WriteResponse(w http.ResponseWriter, content []byte, code int) {
if code == 200 {
w.Write(content)
} else {
http.Error(w, string(content), code)
}
}
<file_sep>package services
import (
"errors"
"fmt"
)
type CreditAssigner interface {
Assign(investment int32) (int32, int32, int32, error)
}
type CreditYoFio struct {
}
func (credit *CreditYoFio) Assign(investment int32) (int32, int32, int32, error) {
if investment%100 != 0 {
return 0, 0, 0, errors.New("Quantity must be multiple of 100")
}
if investment < 1500 {
return 0, 0, 0, errors.New("Quantity must be greater than 1500")
}
investment2 := investment
var creditType700, creditType500, creditType300 int32
if investment >= 700 {
creditType700 = int32(investment / 700)
investment = investment - (creditType700 * 700)
if investment < 800 {
creditType700--
investment += 700
}
}
for investment >= 300 && creditType700 >= 1 {
if investment >= 500 {
can := int32(investment / 500)
creditType500 += can
investment -= can * 500
if investment < 300 {
creditType500--
investment += 500
}
}
if investment >= 300 {
can := int32(investment / 300)
creditType300 += int32(investment / 300)
investment -= can * 300
}
if (investment > 0 && creditType700 > 1) || creditType700 > creditType300 {
creditType700--
investment += 700
}
}
fmt.Printf("investment received %d result %d \n", investment2, (creditType300*300 + creditType500*500 + creditType700*700))
if investment > 0 {
return 0, 0, 0, errors.New(fmt.Sprintf("It's impossible to make an assign with %d", investment2))
}
return creditType300, creditType500, creditType700, nil
}
func GetCreditAssigner() CreditAssigner {
return &CreditYoFio{}
}
<file_sep>module github.com/hendry19901990/yofio_backend
go 1.15
require (
github.com/go-chi/chi/v5 v5.0.3
github.com/go-sql-driver/mysql v1.6.0
github.com/jinzhu/gorm v1.9.16
github.com/joho/godotenv v1.3.0
github.com/stretchr/testify v1.7.0
)
<file_sep>package main
import (
"fmt"
"net/http"
"os"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/hendry19901990/yofio_backend/controllers"
"github.com/joho/godotenv"
)
func main() {
if err := godotenv.Load(".env"); err != nil {
panic(err)
}
r := chi.NewRouter()
// A good base middleware stack
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
// Set a timeout value on the request context (ctx), that will signal
// through ctx.Done() that the request has timed out and further
// processing should be stopped.
r.Use(middleware.Timeout(60 * time.Second))
cont := controllers.Controller{
DBType: os.Getenv("DB_TYPE"),
URLConnection: fmt.Sprintf("%s:%s@/%s?charset=utf8&parseTime=True&loc=Local", os.Getenv("USER"), os.Getenv("PASSWORD"), os.Getenv("DB_NAME")),
}
if err := cont.Init(); err != nil {
panic(err)
}
r.Route("/api", func(r chi.Router) {
r.Post("/credit-assignment", cont.CreditAssignment)
r.Post("/statistics", cont.Statistics)
})
http.ListenAndServe(":9090", r)
}
| b4eb560c262bd6c9e42c87eb0184e28298a2b38c | [
"Markdown",
"SQL",
"Go Module",
"Go"
] | 11 | Markdown | hendry19901990/yofio_backend | 59d3e7988f6eb17fdeb8f71405b5727f65dc6dde | a78002bbe65bcb221493cf1a10f88bad8b1e337b |
refs/heads/main | <repo_name>Lazuli22/OC_V2_P7<file_sep>/controllers/optimized.py
from typing import List
from controllers.strategy import Strategy
from models.portfolio import Portfolio
from models.combination import Combination
class Optimized(Strategy):
def __init__(self, portfolio: Portfolio, max_cost: float):
super().__init__(portfolio=portfolio)
self.max_cost = max_cost
def run(self,) -> List:
""" Method that generates the best combination of a shares portfolio
with GK algo
"""
super().run()
spent_money = 0
list_share = []
actions_list = self.data["portfolio"].actions_list
sorted_portfolio = sorted(
actions_list,
key=lambda share: float(share.benefits),
reverse=True)
for share in sorted_portfolio:
if spent_money + share.cost <= self.max_cost:
list_share.append(share)
spent_money += share.cost
one_comb = Combination(list_share)
print(f"{one_comb}")
self.stop()
return one_comb
<file_sep>/README.md
# OC_V2_P7
Projet sur les algorithmes
## Description du projet :
L'application propose de calculer le meilleur investissement à réaliser par un client
selon 2 types d'algorithmes :
* Force Brute
* Algorithme optimisé
## Installation :
Dans votre répertoire de travail, créer un répertoire d'installation nommé "OC_V2_P7"
et placez - vous sous ce répertoire de travail
* Pour Linux :
`$ cd /home/user/OC_V2_P7`
* Pour Windows :
` cd C:/Users/user/OC_V2_P7`
Puis entrer :
` git clone https://github.com/Lazuli22/OC_V2_P7.git`
## Pré-requis :
Utilisation du fichier requirements.txt en vue de créer l'environnement des librairies du projet
* Se placer dans le répertoire d'installation du projet
* Pour Linux :
`$ cd /home/user/OC_V2_P7`
* Pour Windows :
` cd C:/Users/user/OC_V2_P7`
* pour le créer, lancer la commande :
`python -m -venv env`
* Pour l'activer, lancer la commande :
* Pour Linux :
`env/bin/activate `
* Pour Windows :
`.\env\Script\activate.bat`
* Pour l'alimenter, lancer la commande :
`pip install -r requirements.txt`
## Lancement du projet :
Pour lancer le projet : `python main.py`
## Autrice
* Dolores DIAZ alias Lazuli22
<file_sep>/controllers/strategy.py
import abc
import time
class Strategy(metaclass=abc.ABCMeta):
def __init__(self, **kwargs):
self.data = kwargs
self.start_time = None
@abc.abstractmethod
def run(self):
""" general all possible combinations of a portfolio """
self.start_time = time.time()
def stop(self):
elapsed_time = time.time() - self.start_time
print(f"Temps écoulé : {elapsed_time} s")
<file_sep>/models/share.py
from models.seriable import Serializable
class Share(Serializable):
"""
Class that represents an enterprise's action
"""
def __init__(
self,
name,
cost,
percentage,
benefits
):
self.name = name
self.cost = float(cost)
self.percentage = float(percentage)
self.benefits = float(benefits)
def serialize(self):
"""
function that serialize an object action.
In output, the function gives a dict of data
"""
return{
"name": self.name,
"cost": self.cost, "percentage": self.percentage,
"benefits": self.benefits
}
def __repr__(self) -> str:
""" function that represents a share"""
return (
f"[{self.name}, {self.cost}, {self.benefits}]"
)
<file_sep>/models/combination.py
from typing import List
from models.share import Share
from terminaltables import AsciiTable
class Combination:
def __init__(self, shares: List[Share] = None) -> None:
""" unicité de la share"""
self.shares = shares if shares else []
self.cost = self.total_cost()
self.benefits = self.total_benefits()
def total_cost(self):
return sum([float(share.cost) for share in self.shares])
def total_benefits(self):
return sum([float(share.benefits) for share in self.shares])
@classmethod
def __gt__(cls, a, b):
return a.cost > b.cost
def __repr__(self) -> str:
""" function that represents a combination"""
comp = [("Shares", "Cost", "Benefits")]
for e in self.shares:
comp.append([e.name,
e.cost,
e.benefits])
table_instance = AsciiTable(comp, "Meilleure combinaison")
print(table_instance.table)
return (
f"Cost of the Combination : {self.cost}, "
f"Benefits of the Combination : {self.benefits} "
"\n"
)
<file_sep>/models/portfolio.py
from models.share import Share
import json
import csv
class Portfolio:
"""
class that groups severals actions
"""
def __init__(self):
self.actions_list = []
self.size = 0
def serialize(self):
action_list = []
for elt in self.actions_list:
action_list.append(elt.serialize())
return action_list
def load_from_json(self, name):
with open(name) as f:
data = json.load(f)
for elt in data:
self.actions_list.append(Share(**elt))
def load_from_csv(self, name):
f = open(name)
myReader = csv.reader(f, delimiter=";")
myReader.__next__()
for row in myReader:
if(float(row[1]) > 0.0):
self.actions_list.append(
Share(row[0], row[1], row[2], row[3]))
# print(self.actions_list)
def __iter__(self):
self.size = 0
return self
def __next__(self):
self.size += 1
if self.size > len(self.actions_list):
raise StopIteration()
return self.actions_list[self.size-1]
def __len__(self):
return len(self.actions_list)
<file_sep>/models/seriable.py
import abc
class Serializable(abc.ABC):
@abc.abstractclassmethod
def serialize(self):
pass
<file_sep>/main.py
from controllers.brute_force import BruteForce
# from controllers.optimized import Optimized
from models.portfolio import Portfolio
def main():
# Exemple de la force brute
one_library = Portfolio()
one_library.load_from_json("actions_library.json")
strategy_brute_force = BruteForce(one_library, 500.0)
print(strategy_brute_force.run())
# Exemple de l'algo optimisé
# one_library = Portfolio()
# one_library.load_from_json("actions_library.json")
# optimised_strategy = Optimized(one_library, 500.0)
# optimised_strategy.run()
# Exemples de comparaison avec les résultats SIENNA
# one_library = Portfolio()
# one_library.load_from_csv("dataset1.csv")
# library_two = Portfolio()
# library_two.load_from_csv("dataset2.csv")
# strategy_optimised_one = Optimized(one_library, 500.0)
# strategy_optimised_two = Optimized(library_two, 500.0)
# strategy_optimised_one.run()
# strategy_optimised_two.run()
if __name__ == "__main__":
main()
<file_sep>/controllers/brute_force.py
from itertools import combinations
from typing import List
from controllers.strategy import Strategy
from models.portfolio import Portfolio
from models.combination import Combination
class BruteForce(Strategy):
def __init__(self, portfolio: Portfolio, max_cost: float):
super().__init__(portfolio=portfolio)
self.max_cost = max_cost
def run(self) -> List:
""" function that generates all combinations of a portfolio"""
super().run()
the_comb = Combination()
for r in range(2, len(self.data['portfolio']) + 1):
for e in combinations(self.data['portfolio'], r):
one_comb = Combination(e)
if (one_comb.cost <= self.max_cost and
one_comb.benefits > the_comb.benefits):
the_comb = one_comb
self.stop()
return the_comb
| 406c7b07bf198b2f7f0eaa2763ef688d96bf6a1e | [
"Markdown",
"Python"
] | 9 | Python | Lazuli22/OC_V2_P7 | 089a5467742117ca8f787a8f2b90ff48d553cf3a | 01affbee4863cb5f323f5d599c9c6ece7ee9199f |
refs/heads/master | <file_sep>import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class HttpTest {
@Test
public void httpTest() throws IOException {
HttpUriRequest request = new HttpGet("https://pandao.ru/");
HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);
assertEquals(HttpStatus.SC_OK, httpResponse.getStatusLine().getStatusCode());
}
}
| 46f4dafaab36f3e192107753ca28fd435a8f014d | [
"Java"
] | 1 | Java | peefpuf/pantestao | 1fac668a3b88ea5b9bad164e583c8885973a259b | 2efe24d211a65c120ec7c181c8b61db69f84f8e6 |
refs/heads/master | <repo_name>venkybavisetti/buzzcric<file_sep>/src/updateScore.js
const {
getMatch,
getBattingTeam,
getBowlingTeam,
getPlayer,
getScoreCard,
} = require('./utilities');
const updateBatingTeam = (lookup, team, ball, batsmanName) => {
let [runs, extras] = getBallInfo(ball);
team.score += +runs + lookup[extras].runs;
team.balls += lookup[extras].ballCount;
if (extras === 'wk') team.wickets += 1;
let batsman = getPlayer(team, batsmanName);
batsman.batting.score += +runs;
batsman.batting.balls += lookup[extras].ballCount;
};
const updateBowlingTeam = (lookup, team, ball, bowlerName) => {
let [runs, extras] = getBallInfo(ball);
let bowler = getPlayer(team, bowlerName);
bowler.bowling.score += +runs + lookup[extras].runs;
bowler.bowling.balls += lookup[extras].ballCount;
if (extras === 'wk') bowler.bowling.wickets += 1;
};
const isFirstBallWithWide = (inPlay) =>
['wd', 'nb'].some((el) => inPlay.currentOver.slice(-1)[0].includes(el));
const updateInPlayStatus = (match, ball) => {
let { inPlay } = match;
let bowlingTeam = getBowlingTeam(match);
let bowler = getPlayer(bowlingTeam, inPlay.bowler);
let [runs, extras] = getBallInfo(ball);
inPlay.currentOver.push(ball);
if (extras === 'wk') inPlay.batsman = null;
if (bowler.bowling.balls % 6 === 0 && !isFirstBallWithWide(inPlay)) {
inPlay.currentOver = [];
inPlay.bowler = null;
let playerName = inPlay.batsman;
inPlay.batsman = inPlay.opponentBatsman;
inPlay.opponentBatsman = playerName;
}
if (+runs === 1 || +runs === 3 || ball === '1lb' || ball === '3lb') {
let playerName = inPlay.batsman;
inPlay.batsman = inPlay.opponentBatsman;
inPlay.opponentBatsman = playerName;
}
};
const getBallInfo = (ball) => [ball[0], ball.slice(1)];
const updateInningStatus = (match) => {
const battingTeam = getBattingTeam(match);
const bowlingTeam = getBowlingTeam(match);
const isWicketsDown = battingTeam.wickets === battingTeam.players.length - 1;
const isOverDone = match.overs * 6 === battingTeam.balls;
if (isWicketsDown || isOverDone) {
match.currentStatus = { battingTeam: bowlingTeam.name, inning: '2nd' };
match.target = battingTeam.score + 1;
match.inPlay = {
batsman: null,
opponentBatsman: null,
bowler: null,
currentOver: [],
};
}
};
const updateIsMatchCompleted = (match) => {
const battingTeam = getBattingTeam(match);
const bowlingTeam = getBowlingTeam(match);
const isScoreAboveTarget = match.target <= battingTeam.score;
const isWicketsDown = battingTeam.wickets === battingTeam.players.length - 1;
const isOverDone = match.overs * 6 === battingTeam.balls;
if (isWicketsDown || isOverDone) {
match.winner = bowlingTeam.name;
}
if (isScoreAboveTarget) match.winner = battingTeam.name;
};
const updateMatchStatus = (match) => {
if (match.currentStatus.inning === '1st') {
updateInningStatus(match);
} else {
updateIsMatchCompleted(match);
}
};
const updateScore = (matches, matchId, ball) => {
const extrasRunsLookup = {
'': { runs: 0, ballCount: 1 },
lb: { runs: 0, ballCount: 1 },
wk: { runs: 0, ballCount: 1 },
wd: { runs: 1, ballCount: 0 },
nb: { runs: 1, ballCount: 0 },
};
let match = getMatch(matches, matchId);
const battingTeam = getBattingTeam(match);
const bowlingTeam = getBowlingTeam(match);
updateBatingTeam(extrasRunsLookup, battingTeam, ball, match.inPlay.batsman);
updateBowlingTeam(extrasRunsLookup, bowlingTeam, ball, match.inPlay.bowler);
updateInPlayStatus(match, ball);
updateMatchStatus(match);
return getScoreCard(matches, matchId);
};
module.exports = { updateScore };
<file_sep>/README.md
# buzzcric
link for app : https://buzzcric.herokuapp.com/
<file_sep>/src/app.js
const express = require('express');
const morgan = require('morgan');
const redis = require('redis');
const { DB } = require('./db');
const session = require('cookie-session');
const {
CLIENT_ID,
CLIENT_SECRET,
REACT_HOME_PAGE_URL,
SECRET_MSG,
} = require('../config');
const {
setupMatch,
loadData,
getInPlay,
choosePlayers,
updateInPP,
updateScoreCard,
getMatches,
getScoreBoard,
checkAuthentication,
getUserDetails,
authenticate,
getUser,
setUserLogout,
checkOwner,
getAllUsers,
} = require('./handlers');
const url = process.env.REDIS_URL || '6379';
const redisClient = redis.createClient(url);
const db = new DB(redisClient);
const app = express();
app.locals.CLIENT_ID = CLIENT_ID;
app.locals.CLIENT_SECRET = CLIENT_SECRET;
app.locals.REACT_HOME_PAGE_URL = REACT_HOME_PAGE_URL;
app.locals.db = db;
app.set('sessionMiddleware', session({ secret: SECRET_MSG }));
app.use(morgan('dev'));
app.use(express.json());
app.use((...args) => app.get('sessionMiddleware')(...args));
app.use(loadData);
app.use(express.static('build'));
app.get('/api/scoreBoard/:id', getScoreBoard);
app.get('/api/getMatches', getMatches);
app.get('/api/getUser', getUser);
app.get('/api/authenticate', authenticate);
app.get('/callback', getUserDetails);
app.use(checkAuthentication);
app.get('/api/getAllUsers', getAllUsers);
app.post('/api/logout', setUserLogout);
app.post('/api/setupMatch', setupMatch);
app.param('matchId', checkOwner);
app.get('/api/getInPlay/:matchId', getInPlay);
app.get('/api/choosePlayers/:matchId', choosePlayers);
app.post('/api/updateInPP/:matchId', updateInPP);
app.post('/api/updateScore/:matchId', updateScoreCard);
module.exports = { app };
<file_sep>/src/db.js
class DB {
constructor(client) {
this.client = client;
}
loadData() {
return new Promise((resolve, reject) => {
this.client.get('BuzzCric', (err, res) => resolve(JSON.parse(res)));
});
}
saveData(BuzzCric) {
return new Promise((resolve, reject) => {
this.client.set('BuzzCric', JSON.stringify(BuzzCric), (err, res) =>
resolve(true)
);
});
}
addUser({ id, name, img }) {
return new Promise((resolve, reject) => {
this.client.hmset(id, { id, name, img }, (err, res) => {
resolve(true);
});
});
}
getUser(id) {
return new Promise((resolve, reject) => {
this.client.hgetall(id, (err, res) => {
if (err) resolve({});
resolve(res);
});
});
}
getAllUsers() {
return new Promise((resolve, reject) => {
this.client.keys('*', (err, res) => {
if (err) resolve({});
resolve(res);
});
});
}
}
module.exports = { DB };
<file_sep>/src/utilities.js
const getBattingTeamName = (hostingTeam, visitorTeam, matchDetails) => {
let battingTeam = '';
if (matchDetails.opted === 'bat') {
battingTeam = matchDetails.toss;
} else {
battingTeam = matchDetails.toss === hostingTeam ? visitorTeam : hostingTeam;
}
return battingTeam;
};
const getBattingTeam = (match) => {
const teams = {
[match.visitorTeam.name]: match.visitorTeam,
[match.hostingTeam.name]: match.hostingTeam,
};
return teams[match.currentStatus.battingTeam];
};
const getBowlingTeam = (match) => {
const teams = {
[match.hostingTeam.name]: match.visitorTeam,
[match.visitorTeam.name]: match.hostingTeam,
};
return teams[match.currentStatus.battingTeam];
};
const getMatch = (matches, matchId) =>
matches.find((match) => match.matchId === matchId);
const getPlayer = (team, name) =>
team.players.find((player) => player.name === name);
const getScoreCard = (matches, matchId) => {
const match = getMatch(matches, matchId);
const battingTeam = getBattingTeam(match);
const bowlingTeam = getBowlingTeam(match);
const {
inPlay,
target,
tossWon,
hostingTeam,
visitorTeam,
opted,
overs,
winner,
} = match;
const teams = {
hostingTeam: hostingTeam.name,
visitorTeam: visitorTeam.name,
};
const { name, score, wickets, balls } = battingTeam;
const { inning } = match.currentStatus;
const batsman = getPlayer(battingTeam, inPlay.batsman);
const opponentBatsman = getPlayer(battingTeam, inPlay.opponentBatsman);
const bowler = getPlayer(bowlingTeam, inPlay.bowler);
const { currentOver } = inPlay;
return {
teams,
scoreBoard: {
team: name,
inning,
score,
wickets,
balls,
target,
opted,
tossWon,
overs,
},
inPlay: { batsman, opponentBatsman, bowler },
currentOver,
winner,
};
};
module.exports = {
getBattingTeamName,
getMatch,
getBattingTeam,
getBowlingTeam,
getPlayer,
getScoreCard,
};
<file_sep>/config.js
// require('dotenv').config();
module.exports = {
CLIENT_ID: process.env.CLIENT_ID,
CLIENT_SECRET: process.env.CLIENT_SECRET,
REACT_HOME_PAGE_URL: process.env.REACT_HOME_PAGE_URL,
SECRET_MSG: process.env.SECRET_MSG,
};
| 5cb8e79fcd1d1b36d77b9997f8419a676a13fa5f | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | venkybavisetti/buzzcric | 7fc165ac06936c0a9836863ea6af32463463de91 | 0c40a08fcff59d0ad6d6a9043d55e952ab2eeca4 |
refs/heads/master | <repo_name>StoneMain/WelcomeTutorial<file_sep>/src/main/java/me/lucko/welcometutorial/TutorialCommand.java
package me.lucko.welcometutorial;
import lombok.RequiredArgsConstructor;
import com.sk89q.worldguard.bukkit.WGBukkit;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import me.lucko.helper.metadata.Metadata;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.stream.Collectors;
@RequiredArgsConstructor
public class TutorialCommand implements CommandExecutor {
private final TutorialPlugin plugin;
@Override
public boolean onCommand(CommandSender sender, Command command, String s, String[] args) {
if (args.length > 0 && args[0].equalsIgnoreCase("reload") && sender.isOp()) {
plugin.reloadConfig();
plugin.msg(sender, "Config reloaded.");
return true;
}
if (!(sender instanceof Player)) {
plugin.msg(sender, "You need to be a player to do this.");
return true;
}
Player player = (Player) sender;
if (!player.hasPermission("welcometutorial.use")) {
plugin.msg(sender, "No permission.");
return true;
}
if (Metadata.provideForPlayer(player).has(TutorialPlugin.VANISHED_KEY)) {
plugin.msg(sender, "You are already in a tutorial.");
return true;
}
if (args.length == 0) {
plugin.msg(player, "Usage: /tutorial <name>");
plugin.msg(player, "Available Tutorials: " + plugin.getTutorials().keySet().stream().collect(Collectors.joining("&7, &f")));
return true;
}
String tutorialName = args[0];
Tutorial tutorial = plugin.getTutorials().get(tutorialName.toLowerCase());
if (tutorial == null) {
plugin.msg(player, "That tutorial does not exist.");
plugin.msg(player, "Available Tutorials: " + plugin.getTutorials().keySet().stream().collect(Collectors.joining("&7, &f")));
return true;
}
regioncheck:
if (!tutorial.getRequiredRegion().equals("")) {
ApplicableRegionSet set = WGBukkit.getRegionManager(player.getWorld()).getApplicableRegions(player.getLocation());
for (ProtectedRegion r : set.getRegions()) {
if (r.getId().equalsIgnoreCase(tutorial.getRequiredRegion())) {
break regioncheck;
}
}
plugin.msg(player, "You cannot start that tutorial in this region.");
return true;
}
plugin.vanishPlayer(player);
new TutorialRunnable(player, player.getLocation().clone(), tutorial, tutorial.getStages()).runTaskTimer(plugin, 10L, 1L);
return true;
}
}
<file_sep>/src/main/java/me/lucko/welcometutorial/TutorialPlugin.java
package me.lucko.welcometutorial;
import lombok.Getter;
import me.lucko.helper.Events;
import me.lucko.helper.Scheduler;
import me.lucko.helper.metadata.Metadata;
import me.lucko.helper.metadata.MetadataKey;
import me.lucko.helper.plugin.ExtendedJavaPlugin;
import me.lucko.helper.plugin.ap.Plugin;
import me.lucko.helper.plugin.ap.PluginDependency;
import me.lucko.helper.terminable.CompositeTerminable;
import me.lucko.helper.terminable.Terminable;
import me.lucko.helper.utils.Color;
import me.lucko.welcometutorial.event.TutorialCompleteEvent;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
@Getter
@Plugin(name = "WelcomeTutorial", depends = @PluginDependency("WorldGuard"))
public class TutorialPlugin extends ExtendedJavaPlugin implements TutorialApi, CompositeTerminable {
public static final MetadataKey<Boolean> VANISHED_KEY = MetadataKey.createBooleanKey("wt-vanished");
private String prefix;
private final Map<String, Tutorial> tutorials = Collections.synchronizedMap(new HashMap<>());
@Override
public void onEnable() {
loadConfig();
bindTerminable(this);
registerCommand(new TutorialCommand(this), "tutorial");
provideService(TutorialApi.class, this);
}
public void reloadConfig() {
this.tutorials.clear();
loadConfig();
}
public void loadConfig() {
FileConfiguration config = loadConfig("config.yml");
this.prefix = Color.colorize(config.getString("prefix", "&7[&bTutorial&7] &f"));
Set<String> tutorials = config.getKeys(false);
for (String tutorialId : tutorials) {
if (tutorialId.equalsIgnoreCase("prefix")) {
continue;
}
ConfigurationSection tutorialSection = config.getConfigurationSection(tutorialId);
String name = Color.colorize(tutorialSection.getString("name", tutorialId));
String requiredRegion = tutorialSection.getString("required-region", "");
Tutorial tutorial = new Tutorial(name, requiredRegion);
ConfigurationSection locationsSection = tutorialSection.getConfigurationSection("locations");
Set<String> locationKeys = locationsSection.getKeys(false);
for (String locationKey : locationKeys) {
ConfigurationSection locationSection = locationsSection.getConfigurationSection(locationKey);
tutorial.addStage(new TutorialStage(locationSection));
}
this.tutorials.put(ChatColor.stripColor(Color.colorize(name.toLowerCase())), tutorial);
}
}
public void vanishPlayer(Player p) {
Metadata.provideForPlayer(p).put(VANISHED_KEY, true);
for (Player other : getServer().getOnlinePlayers()) {
if (other.getUniqueId().equals(p.getUniqueId())) {
continue;
}
other.hidePlayer(p);
}
}
public void unvanishPlayer(Player p) {
Metadata.provideForPlayer(p).remove(VANISHED_KEY);
for (Player other : getServer().getOnlinePlayers()) {
if (other.getUniqueId().equals(p.getUniqueId())) {
continue;
}
other.showPlayer(p);
}
}
@Override
public void bind(Consumer<Terminable> consumer) {
Events.subscribe(TutorialCompleteEvent.class)
.handler(e -> Scheduler.runLaterSync(() -> unvanishPlayer(e.getPlayer()), 2L))
.register(consumer);
Events.subscribe(PlayerJoinEvent.class)
.handler(e -> {
for (Player vanished : Metadata.lookupPlayersWithKey(VANISHED_KEY).keySet()) {
e.getPlayer().hidePlayer(vanished);
}
if (e.getPlayer().getWalkSpeed() < 0.2f) {
e.getPlayer().setWalkSpeed(0.2f);
}
})
.register(consumer);
Events.subscribe(PlayerQuitEvent.class)
.filter(Events.DEFAULT_FILTERS.playerHasMetadata(VANISHED_KEY))
.handler(e -> unvanishPlayer(e.getPlayer()))
.register(consumer);
Events.subscribe(PlayerCommandPreprocessEvent.class)
.filter(Events.DEFAULT_FILTERS.playerHasMetadata(VANISHED_KEY))
.handler(e -> {
msg(e.getPlayer(), "You cannot use commands whilst in a tutorial!");
e.setCancelled(true);
})
.register(consumer);
Events.subscribe(AsyncPlayerChatEvent.class)
.handler(e -> e.getRecipients().removeIf(p -> Metadata.provideForPlayer(p).has(VANISHED_KEY)))
.register(consumer);
Events.subscribe(EntityDamageEvent.class)
.filter(e -> e.getEntity() instanceof Player)
.filter(e -> Metadata.provideForEntity(e.getEntity()).has(VANISHED_KEY))
.handler(e -> e.setCancelled(true))
.register(consumer);
Events.subscribe(PlayerMoveEvent.class)
.filter(e -> !(e instanceof PlayerTeleportEvent))
.filter(Events.DEFAULT_FILTERS.ignoreSameBlockAndY())
.filter(Events.DEFAULT_FILTERS.playerHasMetadata(VANISHED_KEY))
.handler(e -> e.setCancelled(true))
.register(consumer);
}
public void msg(CommandSender sender, String msg) {
sender.sendMessage(prefix + Color.colorize(msg));
}
@Override
public boolean isInTutorial(Player player) {
return Metadata.provideForPlayer(player).has(VANISHED_KEY);
}
}
<file_sep>/src/main/java/me/lucko/welcometutorial/TutorialRunnable.java
package me.lucko.welcometutorial;
import lombok.RequiredArgsConstructor;
import me.lucko.helper.Events;
import me.lucko.welcometutorial.event.TutorialCompleteEvent;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
@RequiredArgsConstructor
public class TutorialRunnable extends BukkitRunnable {
private final Player player;
private final Location returnLocation;
private final Tutorial tutorial;
private final List<TutorialStage> stages;
private final AtomicInteger currentStage = new AtomicInteger(-1);
private final AtomicInteger progress = new AtomicInteger(-1);
@Override
public void run() {
player.setWalkSpeed(0.0f);
if (!player.isOnline()) {
player.setWalkSpeed(0.2f);
Events.call(new TutorialCompleteEvent(player, tutorial.getName(), TutorialCompleteEvent.Reason.QUIT));
cancel();
return;
}
if (progress.get() > 0) {
progress.decrementAndGet();
return;
}
currentStage.incrementAndGet();
if (currentStage.get() < 0 || currentStage.get() >= stages.size()) {
player.teleport(returnLocation);
player.setWalkSpeed(0.2f);
Events.call(new TutorialCompleteEvent(player, tutorial.getName(), TutorialCompleteEvent.Reason.FINISHED));
cancel();
return;
}
TutorialStage stage = stages.get(currentStage.get());
progress.set(stage.getWaitTime());
stage.playStage(player);
}
}
| 4dfcfe6e0e6567595f23b298b8880c0db2f83fd7 | [
"Java"
] | 3 | Java | StoneMain/WelcomeTutorial | 08ace7b8f2f96da9387a840d376282a6580c1766 | 156531f32213c2da82ef83f16f79956bbe469bae |
refs/heads/main | <file_sep># Web-scraper
Basic webscraper to get top 10 Real madrid news
This webscraper only works to scrape news from Newsnow.com, if you want to get top 10 news of any other team just replace the initial link with your teams link
<file_sep>import bs4 as bs
import urllib.request
source = urllib.request.urlopen('https://www.newsnow.co.uk/h/Sport/Football/La+Liga/Real+Madrid/Transfer+News')
soup = bs.BeautifulSoup(source, 'lxml')
count=0
urls=[]
for url in soup.find_all('a', class_="hll"):
count+=1
if 0<count<=30:
a=url.get('href')
a+='#out'
urls+=[a]
elif count>31:
break
actual_url=[]
for url1 in urls:
source1=urllib.request.urlopen(url1)
soup1= bs.BeautifulSoup(source1, 'lxml')
for url in soup1.find_all('a'):
actual_url+=[url.get('href')]
count1=0
title=[]
for url2 in actual_url:
if count1<=10:
try:
source2=urllib.request.urlopen(url2)
soup2= bs.BeautifulSoup(source2, 'lxml')
count1+=1
title+=[(soup2.title,url2)]
except:
continue
elif count1>11:
break
print(title)
| 7353fbd5b44466063a89997206b8cd378702b81c | [
"Markdown",
"Python"
] | 2 | Markdown | Vishwas-UI/Web-scraper | 7465f170979c6eedb72de6c03367fcaa8a88d91e | 2daf9c0a701d54d2141cbace31642075c009c8f6 |
refs/heads/master | <repo_name>aydinjalil/Belly-Button-Biodiversity-Plotly<file_sep>/static/js/app.js
function init(){
var selector = d3.select("#selDataset");
d3.json("../../samples.json").then((sampleNames) => {
sampleNames.names.forEach((sample) => {
selector.append("option")
.text(sample)
.property("value", sample);
});
chart(sampleNames.names[0]);
meta_data(sampleNames.names[0]);
// console.log(sampleNames.names);
});
}
function meta_data(id){
d3.json("../../samples.json").then((sampleNames)=>{
sampleNames.metadata.forEach((meta)=>{
if (meta.id === parseInt(id)) {
var div_metadata = d3.select("#sample-metadata");
div_metadata.html("");
Object.entries(meta).forEach(([key, value])=>{
var row = div_metadata.append("p");
row.text(key + ": " + value);
});
// BONUS TASK - Gauge chart
var level = meta.wfreq;
var degrees = 180 - (level*20),
radius = 0.7;
var radians = degrees * Math.PI / 180;
var x = radius*Math.cos(radians);
var y = radius*Math.sin(radians);
var mainPath = 'M -.0 -0.025 L .0 0.025 L ',
pathX = (x).toString(),
space = ' ',
pathY = (y).toString(),
pathEnd = ' Z';
var path = mainPath.concat(pathX,space,pathY,pathEnd);
var data = [{ type: 'scatter',
x: [0], y:[0],
marker: {size: 28, color:'850000'},
showlegend: false,
text: level,
hoverinfo: 'text'},
{ values: [45/8, 45/8, 45/8, 45/8, 45/8, 45/8, 45/8, 45/8, 45/8, 50],
rotation: 90,
text: ['8-9','7-8','6-7','5-6', '4-5', '3-4', '2-3',
'1-2', '0-1', ''],
textinfo: 'text',
textposition:'inside',
marker: {colors:['#84B589','rgba(14, 127, 0, .5)', '#64e764',
'#7aea7a', '#90ee90',
'#a6f1a6', '#bcf4bc',
'#d2f8d2','#e8fbe8', 'rgba(255, 255, 255, 0)',]},
labels: ['8-9','7-8','6-7','5-6', '4-5', '3-4', '2-3',
'1-2', '0-1', ''],
hoverinfo: 'label',
hole: .45,
type: 'pie',
showlegend: false
}];
var layout = {
shapes:[{
type: 'path',
path: path,
fillcolor: '850000',
line: {
color: '850000'
}
}],
title: 'Belly Button Wash Frequency',
xaxis: {zeroline:false, showticklabels:false,
showgrid: false, range: [-1, 1]},
yaxis: {zeroline:false, showticklabels:false,
showgrid: false, range: [-1, 1]}
};
Plotly.newPlot('gauge', data, layout);
};
});
});
}
function chart(id){
d3.json("../../samples.json").then((sampleNames) => {
sampleNames.samples.forEach((sample)=>{
// Bar Chart Plotly code
var x_data = [];
var y_data = [];
var labels = [];
var bubble_x = [];
switch(sample.id){
case id:
sample.otu_ids.forEach((otu_id)=>{
x_data.push("OTU " + otu_id);
});
sample.sample_values.forEach((sample_values)=>{
y_data.push(sample_values);
});
sample.otu_labels.forEach((otu_label)=>{
labels.push(otu_label);
});
sample.otu_ids.forEach((otu_id)=>{
bubble_x.push(otu_id);
});
// Separate data for bar_chart
var bar_data = [{
type: "bar",
x: y_data.slice(0,10).reverse(),
y: x_data.slice(0,10).reverse(),
mode: "markers",
text: labels.slice(0,10),
marker: {
// color: (otu.otu_ids),
size: (y_data.slice(0,10)),
width: 1
},
orientation: "h",
}];
// Separate data for bubble chart
var bubble_data = [{
type: "scatter",
y: y_data,
x: bubble_x,
mode: "markers",
text: labels,
marker: {
color: (bubble_x),
size: (y_data),
// sizemode: 'area'
},
}];
var bubble_layout = {
title: 'Bubble Chart',
showlegend: false,
height: 600,
width: 600
// xaxis: {text: "OTU_ID"}
};
// Plot bar_chart
Plotly.newPlot("bar", bar_data);
Plotly.newPlot("bubble", bubble_data);
break;
}
});
});
}
function optionChanged(new_id) {
chart(new_id);
meta_data(new_id);
};
init();
| d0d45649da63a5fa2d962884fb43dcee1fa82d97 | [
"JavaScript"
] | 1 | JavaScript | aydinjalil/Belly-Button-Biodiversity-Plotly | b1cf304cc5bc37cb434e26f3d3208e66005b42e6 | aef30aa90ae84610d7fbe3f6bdd8084f064852e6 |
refs/heads/master | <file_sep>class PagesController < ApplicationController
def home
@title = "Home"
end
def aboutus
@title = "About Us"
end
def solutions
@title = "Solutions"
end
def contactus
@title = "Contact Us"
end
def people
@title = "About Us"
end
end
| 67d078c081b71bcf2d2b2ff1e6bfc1cdf9b852df | [
"Ruby"
] | 1 | Ruby | Rajawat/web | 75a1b98ecf9670b5c785dfe518b39873cebc0fbf | 638d1cacb10a4077efcade5dadfe2cafae9f095a |
refs/heads/master | <repo_name>puppetd/-<file_sep>/js/js.js
/**
* Created by Administrator on 2016/8/30.
*/
var XC={
navUlNode: $(".nav"),
flashLeftNode: $(".flashLeft"),
flashRightNode: $(".flashRight"),
flashUlNode: $(".flash_ul"),
flashNode: $("#flash"),
flashDSpanNode:$(".flash_span"),
mianTransNode:$(".mian_trans"),
mainANode:$(".photo"),
MCimgNode:$(".MCimg"),
MCRightNode:$(".MCRight"),
MCBLeftNode: $(".MCBLeft"),
MCBRightNode: $(".MCBRight"),
MBRightUlNode: $(".MCRight"),
MBtransnNode:$(".MBtrans"),
MCbRightNode: $(".MCbRight"),
MCbLeftNode: $(".MCbLeft"),
navShowFun:function(e){
var lisNode=this.navUlNode.children("li");
var navTopNode=lisNode.children("dl");
lisNode.mouseover(function(e){
$(this).children("dl").show();
});
navTopNode.children("dd").mouseover(function(e){
$(this).children("dl").show();
})
lisNode.mouseout(function(e){
$(this).children("dl").hide();
});
navTopNode.children("dd").mouseout(function(e){
$(this).children("dl").hide();
})
},
arrowShowFun:function(){//按钮的隐藏与显示
var $this = this;
$this.flashUlNode.mouseover(function (e){
$this.flashLeftNode.show();
$this.flashRightNode.show();
});
$this.flashUlNode.mouseout(function (e){
$this.flashLeftNode.hide();
$this.flashRightNode.hide();
});
},
moveFun:function(){//点击按钮的变化
var $this=this;
var lisNode=$this.flashNode.find('li');
$this.flashLeftNode.click(function(){
var oldPos=$this.flashUlNode.find('.current').index();//之前li位置
var lastPos=$this.flashUlNode.find('li').length-1;
var curPos=oldPos==0?lastPos:oldPos-1;
$this.changeFun(oldPos,curPos,$this);
});
$this.flashRightNode.click(function(){
var oldPos=$this.flashUlNode.find('.current').index();//之前li位置
var lastPos=$this.flashUlNode.find('li').length-1;
var curPos=oldPos==lastPos?0:oldPos+1;
$this.changeFun(oldPos,curPos,$this);
});
},
spanMoveFun:function(e){//span运动
var $this=this;
var flashSpanNode=$this.flashNode.find("span");
flashSpanNode.mouseenter(function(e){
if($(this).hasClass("current")){
return;
}
var oldPos=$this.flashNode.find('.current').index();//之前li位置
var curPos=$(this).index();
$this.changeFun(oldPos,curPos,$this);
});
},
changeFun:function (oldPos,curPos,$this){//幻灯片运动
var lisNode=$this.flashNode.find('li');
var flashSpanNode=$this.flashNode.find("span");
flashSpanNode.eq(curPos).addClass("current");
flashSpanNode.eq(oldPos).removeClass("current");
lisNode.eq(curPos).addClass("current");
lisNode.eq(oldPos).removeClass("current");
lisNode.eq(curPos).stop(false,true).fadeIn("slow");
lisNode.eq(oldPos).stop(false,true).fadeOut("slow");
},
transFun:function(){//球运动
var $this=this;
var mliNode=$this.mianTransNode.find("li");
mliNode.mouseenter(function(){
if($(this).hasClass("main_Cur")){
return;
}
var oldPos=$(".main_Cur").index();
$(this).addClass("main_Cur").animate({width:"486px"},300);
mliNode.eq(oldPos).removeClass("main_Cur").animate({width:"160px"},300);
});
},
windFlash:function(){//自动切换
var $this=this;
windowDo=setInterval(function(){
var oldPos=$this.flashUlNode.find('.current').index();//之前li位置
var lastPos=$this.flashUlNode.find('li').length-1;
var curPos=oldPos==lastPos?0:oldPos+1;
$this.changeFun(oldPos,curPos,$this);
},3000);
$this.flashUlNode.mouseenter(function(){
clearInterval(windowDo);
});
$this.flashUlNode.mouseleave(function(){
windowDo=setInterval(function(){
var oldPos=$this.flashUlNode.find('.current').index();//之前li位置
var lastPos=$this.flashUlNode.find('li').length-1;
var curPos=oldPos==lastPos?0:oldPos+1;
$this.changeFun(oldPos,curPos,$this);
},3000);
});
},
BigImageFun:function(){//图片缩放
var $this=this;
var ImgNode=$this.MCimgNode.find("img");
var ImgSpanNode=$this.MCimgNode.find("span");
$this.MCimgNode.mouseenter(function(){
ImgNode.animate({width:"120%",hight:"120%",marginLeft:"-30px",marginTop:"-20px"},500);
ImgSpanNode.animate({top:"0"},500);
});
$this.MCimgNode.mouseleave(function(){
ImgNode.animate({width:"100%",hight:"100%",marginLeft:"0px",marginTop:"0px"},500);
ImgSpanNode.animate({top:"243px"},500);
});
},
CentMoveFun:function(){
var $this=this;
var MCliNode=$this.MBRightUlNode.find("li");
$this.MCBLeftNode.click(function(){
var oldPos=$this.MBRightUlNode.find('.MBt_cur').index();//之前li位置
var lastPos=$this.MBRightUlNode.find('li').length-1;
var curPos=oldPos==0?lastPos:oldPos-1;
$this.ImgChangeFun(oldPos,curPos,$this,MCliNode);
});
$this.MCBRightNode.click(function(){
var oldPos=$this.MBRightUlNode.find('.MBt_cur').index();//之前li位置
var lastPos=$this.MBRightUlNode.find('li').length-1;
var curPos=oldPos==lastPos?0:oldPos+1;
$this.ImgChangeFun(oldPos,curPos,$this,MCliNode);
});
},
ImgChangeFun:function (oldPos,curPos,$this,MCliNode){//幻灯片运动
MCliNode.eq(curPos).addClass("MBt_cur");
MCliNode.eq(oldPos).removeClass("MBt_cur");
MCliNode.eq(curPos).stop(false,true).show();
MCliNode.eq(oldPos).stop(false,true).hide();
},
ImgMoveFun:function(){
var $this=this;
var MBtransliNode=$this.MBtransnNode.find("li");
$this.MCbLeftNode.click(function(){
var oldPos=$this.MBtransnNode.find('.MBt_cur').index();//之前li位置
var lastPos=$this.MBtransnNode.find('li').length-1;
var curPos=oldPos==0?lastPos:oldPos-1;
MBtransliNode.eq(curPos).parent().prepend(MBtransliNode.eq(curPos));
MBtransliNode.eq(curPos).parent().css({marginLeft:'-202px'});
MBtransliNode.eq(curPos).parent().animate({marginLeft:"0px"},500);
});
$this.MCbRightNode.click(function(){
var oldPos=$this.MBtransnNode.find('.MBt_cur').index();//之前li位置
var lastPos=$this.MBtransnNode.find('li').length-1;
var curPos=oldPos==lastPos?0:oldPos+1;
MBtransliNode.eq(curPos).parent().animate({marginLeft:"-202px"},500,function(){
$(this).css({marginLeft:'0px'});
MBtransliNode.eq(curPos).addClass("MBt_cur");
MBtransliNode.eq(oldPos).removeClass("MBt_cur");
});
});
},
init:function(){//初始
this.navShowFun();
this.arrowShowFun();
this.moveFun();
this.spanMoveFun();
this.transFun();
this.windFlash();
this.BigImageFun();
this.CentMoveFun();
this.ImgMoveFun();
}
}
XC.init();
$('.allShowUl').isotope({
itemSelector: '.allShow li'
});
$('.showNavUl li').click(function(){
$(this).addClass('showNav_Cur').siblings('li').removeClass('showNav_Cur');
var dataValue=$(this).attr('data');
$('.allShowUl').isotope({
itemSelector: '.allShowUl li',
filter:dataValue
});
}); | b0dc762284264376e5e853baa149a41a7f294445 | [
"JavaScript"
] | 1 | JavaScript | puppetd/- | ecb513b66e172107d3651c0015c57e05b7c18fb0 | 002c7c21da8728cf453fbbc66650385572ed90fc |
refs/heads/master | <file_sep>/* a parent class reference is used to refer a child class object
*
* objects created with datatype as parent class can access only methods common to parent and child class
* that object cannot access methods present only in child class
* but that object can access method present in parent class and not in child class
*
*
*/
package udemy04_OOP_Part2_polymorphism;
public class Main {
public static void main(String[] args) {
Car car2 = new HondaCivic();
HondaCivic car3 = new HondaCivic();
car3.testmethod();
((HondaCivic) car2).testmethod();
System.out.println("our change :");
car2.testmethod();
car3.testmethod2();
System.out.println("before for loop");
for (int i=1;i<=3;i++) {
Car car1 = getcarmethod(i);
car1.printcardetails();
car1.accelerate(50);
System.out.println(car1.getName() +": accelerated to 50");
car1.brake(10);
System.out.println(car1.getName() +": brake applied - 10");
car1.accelerate(-10);
System.out.println(car1.getName() +": accelerated to -10");
System.out.println(car1.getName() +": car speed is :" +car1.getCarspeed());
//car1.printcardetails();
}
System.out.println("Test Starts Here");
Main obj = new Main();
obj.test();
}
public void test () {
//Car a = new HondaCivic();
Car a = getcarmethod(2);
a.printcardetails();
}
public static Car getcarmethod(int i) {
switch (i){
case 1:
return new DodgeCharger();
case 2:
return new HondaCivic();
case 3:
return new Car(8,"Hellcat","Red");
default:
return null;
}
}
}
//end of class
class Car {
private boolean engine;
private int cylilnders;
private String name;
private String color;
private int carspeed;
public Car(int cylinders, String name, String color) {
this.cylilnders = cylinders;
this.name = name;
this.color = color;
this.engine = true;
}
public int getCylilnders() {
return cylilnders;
}
public String getName() {
return name;
}
public void startengine() {
//this.engine = true;
System.out.println("Engine Started :" +this.engine);
}
public void accelerate(int speed) {
this.carspeed = this.carspeed + speed;
}
public void brake(int brake) {
this.carspeed -= brake;
}
public String getColor() {
return color;
}
public void printcardetails() {
System.out.println("******Printed from Car Class ->*********");
System.out.println("This is a " +this.getName() +" with " +this.getCylilnders()
+" cylinders" +", color: " +this.getColor());
}
public int getCarspeed() {
return carspeed;
}
public void testmethod() {
System.out.println("car test method");
}
}
//end of class
class DodgeCharger extends Car {
public DodgeCharger() {
super(6, "Dodge", "Billet");
}
public void printcardetails() {
System.out.println("This is a " +this.getName() +" with " +this.getCylilnders()
+" cylinders" +", color: " +this.getColor());
}
}
class HondaCivic extends Car {
public HondaCivic() {
super(4, "Honda", "Black");
}
public void testmethod() {
System.out.println("Test Method");
}
public void testmethod2() {
System.out.println("Test Method2");
}
}
| 8f446a8b9b47194beb43d54062a3bd94596fd2c6 | [
"Java"
] | 1 | Java | isas88/udemy04_OOP_Part2_polymorphism | 179a559a969898532cc9a16452f983c1c1f9dbe4 | dc36f64e438f0564faf46b0304d599342855eb73 |
refs/heads/master | <file_sep>"""jenkins_api URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from jauth.views import *
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/v1/get_token/$', get_token, name="get_token"),
url(r'^api/v1/create_job/$', create_job, name="create_job"),
url(r'^api/v1/copy_job/$', copy_job, name="copy_job"),
url(r'^api/v1/reconfig_job/$', reconfig_job, name="reconfig_job"),
url(r'^api/v1/status_job/$', status_job, name="status_job"),
url(r'^api/v1/start_build/$', start_build, name="start_build"),
url(r'^api/v1/stop_build/$', stop_build, name="stop_build"),
url(r'^api/v1/delete_job/$', delete_job, name="delete_job"),
url(r'^api/v1/create_node/$', create_node, name="create_node"),
url(r'^api/v1/enable_node/$', enable_node, name="enable_node"),
url(r'^api/v1/disable_node/$', disable_node, name="disable_node"),
url(r'^api/v1/delete_node/$', delete_node, name="delete_node"),
url(r'^api/v1/install_plugin/$', install_plugin, name="install_plugin"),
]
<file_sep>Django
djangorestframework
PyJWT
# psycopg2==2.6.2
python-jenkins<file_sep>## Jenkins API
#### All requests are POST
- sign up and get token
```
/api/v1/get_token/
{
"url":"http://127.0.0.1:8080",
"username": "demo",
"password": "<PASSWORD>"
}
```
- create a job
```
/api/v1/create_job/
header: token:<token>
{
"name":"empty-2",
"config_xml":"<xml></xml>"
}
```
- delete a job
```
/api/v1/delete_job/
header: token:<token>
{
"name":"empty"
}
```
- copy a job
```
/api/v1/copy_job/
header: token:<token>
{
"from_name":"empty-1",
"to_name":"empty-3"
}
```
- reconfigure a job
```
/api/v1/reconfig_job/
header: token:<token>
{
"name":"empty-1",
"config_xml":"<xml></xml>"
}
```
- get status of a job
```
/api/v1/status_job/
header: token:<token>
{
"name":"first_job",
"depth": 1,
"fetch_all_builds":true
}
```
- start build a job
```
/api/v1/start_build/
header: token:<token>
{
"name":"empty-1",
"params1":{
"first":1,
"second":2
}
}
```
- stop build a job
```
/api/v1/stop_build/
header: token:<token>
{
"name":"empty-1",
"build_number":3
}
```
- create a node
```
/api/v1/create_node/
header: token:<token>
{
"name":"node-3",
"numExecutors":5,
"nodeDescription":"nodeDescription",
"labels":"labels",
"exclusive":true
}
```
- delete a node
```
/api/v1/delete_node/
header: token:<token>
{
"name":"node-1"
}
```
- disable a node
```
/api/v1/disable_node/
header: token:<token>
{
"name":"node-2"
}
```
- install plugin
```
/api/v1/install_plugin/
header: token:<token>
{
"name":"CCM Plug-in",
"include_dependencies":false
}
```
<file_sep>import jenkins
import random
import hashlib
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User
from django.contrib.auth import login
from jauth.models import *
import logging
log = logging.getLogger(__name__)
@api_view(["POST"])
def get_token(request):
url = request.data.get('url')
username = request.data.get('username')
password = request.data.get('password')
log.debug('get_token is called with url:{}, username:{}, password:{}' \
.format(url, username, password))
server = jenkins.Jenkins(url, username=username, password=<PASSWORD>)
tag = abs(hash(url)) % (10 ** 6)
try:
user_ = server.get_whoami()
user, created = User.objects.get_or_create(username=username+str(tag), first_name=password, last_name=url)
if created:
user.set_password(<PASSWORD>)
user.save()
token = Token.objects.create(user=user)
log.info('Token is created')
else:
token = Token.objects.get(user=user)
log.info('Token is retrieved')
except Exception, e:
log.debug(e)
return Response({"status": "failed",
"msg": "The credential or server url is not correct!"})
return Response({"status": "success",
"token": token.key})
def login_only(function):
def wrap(request, *args, **kwargs):
token = request.META.get('HTTP_TOKEN')
token = Token.objects.filter(key=token).first()
if token:
login(request, token.user)
return function(request, *args, **kwargs)
return Response({"status": "failed", "msg": "Auth token is invalid!"})
wrap.__doc__=function.__doc__
wrap.__name__=function.__name__
return wrap
def get_server(request):
url = request.user.last_name
username = request.user.username[:-6]
password = request.user.first_name
return jenkins.Jenkins(url, username=username, password=<PASSWORD>)
@api_view(["POST"])
@login_only
def create_job(request):
server = get_server(request)
name = request.data.get('name', '')
config_xml = request.data.get('config_xml') or jenkins.EMPTY_CONFIG_XML
log.debug('create_job is called with name:{}, config_xml:{}' \
.format(name, config_xml))
try:
server.create_job(name, config_xml)
# jobs = server.get_jobs()
except Exception, e:
log.debug(e)
return Response({"status": "failed",
"msg": e.message or "Invalid job name"})
log.info('The job:{} is created successfully'.format(name))
return Response({"status": "success"})
@api_view(["POST"])
@login_only
def delete_job(request):
server = get_server(request)
name = request.data.get('name', '')
log.debug('delete_job is called with name:{}'.format(name))
try:
server.delete_job(name)
except Exception, e:
log.debug(e)
return Response({"status": "failed",
"msg": e.message})
log.info('The job:{} is deleted successfully'.format(name))
return Response({"status": "success"})
@api_view(["POST"])
@login_only
def copy_job(request):
server = get_server(request)
from_name = request.data.get('from_name', '')
to_name = request.data.get('to_name', '')
log.debug('copy_job is called with from_name:{}, to_name:{}'.format(from_name, to_name))
if not server.get_job_name(from_name):
return Response({"status": "failed",
"msg": "Source job does not exist."})
if server.get_job_name(to_name):
return Response({"status": "failed",
"msg": "Destination job already exists."})
try:
server.copy_job(from_name, to_name)
except Exception, e:
log.debug(e)
return Response({"status": "failed",
"msg": e.message or "Invalid job names"})
log.info('The job:{} is copyed into job:{} successfully'.format(from_name, to_name))
return Response({"status": "success"})
@api_view(["POST"])
@login_only
def reconfig_job(request):
server = get_server(request)
name = request.data.get('name', '')
config_xml = request.data.get('config_xml') or jenkins.RECONFIG_XML
log.debug('reconfig_job is called with name:{}, config_xml:{}' \
.format(name, config_xml))
try:
server.reconfig_job(name, config_xml)
jobs = server.get_jobs()
except Exception, e:
log.debug(e)
return Response({"status": "failed",
"msg": e.message or "Invalid job name"})
log.info('The job:{} is reconfigured successfully'.format(name))
return Response({"status": "success", "jobs": jobs})
@api_view(["POST"])
@login_only
def status_job(request):
server = get_server(request)
name = request.data.get('name', '')
depth = int(request.data.get('depth', 0))
fetch_all_builds = request.data.get('fetch_all_builds', False)
log.debug('status_job is called with name:{}, depth:{}, fetch_all_builds:{}' \
.format(name, depth, fetch_all_builds))
try:
info = server.get_job_info(name, depth=depth, fetch_all_builds=fetch_all_builds)
except Exception, e:
log.debug(e)
return Response({"status": "failed",
"msg": e.message or "Invalid job name"})
log.info('The job ({}) status is retrieved successfully'.format(name))
return Response({"status": "success", "job_info": info})
@api_view(["POST"])
@login_only
def start_build(request):
server = get_server(request)
name = request.data.get('name', '')
params = request.data.get('params')
log.debug('start_build is called with name:{}, params:{}' \
.format(name, params))
try:
next_build_number = server.get_job_info(name)['nextBuildNumber']
server.build_job(name, params)
except Exception, e:
log.debug(e)
return Response({"status": "failed",
"msg": e.message or "Invalid job name"})
log.info('The build of the job ({}) is started successfully'.format(name))
return Response({"status": "success", "build_number": next_build_number})
@api_view(["POST"])
@login_only
def stop_build(request):
server = get_server(request)
name = request.data.get('name', '')
number = int(request.data.get('build_number'))
log.debug('stop_build is called with name:{}, number:{}' \
.format(name, number))
try:
is_building = server.get_build_info(name, number)
if not is_building.get('building'):
return Response({"status": "success", "msg": "The build already stoped"})
server.stop_build(name, number)
except Exception, e:
log.debug(e)
return Response({"status": "failed",
"msg": e.message})
log.info('The build of the job ({}) is stoped successfully'.format(name))
return Response({"status": "success", "msg": "build stoped"})
@api_view(["POST"])
@login_only
def create_node(request):
server = get_server(request)
name = request.data.get('name', '')
numExecutors = request.data.get('numExecutors', 2)
nodeDescription = request.data.get('nodeDescription')
labels = request.data.get('labels')
exclusive = request.data.get('exclusive', False)
log.debug('create_node is called with name:{}, numExecutors:{}, nodeDescription:{}, labels:{}, exclusive:{}' \
.format(name, numExecutors, nodeDescription, labels, exclusive))
try:
# create node with parameters
# params = {
# 'port': '22',
# 'username': 'juser',
# 'credentialsId': '<PASSWORD>',
# 'host': 'my.jenkins.slave1'
# }
server.create_node(
name,
numExecutors=numExecutors,
nodeDescription=nodeDescription,
# remoteFS='/home/juser',
labels=labels,
exclusive=exclusive
# launcher=jenkins.LAUNCHER_SSH,
# launcher_params=params
)
nodes = server.get_nodes()
except Exception, e:
log.debug(e)
return Response({"status": "failed",
"msg": e.message})
log.info('The node:{} is created successfully'.format(name))
return Response({"status": "success", "nodes": nodes})
@api_view(["POST"])
@login_only
def delete_node(request):
server = get_server(request)
name = request.data.get('name', '')
log.debug('delete_node is called with name:{}'.format(name))
try:
server.delete_node(name)
nodes = server.get_nodes()
except Exception, e:
log.debug(e)
return Response({"status": "failed",
"msg": e.message})
log.info('The node:{} is deleted successfully'.format(name))
return Response({"status": "success", "nodes": nodes})
@api_view(["POST"])
@login_only
def enable_node(request):
server = get_server(request)
name = request.data.get('name', '')
log.debug('enable_node is called with name:{}'.format(name))
try:
server.enable_node(name)
node_config = server.get_node_info(name)
except Exception, e:
log.debug(e)
return Response({"status": "failed",
"msg": e.message})
log.info('The node:{} is enabled successfully'.format(name))
return Response({"status": "success", "node_config": node_config})
@api_view(["POST"])
@login_only
def disable_node(request):
server = get_server(request)
name = request.data.get('name', '')
log.debug('disable_node is called with name:{}'.format(name))
try:
server.disable_node(name)
node_config = server.get_node_info(name)
except Exception, e:
log.debug(e)
return Response({"status": "failed",
"msg": e.message})
log.info('The node:{} is disabled successfully'.format(name))
return Response({"status": "success", "node_config": node_config})
@api_view(["POST"])
@login_only
def install_plugin(request):
server = get_server(request)
name = request.data.get('name', '')
include_dependencies = request.data.get('include_dependencies', True)
log.debug('install_plugin is called with name:{}, include_dependencies:{}' \
.format(name, include_dependencies))
try:
info = server.install_plugin(name, include_dependencies=include_dependencies)
except Exception, e:
log.debug(e)
return Response({"status": "failed",
"msg": e.message})
log.info('The plugin:{} is installed successfully'.format(name))
return Response({"status": "success", "restart": info})
| ebe13dbc3b140c4aa9ddad98968b673722cf349d | [
"Markdown",
"Python",
"Text"
] | 4 | Python | mazeit/jenkins-api | ecb73a3a73ae4ccf0dacad9b4382dc77b4d41fa7 | cc99dcf774492455dbb61df31cf469848c758c88 |
refs/heads/master | <repo_name>ganeshbhargav/fakeNoteDetection<file_sep>/detect_fake_note.py
# coding: utf-8
# In[1]:
import pandas as pd
# In[2]:
data = pd.read_csv('bank_note_data.csv')
# In[3]:
data.head()
# ## EDA
# In[4]:
import seaborn as sns
#get_ipython().magic('matplotlib inline')
# In[5]:
sns.countplot(x='Class',data=data)
# In[6]:
sns.pairplot(data,hue='Class')
# ## Data Preparation
# ### Standard Scaling
#
# **
# In[7]:
from sklearn.preprocessing import StandardScaler
# In[8]:
scaler = StandardScaler()
# In[9]:
scaler.fit(data.drop('Class',axis=1))
# In[10]:
scaled_features = scaler.fit_transform(data.drop('Class',axis=1))
# In[11]:
df_feat = pd.DataFrame(scaled_features,columns=data.columns[:-1])
df_feat.head()
# ## Train Test Split
#
#
# In[12]:
X = df_feat
# In[13]:
y = data['Class']
# In[14]:
X = X.as_matrix()
y = y.as_matrix()
# In[15]:
from sklearn.model_selection import train_test_split
# In[16]:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
# In[17]:
import tensorflow.contrib.learn as learn
import tensorflow as tf
# In[18]:
feature_columns = tf.contrib.learn.infer_real_valued_columns_from_input(X_train)
classifier = learn.DNNClassifier(feature_columns=feature_columns,hidden_units=[10, 20, 10], n_classes=2)
# In[19]:
classifier.fit(X_train, y_train, steps=200, batch_size=20)
# ## Model Evaluation
#
note_predictions = classifier.predict(X_test)
#Accuracy
accuracy_score = classifier.evaluate(x=X_test,
y=y_test)["accuracy"]
print('Accuracy: {0:f}'.format(accuracy_score))
#correct_predictions = tf.cast(tf.equal(tf.argmax(note_predictions, 1), tf.argmax(y, 1)), tf.float32)
#accuracy = tf.reduce_mean(correct_predictions)
#print("Accuracy:", accuracy.eval(feed_dict={x: X_test, y: y_test}))
"""
test_input_fn = tf.estimator.inputs.numpy_input_fn(
x=input(y_test)[0:3],
y=input(y_test)[4],
num_epochs=1,
shuffle=False
)
"""
#accuracy_score = classifier.evaluate(input_fn=test_input_fn)[“accuracy”]
#print(“Test Accuracy: {0:f}%”.format(accuracy_score*100))
# In[21]:
from sklearn.metrics import classification_report,confusion_matrix
import numpy as np
data=np.array(list(note_predictions))
# In[22]:
print(confusion_matrix(y_test,data))
# In[23]:
print(classification_report(y_test,data))
# ## Comparison
#
# In[24]:
from sklearn.ensemble import RandomForestClassifier
# In[25]:
rfc = RandomForestClassifier(n_estimators=200)
# In[26]:
rfc.fit(X_train,y_train)
# In[27]:
rfc_preds = rfc.predict(X_test)
#Prediction
print(rfc_preds)
print(X_test)
# In[28]:
print(classification_report(y_test,rfc_preds))
# In[29]:
print(confusion_matrix(y_test,rfc_preds))
#accuracy
<file_sep>/README.md
# Fake_Note_Detection
Fake Note Detection using TensorFlow in Python
I used the [Bank Authentication Data Set](https://archive.ics.uci.edu/ml/datasets/banknote+authentication) from the UCI repository.
# Exploratory data analysis

# Model Evaluation

| c9af7f795aeb6ddc77ec349014d47e4b36463e94 | [
"Markdown",
"Python"
] | 2 | Python | ganeshbhargav/fakeNoteDetection | 7ab2fdd45f4c930f0d76d6df38f8ad425253acc8 | ec290f26fbdfc712e0df7f0eb469852ad5811ec7 |
refs/heads/master | <repo_name>jindalatul/Vagrant-config-for-local-development<file_sep>/bootstrap.sh
# Shell Script named bootstrap.sh
#!/usr/bin/env bash
#assure that your system is updated
#Add Proxy for temprary automation
#mysql Password is <PASSWORD>
export http_proxy=http://domain.com:port
export https_proxy=https://domain.com:port
apt-get -y update
# install LAMP Stack
apt-get install -y apache2
apt-get install -y php5
#install required PHP modules
apt-get install -y libapache2-mod-php5 php5-mcrypt php5-mysql
apt-get install -y php5-curl php5-gd php5-imagick php5-memcache
apt-get install -y php5-pspell php5-recode php5-xmlrpc php5-xsl
apt-get install -y unzip
apt-get install -y gunzip
apt-get install -y git
export DEBIAN_FRONTEND="noninteractive"
debconf-set-selections <<< "mariadb-server mysql-server/root_password password <PASSWORD>"
debconf-set-selections <<< "mariadb-server mysql-server/root_password_again password <PASSWORD>"
apt-get install -y mariadb-server mariadb-client
a2enmod rewrite
echo "<?php phpinfo();?>" >> /var/www/html/info.php
mkdir /etc/apache2/ssl
cd /etc/apache2/ssl
openssl genrsa -out stage-iot.dev.key 2048
openssl req -new -x509 -key domain.key -out domain.cer -days 3650 -subj /CN=domain.com
a2enmod ssl
service apache2 restart
sudo cp /vagrant/provision/apache2/default.conf /etc/apache2/sites-available/default.conf
sudo chmod 644 /etc/apache2/sites-available/default.conf
sudo ln -s /etc/apache2/sites-available/site.conf /etc/apache2/sites-enabled/default.conf
echo "Sucessfully installed - open your browser and type ip address of this machine and locate info.php";
<file_sep>/README.md
# Vagrant-configuration-for-local-development
Building LAMP Stack using vagrant on your local enviornment for continous development and integration DevOPS
| 057ad7cdbae7d75bfbdb5ee97de07f82eee3c0ba | [
"Markdown",
"Shell"
] | 2 | Shell | jindalatul/Vagrant-config-for-local-development | 2aca0aea0061294a85339c0ad2f17e12931e306b | 7ba16961cd93928b4094a63a5daeed90a686e9a1 |
refs/heads/master | <repo_name>FritzFranz/ExData_Plotting1<file_sep>/plot1.R
# plot1.R
filename = "./data/household_power_consumption.txt"
# read data, use some optimizations
d0 = read.table(filename,quote="",
comment.char="",
colClasses=c("character","character",rep("numeric",7)),
na.strings="?", # recognize as NA
nrows=2100000,sep=";", header=T)
dim(d0)
# get and convert date fields for extractin
date0 = as.Date(d0$Date,"%d/%m/%Y") ## convert to yyyy-mm-dd
date0c = as.character(date0) ## convert to character
# extract relevant data - 2880 records (1 per minute)
ds = d0[date0c >= "2007-02-01" & date0c <= "2007-02-02",]
# create png plots 480x480
png(filename="plot1.png",
width=480,height=480)
hist(ds$Global_active_power,
col="red",
xlab="Global Active Power (kilowatts)",
ylab="Frequency count",
main="Global Active Power")
dev.off()
<file_sep>/plot2.R
# plot2.R
filename = "./data/household_power_consumption.txt"
# read data, use some optimizations
d0 = read.table(filename,quote="",
comment.char="",
colClasses=c("character","character",rep("numeric",7)),
na.strings="?", # recognize as NA
nrows=2100000,
sep=";", header=T)
# get and convert dates for needed selection
date0 = as.Date(d0$Date,"%d/%m/%Y") ## convert to yyyy-mm-dd
date0c = as.character(date0) ## convert to character
# extract relevant data - 2880 records (1 per minute)
ds = d0[date0c >= "2007-02-01" & date0c <= "2007-02-02",]
# combine date+time and convert to POSIXlt
ds$date_time_0 = paste(as.character(ds$Date), as.character(ds$Time))
ds$date_time_1 = as.POSIXlt(strptime(ds$date_time_0, "%d/%m/%Y %H:%M:%S"))
# Plot 2
png(filename="plot2.png",
width=480,height=480)
par(mar=c(6,4,2,1)+0.1)
plot(x=ds$date_time_1,
y=ds$Global_active_power,
type="l",
sub="Note: Weekday labels are in German due to R configuration",
cex.sub=0.8,
xlab=" ",
ylab="Global Active Power (kilowatts)")
dev.off()
<file_sep>/plot4.R
# plot1.R
filename = "./data/household_power_consumption.txt"
# read data, use some optimizations
d0 = read.table(filename,quote="",
comment.char="",
colClasses=c("character","character",rep("numeric",7)),
na.strings="?", # recognize as NA
nrows=2100000, # estimate rows -> storage
sep=";", header=T)
# get and convert dates for needed selection
date0 = as.Date(d0$Date,"%d/%m/%Y") ## convert to yyyy-mm-dd
date0c = as.character(date0) ## convert to character
# extract relevant data - 2880 records (1 per minute)
ds = d0[date0c >= "2007-02-01" & date0c <= "2007-02-02",]
# combine date+time and convert to POSIXlt
ds$date_time_0 = paste(as.character(ds$Date), as.character(ds$Time))
ds$date_time_1 = as.POSIXlt(strptime(ds$date_time_0, "%d/%m/%Y %H:%M:%S"))
#---------------------------------------------------
# Plot 4: combine all plots
#----------------------------------------------------
png(filename="plot4.png",
width=480,height=480)
par(mfrow=c(2,2))
par(oma=c(2,0,0,0))
# Left upper
par(mar=c(4,4,1,1)+0.1)
# part 1
plot(x=ds$date_time_1,
y=ds$Global_active_power,
type="l",
xlab=" ",
ylab="Global Active Power (kilowatts)")
# part 2
plot(x=ds$date_time_1,
y=ds$Voltage,
type="l",
xlab="datetime",
ylab="Voltage")
# Plot 3
plot(x=ds$date_time_1,
y=ds$Sub_metering_1, # determines y-axis
type="l",
col="black",
xlab=" ",
ylab="Energy sub metering ")
points(x=ds$date_time_1,
y=ds$Sub_metering_2,
type="l",
col="red")
points(x=ds$date_time_1,
y=ds$Sub_metering_3,
type="l",
col="blue")
legend("topright",
legend=c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"),
lty=1,lwd=1,
cex=0.7,
col=c("black", "red", "blue"))
# plot 4
plot(x=ds$date_time_1,
y=ds$Global_reactive_power,
type="l",
xlab="datetime",
ylab="Global Reactive Power")
mtext("datetime - Weekdays are in German due to R config", outer=T,line=1,side=1)
# reset
dev.off()
par(mfrow=c(1,1))
<file_sep>/plot3.R
# plot3.R
filename = "./data/household_power_consumption.txt"
# read data, use some optimizations
d0 = read.table(filename,quote="",
comment.char="",
colClasses=c("character","character",rep("numeric",7)),
na.strings="?", # recognize as NA
nrows=2100000, # estimate rows -> storage
sep=";", header=T)
# get and convert dates for needed selection
date0 = as.Date(d0$Date,"%d/%m/%Y") ## convert to yyyy-mm-dd
date0c = as.character(date0) ## convert to character
# extract relevant data - 2880 records (1 per minute)
ds = d0[date0c >= "2007-02-01" & date0c <= "2007-02-02",]
# create png plots 480x480
# combine date+time and convert to POSIXlt
ds$date_time_0 = paste(as.character(ds$Date), as.character(ds$Time))
ds$date_time_1 = as.POSIXlt(strptime(ds$date_time_0, "%d/%m/%Y %H:%M:%S"))
# Plot 3
png(filename="plot3.png",
width=480,height=480)
par(mar=c(6,4,1,1)+0.1)
plot(x=ds$date_time_1,
y=ds$Sub_metering_1, # determines y-axis
type="l",
sub="Note: Weekday labels are in German due to R configuration",
cex.sub=0.8, # reduce font for sub-title
col="black",
xlab=" ",
ylab="Energy sub metering ")
points(x=ds$date_time_1,
y=ds$Sub_metering_2,
type="l",
col="red")
points(x=ds$date_time_1,
y=ds$Sub_metering_3,
type="l",
col="blue")
legend("topright",
legend=c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"),
lty=1,lwd=1,
cex=0.7,
col=c("black", "red", "blue"))
dev.off()
| 79449082399e3f10e14761fc70f71ccfdf95e9e7 | [
"R"
] | 4 | R | FritzFranz/ExData_Plotting1 | 67f1cbfffa3152ba11011ad058f6e686fefeab9d | 328abbdbb4574eb4dc783cdc90c0e148a8311e82 |
refs/heads/master | <file_sep>package com.system.future.service.impl;
import com.system.future.domain.ProjectPrototype;
import com.system.future.service.ProjectPrototypeService;
import org.springframework.stereotype.Service;
@Service("projectPrototypeService")
public class ProjectPrototypeServiceImpl implements ProjectPrototypeService {
@Override
public Iterable<ProjectPrototype> findAll() {
return null;
}
}
<file_sep>package com.system.future.service;
import com.system.future.entity.UserDO;
public interface UserService extends BaseService<UserDO> {
}
<file_sep>package com.system.future.vo;
import lombok.Data;
import java.io.Serializable;
@Data
public class TemplateVO implements Serializable {
private Long id;
private Long sshKeyId;
private Long projectId;
private Long inventoryId;
private Long repositoryId;
private Long environmentId;
private String alias;
private String playbook;
private String arguments;
private Boolean overrideArgs;
}
<file_sep>baseUrl=http://192.168.127.12/api/
auth_code=bearer ea26cdr_ftazqk2au2fknbn9r1_zq07id38wfdmfudu=<file_sep>package com.system.future.service;
import com.system.future.entity.InstanceDO;
/**
*
*/
public interface InstanceService extends BaseService<InstanceDO> {
}
<file_sep># future
## H2 database url
http://localhost:8080/h2-console
<file_sep>package com.system.future.katharsis.repository;
import com.system.future.domain.Demoable;
import com.system.future.service.RestService;
import io.katharsis.queryspec.QuerySpec;
import io.katharsis.repository.ResourceRepositoryBase;
import io.katharsis.resource.list.ResourceList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* Created by gzhang061 on 5/15/18.
*/
@Component
public class DemoableRepositoryImpl extends ResourceRepositoryBase<Demoable, Long> {
@Autowired
private RestService restService;
public DemoableRepositoryImpl() {
super(Demoable.class);
}
@Override
public <S extends Demoable> S create(S resource) {
resource.setId(0L);
// System.out.println(resource.getServerKey());
return resource;
}
@Override
public ResourceList<Demoable> findAll(QuerySpec querySpec) {
return querySpec.apply(restService.findAll());
}
}<file_sep>package com.system.future.controller;
import com.system.future.entity.UserDO;
import com.system.future.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public void get(@PathVariable("id") Long id) {
if (log.isDebugEnabled()) {
log.debug("Get User by id:" + id);
}
userService.get(id);
}
@GetMapping("/listAll")
public void listAll() {
userService.listAll();
}
@PostMapping("/add")
public void add(UserDO record) {
userService.save(record);
}
@PostMapping("/{id}")
public void update(UserDO record, @PathVariable("id") Long id) {
userService.update(record, id);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable("id") Long id) {
userService.delete(id);
}
}
<file_sep>package com.system.future.service.impl;
import com.system.future.dao.UserDao;
import com.system.future.entity.UserDO;
import com.system.future.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public List<UserDO> listAll() {
return userDao.findAll();
}
@Override
public UserDO get(Long id) {
return userDao.findOne(id);
}
@Override
@Transactional
public void save(UserDO record) {
userDao.save(record);
}
@Override
@Transactional
public void delete(Long id) {
userDao.delete(id);
}
@Override
@Transactional
public void update(UserDO record, Long id) {
userDao.save(record);
}
}
<file_sep>package com.system.future.service;
import com.system.future.domain.Demoable;
import io.katharsis.resource.list.ResourceList;
import java.util.List;
public interface RestService {
List<Demoable> findAll();
}
<file_sep>package com.system.future.domain;
import io.katharsis.resource.annotations.JsonApiId;
import io.katharsis.resource.annotations.JsonApiResource;
import lombok.Data;
@JsonApiResource(type = "project-prototypes")
@Data
public class ProjectPrototype {
@JsonApiId
private Long id;
private String name;
private String owner;
private String description;
private String version;
private Long semaphoreProjectId;
private Long demoDeploymentTaskId;
}
<file_sep>package com.system.future.controller;
import com.system.future.entity.InstanceDO;
import com.system.future.service.InstanceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/instance")
@Slf4j
public class InstanceController {
@Autowired
private InstanceService instanceService;
@GetMapping("/{id}")
public void get(@PathVariable("id") Long id) {
if (log.isDebugEnabled()) {
log.debug("Get Instance by id:" + id);
}
instanceService.get(id);
}
@GetMapping("/listAll")
public void listAll() {
instanceService.listAll();
}
@PostMapping("/add")
public void add(InstanceDO record) {
instanceService.save(record);
}
@PostMapping("/{id}")
public void update(InstanceDO record,@PathVariable("id") Long id) {
instanceService.update(record, id);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable("id") Long id) {
instanceService.delete(id);
}
}
<file_sep>package com.system.future.dao;
import com.system.future.entity.InstanceDO;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class InstanceDaoTest {
@Autowired
private InstanceDao instanceDao;
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testFindByServerIP() {
final String testIP = "192.168.1.1";
List<InstanceDO> records = instanceDao.findByServerIP(testIP);
}
} | 14a206ba95b2ef745c9c4e05fb7819e309bf053a | [
"Markdown",
"Java",
"INI"
] | 13 | Java | deanwang1943/future | 1d9262693296b3ff6171556f570611390320fbc5 | 136b175d9bb3b533ac913593c63ef0ff79128f1e |
refs/heads/master | <repo_name>cricarba/Refactoring<file_sep>/Cricarba.Refactoring/Cricarba.Refactoring/SOLID/4.I/Bien/ICalcularImpuesto.cs
using Cricarba.Refactoring.Dominio;
namespace Cricarba.Refactoring.SOLID._4.I.Bien
{
interface ICalcularImpuesto
{
double CalcularImpuesto(Producto producto);
}
}
<file_sep>/Cricarba.Refactoring/Cricarba.Refactoring/SOLID/4.I/Mal/Impuesto19.cs
using Cricarba.Refactoring.Dominio;
using System;
using System.Collections.Generic;
using System.Text;
namespace Cricarba.Refactoring.SOLID._4.I.Mal
{
class Impuesto19 : IImpuesto
{
public double CalcularImpuesto(Producto producto)
{
return producto.Valor * 19 / 100;
}
public IEnumerable<int> CargarImpuestos()
{
throw new NotImplementedException();
}
public bool GuardarImpuesto()
{
throw new NotImplementedException();
}
}
}
<file_sep>/Cricarba.Refactoring/Cricarba.Refactoring/SOLID/4.I/Bien/IImpuestoRepositorio.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Cricarba.Refactoring.SOLID._4.I.Bien
{
interface IImpuestoRepositorio
{
IEnumerable<int> CargarImpuestos();
bool GuardarImpuesto();
}
}
<file_sep>/Cricarba.Refactoring/Cricarba.Refactoring/SOLID/2.O/Mal/Impuesto.cs
using Cricarba.Refactoring.Dominio;
namespace Cricarba.Refactoring.SOLID._2.O.Mal
{
class Impuesto
{
public double ObtenerImpuesto(Producto producto)
{
if (producto.TipoImpuesto == 1)
return producto.Valor * 19 / 100;
else if (producto.TipoImpuesto == 2)
return producto.Valor * 10 / 100;
else if (producto.TipoImpuesto == 3)
return producto.Valor * 8 / 100;
return 0;
}
}
}
<file_sep>/Cricarba.Refactoring/Cricarba.Refactoring/SOLID/1.S/Bien/Impuesto.cs
using Cricarba.Refactoring.Dominio;
namespace Cricarba.Refactoring.SOLID.S.Bien
{
public class Impuesto
{
public double ObtenerImpuesto(Producto producto)
{
return producto.Valor * 19 / 100;
}
}
}
<file_sep>/Cricarba.Refactoring/Cricarba.Refactoring/SOLID/2.O/Bien/Impuesto8.cs
using System;
using System.Collections.Generic;
using System.Text;
using Cricarba.Refactoring.Dominio;
namespace Cricarba.Refactoring.SOLID._2.O.Bien
{
class Impuesto8 : ICalcularImpuesto
{
public double ObtenerImpuesto(Producto producto)
{
return producto.Valor * 8 / 100;
}
}
}
<file_sep>/README.md
# **Guía de programación**
## **Consideraciones principales**
- Siga los principios básicos de desarrollo de software KISS, YAGNI y DRY
- El idioma en que se escribirá el software debe ser el idioma que mejor maneje su equipo, si todos haban español y no todos hablan ingles, el código debe estar escrito en español
- El estilo de escritura a usar es CamelCase
- Existen dos tipos de CamelCase
o UpperCamelCase, la primera letra de cada palabra en mayúscula
o lowerCamelCase, igual que la anterior pero la primera palabra es toda en minúscula.
### **Nombramiento de objetos**
En esta sección se describe la forma como se deben nombrar generalmente los componentes de la aplicación
**Convenciones generales**
- No use guiones “ - “ ni guiones bajos “ _ “ para separar las palabras
- No use prefijos para la elección de nombres
- Utilice nombres que se puedan pronunciar
- No use abreviaturas o acrónimos para la elección de nombres
- Elija nombres que reflejen su propósito dentro del software
**Convenciones especificas**
**Clases/Interfaces**
• Los nombres de interfaces deben ir antecedidas de I
• Los nombres de clase deben ser sustantivos en UpperCamelCase
• Los nombres de clase deben ser en singular
**Enumerados**
• Los enumerados se deben crear en un archivo independiente por cada enumerado
enumerados deben contener su debida descripción
• Los valores del enumerado deben ser escritos en UpperCamelCase
• Los nombres de clases para DTOs (Data Transfert Object) deben terminar en Dto.
• Los objetos de capa de repositorio que heredan de la clase Repositorio<T> deben terminar en Repositorio.
• Los objetos de capa de repositorio que heredan de la clase DbContext deben terminar en Contexto.
**Métodos**
• Los nombres de los métodos deben ser verbos en UpperCamelCase
• Los nombres de los métodos deben reflejar lo que hacen en su implementación
• Los parámetros de los métodos no deben ser superar más de 3 tipos primitivos, si requiere más de 3 parámetros primitivos haga un DTO
• Los nombres de los parámetros deben ser en lowerCamelCase
**Variables**
- Los nombres de las variables locales deben se lowerCamelCase
- Las variables globales deben ser privadas y nombradas lowerCamelCase antecedidas de “_”
- Los valores constantes o “quemados” deben ser creados como constantes globales dentro del archivo a clase que se esté utilizando, si la constante se usa en más de un archivo se debe crear una clase para definir estas constantes.
<file_sep>/Cricarba.Refactoring/Cricarba.Refactoring/SOLID/1.S/Mal/Factura.cs
using Cricarba.Refactoring.Dominio;
using System;
using System.Collections.Generic;
namespace Cricarba.Refactoring.SOLID.S.Mal
{
public class Factura
{
public List<Producto> Productos { get; set; }
bool CrearFactura()
{
var total = 0d;
foreach (var producto in Productos)
{
Console.WriteLine($"{producto.Nombre}");
producto.Valor += ObtenerImpuesto(producto);
total += producto.Valor;
}
return true;
}
double ObtenerImpuesto(Producto producto)
{
return producto.Valor * 19 / 100;
}
}
}
<file_sep>/Cricarba.Refactoring/Cricarba.Refactoring.Dominio/Cliente.cs
using System;
namespace Cricarba.Refactoring.Dominio
{
public class Cliente
{
public string Nombre { get; set; }
public int Tipo { get; set; }
}
}
<file_sep>/Cricarba.Refactoring/Cricarba.Refactoring/SOLID/4.I/Bien/Impuesto19.cs
using Cricarba.Refactoring.Dominio;
namespace Cricarba.Refactoring.SOLID._4.I.Bien
{
class Impuesto19 : ICalcularImpuesto
{
public double CalcularImpuesto(Producto producto)
{
return producto.Valor * 19 / 100;
}
}
}
<file_sep>/Cricarba.Refactoring/Cricarba.Refactoring/SOLID/4.I/Mal/Impuesto.cs
using System;
using System.Collections.Generic;
using System.Text;
using Cricarba.Refactoring.Dominio;
namespace Cricarba.Refactoring.SOLID._4.I.Mal
{
class Impuesto : IImpuesto
{
public double CalcularImpuesto(Producto producto)
{
throw new NotImplementedException();
}
public IEnumerable<int> CargarImpuestos()
{
return new List<int>();
}
public bool GuardarImpuesto()
{
return true;
}
}
}
<file_sep>/Cricarba.Refactoring/Cricarba.Refactoring/SOLID/2.O/Bien/ICalcularImpuesto.cs
using Cricarba.Refactoring.Dominio;
namespace Cricarba.Refactoring.SOLID._2.O.Bien
{
interface ICalcularImpuesto
{
double ObtenerImpuesto(Producto producto);
}
}
<file_sep>/Cricarba.Refactoring/Cricarba.Refactoring/SOLID/4.I/Mal/IImpuesto.cs
using Cricarba.Refactoring.Dominio;
using System.Collections.Generic;
namespace Cricarba.Refactoring.SOLID._4.I.Mal
{
interface IImpuesto
{
double CalcularImpuesto(Producto producto);
IEnumerable<int> CargarImpuestos();
bool GuardarImpuesto();
}
}
<file_sep>/Cricarba.Refactoring/Cricarba.Refactoring/SOLID/2.O/Bien/Factura.cs
using Cricarba.Refactoring.Dominio;
using System;
using System.Collections.Generic;
using System.Text;
namespace Cricarba.Refactoring.SOLID._2.O.Bien
{
class Factura
{
public List<Producto> Productos { get; set; }
public Dictionary<int,ICalcularImpuesto> DiccionarioImpuestos { get; set; }
public Factura()
{
DiccionarioImpuestos = new Dictionary<int, ICalcularImpuesto>();
DiccionarioImpuestos.Add(1, new Impuesto19());
DiccionarioImpuestos.Add(2, new Impuesto10());
DiccionarioImpuestos.Add(3, new Impuesto8());
}
bool CrearFactura()
{
var total = 0d;
foreach (var producto in Productos)
{
Console.WriteLine($"{producto.Nombre}");
total -= DiccionarioImpuestos[producto.TipoImpuesto].ObtenerImpuesto(producto);
}
return true;
}
}
}
<file_sep>/Cricarba.Refactoring/Cricarba.Refactoring/SOLID/1.S/Bien/Factura.cs
using Cricarba.Refactoring.Dominio;
using System;
using System.Collections.Generic;
using System.Text;
namespace Cricarba.Refactoring.SOLID.S.Bien
{
class Factura
{
public List<Producto> Productos { get; set; }
bool CrearFactura()
{
var total = 0d;
foreach (var producto in Productos)
{
Console.WriteLine($"{producto.Nombre}");
total -= new Impuesto().ObtenerImpuesto(producto);
}
return true;
}
}
}
<file_sep>/Cricarba.Refactoring/Cricarba.Refactoring/SOLID/4.I/Bien/Impuesto.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Cricarba.Refactoring.SOLID._4.I.Bien
{
class Impuesto : IImpuestoRepositorio
{
public IEnumerable<int> CargarImpuestos()
{
return new List<int>();
}
public bool GuardarImpuesto()
{
return true;
}
}
}
| c1957dd318a0df9bb176691305dc2972326a95b9 | [
"Markdown",
"C#"
] | 16 | C# | cricarba/Refactoring | 3536eb0c4b46e52852c05777f16442a420324c45 | 55885b599d899f2b35897c8a717ac82e9febf3d7 |
refs/heads/master | <file_sep>import React from 'react';
const About = () => {
return (
<div className="about-div">
<h1>Powered By <a href='https://en.m.wikipedia.org/wiki/Cryptocurrency'>Wikipedia</a></h1>
<h2>What is CryptoCurrency</h2>
<p>A cryptocurrency (or crypto currency) is a digital asset designed to work as a medium of exchange that uses strong cryptography to secure financial transactions, control the creation of additional units, and verify the transfer of assets.
<br />Cryptocurrencies use decentralized control as opposed to centralized digital currency and central banking systems.</p>
<h2>History of CryptoCurrency</h2>
<p>In 1983, the American cryptographer <NAME> conceived an anonymous cryptographic electronic money called ecash.
<br /> Later, in 1995, he implemented it through Digicash, an early form of cryptographic electronic payments which required user software in order to withdraw notes from a bank and designate specific encrypted keys before it can be sent to a recipient.
<br /> This allowed the digital currency to be untraceable by the issuing bank, the government, or any third party. </p>
</div>
)
}
export default About;
| ae4114f494d93988ae30e7f8fd96c2ecbb650a96 | [
"JavaScript"
] | 1 | JavaScript | amguenoun/dark-mode | 0684e20d35285367a8eb090ff6085f267a34d9d8 | 2f46e4d90a5d0840bdf049693129fc532f3cab04 |
refs/heads/master | <repo_name>Ouss4/A6GSMDriver<file_sep>/tests/ATGatwayTestRunner.c
#include "unity_fixture.h"
TEST_GROUP_RUNNER(ATGateway)
{
RUN_TEST_CASE(ATGateway, SendAT);
RUN_TEST_CASE(ATGateway, AllTextEndsWithLFandCR);
RUN_TEST_CASE(ATGateway, SendATAndReturnOK);
RUN_TEST_CASE(ATGateway, SendACommandAndModuleReturnsError);
RUN_TEST_CASE(ATGateway, NoReadIfDataIsNotAvailableAndReturnTimeout);
}
<file_sep>/inc/ATGateway.h
#ifndef MODULE_GATEWAY_H_INCLUDDED
#define MODULE_GATEWAY_H_INCLUDDED
typedef enum
{
MODULE_NO_ANSWER,
MODULE_OK,
MODULE_ERROR,
MODULE_TIMEOUT
}ModuleReturns;
ModuleReturns sendAT(char* ATCmd, char* okAnswer,
char* errorAnswer,
unsigned int timout);
ModuleReturns sendATCommand(char* ATCmd, char* okAnswer,
char* errorAnswer,
unsigned int timout);
#endif
<file_sep>/README.md
# A6GSMDriver
Driver for A6 GSM Module
<file_sep>/src/GSMDriver.c
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "GSMDriver.h"
#include "GSMDriverInterface.h"
#include "ATGateway.h"
static ModuleStatus moduleStatus = MODULE_POWERED_OFF;
static GSMDriverInterface interface = NULL;
void GSMDriver_SetInterface(GSMDriverInterface i)
{
interface = i;
}
int GSMDriver_TurnOnModule(void)
{
if(interface)
{
interface->TurnOn();
}
else
{
/*No interface is installed!*/
}
moduleStatus = MODULE_POWERED_ON;
return 1;
}
int GSMDriver_TurnOffModule(void)
{
if(interface)
{
interface->TurnOff();
}
else
{
/*No interface is installed!*/
}
moduleStatus = MODULE_POWERED_OFF;
return 1;
}
int GSMDriver_SleepModule(void)
{
if(interface)
{
interface->Sleep();
}
else
{
/*No interface is installed!*/
}
moduleStatus = MODULE_SLEEPING;
return 1;
}
int GSMDriver_WakeupModule(void)
{
if(interface)
{
interface->Wakeup();
}
else
{
/*No interface is installed!*/
}
moduleStatus = MODULE_POWERED_ON;
return 1;
}
ModuleStatus GSMDriver_GetModuleStatus(void)
{
return moduleStatus;
}
/*
static void getSetCommand(char *cmd)
{
}
static void getTestCommand(char *cmd)
{
}
static void getReadCommand(char *cmd)
{
}
*/
static void setEchoParam(char *cmd, EchoParameters echo)
{
if(echo == NO_ECHO)
{
strcpy(cmd, "ATE0");
}
else if(echo == ENABLE_ECHO)
{
strcpy(cmd, "ATE1");
}
else
{
}
}
static void setErrorParam(char *cmd, ErrorParameters err)
{
if(err == DISABLE_RESULT_ERROR)
{
strcpy(cmd, "AT+CMEE=0");
}
else if(err == NUMERIC_RESULT_ERROR)
{
strcpy(cmd, "AT+CMEE=1");
}
else if(err == VERBOUS_RESULT_ERROR)
{
strcpy(cmd, "AT+CMEE=2");
}
else
{
}
}
ModuleReturns GSMDriver_GSMInit(EchoParameters echo, ErrorParameters err)
{
char ATE_final_cmd[5] = "";
char AT_err_final_cmd[10] = "";
ModuleReturns moduleReturn = MODULE_NO_ANSWER;
/* At init, send AT until the module responds with an OK.
If it doesn't for a certain time, something is wrong. */
while(sendATCommand(at_commands[AT].command,
MODULE_ANSWERS[at_commands[AT].answer1],
MODULE_ANSWERS[at_commands[AT].answer2],
at_commands[AT].timeout) != MODULE_OK)
{
;
}
setEchoParam(ATE_final_cmd, echo);
moduleReturn = sendATCommand(ATE_final_cmd,
MODULE_ANSWERS[at_commands[ATE].answer1],
MODULE_ANSWERS[at_commands[ATE].answer2],
at_commands[ATE].timeout);
setErrorParam(AT_err_final_cmd, err);
moduleReturn = sendATCommand(AT_err_final_cmd,
MODULE_ANSWERS[at_commands[AT_ERR_REPORT].answer1],
MODULE_ANSWERS[at_commands[AT_ERR_REPORT].answer2],
at_commands[AT_ERR_REPORT].timeout);
return moduleReturn;
}
static char* formatMessage(char *msg)
{
char* fullMsg = malloc((strlen(msg) + 2) * sizeof(char));
strcpy(fullMsg, msg);
fullMsg[strlen(msg)] = 0x1A;
fullMsg[strlen(msg) + 1] = '\0';
return fullMsg;
}
static void formatNumberForSMS(char* at, char* num)
{
strcpy(at, at_commands[AT_SMS_SET_NUM].command);
strcat(at, "=\"");
strcat(at, num);
strcat(at, "\"");
}
ModuleReturns GSMDriver_SendSMS(char* msg, char* num)
{
char numberForAT[25] = "";
char *fullMsg = NULL;
ModuleReturns moduleReturn = MODULE_NO_ANSWER;
fullMsg = formatMessage(msg);
formatNumberForSMS(numberForAT, num);
moduleReturn = sendATCommand(at_commands[AT_SMS_SET_FORMAT].command,
MODULE_ANSWERS[at_commands[AT_SMS_SET_FORMAT].answer1],
MODULE_ANSWERS[at_commands[AT_SMS_SET_FORMAT].answer2],
at_commands[AT_SMS_SET_FORMAT].timeout);
moduleReturn = sendATCommand(numberForAT,
MODULE_ANSWERS[at_commands[AT_SMS_SET_NUM].answer1],
MODULE_ANSWERS[at_commands[AT_SMS_SET_NUM].answer2],
at_commands[AT_SMS_SET_NUM].timeout);
moduleReturn = sendATCommand(fullMsg,
MODULE_ANSWERS[OK],
MODULE_ANSWERS[ERROR],
1000);
free(fullMsg), fullMsg = NULL;
return moduleReturn;
}
static void formatNumberForCall(char *atNumber, char *num)
{
strcpy(atNumber, at_commands[AT_CALL].command);
strcat(atNumber, num);
}
ModuleReturns GSMDriver_Call(char* num)
{
/* Max char in a number = 20. */
char numberForAT[25] = "";
ModuleReturns moduleReturn = MODULE_NO_ANSWER;
formatNumberForCall(numberForAT, num);
moduleReturn = sendATCommand(numberForAT,
MODULE_ANSWERS[at_commands[AT_CALL].answer1],
MODULE_ANSWERS[at_commands[AT_CALL].answer2],
at_commands[AT_CALL].timeout);
return moduleReturn;
}
<file_sep>/inc/GSMClient.h
#ifndef GSM_CLIENT_H_INCLUDDED
#define GSM_CLIENT_H_INCLUDDED
#endif
<file_sep>/main.c
#include "unity_fixture.h"
static void RunAllTests(void)
{
RUN_TEST_GROUP(GSMDriver);
RUN_TEST_GROUP(ATGateway);
}
int main(int argc, char *argv[])
{
printf("Starting tests\n\n");
return UnityMain(argc, (const char **)argv, RunAllTests);
}
<file_sep>/mocks/FakeMicroTime.c
#include "FakeMicroTime.h"
static uint32_t time;
static uint32_t increment;
void FakeMicroTime_Init(uint32_t start, uint32_t incr)
{
time = start;
increment = incr;
}
uint32_t MicroTime_Get(void)
{
uint32_t temp = time;
time += increment;
return temp;
}
<file_sep>/mocks/FakeMicroTime.h
#ifndef FAKE_MICRO_TIME_H_INCLUDDED
#define FAKE_MICRO_TIME_H_INCLUDDED
#include <stdint.h>
void FakeMicroTime_Init(uint32_t start, uint32_t incr);
uint32_t MicroTime_Get(void);
#endif
<file_sep>/inc/GSMDriver.h
#ifndef GSM_DRIVER_H_INCLUDDED
#define GSM_DRIVER_H_INCLUDDED
#include "ATGateway.h"
#define A6GSM
#ifdef A6GSM
#include "dsh_a6gsm.h"
#endif
/* Indexes for the commands array defined in each dsh. */
#define AT 0
#define ATE 1
#define AT_ERR_REPORT 2
#define AT_SMS_SET_FORMAT 3
#define AT_SMS_SET_NUM 4
#define AT_CALL 5
typedef enum
{
MODULE_POWERED_OFF = 0,
MODULE_POWERED_ON,
MODULE_SLEEPING
}ModuleStatus;
typedef enum
{
NO_ECHO = 0,
ENABLE_ECHO
}EchoParameters;
typedef enum
{
DISABLE_RESULT_ERROR = 0,
NUMERIC_RESULT_ERROR,
VERBOUS_RESULT_ERROR
}ErrorParameters;
typedef struct GSMDriverInterfaceStruct * GSMDriverInterface;
void GSMDriver_SetInterface(GSMDriverInterface i);
ModuleStatus GSMDriver_GetModuleStatus(void);
int GSMDriver_TurnOnModule(void);
int GSMDriver_TurnOffModule(void);
int GSMDriver_SleepModule(void);
int GSMDriver_WakeupModule(void);
ModuleReturns GSMDriver_GSMInit(EchoParameters echo, ErrorParameters err);
ModuleReturns GSMDriver_SendSMS(char* txt, char* num);
ModuleReturns GSMDriver_Call(char* num);
#endif
<file_sep>/src/bsp_stm32_a6gsm.c
#include "bsp_stm32_a6gsm.h"
#include "GSMDriverInterface.h"
#include "GSMDriver.h"
#include <stdio.h>
static void turnOn(void)
{
printf("Turn On!\n\n");
}
static void turnOff(void)
{
printf("Turn Off!\n\n");
}
static void reset(void)
{
printf("Restart!\n\n");
}
static void sleep(void)
{
printf("Sleeping!\n\n");
}
static void wakeup(void)
{
printf("Waken up!\n\n");
}
static GSMDriverInterfaceStruct interface = {
turnOn,
turnOff,
reset,
sleep,
wakeup
};
/*
Installs the A6GSM module's interface.
GSMDriver will then use the functions defined here.
*/
void STM32_A6GSM_Setup(void)
{
GSMDriver_SetInterface(&interface);
}
<file_sep>/src/GSMClient.c
#include "GSMClient.h"
<file_sep>/tests/GSMDriverTestRunner.c
#include "unity_fixture.h"
TEST_GROUP_RUNNER(GSMDriver)
{
RUN_TEST_CASE(GSMDriver, TurnOnModule);
RUN_TEST_CASE(GSMDriver, TurnOffModule);
RUN_TEST_CASE(GSMDriver, SleepModule);
RUN_TEST_CASE(GSMDriver, WakeUpModuleAfterSleep);
RUN_TEST_CASE(GSMDriver, InitGSMServicesWithNoEchoAndVerbousError);
RUN_TEST_CASE(GSMDriver, InitShouldWaitUntillModuleReturnsOK);
RUN_TEST_CASE(GSMDriver, SendSMSHelloWorld);
RUN_TEST_CASE(GSMDriver, CallANumber);
RUN_TEST_CASE(GSMDriver, CallCommandTimedout);
}
<file_sep>/inc/HAL_UART.h
#ifndef UART_HAL_H_INCLUDDED
#define UART_HAL_H_INCLUDDED
void UART_Write(char c);
char UART_Read(void);
int UART_Data_Available(void);
#endif
<file_sep>/tests/GSMDriverTest.c
#include "unity_fixture.h"
#include "GSMDriver.h"
#include "MockATGateway.h"
#include "bsp_stm32_a6gsm.h"
TEST_GROUP(GSMDriver);
TEST_SETUP(GSMDriver)
{
MockATGateway_Init();
STM32_A6GSM_Setup();
}
TEST_TEAR_DOWN(GSMDriver)
{
MockATGateway_Destroy();
}
TEST(GSMDriver, TurnOnModule)
{
GSMDriver_TurnOnModule();
TEST_ASSERT_EQUAL_INT(MODULE_POWERED_ON,
GSMDriver_GetModuleStatus());
}
TEST(GSMDriver, TurnOffModule)
{
GSMDriver_TurnOffModule();
TEST_ASSERT_EQUAL_INT(MODULE_POWERED_OFF,
GSMDriver_GetModuleStatus());
}
TEST(GSMDriver, SleepModule)
{
GSMDriver_SleepModule();
TEST_ASSERT_EQUAL_INT(MODULE_SLEEPING,
GSMDriver_GetModuleStatus());
}
TEST(GSMDriver, WakeUpModuleAfterSleep)
{
GSMDriver_SleepModule();
TEST_ASSERT_EQUAL_INT(MODULE_SLEEPING,
GSMDriver_GetModuleStatus());
GSMDriver_WakeupModule();
TEST_ASSERT_EQUAL_INT(MODULE_POWERED_ON,
GSMDriver_GetModuleStatus());
}
TEST(GSMDriver, InitGSMServicesWithNoEchoAndVerbousError)
{
ModuleReturns moduleReturn;
sendATCommand_ExpectAndReturn("AT",
"OK",
"OK",
at_commands[AT].timeout,
MODULE_OK);
sendATCommand_ExpectAndReturn("ATE0",
"OK",
"ERROR",
at_commands[AT].timeout,
MODULE_OK);
sendATCommand_ExpectAndReturn("AT+CMEE=2",
"OK",
"ERROR",
at_commands[AT].timeout,
MODULE_OK);
moduleReturn = GSMDriver_GSMInit(NO_ECHO, VERBOUS_RESULT_ERROR);
MockATGateway_Verify();
TEST_ASSERT_EQUAL_INT(MODULE_OK, moduleReturn);
}
TEST(GSMDriver, InitShouldWaitUntillModuleReturnsOK)
{
ModuleReturns moduleReturn;
/* Simulate a not ready module for the AT. */
for(int i = 0; i < 5; i++)
{
sendATCommand_ExpectAndReturn("AT",
"OK",
"OK",
at_commands[AT].timeout,
MODULE_NO_ANSWER);
}
sendATCommand_ExpectAndReturn("AT",
"OK",
"OK",
at_commands[AT].timeout,
MODULE_OK);
sendATCommand_ExpectAndReturn("ATE0",
"OK",
"ERROR",
at_commands[AT].timeout,
MODULE_OK);
sendATCommand_ExpectAndReturn("AT+CMEE=2",
"OK",
"ERROR",
at_commands[AT].timeout,
MODULE_OK);
moduleReturn = GSMDriver_GSMInit(NO_ECHO, VERBOUS_RESULT_ERROR);
MockATGateway_Verify();
TEST_ASSERT_EQUAL_INT(MODULE_OK, moduleReturn);
}
TEST(GSMDriver, SendSMSHelloWorld)
{
ModuleReturns moduleReturn;
char msg[14] = {'H', 'e', 'l', 'l', 'o', ' ',
'W', 'o', 'r', 'l', 'd', '!',
0x1A, '\0'};
sendATCommand_ExpectAndReturn("AT+CMGF=1",
"OK",
"ERROR",
1000,
MODULE_OK);
sendATCommand_ExpectAndReturn("AT+CMGS=\"+213549812834\"",
">",
"ERROR",
1000,
MODULE_OK);
sendATCommand_ExpectAndReturn(msg,
"OK",
"ERROR",
1000,
MODULE_OK);
moduleReturn = GSMDriver_SendSMS("Hello World!", "+213549812834");
MockATGateway_Verify();
TEST_ASSERT_EQUAL_INT(MODULE_OK, moduleReturn);
}
TEST(GSMDriver, CallANumber)
{
ModuleReturns moduleReturn;
sendATCommand_ExpectAndReturn("ATD+21323782659",
"OK",
"ERROR",
1000,
MODULE_OK);
moduleReturn = GSMDriver_Call("+21323782659");
MockATGateway_Verify();
TEST_ASSERT_EQUAL_INT(MODULE_OK, moduleReturn);
}
TEST(GSMDriver, CallCommandTimedout)
{
ModuleReturns moduleReturn;
sendATCommand_ExpectAndReturn("ATD+21323782659",
"OK",
"ERROR",
1000,
MODULE_TIMEOUT);
moduleReturn = GSMDriver_Call("+21323782659");
MockATGateway_Verify();
TEST_ASSERT_EQUAL_INT(MODULE_TIMEOUT, moduleReturn);
}
<file_sep>/src/ATGateway.c
#include <string.h>
#include <stdint.h>
#include "ATGateway.h"
#include "HAL_UART.h"
#include "FakeMicroTime.h"
static void sendToModule(char *msg)
{
if(msg)
{
while(*msg)
{
UART_Write(*msg++);
}
UART_Write('\r');
UART_Write('\n');
}
}
static char readFromModule(void)
{
return UART_Read();
}
static ModuleReturns checkAnswer(char *answer, char *okAnswer,
char *errorAnswer)
{
ModuleReturns moduleReturn = MODULE_NO_ANSWER;
if(strstr(answer, okAnswer))
{
moduleReturn = MODULE_OK;
}
else if(strstr(answer, errorAnswer))
{
moduleReturn = MODULE_ERROR;
}
return moduleReturn;
}
ModuleReturns sendAT(char* ATCmd, char* okAnswer,
char* errorAnswer,
uint32_t timeout)
{
ModuleReturns moduleReturn = MODULE_NO_ANSWER;
char answer[10] = "";
int i = 0;
uint32_t timestamp = 0;
sendToModule(ATCmd);
timestamp = MicroTime_Get();
do{
if(UART_Data_Available())
{
answer[i] = readFromModule();
++i;
moduleReturn = checkAnswer(answer, okAnswer, errorAnswer);
}
if(MicroTime_Get() - timestamp >= timeout && moduleReturn == MODULE_NO_ANSWER)
{
moduleReturn = MODULE_TIMEOUT;
}
}while(moduleReturn == MODULE_NO_ANSWER);
return moduleReturn;
}
<file_sep>/inc/dsh_a6gsm.h
#ifndef DSH_A6GSM_H_INCLUDDED
#define DSH_A6GSM_H_INCLUDDED
/* A6 GSM/GPRS Device Specific Header. */
/* A6 responses. */
enum {ERROR, OK, CONNECTED, READY};
static char* MODULE_ANSWERS[4] =
{
"ERROR",
"OK",
"CONNECTED",
">"
};
/* A6 AT Commands. */
static struct Commands
{
char* command;
unsigned int answer1;
unsigned int answer2;
unsigned int timeout;
}at_commands[] =
{
{"AT", OK, OK, 1000},
{"ATE", OK, ERROR, 1000},
{"AT+CMEE", OK, ERROR, 1000},
{"AT+CMGF=1", OK, ERROR, 1000},
{"AT+CMGS", READY, ERROR, 1000},
{"ATD", OK, ERROR, 1000}
};
#endif
<file_sep>/inc/GSMDriverInterface.h
#ifndef GSM_DRIVER_INTERFACE_H_INCLUDDED
#define GSM_DRIVER_INTERFACE_H_INCLUDDED
typedef struct GSMDriverInterfaceStruct
{
void (*TurnOn)(void);
void (*TurnOff)(void);
void (*Reset)(void);
void (*Sleep)(void);
void (*Wakeup)(void);
}GSMDriverInterfaceStruct;
#endif
<file_sep>/inc/bsp_stm32_a6gsm.h
#ifndef BSP_STM32_A6GSM_H_INCLUDDED
#define BSP_STM32_A6GSM_H_INCLUDDED
#define __GSM_PWR_KEY__
#define __GSM_RST_KEY__
#define __GSM_SLP_KEY__
void STM32_A6GSM_Setup(void);
#endif
<file_sep>/src/HAL_UART.c
#include "HAL_UART.h"
<file_sep>/tests/ATGatewayTest.c
#include "unity_fixture.h"
#include "ATGateway.h"
#include "HAL_UART.h"
#include "MockHAL_UART.h"
#include "FakeMicroTime.h"
TEST_GROUP(ATGateway);
TEST_SETUP(ATGateway)
{
MockHAL_UART_Init();
}
TEST_TEAR_DOWN(ATGateway)
{
MockHAL_UART_Destroy();
}
static void expectWriteText(char *s)
{
while(*s)
{
UART_Write_Expect(*s++);
}
UART_Write_Expect('\r');
UART_Write_Expect('\n');
}
static void expectReadText(char *s)
{
while(*s)
{
UART_Data_Available_ExpectAndReturn(1);
UART_Read_ExpectAndReturn(*s++);
}
// UART_Data_Available_ExpectAndReturn(0);
/* UART_Read_ExpectAndReturn('\r');
UART_Read_ExpectAndReturn('\n');*/
}
TEST(ATGateway, SendAT)
{
ModuleReturns moduleReturn;
expectWriteText("AT");
expectReadText("OK");
moduleReturn = sendAT("AT", "OK", "OK", 1000);
MockHAL_UART_Verify();
TEST_ASSERT_EQUAL_INT(MODULE_OK, moduleReturn);
}
TEST(ATGateway, AllTextEndsWithLFandCR)
{
char *at = "AT+CMEE=2";
ModuleReturns moduleReturn;
expectWriteText(at);
expectReadText("OK");
moduleReturn = sendAT(at, "OK", "OK", 1000);
MockHAL_UART_Verify();
TEST_ASSERT_EQUAL_INT(MODULE_OK, moduleReturn);
}
TEST(ATGateway, SendATAndReturnOK)
{
char *at = "AT";
ModuleReturns moduleReturn;
expectWriteText(at);
expectReadText("OK");
moduleReturn = sendAT(at, "OK", "OK", 1000);
MockHAL_UART_Verify();
TEST_ASSERT_EQUAL_INT(MODULE_OK, moduleReturn);
}
TEST(ATGateway, SendACommandAndModuleReturnsError)
{
char *at = "AT+CMEE=2";
ModuleReturns moduleReturn;
FakeMicroTime_Init(0, 500);
expectWriteText(at);
/* Simulate a delay in response. */
for(int i = 0; i < 5; i++)
{
UART_Data_Available_ExpectAndReturn(0);
}
expectReadText("ERROR");
moduleReturn = sendAT(at, "OK", "ERROR", 5000);
MockHAL_UART_Verify();
TEST_ASSERT_EQUAL_INT(MODULE_ERROR, moduleReturn);
}
TEST(ATGateway, NoReadIfDataIsNotAvailableAndReturnTimeout)
{
char *at = "AT";
ModuleReturns moduleReturn;
FakeMicroTime_Init(0, 500);
expectWriteText(at);
for(int i = 0; i < 10; i++)
{
UART_Data_Available_ExpectAndReturn(0);
}
moduleReturn = sendAT(at, "OK", "ERROR", 5000);
MockHAL_UART_Verify();
TEST_ASSERT_EQUAL_INT(MODULE_TIMEOUT, moduleReturn);
}
| 676a6c0cf2993e01c167de3958c0733089e08630 | [
"Markdown",
"C"
] | 20 | C | Ouss4/A6GSMDriver | 0df319ea36dc0cb9a2c85c0d1d1ff44db2700383 | bdf4094719cb40cd1c20e4975e6076dfdf780ce0 |
refs/heads/master | <repo_name>temun17/ft_select<file_sep>/includes/ft_select.h
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_select.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: atemunov <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/08/22 13:43:20 by atemunov #+# #+# */
/* Updated: 2018/08/22 16:35:10 by atemunov ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef FT_SELECT_H
# define FT_SELECT_H
/*
**---------------------------- External Headers ------------------------------
*/
# include "../libft/libft.h"
# include <unistd.h>
# include <stdio.h>
# include <stdlib.h>
# include <strings.h>
# include <sys/types.h>
# include <sys/ioctl.h>
# include <signal.h>
# include <sys/param.h>
# include <termcap.h>
# include <termios.h>
# include <curses.h>
# include <term.h>
/*
**---------------------------- Macros Definiton -----------------------------
*/
# define ENTER_KEY 13
# define ESCAPE_KEY 27
# define SPC_KEY 32
# define BSP_KEY 127
# define UP_KEY 4283163
# define DOWN_KEY 4348699
# define BLUE "\033[34m"
# define RESET "\033[00m"
# define RED "\033[31m"
# define WHITE "\033[37m"
# define GREEN "\033[32m"
# define YELLOW "\033[33m"
/*
**--------------------------- Struct Definition -----------------------------
*/
typedef struct s_env
{
size_t keycode;
int fd;
char **element;
int argc;
int *select_pos;
int current_element;
int cursor;
int cap_names;
int max_length;
struct termios termios;
} t_env;
/*
**-------------------------- Helping Functions ------------------------------
*/
int check_empty_args(int argc, char **argv, int i, int j);
t_env *orig_term(t_env **term);
void print_list(t_env *term);
void set_signal(t_env *term);
void return_highlighted_words(t_env *term);
void select_deselect(t_env *term);
void reset_and_complete(int sig);
void keycode(t_env *term);
void init_struct(t_env *term, int argc, char **argv);
void init_term(t_env *term, int argc);
void move_up(t_env *term);
void move_down(t_env *term);
int my_putchar(int c);
void window_size_change(int sig);
void turn_off_appearance_mode(t_env *term);
void leave_standout_mode(t_env *term);
int check_size(t_env *term);
#endif
<file_sep>/srcs/keycode.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* keycode.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: allentemunovic <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/08/21 01:38:13 by allentemu #+# #+# */
/* Updated: 2018/08/22 13:59:47 by atemunov ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/ft_select.h"
void keycode(t_env *term)
{
int should_refresh;
should_refresh = 1;
if (term->keycode == ESCAPE_KEY || term->keycode == 113)
reset_and_complete(0);
if (term->keycode == SPC_KEY)
select_deselect(term);
if (term->keycode == '\n')
return_highlighted_words(term);
if (term->keycode == UP_KEY)
move_up(term);
if (term->keycode == DOWN_KEY)
move_down(term);
else
should_refresh = 0;
if (should_refresh)
window_size_change(0);
term->keycode = 0;
}
<file_sep>/srcs/valid.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* valid.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: allentemunovic <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/08/20 20:51:21 by allentemu #+# #+# */
/* Updated: 2018/08/22 16:09:13 by atemunov ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/ft_select.h"
/*
** This function is an error checker for my command line arguments.
** In other words, the arguments can never be null. They just won't exist.
** I must check the length of my arguments to see if it is valid.
*/
int check_empty_args(int argc, char **argv, int i, int j)
{
unsigned int spaces;
while (i < argc)
{
spaces = 0;
while (argv[i][j])
{
if (ft_isspace(argv[i][j]))
spaces++;
j++;
}
if (spaces == ft_strlen(argv[i]))
return (-1);
i++;
}
return (0);
}
<file_sep>/srcs/init.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* init.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: allentemunovic <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/08/20 21:07:46 by allentemu #+# #+# */
/* Updated: 2018/08/22 16:16:11 by atemunov ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/ft_select.h"
void init_term(t_env *term, int i)
{
if ((tgetent(NULL, getenv("TERM")) < 1))
write(1, "Cannot retrieve environment variable Term\n", 42);
if (tcgetattr(0, &(term->termios)) == -1)
write(1, "Unable to retrieve terminal information\n", 40);
tcgetattr(term->fd, &term->termios);
term->termios.c_lflag &= ~(ICANON);
term->termios.c_lflag &= ~(ECHO);
term->termios.c_cc[VMIN] = 1;
term->termios.c_cc[VTIME] = 0;
tcsetattr(term->fd, TCSANOW, &term->termios);
if ((tcsetattr(0, 0, &(term->termios)) == -1))
write(1, "Unable to set the terminal parameters\n", 38);
set_signal(term);
term->max_length = 0;
term->cursor = 0;
while (i-- > 0)
term->select_pos[i] = 0;
i = -1;
ft_putstr_fd(tgetstr("vi", NULL), 0);
}
void init_struct(t_env *term, int argc, char **argv)
{
term->select_pos = (int*)malloc(argc - 1);
term->element = ++argv;
term->argc = --argc;
term->cap_names = argc;
}
<file_sep>/Makefile
# **************************************************************************** #
# #
# ::: :::::::: #
# Makefile :+: :+: :+: #
# +:+ +:+ +:+ #
# By: allentemunovic <<EMAIL>> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2018/08/20 20:42:10 by allentemu #+# #+# #
# Updated: 2018/08/21 02:23:09 by allentemu ### ########.fr #
# #
# **************************************************************************** #
NAME = ft_select
CC = gcc
CFLAGS = -g -Wall -Werror -Wextra
INCLUDES = ./libft/libft.h libft/libft.a
SRCS = srcs/main.c \
srcs/valid.c \
srcs/init.c \
srcs/print.c \
srcs/keycode.c \
srcs/keys.c \
srcs/arrows.c \
srcs/original.c \
srcs/signal.c \
OBJS = $(SRCS:.c=.o)
READY = @echo "\033[0;32mft_select ready to use!"
all : $(NAME)
$(NAME): $(OBJS)
make -C libft/
cp ./libft/libft.a ./lib
$(CC) $(CFLAGS) -o $(NAME) $(OBJS) -I $(INCLUDES) -ltermcap
$(READY)
clean:
make clean -C ./libft
/bin/rm -f ./lib
fclean:
/bin/rm -f $(NAME)
/bin/rm -f $(OBJS)
make -C ./libft fclean
re: fclean all
<file_sep>/srcs/print.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* print.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: allentemunovic <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/08/21 01:11:35 by allentemu #+# #+# */
/* Updated: 2018/08/22 16:15:29 by atemunov ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/ft_select.h"
/*
** Capabilites Names
** "se" - leave standout mode (generally to highlight some text)
** "so" - string to enter standout mode
** "me" - if any possible appearance modes are on this turns it off.
** "co" - the number of width of the screen.
** "li" - the number of height of the screen.
** "cl" - stirng to clear the entire screen and put cursor at upper left corner.
** "so" - string to enter standout mode.
** "us" - string to turn on underline mode.
*/
void leave_standout_mode(t_env *term)
{
if (tgetstr("se", NULL))
ft_putstr_fd(tgetstr("se", NULL), 0);
else
turn_off_appearance_mode(term);
}
void turn_off_appearance_mode(t_env *term)
{
if (tgetstr("me", NULL))
ft_putstr_fd(tgetstr("me", NULL), 0);
else
leave_standout_mode(term);
}
int check_size(t_env *term)
{
int column_range;
column_range = ((tgetnum("co")) / (term->max_length + 1));
return ((column_range * (tgetnum("li") - 1)) > term->cap_names);
}
void print_list(t_env *term)
{
int i;
int col;
int row;
i = 0;
ft_putstr_fd(tgetstr("cl", NULL), 0);
if (!check_size(term))
write(1, "Unable to resize window.\n", 25);
col = 0;
row = 0;
while (term->element[i])
{
if (term->select_pos[i] == -1)
continue ;
(term->select_pos[i]) ? ft_putstr_fd(tgetstr("so", NULL), 0) : 0;
(i == term->cursor) ? ft_putstr_fd(tgetstr("us", NULL), 0) : 0;
ft_putstr_fd(GREEN, 2);
ft_putstr_fd(term->element[i], 0);
ft_putstr_fd("\n", 0);
turn_off_appearance_mode(term);
(term->select_pos[i]) ? ft_putstr_fd(tgetstr("se", NULL), 0) : 0;
(col == tgetnum("li") - 2) ? (row += term->max_length + 1) : 0;
col += (col == tgetnum("li") - 2) ? -col : 1;
i++;
}
}
<file_sep>/libft/get_next_line.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: atemunov <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/04/03 09:37:45 by atemunov #+# #+# */
/* Updated: 2018/06/30 16:43:52 by atemunov ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int find_buffer(int fd, char **buff, char **line)
{
if (*buff[fd])
{
*line = ft_strdup(buff[fd]);
buff[fd] = ft_strnew(BUFF_SIZE + 1);
return (1);
}
return (0);
}
int find_newline(int fd, char **buff, char **line)
{
char *curr;
char *ptr;
if ((curr = ft_strchr(buff[fd], '\n')))
{
ptr = buff[fd];
*curr = '\0';
*line = ft_strdup(buff[fd]);
buff[fd] = ft_strdup(curr + 1);
free(ptr);
return (1);
}
else if (*buff[fd])
return (find_buffer(fd, buff, line));
return (0);
}
int read_tmp(int fd, char **buff)
{
char *tmp;
char *ptr;
int bytes_read;
tmp = ft_strnew(BUFF_SIZE + 1);
while ((bytes_read = read(fd, tmp, BUFF_SIZE)) > 0)
{
if (!buff[fd])
buff[fd] = ft_strdup(tmp);
else
{
ptr = buff[fd];
buff[fd] = ft_strjoin(buff[fd], tmp);
free(ptr);
}
ft_bzero(tmp, BUFF_SIZE);
}
free(tmp);
return (bytes_read);
}
int get_next_line(const int fd, char **line)
{
static char *buff[4864];
if (!line || fd < 0 || BUFF_SIZE < 0)
return (-1);
if (read_tmp(fd, &buff[fd]) < 0)
return (-1);
if (find_newline(fd, &buff[fd], line) == 1)
return (1);
return (0);
}
<file_sep>/srcs/signal.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* signal.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: allentemunovic <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/08/21 00:40:49 by allentemu #+# #+# */
/* Updated: 2018/08/22 16:12:49 by atemunov ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/ft_select.h"
static void terminate(int sig)
{
(void)sig;
exit(0);
}
/*
** ICANON() - Enables canonical mode (terminal input processed in lines
** terminated by newline ('\n'), EOF, or EOL charcters.
** ECHO() - echo the input characters.
** signal() - a simplified interface to mainpulate a process from outside it's
** domain, as well as allowing the process to manipulate itself.
** stop_process() - This function listens for a SIGTSTP or 18 signal that stops
** the signal gernerated from the keyboard.
** tputs() - output commands to the terminal.
** tcsetattr() - set the parameters associated with the terminal.
** tcgetattr() - get the parameters associated with the terminal.
** tgetstr() - returns the string entry fo r id, or zero if it is not available.
** Use tputs() to output the return string.
*/
static void stop_process(int sig)
{
t_env *term;
char cp[2];
(void)sig;
term = NULL;
cp[0] = term->termios.c_cc[VSUSP];
cp[1] = 0;
term->termios.c_lflag &= ~(ICANON | ECHO);
signal(18, SIG_DFL);
if (tcsetattr(0, TCSADRAIN, &term->termios) == -1)
write(1, "Cannot retrieve termcap attributes TERM\n", 40);
tcsetattr(0, 0, &(term->termios));
tputs(tgetstr("ve", NULL), 1, my_putchar);
tputs(tgetstr("te", NULL), 1, my_putchar);
ioctl(0, TIOCSTI, cp);
}
/*
** restart() - This function sends a signal define macro called SIGCONT or 19
** that continues the process. This signal is special - it always
** makes the process contiue if it is stopped, before the signal
** is delievered.
*/
static void restart(int sig)
{
t_env *term;
(void)sig;
term = NULL;
term = orig_term(&term);
tcgetattr(term->fd, &term->termios);
term->termios.c_lflag &= ~(ICANON | ECHO);
term->termios.c_cc[VMIN] = 1;
term->termios.c_cc[VTIME] = 0;
tcsetattr(term->fd, TCSANOW, &term->termios);
set_signal(term);
tputs(tgetstr("vi", NULL), 1, my_putchar);
tputs(tgetstr("ti", NULL), 1, my_putchar);
window_size_change(sig);
check_size(term);
}
/*
** window_size_change() - This funciton is generated when the terminal
** driver's record of the number of rows and cols
** on the screen changes. This helps ignore it.
*/
void window_size_change(int sig)
{
t_env *term;
struct winsize winsize;
(void)sig;
term = NULL;
term = orig_term(&term);
ioctl(0, TIOCGWINSZ, &winsize);
if (tgetent(NULL, getenv("TERM")) <= 0)
write(1, "Cannot resize window.\n", 22);
print_list(term);
}
/*
** set_signal() - Function acts as a dispatch table and listens for any
** signal sent from the user to be executed.
*/
void set_signal(t_env *term)
{
term = orig_term(&term);
signal(28, window_size_change);
signal(18, stop_process);
signal(19, restart);
signal(2, terminate);
}
<file_sep>/srcs/keys.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* keys.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: allentemunovic <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/08/21 01:56:59 by allentemu #+# #+# */
/* Updated: 2018/08/22 16:17:14 by atemunov ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/ft_select.h"
void reset_and_complete(int sig)
{
t_env *term;
(void)sig;
term = NULL;
term = orig_term(&term);
term->termios.c_lflag &= ~(ICANON | ECHO);
tcsetattr(term->fd, TCSANOW, &term->termios);
(sig == -1) ? 0 : ft_putstr_fd(tgetstr("cl", NULL), 0);
ft_putstr_fd(tgetstr("ve", NULL), 0);
close(term->fd);
free(term->select_pos);
free(term);
exit(sig);
}
void select_deselect(t_env *term)
{
term->select_pos[term->cursor] = (term->select_pos[term->cursor]) ? 0 : 1;
term->cursor++;
while (term->cursor == term->argc)
{
(term->select_pos[term->cursor] == -1) ? term->cursor++ : 0;
(term->cursor == term->argc) ? term->cursor = 0 : 0;
}
}
/*
** return_highlighted_words() - put the cursor in the upper left corner and
** any of the selected words we will return them to the original shell with
** spaces seperated any other words that are selected.
*/
void return_highlighted_words(t_env *term)
{
int i;
i = 0;
ft_putstr_fd(tgetstr("cl", NULL), 0);
while (term->element[i])
{
if (term->select_pos[i] == 1)
{
ft_putstr(term->element[i]);
ft_putchar(' ');
}
i++;
}
reset_and_complete(-1);
}
<file_sep>/README.md
# ft_select
A program using the termcaps library to display a list of arguments and return those that the user has selected to the shell.
<file_sep>/srcs/main.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: allentemunovic <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/08/20 20:42:38 by allentemu #+# #+# */
/* Updated: 2018/08/22 16:19:47 by atemunov ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/ft_select.h"
int my_putchar(int c)
{
return (write(2, &c, 1));
}
static void input_loop(t_env *term)
{
while (42)
{
print_list(term);
read(0, &term->keycode, 4);
keycode(term);
if (!term->cap_names)
reset_and_complete(0);
}
}
int main(int argc, char **argv)
{
t_env *term;
int i;
int j;
i = 0;
j = 0;
if (argc == 1)
{
write(1, "ft_select: arguments missing\n", 29);
exit(1);
}
check_empty_args(argc, argv, i, j);
term = (t_env *)malloc(sizeof(t_env));
init_struct(term, argc, argv);
init_term(term, argc);
set_signal(term);
input_loop(term);
}
| 66af154c149d1b4adb3da0107a02add024056bfd | [
"Markdown",
"C",
"Makefile"
] | 11 | C | temun17/ft_select | 5b7ca11e9d2d8571c6e3b0acf4f7c89c6d15c813 | aafe235e95196e7fcd4dd6cc16c7f01622888aad |
refs/heads/master | <file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>
//gnuplot ->plot "demo_xxxx" with line
unsigned char invSBOX[256] =
{
0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB,
0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB,
0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E,
0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25,
0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92,
0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84,
0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06,
0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B,
0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73,
0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E,
0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B,
0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4,
0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F,
0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF,
0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D
};
double trace[2000][29000];
void crea_trace_moy(){
FILE* courbe = NULL;
char s[20] = "";
double c = 0;
double mu[29000];
for (int k = 0; k < 29000; ++k)
{
mu[k]=0;
}
for (int i = 0; i < 2000; ++i)
{
sprintf(s,"curves/demo_%04d",i);
courbe = fopen(s,"r");
//printf("%p,%i \n",courbe,i);
for (int j = 0; j < 29000; ++j)
{
fscanf(courbe,"%lf\n",&c);
mu[j]=(mu[j]+c);
}
fclose(courbe);
}
for (int k = 0; k < 29000; ++k)
{
mu[k]=mu[k]/2000;
printf("%lf\n",mu[k] );;
}
}
int main(int argc, char const *argv[])
{
// création du tableau contenant les chiffres en decimale a partur du fichier demo_output.txt
FILE* output =NULL;
output = fopen("demo_output.txt","r");
unsigned int chiffre[2000][16];
char s[33];
char z[3];
for (int i = 0; i < 2000; ++i)
{
fscanf(output,"%s",s);
for (int j = 0; j < 16; ++j)
{
z[0]=s[2*j];
z[1]=s[2*j+1];
z[2]='\0';
sscanf(z,"%02x",&chiffre[i][j]);
}
}
printf("lecture fichier fini\n");
//création du fichier de trace moyenne
//crea_trace_moy();
//création du tableau qui contient toute les traces.
double c = 0;
FILE* courbe =NULL;
courbe = fopen("demo_output.txt","r");
for (int i = 0; i < 2000; ++i)
{
sprintf(s,"curves/demo_%04d",i);
courbe = fopen(s,"r");
for (int u = 0; u < 29000; ++u)
{
fscanf(courbe,"%lf\n",&c);
trace[i][u] = c;
}
fclose(courbe);
}
//calcul de la trace de delta^(g)
int vi=0;
double max;
double max_g = 0;
int gmax=0;
double acc0[29000];
double acc1[29000];
double acc[29000];
int count0 =0;
int count1 =0;
for (int j = 0; j < 16; ++j)
{
gmax = 0;
max=-100000;
for (int g = 0; g < 256; ++g)
{
//printf("%lu | g=%d\n", time(NULL), g);
for(int i=0;i<29000;i++){
acc1[i]=0;
acc0[i]=0;
acc[i]=0;
}
count1 =0;
count0 =0;
//printf("%lu | g=%d\n", time(NULL), g);
//calcule de ka trace de DPA
for (int i = 0; i < 2000; ++i)
{
//printf("i=%d\n",i );
vi = invSBOX[chiffre[i][j]^g];
if (((vi>>0)&1)==1)// vi>>x , valeur de vi shifter de x place
//donc si on a 11001001 >> 3 ont obtient 00011001
//le & est un et binaire donc 00011001 & 1 <=> 0011001 & 00000001 = 00000001
{
for (int u = 0; u < 29000; ++u)
{
//printf("j1=%d\n",j );
acc1[u]=(acc1[u]+trace[i][u]);
}
count1 ++ ;
}
else{
for (int w = 0; w < 29000; ++w)
{
//printf("j0=%d\n",j );
acc0[w]=(acc0[w]+trace[i][w]);
}
count0 ++ ;
}
}
//printf("%lu | g=%d\n", time(NULL), g);
//moyenne pour les trace de DPA
for (int k = 0; k < 29000; ++k)
{
acc0[k]=acc0[k]/count0;
acc1[k]=acc1[k]/count1;
acc[k] = fabs(acc1[k] - acc0[k]);
}
// calcule du max de delta g
max_g=0;
for (int k = 0; k < 29000; ++k)
{
if (max_g < acc[k])
{
max_g = acc[k];
}
}
if (max_g>max)
{
max= max_g;
gmax = g;
}
printf("j= %d , g= %d , max_g = %lf \n", j,g,max_g);
}
printf("j=%d,max=%lf ,gmax =%d\n",j,max,gmax);
}
//printf("temps = %lu \n", t - time(NULL));
return 0;
}<file_sep>#include "aes_dlc.h"
/******************aes_table.c*************************************/
const unsigned char invSBOX[256] =
{
0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB,
0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB,
0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E,
0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25,
0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92,
0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84,
0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06,
0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B,
0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73,
0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E,
0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B,
0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4,
0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F,
0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF,
0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D
};
const unsigned long int mul9[256] =
{
0x00,0x09,0x12,0x1b,0x24,0x2d,0x36,0x3f,0x48,0x41,0x5a,0x53,0x6c,0x65,0x7e,0x77,
0x90,0x99,0x82,0x8b,0xb4,0xbd,0xa6,0xaf,0xd8,0xd1,0xca,0xc3,0xfc,0xf5,0xee,0xe7,
0x3b,0x32,0x29,0x20,0x1f,0x16,0x0d,0x04,0x73,0x7a,0x61,0x68,0x57,0x5e,0x45,0x4c,
0xab,0xa2,0xb9,0xb0,0x8f,0x86,0x9d,0x94,0xe3,0xea,0xf1,0xf8,0xc7,0xce,0xd5,0xdc,
0x76,0x7f,0x64,0x6d,0x52,0x5b,0x40,0x49,0x3e,0x37,0x2c,0x25,0x1a,0x13,0x08,0x01,
0xe6,0xef,0xf4,0xfd,0xc2,0xcb,0xd0,0xd9,0xae,0xa7,0xbc,0xb5,0x8a,0x83,0x98,0x91,
0x4d,0x44,0x5f,0x56,0x69,0x60,0x7b,0x72,0x05,0x0c,0x17,0x1e,0x21,0x28,0x33,0x3a,
0xdd,0xd4,0xcf,0xc6,0xf9,0xf0,0xeb,0xe2,0x95,0x9c,0x87,0x8e,0xb1,0xb8,0xa3,0xaa,
0xec,0xe5,0xfe,0xf7,0xc8,0xc1,0xda,0xd3,0xa4,0xad,0xb6,0xbf,0x80,0x89,0x92,0x9b,
0x7c,0x75,0x6e,0x67,0x58,0x51,0x4a,0x43,0x34,0x3d,0x26,0x2f,0x10,0x19,0x02,0x0b,
0xd7,0xde,0xc5,0xcc,0xf3,0xfa,0xe1,0xe8,0x9f,0x96,0x8d,0x84,0xbb,0xb2,0xa9,0xa0,
0x47,0x4e,0x55,0x5c,0x63,0x6a,0x71,0x78,0x0f,0x06,0x1d,0x14,0x2b,0x22,0x39,0x30,
0x9a,0x93,0x88,0x81,0xbe,0xb7,0xac,0xa5,0xd2,0xdb,0xc0,0xc9,0xf6,0xff,0xe4,0xed,
0x0a,0x03,0x18,0x11,0x2e,0x27,0x3c,0x35,0x42,0x4b,0x50,0x59,0x66,0x6f,0x74,0x7d,
0xa1,0xa8,0xb3,0xba,0x85,0x8c,0x97,0x9e,0xe9,0xe0,0xfb,0xf2,0xcd,0xc4,0xdf,0xd6,
0x31,0x38,0x23,0x2a,0x15,0x1c,0x07,0x0e,0x79,0x70,0x6b,0x62,0x5d,0x54,0x4f,0x46
};
const unsigned long int mulb[256] =
{
0x00,0x0b,0x16,0x1d,0x2c,0x27,0x3a,0x31,0x58,0x53,0x4e,0x45,0x74,0x7f,0x62,0x69,
0xb0,0xbb,0xa6,0xad,0x9c,0x97,0x8a,0x81,0xe8,0xe3,0xfe,0xf5,0xc4,0xcf,0xd2,0xd9,
0x7b,0x70,0x6d,0x66,0x57,0x5c,0x41,0x4a,0x23,0x28,0x35,0x3e,0x0f,0x04,0x19,0x12,
0xcb,0xc0,0xdd,0xd6,0xe7,0xec,0xf1,0xfa,0x93,0x98,0x85,0x8e,0xbf,0xb4,0xa9,0xa2,
0xf6,0xfd,0xe0,0xeb,0xda,0xd1,0xcc,0xc7,0xae,0xa5,0xb8,0xb3,0x82,0x89,0x94,0x9f,
0x46,0x4d,0x50,0x5b,0x6a,0x61,0x7c,0x77,0x1e,0x15,0x08,0x03,0x32,0x39,0x24,0x2f,
0x8d,0x86,0x9b,0x90,0xa1,0xaa,0xb7,0xbc,0xd5,0xde,0xc3,0xc8,0xf9,0xf2,0xef,0xe4,
0x3d,0x36,0x2b,0x20,0x11,0x1a,0x07,0x0c,0x65,0x6e,0x73,0x78,0x49,0x42,0x5f,0x54,
0xf7,0xfc,0xe1,0xea,0xdb,0xd0,0xcd,0xc6,0xaf,0xa4,0xb9,0xb2,0x83,0x88,0x95,0x9e,
0x47,0x4c,0x51,0x5a,0x6b,0x60,0x7d,0x76,0x1f,0x14,0x09,0x02,0x33,0x38,0x25,0x2e,
0x8c,0x87,0x9a,0x91,0xa0,0xab,0xb6,0xbd,0xd4,0xdf,0xc2,0xc9,0xf8,0xf3,0xee,0xe5,
0x3c,0x37,0x2a,0x21,0x10,0x1b,0x06,0x0d,0x64,0x6f,0x72,0x79,0x48,0x43,0x5e,0x55,
0x01,0x0a,0x17,0x1c,0x2d,0x26,0x3b,0x30,0x59,0x52,0x4f,0x44,0x75,0x7e,0x63,0x68,
0xb1,0xba,0xa7,0xac,0x9d,0x96,0x8b,0x80,0xe9,0xe2,0xff,0xf4,0xc5,0xce,0xd3,0xd8,
0x7a,0x71,0x6c,0x67,0x56,0x5d,0x40,0x4b,0x22,0x29,0x34,0x3f,0x0e,0x05,0x18,0x13,
0xca,0xc1,0xdc,0xd7,0xe6,0xed,0xf0,0xfb,0x92,0x99,0x84,0x8f,0xbe,0xb5,0xa8,0xa3
};
const unsigned long int muld[256]=
{
0x00,0x0d,0x1a,0x17,0x34,0x39,0x2e,0x23,0x68,0x65,0x72,0x7f,0x5c,0x51,0x46,0x4b,
0xd0,0xdd,0xca,0xc7,0xe4,0xe9,0xfe,0xf3,0xb8,0xb5,0xa2,0xaf,0x8c,0x81,0x96,0x9b,
0xbb,0xb6,0xa1,0xac,0x8f,0x82,0x95,0x98,0xd3,0xde,0xc9,0xc4,0xe7,0xea,0xfd,0xf0,
0x6b,0x66,0x71,0x7c,0x5f,0x52,0x45,0x48,0x03,0x0e,0x19,0x14,0x37,0x3a,0x2d,0x20,
0x6d,0x60,0x77,0x7a,0x59,0x54,0x43,0x4e,0x05,0x08,0x1f,0x12,0x31,0x3c,0x2b,0x26,
0xbd,0xb0,0xa7,0xaa,0x89,0x84,0x93,0x9e,0xd5,0xd8,0xcf,0xc2,0xe1,0xec,0xfb,0xf6,
0xd6,0xdb,0xcc,0xc1,0xe2,0xef,0xf8,0xf5,0xbe,0xb3,0xa4,0xa9,0x8a,0x87,0x90,0x9d,
0x06,0x0b,0x1c,0x11,0x32,0x3f,0x28,0x25,0x6e,0x63,0x74,0x79,0x5a,0x57,0x40,0x4d,
0xda,0xd7,0xc0,0xcd,0xee,0xe3,0xf4,0xf9,0xb2,0xbf,0xa8,0xa5,0x86,0x8b,0x9c,0x91,
0x0a,0x07,0x10,0x1d,0x3e,0x33,0x24,0x29,0x62,0x6f,0x78,0x75,0x56,0x5b,0x4c,0x41,
0x61,0x6c,0x7b,0x76,0x55,0x58,0x4f,0x42,0x09,0x04,0x13,0x1e,0x3d,0x30,0x27,0x2a,
0xb1,0xbc,0xab,0xa6,0x85,0x88,0x9f,0x92,0xd9,0xd4,0xc3,0xce,0xed,0xe0,0xf7,0xfa,
0xb7,0xba,0xad,0xa0,0x83,0x8e,0x99,0x94,0xdf,0xd2,0xc5,0xc8,0xeb,0xe6,0xf1,0xfc,
0x67,0x6a,0x7d,0x70,0x53,0x5e,0x49,0x44,0x0f,0x02,0x15,0x18,0x3b,0x36,0x21,0x2c,
0x0c,0x01,0x16,0x1b,0x38,0x35,0x22,0x2f,0x64,0x69,0x7e,0x73,0x50,0x5d,0x4a,0x47,
0xdc,0xd1,0xc6,0xcb,0xe8,0xe5,0xf2,0xff,0xb4,0xb9,0xae,0xa3,0x80,0x8d,0x9a,0x97
};
const unsigned long int mule[256] =
{
0x00,0x0e,0x1c,0x12,0x38,0x36,0x24,0x2a,0x70,0x7e,0x6c,0x62,0x48,0x46,0x54,0x5a,
0xe0,0xee,0xfc,0xf2,0xd8,0xd6,0xc4,0xca,0x90,0x9e,0x8c,0x82,0xa8,0xa6,0xb4,0xba,
0xdb,0xd5,0xc7,0xc9,0xe3,0xed,0xff,0xf1,0xab,0xa5,0xb7,0xb9,0x93,0x9d,0x8f,0x81,
0x3b,0x35,0x27,0x29,0x03,0x0d,0x1f,0x11,0x4b,0x45,0x57,0x59,0x73,0x7d,0x6f,0x61,
0xad,0xa3,0xb1,0xbf,0x95,0x9b,0x89,0x87,0xdd,0xd3,0xc1,0xcf,0xe5,0xeb,0xf9,0xf7,
0x4d,0x43,0x51,0x5f,0x75,0x7b,0x69,0x67,0x3d,0x33,0x21,0x2f,0x05,0x0b,0x19,0x17,
0x76,0x78,0x6a,0x64,0x4e,0x40,0x52,0x5c,0x06,0x08,0x1a,0x14,0x3e,0x30,0x22,0x2c,
0x96,0x98,0x8a,0x84,0xae,0xa0,0xb2,0xbc,0xe6,0xe8,0xfa,0xf4,0xde,0xd0,0xc2,0xcc,
0x41,0x4f,0x5d,0x53,0x79,0x77,0x65,0x6b,0x31,0x3f,0x2d,0x23,0x09,0x07,0x15,0x1b,
0xa1,0xaf,0xbd,0xb3,0x99,0x97,0x85,0x8b,0xd1,0xdf,0xcd,0xc3,0xe9,0xe7,0xf5,0xfb,
0x9a,0x94,0x86,0x88,0xa2,0xac,0xbe,0xb0,0xea,0xe4,0xf6,0xf8,0xd2,0xdc,0xce,0xc0,
0x7a,0x74,0x66,0x68,0x42,0x4c,0x5e,0x50,0x0a,0x04,0x16,0x18,0x32,0x3c,0x2e,0x20,
0xec,0xe2,0xf0,0xfe,0xd4,0xda,0xc8,0xc6,0x9c,0x92,0x80,0x8e,0xa4,0xaa,0xb8,0xb6,
0x0c,0x02,0x10,0x1e,0x34,0x3a,0x28,0x26,0x7c,0x72,0x60,0x6e,0x44,0x4a,0x58,0x56,
0x37,0x39,0x2b,0x25,0x0f,0x01,0x13,0x1d,0x47,0x49,0x5b,0x55,0x7f,0x71,0x63,0x6d,
0xd7,0xd9,0xcb,0xc5,0xef,0xe1,0xf3,0xfd,0xa7,0xa9,0xbb,0xb5,0x9f,0x91,0x83,0x8d
};
const unsigned long int MatriceMixcolum_inverse[4][4] =
{ {0x0e , 0x0b , 0x0d , 0x09},
{0x09 , 0x0e , 0x0b , 0x0d},
{0x0d , 0x09 , 0x0e , 0x0b},
{0x0b , 0x0d , 0x09 , 0x0e}
};
const unsigned long int mul3[256] =
{ 0x00, 0x03, 0x06, 0x05, 0x0c, 0x0f, 0x0a, 0x09, 0x18, 0x1b, 0x1e, 0x1d, 0x14, 0x17, 0x12, 0x11,
0x30, 0x33, 0x36, 0x35, 0x3c, 0x3f, 0x3a, 0x39, 0x28, 0x2b, 0x2e, 0x2d, 0x24, 0x27, 0x22, 0x21,
0x60, 0x63, 0x66, 0x65, 0x6c, 0x6f, 0x6a, 0x69, 0x78, 0x7b, 0x7e, 0x7d, 0x74, 0x77, 0x72, 0x71,
0x50, 0x53, 0x56, 0x55, 0x5c, 0x5f, 0x5a, 0x59, 0x48, 0x4b, 0x4e, 0x4d, 0x44, 0x47, 0x42, 0x41,
0xc0, 0xc3, 0xc6, 0xc5, 0xcc, 0xcf, 0xca, 0xc9, 0xd8, 0xdb, 0xde, 0xdd, 0xd4, 0xd7, 0xd2, 0xd1,
0xf0, 0xf3, 0xf6, 0xf5, 0xfc, 0xff, 0xfa, 0xf9, 0xe8, 0xeb, 0xee, 0xed, 0xe4, 0xe7, 0xe2, 0xe1,
0xa0, 0xa3, 0xa6, 0xa5, 0xac, 0xaf, 0xaa, 0xa9, 0xb8, 0xbb, 0xbe, 0xbd, 0xb4, 0xb7, 0xb2, 0xb1,
0x90, 0x93, 0x96, 0x95, 0x9c, 0x9f, 0x9a, 0x99, 0x88, 0x8b, 0x8e, 0x8d, 0x84, 0x87, 0x82, 0x81,
0x9b, 0x98, 0x9d, 0x9e, 0x97, 0x94, 0x91, 0x92, 0x83, 0x80, 0x85, 0x86, 0x8f, 0x8c, 0x89, 0x8a,
0xab, 0xa8, 0xad, 0xae, 0xa7, 0xa4, 0xa1, 0xa2, 0xb3, 0xb0, 0xb5, 0xb6, 0xbf, 0xbc, 0xb9, 0xba,
0xfb, 0xf8, 0xfd, 0xfe, 0xf7, 0xf4, 0xf1, 0xf2, 0xe3, 0xe0, 0xe5, 0xe6, 0xef, 0xec, 0xe9, 0xea,
0xcb, 0xc8, 0xcd, 0xce, 0xc7, 0xc4, 0xc1, 0xc2, 0xd3, 0xd0, 0xd5, 0xd6, 0xdf, 0xdc, 0xd9, 0xda,
0x5b, 0x58, 0x5d, 0x5e, 0x57, 0x54, 0x51, 0x52, 0x43, 0x40, 0x45, 0x46, 0x4f, 0x4c, 0x49, 0x4a,
0x6b, 0x68, 0x6d, 0x6e, 0x67, 0x64, 0x61, 0x62, 0x73, 0x70, 0x75, 0x76, 0x7f, 0x7c, 0x79, 0x7a,
0x3b, 0x38, 0x3d, 0x3e, 0x37, 0x34, 0x31, 0x32, 0x23, 0x20, 0x25, 0x26, 0x2f, 0x2c, 0x29, 0x2a,
0x0b, 0x08, 0x0d, 0x0e, 0x07, 0x04, 0x01, 0x02, 0x13, 0x10, 0x15, 0x16, 0x1f, 0x1c, 0x19, 0x1a,
};
const unsigned long int mul2[256] =
{ 0x00, 0x02, 0x04, 0x06, 0x08, 0x0a ,0x0c , 0x0e, 0x10 ,0x12, 0x14, 0x16, 0x18, 0x1a, 0x1c, 0x1e,
0x20, 0x22, 0x24, 0x26, 0x28, 0x2a ,0x2c , 0x2e, 0x30 ,0x32, 0x34, 0x36, 0x38, 0x3a, 0x3c, 0x3e,
0x40, 0x42, 0x44, 0x46, 0x48, 0x4a ,0x4c , 0x4e, 0x50 ,0x52, 0x54, 0x56, 0x58, 0x5a, 0x5c, 0x5e,
0x60, 0x62, 0x64, 0x66, 0x68, 0x6a ,0x6c , 0x6e, 0x70 ,0x72, 0x74, 0x76, 0x78, 0x7a, 0x7c, 0x7e,
0x80, 0x82, 0x84, 0x86, 0x88, 0x8a ,0x8c , 0x8e, 0x90 ,0x92, 0x94, 0x96, 0x98, 0x9a, 0x9c, 0x9e,
0xa0, 0xa2, 0xa4, 0xa6, 0xa8, 0xaa ,0xac , 0xae, 0xb0 ,0xb2, 0xb4, 0xb6, 0xb8, 0xba, 0xbc, 0xbe,
0xc0, 0xc2, 0xc4, 0xc6, 0xc8, 0xca ,0xcc , 0xce, 0xd0 ,0xd2, 0xd4, 0xd6, 0xd8, 0xda, 0xdc, 0xde,
0xe0, 0xe2, 0xe4, 0xe6, 0xe8, 0xea ,0xec , 0xee, 0xf0 ,0xf2, 0xf4, 0xf6, 0xf8, 0xfa, 0xfc, 0xfe,
0x1b, 0x19, 0x1f, 0x1d, 0x13, 0x11 ,0x17 , 0x15, 0x0b ,0x09, 0x0f, 0x0d, 0x03, 0x01, 0x07, 0x05,
0x3b, 0x39, 0x3f, 0x3d, 0x33, 0x31 ,0x37 , 0x35, 0x2b ,0x29, 0x2f, 0x2d, 0x23, 0x21, 0x27, 0x25,
0x5b, 0x59, 0x5f, 0x5d, 0x53, 0x51 ,0x57 , 0x55, 0x4b ,0x49, 0x4f, 0x4d, 0x43, 0x41, 0x47, 0x45,
0x7b, 0x79, 0x7f, 0x7d, 0x73, 0x71 ,0x77 , 0x75, 0x6b ,0x69, 0x6f, 0x6d, 0x63, 0x61, 0x67, 0x65,
0x9b, 0x99, 0x9f, 0x9d, 0x93, 0x91 ,0x97 , 0x95, 0x8b ,0x89, 0x8f, 0x8d, 0x83, 0x81, 0x87, 0x85,
0xbb, 0xb9, 0xbf, 0xbd, 0xb3, 0xb1 ,0xb7 , 0xb5, 0xab ,0xa9, 0xaf, 0xad, 0xa3, 0xa1, 0xa7, 0xa5,
0xdb, 0xd9, 0xdf, 0xdd, 0xd3, 0xd1 ,0xd7 , 0xd5, 0xcb ,0xc9, 0xcf, 0xcd, 0xc3, 0xc1, 0xc7, 0xc5,
0xfb, 0xf9, 0xff, 0xfd, 0xf3, 0xf1 ,0xf7 , 0xf5, 0xeb ,0xe9, 0xef, 0xed, 0xe3, 0xe1, 0xe7, 0xe5
};
const unsigned long int MatriceMixcolum[4][4] =
{ {0x02 , 0x03 , 0x01 , 0x01},
{0x01 , 0x02 , 0x03 , 0x01},
{0x01 , 0x01 , 0x02 , 0x03},
{0x03 , 0x01 , 0x01 , 0x02}
};
const unsigned long int RCON[11] ={ 0x8d , 0x01 , 0x02 , 0x04, 0x08 , 0x10 , 0x20 ,0x40 , 0x80 , 0x1b , 0x36 };
const unsigned long int SBOX_AES[256] =
{
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16
};
void paddingExtractor(char * filename){
FILE *fic= fopen(filename , "rb");
char *buffer;
fseek(fic, 0L, SEEK_END);
unsigned long fileLen = ftell(fic);
fseek(fic, 0L, SEEK_SET);
buffer = calloc(fileLen+1, sizeof(char));
fread(buffer, fileLen,1,fic);
fclose(fic);
buffer[fileLen]='\0';
int j = fileLen;
for(int i= fileLen-1; i > fileLen -16; i--){
if (buffer[i]!=0){
j=i;
break;
}
}
// buffer[j]='\0';
fic= fopen(filename , "wb");
fwrite(buffer,j+1, 1, fic);
fclose(fic);
}
/*******************fonction_commune*******************/
int expension_cle_rsa( unsigned long int k[][4] , unsigned long int **w ){
unsigned long int i , j ;
for ( j = 0; j <=3; ++j) //pour tout les colonnes
{
for ( i = 0; i <=3 ; ++i) // pour tout les lignes
{
w[j][i]=k[j][i];
}
}
for ( j =4 ; j < 44; ++j )
{
if ( j%4 == 0 )
{
w[0][j]=w[0][j-4]^SBOX_AES[ (int)w[1][j-1] ]^RCON[j/4];
for ( i = 1; i <4; ++i)
{
w[i][j]=w[i][j-4]^SBOX_AES[ (int)w[(i+1)%4 ][j-1] ];
}
}
else {
for (i=0 ; i<4 ; i++ )
{
w[i][j]=w[i][j-4]^w[i][j-1];
}
}
}
return 0 ;
}
int numero_cle_aes(unsigned long int ** w , unsigned long int K[][4] , int numero ){
for (int i = 0; i <4 ; ++i)
for (int j = 0; j <4 ; ++j )
{
K[i][j]=w[i][4*numero + j];
}
return 0 ;
}
void afficherTableau( unsigned long int t[][4] , unsigned long int x, unsigned long int y)
{
int i;
int j;
for(i=0; i<x; i++)
{
for(j=0; j<y; j++)
{
printf("%02lx \t ", t[i][j]);
}
printf("\n");
printf("\n");
printf("\n");
}
}
int AddRoundKey(unsigned long int entre[][4] , unsigned long int cles[][4] )
{
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
entre[i][j]=entre[i][j]^cles[i][j];
}
}
return 0;
}
int copie_tableau(unsigned long int entre[][4] , unsigned long int sortie[][4] )
{
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
sortie[i][j]=entre[i][j];
}
}
return 0 ;
}
/********************************************/
int XOR(unsigned long int tab1[][4] , unsigned long int tab2[][4] )
{
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
tab2[i][j]=tab2[i][j]^tab1[i][j];
}
}
return 0;
}
int creer_fichier_128_bit(char *nom_fichier , unsigned long int tab[][4]){
FILE *fic ;
if ((fic= fopen(nom_fichier , "wb")) == NULL) {
printf("Je ne peux pas ouvrir %s", nom_fichier );
return 0;
}
for (int i = 0; i < 4 ; ++i)
{
for (int j = 0; j < 4 ; ++j)
{
fprintf(fic, "%02lx",tab[j][i] );
}
}
fclose(fic);
return 1 ;
}
int lecture_cles_128_bit(char *nom_fichier , unsigned long int tab[][4]){
FILE *fic ;
int val ;
int compteur=0 ;
if ((fic= fopen(nom_fichier , "rb")) == NULL) {
printf("Je ne peux pas ouvrir %s", nom_fichier );
return 0;
}
fseek(fic , 0L , SEEK_END );
compteur=ftell(fic);
fseek(fic,0L,SEEK_SET);
fclose(fic);
if (compteur!=32)
{
fprintf(stderr, "\n erreur taille de cles incorrect dans le fichier :%s\n",nom_fichier );
fclose(fic);
return 0;
}
if ((fic= fopen(nom_fichier , "rb")) == NULL) {
printf("Je ne peux pas ouvrir %s", nom_fichier );
return 0; }
for (int i = 0; i < 4 ; ++i)
{
for (int j = 0; j < 4 ; ++j)
{
fscanf(fic, "%02lx",&tab[j][i] );
}
}
fclose(fic);
return 1;
}
int completer_fichier(char *nom_fichier ){
FILE *fic , *fic2;
int i=0 ,val , reste , mul_16 ;
int car=0 ;
if ((fic= fopen(nom_fichier , "rb+")) == NULL) {
printf("Je ne peux pas ouvrir %s", nom_fichier );
return 0;
}
while (( val = fgetc(fic)) !=EOF) {
i++;
}
mul_16 = i/16;
if ( i%16 == 0)
{
fclose(fic);
return mul_16 ;
/* code */
}
if ( i%16 != 0 )
{
reste=i%16 ;
reste = 16-reste ;
for (int j = 0; j < reste; ++j)
{ //putchar( (char)car );
fputc( car , fic );
}
fclose(fic);
mul_16 = mul_16 +1 ;
return mul_16 ;
}
}
int completer_fichier2(char *nom_fichier ){
FILE *fic , *fic2;
int i=0 ,val , reste , mul_16 ;
int car=0 ;
if ((fic= fopen(nom_fichier , "rb+")) == NULL) {
printf("Je ne peux pas ouvrir %s", nom_fichier );
return 0;
}
while (( val = fgetc(fic)) !=EOF) {
i++;
}
mul_16 = i/16;
if ( i%16 == 0)
{
fclose(fic);
return mul_16 ;
}
return 0;
}
int decouper_16(char *nom_fichier , int numero_curseur , unsigned long int tab[][4] ){
FILE *fic ;
unsigned long int val ;
if ((fic= fopen(nom_fichier, "rb")) == NULL) {
printf("Je ne peux pas ouvrir %s", nom_fichier );
return 0;
}
fseek(fic , numero_curseur*16 , SEEK_SET );
for (int i = 0; i < 4 ; ++i)
{
for (int j = 0; j < 4 ; ++j )
{
//fread(&car, 1,1, fic);
val = fgetc( fic );
tab[j][i]=val;
}
}
fclose(fic);
return 0 ;
}
/**********************************fin*******************/
/*******************fonction_inverse****************/
int Mixcolum_inverse(unsigned long int entre[][4] , unsigned long int sortie[][4] )
{
int i,j,k;
for ( i = 0; i < 4; ++i)
{
for ( j = 0; j < 4; ++j)
{
sortie[j][i]=0x00;
for ( k = 0; k < 4; ++k)
{
if ( MatriceMixcolum_inverse[j][k]==0x0e )
{
sortie[j][i]=sortie[j][i]^mule[entre[k][i]] ;
}
if ( MatriceMixcolum_inverse[j][k]==0x0b )
{
sortie[j][i]=sortie[j][i] ^ mulb[entre[k][i]] ;
}
if ( MatriceMixcolum_inverse[j][k]==0x0d )
{
sortie[j][i]=sortie[j][i]^ muld[ entre[k][i] ] ;
}
if ( MatriceMixcolum_inverse[j][k]==0x09 )
{
sortie[j][i]=sortie[j][i]^ mul9[ entre[k][i] ] ;
}
}
}
}
return 0 ;
}
int SubByte_inverse(unsigned long int entre[][4] )
{
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4 ; ++j)
{
entre[i][j] = invSBOX[entre[i][j]];
}
}
return 0 ;
}
int ShiftRow_inverse(unsigned long int entre[][4] ){
unsigned long int tempo , tempo2 ;
int i ;
for ( i = 1 ; i < 4; ++i)
{
if (i==1)
{
tempo=entre[1][3];
entre[1][3]=entre[1][2];
entre[1][2]=entre[1][1];
entre[1][1]=entre[1][0] ;
entre[1][0]=tempo;
}
if (i==2)
{
tempo=entre[2][3];
tempo2=entre[2][2];
entre[2][2]=entre[2][0];
entre[2][3]=entre[2][1];
entre[2][1]=tempo;
entre[2][0]=tempo2;
}
if (i==3)
{
tempo=entre[3][0];
entre[3][0]=entre[3][1];
entre[3][1]=entre[3][2];
entre[3][2]=entre[3][3];
entre[3][3]=tempo;
}
}
return 0 ;
}
int Round_Aes_inverse(unsigned long int entre[][4] , unsigned long int cles[][4] )
{ unsigned long int sortie[4][4];
ShiftRow_inverse(entre);
SubByte_inverse(entre);
AddRoundKey(entre , cles );
Mixcolum_inverse(entre , sortie );
/*copier la sortie dans le tableau entre*/
copie_tableau(sortie , entre );
return 0 ;
}
int AES_inverse(unsigned long int entre[][4] , unsigned long int cle_initiale[][4] ){
unsigned long int **W ;
unsigned long int cles[4][4];
W=(unsigned long int **)malloc(4 * sizeof(unsigned long int *));
for (int i = 0; i < 4; ++i) W[i]=(unsigned long int *)malloc(44*sizeof( unsigned long int )) ;
/*etendre la cle initiale pour avoir les 11 sous cles dans W */
expension_cle_rsa(cle_initiale , W );
numero_cle_aes(W, cles , 10 );
AddRoundKey(entre, cles );
for (int i =9; i > 0 ; --i)
{
numero_cle_aes(W, cles , i );
Round_Aes_inverse(entre , cles );
}
numero_cle_aes(W, cles , 0 );
ShiftRow_inverse(entre);
SubByte_inverse(entre);
AddRoundKey(entre , cles );
}
/************************fin**************************/
/********************************gen.c*************/
int appele_srand = 0;
int generer_bornes(int min, int max)
{
if(appele_srand != 1)
initialiser_aleat((unsigned)time(NULL));
return rand()%(max-min+1) + min;
}
void initialiser_aleat(unsigned int n)
{
srand(n);
appele_srand = 1;
}
void generer_key(unsigned long int K[][4]){
unsigned long int val;
initialiser_aleat((unsigned)time(NULL));
for(int i = 0; i < 4; ++i){
for (int j = 0; j < 4; ++j)
{
val=generer_bornes(0, 255);
K[j][i]=val;
//printf("%lx\n", val);
}
}
}
//le vecteur d initialisation pour le ECB--------------------
void vecteur_init(unsigned long int vect[][4]){
unsigned long int val;
initialiser_aleat((unsigned)time(NULL)+generer_bornes(23624,759494));
for(int i = 0; i < 4; ++i){
for (int j = 0; j < 4; ++j)
{
val=generer_bornes(0, 255);
vect[j][i]=val;
//printf("%lx\n", val);
}
}
}
/******************************fin**********************/
int Mixcolum(unsigned long int entre[][4] , unsigned long int sortie[][4] )
{
int i,j,k;
for ( i = 0; i < 4; ++i)
{
for ( j = 0; j < 4; ++j)
{
sortie[j][i]=0x00;
for ( k = 0; k < 4; ++k)
{
if ( MatriceMixcolum[j][k]==0x01 )
{
sortie[j][i]=sortie[j][i]^entre[k][i] ;
}
if ( MatriceMixcolum[j][k]==0x02 )
{
sortie[j][i]=sortie[j][i] ^ mul2[entre[k][i]] ;
}
if ( MatriceMixcolum[j][k]==0x03 )
{
sortie[j][i]=sortie[j][i]^ mul3[ entre[k][i] ] ;
}
}
}
}
return 0 ;// returne 0 si tout les calculs sont effectuee
}
int ShiftRow(unsigned long int entre[][4] ){
unsigned long int tempo , tempo2 ;
int i ;
for ( i = 1 ; i < 4; ++i)
{
if (i==1)
{
tempo=entre[1][0];
entre[1][0]=entre[1][1];
entre[1][1]=entre[1][2];
entre[1][2]=entre[1][3] ;
entre[1][3]=tempo;
}
if (i==2)
{
tempo=entre[2][0];
tempo2=entre[2][1];
entre[2][0]=entre[2][2];
entre[2][1]=entre[2][3];
entre[2][2]=tempo;
entre[2][3]=tempo2;
}
if (i==3)
{
tempo=entre[3][3];
entre[3][3]=entre[3][2];
entre[3][2]=entre[3][1];
entre[3][1]=entre[3][0];
entre[3][0]=tempo;
}
}
return 0 ;
}
int SubByte(unsigned long int entre[][4] )
{
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4 ; ++j)
{
entre[i][j] = SBOX_AES[entre[i][j]];
}
}
return 0 ;
}
int Round_Aes(unsigned long int entre[][4] , unsigned long int cles[][4] )
{ unsigned long int sortie[4][4];
SubByte(entre);
ShiftRow(entre);
Mixcolum(entre , sortie );
AddRoundKey(sortie , cles );
/*copier la sortie dans le tableau entre*/
copie_tableau(sortie , entre );
return 0 ;
}
/*la fonction de AES qui fait toute les 10 tours*/
int AES(unsigned long int entre[][4] , unsigned long int cle_initiale[][4] ){
unsigned long int **W ;
unsigned long int cles[4][4];
W=(unsigned long int **)malloc(4 * sizeof(unsigned long int *));
for (int i = 0; i < 4; ++i) W[i]=(unsigned long int *)malloc(44*sizeof( unsigned long int )) ;
/*etendre la cle initiale pour avoir les 11 sous cles dans W */
expension_cle_rsa(cle_initiale , W );
numero_cle_aes(W, cles , 0 );
AddRoundKey(entre, cles );
for (int i = 1; i < 10 ; ++i)
{
numero_cle_aes(W, cles , i );
Round_Aes(entre , cles );
}
numero_cle_aes(W, cles , 10 );
SubByte(entre);
ShiftRow(entre);
AddRoundKey(entre , cles );
}
/*******************************MODE ECB************************************************/
int ecb_aes_chiffrer(char *nom_fichier_entre , char *nom_fichier_sortie , char *fichier_key ){
int mul_16 ;
FILE *fic , *fic1, *fic3 ;
unsigned long int cle[4][4];
unsigned long int donne[4][4];
lecture_cles_128_bit(fichier_key , cle);
if ((fic= fopen(nom_fichier_entre , "rb")) == NULL) {
printf("Je ne peux pas ouvrir %s", nom_fichier_entre );
return 0;
}
if ((fic3= fopen("tmp/aes.tmp", "wb")) == NULL) {
printf("Je ne peux pas ouvrir %s", nom_fichier_entre );
return 0;
}
fseek(fic, 0L, SEEK_END);
int fileLen= ftell(fic);
fseek(fic, 0L, SEEK_SET);
char *buffer=calloc(fileLen+1,sizeof(char));
fread(buffer, fileLen, 1, fic);
fwrite(buffer,fileLen,1,fic3);
fclose(fic);
fclose(fic3);
nom_fichier_entre = calloc(strlen("tmp/aes.tmp"), sizeof(char));
strcpy(nom_fichier_entre,"tmp/aes.tmp");
mul_16 = completer_fichier(nom_fichier_entre );
if ((fic1= fopen(nom_fichier_sortie , "wb")) == NULL)
{
printf("Je ne peux pas ouvrir %s", nom_fichier_sortie );
exit(1);
}
for (int k = 0 ; k < mul_16 ; ++k)
{
decouper_16(nom_fichier_entre , k , donne ) ;
AES(donne , cle );
//afficherTableau(donne,4,4);
//printf("--------------------------\n");
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
//fprintf(fic1 , "%lx\t",donne[j][i] );
fputc((int)donne[j][i] , fic1 );
}
}
}
fclose( fic1 );
return 1;
}
int ecb_aes_dechiffrer(char *nom_fichier_entre , char *nom_fichier_sortie , char *fichier_key ){
int mul_16 ;
FILE *fic , *fic1, *fic3;
unsigned long int donne[4][4] , cle[4][4];
lecture_cles_128_bit( fichier_key, cle);
if ((fic= fopen(nom_fichier_entre , "rb")) == NULL) {
printf("Je ne peux pas ouvrir %s", nom_fichier_entre );
return 0;
}
if ((fic3= fopen("tmp/aes.tmp", "wb")) == NULL) {
printf("Je ne peux pas ouvrir %s", nom_fichier_entre );
return 0;
}
fseek(fic, 0L, SEEK_END);
int fileLen= ftell(fic);
fseek(fic, 0L, SEEK_SET);
char *buffer=calloc(fileLen+1,sizeof(char));
fread(buffer, fileLen, 1, fic);
fwrite(buffer,fileLen,1,fic3);
fclose(fic);
fclose(fic3);
nom_fichier_entre = calloc(strlen("tmp/aes.tmp"), sizeof(char));
strcpy(nom_fichier_entre,"tmp/aes.tmp");
/****************************************************/
/* A CORRIGER */
mul_16 = completer_fichier2(nom_fichier_entre );
if(mul_16==0)
return 0;
if ((fic1= fopen(nom_fichier_sortie , "wb")) == NULL) {
printf("Je ne peux pas ouvrir %s", nom_fichier_sortie );
return 0 ;
}
for (int k = 0 ; k < mul_16 ; ++k)
{
decouper_16(nom_fichier_entre , k , donne ) ;
AES_inverse(donne , cle );
//afficherTableau(donne,4,4);
//printf("--------------------------\n");
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
//fprintf(fic1 , "%lx\t",donne[j][i] );
fputc((int)donne[j][i] , fic1 );
}
}
}
fclose( fic1 );
paddingExtractor(nom_fichier_sortie);
return 1;
}
int CBC_aes_chiffrer(char *nom_fichier_entre , char *nom_fichier_sortie , char *fichier_key , char *fichier_vecteur_initial ){
int mul_16 ;
FILE *fic , *fic1, *fic3 ;
unsigned long int donne[4][4] , donne1[4][4] ;
unsigned long int vecteur[4][4] , cle[4][4] ;
lecture_cles_128_bit( fichier_key, cle);
//vecteur_init(vecteur);
if ((fic= fopen(nom_fichier_entre , "rb")) == NULL) {
printf("Je ne peux pas ouvrir %s", nom_fichier_entre );
return 0;
}
if ((fic3= fopen("tmp/aes.tmp", "wb")) == NULL) {
printf("Je ne peux pas ouvrir %s", nom_fichier_entre );
return 0;
}
fseek(fic, 0L, SEEK_END);
int fileLen= ftell(fic);
fseek(fic, 0L, SEEK_SET);
char *buffer=calloc(fileLen+1,sizeof(char));
fread(buffer, fileLen, 1, fic);
fwrite(buffer,fileLen,1,fic3);
fclose(fic);
fclose(fic3);
nom_fichier_entre = calloc(strlen("tmp/aes.tmp"), sizeof(char));
strcpy(nom_fichier_entre, "tmp/aes.tmp");
lecture_cles_128_bit( fichier_vecteur_initial , vecteur );
mul_16 = completer_fichier(nom_fichier_entre );
if ((fic1= fopen(nom_fichier_sortie , "wb")) == NULL) {
printf("Je ne peux pas ouvrir %s", nom_fichier_sortie );
return 0;
}
decouper_16(nom_fichier_entre , 0 , donne ) ;
XOR(vecteur , donne);
AES(donne , cle );
/**ecrire dans le fichier**/
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
//fprintf(fic1 , "%lx\t",donne[j][i] );
fputc((int)donne[j][i] , fic1 );
}
}
/*****fin ecritutre***/
for (int k = 1 ; k < mul_16 ; ++k)
{
decouper_16(nom_fichier_entre , k , donne1 ) ;
XOR(donne1 , donne );
AES(donne , cle );
//afficherTableau(donne,4,4);
//printf("--------------------------\n");
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
//fprintf(fic1 , "%lx\t",donne[j][i] );
fputc((int)donne[j][i] , fic1 );
}
}
}
fclose( fic1 );
return 1;
}
int CBC_aes_dechiffrer(char *nom_fichier_entre , char *nom_fichier_sortie , char *fichier_key , char *fichier_vecteur_initial ){
int mul_16 ;
FILE *fic , *fic1, *fic3 ;
unsigned long int donne[4][4] , donne1[4][4] , tampo[4][4] ;
unsigned long int vecteur[4][4] , cle[4][4];
//vecteur_init(vecteur);
lecture_cles_128_bit( fichier_vecteur_initial , vecteur);
lecture_cles_128_bit( fichier_key, cle);
if ((fic= fopen(nom_fichier_entre , "rb")) == NULL) {
printf("Je ne peux pas ouvrir %s", nom_fichier_entre );
return 0;
}
if ((fic3= fopen("tmp/aes.tmp", "wb")) == NULL) {
printf("Je ne peux pas ouvrir %s", nom_fichier_entre );
return 0;
}
fseek(fic, 0L, SEEK_END);
int fileLen= ftell(fic);
fseek(fic, 0L, SEEK_SET);
char *buffer=calloc(fileLen+1,sizeof(char));
fread(buffer, fileLen, 1, fic);
fwrite(buffer,fileLen,1,fic3);
fclose(fic);
fclose(fic3);
strcpy(nom_fichier_entre,"tmp/aes.tmp");
mul_16 = completer_fichier2(nom_fichier_entre );
if(mul_16 ==0)
return 0;
if ((fic1= fopen(nom_fichier_sortie , "wb")) == NULL) {
printf("Je ne peux pas ouvrir %s", nom_fichier_sortie );
return 0 ;
}
for (int k = 0 ; k < mul_16 ; ++k)
{
decouper_16(nom_fichier_entre , k , donne ) ;
copie_tableau(donne ,tampo );
AES_inverse(donne , cle );
XOR(vecteur , donne );
copie_tableau(tampo,vecteur);
//afficherTableau(donne,4,4);
//printf("--------------------------\n");
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
//fprintf(fic1 , "%lx\t",donne[j][i] );
fputc((int)donne[j][i] , fic1 );
}
}
}
fclose( fic1 );
paddingExtractor(nom_fichier_sortie);
return 1;
}
/********************************************************************/
char * CBC_MAC_AES(char *nom_fichier_entre , char *nom_fichier_sortie , char *fichier_key, char *sortie ){
FILE *fic;
if ((fic= fopen("tmp/tmp.iv.key" , "wb")) == NULL) {
printf("Je ne peux pas ouvrir ");
return 0;
}
/*********************************************************/
/* MAC CBC IV = 0 *
**********************************************************/
char *buf1 = calloc(33,sizeof(char));
for (int i = 0, j = 0; i < 16; ++i, j += 2)
sprintf(buf1 + j, "%02x", 0 & 0xff);
fwrite(buf1,32,1,fic);
fclose(fic);
int ret = CBC_aes_chiffrer(nom_fichier_entre ,nom_fichier_sortie ,fichier_key, "tmp/tmp.iv.key");
if (ret == 1){
fic= fopen(nom_fichier_sortie , "rb");
char buf2[16];
fseek(fic, -16, SEEK_END);
fread(buf2, 16, 1, fic);
fclose(fic);
for (int i = 0, j = 0; i < 16; ++i, j += 2)
sprintf(buf1 + j, "%02x", buf2[i] & 0xff);
buf1[32]='\0';
fic= fopen(nom_fichier_sortie , "wb");
fwrite(buf1,32,1,fic);
fclose(fic);
strcpy(sortie,buf1);
return sortie;
}
return "";
}
<file_sep>#include <stdio.h>
#include<stdlib.h>
#include<time.h>
unsigned char SBOX[256] =
{
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16
};
int Table_poids_hamming_octet[256] =
{
0 , 1 , 1 , 2 , 1 , 2 , 2 , 3 , 1 , 2 , 2 , 3 , 2 , 3 , 3 , 4,
1 , 2 , 2 , 3 , 2 , 3 , 3 , 4 , 2 , 3 , 3 , 4 , 3 , 4 , 4 , 5,
1 , 2 , 2 , 3 , 2 , 3 , 3 , 4 , 2 , 3 , 3 , 4 , 3 , 4 , 4 , 5,
2 , 3 , 3 , 4 , 3 , 4 , 4 , 5 , 3 , 4 , 4 , 5 , 4 , 5 , 5 , 6,
1 , 2 , 2 , 3 , 2 , 3 , 3 , 4 , 2 , 3 , 3 , 4 , 3 , 4 , 4 , 5,
2 , 3 , 3 , 4 , 3 , 4 , 4 , 5 , 3 , 4 , 4 , 5 , 4 , 5 , 5 , 6,
2 , 3 , 3 , 4 , 3 , 4 , 4 , 5 , 3 , 4 , 4 , 5 , 4 , 5 , 5 , 6,
3 , 4 , 4 , 5 , 4 , 5 , 5 , 6 , 4 , 5 , 5 , 6 , 5 , 6 , 6 , 7,
1 , 2 , 2 , 3 , 2 , 3 , 3 , 4 , 2 , 3 , 3 , 4 , 3 , 4 , 4 , 5,
2 , 3 , 3 , 4 , 3 , 4 , 4 , 5 , 3 , 4 , 4 , 5 , 4 , 5 , 5 , 6,
2 , 3 , 3 , 4 , 3 , 4 , 4 , 5 , 3 , 4 , 4 , 5 , 4 , 5 , 5 , 6,
3 , 4 , 4 , 5 , 4 , 5 , 5 , 6 , 4 , 5 , 5 , 6 , 5 , 6 , 6 , 7,
2 , 3 , 3 , 4 , 3 , 4 , 4 , 5 , 3 , 4 , 4 , 5 , 4 , 5 , 5 , 6,
3 , 4 , 4 , 5 , 4 , 5 , 5 , 6 , 4 , 5 , 5 , 6 , 5 , 6 , 6 , 7,
3 , 4 , 4 , 5 , 4 , 5 , 5 , 6 , 4 , 5 , 5 , 6 , 5 , 6 , 6 , 7,
4 , 5 , 5 , 6 , 5 , 6 , 6 , 7 , 5 , 6 , 6 , 7 , 6 , 7 , 7 , 8
};
int calcul_distribution( int trace[] , int taille_trace , int distrib[] ){
for (int i=0 ; i<9 ; i++){
distrib[i]=0 ;
}
for (int i=0 ; i< taille_trace ; i++){
distrib[ trace[i] ] = distrib[ trace[i] ] + 1 ;
}
return 0 ;
}
int main(int argc, char *argv[] )
{
unsigned char k , m , y , g , bonne_g ;
int h , N_nbre_trace , Nbre_Run , W_taille_trace ;
double score[256] , max ;
int compteur=0 ;
double ACCumulateur[256][9][9];
double D_g_h[256][9][9];
double ACC_A[9];
int *trace ;
int distribution[9];
if ( argc !=4 )
{
fprintf(stderr, "\n erreur : le nombre parametre doit etre égale à 3 : W , N , R \n" );
return 0;
}
W_taille_trace=atoi(argv[1]);
N_nbre_trace=atoi(argv[2]);
Nbre_Run = atoi(argv[3]);
srand(time(NULL));
printf("\n hello world \n");
trace = (int*)malloc( W_taille_trace*sizeof( int) ) ;
for( int i=0 ; i < Nbre_Run ; i++)
{
k = rand()%256 ;
/*initialiser ACCumulateur*/
for( g=0 ; g<256 ; g ++ )
{
for ( h =0; h<9 ; h++)
{
for( int i =0 ; i <9 ; i++ )
{
ACCumulateur[g][h][i]=0 ;
}
}
if ( g == 255 ) break ;/*pour eviter une boucle infinie car 255 + 1 = 0 */
}
/*initialiser ACC_A */
for( h=0 ; h< 9 ; h++ )
{
ACC_A[h]=0 ;
}
//printf("\n hello world \n");
/*pour les N chiffrements */
for(int i= 0 ; i<N_nbre_trace ; i++)
{
m = rand()%256 ;
y = SBOX[m^k];
h = Table_poids_hamming_octet[y];
/*génération d'une trace aléatoire : W_taille_trace-1 point aleatoire et 1 point correspondant au poids hamming de sortie de sbox*/
trace[0] = h ;
for( int i=1 ; i< W_taille_trace ; i++ )
{
trace[i] = Table_poids_hamming_octet[ (rand()%256) ];
}
/*calcul de la distribution du trace */
calcul_distribution( trace , W_taille_trace , distribution );
/*integrer la trace dans ACC_A*/
for( h = 0 ; h <9 ; h++ ) ACC_A[h] = ACC_A[h] + distribution [h] ;
/*pour tout les hyptothèse de clés*/
for ( g = 0 ; g<256 ; g++ )
{
y =SBOX[ m^g ];
h =Table_poids_hamming_octet[y];
/*integrer la trace dans ACCumulateur_g_h*/
for( int i=0 ; i <9 ; i++ ) ACCumulateur[g][h][i]= ACCumulateur[g][h][i] + distribution[i] ;
if ( g == 255 ) break ;/*pour eviter une boucle infinie car 255 + 1 = 0 */
}
}
/*Calcul de la somme des effectifs de ACCumulateur_g_h et de ACC_c*/
long int somme_effectif[256][9] , somme = 0 ;
for( g=0 ; g<256 ; g++ )
{
for (h=0; h<9 ; h++)
{
somme_effectif[g][h]=0;
for( int i=0 ; i<9 ; i++ )
{
somme_effectif[g][h] = somme_effectif[g][h] + ACCumulateur [g][h][i] ;
}
}
if ( g == 255 ) break ;/*pour eviter une boucle infinie car 255 + 1 = 0 */
}
for( h=0 ; h<9 ; h++) somme = somme + ACC_A[h] ;
/* diviser par la somme des effectifs pour avoir la normalisation */
for( g=0 ; g<256 ; g++ )
{
for ( h =0; h<9 ; h++)
{
for( int i=0 ; i<9 ; i++ )
{
ACCumulateur[g][h][i]= ACCumulateur[g][h][i]/somme_effectif[g][h] ;
}
}
if ( g == 255 ) break ;/*pour eviter une boucle infinie car 255 + 1 = 0 */
}
/* diviser par la somme des effectifs pour avoir la normalisation */
for( h=0 ; h<9 ; h++) ACC_A[h] = ACC_A[h]/somme ;
/*initialisation de D_g_h*/
for( g=0 ; g<256 ; g++ )
{
for ( h=0; h<9 ; h++)
{
for( int i=0 ; i<9 ; i++ )
{
D_g_h[g][h][i]=0 ;
}
}
if ( g == 255 ) break ;/*pour eviter une boucle infinie car 255 + 1 = 0 pour un octet*/
}
/*calcul de tout les D_g_h = ACC_g_h - ACC_A */
for( g=0 ; g<256 ; g++ )
{
for ( h=0; h<9 ; h++)
{
for( int i=0 ; i<9 ; i++ )
{
D_g_h[g][h][i] = ACCumulateur[g][h][i]-ACC_A[i];
}
}
if ( g == 255 ) break ;/*pour eviter une boucle infinie car 255 + 1 = 0 */
}
/*calcul des scores pour le cas: score[g][4] */
for(int i=0 ; i<256 ; i++) score[i]=0 ;
for ( g =0 ; g<256 ; g++ )
{
for( int i = 0 ; i<9 ; i++ )
{
score[g]= score[g] + ( D_g_h[g][4][i] * D_g_h[g][4][i] ) ;
}
if ( g == 255 ) break ;/*pour eviter une boucle infinie car 255 + 1 = 0 */
}
/*la clée est le g qui est au max des scores[g] */
max = score[0];
bonne_g = 0 ;
for ( g=1 ; g<256 ; g++)
{
if (score[g]>max)
{
max = score[g];
bonne_g = g ;
}
//printf("score[%d]=%d , max = %d \n",g,score[g] , max);
if ( g == 255 ) break ;/*pour eviter une boucle infinie car 255 + 1 = 0 */
}
/*tester si l'attaque à reussi*/
if (bonne_g == k )
{
compteur = compteur + 1 ;
printf("\n max = %f bonne_g = %d et k= %u : succés \n",max , bonne_g , k);
}
}
printf("\n l'attaque à reussi en moyenne %d sur %d runs\n", compteur , Nbre_Run );
return 0 ;
}
| 9fe80b307746095e5ca4a588bd3ef9e93d540f08 | [
"C"
] | 3 | C | diaodiallo1996/Master2-cryptis | 0b000acd7b71ca814b384a7f9e29cb98f2f24f64 | b5ccff39c1e53cc6e9de5aff3aa78c295daba173 |
refs/heads/master | <file_sep>#!/usr/bin/env bash
### end common-components/bash-shebang
# ASSUMPTIONS
# 1. Zsh is your current shell
# 2. Git is already installed
# Welcome to the Tripcraft Rails deployment script. We forked the Thoughtbot script
# after they abandoned linux support.
trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT
set -e
### end common-components/exit-trap
if [[ ! -d "$HOME/.bin/" ]]; then
mkdir "$HOME/.bin"
fi
if [ ! -f "$HOME/.zshrc" ]; then
touch $HOME/.zshrc
fi
if [[ ":$PATH:" != *":$HOME/.bin:"* ]]; then
printf 'export PATH="$HOME/.bin:$PATH"\n' >> ~/.zshrc
export PATH="$HOME/.bin:$PATH"
fi
### end common-components/check-home-bin
fancy_echo() {
printf "\n%b\n" "$1"
}
### end common-components/shared-functions
if ! grep -qiE 'precise|quantal|wheezy|raring|jessie|saucy|trusty' /etc/os-release; then
fancy_echo "Sorry! we don't currently support that distro."
exit 1
fi
### end linux-components/distro-check
fancy_echo "Updating system packages ..."
if command -v aptitude >/dev/null; then
fancy_echo "Using aptitude ..."
else
fancy_echo "Installing aptitude ..."
sudo apt-get install -y aptitude
fi
sudo aptitude update
### end linux-components/debian-package-update
fancy_echo "Installing ntp"
sudo aptitude install -y ntp
fancy_echo "Installing libraries for common gem dependencies ..."
sudo aptitude install -y libxslt1-dev libcurl4-openssl-dev libksba8 libksba-dev libqtwebkit-dev libreadline-dev
fancy_echo "Installing build-essential"
sudo aptitude install -y build-essential
fancy_echo "Installing Postgres, a good open source relational database ..."
sudo aptitude install -y postgresql postgresql-server-dev-all
fancy_echo "Installing curl ..."
sudo aptitude install -y curl
fancy_echo "Installing pg dev libraries ..."
sudo aptitude install -y libpq-dev
# ATTEMPTS TO INSTALL NGINX
# Install Phusion's PGP key to verify packages
gpg --keyserver keyserver.ubuntu.com --recv-keys <KEY>
gpg --armor --export <KEY>F7 | sudo apt-key add -
# Add HTTPS support to APT
sudo apt-get install apt-transport-https
# Add the passenger repository
sudo sh -c "echo 'deb https://oss-binaries.phusionpassenger.com/apt/passenger trusty main' >> /etc/apt/sources.list.d/passenger.list"
sudo chown root: /etc/apt/sources.list.d/passenger.list
sudo chmod 600 /etc/apt/sources.list.d/passenger.list
sudo apt-get update
# Install nginx and passenger
sudo apt-get -y install nginx-full passenger
<file_sep>Laptop
======
Laptop is a script to set up linux servers and laptops with a Rails environment. It was forked from the Thoughtbot script of the same name after they dropped linux support.
This script is useful for server deployments as well so I've created seperate versions for those environments.
linux == A generic linux laptop. It can feasibly have the text editing software added back and allow the database to exist on the same machine.
development_server == Remove text editing and allow the database to exist on the same machine.
production_server == No text editing or database.
I get that puppet or chef is a more accepted way of automating this. :)
Requirements
------------
We support:
Ubuntu 14
Ubuntu 15
Install
-------
Install zsh and make it your default shell
chmod +x ./linux
./linux
Debugging
---------
Your last Laptop run will be saved to `~/laptop.log`. Read through it to see if
you can debug the issue yourself.
What it sets up
---------------
* [Bundler] for managing Ruby libraries
* [ImageMagick] for cropping and resizing images
* [Node.js] and [NPM], for running apps and installing JavaScript packages
* [NVM] for managing versions of Node.js
* [Parity] for development, staging, and production parity
* [Rails] gem for writing web applications
* [Rbenv] for managing versions of Ruby
* [Ruby Build] for installing Rubies
* [Ruby] stable for writing general-purpose code
* [Watch] for periodically executing a program and displaying the output
[Bundler]: http://bundler.io/
[ImageMagick]: http://www.imagemagick.org/
[Node.js]: http://nodejs.org/
[NVM]: https://github.com/creationix/nvm
[Parity]: https://github.com/croaky/parity
[Rails]: http://rubyonrails.org/
[Rbenv]: https://github.com/sstephenson/rbenv
[Ruby Build]: https://github.com/sstephenson/ruby-build
[Ruby]: https://www.ruby-lang.org/en/
[Watch]: http://linux.die.net/man/1/watch
It should take less than 15 minutes to install (depends on your machine).
Laptop can be run multiple times on the same machine safely. It will upgrade
already installed packages and install and activate a new version of ruby (if
one is available).
Credits
-------
Thoughtbot created the original version of the linux script but has abandoned support of it.

Contributing
------------
Edit the `linux` file.
License
-------
It is free software, and may be redistributed under the terms specified in the LICENSE file.
| 9b27e7ee355f1baaad2dc46533eeeeff3fa9f5d6 | [
"Markdown",
"Shell"
] | 2 | Shell | eightfiveseven/laptop | f0b5d581e08d42b95f3af84d56c0713e057e873b | ac790163e8fa28ed1dcad608c801f905d1a5125e |
refs/heads/master | <file_sep>"use strict";
{
const table = document.querySelector('table');
const myId = promisify((cb) => chrome.windows.getCurrent(cb));
const focusMe = promisify((wid, cb) => chrome.windows.update(wid, {focused:true}, cb));
Object.assign(self, {focusMe,myId});
table.addEventListener('click', e => {
const target = e.target;
if ( target.matches('button.run') ) {
document.querySelector('.scanning').classList.add('show');
chrome.tabs.create({url:'https://www.facebook.com/',active:false});
} else if ( target.matches('button.fix') ) {
alert(target.closest('.report').dataset.advice);
}
});
let id;
let scansRunning = 4;
chrome.runtime.onMessage.addListener( async (msg, sender, reply) => {
if ( msg.type == 'idFound' ) {
id = msg.id;
scansRunning = 4;
const {id:windowId} = await myId();
await countPublicPhotosTagged(id);
await focusMe(windowId);
await countPublicPhotosLiked(id);
await focusMe(windowId);
await countPublicStoriesTagged(id);
await focusMe(windowId);
await countPublicStoriesLiked(id);
await focusMe(windowId);
} else if ( msg.type == 'countUpdate' ) {
const countEl = document.querySelector(`#${msg.countType} .count`);
countEl.innerText = msg.count;
if ( !! msg.done ) {
document.querySelector(`#${msg.countType} button.fix`).disabled = false;
scansRunning --;
if ( scansRunning == 0 ) {
document.querySelector('.scanning').classList.remove('show');
}
}
}
});
}
<file_sep>"use strict";
{
// aim is to promisify all extension apis that use callbacks
const expose = {
promisify
};
Object.assign(self, expose);
function promisify(func) {
return async function(...args) {
return new Promise((res,rej) => {
try {
func(...args, res);
} catch(e) {
rej(e);
}
});
}
}
}
<file_sep>"use strict";
{
chrome.tabs.create({active:true,url: chrome.extension.getURL('ui.html')});
chrome.runtime.onMessage.addListener( (msg, sender, reply) => {
console.log("MSG", msg);
});
}
<file_sep># Social Surface
[On the Chrome Web Store](https://chrome.google.com/webstore/detail/ddppdlkajpgigjdadijekacliockbchd)
*Note: this item may still be being published. You can download and install it as an "Unpacked Extension" from this repository.*
Review public items exposed on your social surface with a **very simple and basic** Security Assessment tool.
## Screenshot

## Info
**Scan and Fix all public information you are exposing to people through your Facebook account**
Review counts and details of public stories and photos you are tagged in or which you have liked on Facebook, to understand what items are exposed on your social surface. This basic beta-version extension includes very simple advice to fix these vulnerabilities, with future paid versions maybe including the ability to fix it automatically for you.
### Usage
After you click "Run Facebook Security Assessment", we will open 4 windows in the background. We use these to scan public information about your profile to report to you the numbers of exposed items regarding you in your social surface.
Our advice to fix any unintentional exposure is simple and manual. It will require you to do it yourself. In future, paid versions of this extension may offer the ability to automatically fix your social surface exposure.
The 4 windows are created in the background. You can review the photos and stores you are tagged in and have liked by viewing those windows.
### More Info
Determine if any information you would rather be private has become public by accident. Use this Security Assessment tool to reveal exposed items on your social surface.
### Disclaimer
Don't use this for anything bad. We're not responsible for any harm arising from using this.
| f9a7345754333b062314e7027507cf8833e41b8d | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | DOSYCORPS/social-surface | c0143f23064a330b2e8f05ba64d2127dd9c0d2c1 | 3769d6241b3e1a40f741131b5492ef9f547face4 |
refs/heads/master | <file_sep>package ExcelTest.ExcelTry;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class MainPage extends BasePage {
public MainPage(WebDriver driver) {
super(driver);
}
// WebElements
@FindBy(id = "header_logo")
WebElement logo;
@FindBy(className = "login")
WebElement signInBtn;
@FindBy(id="email")
WebElement loginFld;
@FindBy(id="passwd")
WebElement passwordFld;
@FindBy(id="SubmitLogin")
WebElement submitBtn;
@FindBy(className="logout")
WebElement logoutBtn;
// Open target page
public void openPage(String url) {
driver.get(url);
waitForPageLoad();
Log.info("Opening page " + url);
}
// Verification if Page is displayed
public boolean isLogoDisplayed() {
boolean isLogoDisplayed = false;
isLogoDisplayed = isElementOnPage(logo);
if (isLogoDisplayed = true) {
Log.info("User is on Page");
} else {
Log.info("User is not on Page");
}
return isLogoDisplayed;
}
//Method to login the page
public void logIn(String value) {
signInBtn.click();
Log.info("Zaloguj was clicked");
loginFld.sendKeys(value);
passwordFld.sendKeys("<PASSWORD>");
submitBtn.click();
}
//Veryfication if user is loged in
public boolean isLogedIn() {
boolean isLogedIn = false;
isLogedIn=isElementOnPage(logoutBtn);
if(isLogedIn=true) {
Log.info("User is Loged In");
}else {
Log.error("User is not loged In");
}
return isLogedIn;
}
}
<file_sep>browser=chrome
login=<EMAIL>
password=<PASSWORD>
url=http://automationpractice.com | c7448874b28d6d9410d33510f96ce7d851f52904 | [
"Java",
"INI"
] | 2 | Java | PiotrMilosz/CleanFramework | 088bb8b6671308c062223c5d87b7724a55fe110e | 51a2b86c6185171941ad2086cb070e596ac87214 |
refs/heads/master | <repo_name>kri55is/LocationCatScanner<file_sep>/src/com/example/locationcatscanner/SplashScreenActivity.java
package com.example.locationcatscanner;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
public class SplashScreenActivity extends Activity {
private static final String TAG = "SplashScreenActivity";
private final long DELAY = 1000;
LinearLayout mLayout = null;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Log.d(TAG, "***onCreate***");
mLayout = (LinearLayout)RelativeLayout.inflate(this, R.layout.splash_screen, null);
setContentView(mLayout);
try{
new Handler().postDelayed(new Runnable(){
@Override
public void run(){
Intent mainIntent = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(mainIntent);
}
}
, DELAY);
}
catch(Exception e){
Log.e(TAG, e.toString());
}
}
}
<file_sep>/src/com/example/locationcatscanner/MainActivity.java
package com.example.locationcatscanner;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;
public class MainActivity extends ActionBarActivity {
private static final String TAG = "MainActivity";
RelativeLayout mLayout = null;
TextView mPositionValue = null;
ToggleButton mNetworkButton = null;
ToggleButton mSatelliteButton = null;
ToggleButton mAutoButton = null;
LocationManager locMan = null;
boolean mGpsInUse = false;
boolean mNetworkInUse = false;
boolean mAutoInUse = true;
LocationListener locListener;
long MIN_TIME = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLayout = (RelativeLayout)RelativeLayout.inflate(this, R.layout.activity_main, null);
Log.d(TAG, "***onCreate***");
locMan = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
if (locMan != null) {
locListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
Log.d(TAG, "***onStatusChanged to " + status);
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onLocationChanged(Location location) {
Log.d(TAG,
"***onLocationChanged to lat "
+ location.getLatitude() + ", long "
+ location.getLongitude());
printPosition(location);
}
};
} else {
Log.d(TAG, "locMan is null");
}
updateLocationManagerListener();
mPositionValue = (TextView) mLayout.findViewById(R.id.positionValue);
mNetworkButton = (ToggleButton) mLayout.findViewById(R.id.networkButton);
mNetworkButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
forceNetworkUse();
}
});
mSatelliteButton = (ToggleButton) mLayout.findViewById(R.id.satelliteButton);
mSatelliteButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
forceSatelliteUse();
}
});
mAutoButton = (ToggleButton) mLayout.findViewById(R.id.autoButton);
mAutoButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
forceAutoUse();
}
});
mAutoButton.setPressed(true);
mAutoButton.setChecked(true);
setContentView(mLayout);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
void updateLocationManagerListener(){
if (locMan == null) {
locMan = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
}
else{
locMan.removeUpdates(locListener);
if (mAutoInUse){
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, 0.1f,
locListener);
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, 0.1f,
locListener);
}
else{
if(mGpsInUse)
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, 0.1f,
locListener);
if(mNetworkInUse)
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, 0.1f,
locListener);
}
}
}
void forceNetworkUse(){
mNetworkInUse = true;
mGpsInUse = false;
mAutoInUse = false;
updateLocationManagerListener();
mSatelliteButton.setChecked(false);
mAutoButton.setChecked(false);
}
void forceSatelliteUse(){
mNetworkInUse = false;
mGpsInUse = true;
mAutoInUse = false;
updateLocationManagerListener();
mNetworkButton.setChecked(false);
mAutoButton.setChecked(false);
}
void forceAutoUse(){
mNetworkInUse = false;
mGpsInUse = false;
mAutoInUse = true;
updateLocationManagerListener();
mNetworkButton.setChecked(false);
mSatelliteButton.setChecked(false);
}
void networkOn(){
if (!mNetworkInUse){
mNetworkInUse = true;
mNetworkButton.setChecked(true);
}
}
void networkOff(){
if (mNetworkInUse){
mNetworkInUse = false;
mNetworkButton.setChecked(false);
}
}
void gpsOff(){
if (mGpsInUse){
mGpsInUse = false;
mSatelliteButton.setChecked(false);
}
}
void gpsOn(){
if (!mGpsInUse){
mGpsInUse = true;
mSatelliteButton.setChecked(true);
}
}
public void printPosition(Location loc) {
String provider = loc.getProvider();
String position = "lat: " + loc.getLatitude() + " long "
+ loc.getLongitude() + provider;
mPositionValue.setText(position);
if (provider.equals("network")){
networkOn();
gpsOff();
}
else{
networkOff();
gpsOn();
}
}
}
<file_sep>/README.md
# LocationCatScanner
Android App
Android app retreiving coordinates either with gps or with network
Eclipse used.
| 0bcb0311c28907cc3357193cf1d97c82625524cd | [
"Markdown",
"Java"
] | 3 | Java | kri55is/LocationCatScanner | 1767594ba5592ba4d847dfe365277c908ed4d9cf | 7e79bd71b69717e3af16352dfe59c479987f9f99 |
refs/heads/master | <repo_name>smokeme/challenge<file_sep>/main.py
def check_param(param):
total = 0
for letter in param:
total += ord(letter)
return total
def main_function():
print('- Type `exit` to stop the application')
print('- Try and find the secret key')
while(1):
print('- ')
print('- Enter secret code:')
user_input = input('> ')
if (user_input == "exit"):
print('- Thank you for trying!')
exit()
if (len(user_input) > 17):
print('- Too long try again')
else:
user_input = user_input.split('-')
if check_param("".join(user_input)) == 1121:
if check_param(user_input[0]) == 377:
if check_param(user_input[1]) == 225:
if check_param(user_input[2]) == 519:
print('--------------------------------------------------------')
print('- Like a Boss -')
print('--------------------------------------------------------')
break
print('- Wrong code try again')
if __name__ == '__main__':
main_function()
#hint, it should be something like this "my-secret-key"
| 8f2668df576bd255a47f6442550be11d38c072e5 | [
"Python"
] | 1 | Python | smokeme/challenge | 401a66f9e238fac419e05a9c56e272c411b052b5 | 11b54534a1979b75e6b383344d32131171e83207 |
refs/heads/master | <repo_name>TheHeidal/a9<file_sep>/tRead.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <sys/errno.h>
#include <assert.h>
#include "queue.h"
#include "disk.h"
#include "uthread.h"
queue_t pending_read_queue;
unsigned int sum = 0;
void interrupt_service_routine () {
// TODO
uthread_t pendingReadwaitingThread;
void* pendingReadingWaitingThreadv = &pendingReadwaitingThread;
queue_dequeue(pending_read_queue, pendingReadingWaitingThreadv, NULL, NULL);
uthread_unblock (pendingReadwaitingThread);
}
void* read_block (void* blocknov) {
// TODO schedule read and the update (correctly)
int result;
uthread_t pendingReadwaitingThread = uthread_self();
disk_schedule_read(&result, *(int*) blocknov);
queue_enqueue(pending_read_queue, pendingReadwaitingThread, NULL, NULL);
uthread_block();
// update sum
sum = result + sum;
return NULL;
}
int main (int argc, char** argv) {
// Command Line Arguments
static char* usage = "usage: tRead num_blocks";
int num_blocks;
char *endptr;
if (argc == 2)
num_blocks = strtol (argv [1], &endptr, 10);
if (argc != 2 || *endptr != 0) {
printf ("argument error - %s \n", usage);
return EXIT_FAILURE;
}
// Initialize
uthread_init (1);
disk_start (interrupt_service_routine);
pending_read_queue = queue_create();
// Sum Blocks
// TODO
int blocks[num_blocks];
uthread_t threads[num_blocks];
for (int blockno = 0; blockno < num_blocks; blockno++) {
blocks[blockno] = blockno;
threads[blockno] = uthread_create(&read_block, &blocks[blockno]);
}
for (int blockno = 0; blockno < num_blocks; blockno++) {
uthread_join(threads[blockno], 0);
}
printf ("%d\n", sum);
}<file_sep>/treasureHunt.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/errno.h>
#include <assert.h>
#include "uthread.h"
#include "queue.h"
#include "disk.h"
queue_t pending_read_queue;
int areyoudoneyet;
void interrupt_service_routine() {
areyoudoneyet = 0;
}
// initiate next read once u have result from previous read
void handleOtherReads (void* resultv, void* countv) {
if (*(int*) countv == 0) {
printf("%d \n", *(int*) resultv);
free(resultv);
free(countv);
exit (EXIT_SUCCESS);
} else {
areyoudoneyet = 1;
disk_schedule_read(resultv, *(int*) resultv);
while (areyoudoneyet == 1) {
}
*(int*) countv = *(int*) countv - 1;
handleOtherReads(resultv, countv);
}
}
void handleFirstRead (void* resultv, void* countv) {
areyoudoneyet = 1;
int* counter = malloc(sizeof(int));
int* nextadd = malloc(sizeof(int));
disk_schedule_read(nextadd, *(int*) resultv);
while (areyoudoneyet == 1) {
}
*counter = *nextadd;
handleOtherReads(nextadd, counter);
}
int main (int argc, char** argv) {
// Command Line Arguments
static char* usage = "usage: treasureHunt starting_block_number";
int starting_block_number;
char *endptr;
if (argc == 2)
starting_block_number = strtol (argv [1], &endptr, 10);
if (argc != 2 || *endptr != 0) {
printf ("argument error - %s \n", usage);
return EXIT_FAILURE;
}
// Initialize
uthread_init (1);
disk_start (interrupt_service_routine);
pending_read_queue = queue_create();
// Start the Hunt
handleFirstRead(&starting_block_number, &starting_block_number);
while (1);
}
| a5c4668ed36c0b8aa3fba467439b7aeb0399cad7 | [
"C"
] | 2 | C | TheHeidal/a9 | ab79ad2bb7730d939a453bd5af3256080e3224d0 | 753fca74016e2857cdbc18b83cbd6ebbabaa309e |
refs/heads/master | <repo_name>simonstre/jobot<file_sep>/README.md
Dependencies:
* Require patched hubot to forward http options and HUBOT_ADAPTER_PATH workaround. See https://github.com/MacKeeper/hubot
* Require patched scoped-http-client to accept 'rejectUnauthorized: false'. See https://github.com/MacKeeper/node-scoped-http-client
* Require redis. Install from http://redis.io/ and run redis-server
* Require
To use forks of 'hubot' and 'scoped-http-client':
* In 'hubot' and 'node-scoped-http-client' repo, run 'npm link'
* In 'jobot' repo, run 'npm link hubot' and 'npm link scoped-http-client'
* Because of the way nope find dependencies, hubot won't be able to find the hubot-xmpp adapter. node lookup directories for dependencies but fails big time with symlink (which npm link creates)
* Environment variable HUBOT_ADAPTER_PATH is set in the launchers to workaround this
Configure IntelliJ:
* Install coffeescript plugin
* Install File watcher plugin
* To run a .coffee file, edit the default run configuration for node and check the 'Run with coffeescript plugin'.
* You will have to set a path to the coffee executable. If not installed, install with 'npm install -g coffeescript' and the executable should be '/usr/local/bin/coffee'
* To debug a .coffee file
* In Projects Settings, File Watcher, add a coffeescript file watcher (_coffeescript_ *not* coffeescript source map)
* Uncheck 'Immediate file synchronization'
* Arguments should be '--compile --map $FileName$'
* Output paths should be '$FileNameWithoutExtension$.js:$FileNameWithoutExtension$.map'
* Edit the default run configuration for node and *uncheck* the 'Run with coffeescript plugin'.
* On the generated .js file, run in debug and the .coffee file breakpoints will trigger.
* Note: debugging feels a bit experimental. You can also add breakpoints in the .js file
<file_sep>/testutil/ssh_test.js
var control = require( 'control' )
var shared = Object.create( control.controller ), addresses = [ 'localhost' ]
shared.user = 'mdarveau'
//shared.sshOptions = ['-p 922']
var controllers = control.controllers( addresses, shared )
for ( i = 0, l = controllers.length; i < l; i += 1 ) {
controller = controllers[i]
controller.ssh( 'date', function(data){
console.log(data)
console.log(arguments)
} )
}
// TODO test with https://github.com/mscdex/ssh2<file_sep>/run_localhost.sh
#!/bin/sh
HOSTNAME=`hostname`
#export HUBOT_LOG_LEVEL=debug
export HUDSON_TEST_MANAGER_URL="https://solic1.dev.8d.com:8443"
# Set path to adapter since we are using npm link for hubot dependency. See Readme
export HUBOT_ADAPTER_PATH=`pwd`/node_modules/
export HUBOT_XMPP_USERNAME=hubot@${HOSTNAME}
export HUBOT_XMPP_CONFERENCE_DOMAINS=conference.${HOSTNAME}
export HUBOT_XMPP_PASSWORD=<PASSWORD>
export HUBOT_XMPP_ROOMS=deploy@conference.${HOSTNAME}
export HUBOT_XMPP_HOST=localhost
export HUBOT_XMPP_PORT=5222
./bin/hubot -n jobot -a xmpp
<file_sep>/run_8D.sh
#!/bin/sh
#export HUBOT_LOG_LEVEL=debug
# Set path to adapter since we are using npm link for hubot dependency. See Readme
export HUBOT_ADAPTER_PATH=`pwd`/node_modules/
# ${HUBOT_XMPP_PASSWORD:?"Need to set HUBOT_XMPP_PASSWORD: export HUBOT_XMPP_PASSWORD=..."}
if [ -z "$HUBOT_XMPP_PASSWORD" ]; then
read -p "Jabber password:" HUBOT_XMPP_PASSWORD
export HUBOT_XMPP_PASSWORD=$HUBOT_XMPP_PASSWORD
echo $HUBOT_XMPP_PASSWORD
fi
export HUBOT_XMPP_CONFERENCE_DOMAINS=conference.jabber.8d.com
export HUBOT_XMPP_USERNAME=<EMAIL>
export HUBOT_XMPP_ROOMS=<EMAIL>
export HUBOT_XMPP_HOST=jabber.8d.com
export HUBOT_XMPP_PORT=5222
./bin/hubot -n jobot -a xmpp
| da75e577b3d566f01339f7537748b5218c657b0e | [
"Markdown",
"JavaScript",
"Shell"
] | 4 | Markdown | simonstre/jobot | 719e8926d00c33c7da4d0561cb10190e7b60b0aa | d511eb0937950f3d32572267506f370324b54f9f |
refs/heads/master | <repo_name>Gaurang2811/DsJs<file_sep>/README.md
# DsJs
Data Structures with Java Script
<file_sep>/src/stack.js
function Stack() {
let stack = [];
return {
push(item) {
return stack.push(item)
},
pop() {
return stack.pop();
},
isEmpty() {
return stack.length === 0;
},
peek() {
return stack[stack.length -1];
}
}
}
let stack = new Stack();
stack.push('Item1');
stack.push('Item2');
console.log(stack.isEmpty());
console.log(stack.peek());
console.log(stack.pop());
console.log(stack.peek());
stack.push('Item3');
console.log(stack.pop());
console.log(stack.isEmpty());
console.log(stack.pop());
console.log(stack.isEmpty());<file_sep>/src/linkedList.js
function createNode(value) {
return {
value,
next: null
}
}
function LinkedList() {
return {
head: null,
tail: null,
length: 0,
add(item) {
const node = createNode(item);
if (this.head === null) { // this.isEmpty() (i.e this.length === 0)
this.head = node;
this.tail = node;
this.length++;
return node;
}
this.tail.next = node;
this.tail = node;
this.length++;
return node;
},
remove() {
if (this.head === null) { // this.isEmpty() (i.e this.length === 0)
return null;
}
const node = this.tail;
if (this.head === this.tail) { // this.length === 1
this.head = null;
this.tail = null;
this.length--;
return node;
}
let current = this.head;
let penultimate;
while (current) {
if (current.next === this.tail) {
penultimate = current;
break;
}
current = current.next;
}
penultimate.next = null;
this.tail = penultimate;
this.length--;
return node;
},
get(index) {
if (index < 0 || index > this.length) {
return null;
}
if (index === 0) {
return this.head;
}
let current = this.head;
for (let i = 0; i < index; i++) {
current = current.next;
}
return current;
},
delete(index) {
if (index < 0 || index > this.length) {
return null;
}
if (index === 0) {
const deleted = this.head;
this.head = this.head.next;
this.length--;
return deleted;
}
let current = this.head;
let previous;
for (let i = 0; i < index; i++) {
previous = current;
current = current.next;
}
const deleted = current;
previous.next = current.next;
this.length--;
return deleted;
},
isEmpty() {
return this.length === 0;
},
print() {
let current = this.head;
let list = [];
while (current) {
list.push(current.value);
current = current.next;
}
return console.log(list.join(' => '));
}
}
}
let list = new LinkedList();
console.log(list.isEmpty());
list.add('a');
list.add('b');
list.add('c');
list.add('d');
list.add('e');
list.print();
console.log(list.remove())
list.print();
console.log(list.get(2))
list.delete(2);
list.print();
<file_sep>/src/queue.js
function Queue() {
let queue = []
return {
enqueue(item) {
return queue.push(item)
},
dequeue() {
return queue.shift() || null;
},
get length() {
return queue.length;
},
peek() {
return queue[0];
},
isEmpty() {
return queue.length === 0;
}
}
}
let q = new Queue();
q.enqueue('Gaurang');
q.enqueue('Omar')
q.enqueue('Smart')
console.log(q.length)
q.enqueue('Man')
console.log(q.length)
console.log(q.dequeue())
console.log(q.dequeue())
console.log(q.peek())
console.log(q.dequeue())
console.log(q.peek())
console.log(q.dequeue())
console.log(q.dequeue())
q.enqueue('Yooo')
console.log(q.length)
console.log(q.peek())
console.log(q.isEmpty())
console.log(q.dequeue())
console.log(q.isEmpty())
| 318768930aecf9c07fb3a6d4feac59c0815bffcd | [
"Markdown",
"JavaScript"
] | 4 | Markdown | Gaurang2811/DsJs | d4465cedee84788aefbe20110769525e09d147fe | 10097d3a52cc40105e93448f0bf4dacab85a27a9 |
refs/heads/main | <repo_name>swathi1310/Basic_Practicing_Codes<file_sep>/max_sum.py
""" Kadane’s Algorithm
here we have to find max sum of corresponding numbers for example
in a list [1, 2, 3, -2, 5] the max number is 9 i.e, sum(1, 2, 3, -2, 5)
list [-1, -2, -3, -4] the max sum is -1
"""
"""t = int(input())
for _ in range(t):
n = int(input())
arr = list(map(int, input().split()))
sub_arr = []
for i in range(n + 1):
for j in range(i + 1, n + 1):
sub_arr.append(arr[i:j]) # this is to make sublist
_sum = list(map(sum, sub_arr)) # instead of this we can also use [sum(i) for i in zip(*sub_arr)]
print(max(_sum))"""
t = int(input()) # other code
for _ in range(t):
n = int(input())
arr = list(map(int, input().split()[:n]))
_sum = [arr[0]]
for i in range(1, n):
_sum.append(max(arr[i], _sum[i - 1] + arr[i]))
print(max(_sum))
<file_sep>/noshi.py
for i in range(0, 7):
for j in range(0, 7):
if j == 0 or j == 6 or (i == j and j > 0):
print("*", end="")
else:
print(end=" ")
print(end=" ")
for j in range(8, 14):
if (j == 8 and (0 < i < 6)) or (j == 13 and (0 < i < 6)) or ((8 < j < 13) and (i == 0 or i == 6)):
print("*", end="")
else:
print(end=" ")
print(end=" ")
for j in range(15, 22):
if (j > 15 and i == 0) or (j == 15 and (i == 1 or i == 2)) or (j > 15 and i == 3) or (j == 21 and (i == 4 or i == 5)) or (j < 21 and i == 6):
print("*", end="")
else:
print(end=" ")
print(end=" ")
for j in range(23, 30):
if j == 23 or j == 29 or (j >= 23 and i == 3):
print("*", end="")
else:
print(end=" ")
print(end=" ")
for j in range(31, 38):
if j == 34 or (j >= 31 and (i == 0 or i == 6)):
print("*", end="")
else:
print(end=" ")
print()
<file_sep>/convertdate.py
Date=input("Enter the date:")
list=["January","February","March","April","May","June","July","August","September","October","November","December"]
if Date[-5]=='/':
M,D,Y=Date.split("/")
print("{}/{}/{}".format(D,M,Y))
else:
M,Date=Date.split(" ")
D,Y=Date.split(",")
if M in list:
M=list.index(M)+1
print("{}/{}/{}".format(D,M,Y))
<file_sep>/majority_ele.py
"""t = int(input())
for _ in range(t):
n = int(input())
ele = list(map(int, input().split()[:n]))
_max = 0
flag = 0
for i in ele:
cnt = ele.count(i)
ele = list(filter(lambda x: x != i, ele))
if cnt > _max and cnt > n/2:
_max = cnt
flag = 1
if flag == 1:
print(i)
else:
print("-1")"""
test = int(input())
for z in range(test):
size = int(input())
arr = list(map(int, input().split()))
s = set(arr)
d = {}
for i in s:
d[i] = 0
for i in arr:
d[i] += 1
a = -1
for i in d.keys():
if d.get(i) > size // 2:
a = i
print(a)
<file_sep>/closing value.py
n = int(input())
bu = []
values = []
for i in range(n):
value = list(map(str, input().split()))
buy = {'id': 0, 'type': 'xx', 'name': 'aa', 'price': 0, 'quantity': 0}
if value[1] == 'Buy':
buy['id'] = int(value[0])
buy['type'] = str(value[1])
buy['name'] = str(value[2])
buy['price'] = int(value[3])
buy['quantity'] = int(value[4])
bu.append(buy)
values.append(value)
res = [[key for key in bu[0].keys()], *[list(idx.values()) for idx in bu]]
cnt = 0
cn = 0
for j in range(n):
for k in range(1, len(res)):
if values[j][2] == res[k][2] and values[j][1] != 'Buy':
if int(values[j][3]) <= res[k][3] and int(values[j][4]) <= res[k][4]:
print("{}:{}".format(values[j][2], values[j][3]))
cn = 1
break
else:
cnt = 1
break
else:
cnt = 1
break
if cnt == 1 and cn != 1:
print("Stocks not traded")<file_sep>/Subarray.py
# problem:
"""Given an unsorted array A of size N of non-negative integers, find a continuous sub-array which adds to a given number S.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow.
Each test case consists of two lines. The first line of each test case is N and S, where N is the size of array and S is the sum
The second line of each test case contains N space separated integers denoting the array elements.
Output:
For each testcase, in a new line, print the starting and ending positions(1 indexing) of first such occuring subarray from the left if sum equals to subarray, else print -1.
Constraints:
1 <= T <= 100
1 <= N <= 107
1 <= Ai <= 1010
Example:
Input:
2
5 12
1 2 3 7 5
10 15
1 2 3 4 5 6 7 8 9 10
Output:
2 4
1 5
Explanation :
Testcase1: sum of elements from 2nd position to 4th position is 12
Testcase2: sum of elements from 1st position to 5th position is 15"""
T = int(input())
for i in range(T):
N, S = map(int, input().split())
a = list(map(int, input().split()))
wsum = 0
start = 0
flag = 0
for j in range(N):
if flag == 0:
wsum = wsum + a[j]
while wsum > S:
wsum = wsum - a[start]
start = start + 1
if wsum == S:
flag = 1
print(start + 1, end=" ")
print(j + 1)
break
if flag == 0:
print('-1')
<file_sep>/gsk.py
# remove consecutive letters from a string
t = int(input())
for _ in range(t):
string = input()
_str = ""
for i in range(len(string) - 1):
if string[i] != string[i + 1]:
if string[i] != string[i - 1]:
_str += string[i]
if string[-1] != _str[-1] and string[-1] != string[-2]:
_str += string[-1]
print(_str)
# others
t = int(input())
while t > 0:
t = t - 1
s = input()
while True:
p = 0
i = 0
while i < len(s):
j = i + 1
while j < len(s) and s[j] == s[i]:
j += 1
if j != i + 1:
s = s[:i] + s[j:]
p = 1
else:
i += 1
if p == 0:
break
print(s)
<file_sep>/turtile.1.py
import turtle
box = turtle.Screen()
box.bgcolor("yellow")
toy = turtle.Turtle()
toy.color("red")
toy.shape("turtle")
dist = 2
for i in range(100):
toy.forward(dist)
toy.left(45)
toy.forward(dist)
dist += 2
box.exitonclick()
<file_sep>/pythagoren_triplet.py
for _ in range(int(input())):
n = int(input())
arr = [int(i) for i in input().split(",")]
flag = 0
for i in range(n - 2):
for j in range(i+1, n - 1):
for k in range(j+1, n):
a = arr[i]*arr[i]
b = arr[j]*arr[j]
c = arr[k]*arr[k]
if a + b == c or c + a == b or b + c == a:
flag = 1
break
if flag == 1:
print("Yes")
else:
print("No")
<file_sep>/Reverse_array_in_groups.py
t = int(input())
for _ in range(t):
n, k = map(int, input().split())
arr = list(map(int, input().split()[:n]))
sub_arr = []
for i in range((n+k-1)//k):
sub_arr1 = list(reversed(arr[i * k:(i + 1) * k]))
sub_arr.extend(sub_arr1)
print(sub_arr)
<file_sep>/bubble.py
string = (input("Enter the string:"))
i = 0
for i in range(0, len(string)):
for j in range(0, len(string)):
if string[i] == string[j]:
if j > i:
print("$", end="")
else:
print(string[j], end="")
else:
print(string[j], end="")
print()
'''x=input("enter the string:")
#b=x.rfind(x[0])
#print(b)
a=x[1:]
y=(x[0]+a.replace(x[0],'*'))
print(y)'''
# harika program
<file_sep>/palindrome.py
t = int(input())
for _ in range(t):
string = input()
string_rev = string[::-1]
flag = 0
cnt = 0
for i in range(len(string)):
for j in range(len(string), i, -1):
if string[i:] == string_rev[i:j]:
print(string[i:])
flag = 1
break
else:
cnt = 1
if cnt == 1 and flag == 0:
print(string[0]) # vnrtysfrzrmzlygfv
<file_sep>/TrappingRainWater.py
t = int(input())
for _ in range(t):
n = int(input())
arr = list(map(int, input().split()[:n]))
fmax = arr[0]
lmax = max(arr[1:])
unit = 0
for i in range(n):
if arr[i] > fmax:
fmax = arr[i]
if arr[i] == lmax and i < n-1:
lmax = max(arr[i + 1:])
capacity = min(fmax, lmax)
trap = max(capacity - arr[i], 0)
unit += trap
print(unit)
"""for _ in range(int(input())): # other code
n=int(input())
a=list(map(int,input().split()))
lmax=a[0]
rmax=max(a[1:])
count=0
for i in range(n):
if(a[i]>lmax):
lmax=a[i]
if(a[i]==rmax and i<n-1):
rmax=max(a[i+1:])
h=min(lmax,rmax)
count+=max(h-a[i],0)
print(count)"""
| 30f130b657fc4f332a5f5eb048700b4997a4a5e3 | [
"Python"
] | 13 | Python | swathi1310/Basic_Practicing_Codes | a888d80618fbc2b6d07ecc25f06d755681e0973d | 1528a2389fcbc3feb28df8738cdf9f58552baf2e |
refs/heads/master | <repo_name>saumyashah/OsLab<file_sep>/ProducerConsumerTest.java
public class ProducerConsumerTest {
public static void main(String[] args) {
monitor y = new monitor();
Consumer c1 = new Consumer(y, 1);
Producer p1 = new Producer(y, 1);
c1.start();
p1.start();
}
}
class monitor {
private int buffer;
private boolean available = false;
public synchronized int get() {
while (available == false) {
try {
wait();
}
catch (InterruptedException e) {
}
}
available = false;
notifyAll();
return buffer;
}
public synchronized void put(int val) {
while (available == true) {
try {
wait();
}
catch (InterruptedException e) {
}
}
buffer = val;
available = true;
notifyAll();
}
}
class Consumer extends Thread {
private monitor monitor;
private int number;
public Consumer(monitor y, int number) {
monitor = y;
this.number = number;
}
public void run() {
int value = 0;
value = monitor.get();
System.out.println("Consumer #"
+ this.number
+ " got: " + value);
}
}
class Producer extends Thread {
private monitor monitor;
private int number;
public Producer(monitor y, int number) {
monitor = y;
this.number = number;
}
public void run() {
monitor.put(this.number);
System.out.println("Producer #" + this.number
+ " put: " + this.number);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
}
}
<file_sep>/banker_121046.c
#include<stdio.h>
void main()
{
int p,r,i,j;
printf("Enter the number of processes");
scanf("%d",&p);
printf("Enter the number or resources");
scanf("%d",&r);
//Current Allocation Matrix
int curr[p][r];
printf("Enter the current allocation matrix\n");
for (i=0; i<p; i++)
{
for (j=0; j<r; j++)
{
scanf("\n %d",&curr[i][j]);
}
}
printf("\nthe current allocation matrix\n");
for ( i=0; i<p; i++)
{
for (j=0; j<r; j++)
{
printf("%d \t" ,curr[i][j]);
}
printf("\n");
}
//Maximum Allocation Matrix
int max[p][r];
printf("Enter the maximum allocation matrix\n");
for (i=0; i<p; i++)
{
for (j=0; j<r; j++)
{
scanf("\n %d",&max[i][j]);
}
}
printf("\nthe maximum allocation matrix \n");
for ( i=0; i<p; i++)
{
for (j=0; j<r; j++)
{
printf("%d \t" ,max[i][j]);
}
printf("\n");
}
//Need matrix
int need[p][r];
for ( i=0; i<p; i++)
{
for (j=0; j<r; j++)
{
need[i][j]= max[i][j]-curr[i][j];
}
printf("\n");
}
printf("The need matrix is \n ");
for ( i=0; i<p; i++)
{
for (j=0; j<r; j++)
{
printf("%d \t",need[i][j]);
}
printf("\n");
}
//Total reources
int total[r];
printf("\nEnter the total available resources\n");
for(i=0; i<r; i++)
{
scanf("%d",&total[i]);
}
printf("\nThe total available resources\n");
for(i=0; i<r; i++)
{
printf("%d \n",total[i]);
}
//Available resources
int avail[r];
printf("\nEnter the available resources\n");
for(i=0; i<r; i++)
{
scanf("%d",&avail[i]);
}
printf("\nThe available resources\n");
for(i=0; i<r; i++)
{
printf("%d \n",avail[i]);
}
int cnt=0;
int a=0;
int k,b;
int safe[p];
int dead[p];
for(i=0;i<p;i++)
{
dead[i] = 0;
}
for(i=0;i<p;i++)
{
cnt=0;
for(j=0;j<r;j++)
{
//printf("\n j in %d",i);
if(need[i][j]<=avail[j]);
cnt++;
}
//printf("after j for");
if(cnt==r)
{
//printf(" in if");
safe[a]=i+1;
a++;
//printf(" before available print");
for(k =0; k<r; k++)
{
avail[k] = avail[k] + curr[i][k];
need[i][k] = 0;
// printf("avail matrix : %d " , avail[k]);
}
for(k =0; k<r; k++)
{
printf("\n avail matrix :%d",avail[k]);
}
}
else
{
dead[b]=i+1;
b++;
}
//printf (" \n in : %d",i);
}
//printf(" \n out : %d",i);
/*int cnt1;
for(i=0 ; i<(p-a); i++)
{
for(j=0;j<p;j++)
{
for(k=0;k<r;k++)
{
if(need[j][k] != 0)
cnt1++;
}
if(cnt1 == r)
{
}*/
if(dead[0] == 0)
{
for(k =0; k<p; k++)
{
printf("\nSafe state order %d \t",safe[k]);
}
}
else
{
for(i=0;i<b;i++)
{
for(j=dead[i];j<b;j++)
{
for(k=0;k<r;k++)
{
if(need[j][k]<=avail[j])
cnt1++;
}
if(cnt1==r)
{
}
}
| bfc7e6f555c10053d35652cf1a842a9f21f4cf47 | [
"Java",
"C"
] | 2 | Java | saumyashah/OsLab | 1450f79d4613ef0d51711c5fff2f085d2c219392 | db73e991fa355d43e47c87216b5eb47f02f98a02 |
refs/heads/master | <repo_name>crisla/Diss<file_sep>/SimDelta.py
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
import numpy as np
import scipy as sp
import matplotlib.pyplot as pl
import matplotlib as mpl
from scipy import optimize, integrate, interp, randn, stats
from scipy.optimize import fminbound
# <codecell>
""" Parameters """
delta = 0.2
r = 0.05
b = 0.1
y1 = 1.0
y2 = 1.2
beta = 0.5
c = 0.3
p0 = 0.6
# <codecell>
def m(theta):
""" job finding rate for an unemployed worker, assuming cobb-douglas matching technology """
return (theta**0.5)*2
def theta_solve(theta):
""" Using a combination of V1=V2=0 and the equation for the value of U1 and U2, when solved gives the value of theta in equilibirum """
return (m(theta)/theta) * (( (1-beta)*(y1-c-b) ) / (r+delta+beta*m(theta)) ) - c
# <codecell>
theta_star = optimize.fsolve(theta_solve, x0=1.9)
print "Equilibrium labour market tightness: ", theta_star
print "Equilibrium job finding rate: ", m(theta_star)
# <codecell>
p = p0
# <codecell>
def phi(gamma, theta):
""" Unsing the steady-state unemployment conditions for high and low skill, delivers phi in equilinirum """
def pii(gamma, theta):
return ( ((1.0-gamma)*p*m(theta)) + ((p-gamma)*delta) ) / (m(theta)*gamma*(1.0-p))
if pii(gamma, theta) >= 1:
return 1
elif pii(gamma, theta) <= 0 :
return 0
else:
return pii(gamma, theta)
def u(theta, gamma):
"""Steady-state value of unemployment, given a certain labour market tightness (theta= v/u)"""
return (delta*(1-p)) / ((1-gamma)*(m(theta)+delta))
# <codecell>
print phi(0.639, theta_star)
print u(theta_star, 0.639)
# <codecell>
def gamma_solve(gamma):
""" When solved, delivers the value of gamma in equilibrium. Needs to have theta_star first """
return ( gamma*(r+delta)*(y1-c-b) ) - ( (1-gamma)*(y2-y1)*(r+delta+beta*m(theta_star)*phi(gamma, theta_star)) )
def gimme_gamma():
""" Using gamma_solve, delivers gamma in equilibrium, and ensures is between 0 and 1 """
gammita = optimize.fsolve(gamma_solve, x0=0.9)
if gammita >= 1:
return 1
elif gammita <= 0:
return 0
else:
return gammita
# <codecell>
gamma_star = gimme_gamma()
print "Low-skill umeployment, gamma: ",gamma_star
phi_star = phi(gamma_star, theta_star)
print "Low-skill requiment jobs, phi: ", phi_star
print "Unemployment rate in equilibirum, u: ", u(theta_star, gamma_star)
# <codecell>
def U1(gamma, theta):
""" Delivers the flow value of unemployment for low skill workers """
return (b*(r+delta) + m(theta)*phi(gamma, theta)*beta*(y1-c)) / (r+delta+beta*m(theta)*phi(gamma, theta)) / r
def U2(gamma, theta):
""" Delivers the flow value of unemployment for high skill workers """
return ( (b*(r+delta)+beta*m(theta)*(phi(gamma, theta)*y1 + (1-phi(gamma, theta))*y2 - c)) / (r+delta+beta*m(theta)) ) / r
# <codecell>
print "U1 equals", U1(gamma_star, theta_star)
print "U2 equals", U2(gamma_star, theta_star)
print U2(gamma_star, theta_star)*1.2
# <codecell>
def Cross_cond(gamma, theta):
""" Returns True if the mismatch equilibirum condition is met, for ceratin value of U2 """
return y1-c > r*U2(gamma, theta)
def Corner_cond(theta, some_p):
""" Returns True if the corner solution condition is met, for ceratin value of theta and p"""
return (y1-c-b) > (1-some_p)*(y2-c-b+((beta*m(theta_star)*(y2-y1))/(r+delta)))
print "Mismatch condition", Cross_cond(gamma_star, theta_star)
print "Corner solution condition", Corner_cond(theta_star, p0)
# <codecell>
def cornerp(some_p):
""" When solved, delivers the critical p that triggers the corner solution. Needs to ahve solved for theta_star before"""
return (1-some_p)*(y2-c-b+((beta*m(theta_star)*(y2-y1))/(r+delta))) - (y1-c-b)
p_limit = optimize.fsolve(cornerp, x0=0.6)
print p_limit
# <codecell>
""" Normal (1,0.5)"""
def H(gamma, theta):
""" Participation rate of the low-skill population, or how many people stay in the labour market """
G = stats.norm(1, 0.5)
if (M-U2(gamma, theta)) > 0:
return G.cdf(r*(M-U2(gamma, theta)))
else:
return 0
def p_new(gamma, theta):
""" Returns the p that corresponds to the value of U2 """
return p0 / (1- (H(gamma, theta)))
# <codecell>
def solve_model2():
gamma_star = gimme_gamma()
p_star = p_new(gamma_star, theta_star)
print "gamma_star", gamma_star
if Corner_cond(theta_star, p_star):
print "Dead by corner"
print "gamma final", gamma_star
return p_star
elif p_star == p:
print "The End"
return p_star
else:
print "Una vuelta"
return p_star
# <codecell>
y2 = 1.20
p=p0
M=25
X12 = []
X12.append(p)
solve_model2()
# <codecell>
p = solve_model2()
X12.append(p)
print X12
solve_model2()
# <codecell>
""" Normal (1,1)"""
def H(gamma, theta):
""" Participation rate of the low-skill population, or how many people stay in the labour market """
G = stats.norm(1, 1)
if (M-U2(gamma, theta)) > 0:
return G.cdf(r*(M-U2(gamma, theta)))
else:
return 0
def p_new(gamma, theta):
""" Returns the p that corresponds to the value of U2 """
return p0 / (1- (H(gamma, theta)))
# <codecell>
y2 = 1.2
p = p0
M = 25
X13 = []
X13.append(p0)
solve_model2()
# <codecell>
X13.append(0.72815604)
# <codecell>
""" Normal (0.5,0.5)"""
def H(gamma, theta):
""" Participation rate of the low-skill population, or how many people stay in the labour market """
G = stats.norm(0.5, 0.5)
if (M-U2(gamma, theta)) > 0:
return G.cdf(r*(M-U2(gamma, theta)))
else:
return 0
def p_new(gamma, theta):
""" Returns the p that corresponds to the value of U2 """
return p0 / (1- (H(gamma, theta)))
# <codecell>
y2 = 1.20
p=p0
M=25
X14 = []
X14.append(p)
solve_model2()
# <codecell>
X14.append(0.9358766)
# <codecell>
""" Unifromland """
def H(gamma, theta):
""" Migration rate of the high-skill population, or how many people leave the labour market """
G = stats.uniform(loc=0, scale = 1)
if (M-U2(gamma, theta)) > 0:
return G.cdf(r*(M-U2(gamma, theta)))
else:
return 0
def p_new(gamma, theta):
""" Returns the p that corresponds to the value of U2 """
return p0 / (1- (H(gamma, theta)))
# <codecell>
y2 = 1.20
p=p0
M=25
X21 = []
X21.append(p)
solve_model2()
# <codecell>
X21.append(0.88142758)
# <codecell>
p = solve_model2()
X21.append(p)
print X21
solve_model2()
# <codecell>
"""Shows the value of p after the number of iterations in the x axis. Doted Line is critical p for corner solution"""
Y22 = np.linspace(0, (len(X21)-1), len(X21))
pl.plot(Y22,X21)
pl.plot([0, 7], [p_limit, p_limit], linewidth=2.5, linestyle="--")
pl.show()
# <codecell>
""" Unifromland 2 """
def H(gamma, theta):
""" Migration rate of the high-skill population, or how many people leave the labour market """
G = stats.uniform(loc=0, scale = 2)
if (M-U2(gamma, theta)) > 0:
return G.cdf(r*(M-U2(gamma, theta)))
else:
return 0
def p_new(gamma, theta):
""" Returns the p that corresponds to the value of U2 """
return p0 / (1- (H(gamma, theta)))
# <codecell>
y2 = 1.20
p=p0
M=12
X22 = []
X22.append(p)
solve_model2()
# <codecell>
p = solve_model2()
X22.append(p)
print X22
solve_model2()
# <codecell>
y2 = 1.20
p=p0
M=12
delta =0.8
theta_star = optimize.fsolve(theta_solve, x0=1.9)
print theta_star
# <codecell>
solve_model2()
# <codecell>
print U2(0.6550869, theta_star)
print phi(0.6550869, theta_star)
print u(theta_star, 0.6550869)
print U1(0.6550869, theta_star)
# <codecell>
""" No migration, N(1, 1) """
y2 = 1.20
p=p0
M=0
delta =0.25
theta_star = optimize.fsolve(theta_solve, x0=1.9)
print theta_star
# <codecell>
solve_model2()
# <codecell>
gamma_star = 0.61923384
print U2(gamma_star, theta_star)
print phi(gamma_star, theta_star)
print u(theta_star, gamma_star)
print U1(gamma_star, theta_star)
Corner_cond(theta_star, 0.6)
p_limit = optimize.fsolve(cornerp, x0=0.6)
print "p limit", p_limit
# <codecell>
""" Migration """
y2 = 1.20
p=p0
M=12.5
delta =0.25
theta_star = optimize.fsolve(theta_solve, x0=1.9)
print theta_star
# <codecell>
solve_model2()
# <codecell>
gamma_star = 0.61923384
print U2(gamma_star, theta_star)
print phi(gamma_star, theta_star)
print u(theta_star, gamma_star)
print U1(gamma_star, theta_star)
Corner_cond(theta_star, 0.6)
p_limit = optimize.fsolve(cornerp, x0=0.6)
print "p limit", p_limit
# <codecell>
<file_sep>/README.md
Diss
====
"Skill Migration in a Mismatch Model" related coding.
I include both python and ipython formats
SimM contains code to replicate table 2.
SimDelta contains code to replicate table 3.
Diagram5 contains data to generate diagram 5.
| e6516bdda275f9f6368090cd50f0eddc21600190 | [
"Markdown",
"Python"
] | 2 | Python | crisla/Diss | 3b966aa0b745b5bac0cc9ab1dc262e385bf49634 | 72da4e8bcfe30142a5c8854a52b7b26282a12907 |
refs/heads/master | <file_sep><?php
// Base controller
class ControllerBase extends \Prefab
{
protected $f3;
//! Instantiate class
function __construct()
{
$this->f3 = Base::instance();
}
}
<file_sep>[globals]
; Database settings
; or set individually:
db.driver = mysql
db.hostname = localhost
db.port = 3306
db.name =
db.username = root
db.password = <PASSWORD>
;if using sqlite, uncomment below
;the path is relative to the top-level of the project checkout
;db.driver=sqlite
;db.dsn=sqlite:/data/database.sqlite<file_sep>[routes]
GET / = Welcome->index<file_sep><?php
chdir(realpath(__DIR__ . '/app'));
require_once 'app/bootstrap.php';<file_sep><?php
/**
* -------------------------------------------------------------------------
* PHP Form Validator (formvalidator.php)
* Version 1.0
* -------------------------------------------------------------------------
* Author: Md. Monjur-ul-Hasan. (<NAME>)
* Email: <EMAIL>
* Release: 2 Nov 2009
* Copyright 2009
* Documentation: http://phpformvalidation.monjur-ul-hasan.info
*
* @requires PHP 4 >= 4.3.2
*
* License: under GNU GENERAL PUBLIC LICENSE, Version 1.0, August 2009
*
**/
class Validator
{
var $_errmessages;
var $_rules;
var $_errors;
var $_messages;
var $_defauleErrorMessage;
var $_defaultDateFormat;
var $_data;
var $_curElement;
function Reset()
{
$this->_errormessages = array();
$this->_rules = array();
$this->_messages = array();
$this->_defauleErrorMessage = array();
}
function setDefaultDateFormat($format)
{
$this->_defaultDateFormat = $format;
}
function Validator($rules="",$messages="")
{
$this->Reset();
$this->setDefaultDateFormat("mmddyy");
if(is_array($rules)) $this->_rules = $rules;
if(is_array($messages)) $this->_errmessages = $messages;
}
function addRules($rules,$reset=false)
{
if($reset)
$this->Reset();
$this->_rules = array_merge($this->_rules,$rules);
}
function addErrors($errors,$reset=false)
{
if($reset)
$this->Reset();
$this->_errmessages = array_merge($this->_errmessages,$errors);
}
function isValid($data)
{
$valid = true;
$this->_data = $data;
foreach($data as $element => $value)
{
if(isset($this->_rules[$element]))
{
if(!$this->validate($element,$value))
$valid = false;
}
}
return $valid;
}
function validate($element, $value)
{
$this->_curElement = $element;
$rules = $this->_rules[$element];
if(isset($this->_errmessages[$element]))
$errormessage = $this->_errmessages[$element];
if(is_array($rules))
{
$valid = true;
$curErr = array();
foreach($rules as $rule=>$con)
{
if(!$this->check($rule,$value,$con))
{
$valid = false;
if(isset($errormessage[$rule]))
$curErr[]=$errormessage[$rule];
else $curErr[]=$this->DefaultErrorMsg($rule);
}
}
if(!$valid && !isset($this->_messages[$element]))
$this->_messages[$element] = $curErr;
return $valid;
}
else
{
if(!$this->check($rules,$value))
{
if(isset($errormessage))
$this->_messages[$element] = $errormessage;
else $this->_messages[$element] = $this->DefaultErrorMsg($rules);
return false;
}
else return true;
}
}
function check($rule,$value,$condition=true)
{
switch(strtolower($rule))
{
case "require" : return !(trim($value)==""); //
case "maxlength" : return (strlen($value)<=$condition);//
case "minlength" : return (strlen($value)>=$condition); //
case "eqlength" : return (strlen($value)==$condition);//
case "equal" : return ($value==$condition);//
case "numeric" : return is_numeric($value);//
case "int" : $v = (int) $value;
return ((string)$v===(string)$value);
case "float" : $v = (float) $value;
return ((string)$v===(string)$value);
case "min" : if($value<$condition) return false; break;
case "max" : if($value>$condition) return false; break;
case "gt" : if($value<$condition) return false; break;
case "lt" : if($value>$condition) return false; break;
default:
if(method_exists($this,$rule))
{
return @call_user_method($rule,$this,$condition,$value);
}
else die("Error: rule '".$rule."' not found");
}
return true;
}
function DefaultErrorMsg($rule)
{
switch(strtolower($rule))
{
case "require" : return "Require"; //
case "maxlength" : return "Over Length"; //
case "minlength" : return "Under Length"; //
case "eqlength" : return "Length Mismatch";//
case "equal" : return "Data Mismatch";//
case "numeric" : return "Numeric Value Require";//
case "int" : return "Integer Value require";
case "float" : return "Float Value require";
case "gt" :
case "min" : return "Too small";
case "lt" :
case "max" : return "Too high";
case "date" : return "Invalid Date";
default : return "error";
}
return true;
}
function CountError()
{
return count($this->_messages);
}
function ErrorFields()
{
// print_r($this->_errmessages);
return array_keys($this->_messages);
}
function getErrors($element)
{
return $this->_messages[$element];
}
function date($con,$value)
{
$d = $value;
if(!preg_match("/^((\d){1,2})[\/\.-]((\d){1,2})[\/\.-](\d{2,4})$/",$d,$matches))
return false;//Bad Date Format
$T = split("[\/\.-]",$d);
if(is_array($con))
{
if(isset($con["format"]))
$format = $con["format"];
else $format = $this->_defaultDateFormat;
}
else $format = $this->_defaultDateFormat;
switch($format)
{
case "mmddyyyy":
$M = (int)$T[0];
$D = (int)$T[1];
$Y = (int)$T[2];
if($Y<999)
return false;
break;
case "mmddyy":
//print_r($T);
$M = (int)$T[0];
$D = (int)$T[1];
$Y = (int)$T[2];
if($Y>99)
return false;
break;
case "ddmmyyyy":
$D = (int)$T[0];
$M = (int)$T[1];
$Y = (int)$T[2];
if($Y<999)
return false;
break;
case "ddmmyy":
$D = (int)$T[0];
$M = (int)$T[1];
$Y = (int)$T[2];
if($Y>99)
return false;
break;
}
$MON=array(0,31,28,31,30,31,30,31,31,30,31,30,31);
return $D>0 && ($D<=$MON[$M] || $D==29 && $Y%4==0 && ($Y%100!=0 || $Y%400==0));
}
function depend($con,$value)
{
// die($con);
if($this->check("require",$this->_data[$con['depend_on']]))
{
$valid = true;
$curErr = array();
foreach($con as $rule=>$con)
{
if($rule!='depend_on')
if(!$this->check($rule,$value,$con))
{
$valid = false;
if(isset($errormessage[$rule]))
$curErr[]=$errormessage[$rule];
else $curErr[]=$this->DefaultErrorMsg($rule);
}
}
if(!$valid)
$this->_messages[$this->_curElement] = $curErr;
return $valid;
}
else return true;
}
}
?><file_sep><?php
$f3 = require_once '../system/base.php';
$f3->set('DEBUG',1);
if ((float)PCRE_VERSION < 7.9)
trigger_error('PCRE version is out of date');
// Load configuration
$f3->config('config/config.ini');
//Auto load classes
$f3->set('AUTOLOAD', __dir__.'/; controller/; model/; library/; vendor/');
//Application logging
$logger = new \Log($f3->get('LOGFILE'));
\Registry::set('logger', $logger);
//Database connection
if($f3->get('DATABASE'))
{
if ($f3->get('db.driver') == 'sqlite')
{
$dsn = $f3->get('db.dsn');
$dsn = substr($dsn, 0, strpos($dsn, '/')) . realpath('../') . substr($dsn, strpos($dsn, '/'));
$db = new \DB\SQL($dsn);
}
else
{
$f3->set('db.dsn', sprintf("%s:host=%s;port=%d;dbname=%s",
$f3->get('db.driver'), $f3->get('db.hostname'), $f3->get('db.port'), $f3->get('db.name'))
);
$db = new \DB\SQL($f3->get('db.dsn'), $f3->get('db.username'), $f3->get('db.password'));
}
\Registry::set('db', $db);
}
// log script execution time if debugging
if ($f3->get('DEBUG') || $f3->get('application.ENVIRONMENT') == 'development') {
//Log database transactions if level 3
if ($f3->get('DEBUG') == 3 && $f3->get('DATABASE'))
$logger->write(\Registry::get('db')->log());
$execution_time = round(microtime(true) - $f3->get('TIME'), 3);
$logger->write('Script executed in ' . $execution_time . ' seconds using ' . round(memory_get_usage() / 1024 / 1024, 2) . '/' . round(memory_get_peak_usage() / 1024 / 1024, 2) . ' MB memory/peak');
}
//Load routes
$f3->config('config/routes.ini');
$f3->run();
<file_sep><?php
/*
---------------------------------INCLUDE THIS SECTION IN ANY MODIFICATION OR REDISTRIBUTION----------------------------------
Project: Form Builder Class
Author: <NAME>
Original Release Date: 2009-04-24
Latest Release Date: 2009-11-05
License: GPL - for more information visit http://www.gnu.org/licenses/quick-guide-gplv3.html
Current Version: 0.9.3
---------------------------------INCLUDE THIS SECTION IN ANY MODIFICATION OR REDISTRIBUTION----------------------------------
*/
class HelperBase {
/*This class provides two methods - setAttributes and debug - that can be used for all classes that extend this class.*/
function setAttributes($params) {
if(!empty($params) && is_array($params))
{
/*Loop through and get accessible class variables.*/
$objArr = array();
foreach($this as $key => $value)
$objArr[$key] = $value;
foreach($params as $key => $value)
{
if(array_key_exists($key, $objArr))
{
if(is_array($this->$key) && !empty($this->$key))
{
/*Using array_merge prevents any default values from being overwritten.*/
$this->$key = array_merge($this->$key, $value);
}
else
$this->$key = $value;
}
elseif(array_key_exists("attributes", $objArr))
$this->attributes[$key] = $value;
}
unset($objArr);
}
}
/*Used for development/testing.*/
function debug()
{
echo "<pre>";
print_r($this);
echo "</pre>";
}
}
class FormHelper extends HelperBase {
/*Variables that can be set through the setAttributes function on the base class.*/
protected $attributes; /*HTML attributes attached to <form> tag.*/
protected $tableAttributes; /*HTML attributes attached to <table> tag.*/
protected $tdAttributes; /*HTML attributes attached to <td> tag.*/
protected $labelAttributes; /*HTML attributes attached to <div> tag.*/
protected $requiredAttributes; /*HTML attributes attached to <span> tag.*/
protected $jqueryPath; /*Allows jquery directory's location to be identified.*/
protected $googleMapsAPIKey; /*Required for using latlng/map field type.*/
protected $map; /*Unrelated to latlng/map field type. Used to control table structure.*/
protected $returnUrl; /*Only used when doign php validation via the checkForm function.*/
protected $ajax; /*Activate ajax form submission.*/
protected $ajaxType; /*Specify form submission as get/post.*/
protected $ajaxUrl; /*Where to send ajax submission.*/
protected $ajaxCallback; /*Optional function to call after successful ajax form submission.*/
protected $ajaxDataType; /*Defaults to text. Options include xml, html, script, json, jsonp, and text. View details at http://docs.jquery.com/Ajax/jQuery.ajax#options*/
protected $tooltipIcon; /*Overrides default tooltip icon.*/
protected $tooltipBorderColor; /*Overrides default tooltip border color.*/
protected $preventJQueryLoad; /*Prevents jQuery js file from being loaded twice.*/
protected $preventJQueryUILoad; /*Prevents jQuery UI js file from being loaded twice.*/
protected $preventQTipLoad; /*Prevents qTip js file from being loaded twice.*/
protected $preventGoogleMapsLoad; /*Prevents Google Maps js file from being loaded twice.*/
protected $noLabels; /*Prevents labels from being rendered on checkboxes and radio buttons.*/
protected $noAutoFocus; /*Prevents auto-focus feature..*/
protected $tinymcePath; /*Allows tiny_mce directory's location to be identified.*/
/*Variables that can only be set inside this class.*/
private $elements;
private $buttons;
private $jqueryDateArr;
private $jqueryDateRangeArr;
private $jquerySortArr;
private $jquerySliderArr;
private $jqueryCheckSort;
private $latlngArr;
private $checkform;
private $allowedFields; /*Controls what attributes can be attached to various html elements.*/
private $stateArr;
private $countryArr;
private $referenceValues; /*Associative array of values to pre-fill form fields.*/
private $tooltipArr;
private $focusElement;
private $includeTinyMce; /*Will be set if a field of type webeditor is detected.*/
private $tinymceIDArr; /*Ensurse that each webeditor form element has a unique identifier.*/
private $captchaNameArr; /*Ensurse that each captcha form element has a unique identifier.*/
public function __construct() {
/*Provide default values for class variables.*/
$this->attributes = array(
"name" => "formclass_" . rand(0, 999),
"method" => "post",
"action" => basename($_SERVER["SCRIPT_NAME"]),
"style" => "padding: 0; margin: 0;"
);
$this->tableAttributes = array(
"cellpadding" => "4",
"cellspacing" => "0",
"border" => "0"
);
$this->tdAttributes = array(
"valign" => "top",
"align" => "left"
);
$this->requiredAttributes = array(
"style" => "color: #990000;"
);
$this->jqueryPath = "jquery";
$this->tinymcePath = "tiny_mce";
$this->captchaPath = "animatedcaptcha";
/*This array prevents junk from being inserted into the form's HTML. If you find that an attributes you need to use is not included
in this list, feel free to customize to fit your needs.*/
$this->allowedFields = array(
"form" => array("method", "action", "enctype", "onsubmit", "id", "class", "name"),
"table" => array("cellpadding", "cellspacing", "border", "style", "id", "class", "name", "align", "width"),
"td" => array("id", "name", "valign", "align", "style", "id", "class", "width"),
"div" => array("id", "name", "valign", "align", "style", "id", "class"),
"span" => array("id", "name", "valign", "align", "style", "id", "class"),
"hidden" => array("id", "name", "value", "type"),
"text" => array("id", "name", "value", "type", "class", "style", "onclick", "onkeyup", "onblur", "maxlength", "size"),
"file" => array("id", "name", "value", "type", "class", "style", "onclick", "onkeyup", "onblur", "maxlength", "size"),
"textarea" => array("id", "name", "class", "style", "onclick", "onkeyup", "maxlength", "onblur", "size", "rows", "cols"),
"select" => array("id", "name", "class", "style", "onclick", "onchange", "onblur", "size"),
"radio" => array("name", "style", "class", "onclick", "type"),
"checkbox" => array("name", "style", "class", "onclick", "type"),
"checksort" => array("style", "class"),
"date" => array("id", "name", "value", "type", "class", "style", "onclick", "onkeyup", "onblur", "maxlength", "size"),
"button" => array("name", "value", "type", "id", "onclick", "class", "style"),
"a" => array("id", "name", "href", "class", "style"),
"latlng" => array("id", "name", "type", "class", "style", "onclick", "onkeyup", "maxlength", "size")
);
$this->ajaxType = "post";
$this->ajaxUrl = basename($_SERVER["SCRIPT_NAME"]);
$this->ajaxDataType = "text";
}
/*Creates new element object instances and attaches them to the form object. This function is private and can only be called inside this class.*/
private function attachElement($params)
{
$ele = new element();
$ele->setAttributes($params);
$eleType = &$ele->attributes["type"];
if($eleType == "state")
{
/*This section prevents the stateArr from being generated for each form and/or multiple state field types per form.*/
$eleType = "select";
if(empty($this->stateArr))
{
$this->stateArr = array(
array("value" => "", "text" => "--Select a State/Province--"),
array("value" => "AL", "text" => "Alabama"),
array("value" => "AK", "text" => "Alaska"),
array("value" => "AZ", "text" => "Arizona"),
array("value" => "AR", "text" => "Arkansas"),
array("value" => "CA", "text" => "California"),
array("value" => "CO", "text" => "Colorado"),
array("value" => "CT", "text" => "Connecticut"),
array("value" => "DE", "text" => "Delaware"),
array("value" => "DC", "text" => "District of Columbia"),
array("value" => "FL", "text" => "Florida"),
array("value" => "GA", "text" => "Georgia"),
array("value" => "HI", "text" => "Hawaii"),
array("value" => "ID", "text" => "Idaho"),
array("value" => "IL", "text" => "Illinois"),
array("value" => "IN", "text" => "Indiana"),
array("value" => "IA", "text" => "Iowa"),
array("value" => "KS", "text" => "Kansas"),
array("value" => "KY", "text" => "Kentucky"),
array("value" => "LA", "text" => "Louisiana"),
array("value" => "ME", "text" => "Maine"),
array("value" => "MD", "text" => "Maryland"),
array("value" => "MA", "text" => "Massachusetts"),
array("value" => "MI", "text" => "Michigan"),
array("value" => "MN", "text" => "Minnesota"),
array("value" => "MS", "text" => "Mississippi"),
array("value" => "MO", "text" => "Missouri"),
array("value" => "MT", "text" => "Montana"),
array("value" => "NE", "text" => "Nebraska"),
array("value" => "NV", "text" => "Nevada"),
array("value" => "NH", "text" => "New Hampshire"),
array("value" => "NJ", "text" => "New Jersey"),
array("value" => "NM", "text" => "New Mexico"),
array("value" => "NY", "text" => "New York"),
array("value" => "NC", "text" => "North Carolina"),
array("value" => "ND", "text" => "North Dakota"),
array("value" => "OH", "text" => "Ohio"),
array("value" => "OK", "text" => "Oklahoma"),
array("value" => "OR", "text" => "Oregon"),
array("value" => "PA", "text" => "Pennsylvania"),
array("value" => "RI", "text" => "Rhode Island"),
array("value" => "SC", "text" => "South Carolina"),
array("value" => "SD", "text" => "South Dakota"),
array("value" => "TN", "text" => "Tennessee"),
array("value" => "TX", "text" => "Texas"),
array("value" => "UT", "text" => "Utah"),
array("value" => "VT", "text" => "Vermont"),
array("value" => "VA", "text" => "Virginia"),
array("value" => "WA", "text" => "Washington"),
array("value" => "WV", "text" => "West Virginia"),
array("value" => "WI", "text" => "Wisconsin"),
array("value" => "WY", "text" => "Wyoming"),
array("value" => "", "text" => ""),
array("value" => "", "text" => "-- Canadian Province--"),
array("value" => "AB", "text" => "Alberta"),
array("value" => "BC", "text" => "British Columbia"),
array("value" => "MB", "text" => "Manitoba"),
array("value" => "NB", "text" => "New Brunswick"),
array("value" => "NL", "text" => "Newfoundland and Labrador"),
array("value" => "NS", "text" => "Nova Scotia"),
array("value" => "NT", "text" => "Northwest Territories"),
array("value" => "NU", "text" => "Nunavut"),
array("value" => "ON", "text" => "Ontario"),
array("value" => "PE", "text" => "Prince Edward Island"),
array("value" => "QC", "text" => "Québec"),
array("value" => "SK", "text" => "Saskatchewan"),
array("value" => "YT", "text" => "Yukon"),
array("value" => "", "text" => ""),
array("value" => "", "text" => "-- US Territories--"),
array("value" => "AS", "text" => "American Samoa"),
array("value" => "FM", "text" => "Federated States of Micronesia"),
array("value" => "GU", "text" => "Guam"),
array("value" => "MH", "text" => "Marshall Islands"),
array("value" => "PW", "text" => "Palau"),
array("value" => "PR", "text" => "Puerto Rico"),
array("value" => "VI", "text" => "Virgin Islands")
);
}
$ele->options = array();
$stateSize = sizeof($this->stateArr);
for($s = 0; $s < $stateSize; ++$s)
{
$opt = new option();
$opt->setAttributes($this->stateArr[$s]);
$ele->options[] = $opt;
}
}
elseif($eleType == "country")
{
/*This section prevents the countryArr from being generated for each form and/or multiple country field types per form.*/
$eleType = "select";
if(empty($this->countryArr))
{
$this->countryArr = array(
array("value" => "", "text" => "--Select a Country--"),
array("value" => "US", "text" => "United States"),
array("value" => "AF", "text" => "Afghanistan"),
array("value" => "AL", "text" => "Albania"),
array("value" => "DZ", "text" => "Algeria"),
array("value" => "AS", "text" => "American Samoa"),
array("value" => "AD", "text" => "Andorra"),
array("value" => "AO", "text" => "Angola"),
array("value" => "AI", "text" => "Anguilla"),
array("value" => "AG", "text" => "Antigua and Barbuda"),
array("value" => "AR", "text" => "Argentina"),
array("value" => "AM", "text" => "Armenia"),
array("value" => "AW", "text" => "Aruba"),
array("value" => "AU", "text" => "Australia"),
array("value" => "AT", "text" => "Austria"),
array("value" => "AZ", "text" => "Azerbaijan"),
array("value" => "BS", "text" => "Bahamas"),
array("value" => "BH", "text" => "Bahrain"),
array("value" => "BD", "text" => "Bangladesh"),
array("value" => "BB", "text" => "Barbados"),
array("value" => "BY", "text" => "Belarus"),
array("value" => "BE", "text" => "Belgium"),
array("value" => "BZ", "text" => "Belize"),
array("value" => "BJ", "text" => "Benin"),
array("value" => "BM", "text" => "Bermuda"),
array("value" => "BT", "text" => "Bhutan"),
array("value" => "BO", "text" => "Bolivia"),
array("value" => "BA", "text" => "Bosnia and Herzegowina"),
array("value" => "BW", "text" => "Botswana"),
array("value" => "BR", "text" => "Brazil"),
array("value" => "IO", "text" => "British Indian Ocean Territory"),
array("value" => "BN", "text" => "Brunei Darussalam"),
array("value" => "BG", "text" => "Bulgaria"),
array("value" => "BF", "text" => "Burkina Faso"),
array("value" => "BI", "text" => "Burundi"),
array("value" => "KH", "text" => "Cambodia"),
array("value" => "CM", "text" => "Cameroon"),
array("value" => "CA", "text" => "Canada"),
array("value" => "CV", "text" => "Cape Verde"),
array("value" => "KY", "text" => "Cayman Islands"),
array("value" => "CF", "text" => "Central African Republic"),
array("value" => "TD", "text" => "Chad"),
array("value" => "CL", "text" => "Chile"),
array("value" => "CN", "text" => "China"),
array("value" => "CO", "text" => "Colombia"),
array("value" => "CG", "text" => "Congo"),
array("value" => "CK", "text" => "Cook Islands"),
array("value" => "CR", "text" => "Costa Rica"),
array("value" => "CI", "text" => "Cote d'Ivoire"),
array("value" => "HR", "text" => "Croatia"),
array("value" => "CY", "text" => "Cyprus"),
array("value" => "CZ", "text" => "Czech Republic"),
array("value" => "DK", "text" => "Denmark"),
array("value" => "DJ", "text" => "Djibouti"),
array("value" => "DM", "text" => "Dominica"),
array("value" => "DO", "text" => "Dominican Republic"),
array("value" => "EC", "text" => "Ecuador"),
array("value" => "EG", "text" => "Egypt"),
array("value" => "SV", "text" => "El Salvador"),
array("value" => "GQ", "text" => "Equatorial Guinea"),
array("value" => "ER", "text" => "Eritrea"),
array("value" => "EE", "text" => "Estonia"),
array("value" => "ET", "text" => "Ethiopia"),
array("value" => "FO", "text" => "Faroe Islands"),
array("value" => "FJ", "text" => "Fiji"),
array("value" => "FI", "text" => "Finland"),
array("value" => "FR", "text" => "France"),
array("value" => "GF", "text" => "French Guiana"),
array("value" => "PF", "text" => "French Polynesia"),
array("value" => "GA", "text" => "Gabon"),
array("value" => "GM", "text" => "Gambia"),
array("value" => "GE", "text" => "Georgia"),
array("value" => "DE", "text" => "Germany"),
array("value" => "GH", "text" => "Ghana"),
array("value" => "GI", "text" => "Gibraltar"),
array("value" => "GR", "text" => "Greece"),
array("value" => "GL", "text" => "Greenland"),
array("value" => "GD", "text" => "Grenada"),
array("value" => "GP", "text" => "Guadeloupe"),
array("value" => "GU", "text" => "Guam"),
array("value" => "GT", "text" => "Guatemala"),
array("value" => "GN", "text" => "Guinea"),
array("value" => "GW", "text" => "Guinea-Bissau"),
array("value" => "GY", "text" => "Guyana"),
array("value" => "HT", "text" => "Haiti"),
array("value" => "HM", "text" => "Heard Island And Mcdonald Islands"),
array("value" => "HK", "text" => "Hong Kong"),
array("value" => "HU", "text" => "Hungary"),
array("value" => "IS", "text" => "Iceland"),
array("value" => "IN", "text" => "India"),
array("value" => "ID", "text" => "Indonesia"),
array("value" => "IR", "text" => "Iran, Islamic Republic Of"),
array("value" => "IL", "text" => "Israel"),
array("value" => "IT", "text" => "Italy"),
array("value" => "JM", "text" => "Jamaica"),
array("value" => "JP", "text" => "Japan"),
array("value" => "JO", "text" => "Jordan"),
array("value" => "KZ", "text" => "Kazakhstan"),
array("value" => "KE", "text" => "Kenya"),
array("value" => "KI", "text" => "Kiribati"),
array("value" => "KP", "text" => "Korea, Democratic People's Republic Of"),
array("value" => "KW", "text" => "Kuwait"),
array("value" => "KG", "text" => "Kyrgyzstan"),
array("value" => "LA", "text" => "Lao People's Democratic Republic"),
array("value" => "LV", "text" => "Latvia"),
array("value" => "LB", "text" => "Lebanon"),
array("value" => "LS", "text" => "Lesotho"),
array("value" => "LR", "text" => "Liberia"),
array("value" => "LI", "text" => "Liechtenstein"),
array("value" => "LT", "text" => "Lithuania"),
array("value" => "LU", "text" => "Luxembourg"),
array("value" => "MO", "text" => "Macau"),
array("value" => "MK", "text" => "Macedonia, The Former Yugoslav Republic Of"),
array("value" => "MG", "text" => "Madagascar"),
array("value" => "MW", "text" => "Malawi"),
array("value" => "MY", "text" => "Malaysia"),
array("value" => "MV", "text" => "Maldives"),
array("value" => "ML", "text" => "Mali"),
array("value" => "MT", "text" => "Malta"),
array("value" => "MH", "text" => "Marshall Islands"),
array("value" => "MQ", "text" => "Martinique"),
array("value" => "MR", "text" => "Mauritania"),
array("value" => "MU", "text" => "Mauritius"),
array("value" => "MX", "text" => "Mexico"),
array("value" => "FM", "text" => "Micronesia, Federated States Of"),
array("value" => "MD", "text" => "Moldova, Republic Of"),
array("value" => "MC", "text" => "Monaco"),
array("value" => "MN", "text" => "Mongolia"),
array("value" => "MS", "text" => "Montserrat"),
array("value" => "MA", "text" => "Morocco"),
array("value" => "MZ", "text" => "Mozambique"),
array("value" => "NA", "text" => "Namibia"),
array("value" => "NP", "text" => "Nepal"),
array("value" => "NL", "text" => "Netherlands"),
array("value" => "AN", "text" => "Netherlands Antilles"),
array("value" => "NC", "text" => "New Caledonia"),
array("value" => "NZ", "text" => "New Zealand"),
array("value" => "NI", "text" => "Nicaragua"),
array("value" => "NE", "text" => "Niger"),
array("value" => "NG", "text" => "Nigeria"),
array("value" => "NF", "text" => "Norfolk Island"),
array("value" => "MP", "text" => "Northern Mariana Islands"),
array("value" => "NO", "text" => "Norway"),
array("value" => "OM", "text" => "Oman"),
array("value" => "PK", "text" => "Pakistan"),
array("value" => "PW", "text" => "Palau"),
array("value" => "PA", "text" => "Panama"),
array("value" => "PG", "text" => "Papua New Guinea"),
array("value" => "PY", "text" => "Paraguay"),
array("value" => "PE", "text" => "Peru"),
array("value" => "PH", "text" => "Philippines"),
array("value" => "PL", "text" => "Poland"),
array("value" => "PT", "text" => "Portugal"),
array("value" => "PR", "text" => "Puerto Rico"),
array("value" => "QA", "text" => "Qatar"),
array("value" => "RE", "text" => "Reunion"),
array("value" => "RO", "text" => "Romania"),
array("value" => "RU", "text" => "Russian Federation"),
array("value" => "RW", "text" => "Rwanda"),
array("value" => "KN", "text" => "Saint Kitts and Nevis"),
array("value" => "LC", "text" => "Saint Lucia"),
array("value" => "VC", "text" => "Saint Vincent and the Grenadines"),
array("value" => "WS", "text" => "Samoa"),
array("value" => "SM", "text" => "San Marino"),
array("value" => "SA", "text" => "Saudi Arabia"),
array("value" => "SN", "text" => "Senegal"),
array("value" => "SC", "text" => "Seychelles"),
array("value" => "SL", "text" => "Sierra Leone"),
array("value" => "SG", "text" => "Singapore"),
array("value" => "SK", "text" => "Slovakia"),
array("value" => "SI", "text" => "Slovenia"),
array("value" => "SB", "text" => "Solomon Islands"),
array("value" => "SO", "text" => "Somalia"),
array("value" => "ZA", "text" => "South Africa"),
array("value" => "ES", "text" => "Spain"),
array("value" => "LK", "text" => "Sri Lanka"),
array("value" => "SD", "text" => "Sudan"),
array("value" => "SR", "text" => "Suriname"),
array("value" => "SZ", "text" => "Swaziland"),
array("value" => "SE", "text" => "Sweden"),
array("value" => "CH", "text" => "Switzerland"),
array("value" => "SY", "text" => "Syrian Arab Republic"),
array("value" => "TW", "text" => "Taiwan, Province Of China"),
array("value" => "TJ", "text" => "Tajikistan"),
array("value" => "TZ", "text" => "Tanzania, United Republic Of"),
array("value" => "TH", "text" => "Thailand"),
array("value" => "TG", "text" => "Togo"),
array("value" => "TO", "text" => "Tonga"),
array("value" => "TT", "text" => "Trinidad and Tobago"),
array("value" => "TN", "text" => "Tunisia"),
array("value" => "TR", "text" => "Turkey"),
array("value" => "TM", "text" => "Turkmenistan"),
array("value" => "TC", "text" => "Turks and Caicos Islands"),
array("value" => "TV", "text" => "Tuvalu"),
array("value" => "UG", "text" => "Uganda"),
array("value" => "UA", "text" => "Ukraine"),
array("value" => "AE", "text" => "United Arab Emirates"),
array("value" => "GB", "text" => "United Kingdom"),
array("value" => "UY", "text" => "Uruguay"),
array("value" => "UZ", "text" => "Uzbekistan"),
array("value" => "VU", "text" => "Vanuatu"),
array("value" => "VE", "text" => "Venezuela"),
array("value" => "VN", "text" => "Vietnam"),
array("value" => "VG", "text" => "Virgin Islands (British)"),
array("value" => "VI", "text" => "Virgin Islands (U.S.)"),
array("value" => "WF", "text" => "Wallis and Futuna Islands"),
array("value" => "EH", "text" => "Western Sahara"),
array("value" => "YE", "text" => "Yemen"),
array("value" => "YU", "text" => "Yugoslavia"),
array("value" => "ZM", "text" => "Zambia"),
array("value" => "ZR", "text" => "Zaire"),
array("value" => "ZW", "text" => "Zimbabwe")
);
}
$ele->options = array();
$countrySize = sizeof($this->countryArr);
for($s = 0; $s < $countrySize; ++$s)
{
$opt = new option();
$opt->setAttributes($this->countryArr[$s]);
$ele->options[] = $opt;
}
}
elseif($eleType == "yesno")
{
$eleType = "radio";
$ele->options = array();
$opt = new option();
$opt->setAttributes(array("value" => "1", "text" => "Yes"));
$ele->options[] = $opt;
$opt = new option();
$opt->setAttributes(array("value" => "0", "text" => "No"));
$ele->options[] = $opt;
}
elseif($eleType == "truefalse")
{
$eleType = "radio";
$ele->options = array();
$opt = new option();
$opt->setAttributes(array("value" => "1", "text" => "True"));
$ele->options[] = $opt;
$opt = new option();
$opt->setAttributes(array("value" => "0", "text" => "False"));
$ele->options[] = $opt;
}
else
{
/*Various form types (select, radio, check, sort) use the options parameter to handle multiple choice elements.*/
if(array_key_exists("options", $params) && is_array($params["options"]))
{
$ele->options = array();
/*If the options array is numeric, assign the key and text to each value.*/
if(array_values($params["options"]) === $params["options"])
{
foreach($params["options"] as $key => $value)
{
$opt = new option();
$opt->setAttributes(array("value" => $value, "text" => $value));
$ele->options[] = $opt;
}
}
/*If the options array is associative, assign the key and text to each key/value pair.*/
else
{
foreach($params["options"] as $key => $value)
{
$opt = new option();
$opt->setAttributes(array("value" => $key, "text" => $value));
$ele->options[] = $opt;
}
}
}
/*If there is a file field type in the form, make sure that the encytype is set accordingly.*/
if($eleType == "file")
$this->attributes["enctype"] = "multipart/form-data";
/*Ensures tinymce code will be included if an element of type webeditor is detected.*/
if($eleType == "webeditor")
$this->includeTinyMce = 1;
}
/*If there is a required field type in the form, make sure javascript error checking is enabled.*/
if(!empty($ele->required) && empty($this->checkform))
$this->checkform = 1;
$this->elements[] = $ele;
}
/*-------------------------------------------START: HOW USERS CAN ADD FORM FIELDS--------------------------------------------*/
/*addElements allows users to add multiple form elements by passing a multi-dimensional array.*/
public function addElements($params)
{
$paramSize = sizeof($params);
for($i = 0; $i < $paramSize; ++$i)
$this->attachElement($params[$i]);
}
/*addElement allows users to add a single form element by passing an array.*/
public function addElement($label, $name, $type="", $value="", $additionalParams="")
{
$params = array("label" => $label, "name" => $name);
if(!empty($type))
$params["type"] = $type;
$params["value"] = $value;
/*Commonly used attributes such as name, type, and value exist as parameters in the function. All other attributes
that need to be included should be passed in the additionalParams field. This field should exist as an associative
array with the key being the attribute's name. Examples of attributes passed in the additionalParams field include
style, class, and onkeyup.*/
if(!empty($additionalParams) && is_array($additionalParams))
{
foreach($additionalParams as $key => $value)
$params[$key] = $value;
}
$this->attachElement($params);
}
/*The remaining function are shortcuts for adding each supported form field.*/
public function addHidden($name, $value="", $additionalParams="") {
$this->addElement("", $name, "hidden", $value, $additionalParams);
}
public function addTextbox($label, $name, $value="", $additionalParams="") {
$this->addElement($label, $name, "text", $value, $additionalParams);
}
public function addTextarea($label, $name, $value="", $additionalParams="") {
$this->addElement($label, $name, "textarea", $value, $additionalParams);
}
public function addWebEditor($label, $name, $value="", $additionalParams="") {
$this->addElement($label, $name, "webeditor", $value, $additionalParams);
}
public function addPassword($label, $name, $value="", $additionalParams="") {
$this->addElement($label, $name, "password", $value, $additionalParams);
}
public function addFile($label, $name, $additionalParams="") {
$this->addElement($label, $name, "file", "", $additionalParams);
}
public function addDate($label, $name, $value="", $additionalParams="") {
$this->addElement($label, $name, "date", $value, $additionalParams);
}
public function addDateRange($label, $name, $value="", $additionalParams="") {
$this->addElement($label, $name, "daterange", $value, $additionalParams);
}
public function addState($label, $name, $value="", $additionalParams="") {
$this->addElement($label, $name, "state", $value, $additionalParams);
}
public function addCountry($label, $name, $value="", $additionalParams="") {
$this->addElement($label, $name, "country", $value, $additionalParams);
}
public function addYesNo($label, $name, $value="", $additionalParams="") {
$this->addElement($label, $name, "yesno", $value, $additionalParams);
}
public function addTrueFalse($label, $name, $value="", $additionalParams="") {
$this->addElement($label, $name, "truefalse", $value, $additionalParams);
}
/*This function is included for backwards compatability.*/
public function addSelectbox($label, $name, $value="", $options="", $additionalParams="") {
$this->addSelect($label, $name, $value, $options, $additionalParams);
}
public function addSelect($label, $name, $value="", $options="", $additionalParams="") {
if(!is_array($additionalParams))
$additionalParams = array();
$additionalParams["options"] = $options;
$this->addElement($label, $name, "select", $value, $additionalParams);
}
public function addRadio($label, $name, $value="", $options="", $additionalParams="") {
if(!is_array($additionalParams))
$additionalParams = array();
$additionalParams["options"] = $options;
$this->addElement($label, $name, "radio", $value, $additionalParams);
}
public function addCheckbox($label, $name, $value="", $options="", $additionalParams="") {
if(!is_array($additionalParams))
$additionalParams = array();
$additionalParams["options"] = $options;
$this->addElement($label, $name, "checkbox", $value, $additionalParams);
}
public function addSort($label, $name, $options="", $additionalParams="") {
if(!is_array($additionalParams))
$additionalParams = array();
$additionalParams["options"] = $options;
$this->addElement($label, $name, "sort", "", $additionalParams);
}
public function addLatLng($label, $name, $value="", $additionalParams="") {
$this->addMap($label, $name, $value, $additionalParams);
}
/*This function is included for backwards compatability.*/
public function addMap($label, $name, $value="", $additionalParams="") {
$this->addElement($label, $name, "latlng", $value, $additionalParams);
}
public function addCheckSort($label, $name, $value="", $options="", $additionalParams="") {
if(!is_array($additionalParams))
$additionalParams = array();
$additionalParams["options"] = $options;
$this->addElement($label, $name, "checksort", $value, $additionalParams);
}
public function addCaptcha($label, $name, $value="", $additionalParams="") {
$this->addElement($label, $name, "captcha", $value, $additionalParams);
}
public function addSlider($label, $name, $value="", $additionalParams="") {
$this->addElement($label, $name, "slider", $value, $additionalParams);
}
/*-------------------------------------------END: HOW USERS CAN ADD FORM FIELDS--------------------------------------------*/
/*This function can be called to clear all attached element object instances from the form - beneficial when using the elementsToString function.*/
public function clearElements() {
$this->elements = array();
}
/*This function can be called to clear all attached button object instances from the form.*/
public function clearButtons() {
$this->buttons = array();
}
/*This function creates new button object instances and attaches them to the form. It is private and can only be used inside this class.*/
private function attachButton($params)
{
$button = new button();
$button->setAttributes($params);
$this->buttons[] = $button;
}
/*This function allows users to add multiple button object instances to the form by passing a multi-dimensional array.*/
public function addButtons($params)
{
$paramSize = sizeof($params);
for($i = 0; $i < $paramSize; ++$i)
$this->attachButton($params[$i]);
}
/*This function allows users to add a single button object instance to the form by passing an array.*/
function addButton($value="Submit", $type="submit", $additionalParams="")
{
$params = array("value" => $value, "type" => $type);
/*The additionalParams performs a similar role as in the addElement function. For more information, please read to description
of this field in the addElement function. Commonly used attributes included for additionalParams in this function include
onclick.*/
if(!empty($additionalParams) && is_array($additionalParams))
{
foreach($additionalParams as $key => $value)
$params[$key] = $value;
}
$this->attachButton($params);
}
/*This function renders the form's HTML.*/
public function render()
{
ob_start();
echo("\n<form");
if(!empty($this->attributes) && is_array($this->attributes))
{
$tmpAllowFieldArr = $this->allowedFields["form"];
foreach($this->attributes as $key => $value)
{
if($key == "onsubmit" && (!empty($this->checkform) || !empty($this->ajax)))
continue;
if(in_array($key, $tmpAllowFieldArr))
echo ' ', $key, '="', str_replace('"', '"', $value), '"';
}
}
if(!empty($this->checkform) || !empty($this->ajax))
echo ' onsubmit="return formhandler_', $this->attributes["name"], '(this);"';
echo(">\n");
$elementSize = sizeof($this->elements);
for($i = 0; $i < $elementSize; ++$i)
{
$ele = $this->elements[$i];
if($ele->attributes["type"] == "hidden")
{
echo "<input";
if(!empty($ele->attributes) && is_array($ele->attributes))
{
$tmpAllowFieldArr = $this->allowedFields["hidden"];
foreach($ele->attributes as $key => $value)
{
if(in_array($key, $tmpAllowFieldArr))
echo ' ', $key, '="', str_replace('"', '"', $value), '"';
}
}
echo "/>\n";
}
}
echo("<table");
if(!empty($this->tableAttributes) && is_array($this->tableAttributes))
{
$tmpAllowFieldArr = $this->allowedFields["table"];
foreach($this->tableAttributes as $key => $value)
{
if(in_array($key, $tmpAllowFieldArr))
echo ' ', $key, '="', str_replace('"', '"', $value), '"';
}
}
echo(">\n");
/*Render the elements by calling elementsToString function with the includeTable tags field set to false. There is no need
to render the table tag b/c we have just done that above.*/
echo($this->elementsToString(false));
/*If there are buttons included, render those to the screen now.*/
if(!empty($this->buttons))
{
echo "\t", '<tr><td align="right"';
if(!empty($this->tdAttributes) && is_array($this->tdAttributes))
{
$tmpAllowFieldArr = $this->allowedFields["td"];
foreach($this->tdAttributes as $key => $value)
{
if($key != "align" && in_array($key, $tmpAllowFieldArr))
echo ' ', $key, '="', str_replace('"', '"', $value), '"';
}
}
echo(">\n");
$buttonSize = sizeof($this->buttons);
for($i = 0; $i < $buttonSize; ++$i)
{
if(!empty($this->buttons[$i]->wrapLink))
{
echo("\t\t<a");
if(!empty($this->buttons[$i]->linkAttributes) && is_array($this->buttons[$i]->linkAttributes))
{
$tmpAllowFieldArr = $this->allowedFields["a"];
foreach($this->buttons[$i]->linkAttributes as $key => $value)
{
if(in_array($key, $tmpAllowFieldArr))
echo ' ', $key, '="', str_replace('"', '"', $value), '"';
}
}
echo(">");
}
else
echo("\t");
if(!empty($this->buttons[$i]->phpFunction))
{
$execStr = $this->buttons[$i]->phpFunction . "(";
if(!empty($this->buttons[$i]->phpParams))
{
if(is_array($this->buttons[$i]->phpParams))
{
$paramSize = sizeof($this->buttons[$i]->phpParams);
for($p = 0; $p < $paramSize; ++$p)
{
if($p != 0)
$execStr .= ",";
if(is_string($this->buttons[$i]->phpParams[$p]))
$execStr .= '"' . $this->buttons[$i]->phpParams[$p] . '"';
else
$execStr .= $this->buttons[$i]->phpParams[$p];
}
}
else
$execStr .= $this->buttons[$i]->phpParams;
}
$execStr .= ");";
echo(eval("return " . $execStr));
}
else
{
if(empty($this->buttons[$i]->wrapLink))
echo("\t");
echo("<input");
if(!empty($this->buttons[$i]->attributes) && is_array($this->buttons[$i]->attributes))
{
$tmpAllowFieldArr = $this->allowedFields["button"];
foreach($this->buttons[$i]->attributes as $key => $value)
{
if(in_array($key, $tmpAllowFieldArr))
echo ' ', $key, '="', str_replace('"', '"', $value), '"';
}
}
echo("/>");
}
if(!empty($this->buttons[$i]->wrapLink))
echo("</a>");
echo("\n");
}
echo("\t</td></tr>\n");
}
echo("</table>\n");
echo("</form>\n\n");
/*
If there are any required fields in the form or if this form is setup to utilize ajax, build a javascript
function for performing form validation before submission and/or for building and submitting a data string through ajax.
*/
if(!empty($this->checkform) || !empty($this->ajax))
{
echo '<script language="javascript">';
echo "\n\tfunction formhandler_", $this->attributes["name"], "(formObj) {";
$elementSize = sizeof($this->elements);
if(!empty($this->ajax))
echo "\n\t\t", 'var form_data = ""';
for($i = 0; $i < $elementSize; ++$i)
{
$ele = $this->elements[$i];
$eleType = $ele->attributes["type"];
$eleName = str_replace('"', '"', $ele->attributes["name"]);
$eleLabel = str_replace('"', '"', strip_tags($ele->label));
if($eleType == "checkbox")
{
echo "\n\t\t" , 'if(formObj.elements["', $eleName, '"].length) {';
if(!empty($ele->required))
echo "\n\t\t\tvar is_checked = false;";
echo "\n\t\t\t", 'for(i = 0; i < formObj.elements["', $eleName, '"].length; i++) {';
echo "\n\t\t\t\t", 'if(formObj.elements["', $eleName, '"][i].checked) {';
if(!empty($this->ajax))
echo "\n\t\t\t\t\t", 'form_data += "&', $eleName, '=" + escape(formObj.elements["', $eleName, '"][i].value);';
if(!empty($ele->required))
echo "\n\t\t\t\t\tis_checked = true;";
echo "\n\t\t\t\t}";
echo "\n\t\t\t}";
if(!empty($ele->required))
{
echo "\n\t\t\tif(!is_checked) {";
echo "\n\t\t\t\t" , 'alert("', $eleLabel, ' is a required field.");';
echo "\n\t\t\t\treturn false;";
echo "\n\t\t\t}";
}
echo "\n\t\t}";
echo "\n\t\telse {";
if(!empty($this->ajax))
{
echo "\n\t\t\t", 'if(formObj.elements["', $eleName, '"].checked)';
echo "\n\t\t\t", 'form_data += "&', $eleName, '=" + escape(formObj.elements["', $eleName, '"].value);';
}
if(!empty($ele->required))
{
echo "\n\t\t\t", 'if(!formObj.elements["', $eleName, '"].checked) {';
echo "\n\t\t\t\t", 'alert("', $ele->label, ' is a required field.");';
echo "\n\t\t\t\treturn false;";
echo "\n\t\t\t}";
}
echo "\n\t\t}";
}
elseif($eleType == "text" || $eleType == "textarea" || $eleType == "select" || $eleType == "hidden" || $eleType == "file" || $eleType == "password" || $eleType == "captcha")
{
if(!empty($this->ajax))
echo "\n\t\t", 'form_data += "&', $eleName, '=" + escape(formObj.elements["', $eleName, '"].value);';
if(!empty($ele->required))
{
echo "\n\t\t" , 'if(formObj.elements["', $eleName, '"].value == "") {';
echo "\n\t\t\t" , 'alert("', $eleLabel, ' is a required field.");';
echo "\n\t\t\t" , 'formObj.elements["', $eleName, '"].focus();';
echo "\n\t\t\treturn false;";
echo "\n\t\t}";
}
}
elseif($eleType == "webeditor")
{
if(!empty($this->ajax))
echo "\n\t\t", 'form_data += "&', $eleName, '=" + escape(tinyMCE.get("', $ele->attributes["id"], '").getContent());';
if(!empty($ele->required))
{
echo "\n\t\t", 'if(tinyMCE.get("', $ele->attributes["id"], '").getContent() == "") {';
echo "\n\t\t\t" , 'alert("', $eleLabel, ' is a required field.");';
echo "\n\t\t\t" , 'tinyMCE.get("', $ele->attributes["id"], '").focus();';
echo "\n\t\t\treturn false;";
echo "\n\t\t}";
}
}
elseif($eleType == "date")
{
if(!empty($this->ajax))
{
echo "\n\t\t", 'form_data += "&', $eleName, '="';
echo "\n\t\t" , 'if(formObj.elements["', $eleName, '"].value != "Click to Select Date...")';
echo "\n\t\t\t", 'form_data += formObj.elements["', $eleName, '"].value;';
}
if(!empty($ele->required))
{
echo "\n\t\t" , 'if(formObj.elements["', $eleName, '"].value == "Click to Select Date...") {';
echo "\n\t\t\t" , 'alert("', $eleLabel, ' is a required field.");';
echo "\n\t\t\t" , 'formObj.elements["', $eleName, '"].focus();';
echo "\n\t\t\treturn false;";
echo "\n\t\t}";
}
}
elseif($eleType == "daterange")
{
if(!empty($this->ajax))
{
echo "\n\t\t", 'form_data += "&', $eleName, '=";';
echo "\n\t\t" , 'if(formObj.elements["', $eleName, '"].value != "Click to Select Date Range...")';
echo "\n\t\t\t", 'form_data += formObj.elements["', $eleName, '"].value;';
}
if(!empty($ele->required))
{
echo "\n\t\t" , 'if(formObj.elements["', $eleName, '"].value == "Click to Select Date Range...") {';
echo "\n\t\t\t" , 'alert("', $eleLabel, ' is a required field.");';
echo "\n\t\t\t" , 'formObj.elements["', $eleName, '"].focus();';
echo "\n\t\t\treturn false;";
echo "\n\t\t}";
}
}
elseif($eleType == "latlng")
{
if(!empty($this->ajax))
{
echo "\n\t\t", 'form_data += "&', $eleName, '=";';
echo "\n\t\t" , 'if(formObj.elements["', $eleName, '"].value != "Drag Map Marker to Select Location...")';
echo "\n\t\t\t", 'form_data += formObj.elements["', $eleName, '"].value;';
}
if(!empty($ele->required))
{
echo "\n\t\t" , 'if(formObj.elements["', $eleName, '"].value == "Drag Map Marker to Select Location...") {';
echo "\n\t\t\t", 'alert("', $eleLabel, ' is a required field.");';
echo "\n\t\t\t", 'formObj.elements["', $eleName, '"].focus();';
echo "\n\t\t\treturn false;";
echo "\n\t\t}";
}
}
elseif($eleType == "checksort")
{
if(!empty($this->ajax))
{
echo "\n\t\t", 'if(formObj.elements["', $eleName, '"]) {';
echo "\n\t\t\t" , 'if(formObj.elements["', $eleName, '"].length) {';
echo "\n\t\t\t\t" , 'var ulObj = document.getElementById("', str_replace('"', '"', $ele->attributes["id"]), '");';
echo "\n\t\t\t\tvar childLen = ulObj.childNodes.length;";
echo "\n\t\t\t\tfor(i = 0; i < childLen; i++) {";
echo "\n\t\t\t\t\t", 'childObj = document.getElementById("', str_replace('"', '"', $ele->attributes["id"]), '").childNodes[i];';
echo "\n\t\t\t\t\t", 'if(childObj.tagName && childObj.tagName.toLowerCase() == "li")';
echo "\n\t\t\t\t\t\t", 'form_data += "&', $eleName, '=" + escape(childObj.childNodes[0].value);';
echo "\n\t\t\t\t}";
echo "\n\t\t\t}";
echo "\n\t\t\telse";
echo "\n\t\t\t\t", 'form_data += "&', $eleName, '=" + escape(formObj.elements["', $eleName, '"].value);';
echo "\n\t\t}";
}
if(!empty($ele->required))
{
echo "\n\t\t", 'if(!formObj.elements["', $eleName, '"]) {';
echo "\n\t\t\t", 'alert("', $eleLabel, ' is a required field.");';
echo "\n\t\t\treturn false;";
echo "\n\t\t}";
}
}
elseif(!empty($this->ajax) && $eleType == "radio")
{
echo "\n\t\t" , 'if(formObj.elements["', $eleName, '"].length) {';
echo "\n\t\t\t", 'for(i = 0; i < formObj.elements["', $eleName, '"].length; i++) {';
echo "\n\t\t\t\t", 'if(formObj.elements["', $eleName, '"][i].checked) {';
echo "\n\t\t\t\t\t", 'form_data += "&', $eleName, '=" + escape(formObj.elements["', $eleName, '"][i].value);';
echo "\n\t\t\t\t}";
echo "\n\t\t\t}";
echo "\n\t\t}";
echo "\n\t\telse {";
echo "\n\t\t\t", 'if(formObj.elements["', $eleName, '"].checked)';
echo "\n\t\t\t\t", 'form_data += "&', $eleName, '=" + escape(formObj.elements["', $eleName, '"].value);';
echo "\n\t\t}";
}
elseif(!empty($this->ajax) && $eleType == "sort")
{
echo "\n\t\t", 'if(formObj.elements["', $eleName, '"]) {';
echo "\n\t\t\t" , 'if(formObj.elements["', $eleName, '"].length) {';
echo "\n\t\t\t\t" , 'var ulObj = document.getElementById("', str_replace('"', '"', $ele->attributes["id"]), '");';
echo "\n\t\t\t\tvar childLen = ulObj.childNodes.length;";
echo "\n\t\t\t\tfor(i = 0; i < childLen; i++) {";
echo "\n\t\t\t\t\t", 'childObj = document.getElementById("', str_replace('"', '"', $ele->attributes["id"]), '").childNodes[i];';
echo "\n\t\t\t\t\t", 'if(childObj.tagName && childObj.tagName.toLowerCase() == "li")';
echo "\n\t\t\t\t\t\t", 'form_data += "&', $eleName, '=" + escape(childObj.childNodes[0].value);';
echo "\n\t\t\t\t}";
echo "\n\t\t\t}";
echo "\n\t\t\telse";
echo "\n\t\t\t\t", 'form_data += "&', $eleName, '=" + escape(formObj.elements["', $eleName, '"].value);';
echo "\n\t\t}";
}
}
if(!empty($this->ajax))
{
echo "\n\t\tform_data = form_data.substring(1, form_data.length);";
echo "\n\t\t$.ajax({";
echo "\n\t\t\t", 'type: "', $this->ajaxType, '",';
echo "\n\t\t\t", 'url: "', $this->ajaxUrl, '",';
echo "\n\t\t\t", 'dataType: "', $this->ajaxDataType, '",';
echo "\n\t\t\tdata: form_data,";
echo "\n\t\t\tsuccess: function(responseMsg, textStatus) {";
if(!empty($this->ajaxCallback))
echo "\n\t\t\t\t", $this->ajaxCallback, "(responseMsg);";
else
{
echo "\n\t\t\t\t", 'if(responseMsg != "")';
echo "\n\t\t\t\t\talert(responseMsg);";
}
echo "\n\t\t\t},";
echo "\n\t\t\terror: function(XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest.responseText); }";
echo "\n\t\t});";
echo "\n\t\treturn false;";
}
else
echo "\n\t\treturn true;";
echo "\n\t}";
echo "\n</script>\n\n";
}
if(empty($this->noAutoFocus) && !empty($this->focusElement))
{
echo '<script language="javascript">';
if(!empty($this->tinymceIDArr) && is_array($this->tinymceIDArr) && in_array($this->focusElement, $this->tinymceIDArr))
echo "\n\t\t", 'setTimeout("if(tinyMCE.get(\"', $this->focusElement, '\")) tinyMCE.get(\"', $this->focusElement, '\").focus();", 500);';
else
{
echo "\n\t", 'if(document.forms["', $this->attributes["name"], '"].elements["', $this->focusElement, '"].type != "select-one" && document.forms["', $this->attributes["name"], '"].elements["', $this->focusElement, '"].type != "select-multiple" && document.forms["', $this->attributes["name"], '"].elements["', $this->focusElement, '"].length)';
echo "\n\t\t", 'document.forms["', $this->attributes["name"], '"].elements["', $this->focusElement, '"][0].focus();';
echo "\n\telse";
echo "\n\t\t", 'document.forms["', $this->attributes["name"], '"].elements["', $this->focusElement, '"].focus();';
}
echo "\n</script>\n\n";
}
$content = ob_get_contents();
ob_end_clean();
echo($content);
}
/*This function builds and returns a string containing the HTML for the form fields. Typeically, this will be called from within the render() function; however, it can also be called by the user during unique situations.*/
public function elementsToString($includeTableTags = true)
{
$str = "";
/*If this first non-hidden element is of type text, textarea, password, select, file, checkbox, or radio, then focus will automatically be applied.*/
if(empty($this->noAutoFocus))
$focus = true;
else
$focus = false;
/*If this map array is set, an additional table will be inserted in each row - this way colspans can be omitted.*/
if(!empty($this->map))
{
$mapIndex = 0;
$mapCount = 0;
if($includeTableTags)
$str .= "\n<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\">\n";
if(!empty($this->tdAttributes["width"]))
$mapOriginalWidth = $this->tdAttributes["width"];
}
else
{
if($includeTableTags)
{
$str .= "\n<table";
$tmpAllowFieldArr = $this->allowedFields["table"];
if(!empty($this->tableAttributes) && is_array($this->tableAttributes))
{
foreach($this->tableAttributes as $key => $value)
{
if(in_array($key, $tmpAllowFieldArr))
$str .= ' ' . $key . '="' . str_replace('"', '"', $value) . '"';
}
}
$str .= ">\n";
}
}
$elementSize = sizeof($this->elements);
for($i = 0; $i < $elementSize; ++$i)
{
$ele = $this->elements[$i];
/*If the referenceValues array is filled, check for this specific elemet's name in the associative array key and populate the field's value if applicable.*/
if(!empty($this->referenceValues) && is_array($this->referenceValues) && array_key_exists($ele->attributes["name"], $this->referenceValues))
$ele->attributes["value"] = $this->referenceValues[$ele->attributes["name"]];
/*Hidden values do not need to be inside any table cell container; therefore, they are handled differently than the other fields.*/
if($ele->attributes["type"] == "hidden")
{
if($includeTableTags)
{
$str .= "\t<input";
if(!empty($ele->attributes) && is_array($ele->attributes))
{
$tmpAllowFieldArr = $this->allowedFields["hidden"];
foreach($ele->attributes as $key => $value)
{
if(in_array($key, $tmpAllowFieldArr))
$str .= ' ' . $key . '="' . str_replace('"', '"', $value) . '"';
}
}
$str .= "/>\n";
}
}
else
{
if(!empty($this->map))
{
if(array_key_exists($mapIndex, $this->map) && $this->map[$mapIndex] > 1)
{
if($mapCount == 0)
{
$str .= "\t" . '<tr><td style="padding: 0;">' . "\n";
$str .= "\t\t<table";
if(!empty($this->tableAttributes) && is_array($this->tableAttributes))
{
$tmpAllowFieldArr = $this->allowedFields["table"];
foreach($this->tableAttributes as $key => $value)
{
if(in_array($key, $tmpAllowFieldArr))
$str .= ' ' . $key . '="' . str_replace('"', '"', $value) . '"';
}
}
$str .= ">\n";
$str .= "\t\t\t<tr>\n\t\t\t\t";
/*Widths are percentage based and are calculated by dividing 100 by the number of form fields in the given row.*/
if(($elementSize - $i) < $this->map[$mapIndex])
$this->tdAttributes["width"] = number_format(100 / ($elementSize - $i), 2, ".", "") . "%";
else
$this->tdAttributes["width"] = number_format(100 / $this->map[$mapIndex], 2, ".", "") . "%";
}
else
$str .= "\t\t\t\t";
}
else
{
$str .= "\t" . '<tr><td style="padding: 0;">' . "\n";
$str .= "\t\t<table";
if(!empty($this->tableAttributes) && is_array($this->tableAttributes))
{
$tmpAllowFieldArr = $this->allowedFields["table"];
foreach($this->tableAttributes as $key => $value)
{
if(in_array($key, $tmpAllowFieldArr))
$str .= ' ' . $key . '="' . str_replace('"', '"', $value) . '"';
}
}
$str .= ">\n";
$str .= "\t\t\t<tr>\n\t\t\t\t";
if(!empty($mapOriginalWidth))
$this->tdAttributes["width"] = $mapOriginalWidth;
else
unset($this->tdAttributes["width"]);
}
}
else
$str .= "\t<tr>";
$str .= "<td";
if(!empty($this->tdAttributes) && is_array($this->tdAttributes))
{
$tmpAllowFieldArr = $this->allowedFields["td"];
foreach($this->tdAttributes as $key => $value)
{
if(in_array($key, $tmpAllowFieldArr))
$str .= ' ' . $key . '="' . str_replace('"', '"', $value) . '"';
}
}
$str .= ">\n";
if(!empty($ele->label))
{
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
/*preHTML and postHTML allow for any special case scenarios. One specific situation where these may be used would
be if you need to toggle the visibility of an item or items based on the state of another field such as a radio button.*/
if(!empty($ele->preHTML))
{
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
$str .= $ele->preHTML;
$str .= "\n";
}
/*Render the label inside a <div> tag.*/
$str .= "<div";
if(!empty($this->labelAttributes) && is_array($this->labelAttributes))
{
$tmpAllowFieldArr = $this->allowedFields["div"];
foreach($this->labelAttributes as $key => $value)
{
if(in_array($key, $tmpAllowFieldArr))
$str .= ' ' . $key . '="' . str_replace('"', '"', $value) . '"';
}
}
$str .= ">";
/*If this field is set as required, render an "*" inside a <span> tag.*/
if(!empty($ele->required))
{
$str .= " <span";
if(!empty($this->requiredAttributes) && is_array($this->requiredAttributes))
{
$tmpAllowFieldArr = $this->allowedFields["span"];
foreach($this->requiredAttributes as $key => $value)
{
if(in_array($key, $tmpAllowFieldArr))
$str .= ' ' . $key . '="' . str_replace('"', '"', $value) . '"';
}
}
$str .= ">*</span> ";
}
$str .= $ele->label;
/*jQuery Tooltip Functionality*/
if(!empty($ele->tooltip))
{
if(empty($this->tooltipIcon))
$this->tooltipIcon = $this->jqueryPath . "/qtip/tooltip_icon.png";
if(!is_array($this->tooltipArr))
$this->tooltipArr = array();
/*jQuery tooltips need a unique id to function properly.*/
$tooltipID = "tooltip_" . rand(0, 999);
/*Ensure that this field id hasn't already been used.*/
while(array_key_exists($tooltipID, $this->tooltipArr))
$tooltipID = "tooltip_" . rand(0, 999);
$this->tooltipArr[$tooltipID] = $ele->tooltip;
$str .= ' <img id="' . $tooltipID . '" src="' . $this->tooltipIcon . '">';
}
$str .= "</div>\n";
}
/*Check the element's type and render the field accordinly.*/
$eleType = &$ele->attributes["type"];
if($eleType == "text" || $eleType == "password")
{
if(empty($ele->attributes["style"]))
$ele->attributes["style"] = "width: 100%;";
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
$str .= "<input";
if(!empty($ele->attributes) && is_array($ele->attributes))
{
$tmpAllowFieldArr = $this->allowedFields["text"];
foreach($ele->attributes as $key => $value)
{
if(in_array($key, $tmpAllowFieldArr))
$str .= ' ' . $key . '="' . str_replace('"', '"', $value) . '"';
}
}
if(!empty($ele->disabled))
$str .= " disabled";
if(!empty($ele->readonly))
$str .= " readonly";
$str .= "/>\n";
if($focus)
$this->focusElement = $ele->attributes["name"];
}
elseif($eleType == "file")
{
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
$str .= "<input";
if(!empty($ele->attributes) && is_array($ele->attributes))
{
$tmpAllowFieldArr = $this->allowedFields["file"];
foreach($ele->attributes as $key => $value)
{
if(in_array($key, $tmpAllowFieldArr))
$str .= ' ' . $key . '="' . str_replace('"', '"', $value) . '"';
}
}
if(!empty($ele->disabled))
$str .= " disabled";
if(!empty($ele->readonly))
$str .= " readonly";
$str .= "/>\n";
if($focus)
$this->focusElement = $ele->attributes["name"];
}
elseif($eleType == "textarea")
{
if(empty($ele->attributes["style"]))
$ele->attributes["style"] = "width: 100%; height: 100px;";
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
$str .= "<textarea";
if(!empty($ele->attributes) && is_array($ele->attributes))
{
$tmpAllowFieldArr = $this->allowedFields["textarea"];
foreach($ele->attributes as $key => $value)
{
if(in_array($key, $tmpAllowFieldArr))
$str .= ' ' . $key . '="' . str_replace('"', '"', $value) . '"';
}
}
if(!empty($ele->disabled))
$str .= " disabled";
if(!empty($ele->readonly))
$str .= " readonly";
$str .= ">" . $ele->attributes["value"] . "</textarea>\n";
if($focus)
$this->focusElement = $ele->attributes["name"];
}
elseif($eleType == "webeditor")
{
if(empty($ele->attributes["style"]))
$ele->attributes["style"] = "width: 100%; height: 100px;";
if(empty($ele->attributes["class"]))
$ele->attributes["class"] .= " ";
if(!empty($ele->webeditorSimple))
$ele->attributes["class"] .= "tiny_mce_simple";
else
$ele->attributes["class"] .= "tiny_mce";
if(empty($ele->attributes["id"]))
$ele->attributes["id"] = "webeditor_" . rand(0, 999);
if(!is_array($this->tinymceIDArr))
$this->tinymceIDArr = array();
while(in_array($ele->attributes["id"], $this->tinymceIDArr))
$ele->attributes["id"] = "webeditor_" . rand(0, 999);
$this->tinymceIDArr[] = $ele->attributes["id"];
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
$str .= "<textarea";
if(!empty($ele->attributes) && is_array($ele->attributes))
{
$tmpAllowFieldArr = $this->allowedFields["textarea"];
foreach($ele->attributes as $key => $value)
{
if(in_array($key, $tmpAllowFieldArr))
$str .= ' ' . $key . '="' . str_replace('"', '"', $value) . '"';
}
}
if(!empty($ele->disabled))
$str .= " disabled";
if(!empty($ele->readonly))
$str .= " readonly";
$str .= ">" . $ele->attributes["value"] . "</textarea>\n";
if($focus)
$this->focusElement = $ele->attributes["id"];
}
elseif($eleType == "select")
{
if(empty($ele->attributes["style"]))
$ele->attributes["style"] = "width: 100%;";
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
$str .= "<select";
if(!empty($ele->attributes) && is_array($ele->attributes))
{
$tmpAllowFieldArr = $this->allowedFields["select"];
foreach($ele->attributes as $key => $value)
{
if(in_array($key, $tmpAllowFieldArr))
$str .= ' ' . $key . '="' . str_replace('"', '"', $value) . '"';
}
}
if(!empty($ele->disabled))
$str .= " disabled";
if(!empty($ele->readonly))
$str .= " readonly";
if(!empty($ele->multiple))
$str .= " multiple";
$str .= "/>\n";
$selected = false;
if(is_array($ele->options))
{
$optionSize = sizeof($ele->options);
for($o = 0; $o < $optionSize; ++$o)
{
$str .= "\t\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
$str .= '<option value="' . str_replace('"', '"', $ele->options[$o]->value) . '"';
if((!is_array($ele->attributes["value"]) && !$selected && $ele->attributes["value"] == $ele->options[$o]->value) || (is_array($ele->attributes["value"]) && in_array($ele->options[$o]->value, $ele->attributes["value"], true)))
{
$str .= " selected";
$selected = true;
}
$str .= '>' . $ele->options[$o]->text . "</option>\n";
}
}
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
$str .= "</select>\n";
if($focus)
$this->focusElement = $ele->attributes["name"];
}
elseif($eleType == "radio")
{
if(is_array($ele->options))
{
$optionSize = sizeof($ele->options);
for($o = 0; $o < $optionSize; ++$o)
{
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
if($o != 0)
{
if(!empty($ele->nobreak))
$str .= " ";
else
$str .= "<br>";
}
$str .= "<input";
$tmpAllowFieldArr = $this->allowedFields["radio"];
if(!empty($ele->attributes) && is_array($ele->attributes))
{
foreach($ele->attributes as $key => $value)
{
if(in_array($key, $tmpAllowFieldArr))
$str .= ' ' . $key . '="' . str_replace('"', '"', $value) . '"';
}
}
$str .= ' id="' . str_replace('"', '"', $ele->attributes["name"]) . $o . '" value="' . str_replace('"', '"', $ele->options[$o]->value) . '"';
if(($ele->attributes["value"] == "" && $o == 0) || $ele->attributes["value"] == $ele->options[$o]->value)
$str .= " checked";
if(!empty($ele->disabled))
$str .= " disabled";
$str .= '>';
if(empty($this->noLabels))
$str .= '<label for="' . str_replace('"', '"', $ele->attributes["name"]) . $o . '" style="cursor: pointer;">';
$str .= $ele->options[$o]->text;
if(empty($this->noLabels))
$str .= "</label>\n";
}
if($focus)
$this->focusElement = $ele->attributes["name"];
}
}
elseif($eleType == "checkbox")
{
if(is_array($ele->options))
{
$optionSize = sizeof($ele->options);
if($optionSize > 1 && substr($ele->attributes["name"], -2) != "[]")
$ele->attributes["name"] .= "[]";
for($o = 0; $o < $optionSize; ++$o)
{
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
if($o != 0)
{
if(!empty($ele->nobreak))
$str .= " ";
else
$str .= "<br>";
}
$str .= "<input";
if(!empty($ele->attributes) && is_array($ele->attributes))
{
$tmpAllowFieldArr = $this->allowedFields["checkbox"];
foreach($ele->attributes as $key => $value)
{
if(in_array($key, $tmpAllowFieldArr))
$str .= ' ' . $key . '="' . str_replace('"', '"', $value) . '"';
}
}
$str .= ' id="' . str_replace('"', '"', $ele->attributes["name"]) . $o . '" value="' . str_replace('"', '"', $ele->options[$o]->value) . '"';
/*For checkboxes, the value parameter can be an array - which allows for multiple boxes to be checked by default.*/
if((!is_array($ele->attributes["value"]) && $ele->attributes["value"] == $ele->options[$o]->value) || (is_array($ele->attributes["value"]) && in_array($ele->options[$o]->value, $ele->attributes["value"], true)))
$str .= " checked";
if(!empty($ele->disabled))
$str .= " disabled";
$str .= '>';
if(empty($this->noLabels))
$str .= '<label for="' . str_replace('"', '"', $ele->attributes["name"]) . $o . '" style="cursor: pointer;">';
$str .= $ele->options[$o]->text;
if(empty($this->noLabels))
$str .= "</label>\n";
}
if($focus)
$this->focusElement = $ele->attributes["name"];
}
}
elseif($eleType == "date")
{
if(empty($ele->attributes["style"]))
$ele->attributes["style"] = "width: 100%; cursor: pointer;";
if(empty($ele->attributes["id"]))
$ele->attributes["id"] = "dateinput_" . rand(0, 999);
if(empty($ele->attributes["value"]))
$ele->attributes["value"] = "Click to Select Date...";
if(!is_array($this->jqueryDateArr))
$this->jqueryDateArr = array();
while(in_array($ele->attributes["id"], $this->jqueryDateArr))
$ele->attributes["id"] = "dateinput_" . rand(0, 999);
$this->jqueryDateArr[] = $ele->attributes["id"];
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
$str .= "<input";
if(!empty($ele->attributes) && is_array($ele->attributes))
{
$tmpAllowFieldArr = $this->allowedFields["date"];
foreach($ele->attributes as $key => $value)
{
if(in_array($key, $tmpAllowFieldArr))
$str .= ' ' . $key . '="' . str_replace('"', '"', $value) . '"';
}
}
$str .= " readonly";
$str .= "/>\n";
}
elseif($eleType == "daterange")
{
if(empty($ele->attributes["style"]))
$ele->attributes["style"] = "width: 100%; cursor: pointer;";
if(empty($ele->attributes["id"]))
$ele->attributes["id"] = "daterangeinput_" . rand(0, 999);
if(empty($ele->attributes["value"]))
$ele->attributes["value"] = "Click to Select Date Range...";
if(!is_array($this->jqueryDateRangeArr))
$this->jqueryDateRangeArr = array();
while(in_array($ele->attributes["id"], $this->jqueryDateRangeArr))
$ele->attributes["id"] = "daterangeinput_" . rand(0, 999);
$this->jqueryDateRangeArr[] = $ele->attributes["id"];
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
$str .= "<input";
if(!empty($ele->attributes) && is_array($ele->attributes))
{
$tmpAllowFieldArr = $this->allowedFields["date"];
foreach($ele->attributes as $key => $value)
{
if(in_array($key, $tmpAllowFieldArr))
$str .= ' ' . $key . '="' . str_replace('"', '"', $value) . '"';
}
}
$str .= " readonly";
$str .= "/>\n";
}
elseif($eleType == "sort")
{
if(is_array($ele->options))
{
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
if(empty($ele->attributes["id"]))
$ele->attributes["id"] = "sort_" . rand(0, 999);
if(substr($ele->attributes["name"], -2) != "[]")
$ele->attributes["name"] .= "[]";
$this->jquerySortArr[] = array($ele->attributes["id"], $ele->attributes["name"]);
$str .= '<ul id="' . str_replace('"', '"', $ele->attributes["id"]) . '" style="list-style-type: none; margin: 2px 0 0 0; padding: 0; cursor: pointer;">' . "\n";
$optionSize = sizeof($ele->options);
for($o = 0; $o < $optionSize; ++$o)
{
$str .= "\t\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
$str .= '<li class="ui-state-default" style="margin: 0 3px 3px 3px; padding: 0.4em; padding-left: 1.5em; font-size: 15px !important;"><input type="hidden" name="' . str_replace('"', '"', $ele->attributes["name"]) . '" value="' . str_replace('"', '"', $ele->options[$o]->value) . '"><span class="ui-icon ui-icon-arrowthick-2-n-s" style="position: absolute; margin-left: -1.3em;"></span>' . $ele->options[$o]->text . '</li>' . "\n";
}
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
$str .= "</ul>\n";
}
}
elseif($eleType == "latlng")
{
if(empty($ele->attributes["style"]))
$ele->attributes["style"] = "width: 100%;";
if(empty($ele->attributes["id"]))
$ele->attributes["id"] = "latlnginput_" . rand(0, 999);
$this->latlngArr[] = $ele;
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
$str .= "<input";
/*Allowed fields used from date field type as they perform identically.*/
if(!empty($ele->attributes) && is_array($ele->attributes))
{
$tmpAllowFieldArr = $this->allowedFields["latlng"];
foreach($ele->attributes as $key => $value)
{
if(in_array($key, $tmpAllowFieldArr))
$str .= ' ' . $key . '="' . str_replace('"', '"', $value) . '"';
}
}
$str .= ' value="';
if(empty($ele->attributes["value"]))
$str .= "Drag Map Marker to Select Location...";
elseif(!empty($ele->attributes["value"]) && is_array($ele->attributes["value"]))
$str .= "Latitude: " . $ele->attributes["value"][0] . ", Longitude: " . $ele->attributes["value"][1];
$str .= '"';
$str .= " readonly";
$str .= "/>\n";
if(empty($ele->latlngHeight))
$ele->latlngHeight = 200;
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
$str .= '<div id="' . str_replace('"', '"', $ele->attributes["id"]) . '_canvas" style="margin-top: 2px; height: ' . $ele->latlngHeight . 'px;';
if(!empty($ele->latlngWidth))
$str .= ' width: ' . $ele->latlngWidth . 'px;';
$str .= '"></div>' . "\n";
}
elseif($eleType == "checksort")
{
if(is_array($ele->options))
{
if(empty($ele->attributes["id"]))
$ele->attributes["id"] = "checksort_" . rand(0, 999);
if(substr($ele->attributes["name"], -2) != "[]")
$ele->attributes["name"] .= "[]";
$this->jquerySortArr[] = array($ele->attributes["id"], $ele->attributes["name"]);
$this->jqueryCheckSort = 1;
/*Temporary variable for building <ul> sorting structure for checked options.*/
$sortLIArr = array();
$optionSize = sizeof($ele->options);
for($o = 0; $o < $optionSize; ++$o)
{
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
if($o != 0)
{
if(!empty($ele->nobreak))
$str .= " ";
else
$str .= "<br>";
}
$str .= "<input";
if(!empty($ele->attributes) && is_array($ele->attributes))
{
$tmpAllowFieldArr = $this->allowedFields["checksort"];
foreach($ele->attributes as $key => $value)
{
if(in_array($key, $tmpAllowFieldArr))
$str .= ' ' . $key . '="' . str_replace('"', '"', $value) . '"';
}
}
$str .= ' id="' . str_replace('"', '"', $ele->attributes["name"]) . $o . '" type="checkbox" value="' . str_replace('"', '"', $ele->options[$o]->value) . '" onclick="addOrRemoveCheckSortItem_' . $this->attributes["name"] . '(this, \'' . str_replace(array('"', "'"), array('"', "\'"), $ele->attributes["id"]) . '\', \'' . str_replace(array('"', "'"), array('"', "\'"), $ele->attributes["name"]) . '\', ' . $o . ', \'' . str_replace(array('"', "'"), array('"', "\'"), $ele->options[$o]->value) . '\', \'' . str_replace(array('"', "'"), array('"', "\'"), $ele->options[$o]->text) . '\');"';
/*For checkboxes, the value parameter can be an array - which allows for multiple boxes to be checked by default.*/
if((!is_array($ele->attributes["value"]) && $ele->attributes["value"] == $ele->options[$o]->value) || (is_array($ele->attributes["value"]) && in_array($ele->options[$o]->value, $ele->attributes["value"], true)))
{
$str .= " checked";
$sortLIArr[$ele->options[$o]->value] = '<li class="ui-state-default" id="' . str_replace('"', '"', $ele->attributes["id"]) . $o . '" style="margin: 0 3px 3px 3px; padding: 0.4em; padding-left: 1.5em; font-size: 15px !important;"><input type="hidden" name="' . str_replace('"', '"', $ele->attributes["name"]) . '" value="' . str_replace('"', '"', $ele->options[$o]->value) . '"><span class="ui-icon ui-icon-arrowthick-2-n-s" style="position: absolute; margin-left: -1.3em;"></span>' . $ele->options[$o]->text . '</li>' . "\n";
}
if(!empty($ele->disabled))
$str .= " disabled";
$str .= '>';
if(empty($this->noLabels))
$str .= '<label for="' . str_replace('"', '"', $ele->attributes["name"]) . $o . '" style="cursor: pointer;">';
$str .= $ele->options[$o]->text;
if(empty($this->noLabels))
$str .= "</label>\n";
}
/*If there are any check options by default, render the <ul> sorting structure.*/
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
$str .= '<ul id="' . str_replace('"', '"', $ele->attributes["id"]) . '" style="list-style-type: none; margin: 2px 0 0 0; padding: 0; cursor: pointer;">' . "\n";
if(!empty($sortLIArr))
{
if(is_array($ele->attributes["value"]))
{
$eleValueSize = sizeof($ele->attributes["value"]);
for($li = 0; $li < $eleValueSize; $li++)
{
if(isset($sortLIArr[$ele->attributes["value"][$li]]))
{
$str .= "\t\t\t";
if(!empty($this->map))
$str .= "\t\t\t\t";
$str .= $sortLIArr[$ele->attributes["value"][$li]];
}
}
}
else
{
if(isset($sortLIArr[$ele->attributes["value"][$li]]))
{
$str .= "\t\t\t";
if(!empty($this->map))
$str .= "\t\t\t\t";
$str .= $sortLIArr[$ele->attributes["value"]];
}
}
}
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
$str .= "</ul>\n";
}
}
elseif($eleType == "captcha")
{
if(empty($ele->attributes["style"]))
$ele->attributes["style"] = "width: 100%;";
if(!is_array($this->captchaNameArr))
$this->captchaNameArr = array();
if(empty($ele->attributes["name"]))
$ele->attributes["name"] = "captchainput_0";
$captchaCounter = 1;
while(in_array($ele->attributes["name"], $this->captchaNameArr))
{
$ele->attributes["name"] = "captchainput_" . $captchaCounter;
$captchaCounter++;
}
$this->captchaNameArr[] = $ele->attributes["name"];
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
$str .= '<img src="' . $this->captchaPath . '/captcha.php?fid=' . $this->attributes["name"] . '&eid=' . $ele->attributes["name"] . '" border="0" style="margin: 5px 0;">' . "\n";
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
$str .= "<br><input";
if(!empty($ele->attributes) && is_array($ele->attributes))
{
$tmpAllowFieldArr = $this->allowedFields["text"];
foreach($ele->attributes as $key => $value)
{
if(in_array($key, $tmpAllowFieldArr))
$str .= ' ' . $key . '="' . str_replace('"', '"', $value) . '"';
}
}
if(!empty($ele->disabled))
$str .= " disabled";
if(!empty($ele->readonly))
$str .= " readonly";
$str .= "/>\n";
if($focus)
$this->focusElement = $ele->attributes["name"];
}
elseif($eleType == "slider")
{
if(empty($ele->attributes["id"]))
$ele->attributes["id"] = "sliderinput_" . rand(0, 999);
if(!is_array($this->jquerySliderArr))
$this->jquerySliderArr = array();
while(in_array($ele->attributes["id"], $this->jquerySliderArr))
$ele->attributes["id"] = "sliderinput_" . rand(0, 999);
if(empty($ele->attributes["value"]))
$ele->attributes["value"] = "0";
if(empty($ele->sliderMin))
$ele->sliderMin = "0";
if(empty($ele->sliderMax))
$ele->sliderMax = "100";
if(empty($ele->sliderOrientation) || !in_array($ele->sliderOrientation, array("horizontal", "vertical")))
$ele->sliderOrientation = "horizontal";
if(empty($ele->sliderPrefix))
$ele->sliderPrefix = "";
if(empty($ele->sliderSuffix))
$ele->sliderSuffix = "";
if(is_array($ele->attributes["value"]) && sizeof($ele->attributes["value"]) == 1)
$ele->attributes["value"] = $ele->attributes["value"][0];
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
$str .= '<div id="' . $ele->attributes["id"] . '" style="font-size: 12px !important; margin: 2px 0;';
if($ele->sliderOrientation == "vertical" && !empty($ele->sliderHeight))
{
if(substr($ele->sliderHeight, -2) != "px")
$ele->sliderHeight .= "px";
$str .= ' height: ' . $ele->sliderHeight;
}
$str .= '"></div>' . "\n";
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
if(empty($ele->sliderHideDisplay))
{
$str .= '<div id="' . $ele->attributes["id"] . '_display">';
if(is_array($ele->attributes["value"]))
{
sort($ele->attributes["value"]);
$str .= $ele->sliderPrefix . $ele->attributes["value"][0] . $ele->sliderSuffix . " - " . $ele->sliderPrefix . $ele->attributes["value"][1] . $ele->sliderSuffix;
}
else
$str .= $ele->sliderPrefix . $ele->attributes["value"] . $ele->sliderSuffix;
$str .= '</div>' . "\n";
}
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
if(is_array($ele->attributes["value"]))
{
if(substr($ele->attributes["name"], -2) != "[]")
$ele->attributes["name"] .= "[]";
$str .= '<input type="hidden" name="' . str_replace('"', '"', $ele->attributes["name"]) . '" value="' . str_replace('"', '"', $ele->attributes["value"][0]) . '">' . "\n";
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
$str .= '<input type="hidden" name="' . str_replace('"', '"', $ele->attributes["name"]) . '" value="' . str_replace('"', '"', $ele->attributes["value"][1]) . '">' . "\n";
}
else
$str .= '<input type="hidden" name="' . str_replace('"', '"', $ele->attributes["name"]) . '" value="' . str_replace('"', '"', $ele->attributes["value"]) . '">' . "\n";
$this->jquerySliderArr[] = $ele;
}
if(!empty($ele->postHTML))
{
$str .= "\t\t";
if(!empty($this->map))
$str .= "\t\t\t";
$str .= $ele->postHTML;
$str .= "\n";
}
$str .= "\t";
if(!empty($this->map))
$str .= "\t\t\t";
$str .= "</td>";
if(!empty($this->map))
{
if(($i + 1) == $elementSize)
$str .= "\n\t\t\t</tr>\n\t\t</table>\n\t</td></tr>\n";
elseif(array_key_exists($mapIndex, $this->map) && $this->map[$mapIndex] > 1)
{
if(($mapCount + 1) == $this->map[$mapIndex])
{
$mapCount = 0;
++$mapIndex;
$str .= "\n\t\t\t</tr>\n\t\t</table>\n\t</td></tr>\n";
}
else
{
++$mapCount;
$str .= "\n";
}
}
else
{
++$mapIndex;
$mapCount = 0;
$str .= "\n\t\t\t</tr>\n\t\t</table>\n\t</td></tr>\n";
}
}
else
$str .= "</tr>\n";
$focus = false;
}
}
if(!empty($this->map) && !empty($mapOriginalWidth))
$this->tdAttributes["width"] = $mapOriginalWidth;
else
unset($this->tdAttributes["width"]);
if($includeTableTags)
$str .= "</table>\n";
/*The two jQuery hybrid fields - sort and date - require javascript and css elements to be included in the markup. Feel free
to edit the css and/or javascript to fit your needs. For instance, you can change the date field's formatted date string below, or
change how the sort operates. Visit http://www.jqueryui.com for instructions/examples on how to do this.*/
if(!empty($this->jqueryDateArr) || !empty($this->jqueryDateRangeArr) || !empty($this->jquerySortArr) || !empty($this->tooltipArr) || !empty($this->jquerySliderArr))
{
if(empty($this->preventJQueryLoad))
$str .= "\n\t" . '<script language="javascript" src="' . $this->jqueryPath . '/jquery-1.3.2.min.js"></script>';
if(!empty($this->jqueryDateArr) || !empty($this->jqueryDateRangeArr) || !empty($this->jquerySortArr) || !empty($this->jquerySliderArr))
{
$str .= "\n\t" . '<link href="' . $this->jqueryPath . '/jquery-ui-1.7.2.custom.css" rel="stylesheet" type="text/css">';
if(empty($this->preventJQueryUILoad))
$str .= "\n\t" . '<script language="javascript" src="' . $this->jqueryPath . '/jquery-ui-1.7.2.custom.min.js"></script>';
}
if(!empty($this->tooltipArr) && empty($this->preventQTipLoad))
$str .= "\n\t" . '<script language="javascript" src="' . $this->jqueryPath . '/qtip/jquery.qtip-1.0.0-rc3.min.js"></script>';
if(!empty($this->jqueryDateArr))
$str .= "\n\t" . '<style type="text/css">.ui-datepicker-div, .ui-datepicker-inline, #ui-datepicker-div { font-size: 0.8em !important; }</style>';
if(!empty($this->jquerySliderArr))
$str .= "\n\t" . '<style type="text/css">.ui-slider-handle { cursor: pointer !important; }</style>';
if(!empty($this->jqueryDateRangeArr))
{
$str .= "\n\t" . '<link href="' . $this->jqueryPath . '/ui.daterangepicker.css" rel="stylesheet" type="text/css">';
$str .= "\n\t" . '<script language="javascript" src="' . $this->jqueryPath . '/daterangepicker.jquery.js"></script>';
}
$str .= "\n\t" . '<script language="javascript" defer="true">';
$str .= "\n\t\t" . "$(function() {";
if(!empty($this->jqueryDateArr))
{
$jquerySize = sizeof($this->jqueryDateArr);
for($j = 0; $j < $jquerySize; ++$j)
$str .= "\n\t\t\t" . '$("#' . $this->jqueryDateArr[$j] . '").datepicker({ dateFormat: "MM d, yy", showButtonPanel: true });';
}
if(!empty($this->jqueryDateRangeArr))
{
$jquerySize = sizeof($this->jqueryDateRangeArr);
for($j = 0; $j < $jquerySize; ++$j)
$str .= "\n\t\t\t" . '$("#' . $this->jqueryDateRangeArr[$j] . '").daterangepicker();';
}
if(!empty($this->jquerySortArr))
{
$jquerySize = sizeof($this->jquerySortArr);
for($j = 0; $j < $jquerySize; ++$j)
{
$str .= "\n\t\t\t" . '$("#' . $this->jquerySortArr[$j][0] . '").sortable({ axis: "y" });';
$str .= "\n\t\t\t" . '$("#' . $this->jquerySortArr[$j][0] . '").disableSelection();';
}
}
/*For more information on qtip, visit http://craigsworks.com/projects/qtip/.*/
if(!empty($this->tooltipArr))
{
$tooltipKeys = array();
$tooltipKeys = array_keys($this->tooltipArr);
$tooltipSize = sizeof($tooltipKeys);
for($j = 0; $j < $tooltipSize; ++$j)
{
$str .= "\n\t\t\t" . '$("#' . $tooltipKeys[$j] . '").qtip({ content: "' . str_replace('"', '\"', $this->tooltipArr[$tooltipKeys[$j]]) . '", style: { name: "light", tip: "bottomLeft", border: { radius: 5, width: 5';
if(!empty($this->tooltipBorderColor))
{
if($this->tooltipBorderColor[0] != "#")
$this->tooltipBorderColor = "#" . $this->tooltipBorderColor;
$str .= ', color: "' . $this->tooltipBorderColor . '"';
}
$str .= ' } }, position: { corner: { target: "topRight", tooltip: "bottomLeft" } } });';
}
}
if(!empty($this->jquerySliderArr))
{
$jquerySize = sizeof($this->jquerySliderArr);
for($j = 0; $j < $jquerySize; ++$j)
{
$slider = $this->jquerySliderArr[$j];
$str .= "\n\t\t\t" . '$("#' . $slider->attributes["id"] . '").slider({';
if(is_array($slider->attributes["value"]))
$str .= 'range: true, values: [' . $slider->attributes["value"][0] . ', ' . $slider->attributes["value"][1] . ']';
else
$str .= 'range: "min", value: ' . $slider->attributes["value"];
$str .= ', min: ' . $slider->sliderMin . ', max: ' . $slider->sliderMax . ', orientation: "' . $slider->sliderOrientation . '"';
if(!empty($slider->sliderSnapIncrement))
$str .= ', step: ' . $slider->sliderSnapIncrement;
if(is_array($slider->attributes["value"]))
{
$str .= ', slide: function(event, ui) { ';
if(empty($slider->sliderHideDisplay))
$str .= '$("#' . $slider->attributes["id"] . '_display").text("' . $slider->sliderPrefix . '" + ui.values[0] + "' . $slider->sliderSuffix . ' - ' . $slider->sliderPrefix . '" + ui.values[1] + "' . $slider->sliderSuffix . '"); ';
$str .= 'document.forms["' . $this->attributes["name"] . '"].elements["' . str_replace('"', '"', $slider->attributes["name"]) . '"][0].value = ui.values[0]; document.forms["' . $this->attributes["name"] . '"].elements["' . str_replace('"', '"', $slider->attributes["name"]) . '"][1].value = ui.values[1];}';
}
else
{
$str .= ', slide: function(event, ui) { ';
if(empty($slider->sliderHideDisplay))
$str .= '$("#' . $slider->attributes["id"] . '_display").text("' . $slider->sliderPrefix . '" + ui.value + "' . $slider->sliderSuffix . '");';
$str .= ' document.forms["' . $this->attributes["name"] . '"].elements["' . str_replace('"', '"', $slider->attributes["name"]) . '"].value = ui.value;}';
}
$str .= '});';
}
}
$str .= "\n\t\t});";
$str .= "\n\t</script>\n\n";
}
elseif(!empty($this->ajax) && empty($this->preventJQueryLoad))
$str .= "\n\t" . '<script language="javascript" src="' . $this->jqueryPath . '/jquery-1.3.2.min.js"></script>';
if(!empty($this->latlngArr) && !empty($this->googleMapsAPIKey))
{
if(empty($this->preventGoogleMapsLoad))
$str .= "\n\t" . '<script src="http://maps.google.com/maps?file=api&v=2&key=' . $this->googleMapsAPIKey . '" type="text/javascript"></script>';
$str .= "\n\t" . '<script language="javascript" defer="true">';
$str .= "\n\t\tfunction initializeLatLng_" . $this->attributes["name"] . "() {";
$str .= "\n\t\t\tif (GBrowserIsCompatible()) {";
$latlngSize = sizeof($this->latlngArr);
for($l = 0; $l < $latlngSize; ++$l)
{
$latlng = $this->latlngArr[$l];
$latlngID = str_replace('"', '"', $latlng->attributes["id"]);
if(!empty($latlng->attributes["value"]))
{
$latlngCenter = $latlng->attributes["value"];
if(empty($latlng->latlngZoom))
$latlngZoom = 9;
else
$latlngZoom = $latlng->latlngZoom;
}
else
{
$latlngCenter = array(39, -96);
if(empty($latlng->latlngZoom))
$latlngZoom = 3;
else
$latlngZoom = $latlng->latlngZoom;
}
$str .= "\n\t\t\t\t" . 'var map_' . $latlngID . ' = new GMap2(document.getElementById("' . $latlngID . '_canvas"));';
$str .= "\n\t\t\t\t" . 'map_' . $latlngID . '.addControl(new GSmallMapControl());';
$str .= "\n\t\t\t\t" . 'var center_' . $latlngID . ' = new GLatLng(' . $latlngCenter[0] . ', ' . $latlngCenter[1] . ');';
$str .= "\n\t\t\t\t" . 'map_' . $latlngID . '.setCenter(center_' . $latlngID . ', ' . $latlngZoom . ');';
$str .= "\n\t\t\t\t" . 'var marker_' . $latlngID . ' = new GMarker(center_' . $latlngID . ', {draggable: true});';
$str .= "\n\t\t\t\t" . 'map_' . $latlngID . '.addOverlay(marker_' . $latlngID . ');';
$str .= "\n\t\t\t\t" . 'GEvent.addListener(marker_' . $latlngID . ', "dragend", function() {';
$str .= "\n\t\t\t\t\tvar latlng = marker_" . $latlngID . ".getLatLng();";
$str .= "\n\t\t\t\t\tvar lat = latlng.lat();";
$str .= "\n\t\t\t\t\tvar lng = latlng.lng();";
$str .= "\n\t\t\t\t\t" . 'document.forms["' . $this->attributes["name"] . '"].elements["' . str_replace('"', '"', $latlng->attributes["name"]) . '"].value = "Latitude: " + lat.toFixed(3) + ", Longitude: " + lng.toFixed(3);';
$str .= "\n\t\t\t\t});";
}
$str .= "\n\t\t\t}";
$str .= "\n\t\t}";
$str .= "\n\t\t" . 'if(window.addEventListener) { window.addEventListener("load", initializeLatLng_' . $this->attributes["name"] . ', false); }';
$str .= "\n\t\t" . 'else if(window.attachEvent) { window.attachEvent("onload", initializeLatLng_' . $this->attributes["name"] . '); }';
$str .= "\n\t</script>\n\n";
}
if(!empty($this->jqueryCheckSort))
{
$str .= "\n\t" . '<script language="javascript" defer="true">';
$str .= "\n\t\tfunction addOrRemoveCheckSortItem_" . $this->attributes["name"] . "(cs_fieldObj, cs_id, cs_name, cs_index, cs_value, cs_text) {";
$str .= "\n\t\t\tif(cs_fieldObj.checked != true)";
$str .= "\n\t\t\t\t" . 'document.getElementById(cs_id).removeChild(document.getElementById(cs_id + cs_index));';
$str .= "\n\t\t\telse {";
$str .= "\n\t\t\t\tvar li = document.createElement('li');";
$str .= "\n\t\t\t\tli.id = cs_id + cs_index;";
$str .= "\n\t\t\t\tli.className = 'ui-state-default';";
$str .= "\n\t\t\t\tli.style.cssText = 'margin: 0 3px 3px 3px; padding: 0.4em; padding-left: 1.5em; font-size: 15px !important;'";
$str .= "\n\t\t\t\tli.innerHTML = '<input type=\"hidden\" name=\"' + cs_name + '\" value=\"' + cs_value + '\"><span class=\"ui-icon ui-icon-arrowthick-2-n-s\" style=\"position: absolute; margin-left: -1.3em;\"></span>' + cs_text;";
$str .= "\n\t\t\t\tdocument.getElementById(cs_id).appendChild(li);";
$str .= "\n\t\t\t}";
$str .= "\n\t\t}";
$str .= "\n\t</script>\n\n";
}
if(!empty($this->includeTinyMce))
{
$str .= "\n\t" . '<script language="javascript" src="' . $this->tinymcePath . '/tiny_mce.js"></script>';
$str .= "\n\t" . '<script language="javascript">';
$str .= "\n\t\ttinyMCE.init({";
$str .= "\n\t\t\t" . 'mode: "textareas",';
$str .= "\n\t\t\t" . 'theme: "advanced",';
$str .= "\n\t\t\t" . 'plugins: "safari,table,paste",';
$str .= "\n\t\t\t" . 'theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,outdent,indent,|,forecolor,backcolor",';
$str .= "\n\t\t\t" . 'theme_advanced_buttons2: "formatselect,fontselect,fontsizeselect,|,pastetext,pasteword,|,link,image",';
$str .= "\n\t\t\t" . 'theme_advanced_buttons3: "tablecontrols,|,code,cleanup,|,undo,redo",';
$str .= "\n\t\t\t" . 'theme_advanced_toolbar_location: "top",';
$str .= "\n\t\t\t" . 'editor_selector: "tiny_mce"';
$str .= "\n\t\t});";
$str .= "\n\t\ttinyMCE.init({";
$str .= "\n\t\t\t" . 'mode: "textareas",';
$str .= "\n\t\t\t" . 'theme: "simple",';
$str .= "\n\t\t\t" . 'editor_selector: "tiny_mce_simple"';
$str .= "\n\t\t});";
$str .= "\n\t</script>\n\n";
}
return $str;
}
/*This function handles php form checking to be used after submission. Serialization needs to be utilized before calling this function to revive the forms past state. If returnUrl is set, this function will redirect and exit.*/
public function checkForm()
{
if((empty($this->ajax) && strtolower($this->attributes["method"]) == "post") || (!empty($this->ajax) && strtolower($this->ajaxType) == "post"))
$ref = $_POST;
else
$ref = $_GET;
$error_msg = "";
$elementSize = sizeof($this->elements);
for($i = 0; $i < $elementSize; ++$i)
{
$ele = $this->elements[$i];
if(!empty($ele->required))
{
/*Radio buttons and the sort element types are ignored.*/
if($ele->attributes["type"] == "radio" || $ele->attributes["type"] == "sort")
continue;
elseif($ele->attributes["type"] == "date" && (empty($ref[$ele->attributes["name"]]) || $ref[$ele->attributes["name"]] == "Click to Select Date..."))
{
$error_msg = $ele->label . " is a required field.";
break;
}
elseif($ele->attributes["type"] == "daterange" && (empty($ref[$ele->attributes["name"]]) || $ref[$ele->attributes["name"]] == "Click to Select Date Range..."))
{
$error_msg = $ele->label . " is a required field.";
break;
}
elseif($ele->attributes["type"] == "latlng" && (empty($ref[$ele->attributes["name"]]) || $ref[$ele->attributes["name"]] == "Drag Map Marker to Select Location..."))
{
$error_msg = $ele->label . " is a required field.";
break;
}
elseif(($ele->attributes["type"] == "checkbox" || $ele->attributes["type"] == "checksort") && !isset($ref[$ele->attributes["name"]]))
{
$error_msg = $ele->label . " is a required field.";
break;
}
elseif($ref[$ele->attributes["name"]] == "")
{
$error_msg = $ele->label . " is a required field.";
break;
}
}
}
if(!empty($error_msg))
{
if(!empty($this->ajax))
{
echo($error_msg);
exit();
}
else
{
if(strpos($this->returnUrl, "?") === false)
$error_msg = "?error_message=" . rawurlencode($error_msg);
else
$error_msg = "&error_message=" . rawurlencode($error_msg);
if(!empty($this->returnUrl))
{
header("Location: " . $this->returnUrl . $error_msg);
exit();
}
else
return $error_msg;
}
}
else
return;
}
/*This function set the referenceValues variables which can be used to pre-fill form fields. This function needs to be called before the render function.*/
public function setReferenceValues($ref)
{
$this->referenceValues = $ref;
}
}
class element extends HelperBase {
/*Public variables to be read/written in both the base and form classes.*/
public $attributes;
public $label;
public $options;
public $required;
public $disabled;
public $multiple;
public $readonly;
public $nobreak;
public $preHTML;
public $postHTML;
public $tooltip;
/*webeditor specific fields*/
public $webeditorSimple;
/*latlng specific fields*/
public $latlngHeight;
public $latlngWidth;
public $latlngZoom;
/*slider specific fields*/
public $sliderMin;
public $sliderMax;
public $sliderSnapIncrement;
public $sliderOrientation;
public $sliderPrefix;
public $sliderSuffix;
public $sliderHeight;
public $sliderHideDisplay;
public function __construct() {
/*Set default values where appropriate.*/
$this->attributes = array(
"type" => "text"
);
}
}
class option extends HelperBase {
/*Public variables to be read/written in both the base and form classes.*/
public $value;
public $text;
}
class button extends HelperBase {
/*Public variables to be read/written in both the base and form classes.*/
public $attributes;
public $phpFunction;
public $phpParams;
public $wrapLink;
public $linkAttributes;
/*Set default values where appropriate.*/
public function __construct() {
$this->linkAttributes = array(
"style" => "text-decoration: none;"
);
}
}
?>
<file_sep>[globals]
;Stack trace verbosity. Assign values 1 to 3 for increasing verbosity levels. Zero (0) suppresses the stack trace. This is the default value and it should be the assigned setting on a production server.
DEBUG = 3
;Path to the views
UI = ../app/views/
;Use Database
DATABASE = false
;Location of custom logs.
LOGS = log/
;Temporary folder for cache, filesystem locks, compiled F3 templates, etc. Default is the tmp/ folder inside the Web root. Adjust accordingly to conform to your site's security policies.
TEMP = ../../tmp/
;Directory where file uploads are saved.
UPLOADS = ../../tmp/uploads/
;Location of the language dictionaries.
LOCALES = ../../language/
;Current active language. Value is used to load the appropriate language translation file in the folder pointed to by LOCALES. If set to NULL, language is auto-detected from the HTTP Accept-Language request header.
LANGUAGE =
; timezone settings
; http://de2.php.net/manual/en/timezones.php
TZ = Africa/Lagos
; application settings
LOGFILE = app.log
; set to development | testing | staging | production | maintenance or whatever you like
application.ENVIRONMENT = production
<file_sep><?php
// Base Model
class ModelBase {
protected $db;
protected $f3;
//Model Constructor
function __construct()
{
$this->f3 = Base::instance();
$this->db = \Registry::get('db');
}
}
<file_sep><?
if(!isset($_SESSION))
session_start();
/*
This Animated Gif Captcha system is brought to you courtesy of ...
<EMAIL> ==> <NAME>
http://www.querythe.net/Animated-Gif-Captcha/ ==> Download Current Version
OOP (PHP 4 & 5) Interface by ...
<EMAIL> ==> <NAME>
The GIFEncoder class was written by ...
http://gifs.hu ==> <NAME>
http://www.phpclasses.org/browse/package/3163.html ==> Download Current Version
This file is part of QueryThe.Net's AnimatedCaptcha Package.
QueryThe.Net's AnimatedCaptcha is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
QueryThe.Net's AnimatedCaptcha is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with QueryThe.Net's AnimatedCaptcha; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
class AnimCaptcha
{
static $frames;
static $time;
static $num;
static $pause;
static $ops;
static $gifs;
static $rand;
static $math;
function AnimCaptcha( $gifs, $pause )
{
if( !class_exists( 'GIFEncoder' ) and !include('GIFEncoder.class.php') )
die( 'I require GIFEncoder to be loaded before operation' );
self::$pause = (int)$pause;
self::$gifs = $gifs;
self::$ops = array
(
'minus',
'plus',
'times'
);
self::$math = array
(
'-',
'+',
'*'
);
self::$num['rand1'] = rand( 1, 9 );
self::$num['rand2'] = rand( 1, 9 );
self::$num['op'] = rand( 0, count( self::$math ) - 1 );
self::BuildImage( );
}
function BuildImage( )
{
self::$frames[ ] = sprintf( '%s/solve.gif', self::$gifs );
self::$time[ ] = 260;
self::$frames[ ] = sprintf( '%s/%d.gif', self::$gifs, self::$num['rand1'] );
self::$time[ ] = self::$pause;
self::$frames[ ] = sprintf( '%s/%s.gif', self::$gifs, self::$ops[ self::$num['op'] ] );
self::$time[ ] = self::$pause;
self::$frames[ ] = sprintf( '%s/%d.gif', self::$gifs, self::$num['rand2'] );
self::$time[ ] = self::$pause;
self::$frames[ ] = "frames/equals.gif";
self::$time [ ] = 280;
}
function GetImage( )
{
eval( sprintf( '$_SESSION["captcha"][$_GET["fid"]][$_GET["eid"]] = (%d %s %d);',
self::$num['rand1'],
self::$math[ self::$num['op'] ],
self::$num['rand2']
) );
if( $_SESSION['answer'] < 0 )
self::AnimCaptcha( self::$gifs, self::$pause );
$gif = new GIFEncoder( self::$frames, self::$time, 0, 2, 0, 0, 0, "url" );
if( !headers_sent( ) )
{
header ( 'Content-type:image/gif' );
echo $gif->GetAnimation ( );
}
}
}
new AnimCaptcha( 'frames', 140 );
AnimCaptcha::GetImage( );
?>
| 49f12d163e348ec95b1bb0540b3a4e8997e81b3d | [
"PHP",
"INI"
] | 10 | PHP | akinyeleolubodun/f3-boiler-plate | d10bf28c57935ca48c3e02ce1f8fe74d093a8b07 | 8a447683042ea179827ef839c5634a156b8ac985 |
refs/heads/main | <repo_name>StevenACZ/ruby-basics-1-StevenACZ<file_sep>/05cash/cash.rb
# This exercise won't have useful comments to guide you. Go for it!
# 1 Sol, 50 centimos, 20 centimos and 10 centimos
def change_cash(cash)
sol, cent = cash.round(1).to_s.split(".")
five_cent, other_cent = cent.to_i.divmod(5)
twenty_cent, ten_cent = other_cent.divmod(2)
[sol.to_i, five_cent, twenty_cent, ten_cent].sum
end
cash = 0
loop do
print("Change owed: ")
cash = gets.to_f
cash.positive? && break
end
print("You will need at least coins #{change_cash(cash)}")
<file_sep>/02bmi_calculator/bmi_calculator.rb
# Prompt the user for they weight and store the answer in a variable
# Prompt the user for they height and store the answer in a variable
# Calculate the BMI and print the message with the result
# If the result is less than 18.5 print "You are underweight, add more potato to the broth."
print("How much do you weigh? (don't lie)\n")
weight = gets.to_f
print("How tall are you? (barefoot)\n")
height = gets.to_f
BMI = ((weight / height**2) * 100).round / 100.0
print("Right now your BMI is #{BMI}\n")
BMI < 18.5 && print("You are underweight, add more potato to the broth")
(BMI >= 18.5 && BMI < 25) && print("You have a normal weight, I have healthy envy of you")
BMI > 25 && print("You are overweight, I know, the pandemic has affected us all")
<file_sep>/03multiplier/multiplier.rb
# Start printing the welcome message
# In the next line prompt the user for a number and leave the cursor on the same line.
# Save the user input in a variable.
# If the user input is not a number greater than 0, ask again until it is.
# Print the message "The first 20 multiples of <user_number> are:"
# Use some looping technique to print each multiple followed by a comma.
# The last one should be preceded by "and"
value = "My name is Multiplier and I will give you the first 20 multiples of any number"
print("#{value}\nChoose a number greater than 0: ")
num = gets.to_i
while num <= 0
print("#{value}\nChoose a number greater than 0: ")
num = gets.to_i
end
print("The first 20 multiples of #{num} are:\n")
if num.positive?
x = 1
arr = []
while x <= 20
arr.push(num * x)
x += 1
end
print(arr.join(", ").tap { |s| s[s.rindex(", "), 2] = ", and " })
end
<file_sep>/04mario/mario.rb
# This and the next exercise won't have useful comments to guide you.
# Start by thinking in pseudocode which steps you need to do to solve the proble.
# Then, start writing beatuful ruby code! Go for it!
height = 0
loop do
print("Pyramid height: ")
height = gets.to_i
height.positive? && height < 8 && break
end
y = height - 1
x = 1
while x <= height
while y >= 0
print(" " * y)
print("#" * x)
print("\n")
x += 1
y -= 1
end
x += 1
end
<file_sep>/00hello_world/hello_world.rb
# Print "Hello World!"" to the console :)
print("Hello World!")
<file_sep>/01say_hello/say_hello.rb
# Ask the user to input his name and store it in a variable
# If the user enters some text like "Monica", print "Hello Monica! Welcome to the Ruby module."
# If the user enters nothing, print "No one to say hello to. :cry:"
name = gets.to_s.strip
if !name.empty?
print("Hello #{name}! Welcome to the Ruby module.")
else
print("No one to say hello to. :cry:")
end
| 9f3863d0041cdf9217d6676cdb192fb43873ccc1 | [
"Ruby"
] | 6 | Ruby | StevenACZ/ruby-basics-1-StevenACZ | f5cef4a31f5fd6644e1c378f8a205e4bef8cd4c3 | cb5e7e161c38ff5c32a540abd02c801c7eadf055 |
refs/heads/master | <repo_name>Bgoodee/GoJS<file_sep>/Palette/PaletteManager.js
PaletteManager = (() => {
const $ = go.GraphObject.make;
const init = () => {
const myPalette = $(go.Palette, "PaletteDiv");
var PaletteNodeDataArray = [
{key: "1", Text: "Green", Color: "Green", Shape: "RoundedRectangle"},
{key: "2", Text: "Blue", Color: "Blue", Shape: "Square"},
{key: "3", Text: "Red", Color: "Red", Shape: "Triangle"},
{key: "4", Text: "Group", "isGroup": true, Color: "Grey", Shape: "RoundedRectangle"}
];
myPalette.nodeTemplate = PaletteNodeTemplate.provideTemplates();
myPalette.model = new go.Model(PaletteNodeDataArray);
}
return{
init
}
})()
<file_sep>/init.js
(() =>{
window.onload = () => {
DiagramManager.init();
PaletteManager.init();
PropertiesManager.setColor();
PropertiesManager.setShape();
PropertiesManager.setText();
PropertiesManager.readProperties();
}
})();<file_sep>/Diagram/DiagramGroupTemplate.js
DiagramGroupTemplate = (() => {
const $ = go.GraphObject.make;
const provideTemplates = () => {
return $(go.Group, "Spot",
{
resizable: true,
computesBoundsAfterDrag: true,
mouseDrop: DiagramManager.finishDrop,
handlesDragDropForMembers: true,
},
$(go.Shape, "Square",
new go.Binding("figure", "Shape"),
new go.Binding("fill", "Color"),
),
);
}
return{
provideTemplates
}
}
)()<file_sep>/Palette/PaletteNodeTemplate.js
PaletteNodeTemplate = (() => {
const $ = go.GraphObject.make;
const provideTemplates = () => {
return $(go.Node, "Spot",
$(go.Shape, "Square",
new go.Binding("figure", "Shape"),
new go.Binding("fill", "Color"),
),
$(go.TextBlock, "text",
new go.Binding("text", "Text")
)
);
}
return{
provideTemplates
}
}
)()<file_sep>/Diagram/DiagramNodeTemplate.js
DiagramNodeTemplate = (() => {
const $ = go.GraphObject.make;
const provideTemplates = () => {
return $(go.Node, "Spot",
{
resizable: true,
},
$(go.Shape, "Square",
new go.Binding("figure", "Shape"),
new go.Binding("fill", "Color"),
),
$(go.TextBlock, "text",
{
portId: "", cursor: "pointer",
fromLinkable: true,
toLinkable: true,
} ,
new go.Binding("text", "Text")
)
);
}
return{
provideTemplates
}
}
)() | 1f877d3604c267e8a5fb8d7c2ee80f4280ae52ed | [
"JavaScript"
] | 5 | JavaScript | Bgoodee/GoJS | 7d633333524c1694137813673d339ec27c91085c | 0e14d4d9d5dbb485bfc170e09a74999eea26ff9c |
refs/heads/master | <repo_name>parara/pip<file_sep>/twitappv2/utama/pengaturan.php
<?php
include ("utama/header_.php");
?>
<div id="content">
<div id="wrap">
<h3>Pengaturan Twitter</h3>
<?php
// save
// how if it no clue
//include('inc/config.php');
if($_SERVER["REQUEST_METHOD"] == "POST") {
$HASTAG=addslashes($_POST['hastag']);
$apdate = mysql_query("UPDATE twitter SET HASTAG='$HASTAG' WHERE app='twitter'");
}
?>
<form role="form" action="" method="POST">
<?php
$atur = mysql_query("SELECT * FROM twitter");
while ($row = mysql_fetch_array($atur)) {
$hastag = $row['HASTAG'];
}
?>
<div class="form-group">
<label>Hastag Pencarian</label>
<input type="text" class="form-control" name="hastag" placeholder="<?php echo $hastag;?>">
</div>
<button type="submit" class="btn btn-default">Simpan</button>
</form>
</div>
</div>
<?php
include ("utama/footer.php");
?><file_sep>/twitappv2/login.php
<?php
include('inc/config.php');
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from form
$myusername=addslashes($_POST['username']);
$mypassword=addslashes($_POST['password']);
$sql="SELECT id FROM admin WHERE username='$myusername' and password=md5('<PASSWORD>')";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$active=$row['active'];
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1) {
$_SESSION['login_user']=$myusername;
header('location:index.php?mod=home');
exit();
## set last login
}
else {
$error="Your Login Name or Password is invalid";
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Administrator Login Form</title>
<link type="text/css" rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="stylized">
<div class="loginform">
<div class="logo"><img src="img/logo2.png" height="80" width="80"><br><br><br>
<p><b>Badan Pelayanan Perizinan Terpadu dan Penanaman Modal</b><br><font size="2">KOTA BOGOR</font></p>
</div>
<form action="" method="post">
<div class="form">
<ul>
<li><h2>Username</h2> <input name="username" id="username" type="text"></li>
<li><h2>Password</h2> <input name="password" id="password" type="password"></li>
<li><button type="submit">Log In</button></li>
</ul>
</div>
</form>
</div>
<p style="margin-bottom: 10px;margin-left: 40px;"><span style="color: red;font-style: italic;"></span></p>
<div class="footer">
<h3>Copyright | 2014 Aplikasi Pelayanan Perizinan Terpadu</h3>
</div>
</div>
</body>
</html><file_sep>/fb/fb.py
import requests # pip install requests
import json
base_url = 'https://graph.facebook.com/me'
ACCESS_TOKEN = '<KEY>'
# Get 10 likes for 10 friends
fields = 'id,name,friends.limit(10).fields(likes.limit(10))'
url = '%s?fields=%s&access_token=%s' % \
(base_url, fields, ACCESS_TOKEN,)
# This API is HTTP-based and could be requested in the browser,
# with a command line utlity like curl, or using just about
# any programming language by making a request to the URL.
# Click the hyperlink that appears in your notebook output
# when you execute this code cell to see for yourself...
print url
# Interpret the response as JSON and convert back
# to Python data structures
content = requests.get(url).json()
# Pretty-print the JSON and display it
print json.dumps(content, indent=1)<file_sep>/twitappv2/index.php
<?php
//include_once "lock.php";
include "inc/config.php";
session_start();
$user_check=$_SESSION['login_user'];
$ses_sql=mysql_query("select username from admin where username='$user_check'");
$row=mysql_fetch_array($ses_sql);
$login_session=$row['username'];
if(!isset($login_session)) {
header('location:login.php');
}
$mod = $_GET['mod'];
switch($mod){
case "home" :
$view = "utama/home.php";
break;
case "pengaduan" :
$view = "utama/pengaduan.php";
break;
case "verifikasi" :
$view = "utama/verifikasi.php";
break;
case "pengecekan" :
$view = "utama/pengecekan.php";
break;
case "pembahasan" :
$view = "utama/pembahasan.php";
break;
case "jawaban" :
$view = "utama/jawaban.php";
break;
case "editor" :
$view = "utama/editor.php";
break;
case "pengaturan" :
$view = "utama/pengaturan.php";
break;
case "pengaturan_surel" :
$view = "utama/pengaturan_surel.php";
break;
}
include $view;
if(empty($_GET['mod'])){
header("location:?mod=home");
}
?><file_sep>/README.md
# Crawling Twitter Base On Hastag
=================================
<NAME> (<EMAIL>). Lisensi kode sumber dibawah MIT
## Cara Memasang
Linux, OSX
### Base System
* Install gitcore:
`$ sudo apt-get install gitcore`
### [Frontend](https://wiki.debian.org/LaMp)
* Install mysql-server:
`$ sudo apt-get install mysql-server mysql-client`
* Install apache2 (webserver):
`$ sudo apt-get install apache2`
* Install php5:
`$ sudo apt-get install install php5 php5-mysql libapache2-mod-php5`
### Backend
* Install python 2.7:
`$ sudo apt-get install python2.7`
* Install pip from [here](https://pip.pypa.io/en/latest/installing.html):
$ wget https://bootstrap.pypa.io/get-pip.py && python get-pip.py
* Install twitter (from pip):
$ pip install twitter
* Install mysql-python:
$ apt-get install python-mysqldb
* Install tweepy (under pip)
$ pip install tweepy
### Configurasi
* git clone https://github.com/tuanpembual/pip.git
* Clone db minimal.
* Set db token [twitter apps](https://apps.twitter.com/)
* Set keyword for crawling
<file_sep>/save.py
#!/usr/bin/env python
#
# Crawling Twitter
#
# Copyright (c) 2014, <NAME> <<EMAIL>>
# All rights reserved. Released under the MIT license.
import json
import MySQLdb as mdb
import datetime
import os
import shutil
#http://zetcode.com/db/mysqlpython/ & http://stackoverflow.com/questions/18465411/python-mysqldb-insert-with-variables-as-parameters
# read from http://www.tutorialspoint.com/python/python_for_loop.htm
con = mdb.connect('localhost','twitapp','tw1t4pp','testdb', use_unicode=True,charset='utf8');
# add kondisi to nilai
kondisi ='0'
editor ='admin'
# read json file
statuses = json.loads(open('mining.json').read())
# extract from statuses | done
# discard retuit, how? | done
# add better algoritme?
for index in range(len(statuses)):
text = statuses[index]['text']
if (text[0:2] != 'RT'):
# if date duplicate
screen_name = '@'+statuses[index]['user']['screen_name']
coordinates = statuses[index]['coordinates']
created_at = statuses[index]['created_at']
id_twit = statuses[index]['id']
#input to sql
with con:
cur = con.cursor(mdb.cursors.DictCursor)
cur.execute("""INSERT INTO lapor(id_twit, tanggal, name, isi, id_progres, editor) VALUES (%s,%s,%s,%s,%s,%s) """, (id_twit, created_at,screen_name,text,kondisi,editor))
print "sukses"
#end
# rename file and store in deference folder
dt = str(datetime.date.today())
newname = 'file_'+dt+'.json'
os.rename('mining.json', newname)
shutil.move(newname, 'db_json/'+newname)<file_sep>/insert.py
#!/usr/bin/env python
#
# Crawling Twitter
#
# Copyright (c) 2014, <NAME> <<EMAIL>>
# All rights reserved. Released under the MIT license.
# import module
import json
import MySQLdb as mdb
kondisi = 'Belum terverifikasi'
# masukkan data file ke variabel
open_file = open('mining.json','r').read()
# load data ke array
data = json.loads(open_file)
# iterasi data array
for tweet in data:
# buka koneksi ke database
db = mdb.connect('localhost','twitapp','tw1t4pp','testdb', use_unicode=True,charset='utf8')
cursor = db.cursor(mdb.cursors.DictCursor)
# inisialisasi
text = tweet['text']
tweet_id = tweet['id']
screen_name = tweet['user']['screen_name']
created_at = tweet['created_at']
# query untuk cek ke database apakah twit tersebut ada atau tidak
sql_select = '''SELECT
id_twit
FROM
Lapor
WHERE id_twit=%s'''
cursor.execute(sql_select, (tweet_id,))
check_tweet = cursor.fetchone()
# kalau tidak ada, insert data ke database
if not check_tweet:
insert_data = '''INSERT INTO
Lapor (id_twit,
Tanggal,
Name,
Isi,
Verifikasi)
VALUES (%s, %s, %s, %s, %s)'''
cursor.execute(insert_data, (tweet_id,
created_at,
screen_name,
text,
kondisi,))
# commit data ke database
db.commit()
print 'insert sukses'
else:
print 'sudah ada datanya, tidak dimasukkan'
# tutup koneksi database
db.close()<file_sep>/fb/fb2.py
import facebook # pip install facebook-sdk
import json
ACCESS_TOKEN = '<KEY>'
# A helper function to pretty-print Python objects as JSON
def pp(o):
print json.dumps(o, indent=1)
# Create a connection to the Graph API with your access token
g = facebook.GraphAPI(ACCESS_TOKEN)
# Execute a few sample queries
print '---------------'
print 'Me'
print '---------------'
pp(g.get_object('me'))
print
print '---------------'
print 'My Friends'
print '---------------'
pp(g.get_connections('me', 'friends'))
print
print '---------------'
print 'Social Web'
print '---------------'
pp(g.request("search", {'q' : 'social web', 'type' : 'page'}))<file_sep>/twitappv2/db.sql
create user 'twitapp'@'localhost' identified by 'tw1t4pp';
create database testdb;
use testdb;
grant all on *.* to 'twitapp'@'localhost';
CREATE TABLE IF NOT EXISTS `admin` (
`id` int(11) NOT NULL,
`name` varchar(30) DEFAULT NULL,
`username` varchar(30) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
`email` varchar(30) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
INSERT INTO `admin` (`id`, `name`, `username`, `password`, `email`) VALUES
(1, 'admin', 'admin', '<PASSWORD>', '<EMAIL>');
DROP TABLE IF EXISTS `progres`;
CREATE TABLE IF NOT EXISTS `progres` (
`id` char(1) NOT NULL,
`name` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `progres` (`id`, `name`) VALUES
('0', 'Belum Verifikasi'),
('1', 'Verifikasi'),
('2', 'Pengecekan Lapangan'),
('3', 'Pembahasan'),
('4', 'Jawaban');
DROP TABLE IF EXISTS `lapor`;
CREATE TABLE IF NOT EXISTS `lapor` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_twit` BIGINT NOT NULL,
`tanggal` VARCHAR(50) NOT NULL,
`name` VARCHAR(25) NOT NULL,
`isi` VARCHAR (160) NOT NULL,
`id_progres` char(1) NOT NULL,
`lastvisit` date DEFAULT NULL,
`komentar` VARCHAR(300) DEFAULT NULL,
`editor` VARCHAR(300) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=501 ;
INSERT INTO `lapor` (`id`,`id_twit`,`tanggal`,`name`,`isi`,`id_progres`,`lastvisit`) VALUES
(1,529465502553227264,'Tue Nov 04 02:49:47 +0000 2014','@yayaxzz','#JogjaAsat ','1','2012-04-17'),
(2,529465353454112768,'Tue Nov 04 02:49:11 +0000 2014','@yayaxzz','My house . . \"killthedj\'s \"Perjuangan Warga Miliran #JogjaAsat by dodoputrabangsa #JogjaOraDidol\" enters lunch talk. http://t.co/b1r5fdXpJS\"','0','2012-04-17'),
(3,529464169620570113,'Tue Nov 04 02:44:29 +0000 2014','@gabrielalaras','RT @chirpstory: .@killthedj\'s \"Perjuangan Warga Miliran #JogjaAsat by @dodoputrabangsa #JogjaOraDidol\" enters lunch talk. http://t.co/wq8Dn…','0','2012-04-17'),
(4,529462433182523393,'Tue Nov 04 02:37:35 +0000 2014','@st_kurniawan','RT @chirpstory: .@killthedj\'s \"Perjuangan Warga Miliran #JogjaAsat by @dodoputrabangsa #JogjaOraDidol\" enters lunch talk. http://t.co/wq8Dn…','0','2012-04-17'),
(5,529462351913709568,'Tue Nov 04 02:37:16 +0000 2014','@Rio_Ramabaskara','RT @chirpstory: .@killthedj\'s \"Perjuangan Warga Miliran #JogjaAsat by @dodoputrabangsa #JogjaOraDidol\" enters lunch talk. http://t.co/wq8Dn…','0','2012-04-17'),
(6,529461612143341568,'Tue Nov 04 02:34:19 +0000 2014','@killthedj','RT @chirpstory: .@killthedj\'s \"Perjuangan Warga Miliran #JogjaAsat by @dodoputrabangsa #JogjaOraDidol\" enters lunch talk. http://t.co/wq8Dn…','1','2012-04-17'),
(7,529456876480499712,'Tue Nov 04 02:15:30 +0000 2014','@dodoputrabangsa','RT @chirpstory: .@killthedj\'s \"Perjuangan Warga Miliran #JogjaAsat by @dodoputrabangsa #JogjaOraDidol\" enters lunch talk. http://t.co/wq8Dn…','0','2012-04-17'),
(8,529376866042249216,'Mon Nov 03 20:57:34 +0000 2014','@penumpang_gelap','Pak Wali kok ga ada? \"@killthedj\'s \"Perjuangan Warga Miliran #JogjaAsat by @dodoputrabangsa #JogjaOraDidol\" http://t.co/GCLddesCS0 \"','0','2012-04-17'),
(9,529365253227036672,'Mon Nov 03 20:11:26 +0000 2014','@sangkunet','RT @chirpstory: .@killthedj\'s \"Perjuangan Warga Miliran #JogjaAsat by @dodoputrabangsa #JogjaOraDidol\" enters lunch talk. http://t.co/wq8Dn…','0','2012-04-17'),
(10,529364395793473536,'Mon Nov 03 20:08:01 +0000 2014','@chirpstory','.@killthedj\'s \"Perjuangan Warga Miliran #JogjaAsat by @dodoputrabangsa #JogjaOraDidol\" enters lunch talk. http://t.co/wq8DnmUE8U','0','2012-04-17');
DROP TABLE IF EXISTS `mailserver`;
CREATE TABLE `mailserver` (
`username` varchar(30) DEFAULT NULL,
`password` varchar(30) DEFAULT NULL,
`server` varchar(30) DEFAULT NULL,
`port` varchar(10) DEFAULT NULL,
`app` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `mailserver` (`username`, `password`, `server`, `port`, `app`) VALUES
('<EMAIL>', 'cobainaja', 'smtp.gmail.com', '587', `twitter`);
DROP TABLE IF EXISTS `twitter`;
CREATE TABLE `twitter` (
`CONSUMER_KEY` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`CONSUMER_SECRET` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`OAUTH_TOKEN` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`OAUTH_TOKEN_SECRET` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`HASTAG` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`app` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `twitter` VALUES ('<KEY>','<KEY>','<KEY>','<KEY>','#JogjaAsat','twitter');
<file_sep>/next.mdown
### Crawling Twitter Base On Hastag
=========
ole<NAME> (<EMAIL>)
Peer,
session expired
ganti user password
tambah user, set editor by login (session)
DB contoh, sample json
Query pencarian
Ganti gambar, isi dengan desain keluhan
aliran kerja
halaman awal,
klik menu, redireklink login
## Cara Memasang
=========
OS Debian, OSX, Fedora
* Backend
Install python 2.7
Install pip
Install twitter (under pip)
Install mysql-python (under pip)
Install tweepy (under pip)
* Frontend
Install PHP5
Install mysql-server
Install apache2 (webserver)
* Lampp
git clone and save to htdoc directory
clone db minimal.
set db token twitter apps (create app | links)
set db mailserver
set input query for crawling
---------
merapikan dokumen pemasangan
hastag pak bima,
Selasa, 23 desember server aktip 9-12 siang,
ngetwit bpptpm pengaduan, bimaaryas perizinan.
<file_sep>/twitappv2/inc/config.php
<?php
$mysql_hostname = "localhost";
$mysql_user = "twitapp";
$mysql_password = "<PASSWORD>";
$mysql_database = "testdb";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
?><file_sep>/twitappv2/process.php
<?php
include("inc/config.php");
$user_check="admin";
// add jam edit;
if(empty($_GET['id'])) //or empty($_GET['data']))
{
return false;
}
$id = $_GET['id'];
$data = $_GET['data'];
//how id
if (strlen($data) == 1) {
$kolom = "id_progres";
} else {
$kolom = "komentar";
}
$sql = "UPDATE lapor SET $kolom='$data', editor='$user_check' WHERE id = $id";
//print_r($sql);exit;
if(mysql_query($sql))
echo 'success';
?><file_sep>/twitappv2/utama/home.php
<?php
include ("utama/header_.php");
?>
<div id="content">
<div id="wrap">
<img src="img/tw_01.jpg">
</div>
</div>
<?php
include ("utama/footer.php");
?> <file_sep>/sendmail.py
#!/usr/bin/env python
#
# Crawling Twitter
#
# Copyright (c) 2014, <NAME> <<EMAIL>>
# All rights reserved. Released under the MIT license.
## Send mail from python, retrive from http://stackoverflow.com/questions/882712/sending-html-email-using-python
## and from gmail from http://stackoverflow.com/questions/10147455/trying-to-send-email-gmail-as-mail-provider-using-python
import smtplib
import MySQLdb as mdb
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
con = mdb.connect('localhost','twitapp','tw1t4pp','testdb');
with con:
cur = con.cursor()
cur.execute("SELECT * FROM mailserver")
for i in range(cur.rowcount):
row = cur.fetchone()
a = row[0]
b = row[1]
c = row[2]
d = row[3]
with con:
cur = con.cursor()
cur.execute("SELECT * FROM langganan where status='true'")
for i in range(cur.rowcount):
list = cur.fetchone()
target = list[2]
# username == my email address | it retrive from machine or gmail setup
# you == recipient's email address | its get from database
username = a
password = b
you = target #its target from langganan
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Crawling Testing"
msg['From'] = username
msg['To'] = you
# Create the body of the message (a plain-text and an HTML version).
## How inset variable from query to html text
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the <a href="http://www.python.org">link</a> you wanted.
</p>
</body>
</html>
"""
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
# so prefered send html message.
msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
#server = c
#port = d
s = smtplib.SMTP(c+":"+d)
s.starttls()
s.login(username,password)
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(username, you, msg.as_string())
s.quit()<file_sep>/run.sh
#!/bin/bash
#
# Crawling Twitter
#
# Copyright (c) 2014, <NAME> <<EMAIL>>
# All rights reserved. Released under the MIT license.
# crontab -e
# 30 23 * * * cd /home/user/pip/ && ./run.sh 2>&1 >> ../twitlog.log
python mining.py > mining.json #use move old twit
python save.py<file_sep>/mining.py
#!/usr/bin/env python
#
# Crawling Twitter
#
# Copyright (c) 2014, <NAME> <<EMAIL>>
# All rights reserved. Released under the MIT license.
import twitter
import datetime
import json
import MySQLdb as mdb
con = mdb.connect('localhost','twitapp','tw1t4pp','testdb', use_unicode=True,charset='utf8');
with con:
cur = con.cursor(mdb.cursors.DictCursor)
cur.execute("SELECT * FROM twitter")
rows = cur.fetchall()
for row in rows:
pass
CONSUMER_KEY = row["CONSUMER_KEY"]
CONSUMER_SECRET = row["CONSUMER_SECRET"]
OAUTH_TOKEN = row["OAUTH_TOKEN"]
OAUTH_TOKEN_SECRET = row["OAUTH_TOKEN_SECRET"]
q = row["HASTAG"]
auth = twitter.oauth.OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET,
CONSUMER_KEY, CONSUMER_SECRET)
twitter_api = twitter.Twitter(auth=auth)
# since:2010-12-27
# q = "@tuanpembual since:2014-11-4 until:2014-11-5"
# q="RaboSoto"
# jumlah query
count = 200
hariini = str(datetime.date.today())
besok = str(datetime.date.today()+datetime.timedelta(days=1))
query =q+" since:"+hariini+" until:"+besok
# See https://dev.twitter.com/docs/api/1.1/get/search/tweets
search_results = twitter_api.search.tweets(q=query, count=count)
statuses = search_results['statuses']
# Iterate through count more batches of results by following the cursor
for _ in range(count):
#print "Length of statuses", len(statuses)
try:
next_results = search_results['search_metadata']['next_results']
except KeyError, e: # No more results when next_results doesn't exist
break
# Create a dictionary from next_results, which has the following form:
# ?max_id=313519052523986943&q=NCAA&include_entities=1
kwargs = dict([ kv.split('=') for kv in next_results[1:].split("&") ])
search_results = twitter_api.search.tweets(**kwargs)
statuses += search_results['statuses']
# Show sample search result by slicing the list base on count...
print json.dumps(statuses[0:count], indent=1)
# run
# python mining.py > mining.json<file_sep>/twitappv2/utama/pengecekan.php
<?php
include("inc/config.php");
include('utama/header_.php');
?>
<div id="content">
<div id="wrap">
<h2>Laporan Dalam Pengecekan Lapangan/Dokumen</h2>
<pre>
Nilai Proses:
0: Belum Verifikasi
1: Verifikasi
2: Pengecekan Lapangan/Berkas
3: Pembahasan
4: Telah Dijawab</pre>
<table class="testgrid">
<thead>
<tr>
<th colspan="1" rowspan="1" style="text-align: center;width: 90px;" tabindex="0">Name</th>
<th colspan="1" rowspan="1" style="text-align: center;width: 90px;" tabindex="0">Tanggal</th>
<th colspan="1" rowspan="1" style="text-align: center;width: 288px;" tabindex="0">Status</th>
<th colspan="1" rowspan="1" style="text-align: center;width: 288px;" tabindex="0">Jawaban</th>
<th colspan="1" rowspan="1" style="text-align: center;width: 20px;" tabindex="0">Progress</th>
<th colspan="1" rowspan="1" style="text-align: center;width: 90px;" tabindex="0">Petugas</th>
</tr>
</thead>
<tbody>
<?php
$query = mysql_query("select * from lapor WHERE id_progres='2'");
$i=0;
while($fetch = mysql_fetch_array($query)){
if($i%2==0)
$class = 'even';
else
$class = 'odd';
echo'<tr class="'.$class.'">
<td>'.$fetch['name'].'</td>
<td>'.$fetch['tanggal'].'</td>
<td>'.$fetch['isi'].'</td>
<td><span class= "xedit" id="'.$fetch['id'].'">'.$fetch['komentar'].'</span></td>
<td><span class= "xedit" id="'.$fetch['id'].'">'.$fetch['id_progres'].'</span></td>
<td>'.$fetch['editor'].'</td>
</tr>';
}
?>
</tbody>
</table>
</div>
</div>
<script src="js/jquery-1.11.1.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script src="assets/js/bootstrap-editable.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.xedit').editable();
$(document).on('click','.editable-submit',function(){
var x = $(this).closest('td').children('span').attr('id');
var y = $('.input-sm').val();
var z = $(this).closest('td').children('span');
$.ajax({
url: "process.php?id="+x+"&data="+y,
type: 'GET',
success: function(s){
if(s == 'status'){
$(z).html(y);}
if(s == 'error') {
alert('Error Processing your Request!');}
},
error: function(e){
alert('Error Processing your Request!!');
}
});
});
});
</script>
</div>
</body>
<div id="footer">
<span style="font-family: 'Arial'; color: #FFF">Copyright ©2014 v 1.0.0</span>
</div>
</html><file_sep>/sendtwit.py
#!/usr/bin/env python2.7
#
# Crawling Twitter
#
# Copyright (c) 2014, <NAME> <<EMAIL>>
# All rights reserved. Released under the MIT license.
# Source tweet.py by <NAME> retrive from http://raspi.tv/?p=5908
import tweepy
import sys
# Consumer keys and access tokens, used for OAuth
# i am use static info, just for this moment
consumer_key = 'mcRY7JvBk33YnTTQ5HI8wktCc'
consumer_secret = '<KEY>'
access_token = '<KEY>'
access_token_secret = '<KEY>'
# OAuth process, using the keys and tokens
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
# Creation of the actual interface, using authentication
api = tweepy.API(auth)
if len(sys.argv) >= 2:
tweet_text = sys.argv[1]
else:
tweet_text = "Ki mesti cah kae seng ngajari.."
if len(tweet_text) <= 140:
api.update_status(tweet_text)
else:
print "tweet not sent. Too long. 140 chars Max."
<file_sep>/twitappv2/utama/pengaturan_surel.php
<?php
include ("utama/header_.php");
?>
<div id="content">
<div id="wrap">
<h3>Pengaturan Surel</h3>
<?php
// save
// how if it no clue
//include('inc/config.php');
if($_SERVER["REQUEST_METHOD"] == "POST") {
$mailusername=addslashes($_POST['mailusername']);
$mailpassword=addslashes($_POST['mailpassword']);
$servermail=addslashes($_POST['servermail']);
$port=addslashes($_POST['port']);
$apdate_mail = mysql_query("UPDATE mailserver SET username='$mailusername', password='<PASSWORD>', server='$servermail', port='$port' WHERE app='twitter'");
}
?>
<form role="form" action="" method="POST">
<?php
$mail = mysql_query("SELECT * FROM mailserver");
while ($row = mysql_fetch_array($mail)) {
?>
<div class="form-group">
<label>Username Email</label>
<input type="text" class="form-control" name="mailusername"
placeholder=<?php echo $row['username'];?>>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="mailpassword"
placeholder="●●●●●●●●">
</div>
<div class="form-group">
<label>Alamat Server Email</label>
<input type="text" class="form-control" name="servermail"
placeholder=<?php echo $row['server'];?>>
</div>
<div class="form-group">
<label>Port SMTP</label>
<input type="text" class="form-control" name="port"
placeholder=<?php echo $row['port']; } ?>>
</div>
<button type="submit" class="btn btn-default">Simpan</button>
</form>
</div>
</div>
<?php
include ("utama/footer.php");
?> | fba7a94f5cc6727ce4713036f942f3f69ea3bf38 | [
"SQL",
"Markdown",
"Python",
"PHP",
"Shell"
] | 19 | PHP | parara/pip | cd75403fb1a22fc813b242a33beff816b0b059a2 | 79aa159b6016fe3c6ecb1b20456f7ef427d4fc03 |
refs/heads/master | <repo_name>dongbin1999/Bin-Packing<file_sep>/src/NextFit.java
import java.util.ArrayList;
public class NextFit implements Fit {
@Override
public void Fit(ArrayList<Bin> arr, Item item) {
boolean create = false; //새로운 bin을 생성해야 하는가?
Bin bin;
if(arr.isEmpty()) { //원래 bin이 없었다면,
create = true; //생성해야한다.
bin = new Bin();
}
else bin = arr.get(arr.size() - 1); //직전에 확인한 bin을 본다.
if(!bin.check(item)) { //그 bin에 넣을 수 없다면,
create = true; //생성해야한다.
bin = new Bin();
}
bin.add(item);
if(create) arr.add(bin); //새로운 bin을 생성했다면, arr에 추가.
}
}
<file_sep>/README.md
# Bin-Packing
### 201901694 이동빈
## #1. First Fit (최초 적합)
### 방법
첫 번째 bin부터 차례로 살펴보며, 가장 먼저 발견된 여유가 있는 bin에 item을 넣는다.
```java
import java.util.ArrayList;
public class FirstFit implements Fit {
@Override
public void Fit(ArrayList<Bin> arr, Item item) {
for (int i = 0; i < arr.size(); i++) {
Bin bin = arr.get(i);
if(bin.check(item)) {
bin.add(item);
return;
}
}
//for문에서 return이 일어나지 않았다면, 기존의 bin에 item을 넣을 수 없음.
Bin bin = new Bin();
if(bin.check(item)) bin.add(item);
arr.add(bin);
}
}
```
### 결과

---
## #2. Next Fit (다음 적합)
### 방법
직전에 작업한 bin에 여유가 있으면 item을 넣는다.
```java
import java.util.ArrayList;
public class NextFit implements Fit {
@Override
public void Fit(ArrayList<Bin> arr, Item item) {
boolean create = false; //새로운 bin을 생성해야 하는가?
Bin bin;
if(arr.isEmpty()) { //원래 bin이 없었다면,
create = true; //생성해야한다.
bin = new Bin();
}
else bin = arr.get(arr.size() - 1); //직전에 확인한 bin을 본다.
if(!bin.check(item)) { //그 bin에 넣을 수 없다면,
create = true; //생성해야한다.
bin = new Bin();
}
bin.add(item);
if(create) arr.add(bin); //새로운 bin을 생성했다면, arr에 추가.
}
}
```
### 결과

---
## #3. Best Fit (최선 적합)
### 방법
기존 bin중 남는 부분이 가장 작은 bin에 item을 넣는다.
```java
import java.util.ArrayList;
public class BestFit implements Fit {
@Override
public void Fit(ArrayList<Bin> arr, Item item) {
boolean flag = false; //기존의 bin에 담을 수 있는가?
Bin bin = new Bin();
for (int i = 0; i < arr.size(); i++) {
Bin temp = arr.get(i);
if (temp.check(item)) {
flag = true; //담을 수 있다.
//기존 bin중 remainCapacity가 가장 작은 bin에 item을 넣는다.
if(bin.remainCapacity > temp.remainCapacity) bin = temp;
}
}
bin.add(item);
if(!flag) arr.add(bin); //그렇지 않으면 새로 bin 추가.
}
}
```
### 결과

---
## #4. Worst Fit (최악 적합)
### 방법
기존의 bin 중 남는 부분이 가장 큰 bin 에 item을 넣는다.
```java
import java.util.ArrayList;
public class WorstFit implements Fit {
@Override
public void Fit(ArrayList<Bin> arr, Item item) {
boolean flag = false; //기존의 bin에 담을 수 있는가?
Bin bin = new Bin();
for (int i = 0; i < arr.size(); i++) {
Bin temp = arr.get(i);
if (temp.check(item)) {
if(!flag) bin = temp;
flag = true; //담을 수 있다.
//기존 bin중 remainCapacity가 가장 큰 bin에 item을 넣는다.
if(bin.remainCapacity < temp.remainCapacity) bin = temp;
}
}
bin.add(item);
if(!flag) arr.add(bin); //그렇지 않으면 새로 bin 추가.
}
}
```
### 결과
 | ed401906d5d4800f9355f1a2569cb7713231eebb | [
"Markdown",
"Java"
] | 2 | Java | dongbin1999/Bin-Packing | af3f1d6b9da347af247a17ecf7df9e9e8096a512 | bb66a231dd2e1f4ef47a405d10e7598dd0413704 |
refs/heads/master | <repo_name>madsendennis/hackzurich2017<file_sep>/test/normalize.py
from os import listdir
from os.path import isfile, join
import cv2
###################
# Normalization is done by discarding too small or too big images
# and by resizing (streaching) the images to 100x100
###################
# limits for image size
max_height = 100
min_height = 50
max_width = 100
min_width = 50
# List all the grains from the 'okay' folder
path = 'okay/'
data_set_path_safe = "data_set/safe/"
images_safe = [f for f in listdir(path) if isfile(join(path, f))]
# Filter the images based on the size
# - if one of the dimensions is > 100 px - discard
# - if the image has both dimensions < 50 px - discarded
counter = 0
for image_path in images_safe:
img = cv2.imread(path + image_path, cv2.IMREAD_GRAYSCALE)
height, width= img.shape
if (width > max_width or height > max_height):
continue
if (width < min_width and height < min_height):
continue
# Save the resized image to the new folder
counter += 1
cv2.imwrite(data_set_path_safe + image_path, cv2.resize(img, (100, 100)))
print("Out of " + str(len(images_safe)) + " images " + str(counter) + " passed the filter in the 'okay' folder.")
# List all the grains from the 'okay' folder
path = 'contaminated/'
data_set_path_safe = "data_set/not_safe/"
images_not_safe = [f for f in listdir(path) if isfile(join(path, f))]
# Filter the images based on the size
# - if one of the dimensions is > 100 px - discard
# - if the image has both dimentions < 50 px - discarded
counter = 0
for image_path in images_not_safe:
img = cv2.imread(path + image_path, cv2.IMREAD_GRAYSCALE)
height, width= img.shape
if (width > max_width or height > max_height):
continue
if (width < min_width and height < min_height):
continue
# Save the resized image to the new folder
cv2.imwrite(data_set_path_safe + image_path, cv2.resize(img, (100, 100)))
counter += 1
print("Out of " + str(len(images_not_safe)) + " images " + str(counter) + " passed the filter in the 'contaminated' folder.")
<file_sep>/camera/captureImage.py
import picamera
import base64
import time
from flask import Flask, Response
from flask_cors import CORS, cross_origin
from flask import send_file
import os.path
app = Flask(__name__)
CORS(app, support_credentials=True)
camera = picamera.PiCamera()
camera.resolution = (600, 480)
@app.route("/captureImage")
@cross_origin(supports_credentials=True)
def captureImage():
camera.capture('cameraImages/Image.jpg')
return send_file('cameraImages/Image.jpg', mimetype='image/jpeg')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000)
<file_sep>/dennis.py
# -*- coding: utf-8 -*-
import cv2
import numpy as np
from matplotlib import pyplot as plt
import os
from datetime import datetime
import random
def isThisOkay(img):
return bool(random.getrandbits(1))
def testMyImage(imgPath):
print("Stuff")
imgRaw = cv2.imread(imgPath, cv2.IMREAD_COLOR) #IMREAD_GRAYSCALE IMREAD_UNCHANGED IMREAD_COLOR
imgRawOrig = imgRaw.copy()
img_b,img_g,img_r = cv2.split(imgRaw)
img_gray = cv2.cvtColor(imgRaw, cv2.COLOR_BGR2GRAY)
equ = cv2.equalizeHist(img_r)
#equ_th, dst = cv2.threshold(equ, 0, 200, cv2.THRESH_BINARY);
th, bw = cv2.threshold(img_r, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
edges = cv2.Canny(imgRaw, th/2, th)
plt.subplot(3,3,1),plt.imshow(imgRaw)
plt.subplot(3,3,2),plt.imshow(bw, 'gray')
# noise removal
kernel = np.ones((13,13),np.uint8)
opening = cv2.morphologyEx(bw, cv2.MORPH_OPEN,kernel, iterations = 2)
# sure background area
sure_bg = cv2.dilate(opening,kernel,iterations=3)
# Finding sure foreground area
dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,5)
ret, sure_fg = cv2.threshold(dist_transform,0.4*dist_transform.max(),255,0)
# Finding unknown region
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg,sure_fg)
plt.subplot(3,3,4), plt.imshow(sure_bg)
plt.subplot(3,3,5), plt.imshow(sure_fg)
# Marker labelling
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(sure_fg)
# Add one to all labels so that sure background is not 0, but 1
labels = labels+1
# Now, mark the region of unknown with zero
labels[unknown==255] = 0
labels = cv2.watershed(imgRaw, labels)
imgRaw[labels == -1] = [255,0,0]
plt.subplot(3,3,3),plt.imshow(labels)
plt.subplot(3,3,6),plt.imshow(imgRaw)
print("Number of markers: ", num_labels)
newpath = "test/contures/" + datetime.today().strftime("%d-%b-%Y_%Hh%Mm%S")
if not os.path.exists(newpath):
os.makedirs(newpath)
for i in range(1, num_labels):
if True: #i < 50:
newLabel = labels.copy()
newLabel[newLabel != i] = 0
newLabel[newLabel == i] = 255
newLabel = newLabel.astype(np.uint8)
th, imgloc = cv2.threshold(newLabel, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
image, contours, hierarchy = cv2.findContours(imgloc, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for cont in contours:
x,y,w,h = cv2.boundingRect(cont)
okayCheck = isThisOkay(imgRawOrig[y:y+h,x:x+w])
if not okayCheck:
labels[labels == i] = 0
cv2.imwrite(newpath + '/' + str(i) +'.png', imgRawOrig[y:y+h,x:x+w])
numNotBG = np.count_nonzero(bw.flatten())
print("Not Background: ", numNotBG)
labelCp = labels.copy()
labelCp[labelCp < 2] = 0
numOK = np.count_nonzero(labelCp.flatten())
print("Good stuff: ", numOK)
percOk = (numOK/numNotBG)*100.0
print("OK: ", percOk)
fred = np.fft.fft2(img_r)
fshiftred = np.fft.fftshift(fred)
magnitude_spectrum_red = 20*np.log(np.abs(fshiftred))
plt.subplot(3,3,7),plt.imshow(magnitude_spectrum_red, 'gray')
# Overlay image
total = bw
good = labels.copy()
alpha = 0.5
overlay = imgRawOrig.copy()
output = imgRawOrig.copy()
output[total > 0] = (0, 255, 0)
output[labels > 1] = (0, 0, 255)
cv2.addWeighted(overlay, alpha, output, 1 - alpha, 0, output)
plt.subplot(3,3,8),plt.imshow(output)
plt.show()
cv2.namedWindow("window", cv2.WINDOW_FREERATIO)
cv2.imshow('window', output)
cv2.imwrite('okay_reportSingle.jpg', output)
print("WUHUUU")
if __name__ == "__main__":
testMyImage('dorde/okay1.jpg')<file_sep>/test/normalize2.py
from os import listdir
from os.path import isfile, join
import numpy as np
import cv2
###################
# Normalization is done by discarding too small or too big images
# and by fiiling in for the missing rows by adding rows/columns with 0s until
# the size of the image is 100x100
# Moreover, the that are bigger than 200px in some dimension are split to two
# smaller ones and added separately
###################
# limits for image size
max_height = 100
min_height = 50
max_width = 100
min_width = 50
def split(img):
height, width= img.shape
if (width > height):
img1 = img[:max_height, :max_width]
img2 = img[:max_height, max_width:2*max_width]
return img1, img2
if (width < height):
img1 = img[:max_height, :max_width]
img2 = img[max_height:2*max_height, :max_width]
return img1, img2
def fill_the_missing(img):
height, width = img.shape
# Filling rows
if (height < max_height):
tmp = np.array([np.zeros(width)])
while (height < max_height):
img = np.concatenate((img, tmp))
height += 1
height, width = img.shape
# Filling columns
if (width < max_width):
tmp = np.zeros(height)
while (width < max_width):
img = np.c_[img, tmp]
width += 1
return img
# List all the grains from the 'okay' folder
path = 'okay/'
data_set_path_safe = "data_set/safe/"
images_safe = [f for f in listdir(path) if isfile(join(path, f))]
# Filter the images based on the size
# - if one of the dimensions is > 100 px - discard
# - if the image has both dimentions < 50 px - discarded
counter = 0
for image_path in images_safe:
img = cv2.imread(path + image_path, cv2.IMREAD_GRAYSCALE)
height, width= img.shape
if (width < min_width and height < min_height):
continue
# # We don't do the splitting in the case of the 'okay' datasets
# # In case the image has one of the dimensions twice the size of the allowed
# # we split it into two images
# if (width > 2*max_width or height > 2*max_height):
# img1, img2 = split(img)
# counter += 2
# cv2.imwrite(data_set_path_safe + image_path + "1", fill_the_missing(img1))
# cv2.imwrite(data_set_path_safe + image_path + "2", fill_the_missing(img2))
# continue
if (width > max_width or height > max_height):
continue
# Save the resized image to the new folder
counter += 1
cv2.imwrite(data_set_path_safe + image_path, fill_the_missing(img))
print("Out of " + str(len(images_safe)) + " images " + str(counter) + " passed the filter in the 'okay' folder.")
# List all the grains from the 'okay' folder
path = 'contaminated/'
data_set_path_safe = "data_set/not_safe/"
images_not_safe = [f for f in listdir(path) if isfile(join(path, f))]
# Filter the images based on the size
# - if one of the dimensions is > 100 px - discard
# - if the image has both dimentions < 50 px - discarded
counter = 0
for image_path in images_not_safe:
img = cv2.imread(path + image_path, cv2.IMREAD_GRAYSCALE)
height, width= img.shape
if (width < min_width and height < min_height):
continue
# In case the image has one of the dimensions twice the size of the allowed
# we split it into two images
if (width > max_width+min_width or height > max_height+min_height):
img1, img2 = split(img)
counter += 2
cv2.imwrite(data_set_path_safe + image_path[:image_path.find('.')] + "-1" + image_path[image_path.find('.'):], fill_the_missing(img1))
cv2.imwrite(data_set_path_safe + image_path[:image_path.find('.')] + "-2" + image_path[image_path.find('.'):], fill_the_missing(img2))
continue
if (width > max_width or height > max_height):
continue
# Save the resized image to the new folder
counter += 1
cv2.imwrite(data_set_path_safe + image_path, fill_the_missing(img))
print("Out of " + str(len(images_not_safe)) + " images " + str(counter) + " passed the filter in the 'contaminated' folder.")
<file_sep>/watershed.py
# -*- coding: utf-8 -*-
import numpy as np
import cv2
from matplotlib import pyplot as plt
#imgRaw = cv2.imread('images/water_coins.jpg', cv2.IMREAD_COLOR)
imgRaw = cv2.imread('raw/normal3_crop.jpg', cv2.IMREAD_COLOR)
b,g,r = cv2.split(imgRaw)
gray = cv2.cvtColor(imgRaw, cv2.COLOR_BGR2GRAY)
img = gray
print(img.shape)
#hist,bins = np.histogram(img.flatten(),256,[0,256])
#cdf = hist.cumsum()
#cdf_normalized = cdf * hist.max()/ cdf.max()
thresholdLevel= cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU
print("Threshold: ", thresholdLevel)
ret, thresh = cv2.threshold(img,0,255,thresholdLevel)
plt.subplot(121),plt.imshow(img)
plt.subplot(122),plt.imshow(thresh, cmap = 'gray')
plt.show()
# noise removal
kernel = np.ones((10,10),np.uint8)
opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2)
# sure background area
sure_bg = cv2.dilate(opening,kernel,iterations=3)
# Finding sure foreground area
dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,5)
ret, sure_fg = cv2.threshold(dist_transform,0.1*dist_transform.max(),255,0)
# Finding unknown region
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg,sure_fg)
plt.subplot(121),plt.imshow(sure_bg, cmap = 'gray')
plt.subplot(122),plt.imshow(sure_fg, cmap = 'gray')
plt.show()
# Marker labelling
ret, markers = cv2.connectedComponents(sure_fg)
# Add one to all labels so that sure background is not 0, but 1
markers = markers+1
# Now, mark the region of unknown with zero
markers[unknown==255] = 0
plt.subplot(111),plt.imshow(markers)
plt.show()
markers = cv2.watershed(imgRaw,markers)
imgRaw[markers == -1] = [255,0,0]
plt.subplot(111),plt.imshow(imgRaw)
plt.show()
print("Number of grains: ", ret)
<file_sep>/main.py
import cv2
import numpy as np
from matplotlib import pyplot as plt
import os
from datetime import datetime
def readImage(path):
img = cv2.imread(path, cv2.IMREAD_COLOR) #IMREAD_GRAYSCALE IMREAD_UNCHANGED IMREAD_COLOR
b,g,r = cv2.split(img)
th, bw = cv2.threshold(r, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
return img, bw
def denoiseImage(img):
# noise removal
kernel = np.ones((13,13),np.uint8)
opening = cv2.morphologyEx(img, cv2.MORPH_OPEN,kernel, iterations = 2)
# sure background area
sure_bg = cv2.dilate(opening,kernel,iterations=3)
# Finding sure foreground area
dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,5)
ret, sure_fg = cv2.threshold(dist_transform,0.5*dist_transform.max(),255,0)
# Finding unknown region
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg,sure_fg)
# Marker labelling
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(sure_fg)
# Add one to all labels so that sure background is not 0, but 1
labels = labels+1
# Now, mark the region of unknown with zero
labels[unknown==255] = 0
return labels, sure_bg, sure_fg
def main(imgPath):
imgRaw, equ = readImage(imgPath)
imgRawOrig = imgRaw.copy()
if __name__ == "__main__":
main('dorde/black_contaminated_1.jpg')
<file_sep>/README.md
# hackzurich2017
Zurich Hackathon 2017 - Buhler challenge
<file_sep>/webApp/js/dashboard.js
$(document).ready(function () {
var getCameraImageUrl = "http://172.31.1.17:5000/captureImage";
var sendImageToMagicBoxUrl = "http://localhost:5000/receiveImage";
var imageBase64String;
$("#takeImage").show();
$("#contaminationReport").hide();
$("#getContaminationReport").hide();
// Get Grain Image content
$("#getGrainImage").click(function () {
$.ajax({
url: getCameraImageUrl,
type: "GET",
dataType:"image/jpeg",
success: function (data) {
alert("response");
// Send grain image content to Magic Box
$("#getContaminationReport").show();
},
error: function () {
},
async: false
});
});
$("#getContaminationReport").click(function () {
$.ajax({
url: sendImageToMagicBoxUrl,
type: "POST",
data: {
imageString: imageBase64String
},
success: function (data) {
$("#contaminationReport").show();
},
error: function () {
},
async: false
});
});
});<file_sep>/test/retrieve_label.py
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 17 04:46:13 2017
An example on how to get the evaluation of an image
@author: djordje
"""
import cv2, os, sys
import numpy as np
scriptpath = 'predict.py'
sys.path.append(os.path.abspath(scriptpath))
import predict
not_safe_image = cv2.imread("data_set/not_safe/45-1.png", cv2.IMREAD_GRAYSCALE)
not_safe_image_array = []
for row in not_safe_image:
not_safe_image_array = np.concatenate((not_safe_image_array, row))
chk = Check(not_safe_image_array)
print(chk.Label())
safe_image = cv2.imread("data_set/safe/1.png", cv2.IMREAD_GRAYSCALE)
safe_image_array = []
for row in safe_image:
safe_image_array = np.concatenate((safe_image_array, row))
chk = Check(safe_image_array)
print(chk.Label())<file_sep>/test/convert_to_csv_and_label.py
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 17 02:09:28 2017
@author: brlauuu
"""
from os import listdir
from os.path import isfile, join
import numpy as np
import cv2
from random import shuffle
def toArrayOfArrays(image):
result = []
for row in image:
result = np.concatenate((result, row))
return result
def array2string(array):
result = ""
for a in array:
result += str(a) + ","
return result[:-1] + "\n"
data_set_path_safe = "data_set/safe/"
data_set_path_not_safe = "data_set/not_safe/"
images_safe = [data_set_path_safe + f for f in listdir(data_set_path_safe) if isfile(join(data_set_path_safe, f))]
images_not_safe = [data_set_path_not_safe + f for f in listdir(data_set_path_not_safe) if isfile(join(data_set_path_not_safe, f))]
data = []
for image in images_safe:
img = cv2.imread(image, cv2.IMREAD_GRAYSCALE)
data.append(np.concatenate(([1], toArrayOfArrays(img))))
for image in images_not_safe:
img = cv2.imread(image, cv2.IMREAD_GRAYSCALE)
data.append(np.concatenate(([0], toArrayOfArrays(img))))
shuffle(data)
header = ["label"]
for i in range(0,10000):
header.append('c'+str(i))
with open('data.csv', 'w') as file:
file.write(array2string(header))
for d in data:
file.write(array2string(d))
<file_sep>/magicStuff/receiveImage.py
import base64
from flask import Flask
from flask import request
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app, support_credentials=True)
@app.route("/receiveImage", methods=['POST'])
@cross_origin(supports_credentials=True)
def receiveImage():
# Read base64 representation of Image
imageString = request.form.get('imageString')
# Convert to jpeg image
fh = open("receivedImage.jpg", "wb")
fh.write(base64.b64decode(imageString))
fh.close()
# Call the contamination detection logic here
# Generate Report
# Return Report
return "the best report ever - will be a JSON string."
if __name__ == "__main__":
app.run(host='127.0.0.1', port=5000)
<file_sep>/extracting_contours.py
import cv2
import numpy as np
from matplotlib import pyplot as plt
import os
from datetime import *
filename = 'stuff.jpg'
img = cv2.imread(filename,0)
#img = cv2.medianBlur(img,5)
img = cv2.GaussianBlur(img,(5,5),0)
ret,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)
th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY_INV,11,2)
th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,11,2)
titles = ['Original Image', 'Global Thresholding (v = 127)',
'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']
images = [img, th1, th2, th3]
for i in range(0, 4):
plt.subplot(2, 2, i+1),plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.show()
image, contours, hierarchy = cv2.findContours(th2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
print(len(contours))
cnt = contours[0]
cv2.drawContours(image, [cnt],-1,(0,0,0),1)
#plt.plot(image)
#plt.show()
#cv2.imshow('contours', image)
cv2.imwrite(filename + '-contours.png',image)
#cv2.waitKey(0) ## Wait for keystroke
#cv2.destroyAllWindows() ## Destroy all windows
# Directory for storing grain contures
newpath = "C:/Users/djord/OneDrive/Shljaka/HackZurich2017/test/contures/" + datetime.today().strftime("%d-%b-%Y %Hh%Mm%S")
if not os.path.exists(newpath):
os.makedirs(newpath)
### Extracting contours
for i in range(0, len(contours)):
if (i % 2 == 0):
cnt = contours[i]
#mask = np.zeros(im2.shape,np.uint8)
#cv2.drawContours(mask,[cnt],0,255,-1)
x,y,w,h = cv2.boundingRect(cnt)
#cv2.rectangle(image, (x,y), (x+w,y+h), (0,255,0), 1)
# cv2.imshow('Features', image)
cv2.imwrite(newpath + '/' + str(i) +'.png', image[y:y+h,x:x+w])
cv2.destroyAllWindows()
| 0a0a5c5a883009f8c5d30a877e3685331a82ee06 | [
"Markdown",
"Python",
"JavaScript"
] | 12 | Python | madsendennis/hackzurich2017 | 2e1dc51ce3828030a4a0e6022b6ce1d5ab94fb11 | 90419018a55b53bb4dbac38ea370c02601706b3b |
refs/heads/master | <repo_name>JatinDandona/Automation_Uniteller<file_sep>/src/main/java/com/unitellerAutomation/Keywords/LogInPage.java
package com.unitellerAutomation.Keywords;
import java.util.ArrayList;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.Reporter;
import com.unitellerAutomation.TestInitiator.TestInitiator;
public class LogInPage{
WebDriver driver;
public LogInPage(WebDriver driver){
this.driver = driver;
}
public void verifyLoginPageTitle(){
Assert.assertEquals(driver.getTitle().trim(), "Login | Uniteller",
"[Assertion Failed]: lOGIN Page title is not as expected");
Reporter.log("Assertion passed: LOGIN Page title is same as expected",true);
}
public void enterUsrname(String userId){
driver.findElement(By.id("email")).sendKeys(userId);
Reporter.log("user entered user id as "+userId, true);
}
public void EnterPassword(String pass){
driver.findElement(By.id("password")).sendKeys(pass);
Reporter.log("user enterd password", true);
}
public void clickLoginButton(){
driver.findElement(By.xpath("//input[@value='Login']")).click();
Reporter.log("User clicked on login button", true);
}
public void verifyFailedLogInMessage(String errorMessage){
Assert.assertEquals(driver.findElement(By.xpath("//ul[@class='errorMessage']/li/span")).getText(),
errorMessage,
"[Assertion Failed]: Error Message is not as expected");
Reporter.log("Assertion passed: Error Message is same as expected",true);
}
public void getSecurityQuestion(ArrayList<String> securityQuestion_ans){
int flag=0;
{
for(String s: securityQuestion_ans){
String[] a = s.split("/");
System.out.println(a[0]);
System.out.println(a[1]);
TestInitiator.hardwait(2);
if(a[1].contains(driver.findElement(By.xpath("//div[@class='email_box']")).getText().split("[0-9]")[1])){
TestInitiator.hardwait(2);
driver.findElement(By.id("firstAnswer")).sendKeys(a[0]);
flag=1;
}
}
}
if(flag==0){
Assert.fail();
}
}
public void verifyCompleteProfilePopUp(){
driver.findElement(By.xpath(".//div[@id='boonton_pop' and @style!='display:none;']")).isDisplayed();
Reporter.log("Pop up to complete the profile is displayed", true);
driver.findElement(By.xpath(".//img[@id='hide_nav_pop']")).click();
}
}
<file_sep>/src/main/java/com/unitellerAutomation/Tests/Uniteller_AddBeneficiary_cashPickup.java
package com.unitellerAutomation.Tests;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Properties;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.unitellerAutomation.TestInitiator.TestInitiator;
public class Uniteller_AddBeneficiary_cashPickup {
TestInitiator test = new TestInitiator();
Properties properties = new Properties();
String userId;
String password;
InputStream input = null;
ArrayList<String> securityQuestion_ans;
File file = new File("testData.data");
@BeforeClass
public void loadTestData() throws FileNotFoundException, IOException{
input = new FileInputStream(file);
properties.load(input);
userId = properties.getProperty("userId_addBen_cashPichUp");
password = <PASSWORD>("userId_addBen_Password");
securityQuestion_ans = new ArrayList<String>(
Arrays.asList(properties.getProperty("securityQuestion_ans1"),
properties.getProperty("securityQuestion_ans2"),properties.getProperty("securityQuestion_ans3")));
}
@Test
public void Step_01_LaunchApplication(){
test.launchURL("http://orapitest.uniteller.com/");
test.loginPage.verifyLoginPageTitle();
test.loginPage.enterUsrname(userId);
test.loginPage.clickLoginButton();
test.loginPage.EnterPassword(<PASSWORD>);
test.loginPage.clickLoginButton();
test.loginPage.getSecurityQuestion(securityQuestion_ans);
test.loginPage.clickLoginButton();
test.loginPage.verifyCompleteProfilePopUp();
test.headerSection.clickBeneficiaryTab();
test.addNewBenfeciaryPage.addNewBeneficiaryLink();
test.addNewBenfeciaryPage.verifyAddNewBeneficiaryHeading("Add New Beneficiary");
test.addNewBenfeciaryPage.clickDestinationCountryDropDown();
test.addNewBenfeciaryPage.selctPaymentCurrency();
test.addNewBenfeciaryPage.selectReceptionMethod();
test.addNewBenfeciaryPage.enterBenficiaryDetails();
test.addNewBenfeciaryPage.selectState();
test.addNewBenfeciaryPage.verifyBeninfoURL();
test.addNewBenfeciaryPage.addPayerInfo();
test.loginPage.clickLoginButton();
test.addNewBenfeciaryPage.verifyBenAdded();
}
}
<file_sep>/src/main/java/com/unitellerAutomation/Keywords/HeaderSection.java
package com.unitellerAutomation.Keywords;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.Reporter;
public class HeaderSection {
WebDriver driver;
public HeaderSection(WebDriver driver){
this.driver = driver;
}
public void clickBeneficiaryTab(){
driver.findElement(By.xpath("//a[@href='first<EMAIL>']")).click();
Reporter.log("User clicked on beneficiary tab", true);
}
}
<file_sep>/src/main/java/com/unitellerAutomation/Keywords/AddNewBeneficiaryPage.java
package com.unitellerAutomation.Keywords;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;
import org.testng.Reporter;
import com.unitellerAutomation.TestInitiator.TestInitiator;
public class AddNewBeneficiaryPage {
WebDriver driver;
Select selectByValue ;
public AddNewBeneficiaryPage(WebDriver driver){
this.driver = driver;
}
public void addNewBeneficiaryLink(){
driver.findElement(By.xpath("//div[@class='add_new_ben_button']//a")).click();
Reporter.log("user clicked on add new beneficiary link");
}
public void verifyAddNewBeneficiaryHeading(String heading){
TestInitiator.hardwait(2);
Assert.assertEquals(driver.findElement(By.xpath("//div[@id='container']/h1")).getText().trim(),heading,"Assertion failed");
Reporter.log("assertion passed", true);
}
public void clickDestinationCountryDropDown(){
selectByValue = new Select(driver.findElement(By.xpath("//select[@id='quoteCountry']")));
selectByValue.selectByValue("Philippines");
Reporter.log("user clicked on destination country drop down", true);
}
public void selctPaymentCurrency(){
selectByValue = new Select(driver.findElement(By.id("currencyId")));
selectByValue.selectByValue("Philippine Pesos");
Reporter.log("user selected on preffered currency ", true);
}
public void selectReceptionMethod(){
TestInitiator.hardwait(1);
selectByValue = new Select(driver.findElement(By.id("PMId")));
selectByValue.selectByValue("Cash Pickup");
Reporter.log("user selected on reception method as cashpickup ", true);
}
public void enterBenficiaryDetails(){
driver.findElement(By.id("firstName")).sendKeys("abcd");
Reporter.log(" ", true);
driver.findElement(By.id("lastName")).sendKeys("abcd");
Reporter.log(" ", true);
driver.findElement(By.id("genderM")).click();
Reporter.log(" ", true);
driver.findElement(By.id("address1")).sendKeys("delhi");
Reporter.log(" ", true);
driver.findElement(By.id("modifyDobdatepicker")).sendKeys("03/15/1985");
Reporter.log(" ", true);
driver.findElement(By.id("city")).sendKeys("new delhi");
Reporter.log(" ", true);
driver.findElement(By.id("zipCode")).sendKeys("589654");
Reporter.log(" ", true);
driver.findElement(By.id("cellPhone")).sendKeys("5897463521");
Reporter.log(" ", true);
}
public void selectState(){
selectByValue = new Select(driver.findElement(By.id("state")));
selectByValue.selectByValue("Manila Metropolitan");
Reporter.log("user selected state ", true);
driver.findElement(By.id("proceed")).click();
}
public void verifyBeninfoURL(){
Assert.assertTrue(driver.getCurrentUrl().contains("BeneInfoAction"), "Assertion failed");
Reporter.log("assertion passed",true);
}
public void addPayerInfo(){
driver.findElement(By.xpath("//img[contains(@src,'BancoDeOroUniversalBank')]//following-sibling::span")).click();
Reporter.log("addded payer info",true);
}
public void verifyBenAdded(){
TestInitiator.hardwait(2);
driver.findElement(By.xpath("//div[@class='beneficiary_container']")).isDisplayed();
}
}
| 8796facd3fe4aff20015f97c6abfac4e204dca94 | [
"Java"
] | 4 | Java | JatinDandona/Automation_Uniteller | 479c7e3bf334eda7a7398fa7e2d3ff6bc4051510 | 7c213f79ead61ce0ad8ad0871a8df45618151834 |
refs/heads/master | <repo_name>csdodd/GiphyTest<file_sep>/app/src/main/java/net/colindodd/giphytest/view/MainActivity.java
package net.colindodd.giphytest.view;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.EditText;
import net.colindodd.giphytest.R;
import net.colindodd.giphytest.model.GiphyData;
import net.colindodd.giphytest.presenters.SearchPresenter;
import net.colindodd.giphytest.services.GiphyInterface;
import net.colindodd.giphytest.services.GiphyService;
import net.colindodd.giphytest.view.adapters.GiphyAdapter;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private SearchPresenter presenter;
private RecyclerView recyclerView;
private GiphyAdapter giphyAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
loadImages();
}
private void init() {
initGiphyService();
initRecyclerView();
initInput();
}
private void initInput() {
final EditText input = (EditText) findViewById(R.id.main_activity__input);
input.addTextChangedListener(presenter.getTextChangedListener());
}
private void initGiphyService() {
final GiphyService giphyService = new GiphyService();
final GiphyInterface giphyInterface = giphyService.getApi();
this.presenter = new SearchPresenter(this, giphyInterface);
}
private void initRecyclerView() {
this.recyclerView = (RecyclerView) findViewById(R.id.main_activty__recycler_view);
this.recyclerView.setHasFixedSize(true);
final RecyclerView.LayoutManager recyclerLayoutManager = new GridLayoutManager(this, GiphyAdapter.NUM_ROWS);
this.recyclerView.setLayoutManager(recyclerLayoutManager);
this.giphyAdapter = new GiphyAdapter(this);
this.recyclerView.setAdapter(this.giphyAdapter);
}
private void loadImages() {
this.presenter.searchGifs("make it rain");
}
public void displayGifs(final List<GiphyData> gifs) {
this.giphyAdapter.setGifs(gifs);
}
}
<file_sep>/app/src/main/java/net/colindodd/giphytest/model/ImageSet.java
package net.colindodd.giphytest.model;
public class ImageSet {
public GiphyImage fixed_width;
public GiphyImage downsized;
public GiphyImage original;
}<file_sep>/app/src/main/java/net/colindodd/giphytest/model/GiphyResponse.java
package net.colindodd.giphytest.model;
import java.util.List;
public class GiphyResponse {
public List<GiphyData> data;
}
| 712630c29e539b52a1fcbf2cba23c9e2706872b1 | [
"Java"
] | 3 | Java | csdodd/GiphyTest | f77e8c955caba93ca6654463fa360d3e9a084968 | 41322b72d2d2b353342122db1304e8bdb633699e |
refs/heads/master | <file_sep>var jade
var html2jade
var keywords = [
"if", "else",
"each", "for",
"case", "when", "default",
"include", "mixin",
"extends", "block"
]
var replaceAll = function(string, omit, place, prevstring) {
if (prevstring && string === prevstring) {
return string;
}
prevstring = string.replace(omit, place);
return replaceAll(prevstring, omit, place, string);
};
exports.toJade = function (html, cb) {
if (html2jade == null) html2jade = require("html2jade")
keywords.forEach(function (E) {
html = html.replace(new RegExp("(<|</)" + E + "\\b","g"), "$1_" + E);
})
html = replaceAll(html, " id=", " rw_id=")
html = replaceAll(html, " name=", " id=")
html = replaceAll(html, " class=", " rw_class=")
html = replaceAll(html, " style=", " class=")
html = html.replace(/<([_\w\d]+)[^>]+\/>/g, function(match, tagname) {
return match.replace("\/>", "></" + tagname + ">");
})
var tagnames = {}
html = html.replace(/(<|<\/)([_\w\d]+)/g, function(match, chev, tagname) {
tagnames[tagname] = true
return chev + "rw_" + tagname
})
html = "<html>\n<body>\n<html>\n<body>\n" + html + "\n</body>\n</html>\n</body>\n</html>"
html2jade.convertHtml(html, {}, function (err, jade) {
var newJade = ""
jade.split("\n").forEach(function(line, index){
if (index < 4) return;
newJade += line.slice(8) + "\n"
})
jade = newJade
jade = replaceAll(jade, "rw_id=", "id=")
jade = replaceAll(jade, "rw_class=", "class=")
Object.keys(tagnames).forEach(function (E) {
jade = jade.replace(new RegExp("\\brw_" + E + "\\b","g"), E);
})
cb(jade)
})
}
var postWirer = function(code) {
code = replaceAll(code, " id=", " name=");
code = replaceAll(code, " class=", " style=");
code = replaceAll(code, "<div", "<panel");
code = replaceAll(code, "</div", "</panel");
return code.replace(/(<|<\/)rw_(\w+)/g, "$1$2");
};
var preWirer = function(code) {
code = code.replace(/@([\w\d_\-]+)(\(?)/g, function(match, target, openparen) {
return ("(target=\"" + target + "\"") + (openparen.length ? "" : ")");
});
keywords.forEach(function (E) {
code = code.replace(new RegExp("\\b_" + E + "\\b","g"), "rw_" + E);
})
return code
};
exports.render = function (jadeCode, jadeOptions, filename) {
if (jade == null) jade = require("jade")
if (jadeOptions == null) jadeOptions = {}
jadeOptions.pretty = true
if (typeof filename === "string") jadeOptions.filename = filename
return postWirer(jade.render(preWirer(jadeCode), jadeOptions));
}
exports.toWire = function (jade, locals, cb) {
if (jade == null) jade = require("jade")
cb(exports.render(jade, locals))
}
// When watching scripts, it's useful to log changes with the timestamp.
exports.timeLog = function (message) {
console.log((new Date).toLocaleTimeString() + " - " + message)
}<file_sep>jade-to-wire
============
Jade syntax to wire xml compiler
Use node.js to watch changes to `.jade` files to compile into corresponding `.wire` files.
After installing globally, you can run the command `jade-to-wire` from any folder to start a file watcher.
```
sudo npm install -g jade-to-wire
jade-to-wire
```
I recommend this compiler be used with SFTP for Sublime Text to monitor compiled wire files for uploading to create a quick-paced workflow for making WIRE apps.
## Pre-preprocessors
`jade-to-wire` does use some of its own pre and post compilation processors to help you write wire.
Some basics of the post-compiling, are that `id=` is replaced with `name=` to better suit the WIRE XML language.
And `class=` is replaced with `style=`
So the tag `panel#bacon.square` is compiled into `<panel name="bacon" style="square"></panel>`
## Jade keywords
Some keywords are shared between WIRE XML and jade like `include` and `if` tags. So if you want to generate a `<if>` tag you use `_if` in jade,
***so:***
```jade
- var happy = true
if happy
_if(lhs="" operator="" rhs="")
assign(property="" value="")
```
***becomes:***
```xml
<if lhs="" operator="" rhs="">
<assign property="" value=""/>
</if>
```
## Vars file
If a `vars.cson` or a `vars.json` file is located in the directory where `jade-to-wire` is executed, it will be read in for local variables to be used with each jade conversion.
## Converting wire to jade
To convert past projects into the nifty and fantastic language of jade, just run the command `wire-to-jade` from the directory containing your wire files.<file_sep>var fs = require("fs")
var jadeToWire = require("./main")
var isJson = null
var varsExt
var genWireFile = function(filename) {
var jadeCode = fs.readFileSync(filename, "utf8")
var optionsFile
var jadeOptions = {}
try {
optionsFile = fs.readFileSync("vars.cson", "utf8")
// if no error, cson file read
isJson = false
} catch (err) {
try {
optionsFile = fs.readFileSync("vars.json", "utf8")
isJson = true
} catch (err) {
jadeToWire.timeLog("Warning: no 'vars.json' or 'vars.cson' files found for jade to use.")
}
}
if (optionsFile) {
varsExt = (isJson?".json":".cson")
var cson = require("./cson")
try {
jadeOptions = cson.parse(optionsFile, isJson)
} catch (err) {
jadeToWire.timeLog("Error! 'vars" + varsExt + "' is incorrectly formatted!")
console.error(err.message)
}
}
jadeOptions.filename = filename
jadeToWire.toWire(jadeCode, jadeOptions, function (wire) {
var wireFilename = filename.slice(0, -4) + "wire"
fs.writeFile(wireFilename, wire, function(err) {
jadeToWire.timeLog("Compiled " + wireFilename)
if (err) {
throw err
}
})
})
}
var checkToCompile = function(filename, checkVars) {
if (filename != null){
ext = filename.slice(-5)
if (ext === ".jade")
genWireFile(filename)
else if (checkVars === true && isJson != null) {
if (ext === varsExt) {
jadeToWire.timeLog("'vars" + varsExt + "' changed")
genAll()
}
}
}
}
var genAll = function() {
fs.readdirSync("./").forEach(checkToCompile)
}
exports.run = function () {
jadeToWire.timeLog("Compiling jade files")
genAll()
var srcFW = fs.watch("./", {
interval: 500
})
srcFW.on("change", function(event, filename) {
if (event === "change") checkToCompile(filename, true)
})
jadeToWire.timeLog("Watching jade files")
} | 147cad3080f91d620f1b7e5d9dcc3ade5a57f5e7 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | colelawrence/jade-to-wire | 1523825e45ab3218265f4555c611b1d83eafda0e | f257f5803223b239d9b38a0d1b615c68d2d3589d |
refs/heads/master | <file_sep>require "codebreaker/version"
require "codebreaker/interface"
module Codebreaker
class Error < StandardError; end
# Your code goes here...
end
| 8ed53ac76332bb0f59c8fb848b65bc35233d6dc5 | [
"Ruby"
] | 1 | Ruby | Wayzyk/codebreaker-gem | 202af8149cfc3eddad17728327e70d85c0b46268 | 0a6670db8ae23960563d91190f02004119c7eed4 |
refs/heads/master | <repo_name>um4sk/fuminho-master<file_sep>/fuminho.py
import os
import socket
import sys
import time
os.system('apt install curl -y')
os.system('apt install figlet -y')
os.system('cls||clear')
print "########################################################################"
os.system('figlet fuminho.py')
print ""
print "coded by > um4sk"
print "########################################################################"
print ""
print " [ MENU ] "
print ""
print " [ 1 ] whois"
print " [ 2 ] header check"
print " [ 3 ] Port Scan"
print " [ 4 ] Subdomains check"
print " [ 0 ] Quit"
print ""
op1 = int(input('> '))
if op1 == 1:
os.system('cls||clear')
print "##########################"
print "#! WHOIS !#"
print "##########################"
print ""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
url = raw_input('alvo: ')
host = "172.16.17.32"
port = 43
s.connect((host, port))
s.send(url+"\r\n")
resposta = s.recv(1024)
print "###########! CONSULTA WHOIS !################"
print ""
print resposta
print ""
print "#############################################"
if op1 == 2:
os.system('cls||clear')
print "##########################"
print "#! HEADER CHECK !#"
print "##########################"
print ""
url = raw_input('alvo: ')
print "#############################################"
print ""
os.system('curl --head {}'.format(url))
print ""
print "#############################################"
exit()
if op1 == 3:
os.system('cls||clear')
print "##########################"
print "#! PORT SCAN !#"
print "##########################"
print ""
url = raw_input('alvo: ')
porta = int(input('Digite uma porta: '))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(0.5)
try:
s.connect((url, porta))
s.send('fuminho.py\r\n')
resposta = s.recv(100)
print(">> PORTA: [ "+str(porta)+" ] ABERTA!")
except:
print(">> PORTA: [ "+str(porta)+" ] FECHADA!")
finally:
s.close
exit()
if op1 == 4:
os.system('cls||clear')
print "##########################"
print "#! SUBDOMAINS CHECK !#"
print "##########################"
print ""
url = raw_input('alvo: ')
print ""
print "#############! SUB DOMAINS !#################"
print ""
os.system('dig {} +noall +answer'.format(url))
print ""
print "#############################################"
exit()
| 0ffe06e42b4511316defc957db221159b8f81ac6 | [
"Python"
] | 1 | Python | um4sk/fuminho-master | 2fa7c84543485246224f2b489dd872f6a49a4307 | 324382b0b2a6415376f25ebfd21c6139f2136afd |
refs/heads/master | <file_sep>import React from "react";
import Farm from "./Farm"
export default function App() {
return (
<div className="App">
<Farm location="Barcelona"/>
</div>
);
} | b9482c300671e99c644221cfc1687bdc6d95da36 | [
"JavaScript"
] | 1 | JavaScript | JimmyBcn/olad-react-jest-enzyme | d27a9b03d4622f0b339a42cad1088ed5df2e87ad | 78f256fcdb6238f6c1ba62f977f0d10334672566 |
refs/heads/master | <repo_name>rprtr258/rprtr258-s-2048<file_sep>/app/src/main/cpp/main.cpp
#include <iostream>
#include <sstream>
#include <time.h>
#include <SFML/Graphics.hpp>
const int TILES_COUNT = 29;
const int HEIGHT = 10;
const int WIDTH = 10;
const int MAX_TILES = HEIGHT * WIDTH;
const int TILE_SIZE = 66;
void generatetile(sf::Sprite *spr_tiles, int (&map)[WIDTH][HEIGHT], int &tiles, sf::Texture empty, sf::Texture &n1) {
if (tiles == MAX_TILES) return;
int x = rand() % WIDTH;
int y = rand() % HEIGHT;
while (map[x][y] != 0) {
x = rand() % WIDTH;
y = rand() % HEIGHT;
}
spr_tiles[x * WIDTH + y].setTexture(n1);
map[x][y] = 1;
}
std::string get_cwd(char **argv) {
std::string exe_path = std::string(argv[0]);
int index = exe_path.find_last_of('\\');
return exe_path.substr(0, index);
}
int main(int argc, char **argv) {
srand(time(0));
sf::RenderWindow window(sf::VideoMode(TILE_SIZE * WIDTH, TILE_SIZE * HEIGHT), "rprtr258's 2048");
sf::Texture tex_tiles[TILES_COUNT];
int tiles = 1;
// TODO: specify size from argv
//in << WIDTH << HEIGHT;
bool press_but = false;
std::string cwd = get_cwd(argv);
for (int i = 0; i < TILES_COUNT; i++) {
std::ostringstream str;
str << cwd << "\\img\\" << i << ".png";
if (!tex_tiles[i].loadFromFile(str.str())) {
return 1;
}
}
sf::Sprite spr_tiles[WIDTH][HEIGHT];
int map[WIDTH][HEIGHT];
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
spr_tiles[j][i].setTexture(tex_tiles[0]);
spr_tiles[j][i].setPosition(j * TILE_SIZE, i * TILE_SIZE);
map[j][i] = 0;
}
}
generatetile((sf::Sprite*)spr_tiles, map, tiles, tex_tiles[0], tex_tiles[1]);
while (window.isOpen()) {
sf::Event Event;
while (window.pollEvent(Event)) {
if (Event.type == sf::Event::Closed) {
window.close();
return 0;
}
if (Event.type == sf::Event::KeyPressed) {
bool turnmade = false;
if (Event.key.code == sf::Keyboard::Up && !press_but) {
press_but = true;
for (int i = 0; i < WIDTH; i++) {
for (int j = 1; j < HEIGHT; j++) {
if (map[i][j] != 0 && map[i][j - 1] == 0) {
int k = j - 1;
while (k >= 0 && map[i][k] == 0)
k--;
if (map[i][k + 1] == 0) {
if (map[i][j] == map[i][k]) {
map[i][k]++;
map[i][j] = 0;
spr_tiles[i][j].setTexture(tex_tiles[0]);
spr_tiles[i][k].setTexture(tex_tiles[map[i][k]]);
tiles--;
} else {
spr_tiles[i][k + 1].setTexture(tex_tiles[map[i][j]]);
spr_tiles[i][j].setTexture(tex_tiles[0]);
std::swap(map[i][j], map[i][k + 1]);
}
turnmade = true;
}
} else if (map[i][j] != 0 && map[i][j] == map[i][j - 1]) {
map[i][j - 1]++;
map[i][j] = 0;
tiles--;
spr_tiles[i][j].setTexture(tex_tiles[0]);
spr_tiles[i][j - 1].setTexture(tex_tiles[map[i][j - 1]]);
turnmade = true;
}
}
}
}
if (Event.key.code == sf::Keyboard::Right && !press_but) {
press_but = true;
for (int j = 0; j < HEIGHT; j++) {
for (int i = WIDTH - 1; i >= 0; i--) {
if (map[i][j] != 0 && map[i + 1][j] == 0) {
int k = i + 1;
while (k < WIDTH && map[k][j] == 0)
k++;
if (map[k - 1][j] == 0) {
if (map[i][j] == map[k][j]) {
map[k][j]++;
map[i][j] = 0;
spr_tiles[i][j].setTexture(tex_tiles[0]);
spr_tiles[k][j].setTexture(tex_tiles[map[k][j]]);
tiles--;
} else {
spr_tiles[k - 1][j].setTexture(tex_tiles[map[i][j]]);
spr_tiles[i][j].setTexture(tex_tiles[0]);
std::swap(map[i][j], map[k - 1][j]);
}
turnmade = true;
}
} else if (map[i][j] != 0 && map[i][j] == map[i + 1][j]) {
map[i + 1][j]++;
map[i][j] = 0;
tiles--;
spr_tiles[i][j].setTexture(tex_tiles[0]);
spr_tiles[i + 1][j].setTexture(tex_tiles[map[i + 1][j]]);
turnmade = true;
}
}
}
}
if (Event.key.code == sf::Keyboard::Left && press_but == false) {
press_but = true;
for (int j = 0; j < HEIGHT; j++) {
for (int i = 1; i < WIDTH; i++) {
if (map[i][j] != 0 && map[i - 1][j] == 0) {
int k = i - 1;
while (k >= 0 && map[k][j] == 0)
k--;
if (map[k + 1][j] == 0) {
if (map[i][j] == map[k][j]) {
map[k][j]++;
map[i][j] = 0;
spr_tiles[i][j].setTexture(tex_tiles[0]);
spr_tiles[k][j].setTexture(tex_tiles[map[k][j]]);
tiles--;
} else {
spr_tiles[k + 1][j].setTexture(tex_tiles[map[i][j]]);
spr_tiles[i][j].setTexture(tex_tiles[0]);
std::swap(map[i][j], map[k + 1][j]);
}
turnmade = true;
}
} else if (map[i][j] != 0 && map[i][j] == map[i - 1][j]) {
map[i - 1][j]++;
map[i][j] = 0;
tiles--;
spr_tiles[i][j].setTexture(tex_tiles[0]);
spr_tiles[i - 1][j].setTexture(tex_tiles[map[i - 1][j]]);
turnmade = true;
}
}
}
}
if (Event.key.code == sf::Keyboard::Down && !press_but) {
press_but = true;
for (int i = 0; i < WIDTH;i++) {
for (int j = HEIGHT - 2; j >= 0; j--) {
if (map[i][j] != 0 && map[i][j + 1] == 0) {
int k = j + 1;
while (k < HEIGHT && map[i][k] == 0)
k++;
if (map[i][k - 1] == 0) {
if (k != HEIGHT && map[i][j] == map[i][k]) {
map[i][k]++;
map[i][j] = 0;
spr_tiles[i][j].setTexture(tex_tiles[0]);
spr_tiles[i][k].setTexture(tex_tiles[map[i][k]]);
tiles--;
} else {
spr_tiles[i][k - 1].setTexture(tex_tiles[map[i][j]]);
spr_tiles[i][j].setTexture(tex_tiles[0]);
std::swap(map[i][j], map[i][k - 1]);
}
turnmade = true;
}
} else if (map[i][j] != 0 && map[i][j] == map[i][j + 1]) {
map[i][j + 1]++;
map[i][j] = 0;
tiles--;
spr_tiles[i][j].setTexture(tex_tiles[0]);
spr_tiles[i][j + 1].setTexture(tex_tiles[map[i][j + 1]]);
turnmade = true;
}
}
}
}
if (Event.key.code == sf::Keyboard::Up ||
Event.key.code == sf::Keyboard::Right ||
Event.key.code == sf::Keyboard::Left ||
Event.key.code == sf::Keyboard::Down) {
if (turnmade) {
if (tiles < MAX_TILES) {
tiles++;
generatetile((sf::Sprite*)spr_tiles, map, tiles, tex_tiles[0], tex_tiles[1]);
}
} else if (tiles == WIDTH * HEIGHT) {
return 0;
}
}
if (Event.key.code == sf::Keyboard::Space) {
for (int i = 0; i < WIDTH; i++) {
for (int j = 0; j < HEIGHT; j++) {
if (map[i][j] == 0) {
map[i][j] = 1;
spr_tiles[i][j].setTexture(tex_tiles[1]);
}
}
}
}
}
if (Event.type == sf::Event::KeyReleased) {
press_but = false;
}
}
window.clear();
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
window.draw(spr_tiles[j][i]);
}
}
window.display();
}
return 0;
}
<file_sep>/settings.gradle.kts
rootProject.name = "rprtr258-s-2048"
include("app")
<file_sep>/README.md
# rprtr258-s-2048
My copy of 2048 on C++
## Build
```bash
./gradlew release
```
The game will be archived in `app/build/dist/`. Unarchived version is in `app/build/exe/main/debug/`.
You can substitute `img` image files with `img1` image files for classic 2048 sprites.
## Control
Up, Left, Right, Down arrows to move blocks.
Space to fill the board.
## Screenshots

| cad3fd37bec4d4f06fd669e0c471a41e8eaab7ae | [
"Markdown",
"Kotlin",
"C++"
] | 3 | C++ | rprtr258/rprtr258-s-2048 | 03032978e6bbdc598144b025ac312eceb1953786 | 61051dddefc923a53d07fb22d816ca56495a1e0d |
refs/heads/master | <repo_name>mostafaMahfouz25/javascript-oop-app<file_sep>/js/script.js
const inputName = document.getElementById("name");
const inputEmail = document.getElementById("email");
const inputMobile = document.getElementById("mobile");
const contIdEdit = document.getElementById("contIdEdit");
const submit = document.getElementById("submit");
const formEmp = document.getElementById("formEmp");
const tableBody = document.querySelector("#example tbody");
class Employee
{
constructor(id,name,email,mobile)
{
this.name = name;
this.email = email;
this.mobile = mobile;
this.id = id;
}
storeEmployee()
{
const allData = JSON.parse(localStorage.getItem("employees")) ?? [];
allData.push({id:this.id,name:this.name,email:this.email,mobile:this.mobile});
localStorage.setItem("employees",JSON.stringify(allData));
}
showData()
{
const trEl = document.createElement("tr");
trEl.innerHTML = this.showHtmlRow();
tableBody.appendChild(trEl);
return this;
}
static showAllEmployees()
{
if(localStorage.getItem("employees"))
{
JSON.parse(localStorage.getItem("employees")).forEach((item)=>{
let newEmp = new Employee(item.id,item.name,item.email,item.mobile);
newEmp.showData();
})
}
}
updateData(id)
{
const newItem = {id:id,name:this.name,email:this.email,mobile:this.mobile}
const updatedData = JSON.parse(localStorage.getItem("employees")).map((item)=> {
if(item.id == id)
{
return newItem;
}
else
{
return item
}
});
localStorage.setItem("employees",JSON.stringify(updatedData));
}
showHtmlRow(){
return`
<td>${this.name}</td>
<td>${this.email}</td>
<td>${this.mobile}</td>
<td class="text-center">
<button class="btn btn-danger delete" data-id="${this.id}">Delete</button>
<button class="btn btn-info edit" data-id="${this.id}">Edit</button>
</td>
`
}
}
// Show All Data From Local Storage
Employee.showAllEmployees();
// add new item
formEmp.addEventListener("submit",(e)=>
{
e.preventDefault();
let nameVal = inputName.value;
let emailVal = inputEmail.value;
let mobileVal = inputMobile.value;
if(!contIdEdit.value)
{
let id = Math.floor(Math.random()*1000000);
const newEmp = new Employee(id,nameVal,emailVal,mobileVal);
newEmp.showData().storeEmployee();
}
else
{
let id = contIdEdit.value;
const newEmp = new Employee(id,nameVal,emailVal,mobileVal);
newEmp.updateData(id);
submit.value = "Submit";
tableBody.innerHTML = '';
Employee.showAllEmployees();
}
inputName.value = '';
inputEmail.value = '';
inputMobile.value = '';
})
// delete item
tableBody.addEventListener("click",(e)=>{
if(e.target.classList.contains("delete"))
{
const id = e.target.getAttribute("data-id");
const emps = JSON.parse(localStorage.getItem("employees"));
const newData = emps.filter(item => item.id != id);
localStorage.setItem("employees",JSON.stringify(newData));
e.target.parentElement.parentElement.remove();
}
else if(e.target.classList.contains("edit"))
{
const id = e.target.getAttribute("data-id");
const item = JSON.parse(localStorage.getItem("employees")).find((item)=> item.id == id);
inputName.value = item.name;
inputEmail.value = item.email;
inputMobile.value = item.mobile;
contIdEdit.value = item.id;
submit.value = "Edit Data Of This Employee"
}
}) | 11542cec270bfac60405d5594c8a11668df3aa68 | [
"JavaScript"
] | 1 | JavaScript | mostafaMahfouz25/javascript-oop-app | b2fc1e82d62421f5a2570ce330c9fea57b486f3f | 3b575cf7a2413f79a967482e063331d7331ca53d |
refs/heads/master | <repo_name>boing102/ppgso<file_sep>/src/gl_scene/brick.cpp
#include "brick.h"
#include "object_frag.h"
#include "object_vert.h"
#include "block.h"
#include <GLFW/glfw3.h>
Brick::Brick() {
// Set random scale speed and rotation
scale *= 1.0f;
speed = glm::vec3(0.0f, 0.0f, 0.0f);
rotation = glm::vec3(0.0f, 0.0f, 0.0f);
lives = (int) Rand(1.0f, 3.0f);
animateTop = false;
animateBot = false;
// Initialize static resources if needed
if (!shader) shader = ShaderPtr(new Shader{object_vert, object_frag});
if(lives == 1) {
texture = TexturePtr(new Texture{"green.rgb", 256, 256});
} else if(lives == 2) {
texture = TexturePtr(new Texture{"red.rgb", 256, 256});
}
if (!mesh) mesh = MeshPtr(new Mesh{shader, "brick.obj"});
}
Brick::~Brick() {
}
bool Brick::Update(Scene &scene, float dt) {
if(animateTop) {
this->position.y = animBot.y + (animTop.y-animBot.y)*t;
t+=0.5f;
printf("t\n");
if(this->position.y >= animTop.y) {
animateTop = false;
}
}
// Collide with scene
for (auto obj : scene.objects) {
// Ignore self in scene
if (obj.get() == this) continue;
// We only need to collide with asteroids and projectiles, ignore other objects
auto ball = std::dynamic_pointer_cast<Block>(obj);
if (!ball) continue;
// Compare distance to approximate size of the ball estimated from scale.
if ((glm::distance(position.y, ball->position.y) < 0.686f ) &&
((glm::distance(position.x, ball->position.x) < 1.391f ))) {
// Change ball's speed
ball->speed.y = -ball->speed.y;
if(ball->position.x < position.x) {
ball->speed.x = -ball->speed.x;
}
else {
ball->speed.x = ball->speed.x;
}
lives--;
if(lives == 1) {
texture = TexturePtr(new Texture{"green.rgb", 256, 256});
animateTop = true;
animBot = this->position;
animTop = this->position + glm::vec3(0.0f,0.3f,0.0f);
t = 0;
} else if(lives == 0) {
return false;
}
}
}
// Generate modelMatrix from position, rotation and scale
GenerateModelMatrix();
return true;
}
void Brick::Render(Scene &scene) {
shader->Use();
// use camera
shader->SetMatrix(scene.camera->projectionMatrix, "ProjectionMatrix");
shader->SetMatrix(scene.camera->viewMatrix, "ViewMatrix");
// render mesh
shader->SetMatrix(modelMatrix, "ModelMatrix");
shader->SetTexture(texture, "Texture");
shader->SetVector(scene.camera->position, "ViewPosition");
mesh->Render();
}
// shared resources
MeshPtr Brick::mesh;
ShaderPtr Brick::shader;
<file_sep>/src/gl_scene/block.cpp
#include "block.h"
#include "object_frag.h"
#include "object_vert.h"
#include <GLFW/glfw3.h>
Block::Block() {
// Set random scale speed and rotation
scale *= 1.0f;
speed = glm::vec3(Rand(-5.0f, 5.0f), 10.5f, 0.0f);
rotation = glm::vec3(PI, 0.0f, 0.0f);
rotMomentum = glm::vec3(0.0f, 0.0f, 0.0f);
// Initialize static resources if needed
if (!shader) shader = ShaderPtr(new Shader{object_vert, object_frag});
if (!texture) texture = TexturePtr(new Texture{"sphere.rgb", 256, 256});
if (!mesh) mesh = MeshPtr(new Mesh{shader, "ball2.obj"});
}
Block::~Block() {
}
bool Block::Update(Scene &scene, float dt) {
// Animate position according to time
position += speed * dt;
// Collisions with view borders
if(left() < -7.5f) {
speed.x *= -1;
}
else if(right() > 7.5f) {
speed.x *= -1;
}
if(top() > 7.5f) {
speed.y *= -1;
}
if(bottom() < -7.5f) {
speed.y *= -1;
}
// Generate modelMatrix from position, rotation and scale
GenerateModelMatrix();
return true;
}
void Block::Render(Scene &scene) {
shader->Use();
// use camera
shader->SetMatrix(scene.camera->projectionMatrix, "ProjectionMatrix");
shader->SetMatrix(scene.camera->viewMatrix, "ViewMatrix");
// render mesh
shader->SetMatrix(modelMatrix, "ModelMatrix");
shader->SetTexture(texture, "Texture");
mesh->Render();
}
float Block::left() {
return position.x + 0.686f;
}
float Block::right() {
return position.x - 0.686f;
}
float Block::top() {
return position.y - 0.686f;
}
float Block::bottom() {
return position.y + 0.686f;
}
// shared resources
MeshPtr Block::mesh;
ShaderPtr Block::shader;
TexturePtr Block::texture;
<file_sep>/src/gl_scene/generator_block.h
#ifndef PPGSO_GENERATOR_BLOCK_H
#define PPGSO_GENERATOR_BLOCK_H
#include <random>
#include "object.h"
#include "scene.h"
#include "block.h"
// Example generator of objects
// Constructs a new object during Update and adds it into the scene
// Does not render anything
class Generator_Block : public Object {
public:
Generator_Block();
~Generator_Block();
bool Update(Scene &scene, float dt) override;
void Render(Scene &scene) override;
float time;
int spawnedBricks;
};
typedef std::shared_ptr< Generator_Block > GeneratorBlockPtr;
#endif //PPGSO_GENERATOR_BLOCK_H
<file_sep>/src/gl_scene/world.cpp
#include "world.h"
#include "scene.h"
#include "asteroid.h"
#include "projectile.h"
#include "explosion.h"
#include "object_frag.h"
#include "object_vert.h"
#include <GLFW/glfw3.h>
World::World() {
// Scale the default model
scale *= 3.0f;
// Initialize static resources if needed
if (!shader) shader = ShaderPtr(new Shader{object_vert, object_frag});
if (!texture) texture = TexturePtr(new Texture{"sphere.rgb", 256, 256});
if (!mesh) mesh = MeshPtr(new Mesh{shader, "world.obj"});
}
World::~World() {
}
bool World::Update(Scene &scene, float dt) {
GenerateModelMatrix();
return true;
}
void World::Render(Scene &scene) {
shader->Use();
// use camera
shader->SetMatrix(scene.camera->projectionMatrix, "ProjectionMatrix");
shader->SetMatrix(scene.camera->viewMatrix, "ViewMatrix");
// render mesh
shader->SetMatrix(modelMatrix, "ModelMatrix");
shader->SetTexture(texture, "Texture");
mesh->Render();
}
// shared resources
MeshPtr World::mesh;
ShaderPtr World::shader;
TexturePtr World::texture;<file_sep>/src/gl_scene/generator_block.cpp
#include "generator_block.h"
#include "block.h"
#include "brick.h"
bool Generator_Block::Update(Scene &scene, float dt) {
float offset = 0.0f;
// Spawn 5 brick
while(spawnedBricks < 5) {
auto brick = BrickPtr(new Brick());
brick->position = this->position;
brick->position.y += offset;
scene.objects.push_back(brick);
spawnedBricks++;
offset += 1.1f;
}
return true;
}
void Generator_Block::Render(Scene &scene) {
// Generator will not be rendered
}
Generator_Block::~Generator_Block() {
}
Generator_Block::Generator_Block() {
time = 0;
spawnedBricks = 0;
}
<file_sep>/src/gl_scene/block.h
#ifndef PPGSO_BLOCK_H
#define PPGSO_BLOCK_H
#include <memory>
#include "scene.h"
#include "object.h"
#include "mesh.h"
#include "texture.h"
#include "shader.h"
// Simple asteroid object
// This sphere object represents an instance of mesh geometry
// It initializes and loads all resources only once
// It will move down along the Y axis and self delete when reaching below -10
class Block : public Object {
public:
Block();
~Block();
// Implement object interface
bool Update(Scene &scene, float dt) override;
void Render(Scene &scene) override;
float left();
float right();
float top();
float bottom();
// Speed momentum
glm::vec3 speed;
private:
// Rotation momentum
glm::vec3 rotMomentum;
// Static resources (Shared between instances)
static MeshPtr mesh;
static ShaderPtr shader;
static TexturePtr texture;
};
typedef std::shared_ptr<Block> BlockPtr;
#endif //PPGSO_BLOCK_H
<file_sep>/src/gl_scene/brick.h
#ifndef PPGSO_BRICK_H
#define PPGSO_BRICK_H
#include <memory>
#include "scene.h"
#include "object.h"
#include "mesh.h"
#include "texture.h"
#include "shader.h"
// Simple asteroid object
// This sphere object represents an instance of mesh geometry
// It initializes and loads all resources only once
// It will move down along the Y axis and self delete when reaching below -10
class Brick : public Object {
public:
Brick();
~Brick();
// Implement object interface
bool Update(Scene &scene, float dt) override;
void Render(Scene &scene) override;
// Speed momentum
glm::vec3 speed;
int lives;
private:
bool animateTop;
bool animateBot;
glm::vec3 animTop;
glm::vec3 animBot;
// Static resources (Shared between instances)
static MeshPtr mesh;
static ShaderPtr shader;
float t;
TexturePtr texture;
};
typedef std::shared_ptr<Brick> BrickPtr;
#endif //PPGSO_BRICK_H
<file_sep>/src/gl_scene/player.cpp
#include "player.h"
#include "scene.h"
#include "asteroid.h"
#include "projectile.h"
#include "explosion.h"
#include "object_frag.h"
#include "object_vert.h"
#include "block.h"
#include <GLFW/glfw3.h>
Player::Player() {
// Rotate and scale model
rotation = glm::vec3(PI, 0.0f, 0.0f);
scale *= 1.5f;
// Initialize static resources if needed
if (!shader) shader = ShaderPtr(new Shader{object_vert, object_frag});
if (!texture) texture = TexturePtr(new Texture{"asteroid.rgb", 512, 512});
if (!mesh) mesh = MeshPtr(new Mesh{shader, "brick.obj"});
}
Player::~Player() {
}
bool Player::Update(Scene &scene, float dt) {
// Hit detection
for ( auto obj : scene.objects ) {
// Ignore self in scene
if (obj.get() == this)
continue;
// We only need to collide with ball
auto ball = std::dynamic_pointer_cast<Block>(obj);
if (!ball) continue;
if ((glm::distance(position.y, ball->position.y) < 0.886f ) &&
((glm::distance(position.x, ball->position.x) < 1.391f ))) {
// Change ball's speed
ball->speed.y *=-1.0f;
if(ball->position.x < position.x) {
ball->speed.x *=-1.0f;
}
else {
ball->speed.x *=1.0f;
}
}
}
// Keyboard controls
if(scene.keyboard[GLFW_KEY_LEFT]) {
position.x += 10 * dt;
} else if(scene.keyboard[GLFW_KEY_RIGHT]) {
position.x -= 10 * dt;
} else {
rotation.z = 0;
}
GenerateModelMatrix();
return true;
}
void Player::Render(Scene &scene) {
shader->Use();
// use camera
shader->SetMatrix(scene.camera->projectionMatrix, "ProjectionMatrix");
shader->SetMatrix(scene.camera->viewMatrix, "ViewMatrix");
// render mesh
shader->SetMatrix(modelMatrix, "ModelMatrix");
shader->SetTexture(texture, "Texture");
mesh->Render();
}
float Player::left() {
return position.x + 1.835f;
}
float Player::right() {
return position.x - 1.835f;
}
float Player::top() {
return position.y - 0.453f;
}
float Player::bottom() {
return position.y + 0.453f;
}
// shared resources
MeshPtr Player::mesh;
ShaderPtr Player::shader;
TexturePtr Player::texture; | a1a702edc7fec277d768f784e6ae36bdbc69c513 | [
"C++"
] | 8 | C++ | boing102/ppgso | aa4745926684da659c2139638fd9880844ab86c7 | e38c7d901a04e85763d786f36fad0a314b50dadd |
refs/heads/master | <file_sep><?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run() {
for ($i = 1; $i <= 10; $i++) {
DB::table('categories')->insert([
'category_name' => Str::random(8),
]);
}
for ($i = 1; $i <= 15; $i++) {
$post_name = Str::random(8);
DB::table('posts')->insert([
'post_slug' => $post_name,
'post_name' => $post_name,
'cat_id' => 1,
'post_image' => '2076158609.jpg',
'post_description' => Str::random(30),
'created_at' => date('Y-m-d'),
'updated_at' => date('Y-m-d'),
]);
}
}
}
<file_sep><?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ConfigServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
// echo "heres"; die;
$arr_constant['site_url'] = url('/')."/";
$arr_constant['admin_site_url'] = url('admin');
$arr_constant['root_path'] = base_path();
$arr_constant['public_root_path'] = public_path();
$arr_constant['public_url'] = url('public');
$arr_constant['application_root_path'] = app_path();
$arr_constant['asset_url'] = url('/');
// $arr_constant['asset_url'] = url('/');
$arr_constant['upload_root_path'] = public_path('uploads/');
$arr_constant['upload_url'] = url('public/uploads')."/";
$arr_constant['image_size'] = 10;
$arr_constant['image_mimes'] = "jpg,jpeg,png,gif";
$arr_constant['upload_url'] = url('uploads')."/";
$arr_constant['front_js_url'] = $arr_constant['asset_url']."/js";
$arr_constant['front_css_url'] = $arr_constant['asset_url']."/css";
$arr_constant['front_image_url'] = $arr_constant['asset_url']."/images";
$arr_constant['front_font_url'] = $arr_constant['asset_url']."/fonts";
$arr_constant['post_image_root']=$arr_constant['upload_root_path'].'post_images/';
$arr_constant['post_image_url']=$arr_constant['upload_url'].'post_images/';
$arr_constant['post_image_root_100X100'] =$arr_constant['post_image_root'].'100X100/thumb_';
$arr_constant['post_image_url_100X100']=$arr_constant['post_image_url'].'100X100/thumb_';
config($arr_constant);
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
//echo "heres2"; die;
//
}
}
<file_sep><?php
function arrayValueBlankNot($data){
$return = false;
foreach($data as $key=>$value)
{
if($value != "")
{
$return = true;
break;
}
}
return $return;
}
function varFromArray($arr_data){
$arr_new_array = array();
$tbl_name = key($arr_data);
foreach($arr_data[$tbl_name] as $var_name_parent=>$var_val_parent){
$arr_new_array[$var_name_parent] = $var_val_parent;
}
unset($arr_data[$tbl_name]);
foreach($arr_data as $var_name_parent=>$var_val_parent){
$arr_new_array[$var_name_parent] = $var_val_parent;
}
//echo "start<pre>"; print_r($arr_new_array); echo "end"; die;
//echo $user_name_derror_msg;
//extract($arr_data);
return $arr_new_array;
}
function doUpload(&$data,$model_name="",$arr_files)
{
//echo "<pre> $model_name"; print_r($data); die;
//echo "<pre>"; print_r($arr_files); die;
if($model_name =="" || is_array($model_name))
{
$arr_extra = $model_name;
$model_name = key($data);
}
if(!empty($arr_files)){
//var_dump(arrayValueBlankNot($arr_files[$model_name]["name"])); die;
if(arrayValueBlankNot($arr_files[$model_name]["name"]))
{
//echo "<pre>"; print_r($arr_files[$model_name]["name"]);
foreach($arr_files[$model_name]["name"] as $key=>$value)
{
if($value!="")
{
//echo $key; die;
//$arr_pathNfield = explode("-",$key);
//$folder_name = $arr_pathNfield[0];
//$field_name = $arr_pathNfield[1];
$folder_name = $data[$model_name][$key."_image_root"];
$field_name = $key;
//echo $key;
//echo $folder_name; die;
$source_path = $arr_files[$model_name]["tmp_name"][$key];
$org_filename = basename($value);
$extension = pathinfo($org_filename, PATHINFO_EXTENSION);
$new_filename = rand().'.'.$extension;
$org_dest_path = $folder_name.$new_filename;
//echo $source_path."==".$org_dest_path;
$is_upload = move_uploaded_file($source_path,$org_dest_path);
//var_dump($is_upload); die;
//echo "<pre>"; print_r($data[$model_name]); die;
if($is_upload)
{
if(!empty($data[$model_name]["create_thumb"]))
{
foreach($data[$model_name]["create_thumb"][$field_name] as $upload_folder=>$size)
{
$thumb_destination = $upload_folder.$new_filename;
$arr_thumb_h_w = explode(",",$size);
$thumb_w = $arr_thumb_h_w[0];
$thumb_h = $arr_thumb_h_w[1];
//echo $org_dest_path.">>".$thumb_destination.">>".$thumb_w.">>".$thumb_h; die;
createthumb($org_dest_path,$thumb_destination,$thumb_w,$thumb_h);
}
}
$data[$model_name][$field_name] = $new_filename;
//echo $key; die;
//echo $field_name.">>".$new_filename."<br>";
//echo "<pre>"; print_r($data[$model_name][$field_name]); die;
if(!empty($data[$model_name]["delete_image"]))
{
if(!empty($data[$model_name]["create_thumb"][$field_name]))
{
foreach($data[$model_name]["create_thumb"][$field_name] as $upload_folder=>$size)
{
//echo $upload_folder."".$data[$model_name]["delete_image"]["old_".$field_name]; die;
if(isset($data[$model_name]["delete_image"]["old_".$field_name]) && file_exists($upload_folder.$data[$model_name]["delete_image"]["old_".$field_name])){
unlink($upload_folder.$data[$model_name]["delete_image"]["old_".$field_name]);
}
}
}
if(isset($data[$model_name]["delete_image"]["old_".$field_name]) && file_exists($folder_name."/".$data[$model_name]["delete_image"]["old_".$field_name])){
unlink($folder_name."/".$data[$model_name]["delete_image"]["old_".$field_name]);
}
}
//unset($data[$model_name][$key]);
unset($data[$model_name][$key."_image_root"]);
}
}else{
unset($data[$model_name][$key."_image_root"]);
}
}
}else{
foreach($arr_files[$model_name]["name"] as $key=>$value){
unset($data[$model_name][$key]);
unset($data[$model_name][$key."_image_root"]);
}
}
}
if(!empty($data[$model_name]["delete_image"]))
{
unset($data[$model_name]["delete_image"]);
}
if(!empty($data[$model_name]["create_thumb"]))
{
unset($data[$model_name]["create_thumb"]);
}
// echo "<pre>"; print_r($data); die;
}
function arrange_file_validation($arr_data,$arr_files,$tbl_name,&$rules){
if(!empty($arr_files)){
foreach($arr_files[$tbl_name]["name"] as $field_name=>$value)
{
if($value != "" || $arr_data[$tbl_name]["delete_image"]["old_".$field_name] != "")
{
$field_validation = $rules[$tbl_name.".".$field_name];
if(strpos($field_validation,"required") !== false){
$remove_required_validation = str_replace("required|","",$field_validation);
$rules[$tbl_name.".".$field_name] = $remove_required_validation;
}
}
}
}
}
function createthumb($name,$filename,$new_w,$new_h)
{
/*$system=strtolower(end(explode(".",$name)));
if (preg_match("/jpg|jpeg/",$system)){$src_img=imagecreatefromjpeg($name);}
if (preg_match("/png/",$system)){$src_img=imagecreatefrompng($name);}
if (preg_match("/gif/",$system)){$src_img=imagecreatefromgif($name);}*/
$system=explode(".",$name);
$count = count($system);
if($count>0){
$ext = strtolower($system[$count-1]);
}else{
$ext = "";
}
$src_img = "";
if (preg_match("/jpg|jpeg/",$system[1])){
$src_img=imagecreatefromjpeg($name);
}else if (preg_match("/png/",$system[1])){
$src_img=imagecreatefrompng($name);
}else if (preg_match("/gif/",$system[1])){
$src_img=imagecreatefromgif($name);
}else if (preg_match("/bmp/",$system[1])){
$src_img=imagecreatefromwbmp($name);
}else if($ext=="jpg" || $ext=="jpeg" || $ext=="JPEG" || $ext=="JPG"){
$src_img=imagecreatefromjpeg($name);
}else if($ext=="gif" || $ext=="GIF"){
$src_img=imagecreatefromgif($name);
}else if($ext=="png" || $ext=="PNG"){
$src_img=imagecreatefrompng($name);
}else if($ext=="bmp" || $ext=="BMP"){
$src_img=ImageCreateFromBMP($name);
}else{
$src_img=imagecreatefromjpeg($name);
}
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);
if ($old_x > $old_y)
{
$thumb_w=$new_w;
$thumb_h=$old_y*($new_h/$old_x);
}
if ($old_x < $old_y)
{
$thumb_w=$old_x*($new_w/$old_y);
$thumb_h=$new_h;
}
if ($old_x == $old_y)
{
$thumb_w=$new_w;
$thumb_h=$new_h;
}
//$thumb_w=$new_w;
//$thumb_h=$new_h;
$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
if (preg_match("/png/",$system[1]))
{
imagepng($dst_img,$filename);
}
else
{
imagejpeg($dst_img,$filename);
}
imagedestroy($dst_img);
imagedestroy($src_img);
}
/**
it will be called from the createthumb function
*/
/*
function ImageCreateFromBMP($filename)
{
//Ouverture du fichier en mode binaire
if (! $f1 = fopen($filename,"rb")) return FALSE;
//1 : Chargement des enttes FICHIER
$FILE = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1,14));
if ($FILE['file_type'] != 19778) return FALSE;
//2 : Chargement des enttes BMP
$BMP = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel'.
'/Vcompression/Vsize_bitmap/Vhoriz_resolution'.
'/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1,40));
$BMP['colors'] = pow(2,$BMP['bits_per_pixel']);
if ($BMP['size_bitmap'] == 0) $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset'];
$BMP['bytes_per_pixel'] = $BMP['bits_per_pixel']/8;
$BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel']);
$BMP['decal'] = ($BMP['width']*$BMP['bytes_per_pixel']/4);
$BMP['decal'] -= floor($BMP['width']*$BMP['bytes_per_pixel']/4);
$BMP['decal'] = 4-(4*$BMP['decal']);
if ($BMP['decal'] == 4) $BMP['decal'] = 0;
//3 : Chargement des couleurs de la palette
$PALETTE = array();
if ($BMP['colors'] < 16777216)
{
$PALETTE = unpack('V'.$BMP['colors'], fread($f1,$BMP['colors']*4));
}
//4 : Cration de l'image
$IMG = fread($f1,$BMP['size_bitmap']);
$VIDE = chr(0);
$res = imagecreatetruecolor($BMP['width'],$BMP['height']);
$P = 0;
$Y = $BMP['height']-1;
while ($Y >= 0)
{
$X=0;
while ($X < $BMP['width'])
{
if ($BMP['bits_per_pixel'] == 24)
$COLOR = unpack("V",substr($IMG,$P,3).$VIDE);
elseif ($BMP['bits_per_pixel'] == 16)
{
$COLOR = unpack("n",substr($IMG,$P,2));
$COLOR[1] = $PALETTE[$COLOR[1]+1];
}
elseif ($BMP['bits_per_pixel'] == 8)
{
$COLOR = unpack("n",$VIDE.substr($IMG,$P,1));
$COLOR[1] = $PALETTE[$COLOR[1]+1];
}
elseif ($BMP['bits_per_pixel'] == 4)
{
$COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
if (($P*2)%2 == 0) $COLOR[1] = ($COLOR[1] >> 4) ; else $COLOR[1] = ($COLOR[1] & 0x0F);
$COLOR[1] = $PALETTE[$COLOR[1]+1];
}
elseif ($BMP['bits_per_pixel'] == 1)
{
$COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
if (($P*8)%8 == 0) $COLOR[1] = $COLOR[1] >>7;
elseif (($P*8)%8 == 1) $COLOR[1] = ($COLOR[1] & 0x40)>>6;
elseif (($P*8)%8 == 2) $COLOR[1] = ($COLOR[1] & 0x20)>>5;
elseif (($P*8)%8 == 3) $COLOR[1] = ($COLOR[1] & 0x10)>>4;
elseif (($P*8)%8 == 4) $COLOR[1] = ($COLOR[1] & 0x8)>>3;
elseif (($P*8)%8 == 5) $COLOR[1] = ($COLOR[1] & 0x4)>>2;
elseif (($P*8)%8 == 6) $COLOR[1] = ($COLOR[1] & 0x2)>>1;
elseif (($P*8)%8 == 7) $COLOR[1] = ($COLOR[1] & 0x1);
$COLOR[1] = $PALETTE[$COLOR[1]+1];
}
else
return FALSE;
imagesetpixel($res,$X,$Y,$COLOR[1]);
$X++;
$P += $BMP['bytes_per_pixel'];
}
$Y--;
$P+=$BMP['decal'];
}
//Fermeture du fichier
fclose($f1);
return $res;
}
*/
function get_file_button_control_info($arr_files,$field_name,$file_key){
foreach($arr_files[$file_key] as $file_button_control_name=>$value){
if(strpos($file_button_control_name,$field_name) != false){
return $value;
}
}
}
function multipleRadioButtonStaticList($settings,$selected_checkbox='')
{
extract($settings);
if(!is_array($selected_checkbox)){
$arr_selected = explode(",",$selected_checkbox);
if(count($arr_selected) > 0){
$selected_checkbox = $arr_selected;
}
}
$i=1;
foreach($data as $value=>$caption)
{
if(is_array($selected_checkbox))
{
$checked = "";
if(in_array($value,$selected_checkbox))
{
$checked = "checked='checked'";
}
}
if($i >= 2){
$control_class = "";
}
$class_str = "chk_".$control_id;
if($control_class!=""){
$class_str .= " ".$control_class;
}
if(!isset($extra)){$extra = "";}
if(($i/$per_line)== 0){?>
<tr>
<?php }
if(!isset($extra)){ $extra = "";}
?>
<td>
<input type="radio" class="<?php echo $class_str; ?>" name="<?php echo $control_name; ?>" id="<?php echo $control_id;?>" value="<?php echo $value; ?>" <?php echo $checked; ?> <?php echo $extra; ?> >
<span class="chk_title"><?php echo $caption; ?></span>
</td>
<?php if(($i%$per_line)== 0){?>
</tr>
<?php } ?>
<?php $i++;
}
}
function objToArray($arr_data){
$arr_data = collect($arr_data)->map(function($x){ return (array) $x; })->toArray();
return $arr_data;
}
?>
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use DB;
use Request;
use Request as Input;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
function getDBSelectListSingle($table_name,$arr_select_field="*",$arr_where=array(),$order_by=""){
$query = DB::table($table_name)
->select($arr_select_field)
->where($arr_where);
if($order_by !=""){
$query->orderByRaw($order_by);
}
$arr_data = $query->get();
$arr_data = objToArray($arr_data);
return $arr_data[0];
}
function getDBSelectPluckList($table_name,$arr_select_field="*",$arr_where=array(),$order_by=""){
$query = DB::table($table_name)
->where($arr_where);
if($order_by !=""){
$query->orderByRaw($order_by);
}
$arr_data = $query->pluck($arr_select_field[1],$arr_select_field[0])->toArray();
//echo "<pre>"; print_r($arr_data); die;
return $arr_data;
}
}
<file_sep>
function emailInvalid(s)
{
if(!(s.match(/^[\w]+([_|\.-][\w]{1,})*@[\w]{1,}([_|-|\.-][\w]{1,})*\.([a-z]{2,4})$/i)) ){
return false;
}
else{
return true;
}
}
function check_single_file_required(obj)
{
//alert(obj.type);
if(obj.type == "file")
{
var file_hdn_id = "old_"+obj.id;
file_hdn_obj_val = document.getElementById(file_hdn_id);
if(obj.value=="" && (file_hdn_obj_val == null || file_hdn_obj_val == ""))
{
return true;
}else{
return false;
}
}
else
{
return false;
}
}
function check_radio_or_checkbox_required(obj)
{
if(obj.type == "checkbox" || obj.type == "radio")
{
if(obj.type == "checkbox")
{
var r = document.getElementsByClassName("chk_"+obj.id);
//alert(r);
}else if(obj.type == "radio"){
var r = document.getElementsByName(obj.name);
}
var c = -1
for(var i=0; i < r.length; i++){
if(obj.id == "active"){
}
if(r[i].checked) {
c = i;
}
}
if (c == -1)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
function onlyNumber(event)
{
var key = window.event ? event.keyCode : event.which;
if (event.keyCode == 8 || event.keyCode == 46
|| event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 9) {
return true;
}
else if ( key < 48 || key > 57 ) {
return false;
}
else return true;
return true;
}
function UserValidation(){
var is_form_have_to_submit = true;
var obj_first_name = $("#first_name");
var obj_last_name = $("#last_name");
var obj_email = $("#email");
var obj_password = $("#<PASSWORD>");
var obj_password_confirmation = $("#password_confirmation");
var obj_gender = $("#gender");
var obj_telephone = $("#telephone");
var obj_profile_picutre = $("#profile_picutre");
var obj_update_id = $("#update_id");
var obj_first_name_derror_msg = $("#first_name_derror_msg");
var obj_last_name_derror_msg = $("#last_name_derror_msg");
var obj_email_derror_msg = $("#email_derror_msg");
var obj_password_derror_msg = $("#password_<PASSWORD>");
var obj_password_confirmation_derror_msg = $("#password_confirmation_der<PASSWORD>");
var obj_gender_derror_msg = $("#gender_derror_msg");
var obj_telephone_derror_msg = $("#telephone_derror_msg");
var obj_profile_picutre_derror_msg = $("#profile_picutre_derror_msg");
obj_first_name_derror_msg.html("");
obj_last_name_derror_msg.html("");
obj_email_derror_msg.html("");
obj_password_derror_msg.html("");
obj_password_confirmation_derror_msg.html("");
obj_gender_derror_msg.html("");
obj_telephone_derror_msg.html("");
obj_profile_picutre_derror_msg.html("");
if(obj_first_name.val() == ""){
obj_first_name_derror_msg.html("Please Enter First Name");
is_form_have_to_submit = false;
}
if(obj_last_name.val() == ""){
obj_last_name_derror_msg.html("Please Enter Last Name");
is_form_have_to_submit = false;
}
if(obj_email.val() == ""){
obj_email_derror_msg.html("Please Enter Email");
is_form_have_to_submit = false;
}
if(!emailInvalid(obj_email.val()) && obj_email.val() != ""){
obj_email_derror_msg.html("Please Enter Valid Email");
is_form_have_to_submit = false;
}
if(obj_update_id.val() == ""){
if(obj_password.val() == ""){
obj_password_derror_msg.html("Please Enter Password");
is_form_have_to_submit = false;
}
if(obj_password_confirmation.val() == ""){
obj_password_confirmation_derror_msg.html("Plese Enter Confirm Password");
is_form_have_to_submit = false;
}
if(obj_password.val() != obj_password_confirmation.val()){
obj_password_derror_msg.html("Password and Confirm passoword should be matched");
is_form_have_to_submit = false;
}
if(obj_password.val().length < 5 && obj_password.val() != ""){
obj_password_derror_msg.html("Password must be minimum of 5 characters");
is_form_have_to_submit = false;
}
}
if(check_radio_or_checkbox_required(obj_gender.get(0))){
obj_gender_derror_msg.html("Please Select Gender");
is_form_have_to_submit = false;
}
if(obj_telephone.val() == ""){
obj_telephone_derror_msg.html("Please Enter Telephone");
is_form_have_to_submit = false;
}
if(obj_telephone.val().length < 10 && obj_telephone.val() != ""){
obj_telephone_derror_msg.html("Telephone must be minimum of 10 characters");
is_form_have_to_submit = false;
}
if(obj_telephone.val().length > 10 && obj_telephone.val() != ""){
obj_telephone_derror_msg.html("Telephone must be maximum of 10 characters");
is_form_have_to_submit = false;
}
if(check_single_file_required(obj_profile_picutre.get(0))){
obj_profile_picutre_derror_msg.html("Please Select Profile Picutre");
is_form_have_to_submit = false;
}
return is_form_have_to_submit;
}
<file_sep>/*
==================================================== UPLOAD controll validation ===================================================================
*/
function addmore(ctrl_name)
{
str_ctrl_order = "";
if(document.getElementById("hdn_img_order_"+ctrl_name).value == "yes")
{
str_ctrl_order = '<input type="text" class="gallery_order" name="img_order[]" id="img_order[]"> ';
}
var hdn_validation_method = document.getElementById("hdn_validation_method").value;
var div_obj = document.getElementsByClassName(ctrl_name+"_cnt_lst_div");
current = 0;
if(div_obj.length > 0)
{
current = giveLastId(div_obj);
}
counter=current+1;
str_ctrl_active = "";
if(document.getElementById("hdn_img_active_"+ctrl_name).value == "yes")
{
str_ctrl_active = '<input type="checkbox" class="cls_active_'+ctrl_name+'" name="img_active['+ctrl_name+']['+counter+']" id="img_active[]"><input type="hidden" class="cls_active" name="hdn_img_active['+ctrl_name+']['+counter+']" id="hdn_img_active[]"/> ';
}
str = '<div class="gallery_raw '+ctrl_name+'_cnt_lst_div" id="'+ctrl_name+"_"+counter+'"><div class="gallery_col_file"><input type="file" '+hdn_validation_method+' value="" class="gallery_file" id="'+ctrl_name+counter+'" name="'+ctrl_name+'[]"></div><div class="gallery_col_order">'+str_ctrl_order+'</div><div class="gallery_col_active">'+str_ctrl_active+'</div><div class="gallery_col_delete"><a href="javascript:void(0)" onClick=javascript:deleteGalleryStaticImage("'+counter+'","'+ctrl_name+'")><img src="images/fileclose.png" width="20" height="20" border="0" alt="Remove" title="Remove"></a></div><span id="msg_'+ctrl_name+counter+'" class="gallery_status_error"></span></div>';
// document.getElementById("counter").value = counter;
if(current == 0)
{
document.getElementById(ctrl_name+"_"+counter).innerHTML = str;
}
else
{
document.getElementById(ctrl_name+"_"+current).insertAdjacentHTML("afterEnd",str);
}
}
function giveLastId(div_obj)
{
for(i=0;i<div_obj.length;i++)
{
last_div_id = div_obj[i].id;
}
arr = last_div_id.split("_");
index = arr.length-1;
last_id = arr[index];
return parseInt(last_id);
}
function changeStatus_backup(request_url,tbl_name,update_field_name,status,where_field_name,where_field_value,checked_on,msg_id,additional_where){
extra_where = "";
if(typeof additional_where !='undefined'){
extra_where = additional_where;
}
/*
checked on is for Y OR 1 vlaue
*/
if(typeof checked_on =='undefined' || checked_on == 1){
if(status == true){
str_status = 1;
}else{
str_status = 0;
}
}else{
if(status == true){
str_status = "Y";
}else{
str_status = "N";
}
}
if(checked_on =='checked_from_cmb'){
str_status = status;
}
//msg_id= "#msg_chk_status_change_"+pk_id;
var post_data =
{
"mode": "change_status",
"tbl_name": tbl_name,
"update_field_name": update_field_name,
"update_field_value": str_status,
"where_field_name": where_field_name,
"where_field_value": where_field_value,
"additional_where": extra_where
}
$.post(request_url, post_data, function(response){
if(response.success == 1) {
$("#"+msg_id).addClass('cls_success');
$("#"+msg_id).removeClass('cls_error');
$("#"+msg_id).html(response.message).show().delay(300).fadeOut('slow', function() {
$("#"+msg_id).html("").show();
});
}else{
$("#"+msg_id).removeClass('cls_success');
$("#"+msg_id).addClass('cls_error');
$("#"+msg_id).html(response.errors);
}
},'json');
}
function changeStatus(request_url,status,where_field_value,checked_on,msg_id,additional_where){
extra_where = "";
if(typeof additional_where !='undefined'){
extra_where = additional_where;
}
/*
checked on is for Y OR 1 vlaue
*/
if(typeof checked_on =='undefined' || checked_on == 1){
if(status == true){
str_status = 1;
}else{
str_status = 0;
}
}else{
if(status == true){
str_status = "Y";
}else{
str_status = "N";
}
}
if(checked_on =='checked_from_cmb'){
str_status = status;
}
//msg_id= "#msg_chk_status_change_"+pk_id;
var post_data =
{
"mode": "change_status",
"tbl_name": tbl_name,
"update_field_value": str_status,
"where_field_value": where_field_value,
"additional_where": extra_where
}
$.post(request_url, post_data, function(response){
if(response.success == 1) {
$("#"+msg_id).addClass('cls_success');
$("#"+msg_id).removeClass('cls_error');
$("#"+msg_id).html(response.message).show().delay(300).fadeOut('slow', function() {
$("#"+msg_id).html("").show();
});
}else{
$("#"+msg_id).removeClass('cls_success');
$("#"+msg_id).addClass('cls_error');
$("#"+msg_id).html(response.errors);
}
},'json');
}
function deleteImage_backup(request_url,tbl_name,delete_image_name,update_field_name,where_field_name,where_field_value,str_delete_image_path,msg_id)
{
/*
var did = $("#confirm_"+where_field_value).data("id");
var type = $("#confirm_"+where_field_value).data("type");
var msg = $("#confirm_"+where_field_value).data("msg");
var specialid = $("#confirm_"+where_field_value).data("specialid");
var clicked = function(){
$.fallr('hide');
*/
var post_data =
{
"mode": "delete_update_image",
"tbl_name": tbl_name,
"delete_image_name" : delete_image_name,
"update_field_name" : update_field_name,
"update_field_value" : '',
"where_field_name" : where_field_name,
"where_field_value": where_field_value,
"str_delete_image_path": str_delete_image_path,
}
//post_data = $(frmid).serialize();
$.post(request_url, post_data, function(response){
if(response.success == 1) {
$("#"+msg_id).addClass('cls_success');
$("#"+msg_id).removeClass('cls_error');
$("#hdn_"+ctrl_name).val('');
$("#"+msg_id).html(response.message).show().delay(300).fadeOut('slow', function() {
$("#"+msg_id).html("").show();
});
}else{
$("#"+msg_id).removeClass('cls_success');
$("#"+msg_id).addClass('cls_error');
$("#"+msg_id).html(response.errors);
}
},'json');
/* };
$.fallr('show', {
buttons : {
button1 : {text: 'Yes', danger: true, onclick: clicked},
button2 : {text: 'Cancel', onclick: function(){$.fallr('hide')}}
},
content : msg,
icon : 'error'
});
*/
}
function deleteImage(request_url,where_field_value,str_delete_image_path,msg_id,ctrl_name)
{
var post_data =
{
"where_field_value": where_field_value,
"str_delete_image_path": str_delete_image_path,
}
//post_data = $(frmid).serialize();
$.post(request_url, post_data, function(response){
if(response.success == 1) {
$("#"+msg_id).addClass('cls_success');
$("#"+msg_id).removeClass('cls_error');
$("#hdn_"+ctrl_name).val('');
$("#"+msg_id).html(response.message).show().delay(300).fadeOut('slow', function() {
$("#"+msg_id).html("").show();
});
}else{
$("#"+msg_id).removeClass('cls_success');
$("#"+msg_id).addClass('cls_error');
$("#"+msg_id).html(response.errors);
}
},'json');
}
function deleteGalleryStaticImage(counter_id,control_name)
{
div_obj = document.getElementById(control_name+"_"+counter_id);
div_obj.innerHTML = "";
if(document.getElementsByClassName("cnt_lst_div").length != 1)
{
div_obj.counter_id = "";
div_obj.className = "";
}
}
function deleteGalleryImage(request_url,tbl_name,delete_image_name,where_field_name,where_field_value,str_delete_image_path,counter_id,control_name,msg_id)
{
/*
var did = $("#confirm_"+where_field_value).data("id");
var type = $("#confirm_"+where_field_value).data("type");
var msg = $("#confirm_"+where_field_value).data("msg");
var specialid = $("#confirm_"+where_field_value).data("specialid");
var clicked = function(){
$.fallr('hide');
*/
var post_data =
{
"mode": "delete_gallery_image",
"tbl_name": tbl_name,
"delete_image_name" : delete_image_name,
"where_field_name": where_field_name,
"where_field_value": where_field_value,
"str_delete_image_path": str_delete_image_path,
}
//post_data = $(frmid).serialize();
$.post(request_url, post_data, function(response){
if(response.success == 1) {
$("#"+msg_id).addClass('cls_success');
$("#"+msg_id).removeClass('cls_error');
$("#"+msg_id).html(response.message).show().delay(300).fadeOut('slow', function() {
$("#"+msg_id).html("").show();
div_obj = document.getElementById(control_name+"_"+counter_id);
div_obj.innerHTML = "";
if(document.getElementsByClassName("cnt_lst_div").length != 1)
{
div_obj.counter_id = "";
div_obj.className = "";
}
});
hdn_dbrow_cnt = document.getElementById("hdn_dbrow_cnt_"+control_name).value ;
document.getElementById("hdn_dbrow_cnt_"+control_name).value = parseInt(hdn_dbrow_cnt)-1;
}else{
$("#"+msg_id).removeClass('cls_success');
$("#"+msg_id).addClass('cls_error');
$("#"+msg_id).html(response.errors);
}
},'json');
/* };
$.fallr('show', {
buttons : {
button1 : {text: 'Yes', danger: true, onclick: clicked},
button2 : {text: 'Cancel', onclick: function(){$.fallr('hide')}}
},
content : msg,
icon : 'error'
});
*/
}
function deleteRec(request_url,tbl_name,where_field_name,where_field_value,redirect_url)
{
var did = $("#confirm_"+where_field_value).data("id");
var type = $("#confirm_"+where_field_value).data("type");
var msg = $("#confirm_"+where_field_value).data("msg");
var specialid = $("#confirm_"+where_field_value).data("specialid");
var clicked = function(){
$.fallr('hide');
var post_data =
{
"tbl_name": tbl_name,
"where_field_name": where_field_name,
"where_field_value": where_field_value,
"delete_mode": "delete"
}
//post_data = $(frmid).serialize();
$.post(request_url, post_data, function(response){
if(response == 1) {
location.href=redirect_url;
}
});
};
$.fallr('show', {
buttons : {
button1 : {text: 'Yes', danger: true, onclick: clicked},
button2 : {text: 'Cancel', onclick: function(){$.fallr('hide')}}
},
content : msg,
icon : 'error'
});
}
function updateOrder(request_url,tbl_name,order_field,pk_field_name,frm_id,additional_where) {
extra_where = "";
if(typeof additional_where !='undefined'){
extra_where = "&additional_where="+additional_where;
}
form_data = $("#"+frm_id).serialize();
post_data = form_data+"&tbl_name="+tbl_name+"&order_field="+order_field+"&pk_field_name="+pk_field_name+"&order_status=1"+extra_where;
//alert(additional_where);
$.post(request_url, post_data, function(response){
if(response.success == 1) {
$("#msg_update_order_status_change").html(response.message).show().delay(300).fadeOut();
$("#msg_update_order_status_change").addClass('success_msg');
}else{
$("#msg_update_order_status_change").html(response.errors);
$("#msg_update_order_status_change").addClass('errr_msg');
}
},'json');
}
function get_ajax_dropdown(request_url,response_id,tbl_name,value_field,caption_field,where_field_name,where_field_value,extra_where){
var post_data =
{
"mode": "ajax_dropdown",
"tbl_name": tbl_name,
"value_field": value_field,
"caption_field": caption_field,
"where_field_name": where_field_name,
"where_field_value": where_field_value,
"additional_where": extra_where
}
$.post(request_url, post_data, function(response){
if(response.success == 1) {
$("#"+response_id).html(response.dropdown_options_html);
}else{
$("#"+response_id).addClass('errr_msg');
$("#"+response_id).append(response.errors);
}
},'json');
}<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Session;
use Redirect;
use DB;
use Request as Input;
use Datatables;
use App\Post;
use Auth;
class PostController extends Controller {
public function __construct(){
//parent::__construct();
}
public function index(Request $request) {
$query = Post::query();
if($request->get('created_date') != ""){
$query->where('created_at','=',date('Y-m-d',strtotime($request->get('created_date'))));
}
return Datatables::of($query)
->addColumn('post_image', function ($row) {
return '<img src="'.config('post_image_url_100X100').$row->post_image.'" border="0" width="40" class="img-rounded" align="center" />';
})->addColumn('created_at', function ($row) {
return date('d-M-Y',strtotime($row->created_at));
})->addColumn('action', function ($row) {
return '<a href="'.route('post_edit',[$row->id]).'" class="btn btn-primary">Edit</a>';
})->rawColumns(['action' => 'action','post_image' => 'post_image'])
->make(true);
}
public function list() {
return view('post/list');
}
public function add(Request $request){
$arr_form_data = Input::all();
$arr_form_data = empty($arr_form_data) ? array("post"=>array()) : $arr_form_data;
extract($arr_form_data["post"]);
$cat_id = isset($cat_id) ? $cat_id : "";
$arr_form_data["selected_cat_id"] = $cat_id;
$arr_form_data["arr_cat_id_list"] = $this->getDBSelectPluckList("categories",["id","category_name"]);
if($request->isMethod("get")) {
return view("post.add")->with("arr_form_data", $arr_form_data);
}
$arr_validation = $this->PostValidation();
$validator = validator::make($arr_form_data, $arr_validation["rule"], $arr_validation["messages"]);
if($validator->fails()) {
return view("post.add")->withErrors($validator)->with("arr_form_data", $arr_form_data);
}
$arr_form_data["post"]["create_thumb"]["post_image"][config('post_image_root_100X100')] ="100,100";
$arr_form_data["post"]["post_image_image_root"] = config("post_image_root");
doUpload($arr_form_data,"post",$_FILES);
$arr_form_data["post"]["user_id"] = auth()->user()->id;
$post = Post::create($arr_form_data["post"]);
$arr_slug["post_slug"] = str_replace(" ","-",strtolower($arr_form_data["post"]["post_name"]."-".$post->id));
$result = Post::where("id",$post->id)->update($arr_slug);
if($post->id > 0){
Session::flash("success", "Post is successfully added");
return redirect::route("home");
}
}
public function edit(Request $request){
$arr_form_data = Input::all();
$update_id = $request->id;
if(empty($arr_form_data)){
$arr_form_data["post"] = $this->getDBSelectListSingle("posts","*",array("id"=>$update_id));
extract($arr_form_data["post"]);
}
extract($arr_form_data["post"]);
$cat_id = isset($cat_id) ? $cat_id : "";
$arr_form_data["selected_cat_id"] = $cat_id;
$arr_form_data["arr_cat_id_list"] = $this->getDBSelectPluckList("categories",["id","category_name"]);
$arr_form_data["update_id"] = $update_id;
if($request->isMethod("get")) {
return view("post.add",compact("arr_form_data"));
}
$arr_validation = $this->PostValidation($update_id);
$validator = validator::make($arr_form_data, $arr_validation["rule"], $arr_validation["messages"]);
if($validator->fails()) {
return view("post.add")->withErrors($validator)->with("arr_form_data", $arr_form_data);
}
$arr_form_data["post"]["create_thumb"]["post_image"][config('post_image_root_100X100')] ="100,100";
$arr_form_data["post"]["post_image_image_root"] = config("post_image_root");
doUpload($arr_form_data,"post",$_FILES);
$arr_form_data["post"]["user_id"] = auth()->user()->id;
$arr_form_data["post"]["post_slug"] = str_replace(" ","-",strtolower($arr_form_data["post"]["post_name"]."-".$update_id));
$result = Post::where("id",$update_id)->update($arr_form_data["post"]);
Session::flash("success", "Post is successfully updated");
return redirect::route("home");
}
function PostValidation($update_id = NULL){
$arr_post_data = Input::all();
$arr_form_data = $arr_post_data["post"];
$arr_validation["rule"] = array(
"post.post_name" =>"required|unique:posts,post_name,$update_id,id",
"post.cat_id" =>"required",
"post.post_image" =>(empty($arr_post_data["post_image"])) ? "required|mimes:".config("image_mimes") : "",
"post.post_description" =>"required"
);
$arr_validation["messages"] = array(
"post.post_name.required" => "Please Enter Post Name",
"post.post_name.unique" => "Post Name is allready exist",
"post.cat_id.required" => "Please Select Category Name",
"post.post_image.required" => "Please Select Post Image",
"post.post_image.mimes" => "You are only allowed to upload ".config("image_mimes")." files only",
"post.post_description.required" => "Please Enter Post Description"
);
return $arr_validation;
}
} | 3e5cbda949d43388e51e2aa49e216a14c531cf69 | [
"JavaScript",
"PHP"
] | 7 | PHP | kmkhunt/webMobTech_kmk | e24337f7f6ad77f83a3c3469844b3737940c807a | f0125c400a9d0ce68e17e3c638da510765638fc6 |
refs/heads/master | <repo_name>frankbeirne/postalCodeDistance<file_sep>/README.md
# postalCodeDistance
Using google distance API to calculate drive time and distance from one point to many
<file_sep>/distanceFromPoint.R
library(gmapsdistance)
#reading in csv with postal codes, description, weekend flad and lat/lon
raw<-read.csv("data/raw.csv")
#API key named R distance
set.api.key("############")
distances<-data.frame("pc"=character(109), "dow"=integer(109), "time (s)"=integer(109), "distance (m)"=integer(109))
distances$PC<-as.character(distances$PC)
for (i in 1:length(raw$WeekEnd[raw$WeekEnd<3])) {
result<-gmapsdistance(
origin= paste0(raw$Lat[i],"+", raw$Lon[i]),
destination= paste0(raw$Lat[raw$Description == "Point1"], "+", raw$Lon[raw$Description == "Point1"]),
mode = "driving")
distances$PC[i]<-as.character(raw$PC[i])
distances$DOW[i]<-raw$WeekEnd[i]
distances$time[i]<-result$Time
distances$distance[i]<-result$Distance
}
write.csv(distances, "distanceFromPoint.csv")
version
| 597c39c7698fa8dcd8aaa2858e573b9f8d54508d | [
"Markdown",
"R"
] | 2 | Markdown | frankbeirne/postalCodeDistance | 47f68011fcf87e93fa03d0bc899f5efff8144f56 | 4852ffce1980786cb40dbdb9bc288c1b0ac9b987 |
refs/heads/master | <repo_name>sth/libpqxx<file_sep>/include/pqxx/internal/statement_parameters.hxx
/** Common implementation for statement parameter lists.
*
* These are used for both prepared statements and parameterized statements.
*
* DO NOT INCLUDE THIS FILE DIRECTLY. Other headers include it for you.
*
* Copyright (c) 2009-2017, <NAME>.
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*/
#ifndef PQXX_H_STATEMENT_PARAMETER
#define PQXX_H_STATEMENT_PARAMETER
#include "pqxx/compiler-public.hxx"
#include "pqxx/compiler-internal-pre.hxx"
#include <cstring>
#include <string>
#include <vector>
#if defined(PQXX_HAVE_OPTIONAL)
#include <optional>
#endif
#if defined(PQXX_HAVE_EXP_OPTIONAL)
#include <experimental/optional>
#endif
#include "pqxx/binarystring"
#include "pqxx/strconv"
#include "pqxx/util"
namespace pqxx
{
namespace internal
{
class PQXX_LIBEXPORT statement_parameters
{
protected:
statement_parameters() =default;
statement_parameters &operator=(const statement_parameters &) =delete;
void add_param() { this->add_checked_param("", false, false); }
template<typename T> void add_param(const T &v, bool nonnull)
{
nonnull = (nonnull && !pqxx::string_traits<T>::is_null(v));
this->add_checked_param(
(nonnull ? pqxx::to_string(v) : ""),
nonnull,
false);
}
void add_binary_param(const binarystring &b, bool nonnull)
{ this->add_checked_param(b.str(), nonnull, true); }
/// Marshall parameter values into C-compatible arrays for passing to libpq.
int marshall(
std::vector<const char *> &values,
std::vector<int> &lengths,
std::vector<int> &binaries) const;
private:
void add_checked_param(const std::string &, bool nonnull, bool binary);
std::vector<std::string> m_values;
std::vector<bool> m_nonnull;
std::vector<bool> m_binary;
};
/// Internal type: encode statement parameters.
/** Compiles arguments for prepared statements and parameterised queries into
* a format that can be passed into libpq.
*
* Objects of this type are meant to be short-lived. If you pass in a non-null
* pointer as a parameter, it may simply use that pointer as a parameter value.
*/
struct params
{
/// Construct directly from a series of statement arguments.
/** The arrays all default to zero, null, and empty strings.
*/
template<typename ...Args> params(Args... args) :
values(sizeof...(args), nullptr),
lengths(sizeof...(args), 0),
nonnulls(sizeof...(args), 0),
binaries(sizeof...(args), 0)
{
// Pre-allocate room for all strings. There's no need to construct them
// now, but we *must* allocate the space here. Otherwise, re-allocation
// inside the vector may invalidate the c_str() pointers that we store!
//
// How could re-allocation invalidate those pointers? Possibly because
// the library implementation uses copy-construction instead of move
// construction when growing the vector, or possibly because of the
// Small String Optimisation.
m_strings.reserve(sizeof...(args));
// Start recursively storing parameters.
set_fields(0, args...);
}
/// As used by libpq: values, as C string pointers.
std::vector<const char *> values;
/// As used by libpq: lengths of non-null arguments, in bytes.
std::vector<int> lengths;
/// As used by libpq: boolean "is this parameter non-null?"
std::vector<int> nonnulls;
/// As used by libpq: boolean "is this parameter in binary format?"
std::vector<int> binaries;
private:
/// Compile one argument (default implementation).
/** Uses string_traits to represent the argument as a std::string.
*/
template<typename Arg> void set_field(std::size_t index, Arg arg)
{
if (!string_traits<Arg>::is_null(arg))
{
nonnulls[index] = 1;
// Convert to string, store the result in m_strings so that we can pass
// a C-style pointer to its text.
m_strings.emplace_back(to_string(arg));
const auto &storage = m_strings.back();
values[index] = storage.c_str();
lengths[index] = int(storage.size());
}
}
/// Compile one argument (specialised for null pointer, a null value).
void set_field(std::size_t, std::nullptr_t)
{
// Nothing to do: using default values.
}
/// Compile one argument (specialised for C-style string).
void set_field(std::size_t index, const char arg[])
{
// This argument is already in exactly the right format. Don't bother
// turning it into a std::string; just use the pointer we were given.
// Of course this would be a memory bug if the string's memory were
// deallocated before we made our actual call.
values[index] = arg;
if (arg != nullptr)
{
nonnulls[index] = 1;
lengths[index] = int(std::strlen(arg));
}
}
/// Compile one argument(specialised for C-style string, signed).
void set_field(std::size_t index, const signed char arg[])
{
// The type we got is close enough to the one we want. Just cast it.
using target_type = const char *;
set_field(index, target_type(arg));
}
/// Compile one argument (specialised for C-style string, unsigned).
void set_field(std::size_t index, const unsigned char arg[])
{
// The type we got is close enough to the one we want. Just cast it.
using target_type = const char *;
set_field(index, target_type(arg));
}
/// Compile one argument (specialised for binarystring).
void set_field(std::size_t index, const binarystring &arg)
{
// Again, assume that the value will stay in memory until we're done.
values[index] = arg.get();
nonnulls[index] = 1;
binaries[index] = 1;
lengths[index] = int(arg.size());
}
#if defined(PQXX_HAVE_OPTIONAL)
/// Compile one argument (specialised for std::optional<type>).
template<typename Arg> void set_field(
std::size_t index,
const std::optional<Arg> &arg)
{
if (arg.has_value()) set_field(index, arg.value());
else set_field(index, nullptr);
}
#endif
#if defined(PQXX_HAVE_EXP_OPTIONAL)
/// Compile one argument (specialised for std::experimental::optional<type>).
template<typename Arg> void set_field(
std::size_t index,
const std::experimental::optional<Arg> &arg)
{
if (arg) set_field(index, arg.value());
else set_field(index, nullptr);
}
#endif
/// Compile argument list.
/** This recursively "peels off" the next remaining element, compiles its
* information into its final form, and calls itself for the rest of the
* list.
*
* @param index Number of this argument, zero-based.
* @param arg Current argument to be compiled.
* @param args Optional remaining arguments, to be compiled recursively.
*/
template<typename Arg, typename ...More>
void set_fields(std::size_t index, Arg arg, More... args)
{
set_field(index, arg);
// Compile remaining arguments, if any.
set_fields(index + 1, args...);
}
/// Terminating version of set_fields, at the end of the list.
/** Recurstion in set_fields ends with this call.
*/
void set_fields(std::size_t) {}
/// Storage for stringified parameter values.
std::vector<std::string> m_strings;
};
} // namespace pqxx::internal
} // namespace pqxx
#include "pqxx/compiler-internal-post.hxx"
#endif
| 317c372b02694426ab237c9e6402fdc1c633ff81 | [
"C++"
] | 1 | C++ | sth/libpqxx | 4ffa64345a9423c6e10a4065efe628f478ce1463 | cfd725c78c377b7fefed7dd495cc659f3d0621f9 |
refs/heads/master | <repo_name>shashwat14/OsmPy<file_sep>/OSM2Graph.py
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 19 21:32:36 2017
@author: Shashwat
"""
import xml.etree.ElementTree
import cv2
import numpy as np
import matplotlib.pyplot as plt
class Map(object):
def __init__(self, map_file):
self.root = xml.etree.ElementTree.parse(map_file).getroot()
self.tags = set()
children = self.root.getchildren()
for child in children:
self.tags.add(child.tag)
boundElement = children[0]
self.minlat = float(boundElement.get('minlat'))
self.maxlat = float(boundElement.get('maxlat'))
self.minlon = float(boundElement.get('minlon'))
self.maxlon = float(boundElement.get('maxlon'))
def getTags(self):
'''
Param: None
Return: set of available tags for given map
'''
return self.tags
def getElementByTag(self, tag, element=None):
'''
Param: tag as string. Options available - way, node, bounds, member
Return: list of element with given tag
'''
if element is not None:
return element.findall(tag)
return self.root.findall(tag)
def getNodeTags(self):
'''
Param: None
Return: Set of available tags within a node
'''
tagSetKey = set()
tagSetValue = set()
nodeList = self.getElementByTag('node', self.root)
for node in nodeList:
childTags = self.getElementByTag('tag', node)
for childTag in childTags:
tagSetKey.add(childTag.get('k'))
tagSetValue.add(childTag.get('v'))
return tagSetKey, tagSetValue
def getWayTags(self):
'''
Param: None
Return: Set of available tags within a way
'''
tagKeySet = set()
tagValueSet = set()
wayList = self.getElementByTag('way', self.root)
for way in wayList:
childTags = self.getElementByTag('tag', way)
for childTag in childTags:
tagKeySet.add(childTag.get('k'))
tagValueSet.add(childTag.get('v'))
return tagKeySet, tagValueSet
#DO THIS
def getNodeByTag(self, tags=None):
'''
Param: tags as a list of string
Return: List of nodes with a particular set of tags. For eg. nodes with tags of bus_stop.
'''
nodeObjectList = []
nodeList = self.getElementByTag('node', self.root)
for node in nodeList:
ref = node.get('id')
lat = node.get('lat')
lon = node.get('lon')
childTags = self.getElementByTag('tag', node)
key_value_pair = {}
for childTag in childTags:
key = childTag.get('k')
value = childTag.get('v')
key_value_pair[key] = value
nodeObject = Node(ref, lat, lon, key_value_pair)
nodeObjectList.append(nodeObject)
return nodeObjectList
def getWayByTag(self, tags=None):
'''
Param: tags as a list of string
Return: List of ways with a particular set of tags. For eg. ways with tags of highway
'''
wayList = self.getElementByTag('way', self.root)
wayObjectList = []
for way in wayList:
ref = way.get('id')
#Save list of nodes making up a way
childTags = self.getElementByTag('nd', way)
lst = []
for childTag in childTags:
if childTag.get('ref') is not None:
lst.append(childTag.get('ref'))
#Save list of key value pair for each way
childTags = self.getElementByTag('tag', way)
key_value_pairs = {}
for childTag in childTags:
key = childTag.get('k')
value = childTag.get('v')
key_value_pairs[key] = value
#Create Way Object
wayObject = Way(ref, lst, key_value_pairs)
wayObjectList.append(wayObject)
return wayObjectList
def getNodeHash(self):
'''
Param: None
Return: Dictionary of node references to node objects
'''
nodeList = self.getNodeByTag()
nodeHash = {}
for node in nodeList:
nodeHash[node.ref] = node
return nodeHash
def generateAdjacencyList(self, wayList):
'''
Param: list of ways where each way is Way object
Return: Dictionary as adjacency list
'''
adjacencyList = {}
for way in wayList:
if 'highway' not in way.dict.keys() :#or way.dict['highway'] != 'footway':
continue
nodes_refs = way.nodes
for i in range(1, len(nodes_refs)):
node_i = nodes_refs[i-1]
node_j = nodes_refs[i]
nodeSet = set(adjacencyList.keys())
if node_i not in nodeSet and node_j not in nodeSet:
adjacencyList[node_i] = [node_j]
adjacencyList[node_j] = [node_i]
elif node_i not in nodeSet and node_j in nodeSet:
adjacencyList[node_i] = [node_j]
adjacencyList[node_j].append(node_i)
elif node_i in nodeSet and node_j not in nodeSet:
adjacencyList[node_i].append(node_j)
adjacencyList[node_j] = [node_i]
else:
adjacencyList[node_i].append(node_j)
adjacencyList[node_j].append(node_i)
return adjacencyList
def toXY(self, lat, lon):
'''
Custom function for user defined transformation to x,y coordinates
Param: list of latitude in degrees, list of longitudes in degrees
Return: List of X and Y
'''
lat-=1.3
lon-=103.77
lat*=110574.84
lon*=111291.00
return lat, lon
class Way(object):
def __init__(self, ref, nd, key_value_pairs):
self.ref = ref
self.nodes = nd
self.dict = key_value_pairs
class Node(object):
def __init__(self, ref, lat, lon, key_value_pairs):
self.ref = ref
self.lat = float(lat)
self.lon = float(lon)
self.dict = key_value_pairs
map = Map('C:\\Users\\Shashwat\\Downloads\\map(2).osm')
nodeHash = map.getNodeHash()
wayList = map.getWayByTag()
al = map.generateAdjacencyList(wayList)
lat = []
lon = []
for each in al.keys():
latitude = float(nodeHash[each].lat)
longitude = float(nodeHash[each].lon)
if latitude > map.minlat and latitude < map.maxlat and longitude < map.maxlon and longitude > map.minlon:
lat.append(latitude)
lon.append(longitude)
lat = np.array(lat)
lon = np.array(lon)
lat, lon = map.toXY(lat, lon)
#rows = latitude
#cols = longitude
#cv2.namedWindow("Frame", cv2.WINDOW_NORMAL)
img = np.zeros((900*2, 600*2))
for l1, l2 in zip(lon, lat):
cv2.circle(img, (int(l1), 1500-int(l2)), 2, 255, -1)
for init in al.keys():
init_node = nodeHash[init]
ilat, ilon = map.toXY(np.array([init_node.lat]), np.array([init_node.lon]))
fins = al[init]
for each in fins:
each_node = nodeHash[each]
flat, flon = map.toXY(np.array([each_node.lat]), np.array([each_node.lon]))
cv2.line(img, (int(ilon), 1500-int(ilat)),(int(flon), 1500-int(flat)), 255, 1)
cv2.imshow("Frame", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
#cv2.imwrite("C:\\Users\\Shashwat\\Desktop\\osm_utown_map.png", img)<file_sep>/README.md
# OsmPy
This package is being developed for usage in self-driving vehicles. The aim of this project is to allow vehicles to ping their GPS location to this server and obtain way/node its cuurently on. More semantic information can be added to the maps such as lane width, traffic sign locations, etc for improving the prior over unmapped area. This project can also be used as a simulation toolbox for taxi-customer assignment problem.
Note: This project is curently under development - to be converted into a ROS Package.
| 27764e94e03e4a08e5b29f2c7f62413816ea72c9 | [
"Markdown",
"Python"
] | 2 | Python | shashwat14/OsmPy | c82ccdccd67ec4795f2a56109523bac94371b4b1 | 00985db741f70d8e558a07c6a3ba44d9b566bed8 |
refs/heads/master | <file_sep>package com.kulykova.services;
import com.kulykova.model.FormModel;
import org.springframework.stereotype.Service;
@Service
public class FormService {
public FormModel createForm(String firstName, String lastName, String passport) {
FormModel form = new FormModel();
form.setFirstName(firstName);
form.setLastName(lastName);
form.setPassport(passport);
return form;
}
}
<file_sep># PDFProfile
=)
=)<file_sep>package com.kulykova.model;
public class FormModel {
private String firstName;
private String lastName;
private String passport;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPassport() {
return passport;
}
public void setPassport(String passport) {
this.passport = passport;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FormModel formModel = (FormModel) o;
if (firstName != null ? !firstName.equals(formModel.firstName) : formModel.firstName != null) return false;
if (lastName != null ? !lastName.equals(formModel.lastName) : formModel.lastName != null) return false;
return !(passport != null ? !passport.equals(formModel.passport) : formModel.passport != null);
}
@Override
public int hashCode() {
int result = firstName != null ? firstName.hashCode() : 0;
result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
result = 31 * result + (passport != null ? passport.hashCode() : 0);
return result;
}
}
| 35b32e8824b5c6daded1f79cce5e11714627d265 | [
"Markdown",
"Java"
] | 3 | Java | OlgaKulikova/PDFProfile | 89f15410261e6da20c3e31f4095d667cb53f45bc | 4cc9ecc9606d570e086d483297bfc3c4201472b4 |
refs/heads/master | <repo_name>Ulduman/task_04<file_sep>/README.md
# task_04
Find area and perimeter of a quadrangle by coordinates
<file_sep>/Quadrangles/Quadrangles/Quadrangle.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Quadrangles
{
public class Quadrangle
{
public bool TestQuad(params double[] x)
{
if (x.Length == 8)
{
if ((x[0] == x[2] && x[0] == x[6]) || (x[1] == x[3] && x[1] == x[7]) || (x[0] == x[6] && x[6] == x[4]) || (x[1] == x[7] && x[7] == x[5]) || (x[6] == x[4] && x[4] == x[2]) || (x[7] == x[5] && x[5] == x[3]) || (x[4] == x[2] && x[2] == x[0]) || (x[5] == x[3] && x[3] == x[1]))
{
return false;
} else {
double k1 = (x[1] - x[3]) / (x[0] - x[2]), k2 = (x[3] - x[5]) / (x[2] - x[4]), k3 = (x[5] - x[7]) / (x[4] - x[6]), k4 = (x[7] - x[1]) / (x[6] - x[0]);
if (k1 == k2 || k2 == k3 || k3 == k4 || k4 == k1)
{
return false;
}
else return true;
}
}else return false;
}
public double[] ReplaceCoordinates(params double[] x)
{
double[] z = (double[])x.Clone();
double ax = z[0] - z[2], bx = z[0] - z[4], cx = z[0] - z[6], ay = z[1] - z[3], by = z[1] - z[5], cy = z[1] - z[7], cosab = (ax * bx + ay * by) / (Math.Sqrt(Math.Pow(ax, 2) + Math.Pow(ay, 2)) * Math.Sqrt(Math.Pow(bx, 2) + Math.Pow(by, 2)));
double cosac = (ax * cx + ay * cy) / (Math.Sqrt(Math.Pow(ax, 2) + Math.Pow(ay, 2)) * Math.Sqrt(Math.Pow(cx, 2) + Math.Pow(cy, 2)));
double cosbc = (cx * bx + cy * by) / (Math.Sqrt(Math.Pow(bx, 2) + Math.Pow(by, 2)) * Math.Sqrt(Math.Pow(cx, 2) + Math.Pow(cy, 2)));
if (cosab < cosac && cosab < cosbc)
{
return new double[] { z[0], z[1], z[2], z[3], z[6], z[7], z[4], z[5] };
}
else if (cosac < cosab && cosac < cosbc)
{
return z;
}
else return new double[] { z[0], z[1], z[4], z[5], z[2], z[3], z[6], z[7] };
}
public string SpotTypeQuad(params double[] x)
{
double[] z = (double[])x.Clone();
z = ReplaceCoordinates(z);
bool ans = TestQuad(z);
if (ans)
{
return "0";
}
else return "0";
}
public double CalcAreaQuad(params double[] x)
{
double[] z = ReplaceCoordinates(x);
bool ans = TestQuad(z);
if (ans)
{
return Math.Abs((z[0] * z[3] - z[1] * z[2] + z[2] * z[5] - z[3] * z[4] + z[4] * z[7] - z[5] * z[6] + z[6] * z[1] - z[7] * z[0]) / 2);
}
else return 0;
}
public double CalcPerimetrQuad(params double[] x)
{
double[] z = (double[])x.Clone();
z = ReplaceCoordinates(z);
bool ans = TestQuad(z);
if (ans)
{
double a = Math.Pow((Math.Pow(Math.Abs(z[0] - z[2]), 2) + Math.Pow(Math.Abs(z[1] - z[3]), 2)), 0.5), b = Math.Pow((Math.Pow(Math.Abs(z[2] - z[4]), 2) + Math.Pow(Math.Abs(z[3] - z[5]), 2)), 0.5), c = Math.Pow((Math.Pow(Math.Abs(z[6] - z[4]), 2) + Math.Pow(Math.Abs(z[7] - z[5]), 2)), 0.5), d = Math.Pow((Math.Pow(Math.Abs(z[6] - z[0]), 2) + Math.Pow(Math.Abs(z[7] - z[1]), 2)), 0.5);
return a + b + c + d;
}
else return 0;
}
}
}
<file_sep>/Quadrangles/ConsoleApp1/Program.cs
using Quadrangles;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Quadrangle q = new Quadrangle();
double[] x;
string[] str;
Console.Write("Введите координаты четырехугольника через пробел:\n");
str = Console.ReadLine().Split(' ');
x = new double[str.Length];
for (int i = 0; i < str.Length; i++)
{
x[i] = Convert.ToDouble(str[i]);
}
Console.WriteLine("Периметр: {0:f} Площадь: {1:f}",q.CalcPerimetrQuad(x), q.CalcAreaQuad(x));
Console.ReadKey();
}
}
}
| 7b93a27af0b0d8be50adc9177e30751f37432096 | [
"Markdown",
"C#"
] | 3 | Markdown | Ulduman/task_04 | f0ac7c3c0f1a9853cba3dfc0c628b06b8f09545d | 60d84903cee2fd825f6c144022646ffb9db1ec0d |
refs/heads/master | <file_sep>//Dependencies
const { ApolloServer } = require("apollo-server");
const mongoose = require("mongoose");
//Files
const typeDefs = require("./graphql/typeDefs");
const { MONGODB } = require("./config.js");
const resolvers = require("./graphql/resolvers");
//Creating Server
const server = new ApolloServer({ typeDefs, resolvers });
//Connecting Database
mongoose
.connect(MONGODB, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log("connected to database");
return server.listen({ port: 4000 });
})
.then((res) => {
console.log(`Server is running on port ${res.url}`);
});
<file_sep>module.exports = {
MONGODB:
"mongodb+srv://Saizazur:<EMAIL>Yo<EMAIL>/merng?retryWrites=true&w=majority",
SECRET_KEY: "This is a very secret key",
};
| c578ecbb5b093afa0095e58309a41a5da4349e1f | [
"JavaScript"
] | 2 | JavaScript | saizazur1/MERNG | 942becea3323574654c81232bfdbd71c3456e8e0 | 4e233023d792cd88fb7e690a33b3276efa84b20c |
refs/heads/master | <file_sep>import React from 'react'
import {NavLink} from "react-router-dom";
const NotFound = () => (
<div className='not_found'>
<NavLink exact to="/" className='btn'>
Back
</NavLink>
<div className='msg'>Page not found</div>
</div>
)
export default NotFound<file_sep>import React, {useState} from "react";
import Todo from "./Todo";
import NewTodoForm from "./NewTodoForm";
import "./css/TodoList.css";
function TodoList() {
const getTodos = () => {
const todos = window.localStorage.getItem('todos');
if (!todos) {
return [];
}
return JSON.parse(todos);
}
const [list, setList] = useState(getTodos());
const updateTodos = (newTodos) => {
const stringifiedTodos = JSON.stringify(newTodos);
window.localStorage.setItem('todos', stringifiedTodos);
setList(newTodos);
};
const toggleComplete = (id, completed) => {
const todoIdx = list.findIndex(todo => todo.id === id);
const newTodos = [...list];
newTodos[todoIdx].completed = completed;
updateTodos(newTodos);
};
const create = (newTodo) => {
updateTodos([...list, newTodo]);
};
const remove = id => {
const updatedList = list.filter(todo => todo.id !== id);
updateTodos(updatedList)
};
const update = (id, updatedTask) => {
const updatedList = list.map(todo => {
if (todo.id === id) {
return updatedTask;
}
return todo;
});
updateTodos(updatedList);
};
const toDoList = list.map(todo => (
<Todo
toggleComplete={toggleComplete}
update={update}
remove={remove}
key={todo.id}
todo={todo}
/>
));
return (
<div className="TodoList">
<h1>Todo List </h1>
<ul>{toDoList}</ul>
<NewTodoForm createTodo={create}/>
</div>
);
}
export default TodoList;
<file_sep>import React, {useState} from "react";
import {NavLink} from "react-router-dom";
import NotFound from "../common/NotFound";
import './css/ToDoDetail.css'
const TodoDetail = (props) => {
const getTodoDetail = () => {
const todos = window.localStorage.getItem('todos');
return JSON.parse(todos).filter(i => i.id === props.match.params.id);
}
const toDoDetail = useState(getTodoDetail());
let result;
if (toDoDetail[0].length > 0) {
result = (<div>
<div className="ToDoDetail">
<div className="whole">
<div className="title">
<h1 style={{textDecoration: toDoDetail[0][0].completed ? 'line-through' : 'none'}}>
{toDoDetail[0][0].title}
</h1>
</div>
<div className="info">
<div className="content">
<ul>
<li>ID: {toDoDetail[0][0].id}</li>
<li>Description: {toDoDetail[0][0].description}</li>
</ul>
</div>
<div className="nav">
<NavLink exact to="/" className='btn'>
Back
</NavLink>
</div>
</div>
</div>
</div>
</div>)
} else {
result = <NotFound/>
}
return result
}
export default TodoDetail<file_sep>let express = require('express');
let app = express();
let cors = require('cors');
app.use(cors());
let data = [
{
id: '1',
title: "Go shopping",
completed: false,
description: 'Take some food for cat'
},
{
id: '2',
title: 'Feed the cat',
description: 'Matters of prime importance',
completed: false,
},
{
id: '3',
title: 'Discover a new chemical element',
description: 'If time is left',
completed: false,
},
{
id: '4',
title: 'Go to training',
description: 'Don\'t forget to have a tight lunch before',
completed: false,
},
{
id: '5',
title: 'Watch some movie',
description: '',
completed: false,
}
]
app.get("/data", function(request, response){
response.send(data)});
app.listen(3001, function() {
console.log('App running on port 3001,');
});<file_sep># to-do-app
Instruction for starting:
In the root directory of project enter in console:
-npm i;
-node server.js;
-npm start;
Server will be started on localhost:3001
App will be started on localhost:3000 | 1fd3648c0d5e6bae2b38c65ff45be5314bd1aac6 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | Alt-airr/to-do-app | 4c656136e635139be72953ae138966baecda9225 | 66e1e3a0989903cb8cf0189f1124f1d5ee90cb95 |
refs/heads/master | <file_sep>#!/bin/bash
apt install npm
npm install -g heroku
export HEROKU_API_KEY=${{secrets.HEROKU_API_KEY}}
bash inst*
| 6ee019c6b1badd76e554bc38b2b83b25d9ee6b50 | [
"Shell"
] | 1 | Shell | kcubeterm/Ubuntu-gui | 7c20e691e5fa44636a1d89ddb44c07f74eef1bae | c3a9b1492598a6f21ee3c7f6bf398cbf625c80c4 |
refs/heads/master | <repo_name>Tereflech17/FacultyResearchDB<file_sep>/faculty_research.sql
DROP DATABASE IF EXISTS faculty_research;
CREATE DATABASE faculty_research;
USE faculty_research;
DROP TABLE IF EXISTS department;
CREATE TABLE department(
DepartmentID int(10) NOT NULL,
DepartmentName varchar(50),
OfficeRoomNumber varchar(10),
PRIMARY KEY (DepartmentID)
);
DROP TABLE IF EXISTS faculty;
CREATE TABLE faculty(
FacultyID int(10) NOT NULL,
DepartmentID int(10),
FirstName varchar(20),
LastName varchar(20),
Email varchar(30),
Interest varchar(30),
OfficeBuilding varchar(10),
OfficePhoneNumber varchar(20),
OfficeRoomNumber varchar(10),
Password char(96),
PRIMARY KEY (FacultyID),
CONSTRAINT FK_faculty_department FOREIGN KEY (DepartmentID) REFERENCES department(DepartmentID)
);
DROP TABLE IF EXISTS student;
CREATE TABLE student(
StudentID int(10) NOT NULL,
DepartmentID int(10),
FirstName varchar(20),
LastName varchar(20),
Email varchar(30),
SchoolYear varchar(20),
Major varchar(30),
Password char(96),
PRIMARY KEY(StudentID),
CONSTRAINT FK_student_department FOREIGN KEY(DepartmentID) REFERENCES department(DepartmentID)
);
DROP TABLE IF EXISTS project;
CREATE TABLE project(
ProjectID int(10) NOT NULL AUTO_INCREMENT,
FacultyID int(10),
ProjectName varchar(255),
ProjectDescription varchar(255),
Budget decimal(7,2),
StartDate date,
EndDate date,
StudentID int(11),
PRIMARY KEY(ProjectID),
CONSTRAINT FK_project_faculty FOREIGN KEY(FacultyID) REFERENCES faculty(FacultyID),
CONSTRAINT FK_project_student FOREIGN KEY(StudentID) REFERENCES student(StudentID)
);
--
-- Dumping data for table 'department'
--
-- Fields: DepartmentID, DepartmentName, OfficeNumber
INSERT INTO department VALUES(1, "Computer Science","GOL-3005");
INSERT INTO department VALUES(2, "Computing Security","GOL-2120");
INSERT INTO department VALUES(3, "Information Sciences & Technologies","GOL-2100");
INSERT INTO department VALUES(4, "School of Interactive Games & Media","GOL-2145");
INSERT INTO department VALUES(5, "Software Engineering","GOL-1690");
--
-- Dumping data for table 'faculty'
--
-- Fields: FacultyID, DepartmentID, FirstName, LastName, Email, Interest, OfficeBuilding, OfficePhoneNumber, OfficeRoomNumber, Password
INSERT INTO faculty select 1, 1, "Reynold", "Bailey", "<EMAIL>", "CS", "Golisano", "585-475-6181", "GOL-3005", SHA2("password", 256);;
INSERT INTO faculty select 2, 1, "Ivona", "Bezakova", "<EMAIL>", "CS", "Golisano", "585-475-4526", "GOL-3645", SHA2("password", 256);
INSERT INTO faculty select 3, 2, "Giovani", "Abuaitah", "<EMAIL>", "CSEC", "Golisano", "585-475-4316", "GOL-2321", SHA2("password", 256);
INSERT INTO faculty select 4, 2, "Hrishikesh", "Archarya", "<EMAIL>", "CSEC", "Golisano", "585-475-2801", "GOL-2647", SHA2("password", 256);
INSERT INTO faculty select 5, 3, "Dan", "Bogaard", "<EMAIL>", "ISTE", "Golisano", "585-475-5231", "GOL-2111", SHA2("password", 256);
INSERT INTO faculty select 6, 3, "Michael", "Floeser", "Michael.Flo<EMAIL>", "ISTE", "Golisano", "585-475-7031", "GOL-2669", SHA2("password", 256);
INSERT INTO faculty select 7, 4, "David", "Schwartz", "<EMAIL>", "IGM", "Golisano", "585-475-5521", "GOL-2157", SHA2("password", 256);
INSERT INTO faculty select 8, 4, "Jessica", "Bayliss", "<EMAIL>", "IGM", "Golisano", "585-475-2507", "GOL-2153", SHA2("password", 256);
INSERT INTO faculty select 9, 5, "Travis", "Desell", "<EMAIL>", "SE", "Golisano", NULL, "GOL-1559", SHA2("password", 256);
INSERT INTO faculty select 10, 5, "Scott", "Hawker", "<EMAIL>", "SE", "Golisano", "585-475-2705", "GOL-1696", SHA2("password", 256);
--
-- Dumping data for table 'student'
--
-- Fields: StudentID, DepartmentID, FirstName, LastName, Email, SchoolYear, Major, Password
INSERT INTO student select 1, 1, 'John', 'Smith','<EMAIL>','Sophomore','CS', SHA2("password", 256);
INSERT INTO student select 2, 2, 'George', 'Brown','<EMAIL>','Junior','CSEC', SHA2("password", 256);
INSERT INTO student select 3, 3, 'Carmen', 'Tang','<EMAIL>','Freshman','IST', SHA2("password", 256);
INSERT INTO student select 4, 4, 'Laura', 'Diaze','<EMAIL>','Freshman','IGM', SHA2("password", 256);
INSERT INTO student select 5, 5, 'Fred', 'Amarty','<EMAIL>','Junior','SE', SHA2("password", 256);
INSERT INTO student select 6, 1, 'Ronald', 'Sowah','<EMAIL>','Senior','CS', SHA2("password", 256);
INSERT INTO student select 7, 2, 'Desley','Brown','<EMAIL>','Freshman','CSEC', SHA2("password", 256);
INSERT INTO student select 8, 3, 'Tiffany', 'Dubon','<EMAIL>','Sophomore','IST', SHA2("password", 256);
INSERT INTO student select 9, 4, 'Lauren', 'Campbell','<EMAIL>','Freshman','IGM', SHA2("password", 256);
INSERT INTO student select 10, 5, 'Sam', 'Illesamni','<EMAIL>','Junior','SE', SHA2("password", 256);
--
-- Dumping data for table 'project'
--
-- Fields: ProjectID, StudentID, FacultyID, ProjectName, ProjectDescription, Budget, StartDate, EndDate
INSERT INTO project (projectid, facultyid, projectname, projectdescription, budget, startdate, enddate) VALUES(1, 1, 'Lookup or Learn: A Grounded Theory Approach to the Student-Task', 'Proceedings of the 9th International Conference on Education and Information Systems, Technologies and Applications', 1000.00, '2018-08-27','2018-12-11');
INSERT INTO project (projectid, facultyid, projectname, projectdescription, budget, startdate, enddate) VALUES(2, 2, 'Progress on Website Accessibility?' , 'ACM Transactions on the Web', 1000.00, '2017-08-22','2017-12-08');
INSERT INTO project (projectid, facultyid, projectname, projectdescription, budget, startdate, enddate) VALUES(3, 3, 'Accessibility Support with the ACCESS Framework', 'International Journal of Human Computer Interaction', 1000.00, '2017-01-22','2017-05-08');
INSERT INTO project (projectid, facultyid, projectname, projectdescription, budget, startdate, enddate) VALUES(4,4,'Digital Motherhood: How Does Technology Support New Mothers?', 'Proceedings of the ACM SIGCHI Conference on Human Factors in Computing Systems', 1000.00, '2017-01-27','2017-08-08');
INSERT INTO project (projectid, facultyid, projectname, projectdescription, budget, startdate, enddate) VALUES(5,5,'A Protocol for Software-Supported Interaction with Broadcast Debates','Proceedings of the Open Digital, Fourth Annual Digital Economy All Hands Conference', 1000.00, '2016-01-23','2016-05-10');
INSERT INTO project (projectid, facultyid, projectname, projectdescription, budget, startdate, enddate) VALUES(6,6,'Older Adults and Social Networking Sites: Developing Recommendations for Inclusive Design','Proceedings of the Open Digital, Fourth Annual Digital Economy All Hands Conference', 1000.00, '2016-08-30','2016-12-14');
INSERT INTO project (projectid, facultyid, projectname, projectdescription, budget, startdate, enddate) VALUES(7,7,'Implementation and Evaluation of Animation Controls Sufficient for Conveying ASL Facial Expressions','Proceedings of the 15th International ACM SIGACCESS Conference on Computers and Accessibility', 1000.00, '2017-02-01','2017-05-15');
INSERT INTO project (projectid, facultyid, projectname, projectdescription, budget, startdate, enddate) VALUES(8,8,'Release of Experimental Stimuli and Questions for Evaluating Facial Expressions in Animations of American Sign Language',' Proceedings of the 6th Workshop on the Representation and Processing of Sign Languages: Beyond the Manual Channel, The 9th International Conference on Language Resources and Evaluation', 1000.00, '2018-08-31','2018-12-02');
INSERT INTO project (projectid, facultyid, projectname, projectdescription, budget, startdate, enddate) VALUES(9,9, 'Using a Low-Cost Open Source Hardware Development Platform in Teaching Young Students Programming Skills','Proceedings of the SIGITE', 1000.00, '2017-01-31','2017-05-04');
<file_sep>/src/data/Faculty.java
package data;
import java.util.ArrayList;
/**
* Data layer for Faculty
*/
public class Faculty {
private String id;
private String departmentId;
private String fName;
private String lName;
private String email;
private String interest;
private String officeBuilding;
private String officePhoneNumber;
private String officeRoomNumber;
private String password;
// MySQL
MySQLDatabase mysql = new MySQLDatabase();
// Constructors
public Faculty() { }
public Faculty(String id) {
this.id = id;
}
public Faculty(String id, String password) {
this.id = id;
this.password = <PASSWORD>;
}
public Faculty(String id, String departmentId, String fName, String lName, String email, String interest, String officeBuilding, String officePhoneNumber, String officeRoomNumber) {
this.id = id;
this.departmentId = departmentId;
this.fName = fName;
this.lName = lName;
this.email = email;
this.interest = interest;
this.officeBuilding = officeBuilding;
this.officePhoneNumber = officePhoneNumber;
this.officeRoomNumber = officeRoomNumber;
}
/**
* Retrieve the values from the db using the faculty's id and update other attributes
*
* @throws DLException if any MySQLDatabase methods errors
* @return size of the data fetched
*/
public int get() throws DLException {
// Connect to Mysql
mysql.connect();
// Add the equipment id to an ArrayList
ArrayList<String> values = new ArrayList<>();
values.add( this.getId() );
// Create query string
String query = "select departmentid, firstname, lastname, email, interest, officebuilding, officephonenumber, officeroomnumber from faculty where facultyid = ?";
// Retrieve data from db using .getData()
ArrayList<ArrayList<String>> queryData = mysql.getData( query, values );
// Iterate through queryData and set the object's attributes
if(queryData.size() > 1) {
// Get the second row as the first row will be the column names
this.departmentId = queryData.get(1).get(0);
this.fName = queryData.get(1).get(1);
this.lName = queryData.get(1).get(2);
this.email = queryData.get(1).get(3);
this.interest = queryData.get(1).get(4);
this.officeBuilding = queryData.get(1).get(5);
this.officePhoneNumber = queryData.get(1).get(6);
this.officeRoomNumber = queryData.get(1).get(7);
}
// Close mysql
mysql.close();
return queryData.size();
}
/**
* Update the attributes in the db
*
* @throws DLException if any MySQLDatabase methods errors
* @return num of rows affected
*/
public int put() throws DLException {
// Connect to Mysql
mysql.connect();
// Create query
String query = "update faculty set departmentId = ?, firstname = ?, lastname = ?, email = ?, interest = ?, officebuilding = ?, officephonenumber = ?, officeroomnumber where facultyid = ?";
// Add properties to values ArrayList
ArrayList<String> values = new ArrayList<>();
values.add(this.getDepartmentId());
values.add(this.getfName());
values.add(this.getlName());
values.add(this.getEmail());
values.add(this.getInterest());
values.add(this.getOfficeBuilding());
values.add(this.getOfficePhoneNumber());
values.add(this.getOfficeRoomNumber());
values.add(this.getId());
int modified = mysql.setData(query, values);
// Close mysql
mysql.close();
return modified;
}
/**
* Insert the attributes in the db
*
* @throws DLException if any MySQLDatabase methods errors
* @return num of rows affected
*/
public int post() throws DLException {
// Connect to Mysql
mysql.connect();
// Create query
String query = "insert into faculty values(?, ?, ?, ?, ?, ?, ?, ?, ?);";
// Add properties to values ArrayList
ArrayList<String> values = new ArrayList<>();
values.add(this.getId());
values.add(this.getDepartmentId());
values.add(this.getfName());
values.add(this.getlName());
values.add(this.getEmail());
values.add(this.getInterest());
values.add(this.getOfficeBuilding());
values.add(this.getOfficePhoneNumber());
values.add(this.getOfficeRoomNumber());
int modified = mysql.setData(query, values);
// Close mysql
mysql.close();
return modified;
}
/**
* Delete a record in the database
*
* @throws DLException if any MySQLDatabase methods errors
* @return num of rows deleted
*/
public int delete() throws DLException {
// Connect to Mysql
mysql.connect();
// Connect to Mysql
String query = "delete from faculty where facultyId = ?;";
// Add properties to values ArrayList
ArrayList<String> values = new ArrayList<>();
values.add(this.getId());
int modified = mysql.setData(query, values);
// Close mysql
mysql.close();
return modified;
}
/**
* Checks the faculty's id and password against the ones in the database
*
* @throws DLException if any MySQLDatabase methods errors
* @return 1 - if the faculty exists based on the id and password given, 0 - if otherwise
*/
public int login() throws DLException {
// Open mysql
mysql.connect();
// Create query
String query = "select * from faculty where password = <PASSWORD>(?, 256) and facultyid = ?";
// Prepare values
ArrayList<String> values = new ArrayList<>();
values.add(this.getPassword());
values.add(this.getId());
ArrayList<ArrayList<String>> data = mysql.getData( query, values );
data.remove(0); // Remove column names
// On faculty data found, set the faculty's values and return the number
if(data.size() == 1) {
get();
return data.size();
}
// Close mysql
mysql.close();
return 0;
}
/**
* Gets all the faculty's projects
*
* @throws DLException if any MySQLDatabase methods errors
* @return 2D arraylist of all projects associated with the faculty
*/
public ArrayList<ArrayList<String>> getAllMyProjects() throws DLException {
// Open mysql
mysql.connect();
// Create query
String query = "select p.projectid, p.projectname, f.lastname, p.projectdescription, p.budget, p.startdate, p.enddate from project p join faculty f on p.facultyid = ? and f.facultyid = p.facultyid";
// Prepare values
ArrayList<String> values = new ArrayList<>();
values.add(this.getId());
ArrayList<ArrayList<String>> data = mysql.getData( query, values );
data.remove(0); // Remove column names
// Close mysql
mysql.close();
return data;
}
// Getters
public String getId() {
return id;
}
public String getDepartmentId() {
return departmentId;
}
public String getfName() {
return fName;
}
public String getlName() {
return lName;
}
public String getEmail() {
return email;
}
public String getInterest() {
return interest;
}
public String getOfficeBuilding() {
return officeBuilding;
}
public String getOfficePhoneNumber() {
return officePhoneNumber;
}
public String getOfficeRoomNumber() {
return officeRoomNumber;
}
public String getPassword() { return <PASSWORD>; }
}
<file_sep>/src/business/BLFaculty.java
package business;
import data.DLException;
import data.Faculty;
import java.util.ArrayList;
/**
* Business layer for Faculty
*/
public class BLFaculty extends Faculty {
// Constructors
public BLFaculty() { }
public BLFaculty(String id) {
super(id);
}
public BLFaculty(String id, String password) {
super(id, password);
}
/**
* Calls login()
*
* @throws DLException if login() fails
* @return true - if successful login, false - if otherwise
*/
public boolean doLogin() throws DLException {
if(login() == 1) {
return true;
}
return false;
}
/**
* Calls getAllMyProjects()
*
* @throws DLException if getAllMyProjects() fails
* @return 2D ArrayList of all the faculty's projects
*/
public ArrayList<ArrayList<String>> doGetMyProjects() throws DLException {
return getAllMyProjects();
}
}
| 0e481cca0736ad813b898d9edf94052d6f4f65f8 | [
"Java",
"SQL"
] | 3 | SQL | Tereflech17/FacultyResearchDB | 2495c9a19cc96cc6daaa2f14d7bae71af57c09bc | 9cdadc30cfc8eab399a84248a540d27a9102422e |
refs/heads/main | <file_sep># 用于 Flomo 的 PopClip 扩展
设置好 API 即可使用


<file_sep><?php
function force_string($str) {
return is_string($str)?$str:'';
}
$api=trim(force_string(getenv('POPCLIP_OPTION_API')));
$content=trim(force_string(getenv('POPCLIP_TEXT')));
$tag = getenv('POPCLIP_OPTION_TAG');
$browser_title = getenv("POPCLIP_BROWSER_TITLE");
$browser_url = getenv("POPCLIP_BROWSER_URL");
$ch = curl_init($api);
curl_setopt($ch, CURLOPT_URL, $api);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json; charset=utf-8',
]);
if ($browser_title != '' && $browser_url != '') {
$content .= "\n\n网页标题:{$browser_title}";
$content .= "\nURL:{$browser_url}";
}
if ($tag != '') {
$content .= "\n\n#{$tag}";
}
$json_array = [
'content' => $content
];
$body = json_encode($json_array);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
$response = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code===200) {
$data=json_decode($response, TRUE);
$result=trim(force_string($data['message']));
if(strlen($result) > 0) {
echo($result);
exit(0);
}
}else if ($code==403) {
echo("Auth Error");
exit(2); // bad auth
}
# bad response
echo("Send failed");
exit(1); | 7ce6c58c095fc466c46e3bc4cb7f2c8511a8ed68 | [
"Markdown",
"PHP"
] | 2 | Markdown | levie-vans/Flomo_PopClip_Extension | 182ca4e43949d07e209806e6723d59e8c1646082 | ce6f27f2bb60b388ec13954d2244bdfe2a3e1d50 |
refs/heads/master | <file_sep>package com.demo.processor;
import com.demo.model.Person;
import org.springframework.batch.item.ItemProcessor;
/**
* Created by maharshi.bhatt on 16/4/17.
*/
public class PersonProcessor implements ItemProcessor<Person,Person> {
@Override
public Person process(Person person) throws Exception {
return person;
}
}
<file_sep>spring.application.name = spring-batch-web
spring.datasource.url: jdbc:mysql://localhost:3306/staging_db
spring.datasource.username: root
spring.datasource.password: <PASSWORD>
spring.batch.job.enabled: false
management.security.enabled=false<file_sep># spring-batch-web
Basic Spring Batch with REST control points
| 8a5f2e5df79801d06dc830b4d34b7bb1d72982bb | [
"Markdown",
"Java",
"INI"
] | 3 | Java | maharshi09/spring-batch-web | 1cb46f15e5daafcb6c3011a85b943d72c355e3eb | 5be4823037b82d1ba6a31ae5eb58894cbb2a98b4 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataSource
{
public class user_item_pic
{
public Guid IID { get; set; }
public string Title { get; set; }
public Guid UID { get; set; }
public int Type { get; set; }
public int CID { get; set; }
public int Price { get; set; }
public string Detail { get; set; }
public int Bargin { get; set; }
public int Priority { get; set; }
public string Tel { get; set; }
public string QQ { get; set; }
public string Way { get; set; }
public string From { get; set; }
public string To { get; set; }
public DateTime RunTime { get; set; }
public DateTime PostTime { get; set; }
public DateTime UpdateTime { get; set; }
public DateTime EndTime { get; set; }
public int Statue { get; set; }
//从EF数据库获取的昵称
public string NickName { get; set; }
//从Pic表获取商品第一张图片的id
public Guid PID { get; set; }
//从Category表获取分类名称
public string FirstName { get; set; }
public string SecondName { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TradeWorkstation.Models;
using DataSource;
using System.Text;
using BLL;
namespace TradeWorkstation.Controllers
{
[Export]
[RoutePrefix("Sell")]
public class SellController : Controller
{
[Import]
public Hub.Interface.User.IAuthenticationStrategy AuthentiationStrategy { set; get; }
[Import]
public Hub.Interface.User.IAccountStrategy AccountStrategy { set; get; }
[HttpGet]
public ActionResult Add()
{
//用户
if (Session["User"] == null)
{
return Redirect("~/User/PostLogin");
}
Guid userid = new Guid(Session["User"].ToString());
ViewBag.UserID = userid;
ViewBag.NickName = AccountStrategy.GetNickNameByUserID(userid);
SellForm sf = new SellForm();
return View(sf);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Add(Models.SellForm sf, IEnumerable<HttpPostedFileBase> files)
{
//用户
if (Session["User"] == null)
{
return Redirect("~/User/PostLogin");
}
Guid userid = new Guid(Session["User"].ToString());
ViewBag.UserID = userid;
ViewBag.NickName = AccountStrategy.GetNickNameByUserID(userid);
if (!sf.agreement)
{
return Content("<script>alert('请同意协议');history.go(-1);</script>");
}
if (!ModelState.IsValid)
{
return Content("<script>alert('表单信息验证失败,请重新填写');</script>");
}
else
{
Item item = new Item();
item.IID = Guid.NewGuid();
item.Title = sf.title;
item.CID = sf.secondList == "0" ? Int32.Parse(sf.firstList) : Int32.Parse(sf.secondList);
item.UID = new Guid(Session["User"].ToString());
item.Price = sf.price;
item.Detail = sf.detail;
item.Bargain = 1;
item.Priority = 1;
item.Way = "在线支付";
string qq = sf.qq;
string tel = sf.tel;
//判断QQ或手机至少填一项的那个东西....
if (qq == null && tel == null)
{
return Content("<script>alert('QQ或手机至少填一项');history.go(-1);</script>");
}
else if (qq != null && tel == null)
{
item.QQ = qq;
}
else if (tel != null && qq == null)
{
item.Tel = tel;
}
else if (tel != null && qq != null)
{
item.QQ = qq;
item.Tel = tel;
}
int order = 0;
int count = 0;
if (BLL.SellService.InsertSellForm(item))
{
if (files.Count() > 5)
{
return Content("<script>alert('最多上传5张图片!');</script>");
}
foreach (var file in files)
{
//每张图不超过2M
if (file != null && file.ContentLength > 0 && file.ContentLength < 1024*1024*2)
{
order++;
string[] lastname = file.FileName.Split('.');
string url = Server.MapPath("/TradeWorkstationImages/"+item.UID+"/");
Pic pic = new Pic();
pic.Order = order;
pic.IID = item.IID;
if (!System.IO.Directory.Exists(url))
System.IO.Directory.CreateDirectory(url);
url += DateTime.Now.Ticks + "." + lastname[1];
file.SaveAs(url);
pic.Url = url;
if (BLL.PicService.InsertPic(pic))
{
count++;
}
}
else
{
Response.StatusCode = 400;
return Content("<script>alert('您未选择图片');</script>");
}
}//foreach end
}
else
{
return Content("<script>alert('物品信息保存失败'+'" + order + "');</script>");
}
if (count == order)
{
// if (BLL.SellService.InsertSellForm(item))
return Content("<script>alert('上传成功');location.href='Search/Page/1'</script>");
// else
// return Content("<script>alert('物品信息保存失败'+'"+order+"');</script>");
}
else
{
return Content("<script>alert('上传失败啊啊啊'+'" + order + "');</script>");
}
}
}
[HttpGet]
[Route("Search/Page/{page:int}")]
public ActionResult Search(int page)
{
//用户
if (Session["User"] == null)
{
return Redirect("~/User/PostLogin");
}
Guid userid = new Guid(Session["User"].ToString());
ViewBag.UserID = userid;
ViewBag.NickName = AccountStrategy.GetNickNameByUserID(userid);
ViewData.Model = SellService.Show(page, 8);
return View();
}
[HttpGet]
[Route("Search/CID/{cid:int}/Page/{page:int}")]
public ActionResult Search(int cid, int page)
{
//用户
if (Session["User"] == null)
{
return Redirect("~/User/PostLogin");
}
Guid userid = new Guid(Session["User"].ToString());
ViewBag.UserID = userid;
ViewBag.NickName = AccountStrategy.GetNickNameByUserID(userid);
ViewData.Model = SellService.ShowItemByCID(cid, page, 8);//一页放8个
return View();
}
[HttpGet]
[Route("Detail/ID/{iid}")]
public ActionResult Detail(Guid iid)
{
//用户
if (Session["User"] == null)
{
return Redirect("~/User/PostLogin");
}
Guid userid = new Guid(Session["User"].ToString());
ViewBag.UserID = userid;
ViewBag.NickName = AccountStrategy.GetNickNameByUserID(userid);
user_item_pic good = SellService.ShowDetail(iid);
ViewData["good"] = good;
ViewData["good_pics"] = PicService.ShowByIID(iid);
ViewData["user_other_goods"] = SellService.ShowItemByUID(good.UID, 1, 5);//最多显示4个(不包括当前商品,所以取了5个,这个在view里面有判断)
ViewData["class_other_goods"] = SellService.ShowItemByCID(good.CID, 1, 5);//同上
//good的第一张图片PID
ViewData["first_pic"] = good.PID;
return View();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataSource;
namespace DAL
{
/// <summary>
/// 拼其他数据处理层接口
/// </summary>
interface IOtherPoolHandler
{
/// <summary>
/// 用户发布一条拼其他信息
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
bool Create(Item item);
/// <summary>
/// 显示所有拼其他信息
/// </summary>
/// <param name="page"></param>
/// <param name="n"></param>
/// <returns></returns>
List<user_item_pic> Show(int page, int n);
/// <summary>
/// 显示用户自己的拼其他信息
/// </summary>
/// <param name="uid"></param>
/// <returns></returns>
List<user_item_pic> ShowItemByUID(Guid uid);
/// <summary>
/// 查看具体的拼其他信息
/// </summary>
/// <param name="iid"></param>
/// <returns></returns>
List<user_item_pic> ShowItemInfo(Guid iid);
/// <summary>
/// 用户将拼其他信息的状态改为完成 403
/// </summary>
/// <param name="iid"></param>
/// <returns></returns>
bool ItemComplete(Guid iid);
/// <summary>
/// 拼其他信息过期,系统自动将状态改为401
/// </summary>
/// <param name="iid"></param>
/// <returns></returns>
bool ItemOverdue();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
namespace TradeWorkstation.Models
{
public class LoginForm
{
[MaxLength(16)]
[Required]
public string UserName { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataSource;
namespace DAL
{
/// <summary>
/// 收藏数据处理层接口
/// </summary>
public interface IStoreHandler
{
/// <summary>
/// 用户添加收藏
/// </summary>
/// <returns></returns>
bool Create(Store blacklist);
/// <summary>
/// 后台查看所有收藏记录
/// </summary>
/// <returns></returns>
List<Store> Show();
/// <summary>
/// 后台查看特定用户收藏记录
/// </summary>
/// <param name="uid"></param>
/// <returns></returns>
List<Store> ShowByUID(Guid uid);
/// <summary>
/// 后台查看特定商品被收藏记录
/// </summary>
/// <param name="iid"></param>
/// <returns></returns>
List<Store> ShowByIID(Guid iid);
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataSource;
namespace Common
{
public class Logger : ILogger
{
private static Logger _logger;
private static Guid _sysguid = new Guid("881B5532-5F62-4267-972F-074853FE4BDE");
public static Logger GetImpl()
{
_logger = _logger ?? new Logger();
return _logger;
}
public bool AddLog(string msg)
{
return AddLog(_sysguid, 0, msg);
}
public bool AddLog(Guid uid, int type, string msg)
{
try
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
db.SysLog.InsertOnSubmit(new SysLog { LID = Guid.NewGuid(), UID = uid, LogContent = msg, LogTime = DateTime.Now, Type = type });
db.SubmitChanges();
}
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}
}
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Common;
namespace TradeWorkstation.Tests.Common
{
[TestClass]
public class LoggerTest
{
private ILogger logger = Logger.GetImpl();
[TestMethod]
public void TestAddLog()
{
Assert.IsTrue(logger.AddLog("系统故障~!"));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DAL;
using DataSource;
namespace BLL
{
public class OtherPoolService
{
DAL.OtherPoolHandler otherPoolHandler = new DAL.OtherPoolHandler();
/// <summary>
/// 提交拼其他表单信息
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool Create(Item item)
{
return otherPoolHandler.Create(item);
}
/// <summary>
/// 分页显示拼其他信息
/// </summary>
/// <param name="page"></param>
/// <param name="n"></param>
/// <returns></returns>
public List<user_item_pic> Show(int page, int n)
{
return otherPoolHandler.Show(page, n);
}
/// <summary>
/// 显示具体拼其他信息
/// </summary>
/// <param name="iid"></param>
/// <returns></returns>
public List<user_item_pic> ShowItemInfo(Guid iid)
{
return otherPoolHandler.ShowItemInfo(iid);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Common
{
public interface ILogger
{
/// <summary>
/// 添加系统log
/// </summary>
/// <param name="msg">log信息</param>
/// <returns></returns>
bool AddLog(string msg);
/// <summary>
/// 添加log
/// </summary>
/// <param name="uid">用户id</param>
/// <param name="type">log类型 0 系统log 1管理员log 2用户log</param>
/// <param name="msg">log信息</param>
/// <returns></returns>
bool AddLog(Guid uid, int type, string msg);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataSource;
namespace DAL
{
public class BlackListHandler : IBlackListHandler
{
public bool Create(BlackList blacklist)
{
try
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
db.BlackList.InsertOnSubmit(blacklist);
db.SubmitChanges();
}
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}
}
public List<BlackList> Show()
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
var result = from o in db.BlackList
select o;
return result.ToList<BlackList>();
}
}
public List<BlackList> ShowByUID(Guid uid)
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
var result = from o in db.BlackList
where o.UID == uid
select o;
return result.ToList<BlackList>();
}
}
public List<BlackList> ShowByIID(Guid iid)
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
var result = from o in db.BlackList
where o.IID == iid
select o;
return result.ToList<BlackList>();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataSource;
using DAL;
namespace BLL
{
public class SellService
{
private static ISellHandler ish = new SellHandler();
public static bool InsertSellForm(Item item)
{
return ish.Create(item);
}
public static List<user_item_pic> Show(int page, int n)
{
return ish.Show(page, n);
}
public static user_item_pic ShowDetail(Guid iid)
{
return ish.ShowDetail(iid);
}
public static List<user_item_pic> ShowItemByUID(Guid uid, int page, int n)
{
return ish.ShowItemByUID(uid,page, n);
}
public static List<user_item_pic> ShowItemByCID(int cid, int page, int n)
{
return ish.ShowItemByCID(cid,page,n);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataSource;
namespace DAL
{
/// <summary>
/// 求购数据处理层接口
/// </summary>
public interface IBuyHandler
{
/// <summary>
/// 用户发布一条求购信息
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
bool Create(Item item);
/// <summary>
/// 显示所有求购信息
/// </summary>
/// <returns></returns>
List<user_item_pic> Show(int page);
/// <summary>
/// 显示用户自己的求购信息
/// </summary>
/// <param name="uid"></param>
/// <returns></returns>
List<user_item_pic> ShowItemByUID(Guid uid);
/// <summary>
/// 显示对应分类的商品
/// </summary>
/// <param name="cid">分类id</param>
/// <param name="page">页码</param>
/// <param name="n">一页显示几个</param>
/// <returns></returns>
List<user_item_pic> ShowItemByCID(int cid, int page, int n);
/// <summary>
/// 通过input显示求购信息
/// </summary>
/// <param name="input"></param>
/// <param name="page"></param>
/// <returns></returns>
List<user_item_pic> ShowItemByInput(string input, int page);
/// <summary>
/// 查看具体的求购信息
/// </summary>
/// <param name="iid"></param>
/// <returns></returns>
List<user_item_pic> ShowItemInfo(Guid iid);
/// <summary>
/// 用户将求购信息的状态改为完成 203
/// </summary>
/// <param name="iid"></param>
/// <returns></returns>
bool ItemComplete(Guid iid);
/// <summary>
/// 求购信息过期,系统自动将状态改为201
/// </summary>
/// <param name="iid"></param>
/// <returns></returns>
int ItemOverdue();
List<Category> GetFirstName(int cid);
string GetSecondName(int pid);
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BLL;
using DataSource;
using TradeWorkstation.Models;
namespace TradeWorkstation.Controllers
{
[Export]
[RoutePrefix("Other")]
public class OtherController : Controller
{
[Import]
public Hub.Interface.User.IAuthenticationStrategy AuthentiationStrategy { set; get; }
[Import]
public Hub.Interface.User.IAccountStrategy AccountStrategy { set; get; }
OtherPoolService otherPoolService = new OtherPoolService();
#region 拼其他表单提交
[HttpGet]
public ActionResult Add()
{
//用户
if (Session["User"] == null)
{
return Redirect("~/User/PostLogin");
}
Guid userid = new Guid(Session["User"].ToString());
ViewBag.UserID = userid;
ViewBag.NickName = AccountStrategy.GetNickNameByUserID(userid);
OtherForm other = new OtherForm();
return View(other);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Add(OtherForm other)
{
//用户
if (Session["User"] == null)
{
return Redirect("~/User/PostLogin");
}
Guid userid = new Guid(Session["User"].ToString());
ViewBag.UserID = userid;
ViewBag.NickName = AccountStrategy.GetNickNameByUserID(userid);
if (!other.agreement)
{
return Content("<script>alert('请同意协议');history.go(-1);</script>");
}
if (!ModelState.IsValid)
{
return Content("<script>alert('表单信息验证失败,请重新填写');history.go(-1);</script>");
}
Item item = new Item();
item.UID = new Guid(Session["User"].ToString());
item.Title = other.title;
DateTime? dateOrNull = other.endtime;
if (dateOrNull != null)
{
item.EndTime = dateOrNull.Value;
}
else
{
//如果没填EndTime,默认为2个月
item.EndTime = DateTime.Now.AddMonths(2);
}
item.Detail = other.detail;
string qq = other.qq;
string tel = other.tel;
//判断QQ或手机至少填一项的那个东西....
if (qq == null && tel == null)
{
return Content("<script>alert('QQ或手机至少填一项');history.go(-1);</script>");
}
else if (qq != null && tel == null)
{
item.QQ = qq;
}
else if (tel != null && qq == null)
{
item.Tel = tel;
}
else if (tel != null && qq != null)
{
item.QQ = qq;
item.Tel = tel;
}
if (otherPoolService.Create(item))
{
return Content("<script>alert('发布成功!');location.href='Search/Page/1';</script>");
}
else
{
return Content("<script>alert('插入数据出现异常');</script>");
}
}
#endregion 拼其他表单提交
#region 拼其他检索
[HttpGet]
[Route("Search/Page/{page:int}")]
public ActionResult Search(int page)
{
//用户
if (Session["User"] == null)
{
return Redirect("~/User/PostLogin");
}
Guid userid = new Guid(Session["User"].ToString());
ViewBag.UserID = userid;
ViewBag.NickName = AccountStrategy.GetNickNameByUserID(userid);
ViewData.Model = otherPoolService.Show(page,7);
return View();
}
[HttpGet]
[Route("Search/IID/{iid}")]
public ActionResult Search(Guid iid)
{
//用户
if (Session["User"] == null)
{
return Redirect("~/User/PostLogin");
}
Guid userid = new Guid(Session["User"].ToString());
ViewBag.UserID = userid;
ViewBag.NickName = AccountStrategy.GetNickNameByUserID(userid);
ViewData.Model = otherPoolService.ShowItemInfo(iid);
return View();
}
#endregion 拼其他检索
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataSource;
namespace DAL
{
public class CarPoolHandler:ICarPoolHandler
{
public bool Create(Item item)
{
try
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
item.IID = Guid.NewGuid();
item.Type = 3;
item.PostTime = DateTime.Now;
item.UpdateTime = DateTime.Now;
DateTime? dateOrNull = item.RunTime;
if (dateOrNull != null)
{
item.EndTime = dateOrNull.Value;
}
item.Status = 302;
db.Item.InsertOnSubmit(item);
db.SubmitChanges();
}
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}
}
public List<user_item_pic> Show(int page, int n)
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
GHYUsersDataContext db2 = new GHYUsersDataContext();
List<User> userList = db2.User.ToList<User>();
List<Item> itemList = db.Item.ToList<Item>();
var result = from item in itemList
join user in userList on item.UID equals user.UserID
where (item.Type == 3) && (item.Status == 302)
orderby item.PostTime descending
select new user_item_pic
{
IID = item.IID,
NickName = user.NickName,
Title = item.Title,
Detail = item.Detail,
RunTime = (DateTime)item.RunTime,
From = item.From,
To = item.To,
PostTime = item.PostTime,
QQ = item.QQ,
Tel = item.Tel
};
return result.Skip(n * (page - 1)).Take(n).ToList<user_item_pic>();
}
}
public List<user_item_pic> ShowItemByUID(Guid uid)
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
GHYUsersDataContext db2 = new GHYUsersDataContext();
List<User> userList = db2.User.ToList<User>();
List<Item> itemList = db.Item.ToList<Item>();
var result = from item in itemList
join user in userList on item.UID equals user.UserID
where (item.Type == 3) && (item.Status == 302) && (item.UID == uid)
orderby item.PostTime descending
select new user_item_pic
{
IID = item.IID,
NickName = user.NickName,
Title = item.Title,
Detail = item.Detail,
RunTime = (DateTime)item.RunTime,
From = item.From,
To = item.To,
PostTime = item.PostTime,
QQ = item.QQ,
Tel = item.Tel
};
return result.ToList<user_item_pic>();
}
}
public List<user_item_pic> ShowItemByInfo(DateTime runtime, string carFrom, string carTo)
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
GHYUsersDataContext db2 = new GHYUsersDataContext();
List<User> userList = db2.User.ToList<User>();
List<Item> itemList = db.Item.ToList<Item>();
var result = from item in itemList
join user in userList on item.UID equals user.UserID
where item.Type == 3 && item.Status == 302 && item.RunTime == runtime && item.From.IndexOf(carFrom) != -1 && item.To.IndexOf(carTo) != -1
orderby item.PostTime descending
select new user_item_pic
{
IID = item.IID,
NickName = user.NickName,
Title = item.Title,
Detail = item.Detail,
RunTime = (DateTime)item.RunTime,
From = item.From,
To = item.To,
PostTime = item.PostTime,
QQ = item.QQ,
Tel = item.Tel
};
return result.ToList<user_item_pic>();
}
}
public List<user_item_pic> ShowItemByTag(string tag, int page)
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
using (GHYUsersDataContext db2 = new GHYUsersDataContext())
{
List<User> userList = db2.User.ToList<User>();
List<Item> itemList = db.Item.ToList<Item>();
var result = from item in itemList
join user in userList on item.UID equals user.UserID
where item.Type == 3 && item.Status == 302 && (item.From.IndexOf(tag) != -1 || item.To.IndexOf(tag) != -1)
orderby item.PostTime descending
select new user_item_pic
{
IID = item.IID,
NickName = user.NickName,
Title = item.Title,
Detail = item.Detail,
RunTime = (DateTime)item.RunTime,
From = item.From,
To = item.To,
PostTime = item.PostTime,
QQ = item.QQ,
Tel = item.Tel
};
return result.Skip(7 * (page - 1)).Take(7).ToList<user_item_pic>();
}
}
}
public List<user_item_pic> ShowItemInfo(Guid iid)
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
GHYUsersDataContext db2 = new GHYUsersDataContext();
List<User> userList = db2.User.ToList<User>();
List<Item> itemList = db.Item.ToList<Item>();
var result = from item in itemList
join user in userList on item.UID equals user.UserID
where (item.IID == iid) && (item.Type == 3) && (item.Status == 302)
orderby item.PostTime descending
select new user_item_pic
{
IID = item.IID,
NickName = user.NickName,
Title = item.Title,
Detail = item.Detail,
RunTime = (DateTime)item.RunTime,
From = item.From,
To = item.To,
PostTime = item.PostTime,
QQ = item.QQ,
Tel = item.Tel
};
return result.ToList<user_item_pic>();
}
}
public bool DelItem(Guid iid)
{
try
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
var result = from o in db.Item
where o.IID == iid && o.Status == 302
select o;
result.Single().Status = 301;
db.SubmitChanges();
}
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}
}
public bool ItemOverdue()
{
try
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
var result = from o in db.Item
where o.Type == 3 && DateTime.Compare(DateTime.Now, o.EndTime) > 0 && o.Status == 302
select o;
foreach (Item o in result)
{
o.Status = 303;
}
db.SubmitChanges();
}
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace TradeWorkstation.Models
{
public class SellForm
{
[Required(ErrorMessage = "标题必填")]
[Display(Name = "商品名称")]
[DataType(DataType.Text)]
[MinLength(1)]
[MaxLength(50, ErrorMessage = "标题50字以内")]
public string title { get; set; }
[Required(ErrorMessage = "价格必填")]
[Display(Name = "价格")]
[DataType(DataType.Text)]
public int price { get; set; }
[Required(ErrorMessage = "详细信息必填")]
[Display(Name = "详细信息")]
[DataType(DataType.Text)]
[MinLength(1)]
public string detail { get; set; }
[RegularExpression("[0-9]+")]
[Display(Name = "QQ")]
[MinLength(1)]
[MaxLength(50, ErrorMessage = "QQ号50字以内")]
public string qq { get; set; }
[DataType(DataType.PhoneNumber, ErrorMessage = "请填写正确格式手机号")]
[Display(Name = "手机")]
[MinLength(1)]
[MaxLength(50, ErrorMessage = "手机号50字以内")]
public string tel { get; set; }
public string firstList { get; set; }
public string secondList { get; set; }
[Required(ErrorMessage = "请同意协议")]
public bool agreement { get; set; }
}
}<file_sep>$(function () {
/*if (document.documentElement.clientHeight >= document.documentElement.offsetHeight) {
$("footer").addClass("footer-fixed");
} else {
$("footer").removeClass("footer-fixed");
}*/
//延迟加载
$(".scrollLoading").scrollLoading();
});<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace TradeWorkstation
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();//mvc5
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
#region 用户查询求购二级搜索路由配置
routes.MapRoute(
name: "BuySearch",
url: "Buy/search/Order/{order}/Type/{type}/Page/{page}",
defaults: new { controller ="Buy",action="Index"},
constraints: new { order = @"\d", page = @"[1-9][0-9]*" }
);
#endregion
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataSource;
using DAL;
namespace BLL
{
public class CenterService
{
DAL.StoreHandler storeHandler = new StoreHandler();
/// <summary>
/// 插入一条收藏
/// </summary>
/// <param name="store"></param>
/// <returns></returns>
public bool Create(Store store)
{
return storeHandler.Create(store);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DAL;
using DataSource;
namespace BLL
{
public class CarPoolService
{
DAL.CarPoolHandler carPoolHandler = new DAL.CarPoolHandler();
/// <summary>
/// 提交拼车表单信息
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool Create(Item item)
{
return carPoolHandler.Create(item);
}
/// <summary>
/// 显示所有未过期的拼车信息
/// </summary>
/// <param name="page"></param>
/// <param name="n"></param>
/// <returns></returns>
public List<user_item_pic> Show(int page, int n)
{
return carPoolHandler.Show(page, n);
}
/// <summary>
/// 拼车检索
/// </summary>
/// <param name="runtime"></param>
/// <param name="carFrom"></param>
/// <param name="carTo"></param>
/// <returns></returns>
public List<user_item_pic> ShowItemByInfo(DateTime runtime, string carFrom, string carTo)
{
return carPoolHandler.ShowItemByInfo(runtime, carFrom, carTo);
}
/// <summary>
/// 拼车标签检索
/// </summary>
/// <param name="tag"></param>
/// <param name="page"></param>
/// <returns></returns>
public List<user_item_pic> ShowItemByTag(string tag, int page)
{
return carPoolHandler.ShowItemByTag(tag, page);
}
/// <summary>
/// 根据IID显示拼车信息
/// </summary>
/// <param name="iid"></param>
/// <returns></returns>
public List<user_item_pic> ShowItemInfo(Guid iid)
{
return carPoolHandler.ShowItemInfo(iid);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataSource;
namespace DAL
{
public class OtherPoolHandler:IOtherPoolHandler
{
public bool Create(Item item)
{
try
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
item.IID = Guid.NewGuid();
item.Type = 4;
item.PostTime = DateTime.Now;
item.UpdateTime = DateTime.Now;
item.Status = 402;
db.Item.InsertOnSubmit(item);
db.SubmitChanges();
}
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}
}
public List<user_item_pic> Show(int page,int n)
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
GHYUsersDataContext db2 = new GHYUsersDataContext();
List<User> userList = db2.User.ToList<User>();
List<Item> itemList = db.Item.ToList<Item>();
var result = from item in itemList
join user in userList on item.UID equals user.UserID
where (item.Type == 4) && (item.Status == 402)
orderby item.PostTime descending
select new user_item_pic
{
IID = item.IID,
NickName = user.NickName,
Title = item.Title,
Detail = item.Detail,
PostTime = item.PostTime,
QQ = item.QQ,
Tel = item.Tel
};
return result.Skip(n * (page - 1)).Take(n).ToList<user_item_pic>();
}
}
public List<user_item_pic> ShowItemByUID(Guid uid)
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
GHYUsersDataContext db2 = new GHYUsersDataContext();
List<User> userList = db2.User.ToList<User>();
List<Item> itemList = db.Item.ToList<Item>();
var result = from item in itemList
join user in userList on item.UID equals user.UserID
where (user.UserID == uid) && (item.Type == 4) && (item.Status == 402)
orderby item.PostTime descending
select new user_item_pic
{
IID = item.IID,
NickName = user.NickName,
Title = item.Title,
Detail = item.Detail,
PostTime = item.PostTime,
QQ = item.QQ,
Tel = item.Tel
};
return result.ToList<user_item_pic>();
}
}
public List<user_item_pic> ShowItemInfo(Guid iid)
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
GHYUsersDataContext db2 = new GHYUsersDataContext();
List<User> userList = db2.User.ToList<User>();
List<Item> itemList = db.Item.ToList<Item>();
var result = from item in itemList
join user in userList on item.UID equals user.UserID
where (item.IID == iid) && (item.Type == 4) && (item.Status == 402)
orderby item.PostTime descending
select new user_item_pic
{
IID = item.IID,
NickName = user.NickName,
Title = item.Title,
Detail = item.Detail,
PostTime = item.PostTime,
QQ = item.QQ,
Tel = item.Tel
};
return result.ToList<user_item_pic>();
}
}
public bool ItemComplete(Guid iid)
{
try
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
var result = from o in db.Item
where o.IID == iid && o.Status == 402
select o;
result.Single().Status = 403;
db.SubmitChanges();
}
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}
}
public bool ItemOverdue()
{
try
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
var result = from o in db.Item
where o.Type == 4 && DateTime.Compare(DateTime.Now, o.EndTime) > 0 && o.Status == 402
select o;
foreach (Item o in result)
{
o.Status = 401;
}
db.SubmitChanges();
}
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataSource;
using DAL;
namespace BLL
{
public class BuyService
{
private static IBuyHandler ibh = new BuyHandler();
public static bool InsertBuyForm(Item item)
{
return ibh.Create(item);
}
public static List<user_item_pic> Show(int page)
{
return ibh.Show(page);
}
public static List<user_item_pic> ShowItemByCID(int cid, int page, int n)
{
return ibh.ShowItemByCID(cid, page, n);
}
public static List<user_item_pic> ShowItemInfo(Guid iid)
{
return ibh.ShowItemInfo(iid);
}
public static List<user_item_pic> GetSearchList(string input, int page)
{
return ibh.ShowItemByInput(input, page);
}
public static List<Category> GetFirstName(int cid)
{
return ibh.GetFirstName(cid);
}
public static string GetSecondName(int pid)
{
return ibh.GetSecondName(pid);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataSource;
namespace DAL
{
/// <summary>
/// 二手数据处理层接口
/// </summary>
public interface ISellHandler
{
/// <summary>
/// 用户发布一条二手信息
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
bool Create(Item item);
/// <summary>
/// 显示所有二手信息
/// </summary>
/// <param name="page"></param>
/// <param name="n"></param>
/// <returns></returns>
List<user_item_pic> Show(int page, int n);
/// <summary>
/// 显示二手详情
/// </summary>
/// <param name="iid"></param>
/// <returns></returns>
user_item_pic ShowDetail(Guid iid);
/// <summary>
/// 显示用户所有二手信息
/// </summary>
/// <param name="uid"></param>
/// <param name="page"></param>
/// <returns></returns>
List<user_item_pic> ShowItemByUID(Guid uid, int page, int n);
/// <summary>
/// 显示对应类别的商品
/// </summary>
/// <param name="cid">类别id</param>
/// <param name="page">第几页</param>
/// <param name="n">一页几个</param>
/// <returns></returns>
List<user_item_pic> ShowItemByCID(int cid, int page, int n);
/// <summary>
/// 用户将二手信息的状态改为完成 103
/// </summary>
/// <param name="iid"></param>
/// <returns></returns>
bool ItemComplete(Guid iid);
/// <summary>
/// 二手商品信息过期,系统自动将状态改为 101
/// </summary>
/// <param name="iid"></param>
/// <returns></returns>
int ItemOverdue();
/// <summary>
/// 用户更新二手商品信息(Title Price Detail Tel QQ Way UpdateTime)
/// </summary>
/// <param name="iid"></param>
/// <returns></returns>
int UpdateItem(Item item);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataSource;
namespace DAL
{
/// <summary>
/// 举报数据处理层接口
/// </summary>
interface IBlackListHandler
{
/// <summary>
/// 用户添加举报
/// </summary>
/// <returns></returns>
bool Create(BlackList blacklist);
/// <summary>
/// 后台查看所有举报记录
/// </summary>
/// <returns></returns>
List<BlackList> Show();
/// <summary>
/// 后台查看特定用户举报记录
/// </summary>
/// <param name="uid"></param>
/// <returns></returns>
List<BlackList> ShowByUID(Guid uid);
/// <summary>
/// 后台查看特定商品被举报记录
/// </summary>
/// <param name="iid"></param>
/// <returns></returns>
List<BlackList> ShowByIID(Guid iid);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataSource;
namespace DAL
{
public class PicHandler : IPicHandler
{
public bool Create(Pic pic)
{
try
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
pic.PID = Guid.NewGuid();
pic.Status = 1;
db.Pic.InsertOnSubmit(pic);
db.SubmitChanges();
}
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}
}
public List<Pic> ShowByIID(Guid iid)
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
var result = from a in db.Pic
where a.IID == iid
where a.Status > 0
orderby a.Order ascending
select a;
return result.ToList<Pic>();
}
}
public string GetPicUrl(Guid pid)
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
var result = from a in db.Pic
where a.PID == pid
select a;
return result.Single().Url;
}
}
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using DataSource;
using DAL;
using BLL;
namespace TradeWorkstation.Tests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
//user_item_pic good = SellService.ShowDetail(new Guid("a5c5ca86-122b-4bc4-8256-74345624c75f"));
CarPoolService carPoolService = new CarPoolService();
var results = carPoolService.ShowItemByTag("西南财经大学柳林校区", 1);
Console.WriteLine(results.Count);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
namespace TradeWorkstation.Models
{
public class OtherForm
{
[Required(ErrorMessage = "标题必填")]
[Display(Name = "标题")]
[DataType(DataType.Text)]
[MinLength(1)]
[MaxLength(50, ErrorMessage = "标题50字以内")]
public string title { get; set; }
[Display(Name = "失效时间")]
[DataType(DataType.DateTime)]
public DateTime endtime { get; set; }
[Required(ErrorMessage = "详细信息必填")]
[Display(Name = "详细信息")]
[DataType(DataType.Text)]
[MinLength(1)]
public string detail { get; set; }
[RegularExpression("[0-9]+")]
[Display(Name = "QQ")]
[MinLength(1)]
[MaxLength(50, ErrorMessage = "QQ号50字以内")]
public string qq { get; set; }
[DataType(DataType.PhoneNumber, ErrorMessage = "请填写正确格式手机号")]
[Display(Name = "手机")]
[MinLength(1)]
[MaxLength(50, ErrorMessage = "手机号50字以内")]
public string tel { get; set; }
[Required(ErrorMessage = "请同意协议")]
public bool agreement { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataSource;
namespace DAL
{
/// <summary>
/// 拼车数据处理层接口
/// </summary>
interface ICarPoolHandler
{
/// <summary>
/// 用户发布一条拼车信息
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
bool Create(Item item);
/// <summary>
/// 显示所有拼车信息
/// </summary>
/// <param name="page"></param>
/// <param name="n">一页显示几个</param>
/// <returns></returns>
List<user_item_pic> Show(int page, int n);
/// <summary>
/// 显示用户自己的拼车信息
/// </summary>
/// <param name="uid"></param>
/// <returns></returns>
List<user_item_pic> ShowItemByUID(Guid uid);
/// <summary>
/// 拼车检索
/// </summary>
/// <param name="runtime"></param>
/// <param name="carFrom"></param>
/// <param name="carTo"></param>
/// <returns></returns>
List<user_item_pic> ShowItemByInfo(DateTime runtime, string carFrom, string carTo);
/// <summary>
/// 拼车标签检索
/// </summary>
/// <param name="tag"></param>
/// <param name="page"></param>
/// <returns></returns>
List<user_item_pic> ShowItemByTag(string tag, int page);
/// <summary>
/// 查看具体的求购信息
/// </summary>
/// <param name="iid"></param>
/// <returns></returns>
List<user_item_pic> ShowItemInfo(Guid iid);
/// <summary>
/// 用户删除拼车信息 301
/// </summary>
/// <param name="iid"></param>
/// <returns></returns>
bool DelItem(Guid iid);
/// <summary>
/// 拼车信息过期,系统自动将状态改为 303
/// </summary>
/// <param name="iid"></param>
/// <returns></returns>
bool ItemOverdue();
}
}
<file_sep>using System;
using System.IO;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Data;
using DataSource;
using DAL;
namespace BLL
{
public class PicService
{
private static IPicHandler iph = new PicHandler();
public static bool InsertPic(Pic pic)
{
return iph.Create(pic);
}
public static List<Pic> ShowByIID(Guid iid)
{
return iph.ShowByIID(iid);
}
public static string GetPicUrl(Guid pid)
{
return iph.GetPicUrl(pid);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Optimization;
namespace TradeWorkstation
{
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
//shared
bundles.Add(new StyleBundle("~/bundles/styles").Include(
"~/Resources/Bootstrap/css/bootstrap.min.css",
"~/Resources/Bootstrap/css/bootstrap-datetimepicker.min.css",
"~/Resources/Trunk/trunk.css",
"~/Resources/Site/css/common.css"));
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Resources/JQuery/jquery-1.11.3.min.js"));
bundles.Add(new ScriptBundle("~/bundles/scripts").Include(
"~/Resources/Bootstrap/js/bootstrap.js",
"~/Resources/JQuery/jquery.scrollLoading.js",
"~/Resources/Trunk/trunk.js",
"~/Resources/Bootstrap/js/bootstrap-datetimepicker.min.js",
"~/Resources/Bootstrap/js/datetimepicker.config.js",
"~/Resources/Site/js/common.js"));
bundles.Add(new ScriptBundle("~/bundles/ie8").Include(
"~/Resources/Bootstrap/js/modernizr-2.6.2.js",
"~/Resources/Bootstrap/js/respond.js"));
//index
bundles.Add(new ScriptBundle("~/bundles/index_scripts").Include(
"~/Resources/Site/js/bzbanner.min.js",
"~/Resources/Site/js/index.js"));
bundles.Add(new StyleBundle("~/bundles/index_styles").Include(
"~/Resources/Site/css/index.css"));
//publish
bundles.Add(new StyleBundle("~/bundles/publish_styles").Include(
"~/Resources/Site/css/publish.css"));
//add
bundles.Add(new StyleBundle("~/bundles/add_styles").Include(
"~/Resources/Site/css/form.css"));
//show
bundles.Add(new StyleBundle("~/bundles/show_styles").Include(
"~/Resources/Site/css/show.css"));
//detail
bundles.Add(new ScriptBundle("~/bundles/detail_scripts").Include(
"~/Resources/Site/js/detail.js"));
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using BLL;
using DataSource;
using TradeWorkstation.Models;
namespace TradeWorkstation.Controllers
{
[Export]
[RoutePrefix("Car")]
public class CarController : Controller
{
[Import]
public Hub.Interface.User.IAuthenticationStrategy AuthentiationStrategy { set; get; }
[Import]
public Hub.Interface.User.IAccountStrategy AccountStrategy { set; get; }
CarPoolService carPoolService = new CarPoolService();
#region 拼车表单提交
[HttpGet]
public ActionResult Add()
{
//用户
if (Session["User"] == null)
{
return Redirect("~/User/PostLogin");
}
Guid userid = new Guid(Session["User"].ToString());
ViewBag.UserID = userid;
ViewBag.NickName = AccountStrategy.GetNickNameByUserID(userid);
CarForm car = new CarForm();
return View(car);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Add(CarForm car)
{
//用户
if (Session["User"] == null)
{
return Redirect("~/User/PostLogin");
}
Guid userid = new Guid(Session["User"].ToString());
ViewBag.UserID = userid;
ViewBag.NickName = AccountStrategy.GetNickNameByUserID(userid);
if (!car.agreement)
{
return Content("<script>alert('请同意协议');history.go(-1);</script>");
}
if (!ModelState.IsValid)
{
return Content("<script>alert('表单信息验证失败,请重新填写');history.go(-1);</script>");
}
Item item = new Item();
item.UID = new Guid(Session["User"].ToString());
item.Title = car.title;
item.RunTime = car.runtime;
item.From = car.carFrom;
item.To = car.carTo;
item.Detail = car.detail;
string qq = car.qq;
string tel = car.tel;
//判断QQ或手机至少填一项的那个东西....
if (qq == null && tel == null)
{
return Content("<script>alert('QQ或手机至少填一项');history.go(-1);</script>");
}
else if (qq != null && tel == null)
{
item.QQ = qq;
}
else if (tel != null && qq == null)
{
item.Tel = tel;
}
else if (tel != null && qq != null)
{
item.QQ = qq;
item.Tel = tel;
}
if (carPoolService.Create(item))
{
return Content("<script>alert('发布成功!');location.href='Search/Page/1';</script>");
}
else
{
return Content("<script>alert('插入数据出现异常');</script>");
}
}
#endregion 拼车表单提交
#region 拼车检索
[HttpGet]
[Route("Search/Page/{page:int}")]
public ActionResult Search(int page)
{
//用户
if (Session["User"] == null)
{
return Redirect("~/User/PostLogin");
}
Guid userid = new Guid(Session["User"].ToString());
ViewBag.UserID = userid;
ViewBag.NickName = AccountStrategy.GetNickNameByUserID(userid);
ViewData.Model = carPoolService.Show(page,7);
return View();
}
[HttpPost]
[Route("Search")]
public ActionResult Search(DateTime runtime, string from, string to)
{
//用户
if (Session["User"] == null)
{
return Redirect("~/User/PostLogin");
}
Guid userid = new Guid(Session["User"].ToString());
ViewBag.UserID = userid;
ViewBag.NickName = AccountStrategy.GetNickNameByUserID(userid);
ViewData.Model = carPoolService.ShowItemByInfo(runtime, from, to);
return View();
}
[HttpGet]
[Route("Search/Tag/{tag}/Page/{page:int}")]
public ActionResult Search(string tag, int page)
{
//用户
if (Session["User"] == null)
{
return Redirect("~/User/PostLogin");
}
Guid userid = new Guid(Session["User"].ToString());
ViewBag.UserID = userid;
ViewBag.NickName = AccountStrategy.GetNickNameByUserID(userid);
ViewData.Model = carPoolService.ShowItemByTag(tag,page);
return View();
}
[HttpGet]
[Route("Search/IID/{iid}")]
public ActionResult Search(string iid)
{
//用户
if (Session["User"] == null)
{
return Redirect("~/User/PostLogin");
}
Guid userid = new Guid(Session["User"].ToString());
ViewBag.UserID = userid;
ViewBag.NickName = AccountStrategy.GetNickNameByUserID(userid);
ViewData.Model = carPoolService.ShowItemInfo(new Guid(iid));
return View();
}
#endregion 拼车检索
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DataSource;
using BLL;
namespace TradeWorkstation.Controllers
{
[Export]
[RoutePrefix("Buy")]
public class BuyController : Controller
{
[Import]
public Hub.Interface.User.IAuthenticationStrategy AuthentiationStrategy { set; get; }
[Import]
public Hub.Interface.User.IAccountStrategy AccountStrategy { set; get; }
[HttpGet]
public ActionResult Add()
{
//用户
if (Session["User"] == null)
{
return Redirect("~/User/PostLogin");
}
Guid userid = new Guid(Session["User"].ToString());
ViewBag.UserID = userid;
ViewBag.NickName = AccountStrategy.GetNickNameByUserID(userid);
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Add(Models.BuyForm bf)
{
//用户
if (Session["User"] == null)
{
return Redirect("~/User/PostLogin");
}
Guid userid = new Guid(Session["User"].ToString());
ViewBag.UserID = userid;
ViewBag.NickName = AccountStrategy.GetNickNameByUserID(userid);
if (!bf.agreement)
{
return Content("<script>alert('请同意协议');history.go(-1);</script>");
}
if (!ModelState.IsValid)
{
return Content("<script>alert('表单信息验证失败,请重新填写');</script>");
}
else
{
Item item = new Item();
item.Title = bf.title;
item.CID = bf.secondList == "0" ? Int32.Parse(bf.firstList) : Int32.Parse(bf.secondList);
item.UID = new Guid(Session["User"].ToString());
item.Detail = bf.detail;
item.Tel = bf.tel;
string qq = bf.qq;
string tel = bf.tel;
//判断QQ或手机至少填一项的那个东西....
if (qq == null && tel == null)
{
return Content("<script>alert('QQ或手机至少填一项');history.go(-1);</script>");
}
else if (qq != null && tel == null)
{
item.QQ = qq;
}
else if (tel != null && qq == null)
{
item.Tel = tel;
}
else if (tel != null && qq != null)
{
item.QQ = qq;
item.Tel = tel;
}
if (BuyService.InsertBuyForm(item))
{
return Content("<script>alert('发布成功');location.href='Search/Page/1';</script>");
}
else
{
return Content("<script>alert('插入数据出现异常');</script>");
}
}
}
[HttpGet]
[Route("Search/Page/{page:int}")]
public ActionResult Search(int page)
{
//用户
if (Session["User"] == null)
{
return Redirect("~/User/PostLogin");
}
Guid userid = new Guid(Session["User"].ToString());
ViewBag.UserID = userid;
ViewBag.NickName = AccountStrategy.GetNickNameByUserID(userid);
ViewData.Model = BuyService.Show(page);
return View();
}
[HttpGet]
[Route("Search/Cid/{cid}/Page/{page:int}")]
public ActionResult Search(int cid, int page)
{
//用户
if (Session["User"] == null)
{
return Redirect("~/User/PostLogin");
}
Guid userid = new Guid(Session["User"].ToString());
ViewBag.UserID = userid;
ViewBag.NickName = AccountStrategy.GetNickNameByUserID(userid);
ViewData.Model = BuyService.ShowItemByCID(cid,page,7);
return View();
}
[HttpGet]
[Route("Search/Input/{input}/Page/{page:int}")]
public ActionResult Search(string input, int page)
{
//用户
if (Session["User"] == null)
{
return Redirect("~/User/PostLogin");
}
Guid userid = new Guid(Session["User"].ToString());
ViewBag.UserID = userid;
ViewBag.NickName = AccountStrategy.GetNickNameByUserID(userid);
var vm = BuyService.GetSearchList(input, page);
ViewData.Model = vm;
return View();
}
[HttpGet]
[Route("Search/IID/{iid}")]
public ActionResult Search(string iid)
{
//用户
if (Session["User"] == null)
{
return Redirect("~/User/PostLogin");
}
Guid userid = new Guid(Session["User"].ToString());
ViewBag.UserID = userid;
ViewBag.NickName = AccountStrategy.GetNickNameByUserID(userid);
ViewData.Model = BuyService.ShowItemInfo(new Guid(iid));
return View();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DAL;
using DataSource;
namespace BLL
{
public class StoreService
{
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TradeWorkstation.Models;
using BLL;
namespace TradeWorkstation.Controllers
{
[Export]
[RoutePrefix("Home")]
public class HomeController : Controller
{
[Import]
public Hub.Interface.User.IAuthenticationStrategy AuthentiationStrategy { set; get; }
[Import]
public Hub.Interface.User.IAccountStrategy AccountStrategy { set; get; }
public ActionResult Index()
{
//用户
if (Session["User"] == null)
{
return Redirect("~/User/PostLogin");
}
Guid userid = new Guid(Session["User"].ToString());
ViewBag.UserID = userid;
ViewBag.NickName = AccountStrategy.GetNickNameByUserID(userid);
//二货
ViewData["class11"] = SellService.ShowItemByCID(11, 1, 4);//教科书
ViewData["class12"] = SellService.ShowItemByCID(12, 1, 4);//考研用书
ViewData["class13"] = SellService.ShowItemByCID(13, 1, 4);//考级考证
ViewData["class14"] = SellService.ShowItemByCID(14, 1, 4);//课外书
ViewData["class15"] = SellService.ShowItemByCID(17, 1, 4);//电脑
ViewData["class16"] = SellService.ShowItemByCID(18, 1, 4);//平板
ViewData["class21"] = SellService.ShowItemByCID(9, 1, 4);//自行车
ViewData["class22"] = SellService.ShowItemByCID(30, 1, 4);//小电器
ViewData["class23"] = SellService.ShowItemByCID(33, 1, 4);//化妆品
ViewData["class24"] = SellService.ShowItemByCID(9, 1, 4);//服装.。。。。。这个是大类
ViewData["class31"] = SellService.ShowItemByCID(32, 1, 4);//运动
ViewData["class32"] = SellService.ShowItemByCID(16, 1, 4);//手机
ViewData["class33"] = SellService.ShowItemByCID(20, 1, 4);//相机
ViewData["class34"] = SellService.ShowItemByCID(21, 1, 4);//MP3\MP4
ViewData["class35"] = SellService.ShowItemByCID(7, 1, 4);//虚拟物品
ViewData["class36"] = SellService.ShowItemByCID(19, 1, 4);//游戏机
//最新求购(显示7条)
ViewData["buy"] = BuyService.Show(1);
//最新求拼(3条拼车、3条拼其他)
ViewData["car"] = new CarPoolService().Show(1,3);
ViewData["other"] = new OtherPoolService().Show(1, 3);
return View();
}
public ActionResult Publish()
{
//用户
if (Session["User"] == null)
{
return Redirect("~/User/PostLogin");
}
Guid userid = new Guid(Session["User"].ToString());
ViewBag.UserID = userid;
ViewBag.NickName = AccountStrategy.GetNickNameByUserID(userid);
return View();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
namespace TradeWorkstation.Models
{
public class CarForm
{
[Required(ErrorMessage = "标题必填")]
[Display(Name="标题")]
[DataType(DataType.Text)]
[MinLength(1)]
[MaxLength(50, ErrorMessage = "标题50字以内")]
public string title { get; set; }
[Required(ErrorMessage = "出发时间必填")]
[Display(Name = "出发时间")]
[DataType(DataType.DateTime)]
public DateTime runtime { get; set; }
[Required(ErrorMessage = "出发地必填")]
[Display(Name = "出发地")]
[DataType(DataType.Text)]
[MinLength(1)]
[MaxLength(100, ErrorMessage = "出发地100字以内")]
public string carFrom { get; set; }
[Required(ErrorMessage = "目的地必填")]
[Display(Name = "目的地")]
[DataType(DataType.Text)]
[MinLength(1)]
[MaxLength(100, ErrorMessage = "目的地100字以内")]
public string carTo { get; set; }
[Required(ErrorMessage = "详细信息必填")]
[Display(Name = "详细信息")]
[DataType(DataType.Text)]
[MinLength(1)]
public string detail { get; set; }
[RegularExpression("[0-9]+")]
[Display(Name = "QQ")]
[MinLength(1)]
[MaxLength(50, ErrorMessage = "QQ号50字以内")]
public string qq { get; set; }
[DataType(DataType.PhoneNumber, ErrorMessage = "请填写正确格式手机号")]
[Display(Name = "手机")]
[MinLength(1)]
[MaxLength(50, ErrorMessage = "手机号50字以内")]
public string tel { get; set; }
[Required(ErrorMessage="请同意协议")]
public bool agreement { get; set; }
}
public class CarSearchForm
{
[Required(ErrorMessage = "出发时间必填")]
[Display(Name = "出发时间")]
[DataType(DataType.DateTime)]
public DateTime runtime { get; set; }
[Required(ErrorMessage = "出发地必填")]
[Display(Name = "出发地")]
[DataType(DataType.Text)]
[MinLength(1)]
[MaxLength(100, ErrorMessage = "出发地100字以内")]
public string carFrom { get; set; }
[Required(ErrorMessage = "目的地必填")]
[Display(Name = "目的地")]
[DataType(DataType.Text)]
[MinLength(1)]
[MaxLength(100, ErrorMessage = "目的地100字以内")]
public string carTo { get; set; }
}
}<file_sep>$(function () {
var $big_pic_img = $(".big-pic img");
var $mini_box_pic_img = $(".mini-box-pic>img");
$(".mini-box-pic>img:first").addClass("img-on");
//二货详情-图片轮播
$mini_box_pic_img.mouseover(function () {
$mini_box_pic_img.removeClass("img-on");
$(this).addClass("img-on");
$new_pic_url = $(this).attr("src");
var pid = $new_pic_url.split("/")[5];
$big_pic_img.attr("src", "/TradeWorkstation/PicPool/Get/ID/"+pid+"/Size/700x700");
}).mouseleave(function () {
var $big_pid = $big_pic_img.attr("src").split("/")[5];
var $small_pid = $(this).attr("src").split("/")[5];
if ($big_pid != $small_pid) {
$(this).removeClass("img-on");
}
});
});<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataSource;
namespace DAL
{
public class StoreHandler:IStoreHandler
{
public bool Create(Store store)
{
try
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
store.SID = Guid.NewGuid();
store.StoreTime = DateTime.Now;
store.Status = 1;
db.Store.InsertOnSubmit(store);
db.SubmitChanges();
}
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}
}
public List<Store> Show()
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
var result = from o in db.Store
select o;
return result.ToList<Store>();
}
}
public List<Store> ShowByUID(Guid uid)
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
var result = from o in db.Store
where o.UID == uid
select o;
return result.ToList<Store>();
}
}
public List<Store> ShowByIID(Guid iid)
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
var result = from o in db.Store
where o.IID == iid
select o;
return result.ToList<Store>();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataSource;
namespace DAL
{
public class SellHandler : ISellHandler
{
public bool Create(Item item)
{
try
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
//二手商品的IID需要在Controller那边生成
item.Type = 1;
item.PostTime = DateTime.Now;
item.UpdateTime = DateTime.Now;
item.EndTime = DateTime.Now.AddMonths(2);
item.Status = 102;
db.Item.InsertOnSubmit(item);
db.SubmitChanges();
}
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}
}
public List<user_item_pic> Show(int page, int n)
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
GHYUsersDataContext db2 = new GHYUsersDataContext();
List<User> userList = db2.User.ToList<User>();
List<Item> itemList = db.Item.ToList<Item>();
List<Pic> picList = db.Pic.ToList<Pic>();
var result = from item in itemList
join user in userList on item.UID equals user.UserID
join pic in picList on item.IID equals pic.IID
where (item.Type == 1) && (item.Status == 102) && (pic.Order == 1) && (pic.Status == 1)
orderby item.PostTime descending
select new user_item_pic
{
IID = item.IID,
NickName = user.NickName,
Title = item.Title,
Price = (int)item.Price,
PID = pic.PID
};
return result.Skip(n * (page - 1)).Take(n).ToList<user_item_pic>();
}
}
public user_item_pic ShowDetail(Guid iid)
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
GHYUsersDataContext db2 = new GHYUsersDataContext();
List<User> userList = db2.User.ToList<User>();
List<Item> itemList = db.Item.ToList<Item>();
List<Pic> picList = db.Pic.ToList<Pic>();
var result = from item in itemList
join user in userList on item.UID equals user.UserID
join pic in picList on item.IID equals pic.IID
where (item.IID == iid) && (pic.Order == 1) && (pic.Status == 1)
select new user_item_pic
{
IID = item.IID,
UID = user.UserID,
NickName = user.NickName,
Title = item.Title,
CID = (int)item.CID,
Detail = item.Detail,
Price = (int)item.Price,
PostTime = item.PostTime,
QQ = item.QQ,
Tel = item.Tel,
PID = pic.PID
};
return result.Single();
}
}
public List<user_item_pic> ShowItemByUID(Guid uid, int page, int n)
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
GHYUsersDataContext db2 = new GHYUsersDataContext();
List<User> userList = db2.User.ToList<User>();
List<Item> itemList = db.Item.ToList<Item>();
List<Pic> picList = db.Pic.ToList<Pic>();
var result = from item in itemList
join user in userList on item.UID equals user.UserID
join pic in picList on item.IID equals pic.IID
where (user.UserID == uid) && (item.Type == 1) && (item.Status == 102) && (pic.Order == 1) && (pic.Status == 1)
orderby item.PostTime descending
select new user_item_pic
{
IID = item.IID,
Title = item.Title,
PID = pic.PID
};
return result.Skip(n*(page-1)).Take(n).ToList<user_item_pic>();
}
}
public List<user_item_pic> ShowItemByCID(int cid, int page, int n)
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
GHYUsersDataContext db2 = new GHYUsersDataContext();
List<User> userList = db2.User.ToList<User>();
List<Item> itemList = db.Item.ToList<Item>();
List<Pic> picList = db.Pic.ToList<Pic>();
var result = from item in itemList
join user in userList on item.UID equals user.UserID
join pic in picList on item.IID equals pic.IID
where (item.CID == cid) && (item.Type == 1) && (item.Status == 102) && (pic.Order == 1) && (pic.Status == 1)
orderby item.PostTime descending
select new user_item_pic
{
IID = item.IID,
NickName = user.NickName,
CID = (int)item.CID,
Title = item.Title,
Price = (int)item.Price,
PID = pic.PID
};
return result.Skip(n*(page-1)).Take(n).ToList<user_item_pic>();
}
}
public bool ItemComplete(Guid iid)
{
try
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
var result = from o in db.Item
where o.IID == iid && o.Status == 102
select o;
result.Single().Status = 103;
db.SubmitChanges();
}
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}
}
public int ItemOverdue()
{
try
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
var result = from o in db.Item
where o.Type == 1 && DateTime.Compare(DateTime.Now, o.EndTime) > 0 && o.Status == 102
select o;
foreach (Item o in result)
{
o.Status = 101;
}
db.SubmitChanges();
}
return 1;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return 0;
}
}
public int UpdateItem(Item item)
{
try
{
using (TradeWorkstationDataContext db = new TradeWorkstationDataContext())
{
var result = from o in db.Item
where o.IID == item.IID && o.Status == 102
select o;
result.Single().Title = item.Title;
result.Single().Price = item.Price;
result.Single().Detail = item.Detail;
result.Single().Tel = item.Tel;
result.Single().QQ = item.QQ;
result.Single().Way = item.Way;
result.Single().UpdateTime = DateTime.Now;
db.SubmitChanges();
}
return 1;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return 0;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Http;
using System.Web.Optimization;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
namespace TradeWorkstation
{
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
// 在应用程序启动时运行的代码
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//设置MEF依赖注入容器
DirectoryCatalog catalog = new DirectoryCatalog(AppDomain.CurrentDomain.SetupInformation.PrivateBinPath);
MefDependencySolver solver = new MefDependencySolver(catalog);
DependencyResolver.SetResolver(solver);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataSource;
namespace DAL
{
public interface IPicHandler
{
bool Create(Pic pic);
List<Pic> ShowByIID(Guid iid);
string GetPicUrl(Guid pid);
}
}
| ee5228a1e8fd6f2d17463c1c0a4f67b82316404a | [
"JavaScript",
"C#"
] | 39 | C# | GHY-ORG/TradeWorkstation | 2c3f3a0f05466940816c589906ad0db0b6fe53f8 | 11586ca546a7df733953f76b0d9b1d5fe7cf46c0 |
refs/heads/master | <file_sep><?php
/**
* Created by Shipox.
* User: Shipox
* Date: 11/8/2017
* Time: 2:41 PM
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
class Vehicle_Type
{
/**
* @return array
*/
public function toOptionArray()
{
return array(
array('value' => 'bike', 'label' => 'Bike'),
array('value' => 'sedan', 'label' => 'Sedan'),
array('value' => 'minivan', 'label' => 'Minivan'),
array('value' => 'panelvan', 'label' => 'Panel Van'),
array('value' => 'light_truck', 'label' => 'Light Truck'),
array('value' => 'refrigerated_truck', 'label' => 'Refrigerated Truck'),
array('value' => 'towing', 'label' => 'Towing'),
array('value' => 'relocation', 'label' => 'Relocation'),
);
}
/**
* @return array
*/
public function toValueArray()
{
$result = array();
$options = $this->toOptionArray();
foreach ($options as $option) {
$result[] = $option['value'];
}
return $result;
}
}<file_sep><?php
/**
* Created by Shipox.
* User: Shipox
* Date: 11/8/2017
* Time: 2:41 PM
*/
class Shipox_Log
{
public $ext = '.log';
/**
* API_HELPER constructor.
*/
public function __construct()
{
}
/**
* @param $filename
* @param $status
* @param $date
* @return null|string
*/
public function check_file_name($filename, $status, $date)
{
if (empty($filename))
return $status . "-" . $date . $this->ext;
return $filename . "-" . $date . $this->ext;
}
/**
* Add Custom Wing Log
* @param $content
* @param $status
* @param null $filename
* @internal param $log
*/
public function write($content, $status = SHIPOX_LOG_STATUS::INFO, $filename = null)
{
$file = $this->check_file_name($filename, $status, date("Y-m-d"));
$log_time = '[' . date('Y-m-d H:i:s') . '] - ';
if (is_array($content) || is_object($content)) {
error_log($log_time . print_r($content, true) . PHP_EOL, 3, trailingslashit(SHIPOX_LOGS) . $file);
} else {
error_log($log_time . $content . PHP_EOL, 3, trailingslashit(SHIPOX_LOGS) . $file);
}
}
}<file_sep><?php
/**
* Plugin Name: Fetchr Shipping
* Plugin URI: http://fetchr.us
* Description: Fetchr Shipping Plugin is responsible to build connection between Fetchr Shipping system and WooCommerce store.
* Version: X1.0
* Author: Fetchr
* Author URI: http://www.fetchr.us
*/
/*
* 2018 Fetchr
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to <EMAIL> so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Fetchr Shipping to newer
* versions in the future. If you wish to customize Fetchr Shipping for your
* needs please refer to http://www.fetchr.us for more information.
*
* @author Fetchr <<EMAIL>>
* @author <NAME> <<EMAIL>>
* @copyright 2018 Fetchr
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* Fetchr.us
*/
// Report all errors except E_NOTICE
// error_reporting(E_ALL ^ E_NOTICE);
if ( !function_exists( 'add_action' ) ) {
echo 'You can not load plugin files directly';
exit;
}
define( 'Fetchrxapi_Plugin_Dir', plugin_dir_path( __FILE__ ) );
register_activation_hook( __FILE__, array( 'fetchr', 'plugin_activation' ) );
register_deactivation_hook( __FILE__, array( 'fetchr', 'plugin_deactivation' ) );
require_once( Fetchrxapi_Plugin_Dir . 'fetchr.config.php' );
require_once( Fetchrxapi_Plugin_Dir . 'function.fetchr.php' );
add_action( 'admin_menu', 'fetchrxapi_plugin_setup_menu');
add_action( 'admin_enqueue_scripts', 'fetchrxapi_enqueue_styles' );
add_action('admin_head', 'wc_order_status_styling');
add_action('admin_footer-edit.php', 'custom_bulk_admin_footer');
add_filter( 'woocommerce_admin_order_actions', 'add_fetchr_ship_actions_button', PHP_INT_MAX, 2 );
add_action( 'wp', 'setup_schedule_event' );
add_action( 'init', 'register_fetchrxapi_order_status' );
add_filter( 'wc_order_statuses', 'add_fetchrxapi_processing_to_order_statuses' );
function fetchrxapi_setting_page() {
?>
<div class="fetchrxapi_modal">
<div class="fetchrxapi_modal__container">
<div class="fetchrxapi_modal__featured">
<div class="fetchrxapi_modal__circle"></div>
<img class="fetchrxapi_modal__logo"/>
</div>
<div class="fetchrxapi_modal__content">
<h2><?php echo esc_attr(Fetchrxapi_Plugin_Settings)?></h2>
<ul class="fetchrxapi_form-list">
<form method="post" action="options.php">
<?php settings_fields( 'fetchrxapi-settings-group' ); ?>
<?php do_settings_sections( 'fetchrxapi-settings-group' ); ?>
<li class="fetchrxapi_form-list__row">
<label>Authorization Token</label>
<input class="fetchrxapi_input" type="text" name="fetchrxapi_authorization_token" value="<?php echo esc_attr( get_option('fetchrxapi_authorization_token') ); ?>" required="" />
</li>
<li class="fetchrxapi_form-list__row">
<label>Address ID</label>
<input class="fetchrxapi_input" type="text" name="fetchrxapi_address_id" value="<?php echo esc_attr( get_option('fetchrxapi_address_id') ); ?>" required="" />
</li>
<li class="fetchrxapi_form-list__row">
<label>Service Type</label>
<select name="fetchrxapi_service_type" class="fetchrxapi_input" >
<option value="dropship" <?php if (get_option('fetchrxapi_service_type') == "dropship"): ?> selected="selected" <?php endif; ?>>Dropship</option>
<option value="fulfillment" <?php if (get_option('fetchrxapi_service_type') == "fulfillment"): ?> selected="selected" <?php endif; ?>> Fulfillment</option>
</select>
</li>
<li class="fetchrxapi_form-list__row">
<label>Environment Type</label>
<select name="fetchrxapi_service_environment" class="fetchrxapi_input">
<option value="sandbox" <?php if (get_option('fetchrxapi_service_environment') == "sandbox"): ?> selected="selected" <?php endif; ?>>Sandbox</option>
<option value="production" <?php if (get_option('fetchrxapi_service_environment') == "production"): ?> selected="selected" <?php endif; ?>> Production</option>
</select>
</li>
<li class="fetchrxapi_form-list__row">
<label>Auto Push?</label>
<select name="fetchrxapi_is_auto_push" class="fetchrxapi_input">
<option value="1" <?php if (get_option('fetchrxapi_is_auto_push') == "1"): ?> selected="selected" <?php endif; ?>> Yes</option>
<option value="0" <?php if (get_option('fetchrxapi_is_auto_push') == "0"): ?> selected="selected" <?php endif; ?>> No</option>
</select>
</li>
<li>
<div class="fetchrxapi_button_clearboth"><input type="submit" name="save_settings" id="save_settings" class="fetchrxapi_button" value="Save Settings"></div>
</form>
<form method="post" action="">
<div><input type="submit" name="push_orders" id="push_orders" class="fetchrxapi_button" value="Push Orders"></div>
</form>
</li>
</ul>
</div>
</div>
</div>
<?php
if (isset($_POST['push_orders']) ){
hit_fetchrxapi_api();
}
}
function hit_fetchrxapi_api()
{
switch (get_option( 'fetchrxapi_service_environment' )) {
case 'sandbox':
$environment = Fetchrxapi_Sandbox_Environment;
break;
case 'production':
$environment = Fetchrxapi_Production_Environment;
break;
}
if ( get_option("fetchrxapi_fetch_status") )
{
$where = array( get_option("fetchrxapi_fetch_status") );
}
else
{
// $where = array("wc-processing");
if (get_option( 'fetchrxapi_is_auto_push') == "1" ){
$where = array( "wc-processing" );
}
if (isset($_POST['push_orders'])) {
$where = array( "wc-ship-with-fetchr" );
}
//$where = array_keys( wc_get_order_statuses() );
}
$orders = get_posts( array(
'numberposts' => -1,
'post_type' => 'shop_order',
'post_status' => $where
)
);
// var_dump($orders);
// exit;
foreach ($orders as $order)
{
$shipping_country = get_post_meta($order->ID,'_shipping_country',true);
$order_wc = new WC_Order( $order->ID );
$products = $order_wc->get_items();
if( get_option( 'fetchrxapi_service_type') == "fulfillment" )
{
// fulfillment service
fetchrxapi_fulfillment ($order,$order_wc,$products,$environment);
}
else
{
// delivery service
fetchrxapi_delivery ($order,$order_wc,$products,$environment);
}
}
}
function fetchrxapi_delivery ($order,$order_wc,$products,$environment)
{
$description = '';
$weight = 0;
foreach ($products as $product) {
$description = $description . $product['name'].' - Qty: '.$product['qty'].', ';
$getProductDetail = wc_get_product( $product['product_id'] );
$weight += $getProductDetail->get_weight();
}
$order_id = (string)$order_wc->get_order_number();
if($order_wc->payment_method == "cod"){
$payment_method = "COD";
$grand_total = $order_wc->get_total();
}else{
$payment_method = "CC";
$grand_total = $order_wc->get_total();
}
$data = array(
'client_address_id' => get_option('fetchrxapi_address_id'),
'data' => array(array(
'order_reference' => $order_id,
'name' => $order_wc->shipping_first_name.' '.$order_wc->shipping_last_name,
'email' => $order_wc->billing_email,
'phone_number' => $order_wc->billing_phone,
'alternate_phone' => '',
'receiver_country' => WC()->countries->countries[$order_wc->shipping_country],
'receiver_city' => $order_wc->shipping_city,
'address' => $order_wc->shipping_company.' '.$order_wc->shipping_address_1.' '.$order_wc->shipping_address_2,
'payment_type' => $payment_method,
'total_amount' => $grand_total,
'order_package_type' => '',
'bag_count' => '',
'weight' => $weight,
'description' => $description,
'comments' => $order_wc->customer_message.' '.$order_wc->customer_note,
'latitude' => '',
'longitude' => '')));
$url = $environment.'order/';
$data_string = json_encode($data, JSON_UNESCAPED_UNICODE);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers[] = 'Authorization: '.get_option('fetchrxapi_authorization_token');
$headers[] = 'Content-Type: application/json';
$headers[] = 'xcaller: WordPress X1.0';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
$results = curl_exec($ch);
curl_close ($ch);
?>
<div class="fetchrxapi_response"><?php print_r($results);?></div>
<?php
$results = json_decode($results);
if ($results->data['0']->status == "success")
{
// Change Status Here to Processing
$order_wc->update_status( 'wc-fetchr-processing' );
// Create/update a custom field Airway bill number and Airway bill link
if ( ! update_post_meta ($order->ID, 'Fetchr Tracking No', $results->data['0']->tracking_no ))
{
add_post_meta($order->ID, 'Fetchr Tracking No', $results->data['0']->tracking_no, true );
}
if ( ! update_post_meta ($order->ID, 'Fetchr AWB Link', $results->data['0']->awb_link ))
{
add_post_meta($order->ID, 'Fetchr AWB Link', $results->data['0']->awb_link, true );
}
}
}
function fetchrxapi_fulfillment ($order,$order_wc,$products,$environment)
{
$order_id = (string)$order_wc->get_order_number();
$item_list = array ();
foreach ($products as $product)
{
if($product['variation_id'] != 0){
$product_obj = new WC_Product($product['variation_id']);
}else{
$product_obj = new WC_Product($product['product_id']);
}
$sku = $product_obj->get_sku();
$n_product = array (
'name' => $product['name'],
'sku' => $sku,
'quantity' => $product['qty'],
'price_per_unit' => $product_obj->price,
'processing_fee' => '',
);
array_push($item_list,$n_product);
}
if($order_wc->payment_method == "cod"){
$payment_method = "COD";
$grand_total = $order_wc->get_total();
}else{
$payment_method = "CC";
$grand_total = $order_wc->get_total();
}
$datalist = array('data' => array(array(
'items' => $item_list,
'warehouse_location' => array(
'id' => get_option('fetchrxapi_address_id')
),
'details' => array(
'discount' => $order_wc->get_total_discount(),
'extra_fee' => $order_wc->get_total_shipping(),
'payment_type' => $payment_method,
'order_reference' => $order_id,
'customer_name' => $order_wc->shipping_first_name.' '.$order_wc->shipping_last_name,
'customer_phone' => $order_wc->billing_phone,
'customer_email' => $order_wc->billing_email,
'customer_address' => $order_wc->shipping_company.' '.$order_wc->shipping_address_1.' '.$order_wc->shipping_address_2,
'customer_latitude' => '',
'customer_longitude' => '',
'customer_city' => $order_wc->shipping_city,
'customer_country' => WC()->countries->countries[$order_wc->shipping_country]
)
)));
$data_string = json_encode($datalist, JSON_UNESCAPED_UNICODE);
//var_dump($data_string);
$url = $environment."fulfillment/";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers[] = 'Authorization: '.get_option('fetchrxapi_authorization_token');
$headers[] = 'Content-Type: application/json';
$headers[] = 'xcaller: WordPress X1.0';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
$results = curl_exec($ch);
curl_close ($ch);
?>
<div class="fetchrxapi_response"><?php print_r($results);?></div>
<?php
$results = json_decode($results);
if ($results->data['0']->status == "success")
{
// Change Status Here to Processing
$order_wc->update_status( 'wc-fetchr-processing' );
if ( ! update_post_meta ($order_id, 'Fetchr Fulfillment Tracking No', $results->data['0']->tracking_no ))
{
add_post_meta($order_id, 'Fetchr Fulfillment Tracking No', $results->data['0']->tracking_no, true );
}
}
} // END of function
<file_sep><?php
/**
* Created by Shipox.
* User: Shipox
* Date: 11/8/2017
* Time: 2:41 PM
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
class Status_Mapping
{
public function statusList() {
$array = array();
$array['unassigned'] = 'New';
$array['assigned_to_courier'] = 'Assigned To Courier';
$array['accepted'] = 'Assigned To Driver';
$array['driver_rejected'] = 'Assigned To Driver';
$array['on_his_way'] = 'Driver On Pickup';
$array['arrived'] = 'Parcel in Sorting Facility';
$array['picked_up'] = 'Parcel Picked Up';
$array['pick_up_failed'] = 'Pick up Failed';
$array['in_sorting_facility'] = 'Parcel in Sorting Facility';
$array['out_for_delivery'] = 'Parcel out For Delivery';
$array['in_transit'] = 'In Transit';
$array['to_be_returned'] = 'To Be Returned';
$array['completed'] = 'Parcel Delivered';
$array['delivery_failed'] = 'Delivery Failed';
$array['cancelled'] = 'Delivery Cancelled';
$array['driver_cancelled'] = 'Driver Cancelled';
$array['returned_to_origin'] = 'river Cancelled';
return $array;
}
}<file_sep><?php
/**
* Created by Shipox.
* User: Shipox
* Date: 11/8/2017
* Time: 2:41 PM
*/
class Shipox_API_Helper
{
/**
* API_HELPER constructor.
*/
public function __construct()
{
add_action('wp_ajax_get_shipox_token', array($this, 'get_shipox_token'));
}
/**
* @param $countryId
* @return bool
*/
public function isDomestic($countryId)
{
$marketplaceCountryId = shipox()->wing['settings-helper']->getCountryId();
return $countryId == $marketplaceCountryId ? true : false;
}
/**
* @return string
*/
public function getTrackingURl()
{
// $serviceConfig = shipox()->wing['options']['service_config'];
$marketplaceHost = shipox()->wing['settings-helper']->getMarketplaceHost();
// if ($serviceConfig['test_mode'] == 1) {
// return WING_DEV_SITE_URL;
// }
return 'https://' . $marketplaceHost;
}
/**
* Authenticate to Wing and get Token
*/
public function get_shipox_token()
{
$returned_data = array('success' => false);
check_ajax_referer('shipox-wp-woocommerse-plugin', 'nonce');
$merchant_email = stripslashes($_POST['merchantEmail']);
$merchant_password = stripslashes($_POST['merchantPassword']);
if (!empty($merchant_email) && !empty($merchant_password)) {
$request = array(
'username' => $merchant_email,
'password' => $merchant_password,
'remember_me' => true
);
shipox()->log->write($request, 'error');
$response = shipox()->api->authenticate($request);
shipox()->log->write($response, 'error');
if ($response['success']) {
$options = shipox()->wing['options']['merchant_config'];
$options['merchant_token'] = $response['data']['id_token'];
$options['merchant_username'] = $merchant_email;
$options['merchant_password'] = $<PASSWORD>;
$options['last_login_date'] = time();
update_option('wing_merchant_config', $options);
$this->updateCustomerMarketplace();
$returned_data['success'] = true;
$returned_data['token'] = $options['merchant_token'];
} else {
shipox()->log->write($response['data']['code'] . ": " . $response['data']['message'], 'error');
$returned_data = array('message' => $response['data']['message']);
}
}
echo json_encode($returned_data);
exit;
}
/**
* Get Country ID From WING
* @param $countryCode
* @return int
*/
function getCountryWingId($countryCode)
{
$result = shipox()->api->wingCountries($countryCode);
foreach ($result['data'] as $country) {
if (is_array($country) && $country['code'] == $countryCode) {
return $country;
break;
}
}
return false;
}
/**
* @param int $totalWeight
* @param $countryId
* @return int
*/
function getPackageType($countryId, $totalWeight = 0)
{
$marketplaceCountryId = shipox()->wing['settings-helper']->getCountryId();
$requestPackage = array(
"from_country_id" => $marketplaceCountryId,
"to_country_id" => $countryId,
);
$result = shipox()->api->wingPackageMenuList('?' . http_build_query($requestPackage));
if ($result['success']) {
$list = $result['data'];
foreach ($list['list'] as $package) {
if ($package["weight"] >= $totalWeight) {
return $package["menu_id"];
}
}
}
shipox()->log->write($totalWeight, 'package-error');
shipox()->log->write($result, 'package-error');
return 0;
}
/**
* @param $courierTypes
* @param $packageList
* @return int
*/
function getProperPackage($courierTypes, $packageList)
{
foreach ($packageList as $itemByVehicles) {
$packages = $itemByVehicles['packages'];
foreach ($packages as $packageItem) {
if (in_array($packageItem['courier_type'], $courierTypes, true)) {
return $packageItem['id'];
}
}
}
return 0;
}
/**
* @param $courierTypes
* @param $packageList
* @return int
*/
function getProperPackageV2($courierTypes, $packageList)
{
foreach ($packageList as $package) {
$courierType = $package['courier_type'];
if (in_array($courierType['type'], $courierTypes, true)) {
return $package;
}
}
return null;
}
/**
* @param $paymentOption
* @param $price
* @return int
*/
function getCustomService($paymentOption, $price)
{
//if($paymentOption == 'credit_balance')
// return 0;
return $price;
}
/**
* @param $city
* @param int $cityId
* @param null $region
* @return bool
*/
public function getCitiesLatLon($city, $cityId = 0, $region = null)
{
$request = shipox()->api;
if ($cityId > 0) {
$result = $request->getCity($cityId);
if ($result['status'] == 'success') {
return $result['data'];
}
} else {
$result = $request->getCityList(true);
foreach ($result as $item) {
if (stripos($item['name'], $city) > -1) {
return $item;
break;
}
if (!is_null($region) && stripos($item['name'], $region) > -1) {
return $item;
break;
}
}
}
return false;
}
/**
* @param $country
* @param $shippingAddress
* @param int $cityId
* @return array
* @deprecated
*/
function getAddressLatLon($country, $shippingAddress, $cityId = 0)
{
$responseArray = array();
$city = $shippingAddress["city"];
$region = $shippingAddress["state"];
if ($this->isDomestic($country['id'])) {
// For Domestic Orders
$wingCity = $this->getCitiesLatLon($city, $cityId, $region);
if ($wingCity) {
$responseArray[0] = $wingCity['latitude'];
$responseArray[1] = $wingCity['longitude'];
}
} else {
// For International Orders
if (!is_null($country['lat']) && !is_null($country['lng'])) {
$responseArray[0] = $country['lat'];
$responseArray[1] = $country['lng'];
}
}
return $responseArray;
}
/**
* @param $country
* @param $shippingAddress
* @return null
*/
function getAddressLocation($country, $shippingAddress)
{
$countries = WC()->countries->get_allowed_countries();
$domestic = $this->isDomestic($country['id']);
$responseArray = array();
$request = array(
'address' => $shippingAddress["address_1"] . " " . $shippingAddress["address_2"],
'city' => $shippingAddress["city"],
'country' => $domestic ? $country['name'] : $countries[$shippingAddress['country']],
'provinceOrState' => $shippingAddress["state"],
'domestic' => $domestic,
);
$location = shipox()->api->getLocationByAddress($request);
if ($location['success']) {
if (!is_null($location['data']['lat']) && !is_null($location['data']['lon'])) {
$responseArray[0] = $location['data']['lat'];
$responseArray[1] = $location['data']['lon'];
}
}
return $responseArray;
}
/**
*
* @param $order_wc
* @param $country
* @return array
*/
function getWingPackages($order_wc, $country)
{
$orderConfig = shipox()->wing['options']['order_config'];
$merchantAddress = shipox()->wing['options']['merchant_address'];
$response = array(
'success' => false,
'message' => null,
'data' => null,
);
$shipping_address = $order_wc->get_address('shipping');
$products = $order_wc->get_items();
$weight = 0;
foreach ($products as $product) {
if ($product['variation_id'] != 0) {
// shipox()->log->write($product['variation_id'], 'order-create-product');
$product_obj = new WC_Product_Variation($product['variation_id']);
} else {
$product_obj = new WC_Product($product['product_id']);
}
$product_weight = (float)$product_obj->get_weight();
$quantity = $product['qty'];
$weight += $product_weight * $quantity;
}
$weight = wc_get_weight($weight, 'kg');
if ($orderConfig['order_default_weight'] > 0) {
$weight = intval($orderConfig['order_default_weight']);
}
$order_wc->add_order_note(sprintf("Shipox: Total Weight: %s", $weight), 0);
$countryObject = $this->getCountryWingId($country);
$menuId = $this->getPackageType($countryObject['id'], $weight);
if ($menuId > 0) {
$merchantLatLong = explode(",", $merchantAddress['merchant_lat_long']);
if (!empty($merchantLatLong)) {
$customerLatLonAddress = $this->getAddressLocation($countryObject, $shipping_address);
if (!empty($customerLatLonAddress)) {
$priceRequestData = array(
"service" => 'LOGISTICS',
"from_lat" => trim($merchantLatLong[0]),
"to_lat" => $customerLatLonAddress[0],
"from_lon" => trim($merchantLatLong[1]),
"to_lon" => $customerLatLonAddress[1],
"menu_id" => $menuId,
);
$priceList = shipox()->api->wingCalcPrices('?' . http_build_query($priceRequestData));
if ($priceList['success']) {
$list = $priceList['data']['list'];
if (is_array($list) && !empty($list)) {
$response['success'] = true;
$response['data'] = array(
'list' => $list,
'lat_lon' => $customerLatLonAddress[0] . "," . $customerLatLonAddress[1],
);
}
} else $response['message'] = 'Shipox: Error with Pricing Packages';
} else $response['message'] = 'Shipox: Shipping City/Province is entered wrong';
} else $response['message'] = 'Shipox: Merchant Address Location didn\'t configured properly';
} else $response['message'] = 'Shipox: Could not find proper Menu';
return $response;
}
function getWingPackageV2($order_wc, $country) {
$orderConfig = shipox()->wing['options']['order_config'];
$merchantAddress = shipox()->wing['options']['merchant_address'];
$response = array(
'success' => false,
'message' => null,
'data' => null,
);
$shipping_address = $order_wc->get_address('shipping');
$products = $order_wc->get_items();
$weight = 0;
foreach ($products as $product) {
if ($product['variation_id'] != 0) {
$product_obj = new WC_Product_Variation($product['variation_id']);
} else {
$product_obj = new WC_Product($product['product_id']);
}
$product_weight = (float)$product_obj->get_weight();
$quantity = $product['qty'];
$weight += $product_weight * $quantity;
}
$weight = wc_get_weight($weight, 'kg');
if ($orderConfig['order_default_weight'] > 0) {
$weight = intval($orderConfig['order_default_weight']);
}
$order_wc->add_order_note(sprintf("Shipox: Total Weight: %s", $weight), 0);
$countryObject = $this->getCountryWingId($country);
$merchantLatLong = explode(",", $merchantAddress['merchant_lat_long']);
if (!empty($merchantLatLong)) {
$customerLatLonAddress = $this->getAddressLocation($countryObject, $shipping_address);
if (!empty($customerLatLonAddress)) {
$isDomestic = $this->isDomestic($countryObject["id"]);
$priceRequestData = array(
'dimensions.domestic' => $isDomestic,
'dimensions.length' => 10,
'dimensions.width' => 10,
'dimensions.weight' => $weight,
'dimensions.unit' => 'METRIC',
'from_country_id' => shipox()->wing['settings-helper']->getCountryId(),
'to_country_id' => $countryObject["id"],
'from_latitude' => trim($merchantLatLong[0]),
'from_longitude' => trim($merchantLatLong[1]),
'to_latitude' => $customerLatLonAddress[0],
'to_longitude' => $customerLatLonAddress[1],
'service_types' => implode(",", $orderConfig['order_default_courier_type']),
);
$priceList = shipox()->api->getPackagePricesV2($priceRequestData);
if ($priceList['success']) {
$list = $priceList['data']['list'];
if (is_array($list) && !empty($list)) {
$response['success'] = true;
$response['data'] = array(
'list' => $list,
'lat_lon' => $customerLatLonAddress[0] . "," . $customerLatLonAddress[1],
'weight' => $weight,
'is_domestic' => $isDomestic,
);
}
} else $response['message'] = 'Shipox: Error with Pricing Packages';
} else $response['message'] = 'Shipox: Shipping City/Province is entered wrong';
} else $response['message'] = 'Shipox: Merchant Address Location didn\'t configured properly';
return $response;
}
/**pushOrderToWingWithPackage
* @param $order_wc
* @param $package
* @param $customerLatLong
*/
function pushOrderToWingWithPackage($order_wc, $package, $customerLatLong)
{
$orderConfig = shipox()->wing['options']['order_config'];
$merchantAddress = shipox()->wing['options']['merchant_address'];
$shipping_address = $order_wc->get_address('shipping');
$merchantLatLong = explode(",", $merchantAddress['merchant_lat_long']);
$products = $order_wc->get_items();
$orderItems = null;
foreach ($products as $product) {
$orderItems .= $product['name'] . ' - Qty: ' . $product['qty'] . ', ';
}
if (intval($package) > 0 && !empty($merchantLatLong) && !empty($customerLatLong)) {
$requestData = array();
// Order ID As a Reference
$requestData['reference_id'] = $order_wc->get_id() . "/" . $order_wc->get_order_number();
//Charge Items COD
$requestData['charge_items'] = array();
$wingCod = $order_wc->get_subtotal() + $order_wc->get_total_tax() - $order_wc->get_discount_total();
if ($order_wc->get_payment_method() == "cod") {
$requestData['payer'] = 'recipient';
$requestData['parcel_value'] = $order_wc->get_total();
$requestData['charge_items'] = array(
array(
'charge_type' => "cod",
'charge' => $wingCod // Round Up the COD by requesting Finance
),
array(
'charge_type' => "service_custom",
'charge' => $this->getCustomService($orderConfig['order_default_payment_option'], $order_wc->get_total() - $wingCod)
)
);
} else {
$requestData['payer'] = 'sender';
$requestData['charge_items'] = array(
array(
'charge_type' => "cod",
'charge' => 0
),
array(
'charge_type' => "service_custom",
'charge' => 0
)
);
}
// PickUp Time
$requestData['pickup_time_now'] = false;
// Request Details
$requestData['request_details'] = $orderItems;
// PhotoItems
$requestData['photo_items'] = array();
// PackageInfo
$requestData['package'] = array('id' => $package);
// Must provide this as true to overcome the our cut off times
$requestData['force_create'] = true;
// Locations
$requestData['locations'][] = array(
'pickup' => true,
'lat' => trim($merchantLatLong[0]),
'lon' => trim($merchantLatLong[1]),
'address' => substr($merchantAddress['merchant_street'], 0, 145) .' ' .$merchantAddress['merchant_address'],
'details' => '',
'phone' => $merchantAddress['merchant_phone'],
'email' => $merchantAddress['merchant_contact_email'],
'contact_name' => $merchantAddress['merchant_contact_name'],
'address_city' => $merchantAddress['merchant_city'],
'address_street' => substr($merchantAddress['merchant_street'], 0, 145)
);
$requestData['locations'][] = array(
'pickup' => false,
'lat' => trim($customerLatLong[0]),
'lon' => trim($customerLatLong[1]),
'address' => $shipping_address['address_1'] . ' ' . $shipping_address['address_2'] . ' ' . $shipping_address['city'] . ' ' . $shipping_address['country'],
'details' => $order_wc->get_customer_note(),
'phone' => $order_wc->get_billing_phone(),
'email' => $order_wc->get_billing_email(),
'address_city' => $shipping_address['city'],
'address_street' => substr($shipping_address['address_1'] . ' ' . $shipping_address['address_2'], 0, 145),
'contact_name' => $shipping_address['first_name'] . ' ' . $shipping_address['last_name'],
);
//Note
$requestData['note'] = home_url() . ', ' . $orderItems;
//Payment Type
$requestData['payment_type'] = $orderConfig['order_default_payment_option'];
//If Recipient Not Available
$requestData['recipient_not_available'] = 'do_not_deliver';
$response = shipox()->api->wingCreateOrder($requestData);
if ($response['success']) {
$responseData = $response['data'];
update_post_meta($order_wc->get_id(), '_wing_order_number', $responseData['order_number']);
update_post_meta($order_wc->get_id(), '_wing_order_id', $responseData['id']);
update_post_meta($order_wc->get_id(), '_wing_status', $responseData['status']);
$order_wc->add_order_note("Shipox: Wing Order number is: #" . $responseData['order_number'], 1);
} else {
shipox()->log->write($requestData, 'order-create-error');
shipox()->log->write($response, 'order-create-error');
$order_wc->add_order_note(sprintf("Shipox: Order Creation Error: %s", $response['data']['message']), 0);
}
}
}
/**
* @param $order_wc
* @param $package
* @param $customerLatLong
* @param $to_country
*/
function pushOrderToWingWithPackageNewModel($order_wc, $package, $customerLatLong, $to_country)
{
$orderConfig = shipox()->wing['options']['order_config'];
$merchantAddress = shipox()->wing['options']['merchant_address'];
$shipping_address = $order_wc->get_address('shipping');
$merchantLatLong = explode(",", $merchantAddress['merchant_lat_long']);
$package_price = explode("-", $package);
$products = $order_wc->get_items();
$orderItems = null;
foreach ($products as $product) {
$orderItems .= $product['name'] . ' - Qty: ' . $product['qty'] . ', ';
}
if (intval($package) > 0 && !empty($merchantLatLong) && !empty($customerLatLong)) {
$requestData = array();
// Order ID As a Reference
$requestData['reference_id'] = $order_wc->get_id() . "/" . $order_wc->get_order_number();
//Charge Items COD
$requestData['charge_items'] = array();
$wingCod = $order_wc->get_subtotal() + $order_wc->get_total_tax() - $order_wc->get_discount_total();
if ($order_wc->get_payment_method() == "cod") {
$requestData['payer'] = 'recipient';
$requestData['parcel_value'] = $order_wc->get_total();
$requestData['charge_items'] = array(
array(
'charge_type' => "cod",
'charge' => $wingCod // Round Up the COD by requesting Finance
),
array(
'charge_type' => "service_custom",
'charge' => $this->getCustomService($orderConfig['order_default_payment_option'], $order_wc->get_total() - $wingCod)
)
);
} else {
$requestData['payer'] = 'sender';
$requestData['charge_items'] = array(
array(
'charge_type' => "cod",
'charge' => 0
),
array(
'charge_type' => "service_custom",
'charge' => 0
)
);
}
// PickUp Time
$requestData['pickup_time_now'] = false;
// Request Details
$requestData['request_details'] = $orderItems;
// PhotoItems
$requestData['photo_items'] = array();
$requestData['package_type'] = array(
'id' => $package_price[0],
'package_price' => array(
'id' => $package_price[1],
));
// Must provide this as true to overcome the our cut off times
$requestData['force_create'] = true;
// Locations
$requestData['sender_data'] = array(
'address_type' => 'business',
'name' => $merchantAddress['merchant_contact_name'],
'email' => $merchantAddress['merchant_contact_email'],
'phone' => $merchantAddress['merchant_phone'],
'address' => $merchantAddress['merchant_address'],
'details' => '',
'country' => array('id' => shipox()->wing['settings-helper']->getCountryId()),
'city' => array('name' => $merchantAddress['merchant_city']),
'street' => substr($merchantAddress['merchant_street'], 0, 145),
'lat' => trim($merchantLatLong[0]),
'lon' => trim($merchantLatLong[1]),
);
$requestData['recipient_data'] = array(
'address_type' => 'residential',
'name' => $shipping_address['first_name'] . ' ' . $shipping_address['last_name'],
'phone' => $order_wc->get_billing_phone(),
'email' => $order_wc->get_billing_email(),
'address' => $shipping_address['address_1'] . ' ' . $shipping_address['address_2'] . ' ' . $shipping_address['city'] . ' ' . $shipping_address['country'],
'details' => $order_wc->get_customer_note(),
'country' => array('id' => $to_country['id']),
'city' => array('name' => $shipping_address['city']),
'street' => substr($shipping_address['address_1'] . ' ' . $shipping_address['address_2'], 0, 145),
'lat' => trim($customerLatLong[0]),
'lon' => trim($customerLatLong[1]),
);
$requestData['dimensions'] = array(
'width' => 10,
'length' => 10,
'height' => 10,
'weight' => $package_price[2],
'unit' => 'METRIC',
'domestic' => $package_price[3] == 1 ? true : false,
);
//Note
$requestData['note'] = home_url() . ', ' . $orderItems;
//Payment Type
$requestData['payment_type'] = $orderConfig['order_default_payment_option'];
//If Recipient Not Available
$requestData['recipient_not_available'] = 'do_not_deliver';
$response = shipox()->api->wingCreateOrderV2($requestData);
if ($response['success']) {
$responseData = $response['data'];
update_post_meta($order_wc->get_id(), '_wing_order_number', $responseData['order_number']);
update_post_meta($order_wc->get_id(), '_wing_order_id', $responseData['id']);
update_post_meta($order_wc->get_id(), '_wing_status', $responseData['status']);
$order_wc->add_order_note("Shipox: Wing Order number is: #" . $responseData['order_number'], 1);
} else {
shipox()->log->write($requestData, 'order-create-error');
shipox()->log->write($response, 'order-create-error');
$order_wc->add_order_note(sprintf("Shipox: Order Creation Error: %s", $response['data']['message']), 0);
}
}
}
/**
* @param $wingOrderId
* @return bool
*/
function getAirwaybill($wingOrderId)
{
$response = shipox()->api->getAirwaybill($wingOrderId);
if ($response['success'])
return $response['data']['value'];
return false;
}
public function updateCustomerMarketplace()
{
$response = shipox()->api->getCustomerMarketplace();
$options = array();
if ($response['success']) {
$marketplace = $response['data'];
$options['currency'] = $marketplace['currency'];
$options['custom'] = $marketplace['custom'];
$options['decimal_point'] = isset($marketplace['setting']['settings']['decimalPoint']) ? $marketplace['setting']['settings']['decimalPoint'] : 2;
$options['disable_international_orders'] = isset($marketplace['setting']['settings']['disableInternationalOrders']) ? $marketplace['setting']['settings']['disableInternationalOrders'] : false;
$options['new_model_enabled'] = isset($marketplace['setting']['settings']['newModelEnabled']) ? $marketplace['setting']['settings']['newModelEnabled'] : false;
$options['host'] = isset($marketplace['setting']['settings']['customerDomain']) ? $marketplace['setting']['settings']['customerDomain'] : 'my.wing.ae';
$options['country'] = $marketplace['country'];
update_option('wing_marketplace_settings', $options);
}
}
}<file_sep>(function($){
$('#shipoxGetToken').on('click', function ($e) {
$e.preventDefault();
let $data = [];
$data['merchantEmail'] = $('#shipox_merchant_username').val();
$data['merchantPassword'] = $('#shipox_merchant_password').val();
$data['nonce'] = $('#shipoxTokenNonce').val();
$.ajax({
method: "post",
url: shipoxAjax.ajax_url,
data: {
action: 'get_shipox_token',
merchantEmail: $data['merchantEmail'],
merchantPassword: $data['merchantPassword'],
nonce: shipoxAjax.ajax_nonce
}
}).success(function (response) {
let json = $.parseJSON(response);
if (json['success']) {
$('#woocommerce_shipox_token').val(json['token']);
alert('The Customer successfully authorized');
} else alert(json['message']);
})
})
})(jQuery);<file_sep><?php
/**
* Created by Shipox.
* User: Shipox
* Date: 11/8/2017
* Time: 2:41 PM
*/
class Shipox_Install
{
/**
* API_HELPER constructor.
*/
public function __construct()
{
}
/**
* Update Wing version to current.
*/
private static function update_wing_version() {
delete_option( 'shipox_version' );
add_option( 'shipox_version', shipox()->version );
}
/**
* Install WC.
*/
public static function install() {
self::create_files();
self::update_wing_version();
}
/**
* Create files/directories.
*/
private static function create_files() {
// Bypass if filesystem is read-only and/or non-standard upload system is used
if ( apply_filters( 'woocommerce_install_skip_create_files', false ) ) {
return;
}
$files = array(
array(
'base' => SHIPOX_LOGS,
'file' => '.htaccess',
'content' => 'deny from all',
),
array(
'base' => SHIPOX_LOGS,
'file' => 'index.html',
'content' => '',
),
);
foreach ( $files as $file ) {
if ( wp_mkdir_p( $file['base'] ) && ! file_exists( trailingslashit( $file['base'] ) . $file['file'] ) ) {
if ( $file_handle = @fopen( trailingslashit( $file['base'] ) . $file['file'], 'w' ) ) {
fwrite( $file_handle, $file['content'] );
fclose( $file_handle );
}
}
}
}
}<file_sep><?php
/**
* Created by Shipox.
* User: Shipox
* Date: 11/8/2017
* Time: 2:41 PM
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
class Courier_Type
{
public function getServiceTypes() {
$serviceTypes = shipox()->api->getAllServiceTypes();
if (!$serviceTypes['success']) {
shipox()->log->write($serviceTypes['message'], 'service-type-error');
return array();
}
$response = array();
$list = $serviceTypes['data']['list'];
foreach ($list as $item) {
if($item['code'] === 'FBS') continue;
$response[] = array(
'value' => $item['code'],
'label' => $item['name'],
);
}
return $response;
}
public function toOptionArray()
{
return $this->getServiceTypes();
}
public function toValueArray()
{
$result = array();
$options = $this->toOptionArray();
foreach ($options as $option) {
$result[] = $option['value'];
}
return $result;
}
}<file_sep><?php
/*
* 2018 Fetchr
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to <EMAIL> so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Fetchr Shipping to newer
* versions in the future. If you wish to customize Fetchr Shipping for your
* needs please refer to http://www.fetchr.us for more information.
*
* @author Fetchr <<EMAIL>>
* @author <NAME> <<EMAIL>>
* @copyright 2018 Fetchr
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* Fetchr.us
*/
// Report all errors except E_NOTICE
// error_reporting(E_ALL ^ E_NOTICE);
define( 'Fetchrxapi_Plugin_Version', '2.0' );
define( 'Fetchrxapi_Menu_Title', 'Fetchr Shipping' );
define( 'Fetchrxapi_Plugin_Title', 'Fetchr Integration' );
define( 'Fetchrxapi_Plugin_Settings', 'Fetchr Shipping Settings' );
define( 'Fetchrxapi_Sandbox_Environment', 'https://spawn.stag.fetchr.us/' );
define( 'Fetchrxapi_Production_Environment', 'https://api.order.fetchr.us/' );
<file_sep><?php
/**
* Created by Shipox.
* User: Shipox
* Date: 11/8/2017
* Time: 2:41 PM
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
class Package_Type
{
/**
* @return array
*/
public function toOptionArray()
{
$arr[] = array('value' => 'd2', 'label' => 'D2');
$arr[] = array('value' => 'p3', 'label' => 'P3');
$arr[] = array('value' => 'p5', 'label' => 'P5');
$arr[] = array('value' => 'p10', 'label' => 'P10');
$arr[] = array('value' => 'p30', 'label' => 'P30');
$arr[] = array('value' => 'p100', 'label' => 'P100');
$arr[] = array('value' => '0.5KG', 'label' => '0.5 Kg');
$arr[] = array('value' => '1KG', 'label' => '1 Kg');
$arr[] = array('value' => '1.5KG', 'label' => '1.5 Kg');
$arr[] = array('value' => '2KG', 'label' => '2 Kg');
$arr[] = array('value' => '2.5KG', 'label' => '2.5 Kg');
$arr[] = array('value' => '3KG', 'label' => '3 Kg');
$arr[] = array('value' => '3.5KG', 'label' => '3.5 Kg');
$arr[] = array('value' => '4KG', 'label' => '4 Kg');
$arr[] = array('value' => '4.5KG', 'label' => '4.5 Kg');
$arr[] = array('value' => '5KG', 'label' => '5 Kg');
$arr[] = array('value' => '5.5KG', 'label' => '5.5 Kg');
$arr[] = array('value' => '6KG', 'label' => '6 Kg');
$arr[] = array('value' => '6.5KG', 'label' => '6.5 Kg');
$arr[] = array('value' => '7KG', 'label' => '7 Kg');
$arr[] = array('value' => '7.5KG', 'label' => '7.5 Kg');
$arr[] = array('value' => '8KG', 'label' => '8 Kg');
$arr[] = array('value' => '8.5KG', 'label' => '8.5 Kg');
$arr[] = array('value' => '9KG', 'label' => '9 Kg');
$arr[] = array('value' => '9.5KG', 'label' => '9.5 Kg');
$arr[] = array('value' => '10KG', 'label' => '10 Kg');
return $arr;
}
/**
* @return array
*/
public function toKeyArray()
{
$result = array();
$options = $this->toOptionArray();
foreach ($options as $option) {
$result[$option['value']] = $option['label'];
}
return $result;
}
}<file_sep><?php
/*
* 2018 Fetchr
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to <EMAIL> so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Fetchr Shipping to newer
* versions in the future. If you wish to customize Fetchr Shipping for your
* needs please refer to http://www.fetchr.us for more information.
*
* @author Fetchr <<EMAIL>>
* @author <NAME> <<EMAIL>>
* @copyright 2018 Fetchr
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* Fetchr.us
*/
function fetchrxapi_plugin_setup_menu(){
add_menu_page( Fetchrxapi_Plugin_Title, Fetchrxapi_Menu_Title, 'manage_options', 'fetchr-plugin', 'fetchrxapi_setting_page' );
add_action( 'admin_init', 'register_setting_options' );
}
function fetchrxapi_enqueue_styles(){
wp_enqueue_style( 'fetchrstylesheet', plugins_url( '/css/fetchrstyle.css',__FILE__ ));
}
function wc_order_status_styling() {
}
function custom_bulk_admin_footer() {
global $post_type;
if($post_type == 'shop_order') {
?>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('<option>').val('mark_ship-with-fetchr').text('<?php _e('Mark Fetchr Ship')?>').appendTo("select[name='action']");
});
</script>
<?php
}
}
function add_fetchr_ship_actions_button( $actions, $the_order ) {
if ( $the_order->has_status( array( 'processing' ) ) ) { // if order is not cancelled yet...
$actions['ship-with-fetchr'] = array(
'url' => wp_nonce_url( admin_url( 'admin-ajax.php?action=woocommerce_mark_order_status&status=ship-with-fetchr&order_id=' . $the_order->id ), 'woocommerce-mark-order-status' ),
'name' => __( 'Ship with Fetchr', 'woocommerce' ),
'action' => "view ship-with-fetchr", // setting "view" for proper button CSS
);
}
return $actions;
}
function setup_schedule_event()
{
if ( ! wp_next_scheduled( 'prefix_hourly_event' ) )
{
wp_schedule_event( time(), 'hourly', 'prefix_hourly_event' );
}
}
if (get_option( 'fetchrxapi_is_auto_push') == "1" ){
add_action( 'prefix_hourly_event', 'hit_fetchrxapi_api' );
}
function register_fetchrxapi_order_status()
{
register_post_status( 'wc-fetchr-processing', array(
'label' => 'Fetchr Processing',
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => _n_noop( 'Fetchr Processing <span class="count">(%s)</span>', 'Fetchr Processing <span class="count">(%s)</span>' )
)
);
register_post_status( 'wc-ship-with-fetchr', array(
'label' => 'Ship with Fetchr',
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => _n_noop( 'Ship with Fetchr <span class="count">(%s)</span>', 'Ship with Fetchr <span class="count">(%s)</span>' )
)
);
}
function add_fetchrxapi_processing_to_order_statuses( $order_statuses ) {
$new_order_statuses = array();
// add new order status after processing
foreach ( $order_statuses as $key => $status ) {
$new_order_statuses[ $key ] = $status;
if ( 'wc-processing' === $key )
{
$new_order_statuses['wc-fetchr-processing'] = 'Fetchr Processing';
$new_order_statuses['wc-ship-with-fetchr'] = 'Ship with Fetchr';
}
}
return $new_order_statuses;
}
function register_setting_options(){
register_setting( 'fetchrxapi-settings-group', 'fetchrxapi_authorization_token' );
register_setting( 'fetchrxapi-settings-group', 'fetchrxapi_address_id' );
register_setting( 'fetchrxapi-settings-group', 'fetchrxapi_fetch_status' );
register_setting( 'fetchrxapi-settings-group', 'fetchrxapi_service_type' );
register_setting( 'fetchrxapi-settings-group', 'fetchrxapi_service_environment' );
register_setting( 'fetchrxapi-settings-group', 'fetchrxapi_is_auto_push' );
}
<file_sep><?php
/**
* Created by Shipox.
* User: Shipox
* Date: 11/8/2017
* Time: 2:41 PM
*/
if (!defined('ABSPATH')) {
exit; // Exit if accessed directly.
}
final class Shipox
{
public $version = '4.0.0';
protected static $_instance = null;
public $wing = null;
public $api = null;
public $log = null;
public $sentry = null;
/**
* @return null|Shipox
*/
public static function instance()
{
if (is_null(self::$_instance)) {
self::$_instance = new self();
}
return self::$_instance;
}
/**
* Shipox constructor.
*/
public function __construct()
{
$this->define_constants();
$this->includes();
$this->init_classes();
$this->init_hooks();
}
/**
* Initialize Assets
*/
public function load_admin_scripts()
{
wp_register_style('shipox_admin_css', WP_PLUGIN_URL . '/shipox/assets/css/admin-style.css', false, $this->version);
wp_enqueue_style('shipox_admin_css');
wp_register_script('shipox_admin_ajax', WP_PLUGIN_URL . '/shipox/assets/js/shipox_ajax.js', array('jquery'), '1.0.0', true);
wp_localize_script('shipox_admin_ajax', 'shipoxAjax', array('ajax_url' => admin_url('admin-ajax.php'), 'ajax_nonce' => wp_create_nonce('shipox-wp-woocommerse-plugin')));
wp_enqueue_script('shipox_admin_ajax');
}
/**
* Define Wing Constants.
*/
private function define_constants()
{
$upload_dir = wp_upload_dir(null, false);
$this->define('SHIPOX_DEV_SITE_URL', 'https://my-staging.shipox.com');
$this->define('SHIPOX_LIVE_SITE_URL', 'https://my.shipox.com');
$this->define('SHIPOX_DEV_API_URL', 'https://myapi.wing.ae');
$this->define('SHIPOX_LIVE_API_URL', 'https://liveapi.wing.ae');
$this->define('SHIPOX_ABSPATH', dirname(SHIPOX_PLUGIN_FILE) . '/');
$this->define('SHIPOX_PLUGIN_BASENAME', plugin_basename(SHIPOX_PLUGIN_FILE));
$this->define('SHIPOX_VERSION', $this->version);
$this->define('SHIPOX_SEPARATOR', '|');
$this->define('SHIPOX_LOGS', $upload_dir['basedir'] . '/shipox-logs/');
}
/**
* Define constant if not already set.
*
* @param string $name Constant name.
* @param string|bool $value Constant value.
*/
private function define($name, $value)
{
if (!defined($name)) {
define($name, $value);
}
}
/**
* Includes
*/
private function includes()
{
include_once(SHIPOX_ABSPATH . 'includes/inc-logs.php');
include_once(SHIPOX_ABSPATH . 'enum/enum-log-statuses.php');
include_once(SHIPOX_ABSPATH . 'classes/class-shipox-options.php');
include_once(SHIPOX_ABSPATH . 'classes/class-shipox-menu-type.php');
include_once(SHIPOX_ABSPATH . 'classes/class-shipox-courier-type.php');
include_once(SHIPOX_ABSPATH . 'classes/class-shipox-payment-type.php');
include_once(SHIPOX_ABSPATH . 'classes/class-shipox-package-type.php');
include_once(SHIPOX_ABSPATH . 'classes/class-shipox-shipping-options.php');
include_once(SHIPOX_ABSPATH . 'classes/class-shipox-vehicle-type.php');
include_once(SHIPOX_ABSPATH . 'classes/class-shipox-status-mapping.php');
include_once(SHIPOX_ABSPATH . 'includes/inc-api-helper.php');
include_once(SHIPOX_ABSPATH . 'includes/inc-order-helper.php');
include_once(SHIPOX_ABSPATH . 'includes/inc-settings-helper.php');
include_once(SHIPOX_ABSPATH . 'includes/inc-backend-actions.php');
include_once(SHIPOX_ABSPATH . 'includes/inc-frontend-actions.php');
include_once(SHIPOX_ABSPATH . 'classes/class-shipox-api-client.php');
include_once(SHIPOX_ABSPATH . 'classes/class-shipox-cron-job.php');
include_once(SHIPOX_ABSPATH . 'includes/inc-shipox-install.php');
}
/**
* Init Classes
*/
private function init_classes()
{
$this->wing['options'] = $this->init_options();
$this->log = new Shipox_Log();
$this->wing['menu-type'] = new Menu_Type();
$this->wing['courier-type'] = new Courier_Type();
$this->wing['payment-type'] = new Payment_Type();
$this->wing['package-type'] = new Package_Type();
$this->wing['shipping-options'] = new Shipping_Options();
$this->wing['statuses'] = new Status_Mapping();
$this->wing['vehicle-type'] = new Vehicle_Type();
$this->api = new Shipox_Api_Client();
$this->wing['api-helper'] = new Shipox_API_Helper();
$this->wing['order-helper'] = new \includes\Shipox_Order_Helper();
$this->wing['settings-helper'] = new \includes\Shipox_Settings_Helper();
new Shipox_Cron_Job();
}
/**
* Hook into actions and filters.
* @since 2.0
*/
private function init_hooks()
{
register_activation_hook(SHIPOX_PLUGIN_FILE, array('Shipox_Install', 'install'));
$this->init();
add_action('admin_enqueue_scripts', array($this, 'load_admin_scripts'));
}
/**
* Init Function
*/
public function init()
{
add_action('woocommerce_shipping_init', array($this, 'init_shipping_method'));
add_action('woocommerce_shipping_methods', array($this, 'add_shipping_method'));
$merchantConfig = $this->wing['options']['merchant_config'];
$serviceConfig = $this->wing['options']['service_config'];
}
/**
* Add Shipping Method
*/
public function init_shipping_method()
{
if (!class_exists('Shipox_Shipping_Method')) {
include_once(SHIPOX_ABSPATH . 'classes/class-shipox-shipping-method.php');
}
}
/**
* @param $methods
* @return array
*/
function add_shipping_method($methods)
{
if (class_exists('Shipox_Shipping_Method')) {
$methods[] = 'Shipox_Shipping_Method';
}
return $methods;
}
/**
* Init Wing Options
* @return array
*/
private function init_options()
{
$options = array(
'service_config' => get_option('wing_service_config'),
'merchant_config' => get_option('wing_merchant_config'),
'merchant_address' => get_option('wing_merchant_address'),
'order_config' => get_option('wing_order_config'),
'marketplace_settings' => get_option('wing_marketplace_settings'),
);
return $options;
}
}
<file_sep><?php
/**
* Created by Shipox.
* User: Shipox
* Date: 11/8/2017
* Time: 2:41 PM
*/
class Shipox_Shipping_Method extends WC_Shipping_Method
{
/**
* Shipox_Shipping_Method constructor.
*/
public function __construct()
{
parent::__construct();
$this->id = 'wing';
$this->method_title = __('Shipox', 'wing');
$this->enabled = $this->get_option('enabled');
$this->init();
$this->title = isset($this->settings['title']) ? $this->settings['title'] : __('Shipox Shipping', 'wing');
}
/**
*
*/
private function init()
{
$this->init_form_fields();
$this->init_settings();
add_action('woocommerce_update_options_shipping_' . $this->id, array($this, 'process_admin_options'));
}
/**
* Define settings field for this shipping
* @return void
*/
function init_form_fields()
{
$this->form_fields = array(
'enabled' => array(
'title' => __('Enable', 'wing'),
'type' => 'checkbox',
'description' => __('Enable this shipping.', 'wing'),
'default' => 'yes'
),
'title' => array(
'title' => __('Title', 'wing'),
'type' => 'text',
'description' => __('Title to be display on site', 'wing'),
'default' => __('Shipox Shipping', 'wing')
),
'weight' => array(
'title' => __('Weight (kg)', 'wing'),
'type' => 'number',
'description' => __('Maximum allowed weight', 'wing'),
'default' => 100
),
'availability' => array(
'title' => __('Methods availability', 'wing'),
'type' => 'select',
'default' => 'all',
'class' => 'availability wc-enhanced-select',
'options' => array(
'all' => __('All allowed countries', 'wing'),
'specific' => __('Specific Countries', 'wing')
)
),
'countries' => array(
'title' => __('Specific Countries', 'wing'),
'type' => 'multiselect',
'class' => 'wc-enhanced-select',
'css' => 'width: 450px;',
'default' => '',
'options' => WC()->countries->get_shipping_countries(),
'custom_attributes' => array(
'data-placeholder' => __('Select some countries', 'wing')
)
),
);
}
/**
* Calculate Shipping
* @param array $package
*/
public function calculate_shipping($package = array())
{
if (!$this->enabled) return;
$baseLocation = wc_get_base_location();
$marketplaceCountry = shipox()->wing['settings-helper']->getCountryCode();
$marketplaceCurrency = shipox()->wing['settings-helper']->getCurrency();
if (get_woocommerce_currency() !== $marketplaceCurrency || $baseLocation["country"] !== $marketplaceCountry) return;
$orderConfig = shipox()->wing['options']['order_config'];
$merchantAddress = shipox()->wing['options']['merchant_address'];
$address = $package['destination'];
if ($this->get_option('availability') == 'specific' && !in_array($address["country"], $this->get_option('countries')))
return;
$weight = 0;
foreach ($package['contents'] as $item_id => $values)
if ($values['quantity'] > 0 && $values['data']->needs_shipping())
$weight += intval($values['quantity']) * floatval($values['data']->get_weight());
$weight = wc_get_weight($weight, 'kg');
if ($orderConfig['order_default_weight'] > 0) {
$weight = intval($orderConfig['order_default_weight']);
}
$country = shipox()->wing['api-helper']->getCountryWingId($address["country"]);
$marketplaceIntAvailability = shipox()->wing['settings-helper']->getInternationalAvailability();
$isDomestic = shipox()->wing['api-helper']->isDomestic($country["id"]);
if ($orderConfig['order_international_availability'] == 0 && !$marketplaceIntAvailability && !$isDomestic)
return;
$merchantLatLong = explode(",", $merchantAddress['merchant_lat_long']);
if (!empty($merchantLatLong)) {
$customerLatLonAddress = shipox()->wing['api-helper']->getAddressLocation($country, $address);
if (!empty($customerLatLonAddress)) {
$priceArray = array();
$isNewModel = shipox()->wing['settings-helper']->getNewModelEnabled();
if ($isNewModel) {
// New Model
$priceRequestData = array(
'dimensions.domestic' => $isDomestic,
'dimensions.length' => 10,
'dimensions.width' => 10,
'dimensions.weight' => $weight,
'dimensions.unit' => 'METRIC',
'from_country_id' => shipox()->wing['settings-helper']->getCountryId(),
'to_country_id' => $country["id"],
'from_latitude' => trim($merchantLatLong[0]),
'from_longitude' => trim($merchantLatLong[1]),
'to_latitude' => $customerLatLonAddress[0],
'to_longitude' => $customerLatLonAddress[1],
'service_types' => implode(",", $orderConfig['order_default_courier_type']),
);
$priceList = shipox()->api->getPackagePricesV2($priceRequestData);
if ($priceList['success']) {
$list = $priceList['data']['list'];
foreach ($list as $listItem) {
$priceItem = $listItem['price'];
$name = $listItem['supplier']['name'] . " - " . $listItem['name'];
$method = $listItem['id'].'-'.$priceItem['id'].'-'.$weight.'-'.($isDomestic ? '1' : '0');
$response['type'] = 'success';
$priceArray[$method] = array('label' => $name, 'amount' => $priceItem['total']);
}
}
} else {
// OLD Model
$menuId = shipox()->wing['api-helper']->getPackageType($country['id'], $weight);
if ($menuId > 0) {
$priceRequestData = array(
"service" => 'LOGISTICS',
"from_lat" => trim($merchantLatLong[0]),
"to_lat" => $customerLatLonAddress[0],
"from_lon" => trim($merchantLatLong[1]),
"to_lon" => $customerLatLonAddress[1],
"menu_id" => $menuId,
);
$priceList = shipox()->api->wingCalcPrices('?' . http_build_query($priceRequestData));
if ($priceList['success']) {
$list = $priceList['data']['list'];
foreach ($list as $listItem) {
$packages = $listItem['packages'];
$name = $listItem['name'];
foreach ($packages as $packageItem) {
$label = $packageItem['delivery_label'];
$price = $packageItem['price']['total'];
$method = $packageItem['id'];
$response['type'] = 'success';
$priceArray[$method] = array('label' => $name . " - " . $label, 'amount' => $price);
}
}
}
}
}
}
}
if (isset($priceArray) && !empty($priceArray)) {
foreach ($priceArray as $key => $value) {
$rate = array(
'id' => $this->id . '_' . $key,
'label' => $value['label'],
'cost' => $value['amount'],
'calc_tax' => 'per_order'
);
$this->add_rate($rate);
}
}
}
}
new Shipox_Shipping_Method();<file_sep><?php
/**
* Created by Shipox.
* User: Shipox
* Date: 11/8/2017
* Time: 2:41 PM
*/
class Shipox_Options
{
/**
* Wing_Options constructor.
*/
public function __construct()
{
add_action('admin_menu', array($this, 'add_admin_menu'));
add_action('admin_init', array($this, 'init'));
}
/**
* Add menu to Admin Menu Container
*/
public function add_admin_menu()
{
add_menu_page('Shipox', 'Shipox', 'manage_options', 'wing', array($this, 'render_options'), plugins_url('/shipox/assets/images/logo.png'));
}
/**
* Init Options
*/
public function init()
{
$this->init_service_configuration_fields();
$this->init_merchant_configuration_fields();
$this->init_merchant_address_fields();
$this->init_wing_order_configuration_fields();
}
/**
* Init Service Configuration Fields
*/
public function init_service_configuration_fields() {
register_setting(
'service_config_section', // Option group
'wing_service_config'
);
add_settings_section(
'service_config_section_tab',
__('Service Configuration', 'wing'),
array($this, 'service_config_section_callback'),
'wingServiceConfig'
);
add_settings_field(
'instance',
__('Shipox Instance', 'wing'),
array($this, 'shipox_instance_render'),
'wingServiceConfig',
'service_config_section_tab'
);
add_settings_field(
'test_mode',
__('Debug Mode', 'wing'),
array($this, 'test_mode_render'),
'wingServiceConfig',
'service_config_section_tab'
);
add_settings_field(
'auto_push',
__('Auto Push', 'wing'),
array($this, 'auto_push_render'),
'wingServiceConfig',
'service_config_section_tab'
);
}
/**
* Merchant Configuration Fields
*/
public function init_merchant_configuration_fields() {
register_setting(
'merchant_config_section', // Option group
'wing_merchant_config'
);
add_settings_section(
'merchant_config_section_tab',
__('Service Configuration', 'wing'),
array($this, 'merchant_config_section_callback'),
'page_merchant_config'
);
add_settings_field(
'merchant_username',
__('Merchant Email', 'wing'),
array($this, 'merchant_username_render'),
'page_merchant_config',
'merchant_config_section_tab'
);
add_settings_field(
'merchant_password',
__('Merchant Password', '<PASSWORD>'),
array($this, 'merchant_password_render'),
'page_merchant_config',
'merchant_config_section_tab'
);
add_settings_field(
'merchant_get_token',
'',
array($this, 'merchant_get_token_render'),
'page_merchant_config',
'merchant_config_section_tab'
);
add_settings_field(
'merchant_token',
'',
array($this, 'merchant_token_render'),
'page_merchant_config',
'merchant_config_section_tab'
);
}
/**
* Merchant Address Fields
*/
public function init_merchant_address_fields() {
register_setting(
'merchant_address_section', // Option group
'wing_merchant_address'
);
add_settings_section(
'merchant_address_section_tab',
__('Merchant Address', 'wing'),
array($this, 'merchant_address_section_callback'),
'page_merchant_address'
);
add_settings_field(
'merchant_company_name',
__('Company Name', 'wing'),
array($this, 'merchant_company_name_render'),
'page_merchant_address',
'merchant_address_section_tab'
);
add_settings_field(
'merchant_contact_name',
__('Contact Name', 'wing'),
array($this, 'merchant_contact_name_render'),
'page_merchant_address',
'merchant_address_section_tab'
);
add_settings_field(
'merchant_contact_email',
__('Contact Email', 'wing'),
array($this, 'merchant_contact_email_render'),
'page_merchant_address',
'merchant_address_section_tab'
);
add_settings_field(
'merchant_city',
__('City', 'wing'),
array($this, 'merchant_city_render'),
'page_merchant_address',
'merchant_address_section_tab'
);
add_settings_field(
'merchant_postcode',
__('PostCode', 'wing'),
array($this, 'merchant_postcode_render'),
'page_merchant_address',
'merchant_address_section_tab'
);
add_settings_field(
'merchant_street',
__('Street', 'wing'),
array($this, 'merchant_street_render'),
'page_merchant_address',
'merchant_address_section_tab'
);
add_settings_field(
'wing_merchant_address',
__('Address', 'wing'),
array($this, 'merchant_address_render'),
'page_merchant_address',
'merchant_address_section_tab'
);
add_settings_field(
'merchant_phone',
__('Phone', 'wing'),
array($this, 'merchant_phone_render'),
'page_merchant_address',
'merchant_address_section_tab'
);
add_settings_field(
'merchant_lat_long',
__('Latitude & Longitude', 'wing'),
array($this, 'merchant_lat_long_render'),
'page_merchant_address',
'merchant_address_section_tab'
);
add_settings_field(
'merchant_details',
__('Details', 'wing'),
array($this, 'merchant_details_render'),
'page_merchant_address',
'merchant_address_section_tab'
);
}
/**
* Init Configuration Fields
*/
public function init_wing_order_configuration_fields() {
register_setting(
'wing_order_config_section', // Option group
'wing_order_config'
);
add_settings_section(
'wing_order_config_section_tab',
__('Order Configuration', 'wing'),
array($this, 'wing_order_config_section_callback'),
'page_wing_order_config'
);
add_settings_field(
'order_international_availability',
__('International Order Availability', 'wing'),
array($this, 'order_international_availability_render'),
'page_wing_order_config',
'wing_order_config_section_tab'
);
add_settings_field(
'order_default_weight',
__('Default Weight', 'wing'),
array($this, 'order_default_weight_render'),
'page_wing_order_config',
'wing_order_config_section_tab'
);
add_settings_field(
'order_default_courier_type',
__('Default Courier Type', 'wing'),
array($this, 'order_default_courier_type_render'),
'page_wing_order_config',
'wing_order_config_section_tab'
);
add_settings_field(
'order_default_payment_option',
__('Default Payment Option', 'wing'),
array($this, 'order_default_payment_option_render'),
'page_wing_order_config',
'wing_order_config_section_tab'
);
}
/**
* Service Section
*/
public function service_config_section_callback() {
echo __('', 'wing');
}
/**
* Service Test Mode Render
*/
function shipox_instance_render()
{
$options = get_option('wing_service_config');
?>
<select name='wing_service_config[instance]' class="wing-input-class" title="Shipox Instance">
<option value='1' <?php selected($options['instance'], 1); ?>>Instance 1</option>
<option value='2' <?php selected($options['instance'], 2); ?>>Instance 2</option>
</select>
<?php
}
/**
* Service Test Mode Render
*/
function test_mode_render()
{
$options = get_option('wing_service_config');
?>
<select name='wing_service_config[test_mode]' class="wing-input-class" title="Debug Mode">
<option value='1' <?php selected($options['test_mode'], 1); ?>>Yes</option>
<option value='2' <?php selected($options['test_mode'], 2); ?>>No</option>
</select>
<?php
}
/**
* Service Google Key Render
*/
function auto_push_render()
{
$options = get_option('wing_service_config');
$order_statuses = wc_get_order_statuses();
?>
<select name='wing_service_config[auto_push]' class="wing-input-class" title="Auto Push">
<option value="0" <?php selected($options['auto_push'], 0); ?>>Off</option>
<?php
foreach ($order_statuses as $key => $status) {
echo "<option value='$key' ".selected($options['auto_push'], $key).">$status</option>";
}
?>
</select>
<p><strong>INFO:</strong> You can select auto push trigger function on which order status. Off - means auto push is disabled</p>
<?php
}
/**
* Merchant Section
*/
public function merchant_config_section_callback() {
echo __('', 'wing');
}
/**
* Merchant UserName Field
*/
public function merchant_username_render() {
$options = get_option('wing_merchant_config');
?>
<input id='shipox_merchant_username' class="wing-input-class" type='text' required title="Merchant Username"
name='wing_merchant_config[merchant_username]' value='<?php echo $options['merchant_username']; ?>' />
<?php
}
/**
* Merchant Password Render
*/
function merchant_password_render()
{
$options = get_option('wing_merchant_config');
?>
<input id='shipox_merchant_password' class="wing-input-class" type='password' required title="Merchant Password"
name='wing_merchant_config[merchant_password]'
value='<?php echo $options['merchant_password']; ?>' />
<?php
}
/**
* Merchant Get Token Render
*/
function merchant_get_token_render()
{
?>
<input type="hidden" id="shipoxTokenNonce" value="<?php echo wp_create_nonce( "shipox-wp-woocommerse-plugin" ); ?>">
<button id="shipoxGetToken" class="button button-primary">Get Token</button>
<?php
}
/**
* Merchant Token Hidden Field
*/
function merchant_token_render()
{
$options = get_option('wing_merchant_config');
?>
<textarea id="woocommerce_shipox_token" title="Merchant token" style="visibility: hidden"
name="wing_merchant_config[merchant_token]"><?php echo $options['merchant_token']; ?></textarea>
<?php
}
/**
* Merchant Address Section Callback
*/
public function merchant_address_section_callback() {
echo __('', 'wing');
}
/**
* Merchant Company Name Render
*/
function merchant_company_name_render()
{
$options = get_option('wing_merchant_address');
?>
<input id='wing_woocommerce_company_name' class="wing-input-class" type='text' title="Merchant Company Name"
name='wing_merchant_address[merchant_company_name]' required value='<?php echo $options['merchant_company_name']; ?>' />
<?php
}
/**
* Merchant Contact Name Render
*/
function merchant_contact_name_render()
{
$options = get_option('wing_merchant_address');
?>
<input id='wing_woocommerce_contact_name' class="wing-input-class" type='text' title="Merchant Contact Name"
name='wing_merchant_address[merchant_contact_name]' required value='<?php echo $options['merchant_contact_name']; ?>' />
<?php
}
/**
* Merchant Contact Email Render
*/
function merchant_contact_email_render()
{
$options = get_option('wing_merchant_address');
?>
<input id='wing_woocommerce_contact_name' class="wing-input-class" type='text' title="Merchant Email"
name='wing_merchant_address[merchant_contact_email]' required value='<?php echo $options['merchant_contact_email']; ?>' />
<?php
}
/**
* Merchant City Render
*/
function merchant_city_render()
{
$options = get_option('wing_merchant_address');
?>
<input id='wing_woocommerce_city' class="wing-input-class" type='text' title="Merchant City"
name='wing_merchant_address[merchant_city]' required value='<?php echo $options['merchant_city']; ?>' />
<?php
}
/**
* Merchant Postcode Render
*/
function merchant_postcode_render()
{
$options = get_option('wing_merchant_address');
?>
<input id='wing_woocommerce_postcode' class="wing-input-class" type='text' title="Merchant Postcode"
name='wing_merchant_address[merchant_postcode]' value='<?php echo $options['merchant_postcode']; ?>' />
<?php
}
/**
* Merchant Street Render
*/
function merchant_street_render()
{
$options = get_option('wing_merchant_address');
?>
<input id='wing_woocommerce_street' class="wing-input-class" type='text' title="Merchant Street"
name='wing_merchant_address[merchant_street]' value='<?php echo $options['merchant_street']; ?>' />
<?php
}
/**
* Merchant Address Render
*/
function merchant_address_render()
{
$options = get_option('wing_merchant_address');
?>
<input id='wing_woocommerce_address' class="wing-input-class" type='text' title="Merchant Address"
name='wing_merchant_address[merchant_address]' required value='<?php echo $options['merchant_address']; ?>' />
<?php
}
/**
* Merchant Phone Render
*/
function merchant_phone_render()
{
$options = get_option('wing_merchant_address');
?>
<input id='wing_woocommerce_phone' class="wing-input-class" type='text' title="Merchant Phone Number"
name='wing_merchant_address[merchant_phone]' required value='<?php echo $options['merchant_phone']; ?>' />
<?php
}
/**
* Merchant Latitude & Longitude Render
*/
function merchant_lat_long_render()
{
$options = get_option('wing_merchant_address');
?>
<input id='wing_woocommerce_lat_long' class="wing-input-class" type='text' title="Merchant Latitude & Longitude"
name='wing_merchant_address[merchant_lat_long]' required value='<?php echo $options['merchant_lat_long']; ?>' />
<p><strong>Important:</strong> Merchant Latitude & Longitude is field is required. Latitude & Longitude field should include only numbers and separatd with comma (lat,lon)</p>
<?php
}
/**
* Merchant Details Render
*/
function merchant_details_render()
{
$options = get_option('wing_merchant_address');
?>
<textarea id='wing_woocommerce_details' class="wing-input-class" cols="4" rows="8" title="Merchant Details"
name='wing_merchant_address[merchant_details]'><?php echo $options['merchant_details']; ?></textarea>
<?php
}
/**
* Order Configuration Callback
*/
public function wing_order_config_section_callback() {
echo __('', 'wing');
}
/**
* International Order Availability
*/
public function order_international_availability_render() {
$options = get_option('wing_order_config');
?>
<select name='wing_order_config[order_international_availability]' class="wing-input-class" title="Default International Availability">
<option value='0' <?php selected($options['order_international_availability'], 0); ?>>Not available</option>
<option value='1' <?php selected($options['order_international_availability'], 1); ?>>Available</option>
</select>
<?php
}
/**
* Default Weight
*/
public function order_default_weight_render()
{
$options = get_option('wing_order_config');
?>
<select name='wing_order_config[order_default_weight]' class="wing-input-class" title="Default Weight">
<?php
$items = shipox()->wing['menu-type']->toOptionArray();
foreach ($items as $item) {
echo '<option value="' . $item['value'] . '" ' . selected($options['order_default_weight'] , $item['value']) . '>' . $item['label'] . '</option>';
}
?>
</select>
<?php
}
/**
* Default Courier Type
*/
public function order_default_courier_type_render()
{
$options = get_option('wing_order_config');
?>
<select name=wing_order_config[order_default_courier_type][]' class="wing-input-class" title="Default Courier Type" multiple>
<?php
$items = shipox()->wing['courier-type']->toOptionArray();
foreach ($items as $item) {
$isSelected = in_array($item['value'], $options['order_default_courier_type']);
echo '<option value="' . $item['value'] . '" ' . selected($isSelected) . '>' . $item['label'] . '</option>';
}
?>
</select>
<?php
}
/**
* Default Payment Type
*/
public function order_default_payment_option_render()
{
$options = get_option('wing_order_config');
?>
<select name='wing_order_config[order_default_payment_option]' class="wing-input-class" title="Default Payment Option">
<?php
$items = shipox()->wing['payment-type']->toOptionArray();
foreach ($items as $item) {
echo '<option value="' . $item['value'] . '" ' . selected($options['order_default_payment_option'] , $item['value']) . '>' . $item['label'] . '</option>';
}
?>
</select>
<?php
}
/**
* Rendering Options Fields
*/
public function render_options() {
if (isset($_GET['tab'])) {
$active_tab = $_GET['tab'];
} else {
$active_tab = 'service_config';
}
?>
<form action='options.php' method='post'>
<h1><?php __('Shipox Merchant Settings')?></h1>
<hr/>
<h2 class="nav-tab-wrapper">
<a href="?page=<?php echo SHIPOX_SLUG; ?>&tab=service_config"
class="nav-tab <?php echo $active_tab == 'service_config' ? 'nav-tab-active' : ''; ?>">1. Service
Configuration</a>
<a href="?page=<?php echo SHIPOX_SLUG; ?>&tab=merchant_info"
class="nav-tab <?php echo $active_tab == 'merchant_info' ? 'nav-tab-active' : ''; ?>">2. Merchant
Credentials</a>
<a href="?page=<?php echo SHIPOX_SLUG; ?>&tab=merchant_address"
class="nav-tab <?php echo $active_tab == 'merchant_address' ? 'nav-tab-active' : ''; ?>">3. Merchant Address
Details</a>
<a href="?page=<?php echo SHIPOX_SLUG; ?>&tab=order_settings"
class="nav-tab <?php echo $active_tab == 'order_settings' ? 'nav-tab-active' : ''; ?>">4. Order Settings
</a>
</h2>
<?php
if ($active_tab == 'service_config') {
settings_fields( 'service_config_section' );
do_settings_sections( 'wingServiceConfig' );
} else if ($active_tab == 'merchant_info') {
settings_fields('merchant_config_section');
do_settings_sections('page_merchant_config');
} else if ($active_tab == 'merchant_address') {
settings_fields('merchant_address_section');
do_settings_sections('page_merchant_address');
} else if ($active_tab == 'order_settings') {
settings_fields('wing_order_config_section');
do_settings_sections('page_wing_order_config');
}
submit_button();
?>
</form>
<?php
}
}
new Shipox_Options();<file_sep><?php
/**
* Created by Shipoxy.
* User: Shipox
* Date: 11/8/2017
* Time: 2:41 PM
*/
abstract class SHIPOX_LOG_STATUS {
const __default = self::INFO;
const INFO = 'info';
const ERROR = 'error';
const WARNING = 'warning';
}<file_sep>Official.
Shipox - One-Stop Delivery Solution for Your Business
Most innovative mobile and web-based delivery app for businesses and individual consumers. It offers delivery for businesses throughout the UAE and customers from UAE to anywhere in the world
<file_sep><?php
/**
* Created by Shipox.
* User: Shipox
* Date: 11/8/2017
* Time: 2:41 PM
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
class Shipping_Options
{
/**
* @return array
*/
public function toOptionArray()
{
return array(
array('value' => 'bike_in_5_days', 'label' => 'Bike: Delivery: 1-4 working days'),
array('value' => 'bike_next_day', 'label' => 'Bike: Delivery: within 24 hours'),
array('value' => 'bike_same_day', 'label' => 'Bike: Delivery: within same day'),
array('value' => 'bike_bullet', 'label' => 'Bike: Delivery: within 4 hours'),
array('value' => 'sedan_in_5_days', 'label' => 'Sedan: Delivery: 1-4 working days'),
array('value' => 'sedan_next_day', 'label' => 'Sedan: Delivery: within 24 hours'),
array('value' => 'sedan_same_day', 'label' => 'Sedan: Delivery: within same day'),
array('value' => 'sedan_bullet', 'label' => 'Sedan: Delivery: within 4 hours'),
array('value' => 'minivan_in_5_days', 'label' => 'Small Van: Delivery: 1-4 working days'),
array('value' => 'minivan_next_day', 'label' => 'Small Van: Delivery: within 24 hours'),
array('value' => 'minivan_same_day', 'label' => 'Small Van: Delivery: within same day'),
array('value' => 'minivan_bullet', 'label' => 'Small Van: Delivery: within 4 hours'),
array('value' => 'panelvan_in_5_days', 'label' => 'Panel Van: Delivery: 1-4 working days'),
array('value' => 'panelvan_next_day', 'label' => 'Panel Van: Delivery: within 24 hours'),
array('value' => 'panelvan_same_day', 'label' => 'Panel Van: Delivery: within same day'),
array('value' => 'panelvan_bullet', 'label' => 'Panel Van: Delivery: within 4 hours'),
array('value' => 'light_truck_in_5_days', 'label' => 'International: Delivery: 1-4 working days'),
array('value' => 'light_truck_next_day', 'label' => 'International: Delivery: within 24 hours'),
array('value' => 'light_truck_same_day', 'label' => 'International: Delivery: within same day'),
array('value' => 'light_truck_bullet', 'label' => 'International: Delivery: within 4 hours'),
array('value' => 'refrigerated_truck_in_5_days', 'label' => 'Refrigerated Truck: Delivery: 1-4 working days'),
array('value' => 'refrigerated_truck_next_day', 'label' => 'Refrigerated Truck: Delivery: within 24 hours'),
array('value' => 'refrigerated_truck_same_day', 'label' => 'Refrigerated Truck: Delivery: within same day'),
array('value' => 'refrigerated_truck_bullet', 'label' => 'Refrigerated Truck: Delivery: within 4 hours'),
array('value' => 'towing_in_5_days', 'label' => 'Towing: Delivery: 1-4 working days'),
array('value' => 'towing_next_day', 'label' => 'Towing: Delivery: within 24 hours'),
array('value' => 'towing_same_day', 'label' => 'Towing: Delivery: within same day'),
array('value' => 'towing_bullet', 'label' => 'Towing: Delivery: within 4 hours'),
array('value' => 'relocation_in_5_days', 'label' => 'Relocation: Delivery: 1-4 working days'),
array('value' => 'relocation_next_day', 'label' => 'Relocation: Delivery: within 24 hours'),
array('value' => 'relocation_same_day', 'label' => 'Relocation: Delivery: within same day'),
array('value' => 'relocation_bullet', 'label' => 'Relocation: Delivery: within 4 hours'),
);
}
}<file_sep><?php
/**
* Plugin Name: Shipox
* Plugin URI: https://www.shipox.com
* Description: Official Shipox plugin for WooCommerce
* Version: 4.0.0
* Author: Shipox
* Author URI: https://www.shipox.com
* Requires at least: 4.4
* Tested up to: 5.2.2
* WC requires at least: 3.0.0
* WC tested up to: 3.7.0
*
* Text Domain: shipox
* Domain Path: /i18n/languages/
*
* @package Shipox
* @category Core
* @author <NAME>
*/
if (!defined('ABSPATH')) {
exit; // Exit if accessed directly.
}
// Define WC_PLUGIN_FILE.
if (!defined('SHIPOX_PLUGIN_FILE')) {
define('SHIPOX_PLUGIN_FILE', __FILE__);
}
// Define WC_PLUGIN_FILE.
if (!defined('SHIPOX_SLUG')) {
define('SHIPOX_SLUG', 'wing');
}
if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
// Include the main WooCommerce class.
if (!class_exists('Shipox')) {
include_once dirname(__FILE__) . '/classes/class-shipox.php';
}
/**
* Main instance of Shipox.
*
* Returns the main instance of WING to prevent the need to use globals.
*
* @since 2.0
* @return Shipox
*/
function shipox()
{
return Shipox::instance();
}
// Global for backwards compatibility.
$GLOBALS['shipox'] = shipox();
}<file_sep><?php
/**
* Created by PhpStorm.
* User: UmidAkhmedjanov
* Date: 12/21/2018
* Time: 2:15 PM
*/
if (!defined('ABSPATH')) {
return;
}
class Shipox_Cron_Job
{
private $interval = 60 * 60;
private $_serviceConfig = array();
private $_merchantInfo = array();
private $_merchantConfig = array();
/**
* Start the Integration
*/
public function __construct()
{
$this->_serviceConfig = get_option('wing_service_config');
$this->_merchantInfo = get_option('wing_merchant_address');
$this->_merchantConfig = get_option('wing_merchant_config');
add_filter('cron_schedules', array($this, 'crawl_every_n_minutes'));
if (!wp_next_scheduled('crawl_every_n_minutes')) {
wp_schedule_event(time(), 'every_n_minutes', 'crawl_every_n_minutes');
}
add_action('crawl_every_n_minutes', array($this, 'crawl_feeds'));
}
/**
* @param $schedules
* @return mixed
*/
public function crawl_every_n_minutes($schedules)
{
$schedules['every_n_minutes'] = array(
'interval' => $this->interval,
'display' => __('Every N Minutes', 'aur_domain')
);
return $schedules;
}
/**
* Get Live Events of Soccer
*/
public function crawl_feeds()
{
shipox()->api->checkTokenExpired();
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: umidakhm
* Date: 10/17/2018
* Time: 3:31 PM
*/
namespace includes;
class Shipox_Settings_Helper
{
private $_countryId = 229;
private $_countryCode = 'AE';
private $_countryName = 'United Arab Emirates';
private $_currency = 'AED';
private $_intAvailability = false;
private $_newModelEnabled = false;
private $_host = 'my.shipox.com';
/**
* @return mixed|void
*/
public function getMarketplaceSettings()
{
return get_option('wing_marketplace_settings');
}
/**
* Get Marketplace Host
*/
public function getCountryId()
{
$marketplaceSettings = $this->getMarketplaceSettings();
return isset($marketplaceSettings['country']['id']) ? $marketplaceSettings['country']['id'] : $this->_countryId;
}
/**
* Get Marketplace Host
*/
public function getCountryCode()
{
$marketplaceSettings = $this->getMarketplaceSettings();
return isset($marketplaceSettings['country']['description']) ? $marketplaceSettings['country']['description'] : $this->_countryCode;
}
/**
* Get Marketplace Country Code
*/
public function getMarketplaceHost()
{
$marketplaceSettings = $this->getMarketplaceSettings();
return isset($marketplaceSettings['host']) ? $marketplaceSettings['host'] : $this->_host;
}
/**
* Get Marketplace Country Code
*/
public function getCountryName()
{
$marketplaceSettings = $this->getMarketplaceSettings();
return isset($marketplaceSettings['country']['name']) ? $marketplaceSettings['country']['name'] : $this->_countryName;
}
/**
* Get Marketplace Currency
*/
public function getCurrency()
{
$marketplaceSettings = $this->getMarketplaceSettings();
return isset($marketplaceSettings['currency']) ? $marketplaceSettings['currency'] : $this->_currency;
}
/**
* Get International Availability
*/
public function getInternationalAvailability()
{
$marketplaceSettings = $this->getMarketplaceSettings();
return isset($marketplaceSettings['disable_international_orders']) ? !$marketplaceSettings['disable_international_orders'] : $this->_intAvailability;
}
/**
* Get New Model Enabled
*/
public function getNewModelEnabled()
{
$marketplaceSettings = $this->getMarketplaceSettings();
return isset($marketplaceSettings['new_model_enabled']) ? $marketplaceSettings['new_model_enabled'] : $this->_newModelEnabled;
}
}<file_sep><?php
/**
* Created by Shipoxy.
* User: Shipox
* Date: 11/8/2017
* Time: 2:41 PM
*/
class Shipox_Backend_Actions
{
/**
* API_HELPER constructor.
*/
public function __construct()
{
add_action('woocommerce_order_status_changed', array($this, 'wing_status_changed_action'), 10, 3);
add_action('woocommerce_admin_order_data_after_order_details', array($this, 'wing_order_metabox'));
add_action('woocommerce_process_shop_order_meta', array($this, 'wing_order_save_metabox'), PHP_INT_MAX, 3);
}
/**
* Create Wing order by Order WC Actions
* @param $order_id
* @param $from_status
* @param $to_status
*/
function wing_status_changed_action($order_id, $from_status, $to_status)
{
$serviceConfig = shipox()->wing['options']['service_config'];
$orderConfig = shipox()->wing['options']['order_config'];
$order = new WC_Order($order_id);
$shipping_method = get_post_meta($order->get_id(), '_wing_order_package');
$shipping_method[] = "0";
$shipping_method = reset($shipping_method);
$orderNumber = get_post_meta($order->get_id(), '_wing_order_number');
if ($serviceConfig['auto_push'] == "wc-" . $to_status && strpos($shipping_method, "wing_") == false && empty($orderNumber)) {
$shipping_country = trim(get_post_meta($order->get_id(), '_shipping_country', true));
$availability = shipox()->wing['order-helper']->check_wing_order_create_availability($order, $shipping_country);
if ($availability['success']) {
$isNewModel = shipox()->wing['settings-helper']->getNewModelEnabled();
if($isNewModel) {
// New Model
$priceList = shipox()->wing["api-helper"]->getWingPackageV2($order, $shipping_country);
$toLatLon = $priceList['data']['lat_lon'];
$customerLatLon = explode(",", $toLatLon);
if ($priceList['success']) {
$packageList = $priceList['data']['list'];
$auto_selected_package = shipox()->wing['api-helper']->getProperPackageV2($orderConfig['order_default_courier_type'], $packageList);
if($auto_selected_package) {
$weight = $priceList['data']['weight'];
$isDomestic = $priceList['data']['is_domestic'];
$country = shipox()->wing["api-helper"]->getCountryWingId($shipping_country);
$packageString = $auto_selected_package['id'].'-'.$auto_selected_package['price']['id'].'-'.$weight.'-'.($isDomestic ? '1' : '0');
shipox()->wing['api-helper']->pushOrderToWingWithPackageNewModel($order, $packageString, $customerLatLon, $country);
} else {
$order->add_order_note("Shipox: Could not find proper package!", 0);
shipox()->log->write($packageList, 'package-error');
shipox()->log->write("Default Courier Type: " . $orderConfig['order_default_courier_type'], 'package-error');
}
} else {
$order->add_order_note($priceList['message'], 0);
shipox()->log->write($priceList, 'package-error');
shipox()->log->write("Shipping Country: " . $shipping_country, 'package-error');
}
} else {
// Old Model
$packages = shipox()->wing["api-helper"]->getWingPackages($order, $shipping_country);
if ($packages['success']) {
$toLatLon = $packages['data']['lat_lon'];
$customerLatLon = explode(",", $toLatLon);
$packageList = $packages['data']['list'];
$auto_selected_package_id = shipox()->wing['api-helper']->getProperPackage($orderConfig['order_default_courier_type'], $packageList);
if (intval($auto_selected_package_id) > 0) {
shipox()->wing['api-helper']->pushOrderToWingWithPackage($order, $auto_selected_package_id, $customerLatLon);
} else {
$order->add_order_note("Shipox: Could not find proper package!", 0);
shipox()->log->write($packageList, 'package-error');
shipox()->log->write("Default Courier Type: " . $orderConfig['order_default_courier_type'], 'package-error');
}
} else {
$order->add_order_note($packages['message'], 0);
shipox()->log->write($packages, 'package-error');
shipox()->log->write("Shipping Country: " . $shipping_country, 'package-error');
}
}
} else {
$order->add_order_note($availability['message'], 0);
shipox()->log->write($order, 'availability-error');
shipox()->log->write("Shipping Country: " . $shipping_country, 'availability-error');
}
} elseif($to_status == "cancelled" && !empty($orderNumber)) {
$data = array(
'note' => "Order Cancelled by Customer",
'reason' => "Order Cancelled by Customer",
'status' => 'cancelled'
);
$orderId = get_post_meta($order->get_id(), '_wing_order_id', true);
$response = shipox()->api->updateOrderStatus($orderId, $data);
if ($response['success']) {
$order->add_order_note("Shipox: " . $orderNumber[0] . " is cancelled successfully", 1);
} else {
$order->add_order_note($response['data']['message'], 0);
shipox()->log->write($response, 'order-error');
}
}
}
/**
* @param $order
*/
function wing_order_metabox($order)
{
echo "<br class=\"clear\" />";
$orderNumber = get_post_meta($order->get_id(), '_wing_order_number');
$orderId = get_post_meta($order->get_id(), '_wing_order_id');
$shipping_method = get_post_meta($order->get_id(), '_wing_order_package');
$shipping_method[] = "0";
$shipping_method = reset($shipping_method);
$selectedPackage = null;
$isPackagesAvailable = false;
$packages = null;
$packageOptions = array(
0 => "Select Package"
);
$toLatLon = null;
$errorMessage = null;
if (empty($orderNumber)) {
$shipping_country = trim(get_post_meta($order->get_id(), '_shipping_country', true));
$availability = shipox()->wing['order-helper']->check_wing_order_create_availability($order, $shipping_country);
if ($availability['success']) {
$isNewModel = shipox()->wing['settings-helper']->getNewModelEnabled();
if($isNewModel) {
$priceList = shipox()->wing["api-helper"]->getWingPackageV2($order, $shipping_country);
if ($priceList['success']) {
$isPackagesAvailable = true;
$list = $priceList['data']['list'];
$weight = $priceList['data']['weight'];
$isDomestic = $priceList['data']['is_domestic'];
$toLatLon = $priceList['data']['lat_lon'];
foreach ($list as $listItem) {
$priceItem = $listItem['price'];
$name = $listItem['supplier']['name'] . " - " . $listItem['name'];
$method = $listItem['id'].'-'.$priceItem['id'].'-'.$weight.'-'.($isDomestic ? '1' : '0');
$currency = $priceItem['currency']['code'];
$response['type'] = 'success';
$packageOptions['wing_' .$method] = $name . " (" . $priceItem['total'] . " " . $currency . ")";
}
} else $errorMessage = $packages['message'];
} else {
$packages = shipox()->wing["api-helper"]->getWingPackages($order, $shipping_country);
if ($packages['success']) {
$isPackagesAvailable = true;
$selectedPackage = strpos($shipping_method, "wing_") != false ? $shipping_method : null;
$toLatLon = $packages['data']['lat_lon'];
foreach ($packages['data']['list'] as $listItem) {
$packageList = $listItem['packages'];
$name = $listItem['name'];
foreach ($packageList as $packageItem) {
$label = $packageItem['delivery_label'];
$price = $packageItem['price']['total'];
$currency = $packageItem['price']['currency']['code'];
$packageOptions['wing_' . $packageItem['id']] = $name . " - " . $label . " (" . $price . " " . $currency . ")";
}
}
} else $errorMessage = $packages['message'];
}
} else $errorMessage = $availability['message'];
echo "<h4>Shipox ";
echo $isPackagesAvailable ? "<a href=\"#\" class=\"edit_address\">Edit</a>" : null;
echo "</h4>";
if ($isPackagesAvailable) {
echo "<div class=\"address\">";
echo "<a href=\"#\" class=\"edit_address wing_create_order_link\">".__("Create Shipox Order", 'wing')."</a>";
echo "</div>";
echo "<div class=\"edit_address\">";
woocommerce_wp_select(array(
'id' => 'wing_package',
'label' => 'Packages:',
'value' => $selectedPackage,
'class' => 'wing-select-field',
'options' => $packageOptions,
'wrapper_class' => 'form-field-wide'
));
woocommerce_wp_hidden_input(array(
'id' => 'wing_custom_lat_lon',
'value' => $toLatLon,
'wrapper_class' => 'form-field-wide'
));
echo "</div>";
} else {
echo "<div class='wing-error'>" . $errorMessage . "</div>";
}
} else {
$airwaybill = shipox()->wing['api-helper']->getAirwaybill($orderId[0]);
echo "<h4 style='margin-bottom: 10px'>Shipox</h4>";
echo "<div class=\"address\">";
echo __("Order Number: #" . $orderNumber[0], 'wing');
echo "<br class=\"clear\" />";
echo "<a target=\"_blank\" href='" . shipox()->wing['api-helper']->getTrackingURl() . "/track?id=" . $orderNumber[0] . "'>Track Order</a>";
if($airwaybill) {
echo "<br class=\"clear\" />";
echo "<a target=\"_blank\" href='" . $airwaybill . "'>Download Airwaybill</a>";
}
echo "</div>";
}
}
/**
*
* @param $order_id
*/
function wing_order_save_metabox($order_id)
{
$order = new WC_Order($order_id);
if ($order->get_status() == 'processing') {
$shippingMethod = wc_clean($_POST['wing_package']);
$shipping_country = trim(get_post_meta($order_id, '_shipping_country', true));
$package_data = explode("_", $shippingMethod);
$toLatLon = wc_clean($_POST['wing_custom_lat_lon']);
$customerLatLong = explode(",", $toLatLon);
$country = shipox()->wing["api-helper"]->getCountryWingId($shipping_country);
if (count($package_data) > 0) {
update_post_meta($order->get_id(), '_wing_order_package', $shippingMethod);
$isNewModel = shipox()->wing['settings-helper']->getNewModelEnabled();
if($isNewModel)
shipox()->wing['api-helper']->pushOrderToWingWithPackageNewModel($order, $package_data[1], $customerLatLong, $country);
else
shipox()->wing['api-helper']->pushOrderToWingWithPackage($order, $package_data[1], $customerLatLong);
}
}
}
}
new Shipox_Backend_Actions();<file_sep><?php
/**
* Created by Shipox.
* User: Shipox
* Date: 11/8/2017
* Time: 2:41 PM
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
class Payment_Type
{
public function toOptionArray()
{
return array(
array('value' => 'cash', 'label' => 'Cash'),
array('value' => 'credit_balance', 'label' => 'Credit Balance')
// array('value' => 'paypal', 'label' => 'Online Payment')
);
}
public function toValueArray()
{
$result = array();
$options = $this->toOptionArray();
foreach ($options as $option) {
$result[] = $option['value'];
}
return $result;
}
}<file_sep><?php
/**
* Created by Shipox.
* User: Shipox
* Date: 11/8/2017
* Time: 2:41 PM
*/
class Shipox_Frontend_Actions
{
/**
* WING_FRONTEND_ACTIONS constructor.
*/
public function __construct()
{
add_action('woocommerce_review_order_before_cart_contents', array($this, 'wing_validate_order'), 10);
add_action('woocommerce_after_checkout_validation', array($this, 'wing_validate_order'), 10);
add_filter('woocommerce_available_payment_gateways', array($this, 'wing_available_payment_gateways'));
// add_action('woocommerce_checkout_order_processed', array($this, 'wing_order_processed'), 10, 1);
add_action('woocommerce_thankyou', array($this, 'wing_order_processed'), 10, 1);
}
/**
* @param $posted
*/
public function wing_validate_order($posted)
{
$packages = WC()->shipping->get_packages();
$chosen_methods = WC()->session->get('chosen_shipping_methods', null);
$is_wing_chosen = false;
if (is_array($chosen_methods)) {
foreach ($chosen_methods as $method) {
if (strpos($method, "wing_") !== false) {
$is_wing_chosen = true;
break;
}
}
}
if (is_array($chosen_methods) && $is_wing_chosen) {
foreach ($packages as $i => $package) {
if (strpos($chosen_methods[$i], "wing_") === false) {
continue;
}
$Shipox_Shipping_Method = new Shipox_Shipping_Method();
$weightLimit = (int)$Shipox_Shipping_Method->settings['weight'];
$weight = 0;
foreach ($package['contents'] as $item_id => $values) {
$_product = $values['data'];
$weight = $weight + (float) $_product->get_weight() * (int) $values['quantity'];
}
$weight = wc_get_weight($weight, 'kg');
if ($weight > $weightLimit) {
$message = sprintf(__('Sorry, %d kg exceeds the maximum weight of %d kg for %s', 'wing'), $weight, $weightLimit, $Shipox_Shipping_Method->title);
$messageType = "error";
if (!wc_has_notice($message, $messageType)) {
wc_add_notice($message, $messageType);
}
}
}
}
}
/**
* Remove COD Payment Gateway if order is International
* @param $gateways
* @return mixed
*/
public function wing_available_payment_gateways($gateways)
{
if(isset(WC()->session)) {
$chosen_methods = WC()->session->get('chosen_shipping_methods');
$is_wing_chosen = false;
if (is_array($chosen_methods)) {
foreach ($chosen_methods as $method) {
if (strpos($method, "wing_") !== false) {
$is_wing_chosen = true;
break;
}
}
}
if (is_array($chosen_methods) && $is_wing_chosen) {
$packages = WC()->shipping->get_packages();
$address = isset($packages[0]["destination"]) ? $packages[0]["destination"] : null;
$country = shipox()->wing['api-helper']->getCountryWingId($address["country"]);
if(!shipox()->wing['api-helper']->isDomestic($country["id"])) unset($gateways['cod']);
}
}
return $gateways;
}
/**
* @param $order_id
*/
public function wing_order_processed($order_id) {
if ( ! $order_id )
return;
if( ! get_post_meta( $order_id, '_thankyou_action_done', true ) ) {
$order = new WC_Order( $order_id );
$shipping_country = trim(get_post_meta($order_id, '_shipping_country', true));
$shipping_methods = WC()->session->get( 'chosen_shipping_methods', array() );
foreach ( $shipping_methods as $chosen_method ) {
if (strpos($chosen_method, "wing_") !== false) {
if ($order->get_status() == 'processing') {
$shipping_method_data = explode("_", $chosen_method);
$shipping_address = $order->get_address('shipping');
$country = shipox()->wing["api-helper"]->getCountryWingId($shipping_country);
$customerLatLonAddress = shipox()->wing['api-helper']->getAddressLocation($country, $shipping_address);
if (count($shipping_method_data) > 0) {
update_post_meta($order->get_id(), '_wing_order_package', $chosen_method);
$isNewModel = shipox()->wing['settings-helper']->getNewModelEnabled();
if($isNewModel)
shipox()->wing['api-helper']->pushOrderToWingWithPackageNewModel($order, $shipping_method_data[1], $customerLatLonAddress, $country);
else
shipox()->wing['api-helper']->pushOrderToWingWithPackage($order, $shipping_method_data[1], $customerLatLonAddress);
}
} else {
update_post_meta($order->get_id(), '_wing_order_package', $chosen_method);
shipox()->log->write(sprintf("Payment Title %s and Order status: %s for Order ID: %s", $order->get_payment_method_title(), $order->get_status(), $order_id), 'payment-hold');
$order->add_order_note(sprintf("Shipox: Order is not pushed to Wing because the Payment (Method: %s) is not paid yet.", $order->get_payment_method_title()), 0);
}
}
}
$order->update_meta_data( '_thankyou_action_done', true );
}
}
}
new Shipox_Frontend_Actions();<file_sep><?php
/**
* Created by PhpStorm.
* User: umidakhm
* Date: 10/17/2018
* Time: 3:31 PM
*/
namespace includes;
class Shipox_Order_Helper
{
/**
* @param $order
* @param $shipping_country
* @return array
*/
function check_wing_order_create_availability($order, $shipping_country) {
$baseLocation = wc_get_base_location();
$orderConfig = shipox()->wing['options']['order_config'];
$marketplaceCountry = shipox()->wing['settings-helper']->getCountryCode();
$marketplaceCountryName = shipox()->wing['settings-helper']->getCountryName();
$marketplaceCurrency = shipox()->wing['settings-helper']->getCurrency();
$marketplaceIntAvailability = shipox()->wing['settings-helper']->getInternationalAvailability();
$response = array(
'success' => false,
'message' => null,
);
if ($baseLocation["country"] == $marketplaceCountry) {
$currency = $order->get_currency();
if ($currency == $marketplaceCurrency) {
if ($orderConfig['order_international_availability'] == 0 && !$marketplaceIntAvailability && $shipping_country !== $marketplaceCountry) {
shipox()->log->write($order->get_id() . " - International is turned off", 'error');
$response['message'] = __("Shipox: International Order is turned off", 'wing');
} else {
$response['success'] = true;
}
} else {
shipox()->log->write($order->get_id() . " - CURRENCY should be only ". $marketplaceCurrency, 'error');
$response['message'] = __("Shipox: CURRENCY should be only ". $marketplaceCurrency, 'wing');
}
} else {
shipox()->log->write($order->get_id() . " - Delivery only for ". $marketplaceCountryName, 'error');
$response['message'] = __("Shipox: Service only within ".$marketplaceCountryName, 'wing');
}
return $response;
}
}<file_sep><?php
/**
* Created by Shipox.
* User: Shipox
* Date: 11/8/2017
* Time: 2:41 PM
*/
if (!defined('ABSPATH')) {
exit; // Exit if accessed directly.
}
class Shipox_Api_Client
{
private $_apiHostUrls = array(
1 => array(
"test" => "https://stagingapi.shipox.com",
"live" => "https://prodapi.shipox.com",
),
2 => array(
"test" => "https://stagingapi.shipox.com",
"live" => "https://prodapi.safe-arrival.com",
),
);
private $_authenticateUrl = "/api/v1/customer/authenticate";
private $_countryListUrl = "/api/v1/country/list";
private $_cityListUrl = "/api/v1/cities";
private $_cityItemUrl = "/api/v1/city/";
private $_packageMeuListUrl = "/api/v2/package-menu";
private $_priceListUrl = "/api/v1/packages/prices";
private $_priceListUrlV2 = "/api/v2/packages/plugin/prices/";
private $_createOrderUrl = "/api/v1/customer/order";
private $_createOrderV2Url = "/api/v2/customer/order";
private $_marketplaceUrl = "/api/v1/marketplace";
private $_getOrderDetailsUrl = "/api/v1/customer/order/order_number/";
private $_getCityByName = "/api/v1/city_by_name";
private $_getLocationByAddress = "/api/v1/coordinate_by_address";
private $_getAirwaybill = "/api/v1/customer/order/%s/airwaybill";
private $_updateOrderStatus = "/api/v1/customer/order/{id}/status_update";
private $_getServiceTypes = "/api/v1/admin/service_types";
private $_serviceConfig = array();
private $_merchantInfo = array();
private $_merchantConfig = array();
public $_timeout = 10;
/**
* WingApiClient constructor.
*/
function __construct()
{
$this->init();
}
/**
* Initialize
*/
private function init()
{
$this->_serviceConfig = get_option('wing_service_config');
$this->_merchantInfo = get_option('wing_merchant_address');
$this->_merchantConfig = get_option('wing_merchant_config');
}
/**
* @return int
*/
public function getTimeout()
{
return $this->_timeout;
}
/**
* @return string
*/
public function getAPIBaseURl()
{
$instance = 1;
if(isset($this->_serviceConfig['instance']) && isset($this->_apiHostUrls[$this->_serviceConfig['instance']])) $instance = $this->_serviceConfig['instance'];
if($this->_serviceConfig['test_mode'] == 1) {
return $this->_apiHostUrls[$instance]['test'];
}
return $this->_apiHostUrls[$instance]['live'];
}
/**
* @param null $data
* @return null
*/
public function authenticate($data = null)
{
if ($data == null) {
$data = array(
'username' => $this->_merchantConfig['merchant_username'],
'password' => $this->_<PASSWORD>Config['<PASSWORD>'],
'remember_me' => true
);
}
$response = $this->sendRequest($this->_authenticateUrl, 'post', $data, true);
return $response;
}
/**
* Check Token is expired or not, if expired reauthorize Wing and refresh Token
* @return bool
*/
public function checkTokenExpired()
{
if ((time() - $this->_merchantConfig['last_login_date']) > 100) {
if (is_null($this->_merchantConfig['merchant_username']) && is_null($this->_merchantConfig['merchant_password'])) {
shipox()->log->write("Check Token Expired Function: Merchant option is empty", 'error');
return false;
}
$time_request = time();
$response = $this->authenticate();
if ($response['success']) {
$options['merchant_token'] = $response['data']['id_token'];
$options['merchant_username'] = $this->_merchantConfig['merchant_username'];
$options['merchant_password'] = $this->_merchantConfig['merchant_password'];
$options['last_login_date'] = $time_request;
update_option('wing_merchant_config', $options);
$this->init();
shipox()->wing["api-helper"]->updateCustomerMarketplace();
return true;
}
shipox()->log->write($response['data']['code'] . ": " . $response['data']['message'], 'error');
return false;
}
return true;
}
/**
* @param $url
* @param string $requestMethod
* @param null $data
* @param bool $getToken
* @return array
*/
public function sendRequest($url, $requestMethod = 'get', $data = null, $getToken = false)
{
$response = array();
$response['success'] = false;
if (!$getToken) {
$isTokenValid = $this->checkTokenExpired();
if (!$isTokenValid) {
$response['data']['code'] = 'error.validation';
$response['data']['message'] = __('Token Expired and cannot re-login to the System', 'wing');
return $response;
}
}
$apiURL = $this->getAPIBaseURl();
$requestURL = $apiURL . $url;
$ch = curl_init($requestURL);
switch ($requestMethod) {
case 'get':
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
break;
case 'post':
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
break;
case 'put':
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
break;
case 'delete':
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
}
$json = $data ? json_encode($data) : '';
$curlHeader = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json),
'RemoteAddr: ' . $_SERVER['REMOTE_ADDR']
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$token = $this->_merchantConfig['merchant_token'];
if (!$getToken) {
if ($token) {
$curlHeader[] = 'Authorization: ' . 'Bearer ' . $token;
$curlHeader[] = 'Accept: ' . 'application/json';
} else {
$curlHeader[] = 'Accept: ' . '*/*';
}
} else {
$curlHeader[] = 'Accept: ' . '*/*';
}
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST , 0);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_REFERER, $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
curl_setopt($ch, CURLOPT_HTTPHEADER, $curlHeader);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
$curl_response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if(curl_errno($ch)){
shipox()->log->write(curl_error($ch), 'curl-error');
shipox()->log->write($json, 'curl-error');
shipox()->log->write($httpCode, 'curl-error');
}
$json_result = json_decode($curl_response, true);
shipox()->log->write($requestURL, 'curl-api');
shipox()->log->write($json, 'curl-api');
shipox()->log->write($httpCode, 'curl-api');
shipox()->log->write($curl_response, 'curl-api');
shipox()->log->write($json_result, 'curl-api');
switch (intval($httpCode)) {
case 200:
case 201:
$response['success'] = true;
if ($json_result['status'] == 'success')
$response['data'] = $json_result['data'];
else
$response['data'] = $json_result;
break;
default:
$response['data'] = $json_result;
shipox()->log->write($requestURL, 'api-error');
shipox()->log->write($json, 'api-error');
shipox()->log->write($httpCode, 'api-error');
shipox()->log->write($json_result, 'api-error');
break;
}
return $response;
}
/**
* @return null
*/
public function wingCountries()
{
$response = $this->sendRequest($this->_countryListUrl);
return $response;
}
/**
* @param bool $isDomestic
* @return null
*/
public function getCityList($isDomestic = false)
{
$data = array(
'is_uae' => $isDomestic
);
$response = $this->sendRequest($this->_cityListUrl. "?" . http_build_query($data), 'get');
return $response ? $response['data'] : $response;
}
/**
* @param $cityId
* @return array
*/
public function getCity($cityId)
{
$response = $this->sendRequest($this->_cityItemUrl . $cityId);
return $response;
}
/**
* @param string $params
* @return null
*/
public function wingPackageMenuList($params = '')
{
$response = $this->sendRequest($this->_packageMeuListUrl . $params);
return $response;
}
/**
* @param string $params
* @return null
*/
public function wingCalcPrices($params = '')
{
$response = $this->sendRequest($this->_priceListUrl . $params);
return $response;
}
/**
* @param $data
* @return null
*/
public function wingCreateOrder($data)
{
$response = $this->sendRequest($this->_createOrderUrl, 'post', $data);
return $response;
}
/**
* @param string $orderNumber
* @return null
* @internal param string $params
*/
public function wingGetOrderDetails($orderNumber = '')
{
$response = $this->sendRequest($this->_getOrderDetailsUrl . $orderNumber);
return $response;
}
/**
* @param $cityName
* @return array|mixed
*/
public function wingIsValidCity($cityName)
{
$data = array(
'city_name' => $cityName
);
$url = $this->_getCityByName . "?" . http_build_query($data);
$response = $this->sendRequest($url, 'get');
return $response;
}
/**
* Get Order Aiwaybill
* @param $orderId
* @return array
*/
public function getAirwaybill($orderId) {
$response = $this->sendRequest(sprintf($this->_getAirwaybill, $orderId));
return $response;
}
/**
* @return null
*/
public function getCustomerMarketplace()
{
$response = $this->sendRequest($this->_marketplaceUrl);
return $response;
}
/**
* @param $data
* @return null
*/
public function getLocationByAddress($data)
{
$url = $this->_getLocationByAddress . "?" . http_build_query($data);
$response = $this->sendRequest($url, 'get');
return $response;
}
/**
* @param $orderId
* @param null $data
* @return array|mixed
*/
public function updateOrderStatus($orderId, $data = null)
{
$response = $this->sendRequest(str_replace("{id}", $orderId, $this->_updateOrderStatus), 'put', $data);
return $response;
}
/**
* Get Dynamic Service Types
* @return null
*/
public function getAllServiceTypes()
{
$response = $this->sendRequest($this->_getServiceTypes, 'get');
return $response;
}
/**
* @param $data
* @return array
*/
public function getPackagePricesV2($data) {
$url = $this->_priceListUrlV2 . "?" . http_build_query($data);
$response = $this->sendRequest($url, 'get');
return $response;
}
/**
* @param $data
* @return null
*/
public function wingCreateOrderV2($data)
{
$response = $this->sendRequest($this->_createOrderV2Url, 'post', $data);
return $response;
}
} | c98baf90782c7aa3dd648bea889d982ed05598fc | [
"JavaScript",
"Markdown",
"PHP"
] | 25 | PHP | clintfloyd/sol-plug | c0eaeb6a72691b26e9661b0c586fac2887d41017 | d592c884a9117e1cb14c8bdc7188e0976a402ec6 |
refs/heads/master | <repo_name>buildkite/homebrew-buildkite<file_sep>/buildkite-agent.rb
class BuildkiteAgent < Formula
desc "Build runner for use with Buildkite"
homepage "https://buildkite.com/docs/agent"
stable do
version "3.52.1"
if Hardware::CPU.arm?
url "https://github.com/buildkite/agent/releases/download/v3.52.1/buildkite-agent-darwin-arm64-3.52.1.tar.gz"
sha256 "c22511ee9cd3595bfae2adca3c7ed5f8a0a0dd32be2c4a6dc68204ae11dfd08a"
else
url "https://github.com/buildkite/agent/releases/download/v3.52.1/buildkite-agent-darwin-amd64-3.52.1.tar.gz"
sha256 "e674068b65c8e84c16594fc4fdd4e5f526bc8e59feea139245bcded28f39f38f"
end
end
def agent_etc
etc/"buildkite-agent"
end
def agent_var
var/"buildkite-agent"
end
def agent_hooks_path
agent_etc/"hooks"
end
def agent_builds_path
agent_var/"builds"
end
def agent_plugins_path
agent_var/"plugins"
end
def agent_bootstrap_path
if stable?
agent_etc/"bootstrap.sh"
else
opt_bin/"buildkite-agent bootstrap"
end
end
def agent_config_path
agent_etc/"buildkite-agent.cfg"
end
def agent_config_dist_path
pkgshare/"buildkite-agent.dist.cfg"
end
def install
agent_etc.mkpath
agent_var.mkpath
pkgshare.mkpath
agent_hooks_path.mkpath
agent_builds_path.mkpath
agent_hooks_path.install Dir["hooks/*"]
if stable?
agent_etc.install "bootstrap.sh"
end
agent_config_dist_path.write(default_config_file)
if agent_config_path.exist?
puts "\033[35mIgnoring existing config file at #{agent_config_path}\033[0m"
puts "\033[35mFor changes see the updated dist copy at #{agent_config_dist_path}\033[0m"
else
agent_config_path.write(default_config_file)
end
bin.install "buildkite-agent"
end
def default_config_file
File.read("buildkite-agent.cfg")
.gsub(/bootstrap-script=.+/, "bootstrap-script=\"#{agent_bootstrap_path}\"")
.gsub(/build-path=.+/, "build-path=\"#{agent_builds_path}\"")
.gsub(/hooks-path=.+/, "hooks-path=\"#{agent_hooks_path}\"")
.gsub(/plugins-path=.+/, "plugins-path=\"#{agent_plugins_path}\"")
end
def caveats
<<~EOS
\033[32mbuildkite-agent is now installed!\033[0m
\033[31mDon't forget to update your configuration file with your agent token\033[0m
Configuration file (to configure agent token, meta-data, priority, name, etc):
#{agent_config_path}
Hooks directory (for customising the agent):
#{agent_hooks_path}
Builds directory:
#{agent_builds_path}
Log paths:
#{var}/log/buildkite-agent.log
#{var}/log/buildkite-agent.error.log
If you set up the LaunchAgent, set your machine to auto-login as
your current user.
To prevent your machine from sleeping or logging out, use `caffeinate`. For
example, running `caffeinate -i buildkite-agent start` runs buildkite-agent
and prevents the system from idling until it exits. Run `man caffeinate` for
details.
To run multiple agents simply run the buildkite-agent start command
multiple times, or duplicate the LaunchAgent plist to create another
that starts on login.
EOS
end
service do
run [
HOMEBREW_PREFIX/"bin/buildkite-agent", "start",
"--config", etc/"buildkite-agent/buildkite-agent.cfg"
]
working_dir HOMEBREW_PREFIX/"bin" # Why?
keep_alive successful_exit: false
environment_variables PATH: HOMEBREW_PREFIX/"bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
process_type :interactive
log_path var/"log/buildkite-agent.log"
error_log_path var/"log/buildkite-agent.log"
end
test do
system "#{bin}/buildkite-agent", "--help"
end
end
<file_sep>/README.md
# Buildkite Homebrew Formulae
A collection of [Buildkite](https://buildkite.com/) formulae for [Homebrew](http://brew.sh), a package manager for macOS.
## How do I install these formulae?
`brew install buildkite/buildkite/<formula>`
Or `brew tap buildkite/buildkite` and then `brew install <formula>`.
## Available Formulae
- [`buildkite-agent`](https://github.com/buildkite/agent) (Please see [installation notes](#buildkite-agent))
- [Buildkite CLI](https://github.com/buildkite/cli)
- [`terminal-to-html`](https://github.com/buildkite/terminal-to-html)
### Notes for `buildkite-agent`
To install [`buildkite-agent`](https://github.com/buildkite/agent):
```bash
brew install buildkite/buildkite/buildkite-agent
```
You then need to configure your agent token, which you can find your agent token on your "Agents" page in Buildkite:
```bash
sed -i '' "s/xxx/INSERT-YOUR-AGENT-TOKEN-HERE/g" "$(brew --prefix)"/usr/local/etc/buildkite-agent/buildkite-agent.cfg
```
If you want it start on login follow the `brew install` instructions to install the LaunchAgent plist. You’ll also want to make sure your PC is set to automatically login (the agent won’t launch until you've logged in) and you’ve prevented your machine from going to sleep.
Using a LaunchAgent instead of a LaunchDaemon does require a user login, but it allows your tests to use GUI tools (such as the iOS Simulator) and avoids any file permissions problems.
You can upgrade the agent using these commands:
```bash
brew update && brew upgrade buildkite-agent
```
## For further information about Homebrew
`brew help`, `man brew` or check [Homebrew's documentation](https://docs.brew.sh).
<file_sep>/terminal-to-html.rb
class TerminalToHtml < Formula
desc "Converts arbitrary shell output (with ANSI) into beautifully rendered HTML"
homepage "https://github.com/buildkite/terminal-to-html"
version "3.6.1"
if Hardware::CPU.arm?
url "https://github.com/buildkite/terminal-to-html/releases/download/v3.6.1/terminal-to-html-3.6.1-darwin-arm64.gz"
sha256 "667d164e8dbc4f231f61892a23dac18ac7ca2b911d1b60e5b975b762b48e9718"
else
url "https://github.com/buildkite/terminal-to-html/releases/download/v3.6.1/terminal-to-html-3.6.1-darwin-amd64.gz"
sha256 "45275d2bdd1fa1e9ea730a55435ca4991cd8771d997d353a3d469aa25fcbffce"
end
def install
if Hardware::CPU.arm?
bin.install "terminal-to-html-#{version}-darwin-arm64" => "terminal-to-html"
else
bin.install "terminal-to-html-#{version}-darwin-amd64" => "terminal-to-html"
end
end
test do
system "#{bin}/terminal-to-html", "--help"
end
end
<file_sep>/buildkite-cli.rb
class BuildkiteCli < Formula
desc "A command-line tool for working with Buildkite"
homepage "https://github.com/buildkite/cli"
version "2.0.0"
if Hardware::CPU.arm?
url "https://github.com/buildkite/cli/releases/download/v2.0.0/cli-darwin-arm64"
sha256 "6685371f404b85ce278da138f8f89969da1825d9d4016c6907a3a5e1d118d330"
else
url "https://github.com/buildkite/cli/releases/download/v2.0.0/cli-darwin-amd64"
sha256 "34e387f5bf15c6435ec7f2ae0a844a609c9eb1b997c4790a57bb494f93a8f3fd"
end
def install
if Hardware::CPU.arm?
bin.install "cli-darwin-arm64" => "bk"
else
bin.install "cli-darwin-amd64" => "bk"
end
end
def caveats; <<~EOS
This is experimental! 🦄 🦑
For any questions, issues of feedback please file an issue: 💖
https://github.com/buildkite/cli/issues
EOS
end
test do
system "#{bin}/bk", "--help"
end
end
| d9860bfba35096f911cb2cbd3360a80bcb2f5dac | [
"Markdown",
"Ruby"
] | 4 | Ruby | buildkite/homebrew-buildkite | 723ac11583e9a7189e87cde08e11a54e78fa7834 | d31fae49b4fe6565160d3d66b22713bbcd108935 |
refs/heads/master | <repo_name>AKGM98/The-Student-Store<file_sep>/stdstrproject/views.py
from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect
from .models import Product
from.models import Product_laptop
from.models import Product_tablet
from.models import Product_uniform
from.models import Product_stationery
from.models import Cart
from.models import Pdf
from django.contrib.auth.models import User, auth
from django.urls import reverse
# Create your views here.
def index(request):
return render(request, 'index.html')
def book(request):
products = Product_uniform.objects.all()
params = {'product': products}
return render(request, 'book.html', params)
def uniform(request):
products = Product_uniform.objects.all()
params = {'product': products}
return render(request, 'uniform.html', params)
def tablet(request):
products = Product_uniform.objects.all()
params = {'product': products}
return render(request, 'tablet.html', params)
def pdf(request):
pdfs = Pdf.objects.all()
params = {'pdf': pdfs}
return render(request, 'pdf.html', params)
def laptop(request):
products = Product_uniform.objects.all()
params = {'product': products}
return render(request, 'laptop.html', params)
def stationery(request):
products = Product_uniform.objects.all()
params = {'product': products}
return render(request, 'stationery.html', params)
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['<PASSWORD>']
user = auth.authenticate(username=username,password=password)
if user is not None:
auth.login(request, user)
return redirect('/')
else:
print("no login")
return redirect('login')
else:
return render(request, 'login.html')
def registration(request):
if request.method == 'POST':
email = request.POST['email']
username = request.POST['username']
first_name = request.POST['first_name']
last_name = request.POST['last_name']
password1 = request.POST['<PASSWORD>']
password2 = request.POST['password2']
user = User.objects.create_user(first_name=first_name, last_name=last_name,username = username, password=<PASSWORD>, email=email )
user.save();
return redirect('/')
else:
return render(request, 'registration.html')
def cart(request):
cart = Cart.objects.all()[0]
params = { 'cart' : cart}
return render(request, 'cart.html', params)
def logout(request):
auth.logout(request)
return redirect('/')
def checkout(request):
return render(request,'checkout.html')
<file_sep>/stdstrproject/admin.py
from django.contrib import admin
# Register your models here.
from.models import Product
admin.site.register(Product)
from.models import Product_uniform
admin.site.register(Product_uniform)
from.models import Product_laptop
admin.site.register(Product_laptop)
from.models import Product_tablet
admin.site.register(Product_tablet)
from.models import Product_stationery
admin.site.register(Product_stationery)
from.models import Cart
admin.site.register(Cart)
from.models import Pdf
admin.site.register(Pdf)<file_sep>/stdstrproject/migrations/0015_pdf.py
# Generated by Django 2.2.14 on 2021-07-23 19:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('stdstrproject', '0014_auto_20210722_0016'),
]
operations = [
migrations.CreateModel(
name='Pdf',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('pdf_name', models.CharField(max_length=50)),
('pdf_file', models.FileField(default='', upload_to='ssproject/pdf')),
],
),
]
<file_sep>/stdstrproject/migrations/0002_remove_product_product_img.py
# Generated by Django 3.0.8 on 2021-07-10 17:35
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('stdstrproject', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='product',
name='product_img',
),
]
<file_sep>/stdstrproject/migrations/0006_product_laptop_product_stationery_product_tablet_product_uniform.py
# Generated by Django 3.0.8 on 2021-07-17 18:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('stdstrproject', '0005_auto_20210716_2231'),
]
operations = [
migrations.CreateModel(
name='Product_laptop',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('productl_image', models.ImageField(default='', upload_to='ssproject/images')),
('productl_name', models.CharField(max_length=20)),
('productl_price', models.IntegerField()),
('productl_desc', models.CharField(max_length=100)),
],
),
migrations.CreateModel(
name='Product_stationery',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('productst_image', models.ImageField(default='', upload_to='ssproject/images')),
('productst_name', models.CharField(max_length=20)),
('productst_price', models.IntegerField()),
('productst_desc', models.CharField(max_length=100)),
],
),
migrations.CreateModel(
name='Product_tablet',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('producttab_image', models.ImageField(default='', upload_to='ssproject/images')),
('producttab_name', models.CharField(max_length=20)),
('producttab_price', models.IntegerField()),
('producttab_desc', models.CharField(max_length=100)),
],
),
migrations.CreateModel(
name='Product_uniform',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('productu_image', models.ImageField(default='', upload_to='ssproject/images')),
('productu_name', models.CharField(max_length=20)),
('productu_price', models.IntegerField()),
('productu_desc', models.CharField(max_length=100)),
],
),
]
<file_sep>/stdstrproject/migrations/0011_product_uniform_product_name.py
# Generated by Django 3.0.8 on 2021-07-21 17:52
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('stdstrproject', '0010_auto_20210721_2309'),
]
operations = [
migrations.AddField(
model_name='product_uniform',
name='product_name',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='stdstrproject.Product'),
),
]
<file_sep>/stdstrproject/migrations/0009_auto_20210720_1507.py
# Generated by Django 3.0.8 on 2021-07-20 09:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('stdstrproject', '0008_auto_20210720_1456'),
]
operations = [
migrations.AlterField(
model_name='cart',
name='cart_item',
field=models.CharField(max_length=50, null='true'),
),
migrations.AlterField(
model_name='cart',
name='cart_price',
field=models.IntegerField(max_length=50, null='true'),
),
]
<file_sep>/stdstrproject/migrations/0010_auto_20210721_2309.py
# Generated by Django 3.0.8 on 2021-07-21 17:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('stdstrproject', '0009_auto_20210720_1507'),
]
operations = [
migrations.RemoveField(
model_name='cart',
name='cart_itemdesc',
),
migrations.RemoveField(
model_name='cart',
name='cart_item',
),
migrations.AddField(
model_name='cart',
name='cart_item',
field=models.ManyToManyField(null=True, to='stdstrproject.Product'),
),
]
<file_sep>/stdstrproject/migrations/0012_remove_product_uniform_product_name.py
# Generated by Django 3.0.8 on 2021-07-21 17:53
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('stdstrproject', '0011_product_uniform_product_name'),
]
operations = [
migrations.RemoveField(
model_name='product_uniform',
name='product_name',
),
]
<file_sep>/stdstrproject/migrations/0014_auto_20210722_0016.py
# Generated by Django 3.0.8 on 2021-07-21 18:46
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('stdstrproject', '0013_auto_20210722_0007'),
]
operations = [
migrations.RenameField(
model_name='cart',
old_name='cart_item',
new_name='productu_name',
),
]
<file_sep>/stdstrproject/migrations/0013_auto_20210722_0007.py
# Generated by Django 3.0.8 on 2021-07-21 18:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('stdstrproject', '0012_remove_product_uniform_product_name'),
]
operations = [
migrations.AlterField(
model_name='cart',
name='cart_item',
field=models.ManyToManyField(null=True, to='stdstrproject.Product_uniform'),
),
]
<file_sep>/stdstrproject/urls.py
"""stdstrproject URL Configuration"""
from django.contrib import admin
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path("", views.index, name="index"),
path("book", views.book, name="book"),
path("uniform", views.uniform, name="uniform"),
path("tablet", views.tablet, name="tablet"),
path("pdf", views.pdf, name="pdf"),
path("laptop", views.laptop, name="laptop"),
path("stationery", views.stationery, name="stationery"),
path("login", views.login, name="login"),
path("registration", views.registration, name="registration"),
path("cart", views.cart, name="cart"),
path("logout", views.logout, name="logout"),
path("checkout", views.checkout, name="checkout")
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
<file_sep>/stdstrproject/models.py
from django.db import models
# Create your models here.
class Product(models.Model):
product_image = models.ImageField(upload_to="ssproject/images", default="")
product_name = models.CharField(max_length=20)
product_price = models.IntegerField()
product_desc = models.CharField(max_length=100)
def __str__(self):
return self.product_name
class Product_uniform(models.Model):
productu_image = models.ImageField(upload_to="ssproject/images", default="")
productu_name = models.CharField(max_length=20)
productu_price = models.IntegerField()
productu_desc = models.CharField(max_length=100)
def __str__(self):
return self.productu_name
class Product_laptop(models.Model):
productl_image = models.ImageField(upload_to="ssproject/images", default="")
productl_name = models.CharField(max_length=20)
productl_price = models.IntegerField()
productl_desc = models.CharField(max_length=100)
def __str__(self):
return self.productl_name
class Product_tablet(models.Model):
producttab_image = models.ImageField(upload_to="ssproject/images", default="")
producttab_name = models.CharField(max_length=20)
producttab_price = models.IntegerField()
producttab_desc = models.CharField(max_length=100)
def __str__(self):
return self.producttab_name
class Product_stationery(models.Model):
productst_image = models.ImageField(upload_to="ssproject/images", default="")
productst_name = models.CharField(max_length=20)
productst_price = models.IntegerField()
productst_desc = models.CharField(max_length=100)
def __str__(self):
return self.productst_name
class Cart(models.Model):
productu_name = models.ManyToManyField(Product_uniform, null=True)
cart_price = models.IntegerField(max_length=50, null="true")
class Pdf(models.Model):
pdf_name = models.CharField(max_length=50)
pdf_file = models.FileField(upload_to="ssproject/pdf", default="")
<file_sep>/stdstrproject/migrations/0007_cart.py
# Generated by Django 3.0.8 on 2021-07-20 09:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('stdstrproject', '0006_product_laptop_product_stationery_product_tablet_product_uniform'),
]
operations = [
migrations.CreateModel(
name='Cart',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('cart_item', models.CharField(max_length=50)),
('cart_itemdesc', models.CharField(max_length=100)),
('cart_price', models.IntegerField(max_length=50)),
],
),
]
<file_sep>/stdstrproject/migrations/0004_auto_20210716_2223.py
# Generated by Django 3.0.8 on 2021-07-16 16:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('stdstrproject', '0003_product_product_image'),
]
operations = [
migrations.AlterField(
model_name='product',
name='product_image',
field=models.ImageField(default='', upload_to='static/images'),
),
]
<file_sep>/stdstrproject/migrations/0003_product_product_image.py
# Generated by Django 3.0.8 on 2021-07-16 16:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('stdstrproject', '0002_remove_product_product_img'),
]
operations = [
migrations.AddField(
model_name='product',
name='product_image',
field=models.ImageField(default='', max_length=255, upload_to=''),
),
]
<file_sep>/stdstrproject/apps.py
from django.apps import AppConfig
class StdstrprojectConfig(AppConfig):
name = 'stdstrproject'
| 9398ec9bdfd4de90ccaed719e13932c53c29186a | [
"Python"
] | 17 | Python | AKGM98/The-Student-Store | e0bcb388ee854dbcb0535239408fd2d3fe9687a1 | 45db3cbd9d760c0d3582970de2c953dae6cc33be |
refs/heads/master | <repo_name>alanzheng88/Algorithms<file_sep>/src/strings/StringAlgorithm.java
package strings;
import java.util.HashSet;
import java.util.Set;
import java.util.Arrays;
public class StringAlgorithm {
/*
* O(N) implementation with data structures
*/
public static boolean hasUniqueCharactersWithDs(String s) {
String[] splitted = s.split("");
Set<String> uniqueStrSet = new HashSet<>();
for (String ch : splitted) {
uniqueStrSet.add(ch);
}
return uniqueStrSet.size() == splitted.length;
}
/*
* O(N^2) implementation without data structures
*/
public static boolean hasUniqueCharactersWithoutDs(String s) {
for (int i = 0; i < s.length(); i++) {
for (int j = i + 1; j < s.length(); j++) {
if (s.charAt(i) == s.charAt(j)) {
return false;
}
}
}
return true;
}
/*
* O(N) implementation
*/
public static String reverseString(String s) {
int nullTerminatorIndex = -1;
String nullTerminator = "\0";
if (s.contains(nullTerminator)) {
nullTerminatorIndex = s.indexOf(nullTerminator);
}
String reversedString = "";
int index;
if (nullTerminatorIndex == -1) {
index = s.length() - 1;
while (index >= 0) {
reversedString += s.charAt(index);
index--;
}
} else {
index = nullTerminatorIndex - 1;
while (index >= 0) {
reversedString += s.charAt(index);
index--;
}
reversedString += "\0";
}
return reversedString;
}
/*
* O(N^2) implementation
*/
public static String removeDuplicateCharacters(String s) {
StringBuilder sb = new StringBuilder();
int i = 0;
for (i = 0; i < s.length(); i++) {
String ch = String.valueOf(s.charAt(i));
if (sb.indexOf(ch) == -1) {
sb.append(ch);
}
}
return sb.toString();
}
/*
* O(N) implementation
*/
public static boolean isAnagram(String a, String b) {
if (a.length() != b.length()) return false;
String aLowerCase = a.toLowerCase();
String bLowerCase = b.toLowerCase();
int[] aAlphabets = new int[26];
int[] bAlphabets = new int[26];
for (Character c : aLowerCase.toCharArray()) {
aAlphabets[(int)(c - 'a')]++;
}
for (Character c : bLowerCase.toCharArray()) {
bAlphabets[(int)(c - 'a')]++;
}
return Arrays.equals(aAlphabets, bAlphabets);
}
private static void permutation(String str, String prefix) {
if (str.length() == 0) {
System.out.println(prefix);
} else {
for (int i = 0; i < str.length(); i++) {
String rem = str.substring(0, i) + str.substring(i + 1);
permutation(rem, prefix + str.charAt(i));
}
}
}
public static void countPermutations(String str) {
permutation(str, "");
}
}
<file_sep>/test/arrays/ArrayAlgorithmFindMinElementTest.java
package arrays;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import arrays.ArrayAlgorithm;
public class ArrayAlgorithmFindMinElementTest {
@Before
public void setUp() throws Exception {
}
@Test
public void testOddNumberOfIntegerElements() throws Exception {
int[] elements = {5, 6, 7, 8, 9, 1, 2, 3, 4};
int result = ArrayAlgorithm.findMinElementFromSortedRotatedArray(elements);
assertEquals(1, result);
}
@Test
public void testOddNumberOfIntegerElementsOptimized() throws Exception {
int[] elements = {5, 6, 7, 8, 9, 1, 2, 3, 4};
int result = ArrayAlgorithm.findMinElementFromSortedRotatedArrayOptimized(elements);
assertEquals(1, result);
}
@Test
public void testEvenNumberOfIntegerElements() throws Exception {
int[] elements = {5, 6, 7, 8, 9, 10, 1, 2, 3, 4};
int result = ArrayAlgorithm.findMinElementFromSortedRotatedArray(elements);
assertEquals(1, result);
}
@Test
public void testEvenNumberOfIntegerElementsOptimized() throws Exception {
int[] elements = {5, 6, 7, 8, 9, 10, 1, 2, 3, 4};
int result = ArrayAlgorithm.findMinElementFromSortedRotatedArrayOptimized(elements);
assertEquals(1, result);
}
@Test(expected = Exception.class)
public void testNullArray() throws Exception {
int[] elements = null;
ArrayAlgorithm.findMinElementFromSortedRotatedArray(elements);
}
@Test(expected = Exception.class)
public void testNullArrayOptimized() throws Exception {
int[] elements = null;
ArrayAlgorithm.findMinElementFromSortedRotatedArrayOptimized(elements);
}
@Test
public void testArrayWithOddNumberOfIntegerElementsAndContainsOneNegativeElement() throws Exception {
int[] elements = {5, 6, 7, 8, 9, -1, 0, 1, 2, 3, 4};
int result = ArrayAlgorithm.findMinElementFromSortedRotatedArray(elements);
assertEquals(-1, result);
}
@Test
public void testArrayWithOddNumberOfIntegerElementsAndContainsOneNegativeElementOptimized() throws Exception {
int[] elements = {5, 6, 7, 8, 9, -1, 0, 1, 2, 3, 4};
int result = ArrayAlgorithm.findMinElementFromSortedRotatedArrayOptimized(elements);
assertEquals(-1, result);
}
@Test
public void testSortedAscendingIntegerElements() throws Exception {
int[] elements = {0, 1, 2, 3, 4, 5};
int result = ArrayAlgorithm.findMinElementFromSortedRotatedArray(elements);
assertEquals(0, result);
}
@Test
public void testSortedAscendingIntegerElementsOptimized() throws Exception {
int[] elements = {0, 1, 2, 3, 4, 5};
int result = ArrayAlgorithm.findMinElementFromSortedRotatedArrayOptimized(elements);
assertEquals(0, result);
}
@Test
public void testArrayWithOneElement() throws Exception {
int[] elements = {2};
int result = ArrayAlgorithm.findMinElementFromSortedRotatedArray(elements);
assertEquals(2, result);
}
@Test
public void testArrayWithOneElementOptimized() throws Exception {
int[] elements = {2};
int result = ArrayAlgorithm.findMinElementFromSortedRotatedArrayOptimized(elements);
assertEquals(2, result);
}
}
| 7e600a29b32320504acf320ba69642d8ef11a371 | [
"Java"
] | 2 | Java | alanzheng88/Algorithms | 7745d186e3ef5ecdfcbc573cfc5231afce3bd68a | 4a38957b0035e4cd7fc80b5ed88e545180ec58c8 |
refs/heads/master | <file_sep><?php
namespace Model;
use App;
class Order extends AModel implements IModel {
public function all() {
}
public function get($id, $admin = null) {
$fields = ["order_id", "order_date", "order_processing", "order_total", "order_currency", "order_total", "order_shipping", "order_subtotal",
"order_country", "order_state", "order_city", "order_postal_code", "order_line1", "order_line2"];
if ($admin) {
$fields = ["order_id", "order_payer_id", "order_processing"];
}
return App::$DATABASE->get("order", $fields, ["order_id" => $id]);
}
public function get_by_username($user_id, $id = null, $admin = null) {
if (!isset($id) || empty($id)) {
return App::$DATABASE->select("order", ["order_id", "order_date", "order_processing", "order_total", "order_currency", "order_total", "order_shipping", "order_subtotal",
"order_country", "order_state", "order_city", "order_postal_code", "order_line1", "order_line2"], ["ORDER" => ["order_date" => "DESC"], "order_user_id" => $user_id]);
} else {
$fields = ["order_id", "order_date", "order_processing", "order_total", "order_currency", "order_total", "order_shipping", "order_subtotal",
"order_country", "order_state", "order_city", "order_postal_code", "order_line1", "order_line2"];
if ($admin) {
$fields = ["order_id", "order_payer_id", "order_processing"];
}
return App::$DATABASE->get("order", $fields, ["AND" => ["order_id" => $id, "order_user_id" => $user_id]]);
}
}
public function get_order_items_by($user_id, $id) {
return App::$DATABASE->select("order_item", ["[>]order" => ["order_item_order_id" => "order_id"], "[>]products" => ["order_item_products_id" => "products_id"]], ["order_item_size", "order_item_quantity", "products_title", "products_src", "products_src_back"], ["AND" => ["order_item_order_id" => $id, "order_user_id" => $user_id]]);
}
public function remove($id) {
}
public function save($element) {
App::$DATABASE->insert("order", $element);
}
public function update_processing($id, $processing) {
App::$DATABASE->update("order", ["order_processing" => $processing], ["order_id" => $id]);
}
public function update($fields, $id) {
App::$DATABASE->update("order", $fields, ["order_id" => $id]);
}
}
<file_sep><?php
namespace Model;
use App;
use Model\User;
class Coupon extends AModel implements IModel {
public static $MIN_CLAIM = 5;
public function all() {
}
public function get($id) {
if (!isset($id)) {
return;
}
$where = ["AND" => ["coupon_id" => $id, "coupon_valid" => 1]];
$name = filter_input(INPUT_COOKIE, 'name');
if (isset($name) && !empty($name)) {
$user = new User();
$where["AND"]["coupon_user_id[!]"] = $user->get_current_user_id();
}
return App::$DATABASE->get('coupon', ["coupon_id", "coupon_discount", "coupon_type"], $where);
}
public function get_user_id($coupon) {
return App::$DATABASE->get('coupon', "coupon_user_id", ["coupon_id" => $coupon]);
}
public function get_by_user_id($id, $admin) {
$fields = ["coupon_id", "coupon_profit_total", "coupon_use", "coupon_payed"];
if ($admin === true) {
array_push($fields, "coupon_disabled");
}
$coupon = App::$DATABASE->get('coupon', $fields, ["coupon_user_id" => $id]);
$coupon['coupon_profit_total'] *= 0.95;
$coupon['coupon_payed'] *= 0.95;
return $coupon;
}
public function verify() {
$c = filter_input(INPUT_COOKIE, 'discount');
$json = json_decode($c);
if (isset($json) && isset($json->coupon_id)) {
return $this->get($json->coupon_id);
}
}
public function remove($id) {
}
public function save($element) {
}
public function update($id, $subtotal) {
$perc = App::$DATABASE->get('coupon', 'coupon_profit', ["coupon_id" => $id]);
$total = 0;
if ($perc) {
$total = round($perc / 100 * $subtotal, 2);
App::$DATABASE->update('coupon', ["coupon_use[+]" => "1", "coupon_profit_total[+]" => $total], ["coupon_id" => $id]);
}
return $total;
}
public function update_price($id, $price) {
App::$DATABASE->update('coupon', ["coupon_payed[+]" => $price], ["coupon_id" => $id]);
}
public function disable($id) {
App::$DATABASE->update('coupon', ["coupon_disabled" => 1], ["coupon_id" => $id]);
}
public function enable($id) {
App::$DATABASE->update('coupon', ["coupon_disabled" => 0], ["coupon_id" => $id]);
}
}
<file_sep><?php
namespace Model;
use App;
class ContactUs extends AModel implements IModel {
public function all() {
}
public function get($id) {
}
public function remove($id) {
}
public function save($element) {
return App::$DATABASE->insert('contact_us', $element);
}
}
<file_sep><?php
namespace Model;
use App;
class Claim extends AModel implements IModel {
public function all() {
}
public function get($id) {
return App::$DATABASE->get('claim', ['claim_id', 'claim_user_id', 'claim_price', 'claim_date', 'claim_currency'], ['claim_id' => $id]);
}
public function get_by_user_id($id) {
return App::$DATABASE->select('claim', ['claim_id', 'claim_user_id', 'claim_price', 'claim_date', 'claim_currency'], ['claim_user_id' => $id, "ORDER" => ['claim_date' => 'DESC']]);
}
public function remove($id) {
}
public function save($element) {
App::$DATABASE->insert('claim', $element);
}
}
<file_sep><?php
namespace Model;
use App;
use stdClass;
abstract class AModel {
public function __construct() {
App::initDatabase();
}
public function get_changed_properties($element, $skip = []) {
$model = new stdClass();
foreach ($element as $prop => $value) {
if (isset($value->changed) && $value->changed === true && !array_key_exists($prop, $skip)) {
$model->$prop = $this->sanitize_output($value->value);
}
}
return json_decode(json_encode($model), true);
}
private function sanitize_output($buffer) {
return preg_replace(array('/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s'), array('>', '<', '\\1'), $buffer);
}
public static function get_accepted_properties($array) {
$return = array();
for($i = 0; $i < count($array); $i++) {
$return[$array[$i]] = 0;
}
return $return;
}
}
interface IModel {
public function get($id);
public function all();
public function save($element);
public function remove($id);
}
<file_sep><?php
namespace Model;
use App;
use Exception;
class Payment {
private static $API_CONTEXT;
private static $API_CLIENT_TEST = '<KEY>';
private static $API_SECRET_TEST = '<KEY>';
private static $API_CLIENT = '<KEY>';
private static $API_SECRET = '<KEY>';
public static $URL = '';
public static $LOCALHOST = '';
private static $RETURN = '';
private static $DESCRIPTION = '';
private static $NAME = '';
public function __construct() {
require_once './PayPal-PHP-SDK/autoload.php';
if (App::is_localhost()) {
Payment::$API_CONTEXT = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(Payment::$API_CLIENT_TEST, Payment::$API_SECRET_TEST)
);
} else {
Payment::$API_CONTEXT = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(Payment::$API_CLIENT, Payment::$API_SECRET)
);
Payment::$API_CONTEXT->setConfig(['mode' => 'live']);
}
}
public function order($order, $id) {
if (Products::SHIPPING === false) {
//$experience_id = $this->get_experience_id();
}
return $this->order_link($order, $id, $experience_id);
}
public function get_experience_id() {
$flowConfig = new \PayPal\Api\FlowConfig();
$flowConfig->setLandingPageType("Billing");
$flowConfig->setBankTxnPendingUrl(Payment::$URL);
$flowConfig->setUserAction("commit");
$flowConfig->setReturnUriHttpMethod("GET");
$presentation = new \PayPal\Api\Presentation();
$presentation->setLogoImage("http://www.yeowza.com/favico.ico")->setBrandName(Payment::$NAME)->setLocaleCode("CA")->setReturnUrlLabel("Return")->setNoteToSellerLabel("Thanks!");
$inputFields = new \PayPal\Api\InputFields();
$inputFields->setNoShipping(1)->setAddressOverride(0);
$webProfile = new \PayPal\Api\WebProfile();
$webProfile->setName(Payment::$NAME . uniqid())->setFlowConfig($flowConfig)->setPresentation($presentation)->setInputFields($inputFields)->setTemporary(false);
try {
$createProfileResponse = $webProfile->create(Payment::$API_CONTEXT);
} catch (\PayPal\Exception\PayPalConnectionException $ex) {
App::response(400, "ERROR");
}
return $createProfileResponse->getId();
}
public function order_link($order, $id, $experience_profile_id = null) {
$payer = new \PayPal\Api\Payer();
$payer->setPaymentMethod("paypal");
$details = new \PayPal\Api\Details();
$amount = new \PayPal\Api\Amount();
$transaction = new \PayPal\Api\Transaction();
$redirectUrls = new \PayPal\Api\RedirectUrls();
$payment = new \PayPal\Api\Payment();
try {
$country = $this->country($order->shipping_zone);
$shipping = Products::SHIPPING === false ? 0 : $this->get_shipping($order, $country);
$totalwithshipping = Products::SHIPPING === false ? $order->total : $this->get_total_with_shipping($order, $country);
$details->setSubtotal($order->total)->setShipping($shipping);
$amount->setCurrency($order->currency['currency'])->setTotal($totalwithshipping)->setDetails($details);
$transaction->setAmount($amount)->setItemList($this->items($order))->setDescription(Payment::$DESCRIPTION)->setInvoiceNumber(uniqid() . "|" . $country . "|" . $id);
$redirectUrls->setReturnUrl(Payment::$RETURN . "?success=true")->setCancelUrl(Payment::$RETURN . "verify?success=false");
$payment->setIntent("order")->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction));
if(Products::SHIPPING === false) {
$payment->setExperienceProfileId('XP-PYBQ-EWLW-5SUE-TH3Z');
}
$payment->create(Payment::$API_CONTEXT);
return $payment->getApprovalLink();
} catch (Exception $ex) {
App::response(400, "ERROR");
}
}
private function get_total_with_shipping($order, $country_code) {
if (strtolower($country_code) === 'us') {
return $order->totalwithshipping['USA'];
} else if (strtolower($country_code) === 'ca') {
return $order->totalwithshipping['Canada'];
} else {
return $order->totalwithshipping['International'];
}
}
private function get_shipping($order, $country_code) {
if (strtolower($country_code) === 'us') {
return $order->shipping_price['USA'];
} else if (strtolower($country_code) === 'ca') {
return $order->shipping_price['Canada'];
} else {
return $order->shipping_price['International'];
}
}
private function country($shipping_zone) {
if (strtolower($shipping_zone) === 'usa') {
return 'us';
} else if (strtolower($shipping_zone) === 'canada') {
return 'ca';
} else {
return '';
}
}
private function items($order) {
$itemList = new \PayPal\Api\ItemList();
$itemArray = array();
foreach ($order->items as $element) {
$item = new \PayPal\Api\Item();
$item->setName($element['title'])->setCurrency($order->currency['currency'])->setQuantity($element['quantity'])->setPrice($element['price'])->setSku($element['id'] . '|' . $element['size']);
array_push($itemArray, $item);
}
if ($order->discount !== 0) {
$discount = new \PayPal\Api\Item();
$discount->setName('code: ' . $order->discount_code)->setCurrency($order->currency['currency'])->setQuantity(1)->setPrice(-$order->discount);
array_push($itemArray, $discount);
}
$itemList->setItems($itemArray);
return $itemList;
}
public function verify($id, $payer_id, $order_model) {
$payment = \PayPal\Api\Payment::get($id, Payment::$API_CONTEXT);
$order_model->update_processing($id, 2);
$execution = new \PayPal\Api\PaymentExecution();
$execution->setPayerId($payer_id);
try {
$payment->execute($execution, Payment::$API_CONTEXT);
$order_model->update_processing($id, 3);
$order = $payment->transactions[0]->related_resources[0]->order;
$amount = $payment->transactions[0]->getAmount();
return $this->capture($order, $amount->getCurrency(), $amount->getTotal(), $payment, $order_model, $id, $this->get_user_id($payment->transactions[0]->getInvoiceNumber()));
} catch (Exception $ex) {
$order_model->update_processing($id, 98);
App::response(400, "FAILED TO EXECUTE");
}
}
private function get_user_id($invoice) {
$result = explode('|', $invoice);
return $result[2] !== 0 ? $result[2] : null;
}
private function capture($order, $currency, $total, $payment, $order_model, $id, $user_id) {
$amount = new \PayPal\Api\Amount();
$amount->setCurrency($currency)->setTotal($total);
$captureDetails = new \PayPal\Api\Authorization();
$captureDetails->setAmount($amount);
try {
$result = $order->capture($captureDetails, Payment::$API_CONTEXT);
$order_model->update_processing($id, 4);
return $this->order_info($payment->transactions[0], $id, $order_model, $result, $user_id, $payment);
} catch (Exception $ex) {
$order_model->update_processing($id, 99);
App::response(400, "FAILED TO CAPTURE");
}
}
private function order_info($transaction, $id, $order_model, $result, $user_id, $payment) {
$payer_info = $payment->getPayer()->getPayerInfo();
$shipping_address = $transaction->getItemList()->getShippingAddress();
$amount = $transaction->getAmount();
$transaction_fee = $result->getTransactionFee();
$order = array(
"order_state" => Products::SHIPPING === false ? null : $shipping_address->getState(),
"order_country" => Products::SHIPPING === false ? null : $shipping_address->getCountryCode(),
"order_city" => Products::SHIPPING === false ? null : $shipping_address->getCity(),
"order_postal_code" => Products::SHIPPING === false ? null : $shipping_address->getPostalCode(),
"order_line1" => Products::SHIPPING === false ? null : $shipping_address->getLine1(),
"order_line2" => Products::SHIPPING === false ? null : $shipping_address->getLine2(),
"order_total" => $amount->getTotal(),
"order_shipping" => $amount->getDetails()->getShipping(),
"order_subtotal" => $amount->getDetails()->getSubtotal(),
"order_currency" => $amount->getCurrency(),
"order_email" => $payer_info->getEmail(),
"order_first_name" => $payer_info->getFirstName(),
"order_last_name" => $payer_info->getLastName()
);
if (isset($user_id)) {
$order["order_user_id"] = $user_id;
}
if (isset($transaction_fee)) {
$order["order_transaction_fee"] = $transaction_fee->getValue();
}
return array(
"items" => $transaction->getItemList()->getItems(),
"id" => $id,
"user_id" => $user_id,
"subtotal" => $amount->getDetails()->getSubtotal(),
"currency" => $amount->getCurrency(),
"order" => $order,
"order_model" => $order_model
);
}
public function pay_seller($params) {
$payouts = new \PayPal\Api\Payout();
$currency = new \PayPal\Api\Currency();
$currency->setCurrency($params["currency"])->setValue($params["amount"]);
$sender_batch_header = new \PayPal\Api\PayoutSenderBatchHeader();
$sender_batch_header->setSenderBatchId(uniqid())->setEmailSubject("You have a payment");
$sender_item = new \PayPal\Api\PayoutItem();
$sender_item->setRecipientType('Email')
->setNote('Thanks you.')
->setReceiver($params['email'])
->setAmount($currency);
$payouts->setSenderBatchHeader($sender_batch_header)->addItem($sender_item);
try {
$payouts->create(null, self::$API_CONTEXT);
return 1;
} catch (Exception $ex) {
return 0;
}
}
}
<file_sep><?php
session_start();
class App {
public static $DATABASE;
/** ==============================================================================================================================
* Initialize the database
*/
public static function initDatabase() {
if (!isset(App::$DATABASE) && isset(App::$PARAMETERS) && isset(App::$PARAMETERS['database'])) {
try {
$p = App::is_localhost() ? App::$PARAMETERS['database']['local'] : App::$PARAMETERS['database']['prop'];
App::$DATABASE = new medoo([
'database_type' => 'mysql',
'database_name' => $p['name'],
'server' => 'localhost',
'username' => $p['user'],
'password' => $p['<PASSWORD>'],
'charset' => 'utf8'
]);
} catch (Exception $e) {
echo "ERROR";
die();
}
}
}
private static $PARAMETERS;
/** ==============================================================================================================================
* Initialize the parameters of the framework, calls the controller and the function
* @param type $params array
*/
public function __construct($params) {
if (!isset(App::$PARAMETERS)) {
App::$PARAMETERS = $params;
}
if (isset(App::$PARAMETERS['cors']) && is_array(App::$PARAMETERS['cors']) && isset(App::$PARAMETERS['cors']['allow']) && is_string(App::$PARAMETERS['cors']['allow'])) {
$this->allow_cors();
}
if (isset(App::$PARAMETERS['error_reporting'])) {
error_reporting(App::$PARAMETERS['error_reporting']);
}
$this->request();
}
/** ==============================================================================================================================
* Replaces system getenv...
*/
public static function getenv($name) {
return $_SERVER[$name];
}
/** ==============================================================================================================================
* Alow CORS at the specified ip
*/
private function allow_cors() {
if (self::getenv('HTTP_ORIGIN') !== null) {
header("Access-Control-Allow-Origin: " . App::$PARAMETERS['cors']['allow']);
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400');
}
if (self::getenv('REQUEST_METHOD') == 'OPTIONS') {
if (self::getenv['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] !== null) {
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
}
if (self::getenv('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') !== null) {
header("Access-Control-Allow-Headers: " . self::getenv('HTTP_ACCESS_CONTROL_REQUEST_HEADERS'));
}
exit(0);
}
}
/** ==============================================================================================================================
* Returns if environment is localhost
*/
public static function is_localhost() {
return in_array(self::getenv('REMOTE_ADDR'), self::get_localhost_addresses());
}
/** ==============================================================================================================================
* Returns all localhost addresses
*/
public static function get_localhost_addresses() {
$local_ips = array('127.0.0.1', '::1');
if (isset(App::$PARAMETERS['mobile_testing_ips'])) {
$local_ips = array_merge($local_ips, App::$PARAMETERS['mobile_testing_ips']);
}
return $local_ips;
}
/** ==============================================================================================================================
* Parses and verifies the given request, and invoke the good controller and the good method
*/
private function request() {
$filter = strtolower(filter_input(INPUT_GET, 'query'));
$query = isset($filter) ? $filter : "";
if ($query == "") {
exit;
}
$params = ["controller" => ucfirst(strtolower(explode("/", $query)[0])), "function" => strtolower(explode("/", $query)[1])];
$controller_path = "Controllers/" . $params['controller'] . ".php";
if (file_exists($controller_path)) {
require_once $controller_path;
$controller = new ReflectionClass('\Controller\\' . $params['controller']);
$class = $controller->newInstance();
if (isset($params['function']) && $this->is_function_valid($params['function'], $class)) {
$this->invoke($class, $params, $controller);
} else {
http_response_code(400);
}
} else {
http_response_code(404);
}
}
/** ==============================================================================================================================
* Invoke the given request
*/
private function invoke($class, $params, $controller) {
ob_end_clean();
$method = new ReflectionMethod('\Controller\\' . $params['controller'], $params['function']);
if ($this->no_spamming($controller, $method) && $this->request_access($controller, $method) && $this->ajax($controller, $method)) {
if (App::$PARAMETERS['gzip'] === 1 && $this->get_params_from_doc_comments($method->getDocComment(), "nogzip") === false) {
ob_start("ob_gzhandler");
}
$method->invoke($class);
}
}
/** ==============================================================================================================================
* Verifies if function can be called not from an ajax request
*/
private function ajax($controller, $method) {
if ($this->get_params_from_doc_comments($controller->getDocComment(), "noajax") !== false || $this->get_params_from_doc_comments($method->getDocComment(), "noajax") !== false || !isset(App::$PARAMETERS['ajax_only']) || App::$PARAMETERS['ajax_only'] !== 1) {
return true;
}
$requested = self::getenv('HTTP_X_REQUESTED_WITH', true);
if (empty($requested) || strtolower($requested) !== 'xmlhttprequest') {
echo "NOT_AN_AJAX_REQUEST";
exit;
}
return true;
}
/** ==============================================================================================================================
* Verifies if a function can be invoked from a given controller (exists, public)
*/
private function is_function_valid($func, $class) {
if (!method_exists($class, $func)) {
return false;
}
$reflection = new ReflectionMethod($class, $func);
if (!$reflection->isPublic()) {
return false;
}
return true;
}
/** ==============================================================================================================================
* Request access to function if controller is admin
*/
private function request_access($controller, $method) {
$roles_c = $this->get_params_from_doc_comments($controller->getDocComment(), "roles");
$roles_m = $this->get_params_from_doc_comments($method->getDocComment(), "roles");
if (!$roles_c && !$roles_m) {
return true;
}
$roles = array();
if ($roles_c !== false) {
$roles = array_merge($roles, explode('|', $roles_c));
} if ($roles_m !== false) {
$roles = array_merge($roles, explode('|', $roles_m));
}
if (!(new \Model\User())->token(array_unique($roles))) {
self::response(401, 'LOCKED');
} else {
return true;
}
}
/** ==============================================================================================================================
* Finds value of specified parameter in comments of function or controller
*/
private function get_params_from_doc_comments($doc_comments, $params) {
$p = strrpos($doc_comments, "@" . $params);
if (!$p) {
return false;
}
$z = preg_replace('/\s+/', '', substr($doc_comments, $p + strlen("@" . $params)));
if ($z === "*/" || $z[0] === ',') {
return true;
}
$v = substr($doc_comments, $p + strlen("@" . $params . " "));
$c = str_split($v);
foreach ($c as $char) {
if (ctype_space($char)) {
break;
}
$value .= $char;
}
if (strrpos($value, ',')) {
$value = substr($value, 0, strrpos($value, ','));
}
if (strrpos($value, '*/')) {
$value = substr($value, 0, strrpos($value, '*/'));
}
return $value;
}
/** ==============================================================================================================================
* Prevents function spamming, user must wait at least x seconds
*/
private function no_spamming($controller, $func) {
$wait = $this->get_params_from_doc_comments($controller->getDocComment(), "nospamming");
if (!$wait) {
$wait = $this->get_params_from_doc_comments($func->getDocComment(), "nospamming");
}
if ($wait === true || $wait === 'false') {
return true;
}
if (is_bool($wait) || !is_int((int) $wait)) {
$wait = isset(App::$PARAMETERS['spamming']) && is_int(App::$PARAMETERS['spamming']) ? App::$PARAMETERS['spamming'] : 1;
}
if ($this->no_spamming_sesson($func, $wait)) {
return true;
} else {
echo "NOSPAMMING";
exit;
}
}
/** ==============================================================================================================================
* Verifies if user waited x seconds before requesting function
*/
private function no_spamming_sesson($func, $wait) {
if (!isset($_SESSION['func'])) {
$_SESSION['func'] = [];
}
if (!isset($_SESSION['func'][$func->getName()])) {
$_SESSION['func'][$func->getName()] = time();
return true;
}
if (time() - $_SESSION['func'][$func->getName()] < $wait) {
$_SESSION['func'][$func->getName()] = time();
return false;
} else {
$_SESSION['func'][$func->getName()] = time();
return true;
}
}
/** ==============================================================================================================================
* Returns the client ip address
*/
public static function get_client_ip() {
$ipaddress = '';
if (self::getenv('HTTP_CLIENT_IP')) {
$ipaddress = self::getenv('HTTP_CLIENT_IP');
} else if (self::getenv('HTTP_X_FORWARDED_FOR')) {
$ipaddress = self::getenv('HTTP_X_FORWARDED_FOR');
} else if (self::getenv('HTTP_X_FORWARDED')) {
$ipaddress = self::getenv('HTTP_X_FORWARDED');
} else if (self::getenv('HTTP_FORWARDED_FOR')) {
$ipaddress = self::getenv('HTTP_FORWARDED_FOR');
} else if (self::getenv('HTTP_FORWARDED')) {
$ipaddress = self::getenv('HTTP_FORWARDED');
} else if (self::getenv('REMOTE_ADDR')) {
$ipaddress = self::getenv('REMOTE_ADDR');
} else {
$ipaddress = 'UNKNOWN';
}
if (in_array($ipaddress, self::get_localhost_addresses())) {
return '192.168.127.12'; // RUSSIA 109.172.27.14, ZIMBABWE 172.16.17.32, CANADA 192.168.127.12, USA 192.168.127.12
}
return $ipaddress;
}
/** ==============================================================================================================================
* Returns a uuid
*/
public static function uuid() {
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000, mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff));
}
/** ==============================================================================================================================
* Sets a cookie
*/
public static function set_cookie($name, $value, $time) {
setrawcookie($name, rawurlencode($value), $time, "/", "", false, false);
}
/** ==============================================================================================================================
* Search backwards starting from haystack length characters from the end
*/
public static function starts_with($haystack, $needle) {
return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== false;
}
/** ==============================================================================================================================
* Returns a response
*/
public static function response($code, $response) {
echo json_encode(array('code' => $code, 'response' => $response));
exit;
}
}
spl_autoload_register(function ($class_name) {
$include = $class_name;
if (App::starts_with(strtolower($class_name), 'model')) {
$include = str_replace("Model", "Models", $class_name);
if ($class_name === 'Model\AModel') {
include_once './Models/Model.php';
return;
}
}
if (App::starts_with(strtolower($class_name), 'utils') || App::starts_with(strtolower($class_name), 'validate')) {
include './utils.php';
}
$include = './' . str_replace("\\", "/", $include) . '.php';
include $include;
});<file_sep><?php
namespace Model;
use App;
class User extends AModel implements IModel {
private $roles = ["user" => 1, "client" => 1, "seller" => 1];
private $MAX_ATTEMPS = 10;
/** ==============================================================================================================================
* Verifies user authentication. Verifies if user is logged in, if ip is same, if user have needed roles
*/
public function token($roles) {
$params = ["uuid" => filter_input(INPUT_COOKIE, "uuid"), "name" => filter_input(INPUT_COOKIE, "name"), "token" => filter_input(INPUT_COOKIE, "token")];
$fields = $this->verify_roles($roles, array());
if (isset($params["uuid"]) && isset($params["name"]) && isset($params["token"])) {
$user = App::$DATABASE->get("user_device", ["[>]user" => ["user_device_id" => "user_id"]], $fields, [
"AND" => [
"user_device_uuid" => $params["uuid"], "user_name" => $params["name"], "user_device_token" => $params["token"], "user_device_ip" => App::get_client_ip()
]
]);
if (!$user) {
return false;
}
foreach ($user as $key) {
if ($key !== "1") {
return false;
}
}
return true;
} else {
return false;
}
}
/** ==============================================================================================================================
* Get current user specified fields
*/
public function get_current_user_fields($fields) {
$params = ["uuid" => filter_input(INPUT_COOKIE, "uuid"), "name" => filter_input(INPUT_COOKIE, "name"), "token" => filter_input(INPUT_COOKIE, "token")];
return App::$DATABASE->get("user_device", ["[>]user" => ["user_device_id" => "user_id"]], $fields, [
"AND" => [
"user_device_uuid" => $params["uuid"], "user_name" => $params["name"], "user_device_token" => $params["token"], "user_device_ip" => App::get_client_ip()
]
]);
}
/** ==============================================================================================================================
* Verifies the current user password
*/
public function verify_password($pass) {
$hash = App::$DATABASE->get("user", "user_password", ["user_name" => filter_input(INPUT_COOKIE, "name")]);
return password_verify($pass, $hash);
}
/** ==============================================================================================================================
* Verifies user authentication. Verifies if user is logged in, if ip is same and returns roles
*/
public function token2($return = null) {
$params = ["uuid" => filter_input(INPUT_COOKIE, "uuid"), "name" => filter_input(INPUT_COOKIE, "name"), "token" => filter_input(INPUT_COOKIE, "token")];
$fields = $this->get_roles_fields();
$user = App::$DATABASE->get("user_device", ["[>]user" => ["user_device_id" => "user_id"]], $fields, [
"AND" => [
"user_device_uuid" => $params["uuid"], "user_name" => $params["name"], "user_device_token" => $params["token"], "user_device_ip" => App::get_client_ip()
]
]);
$result = $user ? $user : 'NOT FOUND';
if (!isset($return)) {
App::response($user ? 200 : 400, $result);
} else {
return $result;
}
}
public function is_logged_in() {
return $this->token2(true) !== 'NOT FOUND' ? true : false;
}
/** ==============================================================================================================================
* Gets all roles fields
*/
private function get_roles_fields() {
$fields = array();
foreach ($this->roles as $key => $value) {
array_push($fields, "user_role_" . $key);
}
return $fields;
}
/** ==============================================================================================================================
* Only get roles
*/
private function only_get_roles($hash) {
foreach ($hash as $key => $value) {
if (!App::starts_with($key, 'user_role_')) {
unset($hash[$key]);
}
}
return $hash;
}
/** ==============================================================================================================================
* Verifies if all roles are valid
*/
private function verify_roles($roles, $fields) {
if ($roles[0] === "1") {
echo "NO ROLES SPECIFIED";
exit;
}
foreach ($roles as $role) {
if (!array_key_exists($role, $this->roles)) {
echo "ROLE " . $role . " DOES NOT EXIST";
exit;
} else {
array_push($fields, "user_role_" . $role);
}
}
return $fields;
}
/** ==============================================================================================================================
* Verifies LOGIN information
*/
public function verify($data) {
if (!isset($data) || !isset($data->name) || !isset($data->uuid) || !isset($data->pass)) {
App::response(400, 'NOT_FOUND');
}
$hash = App::$DATABASE->get("user", array_merge(["user_id", "user_name", "user_password", "user_wrong_pass"], $this->get_roles_fields()), ["user_name" => $data->name]);
if ($this->verify_pass_and_attemps($hash, $data->pass)) {
$token = App::uuid();
if (App::$DATABASE->get("user_device", "user_device_uuid", ["AND" => ["user_device_uuid" => $data->uuid]])) {
App::$DATABASE->update("user_device", ["user_device_token" => $token, "user_device_ip" => App::get_client_ip(), "user_device_id" => $hash['user_id']], ["user_device_uuid" => $data->uuid]);
} else {
App::$DATABASE->insert('user_device', ['user_device_uuid' => $data->uuid, 'user_device_id' => $hash['user_id'], 'user_device_token' => $token, "user_device_ip" => App::get_client_ip()]);
}
App::set_cookie('name', $data->name, time() + 3600 * 24 * 365);
App::set_cookie('token', $token, time() + 3600 * 24 * 365);
App::response(200, $this->only_get_roles($hash));
}
}
/** ==============================================================================================================================
* Returns shipping address
*/
public function shipping_address($shipping_address = null) {
if (isset($shipping_address)) {
return array(
'user_state' => $shipping_address->state,
'user_country' => $shipping_address->country,
'user_city' => $shipping_address->city,
'user_postal_code' => $shipping_address->postal_code,
'user_line1' => $shipping_address->line1,
'user_line2' => $shipping_address->line2,
'user_formatted' => $shipping_address->formatted,
);
} else {
$name = filter_input(INPUT_COOKIE, 'name');
if (!isset($name) || empty($name)) {
return [];
}
return App::$DATABASE->get("user", ['user_state', 'user_country', 'user_city', 'user_postal_code', 'user_line1', 'user_line2', 'user_formatted'], ['user_name' => $name]);
}
}
/** ==============================================================================================================================
* Verifies number of attempts before lockdown
*/
private function verify_pass_and_attemps($hash, $pass) {
if ($hash && $hash["user_wrong_pass"] >= $this->MAX_ATTEMPS) {
App::response(401, 'UNAUTHORIZED');
} else if ($hash && password_verify($pass, $hash["user_password"])) {
if ($hash["user_wrong_pass"] > 0) {
App::$DATABASE->update("user", ["user_wrong_pass" => 0], ["user_name" => $hash["user_name"]]);
}
return true;
} else {
if ($hash) {
$wrong_pass = $hash["user_wrong_pass"] + 1;
App::$DATABASE->update("user", ["user_wrong_pass" => $wrong_pass], ["user_name" => $hash["user_name"]]);
}
App::response(400, 'BAD EMAIL OR PASSWORD');
}
}
/** ==============================================================================================================================
* Saves a user
*/
public function save($element) {
$exists = $this->exists($element->user_name);
if (!isset($element->user_id) && $exists) {
App::response(400, 'USER ALREADY EXISTS');
}
if (!isset($element->user_id)) {
$pass = $element->user_retype_password;
unset($element->user_retype_password);
App::$DATABASE->insert("user", (array) $element);
$this->verify((object) array('name' => $element->user_name, 'pass' => $pass, 'uuid' => filter_input(INPUT_COOKIE, 'uuid')));
}
}
/** ==============================================================================================================================
* Updates a user
*/
public function update($element) {
return App::$DATABASE->update("user", (array) $element, ["user_id" => $this->get_current_user_id()]);
}
/** ==============================================================================================================================
* Determines if user exists
*/
public function exists($user_name) {
return App::$DATABASE->get("user", "user_first_name", ["user_name" => $user_name]);
}
/** ==============================================================================================================================
* Change roles of element
*/
public function roles(&$element, $roles) {
$fields = $this->get_roles_fields();
foreach ($fields as $field) {
$element->$field = 0;
foreach ($roles as $role) {
if ($field === 'user_role_' . $role) {
$element->$field = 1;
}
}
}
}
/** ==============================================================================================================================
* Change password of user to a random one
*/
public function change_password($id) {
$name = App::$DATABASE->get("user", "user_first_name", ["user_name" => $id]);
if ($name) {
$p = $this->random_str(20);
return array("result" => App::$DATABASE->update("user", ["user_password" => password_hash($p, PASSWORD_DEFAULT), "user_wrong_pass" => 0], ["user_name" => $id]), "password" => $p, "name" => $name);
} else {
return array("result" => 0);
}
}
/** ==============================================================================================================================
* generates random string
*/
private function random_str($length, $keyspace = '<KEY>') {
$str = '';
$max = mb_strlen($keyspace, '8bit') - 1;
if ($max < 1) {
throw new Exception('$keyspace must be at least two characters long');
}
for ($i = 0; $i < $length; ++$i) {
$str .= $keyspace[rand(0, $max)];
}
return $str;
}
/** ==============================================================================================================================
* gets current user info
*/
public function get_current_user_info() {
return App::$DATABASE->get("user", ["user_name", "user_first_name", "user_last_name", "user_phone_number", "user_state", "user_country",
"user_city", "user_postal_code", "user_line1", "user_line2", "user_formatted"], ["user_name" => $this->get_current_user_name()]);
}
/** ==============================================================================================================================
* gets current user country
*/
public function get_current_user_country() {
return App::$DATABASE->get("user", "user_country", ["user_name" => filter_input(INPUT_COOKIE, 'name')]);
}
private function get_current_user_name() {
$name = filter_input(INPUT_COOKIE, 'name');
if (!isset($name) || empty($name)) {
App::response(400, 'NO NAME');
}
return $name;
}
public function get_current_user_id($exit = true) {
$user_name = filter_input(INPUT_COOKIE, 'name');
if ($exit) {
$user_name = $this->get_current_user_name();
}
return (int) App::$DATABASE->get("user", "user_id", ['user_name' => $user_name]);
}
public function all() {
}
public function get($id) {
}
public function remove($id) {
}
}
<file_sep><?php
namespace Model;
use App;
class OrderItem extends AModel implements IModel {
public function all() {
}
public function get($id) {
}
public function remove($id) {
}
public function save($element) {
App::$DATABASE->insert("order_item", $element);
}
}
<file_sep><?php
namespace Model;
use App;
use Model\User;
class Currency {
const DEFAULT_CURRENCY = 'CAD';
public static function get() {
return Currency::get_rate(Currency::get_currency());
}
/** ==============================================================================================================================
* Verifies if currency rate needs an update
* @param type $cu
* @return type
*/
private static function get_rate($cu) {
if (isset($_SESSION['currency_rate']) && isset($_SESSION['currency_rate_date']) && $_SESSION['currency_rate_date'] < (time() + 3600 / 2) && $_SESSION['currency_rate_currency'] === $cu) {
App::set_cookie('currency_rate', $_SESSION['currency_rate'], 0);
} else {
$_SESSION['currency_rate_currency'] = $cu;
if (strtolower($cu) === strtolower(Currency::DEFAULT_CURRENCY)) {
Currency::set_rate(1);
return;
}
Currency::get_new_rate($cu);
}
return ["currency" => $cu, "rate" => $_SESSION['currency_rate']];
}
/** ==============================================================================================================================
* Gets the default rate from yahoo finance api
* @param type $cu
*/
public static function get_default_rate($cu) {
$ch = curl_init('http://download.finance.yahoo.com/d/quotes.csv?s=' . $cu . Currency::DEFAULT_CURRENCY . '=X&f=l1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, getenv("HTTP_USER_AGENT"));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$rt = curl_exec($ch);
curl_close($ch);
return floatval($rt);
}
/** ==============================================================================================================================
* Gets new currency rate from yahoo finance api
* @param type $cu
*/
public static function get_new_rate($cu, $return = null) {
$ch = curl_init('https://api.fixer.io/latest?base=' . Currency::DEFAULT_CURRENCY . '&symbols=' . $cu);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$result = json_decode(curl_exec($ch));
$rt = $result->rates->$cu;
if ($return !== true) {
Currency::set_rate(floatval($rt));
} else {
return floatval($rt);
}
curl_close($ch);
}
/** ==============================================================================================================================
* Returns the currency based on ip address of the client
* @return type
*/
private static function get_currency() {
if (filter_input(INPUT_COOKIE, 'currency') !== null && filter_input(INPUT_COOKIE, 'shipping_zone') !== null) {
return filter_input(INPUT_COOKIE, 'currency');
}
$ch = curl_init('http://www.geoplugin.net/php.gp?ip=' . App::get_client_ip());
$rt = '';
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if (($rt = curl_exec($ch)) === false) {
echo "ERROR";
curl_close($ch);
exit;
} else {
$un = unserialize($rt);
$rt = array_key_exists($un['geoplugin_currencyCode'], Currency::get_accepted_currencies()) ? $un['geoplugin_currencyCode'] : Currency::DEFAULT_CURRENCY;
setcookie('currency', $rt, time() + 3600 * 24 * 365, "/", "", false, false);
$zn = Store::get_shipping_zone_from_country($un['geoplugin_countryCode']);
setcookie('shipping_zone', $zn, time() + 3600 * 24 * 365, "/", "", false, false);
curl_close($ch);
}
return $rt;
}
/** ==============================================================================================================================
* Sets the currency rate
* @param type $rt
*/
private static function set_rate($rt) {
$_SESSION['currency_rate'] = $rt;
$_SESSION['currency_rate_date'] = time();
App::set_cookie('currency_rate', $rt, 0);
}
/** ==============================================================================================================================
* Returns an array of accepted currency symbols
* @return type
*/
private static function get_accepted_currencies() {
return [
"USD" => true, "CAD" => true, "GBP" => true, "EUR" => true, "AUD" => true,
"JPY" => true, "RUB" => true, "HKD" => true, "CHF" => true
];
}
}
<file_sep><?php
namespace Model;
use App;
class Products extends AModel implements IModel {
const SHIPPING = false;
public function all() {
return App::$DATABASE->select('products', [
"products_id", "products_title", "products_price", "products_src", "products_price_discount", "products_sold_out", "products_small",
"products_medium", "products_large", "products_xlarge", "products_x2large", "products_x3large", "products_x4large", "products_x5large"
], ["ORDER" => ["products_id" => "ASC"], "products_show" => 1]);
}
public function get($id) {
return App::$DATABASE->get('products', [
"products_id", "products_title", "products_price", "products_price_discount", "products_src", "products_src_angle", "products_src_back",
"products_desc", "products_sold_out", "products_type", "products_small", "products_medium",
"products_large", "products_xlarge", "products_x2large", "products_x3large",
"products_x4large", "products_x5large"
], ["AND" => ["products_id" => $id, "products_show" => 1]]);
}
public function order($currency_info, $coupon, $shipping_address) {
$cart = json_decode(filter_input(INPUT_COOKIE, 'cart'));
$order = (object) array('currency' => $currency_info, 'items' => array(), 'subtotal' => 0, 'max' => ["p" => 0], 'discount' => 0, 'discount_code' => '', 'total' => 0, 'shipping' => array(), 'shipping_price' => array('USA' => 0, 'Canada' => 0, 'International' => 0), 'shipping_address' => $shipping_address, 'totalwithshipping' => 0);
foreach ($cart as $id => $element) {
foreach ($element as $size => $qty) {
$s = $this->get_field_from_size($size);
if (!isset($s)) {
continue;
}
$this->get_order_item($id, $s, $size, $qty, $order);
}
}
if (isset($coupon) && isset($coupon['coupon_discount'])) {
$type = (int) $coupon['coupon_type'] === 0 ? $order->subtotal : $order->max["p"];
$order->discount = round($type * 100 * ($coupon['coupon_discount'] / 100) / 100, 2);
$order->discount_code = $coupon['coupon_id'];
$order->total = $order->subtotal - $order->discount;
} else {
$order->total = $order->subtotal;
}
if (Products::SHIPPING === false) {
unset($order->shipping_price);
unset($order->totalwithshipping);
$order->shipping = false;
}
return $this->get_total_with_shipping($order);
}
private function get_shipping(&$order) {
$shipping = Store::shipping();
$order->shipping_zone = filter_input(INPUT_COOKIE, 'shipping_zone');
if ($order->shipping_zone !== 'USA' && $order->shipping_zone !== 'Canada' && $order->shipping_zone !== 'International') {
$order->shipping_zone = 'International';
}
$order->shipping_price['USA'] += $shipping[$order->max["t"]]['USA']['first_item_price'];
$order->shipping_price['Canada'] += $shipping[$order->max["t"]]['Canada']['first_item_price'];
$order->shipping_price['International'] += $shipping[$order->max["t"]]['International']['first_item_price'];
$order->shipping[$order->max["t"]] --;
foreach ($order->shipping as $key => $value) {
if ($value > 0) {
$order->shipping_price['USA'] += $shipping[$key]['USA']['additional_item_price'] * $value;
$order->shipping_price['Canada'] += $shipping[$key]['Canada']['additional_item_price'] * $value;
$order->shipping_price['International'] += $shipping[$key]['International']['additional_item_price'] * $value;
}
}
$order->shipping_price['USA'] = round($order->shipping_price['USA'] * 100 * $order->currency["rate"] / 100, 2);
$order->shipping_price['Canada'] = round($order->shipping_price['Canada'] * 100 * $order->currency["rate"] / 100, 2);
$order->shipping_price['International'] = round($order->shipping_price['International'] * 100 * $order->currency["rate"] / 100, 2);
}
private function get_total_with_shipping(&$order) {
if (Products::SHIPPING === true) {
$this->get_shipping($order);
$order->totalwithshipping = array(
'USA' => $order->shipping_price['USA'] + $order->total,
'Canada' => $order->shipping_price['Canada'] + $order->total,
'International' => $order->shipping_price['International'] + $order->total);
}
return $order;
}
private function get_order_item($id, $size_field, $size, $qty, &$order) {
$re = App::$DATABASE->get('products', [
"products_title", "products_price", "products_price_discount", "products_type", "products_id"
], ["AND" => ["products_id" => $id, "products_show" => 1, "products_sold_out" => 0, $size_field => 1]]);
if ($re) {
$price = round((isset($re["products_price_discount"]) ? $re["products_price_discount"] : $re["products_price"]) * 100 * $order->currency["rate"] / 100, 2);
if ($order->max["p"] < $price) {
$order->max["p"] = $price;
$order->max["t"] = $re['products_type'];
}
if (!array_key_exists($re['products_type'], $order->shipping)) {
$order->shipping[$re['products_type']] = $qty;
} else {
$order->shipping[$re['products_type']] += $qty;
}
array_push($order->items, ["title" => $re['products_title'], "price" => $price, "quantity" => $qty, "total_price" => $price * $qty, "size" => $size, "id" => $re['products_id']]);
$order->subtotal += $price * $qty;
}
}
public function cart() {
$cart = json_decode(filter_input(INPUT_COOKIE, 'cart'));
if (!isset($cart)) {
return array();
}
$return = (object) ["cart" => array(), "not_avalaible" => 0, "shipping" => Products::SHIPPING !== false ? Store::shipping() : false];
foreach ($cart as $id => $element) {
foreach ($element as $size => $qty) {
$size_field = $this->get_field_from_size($size);
if (!isset($size_field)) {
continue;
}
$this->get_return_cart_element($return, $cart, $qty, $size, $size_field, $id);
}
}
$return->cookie_cart = $cart;
return $return;
}
private function get_return_cart_element(&$return, &$cart, $qty, $size, $size_field, $id) {
$element = App::$DATABASE->get('products', [
"products_id", "products_title", "products_price", "products_price_discount", "products_src", "products_type"
], ["AND" => ["products_id" => $id, "products_show" => 1, "products_sold_out" => 0, $size_field => 1]]);
if ($element) {
$element["products_qty"] = $qty;
$element["products_size"] = $size;
array_push($return->cart, $element);
} else {
$return->not_avalaible++;
if (count(get_object_vars($cart->$id)) > 1) {
unset($cart->$id->$size);
} else {
unset($cart->$id);
}
}
}
private function get_field_from_size($size) {
switch ($size) {
case "small":
return "products_small";
case "medium":
return "products_medium";
case "large":
return "products_large";
case "x-large":
return "products_xlarge";
case "x2-large":
return "products_x2large";
case "x3-large":
return "products_x3large";
case "x4-large":
return "products_x4large";
case "x5-large":
return "products_x5large";
default:
return null;
}
}
public function remove($id) {
}
public function save($element) {
}
}
<file_sep><?php
namespace Model;
use App;
class Stats extends AModel implements IModel {
public function all() {
}
public function get($id) {
}
public function remove($id) {
}
public function save($element) {
$stats_ids = ["all" => "-", "year" => date("Y"), "month" => date("Y-m"), "day" => date("Y-m-d")];
$exists_ids = [];
$stats = App::$DATABASE->select("stats", "stats_id", ["stats_id" =>
[$stats_ids["all"], $stats_ids["year"], $stats_ids["month"], $stats_ids["day"]]
]);
for ($i = 0; $i < sizeof($stats); $i++) {
$exists_ids[$stats[$i]] = true;
}
$update = [];
$insert = [];
foreach ($stats_ids as $key => $value) {
if (array_key_exists($value, $exists_ids)) {
array_push($update, $value);
} else {
array_push($insert, $value);
}
}
if (sizeof($update) > 0) {
$update_element = $element;
foreach ($update_element as $key => $value) {
$update_element[$key . '[+]'] = $value;
unset($update_element[$key]);
}
App::$DATABASE->update("stats", $update_element, ["stats_id" => $update]);
}
if (sizeof($insert) > 0) {
$insert_elements = [];
for ($i = 0; $i < sizeof($insert); $i++) {
$element["stats_id"] = $insert[$i];
array_push($insert_elements, $element);
}
App::$DATABASE->insert("stats", $insert_elements);
}
}
}
<file_sep><?php
namespace Controller;
use App;
use Model\User;
use Model\Payment;
use Model\Currency;
use Model\Coupon;
use Model\Products;
use Model\Order;
use Model\OrderItem;
use Model\Stats;
use Model\Store;
use Model\ContactUs;
use Model\Claim;
use utils\Validate;
use utils\UTILS;
class eCommerce {
/** ==============================================================================================================================
* Sends the order to PAYPAL
*/
public function checkout() {
$order = $this->price(true);
$user = new User();
if (count($order->items) === 0) {
App::response(400, "NO ITEMS");
}
App::response(200, (new Payment())->order($order, $user->get_current_user_id(false)));
}
/** ==============================================================================================================================
* Returns final price before checkout on PAYPAL
*/
public function before_checkout() {
App::response(200, $this->price(true));
}
/** ==============================================================================================================================
* Returns cart information (items, prices, address)
*/
private function price($with_shipping = null, $new_coupon = null) {
$currency_info = Currency::get();
$coupon_cookie = !isset($new_coupon) ? json_decode(filter_input(INPUT_COOKIE, 'discount')) : (object) $new_coupon;
if (isset($coupon_cookie->coupon_id)) {
$coupon_model = new Coupon();
$coupon = $coupon_model->get($coupon_cookie->coupon_id);
}
if (!isset($with_shipping)) {
return (new Products())->order($currency_info, $coupon);
} else {
$shipping = json_decode(filter_input(INPUT_GET, 'shipping'));
$shipping_address = (new User())->shipping_address($shipping);
return (new Products())->order($currency_info, $coupon, $shipping_address);
}
}
/** ==============================================================================================================================
* Verifies the PAYPAL order
*/
public function process() {
$id = filter_input(INPUT_GET, 'processing_id');
if (!isset($id) || empty($id)) {
App::response(400, 'NO PROCESSING_ID');
}
$order_model = new Order();
if (!($order = $order_model->get($id, true)) || $order['order_processing']) {
App::response(400, 'ERROR');
}
$order_model->update_processing($id, 1);
$payment_model = new Payment();
$result = $payment_model->verify($order['order_id'], $order['order_payer_id'], $order_model);
$this->process_items($result);
echo App::response(200, $order_model->get($id));
}
public function order() {
$id = filter_input(INPUT_GET, 'id');
if (!isset($id) || empty($id)) {
App::response(400, 'NO ORDER_ID');
}
$order = new Order();
$result = $order->get('PAY-' . $id);
App::response($result ? 200 : 400, $result ? $result : 'NOT_FOUND');
}
/** ==============================================================================================================================
* Process the items returned by PAYPAL
*/
private function process_items($result) {
$orderitem_model = new OrderItem();
$coupon = null;
$coupon_price = null;
$coupon_discount = 0;
foreach ($result['items'] as $value) {
$name = $value->getName();
if (App::starts_with($name, 'code:')) {
$coupon = trim(substr($name, 6, strlen($name)));
$coupon_price = $value->getPrice();
} else {
$parts = explode("|", $value->getSku());
$orderitem_model->save(["order_item_order_id" => $result['id'], "order_item_products_id" => $parts[0], "order_item_quantity" => $value->getQuantity(), "order_item_size" => $parts[1]]);
}
}
$rate = Currency::get_default_rate($result['currency']);
if (isset($coupon)) {
$coupon_model = new Coupon();
$coupon_discount = $coupon_model->update($coupon, ($result['subtotal'] - $coupon_price) * $rate);
$result['order']['order_seller_id'] = $coupon_model->get_user_id($coupon);
}
$result['order']['order_total_default'] = round($result['order']['order_total'] * $rate, 2);
$result['order']['order_subtotal_default'] = round($result['order']['order_subtotal'] * $rate, 2);
$result['order']['order_shipping_default'] = round($result['order']['order_shipping'] * $rate, 2);
if (isset($result['order']['order_transaction_fee'])) {
$result['order']['order_transaction_fee_default'] = round($result['order']['order_transaction_fee'] * $rate, 2);
}
$result['order_model']->update($result['order'], $result['id']);
$stats = new Stats();
$stats->save([
"stats_total" => $result['order']['order_total_default'],
"stats_subtotal" => $result['order']['order_subtotal_default'],
"stats_transaction_fee" => isset($result['order']['order_transaction_fee_default']) ? $result['order']['order_transaction_fee_default'] : 0,
"stats_subtotal_without_coupon" => $result['order']['order_subtotal_default'] - $coupon_discount,
"stats_shipping" => $result['order']['order_shipping_default'],
"stats_coupon" => $coupon_discount,
]);
}
/** ==============================================================================================================================
* Verifies the PAYPAL order
* @noajax
*/
public function verify() {
$success = filter_input(INPUT_GET, 'success');
$payment_id = filter_input(INPUT_GET, 'paymentId');
$payer_id = filter_input(INPUT_GET, 'PayerID');
$order = new Order();
if ($success === 'true' && isset($payment_id) && !empty($payment_id) && isset($payer_id) && !empty($payer_id)) {
$order->save(['order_id' => $payment_id, 'order_payer_id' => $payer_id]);
}
if (App::is_localhost()) {
header('Location: ' . Payment::$LOCALHOST . '#order?p=' . substr($payment_id, 4, strlen($payment_id)));
} else {
header('Location: ' . Payment::$URL . '#order?p=' . substr($payment_id, 4, strlen($payment_id)));
}
}
/** ==============================================================================================================================
* Returns all client orders
* @roles client, @nospamming
*/
public function orders() {
$user_id = (new User())->get_current_user_id();
$id = filter_input(INPUT_GET, 'id');
$order_model = new Order();
if (!isset($id)) {
App::response(200, $order_model->get_by_username($user_id));
} else {
App::response(200, $order_model->get_order_items_by($user_id, $id));
}
}
/** ==============================================================================================================================
* Gets all visible products or product by id
* @nospamming false
*/
public function get() {
Currency::get();
$data = json_decode(filter_input(INPUT_GET, "data"));
if (isset($data->model) && strtolower($data->model) === "products") {
if ($data->id === "") {
App::response(200, (new Products)->all());
} else {
App::response(200, (new Products)->get($data->id));
}
}
}
/** ==============================================================================================================================
* Gets cart and coupon information
*/
public function cart() {
Currency::get();
$country = (new User)->get_current_user_country();
App::response(200, array(
"cart" => (new Products)->cart(),
"coupon" => (new Coupon)->verify(),
"country" => $country ? Store::get_shipping_zone_from_country($country) : null,
));
}
/** ==============================================================================================================================
* Initialize currency options
*/
public function options() {
Currency::get();
}
/** ==============================================================================================================================
* Returns the coupon
*/
public function coupon() {
$search = filter_input(INPUT_GET, "data");
$coupon = (new Coupon)->get($search);
$return = [
"coupon" => $coupon,
"order" => $this->price(true, $coupon)
];
App::response($coupon ? 200 : 400, $return);
}
/** ==============================================================================================================================
* Gets user account information
* @roles client
*/
public function account() {
$user = new User();
App::response(200, $user->get_current_user_info());
}
/** ==============================================================================================================================
* If user is connected the contact_us form is different
* @roles user
*/
public function mail_connected() {
App::response(200, 'YES');
}
/** ==============================================================================================================================
* Verifies contact us form
*/
public function mail() {
$data = json_decode(file_get_contents('php://input'));
if (!isset($data)) {
return;
}
$user = new User();
$id = $user->get_current_user_fields(['user_id', 'user_name', 'user_first_name']);
if (!$id) {
UTILS::validate(Validate::EMAIL, $data->email);
UTILS::validate(Validate::LENGTH, $data->name);
}
UTILS::validate(Validate::LENGTH, $data->mess);
$fields = array("contact_us_mess" => $data->mess);
if (!$id) {
$fields['contact_us_email'] = $data->email;
$fields['contact_us_name'] = $data->name;
} else {
$fields['contact_us_user_id'] = $id['user_id'];
}
(new ContactUs)->save($fields);
$this->mail_send($id, $fields);
}
/** ==============================================================================================================================
* Sends a contact us mail to admin
*/
private function mail_send($id, $fields) {
$name = !$id ? $fields['contact_us_name'] : $id['user_first_name'];
$email = !$id ? $fields['contact_us_email'] : $id['user_name'];
require_once './Mail/Mail.php';
\Mail\Mail::send(array(
"fromName" => $name, "fromEmail" => $email,
"template" => "contact_us", "email" => 'asdasdasd', "subject" => "New Contact Us",
"data" => array(
"name" => 'admin',
"customer" => $name,
"mess" => $fields["contact_us_mess"]
)
));
App::response(200, 'YES');
}
/** ==============================================================================================================================
* Gets seller sales
* @roles seller
*/
public function my_sales() {
Currency::get();
$model_user = new User();
$model_coupon = new Coupon();
$model_claim = new Claim();
$user_id = $model_user->get_current_user_id();
App::response(200, ["coupon" => $model_coupon->get_by_user_id($user_id), "claims" => $model_claim->get_by_user_id($user_id)]);
}
/** ==============================================================================================================================
* Gets seller sales
* @roles seller
*/
public function receive_payment() {
Currency::get();
$v = $this->receive_payment_verify();
$v["coupon_model"]->disable($v["coupon"]['coupon_id']);
$id = uniqid();
$rate = (new Currency)->get_new_rate($v["currency"], true);
$price = round($v["price"] * $rate, 2);
$result = (new Payment())->pay_seller(["email" => $v["email"], "amount" => $price, "currency" => $v["currency"], "id" => $id]);
$model_claim = new Claim();
if ($result === 1) {
$model_claim->save(["claim_id" => $id, "claim_user_id" => $v["user_id"], "claim_price" => $price, "claim_currency" => $v["currency"], "claim_email" => $v["email"]]);
$v["coupon_model"]->update_price($v["coupon"]['coupon_id'], round($v["price"] / 0.95, 2));
$stats = new Stats();
$stats->save(["stats_coupon_payed" => $price]);
}
$v["coupon_model"]->enable($v["coupon"]['coupon_id']);
App::response($result === 1 ? 200 : 400, $result === 1 ? ["claims" => $model_claim->get($id), "coupon" => $v["coupon_model"]->get_by_user_id($v["user_id"])] : "ERROR");
}
private function receive_payment_verify() {
$data = json_decode(filter_input(INPUT_GET, "data"));
UTILS::validate(Validate::EMAIL, $data->email);
UTILS::validate(Validate::PASSWORD, $data->pass);
$user = new User();
if (!$user->verify_password($data->pass)) {
App::response(401, 'BAD PASSWORD');
}
$user_id = $user->get_current_user_id();
$currency = filter_input(INPUT_COOKIE, 'currency');
$coupon_model = new Coupon();
$coupon = $coupon_model->get_by_user_id($user_id, true);
$price = $coupon['coupon_profit_total'] - $coupon['coupon_payed'];
if (!($price > Coupon::$MIN_CLAIM)) {
App::response(400, 'SELLER MUST HAVE AT LEAST 5$ OF PROFIT');
}
if (intval($coupon['coupon_disabled']) === 1) {
App::response(401, 'DISABLED');
}
return ["coupon_model" => $coupon_model, "coupon" => $coupon, "currency" => $currency, "user_id" => $user_id, "email" => $data->email, "price" => $price];
}
}
<file_sep><?php
namespace Controller;
use App;
use Model\User as ModelUser;
use Model\Currency;
use Model\AModel;
use Mail\Mail;
use utils\Validate;
use utils\UTILS;
class User {
/** ==============================================================================================================================
* Verifies user password and username
*/
public function verify() {
$user = new ModelUser();
$user->verify(json_decode(filter_input(INPUT_GET, 'data')));
}
/** ==============================================================================================================================
* Send user new password
*/
public function forgot() {
$email = filter_input(INPUT_GET, 'email');
if (!isset($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
exit;
}
$user = new ModelUser();
$result = $user->change_password($email);
if ($result["result"] === 1) {
require_once './Mail/Mail.php';
Mail::send(array(
"fromName" => "Arc-Sans-Ciel", "fromEmail" => "<EMAIL>",
"template" => "forgot_password", "email" => $email, "subject" => "Lost password",
"data" => array(
"password" => $result["<PASSWORD>"],
"name" => $result["name"]
)
));
}
print_r($result);
}
/** ==============================================================================================================================
* Creates new user
*/
public function create() {
$data = json_decode(file_get_contents('php://input'));
$this->verify_fields($data, true);
$user = new ModelUser();
$data->user_password = password_hash($data->user_password, PASSWORD_DEFAULT);
$user->roles($data, ['client', 'user']);
$user->save($data);
}
/** ==============================================================================================================================
* Updates a user
* @roles user
*/
public function modify() {
$user = new ModelUser();
$data = json_decode(file_get_contents('php://input'));
$this->verify_fields($data);
$result = $user->update($data);
App::response($result === 1 ? 200 : 400, $result === 1 ? "OK" : "ERROR");
}
/** ==============================================================================================================================
* Updates a user
* @roles user
*/
public function modify_password() {
$user = new ModelUser();
$data = json_decode(file_get_contents('php://input'));
if (!$user->verify_password($data->user_old_password)) {
App::response(400, 'BAD OLD');
}
if (!isset($data->user_password) || !isset($data->user_repassword) || $data->user_password !== $data->user_repassword || empty($data->user_password) || empty($data->user_repassword)) {
App::response(400, 'BAD FIELDS');
}
if ($data->user_password === $data->user_old_password) {
App::response(400, 'NEW AND OLD MUST BE DIFFERENT');
}
$result = $user->update(["user_password" => password_hash($data->user_password, PASSWORD_DEFAULT)]);
App::response($result === 1 ? 200 : 400, $result === 1 ? "OK" : "ERROR");
}
/** ==============================================================================================================================
* Verifies user token
*/
public function token() {
Currency::get();
$user = new ModelUser();
$user->token2();
}
private function verify_fields(&$data, $exit = false) {
$verify = AModel::get_accepted_properties(["user_name", "user_password", "user_retype_password", "user_first_name", "user_last_name", "user_phone_number", "user_state", "user_country", "user_city", "user_postal_code", "user_line1", "user_line2", "user_formatted"]);
$array1 = $verify;
$array2 = $data;
if ($exit === false) {
$array1 = $data;
$array2 = $verify;
}
foreach ($array1 as $key => $value) {
if (!array_key_exists($key, $data) && $exit === true) {
App::response(400, $key . ' CANNOT BE EQUAL TO ' . $value);
} else if (!array_key_exists($key, $array2) && $exit === false) {
unset($data->$key);
continue;
}
$this->validate_field($key, $data->$key, $data->user_password);
}
if (isset($data->user_first_name)) {
$data->user_first_name = strtolower($data->user_first_name);
}
if (isset($data->user_last_name)) {
$data->user_last_name = strtolower($data->user_last_name);
}
}
private function validate_field($key, $value, $pass) {
switch ($key) {
case "user_password":
UTILS::validate(Validate::PASSWORD, $value);
break;
case "user_retype_password":
UTILS::validate(Validate::SAME, $pass, $value);
break;
case "user_phone_number":
UTILS::validate(Validate::PHONE, $value);
break;
case "user_name":
UTILS::validate(Validate::EMAIL, $value);
break;
case "user_line2":
case "user_id":
break;
default:
UTILS::validate(Validate::LENGTH, $value);
break;
}
}
}
<file_sep><?php
namespace Model;
use App;
class Store {
public static function shipping() {
return [
"t-shirt" => [
"USA" => ["first_item_price" => 11.00, "additional_item_price" => 2],
"Canada" => ["first_item_price" => 7.3, "additional_item_price" => 2],
"International" => ["first_item_price" => 15.00, "additional_item_price" => 3]
],
"sweatshirt" => [
"USA" => ["first_item_price" => 12.00, "additional_item_price" => 2],
"Canada" => ["first_item_price" => 7.3, "additional_item_price" => 2],
"International" => ["first_item_price" => 15.00, "additional_item_price" => 3]
],
"snapback" => [
"USA" => ["first_item_price" => 6.50, "additional_item_price" => 1.50],
"Canada" => ["first_item_price" => 8.00, "additional_item_price" => 2.00],
"International" => ["first_item_price" => 15.00, "additional_item_price" => 2.00]
]
];
}
public static function get_shipping_zone_from_country($country) {
if ($country === 'US') {
return "USA";
} else if ($country === 'CA') {
return "Canada";
} else {
return "International";
}
}
public static function sizes() {
return [
"small" => "1",
"x-small" => "2",
"medium" => "3",
"large" => "4",
"x-large" => "5",
"2x-large" => "6",
"3x-large" => "7",
"4x-large" => "8",
"5x-large" => "9"
];
}
}
| f0148926057f6e78df7d834b0b273efc02e2a523 | [
"PHP"
] | 15 | PHP | TimMouskhelichvili/e-commerce-server | af9e14590c7824d27fe28f20ac3f35cf175b4b4b | 44dab631e9d0fa4c359514ebdfa79dcb81cb5ae9 |
refs/heads/master | <repo_name>sciron/Katran<file_sep>/del_wys.py
import os
directory = '/Users/Sciron/Documents/public_html'
files = os.listdir(directory)
php = filter(lambda x: x.endswith('.php'), files)
html = filter(lambda x: x.endswith('.html'), files)
php_html = php + html
print php_html
for i in php_html:
print i
file = i
f = open(file, 'r')
#print f.readlines()
wb = 'wysiwygwebb'
temp = ''
for i in f.readlines():
if wb in i:
print i
else: temp += i
f.close()
f = open(file, 'w')
f.writelines(temp)
f.close
<file_sep>/master.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Безымянная страница</title>
<link href="2.css" rel="stylesheet">
<link href="master.css" rel="stylesheet">
</head>
<body>
<div id="container">
<div id="master_Layer2" style="position:absolute;text-align:center;left:7%;top:139px;width:816px;height:26px;z-index:2;">
<div id="master_Layer2_Container" style="width:816px;position:relative;margin-left:auto;margin-right:auto;text-align:left;">
</div>
</div>
<div id="wb_masterCssMenu1" style="position:absolute;left:76px;top:139px;width:809px;height:28px;text-align:center;z-index:3;">
<ul>
<li class="firstmain"><a href="./index.php" target="_self" title="Главная">Главная</a>
</li>
<li><a href="./tarif.html" target="_self" title="Тарифы">Тарифы</a>
</li>
<li><a href="./tablo.html" target="_self" title="On-Line табло аэропорта">On-Line табло аэропорта</a>
</li>
<li><a href="./kontakt.html" target="_self" title="Контакты">Контакты</a>
</li>
<li><a href="./taxi_adler.php" target="_self">Такси Адлер</a>
</li>
</ul>
<br>
</div>
<div id="wb_masterImage2" style="position:absolute;left:421px;top:-5px;width:128px;height:128px;z-index:4;">
<a href="./index.php"><img src="images/img0001.png" id="masterImage2" alt=""></a></div>
<div id="wb_masterkrasnaya_polyanaText4" style="position:absolute;left:630px;top:64px;width:204px;height:32px;text-align:center;z-index:5;">
<span style="color:#000000;font-family:Verdana;font-size:13px;">Заказать такси дешево <br>Тел: 8-963-164-59-49</span></div>
<div id="wb_masterText1" style="position:absolute;left:568px;top:14px;width:329px;height:38px;z-index:6;text-align:left;">
<span style="color:#000000;font-family:Arial;font-size:13px;"> </span><span style="color:#000000;font-family:Verdana;font-size:32px;"><strong>Такси "КАТРАН"</strong></span></div>
<div id="wb_masterImage1" style="position:absolute;left:749px;top:2px;width:216px;height:111px;filter:alpha(opacity=20);opacity:0.20;z-index:7;">
<img src="images/img0002.png" id="masterImage1" alt="заказ такси в сочи, вызов такси" title="Такси "Катран""></div>
<div id="wb_master_Image3" style="position:absolute;left:891px;top:4px;width:78px;height:109px;z-index:8;">
<img src="images/img0003.png" id="master_Image3" alt="заказ такси, дешевое такис, встретить в аэропорту" title="Такси "Катран" Сочи"></div>
<div id="wb_master_Image4" style="position:absolute;left:2px;top:2px;width:216px;height:111px;filter:alpha(opacity=20);opacity:0.20;z-index:9;">
<img src="images/img0004.png" id="master_Image4" alt="заказ такси в сочи, вызов такси" title="Заказать такси в аэропорт"></div>
<div id="master_Layer1" style="position:absolute;text-align:center;left:0%;top:197px;width:965px;height:1308px;z-index:10;">
<div id="master_Layer1_Container" style="width:965px;position:relative;margin-left:auto;margin-right:auto;text-align:left;">
<div id="wb_master_Text12" style="position:absolute;left:226px;top:1254px;width:512px;height:54px;text-align:center;z-index:0;">
<span style="color:#FFFFFF;font-family:Arial;font-size:17px;">© 2014-2016 Такси "Катран". Все права защищены<br> ИНН 231707975752 ОГРН 314236702900142 ОКПО 0159219183</span><span style="color:#000000;font-family:'Times New Roman';font-size:16px;"><br></span></div>
</div>
</div>
</div>
</body>
</html><file_sep>/zakaz.php
<?php
require 'phpmailerautoload.php';
function ValidateEmail($email)
{
$pattern = '/^([0-9a-z]([-.\w]*[0-9a-z])*@(([0-9a-z])+([-\w]*[0-9a-z])*\.)+[a-z]{2,6})$/i';
return preg_match($pattern, $email);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['formid'] == 'form1')
{
$mailto = '<EMAIL>';
$mailfrom = isset($_POST['email']) ? $_POST['email'] : $mailto;
$mailcc = '<EMAIL>';
$mailbcc = '<EMAIL>';
$subject = 'Заказ такси';
$message = 'Информация о заказе';
$success_url = './spasibo.php';
$error_url = './error.php';
$error = '';
$eol = "\n";
$max_filesize = isset($_POST['filesize']) ? $_POST['filesize'] * 1024 : 1024000;
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = 'mx1.hostinger.ru';
$mail->Port = 465;
$mail->SMTPAuth = true;
$mail->Username = '<EMAIL>';
$mail->Password = '<PASSWORD>';
$mail->SMTPSecure = true;
$mail->Subject = stripslashes($subject);
$mail->From = $mailfrom;
$mail->FromName = $mailfrom;
$mailto_array = explode(",", $mailto);
$mailcc_array = explode(",", $mailcc);
$mailbcc_array = explode(",", $mailbcc);
for ($i = 0; $i < count($mailto_array); $i++)
{
if(trim($mailto_array[$i]) != "")
{
$mail->AddAddress($mailto_array[$i], "");
}
}
for ($i = 0; $i < count($mailcc_array); $i++)
{
if(trim($mailcc_array[$i]) != "")
{
$mail->AddCC($mailcc_array[$i], "");
}
}
for ($i = 0; $i < count($mailbcc_array); $i++)
{
if(trim($mailbcc_array[$i]) != "")
{
$mail->AddBCC($mailbcc_array[$i], "");
}
}
$mail->AddReplyTo($mailfrom);
if (!ValidateEmail($mailfrom))
{
$error .= "The specified email address is invalid!\n<br>";
}
if (!empty($error))
{
$errorcode = file_get_contents($error_url);
$replace = "##error##";
$errorcode = str_replace($replace, $error, $errorcode);
echo $errorcode;
exit;
}
$internalfields = array ("submit", "reset", "send", "filesize", "formid", "captcha_code", "recaptcha_challenge_field", "recaptcha_response_field", "g-recaptcha-response");
$message .= $eol;
$message .= "IP Address : ";
$message .= $_SERVER['REMOTE_ADDR'];
$message .= $eol;
foreach ($_POST as $key => $value)
{
if (!in_array(strtolower($key), $internalfields))
{
if (!is_array($value))
{
$message .= ucwords(str_replace("_", " ", $key)) . " : " . $value . $eol;
}
else
{
$message .= ucwords(str_replace("_", " ", $key)) . " : " . implode(",", $value) . $eol;
}
}
}
$mail->CharSet = 'UTF-8';
if (!empty($_FILES))
{
foreach ($_FILES as $key => $value)
{
if ($_FILES[$key]['error'] == 0 && $_FILES[$key]['size'] <= $max_filesize)
{
$mail->AddAttachment($_FILES[$key]['tmp_name'], $_FILES[$key]['name']);
}
}
}
$mail->WordWrap = 80;
$mail->Body = $message;
if (!$mail->Send())
{
die('PHPMailer error: ' . $mail->ErrorInfo);
}
header('Location: '.$success_url);
exit;
}
?>
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<title>Заказать такси в Сочи</title>
<meta name="description" content="Заказать такси онлайн">
<meta name="keywords" content="Заказать такси в Сочи, такси сочи, цены на такси сочи. ">
<link href="taxi.ico" rel="shortcut icon" type="image/x-icon">
<link href="2.css" rel="stylesheet">
<link href="zakaz.css" rel="stylesheet">
<script>
function ValidateZakaz(theForm)
{
var regexp;
if (theForm.Combobox3.selectedIndex < 0)
{
alert("Please select one of the \"Час\" options.");
theForm.Combobox3.focus();
return false;
}
if (theForm.Combobox3.selectedIndex == 0)
{
alert("The first \"Час\" option is not a valid selection. Please choose one of the other options.");
theForm.Combobox3.focus();
return false;
}
return true;
}
</script>
</head>
<body>
<div id="zakaz_PageHeader1" style="position:absolute;overflow:hidden;text-align:left;left:0px;top:0px;width:100%;height:113px;z-index:-1;">
<div id="wb_tarif_Text13" style="position:absolute;left:211px;top:37px;width:186px;height:32px;text-align:center;z-index:0;">
<span style="color:#000000;font-family:Verdana;font-size:13px;"><strong>Заказать такси в Сочи<br>Такси в аэропорт</strong></span></div>
</div>
<div id="space"><br></div>
<div id="container">
<div id="wb_zakazMasterObjects1" style="position:absolute;left:0px;top:0px;width:969px;height:1507px;z-index:23;">
<div id="master_Layer2" style="position:absolute;text-align:center;left:7%;top:139px;width:816px;height:26px;z-index:3;">
<div id="master_Layer2_Container" style="width:816px;position:relative;margin-left:auto;margin-right:auto;text-align:left;">
</div>
</div>
<div id="wb_masterCssMenu1" style="position:absolute;left:76px;top:139px;width:809px;height:28px;text-align:center;z-index:4;">
<ul>
<li class="firstmain"><a href="./index.php" target="_self" title="Главная">Главная</a>
</li>
<li><a href="./tarif.html" target="_self" title="Тарифы">Тарифы</a>
</li>
<li><a href="./tablo.html" target="_self" title="On-Line табло аэропорта">On-Line табло аэропорта</a>
</li>
<li><a href="./kontakt.html" target="_self" title="Контакты">Контакты</a>
</li>
<li><a href="./taxi_adler.php" target="_self">Такси Адлер</a>
</li>
</ul>
<br>
</div>
<div id="wb_masterImage2" style="position:absolute;left:421px;top:-5px;width:128px;height:128px;z-index:5;">
<a href="./index.php"><img src="images/img0001.png" id="masterImage2" alt=""></a></div>
<div id="wb_masterkrasnaya_polyanaText4" style="position:absolute;left:630px;top:64px;width:204px;height:32px;text-align:center;z-index:6;">
<span style="color:#000000;font-family:Verdana;font-size:13px;">Заказать такси дешево <br>Тел: 8-963-164-59-49</span></div>
<div id="wb_masterText1" style="position:absolute;left:568px;top:14px;width:329px;height:38px;z-index:7;text-align:left;">
<span style="color:#000000;font-family:Arial;font-size:13px;"> </span><span style="color:#000000;font-family:Verdana;font-size:32px;"><strong>Такси "КАТРАН"</strong></span></div>
<div id="wb_masterImage1" style="position:absolute;left:749px;top:2px;width:216px;height:111px;filter:alpha(opacity=20);opacity:0.20;z-index:8;">
<img src="images/img0002.png" id="masterImage1" alt="заказ такси в сочи, вызов такси" title="Такси "Катран""></div>
<div id="wb_master_Image3" style="position:absolute;left:891px;top:4px;width:78px;height:109px;z-index:9;">
<img src="images/img0003.png" id="master_Image3" alt="заказ такси, дешевое такис, встретить в аэропорту" title="Такси "Катран" Сочи"></div>
<div id="wb_master_Image4" style="position:absolute;left:2px;top:2px;width:216px;height:111px;filter:alpha(opacity=20);opacity:0.20;z-index:10;">
<img src="images/img0004.png" id="master_Image4" alt="заказ такси в сочи, вызов такси" title="Заказать такси в аэропорт"></div>
<div id="master_Layer1" style="position:absolute;text-align:center;left:0%;top:197px;width:965px;height:1308px;z-index:11;">
<div id="master_Layer1_Container" style="width:965px;position:relative;margin-left:auto;margin-right:auto;text-align:left;">
<div id="wb_master_Text12" style="position:absolute;left:226px;top:1254px;width:512px;height:54px;text-align:center;z-index:1;">
<span style="color:#FFFFFF;font-family:Arial;font-size:17px;">© 2014-2016 Такси "Катран". Все права защищены<br> ИНН 231707975752 ОГРН 314236702900142 ОКПО 0159219183</span><span style="color:#000000;font-family:'Times New Roman';font-size:16px;"><br></span></div>
</div>
</div>
</div>
<div id="wb_Form1" style="position:absolute;left:247px;top:211px;width:500px;height:471px;z-index:24;">
<form name="Zakaz" method="post" action="<?php echo basename(__FILE__); ?>" enctype="multipart/form-data" accept-charset="UTF-8" id="Form1" onsubmit="return ValidateZakaz(this)">
<input type="hidden" name="formid" value="form1">
<input type="text" id="Editbox1" style="position:absolute;left:110px;top:164px;width:278px;height:33px;line-height:33px;z-index:12;" name="Введите Ваше имя" value="" title="Введите Ваше имя" placeholder="Введите Ваше имя">
<input type="text" id="Editbox2" style="position:absolute;left:110px;top:221px;width:278px;height:33px;line-height:33px;z-index:13;" name="Номер телефона" value="" title="Номер телефона" placeholder="Номер телефона">
<input type="text" id="Editbox3" style="position:absolute;left:111px;top:278px;width:277px;height:33px;line-height:33px;z-index:14;" name="Номер рейса" value="" title="Номер рейса" placeholder="Номер рейса">
<select name="День" size="1" id="Combobox1" style="position:absolute;left:209px;top:344px;width:57px;height:21px;z-index:15;" title="День">
<option value="День">День</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="29">29</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<select name="Месяц" size="1" id="Combobox2" style="position:absolute;left:113px;top:344px;width:84px;height:20px;z-index:16;" title="Месяц">
<option value="Месяц">Месяц</option>
<option value="Январь">Январь</option>
<option value="Февраль">Февраль</option>
<option value="Март">Март</option>
<option value="Апрель">Апрель</option>
<option value="Май">Май</option>
<option value="Июнь">Июнь</option>
<option value="Июль">Июль</option>
<option value="Август">Август</option>
<option value="Сентябрь">Сентябрь</option>
<option value="Октябрь">Октябрь</option>
<option value="Ноябрь">Ноябрь</option>
<option value="Декабрь">Декабрь</option>
</select>
<select name="Час" size="1" id="Combobox3" style="position:absolute;left:276px;top:344px;width:51px;height:20px;z-index:17;" title="Час">
<option selected value="Час">Час</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
</select>
<select name="Мин" size="1" id="Combobox4" style="position:absolute;left:335px;top:344px;width:52px;height:21px;z-index:18;" title="Мин">
<option value="Мин">Мин</option>
<option value="00">00</option>
<option value="05">05</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
<option value="35">35</option>
<option value="40">40</option>
<option value="45">45</option>
<option value="50">50</option>
<option value="55">55</option>
</select>
<input type="submit" id="Button1" name="Заказать" value="Заказать" style="position:absolute;left:153px;top:401px;width:195px;height:31px;z-index:19;" title="Заказать">
<div id="wb_Text1" style="position:absolute;left:0px;top:110px;width:500px;height:36px;text-align:center;z-index:20;">
<span style="color:#FFFFFF;font-family:Verdana;font-size:16px;"> Введите данные и нажмите Заказать<br>Наши операторы перезвонят Вам в течении 10 минут</span></div>
<div id="wb_Text2" style="position:absolute;left:3px;top:40px;width:497px;height:42px;text-align:center;z-index:21;">
<span style="color:#000000;font-family:Arial;font-size:13px;"><strong> </strong></span><span style="color:#FFD700;font-family:Verdana;font-size:35px;">On-Line Заказ такси</span></div>
</form>
</div>
</div>
</body>
</html> | 15a6412f88ce464ab3eb2f4997755c342372eee5 | [
"Python",
"PHP"
] | 3 | Python | sciron/Katran | b5a3ed8037258341ef9fc9860a9a86b22b5479ec | 8616647c480bd995138d20ba5b0b00c02252d297 |
refs/heads/master | <file_sep>const express = require('express');
const router = express.Router();
const { ensureAuthenticated, isAdmin } = require('../middleware/checkAuth');
const { connect } = require('./authRoute');
//---------- Welcome Route -----------//
// localhost:8081
router.get('/', (req, res) => {
res.send('welcome');
});
//---------- Dashboard Route -----------//
// localhost:8081/dashboard
router.get('/dashboard', ensureAuthenticated, (req, res) => {
res.render('dashboard', {
user: req.user,
});
});
//---------- Secret Admin Route -----------//
// localhost:8081/admin
router.get('/admin', isAdmin, (req, res) => {
const allSessions = req.sessionStore.sessions;
// console.log(allSessions);
const details = [];
// req.sessionStore.all((error, sessions) => {
// for (let key in sessions) {
// details.push({
// userID: sessions[key].passport.user,
// sessionID: key,
// });
// // console.log("im a looooop");
// console.log(details);
// }
// });
// const allSessions = req.sessionStore.all((err, sessions) => {return sessions});
// console.log(allSessions);
// details.push({
// userID: 10000,
// sessionID: 'qwerty'
// })
// fk this, this is different from above
// for (const sessionID in allSessions) {
// // let sessionInfo = JSON.parse(sessionID);
// let sessionInfo = JSON.parse(allSessions[sessionID]);
// // let sessionInfoObj = JSON.parse(sessionInfoStr);
// console.log(sessionInfo);
// console.log(sessionInfo.passport.user);
// // console.log(sessionInfoObj);
// details.push({
// userID: sessionInfo.passport.user,
// sessionID: sessionID,
// });
// console.log("pooooops");
// console.log(details);
// // }
res.render('admin', {
user: req.user,
sessions: req.sessionStore.sessions,
});
});
//---------- Admin/Revoke Route -----------//
// localhost:8081/dashboard
router.get('/admin/revoke/:sessionID', (req, res) => {
const sessionID = req.params.sessionID;
// destroy session logic
req.sessionStore.destroy(sessionID);
console.log(sessionID + "was revoked");
res.redirect('/admin');
});
module.exports = router;
<file_sep>const database = [
{
id: 1,
name: '<NAME>',
email: '<EMAIL>',
password: '<PASSWORD>!',
isAdmin: false,
},
{
id: 2,
name: '<NAME>',
email: '<EMAIL>',
password: '<PASSWORD>!',
isAdmin: false,
},
{
id: 3,
name: '<NAME>',
email: '<EMAIL>',
password: 'jo',
isAdmin: true,
},
{
id: 4,
name: 'Bob',
email: '<EMAIL>',
password: 'hi',
isAdmin: true,
},
];
const userModel = {
findOne: (email) => {
const user = database.find((user) => user.email === email);
if (user) {
return user;
}
throw new Error(`Couldn't find user with email: ${email}`);
},
findById: (id) => {
const user = database.find((user) => user.id === id);
if (user) {
return user;
}
console.log(`Couldn't find user with id: ${id}`);
return false;
},
createUser: (id, name) => {
const newUser = {
id: id,
name: name,
};
database.push(newUser);
return newUser;
},
};
module.exports = { database, userModel };
| 01842265b244ea943a67fbaa147ee384729fffc7 | [
"JavaScript"
] | 2 | JavaScript | megankuo/comp2523-PassportLab | c301270cfc36860974e2ccb01e7e83ee71cf378a | 677325db5a7f4fa8bee8dff167fbecd9994ed0d7 |
refs/heads/master | <file_sep>package me.wizos.loread.utils;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Environment;
import com.socks.library.KLog;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import me.wizos.loread.App;
/**
* Created by Wizos on 2016/3/19.
*/
public class UFile {
protected static Context mContext;
public static void setContext(Context context){
mContext = context;
}
protected Context getContext(){
return mContext;
}
//判断外部存储(SD卡)是否可以读写
public static boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) { // 判断SD卡是否插入
return true;
}
return false;
}
//判断外部存储是否至少可以读
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
public static String getCacheFileRelativePath(String fileNameInMD5){
return fileNameInMD5;
}
/**
* 递归删除应用下的缓存
* @param dir 需要删除的文件或者文件目录
* @return 文件是否删除
*/
public static boolean deleteHtmlDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean isSuccess = deleteHtmlDir(new File(dir, children[i]));
if (!isSuccess) {
return false;
}
}
}
// KLog.i("删除:" + dir.delete());
return dir.delete();
}
public static void deleteHtmlDirList(ArrayList<String> fileNameInMD5List) {
for (String fileNameInMD5:fileNameInMD5List){
File folder = new File( App.cacheRelativePath + fileNameInMD5 ) ;
deleteHtmlDir( folder );
}
}
public static void saveHtml( String fileNameInMD5 ,String fileContent){
if( !isExternalStorageWritable() ){return;}
// 添加文件写入和创建的权限
// String aaa = Environment.getExternalStorageDirectory() + File.separator + "aaa.txt";
// Environment.getExternalStorageDirectory() 获得sd卡根目录 File.separator 代表 / 分隔符
String filePathName = App.cacheRelativePath + fileNameInMD5 + File.separator + fileNameInMD5 + ".html";
String folderPathName = App.cacheRelativePath + fileNameInMD5;
File file = new File( filePathName );
File folder = new File( folderPathName );
try {
if(!folder.exists())
folder.mkdirs();
// KLog.d("【】" + file.toString() + "--"+ folder.toString());
FileWriter fileWriter = new FileWriter(file,false); //在 (file,false) 后者表示在 fileWriter 对文件再次写入时,是否会在该文件的结尾续写,true 是续写,false 是覆盖。
fileWriter.write( fileContent );
fileWriter.flush(); // 刷新该流中的缓冲。将缓冲区中的字符数据保存到目的文件中去。
fileWriter.close(); // 关闭此流。在关闭前会先刷新此流的缓冲区。在关闭后,再写入或者刷新的话,会抛IOException异常。
} catch (IOException e) {
e.printStackTrace();
}
}
public static String readHtml( String fileNameInMD5 ){
if( !isExternalStorageWritable() ){return null;}
String filePathName = App.cacheRelativePath + fileNameInMD5 + File.separator + fileNameInMD5 + ".html";
String folderPathName = App.cacheRelativePath + fileNameInMD5 ;
File file = new File( filePathName );
File folder = new File( folderPathName );
String fileContent ="" , temp = "";
KLog.d("【】" + file.toString() + "--"+ folder.toString());
try {
if(!folder.exists()){
return null;
}
FileReader fileReader = new FileReader(file);
BufferedReader br = new BufferedReader( fileReader );//一行一行读取 。在电子书程序上经常会用到。
while(( temp = br.readLine())!= null){
fileContent += temp+"\r\n";
}
fileReader.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return fileContent;
}
public static android.graphics.Bitmap getBitmap(String filePath){
if(filePath==null)
return null;
if(filePath.equals(""))
return null;
File file = new File( filePath );
try {
FileInputStream fis = new FileInputStream(file);
return BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
/**
* 此方法在使用完InputStream后会关闭它。
*
* @param is
* @param filePath
* @throws IOException
*/
public static void saveFromStream( InputStream is, String filePath) throws IOException {
KLog.d("【 saveFromStream 1】" + filePath);
File file = new File(filePath);
BufferedInputStream bis = new BufferedInputStream(is);
FileOutputStream os = null;
BufferedOutputStream bos = null; // BufferedReader buffered = null.,故此时之关闭了in
// KLog.d("【 saveFromStream 4】");
// TODO 保存文件,会遇到存储空间满的问题,如果批量保存文件,会一直尝试保存
try {
if (file.exists()) { // 如果目标文件已存在,不保存
return;
}
File dir = file.getParentFile();
dir.mkdirs();
// KLog.d("【saveFromStream 8】" );
byte[] buff = new byte[8192];
int size = 0;
os = new FileOutputStream( file );
bos = new BufferedOutputStream(os);
while ((size = bis.read(buff)) != -1) { // NullPointerException: Attempt to invoke virtual method 'okio.Segment okio.Segment.push(okio.Segment)' on a null object reference
bos.write(buff, 0, size);
}
bos.flush();
} finally {
if (is != null) {
is.close();
}
if (bis != null) {
bis.close();
}
if (os != null) {
os.close();
}
if (bos != null) {
bos.close();
}
}
}
public static boolean isFileExists(String filePath){
File file = new File(filePath);
if (file.exists()) { // 如果目标文件已存在,不保存
return true;
}
return false;
}
public static String getImageType(InputStream in) {
try {
byte[] b = getBytes(in, 10);
byte b0 = b[0];
byte b1 = b[1];
byte b2 = b[2];
byte b3 = b[3];
byte b6 = b[6];
byte b7 = b[7];
byte b8 = b[8];
byte b9 = b[9];
if (b0 == (byte) 'G' && b1 == (byte) 'I' && b2 == (byte) 'F') {
return ".gif";
} else if (b1 == (byte) 'P' && b2 == (byte) 'N' && b3 == (byte) 'G') {
return ".png";
} else if (b6 == (byte) 'J' && b7 == (byte) 'F' && b8 == (byte) 'I' && b9 == (byte) 'F') {
return ".jpg";
} else if (b6 == (byte) 'E' && b7 == (byte) 'x' && b8 == (byte) 'i' && b9 == (byte) 'f') {
return ".jpg";
} else {
return "";
}
} catch (Exception e) {
return "";
}
}
public static String reviseSrc(String url){
int typeIndex = url.lastIndexOf(".");
String fileExt = url.substring(typeIndex, url.length());
if(fileExt.contains(".jpg")){
url = url.substring(0,typeIndex) + ".jpg";
}else if(fileExt.contains(".jpeg")){
url = url.substring(0,typeIndex) + ".jpeg";
}else if(fileExt.contains(".png")){
url = url.substring(0,typeIndex) + ".png";
}else if(fileExt.contains(".gif")){
url = url.substring(0,typeIndex) + ".gif";
}
KLog.d( "【 修正后的url 】" + url );
return url;
}
public static String getFileExtByUrl(String url){
int typeIndex = url.lastIndexOf(".");
int extLength = url.length() - typeIndex;
String fileExt = "";
if(extLength<6){
fileExt = url.substring( typeIndex ,url.length());
}else {
// fileExt = url.substring( typeIndex ,url.length());
if(fileExt.contains(".jpg")){
fileExt = ".jpg";
}else if(fileExt.contains(".jpeg")){
fileExt = ".jpeg";
}else if(fileExt.contains(".png")){
fileExt = ".png";
}else if(fileExt.contains(".gif")){
fileExt = ".gif";
}
}
KLog.d( "【获取 FileExtByUrl 】失败" + url.substring( typeIndex ,url.length()) + extLength );
KLog.d( "【修正正文内的SRC】的格式" + fileExt );
return fileExt;
}
private static byte[] getBytes(InputStream in,int nums){
byte b[]= new byte[nums]; //创建合适文件大小的数组
try {
// in.skip(9);//跳过前9个字节
int read = in.read(b,0,nums); //读取文件中的内容到b[]数组,//读取 nums 个字节赋值给 b
// in.close();
KLog.d("read ="+ read );
KLog.d("b ="+ b[0]);
} catch (IOException e) {
e.printStackTrace();
}
return b;
}
// mkdir()
// 只能在已经存在的目录中创建创建文件夹。
// mkdirs()
// 可以在不存在的目录中创建文件夹。诸如:a\\b,既可以创建多级目录。
//
// mkdirs
// public boolean mkdirs()
//
// 创建一个目录,它的路径名由当前 File 对象指定,包括任一必须的父路径。
//
// 返回值:
// 如果该目录(或多级目录)能被创建则为 true;否则为 false。
//
// mkdir
// public boolean mkdir()
//
// 创建一个目录,它的路径名由当前 File 对象指定。
//
// 返回值:
// 如果该目录能被创建则为 true;否则为 false。
}
<file_sep>apply plugin: 'com.android.application'
apply plugin: 'oneapm'
apply plugin: 'com.neenbedankt.android-apt'
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "me.wizos.loread"
minSdkVersion 21
targetSdkVersion 23
versionCode 1
versionName "1.1"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets {
main {
java.srcDirs = ['src/main/java', 'src/main/java-gen']
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile('com.github.afollestad.material-dialogs:core:0.8.5.8@aar') {
transitive = true
}
// compile 'org.sufficientlysecure:html-textview:1.4'
// compile 'org.greenrobot:eventbus:3.0.0'
// compile files('libs/oneapm-android-agent.jar')
compile files('libs/klog.jar')
compile 'com.facebook.stetho:stetho-okhttp:1.3.1'
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.android.support:cardview-v7:23.3.0'
compile 'com.android.support:support-v4:23.3.0'
compile 'com.android.support:design:23.3.0'
compile 'com.squareup.okhttp:okhttp:2.7.5'
compile 'com.zhy:okhttputils:2.3.8'
compile 'com.readystatesoftware.systembartint:systembartint:1.0.3'// 透明通知栏
compile 'com.github.yuweiguocn:GreenDaoUpgradeHelper:v0.0.5'
compile 'de.greenrobot:greendao:2.1.0'// ORM框架 数据库
compile 'com.google.code.gson:gson:2.6.2'
compile 'org.parceler:parceler-api:1.1.1'// 序列化数据
compile 'com.github.bumptech.glide:glide:3.7.0' // 图片加载
compile 'com.kyleduo.switchbutton:library:1.4.0'// 开关按钮
compile 'com.jakewharton:butterknife:8.0.1'// 依赖注入
apt 'com.jakewharton:butterknife-compiler:8.0.1'
compile 'me.zhanghai.android.materialprogressbar:library:1.1.6'// https://github.com/DreaminginCodeZH/MaterialProgressBar
compile 'me.zhanghai.android.materialedittext:library:1.0.2'
// compile 'com.bigkoo:snappingstepper:1.0.2'
compile files('libs/stetho-1.3.1-fatjar.jar')
}
<file_sep>//package me.wizos.loread.list;
//
//import android.content.Context;
//import android.support.design.widget.AppBarLayout;
//import android.support.design.widget.CoordinatorLayout;
//import android.util.AttributeSet;
//import android.view.View;
//
///**
// * Created by Wizos on 2016/3/19.
// */
//public class LayoutBehavior extends CoordinatorLayout.Behavior<View> {
// public LayoutBehavior(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override
// public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) {
// return dependency instanceof AppBarLayout;
// }
//
// @Override
// public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
// float translationY = Math.abs(dependency.getTranslationY());
// child.setTranslationY(translationY);
// return true;
// }
//}
<file_sep>package me.wizos.loread;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import com.facebook.stetho.Stetho;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import me.wizos.loread.dao.DaoMaster;
import me.wizos.loread.dao.DaoSession;
import me.wizos.loread.utils.HttpUtil;
/**
* Created by Wizos on 2015/12/24.
* 该类为活动管理器,每个活动创建时都添加到该 list (销毁时便移除),可以实时收集到目前存在的 活动 ,方便要退出该应用时调用 finishAll() 来一次性关闭所有活动
*/
public class App extends Application{
public static final String DB_NAME = "loread_DB";
public static String cacheRelativePath,cacheAbsolutePath;
public static String logRelativePath,logAbsolutePath;
public static List<Activity> activities = new ArrayList<>();
private static DaoSession daoSession;
public static Context context;
private static App instance;
public static App getInstance() {
return instance;
}
public static Context getContext(){ return context;}
public static void addActivity(Activity activity){
activities.add(activity);
}
@Override
public void onCreate() {
super.onCreate();
App.context = getApplicationContext();
instance = this;
cacheRelativePath = getExternalFilesDir(null) + File.separator + "cache" + File.separator;
cacheAbsolutePath = "file:"+ File.separator + File.separator + cacheRelativePath;
logRelativePath = getExternalFilesDir(null) + File.separator + "log" + File.separator;
logAbsolutePath = "file:"+ File.separator + File.separator + logRelativePath;
Stetho.initialize(
Stetho.newInitializerBuilder(this)
.enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
.enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this))
.build());
HttpUtil.xx();
}
public static void removeActivity(Activity activity){
activities.remove(activity);
activity.finish();
}
public static void finishAll(){
for (Activity activity : activities){
if (!activity.isFinishing()){
activity.finish();
}
}
}
// 官方推荐将获取 DaoMaster 对象的方法放到 Application 层,这样将避免多次创建生成 Session 对象
public static DaoSession getDaoSession() {
if (daoSession == null) {
DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(getInstance(), DB_NAME, null);
daoSession = new DaoMaster(helper.getWritableDatabase()).newSession();
// // 通过 DaoMaster 的内部类 DevOpenHelper,你可以得到一个便利的 SQLiteOpenHelper 对象。
// // 可能你已经注意到了,你并不需要去编写「CREATE TABLE」这样的 SQL 语句,因为 greenDAO 已经帮你做了。
// // 注意:默认的 DaoMaster.DevOpenHelper 会在数据库升级时,删除所有的表,意味着这将导致数据的丢失。
// // 所以,在正式的项目中,你还应该做一层封装,来实现数据库的安全升级。
// DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, DB_NAME, null);
// db = helper.getWritableDatabase();
// // 注意:该数据库连接属于 DaoMaster,所以多个 Session 指的是相同的数据库连接。
// daoMaster = new DaoMaster(db);
// daoSession = daoMaster.newSession();
//
}
return daoSession;
}
}
<file_sep>package me.wizos.loread.activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.Theme;
import com.kyleduo.switchbutton.SwitchButton;
import com.socks.library.KLog;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.wizos.loread.R;
import me.wizos.loread.data.WithDB;
import me.wizos.loread.data.WithSet;
public class SettingActivity extends BaseActivity {
protected static final String TAG = "SettingActivity";
private Context context;
private Toolbar toolbar;
private Thread mThread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
context = this ;
ButterKnife.bind(this);
initToolbar();
initView();
readSettingAndChangeView();
}
@Override
protected Context getActivity(){
return context;
}
public String getTAG(){
return TAG;
}
@Override
protected void notifyDataChanged(){
}
@Override
protected void onPause() {
super.onPause();
if (mThread != null && !mThread.isInterrupted() && mThread.isAlive())
mThread.interrupt();
}
@Override
public void onClick(View v) {
}
private SwitchButton syncFirstOpen,syncAllStarred,downImgWifi,scrollMark,orderTagFeed;
private TextView clearBeforeDaySummary;
private Button clearLog;
private int clearBeforeDayIndex, clearBeforeDay;
private void initView(){
syncFirstOpen = (SwitchButton) findViewById(R.id.setting_sync_first_open_sb_flyme);
syncAllStarred = (SwitchButton) findViewById(R.id.setting_sync_all_starred_sb_flyme);
downImgWifi = (SwitchButton) findViewById(R.id.setting_down_img_sb_flyme);
scrollMark = (SwitchButton) findViewById(R.id.setting_scroll_mark_sb_flyme);
orderTagFeed = (SwitchButton) findViewById(R.id.setting_order_tagfeed_sb_flyme);
clearBeforeDaySummary = (TextView) findViewById(R.id.setting_clear_day_summary);
// clearLog = (Button)findViewById(R.id.setting_clear_log_button);
}
protected void readSettingAndChangeView(){
syncFirstOpen.setChecked(WithSet.getInstance().isSyncFirstOpen());
syncAllStarred.setChecked(WithSet.getInstance().isSyncAllStarred());
downImgWifi.setChecked(WithSet.getInstance().isDownImgWifi());
scrollMark.setChecked(WithSet.getInstance().isScrollMark());
orderTagFeed.setChecked(WithSet.getInstance().isOrderTagFeed());
clearBeforeDay = WithSet.getInstance().getClearBeforeDay();
changeViewSummary();
KLog.d( "3333=="+ clearBeforeDayIndex );
}
private void changeViewSummary(){
CharSequence[] items = this.context.getResources().getTextArray( R.array.setting_clear_day_dialog_item_array );
int num = items.length;
for(int i=0; i< num; i++){
if (clearBeforeDay == Integer.valueOf(items[i].toString().replace(" 天",""))){
clearBeforeDayIndex = i;
}
}
clearBeforeDaySummary.setText( clearBeforeDay +" 天");
}
public void onSBClick(View view){
SwitchButton v = (SwitchButton)view;
KLog.d( "点击" );
switch (v.getId()) {
case R.id.setting_sync_first_open_sb_flyme:
WithSet.getInstance().setSyncFirstOpen(v.isChecked());
break;
case R.id.setting_sync_all_starred_sb_flyme:
WithSet.getInstance().setSyncAllStarred(v.isChecked());
break;
case R.id.setting_down_img_sb_flyme:
WithSet.getInstance().setDownImgWifi(v.isChecked());
break;
case R.id.setting_scroll_mark_sb_flyme:
WithSet.getInstance().setScrollMark(v.isChecked());
break;
case R.id.setting_order_tagfeed_sb_flyme:
WithSet.getInstance().setOrderTagFeed(v.isChecked());
break;
}
KLog.d("Switch: " , v.isChecked() );
}
@OnClick(R.id.setting_clear_day_title) void showClearBeforeDay() {
KLog.d( clearBeforeDayIndex );
new MaterialDialog.Builder(this)
.title(R.string.setting_clear_day_dialog_title)
.items(R.array.setting_clear_day_dialog_item_array)
.itemsCallbackSingleChoice( clearBeforeDayIndex, new MaterialDialog.ListCallbackSingleChoice() {
@Override
public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
// System.out.println("选择了");
String temp = String.valueOf(text);
clearBeforeDay = Integer.valueOf(temp.replace(" 天",""));
clearBeforeDayIndex = which;
WithSet.getInstance().setClearBeforeDay( clearBeforeDay );
System.out.println("{][][]"+ clearBeforeDayIndex);
changeViewSummary();
dialog.dismiss();
return true; // allow selection
}
})
// .positiveText(R.string.choose_label)
.show();
}
@OnClick(R.id.setting_about) void showAbout() {
new MaterialDialog.Builder(this)
.title(R.string.setting_about_dialog_title)
.content(R.string.setting_about_dialog_content)
.positiveText(R.string.agree)
.negativeText(R.string.disagree)
.positiveColorRes(R.color.material_red_400)
.negativeColorRes(R.color.material_red_400)
.titleGravity(GravityEnum.CENTER)
.titleColorRes(R.color.material_red_400)
.contentColorRes(android.R.color.white)
.backgroundColorRes(R.color.material_blue_grey_800)
.dividerColorRes(R.color.material_teal_a400)
.btnSelector(R.drawable.md_btn_selector_custom, DialogAction.POSITIVE)
.positiveColor(Color.WHITE)
.negativeColorAttr(android.R.attr.textColorSecondaryInverse)
.theme(Theme.DARK)
.show();
}
@OnClick(R.id.setting_clear_log_button) void clearLog() {
WithDB.getInstance().delRequestListAll();
}
private void initToolbar() {
toolbar = (Toolbar) findViewById(R.id.setting_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true); // 这个小于4.0版本是默认为true,在4.0及其以上是false。该方法的作用:决定左上角的图标是否可以点击(没有向左的小图标),true 可点
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // 决定左上角图标的左侧是否有向左的小箭头,true 有小箭头
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.setOnClickListener(this);
// setDisplayShowHomeEnabled(true) //使左上角图标是否显示,如果设成false,则没有程序图标,仅仅就个标题,否则,显示应用程序图标,对应id为android.R.id.home,对应ActionBar.DISPLAY_SHOW_HOME
// setDisplayShowCustomEnabled(true) // 使自定义的普通View能在title栏显示,即actionBar.setCustomView能起作用,对应ActionBar.DISPLAY_SHOW_CUSTOM
}
}
<file_sep>package me.wizos.loread.view;
import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AbsListView;
/**
* Created by Wizos on 2016/3/30.
*/
public class SwipeRefresh extends SwipeRefreshLayout {
private View view;
public SwipeRefresh(Context context) {
super(context);
}
public SwipeRefresh(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setViewGroup(View view) {
this.view = view;
}
@Override
public boolean canChildScrollUp() {
if (view != null && view instanceof AbsListView) {
final AbsListView absListView = (AbsListView) view;
return absListView.getChildCount() > 0
&& (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
.getTop() < absListView.getPaddingTop());
}
return super.canChildScrollUp();
}
/**
* 自从Google推出SwipeRefreshLayout后相信很多人都开始使用它来实现listView的下拉刷新了
* 但是在使用的时候,有一个很有趣的现象,当SwipeRefreshLayout只有listview一个子view的时候是没有任何问题的
* 但如果不是得话就会出现问题了,向上滑动listview一切正常,向下滑动的时候就会出现还没有滑倒listview顶部就触发下拉刷新的动作了
* 看SwipeRefreshLayout源码可以看到在onInterceptTouchEvent里面有这样的一段代码
if (!isEnabled() || mReturningToStart || canChildScrollUp() || mRefreshing) {
// Fail fast if we're not in a state where a swipe is possible
return false;
}
其中有个canChildScrollUp方法,在往下看
public boolean canChildScrollUp() {
if (android.os.Build.VERSION.SDK_INT < 14) {
if (mTarget instanceof AbsListView) {
final AbsListView absListView = (AbsListView) mTarget;
return absListView.getChildCount() > 0
&& (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
.getTop() < absListView.getPaddingTop());
} else {
return ViewCompat.canScrollVertically(mTarget, -1) || mTarget.getScrollY() > 0;
}
} else {
return ViewCompat.canScrollVertically(mTarget, -1);
}
}
决定子view 能否滑动就是在这里了,所以我们只有写一个类继承SwipeRefreshLayout,然后重写该方法即可
*
*/
}
<file_sep>package me.wizos.loread.adapter;
import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import java.util.List;
import me.wizos.loread.App;
import me.wizos.loread.R;
import me.wizos.loread.bean.Article;
import me.wizos.loread.gson.itemContents.Origin;
import me.wizos.loread.net.API;
import me.wizos.loread.utils.UTime;
/**
* Created by Wizos on 2016/3/15.
*/
public class MainSlvAdapter extends ArrayAdapter<Article> {
public MainSlvAdapter(Context context, List<Article> itemArray){
super(context, 0 , itemArray);
this.articleList = itemArray;
this.context = context;
}
// public MainSlvAdapter(Context context, int textViewResourceId, List<Article> itemArray){
// super(context, textViewResourceId, itemArray);
// this.articleList = itemArray;
// this.context = context;
// }
List<Article> articleList;
Context context;
@Override
public int getCount() {
return articleList.size();
}
@Override
public Article getItem(int position) {
return articleList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
CustomViewHolder cvh;
Article article = this.getItem(position);
if (convertView == null) {
cvh = new CustomViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.articleslv_item, null);
cvh.articleTitle = (TextView) convertView.findViewById(R.id.articleslv_item_title);
cvh.articleSummary = (TextView) convertView.findViewById(R.id.articleslv_item_summary);
cvh.articleFeed = (TextView) convertView.findViewById(R.id.articleslv_item_author);
cvh.articleImg = (ImageView) convertView.findViewById(R.id.articleslv_item_img);
cvh.articleTime = (TextView) convertView.findViewById(R.id.articleslv_item_time);
cvh.articleStar = (ImageView)convertView.findViewById(R.id.articleslv_item_star);
cvh.articleReading = (ImageView)convertView.findViewById(R.id.articleslv_item_reading);
convertView.setTag(cvh);
} else {
cvh = (CustomViewHolder) convertView.getTag();
}
cvh.articleTitle.setText(Html.fromHtml(article.getTitle()));
String summary = article.getSummary();
if(summary!=null){
cvh.articleSummary.setText(summary);
}
// Bitmap bitmap = UFile.getBitmap(article.getCoverSrc());
// if(bitmap!=null){
if(article.getCoverSrc()!=null){
cvh.articleImg.setVisibility(View.VISIBLE);
// cvh.articleImg.setImageBitmap(bitmap);
Glide.with(context).load(article.getCoverSrc()).centerCrop().into(cvh.articleImg);
}else {
cvh.articleImg.setVisibility(View.GONE);
}
Gson gson = new Gson();
Origin origin = gson.fromJson(article.getOrigin(), Origin.class);
cvh.articleFeed.setText(Html.fromHtml(origin.getTitle()));
cvh.articleTime.setText(UTime.formatDate(article.getCrawlTimeMsec()));
if (article.getReadState().equals(API.ART_READ)) {
// System.out.println("【1】" + article.getTitle());
cvh.articleTitle.setAlpha(0.50f);
cvh.articleTitle.setTextColor(App.getInstance().getResources().getColor(R.color.main_grey_light));
cvh.articleSummary.setAlpha(0.50f);
cvh.articleSummary.setTextColor(App.getInstance().getResources().getColor(R.color.main_grey_light));
} else {
// System.out.println("【2】" + article.getTitle());
cvh.articleTitle.setAlpha(0.90f);
cvh.articleTitle.setTextColor(App.getInstance().getResources().getColor(R.color.main_grey_dark));
cvh.articleSummary.setAlpha(0.65f);
cvh.articleSummary.setTextColor(App.getInstance().getResources().getColor(R.color.main_grey_dark));
}
if( article.getReadState().equals(API.ART_READING)){
cvh.articleReading.setVisibility(View.VISIBLE);
}else {
cvh.articleReading.setVisibility(View.GONE);
}
if (article.getStarState().equals(API.ART_STAR)) {
cvh.articleStar.setVisibility(View.VISIBLE);
}else {
cvh.articleStar.setVisibility(View.GONE);
}
// System.out.println("【MainSlvAdapter】" + article.getTitle() + article.getCategories());
return convertView;
}
class CustomViewHolder {
public TextView articleTitle;
public TextView articleSummary;
public TextView articleFeed;
public TextView articleTime;
public ImageView articleStar;
public ImageView articleReading;
public ImageView articleImg;
}
}
<file_sep>package me.wizos.loread.net;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import com.socks.library.KLog;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import me.wizos.loread.bean.RequestLog;
import me.wizos.loread.gson.SrcPair;
import me.wizos.loread.utils.HttpUtil;
import me.wizos.loread.utils.UFile;
import me.wizos.loread.utils.UString;
/**
* Created by Wizos on 2016/3/10.
*/
public class Neter {
public Handler handler;
private Context context;
public Neter(Handler handler ,Context context) {
KLog.i("【Neter构造函数】" + handler );
this.handler = handler;
this.context = context;
}
public static boolean isWifiEnabled(Context context) {
if (!isNetworkEnabled(context)) {
return false;
}
return ((WifiManager) context.getSystemService(Context.WIFI_SERVICE)).isWifiEnabled();
}
public static boolean isNetworkEnabled(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
/**
* 网络请求的结口分 3 层
* 1,是最明确的,预置好参数的特制 getXX,postXX
* 2,是仅预置好 AppId AppKey 的 getWithAuth , postWithAuth
* 3,是最基本的 get post 方法,不带有参数
*/
public void getUnReadRefs(final String url,long mUserID){
addHeader("n","160");
addHeader("ot","0");
addHeader("xt","user/"+ mUserID+"/state/com.google/read");
addHeader("s", "user/" + mUserID + "/state/com.google/reading-list");
getWithAuth(url);
}
public void getStarredRefs(final String url,long mUserID){
addHeader("n","160");
addHeader("ot","0");
addHeader("s", "user/" + mUserID + "/state/com.google/starred");
getWithAuth(url);
}
public void getStarredContents(){
addHeader("n","20");
addHeader("ot", "0");
getWithAuth(API.U_STREAM_CONTENTS + API.U_STARRED);
}
// public void postArticle( List<String> articleIDList ){
// addBody("i", articleID);
// long logTime = System.currentTimeMillis();
// logRequest(API.U_EDIT_TAG, "post", logTime, headParamList, bodyParamList);
// postWithAuth(API.U_ARTICLE_CONTENTS,logTime);
// }
public void postArticleContents( String articleID ){
addBody("i", articleID);
postWithAuthLog(API.U_EDIT_TAG);
}
public void postUnReadArticle( String articleID ){
addBody("r", "user/-/state/com.google/read");
addBody("i", articleID);
postWithAuthLog(API.U_EDIT_TAG);
KLog.d("【post】1记录 "+ headParamList.size());
}
public void postReadArticle( String articleID ){
addBody("a", "user/-/state/com.google/read");
addBody("i", articleID);
postWithAuthLog(API.U_EDIT_TAG);
KLog.d("【post】2记录 "+ headParamList.size());
}
public void postUnStarArticle( String articleID ){
addBody("r", "user/-/state/com.google/starred");
addBody("i", articleID);
postWithAuthLog(API.U_EDIT_TAG);
}
public void postStarArticle( String articleID ){
addBody("a", "user/-/state/com.google/starred");
addBody("i", articleID);
postWithAuthLog(API.U_EDIT_TAG);
}
// //测试之用
// public void getWithAuth3(String url, long logCode) {
// KLog.d("【执行 getWithAuth 1 】" + url);
// if(!isNetworkEnabled(context)){
// handler.sendEmptyMessage(55);
// return;}
// Request.Builder builder = new Request.Builder();
// builder.url(url);
// addHeader("Authorization", API.INOREADER_ATUH);
// addHeader("AppId", API.INOREADER_APP_ID);
// addHeader("AppKey", API.INOREADER_APP_KEY);
// for ( Parameter para : headParamList) {
// builder.addHeader( para.getKey() , para.getValue() );
// }
// headParamList.clear();
// Request request = builder.build();
// forData(url, request,logCode);
// }
public void getWithAuth(String url) {
KLog.d("【执行 getWithAuth 】" + url);
if(!isNetworkEnabled(context)){
headParamList.clear();
handler.sendEmptyMessage(55);
return;}
Request.Builder builder = new Request.Builder();
String paraString = "?";
for ( String[] param : headParamList) {
paraString = paraString + param[0] + "=" + param[1] + "&";
}
headParamList.clear(); // headParamList = new ArrayList<>();
if (paraString.equals("?")) {
paraString = "";
}
url = url + paraString;
builder.url(url)
.addHeader("Authorization", API.INOREADER_ATUH)
.addHeader("AppId", API.INOREADER_APP_ID)
.addHeader("AppKey", API.INOREADER_APP_KEY);
Request request = builder.build();
forData(url, request,0);
}
public void postWithAuthLog(final String url) {
addHeader("AppId", API.INOREADER_APP_ID);
addHeader("AppKey", API.INOREADER_APP_KEY);
addHeader("Authorization", API.INOREADER_ATUH);
long logTime = System.currentTimeMillis();
toRequest(API.U_EDIT_TAG, "post", logTime, headParamList, bodyParamList);
post(url,logTime);
}
public void postWithAuth(final String url) {
addHeader("AppId", API.INOREADER_APP_ID);
addHeader("AppKey", API.INOREADER_APP_KEY);
addHeader("Authorization", API.INOREADER_ATUH);
post(url,System.currentTimeMillis());
}
public void post(final String url, long logTime) { // just for login
KLog.d("【执行 = " + url + "】");
if(!isNetworkEnabled(context)){
headParamList.clear();
bodyParamList.clear();
handler.sendEmptyMessage(55);
return;}
// 构建请求头
Request.Builder headBuilder = new Request.Builder().url(url);
// for ( Parameter para : headParamList) {
// headBuilder.addHeader(para.getKey(), para.getValue());
// }
for ( String[] param : headParamList) {
headBuilder.addHeader( param[0], param[1] );
}
headParamList.clear();
// 构建请求体
FormEncodingBuilder bodyBuilder = new FormEncodingBuilder();
for ( String[] param : bodyParamList ) {
bodyBuilder.add( param[0], param[1] );
KLog.d("【2】" + param[0] + param[1]);
}
bodyParamList.clear();
RequestBody body = bodyBuilder.build();
Request request = headBuilder.post(body).build();
forData(url, request,logTime);
}
public void forData(final String url, final Request request ,final long logTime) {
if( !isNetworkEnabled(context) ){
handler.sendEmptyMessage(55);
return ;}
KLog.d("【开始请求】 "+ logTime + "--" + url);
new Thread(new Runnable() {
@Override
public void run() {
HttpUtil.enqueue(request, new Callback() {
@Override
public void onFailure(Request request, IOException e) {
KLog.d("【请求失败】" + url + request.body().toString());
API.request = request;
makeMsg(url, "noRequest",logTime);
}
@Override
public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) {
KLog.d("【响应失败】" + response);
API.request = request;
makeMsg(url, "noResponse",logTime);
return;
}
try {
String res = response.body().string();
KLog.d("【forData】" + res.length());
makeMsg(url, res,logTime);
}catch (IOException e){
KLog.d("【超时】");
API.request = request;
makeMsg(url, "noResponse", logTime);
e.printStackTrace();
}
// catch (SocketTimeoutException e) {
// KLog.d("【超时】");
// API.request = request;
// makeMsg(url, "noResponse", logTime);
// e.printStackTrace();
// }
}
});
}
}).start();
}
private void makeMsg(String url, String res , long logTime) {
Message message = new Message();
Bundle bundle = new Bundle();
bundle.putString("url", url);
bundle.putLong("logTime",logTime);
// 有些可能 url 一样,但头部不一样。而我又是靠 url 来区分请求,从而进行下一步的。
if (res.equals("noRequest")) {
message.what = API.FAILURE_Request;
} else if (res.equals("noResponse")) {
message.what = API.FAILURE_Response;
} else {
bundle.putString("res", res);
message.what = API.url2int(url);
}
message.setData(bundle);
handler.sendMessage(message);
KLog.d("【getData】" + url + " -- "+ res );
}
// public interface Call{
// void onSuccess(long logTime);
// }
// public void post(final String url,final long logTime,final Call call) { // just for login
// KLog.d("【执行 = " + url + "】");
// if(!isNetworkEnabled(context)){
// headParamList.clear();
// bodyParamList.clear();
// handler.sendEmptyMessage(55);
// return;}
// // 构建请求头
// Request.Builder headBuilder = new Request.Builder().url(url);
// for ( Parameter para : headParamList) {
// headBuilder.addHeader(para.getKey(), para.getValue());
// }
// headParamList.clear();
//
// // 构建请求体
// FormEncodingBuilder bodyBuilder = new FormEncodingBuilder();
// for ( Parameter para : bodyParamList ) {
// bodyBuilder.add( para.getKey(), para.getValue());
// }
// bodyParamList.clear();
//
// RequestBody body = bodyBuilder.build();
// final Request request = headBuilder.post(body).build();
//
// if( !isNetworkEnabled(context) ){
// handler.sendEmptyMessage(55);
// return ;}
// KLog.d("【开始请求】 "+ logTime + url);
//
// new Thread(new Runnable() {
// @Override
// public void run() {
// HttpUtil.enqueue(request, new Callback() {
// @Override
// public void onFailure(Request request, IOException e) {
// KLog.d("【请求失败】" + url );
// API.request = request;
// makeMsg(url, "noRequest",logTime);
// }
// @Override
// public void onResponse(Response response) throws IOException {
// if (!response.isSuccessful()) {
// KLog.d("【响应失败】" + response);
// API.request = request;
// makeMsg(url, "noResponse",logTime);
// return;
// }
// try {
// String res = response.body().string();
// call.onSuccess(logTime);
// makeMsg(url, res,logTime);
// }catch (SocketTimeoutException e) {
// KLog.d("【超时】");
// API.request = request;
// makeMsg(url, "noResponse", logTime);
// e.printStackTrace();
// }
//
// }
// });
// }
// }).start();
// }
// public static class Builder {
// private ArrayList<String[]> headParamList;
// private ArrayList<String[]> bodyParamList;
// private Parameter parameter;
//
// public Builder(ArrayList<String[]> headParams,ArrayList<String[]> bodyParams){
// headParamList = headParams;
// bodyParamList = bodyParams;
// }
// public Builder addHeader(ArrayList<String[]> params){
// headParamList.addAll(params);
// return this;
// }
// public Builder addHeader(String[] params){
// headParamList.add(params);
// return this;
// }
// public Builder addHeader(String key ,String value){
// String[] params = new String[2];
// params[0] = key;
// params[1] = value;
// headParamList.add(params);
// return this;
// }
// public Builder addBody(ArrayList<String[]> params){
// bodyParamList.addAll(params);
// return this;
// }
// public Builder addBody(String[] params){
// bodyParamList.add(params);
// return this;
// }
// public Builder addBody(String key ,String value){
// String[] params = new String[2];
// params[0] = key;
// params[1] = value;
// bodyParamList.add(params);
// return this;
// }
// public ArrayList<ArrayList> build() {
// ArrayList<ArrayList> arrayList = new ArrayList<>();
// arrayList.add(headParamList);
// arrayList.add(bodyParamList);
// return arrayList;
// }
// }
// private ArrayList<Parameter> headParamList = new ArrayList<>();
// private ArrayList<Parameter> bodyParamList = new ArrayList<>();
// private ArrayList<String[]> paramList = new ArrayList<>();
private ArrayList<String[]> headParamList = new ArrayList<>();
private ArrayList<String[]> bodyParamList = new ArrayList<>();
private Parameter parameter;
public void addHeader(String key ,String value){
// parameter = new Parameter(key,value);
// headParamList.add(parameter);
String[] params = new String[2];
params[0] = key;
params[1] = value;
headParamList.add(params);
}
public void addHeader(ArrayList<String[]> params){
headParamList.addAll(params);
}
public void addHeader(String[] params){
headParamList.add(params);
}
public void addBody(String key ,String value){
// parameter = new Parameter(key,value);
// bodyParamList.add(parameter);
String[] params = new String[2];
params[0] = key;
params[1] = value;
bodyParamList.add(params);
}
public void addBody(ArrayList<String[]> params){
bodyParamList.addAll(params);
}
private class Parameter {
private String key;
private String value;
Parameter(String key, String value){
this.key = key;
this.value = value;
}
public void setKey(String key){
this.key = key;
}
public String getKey(){
return key;
}
public void setValue(String value){
this.value = value;
}
public String getValue(){
return value;
}
}
public void toRequest(String url, String method, long logTime, ArrayList<String[]> headParamList, ArrayList<String[]> bodyParamList){
String headParamString = UString.formParamListToString(headParamList);
String bodyParamString = UString.formParamListToString(bodyParamList);
RequestLog requests = new RequestLog(logTime,url,method,headParamString,bodyParamString);
if(logRequest==null){return;}
logRequest.add(requests);
}
// private void toRequest(String url, String method,long logTime, ArrayList<Parameter> headParamList, ArrayList<Parameter> bodyParamList){
//// String file = "{\n\"items\": [{\n\"url\": \"" + url + "\",\n\"method\": \"" + method + "\",";
//
// StringBuilder sbHead = new StringBuilder("");
// StringBuilder sbBody = new StringBuilder("");
// if( headParamList!=null){
// if(headParamList.size()!=0){
// for(Parameter param:headParamList){
// sbHead.append(param.getKey() + ":" + param.getValue() + ",");
// }
// sbHead.deleteCharAt(sbHead.length() - 1);
// }
// }
// if( bodyParamList!=null ){
// if( bodyParamList.size()!=0 ){
// for(Parameter param:bodyParamList){
// sbBody.append(param.getKey() + ":" + param.getValue() + ",");
// }
// sbBody.deleteCharAt(sbBody.length() - 1);
// }
// }
// RequestLog requests = new RequestLog(url,method,logTime,sbHead.toString(),sbBody.toString());
// logRequest.addRequest(requests);
// KLog.d("【添加请求1】" + sbHead.toString());
// KLog.d("【添加请求2】" + sbBody.toString());
// }
public void setLogRequestListener(Loger logRequest) {
this.logRequest = logRequest;
}
private Loger logRequest ;
public interface Loger<T> {
void add(T entry);
void del(long index);
}
public int getBitmapList(ArrayList<SrcPair> imgSrcList){
if(!isWifiEnabled(context)){
handler.sendEmptyMessage(55);
return 0;}
if(imgSrcList == null || imgSrcList.size()==0){
return 0;
}
int num = imgSrcList.size();
for(int i=0;i<num;i++){
getBitmap(imgSrcList.get(i).getNetSrc(), imgSrcList.get(i).getLocalSrc(), i );
}
return num;
}
public void getBitmap(final String url ,final String filePath ,final int imgNum) {
KLog.d("【获取图片 " + url + "】" + filePath );
Request.Builder builder = new Request.Builder();
builder.url(url);
Request request = builder.build();
HttpUtil.enqueue(request, new Callback() {
@Override
public void onFailure(Request request, IOException e) {
KLog.d("【图片请求失败 = " + url + "】");
makeMsgForImg(url, filePath ,imgNum );
}
@Override
public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) {
KLog.d("【图片响应失败】" + response);
makeMsgForImg(url, filePath ,imgNum);
return;
}
inputStream = response.body().byteStream();
// 得到响应内容的文件格式
// String fileTypeInResponse = "";
// MediaType mediaType = response.body().contentType();
// if (mediaType != null) {
// fileTypeInResponse = "." + mediaType.subtype();
// }
try {
UFile.saveFromStream(inputStream, filePath);
} catch (IOException e) {
e.printStackTrace();
}
KLog.d("【成功保存图片】" + url + "==" + filePath);
makeMsgForImg(url, filePath,imgNum);
}
});
}
public static InputStream inputStream;
private void makeMsgForImg(String url,String filePath ,int imgNum){
Message message = new Message();
Bundle bundle = new Bundle();
bundle.putString("url", url);
bundle.putString("filePath", filePath);
bundle.putInt("imgNum", imgNum);
message.what = API.S_BITMAP;
if(url != null){ message.what = API.F_BITMAP;}
message.setData(bundle);
handler.sendMessage(message);
}
// public void downImg(String url,String filePath ,final int imgNum){
// String path = filePath.substring(filePath.lastIndexOf(File.separator));
// String name = filePath.substring(filePath.lastIndexOf(File.separator),filePath.length());
// OkHttpUtils
// .get()
// .url(url)
// .build()
// .execute(new FileCallBack(path, name)//
// {
// @Override
// public void inProgress(float progress, long f) {
// }
//
// @Override
// public void onError(Call xx, Exception e) {
// }
//
// @Override
// public void onResponse(File file) {
// makeMsgForImg(null, null, imgNum);
// }
// });
// }
}
<file_sep>package me.wizos.loread.activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.text.Spanned;
import android.view.View;
import android.view.ViewConfiguration;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import com.blueware.agent.android.util.OneapmWebViewClient;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.socks.library.KLog;
import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import me.wizos.loread.App;
import me.wizos.loread.R;
import me.wizos.loread.bean.Article;
import me.wizos.loread.data.WithDB;
import me.wizos.loread.gson.SrcPair;
import me.wizos.loread.net.API;
import me.wizos.loread.net.Neter;
import me.wizos.loread.net.Parser;
import me.wizos.loread.utils.UFile;
import me.wizos.loread.utils.UString;
import me.wizos.loread.utils.UTime;
import me.wizos.loread.utils.UToast;
public class ArticleActivity extends BaseActivity {
protected static final String TAG = "ArticleActivity";
protected WebView webView; // implements Html.ImageGetter
protected Context context;
protected Neter mNeter;
protected Parser mParser;
protected TextView vTitle ,vDate ,vTime ,vFeed;
protected ImageView vStar , vRead;
protected NestedScrollView vScrolllayout ;
protected TextView vArticleNum;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_article);
context = this;
App.addActivity(this);
mNeter = new Neter(handler,this);
// mNeter.setLogRequestListener(this);
mParser = new Parser();
initView();
initData();
}
@Override
protected void onResume(){
super.onResume();
}
@Override
protected Context getActivity(){
return context;
}
public String getTAG(){
return TAG;
}
// protected String webUrl;
private void initView() {
initToolbar();
initWebView();
vTitle = (TextView) findViewById(R.id.article_title);
vDate = (TextView) findViewById(R.id.article_date);
// vTime = (TextView) findViewById(R.id.article_time);
vFeed = (TextView) findViewById(R.id.article_feed);
vStar = (ImageView) findViewById(R.id.art_star);
vRead = (ImageView) findViewById(R.id.art_read);
vArticleNum = (TextView)findViewById(R.id.article_num);
vScrolllayout = (NestedScrollView) findViewById(R.id.art_scroll);
}
private void initToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.art_toolbar);
setSupportActionBar(toolbar); // ActionBar
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.setOnClickListener(this);
// Make arrow color white
// Drawable upArrow = getResources().getDrawable(R.drawable.mz_ic_sb_back);
// upArrow.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
// getSupportActionBar().setHomeAsUpIndicator(upArrow); // 替换返回箭头
}
private void initWebView(){
webView = (WebView) findViewById(R.id.article_content);
WebSettings webSettings = webView.getSettings();
webSettings.setUseWideViewPort(false);// 设置此属性,可任意比例缩放
webSettings.setDisplayZoomControls(false); //隐藏webview缩放按钮
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); // 就是这句使自适应屏幕
webSettings.setLoadWithOverviewMode(true);// 缩放至屏幕的大小
// setOneapmWebViewWatch();
}
/**
* 为了监控 webView 的性能
*/
private void setOneapmWebViewWatch(){
OneapmWebViewClient client = new OneapmWebViewClient( webView){
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
};
webView.setWebViewClient(client);
}
protected String articleID="";
private int numOfImgs,numOfGetImgs = 0 ,numOfFailureImg = 0 ,numOfFailure = 0 ,numOfFailures = 4;
private String showContent = "";
private Article article;
protected int articleNum,articleCount;
private void initData(){
articleID = getIntent().getExtras().getString("articleID");
articleNum = getIntent().getExtras().getInt("articleNum");
articleCount = getIntent().getExtras().getInt("articleCount");
article = WithDB.getInstance().getArticle(articleID);
KLog.d("【article】" + articleID);
if ( article == null ){ KLog.d("【article为空】");return; }
String webUrl = article.getCanonical();
sReadState = article.getReadState();
sStarState = article.getStarState();
Spanned titleWithUrl = Html.fromHtml("<a href=\"" + webUrl +"\">" + article.getTitle() + "</a>");
vTitle.setText( titleWithUrl );
vDate.setText(UTime.formatDate(article.getCrawlTimeMsec()));
// vFeed.setText(article.getFeed().getTitle());
// articleID = article.getId();
numOfGetImgs = 0;
String fileNameInMD5 = UString.stringToMD5(articleID);
String content = UFile.readHtml( fileNameInMD5 );
KLog.d( "【article状态为】" + sReadState + titleWithUrl );
String imgState = article.getImgState();// 读取失败 imgSrc 的字段 , 如果读取的为 ok 代表加载完成,如果为空 or "" ,代表要提取正文与srcList加载图片 ,content
String cssFileName = "normalize.css";
String folderAbsolutePath = "file:"+ File.separator + File.separator + getExternalFilesDir(null)+ File.separator + "config" + File.separator;
String cssPath = folderAbsolutePath + cssFileName;
if(!UFile.isFileExists(cssPath)){
cssPath = "file:///android_asset/" + cssFileName;
KLog.d("自定义的 css 文件不存在");
}
String contentHeader = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head>" + "<link rel=\"stylesheet\" href=\"" + cssPath +"\" type=\"text/css\"/>" + "</head><body>";
String contentFooter = "</body></html>";
if(UString.isBlank(content)){
KLog.d( "【文章内容被删,再去加载获取内容】" + webUrl);
mNeter.postArticleContents(articleID);
}else {
if( imgState == null){
KLog.d( "【imgState为null】" + webUrl);
StringAndList htmlAndSrcList = getSrcListAndNewHtml(content, fileNameInMD5);
if( htmlAndSrcList!= null){
srcList = htmlAndSrcList.getList();
content = htmlAndSrcList.getString();
if( srcList!=null && srcList.size()!=0){
KLog.d( "【srcList】" + srcList.size());
article.setCoverSrc(srcList.get(0).getLocalSrc());
KLog.d(srcList.get(0).getLocalSrc());
}
}
}else if(imgState.equals("OK")){
}else {
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<SrcPair>>() {}.getType();
srcList = gson.fromJson(imgState, type);
}
showContent = contentHeader + content + contentFooter;
numOfImgs = mNeter.getBitmapList(srcList);
// vArticleNum.setText(String.valueOf(articleNum) + " / " + String.valueOf(articleCount));
vArticleNum.setText( fileNameInMD5.substring(0,10) ); // FIXME: 2016/5/3 测试
webView.loadDataWithBaseURL(null, showContent , "text/html", "utf-8", null);
}
initStateView();
}
private void initStateView(){
if(sReadState.equals(API.ART_UNREAD)) {
vRead.setImageDrawable(getDrawable(R.drawable.ic_vector_all));
sReadState = API.ART_READ;
article.setReadState(API.ART_READ);
WithDB.getInstance().saveArticle(article);
mNeter.postReadArticle(articleID);
KLog.d("【 ReadState 】" + WithDB.getInstance().getArticle(articleID).getReadState());
}else if(sReadState.equals(API.ART_READ)){
vRead.setImageDrawable(getDrawable(R.drawable.ic_vector_all));
}else if(sReadState.equals(API.ART_READING)){
vRead.setImageDrawable(getDrawable(R.drawable.ic_vector_unread));
}
if(sStarState.equals(API.ART_UNSTAR)){
vStar.setImageDrawable(getDrawable(R.drawable.ic_vector_unstar));
} else {
vStar.setImageDrawable(getDrawable(R.drawable.ic_vector_star));
}
}
@Override
protected void notifyDataChanged(){
if(showContent==null || showContent.equals("")){
KLog.d("【重载 initData 】" );
initData();
}else {
webView.loadDataWithBaseURL(null, showContent, "text/html", "utf-8", null); // contentView.reload();这种刷新方法无效
KLog.d("【重载】");
}
}
protected Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
String info = msg.getData().getString("res");
String url = msg.getData().getString("url");
String filePath ="";
int imgNum;
KLog.d("【handler】" + msg.what + handler + url );
switch (msg.what) {
case API.S_EDIT_TAG:
long logTime = msg.getData().getLong("logTime");
// del(logTime);
if(!info.equals("OK")){
mNeter.forData(url,API.request,logTime);
KLog.d("【返回的不是 ok");
}
break;
case API.S_ARTICLE_CONTENTS:
mParser.parseArticleContents(info);
notifyDataChanged(); // 通知内容重载
break;
case API.S_BITMAP:
imgNum = msg.getData().getInt("imgNum");
numOfGetImgs = numOfGetImgs + 1;
srcList.remove(imgNum);
KLog.i("【 API.S_BITMAP 】" + numOfGetImgs + "--" + numOfImgs);
if( numOfImgs == numOfGetImgs || numOfGetImgs % 5 == 0) {
KLog.i("【 重新加载 webView 】" + numOfGetImgs % 5 );
logSrcList("OK");
notifyDataChanged();
}
break;
case API.F_BITMAP:
imgNum = msg.getData().getInt("imgNum");
numOfFailureImg = numOfFailureImg + 1;
if ( numOfFailureImg > numOfFailures ){
numOfGetImgs = numOfImgs-1;
handler.sendEmptyMessage(API.S_BITMAP);
break;
}
if (numOfFailureImg == 1){
url = UFile.reviseSrc(url);
}
filePath = msg.getData().getString("filePath");
mNeter.getBitmap(url, filePath, imgNum);
break;
case API.FAILURE_Request:
case API.FAILURE_Response:
numOfFailure = numOfFailure + 1;
if (numOfFailure > 4){break;}
mNeter.forData(url,API.request,0);
// logSrcList();
break;
case 55:
logSrcList();
KLog.i("【网络不好,中断】");
break;
}
return false;
}
});
private ArrayList<SrcPair> srcList = new ArrayList<>();
private String sReadState= "";
private String sStarState= "";
protected void logSrcList(){
logSrcList("");
}
private void logSrcList(String json){
if (srcList==null){return;}
if (srcList.size()!=0){
Gson gson = new Gson();
json = gson.toJson(srcList);
}
KLog.d( "【 logSrcList =】" + json );
article.setImgState( json );
WithDB.getInstance().saveArticle(article);
}
private StringAndList getSrcListAndNewHtml(String oldHtml,String fileNameInMD5) {
if (UString.isBlank(oldHtml))
return null;
int num = 0;
StringBuilder tempHtml = new StringBuilder(oldHtml);
String netSrc,fileType,localSrc,loadSrc,temp;
ArrayList<SrcPair> srcInLocalNetArray = new ArrayList<>();
int indexA = tempHtml.indexOf("<img ", 0);
while (indexA != -1) {
indexA = tempHtml.indexOf(" src=\"", indexA);
if(indexA == -1){break;}
int indexB = tempHtml.indexOf("\"", indexA + 6);
if(indexB == -1){break;}
netSrc = tempHtml.substring( indexA + 6, indexB );
fileType = UFile.getFileExtByUrl(netSrc);
KLog.d("【文章13】" + fileType );
num++;
localSrc = App.cacheAbsolutePath + fileNameInMD5 + File.separator + fileNameInMD5 + "_files" + File.separator + fileNameInMD5 + "_" + num + fileType + API.MyFileType;
loadSrc = App.cacheRelativePath + fileNameInMD5 + File.separator + fileNameInMD5 + "_files" + File.separator + fileNameInMD5 + "_" + num + fileType + API.MyFileType;
temp = " src=\"" + localSrc + "\"" + " netsrc=\"" + netSrc + "\"";
tempHtml = tempHtml.replace( indexA, indexB+1, temp ) ;
srcInLocalNetArray.add(new SrcPair( netSrc,loadSrc ));
indexB = indexA + 6 + localSrc.length() + netSrc.length() + 10;
indexA = tempHtml.indexOf("<img ", indexB);
}
if(srcInLocalNetArray.size()==0){return null;}
showContent = tempHtml.toString();
StringAndList htmlAndImgSrcList = new StringAndList();
htmlAndImgSrcList.setList(srcInLocalNetArray);
htmlAndImgSrcList.setString( showContent );
UFile.saveHtml( fileNameInMD5, showContent );
KLog.d("【文章2】" + showContent);
return htmlAndImgSrcList;
}
private class StringAndList {
private String string;
private ArrayList<SrcPair> list;
private void setString(String string){
this.string = string;
}
private String getString(){
return string;
}
private void setList(ArrayList<SrcPair> list){
this.list = list;
}
private ArrayList<SrcPair> getList(){
return list;
}
}
private static final int MSG_DOUBLE_TAP = 0;
private Handler mHandler = new Handler();
@Override
public void onClick(View v) {
KLog.d( "【 toolbar 是否双击 】" );
switch (v.getId()) {
case R.id.article_num:
case R.id.art_toolbar:
if (mHandler.hasMessages(MSG_DOUBLE_TAP)) {
mHandler.removeMessages(MSG_DOUBLE_TAP);
vScrolllayout.smoothScrollTo(0, 0);
} else {
mHandler.sendEmptyMessageDelayed(MSG_DOUBLE_TAP, ViewConfiguration.getDoubleTapTimeout());
}
break;
}
}
public void onReadClick(View view){
if(sReadState.equals(API.ART_READ)){
changeReadIcon(API.ART_UNREAD);
UToast.showShort("未读");
}else {
changeReadIcon(API.ART_READ);
UToast.showShort("已读");
}
}
public void onStarClick(View view){
if(sStarState.equals(API.ART_UNSTAR)){
changeStarState(API.ART_STAR);
UToast.showShort("已收藏");
}else {
changeStarState(API.ART_UNSTAR);
UToast.showShort("取消收藏");
}
}
private void changeReadIcon(String iconState){
sReadState = iconState; // 在使用过程中,只会 涉及 read 与 reading 的转换。unread 仅作为用户未主动修改文章状态是的默认状态,reading 不参与勾选为已读
if(iconState.equals(API.ART_READ)){
vRead.setImageDrawable(getDrawable(R.drawable.ic_vector_all));
article.setReadState(API.ART_READ);
WithDB.getInstance().saveArticle(article);
mNeter.postReadArticle(articleID);
KLog.d("【 标为已读 】");
}else {
vRead.setImageDrawable(getDrawable(R.drawable.ic_vector_unread));
article.setReadState(API.ART_READING);
WithDB.getInstance().saveArticle(article);
mNeter.postUnReadArticle(articleID);
KLog.d("【 标为未读 】");
}
}
private void changeStarState(String iconState){
sStarState = iconState;
if(iconState.equals(API.ART_STAR)){
vStar.setImageDrawable(getDrawable(R.drawable.ic_vector_star));
article.setStarState(API.ART_STAR);
WithDB.getInstance().saveArticle(article);
mNeter.postStarArticle(articleID);
}else {
vStar.setImageDrawable(getDrawable(R.drawable.ic_vector_unstar));
article.setStarState(API.ART_UNSTAR);
WithDB.getInstance().saveArticle(article);
mNeter.postUnStarArticle(articleID);
}
}
}
<file_sep>package me.wizos.loread.net;
import com.squareup.okhttp.Request;
import java.util.ArrayList;
import me.wizos.loread.gson.Item;
/**
* Created by Wizos on 2016/3/5.
*/
public class API {
public static Request request;
public static final String INOREADER_APP_ID = "1000001277";
public static final String INOREADER_APP_KEY = "<KEY>";
public static String INOREADER_ATUH = "";
public static final String INOREADER_BASE_URL = "https://www.inoreader.com/";
public static String U_CLIENTLOGIN ="https://www.inoreader.com/accounts/ClientLogin";
public static String U_USER_INFO ="https://www.inoreader.com/reader/api/0/user-info";
public static String U_TAGS_LIST ="https://www.inoreader.com/reader/api/0/tag/list";
public static String U_STREAM_PREFS ="https://www.inoreader.com/reader/api/0/preference/stream/list";
public static String U_SUSCRIPTION_LIST ="https://www.inoreader.com/reader/api/0/subscription/list";
public static String U_UNREAD_COUNTS ="https://www.inoreader.com/reader/api/0/unread-count";
public static String U_ITEM_IDS ="https://www.inoreader.com/reader/api/0/stream/items/ids";
public static String U_ITEM_CONTENTS ="https://www.inoreader.com/reader/api/0/stream/items/contents";
public static String U_ARTICLE_CONTENTS ="https://www.inoreader.com/reader/api/0/stream/items/contents";
public static String U_EDIT_TAG ="https://www.inoreader.com/reader/api/0/edit-tag";
public static String U_Stream_Contents_Atom ="https://www.inoreader.com/reader/atom";
public static String U_STREAM_CONTENTS ="https://www.inoreader.com/reader/api/0/stream/contents/";
public static String U_Stream_Contents_User ="https://www.inoreader.com/reader/api/0/stream/contents/user/";
public static String U_READING_LIST ="/state/com.google/reading-list";
public static String U_STARRED ="user/-/state/com.google/starred";
public static String U_NO_LABEL ="/state/com.google/no-label";
public static String U_UNREAND ="/state/com.google/unread";
// public static String U_READED ="user/-/state/com.google/read";
// public static String U_BROADCAST ="user/-/state/com.google/broadcast";
// public static String U_LIKED ="user/-/state/com.google/like";
// public static String U_SAVED ="user/-/state/com.google/saved-web-pages";
public static String MyFileType = ".loread";
// public static final int SUCCESS_AUTH = 1;
// public static final int FAILURE_AUTH = 2;
// public static final int SUCCESS_NET = 3;
// public static final int ID_UPDATE_UI = 4;
// public static final int ID_FROM_CACHE = 5;
public static final int M_BEGIN_SYNC = 66;
public static final int S_CLIENTLOGIN = 10;
public static final int S_USER_INFO = 11;
public static final int S_TAGS_LIST = 12;
public static final int S_STREAM_PREFS = 13;
public static final int S_SUBSCRIPTION_LIST = 22;
public static final int S_UNREAD_COUNTS = 23;
public static final int S_ITEM_IDS = 20;
public static final int S_ITEM_IDS_STARRED = 28;
public static final int S_STREAM_CONTENTS_STARRED = 31;
public static final int S_ITEM_CONTENTS = 24;
public static final int S_READING_LIST = 21;
public static final int S_EDIT_TAG = 25;
public static final int S_BITMAP = 26;
public static final int S_Contents = 19;
public static final int S_ARTICLE_CONTENTS = 27;
public static final int S_ALL_STARRED = 30;
public static final int FAILURE = 00;
public static final int FAILURE_Request = 01;
public static final int FAILURE_Response = 02;
public static final int F_BITMAP = 03;
public static ArrayList<Item> itemlist;
public static int url2int(String api){
if (api.equals(U_CLIENTLOGIN)){
return S_CLIENTLOGIN;
}else if(api.equals(U_USER_INFO)){
return S_USER_INFO;
}else if(api.equals(U_STREAM_PREFS)){
return S_STREAM_PREFS;
}else if(api.equals(U_TAGS_LIST)){
return S_TAGS_LIST;
}else if(api.equals(U_SUSCRIPTION_LIST)) {
return S_SUBSCRIPTION_LIST;
}else if(api.contains(U_ITEM_IDS)){
return S_ITEM_IDS;
}else if(api.contains(U_READING_LIST)){
return S_READING_LIST;
}else if(api.equals(U_UNREAD_COUNTS)){
return S_UNREAD_COUNTS;
}else if(api.equals(U_ITEM_CONTENTS)){
return S_ITEM_CONTENTS;
}else if(api.equals(U_ARTICLE_CONTENTS)) {
return S_ARTICLE_CONTENTS;
}else if(api.equals(U_EDIT_TAG)){
return S_EDIT_TAG;
}else if(api.contains(U_STREAM_CONTENTS + U_STARRED)){
return S_STREAM_CONTENTS_STARRED;
}
return FAILURE;
}
/**
* 是否需要改变这个为 int 以方便比较呢?
*/
public static final String ART_READ = "Readed";// 1
public static final String ART_READING = "UnReading"; // 00
public static final String ART_UNREAD = "UnRead"; // 0
public static final String ART_STAR = "Stared"; // 1
public static final String ART_UNSTAR = "UnStar"; // 0
public static final String LIST_ALL = "%";
public static final String LIST_STAR = "Stared";
public static final String LIST_UNREAD = "UnRead";
// public static final String LIST_READ = "Readed";
// public static final String LIST_UNREADING = "UnReading";
// public static final String LIST_UNSTAR = "UnStar";
// public static final String ARTICLE_HEADER = "UnRead";
}
<file_sep>package me.wizos.loread.utils;
import com.socks.library.KLog;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Wizos on 2016/3/16.
*/
public class UString {
public static String toLongID(String id) {
return "tag:google.com,2005:reader/item/0000000"+ Long.toHexString( Long.valueOf(id));
}
/**
* 将字符串转成MD5值
*
* @param string
* @return
*/
public static String stringToMD5(String string) {
byte[] hash;
try {
hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10)
hex.append("0");
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString();
}
// public static String tagIdToName(String content){
// }
public static boolean isBlank(String content){
return content==null || content.isEmpty();
}
public static boolean isBlank(List list){return list==null || list.isEmpty() || list.size()==0;}
public static ArrayList<String[]> asList(String[] array){
if(array==null || array.length==0){return null;}
long xx = System.currentTimeMillis();
ArrayList<String[]> arrayList = new ArrayList<>(array.length);
String[] srcPair;
for(String s:array){
srcPair = s.split("|");
arrayList.add( srcPair );
KLog.d("【测试】" + s );
KLog.d("【测试】" + srcPair[0] );
KLog.d("【测试】" + srcPair[1] );
}
KLog.d("【时间】1测试" + (System.currentTimeMillis() - xx));
return arrayList;
}
public static String[][] asArray(String[] array){
if(array==null || array.length==0){return null;}
long xx = System.currentTimeMillis();
String[][] arrayList = new String[array.length][2];
String[] srcPair;
int num = array.length;
for(int i=0 ; i<num ; i++){
srcPair = array[i].split("|");
arrayList[i] = srcPair;
}
KLog.d("【时间】2测试" + (System.currentTimeMillis() - xx));
return arrayList;
}
public interface Con<V>{
Object inputKey(V key);
}
public static <K,V> List<V> mapToList(Map<K,V> map){
ArrayList<V> list = new ArrayList<>(map.size());
for( Map.Entry<K,V> entry: map.entrySet()) {
list.add(entry.getValue());
}
return list;
}
public static <V> Map<Object,V> listToMap(ArrayList<V> arrayList, Con<? super V> con){
Map<Object,V> map = new HashMap<>(arrayList.size());
for(V item:arrayList){
map.put(con.inputKey(item),item);
}
return map;
}
// public static String beanListSort(ArrayList<Tag> list){
// int listSize = list.size()-1;
// for(int i=0; i<listSize; i++){
// char[] chars1 = list.get(i).getTitle().toCharArray();
// char[] chars2 = list.get(i+1).getTitle().toCharArray();
// int x =0, y=0;
// while (chars1[x]>=chars2[x]){
// if(chars1[x]==chars2[x]){
// x = x + 1;
// }
// }
// }
// }
public static ArrayList<String[]> formStringToParamList(String paramString){
if( paramString == null || isBlank(paramString) ){
return null;
}
String[] paramStringArray = paramString.split("_");
String[] paramPair;
ArrayList<String[]> paramList = new ArrayList<>();
for(String string : paramStringArray){
paramPair = string.split("#");
if(paramPair.length!=2){continue;}
paramList.add(paramPair);
KLog.d("【1】" + paramPair[0] + paramPair[1]);
}
return paramList;
}
public static String formParamListToString(ArrayList<String[]> paramList){
if( paramList==null){
return null;
}
if(paramList.size()==0){
return null;
}
StringBuilder sb = new StringBuilder("");
for( String[] paramPair:paramList){
sb.append(paramPair[0] + "#" + paramPair[1] + "_");
}
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
public static String sort(String str){
char[] charArray = str.toCharArray();
for(int i=0;i<charArray.length;i++){
for(int j=0;j<i;j++){
if(charArray[i]<charArray[j]){
char temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
}
}
}
return String.valueOf(charArray);
}
}
<file_sep>//package me.wizos.loread.adapter;
//
//import android.content.Context;
//import android.widget.ArrayAdapter;
//
//import java.util.ArrayList;
//
//import me.wizos.loread.gson.Item;
//
///**
// * Created by Wizos on 2016/3/6.
// */
//public class Slv extends ArrayAdapter<Item> {
// public Slv(Context context, int textViewResourceId, ArrayList<Item> itemArray){
// super(context, textViewResourceId, itemArray);
// }
//
//// public Slv( String time, String desc, String meta, String imgName) {
//// this.time = time;
//// this.desc = desc;
//// this.meta = meta;
//// this.imgName = imgName;
//// }
//
// private String title;
// private String time;
// private String desc;
// private String meta;
// private String imgName;
//
//
// public void setTitle(String title) {
// this.title = title;
// }
// public String getTitle() {
// return title;
// }
// public void setTime(String time) {
// this.time = time;
// }
// public String getTime() {
// return time;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
// public String getDesc() {
// return desc;
// }
//
// public void setMeta(String meta) {
// this.meta = meta;
// }
// public String getMeta() {
// return meta;
// }
//
// public void setImgName(String account){this.imgName = account;}
// public String getImgName(){return imgName;}
//
//
//// public Drawable getDraw(String icontitle) {
//// int resId = ResourceIdUtils.getIdOfResource(icontitle, "drawable");
////// System.out.println("【icontitle】" + "ttt" + icontitle + resId);
//// return App.getContext().getResources().getDrawable(resId,null);
//// }
//
// @Override //"\n" +
// public String toString() {
// return "【meta:--->" + this.getMeta() + "price:--->" + this.getDesc()+"】";
// }
//
//}
//
<file_sep>package me.wizos.loread.net;
import java.util.ArrayList;
/**
* Created by Wizos on 2016/4/22.
*/
public class Requests {
String url;
String method;
long logTime;
String headParamString;
String bodyParamString;
ArrayList<Param> headParamList;
ArrayList<Param> bodyParamList;
public Requests(String url,String method,long logTime,String headParamString,String bodyParamString){
this.url = url;
this.method = method;
this.logTime = logTime;
this.headParamString = headParamString;
this.bodyParamString = bodyParamString;
}
void setUrl(String url){
this.url = url;
}
String getUrl(){
return url;
}
void setHeadParamString(String headParamString){
this.headParamString = headParamString;
}
String getHeadParamString(){
return headParamString;
}
void setBodyParamString(String bodyParamString){
this.bodyParamString = bodyParamString;
}
String getBodyParamString(){
return bodyParamString;
}
void setMethod(String method){
this.method = method;
}
String getMethod(){
return method;
}
void setHeadParamList(ArrayList<Param> headParamList){
this.headParamList = headParamList;
}
ArrayList<Param> getHeadParamList(){
return headParamList;
}
void setBodyParamList(ArrayList<Param> bodyParamList){
this.bodyParamList = bodyParamList;
}
ArrayList<Param> getBodyParamList(){
return bodyParamList;
}
private class Param {
private String key;
private String value;
Param(String key, String value){
this.key = key;
this.value = value;
}
public void setKey(String key){
this.key = key;
}
public String getKey(){
return key;
}
public void setValue(String value){
this.value = value;
}
public String getValue(){
return value;
}
}
}
<file_sep># loread
Inoreader 第三方客户端,RSS 阅读器 | 85896b23cffa3d7606b7212e2b9bc8fc612c7b4a | [
"Markdown",
"Java",
"Gradle"
] | 14 | Java | alunix/loread | f486924578f14e465325b05ebae52a94973d8c18 | 9f695bd220059481919c96f57bfa6b2a428f3044 |
refs/heads/master | <repo_name>thara1511/node-bot<file_sep>/app.js
/*
'use strict';
const http = require('http');
const https = require('https');
const crypto = require('crypto');
const HOST = 'api.line.me';
const REPLY_PATH = '/v2/bot/message/reply';//リプライ用
const CH_SECRET = 'xxxxxxxx'; //Channel Secretを指定
const CH_ACCESS_TOKEN = 'xxxxxx'; //Channel Access Tokenを指定
const SIGNATURE = crypto.createHmac('sha256', CH_SECRET);
const PORT = 3000;
/**
* httpリクエスト部分
*/
/*
const client = (replyToken, SendMessageObject) => {
let postDataStr = JSON.stringify({ replyToken: replyToken, messages: SendMessageObject });
let options = {
host: HOST,
port: 443,
path: REPLY_PATH,
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'X-Line-Signature': SIGNATURE,
'Authorization': `Bearer ${CH_ACCESS_TOKEN}`,
'Content-Length': Buffer.byteLength(postDataStr)
}
};
return new Promise((resolve, reject) => {
let req = https.request(options, (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', () => {
resolve(body);
});
});
req.on('error', (e) => {
reject(e);
});
req.write(postDataStr);
req.end();
});
};
http.createServer((req, res) => {
if(req.url !== '/' || req.method !== 'POST'){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('');
}
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () => {
if(body === ''){
console.log('bodyが空です。');
return;
}
let WebhookEventObject = JSON.parse(body).events[0];
//メッセージが送られて来た場合
if(WebhookEventObject.type === 'message'){
let SendMessageObject;
if(WebhookEventObject.message.type === 'text'){
SendMessageObject = [{
type: 'text',
text: WebhookEventObject.message.text
}];
}
client(WebhookEventObject.replyToken, SendMessageObject)
.then((body)=>{
console.log(body);
},(e)=>{console.log(e)});
}
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('su');
});
}).listen(PORT);
console.log(`Server running at ${PORT}`);
*/
var http = require('http');
var restify = require('restify');
// サーバー生成
var server = restify.createServer();
var port = process.env.port || 8080;
// http://0.0.0.0:8080/hello_worldにGETリクエストしたときの処理
function helloWorld(req, res, next){
// レスポンス
res.send("Hello");
console.log('invoke hellowrold');
//next();
}
// パスと関数の紐付け
// ↓はhttp://0.0.0.0:8080/hello_worldにGETリクエストしたらhelloWorld関数を実行
server.get('/hello_world', helloWorld);
server.listen(port, function() {
console.log('%s listening at %s', server.name, server.url);
});
/*
var server = http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello Azure!Go!!Go!!");
});
var port = process.env.PORT || 1337;
server.listen(port);
console.log("Server running at http://localhost:%d", port);
*/
| a59e6f3e52d2a057246a12a88dbbd99119c33271 | [
"JavaScript"
] | 1 | JavaScript | thara1511/node-bot | ab7d70d49a75953325bf8faa55825c1dfb7e7b7d | 7543e151f00aac20ded3486424e487da61fd1ad8 |
refs/heads/master | <file_sep>package gt.edu.umg.proma1.proyectofinal;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTable;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.table.DefaultTableModel;
import javax.swing.JTextPane;
public class Base extends JFrame {
private JPanel contentPane;
private JTextField txtEntidad;
private JTextField txtAtributo;
private JTextField txtLongitud;
private DefaultTableModel tableModel;
private JTable table;
private JTextField txtTipoDato;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Base frame = new Base();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public int getSumaAscii(String linea) {
int total = 0;
for (int i = 0; i < linea.length(); i++) {
char c = linea.charAt(i);
int ascii = (int) c;
total += ascii;
}
int id = (total % 50);
return id;
}
private boolean verificarColosion(int id) {
boolean existe = false;
for (int i = 0; i < tableModel.getRowCount(); i++) {
String valor = tableModel.getValueAt(i, 0).toString();
if (id == Integer.parseInt(valor)) {
existe = true;
break;
}
}
return existe;
}
/**
* Create the frame.
*/
public Base() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 685, 538);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
tableModel = new DefaultTableModel();
tableModel.addColumn("ID");
tableModel.addColumn("Entidad");
tableModel.addColumn("Atributo");
tableModel.addColumn("Tipo de Dato");
tableModel.addColumn("Longitud");
table = new JTable();
table.setBounds(62, 270, 475, 170);
contentPane.add(table);
JLabel lblEntidad = new JLabel("Nombre Entidad:");
lblEntidad.setBounds(35, 11, 103, 21);
contentPane.add(lblEntidad);
txtEntidad = new JTextField();
txtEntidad.setBounds(168, 11, 126, 21);
contentPane.add(txtEntidad);
txtEntidad.setColumns(10);
JLabel lblAtributo = new JLabel("Nombre del Atributo:");
lblAtributo.setBounds(35, 43, 126, 21);
contentPane.add(lblAtributo);
txtAtributo = new JTextField();
txtAtributo.setBounds(168, 43, 126, 21);
contentPane.add(txtAtributo);
txtAtributo.setColumns(10);
JLabel lblTipoDato = new JLabel("Ingrese Tipo de Dato:");
lblTipoDato.setBounds(35, 75, 126, 29);
contentPane.add(lblTipoDato);
txtTipoDato = new JTextField();
txtTipoDato.setBounds(168, 79, 126, 21);
contentPane.add(txtTipoDato);
txtTipoDato.setColumns(10);
JLabel lblLongitud = new JLabel("Ingrese la Longitud:");
lblLongitud.setBounds(35, 129, 125, 21);
contentPane.add(lblLongitud);
txtLongitud = new JTextField();
txtLongitud.setBounds(168, 129, 72, 21);
contentPane.add(txtLongitud);
txtLongitud.setColumns(10);
JButton btnAgregar = new JButton("Agregar");
btnAgregar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int id = getSumaAscii(txtEntidad.getText().trim());
if (verificarColosion(id)) {
JOptionPane.showMessageDialog(null, "La Entidad ya Existe", "Duplicidad de informacion",
JOptionPane.ERROR_MESSAGE);
} else {
Atributos a = new Atributos();
a.setId(id);
a.setEntidad(txtEntidad.getText().trim());
a.setAtributo(txtAtributo.getText().trim());
a.setTipoDato(txtTipoDato.getText().length());
a.setLongitud(txtLongitud.getText().length());
tableModel.addRow(new Object[] { a.getId(), a.getEntidad(), a.getAtributo(), a.getTipoDato(),
a.getLongitud() });
txtEntidad.setText("");
txtAtributo.setText("");
txtLongitud.setText("");
txtTipoDato.setText(" ");
}
}
});
btnAgregar.setBounds(35, 200, 89, 23);
contentPane.add(btnAgregar);
JButton btnModificar = new JButton("Modificar");
btnModificar.setBounds(183, 200, 89, 23);
contentPane.add(btnModificar);
}
}
<file_sep>package gt.edu.umg.proma1.proyectofinal;
public enum TDatos {
INT(1), LONG(2), STRING(3), DOUBLE(4), FLOAT(5), DATE(6), CHAR(7);
private final int value;
private TDatos(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
| eaeff12ff0fc3b0a5485a947bb52b18404e323fe | [
"Java"
] | 2 | Java | HenryHerrera/ProyectoFinal | abd9bd656bcfcd6da1c4f76fb343156ae06172d3 | 4fc614a0b4a6218290697397f9b8b46c167f4240 |
refs/heads/master | <repo_name>tonogeneral/reproducibleResearch<file_sep>/spamData.R
#Código que mide la tasa de error en un modelo predictivo
library(kernlab)
data(spam)
str(spam[,1:5])
#generando subset de prueba
set.seed(3435)
# Distribución de variables en valores booleanos como trainIndicator
trainIndicator <- rbinom(4601, size = 1, prob = 0.5)
table(trainIndicator)
#Se separan el dataset en Test y Training dataset mediante
# distribución probabilística rbinom
trainSpam = spam[trainIndicator == 1,]
testSpam = spam[trainIndicator == 0,]
names(trainSpam)
head(trainSpam)
table(trainSpam$type)
#Se grafica incidencia entre correos spam que contienen mayor promedio de
# letras mayúsculas en su contenido
plot(trainSpam$capitalAve ~ trainSpam$type)
#en logaritmo base 10 para mejor visualización.
plot(log10(trainSpam$capitalAve+1) ~ trainSpam$type)
#Se eliminan los valores en cero para visualización
plot(log10(trainSpam[,1:4] + 1))
#Cluster que identifica las variables con mayor incidencia en agrupación
hCluster <- hclust(dist(t(trainSpam[,1:57])))
#Gráfico de dendograma de cluster
plot(hCluster)
# Log Base 10
hClusterUpdated <- hclust(dist(t(log10(trainSpam[,1:55] + 1))))
#dendograma
plot(hClusterUpdated)
##### STATISTICAL PREDICTION MODELLING ######################
trainSpam$numtype = as.numeric(trainSpam$type) -1
costFunction = function(x,y) sum(x != (y > 0.5))
cvError = rep(NA,55)
library(boot)
for (i in 1:55){
lmFormula = reformulate(names(trainSpam)[i],response = "numtype")
glmFit = glm(lmFormula, family = "binomial", data = trainSpam)
cvError[i] = cv.glm(trainSpam, glmFit,costFunction,2)$delta[2]
}
# Cual predictor tiene un menor error de validación cruzada?
names(trainSpam)[which.min(cvError)]
#Modelo de regresión logística
predictionModel = glm(numtype ~ charDollar, family = "binomial", data = trainSpam)
## hacer predicciones sobre el set de prueba
predictionTest = predict(predictionModel, testSpam)
predictedSpam = rep("nonspam", dim(testSpam)[1])
#Clasificar como spam aquellos con una probabilidad mayor a 0.5
predictedSpam[predictionModel$fitted > 0.5] = "spam"
#Obtener una medida de incertidumbre
table(predictedSpam, testSpam$type)
#tasa de error
(61 + 458)/(1346 + 458 + 61 + 449)
<file_sep>/testRmarkdown.rmd
---
title: "Rmarkdown html test"
author: "<NAME>"
date: "31-01-2021"
output:
pdf_document: default
html_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
library(kernlab)
data(spam)
str(spam[,1:5])
#generando subset de prueba
set.seed(3435)
# Distribución de variables en valores booleanos como trainIndicator
trainIndicator <- rbinom(4601, size = 1, prob = 0.5)
table(trainIndicator)
#Se separan el dataset en Test y Training dataset mediante
# distribución probabilística rbinom
trainSpam = spam[trainIndicator == 1,]
testSpam = spam[trainIndicator == 0,]
names(trainSpam)
head(trainSpam)
table(trainSpam$type)
#Se grafica incidencia entre correos spam que contienen mayor promedio de
# letras mayúsculas en su contenido
plot(trainSpam$capitalAve ~ trainSpam$type)
#en logaritmo base 10 para mejor visualización.
plot(log10(trainSpam$capitalAve+1) ~ trainSpam$type)
#Se eliminan los valores en cero para visualización
plot(log10(trainSpam[,1:4] + 1))
#Cluster que identifica las variables con mayor incidencia en agrupación
hCluster <- hclust(dist(t(trainSpam[,1:57])))
#Gráfico de dendograma de cluster
plot(hCluster)
# Log Base 10
hClusterUpdated <- hclust(dist(t(log10(trainSpam[,1:55] + 1))))
#dendograma
plot(hClusterUpdated)
##### STATISTICAL PREDICTION MODELLING ######################
trainSpam$numtype = as.numeric(trainSpam$type) -1
costFunction = function(x,y) sum(x != (y > 0.5))
cvError = rep(NA,55)
library(boot)
for (i in 1:55){
lmFormula = reformulate(names(trainSpam)[i],response = "numtype")
glmFit = glm(lmFormula, family = "binomial", data = trainSpam)
cvError[i] = cv.glm(trainSpam, glmFit,costFunction,2)$delta[2]
}
# Cual predictor tiene un menor error de validación cruzada?
names(trainSpam)[which.min(cvError)]
#Modelo de regresión logística
predictionModel = glm(numtype ~ charDollar, family = "binomial", data = trainSpam)
## hacer predicciones sobre el set de prueba
predictionTest = predict(predictionModel, testSpam)
predictedSpam = rep("nonspam", dim(testSpam)[1])
#Clasificar como spam aquellos con una probabilidad mayor a 0.5
predictedSpam[predictionModel$fitted > 0.5] = "spam"
#Obtener una medida de incertidumbre
table(predictedSpam, testSpam$type)
#tasa de error
(61 + 458)/(1346 + 458 + 61 + 449)
<file_sep>/incrustaPlot.Rmd
---
title: "incrustaPlot"
author: "<NAME>"
date: "31-01-2021"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
Este es un archivo que se utiliza para realizar investigación reproducible
Crearemos código en R el cual podrá mostrar o no el código fuente
y podrá incustrar imágenes como gráficos (plot)
## Presentación
Primero simularemos los datos en un chunk de código
```{r simulateData, echo=TRUE}
x <- rnorm(100); y <- x + rnorm(100, sd = 0.5)
```
## Incrustamos en html el grafo
Gráfico de los datos
```{r grafico, fig.height= 4}
par(mar = c(5,4,1,1), las = 1)
plot(x,y, main ="Mi data simulada")
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
<file_sep>/README.md
# reproducibleResearch
Este es el repositorio del curso reproducible research de Coursera.
<file_sep>/airQuality.Rmd
---
title: "modeloPredictivoHtml"
author: "<NAME>"
date: "31-01-2021"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r}
library(datasets)
data("airquality")
summary(airquality)
```
Generamos un plot con la data
``` {r}
pairs(airquality)
```
Generamos un modelo de regresión sobre valores de viento, radiación solar
y temperatura
```{r}
library(stats)
fit <- lm(Ozone ~ Wind + Solar.R + Temp, data = airquality)
summary(fit)
```
Generamos una tabla de coeficientes de regresión con xtable
``` {r showtable, results = "asis"}
library(xtable)
xt <- xtable(summary(fit))
print(xt, type = "html")
```
| 3f249c37924b64bf2c4c942383c84226fb06e06a | [
"Markdown",
"R",
"RMarkdown"
] | 5 | R | tonogeneral/reproducibleResearch | ac1a5ffdd1b40f95d123fc295af88d132df5cbff | 02cdadb8e4a6d80a14587392a32dce0f7a2bf758 |
refs/heads/main | <file_sep><div align = "center">
<img src="https://github.com/spaceml-org/Swipe-Labeler/blob/main/src/images/banner.jpg" >
<p align="center">
Published by <a href="http://spaceml.org/">SpaceML</a> •
<a href="https://arxiv.org/abs/2012.10610">About SpaceML</a> •
</p>
   \
[](https://colab.research.google.com/github/spaceml-org/Swipe-Labeler/blob/main/Swipe_Labeller_Demo.ipynb)
</div>
# Swipe-Labeler
### About
Swipe Labeler is a Graphical User Interface based tool that allows rapid labeling of image data.
Images will be picked one by one from your unlabeled images directory, and presented through the Swipe Labeler GUI. For each image, the user can choose to classify the image as a positive or negative/absent class using the “Accept” or “Reject” button.
For example, if you’re looking to label images as either containing or not containing a cat, the user would choose “Accept” for any images with a cat, and “Reject” for any images without a cat. The application then transfers the newly labeled image file from your unlabeled images directory to your chosen positive or negative directory. The user can choose the label (e.g. cat, dog) too. The user has three ways to input the classification choice:
- [Standard version] Click on the “Accept”/“Reject”/"Unsure" buttons
- [Social version] Swipe to the right for “Accept”, left for “Reject” and down for "Unsure"
- [Gamified version] Use the keyboard right arrow key for “Accept”,the keyboard left arrow key for “Reject” and the down arrow key for "Unsure".

## Usage
1. You’ll need to have python3 and pip installed. (See FAQ's below.)
2. Clone this repo. \
`git clone https://github.com/spaceml-org/Swipe-Labeler`
and `cd Swipe-Labeler`
3. Optionally(but recommended), create and activate a virtual environment.
* Create a virtual environment. \
`python3 -m venv venv`
* Activate the virtual environment. \
` . venv/bin/activate`
4. Install the python dependencies (Flask plus more). \
`pip install -r api/requirements.txt`
5. Run this this application as a python file. (Don't use "flask run" as you might with other Flask applications.) \
As you do so, pass the complete path to the directory containing the images you want to label (as a string) as the argument `--path_for_unlabeled` . \
`python api/api.py --path_for_unlabeled=path/to/unlabelled_images_dir --batch_size=5` \
\
**Important Note** - When you run this application, a new folder will be created for you (if doesn't already exist) under the same parent directory as your `path_for_unlabeled`. This sibling directory, `Labeled`, will contain the following:
* **Labeled/Labeled_Positive** - Gets populated with the image files labeled positive when the user clicks "Accept", swipes right, or presses the right arrow key on the keyboard.
* **Labeled/Labeled_Negative** - Gets populated with the image files labeled negative when the user clicks "Reject", swipes left, or presses the arrow left key on the keyboard.
* **Labeled/Unsure** - Gets populated with the image files for which the user clicked the "skip" button.
6. In your browser, open the url displayed in the terminal window. The app will run on port 5000. \
Copy the following url into your browser's search bar and hit enter. The application should display in your browser window. \
`http://0.0.0.0:5000/`
## Development
### Setup
1. You’ll need to have python3 and pip installed **as well as npm**. (See FAQ's below.)
2. Clone this repo \
`git clone https://github.com/spaceml-org/Swipe-Labeler`
3. Navigate into this project's root directory. \
`cd Swipe-Labeler`
### Setting up the web server
4. Navigate into the subdirectory: "api". \
`cd api`
5. Optionally(but recommended), create and activate a virtual environment.
* Create a virtual environment. \
`python3 -m venv venv`
* Activate the virtual environment. \
` . venv/bin/activate`
6. From inside the api directory, install the python dependencies (Flask plus more). \
`pip install -r requirements.txt`
### Setting up the web application
8. Navigate back to the project's root directory. \
`cd ..`
9. Use npm to install the javascript files and their dependencies. \
`npm install`
### Usage (for development)
Run these two commands in two different terminal shells opened to the project's root directory:
1. `npm start`
2. (In a separate terminal shell) Run this this application as a python file. (Don't use "flask run" as you might with other Flask applications.) \
As you do so, pass the complete path to the directory containing the images you want to label (as a string) as the argument `--to_be_labeled` . \
`python api/api.py --to_be_labeled=path/to/unlabelled_images_dir` \
\
**A Note About Development** - <p>In order to allow the option of using the tool without the need to install all of the javascript packages, the "build" folder is included in this repository, and it serves as the template folder for the Flask application. Because of this, if you are doing development, you should do an\
`npm run build`\
to update the build directory when you are ready to save your work.</p>
## FAQ's
1. **Do I need to use Python 3?** \
Yes. But if this conflicts with the version you have working on your system, you can isolate this version inside a virtual environment (see optional instructions for this above). More info here: https://www.python.org/downloads/ .
2. **Do I need to use pip to install the python packages?** \
You can use other methods, but the instructions above are written using pip. You can find more information about pip here: https://pip.pypa.io/en/stable/installing/ .
3. **Do I need to have npm installed to run this?** \
If you are not developing, you do not need to have npm / node.js installed. \
If you would like to run it for development, however, you will need to have node version 12.16.3 installed (and follow the development instructions above).
4. **What is npm? How do I download npm?** \
npm is basically an installation package for javascript, like pip is for python. You can find more information here : https://www.npmjs.com/get-npm .
## Citation
Please cite us if you use our code.
```
@code{
title={Swipe-Labeler},
author={<NAME>,<NAME>,<NAME>},
url={https://github.com/spaceml-org/Swipe-Labeler/},
year={2021}
}
```
<file_sep>from pathlib import Path
import os
import random
import shutil
import time
from flask import Flask, request, send_from_directory, render_template, session
from flask.logging import create_logger
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('--batch_size', type=int, help='how many items to label')
parser.add_argument('--path_for_unlabeled', type=str,
help='folder with images to be labeled')
parser.add_argument('--path_for_pos_labels',type=str,
help='folder with images labeled positive')
parser.add_argument('--path_for_neg_labels',type=str,
help='folder with images labeled negative')
parser.add_argument('--path_for_unsure_labels',type=str,
help='folder with images labeled unsure')
args = parser.parse_args()
batch_size = args.batch_size or 5
path_for_unlabeled = args.path_for_unlabeled
path_for_pos = args.path_for_pos_labels
path_for_neg = args.path_for_neg_labels
path_for_unsure = args.path_for_unsure_labels
def create_app(batch_size, path_for_unlabeled):
react_build_directory = os.path.join(
str(Path(__file__).resolve().parent.parent), 'build')
# Redirects the template folder and the static folder to the react build directory.
# This allows users to run the application without having to download and run node.
app = Flask(__name__, template_folder=react_build_directory,
static_folder=os.path.join(react_build_directory, 'static'))
app.config['batch_size'] = batch_size
app.config['path_for_unlabeled'] = path_for_unlabeled
# Create a temp folder, if it doesnt exist
app.config["temp"] = os.path.join(Path(path_for_unlabeled).resolve().parent,'temp')
if os.path.exists(app.config["temp"]):
shutil.rmtree(app.config["temp"])
time.sleep(0.5)
os.mkdir(app.config["temp"])
# This is the path_for_unlabeled folder that is passed in as an argument when starting this script.
orig_images_path = app.config['path_for_unlabeled']
# Finds the parent of path_for_unlabeled, so Labeled can be created as a sibling folder.
parent_directory = os.path.dirname(orig_images_path)
#if user provided arguments for paths then define driectory based on that:
if(path_for_neg and path_for_pos and path_for_unsure):
# Make the positive label folder
if not os.path.exists(path_for_pos):
os.mkdir(path_for_pos)
# Make the negative label folder
if not os.path.exists(path_for_neg):
os.mkdir(path_for_neg)
# Make the unsure label folder
if not os.path.exists(path_for_unsure):
os.mkdir(path_for_unsure)
#default case incase user doesnt provide argument paths for labelling folders
else:
# Define Labeled folder to be at the same level as path_for_unlabeled
labeled_folder = os.path.join(str(parent_directory), 'Labeled')
# Make the (parent_directory)/Labeled folder if it doesn't exist already.
if not os.path.exists(labeled_folder):
time.sleep(0.2)
os.mkdir(labeled_folder)
# shutil.rmtree(labeled_folder)
# time.sleep(0.2)
# os.mkdir(labeled_folder)
# Create parent_directory/Labeled/Labeled_Positive folder if it doesn't already exist.
labeled_positive = os.path.join(labeled_folder, 'Labeled_Positive')
if not os.path.exists(labeled_positive):
time.sleep(0.2)
os.mkdir(labeled_positive)
# shutil.rmtree(labeled_positive)
# time.sleep(0.2)
# # Create swipe_labeler_data/labeled_positive folder if it doesn't already exist.
labeled_negative = os.path.join(labeled_folder, 'Labeled_Negative')
if not os.path.exists(labeled_negative):
time.sleep(0.2)
os.mkdir(labeled_negative)
# shutil.rmtree(labeled_negative)
# time.sleep(0.2)
# # Create swipe_labeler_data/labeled_positive folder if it doesn't already exist.
unsure = os.path.join(labeled_folder, 'Unsure')
if not os.path.exists(unsure):
time.sleep(0.2)
os.mkdir(unsure)
return app
app = create_app(batch_size, path_for_unlabeled)
@app.route('/')
def index():
# This serves the react app when the flask app is run.
print("testing")
return render_template('index.html')
@app.route('/image',methods=['POST'])
def list_image_url():
# Servers images by moving them from unlabeled to temp or directly serves from temp
# Checks if there are images in temp to be served otherwise:
# Checks the unlabeled directory, picks a random image , returns its url and moves the image to a temp folder
# Parsing request data
swipes = request.get_json()['swipes']
image_url = request.get_json()['image_url']
if image_url != "none":
# This line cuts off the '/media/' at the start of the image_url from request.
image_name = image_url[7:]
#Check if undo was clicked and serve that missed image from temp
if (image_url != "none"):
# Pick requested file from temp to display
if image_name in os.listdir(app.config["temp"]):
# image = random.choice(os.listdir(app.config["temp"]))
image_path = os.path.join(app.config["temp"],image_name)
msg = None
return {"image":"/media/"+image_name , "path":image_path , "msg":msg,"swipes":swipes,"reached":"1st"}
else:
return {"image":"none", "path":"none", "msg":"none","swipes":swipes,"reached":"1st"}
# Undo didnt happen, pick a random file from unlabeled
else:
src = app.config["path_for_unlabeled"]
image = None
if ( len(os.listdir(src)) ):
image = random.choice(os.listdir(src))
else:
return {"image":"none", "path":"none", "msg":"none","swipes":swipes,"reached":"3rd"}
# Move current file to temp folder
image_path = os.path.join(src,image)
msg = shutil.move(image_path,app.config["temp"])
return {"image":"/media/"+image , "path":image_path , "msg":msg ,"swipes":int(swipes)}
@app.route('/getsize')
def give_size():
src = app.config["path_for_unlabeled"]
size = len( [name for name in os.listdir(src)] )
# Use specific labeled folder paths , if user provided
if path_for_neg and path_for_pos and path_for_unsure:
labeled_positive_size = len( [name for name in os.listdir(path_for_neg)])
labeled_negative_size = len( [name for name in os.listdir(path_for_pos)])
unsure_size = len( [name for name in os.listdir(path_for_unsure)])
labeled_size = labeled_negative_size + labeled_positive_size + unsure_size
# Use default labeled folder paths , if user didnt provide them
else:
parent_directory = os.path.dirname(src)
labeled_folder = os.path.join(str(parent_directory), 'Labeled')
labeled_positive = os.path.join(labeled_folder, 'Labeled_Positive')
labeled_negative = os.path.join(labeled_folder, 'Labeled_Negative')
unsure = os.path.join(labeled_folder, 'Unsure')
labeled_positive_size = len( [name for name in os.listdir(labeled_positive)])
labeled_negative_size = len( [name for name in os.listdir(labeled_negative)])
unsure_size = len( [name for name in os.listdir(unsure)])
labeled_size = labeled_negative_size + labeled_positive_size + unsure_size
# batch_size = min(app.config["batch_size"],size)
return {"batch_size":size,"batch_stop":batch_size,"labeled_size":labeled_size}
#helper route to log test requests, can be removed after project completion
@app.route('/details')
def giveDetails():
#return "<h1>Hello world</h1>"
if(path_for_neg):
return {'msg':path_for_neg}
else:
return {'msg':"no path provided"}
@app.route('/media/<filename>')
def serve_image_url(filename):
'''Serves the single image requested.'''
# This is the path_for_unlabeled folder that is passed in as an argument when starting this script.
orig_images_path = app.config['temp']
# Serves the single image requested from the path_for_unlabeled folder.
return send_from_directory(orig_images_path, filename)
@app.route('/submit', methods=['POST'])
def submit_label():
'''Saves the labeled image file into the positive,negative or unsure directory'''
# Get the label value of this image from the request.
value = request.get_json()['value']
image_url = request.get_json()['image_url']
# This line cuts off the '/media/' at the start of the image_url from request.
image_name = image_url[7:]
# These folders are defined in terms of the path_for_unlabeled folder (passed as argument when you start this script)
orig_images_path = app.config['temp']
# If the User provided path arguments then use those paths:
if(path_for_neg and path_for_pos and path_for_unsure):
old_path = None
if os.path.exists(os.path.join(orig_images_path, image_name)):
msg = "reached nested if"
old_path = os.path.join(orig_images_path, image_name)
elif os.path.exists(os.path.join(path_for_pos, image_name)) :
old_path = os.path.join(path_for_pos, image_name)
elif os.path.exists(os.path.join(path_for_neg, image_name)) :
old_path = os.path.join(path_for_neg, image_name)
elif os.path.exists(os.path.join(path_for_unsure, image_name)) :
old_path = os.path.join(path_for_unsure, image_name)
pos_path = os.path.join(path_for_pos, image_name)
neg_path = os.path.join(path_for_neg, image_name)
unsure_path = os.path.join(path_for_unsure,image_name)
# Depending on the value sent by the user, move the image file into the positive,negative or unsure folder.
if old_path:
if value == 1:
# Move the file to the positive folder.
shutil.move(old_path, pos_path)
elif value == 0:
# Move the file to the negative folder.
shutil.move(old_path, neg_path)
elif value == 2:
# Move the file to the unsure folder.
shutil.move(old_path, unsure_path)
# If user hasnt provided path arguments , use the following as default folders:
else:
parent_directory = os.path.dirname(orig_images_path)
labeled_folder = os.path.join(str(parent_directory), 'Labeled')
labeled_positive = os.path.join(labeled_folder, 'Labeled_Positive')
labeled_negative = os.path.join(labeled_folder, 'Labeled_Negative')
unsure = os.path.join(labeled_folder, 'Unsure')
# These are paths to this specific image in the folders defined above.
# Look in all 4 places: Unlabeled, Labled_Positive, Labeled_Negative, Labeled_Unsure
old_path = None
if os.path.exists(os.path.join(orig_images_path, image_name)):
old_path = os.path.join(orig_images_path, image_name)
# The next 3 elif blocks are to check in lableled folder, in case undo was hit on an image
elif os.path.exists(os.path.join(labeled_positive, image_name)):
old_path = os.path.join(labeled_positive, image_name)
elif os.path.exists(os.path.join(labeled_negative, image_name)):
old_path = os.path.join(labeled_negative, image_name)
elif os.path.exists(os.path.join(unsure, image_name)):
old_path = os.path.join(unsure, image_name)
pos_path = os.path.join(labeled_positive, image_name)
neg_path = os.path.join(labeled_negative, image_name)
unsure_path = os.path.join(unsure,image_name)
# Depending on the value sent by the user, move the image file into the positive,negative or unsure folder.
if old_path:
if value == 1:
# Move the file to the positive folder.
shutil.move(old_path, pos_path)
elif value == 0:
# Move the file to the negative folder.
shutil.move(old_path, neg_path)
elif value == 2:
# Move the file to the unsure folder.
shutil.move(old_path, unsure_path)
return {'status': 'success','old_path':old_path}
@app.route('/undo', methods=['POST'])
def undo_swipe():
# Moves the requested image from labeled to temp
# Checks in the Labeled folder to retrieve requested image.
image_url = request.get_json()['image_url']
#curr_image_url = request.get_json()['curr_image_url']
# This line cuts off the '/media/' at the start of the image_url from request.
image_name = image_url[7:]
#curr_image_name = curr_image_url[7:]
# Get the path of Labeled folder and its sub-folders
# If the User provided path arguments then use those paths:
if(path_for_neg and path_for_pos and path_for_unsure):
labeled_positive = path_for_pos
labeled_negative = path_for_neg
unsure = path_for_unsure
# Use default paths, if user didnt provide
else:
parent_directory = os.path.dirname(app.config['path_for_unlabeled'])
labeled_folder = os.path.join(str(parent_directory), 'Labeled')
labeled_positive = os.path.join(labeled_folder, 'Labeled_Positive')
labeled_negative = os.path.join(labeled_folder, 'Labeled_Negative')
unsure = os.path.join(labeled_folder, 'Unsure')
# Define paths for sub-folder/image
pos_path = os.path.join(labeled_positive, image_name)
neg_path = os.path.join(labeled_negative, image_name)
unsure_path = os.path.join(unsure,image_name)
# Search and transfer requested image to temp folder for serving in future
# dest_path = os.path.join(app.config['path_for_unlabeled'],image_name)
dest_path = os.path.join(app.config['temp'],image_name)
# Search and transfer requested image to temp folder for serving in future
if (os.path.exists(pos_path)):
shutil.move(pos_path,dest_path)
elif (os.path.exists(neg_path)):
shutil.move(neg_path,dest_path)
elif (os.path.exists(unsure_path)):
shutil.move(unsure_path,dest_path)
else:
return {'msg':"ERROR!"}
return {"status":"success",}
@app.route('/quit',methods=['POST'])
def quit_app():
msg = None
# Transfer the request image from temp to unlabeled folder
image_url = request.get_json()['image_url']
curr_image_url = request.get_json()['curr_image_url']
# This line cuts off the '/media/' at the start of the image_url from request.
image_name = image_url[7:]
if(curr_image_url != "none"):
curr_image_name = curr_image_url[7:]
src = os.path.join(app.config['temp'],curr_image_name)
dest = os.path.join(app.config['path_for_unlabeled'],curr_image_name)
msg = shutil.move(src,dest)
src = os.path.join(app.config['temp'],image_name)
dest = os.path.join(app.config['path_for_unlabeled'],image_name)
msg = shutil.move(src,dest)
return {'status':'success','msg':msg}
@app.route('/refresh',methods=['POST'])
def refresh_handler():
msg1 = None
# Transfer the requested image from temp to unlabeled folder
image_url = request.get_json()['image_url']
curr_image_url = request.get_json()['curr_image_url']
if( not image_url and curr_image_url == "none"):
return {'status':'nothing to move'}
#This line cuts off the '/media/' at the start of the image_url from request.
image_name = image_url[7:]
src2 = None
msg2 = None
if(curr_image_url != "none"):
curr_image_name = curr_image_url[7:]
src2 = os.path.join(app.config['temp'],curr_image_name)
dest = os.path.join(app.config['path_for_unlabeled'],curr_image_name)
if( not os.path.exists(src2)):
return {'status':'nothing to move'}
msg2 = shutil.move(src2,dest)
src = os.path.join(app.config['temp'],image_name)
if(not os.path.exists(src)):
return {'status':'nothing to move',"msg":msg1}
dest = os.path.join(app.config['path_for_unlabeled'],image_name)
msg1 = shutil.move(src,dest)
return {'status':'success','msg1':msg1,'msg2':msg2}
@app.route('/end', methods=['GET', 'POST'])
def end_app():
ready_to_end = request.get_json()['ready_to_end']
if ready_to_end == 'ready':
shutdown_hook = request.environ.get('werkzeug.server.shutdown')
if shutdown_hook is not None:
shutdown_hook()
return {'status': 'success'}
app.run(host='0.0.0.0',port=int('8080'))
<file_sep>import React from "react";
import "../styles.css";
import welcome from "../welcome.jpeg";
import { Button } from "@blueprintjs/core";
class Welcome extends React.Component {
constructor(props) {
super(props);
}
render() {
const welcomeStyles = {
backgroundImage: `url(${welcome})`,
height: "100%",
backgroundRepeat: "no-repeat",
backgroundSize: "cover",
};
return (
<div className="welcome-wrapper" style={welcomeStyles}>
<div className="welcome-text">
<h1>Swipe Labeler</h1>
<p>You could start with a tutorial, or get labelling right away!</p>
<div className="welcome-btn-grp">
<Button
intent="warning"
className="welcome-btn"
large={true}
onClick={this.props.startTutorial}
>
Tutorial
</Button>
<Button
intent="warning"
large={true}
className="welcome-btn"
onClick={this.props.startLabel}
>
Start Labelling
</Button>
</div>
</div>
</div>
);
}
}
export { Welcome };
<file_sep>import React,{useEffect} from "react";
import "./styles.css";
import moon from "./tutorial-images/moon.jpg";
import flag from "./tutorial-images/flag.jpg";
import earthrise from "./tutorial-images/earthrise.jpg";
import astronaut from "./tutorial-images/astronaut.jpg";
import TinderCard from "react-tinder-card";
import Timer from './components/timer'
import { Button, ProgressBar } from "@blueprintjs/core";
// import Sparkle from 'react-sparkle'
import "normalize.css";
import "@blueprintjs/icons/lib/css/blueprint-icons.css";
import "@blueprintjs/core/lib/css/blueprint.css";
// import { Magnifier, GlassMagnifier,SideBySideMagnifier,PictureInPictureMagnifier,MOUSE_ACTIVATION,TOUCH_ACTIVATION
// } from "react-image-magnifiers";
import SpeechRecognition, { useSpeechRecognition } from 'react-speech-recognition'
import { TransformWrapper, TransformComponent } from "react-zoom-pan-pinch";
// import SwipeScreen from './swipescreen'
function hasSeenTutorial() {
// Checks for a cookie on the users computer that will tell the user has already done the tutorial.
return document.cookie
.split(";")
.some((item) => item.trim().startsWith("hasSeenTutorial="));
}
function setTutorialSeen() {
document.cookie = "hasSeenTutorial=true";
}
export default class App extends React.Component {
// Main component
constructor(props) {
super(props);
this.state = {
view: hasSeenTutorial() ? "active" : "tutorial",
index: 0,
images: null,
batch_size: null,
};
// bind functions
this.fetchImages = this.fetchImages.bind(this);
this.sendSelection = this.sendSelection.bind(this);
this.onAcceptClick = this.onAcceptClick.bind(this);
this.onRejectClick = this.onRejectClick.bind(this);
this.onSkipClick = this.onSkipClick.bind(this);
this.onBackClick = this.onBackClick.bind(this);
this.endTutorial = this.endTutorial.bind(this);
}
componentDidUpdate(prevProps, prevState) {
// When the index gets updated, show the next image.
if (
prevState.index !== this.state.index &&
this.state.index === this.state.batch_size
)
this.fetchImages();
}
componentDidMount() {
// When the app loads, get all the image urls from flask.
this.fetchImages();
}
fetchImages() {
// Collect the list of image urls to request one by one later.
fetch("/images")
.then((res) => res.json())
.then((data) => {
this.setState({
images: data.images,
batch_size: data.images.length,
index: 0,
});
if (!data.images.length)
this.setState({
view: "end",
});
});
}
sendSelection(value) {
// When the user swipes, clicks, or presses a choice (accept or reject),
// that choice gets sent to flask.
fetch("/submit", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
image_url: this.state.images[this.state.index],
value: value,
}),
});
}
onAcceptClick() {
// Send the positive label to flask,
// and update the index so the next image will show.
this.sendSelection(1);
this.setState({
index: this.state.index + 1,
});
}
onSkipClick(){
// Send no label to flask, mark as ambigous with constant value 10
// and update the index so the next image will show.
this.sendSelection(2);
this.setState({
index: this.state.index + 1,
})
}
onRejectClick() {
// Send the negative label to flask,
// and update the index so the next image will show.
this.sendSelection(0);
this.setState({
index: this.state.index + 1,
});
}
onBackClick() {
this.setState({
index: this.state.index - 1,
});
}
endTutorial() {
this.setState({
view: "active",
});
// Set a cookie on the user's browser so they don't see the tutorial again.
setTutorialSeen();
}
render() {
var body = null;
// {console.log("Parent Props\n",this.state.images)}
if (this.state.view === "tutorial")
body = <TutorialScreen end={this.endTutorial} />;
else if (this.state.view === "active")
body = this.state.images ? (
<SwipeScreen
index={this.state.index}
batch_size={this.state.batch_size}
image={this.state.images[this.state.index]}
onAcceptClick={this.onAcceptClick}
onRejectClick={this.onRejectClick}
onSkipClick={this.onSkipClick}
onBackClick={this.onBackClick}
/>
) : (
<Button loading={true} />
);
else if (this.state.view === "end")
body = <EndScreen />
// body = <EndScreen
// image={this.state.images[4]}
// onAcceptClick={this.onAcceptClick}
// onRejectClick={this.onRejectClick}
// onSkipClick={this.onSkipClick}
// onBackClick={this.onBackClick}
// />;
return <div className="App">{body}</div>;
}
}
class SwipeScreen extends React.Component {
constructor(props) {
super(props);
this.onSwipe = this.onSwipe.bind(this);
this.onKeyPress = this.onKeyPress.bind(this);
//bind functions
this.decideCountText = this.decideCountText.bind(this);
}
componentWillMount() {
// Listens for the keyboard key press events. (Uses "keyup" so the button is only pressed once per choice.)
document.addEventListener("keyup", this.onKeyPress, false);
}
componentWillUnmount() {
// Removes the key press event listener if this component is replaced by another component or view.
// (Currently there are no other components to replace this view, however.)
document.removeEventListener("keyup", this.onKeyPress);
}
onSwipe = (direction) => {
// From TinderCard
if (direction === "right") {
this.props.onAcceptClick();
} else if (direction === "left") {
this.props.onRejectClick();
}else if (direction === "down") {
this.props.onSkipClick();
}
};
onKeyPress = (event) => {
// Key press alternatives
if (event.key === "ArrowRight") {
this.props.onAcceptClick();
} else if (event.key === "ArrowLeft") {
this.props.onRejectClick();
} else if (event.key === "ArrowDown") {
this.props.onSkipClick();
}
};
decideCountText(){
let text = ""
let x = this.props.batch_size - this.props.index;
if(x !== 1)
text = x+" Images Left!";
else
text = x+" Image Left!";
return [text,2*(this.props.index)/5]
}
render() {
let [count_text,x] = this.decideCountText();
return (
<>
{console.log("props= ",this.props)}
<div className="count">
<span>Batch Total: {this.props.batch_size}</span>
<br></br>
<span>{count_text}</span>
{console.log("x= ",x)}
<br></br>
<span className="prog-bar"><ProgressBar intent="success" value={x} ></ProgressBar></span>
</div>
<div className="timer">
<Timer />
</div>
<div className="SwipeScreen">
<div className="Question">
<div className="Image_wrapper">
<TinderCard onSwipe={this.onSwipe} preventSwipe={["right", "left","down","up"]}>
<TransformWrapper options={{centerContent:true}} defaultPositionX={50}>
<TransformComponent>
<img src={this.props.image} alt="" />
{/* <Magnifier imageSrc={this.props.image} alt="" /> */}
</TransformComponent>
</TransformWrapper>
</TinderCard>
</div>
<Button
icon="small-cross"
className="AcceptRejectButton"
intent="primary"
onClick={this.props.onRejectClick}
>
Reject
</Button>
<Button
icon="remove"
className="AcceptRejectButton"
intent="danger"
onClick={this.props.onSkipClick}
>
Skip
</Button>
<Button
icon="tick"
className="AcceptRejectButton"
intent="success"
onClick={this.props.onAcceptClick}
>
Accept
</Button>
</div>
<Button
icon="undo"
disabled={this.props.index === 0}
className="BackButton"
onClick={this.props.onBackClick}
>
Undo
</Button>
</div>
</>
);
}
}
class TutorialScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
prevLabel: null,
tutorialIndex: 0,
tutorialImages: [moon, earthrise, flag],
tutorialMessages: [
{
title: "Welcome to the Swipe Labeler tool.",
caption:
'You can label images in three ways. First click "Accept", "Reject" or "Skip" to continue.',
},
{ caption: "Now try swiping the image left,right, or downwards!." },
{
caption:
"Now try a keyboard shortcut. Press your arrow left key,arrow right key, or your arrow down key on your keybord.",
},
],
};
this.onTutorialAcceptClick = this.onTutorialAcceptClick.bind(this);
this.onTutorialRejectClick = this.onTutorialRejectClick.bind(this);
this.onTutorialSkipClick = this.onTutorialSkipClick.bind(this);
this.onTutorialSwipe = this.onTutorialSwipe.bind(this);
this.onTutorialKeyPress = this.onTutorialKeyPress.bind(this);
}
componentWillMount() {
// Listens for the keyboard key press events. (Uses "keyup" so the button is only pressed once per choice.)
document.addEventListener("keyup", this.onTutorialKeyPress, false);
}
componentWillUnmount() {
// Removes the key press event listener if this component is replaced by another component or view.
// (Currently there are no other components to replace this view, however.)
document.removeEventListener("keyup", this.onTutorialKeyPress);
}
onTutorialAcceptClick() {
// This and onTutorialRejectClick could be one just one function: onTutorialClick.
// Kept as separate function in case later want to add interaction based on user's choice.
if (this.state.tutorialIndex === this.state.tutorialImages.length - 1) {
this.props.end();
}
this.setState({
prevLabel: "accept",
tutorialIndex: this.state.tutorialIndex + 1,
});
}
onTutorialSkipClick() {
// This and onTutorialAcceptClick could be one just one function: onTutorialClick.
// Kept as separate function in case later want to add interaction based on user's choice.
if (this.state.tutorialIndex === this.state.tutorialImages.length - 1) {
this.props.end();
}
this.setState({
prevLabel: "skip",
tutorialIndex: this.state.tutorialIndex + 1,
});
}
onTutorialRejectClick() {
// This and onTutorialAcceptClick could be one just one function: onTutorialClick.
// Kept as separate function in case later want to add interaction based on user's choice.
if (this.state.tutorialIndex === this.state.tutorialImages.length - 1) {
this.props.end();
}
this.setState({
prevLabel: "reject",
tutorialIndex: this.state.tutorialIndex + 1,
});
}
onTutorialSwipe(direction) {
// From TinderCard
if (direction === "right") {
this.onTutorialAcceptClick();
} else if (direction === "left") {
this.onTutorialRejectClick();
} else if (direction === "down") {
this.onTutorialSkipClick();
}
}
onTutorialKeyPress = (event) => {
// Key press alternatives
if (event.key === "ArrowRight") {
this.onTutorialAcceptClick();
} else if (event.key === "ArrowLeft") {
this.onTutorialRejectClick();
}
else if (event.key === "ArrowDown") {
this.onTutorialSkipClick();
}
};
render() {
var message = this.state.tutorialMessages[this.state.tutorialIndex];
return (
<div className="TutorialScreen">
<div className="Question">
<div className="Image_wrapper">
<TinderCard
onSwipe={this.onTutorialSwipe}
preventSwipe={["right", "left","down"]}
>
<div
className="TutorialScreen_Question_Image"
style={{
backgroundImage:
"url('" +
this.state.tutorialImages[this.state.tutorialIndex] +
"')",
}}
>
<div className="TutorialScreen_Question_Image_Text">
<div className="TutorialScreen_Question_Image_Text_Title">
{message.title}
</div>
<div className="TutorialScreen_Question_Image_Text_Caption">
{message.caption}
</div>
{/* {this.state.tutorialMessages[this.state.tutorialIndex]} */}
</div>
</div>
</TinderCard>
</div>
<Button
icon="small-cross"
className="AcceptRejectButton"
intent="primary"
onClick={this.onTutorialRejectClick}
>
Reject
</Button>
<Button
icon="remove"
className="AcceptRejectButton"
intent="danger"
onClick={this.onTutorialSkipClick}
>
Skip
</Button>
<Button
icon="tick"
className="AcceptRejectButton"
intent="success"
onClick={this.onTutorialAcceptClick}
>
Accept
</Button>
</div>
</div>
);
}
}
class EndScreen extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
sendEnd() {
// When the user clicks end,
// that choice gets sent to flask.
fetch("/end", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
ready_to_end: "ready",
}),
});
}
render() {
return (
<div
className="EndScreen"
style={{
backgroundImage: "url('" + astronaut + "')",
}}
>
<div className="EndScreen_Text">Mission accomplished! Good job!</div>
{/* <Sparkle /> */}
<Button
icon="tick"
className="AcceptRejectButton"
intent="success"
onClick={this.sendEnd}
>
Close
</Button>
</div>
);
}
}<file_sep>import React from "react";
import "../styles.css";
import TinderCard from "react-tinder-card";
import Timer from "./timer";
import { Button, ProgressBar, Icon } from "@blueprintjs/core";
import "normalize.css";
import "@blueprintjs/icons/lib/css/blueprint-icons.css";
import "@blueprintjs/core/lib/css/blueprint.css";
import { TransformWrapper, TransformComponent } from "react-zoom-pan-pinch";
import Clipboard from "clipboard";
class SwipeScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
batchTotal: this.props.batch_size,
// progWidth: this.props.progWidth,
};
//bind functions
this.decideCountText = this.decideCountText.bind(this);
this.onSwipe = this.onSwipe.bind(this);
this.onKeyPress = this.onKeyPress.bind(this);
}
componentWillMount() {
document.addEventListener("keyup", this.onKeyPress, false);
}
componentWillUnmount() {
// Removes the key press event listener if this component is replaced by another component or view.
// (Currently there are no other components to replace this view, however.)
document.removeEventListener("keyup", this.onKeyPress);
}
onSwipe = (direction) => {
// From TinderCard
this.setState({
loading: true,
});
if (direction === "right") {
this.props.onAcceptClick();
} else if (direction === "left") {
this.props.onRejectClick();
} else if (direction === "down") {
this.props.onSkipClick();
}
};
onKeyPress = (event) => {
// Key press alternatives
if (event.key === "ArrowRight") {
this.props.onAcceptClick();
} else if (event.key === "ArrowLeft") {
this.props.onRejectClick();
} else if (event.key === "ArrowDown") {
this.props.onSkipClick();
}
};
decideCountText() {
//Helper function to render progress of correct width on the progress bar
let text = "";
let y;
y = this.props.imagesLeft;
if (this.props.imagesLeft > this.props.batch_size) {
console.log("the condition reached!");
y = this.props.batch_size;
}
if (y == 0) {
text = "Last Image!";
return text;
}
if (y !== 1) text = y + " images left in batch!";
else text = y + " image left in batch!";
return text;
}
detectTouch() {
return (
"ontouchstart" in window ||
navigator.maxTouchPoints > 0 ||
navigator.msMaxTouchPoints > 0
);
}
detectMob() {
// helper function to check type of device(mobile/desktop)
const toMatch = [
/Android/i,
/webOS/i,
/iPhone/i,
/iPad/i,
/iPod/i,
/BlackBerry/i,
/Windows Phone/i,
];
return toMatch.some((toMatchItem) => {
return navigator.userAgent.match(toMatchItem);
});
}
decideImgRender() {
let obj;
if (!this.detectTouch()) {
console.log("Not touch!");
} else console.log("touch");
if (this.detectMob()) {
obj = (
<TinderCard
onSwipe={this.onSwipe}
preventSwipe={["right", "left", "down", "up"]}
>
<img src={this.props.image} alt="" />
</TinderCard>
);
} else if (this.detectTouch()) {
obj = (
<TinderCard
onSwipe={this.onSwipe}
preventSwipe={["right", "left", "down", "up"]}
>
<img src={this.props.image} alt="" />
</TinderCard>
);
} else {
obj = (
<TinderCard
onSwipe={this.onSwipe}
preventSwipe={["right", "left", "down", "up"]}
>
<TransformWrapper
options={{ centerContent: true }}
defaultPositionX={50}
>
<TransformComponent>
<img src={this.props.image} alt="" />
</TransformComponent>
</TransformWrapper>
</TinderCard>
);
}
return obj;
}
render() {
let count_text = this.decideCountText();
// console.log("x1= ", x);
let obj = this.decideImgRender();
var clipboard = new Clipboard(".clipboard");
return (
<>
{console.log("swipscreen props= ", this.props)}
<div className="header">
<div className="count">
<div className="timer">
<Timer />
</div>
<div className="ct-grp">
<span className="ct-grp-upper-text">{count_text}</span>
<br></br>
{/* <span className="ct-grp-lower-text">
{this.props.labeledSize} out of {this.props.total_batch_size}{" "}
images labelled
</span> */}
<br></br>
</div>
<div className="button-grp">
<Button
className="quit-button"
intent="danger"
onClick={this.props.onQuitClick}
small={true}
>
<Icon icon="cross" iconSize={20} intent="danger" />{" "}
</Button>
<Button
id="share-button"
className="clipboard"
data-clipboard-target="#blank"
data-clipboard-text={window.location.href}
intent="primary"
small={true}
onClick={() => alert("Link copied to clipboard!")}
>
<Icon icon="share" iconSize={20} />
</Button>
</div>
</div>
</div>
<div id="#SwipeScreen" className="Content">
<div className="Image_wrapper">
<div className={this.props.displayProg}>
<ProgressBar
intent="success"
value={this.props.progWidth}
// value={0.6}
animate={false}
></ProgressBar>
</div>
{obj}
</div>
<div className="footer">
<input type="text" id="blank" value={window.location.href} />
<Button
icon="arrow-down"
className="AcceptRejectButton"
intent="primary"
onClick={this.props.onSkipClick}
>
Skip
</Button>
<Button
icon="arrow-left"
className="AcceptRejectButton"
intent="danger"
onClick={this.props.onRejectClick}
>
Reject
</Button>
<Button
rightIcon="arrow-right"
className="AcceptRejectButton"
intent="success"
onClick={() => {
this.props.onAcceptClick();
}}
>
Accept
</Button>
<Button
icon="undo"
disabled={this.props.undoHappened}
// className="BackButton"
className="AcceptRejectButton"
onClick={this.props.onBackClick}
>
Undo
</Button>
</div>
</div>
</>
);
}
}
export { SwipeScreen };
<file_sep>import React from "react";
import "./styles.css";
import { Button } from "@blueprintjs/core";
import { SwipeScreen } from "./components/swipescreen";
import { TutorialScreen } from "./components/tutorialscreen";
import { EndScreen } from "./components/endscreen";
import { Welcome } from "./components/welcomescreen";
import "normalize.css";
import "@blueprintjs/icons/lib/css/blueprint-icons.css";
import "@blueprintjs/core/lib/css/blueprint.css";
import axios from "axios";
function hasSeenTutorial() {
// Checks for a cookie on the users computer that will tell the user has already done the tutorial.
return document.cookie
.split(";")
.some((item) => item.trim().startsWith("hasSeenTutorial="));
}
function setTutorialSeen() {
console.log("tutorial will be set to seen!");
document.cookie = "hasSeenTutorial=true";
}
export default class App extends React.Component {
// Main component
constructor(props) {
super(props);
this.state = {
view: hasSeenTutorial() ? "active" : "welcome",
// view: "welcome",
index: 0,
image: null,
total_batch_size: null,
batch_size: null,
imgUrls: [],
undoUrls: [],
undoHappened: true,
swipes: 0,
noOfSwipes: 0,
batchStop: 0,
leftBehind: 0,
labeledSize: 0,
progWidth: 0,
displayProg: "prog-bar",
};
// bind functions
this.fetchImage = this.fetchImage.bind(this);
this.sendSelection = this.sendSelection.bind(this);
this.onAcceptClick = this.onAcceptClick.bind(this);
this.onRejectClick = this.onRejectClick.bind(this);
this.onSkipClick = this.onSkipClick.bind(this);
this.onBackClick = this.onBackClick.bind(this);
this.onQuitClick = this.onQuitClick.bind(this);
this.endTutorial = this.endTutorial.bind(this);
this.startTutorial = this.startTutorial.bind(this);
this.startLabel = this.startLabel.bind(this);
this.setLoading = this.setLoading.bind(this);
this.getBatchSize = this.getBatchSize.bind(this);
this.decideProgWidth = this.decideProgWidth.bind(this);
}
componentDidMount() {
// When the app loads,get the batch size and 1 image url from flask.
//refresh handler - to copy the images back to unlabeled incase user hits refresh
if (window.performance) {
if (performance.navigation.type === 1) {
//Send the current image to unlabeled
// If undo stack has a url, send that as well to unlabeled
let image_url = sessionStorage.getItem("url");
let curr_image_url = sessionStorage.getItem("undo-url");
if (curr_image_url === image_url) {
curr_image_url = "none";
}
console.log("Image url: ", image_url);
console.log("Curr_Image url: ", curr_image_url);
axios
.post("/refresh", {
image_url: image_url,
curr_image_url: curr_image_url,
})
.then((res) => {
console.log(res);
})
.catch((err) => console.log("ERROR: ", err));
}
}
let x = parseInt(sessionStorage.getItem("noOfSwipes"));
if (!x) x = 0;
this.setState({
noOfSwipes: x,
});
this.getTotalBatchSize();
this.fetchImage();
}
componentDidUpdate() {
if (this.state.view === "end") {
//change session storage before moving to endscreen
console.log("reached end");
sessionStorage.setItem(`noOfSwipes`, 0);
} else {
// load the current image onto session storage, to be moved later incase user hits refresh
sessionStorage.setItem(`undo-url`, this.state.curr_image_url);
sessionStorage.setItem(`url`, this.state.image);
sessionStorage.setItem(`noOfSwipes`, this.state.noOfSwipes);
}
}
getTotalBatchSize() {
axios
.get("/getsize")
.then((res) => {
console.log("response = ", res.data.batch_size);
this.setState(
{
total_batch_size: res.data.batch_size,
batchStop: res.data.batch_stop,
imagesLeft: res.data.batch_stop - 1,
},
() => {
console.log("got total batch state as: ", this.state.batch_size);
}
);
})
.catch((err) => console.log("ERROR: ", err));
}
getBatchSize() {
axios
.get("/getsize")
.then((res) => {
console.log("response = ", res.data.batch_size);
this.setState(
{
batch_size: res.data.batch_size,
labeledSize: res.data.labeled_size,
},
() => {
console.log("got total batch state as: ", this.state.batch_size);
}
);
})
.catch((err) => console.log("ERROR: ", err));
}
fetchImage() {
// Collect one image url from flask
let url;
if (this.state.leftBehind !== 0) {
url = this.state.undoUrls.pop();
this.setState({
leftBehind: this.state.leftBehind - 1,
});
} else url = "none";
axios
.post("/image", {
swipes: this.state.swipes + 1,
image_url: url || "none",
})
.then((res) => {
if (res.data.image === "none")
this.setState({
view: "end",
});
else {
let x = this.state.imgUrls;
//check if res.data.image is in x before pushing to x
x.push(res.data.image);
let url = this.state.imgUrls[this.state.index]
? this.state.imgUrls[this.state.index]
: "none";
let s = this.state.noOfSwipes + this.state.leftBehind;
this.setState(
{
image: res.data.image,
imgUrls: x,
curr_image_url: url,
swipes: s,
},
() => {
console.log("img ", typeof this.state.image);
this.getBatchSize();
}
);
}
})
.catch((err) => console.log("ERROR: ", err));
}
setLoading(s) {
console.log("reached ");
this.setState({
loading: s,
});
}
sendSelection(value) {
// When the user swipes, clicks, or presses a choice (accept or reject),
// that choice gets sent to flask.
fetch("/submit", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
image_url: this.state.image,
value: value,
}),
});
}
decideProgWidth() {
if (this.state.batchStop > this.state.total_batch_size) {
console.log("reached block");
this.setState({
displayProg: "prog-bar",
msg: "reached!",
});
this.setState(
{
progWidth: this.state.noOfSwipes / (this.state.batch_size + 1),
msg: " reach",
},
() => {
console.log(this.state.msg);
}
);
} else {
let x = this.state.batchStop;
this.setState(
{
progWidth: this.state.noOfSwipes / this.state.batchStop,
msg: "didnt reach",
},
() => {
console.log(this.state.msg);
}
);
}
}
onAcceptClick() {
// Send the positive label to flask, make call to /image to get the next image from flask
// and update the index so the next image will show.
this.setState(
{
index: this.state.index + 1,
noOfSwipes: this.state.noOfSwipes + 1,
swipes: this.state.noOfSwipes + this.state.leftBehind,
undoHappened: false,
imagesLeft: this.state.imagesLeft - 1,
},
() => {
this.sendSelection(1);
this.decideProgWidth();
if (this.state.noOfSwipes === this.state.batchStop)
this.setState({
view: "end",
});
else this.fetchImage();
}
);
}
onSkipClick() {
// Send no label to flask, mark as ambigous with constant value 10
// and update the index so the next image will show.
this.setState(
{
index: this.state.index + 1,
noOfSwipes: this.state.noOfSwipes + 1,
swipes: this.state.noOfSwipes + this.state.leftBehind,
undoHappened: false,
imagesLeft: this.state.imagesLeft - 1,
},
() => {
this.sendSelection(2);
this.decideProgWidth();
if (this.state.noOfSwipes === this.state.batchStop)
this.setState({
view: "end",
});
else this.fetchImage();
}
);
}
onRejectClick() {
// Send the negative label to flask,
// and update the index so the next image will show.
this.setState(
{
index: this.state.index + 1,
noOfSwipes: this.state.noOfSwipes + 1,
swipes: this.state.noOfSwipes + this.state.leftBehind,
undoHappened: false,
imagesLeft: this.state.imagesLeft - 1,
},
() => {
this.sendSelection(0);
this.decideProgWidth();
if (this.state.noOfSwipes === this.state.batchStop)
this.setState({
view: "end",
});
else this.fetchImage();
}
);
}
onBackClick() {
// add the image which is going to be undone to url stack and request the same image from flask
let x = this.state.imgUrls;
let y = this.state.undoUrls;
x.push(this.state.imgUrls[this.state.index - 1]);
y.push(this.state.imgUrls[this.state.index]);
axios
.post("/undo", {
image_url: this.state.imgUrls[this.state.index - 1],
})
.then((res) => {
console.log(res);
this.setState(
{
index: this.state.index + 1,
image: this.state.imgUrls[this.state.index - 1],
imgUrls: x,
undoUrls: y,
noOfSwipes: this.state.noOfSwipes - 1,
leftBehind: this.state.leftBehind + 1,
undoHappened: true,
imagesLeft: this.state.imagesLeft + 1,
},
() => {
this.decideProgWidth();
}
);
})
.catch((err) => console.log("ERROR: ", err));
}
onQuitClick() {
//Send the current image to unlabeled
// If undo stack has a url, send that as well to unlabeled
let image_url, curr_image_url;
if (this.state.undoHappened && this.state.index) {
image_url = this.state.image;
curr_image_url = this.state.undoUrls[0];
} else {
image_url = this.state.curr_image_url;
curr_image_url = "none";
}
axios
.post("/quit", {
image_url: image_url,
curr_image_url: curr_image_url,
})
.then((res) => {
console.log(res);
this.setState({
view: "end",
});
})
.catch((err) => console.log("ERROR: ", err));
}
startTutorial() {
console.log("hello world from start");
this.setState({
view: "tutorial",
});
}
startLabel() {
this.setState({
view: "active",
});
}
endTutorial() {
this.setState({
view: "active",
});
// Set a cookie on the user's browser so they don't see the tutorial again.
setTutorialSeen();
}
render() {
var body = null;
{
console.log("Parent state\n", this.state.images);
}
let toContinue;
if (this.state.batch_size <= 0) toContinue = false;
else toContinue = true;
let displayProg;
if (this.state.batchStop > this.state.total_batch_size) {
console.log("reached if block!");
displayProg = "prg-bar";
// displayProg = "prog-bar";
} else {
displayProg = "prog-bar";
}
if (this.state.view === "welcome")
body = (
<Welcome
startTutorial={this.startTutorial}
startLabel={this.startLabel}
/>
);
else if (this.state.view === "tutorial")
body = <TutorialScreen end={this.endTutorial} />;
else if (this.state.view === "active")
body = this.state.image ? (
<SwipeScreen
index={this.state.index}
undoHappened={this.state.undoHappened}
total_batch_size={this.state.total_batch_size}
swipes={this.state.swipes}
batch_size={this.state.batch_size}
labeledSize={this.state.labeledSize}
image={this.state.image}
onAcceptClick={this.onAcceptClick}
onRejectClick={this.onRejectClick}
onSkipClick={this.onSkipClick}
onBackClick={this.onBackClick}
onQuitClick={this.onQuitClick}
time={this.state.time}
batchStop={this.state.batchStop}
noOfSwipes={this.state.noOfSwipes}
imagesLeft={this.state.imagesLeft}
progWidth={this.state.progWidth}
displayProg={displayProg}
/>
) : (
<Button loading={true} />
);
else if (this.state.view === "end") {
// body = <EndScreen continue={toContinue} />;
if (this.state.batch_size - 1 <= 0)
body = <EndScreen setTutorialSeen={setTutorialSeen} />;
else
body = (
<EndScreen continue={toContinue} setTutorialSeen={setTutorialSeen} />
);
}
return <div className="App">{body}</div>;
}
}
<file_sep>import React , {useState} from 'react';
export default function Timer(){
const [time,setTime] = useState(1);
setTimeout(()=>setTime(time+1),1000);
return (
<>
<strong>{time}</strong>
</>
)
} | fa01fc215dd3f3b9535b8a56ee8114152bf84956 | [
"Markdown",
"Python",
"JavaScript"
] | 7 | Markdown | spaceml-org/Swipe-Labeler | b8742a25d5ef0f74ccc6f73293c8e0a08fae0ab2 | eb7171e565163c4d8033a6520ece5ef0e14294c2 |
refs/heads/master | <repo_name>VedantSupe/css-inline<file_sep>/bindings/wasm/CHANGELOG.md
# Changelog
## [Unreleased]
## [0.7.5] - 2021-07-24
### Fixed
- Panic on invalid URLs for remote stylesheets.
## [0.7.4] - 2021-07-06
### Performance
- Optimize loading of external files.
## [0.7.3] - 2021-06-24
### Performance
- Improve performance for error handling.
## [0.7.2] - 2021-06-22
### Fixed
- Incorrect override of exiting `style` attribute values. [#113](https://github.com/Stranger6667/css-inline/issues/113)
### Performance
- Minor performance improvements
## [0.7.1] - 2021-06-10
### Fixed
- Ignored `style` tags when the document contains multiple of them and the `remove_style_tags: true` config option is used. [#110](https://github.com/Stranger6667/css-inline/issues/110)
## [0.7.0] - 2021-06-09
### Fixed
- Ignored selectors specificity. [#108](https://github.com/Stranger6667/css-inline/issues/108)
## [0.6.1] - 2020-12-07
### Fixed
- Compatibility with the new `cssparser` crate version.
### Performance
- Avoid string allocations during converting `InlineError` to `JsValue`.
## [0.6.0] - 2020-11-02
### Changed
- Links to remote stylesheets are deduplicated now.
### Performance
- Use `Formatter.write_str` instead of `write!` macro in the `Display` trait implementation for `InlineError`. [#85](https://github.com/Stranger6667/css-inline/issues/85)
- Use `Cow` for error messages. [#87](https://github.com/Stranger6667/css-inline/issues/87)
## [0.5.0] - 2020-08-07
### Performance
- Avoid string allocation in `get_full_url`
## [0.4.0] - 2020-07-13
- Initial public release
[Unreleased]: https://github.com/Stranger6667/css-inline/compare/wasm-v0.7.5...HEAD
[0.7.5]: https://github.com/Stranger6667/css-inline/compare/wasm-v0.7.4...wasm-v0.7.5
[0.7.4]: https://github.com/Stranger6667/css-inline/compare/wasm-v0.7.3...wasm-v0.7.3
[0.7.3]: https://github.com/Stranger6667/css-inline/compare/wasm-v0.7.2...wasm-v0.7.3
[0.7.2]: https://github.com/Stranger6667/css-inline/compare/wasm-v0.7.1...wasm-v0.7.2
[0.7.1]: https://github.com/Stranger6667/css-inline/compare/wasm-v0.7.0...wasm-v0.7.1
[0.7.0]: https://github.com/Stranger6667/css-inline/compare/wasm-v0.6.1...wasm-v0.7.0
[0.6.1]: https://github.com/Stranger6667/css-inline/compare/wasm-v0.6.0...wasm-v0.6.1
[0.6.0]: https://github.com/Stranger6667/css-inline/compare/wasm-v0.5.0...wasm-v0.6.0
[0.5.0]: https://github.com/Stranger6667/css-inline/compare/wasm-v0.4.1...wasm-v0.5.0
[0.4.1]: https://github.com/Stranger6667/css-inline/compare/wasm-v0.4.0...wasm-v0.4.1
<file_sep>/css-inline/src/lib.rs
//! # css-inline
//!
//! A crate for inlining CSS into HTML documents. When you send HTML emails, you need to use "style"
//! attributes instead of "style" tags.
//!
//! For example, this HTML:
//!
//! ```html
//! <html>
//! <head>
//! <title>Test</title>
//! <style>h1 { color:blue; }</style>
//! </head>
//! <body>
//! <h1>Big Text</h1>
//! </body>
//! </html>
//! ```
//!
//! Will be turned into this:
//!
//! ```html
//! <html>
//! <head><title>Test</title></head>
//! <body>
//! <h1 style="color:blue;">Big Text</h1>
//! </body>
//! </html>
//! ```
//!
//! ## Usage
//!
//! ```rust
//! const HTML: &str = r#"<html>
//! <head>
//! <title>Test</title>
//! <style>h1 { color:blue; }</style>
//! </head>
//! <body>
//! <h1>Big Text</h1>
//! </body>
//! </html>"#;
//!
//!fn main() -> Result<(), css_inline::InlineError> {
//! let inlined = css_inline::inline(HTML)?; // shortcut with default options
//! // Do something with inlined HTML, e.g. send an email
//! Ok(())
//! }
//! ```
//!
//! ### Features & Configuration
//!
//! `css-inline` can be configured by using `CSSInliner::options()` that implements the Builder pattern:
//!
//! ```rust
//! const HTML: &str = r#"<html>
//! <head>
//! <title>Test</title>
//! <style>h1 { color:blue; }</style>
//! </head>
//! <body>
//! <h1>Big Text</h1>
//! </body>
//! </html>"#;
//!
//! fn main() -> Result<(), css_inline::InlineError> {
//! let inliner = css_inline::CSSInliner::options()
//! .load_remote_stylesheets(false)
//! .build();
//! let inlined = inliner.inline(HTML);
//! // Do something with inlined HTML, e.g. send an email
//! Ok(())
//! }
//! ```
//!
//! - `inline_style_tags`. Whether to inline CSS from "style" tags. Default: `true`
//! - `remove_style_tags`. Remove "style" tags after inlining. Default: `false`
//! - `base_url`. Base URL to resolve relative URLs. Default: `None`
//! - `load_remote_stylesheets`. Whether remote stylesheets should be loaded or not. Default: `true`
//! - `extra_css`. Additional CSS to inline. Default: `None`
//!
#![warn(
clippy::doc_markdown,
clippy::redundant_closure,
clippy::explicit_iter_loop,
clippy::match_same_arms,
clippy::needless_borrow,
clippy::print_stdout,
clippy::integer_arithmetic,
clippy::cast_possible_truncation,
clippy::unwrap_used,
clippy::map_unwrap_or,
clippy::trivially_copy_pass_by_ref,
clippy::needless_pass_by_value,
missing_docs,
missing_debug_implementations,
trivial_casts,
trivial_numeric_casts,
unreachable_pub,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
variant_size_differences,
rust_2018_idioms,
rust_2018_compatibility
)]
use attohttpc::{Method, RequestBuilder};
use kuchiki::{
parse_html, traits::TendrilSink, ElementData, Node, NodeDataRef, NodeRef, Specificity,
};
pub mod error;
mod parser;
use ahash::AHashMap;
pub use error::InlineError;
use smallvec::{smallvec, SmallVec};
use std::{borrow::Cow, collections::hash_map::Entry, fs, io::Write};
pub use url::{ParseError, Url};
/// Configuration options for CSS inlining process.
#[derive(Debug)]
pub struct InlineOptions<'a> {
/// Whether to inline CSS from "style" tags.
pub inline_style_tags: bool,
/// Remove "style" tags after inlining.
pub remove_style_tags: bool,
/// Used for loading external stylesheets via relative URLs.
pub base_url: Option<Url>,
/// Whether remote stylesheets should be loaded or not.
pub load_remote_stylesheets: bool,
// The point of using `Cow` here is Python bindings, where it is problematic to pass a reference
// without dealing with memory leaks & unsafe. With `Cow` we can use moved values as `String` in
// Python wrapper for `CSSInliner` and `&str` in Rust & simple functions on the Python side
/// Additional CSS to inline.
pub extra_css: Option<Cow<'a, str>>,
}
impl<'a> InlineOptions<'a> {
/// Options for "compact" HTML output.
#[must_use]
#[inline]
pub const fn compact() -> Self {
InlineOptions {
inline_style_tags: true,
remove_style_tags: true,
base_url: None,
load_remote_stylesheets: true,
extra_css: None,
}
}
/// Override whether "style" tags should be inlined.
#[must_use]
pub fn inline_style_tags(mut self, inline_style_tags: bool) -> Self {
self.inline_style_tags = inline_style_tags;
self
}
/// Override whether "style" tags should be removed after processing.
#[must_use]
pub fn remove_style_tags(mut self, remove_style_tags: bool) -> Self {
self.remove_style_tags = remove_style_tags;
self
}
/// Set base URL that will be used for loading external stylesheets via relative URLs.
#[must_use]
pub fn base_url(mut self, base_url: Option<Url>) -> Self {
self.base_url = base_url;
self
}
/// Override whether remote stylesheets should be loaded.
#[must_use]
pub fn load_remote_stylesheets(mut self, load_remote_stylesheets: bool) -> Self {
self.load_remote_stylesheets = load_remote_stylesheets;
self
}
/// Set additional CSS to inline.
#[must_use]
pub fn extra_css(mut self, extra_css: Option<Cow<'a, str>>) -> Self {
self.extra_css = extra_css;
self
}
/// Create a new `CSSInliner` instance from this options.
#[must_use]
pub const fn build(self) -> CSSInliner<'a> {
CSSInliner::new(self)
}
}
impl Default for InlineOptions<'_> {
#[inline]
fn default() -> Self {
InlineOptions {
inline_style_tags: true,
remove_style_tags: false,
base_url: None,
load_remote_stylesheets: true,
extra_css: None,
}
}
}
type Result<T> = std::result::Result<T, InlineError>;
/// Customizable CSS inliner.
#[derive(Debug)]
pub struct CSSInliner<'a> {
options: InlineOptions<'a>,
}
impl<'a> CSSInliner<'a> {
/// Create a new `CSSInliner` instance with given options.
#[must_use]
#[inline]
pub const fn new(options: InlineOptions<'a>) -> Self {
CSSInliner { options }
}
/// Return a default `InlineOptions` that can fully configure the CSS inliner.
///
/// # Examples
///
/// Get default `InlineOptions`, then change base url
///
/// ```rust
/// use url::Url;
/// use css_inline::CSSInliner;
/// # use url::ParseError;
/// # fn run() -> Result<(), ParseError> {
/// let url = Url::parse("https://api.example.com")?;
/// let inliner = CSSInliner::options()
/// .base_url(Some(url))
/// .build();
/// # Ok(())
/// # }
/// # run().unwrap();
/// ```
#[must_use]
#[inline]
pub fn options() -> InlineOptions<'a> {
InlineOptions::default()
}
/// Inliner, that will produce "compact" HTML.
/// For example, "style" tags will be removed.
#[must_use]
#[inline]
pub const fn compact() -> Self {
CSSInliner {
options: InlineOptions::compact(),
}
}
/// Inline CSS styles from <style> tags to matching elements in the HTML tree and return a
/// string.
#[inline]
pub fn inline(&self, html: &str) -> Result<String> {
// Allocating the same amount of memory as the input HTML helps to avoid
// some allocations, but most probably the output size will be different than
// the original HTML
let mut out = Vec::with_capacity(html.len());
self.inline_to(html, &mut out)?;
Ok(String::from_utf8_lossy(&out).to_string())
}
/// Inline CSS & write the result to a generic writer. Use it if you want to write
/// the inlined document to a file.
#[inline]
pub fn inline_to<W: Write>(&self, html: &str, target: &mut W) -> Result<()> {
let document = parse_html().one(html);
// CSS rules may overlap, and the final set of rules applied to an element depend on
// selectors' specificity - selectors with higher specificity have more priority.
// Inlining happens in two major steps:
// 1. All available styles are mapped to respective elements together with their
// selector's specificity. When two rules overlap on the same declaration, then
// the one with higher specificity replaces another.
// 2. Resulting styles are merged into existing "style" tags.
#[allow(clippy::mutable_key_type)]
// Each matched element is identified by their raw pointers - they are evaluated once
// and then reused, which allows O(1) access to find them.
// Internally, their raw pointers are used to implement `Eq`, which seems like the only
// reasonable approach to compare them (performance-wise).
let mut styles = AHashMap::with_capacity(128);
let mut style_tags: SmallVec<[NodeDataRef<ElementData>; 4]> = smallvec![];
if self.options.inline_style_tags {
for style_tag in document
.select("style")
.map_err(|_| error::InlineError::ParseError(Cow::from("Unknown error")))?
{
if let Some(first_child) = style_tag.as_node().first_child() {
if let Some(css_cell) = first_child.as_text() {
process_css(&document, css_cell.borrow().as_str(), &mut styles);
}
}
if self.options.remove_style_tags {
style_tags.push(style_tag);
}
}
}
if self.options.remove_style_tags {
if !self.options.inline_style_tags {
style_tags.extend(
document
.select("style")
.map_err(|_| error::InlineError::ParseError(Cow::from("Unknown error")))?,
);
}
for style_tag in &style_tags {
style_tag.as_node().detach();
}
}
if self.options.load_remote_stylesheets {
let mut links = document
.select("link[rel~=stylesheet]")
.map_err(|_| error::InlineError::ParseError(Cow::from("Unknown error")))?
.filter_map(|link_tag| link_tag.attributes.borrow().get("href").map(str::to_string))
.filter(|link| !link.is_empty())
.collect::<Vec<String>>();
links.sort_unstable();
links.dedup();
for href in &links {
let url = self.get_full_url(href);
let css = load_external(url.as_ref())?;
process_css(&document, css.as_str(), &mut styles);
}
}
if let Some(extra_css) = &self.options.extra_css {
process_css(&document, extra_css, &mut styles);
}
for (node_id, styles) in styles {
// SAFETY: All nodes are alive as long as `document` is in scope.
// Therefore, any `document` children should be alive and it is safe to dereference
// pointers to them
let node = unsafe { &*node_id };
// It can be borrowed if the current selector matches <link> tag, that is
// already borrowed in `inline_to`. We can ignore such matches
if let Ok(mut attributes) = node
.as_element()
.expect("Element is expected")
.attributes
.try_borrow_mut()
{
if let Some(existing_style) = attributes.get_mut("style") {
*existing_style = merge_styles(existing_style, &styles)?;
} else {
let mut final_styles = String::with_capacity(128);
for (name, (_, value)) in styles {
final_styles.push_str(name.as_str());
final_styles.push(':');
final_styles.push_str(value.as_str());
final_styles.push(';');
}
attributes.insert("style", final_styles);
};
}
}
document.serialize(target)?;
Ok(())
}
fn get_full_url<'u>(&self, href: &'u str) -> Cow<'u, str> {
// Valid absolute URL
if Url::parse(href).is_ok() {
return Cow::Borrowed(href);
};
if let Some(base_url) = &self.options.base_url {
// Use the same scheme as the base URL
if href.starts_with("//") {
return Cow::Owned(format!("{}:{}", base_url.scheme(), href));
}
// Not a URL, then it is a relative URL
if let Ok(new_url) = base_url.join(href) {
return Cow::Owned(new_url.into());
}
};
// If it is not a valid URL and there is no base URL specified, we assume a local path
Cow::Borrowed(href)
}
}
fn load_external(location: &str) -> Result<String> {
if location.starts_with("https") | location.starts_with("http") {
let request = RequestBuilder::try_new(Method::GET, location)?;
let response = request.send()?;
Ok(response.text()?)
} else {
fs::read_to_string(location).map_err(InlineError::IO)
}
}
type NodeId = *const Node;
#[allow(clippy::mutable_key_type)]
fn process_css(
document: &NodeRef,
css: &str,
styles: &mut AHashMap<NodeId, AHashMap<String, (Specificity, String)>>,
) {
let mut parse_input = cssparser::ParserInput::new(css);
let mut parser = cssparser::Parser::new(&mut parse_input);
let rule_list =
cssparser::RuleListParser::new_for_stylesheet(&mut parser, parser::CSSRuleListParser);
for (selectors, declarations) in rule_list.flatten() {
// Only CSS Syntax Level 3 is supported, therefore it is OK to split by `,`
// With `is` or `where` selectors (Level 4) this split should be done on the parser level
for selector in selectors.split(',') {
if let Ok(matching_elements) = document.select(selector) {
// There is always only one selector applied
let specificity = matching_elements.selectors.0[0].specificity();
for matching_element in matching_elements {
let element_styles = styles
.entry(&**matching_element.as_node())
.or_insert_with(|| AHashMap::with_capacity(8));
for (name, value) in &declarations {
match element_styles.entry(name.to_string()) {
Entry::Occupied(mut entry) => {
if entry.get().0 <= specificity {
entry.insert((specificity, (*value).to_string()));
}
}
Entry::Vacant(entry) => {
entry.insert((specificity, (*value).to_string()));
}
}
}
}
}
// Skip selectors that can't be parsed
// Ignore not parsable entries. E.g. there is no parser for @media queries
// Which means that they will fall into this category and will be ignored
}
}
}
impl Default for CSSInliner<'_> {
#[inline]
fn default() -> Self {
CSSInliner::new(InlineOptions::default())
}
}
/// Shortcut for inlining CSS with default parameters.
#[inline]
pub fn inline(html: &str) -> Result<String> {
CSSInliner::default().inline(html)
}
/// Shortcut for inlining CSS with default parameters and writing the output to a generic writer.
#[inline]
pub fn inline_to<W: Write>(html: &str, target: &mut W) -> Result<()> {
CSSInliner::default().inline_to(html, target)
}
fn merge_styles(
existing_style: &str,
new_styles: &AHashMap<String, (Specificity, String)>,
) -> Result<String> {
// Parse existing declarations in the "style" attribute
let mut input = cssparser::ParserInput::new(existing_style);
let mut parser = cssparser::Parser::new(&mut input);
let declarations =
cssparser::DeclarationListParser::new(&mut parser, parser::CSSDeclarationListParser);
// New rules should not override old ones and we store selectors inline to check the old rules later
let mut buffer: SmallVec<[String; 8]> = smallvec![];
let mut final_styles = String::with_capacity(256);
for declaration in declarations {
let (name, value) = declaration?;
final_styles.push_str(&name);
final_styles.push(':');
final_styles.push_str(value);
final_styles.push(';');
// This property won't be taken from new styles
buffer.push(name.to_string())
}
for (property, (_, value)) in new_styles {
if !buffer.contains(property) {
final_styles.push_str(property);
final_styles.push(':');
final_styles.push_str(value);
final_styles.push(';');
}
}
Ok(final_styles)
}
<file_sep>/bindings/python/build-sdist.sh
#!/bin/bash
set -ex
# Create a symlink for css-inline
ln -sf ../../css-inline css-inline-lib
# Modify Cargo.toml to include this symlink
cp Cargo.toml Cargo.toml.orig
sed -i 's/\.\.\/\.\.\/css-inline/\.\/css-inline-lib/' Cargo.toml
# Build the source distribution
python setup.py sdist
rm css-inline-lib
mv Cargo.toml.orig Cargo.toml
<file_sep>/bindings/python/src/lib.rs
//! Python bindings for css-inline
#![warn(
clippy::pedantic,
clippy::doc_markdown,
clippy::redundant_closure,
clippy::explicit_iter_loop,
clippy::match_same_arms,
clippy::needless_borrow,
clippy::print_stdout,
clippy::integer_arithmetic,
clippy::cast_possible_truncation,
clippy::unwrap_used,
clippy::map_unwrap_or,
clippy::trivially_copy_pass_by_ref,
clippy::needless_pass_by_value,
missing_debug_implementations,
trivial_casts,
trivial_numeric_casts,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
variant_size_differences,
rust_2018_idioms,
rust_2018_compatibility
)]
use css_inline as rust_inline;
use pyo3::{create_exception, exceptions, prelude::*, types::PyList, wrap_pyfunction};
use rayon::prelude::*;
use std::borrow::Cow;
const INLINE_ERROR_DOCSTRING: &str = "An error that can occur during CSS inlining";
create_exception!(css_inline, InlineError, exceptions::PyValueError);
struct InlineErrorWrapper(rust_inline::InlineError);
impl From<InlineErrorWrapper> for PyErr {
fn from(error: InlineErrorWrapper) -> Self {
match error.0 {
rust_inline::InlineError::IO(error) => InlineError::new_err(error.to_string()),
rust_inline::InlineError::Network(error) => InlineError::new_err(error.to_string()),
rust_inline::InlineError::ParseError(message) => {
InlineError::new_err(message.to_string())
}
}
}
}
struct UrlError(url::ParseError);
impl From<UrlError> for PyErr {
fn from(error: UrlError) -> Self {
exceptions::PyValueError::new_err(error.0.to_string())
}
}
fn parse_url(url: Option<String>) -> PyResult<Option<url::Url>> {
Ok(if let Some(url) = url {
Some(url::Url::parse(url.as_str()).map_err(UrlError)?)
} else {
None
})
}
/// CSSInliner(inline_style_tags=True, remove_style_tags=False, base_url=None, load_remote_stylesheets=True, extra_css=None)
///
/// Customizable CSS inliner.
#[pyclass]
#[pyo3(
text_signature = "(inline_style_tags=True, remove_style_tags=False, base_url=None, load_remote_stylesheets=True, extra_css=None)"
)]
struct CSSInliner {
inner: rust_inline::CSSInliner<'static>,
}
#[pymethods]
impl CSSInliner {
#[new]
fn new(
inline_style_tags: Option<bool>,
remove_style_tags: Option<bool>,
base_url: Option<String>,
load_remote_stylesheets: Option<bool>,
extra_css: Option<String>,
) -> PyResult<Self> {
let options = rust_inline::InlineOptions {
inline_style_tags: inline_style_tags.unwrap_or(true),
remove_style_tags: remove_style_tags.unwrap_or(false),
base_url: parse_url(base_url)?,
load_remote_stylesheets: load_remote_stylesheets.unwrap_or(true),
extra_css: extra_css.map(Cow::Owned),
};
Ok(CSSInliner {
inner: rust_inline::CSSInliner::new(options),
})
}
/// inline(html)
///
/// Inline CSS in the given HTML document
#[pyo3(text_signature = "(html)")]
fn inline(&self, html: &str) -> PyResult<String> {
Ok(self.inner.inline(html).map_err(InlineErrorWrapper)?)
}
/// inline_many(htmls)
///
/// Inline CSS in multiple HTML documents
#[pyo3(text_signature = "(htmls)")]
fn inline_many(&self, htmls: &PyList) -> PyResult<Vec<String>> {
inline_many_impl(&self.inner, htmls)
}
}
/// inline(html, inline_style_tags=True, remove_style_tags=False, base_url=None, load_remote_stylesheets=True, extra_css=None)
///
/// Inline CSS in the given HTML document
#[pyfunction]
#[pyo3(
text_signature = "(html, inline_style_tags=True, remove_style_tags=False, base_url=None, load_remote_stylesheets=True, extra_css=None)"
)]
fn inline(
html: &str,
inline_style_tags: Option<bool>,
remove_style_tags: Option<bool>,
base_url: Option<String>,
load_remote_stylesheets: Option<bool>,
extra_css: Option<&str>,
) -> PyResult<String> {
let options = rust_inline::InlineOptions {
inline_style_tags: inline_style_tags.unwrap_or(true),
remove_style_tags: remove_style_tags.unwrap_or(false),
base_url: parse_url(base_url)?,
load_remote_stylesheets: load_remote_stylesheets.unwrap_or(true),
extra_css: extra_css.map(Cow::Borrowed),
};
let inliner = rust_inline::CSSInliner::new(options);
Ok(inliner.inline(html).map_err(InlineErrorWrapper)?)
}
/// inline_many(htmls, inline_style_tags=True, remove_style_tags=False, base_url=None, load_remote_stylesheets=True, extra_css=None)
///
/// Inline CSS in multiple HTML documents
#[pyfunction]
#[pyo3(
text_signature = "(htmls, inline_style_tags=True, remove_style_tags=False, base_url=None, load_remote_stylesheets=True, extra_css=None)"
)]
fn inline_many(
htmls: &PyList,
inline_style_tags: Option<bool>,
remove_style_tags: Option<bool>,
base_url: Option<String>,
load_remote_stylesheets: Option<bool>,
extra_css: Option<&str>,
) -> PyResult<Vec<String>> {
let options = rust_inline::InlineOptions {
inline_style_tags: inline_style_tags.unwrap_or(true),
remove_style_tags: remove_style_tags.unwrap_or(false),
base_url: parse_url(base_url)?,
load_remote_stylesheets: load_remote_stylesheets.unwrap_or(true),
extra_css: extra_css.map(Cow::Borrowed),
};
let inliner = rust_inline::CSSInliner::new(options);
inline_many_impl(&inliner, htmls)
}
fn inline_many_impl(
inliner: &rust_inline::CSSInliner<'_>,
htmls: &PyList,
) -> PyResult<Vec<String>> {
// Extract strings from the list. It will fail if there is any non-string value
let extracted: Result<Vec<_>, _> = htmls.iter().map(pyo3::PyAny::extract::<&str>).collect();
let output: Result<Vec<_>, _> = extracted?
.par_iter()
.map(|html| inliner.inline(html))
.collect();
Ok(output.map_err(InlineErrorWrapper)?)
}
#[allow(dead_code)]
mod build {
include!(concat!(env!("OUT_DIR"), "/built.rs"));
}
/// Fast CSS inlining written in Rust
#[pymodule]
fn css_inline(py: Python<'_>, module: &PyModule) -> PyResult<()> {
module.add_class::<CSSInliner>()?;
module.add_wrapped(wrap_pyfunction!(inline))?;
module.add_wrapped(wrap_pyfunction!(inline_many))?;
let inline_error = py.get_type::<InlineError>();
inline_error.setattr("__doc__", INLINE_ERROR_DOCSTRING)?;
module.add("InlineError", inline_error)?;
// Wait until `pyo3_built` is updated
#[allow(deprecated)]
module.add("__build__", pyo3_built::pyo3_built!(py, build))?;
Ok(())
}
<file_sep>/css-inline/benches/inliner.rs
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use css_inline::{inline, CSSInliner, InlineError};
fn simple(c: &mut Criterion) {
let html = black_box(
r#"<html>
<head>
<title>Test</title>
<style>
h1, h2 { color:blue; }
strong { text-decoration:none }
p { font-size:2px }
p.footer { font-size: 1px}
</style>
</head>
<body>
<h1>Big Text</h1>
<p>
<strong>Solid</strong>
</p>
<p class="footer">Foot notes</p>
</body>
</html>"#,
);
c.bench_function("simple HTML", |b| b.iter(|| inline(html).unwrap()));
}
fn external(c: &mut Criterion) {
let html = black_box(
r#"<html>
<head><link href="benches/styles.css" rel="stylesheet" type="text/css"></head>
<body>
<h1>Big Text</h1>
<p>
<strong>Solid</strong>
</p>
<p class="footer">Foot notes</p>
</body>
</html>"#,
);
c.bench_function("External CSS", |b| b.iter(|| inline(html).unwrap()));
}
fn error_formatting(c: &mut Criterion) {
let error = black_box(InlineError::ParseError("Error description".into()));
c.bench_function("parse error formatting", |b| b.iter(|| error.to_string()));
}
fn io_error_formatting(c: &mut Criterion) {
let error = black_box(
inline(
r#"
<html>
<head><link href="unknown.css" rel="stylesheet" type="text/css"></head>
<body></body>
</html>"#,
)
.expect_err("It is an error"),
);
c.bench_function("io error formatting", |b| b.iter(|| error.to_string()));
}
fn network_error_formatting(c: &mut Criterion) {
let error = black_box(
inline(
r#"
<html>
<head><link href="http://127.0.0.1:0/unknown.css" rel="stylesheet" type="text/css"></head>
<body></body>
</html>"#,
)
.expect_err("It is an error"),
);
c.bench_function("network error formatting", |b| b.iter(|| error.to_string()));
}
fn merging(c: &mut Criterion) {
let html = black_box(
r#"<html>
<head>
<title>Test</title>
<style>
h1, h2 { color:blue; }
strong { text-decoration:none }
p { font-size:2px }
p.footer { font-size: 1px}
</style>
</head>
<body>
<h1 style="background-color: black;">Big Text</h1>
<p style="background-color: black;">
<strong style="background-color: black;">Solid</strong>
</p>
<p class="footer" style="background-color: black;">Foot notes</p>
</body>
</html>"#,
);
c.bench_function("merging styles", |b| b.iter(|| inline(html).unwrap()));
}
fn removing_tags(c: &mut Criterion) {
let html = black_box(
r#"<html>
<head>
<style>
h1 {
text-decoration: none;
}
</style>
<style>
.test-class {
color: #ffffff;
}
a {
color: #17bebb;
}
</style>
</head>
<body>
<a class="test-class" href="https://example.com">Test</a>
<h1>Test</h1>
</body>
</html>"#,
);
let inliner = CSSInliner::compact();
c.bench_function("removing tags", |b| {
b.iter(|| inliner.inline(html).unwrap())
});
}
fn big_email(c: &mut Criterion) {
let html = black_box(
r##"<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title> Newsletter</title>
<meta name="viewport" content="width = 620" />
<style type="text/css">
img {margin:0}
a.bluelink:link,a.bluelink:visited,a.bluelink:active {color:#5b7ab3; text-decoration: none}
a.bluelink:hover {color:#5b7ab3; text-decoration: underline}
</style>
<style media="only screen and (max-device-width: 480px)" type="text/css">
* {line-height: normal !important; -webkit-text-size-adjust: 125%}
</style>
</head>
<body bgcolor="#FFFFFF" style="margin:0; padding:0">
<table width="100%" bgcolor="#FFFFFF" cellpadding="0" cellspacing="0" align="center" border="2">
<tr>
<td style="padding: 30px"><!--
--><table width="636" border="0" cellspacing="0" cellpadding="0" align="center">
<tr>
<td width="636"><img src="http://images.apple.com/data/retail/us/topcap.gif" border="0" alt="" width="636" height="62" style="display:block" /></td>
</tr>
</table><!--
--><table width="636" border="1" cellspacing="0" cellpadding="0" align="center" bgcolor="#fffef6">
<tr>
<td width="59" valign="top" background="http://images.apple.com/data/retail/us/leftbg.gif"><img src="http://images.apple.com/data/retail/us/leftcap.gif" width="59" height="302" border="1" alt="" style="display:block" /></td>
<td width="500" align="left" valign="top"><!--
--><table width="500" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="379" align="left" valign="top">
<div><img src="http://images.apple.com/data/retail/us/headline.gif" width="330" height="29" border="1" alt="Thanks for making a reservation." style="display:block" /></div>
</td>
<td width="21" align="right" valign="top">
<div><img src="http://images.apple.com/data/retail/us/applelogo.gif" width="21" height="25" border="1" alt="" style="display:block" /></div>
</td>
</tr>
</table><!--
--><table width="500" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="500" align="left" valign="top">
<div><img src="http://images.apple.com/data/retail/us/line.gif" width="500" height="36" border="0" alt="" style="display:block" /></div>
</td>
</tr>
</table><!--
--><table width="500" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="10" align="left" valign="top"></td>
<td width="340" align="left" valign="top">
<div style="margin: 0; padding: 2px 10px 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color: #000000 !important; font-size:12px; line-height: 16px">Dear peter,</div>
<div style="margin: 0; padding: 12px 10px 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color: #000000 !important; font-size:12px; line-height: 16px">You are scheduled for a Genius Bar appointment.</div>
<div style="margin: 0; padding: 12px 10px 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color: #000000 !important; font-size:12px; line-height: 16px">Topic: <b>iPhone</b></div>
<div style="margin: 0; padding: 12px 10px 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color: #000000 !important; font-size:12px; line-height: 16px">Date: <b>Wednesday, Aug 26, 2009</b></div>
<div style="margin: 0; padding: 12px 10px 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color: #000000 !important; font-size:12px; line-height: 16px">Time: <b>11:10AM</b></div>
<div style="margin: 0; padding: 12px 10px 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color: #000000 !important; font-size:12px; line-height: 16px">Location: <b>Apple Store, Regent Street</b></div>
</td>
<td width="150" align="left" valign="top">
<div style="margin: 0; padding: 2px 0 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color:#808285; font-size:11px; line-height: 13px">Apple Store,</div>
<div style="margin: 0; padding: 0 0 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color:#808285; font-size:11px; line-height: 13px">Regent Street</div>
<div style="margin: 0; padding: 7px 0 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color:#808285; font-size:11px; line-height: 13px"><a href="http://concierge.apple.com/WebObjects/RRSServices.woa/wa/ics?id=ewoJInByaW1hcnlLZXkiID0gewoJCSJyZXNlcnZhdGlvbklEIiA9ICI1ODEyMDI2NCI7Cgl9OwoJImVudGl0eU5hbWUiID0gIlJlc2VydmF0aW9uIjsKfQ%3D%3D" style="font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; font-size:11px; color:#5b7ab3" class="bluelink">Add this to your calendar<img src="http://images.apple.com/data/retail/us/bluearrow.gif" width="8" height="8" border="0" alt="" style="display:inline; margin:0" /></a></div>
<div style="margin: 0; padding: 7px 0 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color:#808285; font-size:11px; line-height: 13px">If you are no longer able to attend this session, please <a href="http://concierge.apple.com/WebObjects/Concierge.woa/wa/cancelReservation?r=ewoJInByaW1hcnlLZXkiID0gewoJCSJyZXNlcnZhdGlvbklEIiA9ICI1ODEyMDI2NCI7Cgl9OwoJImVudGl0eU5hbWUiID0gIlJlc2VydmF0aW9uIjsKfQ%3D%3D" style="font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; font-size:11px; color:#5b7ab3" class="bluelink">cancel</a> or <a href="http://concierge.apple.com/WebObjects/Concierge.woa/wa/cancelReservation?r=ewoJInByaW1hcnlLZXkiID0gewoJCSJyZXNlcnZhdGlvbklEIiA9ICI1ODEyMDI2NCI7Cgl9OwoJImVudGl0eU5hbWUiID0gIlJlc2VydmF0aW9uIjsKfQ%3D%3D" style="font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; font-size:11px; color:#5b7ab3" class="bluelink">reschedule</a> your reservation.</div>
<div style="margin: 0; padding: 7px 0 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color:#808285; font-size:11px; line-height: 13px"><a href="http://www.apple.com/retail/../uk/retail/regentstreet/map" style="font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; font-size:11px; color:#5b7ab3" class="bluelink">Get directions to the store<img src="http://images.apple.com/data/retail/us/bluearrow.gif" width="8" height="8" border="0" alt="" style="display:inline; margin:0" /></a></div>
</td>
</tr>
</table><!--
--><table width="500" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="10"></td>
<td width="490" align="left" valign="top">
<br>
<div style="margin: 0; padding: 0 20px 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color: #000000 !important; font-size:12px; line-height: 16px">We look forward to seeing you.</div>
<div style="margin: 0; padding: 0 20px 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color: #000000 !important; font-size:12px; line-height: 16px">Your Apple Store team,</div>
<div style="margin: 0; padding: 0 20px 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color: #000000 !important; font-size:12px; line-height: 16px">Regent Street</div>
</td>
</tr>
</table><!--
--></td>
<td width="59" valign="top" background="http://images.apple.com/data/retail/us/rightbg.gif"><img src="http://images.apple.com/data/retail/us/rightcap.gif" width="77" height="302" border="0" alt="" style="display:block" /></td>
</tr>
</table><!--
--><table width="636" border="1" cellspacing="0" cellpadding="0" align="center">
<tr>
<td width="636"><img src="http://images.apple.com/data/retail/us/bottomcap.gif" border="0" alt="" width="636" height="62" style="display:block" /></td>
</tr>
</table><!--
BEGIN FOOTER
--><table width="498" border="1" cellspacing="0" cellpadding="0" align="center">
<tr>
<td style="padding-top:22px">
<div style="font-family: Geneva, Verdana, Arial, Helvetica, sans-serif; font-size:9px; line-height: 12px; color:#b4b4b4">TM and copyright © 2008 Apple Inc. 1 Infinite Loop, MS 303-3DM, Cupertino, CA 95014.</div>
<div style="font-family: Geneva, Verdana, Arial, Helvetica, sans-serif; font-size:9px; line-height: 12px; color:#b4b4b4"><a href="http://www.apple.com/legal/" style="font-family: Geneva, Verdana, Arial, Helvetica, sans-serif; font-size:9px;line-height: 12px; color:#b4b4b4; text-decoration:underline">All Rights Reserved</a> / <a href="http://www.apple.com/enews/subscribe/" style="font-family: Geneva, Verdana, Arial, Helvetica, sans-serif; font-size:9px; line-height: 12px;color:#b4b4b4; text-decoration:underline">Keep Informed</a> / <a href="http://www.apple.com/legal/privacy/" style="font-family: Geneva, Verdana, Arial, Helvetica, sans-serif; font-size:9px; line-height: 12px; color:#b4b4b4; text-decoration:underline">Privacy Policy</a> / <a href="https://myinfo.apple.com/cgi-bin/WebObjects/MyInfo/" style="font-family: Geneva, Verdana, Arial, Helvetica, sans-serif; font-size:9px; line-height: 12px; color:#b4b4b4; text-decoration:underline">My Info</a></div>
</td>
</tr>
</table><!--
--></td>
</tr>
</table>
</body>
</html>"##,
);
c.bench_function("big email", |b| b.iter(|| inline(html).unwrap()));
}
criterion_group!(
benches,
simple,
external,
merging,
removing_tags,
big_email,
error_formatting,
io_error_formatting,
network_error_formatting,
);
criterion_main!(benches);
<file_sep>/bindings/python/tox.ini
[tox]
# Skip Source distribution build to allow each task to install it via pip
# (workaround the fact that setup.py does not honor pyproject.toml)
skipsdist = True
envlist = py{36,37,38,39}
[testenv]
deps =
pytest
hypothesis
commands =
pip install -e . # Installing it within commands allow faster env build (NOTE: uses debug rust build)
python -m pytest tests-py {posargs:}
[testenv:build-sdist]
deps =
setuptools-rust
commands =
./build-sdist.sh
[testenv:build-wheel]
passenv =
PYTHON_SYS_EXECUTABLE
deps =
setuptools-rust
wheel
commands =
python setup.py bdist_wheel
<file_sep>/css-inline/Cargo.toml
[package]
name = "css-inline"
version = "0.7.5"
authors = ["<NAME> <<EMAIL>>"]
edition = "2018"
license = "MIT"
readme = "../README.md"
description = "A crate for inlining CSS into 'style' HTML attributes."
repository = "https://github.com/Stranger6667/css-inline"
keywords = ["html", "css", "css-inline", "email"]
exclude = [".github", ".pre-commit-config.yaml", ".yamllint", ".gitignore", "tests"]
categories = ["web-programming"]
[[bin]]
name = "css-inline"
[features]
default = ["cli"]
cli = ["pico-args", "rayon"]
[dependencies]
cssparser = "0.28"
kuchiki = "0.8"
attohttpc = { version = "0", default-features = false, features = ["compress", "tls-rustls"] }
url = "2"
smallvec = "1"
ahash = "0.7"
pico-args = { version = "0.3", optional = true }
rayon = { version = "1.5", optional = true }
[dev-dependencies]
criterion = ">= 0.1"
[[bench]]
name = "inliner"
harness = false
[profile.release]
lto = "fat"
codegen-units = 1
<file_sep>/bindings/python/benches/bench.py
import multiprocessing
from contextlib import suppress
import inlinestyler.utils
import premailer
import pynliner
import pytest
import css_inline
SIMPLE_HTML = """<html>
<head>
<title>Test</title>
<style>
h1, h2 { color:blue; }
strong { text-decoration:none }
p { font-size:2px }
p.footer { font-size: 1px}
</style>
</head>
<body>
<h1>Big Text</h1>
<p>
<strong>Solid</strong>
</p>
<p class="footer">Foot notes</p>
</body>
</html>"""
SIMPLE_HTMLS = [SIMPLE_HTML] * 5000
MERGE_HTML = """<html>
<head>
<title>Test</title>
<style>
h1, h2 { color:blue; }
strong { text-decoration:none }
p { font-size:2px }
p.footer { font-size: 1px}
</style>
</head>
<body>
<h1 style="background-color: black;">Big Text</h1>
<p style="background-color: black;">
<strong style="background-color: black;">Solid</strong>
</p>
<p class="footer" style="background-color: black;">Foot notes</p>
</body>
</html>"""
MERGE_HTMLS = [MERGE_HTML] * 5000
REALISTIC_HTML = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title> Newsletter</title>
<meta name="viewport" content="width = 620" />
<style type="text/css">
img {margin:0}
a.bluelink:link,a.bluelink:visited,a.bluelink:active {color:#5b7ab3; text-decoration: none}
a.bluelink:hover {color:#5b7ab3; text-decoration: underline}
</style>
<style media="only screen and (max-device-width: 480px)" type="text/css">
* {line-height: normal !important; -webkit-text-size-adjust: 125%}
</style>
</head>
<body bgcolor="#FFFFFF" style="margin:0; padding:0">
<table width="100%" bgcolor="#FFFFFF" cellpadding="0" cellspacing="0" align="center" border="2">
<tr>
<td style="padding: 30px"><!--
--><table width="636" border="0" cellspacing="0" cellpadding="0" align="center">
<tr>
<td width="636"><img src="http://images.apple.com/data/retail/us/topcap.gif" border="0" alt="" width="636" height="62" style="display:block" /></td>
</tr>
</table><!--
--><table width="636" border="1" cellspacing="0" cellpadding="0" align="center" bgcolor="#fffef6">
<tr>
<td width="59" valign="top" background="http://images.apple.com/data/retail/us/leftbg.gif"><img src="http://images.apple.com/data/retail/us/leftcap.gif" width="59" height="302" border="1" alt="" style="display:block" /></td>
<td width="500" align="left" valign="top"><!--
--><table width="500" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="379" align="left" valign="top">
<div><img src="http://images.apple.com/data/retail/us/headline.gif" width="330" height="29" border="1" alt="Thanks for making a reservation." style="display:block" /></div>
</td>
<td width="21" align="right" valign="top">
<div><img src="http://images.apple.com/data/retail/us/applelogo.gif" width="21" height="25" border="1" alt="" style="display:block" /></div>
</td>
</tr>
</table><!--
--><table width="500" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="500" align="left" valign="top">
<div><img src="http://images.apple.com/data/retail/us/line.gif" width="500" height="36" border="0" alt="" style="display:block" /></div>
</td>
</tr>
</table><!--
--><table width="500" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="10" align="left" valign="top"></td>
<td width="340" align="left" valign="top">
<div style="margin: 0; padding: 2px 10px 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color: #000000 !important; font-size:12px; line-height: 16px">Dear peter,</div>
<div style="margin: 0; padding: 12px 10px 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color: #000000 !important; font-size:12px; line-height: 16px">You are scheduled for a Genius Bar appointment.</div>
<div style="margin: 0; padding: 12px 10px 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color: #000000 !important; font-size:12px; line-height: 16px">Topic: <b>iPhone</b></div>
<div style="margin: 0; padding: 12px 10px 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color: #000000 !important; font-size:12px; line-height: 16px">Date: <b>Wednesday, Aug 26, 2009</b></div>
<div style="margin: 0; padding: 12px 10px 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color: #000000 !important; font-size:12px; line-height: 16px">Time: <b>11:10AM</b></div>
<div style="margin: 0; padding: 12px 10px 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color: #000000 !important; font-size:12px; line-height: 16px">Location: <b>Apple Store, Regent Street</b></div>
</td>
<td width="150" align="left" valign="top">
<div style="margin: 0; padding: 2px 0 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color:#808285; font-size:11px; line-height: 13px">Apple Store,</div>
<div style="margin: 0; padding: 0 0 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color:#808285; font-size:11px; line-height: 13px">Regent Street</div>
<div style="margin: 0; padding: 7px 0 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color:#808285; font-size:11px; line-height: 13px"><a href="http://concierge.apple.com/WebObjects/RRSServices.woa/wa/ics?id=ewoJInByaW1hcnlLZXkiID0gewoJCSJyZXNlcnZhdGlvbklEIiA9ICI1ODEyMDI2NCI7Cgl9OwoJImVudGl0eU5hbWUiID0gIlJlc2VydmF0aW9uIjsKfQ%3D%3D" style="font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; font-size:11px; color:#5b7ab3" class="bluelink">Add this to your calendar<img src="http://images.apple.com/data/retail/us/bluearrow.gif" width="8" height="8" border="0" alt="" style="display:inline; margin:0" /></a></div>
<div style="margin: 0; padding: 7px 0 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color:#808285; font-size:11px; line-height: 13px">If you are no longer able to attend this session, please <a href="http://concierge.apple.com/WebObjects/Concierge.woa/wa/cancelReservation?r=ewoJInByaW1hcnlLZXkiID0gewoJCSJyZXNlcnZhdGlvbklEIiA9ICI1ODEyMDI2NCI7Cgl9OwoJImVudGl0eU5hbWUiID0gIlJlc2VydmF0aW9uIjsKfQ%3D%3D" style="font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; font-size:11px; color:#5b7ab3" class="bluelink">cancel</a> or <a href="http://concierge.apple.com/WebObjects/Concierge.woa/wa/cancelReservation?r=<KEY>UiID0gIlJlc2VydmF0aW9uIjsKfQ%3D%3D" style="font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; font-size:11px; color:#5b7ab3" class="bluelink">reschedule</a> your reservation.</div>
<div style="margin: 0; padding: 7px 0 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color:#808285; font-size:11px; line-height: 13px"><a href="http://www.apple.com/retail/../uk/retail/regentstreet/map" style="font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; font-size:11px; color:#5b7ab3" class="bluelink">Get directions to the store<img src="http://images.apple.com/data/retail/us/bluearrow.gif" width="8" height="8" border="0" alt="" style="display:inline; margin:0" /></a></div>
</td>
</tr>
</table><!--
--><table width="500" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="10"></td>
<td width="490" align="left" valign="top">
<br>
<div style="margin: 0; padding: 0 20px 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color: #000000 !important; font-size:12px; line-height: 16px">We look forward to seeing you.</div>
<div style="margin: 0; padding: 0 20px 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color: #000000 !important; font-size:12px; line-height: 16px">Your Apple Store team,</div>
<div style="margin: 0; padding: 0 20px 0 0; font-family: Lucida Grande, Arial, Helvetica, Geneva, Verdana, sans-serif; color: #000000 !important; font-size:12px; line-height: 16px">Regent Street</div>
</td>
</tr>
</table><!--
--></td>
<td width="59" valign="top" background="http://images.apple.com/data/retail/us/rightbg.gif"><img src="http://images.apple.com/data/retail/us/rightcap.gif" width="77" height="302" border="0" alt="" style="display:block" /></td>
</tr>
</table><!--
--><table width="636" border="1" cellspacing="0" cellpadding="0" align="center">
<tr>
<td width="636"><img src="http://images.apple.com/data/retail/us/bottomcap.gif" border="0" alt="" width="636" height="62" style="display:block" /></td>
</tr>
</table><!--
BEGIN FOOTER
--><table width="498" border="1" cellspacing="0" cellpadding="0" align="center">
<tr>
<td style="padding-top:22px">
<div style="font-family: Geneva, Verdana, Arial, Helvetica, sans-serif; font-size:9px; line-height: 12px; color:#b4b4b4">TM and copyright © 2008 Apple Inc. 1 Infinite Loop, MS 303-3DM, Cupertino, CA 95014.</div>
<div style="font-family: Geneva, Verdana, Arial, Helvetica, sans-serif; font-size:9px; line-height: 12px; color:#b4b4b4"><a href="http://www.apple.com/legal/" style="font-family: Geneva, Verdana, Arial, Helvetica, sans-serif; font-size:9px;line-height: 12px; color:#b4b4b4; text-decoration:underline">All Rights Reserved</a> / <a href="http://www.apple.com/enews/subscribe/" style="font-family: Geneva, Verdana, Arial, Helvetica, sans-serif; font-size:9px; line-height: 12px;color:#b4b4b4; text-decoration:underline">Keep Informed</a> / <a href="http://www.apple.com/legal/privacy/" style="font-family: Geneva, Verdana, Arial, Helvetica, sans-serif; font-size:9px; line-height: 12px; color:#b4b4b4; text-decoration:underline">Privacy Policy</a> / <a href="https://myinfo.apple.com/cgi-bin/WebObjects/MyInfo/" style="font-family: Geneva, Verdana, Arial, Helvetica, sans-serif; font-size:9px; line-height: 12px; color:#b4b4b4; text-decoration:underline">My Info</a></div>
</td>
</tr>
</table><!--
--></td>
</tr>
</table>
</body>
</html>"""
REALISTIC_HTMLS = [REALISTIC_HTML] * 100
def parametrize_functions(
*funcs, ids=("css_inline", "premailer", "pynliner", "inlinestyler")
):
return pytest.mark.parametrize("func", funcs, ids=ids)
all_functions = parametrize_functions(
css_inline.inline,
premailer.transform,
pynliner.fromString,
inlinestyler.utils.inline_css,
)
def parallel(func):
return lambda data: multiprocessing.Pool().map(func, data)
all_many_functions = parametrize_functions(
css_inline.inline_many,
parallel(css_inline.inline),
parallel(premailer.transform),
parallel(pynliner.fromString),
parallel(inlinestyler.utils.inline_css),
ids=("css_inline", "css_inline_pyprocess", "premailer", "pynliner", "inlinestyler"),
)
@all_functions
@pytest.mark.benchmark(group="simple")
def test_simple(benchmark, func):
benchmark(func, SIMPLE_HTML)
@all_many_functions
@pytest.mark.benchmark(group="simple many")
def test_simple_many(benchmark, func):
benchmark(func, SIMPLE_HTMLS)
@all_functions
@pytest.mark.benchmark(group="merge")
def test_merge(benchmark, func):
benchmark(func, MERGE_HTML)
@all_many_functions
@pytest.mark.benchmark(group="merge many")
def test_merge_many(benchmark, func):
benchmark(func, MERGE_HTMLS)
@all_functions
@pytest.mark.benchmark(group="realistic")
def test_realistic(benchmark, func):
benchmark(func, REALISTIC_HTML)
@all_many_functions
@pytest.mark.benchmark(group="realistic many")
def test_realistic_many(benchmark, func):
benchmark(func, REALISTIC_HTMLS)
@pytest.mark.benchmark(group="exception")
def test_exception(benchmark):
def func():
with suppress(ValueError):
css_inline.inline("", base_url="!wrong!")
benchmark(func)
<file_sep>/bindings/python/tests-py/test_inlining.py
from contextlib import suppress
import pytest
from hypothesis import given, provisional, settings
from hypothesis import strategies as st
import css_inline
def make_html(style: str, body: str) -> str:
return "<html><head><title>Test</title><style>{style}</style></head><body>{body}</body></html>".format(
style=style, body=body
)
SAMPLE_STYLE = """h1, h2 { color:red; }
strong { text-decoration:none }
p { font-size:2px }
p.footer { font-size: 1px}"""
SAMPLE_INLINED = """<h1 style="color:red;">Big Text</h1>
<p style="font-size:2px ;"><strong style="text-decoration:none ;">Yes!</strong></p>
<p class="footer" style="font-size: 1px;">Foot notes</p>"""
@pytest.mark.parametrize(
"func",
(
lambda html, **kwargs: css_inline.inline(html, **kwargs),
lambda html, **kwargs: css_inline.inline_many([html], **kwargs),
lambda html, **kwargs: css_inline.CSSInliner(**kwargs).inline(html),
lambda html, **kwargs: css_inline.CSSInliner(**kwargs).inline_many([html]),
),
)
@pytest.mark.parametrize(
"kwargs, expected",
(
({}, make_html(SAMPLE_STYLE, SAMPLE_INLINED)),
(
{"remove_style_tags": True},
"<html><head><title>Test</title></head><body>{body}</body></html>".format(
body=SAMPLE_INLINED
),
),
),
)
def test_no_existing_style(func, kwargs, expected):
html = make_html(
SAMPLE_STYLE,
"""<h1>Big Text</h1>
<p><strong>Yes!</strong></p>
<p class="footer">Foot notes</p>""",
)
result = func(html, **kwargs)
if isinstance(result, list):
result = result[0]
assert result == expected
def test_inline_many_wrong_type():
with pytest.raises(TypeError):
css_inline.inline_many([1])
def test_invalid_base_url():
with pytest.raises(ValueError):
css_inline.CSSInliner(base_url="foo")
@given(
document=st.text(),
inline_style_tags=st.booleans() | st.none(),
remove_style_tags=st.booleans() | st.none(),
base_url=provisional.urls() | st.none(),
load_remote_stylesheets=st.booleans() | st.none(),
extra_css=st.text() | st.none(),
)
@settings(max_examples=1000)
def test_random_input(
document,
inline_style_tags,
remove_style_tags,
base_url,
load_remote_stylesheets,
extra_css,
):
with suppress(ValueError):
inliner = css_inline.CSSInliner(
inline_style_tags=inline_style_tags,
remove_style_tags=remove_style_tags,
base_url=base_url,
load_remote_stylesheets=load_remote_stylesheets,
extra_css=extra_css,
)
inliner.inline(document)
<file_sep>/css-inline/src/parser.rs
pub(crate) struct CSSRuleListParser;
pub(crate) struct CSSDeclarationListParser;
pub(crate) type Name<'i> = cssparser::CowRcStr<'i>;
pub(crate) type Declaration<'i> = (Name<'i>, &'i str);
pub(crate) type QualifiedRule<'i> = (&'i str, Vec<Declaration<'i>>);
fn exhaust<'i>(input: &mut cssparser::Parser<'i, '_>) -> &'i str {
let start = input.position();
while input.next().is_ok() {}
input.slice_from(start)
}
/// Parser for qualified rules - a prelude + a simple {} block.
///
/// Usually these rules are a selector + list of declarations: `p { color: blue; font-size: 2px }`
impl<'i> cssparser::QualifiedRuleParser<'i> for CSSRuleListParser {
type Prelude = &'i str;
type QualifiedRule = QualifiedRule<'i>;
type Error = ();
fn parse_prelude<'t>(
&mut self,
input: &mut cssparser::Parser<'i, 't>,
) -> Result<Self::Prelude, cssparser::ParseError<'i, Self::Error>> {
// Proceed with parsing until the end of the prelude.
Ok(exhaust(input))
}
fn parse_block<'t>(
&mut self,
prelude: Self::Prelude,
_: &cssparser::ParserState,
input: &mut cssparser::Parser<'i, 't>,
) -> Result<Self::QualifiedRule, cssparser::ParseError<'i, Self::Error>> {
// Parse list of declarations
let parser = cssparser::DeclarationListParser::new(input, CSSDeclarationListParser);
let declarations: Vec<_> = parser.flatten().collect();
Ok((prelude, declarations))
}
}
/// Parse a declaration within {} block: `color: blue`
impl<'i> cssparser::DeclarationParser<'i> for CSSDeclarationListParser {
type Declaration = Declaration<'i>;
type Error = ();
fn parse_value<'t>(
&mut self,
name: Name<'i>,
input: &mut cssparser::Parser<'i, 't>,
) -> Result<Self::Declaration, cssparser::ParseError<'i, Self::Error>> {
Ok((name, exhaust(input)))
}
}
impl<'i> cssparser::AtRuleParser<'i> for CSSRuleListParser {
type PreludeNoBlock = &'i str;
type PreludeBlock = &'i str;
type AtRule = QualifiedRule<'i>;
type Error = ();
}
/// Parsing for at-rules, e.g: `@charset "utf-8";`
/// Since they are can not be inlined we use the default implementation, that rejects all at-rules.
impl<'i> cssparser::AtRuleParser<'i> for CSSDeclarationListParser {
type PreludeNoBlock = String;
type PreludeBlock = String;
type AtRule = Declaration<'i>;
type Error = ();
}
<file_sep>/css-inline/src/error.rs
//! Errors that may happen during inlining.
use cssparser::{BasicParseErrorKind, ParseError, ParseErrorKind};
use std::{
borrow::Cow,
error::Error,
fmt,
fmt::{Display, Formatter},
io,
};
/// Inlining error
#[derive(Debug)]
pub enum InlineError {
/// Input-output error. May happen during writing the resulting HTML.
IO(io::Error),
/// Network-related problem. E.g. resource is not available.
Network(attohttpc::Error),
/// Syntax errors or unsupported selectors.
ParseError(Cow<'static, str>),
}
impl From<io::Error> for InlineError {
fn from(error: io::Error) -> Self {
Self::IO(error)
}
}
impl From<attohttpc::Error> for InlineError {
fn from(error: attohttpc::Error) -> Self {
Self::Network(error)
}
}
impl Error for InlineError {}
impl Display for InlineError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::IO(error) => error.fmt(f),
Self::Network(error) => error.fmt(f),
Self::ParseError(error) => f.write_str(error),
}
}
}
impl From<(ParseError<'_, ()>, &str)> for InlineError {
fn from(error: (ParseError<'_, ()>, &str)) -> Self {
return match error.0.kind {
ParseErrorKind::Basic(kind) => match kind {
BasicParseErrorKind::UnexpectedToken(token) => {
Self::ParseError(Cow::Owned(format!("Unexpected token: {:?}", token)))
}
BasicParseErrorKind::EndOfInput => Self::ParseError(Cow::Borrowed("End of input")),
BasicParseErrorKind::AtRuleInvalid(value) => {
Self::ParseError(Cow::Owned(format!("Invalid @ rule: {}", value)))
}
BasicParseErrorKind::AtRuleBodyInvalid => {
Self::ParseError(Cow::Borrowed("Invalid @ rule body"))
}
BasicParseErrorKind::QualifiedRuleInvalid => {
Self::ParseError(Cow::Borrowed("Invalid qualified rule"))
}
},
ParseErrorKind::Custom(_) => Self::ParseError(Cow::Borrowed("Unknown error")),
};
}
}
<file_sep>/bindings/python/Cargo.toml
[package]
name = "css-inline-python"
version = "0.7.6"
authors = ["<NAME> <<EMAIL>>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
name = "css_inline"
crate-type = ["cdylib"]
[build-dependencies]
built = { version = "0.5", features = ["chrono"] }
[dependencies.css-inline]
path = "../../css-inline"
version = "*"
default-features = false
[dependencies]
url = "2"
rayon = "1"
pyo3 = { version = "^0.14.1", features = ["extension-module"] }
pyo3-built = "0.4"
[profile.release]
codegen-units = 1
lto = "fat"
<file_sep>/css-inline/src/main.rs
use css_inline::{CSSInliner, InlineOptions};
use rayon::prelude::*;
use std::{
borrow::Cow,
error::Error,
ffi::OsString,
fs::File,
io::{self, Read, Write},
path::Path,
};
const VERSION_MESSAGE: &[u8] = concat!("css-inline ", env!("CARGO_PKG_VERSION"), "\n").as_bytes();
const HELP_MESSAGE: &[u8] = concat!(
"css-inline ",
env!("CARGO_PKG_VERSION"),
r#"
<NAME> <<EMAIL>>
css-inline inlines CSS into HTML documents.
USAGE:
css-inline [OPTIONS] [PATH ...]
command | css-inline [OPTIONS]
ARGS:
<PATH>...
An HTML document to process. In each specified document "css-inline" will look for
all relevant "style" and "link" tags, will load CSS from them and then inline it
to the HTML tags, according to the corresponding CSS selectors.
When multiple documents are specified, they will be processed in parallel, and each inlined
file will be saved with "inlined." prefix. E.g., for "example.html", there will be
"inlined.example.html".
OPTIONS:
--inline-style-tags
Whether to inline CSS from "style" tags. The default value is `true`. To disable inlining
from "style" tags use `--inline-style-tags=false`.
--remove-style-tags
Remove "style" tags after inlining.
--base-url
Used for loading external stylesheets via relative URLs.
--load-remote-stylesheets
Whether remote stylesheets should be loaded or not.
--extra-css
Additional CSS to inline.
"#
)
.as_bytes();
struct Args {
inline_style_tags: bool,
remove_style_tags: bool,
base_url: Option<String>,
extra_css: Option<String>,
load_remote_stylesheets: bool,
files: Vec<String>,
}
fn parse_url(url: Option<String>) -> Result<Option<url::Url>, url::ParseError> {
Ok(if let Some(url) = url {
Some(url::Url::parse(url.as_str())?)
} else {
None
})
}
fn main() -> Result<(), Box<dyn Error>> {
let mut args = pico_args::Arguments::from_env();
if args.contains(["-h", "--help"]) {
io::stdout().write_all(HELP_MESSAGE)?;
} else if args.contains(["-v", "--version"]) {
io::stdout().write_all(VERSION_MESSAGE)?;
} else {
let args = Args {
inline_style_tags: args
.opt_value_from_str("--inline-style-tags")?
.unwrap_or(true),
remove_style_tags: args.contains("--remove-style-tags"),
base_url: args.opt_value_from_str("--base-url")?,
extra_css: args.opt_value_from_str("--extra-css")?,
load_remote_stylesheets: args.contains("--load-remote-stylesheets"),
files: args.free()?,
};
let options = InlineOptions {
inline_style_tags: args.inline_style_tags,
remove_style_tags: args.remove_style_tags,
base_url: parse_url(args.base_url)?,
load_remote_stylesheets: args.load_remote_stylesheets,
extra_css: args.extra_css.as_deref().map(Cow::Borrowed),
};
let inliner = CSSInliner::new(options);
if args.files.is_empty() {
let mut buffer = String::new();
io::stdin().read_to_string(&mut buffer)?;
inliner.inline_to(buffer.as_str().trim(), &mut io::stdout())?;
} else {
args.files
.par_iter()
.map(|file_path| {
File::open(file_path)
.and_then(read_file)
.and_then(|contents| {
let path = Path::new(file_path);
let mut new_filename = OsString::from("inlined.");
new_filename.push(
path.to_path_buf()
.file_name()
.expect("It is already read, therefore it is a file"),
);
let new_path = path.with_file_name(new_filename);
File::create(new_path).map(|file| (file, contents))
})
.map(|(mut file, contents)| {
(file_path, inliner.inline_to(contents.as_str(), &mut file))
})
.map_err(|error| (file_path, error))
})
.for_each(|result| match result {
Ok((filename, result)) => match result {
Ok(_) => println!("{}: SUCCESS", filename),
Err(error) => println!("{}: FAILURE ({})", filename, error),
},
Err((filename, error)) => println!("{}: FAILURE ({})", filename, error),
});
}
}
Ok(())
}
fn read_file(mut file: File) -> io::Result<String> {
let mut contents = String::with_capacity(1024);
file.read_to_string(&mut contents).and(Ok(contents))
}
<file_sep>/css-inline/tests/test_inlining.rs
#[macro_use]
mod utils;
use css_inline::{inline, CSSInliner, InlineOptions, Url};
#[test]
fn no_existing_style() {
// When no "style" attributes exist
assert_inlined!(
style = r#"h1, h2 { color:red; }
strong { text-decoration:none }
p { font-size:2px }
p.footer { font-size: 1px}"#,
body = r#"<h1>Big Text</h1>
<p><strong>Yes!</strong></p>
<p class="footer">Foot notes</p>"#,
// Then all styles should be added to new "style" attributes
expected = r#"<h1 style="color:red;">Big Text</h1>
<p style="font-size:2px ;"><strong style="text-decoration:none ;">Yes!</strong></p>
<p class="footer" style="font-size: 1px;">Foot notes</p>"#
)
}
#[test]
fn overlap_styles() {
// When two selectors match the same element
assert_inlined!(
style = r#"
.test-class {
color: #ffffff;
}
a {
color: #17bebb;
}"#,
body = r#"<a class="test-class" href="https://example.com">Test</a>"#,
// Then the final style should come from the more specific selector
expected =
r#"<a class="test-class" href="https://example.com" style="color: #ffffff;">Test</a>"#
)
}
#[test]
fn simple_merge() {
// When "style" attributes exist and collides with values defined in "style" tag
let style = "h1 { color:red; }";
let html = html!(style, r#"<h1 style="font-size: 1px">Big Text</h1>"#);
let inlined = inline(&html).unwrap();
// Then new styles should be merged with the existing ones
let option_1 = html!(
style,
r#"<h1 style="font-size: 1px;color:red;">Big Text</h1>"#
);
let option_2 = html!(
style,
r#"<h1 style="color:red;font-size: 1px;">Big Text</h1>"#
);
let valid = (inlined == option_1) || (inlined == option_2);
assert!(valid, "{}", inlined);
}
#[test]
fn overloaded_styles() {
// When there is a style, applied to an ID
assert_inlined!(
style = "h1 { color: red; } #test { color: blue; }",
body = r#"<h1 id="test">Hello world!</h1>"#,
// Then it should be preferred over a more generic style
expected = r#"<h1 id="test" style="color: blue;">Hello world!</h1>"#
)
}
#[test]
fn existing_styles() {
// When there is a `style` attribute on a tag that contains a rule
// And the `style` tag contains the same rule applicable to that tag
assert_inlined!(
style = "h1 { color: red; }",
body = r#"<h1 style="color: blue">Hello world!</h1>"#,
// Then the existing rule should be preferred
expected = r#"<h1 style="color: blue;">Hello world!</h1>"#
)
}
#[test]
fn existing_styles_with_merge() {
// When there is a `style` attribute on a tag that contains a rule
// And the `style` tag contains the same rule applicable to that tag
// And there is a new rule in the `style` tag
assert_inlined!(
style = "h1 { color: red; font-size:14px; }",
body = r#"<h1 style="color: blue">Hello world!</h1>"#,
// Then the existing rule should be preferred
// And the new style should be merged
expected = r#"<h1 style="color: blue;font-size:14px;">Hello world!</h1>"#
)
}
#[test]
fn empty_style() {
// When the style tag is empty
assert_inlined!(
style = "",
body = r#"<h1>Hello world!</h1>"#,
// Then the body should remain the same
expected = r#"<h1>Hello world!</h1>"#
)
}
#[test]
fn media_query_ignore() {
// When the style value includes @media query
assert_inlined!(
style = r#"@media screen and (max-width: 992px) {
body {
background-color: blue;
}
}"#,
body = "<h1>Hello world!</h1>",
expected = "<h1>Hello world!</h1>"
)
}
#[test]
fn invalid_rule() {
let html = html!(
"h1 {background-color: blue;}",
r#"<h1 style="@wrong { color: ---}">Hello world!</h1>"#
);
let result = inline(&html);
assert!(result.is_err());
assert_eq!(result.unwrap_err().to_string(), "Invalid @ rule: wrong")
}
#[test]
fn remove_style_tag() {
let html = html!("h1 {background-color: blue;}", "<h1>Hello world!</h1>");
let inliner = CSSInliner::compact();
let result = inliner.inline(&html).unwrap();
assert_eq!(result, "<html><head><title>Test</title></head><body><h1 style=\"background-color: blue;\">Hello world!</h1></body></html>")
}
#[test]
fn remove_multiple_style_tags() {
let html = r#"
<html>
<head>
<style>
h1 {
text-decoration: none;
}
</style>
<style>
.test-class {
color: #ffffff;
}
a {
color: #17bebb;
}
</style>
</head>
<body>
<a class="test-class" href="https://example.com">Test</a>
<h1>Test</h1>
</body>
</html>
"#;
let inliner = CSSInliner::compact();
let result = inliner.inline(html).unwrap();
assert_eq!(
result,
r#"<html><head>
</head>
<body>
<a class="test-class" href="https://example.com" style="color: #ffffff;">Test</a>
<h1 style="text-decoration: none;">Test</h1>
</body></html>"#
)
}
#[test]
fn remove_multiple_style_tags_without_inlining() {
let html = r#"
<html>
<head>
<style>
h1 {
text-decoration: none;
}
</style>
<style>
.test-class {
color: #ffffff;
}
a {
color: #17bebb;
}
</style>
</head>
<body>
<a class="test-class" href="https://example.com">Test</a>
<h1>Test</h1>
</body>
</html>
"#;
let inliner = CSSInliner::options()
.remove_style_tags(true)
.inline_style_tags(false)
.build();
let result = inliner.inline(html).unwrap();
assert_eq!(
result,
r#"<html><head>
</head>
<body>
<a class="test-class" href="https://example.com">Test</a>
<h1>Test</h1>
</body></html>"#
)
}
#[test]
fn do_not_process_style_tag() {
let html = html!("h1 {background-color: blue;}", "<h1>Hello world!</h1>");
let options = InlineOptions {
inline_style_tags: false,
..Default::default()
};
let inliner = CSSInliner::new(options);
let result = inliner.inline(&html).unwrap();
assert_eq!(
result,
"<html><head><title>Test</title><style>h1 {background-color: blue;}</style></head><body><h1>Hello world!</h1></body></html>"
)
}
#[test]
fn do_not_process_style_tag_and_remove() {
let html = html!("h1 {background-color: blue;}", "<h1>Hello world!</h1>");
let options = InlineOptions {
remove_style_tags: true,
inline_style_tags: false,
..Default::default()
};
let inliner = CSSInliner::new(options);
let result = inliner.inline(&html).unwrap();
assert_eq!(
result,
"<html><head><title>Test</title></head><body><h1>Hello world!</h1></body></html>"
)
}
#[test]
fn extra_css() {
let html = html!("h1 {background-color: blue;}", "<h1>Hello world!</h1>");
let options = InlineOptions {
inline_style_tags: false,
extra_css: Some("h1 {background-color: green;}".into()),
..Default::default()
};
let inliner = CSSInliner::new(options);
let result = inliner.inline(&html).unwrap();
assert_eq!(
result,
"<html><head><title>Test</title><style>h1 {background-color: blue;}</style></head><body><h1 style=\"background-color: green;\">Hello world!</h1></body></html>"
)
}
#[test]
fn remote_file_stylesheet() {
let html = r#"
<html>
<head>
<link href="tests/external.css" rel="stylesheet" type="text/css">
<link rel="alternate" type="application/rss+xml" title="RSS" href="/rss.xml">
<style type="text/css">
h2 { color: red; }
</style>
</head>
<body>
<h1>Big Text</h1>
<h2>Smaller Text</h2>
</body>
</html>"#;
let result = inline(html).unwrap();
assert!(result.ends_with(
r#"<body>
<h1 style="color: blue;">Big Text</h1>
<h2 style="color: red;">Smaller Text</h2>
</body></html>"#
))
}
#[test]
fn remote_file_stylesheet_disable() {
let html = r#"
<html>
<head>
<link href="tests/external.css" rel="stylesheet" type="text/css">
<link rel="alternate" type="application/rss+xml" title="RSS" href="/rss.xml">
<style type="text/css">
h2 { color: red; }
</style>
</head>
<body>
<h1>Big Text</h1>
<h2>Smaller Text</h2>
</body>
</html>"#;
let result = inline(html).unwrap();
assert!(result.ends_with(
r#"<body>
<h1 style="color: blue;">Big Text</h1>
<h2 style="color: red;">Smaller Text</h2>
</body></html>"#
))
}
#[test]
fn remote_network_stylesheet() {
let html = r#"
<html>
<head>
<link href="http://127.0.0.1:5000/external.css" rel="stylesheet" type="text/css">
<link rel="alternate" type="application/rss+xml" title="RSS" href="/rss.xml">
<style type="text/css">
h2 { color: red; }
</style>
</head>
<body>
<h1>Big Text</h1>
<h2>Smaller Text</h2>
</body>
</html>"#;
let result = inline(html).unwrap();
assert!(result.ends_with(
r#"<body>
<h1 style="color: blue;">Big Text</h1>
<h2 style="color: red;">Smaller Text</h2>
</body></html>"#
))
}
#[test]
fn remote_network_stylesheet_invalid_url() {
let html = r#"
<html>
<head>
<link href="http:" rel="stylesheet" type="text/css">
</head>
<body>
</body>
</html>"#;
assert!(inline(html).is_err());
}
#[test]
fn remote_network_stylesheet_same_scheme() {
let html = r#"
<html>
<head>
<link href="//127.0.0.1:5000/external.css" rel="stylesheet" type="text/css">
<link rel="alternate" type="application/rss+xml" title="RSS" href="/rss.xml">
<style type="text/css">
h2 { color: red; }
</style>
</head>
<body>
<h1>Big Text</h1>
<h2>Smaller Text</h2>
</body>
</html>"#;
let options = InlineOptions {
base_url: Some(Url::parse("http://127.0.0.1:5000").unwrap()),
..Default::default()
};
let inliner = CSSInliner::new(options);
let result = inliner.inline(html).unwrap();
assert!(result.ends_with(
r#"<body>
<h1 style="color: blue;">Big Text</h1>
<h2 style="color: red;">Smaller Text</h2>
</body></html>"#
))
}
#[test]
fn remote_network_relative_stylesheet() {
let html = r#"
<html>
<head>
<link href="external.css" rel="stylesheet" type="text/css">
<link rel="alternate" type="application/rss+xml" title="RSS" href="/rss.xml">
<style type="text/css">
h2 { color: red; }
</style>
</head>
<body>
<h1>Big Text</h1>
<h2>Smaller Text</h2>
</body>
</html>"#;
let options = InlineOptions {
base_url: Some(Url::parse("http://127.0.0.1:5000").unwrap()),
..Default::default()
};
let inliner = CSSInliner::new(options);
let result = inliner.inline(html).unwrap();
assert!(result.ends_with(
r#"<body>
<h1 style="color: blue;">Big Text</h1>
<h2 style="color: red;">Smaller Text</h2>
</body></html>"#
))
}
#[test]
fn customize_inliner() {
let options = InlineOptions {
load_remote_stylesheets: false,
..Default::default()
};
assert!(!options.load_remote_stylesheets);
assert!(!options.remove_style_tags);
assert_eq!(options.base_url, None);
}
#[test]
fn use_builder() {
let url = Url::parse("https://api.example.com").unwrap();
let _ = CSSInliner::options()
.inline_style_tags(false)
.remove_style_tags(false)
.base_url(Some(url))
.load_remote_stylesheets(false)
.extra_css(Some("h1 {color: green}".into()))
.build();
}
<file_sep>/bindings/wasm/README.md
# css-inline
[](https://github.com/Stranger6667/css-inline/actions)
[](https://badge.fury.io/js/css-inline)
Blazing-fast WASM package for inlining CSS into HTML documents.
Features:
- Removing ``style`` tags after inlining;
- Resolving external stylesheets (including local files);
- Control if ``style`` tags should be processed;
- Additional CSS to inline;
- Inlining multiple documents in parallel (via Rust-level threads)
The project supports CSS Syntax Level 3 implemented with Mozilla's Servo project components.
## Usage
```typescript
import { inline } from "css-inline";
var inlined = inline(
`
<html>
<head>
<title>Test</title>
<style>h1 { color:red; }</style>
</head>
<body>
<h1>Test</h1>
</body>
</html>
`,
{ remove_style_tags: true }
)
// Inlined HTML looks like this:
// <html>
// <head>
// <title>Test</title>
// </head>
// <body>
// <h1 style="color:red;">Test</h1>
// </body>
// </html>
// Do something with the inlined HTML, e.g. send an email
```
<file_sep>/README.md
# css-inline
[](https://github.com/Stranger6667/css-inline/actions)
[](https://crates.io/crates/css-inline)
[](https://docs.rs/css-inline/)
[](https://gitter.im/Stranger6667/css-inline)
A crate for inlining CSS into HTML documents. It is built with Mozilla's Servo project components.
When you send HTML emails, you need to use "style" attributes instead of "style" tags. For example, this HTML:
```html
<html>
<head>
<title>Test</title>
<style>h1 { color:blue; }</style>
</head>
<body>
<h1>Big Text</h1>
</body>
</html>
```
Will be turned into this:
```html
<html>
<head><title>Test</title></head>
<body>
<h1 style="color:blue;">Big Text</h1>
</body>
</html>
```
To use it in your project add the following line to your `dependencies` section in the project's `Cargo.toml` file:
```toml
css-inline = "0.7"
```
## Usage
```rust
use css_inline;
const HTML: &str = r#"<html>
<head>
<title>Test</title>
<style>h1 { color:blue; }</style>
</head>
<body>
<h1>Big Text</h1>
</body>
</html>"#;
fn main() -> Result<(), css_inline::InlineError> {
let inlined = css_inline::inline(HTML)?;
// Do something with inlined HTML, e.g. send an email
Ok(())
}
```
### Features & Configuration
`css-inline` can be configured by using `CSSInliner::options()` that implements the Builder pattern:
```rust
use css_inline;
fn main() -> Result<(), css_inline::InlineError> {
let inliner = css_inline::CSSInliner::options()
.load_remote_stylesheets(false)
.build();
let inlined = inliner.inline(HTML);
// Do something with inlined HTML, e.g. send an email
Ok(())
}
```
- `inline_style_tags`. Whether to inline CSS from "style" tags. Default: `true`
- `remove_style_tags`. Remove "style" tags after inlining. Default: `false`
- `base_url`. Base URL to resolve relative URLs. Default: `None`
- `load_remote_stylesheets`. Whether remote stylesheets should be loaded or not. Default: `true`
- `extra_css`. Additional CSS to inline. Default: `None`
## Bindings
There are bindings for Python and WebAssembly in the `bindings` directory.
## Command Line Interface
`css-inline` provides a command-line interface:
```
$ css-inline --help
css-inline inlines CSS into HTML documents.
USAGE:
css-inline [OPTIONS] [PATH ...]
command | css-inline [OPTIONS]
ARGS:
<PATH>...
An HTML document to process. In each specified document "css-inline" will look for
all relevant "style" and "link" tags, will load CSS from them and then inline it
to the HTML tags, according to the corresponding CSS selectors.
When multiple documents are specified, they will be processed in parallel, and each inlined
file will be saved with "inlined." prefix. E.g., for "example.html", there will be
"inlined.example.html".
OPTIONS:
--inline-style-tags
Whether to inline CSS from "style" tags. The default value is `true`. To disable inlining
from "style" tags use `--inline-style-tags=false`.
--remove-style-tags
Remove "style" tags after inlining.
--base-url
Used for loading external stylesheets via relative URLs.
--load-remote-stylesheets
Whether remote stylesheets should be loaded or not.
--extra-css
Additional CSS to inline.
```
## Support
If you have anything to discuss regarding this library, please, join our [gitter](https://gitter.im/Stranger6667/css-inline)!
<file_sep>/css-inline/tests/utils.rs
#[macro_export]
macro_rules! html {
($style: expr, $body: expr) => {
format!(
r#"<html><head><title>Test</title><style>{}</style></head><body>{}</body></html>"#,
$style, $body
)
};
}
#[macro_export]
macro_rules! assert_inlined {
(style = $style: expr, body = $body: expr, expected = $expected: expr) => {{
let html = html!($style, $body);
let inlined = css_inline::inline(&html).unwrap();
assert_eq!(inlined, html!($style, $expected))
}};
}
<file_sep>/bindings/python/CHANGELOG.md
# Changelog
## [Unreleased]
## [0.7.6] - 2021-08-06
### Fixed
- Docs: Link to the project homepage in `setup.py`.
## [0.7.5] - 2021-07-24
### Fixed
- Panic on invalid URLs for remote stylesheets.
## [0.7.4] - 2021-07-06
### Changed
- Update `PyO3` to `0.14.1`.
### Performance
- Optimize loading of external files.
## [0.7.3] - 2021-06-24
### Performance
- Improve performance for error handling.
## [0.7.2] - 2021-06-22
### Fixed
- Incorrect override of exiting `style` attribute values. [#113](https://github.com/Stranger6667/css-inline/issues/113)
### Performance
- Minor performance improvements
## [0.7.1] - 2021-06-10
### Fixed
- Ignored `style` tags when the document contains multiple of them and the `remove_style_tags: true` config option is used. [#110](https://github.com/Stranger6667/css-inline/issues/110)
## [0.7.0] - 2021-06-09
### Fixed
- Ignored selectors specificity. [#108](https://github.com/Stranger6667/css-inline/issues/108)
### Changed
- Upgrade `Pyo3` to `0.13`.
## [0.6.2] - 2021-01-28
### Fixed
- Source code distribution. It was missing the source code for the underlying Rust crate and were leading to
a build error during `pip install css-inline` on platforms that we don't have wheels for.
[#99](https://github.com/Stranger6667/css-inline/issues/99)
## [0.6.1] - 2020-12-07
### Added
- Python 3.9 support.
### Fixed
- Compatibility with the new `cssparser` crate version.
### Performance
- Avoid string allocations during converting `ParseError` to `InlineError`.
## [0.6.0] - 2020-11-02
### Changed
- Links to remote stylesheets are deduplicated now.
- Upgrade `Pyo3` to `0.12`.
### Performance
- Avoid setting module docstring twice
- Use `Cow` for error messages. [#87](https://github.com/Stranger6667/css-inline/issues/87)
## [0.5.0] - 2020-08-07
### Performance
- Avoid string allocation in `get_full_url`
## [0.4.0] - 2020-07-13
### Added
- Option to disable processing of "style" tags. [#45](https://github.com/Stranger6667/css-inline/issues/45)
- Option to inline additional CSS. [#45](https://github.com/Stranger6667/css-inline/issues/45)
### Changed
- Switch from `openssl` to `rustls` in `attohttpc` dependency. [#49](https://github.com/Stranger6667/css-inline/issues/49)
### Performance
- Use `ToString` trait during error handling to avoid using a formatter.
## [0.3.2] - 2020-07-09
### Fixed
- `CSSInliner` signature detection in PyCharm.
## [0.3.1] - 2020-07-07
### Changed
- Upgrade `Pyo3` to `0.11`. [#40](https://github.com/Stranger6667/css-inline/issues/40)
### Performance
- Pre-allocate the output vector.
- Reduce the average number of allocations during styles merge by a factor of 5.5x.
## [0.3.0] - 2020-06-27
### Changed
- Remove debug symbols from the release build
### Performance
- Various performance improvements
## [0.2.0] - 2020-06-25
### Added
- Loading external stylesheets. [#8](https://github.com/Stranger6667/css-inline/issues/8)
- Option to control whether remote stylesheets should be loaded (`load_remote_stylesheets`). Enabled by default.
### Changed
- Skip selectors that can't be parsed.
- Validate `base_url` to be a valid URL.
### Fixed
- Panic in cases when styles are applied to the currently processed "link" tags.
## 0.1.0 - 2020-06-24
- Initial public release
[Unreleased]: https://github.com/Stranger6667/css-inline/compare/python-v0.7.6...HEAD
[0.7.6]: https://github.com/Stranger6667/css-inline/compare/python-v0.7.5...python-v0.7.6
[0.7.5]: https://github.com/Stranger6667/css-inline/compare/python-v0.7.4...python-v0.7.5
[0.7.4]: https://github.com/Stranger6667/css-inline/compare/python-v0.7.3...python-v0.7.4
[0.7.3]: https://github.com/Stranger6667/css-inline/compare/python-v0.7.2...python-v0.7.3
[0.7.2]: https://github.com/Stranger6667/css-inline/compare/python-v0.7.1...python-v0.7.2
[0.7.1]: https://github.com/Stranger6667/css-inline/compare/python-v0.7.0...python-v0.7.1
[0.7.0]: https://github.com/Stranger6667/css-inline/compare/python-v0.6.2...python-v0.7.0
[0.6.2]: https://github.com/Stranger6667/css-inline/compare/python-v0.6.1...python-v0.6.2
[0.6.1]: https://github.com/Stranger6667/css-inline/compare/python-v0.6.0...python-v0.6.1
[0.6.0]: https://github.com/Stranger6667/css-inline/compare/python-v0.5.0...python-v0.6.0
[0.5.0]: https://github.com/Stranger6667/css-inline/compare/python-v0.4.0...python-v0.5.0
[0.4.0]: https://github.com/Stranger6667/css-inline/compare/python-v0.3.2...python-v0.4.0
[0.3.2]: https://github.com/Stranger6667/css-inline/compare/python-v0.3.1...python-v0.3.2
[0.3.1]: https://github.com/Stranger6667/css-inline/compare/python-v0.3.0...python-v0.3.1
[0.3.0]: https://github.com/Stranger6667/css-inline/compare/python-v0.2.0...python-v0.3.0
[0.2.0]: https://github.com/Stranger6667/css-inline/compare/python-v0.1.0...python-v0.2.0
<file_sep>/bindings/python/README.rst
css_inline
==========
|Build| |Version| |Python versions| |License|
Blazing-fast CSS inlining for Python implemented with Mozilla's Servo project components.
Features:
- Removing ``style`` tags after inlining;
- Resolving external stylesheets (including local files);
- Control if ``style`` tags should be processed;
- Additional CSS to inline;
- Inlining multiple documents in parallel (via Rust-level threads)
The project supports CSS Syntax Level 3.
Installation
------------
To install ``css_inline`` via ``pip`` run the following command:
.. code:: bash
pip install css_inline
Usage
-----
To inline CSS in a HTML document:
.. code:: python
import css_inline
HTML = """<html>
<head>
<title>Test</title>
<style>h1 { color:blue; }</style>
</head>
<body>
<h1>Big Text</h1>
</body>
</html>"""
inlined = css_inline.inline(HTML)
# HTML becomes this:
#
# <html>
# <head>
# <title>Test</title>
# <style>h1 { color:blue; }</style>
# </head>
# <body>
# <h1 style="color:blue;">Big Text</h1>
# </body>
# </html>
If you want to inline many HTML documents, you can utilize ``inline_many`` that processes the input in parallel.
.. code:: python
import css_inline
css_inline.inline_many(["<...>", "<...>"])
``inline_many`` will use Rust-level threads; thus, you can expect it's running faster than ``css_inline.inline`` via Python's ``multiprocessing`` or ``threading`` modules.
For customization options use the ``CSSInliner`` class:
.. code:: python
import css_inline
inliner = css_inline.CSSInliner(remove_style_tags=True)
inliner.inline("...")
Performance
-----------
Due to the usage of efficient tooling from Mozilla's Servo project (``html5ever``, ``rust-cssparser`` and others) this
library has excellent performance characteristics. In comparison with other Python projects, it is ~6-15x faster than the nearest alternative.
For inlining CSS in the html document from the ``Usage`` section above we have the following breakdown in our benchmarks:
- ``css_inline 0.7.0`` - 25.21 us
- ``premailer 3.7.0`` - 340.89 us (**x13.52**)
- ``inlinestyler 0.2.4`` - 2.44 ms (**x96.78**)
- ``pynliner 0.8.0`` - 2.78 ms (**x110.27**)
And for a more realistic email:
- ``css_inline 0.6.0`` - 529.1 us
- ``premailer 3.7.0`` - 3.38 ms (**x6.38**)
- ``inlinestyler 0.2.4`` - 64.41 ms (**x121.73**)
- ``pynliner 0.8.0`` - 93.11 ms (**x175.97**)
You can take a look at the benchmarks' code at ``benches/bench.py`` file.
The results above were measured with stable ``rustc 1.47.0``, ``Python 3.8.6`` on i8700K, and 32GB RAM.
Python support
--------------
``css_inline`` supports Python 3.6, 3.7, 3.8, and 3.9.
License
-------
The code in this project is licensed under `MIT license`_.
By contributing to ``css_inline``, you agree that your contributions
will be licensed under its MIT license.
.. |Build| image:: https://github.com/Stranger6667/css-inline/workflows/ci/badge.svg
:target: https://github.com/Stranger6667/css_inline/actions
.. |Version| image:: https://img.shields.io/pypi/v/css_inline.svg
:target: https://pypi.org/project/css_inline/
.. |Python versions| image:: https://img.shields.io/pypi/pyversions/css_inline.svg
:target: https://pypi.org/project/css_inline/
.. |License| image:: https://img.shields.io/pypi/l/css_inline.svg
:target: https://opensource.org/licenses/MIT
.. _MIT license: https://opensource.org/licenses/MIT
<file_sep>/CHANGELOG.md
# Changelog
## [Unreleased]
## [0.7.5] - 2021-07-24
### Fixed
- Panic on invalid URLs for remote stylesheets.
## [0.7.4] - 2021-07-06
### Changed
- Update `rayon` to `1.5`.
### Performance
- Optimize loading of external files.
## [0.7.3] - 2021-06-24
### Performance
- Avoid allocations in error formatting.
## [0.7.2] - 2021-06-22
### Fixed
- Incorrect override of exiting `style` attribute values. [#113](https://github.com/Stranger6667/css-inline/issues/113)
### Performance
- Use specialized `to_string` implementation on `&&str`.
- Use `ahash`.
## [0.7.1] - 2021-06-10
### Fixed
- Ignored `style` tags when the document contains multiple of them and the `remove_style_tags: true` config option is used. [#110](https://github.com/Stranger6667/css-inline/issues/110)
## [0.7.0] - 2021-06-09
### Fixed
- Ignored selectors specificity. [#108](https://github.com/Stranger6667/css-inline/issues/108)
## [0.6.1] - 2020-12-07
### Fixed
- Compatibility with the new `cssparser` crate version.
### Performance
- Avoid string allocations during converting `ParseError` to `InlineError`.
## [0.6.0] - 2020-11-02
### Changed
- Links to remote stylesheets are deduplicated now.
### Fixed
- Wrong inlined file prefixes handling in CLI. [#89](https://github.com/Stranger6667/css-inline/issues/89)
### Performance
- Use `Formatter.write_str` instead of `write!` macro in the `Display` trait implementation for `InlineError`. [#85](https://github.com/Stranger6667/css-inline/issues/85)
- Use `Cow` for error messages. [#87](https://github.com/Stranger6667/css-inline/issues/87)
## [0.5.0] - 2020-08-07
### Added
- `CSSInliner::options()` that implements the Builder pattern. [#71](https://github.com/Stranger6667/css-inline/issues/71)
### Changed
- Restrict visibility of items in `parser.rs`
### Performance
- Avoid string allocation in `get_full_url`
## [0.4.0] - 2020-07-13
### Added
- Option to disable processing of "style" tags. [#45](https://github.com/Stranger6667/css-inline/issues/45)
- Option to inline additional CSS. [#45](https://github.com/Stranger6667/css-inline/issues/45)
### Changed
- Switch from `openssl` to `rustls` in `attohttpc` dependency. [#49](https://github.com/Stranger6667/css-inline/issues/49)
### Performance
- Use `codegen-units=1` and `lto=fat`.
- Reduce the number of allocations in CLI.
- Avoid CLI output formatting when it is not needed.
## [0.3.3] - 2020-07-07
### Performance
- Pre-allocate the output vector.
- Minor improvement for creating new files via CLI.
- Reduce the average number of allocations during styles merge by a factor of 5.5x.
## [0.3.2] - 2020-06-27
### Changed
- Remove debug symbols from the release build
### Performance
- Reduce the number of `String` allocations.
- Avoid `BTreeMap::insert` when `style` attribute already exists
## [0.3.1] - 2020-06-25
### Changed
- Fix links in docs
## [0.3.0] - 2020-06-25
### Added
- Command Line Interface. [#33](https://github.com/Stranger6667/css-inline/issues/33)
## [0.2.0] - 2020-06-25
### Added
- `CSSInliner` and customization options. [#9](https://github.com/Stranger6667/css-inline/issues/9)
- Option to remove "style" tags (`remove_style_tags`). Disabled by default. [#11](https://github.com/Stranger6667/css-inline/issues/11)
- `CSSInliner::compact()` constructor for producing smaller HTML output.
- `CSSInliner.inline_to` that writes the output to a generic writer. [#24](https://github.com/Stranger6667/css-inline/issues/24)
- Implement `Error` for `InlineError`.
- Loading external stylesheets. [#8](https://github.com/Stranger6667/css-inline/issues/8)
- Option to control whether remote stylesheets should be loaded (`load_remote_stylesheets`). Enabled by default.
### Changed
- Improved error messages. [#27](https://github.com/Stranger6667/css-inline/issues/27)
- Skip selectors that can't be parsed.
### Fixed
- Ignore `@media` queries since they can not be inlined. [#7](https://github.com/Stranger6667/css-inline/issues/7)
- Panic in cases when styles are applied to the currently processed "link" tags.
### Performance
- Improve performance for merging new styles in existing "style" attributes.
## 0.1.0 - 2020-06-22
- Initial public release
[Unreleased]: https://github.com/Stranger6667/css-inline/compare/rust-v0.7.5...HEAD
[0.7.5]: https://github.com/Stranger6667/css-inline/compare/rust-v0.7.4...rust-v0.7.5
[0.7.4]: https://github.com/Stranger6667/css-inline/compare/rust-v0.7.3...rust-v0.7.4
[0.7.3]: https://github.com/Stranger6667/css-inline/compare/rust-v0.7.2...rust-v0.7.3
[0.7.2]: https://github.com/Stranger6667/css-inline/compare/rust-v0.7.1...rust-v0.7.2
[0.7.1]: https://github.com/Stranger6667/css-inline/compare/rust-v0.7.0...rust-v0.7.1
[0.7.0]: https://github.com/Stranger6667/css-inline/compare/rust-v0.6.1...rust-v0.7.0
[0.6.1]: https://github.com/Stranger6667/css-inline/compare/rust-v0.6.0...rust-v0.6.1
[0.6.0]: https://github.com/Stranger6667/css-inline/compare/rust-v0.5.0...rust-v0.6.0
[0.5.0]: https://github.com/Stranger6667/css-inline/compare/rust-v0.4.0...rust-v0.5.0
[0.4.0]: https://github.com/Stranger6667/css-inline/compare/0.3.3...rust-v0.4.0
[0.3.3]: https://github.com/Stranger6667/css-inline/compare/0.3.2...0.3.3
[0.3.2]: https://github.com/Stranger6667/css-inline/compare/0.3.1...0.3.2
[0.3.1]: https://github.com/Stranger6667/css-inline/compare/0.3.0...0.3.1
[0.3.0]: https://github.com/Stranger6667/css-inline/compare/0.2.0...0.3.0
[0.2.0]: https://github.com/Stranger6667/css-inline/compare/0.1.0...0.2.0
<file_sep>/bindings/wasm/Cargo.toml
[package]
name = "css-inline-wasm"
version = "0.7.5"
authors = ["<NAME> <<EMAIL>>"]
edition = "2018"
readme = "README.md"
description = "A WASM package for inlining CSS into HTML documents"
repository = "https://github.com/Stranger6667/css-inline"
keywords = ["html", "css", "css-inline"]
categories = ["web-programming"]
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
name = "css_inline"
crate-type = ["cdylib"]
[dependencies.css-inline]
path = "../../css-inline"
version = "*"
default-features = false
[dependencies]
url = "2"
wasm-bindgen = { version = "0.2", features = ["serde-serialize"] }
serde = { version = "1.0", features = ["derive"] }
wee_alloc = "0.4"
serde_derive = "1"
serde_json = "1"
[dev-dependencies]
wasm-bindgen-test = "0.3.0"
[profile.release]
opt-level = "z"
codegen-units = 1
[package.metadata.wasm-pack.profile.release]
wasm-opt = ["-Oz", "--enable-mutable-globals"]
<file_sep>/css-inline/tests/test_selectors.rs
#[macro_use]
mod utils;
// Most of the following tests are ported to Rust from https://github.com/rennat/pynliner
#[test]
fn identical_element() {
assert_inlined!(
style = r#"
.text-right {
text-align: right;
}
.box {
border: 1px solid #000;
}
"#,
body = r#"<div class="box"><p>Hello World</p><p class="text-right">Hello World on right</p><p class="text-right">Hello World on right</p></div>"#,
expected = r#"<div class="box" style="border: 1px solid #000;"><p>Hello World</p><p class="text-right" style="text-align: right;">Hello World on right</p><p class="text-right" style="text-align: right;">Hello World on right</p></div>"#
)
}
#[test]
fn is_or_prefixed_by() {
assert_inlined!(
style = r#"[data-type|="thing"] {color: red;}"#,
body = r#"<span data-type="thing">1</span>"#,
expected = r#"<span data-type="thing" style="color: red;">1</span>"#
);
assert_inlined!(
style = r#"[data-type|="thing"] {color: red;}"#,
body = r#"<span data-type="thing-1">1</span>"#,
expected = r#"<span data-type="thing-1" style="color: red;">1</span>"#
)
}
#[test]
fn contains() {
assert_inlined!(
style = r#"[data-type*="i"] {color: red;}"#,
body = r#"<span data-type="thing">1</span>"#,
expected = r#"<span data-type="thing" style="color: red;">1</span>"#
)
}
#[test]
fn ends_with() {
assert_inlined!(
style = r#"[data-type$="ng"] {color: red;}"#,
body = r#"<span data-type="thing">1</span>"#,
expected = r#"<span data-type="thing" style="color: red;">1</span>"#
)
}
#[test]
fn starts_with() {
assert_inlined!(
style = r#"[data-type^="th"] {color: red;}"#,
body = r#"<span data-type="thing">1</span>"#,
expected = r#"<span data-type="thing" style="color: red;">1</span>"#
)
}
#[test]
fn one_of() {
assert_inlined!(
style = r#"[data-type~="thing1"] {color: red;}"#,
body = r#"<span data-type="thing1 thing2">1</span>"#,
expected = r#"<span data-type="thing1 thing2" style="color: red;">1</span>"#
);
assert_inlined!(
style = r#"[data-type~="thing2"] {color: red;}"#,
body = r#"<span data-type="thing1 thing2">1</span>"#,
expected = r#"<span data-type="thing1 thing2" style="color: red;">1</span>"#
)
}
#[test]
fn equals() {
assert_inlined!(
style = r#"[data-type="thing"] {color: red;}"#,
body = r#"<span data-type="thing">1</span>"#,
expected = r#"<span data-type="thing" style="color: red;">1</span>"#
);
assert_inlined!(
style = r#"[data-type = "thing"] {color: red;}"#,
body = r#"<span data-type="thing">1</span>"#,
expected = r#"<span data-type="thing" style="color: red;">1</span>"#
)
}
#[test]
fn exists() {
assert_inlined!(
style = r#"[data-type] {color: red;}"#,
body = r#"<span data-type="thing">1</span>"#,
expected = r#"<span data-type="thing" style="color: red;">1</span>"#
)
}
#[test]
fn specificity() {
assert_inlined!(
style = r#"div,a,b,c,d,e,f,g,h,i,j { color: red; } .foo { color: blue; }"#,
body = r#"<div class="foo"></div>"#,
expected = r#"<div class="foo" style="color: blue;"></div>"#
)
}
#[test]
fn first_child_descendant_selector_complex_dom() {
assert_inlined!(
style = r#"h1 :first-child { color: red; }"#,
body = r#"<h1><div><span>Hello World!</span></div><p>foo</p><div class="barclass"><span>baz</span>bar</div></h1>"#,
expected = r#"<h1><div style="color: red;"><span style="color: red;">Hello World!</span></div><p>foo</p><div class="barclass"><span style="color: red;">baz</span>bar</div></h1>"#
)
}
#[test]
fn last_child_descendant_selector() {
assert_inlined!(
style = r#"h1 :last-child { color: red; }"#,
body = r#"<h1><div><span>Hello World!</span></div></h1>"#,
expected = r#"<h1><div style="color: red;"><span style="color: red;">Hello World!</span></div></h1>"#
)
}
#[test]
fn first_child_descendant_selector() {
assert_inlined!(
style = r#"h1 :first-child { color: red; }"#,
body = r#"<h1><div><span>Hello World!</span></div></h1>"#,
expected = r#"<h1><div style="color: red;"><span style="color: red;">Hello World!</span></div></h1>"#
)
}
#[test]
fn child_with_first_child_and_unmatched_class_selector_complex_dom() {
assert_inlined!(
style = r#"h1 > .hello:first-child { color: green; }"#,
body = r#"<h1><span>Hello World!</span><p>foo</p><div class="barclass"><span>baz</span>bar</div></h1>"#,
expected = r#"<h1><span>Hello World!</span><p>foo</p><div class="barclass"><span>baz</span>bar</div></h1>"#
)
}
#[test]
fn child_with_first_child_and_class_selector_complex_dom() {
assert_inlined!(
style = r#"h1 > .hello:first-child { color: green; }"#,
body = r#"<h1><span class="hello">Hello World!</span><p>foo</p><div class="barclass"><span>baz</span>bar</div></h1>"#,
expected = r#"<h1><span class="hello" style="color: green;">Hello World!</span><p>foo</p><div class="barclass"><span>baz</span>bar</div></h1>"#
)
}
#[test]
fn nested_child_with_first_child_override_selector_complex_dom() {
assert_inlined!(
style = r#"div > div > * { color: green; } div > div > :first-child { color: red; }"#,
body = r#"<div><div><span>Hello World!</span><p>foo</p><div class="barclass"><span>baz</span>bar</div></div></div>"#,
expected = r#"<div><div><span style="color: red;">Hello World!</span><p style="color: green;">foo</p><div class="barclass" style="color: green;"><span style="color: red;">baz</span>bar</div></div></div>"#
)
}
#[test]
fn child_with_first_and_last_child_override_selector() {
assert_inlined!(
style = r#"p > * { color: green; } p > :first-child:last-child { color: red; }"#,
body = r#"<p><span>Hello World!</span></p>"#,
expected = r#"<p><span style="color: red;">Hello World!</span></p>"#
)
}
#[test]
fn id_el_child_with_first_child_override_selector_complex_dom() {
assert_inlined!(
style = r#"#abc > * { color: green; } #abc > :first-child { color: red; }"#,
body = r#"<div id="abc"><span class="cde">Hello World!</span><p>foo</p><div class="barclass"><span>baz</span>bar</div></div>"#,
expected = r#"<div id="abc"><span class="cde" style="color: red;">Hello World!</span><p style="color: green;">foo</p><div class="barclass" style="color: green;"><span>baz</span>bar</div></div>"#
)
}
#[test]
fn child_with_first_child_override_selector_complex_dom() {
assert_inlined!(
style = r#"div > * { color: green; } div > :first-child { color: red; }"#,
body = r#"<div><span>Hello World!</span><p>foo</p><div class="barclass"><span>baz</span>bar</div></div>"#,
expected = r#"<div><span style="color: red;">Hello World!</span><p style="color: green;">foo</p><div class="barclass" style="color: green;"><span style="color: red;">baz</span>bar</div></div>"#
)
}
#[test]
fn child_follow_by_last_child_selector_complex_dom() {
assert_inlined!(
style = r#"h1 > :last-child { color: red; }"#,
body = r#"<h1><span>Hello World!</span><p>foo</p><div class="barclass"><span>baz</span>bar</div></h1>"#,
expected = r#"<h1><span>Hello World!</span><p>foo</p><div class="barclass" style="color: red;"><span>baz</span>bar</div></h1>"#
)
}
#[test]
fn parent_pseudo_selector() {
assert_inlined!(
style = r#"span:last-child span { color: red; }"#,
body = r#"<h1><span><span>Hello World!</span></span></h1>"#,
expected = r#"<h1><span><span style="color: red;">Hello World!</span></span></h1>"#
);
assert_inlined!(
style = r#"span:last-child > span { color: red; }"#,
body = r#"<h1><span><span>Hello World!</span></span></h1>"#,
expected = r#"<h1><span><span style="color: red;">Hello World!</span></span></h1>"#
);
assert_inlined!(
style = r#"span:last-child > span { color: red; }"#,
body = r#"<h1><span><span>Hello World!</span></span><span>nope</span></h1>"#,
expected = r#"<h1><span><span>Hello World!</span></span><span>nope</span></h1>"#
)
}
#[test]
fn multiple_pseudo_selectors() {
assert_inlined!(
style = r#"span:first-child:last-child { color: red; }"#,
body = r#"<h1><span>Hello World!</span></h1>"#,
expected = r#"<h1><span style="color: red;">Hello World!</span></h1>"#
);
assert_inlined!(
style = r#"span:first-child:last-child { color: red; }"#,
body = r#"<h1><span>Hello World!</span><span>again!</span></h1>"#,
expected = r#"<h1><span>Hello World!</span><span>again!</span></h1>"#
)
}
#[test]
fn last_child_selector() {
assert_inlined!(
style = r#"h1 > :last-child { color: red; }"#,
body = r#"<h1><span>Hello World!</span></h1>"#,
expected = r#"<h1><span style="color: red;">Hello World!</span></h1>"#
)
}
#[test]
fn child_follow_by_first_child_selector_complex_dom() {
assert_inlined!(
style = r#"h1 > :first-child { color: red; }"#,
body = r#"<h1><span>Hello World!</span><p>foo</p><div class="barclass"><span>baz</span>bar</div></h1>"#,
expected = r#"<h1><span style="color: red;">Hello World!</span><p>foo</p><div class="barclass"><span>baz</span>bar</div></h1>"#
)
}
#[test]
fn child_follow_by_first_child_selector_with_comments() {
assert_inlined!(
style = r#"h1 > :first-child { color: red; }"#,
body = r#"<h1> <!-- enough said --><span>Hello World!</span><p>foo</p><div class="barclass"><span>baz</span>bar</div></h1>"#,
expected = r#"<h1> <!-- enough said --><span style="color: red;">Hello World!</span><p>foo</p><div class="barclass"><span>baz</span>bar</div></h1>"#
)
}
#[test]
fn child_follow_by_first_child_selector_with_white_spaces() {
assert_inlined!(
style = r#"h1 > :first-child { color: red; }"#,
body = r#"<h1> <span>Hello World!</span><p>foo</p><div class="barclass"><span>baz</span>bar</div></h1>"#,
expected = r#"<h1> <span style="color: red;">Hello World!</span><p>foo</p><div class="barclass"><span>baz</span>bar</div></h1>"#
)
}
#[test]
fn child_follow_by_adjacent_selector_complex_dom() {
assert_inlined!(
style = r#"h1 > span + p { color: red; }"#,
body = r#"<h1><span>Hello World!</span><p>foo</p><div class="barclass"><span>baz</span>bar</div></h1>"#,
expected = r#"<h1><span>Hello World!</span><p style="color: red;">foo</p><div class="barclass"><span>baz</span>bar</div></h1>"#
)
}
#[test]
fn unknown_pseudo_selector() {
assert_inlined!(
style = r#"h1 > span:css4-selector { color: red; }"#,
body = r#"<h1><span>Hello World!</span><p>foo</p><div class="barclass"><span>baz</span>bar</div></h1>"#,
expected = r#"<h1><span>Hello World!</span><p>foo</p><div class="barclass"><span>baz</span>bar</div></h1>"#
)
}
#[test]
fn adjacent_selector() {
assert_inlined!(
style = r#"h1 + h2 { color: red; }"#,
body = r#"<h1>Hello World!</h1><h2>How are you?</h2>"#,
expected = r#"<h1>Hello World!</h1><h2 style="color: red;">How are you?</h2>"#
)
}
#[test]
fn child_all_selector_complex_dom() {
assert_inlined!(
style = r#"h1 > * { color: red; }"#,
body = r#"<h1><span>Hello World!</span><p>foo</p><div class="barclass"><span>baz</span>bar</div></h1>"#,
expected = r#"<h1><span style="color: red;">Hello World!</span><p style="color: red;">foo</p><div class="barclass" style="color: red;"><span>baz</span>bar</div></h1>"#
)
}
#[test]
fn child_selector_complex_dom() {
assert_inlined!(
style = r#"h1 > span { color: red; }"#,
body = r#"<h1><span>Hello World!</span><p>foo</p><div class="barclass"><span>baz</span>bar</div></h1>"#,
expected = r#"<h1><span style="color: red;">Hello World!</span><p>foo</p><div class="barclass"><span>baz</span>bar</div></h1>"#
)
}
#[test]
fn nested_child_selector() {
assert_inlined!(
style = r#"div > h1 > span { color: red; }""#,
body = r#"<div><h1><span>Hello World!</span></h1></div>"#,
expected = r#"<div><h1><span style="color: red;">Hello World!</span></h1></div>"#
)
}
#[test]
fn child_selector() {
assert_inlined!(
style = r#"h1 > span { color: red; }"#,
body = r#"<h1><span>Hello World!</span></h1>"#,
expected = r#"<h1><span style="color: red;">Hello World!</span></h1>"#
)
}
#[test]
fn descendant_selector() {
assert_inlined!(
style = r#"h1 span { color: red; }"#,
body = r#"<h1><span>Hello World!</span></h1>"#,
expected = r#"<h1><span style="color: red;">Hello World!</span></h1>"#
)
}
#[test]
fn combination_selector() {
assert_inlined!(
style = r#"h1#a.b { color: red; }"#,
body = r#"<h1 id="a" class="b">Hello World!</h1>"#,
expected = r#"<h1 class="b" id="a" style="color: red;">Hello World!</h1>"#
)
}
#[test]
fn conflicting_multiple_class_selector() {
assert_inlined!(
style = r#"h1.a.b { color: red; }"#,
body = r#"<h1 class="a b">Hello World!</h1><h1 class="a">I should not be changed</h1>"#,
expected = r#"<h1 class="a b" style="color: red;">Hello World!</h1><h1 class="a">I should not be changed</h1>"#
)
}
#[test]
fn multiple_class_selector() {
assert_inlined!(
style = r#"h1.a.b { color: red; }"#,
body = r#"<h1 class="a b">Hello World!</h1>"#,
expected = r#"<h1 class="a b" style="color: red;">Hello World!</h1>"#
)
}
#[test]
fn missing_link_descendant_selector() {
assert_inlined!(
style = r#"#a b i { color: red }"#,
body = r#"<div id="a"><i>x</i></div>"#,
expected = r#"<div id="a"><i>x</i></div>"#
)
}
#[test]
fn comma_specificity() {
assert_inlined!(
style = r#"i, i { color: red; } i { color: blue; }"#,
body = r#"<i>howdy</i>"#,
expected = r#"<i style="color: blue;">howdy</i>"#
)
}
#[test]
fn overwrite_comma() {
assert_inlined!(
style = r#"h1,h2,h3 {color: #000;}"#,
body = r#"<h1 style="color: #fff">Foo</h1><h3 style="color: #fff">Foo</h3>"#,
expected = r#"<h1 style="color: #fff;">Foo</h1><h3 style="color: #fff;">Foo</h3>"#
)
}
<file_sep>/bindings/wasm/src/lib.rs
//! WASM bindings for css-inline
#![warn(
clippy::pedantic,
clippy::doc_markdown,
clippy::redundant_closure,
clippy::explicit_iter_loop,
clippy::match_same_arms,
clippy::needless_borrow,
clippy::print_stdout,
clippy::integer_arithmetic,
clippy::cast_possible_truncation,
clippy::unwrap_used,
clippy::map_unwrap_or,
clippy::trivially_copy_pass_by_ref,
clippy::needless_pass_by_value,
missing_docs,
missing_debug_implementations,
trivial_casts,
trivial_numeric_casts,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
variant_size_differences,
rust_2018_idioms,
rust_2018_compatibility
)]
use css_inline as rust_inline;
use std::{
borrow::Cow,
convert::{TryFrom, TryInto},
};
use wasm_bindgen::prelude::*;
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc<'_> = wee_alloc::WeeAlloc::INIT;
struct InlineErrorWrapper(rust_inline::InlineError);
impl From<InlineErrorWrapper> for JsValue {
fn from(error: InlineErrorWrapper) -> Self {
if let rust_inline::InlineError::ParseError(e) = error.0 {
JsValue::from_str(&e)
} else {
JsValue::from_str(error.0.to_string().as_str())
}
}
}
struct UrlError(url::ParseError);
impl From<UrlError> for JsValue {
fn from(error: UrlError) -> Self {
JsValue::from_str(error.0.to_string().as_str())
}
}
fn parse_url(url: Option<String>) -> Result<Option<url::Url>, JsValue> {
Ok(if let Some(url) = url {
Some(url::Url::parse(url.as_str()).map_err(UrlError)?)
} else {
None
})
}
#[macro_use]
extern crate serde_derive;
#[derive(Serialize, Deserialize)]
#[serde(default)]
struct Options {
inline_style_tags: bool,
remove_style_tags: bool,
base_url: Option<String>,
load_remote_stylesheets: bool,
extra_css: Option<String>,
}
impl Default for Options {
fn default() -> Self {
Options {
inline_style_tags: true,
remove_style_tags: false,
base_url: None,
load_remote_stylesheets: true,
extra_css: None,
}
}
}
struct SerdeError(serde_json::Error);
impl From<SerdeError> for JsValue {
fn from(error: SerdeError) -> Self {
JsValue::from_str(error.0.to_string().as_str())
}
}
impl TryFrom<Options> for rust_inline::InlineOptions<'_> {
type Error = JsValue;
fn try_from(value: Options) -> Result<Self, Self::Error> {
Ok(rust_inline::InlineOptions {
inline_style_tags: value.inline_style_tags,
remove_style_tags: value.remove_style_tags,
base_url: parse_url(value.base_url)?,
load_remote_stylesheets: value.load_remote_stylesheets,
extra_css: value.extra_css.map(Cow::Owned),
})
}
}
/// Inline CSS styles from <style> tags to matching elements in the HTML tree and return a string.
#[wasm_bindgen(skip_typescript)]
pub fn inline(html: &str, options: &JsValue) -> Result<String, JsValue> {
let options: Options = if options.is_undefined() {
Options::default()
} else {
options.into_serde().map_err(SerdeError)?
};
let inliner = rust_inline::CSSInliner::new(options.try_into()?);
Ok(inliner.inline(html).map_err(InlineErrorWrapper)?)
}
#[wasm_bindgen(typescript_custom_section)]
const INLINE: &'static str = r#"
interface InlineOptions {
inline_style_tags?: boolean,
remove_style_tags?: boolean,
base_url?: string,
load_remote_stylesheets?: boolean,
extra_css?: string,
}
export function inline(html: string, options?: InlineOptions): string;
"#;
#[cfg(test)]
pub mod tests {
use super::*;
use wasm_bindgen_test::wasm_bindgen_test;
#[wasm_bindgen_test]
fn default_config() {
let result = inline("<html><head><title>Test</title><style>h1 { color:red; }</style></head><body><h1>Test</h1></body></html>", &JsValue::undefined()).expect("Inlines correctly");
assert_eq!(result, "<html><head><title>Test</title><style>h1 { color:red; }</style></head><body><h1 style=\"color:red;\">Test</h1></body></html>");
}
#[wasm_bindgen_test]
fn remove_style_tags() {
let options = Options {
remove_style_tags: true,
..Options::default()
};
let options = JsValue::from_serde(&options).expect("Valid value");
let result = inline("<html><head><title>Test</title><style>h1 { color:red; }</style></head><body><h1>Test</h1></body></html>", &options).expect("Inlines correctly");
assert_eq!(result, "<html><head><title>Test</title></head><body><h1 style=\"color:red;\">Test</h1></body></html>");
}
}
| d1457637c57d59f9721712b038617ba6570bd774 | [
"reStructuredText",
"Markdown",
"TOML",
"INI",
"Rust",
"Python",
"Shell"
] | 23 | Markdown | VedantSupe/css-inline | abe066af72b542bf0eb88f953c4fa2802d764320 | f066e5ba731889cd9f602d5459f44491d18ed95d |
refs/heads/master | <repo_name>true-datura/Auth_and_logging_hw<file_sep>/Auth_hw/log_processor/views.py
from django.contrib.auth import authenticate, login
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_protect
from .models import LogInfo
@csrf_protect
def auth(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = authenticate(username=username, password=<PASSWORD>)
if user is not None:
# the password verified for the user
if user.is_active:
login(request, user)
print("User is valid, active and authenticated")
else:
print("The password is valid, but the account has been disabled!")
else:
# the authentication system was unable to verify the username and password
print("The username and password were incorrect.")
context = {}
return render(request, "response.html", context)
@login_required
def write_log_to_db(request):
if request.method == 'POST':
time = request.POST.get('asctime', '').split(',')[0]
level = request.POST.get('levelname', '')
logger_name = request.POST.get('name', '')
message = request.POST.get('message', '')
sender = get_client_ip(request)
log = LogInfo.objects.create(time=time, level=level, message=message, logger_name=logger_name, sender=sender)
log.save()
context = {}
return render(request, "response.html", context)
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip<file_sep>/Auth_hw/log_processor/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^auth/', views.auth, name='auth'),
url(r'^log/', views.write_log_to_db, name='log'),
]<file_sep>/Auth_hw/log_processor/apps.py
from django.apps import AppConfig
class LogProcessorConfig(AppConfig):
name = 'log_processor'
<file_sep>/Auth_hw/log_processor/admin.py
from django.contrib import admin
from .models import LogInfo
@admin.register(LogInfo)
class LogInfoAdmin(admin.ModelAdmin):
list_display = ('time', 'level', 'message', 'logger_name', 'sender',)
empty_value_display = 'Empty'
fields = ('time', 'level', 'message', 'logger_name', 'sender',)
<file_sep>/Auth_hw/log_processor/models.py
from django.db import models
class LogInfo(models.Model):
time = models.DateTimeField()
level = models.CharField(max_length=200)
message = models.CharField(max_length=200)
logger_name = models.CharField(max_length=200)
sender = models.CharField(max_length=200)
<file_sep>/logger_1.py
import logging
import requests
class SpaceHandler(logging.Handler):
def __init__(self, URL, *args, **kwargs):
self.URL = URL
super().__init__(*args, **kwargs)
def emit(self, record):
client = requests.Session()
client.get(self.URL + '/auth/')
print(record)
print(client.cookies)
csrf_token = client.cookies['csrftoken']
client.post(self.URL + '/auth/', data=dict(username='Archie',
password='<PASSWORD>',
csrfmiddlewaretoken=csrf_token))
client.get(self.URL + '/log/')
csrf_token = client.cookies['csrftoken']
client.post(self.URL + '/log/', data=dict(message=record.message,
name=record.name,
levelname=record.levelname,
asctime=record.asctime,
csrfmiddlewaretoken=csrf_token))
logger = logging.getLogger('spam_application')
logger.setLevel("DEBUG")
# create console handler with a higher log level
ch = logging.StreamHandler()
space_handler = SpaceHandler('http://127.0.0.1:8000')
ch.setLevel("DEBUG")
space_handler.setLevel("DEBUG")
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
space_handler.setFormatter(formatter)
logger.addHandler(ch)
logger.addHandler(space_handler)
logger.info('creating an instance of auxiliary_module.Auxiliary')<file_sep>/README.md
Auth and logging hw
| 1322f9c356b4045ac825ec39bcac7fa8f749e071 | [
"Markdown",
"Python"
] | 7 | Python | true-datura/Auth_and_logging_hw | 585d7f9e29d26c0e9c31634581ed10f24f01dc80 | 0895314d86ccc014302114edb602e0348aeaff2b |
refs/heads/master | <repo_name>litert/timezone.js<file_sep>/src/lib/index.ts
/**
* Copyright 2021 Angus.Fenying <<EMAIL>>
*
* 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
*
* https://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.
*/
const TIME_ZONES: Record<string, ITimeZone> = {
/* eslint-disable @typescript-eslint/naming-convention */
'africa/abidjan': {
'name': 'Africa/Abidjan',
'description': '',
'location': 'CI',
'offset': 0,
'dstOffset': 0,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'africa/accra': {
'name': 'Africa/Accra',
'description': '',
'location': 'GH',
'offset': 0,
'dstOffset': 0,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'africa/addis_ababa': {
'name': 'Africa/Addis_Ababa',
'description': '',
'location': 'ET',
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Nairobi'
},
'africa/algiers': {
'name': 'Africa/Algiers',
'description': '',
'location': 'DZ',
'offset': 60,
'dstOffset': 60,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'africa/asmara': {
'name': 'Africa/Asmara',
'description': '',
'location': 'ER',
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Nairobi'
},
'africa/asmera': {
'name': 'Africa/Asmera',
'description': '',
'location': 'ER',
'offset': 180,
'dstOffset': 180,
'deprecated': true,
'canonical': false,
'aliasOf': 'Africa/Nairobi'
},
'africa/bamako': {
'name': 'Africa/Bamako',
'description': '',
'location': 'ML',
'offset': 0,
'dstOffset': 0,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Abidjan'
},
'africa/bangui': {
'name': 'Africa/Bangui',
'description': '',
'location': 'CF',
'offset': 60,
'dstOffset': 60,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Lagos'
},
'africa/banjul': {
'name': 'Africa/Banjul',
'description': '',
'location': 'GM',
'offset': 0,
'dstOffset': 0,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Abidjan'
},
'africa/bissau': {
'name': 'Africa/Bissau',
'description': '',
'location': 'GW',
'offset': 0,
'dstOffset': 0,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'africa/blantyre': {
'name': 'Africa/Blantyre',
'description': '',
'location': 'MW',
'offset': 120,
'dstOffset': 120,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Maputo'
},
'africa/brazzaville': {
'name': 'Africa/Brazzaville',
'description': '',
'location': 'CG',
'offset': 60,
'dstOffset': 60,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Lagos'
},
'africa/bujumbura': {
'name': 'Africa/Bujumbura',
'description': '',
'location': 'BI',
'offset': 120,
'dstOffset': 120,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Maputo'
},
'africa/cairo': {
'name': 'Africa/Cairo',
'description': '',
'location': 'EG',
'offset': 120,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'africa/casablanca': {
'name': 'Africa/Casablanca',
'description': '',
'location': 'MA',
'offset': 60,
'dstOffset': 0,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'africa/ceuta': {
'name': 'Africa/Ceuta',
'description': 'Ceuta, Melilla',
'location': 'ES',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'africa/conakry': {
'name': 'Africa/Conakry',
'description': '',
'location': 'GN',
'offset': 0,
'dstOffset': 0,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Abidjan'
},
'africa/dakar': {
'name': 'Africa/Dakar',
'description': '',
'location': 'SN',
'offset': 0,
'dstOffset': 0,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Abidjan'
},
'africa/dar_es_salaam': {
'name': 'Africa/Dar_es_Salaam',
'description': '',
'location': 'TZ',
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Nairobi'
},
'africa/djibouti': {
'name': 'Africa/Djibouti',
'description': '',
'location': 'DJ',
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Nairobi'
},
'africa/douala': {
'name': 'Africa/Douala',
'description': '',
'location': 'CM',
'offset': 60,
'dstOffset': 60,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Lagos'
},
'africa/el_aaiun': {
'name': 'Africa/El_Aaiun',
'description': '',
'location': 'EH',
'offset': 60,
'dstOffset': 0,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'africa/freetown': {
'name': 'Africa/Freetown',
'description': '',
'location': 'SL',
'offset': 0,
'dstOffset': 0,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Abidjan'
},
'africa/gaborone': {
'name': 'Africa/Gaborone',
'description': '',
'location': 'BW',
'offset': 120,
'dstOffset': 120,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Maputo'
},
'africa/harare': {
'name': 'Africa/Harare',
'description': '',
'location': 'ZW',
'offset': 120,
'dstOffset': 120,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Maputo'
},
'africa/johannesburg': {
'name': 'Africa/Johannesburg',
'description': '',
'location': 'ZA',
'offset': 120,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'africa/juba': {
'name': 'Africa/Juba',
'description': '',
'location': 'SS',
'offset': 120,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'africa/kampala': {
'name': 'Africa/Kampala',
'description': '',
'location': 'UG',
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Nairobi'
},
'africa/khartoum': {
'name': 'Africa/Khartoum',
'description': '',
'location': 'SD',
'offset': 120,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'africa/kigali': {
'name': 'Africa/Kigali',
'description': '',
'location': 'RW',
'offset': 120,
'dstOffset': 120,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Maputo'
},
'africa/kinshasa': {
'name': 'Africa/Kinshasa',
'description': 'Dem. Rep. of Congo (west)',
'location': 'CD',
'offset': 60,
'dstOffset': 60,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Lagos'
},
'africa/lagos': {
'name': 'Africa/Lagos',
'description': 'West Africa Time',
'location': 'NG',
'offset': 60,
'dstOffset': 60,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'africa/libreville': {
'name': 'Africa/Libreville',
'description': '',
'location': 'GA',
'offset': 60,
'dstOffset': 60,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Lagos'
},
'africa/lome': {
'name': 'Africa/Lome',
'description': '',
'location': 'TG',
'offset': 0,
'dstOffset': 0,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Abidjan'
},
'africa/luanda': {
'name': 'Africa/Luanda',
'description': '',
'location': 'AO',
'offset': 60,
'dstOffset': 60,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Lagos'
},
'africa/lubumbashi': {
'name': 'Africa/Lubumbashi',
'description': 'Dem. Rep. of Congo (east)',
'location': 'CD',
'offset': 120,
'dstOffset': 120,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Maputo'
},
'africa/lusaka': {
'name': 'Africa/Lusaka',
'description': '',
'location': 'ZM',
'offset': 120,
'dstOffset': 120,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Maputo'
},
'africa/malabo': {
'name': 'Africa/Malabo',
'description': '',
'location': 'GQ',
'offset': 60,
'dstOffset': 60,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Lagos'
},
'africa/maputo': {
'name': 'Africa/Maputo',
'description': 'Central Africa Time',
'location': 'MZ',
'offset': 120,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'africa/maseru': {
'name': 'Africa/Maseru',
'description': '',
'location': 'LS',
'offset': 120,
'dstOffset': 120,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Johannesburg'
},
'africa/mbabane': {
'name': 'Africa/Mbabane',
'description': '',
'location': 'SZ',
'offset': 120,
'dstOffset': 120,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Johannesburg'
},
'africa/mogadishu': {
'name': 'Africa/Mogadishu',
'description': '',
'location': 'SO',
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Nairobi'
},
'africa/monrovia': {
'name': 'Africa/Monrovia',
'description': '',
'location': 'LR',
'offset': 0,
'dstOffset': 0,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'africa/nairobi': {
'name': 'Africa/Nairobi',
'description': '',
'location': 'KE',
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'africa/ndjamena': {
'name': 'Africa/Ndjamena',
'description': '',
'location': 'TD',
'offset': 60,
'dstOffset': 60,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'africa/niamey': {
'name': 'Africa/Niamey',
'description': '',
'location': 'NE',
'offset': 60,
'dstOffset': 60,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Lagos'
},
'africa/nouakchott': {
'name': 'Africa/Nouakchott',
'description': '',
'location': 'MR',
'offset': 0,
'dstOffset': 0,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Abidjan'
},
'africa/ouagadougou': {
'name': 'Africa/Ouagadougou',
'description': '',
'location': 'BF',
'offset': 0,
'dstOffset': 0,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Abidjan'
},
'africa/porto-novo': {
'name': 'Africa/Porto-Novo',
'description': '',
'location': 'BJ',
'offset': 60,
'dstOffset': 60,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Lagos'
},
'africa/sao_tome': {
'name': 'Africa/Sao_Tome',
'description': '',
'location': 'ST',
'offset': 0,
'dstOffset': 0,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'africa/timbuktu': {
'name': 'Africa/Timbuktu',
'description': '',
'location': 'ML',
'offset': 0,
'dstOffset': 0,
'deprecated': true,
'canonical': false,
'aliasOf': 'Africa/Abidjan'
},
'africa/tripoli': {
'name': 'Africa/Tripoli',
'description': '',
'location': 'LY',
'offset': 120,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'africa/tunis': {
'name': 'Africa/Tunis',
'description': '',
'location': 'TN',
'offset': 60,
'dstOffset': 60,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'africa/windhoek': {
'name': 'Africa/Windhoek',
'description': '',
'location': 'NA',
'offset': 120,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/adak': {
'name': 'America/Adak',
'description': 'Aleutian Islands',
'location': 'US',
'offset': -600,
'dstOffset': -540,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/anchorage': {
'name': 'America/Anchorage',
'description': 'Alaska (most areas)',
'location': 'US',
'offset': -540,
'dstOffset': -480,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/anguilla': {
'name': 'America/Anguilla',
'description': '',
'location': 'AI',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': false,
'aliasOf': 'America/Port_of_Spain'
},
'america/antigua': {
'name': 'America/Antigua',
'description': '',
'location': 'AG',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': false,
'aliasOf': 'America/Port_of_Spain'
},
'america/araguaina': {
'name': 'America/Araguaina',
'description': 'Tocantins',
'location': 'BR',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/argentina/buenos_aires': {
'name': 'America/Argentina/Buenos_Aires',
'description': 'Buenos Aires (BA, CF)',
'location': 'AR',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/argentina/catamarca': {
'name': 'America/Argentina/Catamarca',
'description': 'Catamarca (CT); Chubut (CH)',
'location': 'AR',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/argentina/comodrivadavia': {
'name': 'America/Argentina/ComodRivadavia',
'description': '',
'location': 'AR',
'offset': -180,
'dstOffset': -180,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Argentina/Catamarca'
},
'america/argentina/cordoba': {
'name': 'America/Argentina/Cordoba',
'description': 'Argentina (most areas: CB, CC, CN, ER, FM, MN, SE, SF)',
'location': 'AR',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/argentina/jujuy': {
'name': 'America/Argentina/Jujuy',
'description': 'Jujuy (JY)',
'location': 'AR',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/argentina/la_rioja': {
'name': 'America/Argentina/La_Rioja',
'description': 'La Rioja (LR)',
'location': 'AR',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/argentina/mendoza': {
'name': 'America/Argentina/Mendoza',
'description': 'Mendoza (MZ)',
'location': 'AR',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/argentina/rio_gallegos': {
'name': 'America/Argentina/Rio_Gallegos',
'description': 'Santa Cruz (SC)',
'location': 'AR',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/argentina/salta': {
'name': 'America/Argentina/Salta',
'description': 'Salta (SA, LP, NQ, RN)',
'location': 'AR',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/argentina/san_juan': {
'name': 'America/Argentina/San_Juan',
'description': 'San Juan (SJ)',
'location': 'AR',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/argentina/san_luis': {
'name': 'America/Argentina/San_Luis',
'description': 'San Luis (SL)',
'location': 'AR',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/argentina/tucuman': {
'name': 'America/Argentina/Tucuman',
'description': 'Tucumán (TM)',
'location': 'AR',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/argentina/ushuaia': {
'name': 'America/Argentina/Ushuaia',
'description': 'Tierra del Fuego (TF)',
'location': 'AR',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/aruba': {
'name': 'America/Aruba',
'description': '',
'location': 'AW',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': false,
'aliasOf': 'America/Curacao'
},
'america/asuncion': {
'name': 'America/Asuncion',
'description': '',
'location': 'PY',
'offset': -240,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/atikokan': {
'name': 'America/Atikokan',
'description': 'EST - ON (Atikokan); NU (Coral H)',
'location': 'CA',
'offset': -300,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/atka': {
'name': 'America/Atka',
'description': '',
'location': 'US',
'offset': -600,
'dstOffset': -540,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Adak'
},
'america/bahia': {
'name': 'America/Bahia',
'description': 'Bahia',
'location': 'BR',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/bahia_banderas': {
'name': 'America/Bahia_Banderas',
'description': 'Central Time - Bahía de Banderas',
'location': 'MX',
'offset': -360,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/barbados': {
'name': 'America/Barbados',
'description': '',
'location': 'BB',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/belem': {
'name': 'America/Belem',
'description': 'Pará (east); Amapá',
'location': 'BR',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/belize': {
'name': 'America/Belize',
'description': '',
'location': 'BZ',
'offset': -360,
'dstOffset': -360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/blanc-sablon': {
'name': 'America/Blanc-Sablon',
'description': 'AST - QC (Lower North Shore)',
'location': 'CA',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/boa_vista': {
'name': 'America/Boa_Vista',
'description': 'Roraima',
'location': 'BR',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/bogota': {
'name': 'America/Bogota',
'description': '',
'location': 'CO',
'offset': -300,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/boise': {
'name': 'America/Boise',
'description': 'Mountain - ID (south); OR (east)',
'location': 'US',
'offset': -420,
'dstOffset': -360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/buenos_aires': {
'name': 'America/Buenos_Aires',
'description': '',
'location': 'AR',
'offset': -180,
'dstOffset': -180,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Argentina/Buenos_Aires'
},
'america/cambridge_bay': {
'name': 'America/Cambridge_Bay',
'description': 'Mountain - NU (west)',
'location': 'CA',
'offset': -420,
'dstOffset': -360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/campo_grande': {
'name': 'America/Campo_Grande',
'description': 'Mato Grosso do Sul',
'location': 'BR',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/cancun': {
'name': 'America/Cancun',
'description': 'Eastern Standard Time - Quintana Roo',
'location': 'MX',
'offset': -300,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/caracas': {
'name': 'America/Caracas',
'description': '',
'location': 'VE',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/catamarca': {
'name': 'America/Catamarca',
'description': '',
'location': 'AR',
'offset': -180,
'dstOffset': -180,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Argentina/Catamarca'
},
'america/cayenne': {
'name': 'America/Cayenne',
'description': '',
'location': 'GF',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/cayman': {
'name': 'America/Cayman',
'description': '',
'location': 'KY',
'offset': -300,
'dstOffset': -300,
'deprecated': false,
'canonical': false,
'aliasOf': 'America/Panama'
},
'america/chicago': {
'name': 'America/Chicago',
'description': 'Central (most areas)',
'location': 'US',
'offset': -360,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/chihuahua': {
'name': 'America/Chihuahua',
'description': 'Mountain Time - Chihuahua (most areas)',
'location': 'MX',
'offset': -420,
'dstOffset': -360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/coral_harbour': {
'name': 'America/Coral_Harbour',
'description': '',
'location': 'CA',
'offset': -300,
'dstOffset': -300,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Atikokan'
},
'america/cordoba': {
'name': 'America/Cordoba',
'description': '',
'location': 'AR',
'offset': -180,
'dstOffset': -180,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Argentina/Cordoba'
},
'america/costa_rica': {
'name': 'America/Costa_Rica',
'description': '',
'location': 'CR',
'offset': -360,
'dstOffset': -360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/creston': {
'name': 'America/Creston',
'description': 'MST - BC (Creston)',
'location': 'CA',
'offset': -420,
'dstOffset': -420,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/cuiaba': {
'name': 'America/Cuiaba',
'description': '<NAME>',
'location': 'BR',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/curacao': {
'name': 'America/Curacao',
'description': '',
'location': 'CW',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/danmarkshavn': {
'name': 'America/Danmarkshavn',
'description': 'National Park (east coast)',
'location': 'GL',
'offset': 0,
'dstOffset': 0,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/dawson': {
'name': 'America/Dawson',
'description': 'MST - Yukon (west)',
'location': 'CA',
'offset': -420,
'dstOffset': -420,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/dawson_creek': {
'name': 'America/Dawson_Creek',
'description': 'MST - BC (Dawson Cr, Ft St John)',
'location': 'CA',
'offset': -420,
'dstOffset': -420,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/denver': {
'name': 'America/Denver',
'description': 'Mountain (most areas)',
'location': 'US',
'offset': -420,
'dstOffset': -360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/detroit': {
'name': 'America/Detroit',
'description': 'Eastern - MI (most areas)',
'location': 'US',
'offset': -300,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/dominica': {
'name': 'America/Dominica',
'description': '',
'location': 'DM',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': false,
'aliasOf': 'America/Port_of_Spain'
},
'america/edmonton': {
'name': 'America/Edmonton',
'description': 'Mountain - AB; BC (E); SK (W)',
'location': 'CA',
'offset': -420,
'dstOffset': -360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/eirunepe': {
'name': 'America/Eirunepe',
'description': 'Amazonas (west)',
'location': 'BR',
'offset': -300,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/el_salvador': {
'name': 'America/El_Salvador',
'description': '',
'location': 'SV',
'offset': -360,
'dstOffset': -360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/ensenada': {
'name': 'America/Ensenada',
'description': '',
'location': 'MX',
'offset': -480,
'dstOffset': -420,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Tijuana'
},
'america/fort_nelson': {
'name': 'America/Fort_Nelson',
'description': 'MST - BC (Ft Nelson)',
'location': 'CA',
'offset': -420,
'dstOffset': -420,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/fort_wayne': {
'name': 'America/Fort_Wayne',
'description': '',
'location': 'US',
'offset': -300,
'dstOffset': -240,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Indiana/Indianapolis'
},
'america/fortaleza': {
'name': 'America/Fortaleza',
'description': 'Brazil (northeast: MA, PI, CE, RN, PB)',
'location': 'BR',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/glace_bay': {
'name': 'America/Glace_Bay',
'description': 'Atlantic - NS (Cape Breton)',
'location': 'CA',
'offset': -240,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/godthab': {
'name': 'America/Godthab',
'description': '',
'location': 'GL',
'offset': -180,
'dstOffset': -120,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Nuuk'
},
'america/goose_bay': {
'name': 'America/Goose_Bay',
'description': 'Atlantic - Labrador (most areas)',
'location': 'CA',
'offset': -240,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/grand_turk': {
'name': 'America/Grand_Turk',
'description': '',
'location': 'TC',
'offset': -300,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/grenada': {
'name': 'America/Grenada',
'description': '',
'location': 'GD',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': false,
'aliasOf': 'America/Port_of_Spain'
},
'america/guadeloupe': {
'name': 'America/Guadeloupe',
'description': '',
'location': 'GP',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': false,
'aliasOf': 'America/Port_of_Spain'
},
'america/guatemala': {
'name': 'America/Guatemala',
'description': '',
'location': 'GT',
'offset': -360,
'dstOffset': -360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/guayaquil': {
'name': 'America/Guayaquil',
'description': 'Ecuador (mainland)',
'location': 'EC',
'offset': -300,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/guyana': {
'name': 'America/Guyana',
'description': '',
'location': 'GY',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/halifax': {
'name': 'America/Halifax',
'description': 'Atlantic - NS (most areas); PE',
'location': 'CA',
'offset': -240,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/havana': {
'name': 'America/Havana',
'description': '',
'location': 'CU',
'offset': -300,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/hermosillo': {
'name': 'America/Hermosillo',
'description': 'Mountain Standard Time - Sonora',
'location': 'MX',
'offset': -420,
'dstOffset': -420,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/indiana/indianapolis': {
'name': 'America/Indiana/Indianapolis',
'description': 'Eastern - IN (most areas)',
'location': 'US',
'offset': -300,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/indiana/knox': {
'name': 'America/Indiana/Knox',
'description': 'Central - IN (Starke)',
'location': 'US',
'offset': -360,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/indiana/marengo': {
'name': 'America/Indiana/Marengo',
'description': 'Eastern - IN (Crawford)',
'location': 'US',
'offset': -300,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/indiana/petersburg': {
'name': 'America/Indiana/Petersburg',
'description': 'Eastern - IN (Pike)',
'location': 'US',
'offset': -300,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/indiana/tell_city': {
'name': 'America/Indiana/Tell_City',
'description': 'Central - IN (Perry)',
'location': 'US',
'offset': -360,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/indiana/vevay': {
'name': 'America/Indiana/Vevay',
'description': 'Eastern - IN (Switzerland)',
'location': 'US',
'offset': -300,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/indiana/vincennes': {
'name': 'America/Indiana/Vincennes',
'description': 'Eastern - IN (Da, Du, K, Mn)',
'location': 'US',
'offset': -300,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/indiana/winamac': {
'name': 'America/Indiana/Winamac',
'description': 'Eastern - IN (Pulaski)',
'location': 'US',
'offset': -300,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/indianapolis': {
'name': 'America/Indianapolis',
'description': '',
'location': 'US',
'offset': -300,
'dstOffset': -240,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Indiana/Indianapolis'
},
'america/inuvik': {
'name': 'America/Inuvik',
'description': 'Mountain - NT (west)',
'location': 'CA',
'offset': -420,
'dstOffset': -360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/iqaluit': {
'name': 'America/Iqaluit',
'description': 'Eastern - NU (most east areas)',
'location': 'CA',
'offset': -300,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/jamaica': {
'name': 'America/Jamaica',
'description': '',
'location': 'JM',
'offset': -300,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/jujuy': {
'name': 'America/Jujuy',
'description': '',
'location': 'AR',
'offset': -180,
'dstOffset': -180,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Argentina/Jujuy'
},
'america/juneau': {
'name': 'America/Juneau',
'description': 'Alaska - Juneau area',
'location': 'US',
'offset': -540,
'dstOffset': -480,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/kentucky/louisville': {
'name': 'America/Kentucky/Louisville',
'description': 'Eastern - KY (Louisville area)',
'location': 'US',
'offset': -300,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/kentucky/monticello': {
'name': 'America/Kentucky/Monticello',
'description': 'Eastern - KY (Wayne)',
'location': 'US',
'offset': -300,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/knox_in': {
'name': 'America/Knox_IN',
'description': '',
'location': 'US',
'offset': -360,
'dstOffset': -300,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Indiana/Knox'
},
'america/kralendijk': {
'name': 'America/Kralendijk',
'description': '',
'location': 'BQ',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': false,
'aliasOf': 'America/Curacao'
},
'america/la_paz': {
'name': 'America/La_Paz',
'description': '',
'location': 'BO',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/lima': {
'name': 'America/Lima',
'description': '',
'location': 'PE',
'offset': -300,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/los_angeles': {
'name': 'America/Los_Angeles',
'description': 'Pacific',
'location': 'US',
'offset': -480,
'dstOffset': -420,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/louisville': {
'name': 'America/Louisville',
'description': '',
'location': 'US',
'offset': -300,
'dstOffset': -240,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Kentucky/Louisville'
},
'america/lower_princes': {
'name': 'America/Lower_Princes',
'description': '',
'location': 'SX',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': false,
'aliasOf': 'America/Curacao'
},
'america/maceio': {
'name': 'America/Maceio',
'description': 'Alagoas, Sergipe',
'location': 'BR',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/managua': {
'name': 'America/Managua',
'description': '',
'location': 'NI',
'offset': -360,
'dstOffset': -360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/manaus': {
'name': 'America/Manaus',
'description': 'Amazonas (east)',
'location': 'BR',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/marigot': {
'name': 'America/Marigot',
'description': '',
'location': 'MF',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': false,
'aliasOf': 'America/Port_of_Spain'
},
'america/martinique': {
'name': 'America/Martinique',
'description': '',
'location': 'MQ',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/matamoros': {
'name': 'America/Matamoros',
'description': 'Central Time US - Coahuila, Nuevo León, Tamaulipas (US border)',
'location': 'MX',
'offset': -360,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/mazatlan': {
'name': 'America/Mazatlan',
'description': 'Mountain Time - Baja California Sur, Nayarit, Sinaloa',
'location': 'MX',
'offset': -420,
'dstOffset': -360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/mendoza': {
'name': 'America/Mendoza',
'description': '',
'location': 'AR',
'offset': -180,
'dstOffset': -180,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Argentina/Mendoza'
},
'america/menominee': {
'name': 'America/Menominee',
'description': 'Central - MI (Wisconsin border)',
'location': 'US',
'offset': -360,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/merida': {
'name': 'America/Merida',
'description': 'Central Time - Campeche, Yucatán',
'location': 'MX',
'offset': -360,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/metlakatla': {
'name': 'America/Metlakatla',
'description': 'Alaska - Annette Island',
'location': 'US',
'offset': -540,
'dstOffset': -480,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/mexico_city': {
'name': 'America/Mexico_City',
'description': 'Central Time',
'location': 'MX',
'offset': -360,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/miquelon': {
'name': 'America/Miquelon',
'description': '',
'location': 'PM',
'offset': -180,
'dstOffset': -120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/moncton': {
'name': 'America/Moncton',
'description': 'Atlantic - New Brunswick',
'location': 'CA',
'offset': -240,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/monterrey': {
'name': 'America/Monterrey',
'description': 'Central Time - Durango; Coahuila, Nuevo León, Tamaulipas (most areas)',
'location': 'MX',
'offset': -360,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/montevideo': {
'name': 'America/Montevideo',
'description': '',
'location': 'UY',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/montreal': {
'name': 'America/Montreal',
'description': '',
'location': 'CA',
'offset': -300,
'dstOffset': -240,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Toronto'
},
'america/montserrat': {
'name': 'America/Montserrat',
'description': '',
'location': 'MS',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': false,
'aliasOf': 'America/Port_of_Spain'
},
'america/nassau': {
'name': 'America/Nassau',
'description': '',
'location': 'BS',
'offset': -300,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/new_york': {
'name': 'America/New_York',
'description': 'Eastern (most areas)',
'location': 'US',
'offset': -300,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/nipigon': {
'name': 'America/Nipigon',
'description': 'Eastern - ON, QC (no DST 1967-73)',
'location': 'CA',
'offset': -300,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/nome': {
'name': 'America/Nome',
'description': 'Alaska (west)',
'location': 'US',
'offset': -540,
'dstOffset': -480,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/noronha': {
'name': 'America/Noronha',
'description': 'Atlantic islands',
'location': 'BR',
'offset': -120,
'dstOffset': -120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/north_dakota/beulah': {
'name': 'America/North_Dakota/Beulah',
'description': 'Central - ND (Mercer)',
'location': 'US',
'offset': -360,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/north_dakota/center': {
'name': 'America/North_Dakota/Center',
'description': 'Central - ND (Oliver)',
'location': 'US',
'offset': -360,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/north_dakota/new_salem': {
'name': 'America/North_Dakota/New_Salem',
'description': 'Central - ND (Morton rural)',
'location': 'US',
'offset': -360,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/nuuk': {
'name': 'America/Nuuk',
'description': 'Greenland (most areas)',
'location': 'GL',
'offset': -180,
'dstOffset': -120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/ojinaga': {
'name': 'America/Ojinaga',
'description': 'Mountain Time US - Chihuahua (US border)',
'location': 'MX',
'offset': -420,
'dstOffset': -360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/panama': {
'name': 'America/Panama',
'description': '',
'location': 'PA',
'offset': -300,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/pangnirtung': {
'name': 'America/Pangnirtung',
'description': 'Eastern - NU (Pangnirtung)',
'location': 'CA',
'offset': -300,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/paramaribo': {
'name': 'America/Paramaribo',
'description': '',
'location': 'SR',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/phoenix': {
'name': 'America/Phoenix',
'description': 'MST - Arizona (except Navajo)',
'location': 'US',
'offset': -420,
'dstOffset': -420,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/port-au-prince': {
'name': 'America/Port-au-Prince',
'description': '',
'location': 'HT',
'offset': -300,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/port_of_spain': {
'name': 'America/Port_of_Spain',
'description': '',
'location': 'TT',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/porto_acre': {
'name': 'America/Porto_Acre',
'description': '',
'location': 'BR',
'offset': -300,
'dstOffset': -300,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Rio_Branco'
},
'america/porto_velho': {
'name': 'America/Porto_Velho',
'description': 'Rondônia',
'location': 'BR',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/puerto_rico': {
'name': 'America/Puerto_Rico',
'description': '',
'location': 'PR',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/punta_arenas': {
'name': 'America/Punta_Arenas',
'description': 'Region of Magallanes',
'location': 'CL',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/rainy_river': {
'name': 'America/Rainy_River',
'description': 'Central - ON (Rainy R, Ft Frances)',
'location': 'CA',
'offset': -360,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/rankin_inlet': {
'name': 'America/Rankin_Inlet',
'description': 'Central - NU (central)',
'location': 'CA',
'offset': -360,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/recife': {
'name': 'America/Recife',
'description': 'Pernambuco',
'location': 'BR',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/regina': {
'name': 'America/Regina',
'description': 'CST - SK (most areas)',
'location': 'CA',
'offset': -360,
'dstOffset': -360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/resolute': {
'name': 'America/Resolute',
'description': 'Central - NU (Resolute)',
'location': 'CA',
'offset': -360,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/rio_branco': {
'name': 'America/Rio_Branco',
'description': 'Acre',
'location': 'BR',
'offset': -300,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/rosario': {
'name': 'America/Rosario',
'description': '',
'location': 'AR',
'offset': -180,
'dstOffset': -180,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Argentina/Cordoba'
},
'america/santa_isabel': {
'name': 'America/Santa_Isabel',
'description': '',
'location': 'MX',
'offset': -480,
'dstOffset': -420,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Tijuana'
},
'america/santarem': {
'name': 'America/Santarem',
'description': 'Pará (west)',
'location': 'BR',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/santiago': {
'name': 'America/Santiago',
'description': 'Chile (most areas)',
'location': 'CL',
'offset': -240,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/santo_domingo': {
'name': 'America/Santo_Domingo',
'description': '',
'location': 'DO',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/sao_paulo': {
'name': 'America/Sao_Paulo',
'description': 'Brazil (southeast: GO, DF, MG, ES, RJ, SP, PR, SC, RS)',
'location': 'BR',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/scoresbysund': {
'name': 'America/Scoresbysund',
'description': 'Scoresbysund/Ittoqqortoormiit',
'location': 'GL',
'offset': -60,
'dstOffset': 0,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/shiprock': {
'name': 'America/Shiprock',
'description': '',
'location': 'US',
'offset': -420,
'dstOffset': -360,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Denver'
},
'america/sitka': {
'name': 'America/Sitka',
'description': 'Alaska - Sitka area',
'location': 'US',
'offset': -540,
'dstOffset': -480,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/st_barthelemy': {
'name': 'America/St_Barthelemy',
'description': '',
'location': 'BL',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': false,
'aliasOf': 'America/Port_of_Spain'
},
'america/st_johns': {
'name': 'America/St_Johns',
'description': 'Newfoundland; Labrador (southeast)',
'location': 'CA',
'offset': -210,
'dstOffset': -150,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/st_kitts': {
'name': 'America/St_Kitts',
'description': '',
'location': 'KN',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': false,
'aliasOf': 'America/Port_of_Spain'
},
'america/st_lucia': {
'name': 'America/St_Lucia',
'description': '',
'location': 'LC',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': false,
'aliasOf': 'America/Port_of_Spain'
},
'america/st_thomas': {
'name': 'America/St_Thomas',
'description': '',
'location': 'VI',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': false,
'aliasOf': 'America/Port_of_Spain'
},
'america/st_vincent': {
'name': 'America/St_Vincent',
'description': '',
'location': 'VC',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': false,
'aliasOf': 'America/Port_of_Spain'
},
'america/swift_current': {
'name': 'America/Swift_Current',
'description': 'CST - SK (midwest)',
'location': 'CA',
'offset': -360,
'dstOffset': -360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/tegucigalpa': {
'name': 'America/Tegucigalpa',
'description': '',
'location': 'HN',
'offset': -360,
'dstOffset': -360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/thule': {
'name': 'America/Thule',
'description': 'Thule/Pituffik',
'location': 'GL',
'offset': -240,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/thunder_bay': {
'name': 'America/Thunder_Bay',
'description': 'Eastern - ON (Thunder Bay)',
'location': 'CA',
'offset': -300,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/tijuana': {
'name': 'America/Tijuana',
'description': 'Pacific Time US - Baja California',
'location': 'MX',
'offset': -480,
'dstOffset': -420,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/toronto': {
'name': 'America/Toronto',
'description': 'Eastern - ON, QC (most areas)',
'location': 'CA',
'offset': -300,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/tortola': {
'name': 'America/Tortola',
'description': '',
'location': 'VG',
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': false,
'aliasOf': 'America/Port_of_Spain'
},
'america/vancouver': {
'name': 'America/Vancouver',
'description': 'Pacific - BC (most areas)',
'location': 'CA',
'offset': -480,
'dstOffset': -420,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/virgin': {
'name': 'America/Virgin',
'description': '',
'location': 'VI',
'offset': -240,
'dstOffset': -240,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Port_of_Spain'
},
'america/whitehorse': {
'name': 'America/Whitehorse',
'description': 'MST - Yukon (east)',
'location': 'CA',
'offset': -420,
'dstOffset': -420,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/winnipeg': {
'name': 'America/Winnipeg',
'description': 'Central - ON (west); Manitoba',
'location': 'CA',
'offset': -360,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/yakutat': {
'name': 'America/Yakutat',
'description': 'Alaska - Yakutat',
'location': 'US',
'offset': -540,
'dstOffset': -480,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'america/yellowknife': {
'name': 'America/Yellowknife',
'description': 'Mountain - NT (central)',
'location': 'CA',
'offset': -420,
'dstOffset': -360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'antarctica/casey': {
'name': 'Antarctica/Casey',
'description': 'Casey',
'location': 'AQ',
'offset': 660,
'dstOffset': 660,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'antarctica/davis': {
'name': 'Antarctica/Davis',
'description': 'Davis',
'location': 'AQ',
'offset': 420,
'dstOffset': 420,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'antarctica/dumontdurville': {
'name': 'Antarctica/DumontDUrville',
'description': 'Dumont-d\'Urville',
'location': 'AQ',
'offset': 600,
'dstOffset': 600,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'antarctica/macquarie': {
'name': 'Antarctica/Macquarie',
'description': 'Macquarie Island',
'location': 'AU',
'offset': 600,
'dstOffset': 660,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'antarctica/mawson': {
'name': 'Antarctica/Mawson',
'description': 'Mawson',
'location': 'AQ',
'offset': 300,
'dstOffset': 300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'antarctica/mcmurdo': {
'name': 'Antarctica/McMurdo',
'description': 'New Zealand time - McMurdo, South Pole',
'location': 'AQ',
'offset': 720,
'dstOffset': 780,
'deprecated': false,
'canonical': false,
'aliasOf': 'Pacific/Auckland'
},
'antarctica/palmer': {
'name': 'Antarctica/Palmer',
'description': 'Palmer',
'location': 'AQ',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'antarctica/rothera': {
'name': 'Antarctica/Rothera',
'description': 'Rothera',
'location': 'AQ',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'antarctica/south_pole': {
'name': 'Antarctica/South_Pole',
'description': '',
'location': 'AQ',
'offset': 720,
'dstOffset': 780,
'deprecated': true,
'canonical': false,
'aliasOf': 'Pacific/Auckland'
},
'antarctica/syowa': {
'name': 'Antarctica/Syowa',
'description': 'Syowa',
'location': 'AQ',
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'antarctica/troll': {
'name': 'Antarctica/Troll',
'description': 'Troll',
'location': 'AQ',
'offset': 0,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'antarctica/vostok': {
'name': 'Antarctica/Vostok',
'description': 'Vostok',
'location': 'AQ',
'offset': 360,
'dstOffset': 360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'arctic/longyearbyen': {
'name': 'Arctic/Longyearbyen',
'description': '',
'location': 'SJ',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': false,
'aliasOf': 'Europe/Oslo'
},
'asia/aden': {
'name': 'Asia/Aden',
'description': '',
'location': 'YE',
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': false,
'aliasOf': 'Asia/Riyadh'
},
'asia/almaty': {
'name': 'Asia/Almaty',
'description': 'Kazakhstan (most areas)',
'location': 'KZ',
'offset': 360,
'dstOffset': 360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/amman': {
'name': 'Asia/Amman',
'description': '',
'location': 'JO',
'offset': 120,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/anadyr': {
'name': 'Asia/Anadyr',
'description': 'MSK+09 - Bering Sea',
'location': 'RU',
'offset': 720,
'dstOffset': 720,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/aqtau': {
'name': 'Asia/Aqtau',
'description': 'Mangghystaū/Mankistau',
'location': 'KZ',
'offset': 300,
'dstOffset': 300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/aqtobe': {
'name': 'Asia/Aqtobe',
'description': 'Aqtöbe/Aktobe',
'location': 'KZ',
'offset': 300,
'dstOffset': 300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/ashgabat': {
'name': 'Asia/Ashgabat',
'description': '',
'location': 'TM',
'offset': 300,
'dstOffset': 300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/ashkhabad': {
'name': 'Asia/Ashkhabad',
'description': '',
'location': 'TM',
'offset': 300,
'dstOffset': 300,
'deprecated': true,
'canonical': false,
'aliasOf': 'Asia/Ashgabat'
},
'asia/atyrau': {
'name': 'Asia/Atyrau',
'description': 'Atyraū/Atirau/Gur\'yev',
'location': 'KZ',
'offset': 300,
'dstOffset': 300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/baghdad': {
'name': 'Asia/Baghdad',
'description': '',
'location': 'IQ',
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/bahrain': {
'name': 'Asia/Bahrain',
'description': '',
'location': 'BH',
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': false,
'aliasOf': 'Asia/Qatar'
},
'asia/baku': {
'name': 'Asia/Baku',
'description': '',
'location': 'AZ',
'offset': 240,
'dstOffset': 240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/bangkok': {
'name': 'Asia/Bangkok',
'description': 'Indochina (most areas)',
'location': 'TH',
'offset': 420,
'dstOffset': 420,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/barnaul': {
'name': 'Asia/Barnaul',
'description': 'MSK+04 - Altai',
'location': 'RU',
'offset': 420,
'dstOffset': 420,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/beirut': {
'name': 'Asia/Beirut',
'description': '',
'location': 'LB',
'offset': 120,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/bishkek': {
'name': 'Asia/Bishkek',
'description': '',
'location': 'KG',
'offset': 360,
'dstOffset': 360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/brunei': {
'name': 'Asia/Brunei',
'description': '',
'location': 'BN',
'offset': 480,
'dstOffset': 480,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/calcutta': {
'name': 'Asia/Calcutta',
'description': '',
'location': 'IN',
'offset': 330,
'dstOffset': 330,
'deprecated': true,
'canonical': false,
'aliasOf': 'Asia/Kolkata'
},
'asia/chita': {
'name': 'Asia/Chita',
'description': 'MSK+06 - Zabaykalsky',
'location': 'RU',
'offset': 540,
'dstOffset': 540,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/choibalsan': {
'name': 'Asia/Choibalsan',
'description': '<NAME>',
'location': 'MN',
'offset': 480,
'dstOffset': 480,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/chongqing': {
'name': 'Asia/Chongqing',
'description': '',
'location': 'CN',
'offset': 480,
'dstOffset': 480,
'deprecated': true,
'canonical': false,
'aliasOf': 'Asia/Shanghai'
},
'asia/chungking': {
'name': 'Asia/Chungking',
'description': '',
'location': 'CN',
'offset': 480,
'dstOffset': 480,
'deprecated': true,
'canonical': false,
'aliasOf': 'Asia/Shanghai'
},
'asia/colombo': {
'name': 'Asia/Colombo',
'description': '',
'location': 'LK',
'offset': 330,
'dstOffset': 330,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/dacca': {
'name': 'Asia/Dacca',
'description': '',
'location': 'BD',
'offset': 360,
'dstOffset': 360,
'deprecated': true,
'canonical': false,
'aliasOf': 'Asia/Dhaka'
},
'asia/damascus': {
'name': 'Asia/Damascus',
'description': '',
'location': 'SY',
'offset': 120,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/dhaka': {
'name': 'Asia/Dhaka',
'description': '',
'location': 'BD',
'offset': 360,
'dstOffset': 360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/dili': {
'name': 'Asia/Dili',
'description': '',
'location': 'TL',
'offset': 540,
'dstOffset': 540,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/dubai': {
'name': 'Asia/Dubai',
'description': '',
'location': 'AE',
'offset': 240,
'dstOffset': 240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/dushanbe': {
'name': 'Asia/Dushanbe',
'description': '',
'location': 'TJ',
'offset': 300,
'dstOffset': 300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/famagusta': {
'name': 'Asia/Famagusta',
'description': 'Northern Cyprus',
'location': 'CY',
'offset': 120,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/gaza': {
'name': 'Asia/Gaza',
'description': 'Gaza Strip',
'location': 'PS',
'offset': 120,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/harbin': {
'name': 'Asia/Harbin',
'description': '',
'location': 'CN',
'offset': 480,
'dstOffset': 480,
'deprecated': true,
'canonical': false,
'aliasOf': 'Asia/Shanghai'
},
'asia/hebron': {
'name': 'Asia/Hebron',
'description': 'West Bank',
'location': 'PS',
'offset': 120,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/ho_chi_minh': {
'name': 'Asia/Ho_Chi_Minh',
'description': 'Vietnam (south)',
'location': 'VN',
'offset': 420,
'dstOffset': 420,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/hong_kong': {
'name': 'Asia/Hong_Kong',
'description': '',
'location': 'HK',
'offset': 480,
'dstOffset': 480,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/hovd': {
'name': 'Asia/Hovd',
'description': 'Bayan-Ölgii, Govi-Altai, Hovd, Uvs, Zavkhan',
'location': 'MN',
'offset': 420,
'dstOffset': 420,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/irkutsk': {
'name': 'Asia/Irkutsk',
'description': 'MSK+05 - Irkutsk, Buryatia',
'location': 'RU',
'offset': 480,
'dstOffset': 480,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/istanbul': {
'name': 'Asia/Istanbul',
'description': '',
'location': 'TR',
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': false,
'aliasOf': 'Europe/Istanbul'
},
'asia/jakarta': {
'name': 'Asia/Jakarta',
'description': 'Java, Sumatra',
'location': 'ID',
'offset': 420,
'dstOffset': 420,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/jayapura': {
'name': 'Asia/Jayapura',
'description': 'New Guinea (West Papua / Irian Jaya); Malukus/Moluccas',
'location': 'ID',
'offset': 540,
'dstOffset': 540,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/jerusalem': {
'name': 'Asia/Jerusalem',
'description': '',
'location': 'IL',
'offset': 120,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/kabul': {
'name': 'Asia/Kabul',
'description': '',
'location': 'AF',
'offset': 270,
'dstOffset': 270,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/kamchatka': {
'name': 'Asia/Kamchatka',
'description': 'MSK+09 - Kamchatka',
'location': 'RU',
'offset': 720,
'dstOffset': 720,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/karachi': {
'name': 'Asia/Karachi',
'description': '',
'location': 'PK',
'offset': 300,
'dstOffset': 300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/kashgar': {
'name': 'Asia/Kashgar',
'description': '',
'location': 'CN',
'offset': 360,
'dstOffset': 360,
'deprecated': true,
'canonical': false,
'aliasOf': 'Asia/Urumqi'
},
'asia/kathmandu': {
'name': 'Asia/Kathmandu',
'description': '',
'location': 'NP',
'offset': 345,
'dstOffset': 345,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/katmandu': {
'name': 'Asia/Katmandu',
'description': '',
'location': 'NP',
'offset': 345,
'dstOffset': 345,
'deprecated': true,
'canonical': false,
'aliasOf': 'Asia/Kathmandu'
},
'asia/khandyga': {
'name': 'Asia/Khandyga',
'description': 'MSK+06 - Tomponsky, Ust-Maysky',
'location': 'RU',
'offset': 540,
'dstOffset': 540,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/kolkata': {
'name': 'Asia/Kolkata',
'description': '',
'location': 'IN',
'offset': 330,
'dstOffset': 330,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/krasnoyarsk': {
'name': 'Asia/Krasnoyarsk',
'description': 'MSK+04 - Krasnoyarsk area',
'location': 'RU',
'offset': 420,
'dstOffset': 420,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/kuala_lumpur': {
'name': 'Asia/Kuala_Lumpur',
'description': 'Malaysia (peninsula)',
'location': 'MY',
'offset': 480,
'dstOffset': 480,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/kuching': {
'name': 'Asia/Kuching',
'description': 'Sabah, Sarawak',
'location': 'MY',
'offset': 480,
'dstOffset': 480,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/kuwait': {
'name': 'Asia/Kuwait',
'description': '',
'location': 'KW',
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': false,
'aliasOf': 'Asia/Riyadh'
},
'asia/macao': {
'name': 'Asia/Macao',
'description': '',
'location': 'MO',
'offset': 480,
'dstOffset': 480,
'deprecated': true,
'canonical': false,
'aliasOf': 'Asia/Macau'
},
'asia/macau': {
'name': 'Asia/Macau',
'description': '',
'location': 'MO',
'offset': 480,
'dstOffset': 480,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/magadan': {
'name': 'Asia/Magadan',
'description': 'MSK+08 - Magadan',
'location': 'RU',
'offset': 660,
'dstOffset': 660,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/makassar': {
'name': 'Asia/Makassar',
'description': 'Borneo (east, south); Sulawesi/Celebes, Bali, <NAME>; Timor (west)',
'location': 'ID',
'offset': 480,
'dstOffset': 480,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/manila': {
'name': 'Asia/Manila',
'description': '',
'location': 'PH',
'offset': 480,
'dstOffset': 480,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/muscat': {
'name': 'Asia/Muscat',
'description': '',
'location': 'OM',
'offset': 240,
'dstOffset': 240,
'deprecated': false,
'canonical': false,
'aliasOf': 'Asia/Dubai'
},
'asia/nicosia': {
'name': 'Asia/Nicosia',
'description': 'Cyprus (most areas)',
'location': 'CY',
'offset': 120,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/novokuznetsk': {
'name': 'Asia/Novokuznetsk',
'description': 'MSK+04 - Kemerovo',
'location': 'RU',
'offset': 420,
'dstOffset': 420,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/novosibirsk': {
'name': 'Asia/Novosibirsk',
'description': 'MSK+04 - Novosibirsk',
'location': 'RU',
'offset': 420,
'dstOffset': 420,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/omsk': {
'name': 'Asia/Omsk',
'description': 'MSK+03 - Omsk',
'location': 'RU',
'offset': 360,
'dstOffset': 360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/oral': {
'name': 'Asia/Oral',
'description': 'West Kazakhstan',
'location': 'KZ',
'offset': 300,
'dstOffset': 300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/phnom_penh': {
'name': 'Asia/Phnom_Penh',
'description': '',
'location': 'KH',
'offset': 420,
'dstOffset': 420,
'deprecated': false,
'canonical': false,
'aliasOf': 'Asia/Bangkok'
},
'asia/pontianak': {
'name': 'Asia/Pontianak',
'description': 'Borneo (west, central)',
'location': 'ID',
'offset': 420,
'dstOffset': 420,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/pyongyang': {
'name': 'Asia/Pyongyang',
'description': '',
'location': 'KP',
'offset': 540,
'dstOffset': 540,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/qatar': {
'name': 'Asia/Qatar',
'description': '',
'location': 'QA',
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/qostanay': {
'name': 'Asia/Qostanay',
'description': 'Qostanay/Kostanay/Kustanay',
'location': 'KZ',
'offset': 360,
'dstOffset': 360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/qyzylorda': {
'name': 'Asia/Qyzylorda',
'description': 'Qyzylorda/Kyzylorda/Kzyl-Orda',
'location': 'KZ',
'offset': 300,
'dstOffset': 300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/rangoon': {
'name': 'Asia/Rangoon',
'description': '',
'location': 'MM',
'offset': 390,
'dstOffset': 390,
'deprecated': true,
'canonical': false,
'aliasOf': 'Asia/Yangon'
},
'asia/riyadh': {
'name': 'Asia/Riyadh',
'description': '',
'location': 'SA',
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/saigon': {
'name': 'Asia/Saigon',
'description': '',
'location': 'VN',
'offset': 420,
'dstOffset': 420,
'deprecated': true,
'canonical': false,
'aliasOf': 'Asia/Ho_Chi_Minh'
},
'asia/sakhalin': {
'name': 'Asia/Sakhalin',
'description': 'MSK+08 - Sakhalin Island',
'location': 'RU',
'offset': 660,
'dstOffset': 660,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/samarkand': {
'name': 'Asia/Samarkand',
'description': 'Uzbekistan (west)',
'location': 'UZ',
'offset': 300,
'dstOffset': 300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/seoul': {
'name': 'Asia/Seoul',
'description': '',
'location': 'KR',
'offset': 540,
'dstOffset': 540,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/shanghai': {
'name': 'Asia/Shanghai',
'description': 'Beijing Time',
'location': 'CN',
'offset': 480,
'dstOffset': 480,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/singapore': {
'name': 'Asia/Singapore',
'description': '',
'location': 'SG',
'offset': 480,
'dstOffset': 480,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/srednekolymsk': {
'name': 'Asia/Srednekolymsk',
'description': 'MSK+08 - Sakha (E); North Kuril Is',
'location': 'RU',
'offset': 660,
'dstOffset': 660,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/taipei': {
'name': 'Asia/Taipei',
'description': '',
'location': 'TW',
'offset': 480,
'dstOffset': 480,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/tashkent': {
'name': 'Asia/Tashkent',
'description': 'Uzbekistan (east)',
'location': 'UZ',
'offset': 300,
'dstOffset': 300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/tbilisi': {
'name': 'Asia/Tbilisi',
'description': '',
'location': 'GE',
'offset': 240,
'dstOffset': 240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/tehran': {
'name': 'Asia/Tehran',
'description': '',
'location': 'IR',
'offset': 210,
'dstOffset': 270,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/tel_aviv': {
'name': 'Asia/Tel_Aviv',
'description': '',
'location': 'IL',
'offset': 120,
'dstOffset': 180,
'deprecated': true,
'canonical': false,
'aliasOf': 'Asia/Jerusalem'
},
'asia/thimbu': {
'name': 'Asia/Thimbu',
'description': '',
'location': 'BT',
'offset': 360,
'dstOffset': 360,
'deprecated': true,
'canonical': false,
'aliasOf': 'Asia/Thimphu'
},
'asia/thimphu': {
'name': 'Asia/Thimphu',
'description': '',
'location': 'BT',
'offset': 360,
'dstOffset': 360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/tokyo': {
'name': 'Asia/Tokyo',
'description': '',
'location': 'JP',
'offset': 540,
'dstOffset': 540,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/tomsk': {
'name': 'Asia/Tomsk',
'description': 'MSK+04 - Tomsk',
'location': 'RU',
'offset': 420,
'dstOffset': 420,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/ujung_pandang': {
'name': 'Asia/Ujung_Pandang',
'description': '',
'location': 'ID',
'offset': 480,
'dstOffset': 480,
'deprecated': true,
'canonical': false,
'aliasOf': 'Asia/Makassar'
},
'asia/ulaanbaatar': {
'name': 'Asia/Ulaanbaatar',
'description': 'Mongolia (most areas)',
'location': 'MN',
'offset': 480,
'dstOffset': 480,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/ulan_bator': {
'name': 'Asia/Ulan_Bator',
'description': '',
'location': 'MN',
'offset': 480,
'dstOffset': 480,
'deprecated': true,
'canonical': false,
'aliasOf': 'Asia/Ulaanbaatar'
},
'asia/urumqi': {
'name': 'Asia/Urumqi',
'description': 'Xinjiang Time',
'location': 'CN',
'offset': 360,
'dstOffset': 360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/ust-nera': {
'name': 'Asia/Ust-Nera',
'description': 'MSK+07 - Oymyakonsky',
'location': 'RU',
'offset': 600,
'dstOffset': 600,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/vientiane': {
'name': 'Asia/Vientiane',
'description': '',
'location': 'LA',
'offset': 420,
'dstOffset': 420,
'deprecated': false,
'canonical': false,
'aliasOf': 'Asia/Bangkok'
},
'asia/vladivostok': {
'name': 'Asia/Vladivostok',
'description': 'MSK+07 - Amur River',
'location': 'RU',
'offset': 600,
'dstOffset': 600,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/yakutsk': {
'name': 'Asia/Yakutsk',
'description': 'MSK+06 - Lena River',
'location': 'RU',
'offset': 540,
'dstOffset': 540,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/yangon': {
'name': 'Asia/Yangon',
'description': '',
'location': 'MM',
'offset': 390,
'dstOffset': 390,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/yekaterinburg': {
'name': 'Asia/Yekaterinburg',
'description': 'MSK+02 - Urals',
'location': 'RU',
'offset': 300,
'dstOffset': 300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'asia/yerevan': {
'name': 'Asia/Yerevan',
'description': '',
'location': 'AM',
'offset': 240,
'dstOffset': 240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'atlantic/azores': {
'name': 'Atlantic/Azores',
'description': 'Azores',
'location': 'PT',
'offset': -60,
'dstOffset': 0,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'atlantic/bermuda': {
'name': 'Atlantic/Bermuda',
'description': '',
'location': 'BM',
'offset': -240,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'atlantic/canary': {
'name': 'Atlantic/Canary',
'description': 'Canary Islands',
'location': 'ES',
'offset': 0,
'dstOffset': 60,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'atlantic/cape_verde': {
'name': 'Atlantic/Cape_Verde',
'description': '',
'location': 'CV',
'offset': -60,
'dstOffset': -60,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'atlantic/faeroe': {
'name': 'Atlantic/Faeroe',
'description': '',
'location': 'FO',
'offset': 0,
'dstOffset': 60,
'deprecated': true,
'canonical': false,
'aliasOf': 'Atlantic/Faroe'
},
'atlantic/faroe': {
'name': 'Atlantic/Faroe',
'description': '',
'location': 'FO',
'offset': 0,
'dstOffset': 60,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'atlantic/jan_mayen': {
'name': 'Atlantic/Jan_Mayen',
'description': '',
'location': 'SJ',
'offset': 60,
'dstOffset': 120,
'deprecated': true,
'canonical': false,
'aliasOf': 'Europe/Oslo'
},
'atlantic/madeira': {
'name': 'Atlantic/Madeira',
'description': 'Madeira Islands',
'location': 'PT',
'offset': 0,
'dstOffset': 60,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'atlantic/reykjavik': {
'name': 'Atlantic/Reykjavik',
'description': '',
'location': 'IS',
'offset': 0,
'dstOffset': 0,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'atlantic/south_georgia': {
'name': 'Atlantic/South_Georgia',
'description': '',
'location': 'GS',
'offset': -120,
'dstOffset': -120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'atlantic/st_helena': {
'name': 'Atlantic/St_Helena',
'description': '',
'location': 'SH',
'offset': 0,
'dstOffset': 0,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Abidjan'
},
'atlantic/stanley': {
'name': 'Atlantic/Stanley',
'description': '',
'location': 'FK',
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'australia/act': {
'name': 'Australia/ACT',
'description': '',
'location': 'AU',
'offset': 600,
'dstOffset': 660,
'deprecated': true,
'canonical': false,
'aliasOf': 'Australia/Sydney'
},
'australia/adelaide': {
'name': 'Australia/Adelaide',
'description': 'South Australia',
'location': 'AU',
'offset': 570,
'dstOffset': 630,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'australia/brisbane': {
'name': 'Australia/Brisbane',
'description': 'Queensland (most areas)',
'location': 'AU',
'offset': 600,
'dstOffset': 600,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'australia/broken_hill': {
'name': 'Australia/Broken_Hill',
'description': 'New South Wales (Yancowinna)',
'location': 'AU',
'offset': 570,
'dstOffset': 630,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'australia/canberra': {
'name': 'Australia/Canberra',
'description': '',
'location': 'AU',
'offset': 600,
'dstOffset': 660,
'deprecated': true,
'canonical': false,
'aliasOf': 'Australia/Sydney'
},
'australia/currie': {
'name': 'Australia/Currie',
'description': '',
'location': 'AU',
'offset': 600,
'dstOffset': 660,
'deprecated': true,
'canonical': false,
'aliasOf': 'Australia/Hobart'
},
'australia/darwin': {
'name': 'Australia/Darwin',
'description': 'Northern Territory',
'location': 'AU',
'offset': 570,
'dstOffset': 570,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'australia/eucla': {
'name': 'Australia/Eucla',
'description': 'Western Australia (Eucla)',
'location': 'AU',
'offset': 525,
'dstOffset': 525,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'australia/hobart': {
'name': 'Australia/Hobart',
'description': 'Tasmania',
'location': 'AU',
'offset': 600,
'dstOffset': 660,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'australia/lhi': {
'name': 'Australia/LHI',
'description': '',
'location': 'AU',
'offset': 630,
'dstOffset': 660,
'deprecated': true,
'canonical': false,
'aliasOf': 'Australia/Lord_Howe'
},
'australia/lindeman': {
'name': 'Australia/Lindeman',
'description': 'Queensland (Whitsunday Islands)',
'location': 'AU',
'offset': 600,
'dstOffset': 600,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'australia/lord_howe': {
'name': 'Australia/Lord_Howe',
'description': 'Lord Howe Island',
'location': 'AU',
'offset': 630,
'dstOffset': 660,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'australia/melbourne': {
'name': 'Australia/Melbourne',
'description': 'Victoria',
'location': 'AU',
'offset': 600,
'dstOffset': 660,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'australia/north': {
'name': 'Australia/North',
'description': '',
'location': 'AU',
'offset': 570,
'dstOffset': 570,
'deprecated': true,
'canonical': false,
'aliasOf': 'Australia/Darwin'
},
'australia/nsw': {
'name': 'Australia/NSW',
'description': '',
'location': 'AU',
'offset': 600,
'dstOffset': 660,
'deprecated': true,
'canonical': false,
'aliasOf': 'Australia/Sydney'
},
'australia/perth': {
'name': 'Australia/Perth',
'description': 'Western Australia (most areas)',
'location': 'AU',
'offset': 480,
'dstOffset': 480,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'australia/queensland': {
'name': 'Australia/Queensland',
'description': '',
'location': 'AU',
'offset': 600,
'dstOffset': 600,
'deprecated': true,
'canonical': false,
'aliasOf': 'Australia/Brisbane'
},
'australia/south': {
'name': 'Australia/South',
'description': '',
'location': 'AU',
'offset': 570,
'dstOffset': 630,
'deprecated': true,
'canonical': false,
'aliasOf': 'Australia/Adelaide'
},
'australia/sydney': {
'name': 'Australia/Sydney',
'description': 'New South Wales (most areas)',
'location': 'AU',
'offset': 600,
'dstOffset': 660,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'australia/tasmania': {
'name': 'Australia/Tasmania',
'description': '',
'location': 'AU',
'offset': 600,
'dstOffset': 660,
'deprecated': true,
'canonical': false,
'aliasOf': 'Australia/Hobart'
},
'australia/victoria': {
'name': 'Australia/Victoria',
'description': '',
'location': 'AU',
'offset': 600,
'dstOffset': 660,
'deprecated': true,
'canonical': false,
'aliasOf': 'Australia/Melbourne'
},
'australia/west': {
'name': 'Australia/West',
'description': '',
'location': 'AU',
'offset': 480,
'dstOffset': 480,
'deprecated': true,
'canonical': false,
'aliasOf': 'Australia/Perth'
},
'australia/yancowinna': {
'name': 'Australia/Yancowinna',
'description': '',
'location': 'AU',
'offset': 570,
'dstOffset': 630,
'deprecated': true,
'canonical': false,
'aliasOf': 'Australia/Broken_Hill'
},
'brazil/acre': {
'name': 'Brazil/Acre',
'description': '',
'location': 'BR',
'offset': -300,
'dstOffset': -300,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Rio_Branco'
},
'brazil/denoronha': {
'name': 'Brazil/DeNoronha',
'description': '',
'location': 'BR',
'offset': -120,
'dstOffset': -120,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Noronha'
},
'brazil/east': {
'name': 'Brazil/East',
'description': '',
'location': 'BR',
'offset': -180,
'dstOffset': -180,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Sao_Paulo'
},
'brazil/west': {
'name': 'Brazil/West',
'description': '',
'location': 'BR',
'offset': -240,
'dstOffset': -240,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Manaus'
},
'canada/atlantic': {
'name': 'Canada/Atlantic',
'description': '',
'location': 'CA',
'offset': -240,
'dstOffset': -180,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Halifax'
},
'canada/central': {
'name': 'Canada/Central',
'description': '',
'location': 'CA',
'offset': -360,
'dstOffset': -300,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Winnipeg'
},
'canada/eastern': {
'name': 'Canada/Eastern',
'description': '',
'location': 'CA',
'offset': -300,
'dstOffset': -240,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Toronto'
},
'canada/mountain': {
'name': 'Canada/Mountain',
'description': '',
'location': 'CA',
'offset': -420,
'dstOffset': -360,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Edmonton'
},
'canada/newfoundland': {
'name': 'Canada/Newfoundland',
'description': '',
'location': 'CA',
'offset': -210,
'dstOffset': -150,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/St_Johns'
},
'canada/pacific': {
'name': 'Canada/Pacific',
'description': '',
'location': 'CA',
'offset': -480,
'dstOffset': -420,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Vancouver'
},
'canada/saskatchewan': {
'name': 'Canada/Saskatchewan',
'description': '',
'location': 'CA',
'offset': -360,
'dstOffset': -360,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Regina'
},
'canada/yukon': {
'name': 'Canada/Yukon',
'description': '',
'location': 'CA',
'offset': -420,
'dstOffset': -420,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Whitehorse'
},
'cet': {
'name': 'CET',
'description': '',
'location': null,
'offset': 60,
'dstOffset': 120,
'deprecated': true,
'canonical': false,
'aliasOf': null
},
'chile/continental': {
'name': 'Chile/Continental',
'description': '',
'location': 'CL',
'offset': -240,
'dstOffset': -180,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Santiago'
},
'chile/easterisland': {
'name': 'Chile/EasterIsland',
'description': '',
'location': 'CL',
'offset': -360,
'dstOffset': -300,
'deprecated': true,
'canonical': false,
'aliasOf': 'Pacific/Easter'
},
'cst6cdt': {
'name': 'CST6CDT',
'description': '',
'location': null,
'offset': -360,
'dstOffset': -300,
'deprecated': true,
'canonical': false,
'aliasOf': null
},
'cuba': {
'name': 'Cuba',
'description': '',
'location': 'CU',
'offset': -300,
'dstOffset': -240,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Havana'
},
'eet': {
'name': 'EET',
'description': '',
'location': null,
'offset': 120,
'dstOffset': 180,
'deprecated': true,
'canonical': false,
'aliasOf': null
},
'egypt': {
'name': 'Egypt',
'description': '',
'location': 'EG',
'offset': 120,
'dstOffset': 120,
'deprecated': true,
'canonical': false,
'aliasOf': 'Africa/Cairo'
},
'eire': {
'name': 'Eire',
'description': '',
'location': 'IE',
'offset': 60,
'dstOffset': 0,
'deprecated': true,
'canonical': false,
'aliasOf': 'Europe/Dublin'
},
'est': {
'name': 'EST',
'description': '',
'location': null,
'offset': -300,
'dstOffset': -300,
'deprecated': true,
'canonical': false,
'aliasOf': null
},
'est5edt': {
'name': 'EST5EDT',
'description': '',
'location': null,
'offset': -300,
'dstOffset': -240,
'deprecated': true,
'canonical': false,
'aliasOf': null
},
'etc/gmt': {
'name': 'Etc/GMT',
'description': '',
'location': null,
'offset': 0,
'dstOffset': 0,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt+0': {
'name': 'Etc/GMT+0',
'description': '',
'location': null,
'offset': 0,
'dstOffset': 0,
'deprecated': false,
'canonical': false,
'aliasOf': 'Etc/GMT'
},
'etc/gmt+1': {
'name': 'Etc/GMT+1',
'description': '',
'location': null,
'offset': -60,
'dstOffset': -60,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt+10': {
'name': 'Etc/GMT+10',
'description': '',
'location': null,
'offset': -600,
'dstOffset': -600,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt+11': {
'name': 'Etc/GMT+11',
'description': '',
'location': null,
'offset': -660,
'dstOffset': -660,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt+12': {
'name': 'Etc/GMT+12',
'description': '',
'location': null,
'offset': -720,
'dstOffset': -720,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt+2': {
'name': 'Etc/GMT+2',
'description': '',
'location': null,
'offset': -120,
'dstOffset': -120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt+3': {
'name': 'Etc/GMT+3',
'description': '',
'location': null,
'offset': -180,
'dstOffset': -180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt+4': {
'name': 'Etc/GMT+4',
'description': '',
'location': null,
'offset': -240,
'dstOffset': -240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt+5': {
'name': 'Etc/GMT+5',
'description': '',
'location': null,
'offset': -300,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt+6': {
'name': 'Etc/GMT+6',
'description': '',
'location': null,
'offset': -360,
'dstOffset': -360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt+7': {
'name': 'Etc/GMT+7',
'description': '',
'location': null,
'offset': -420,
'dstOffset': -420,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt+8': {
'name': 'Etc/GMT+8',
'description': '',
'location': null,
'offset': -480,
'dstOffset': -480,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt+9': {
'name': 'Etc/GMT+9',
'description': '',
'location': null,
'offset': -540,
'dstOffset': -540,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt-0': {
'name': 'Etc/GMT-0',
'description': '',
'location': null,
'offset': 0,
'dstOffset': 0,
'deprecated': false,
'canonical': false,
'aliasOf': 'Etc/GMT'
},
'etc/gmt-1': {
'name': 'Etc/GMT-1',
'description': '',
'location': null,
'offset': 60,
'dstOffset': 60,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt-10': {
'name': 'Etc/GMT-10',
'description': '',
'location': null,
'offset': 600,
'dstOffset': 600,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt-11': {
'name': 'Etc/GMT-11',
'description': '',
'location': null,
'offset': 660,
'dstOffset': 660,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt-12': {
'name': 'Etc/GMT-12',
'description': '',
'location': null,
'offset': 720,
'dstOffset': 720,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt-13': {
'name': 'Etc/GMT-13',
'description': '',
'location': null,
'offset': 780,
'dstOffset': 780,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt-14': {
'name': 'Etc/GMT-14',
'description': '',
'location': null,
'offset': 840,
'dstOffset': 840,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt-2': {
'name': 'Etc/GMT-2',
'description': '',
'location': null,
'offset': 120,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt-3': {
'name': 'Etc/GMT-3',
'description': '',
'location': null,
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt-4': {
'name': 'Etc/GMT-4',
'description': '',
'location': null,
'offset': 240,
'dstOffset': 240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt-5': {
'name': 'Etc/GMT-5',
'description': '',
'location': null,
'offset': 300,
'dstOffset': 300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt-6': {
'name': 'Etc/GMT-6',
'description': '',
'location': null,
'offset': 360,
'dstOffset': 360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt-7': {
'name': 'Etc/GMT-7',
'description': '',
'location': null,
'offset': 420,
'dstOffset': 420,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt-8': {
'name': 'Etc/GMT-8',
'description': '',
'location': null,
'offset': 480,
'dstOffset': 480,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt-9': {
'name': 'Etc/GMT-9',
'description': '',
'location': null,
'offset': 540,
'dstOffset': 540,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/gmt0': {
'name': 'Etc/GMT0',
'description': '',
'location': null,
'offset': 0,
'dstOffset': 0,
'deprecated': false,
'canonical': false,
'aliasOf': 'Etc/GMT'
},
'etc/greenwich': {
'name': 'Etc/Greenwich',
'description': '',
'location': null,
'offset': 0,
'dstOffset': 0,
'deprecated': true,
'canonical': false,
'aliasOf': 'Etc/GMT'
},
'etc/uct': {
'name': 'Etc/UCT',
'description': '',
'location': null,
'offset': 0,
'dstOffset': 0,
'deprecated': true,
'canonical': false,
'aliasOf': 'Etc/UTC'
},
'etc/universal': {
'name': 'Etc/Universal',
'description': '',
'location': null,
'offset': 0,
'dstOffset': 0,
'deprecated': true,
'canonical': false,
'aliasOf': 'Etc/UTC'
},
'etc/utc': {
'name': 'Etc/UTC',
'description': '',
'location': null,
'offset': 0,
'dstOffset': 0,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'etc/zulu': {
'name': 'Etc/Zulu',
'description': '',
'location': null,
'offset': 0,
'dstOffset': 0,
'deprecated': true,
'canonical': false,
'aliasOf': 'Etc/UTC'
},
'europe/amsterdam': {
'name': 'Europe/Amsterdam',
'description': '',
'location': 'NL',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/andorra': {
'name': 'Europe/Andorra',
'description': '',
'location': 'AD',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/astrakhan': {
'name': 'Europe/Astrakhan',
'description': 'MSK+01 - Astrakhan',
'location': 'RU',
'offset': 240,
'dstOffset': 240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/athens': {
'name': 'Europe/Athens',
'description': '',
'location': 'GR',
'offset': 120,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/belfast': {
'name': 'Europe/Belfast',
'description': '',
'location': 'GB',
'offset': 0,
'dstOffset': 60,
'deprecated': true,
'canonical': false,
'aliasOf': 'Europe/London'
},
'europe/belgrade': {
'name': 'Europe/Belgrade',
'description': '',
'location': 'RS',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/berlin': {
'name': 'Europe/Berlin',
'description': 'Germany (most areas)',
'location': 'DE',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/bratislava': {
'name': 'Europe/Bratislava',
'description': '',
'location': 'SK',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': false,
'aliasOf': 'Europe/Prague'
},
'europe/brussels': {
'name': 'Europe/Brussels',
'description': '',
'location': 'BE',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/bucharest': {
'name': 'Europe/Bucharest',
'description': '',
'location': 'RO',
'offset': 120,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/budapest': {
'name': 'Europe/Budapest',
'description': '',
'location': 'HU',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/busingen': {
'name': 'Europe/Busingen',
'description': 'Busingen',
'location': 'DE',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': false,
'aliasOf': 'Europe/Zurich'
},
'europe/chisinau': {
'name': 'Europe/Chisinau',
'description': '',
'location': 'MD',
'offset': 120,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/copenhagen': {
'name': 'Europe/Copenhagen',
'description': '',
'location': 'DK',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/dublin': {
'name': 'Europe/Dublin',
'description': '',
'location': 'IE',
'offset': 60,
'dstOffset': 0,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/gibraltar': {
'name': 'Europe/Gibraltar',
'description': '',
'location': 'GI',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/guernsey': {
'name': 'Europe/Guernsey',
'description': '',
'location': 'GG',
'offset': 0,
'dstOffset': 60,
'deprecated': false,
'canonical': false,
'aliasOf': 'Europe/London'
},
'europe/helsinki': {
'name': 'Europe/Helsinki',
'description': '',
'location': 'FI',
'offset': 120,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/isle_of_man': {
'name': 'Europe/Isle_of_Man',
'description': '',
'location': 'IM',
'offset': 0,
'dstOffset': 60,
'deprecated': false,
'canonical': false,
'aliasOf': 'Europe/London'
},
'europe/istanbul': {
'name': 'Europe/Istanbul',
'description': '',
'location': 'TR',
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/jersey': {
'name': 'Europe/Jersey',
'description': '',
'location': 'JE',
'offset': 0,
'dstOffset': 60,
'deprecated': false,
'canonical': false,
'aliasOf': 'Europe/London'
},
'europe/kaliningrad': {
'name': 'Europe/Kaliningrad',
'description': 'MSK-01 - Kaliningrad',
'location': 'RU',
'offset': 120,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/kiev': {
'name': 'Europe/Kiev',
'description': 'Ukraine (most areas)',
'location': 'UA',
'offset': 120,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/kirov': {
'name': 'Europe/Kirov',
'description': 'MSK+00 - Kirov',
'location': 'RU',
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/lisbon': {
'name': 'Europe/Lisbon',
'description': 'Portugal (mainland)',
'location': 'PT',
'offset': 0,
'dstOffset': 60,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/ljubljana': {
'name': 'Europe/Ljubljana',
'description': '',
'location': 'SI',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': false,
'aliasOf': 'Europe/Belgrade'
},
'europe/london': {
'name': 'Europe/London',
'description': '',
'location': 'GB',
'offset': 0,
'dstOffset': 60,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/luxembourg': {
'name': 'Europe/Luxembourg',
'description': '',
'location': 'LU',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/madrid': {
'name': 'Europe/Madrid',
'description': 'Spain (mainland)',
'location': 'ES',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/malta': {
'name': 'Europe/Malta',
'description': '',
'location': 'MT',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/mariehamn': {
'name': 'Europe/Mariehamn',
'description': '',
'location': 'AX',
'offset': 120,
'dstOffset': 180,
'deprecated': false,
'canonical': false,
'aliasOf': 'Europe/Helsinki'
},
'europe/minsk': {
'name': 'Europe/Minsk',
'description': '',
'location': 'BY',
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/monaco': {
'name': 'Europe/Monaco',
'description': '',
'location': 'MC',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/moscow': {
'name': 'Europe/Moscow',
'description': 'MSK+00 - Moscow area',
'location': 'RU',
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/nicosia': {
'name': 'Europe/Nicosia',
'description': '',
'location': 'CY',
'offset': 120,
'dstOffset': 180,
'deprecated': false,
'canonical': false,
'aliasOf': 'Asia/Nicosia'
},
'europe/oslo': {
'name': 'Europe/Oslo',
'description': '',
'location': 'NO',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/paris': {
'name': 'Europe/Paris',
'description': '',
'location': 'FR',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/podgorica': {
'name': 'Europe/Podgorica',
'description': '',
'location': 'ME',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': false,
'aliasOf': 'Europe/Belgrade'
},
'europe/prague': {
'name': 'Europe/Prague',
'description': '',
'location': 'CZ',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/riga': {
'name': 'Europe/Riga',
'description': '',
'location': 'LV',
'offset': 120,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/rome': {
'name': 'Europe/Rome',
'description': '',
'location': 'IT',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/samara': {
'name': 'Europe/Samara',
'description': 'MSK+01 - Samara, Udmurtia',
'location': 'RU',
'offset': 240,
'dstOffset': 240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/san_marino': {
'name': 'Europe/San_Marino',
'description': '',
'location': 'SM',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': false,
'aliasOf': 'Europe/Rome'
},
'europe/sarajevo': {
'name': 'Europe/Sarajevo',
'description': '',
'location': 'BA',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': false,
'aliasOf': 'Europe/Belgrade'
},
'europe/saratov': {
'name': 'Europe/Saratov',
'description': 'MSK+01 - Saratov',
'location': 'RU',
'offset': 240,
'dstOffset': 240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/simferopol': {
'name': 'Europe/Simferopol',
'description': 'Crimea',
'location': 'UA',
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/skopje': {
'name': 'Europe/Skopje',
'description': '',
'location': 'MK',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': false,
'aliasOf': 'Europe/Belgrade'
},
'europe/sofia': {
'name': 'Europe/Sofia',
'description': '',
'location': 'BG',
'offset': 120,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/stockholm': {
'name': 'Europe/Stockholm',
'description': '',
'location': 'SE',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/tallinn': {
'name': 'Europe/Tallinn',
'description': '',
'location': 'EE',
'offset': 120,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/tirane': {
'name': 'Europe/Tirane',
'description': '',
'location': 'AL',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/tiraspol': {
'name': 'Europe/Tiraspol',
'description': '',
'location': 'MD',
'offset': 120,
'dstOffset': 180,
'deprecated': true,
'canonical': false,
'aliasOf': 'Europe/Chisinau'
},
'europe/ulyanovsk': {
'name': 'Europe/Ulyanovsk',
'description': 'MSK+01 - Ulyanovsk',
'location': 'RU',
'offset': 240,
'dstOffset': 240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/uzhgorod': {
'name': 'Europe/Uzhgorod',
'description': 'Transcarpathia',
'location': 'UA',
'offset': 120,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/vaduz': {
'name': 'Europe/Vaduz',
'description': '',
'location': 'LI',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': false,
'aliasOf': 'Europe/Zurich'
},
'europe/vatican': {
'name': 'Europe/Vatican',
'description': '',
'location': 'VA',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': false,
'aliasOf': 'Europe/Rome'
},
'europe/vienna': {
'name': 'Europe/Vienna',
'description': '',
'location': 'AT',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/vilnius': {
'name': 'Europe/Vilnius',
'description': '',
'location': 'LT',
'offset': 120,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/volgograd': {
'name': 'Europe/Volgograd',
'description': 'MSK+00 - Volgograd',
'location': 'RU',
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/warsaw': {
'name': 'Europe/Warsaw',
'description': '',
'location': 'PL',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/zagreb': {
'name': 'Europe/Zagreb',
'description': '',
'location': 'HR',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': false,
'aliasOf': 'Europe/Belgrade'
},
'europe/zaporozhye': {
'name': 'Europe/Zaporozhye',
'description': 'Zaporozhye and east Lugansk',
'location': 'UA',
'offset': 120,
'dstOffset': 180,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'europe/zurich': {
'name': 'Europe/Zurich',
'description': 'Swiss time',
'location': 'CH',
'offset': 60,
'dstOffset': 120,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'factory': {
'name': 'Factory',
'description': '',
'location': null,
'offset': 0,
'dstOffset': 0,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'gb': {
'name': 'GB',
'description': '',
'location': 'GB',
'offset': 0,
'dstOffset': 60,
'deprecated': true,
'canonical': false,
'aliasOf': 'Europe/London'
},
'gb-eire': {
'name': 'GB-Eire',
'description': '',
'location': 'GB',
'offset': 0,
'dstOffset': 60,
'deprecated': true,
'canonical': false,
'aliasOf': 'Europe/London'
},
'gmt': {
'name': 'GMT',
'description': '',
'location': null,
'offset': 0,
'dstOffset': 0,
'deprecated': false,
'canonical': false,
'aliasOf': 'Etc/GMT'
},
'gmt+0': {
'name': 'GMT+0',
'description': '',
'location': null,
'offset': 0,
'dstOffset': 0,
'deprecated': true,
'canonical': false,
'aliasOf': 'Etc/GMT'
},
'gmt-0': {
'name': 'GMT-0',
'description': '',
'location': null,
'offset': 0,
'dstOffset': 0,
'deprecated': true,
'canonical': false,
'aliasOf': 'Etc/GMT'
},
'gmt0': {
'name': 'GMT0',
'description': '',
'location': null,
'offset': 0,
'dstOffset': 0,
'deprecated': true,
'canonical': false,
'aliasOf': 'Etc/GMT'
},
'greenwich': {
'name': 'Greenwich',
'description': '',
'location': null,
'offset': 0,
'dstOffset': 0,
'deprecated': true,
'canonical': false,
'aliasOf': 'Etc/GMT'
},
'hongkong': {
'name': 'Hongkong',
'description': '',
'location': 'HK',
'offset': 480,
'dstOffset': 480,
'deprecated': true,
'canonical': false,
'aliasOf': 'Asia/Hong_Kong'
},
'hst': {
'name': 'HST',
'description': '',
'location': null,
'offset': -600,
'dstOffset': -600,
'deprecated': true,
'canonical': false,
'aliasOf': null
},
'iceland': {
'name': 'Iceland',
'description': '',
'location': 'IS',
'offset': 0,
'dstOffset': 0,
'deprecated': true,
'canonical': false,
'aliasOf': 'Atlantic/Reykjavik'
},
'indian/antananarivo': {
'name': 'Indian/Antananarivo',
'description': '',
'location': 'MG',
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Nairobi'
},
'indian/chagos': {
'name': 'Indian/Chagos',
'description': '',
'location': 'IO',
'offset': 360,
'dstOffset': 360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'indian/christmas': {
'name': 'Indian/Christmas',
'description': '',
'location': 'CX',
'offset': 420,
'dstOffset': 420,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'indian/cocos': {
'name': 'Indian/Cocos',
'description': '',
'location': 'CC',
'offset': 390,
'dstOffset': 390,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'indian/comoro': {
'name': 'Indian/Comoro',
'description': '',
'location': 'KM',
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Nairobi'
},
'indian/kerguelen': {
'name': 'Indian/Kerguelen',
'description': 'Kerguelen, St Paul Island, Amsterdam Island',
'location': 'TF',
'offset': 300,
'dstOffset': 300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'indian/mahe': {
'name': 'Indian/Mahe',
'description': '',
'location': 'SC',
'offset': 240,
'dstOffset': 240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'indian/maldives': {
'name': 'Indian/Maldives',
'description': '',
'location': 'MV',
'offset': 300,
'dstOffset': 300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'indian/mauritius': {
'name': 'Indian/Mauritius',
'description': '',
'location': 'MU',
'offset': 240,
'dstOffset': 240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'indian/mayotte': {
'name': 'Indian/Mayotte',
'description': '',
'location': 'YT',
'offset': 180,
'dstOffset': 180,
'deprecated': false,
'canonical': false,
'aliasOf': 'Africa/Nairobi'
},
'indian/reunion': {
'name': 'Indian/Reunion',
'description': 'Réunion, Crozet, Scattered Islands',
'location': 'RE',
'offset': 240,
'dstOffset': 240,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'iran': {
'name': 'Iran',
'description': '',
'location': 'IR',
'offset': 210,
'dstOffset': 270,
'deprecated': true,
'canonical': false,
'aliasOf': 'Asia/Tehran'
},
'israel': {
'name': 'Israel',
'description': '',
'location': 'IL',
'offset': 120,
'dstOffset': 180,
'deprecated': true,
'canonical': false,
'aliasOf': 'Asia/Jerusalem'
},
'jamaica': {
'name': 'Jamaica',
'description': '',
'location': 'JM',
'offset': -300,
'dstOffset': -300,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Jamaica'
},
'japan': {
'name': 'Japan',
'description': '',
'location': 'JP',
'offset': 540,
'dstOffset': 540,
'deprecated': true,
'canonical': false,
'aliasOf': 'Asia/Tokyo'
},
'kwajalein': {
'name': 'Kwajalein',
'description': '',
'location': 'MH',
'offset': 720,
'dstOffset': 720,
'deprecated': true,
'canonical': false,
'aliasOf': 'Pacific/Kwajalein'
},
'libya': {
'name': 'Libya',
'description': '',
'location': 'LY',
'offset': 120,
'dstOffset': 120,
'deprecated': true,
'canonical': false,
'aliasOf': 'Africa/Tripoli'
},
'met': {
'name': 'MET',
'description': '',
'location': null,
'offset': 60,
'dstOffset': 120,
'deprecated': true,
'canonical': false,
'aliasOf': null
},
'mexico/bajanorte': {
'name': 'Mexico/BajaNorte',
'description': '',
'location': 'MX',
'offset': -480,
'dstOffset': -420,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Tijuana'
},
'mexico/bajasur': {
'name': 'Mexico/BajaSur',
'description': '',
'location': 'MX',
'offset': -420,
'dstOffset': -360,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Mazatlan'
},
'mexico/general': {
'name': 'Mexico/General',
'description': '',
'location': 'MX',
'offset': -360,
'dstOffset': -300,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Mexico_City'
},
'mst': {
'name': 'MST',
'description': '',
'location': null,
'offset': -420,
'dstOffset': -420,
'deprecated': true,
'canonical': false,
'aliasOf': null
},
'mst7mdt': {
'name': 'MST7MDT',
'description': '',
'location': null,
'offset': -420,
'dstOffset': -360,
'deprecated': true,
'canonical': false,
'aliasOf': null
},
'navajo': {
'name': 'Navajo',
'description': '',
'location': 'US',
'offset': -420,
'dstOffset': -360,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Denver'
},
'nz': {
'name': 'NZ',
'description': '',
'location': 'NZ',
'offset': 720,
'dstOffset': 780,
'deprecated': true,
'canonical': false,
'aliasOf': 'Pacific/Auckland'
},
'nz-chat': {
'name': 'NZ-CHAT',
'description': '',
'location': 'NZ',
'offset': 765,
'dstOffset': 825,
'deprecated': true,
'canonical': false,
'aliasOf': 'Pacific/Chatham'
},
'pacific/apia': {
'name': 'Pacific/Apia',
'description': '',
'location': 'WS',
'offset': 780,
'dstOffset': 840,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/auckland': {
'name': 'Pacific/Auckland',
'description': 'New Zealand time',
'location': 'NZ',
'offset': 720,
'dstOffset': 780,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/bougainville': {
'name': 'Pacific/Bougainville',
'description': 'Bougainville',
'location': 'PG',
'offset': 660,
'dstOffset': 660,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/chatham': {
'name': 'Pacific/Chatham',
'description': 'Chatham Islands',
'location': 'NZ',
'offset': 765,
'dstOffset': 825,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/chuuk': {
'name': 'Pacific/Chuuk',
'description': 'Chuuk/Truk, Yap',
'location': 'FM',
'offset': 600,
'dstOffset': 600,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/easter': {
'name': 'Pacific/Easter',
'description': 'Easter Island',
'location': 'CL',
'offset': -360,
'dstOffset': -300,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/efate': {
'name': 'Pacific/Efate',
'description': '',
'location': 'VU',
'offset': 660,
'dstOffset': 660,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/enderbury': {
'name': 'Pacific/Enderbury',
'description': 'Phoenix Islands',
'location': 'KI',
'offset': 780,
'dstOffset': 780,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/fakaofo': {
'name': 'Pacific/Fakaofo',
'description': '',
'location': 'TK',
'offset': 780,
'dstOffset': 780,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/fiji': {
'name': 'Pacific/Fiji',
'description': '',
'location': 'FJ',
'offset': 720,
'dstOffset': 780,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/funafuti': {
'name': 'Pacific/Funafuti',
'description': '',
'location': 'TV',
'offset': 720,
'dstOffset': 720,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/galapagos': {
'name': 'Pacific/Galapagos',
'description': 'Galápagos Islands',
'location': 'EC',
'offset': -360,
'dstOffset': -360,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/gambier': {
'name': 'Pacific/Gambier',
'description': 'Gambier Islands',
'location': 'PF',
'offset': -540,
'dstOffset': -540,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/guadalcanal': {
'name': 'Pacific/Guadalcanal',
'description': '',
'location': 'SB',
'offset': 660,
'dstOffset': 660,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/guam': {
'name': 'Pacific/Guam',
'description': '',
'location': 'GU',
'offset': 600,
'dstOffset': 600,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/honolulu': {
'name': 'Pacific/Honolulu',
'description': 'Hawaii',
'location': 'US',
'offset': -600,
'dstOffset': -600,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/johnston': {
'name': 'Pacific/Johnston',
'description': '',
'location': 'UM',
'offset': -600,
'dstOffset': -600,
'deprecated': true,
'canonical': false,
'aliasOf': 'Pacific/Honolulu'
},
'pacific/kiritimati': {
'name': 'Pacific/Kiritimati',
'description': 'Line Islands',
'location': 'KI',
'offset': 840,
'dstOffset': 840,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/kosrae': {
'name': 'Pacific/Kosrae',
'description': 'Kosrae',
'location': 'FM',
'offset': 660,
'dstOffset': 660,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/kwajalein': {
'name': 'Pacific/Kwajalein',
'description': 'Kwajalein',
'location': 'MH',
'offset': 720,
'dstOffset': 720,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/majuro': {
'name': 'Pacific/Majuro',
'description': 'Marshall Islands (most areas)',
'location': 'MH',
'offset': 720,
'dstOffset': 720,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/marquesas': {
'name': 'Pacific/Marquesas',
'description': 'Marquesas Islands',
'location': 'PF',
'offset': -570,
'dstOffset': -570,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/midway': {
'name': 'Pacific/Midway',
'description': 'Midway Islands',
'location': 'UM',
'offset': -660,
'dstOffset': -660,
'deprecated': false,
'canonical': false,
'aliasOf': 'Pacific/Pago_Pago'
},
'pacific/nauru': {
'name': 'Pacific/Nauru',
'description': '',
'location': 'NR',
'offset': 720,
'dstOffset': 720,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/niue': {
'name': 'Pacific/Niue',
'description': '',
'location': 'NU',
'offset': -660,
'dstOffset': -660,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/norfolk': {
'name': 'Pacific/Norfolk',
'description': '',
'location': 'NF',
'offset': 660,
'dstOffset': 720,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/noumea': {
'name': 'Pacific/Noumea',
'description': '',
'location': 'NC',
'offset': 660,
'dstOffset': 660,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/pago_pago': {
'name': 'Pacific/Pago_Pago',
'description': 'Samoa, Midway',
'location': 'AS',
'offset': -660,
'dstOffset': -660,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/palau': {
'name': 'Pacific/Palau',
'description': '',
'location': 'PW',
'offset': 540,
'dstOffset': 540,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/pitcairn': {
'name': 'Pacific/Pitcairn',
'description': '',
'location': 'PN',
'offset': -480,
'dstOffset': -480,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/pohnpei': {
'name': 'Pacific/Pohnpei',
'description': 'Pohnpei/Ponape',
'location': 'FM',
'offset': 660,
'dstOffset': 660,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/ponape': {
'name': 'Pacific/Ponape',
'description': '',
'location': 'FM',
'offset': 660,
'dstOffset': 660,
'deprecated': true,
'canonical': false,
'aliasOf': 'Pacific/Pohnpei'
},
'pacific/port_moresby': {
'name': 'Pacific/Port_Moresby',
'description': 'Papua New Guinea (most areas)',
'location': 'PG',
'offset': 600,
'dstOffset': 600,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/rarotonga': {
'name': 'Pacific/Rarotonga',
'description': '',
'location': 'CK',
'offset': -600,
'dstOffset': -600,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/saipan': {
'name': 'Pacific/Saipan',
'description': '',
'location': 'MP',
'offset': 600,
'dstOffset': 600,
'deprecated': false,
'canonical': false,
'aliasOf': 'Pacific/Guam'
},
'pacific/samoa': {
'name': 'Pacific/Samoa',
'description': '',
'location': 'WS',
'offset': -660,
'dstOffset': -660,
'deprecated': true,
'canonical': false,
'aliasOf': 'Pacific/Pago_Pago'
},
'pacific/tahiti': {
'name': 'Pacific/Tahiti',
'description': 'Society Islands',
'location': 'PF',
'offset': -600,
'dstOffset': -600,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/tarawa': {
'name': 'Pacific/Tarawa',
'description': 'Gilbert Islands',
'location': 'KI',
'offset': 720,
'dstOffset': 720,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/tongatapu': {
'name': 'Pacific/Tongatapu',
'description': '',
'location': 'TO',
'offset': 780,
'dstOffset': 780,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/truk': {
'name': 'Pacific/Truk',
'description': '',
'location': 'FM',
'offset': 600,
'dstOffset': 600,
'deprecated': true,
'canonical': false,
'aliasOf': 'Pacific/Chuuk'
},
'pacific/wake': {
'name': 'Pacific/Wake',
'description': 'Wake Island',
'location': 'UM',
'offset': 720,
'dstOffset': 720,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/wallis': {
'name': 'Pacific/Wallis',
'description': '',
'location': 'WF',
'offset': 720,
'dstOffset': 720,
'deprecated': false,
'canonical': true,
'aliasOf': null
},
'pacific/yap': {
'name': 'Pacific/Yap',
'description': '',
'location': 'FM',
'offset': 600,
'dstOffset': 600,
'deprecated': true,
'canonical': false,
'aliasOf': 'Pacific/Chuuk'
},
'poland': {
'name': 'Poland',
'description': '',
'location': 'PL',
'offset': 60,
'dstOffset': 120,
'deprecated': true,
'canonical': false,
'aliasOf': 'Europe/Warsaw'
},
'portugal': {
'name': 'Portugal',
'description': '',
'location': 'PT',
'offset': 0,
'dstOffset': 60,
'deprecated': true,
'canonical': false,
'aliasOf': 'Europe/Lisbon'
},
'prc': {
'name': 'PRC',
'description': '',
'location': 'CN',
'offset': 480,
'dstOffset': 480,
'deprecated': true,
'canonical': false,
'aliasOf': 'Asia/Shanghai'
},
'pst8pdt': {
'name': 'PST8PDT',
'description': '',
'location': null,
'offset': -480,
'dstOffset': -420,
'deprecated': true,
'canonical': false,
'aliasOf': null
},
'roc': {
'name': 'ROC',
'description': '',
'location': 'TW',
'offset': 480,
'dstOffset': 480,
'deprecated': true,
'canonical': false,
'aliasOf': 'Asia/Taipei'
},
'rok': {
'name': 'ROK',
'description': '',
'location': 'KR',
'offset': 540,
'dstOffset': 540,
'deprecated': true,
'canonical': false,
'aliasOf': 'Asia/Seoul'
},
'singapore': {
'name': 'Singapore',
'description': '',
'location': 'SG',
'offset': 480,
'dstOffset': 480,
'deprecated': true,
'canonical': false,
'aliasOf': 'Asia/Singapore'
},
'turkey': {
'name': 'Turkey',
'description': '',
'location': 'TR',
'offset': 180,
'dstOffset': 180,
'deprecated': true,
'canonical': false,
'aliasOf': 'Europe/Istanbul'
},
'uct': {
'name': 'UCT',
'description': '',
'location': null,
'offset': 0,
'dstOffset': 0,
'deprecated': true,
'canonical': false,
'aliasOf': 'Etc/UTC'
},
'universal': {
'name': 'Universal',
'description': '',
'location': null,
'offset': 0,
'dstOffset': 0,
'deprecated': true,
'canonical': false,
'aliasOf': 'Etc/UTC'
},
'us/alaska': {
'name': 'US/Alaska',
'description': '',
'location': 'US',
'offset': -540,
'dstOffset': -480,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Anchorage'
},
'us/aleutian': {
'name': 'US/Aleutian',
'description': '',
'location': 'US',
'offset': -600,
'dstOffset': -540,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Adak'
},
'us/arizona': {
'name': 'US/Arizona',
'description': '',
'location': 'US',
'offset': -420,
'dstOffset': -420,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Phoenix'
},
'us/central': {
'name': 'US/Central',
'description': '',
'location': 'US',
'offset': -360,
'dstOffset': -300,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Chicago'
},
'us/east-indiana': {
'name': 'US/East-Indiana',
'description': '',
'location': 'US',
'offset': -300,
'dstOffset': -240,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Indiana/Indianapolis'
},
'us/eastern': {
'name': 'US/Eastern',
'description': '',
'location': 'US',
'offset': -300,
'dstOffset': -240,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/New_York'
},
'us/hawaii': {
'name': 'US/Hawaii',
'description': '',
'location': 'US',
'offset': -600,
'dstOffset': -600,
'deprecated': true,
'canonical': false,
'aliasOf': 'Pacific/Honolulu'
},
'us/indiana-starke': {
'name': 'US/Indiana-Starke',
'description': '',
'location': 'US',
'offset': -360,
'dstOffset': -300,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Indiana/Knox'
},
'us/michigan': {
'name': 'US/Michigan',
'description': '',
'location': 'US',
'offset': -300,
'dstOffset': -240,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Detroit'
},
'us/mountain': {
'name': 'US/Mountain',
'description': '',
'location': 'US',
'offset': -420,
'dstOffset': -360,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Denver'
},
'us/pacific': {
'name': 'US/Pacific',
'description': '',
'location': 'US',
'offset': -480,
'dstOffset': -420,
'deprecated': true,
'canonical': false,
'aliasOf': 'America/Los_Angeles'
},
'us/samoa': {
'name': 'US/Samoa',
'description': '',
'location': 'WS',
'offset': -660,
'dstOffset': -660,
'deprecated': true,
'canonical': false,
'aliasOf': 'Pacific/Pago_Pago'
},
'utc': {
'name': 'UTC',
'description': '',
'location': null,
'offset': 0,
'dstOffset': 0,
'deprecated': false,
'canonical': false,
'aliasOf': 'Etc/UTC'
},
'w-su': {
'name': 'W-SU',
'description': '',
'location': 'RU',
'offset': 180,
'dstOffset': 180,
'deprecated': true,
'canonical': false,
'aliasOf': 'Europe/Moscow'
},
'wet': {
'name': 'WET',
'description': '',
'location': null,
'offset': 0,
'dstOffset': 60,
'deprecated': true,
'canonical': false,
'aliasOf': null
},
'zulu': {
'name': 'Zulu',
'description': '',
'location': null,
'offset': 0,
'dstOffset': 0,
'deprecated': true,
'canonical': false,
'aliasOf': 'Etc/UTC'
}
/* eslint-enable @typescript-eslint/naming-convention */
};
export interface ITimeZone {
/**
* The name of a timezone, e.g. "Asia/Shanghai"
*/
'name': string;
/**
* The name of target timezone, if this timezone is an alias of another timezone.
*
* Otherwise, this field must be null.
*/
'aliasOf': string | null;
/**
* Tell if the timezone is deprecated.
*/
'deprecated': boolean;
/**
* Tell if the timezone is a canonical timezone.
*/
'canonical': boolean;
/**
* The offset from UTC in minutes. This field should be positive in eastern hemisphere,
* while negative in western hemisphere.
*
* **THAT MEANS THE VALUE OF THIS FIELD IS NEGATIVE TO THE VALUE OF `Date.prototype.getTimezoneOffset`.**
*/
'offset': number;
/**
* The DST offset from UTC in minutes. This field should be positive in eastern hemisphere,
* while negative in western hemisphere.
*
* **THAT MEANS THE VALUE OF THIS FIELD IS NEGATIVE TO THE VALUE OF `Date.prototype.getTimezoneOffset`.**
*/
'dstOffset': number;
/**
* Country/location codes using this timezone.
*/
'location': string | null;
/**
* More details about this timezone.
*/
'description': string;
}
export interface ITimeZoneManager {
/**
* Find a timezone by its name (case-insensitive).
*
* @param name The name of timezone to be find.
* @returns Return the detail info of the timezone if found. Otherwise, return `null`.
*/
findByName(name: string): ITimeZone | null;
/**
* Find the list of timezones used by the determined location.
*
* @param location The determined location to be searched by.
* @returns Return an array of found timezone.
*/
findByLocation(location: string): ITimeZone[];
/**
* Find the timezone by the offset.
*
* @param offset The timezone offset from UTC in minutes
*/
findByOffset(offset: number): ITimeZone[];
/**
* Find the timezone by the DST offset.
*
* @param offset The timezone DST offset from UTC in minutes
*/
findByDSTOffset(offset: number): ITimeZone[];
/**
* Get the list of all canonical timezones.
*/
findCanonicalList(): ITimeZone[];
/**
* Get the list of all timezones, whatever alias, canonical or deprecated.
*/
findAllList(): ITimeZone[];
/**
* Convert a integer offset into string.
*/
offsetToString(offset: number): string;
/**
* Convert a string offset into integer.
*/
offsetFromString(offset: string): number;
}
const LOCATION_2_TZ_MAPS: Record<string, ITimeZone[]> = {};
const CANONICAL_TZS: ITimeZone[] = [];
const OFFSET_2_TZ_MAPS: Record<string, ITimeZone[]> = {};
const DST_OFFSET_2_TZ_MAPS: Record<string, ITimeZone[]> = {};
function buildIndex(): void {
for (const k in TIME_ZONES) {
const tz = TIME_ZONES[k];
if (tz.location) {
const loc = tz.location.toLowerCase();
if (!LOCATION_2_TZ_MAPS[loc]) {
LOCATION_2_TZ_MAPS[loc] = [];
}
LOCATION_2_TZ_MAPS[loc].push(tz);
}
if (tz.canonical) {
CANONICAL_TZS.push(tz);
}
if (!OFFSET_2_TZ_MAPS[tz.offset]) {
OFFSET_2_TZ_MAPS[tz.offset] = [];
}
OFFSET_2_TZ_MAPS[tz.offset].push(tz);
if (!DST_OFFSET_2_TZ_MAPS[tz.dstOffset]) {
DST_OFFSET_2_TZ_MAPS[tz.dstOffset] = [];
}
DST_OFFSET_2_TZ_MAPS[tz.dstOffset].push(tz);
}
}
buildIndex();
class TimeZoneManager implements ITimeZoneManager {
public offsetToString(offset: number): string {
const absOffset = Math.abs(offset);
const m = absOffset % 60;
const h = (absOffset - m) / 60;
if (offset < 0) {
return `-${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}`;
}
return `+${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}`;
}
public offsetFromString(offset: string): number {
let o;
if (offset.startsWith('-') || offset.startsWith('+')) {
o = offset.slice(1);
}
else {
o = offset;
}
const [h, m] = o.split(':');
return (parseInt(h) * 60 + parseInt(m)) * (offset.startsWith('-') ? -1 : 1);
}
public findByName(name: string): ITimeZone | null {
const ret = TIME_ZONES[name.toLowerCase()];
return ret ? {...ret} : null;
}
public findByLocation(loc: string): ITimeZone[] {
return (LOCATION_2_TZ_MAPS[loc.toLowerCase()] || [] as ITimeZone[]).map((v) => ({...v}));
}
public findByOffset(offset: number): ITimeZone[] {
return (OFFSET_2_TZ_MAPS[offset] || [] as ITimeZone[]).map((v) => ({...v}));
}
public findByDSTOffset(offset: number): ITimeZone[] {
return (DST_OFFSET_2_TZ_MAPS[offset] || [] as ITimeZone[]).map((v) => ({...v}));
}
public findCanonicalList(): ITimeZone[] {
return CANONICAL_TZS.map((v) => ({...v}));
}
public findAllList(): ITimeZone[] {
return Object.values(TIME_ZONES).map((v) => ({...v}));
}
}
const THE_TZ_MGR: ITimeZoneManager = new TimeZoneManager();
export default THE_TZ_MGR;
export function getDefaultTimezoneManager(): ITimeZoneManager {
return THE_TZ_MGR;
}
export function createTimezoneManager(): ITimeZoneManager {
return new TimeZoneManager();
}
<file_sep>/CHANGES.md
# Changes Log
## v0.1.3
- sync(data): Sync the latest data (20210611) from wikipedia.
## v0.1.2
- sync(data): Sync the latest data (20201215) from wikipedia.
- config(lint): Replaced with ESLint.
## v0.1.1
- Updated DST offset of `Africa/Ceuta`.
<file_sep>/src/examples/00.demos.ts
/**
* Copyright 2021 Angus.Fenying <<EMAIL>>
*
* 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
*
* https://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.
*/
// tslint:disable: no-console
import * as $TZ from '../lib';
const tz = $TZ.getDefaultTimezoneManager();
const tzShanghai = tz.findByName('Asia/Shanghai');
console.log(JSON.stringify(tzShanghai, null, 2));
const tzGB = tz.findByLocation('GB');
console.log(JSON.stringify(tzGB, null, 2));
const tz480 = tz.findByOffset(480);
console.log(JSON.stringify(tz480, null, 2));
for (const i of tz.findCanonicalList()) {
console.log(i.name.padEnd(32, ' ') + tz.offsetToString(i.offset));
}
<file_sep>/utils/extract.js
/**
* Copyright 2021 Angus.Fenying <<EMAIL>>
*
* 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
*
* https://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.
*/
(function() {
const rawData = [];
$('#mw-content-text > div > table:nth-child(9) > tbody > tr').each(function() {
const countryCode = $(this).find('td:nth-child(1)').text().trim().toUpperCase();
const tzName = $(this).find('td:nth-child(3)').text().trim();
const description = $(this).find('td:nth-child(4)').text().trim();
const status = $(this).find('td:nth-child(5)').text().trim().toLowerCase();
const offset = $(this).find('td:nth-child(6)').text().trim();
const dstOffset = $(this).find('td:nth-child(7)').text().trim();
const notes = $(this).find('td:nth-child(8)').text().trim();
const alias = notes.startsWith("Link to") ? $(this).find('td:nth-child(8) a').text().trim() : null;
rawData.push({
countryCode,
name: tzName,
description,
status,
offset,
dstOffset,
notes,
alias
});
});
const timezones = {};
function offsetToMinutes(offset) {
let [h, m] = offset.slice(1).split(":");
const minutes = parseInt(h) * 60 + parseInt(m);
/**
* The "−" is not minus sign, it's unicode char `0x2212`.
*/
return offset.charCodeAt(0) !== 43 ? -1 * minutes : minutes;
}
for (const row of rawData) {
const item = timezones[row.name.toLowerCase()] = {
name: row.name,
description: row.description,
location: row.countryCode || null,
offset: offsetToMinutes(row.offset),
dstOffset: offsetToMinutes(row.dstOffset),
deprecated: false,
canonical: false,
aliasOf: null
};
switch (row.status) {
case "deprecated":
item.deprecated = true;
case "alias":
if (row.alias) {
item.aliasOf = row.alias;
}
else if (row.status === "alias") {
console.error("NO ALIAS!");
console.error(row);
}
break;
case "canonical":
item.canonical = true;
break;
}
}
console.log(`const TIME_ZONES = ${JSON.stringify(timezones, null, 4)};`);
})();<file_sep>/README.md
# LiteRT/TimeZone
[](https://www.npmjs.com/package/@litert/timezone "Stable Version")
[](https://github.com/litert/timezone/blob/master/LICENSE)
[](https://github.com/litert/timezone.js/issues)
[](https://github.com/litert/timezone.js/releases "Stable Release")
The timezone support library of LiteRT.
> Copyright: This is just a toolset of timezone operation for JavaScript.
> As all timezone data is extracted from [WikiPedia](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones).
## Requirements
- TypeScript v3.1.x (Or newer)
## Installation
```sh
npm i @litert/timezone --save
```
## Usage
```ts
import TZ from "@litert/timezone";
console.log(TZ.findByName("Asia/Brunei")); // Find the info of timezone Asia/Brunei.
console.log(TZ.findByLocation("US")); // Find the list of timezone used by US.
console.log(TZ.findByOffset(480)); // Find the list of timezones whose offset is 480 (from UTC, ini).
console.log(TZ.findByDSTOffset(480)); // Find the list of timezones whose DST offset is 480.
console.log(TZ.findCanonicalList()); // Find out list of all canonical timezone.
console.log(TZ.offsetToString(480)); // Convert minute offset into string, which should be +08:00.
console.log(TZ.offsetFromString('-08:00')); // Convert a string into minute offset, which should be -480.
```
## Documents
Preparing yet.
## License
This library is published under [Apache-2.0](./LICENSE) license.
| a1ed1fa7752e0dbcbbe570b7fe645872973b9ff2 | [
"Markdown",
"TypeScript",
"JavaScript"
] | 5 | TypeScript | litert/timezone.js | 8be62302d6d022e049148722eec2b32facd073c5 | 0b081bd83d6c768c47df434f58acf3d693a1f347 |
refs/heads/master | <repo_name>mehnazyunus/note-maker-initial<file_sep>/popup.js
$(document).ready(function(){
$('#pagination-demo').twbsPagination({
totalPages: 35,
visiblePages: 4,
onPageClick: function (event, page) {
var refresh = function (page) { //A function which refreshes the current page
$($('.text')[0]).focus();
lists=[];
if(localStorage.lists!=undefined)
lists=JSON.parse(localStorage.lists);
lists.sort(function(a,b){
return b.date>a.date;
});
pagelist=lists.slice((page-1)*pagelimit,page*pagelimit);
ol=$('.lists');
ol.empty();
li=[];
checkbox='<input type="checkbox" class="checkbox">';
buttons='<ul class="notebuttons"><li><button type="button" class="editbutton">Edit</button></li><li><button type="button" class="notebutton">Show</button></li></ul>';
for(i in pagelist){
li[i]='<li class="listItems">'+checkbox+'<span class="done check title">'+ pagelist[i].title +'</span>'+buttons+'<div class="note"><p class="text">'+ pagelist[i].notes +'</p></div>'+'</li> <br>';
}
ol.append(li);
$('.checkbox').click(function(){
for (i in li)
if ($($('.checkbox')[i]).prop("checked"))
lists[(page-1)*pagelimit+parseInt(i)].done=true;
else
lists[(page-1)*pagelimit+parseInt(i)].done=false;
});
$('.container').css({"width":"250px"});
$('.note').css({"width":"80%"})
$('.notebutton').click(function(){
note=$(this).parent().parent().next(".note");
note.toggle();
if (note.css("display")==="none")
$(this).text('Show');
else
$(this).text('Hide');
});
$('#page-content').text('Page '+page);
$('.addbutton').click(function(){ //function which adds a new entry
remove();
text=$('.text');
if ($(text[0]).val()!=''){
var d=new Date();
lists.push({title: $(text[0]).val(), notes: $(text[1]).val(),done:false, date: d});
$(text[0]).val('');
$(text[1]).val('');
}
this.value="Add",
localStorage.setItem('lists',JSON.stringify(lists));
location.reload();
});
var remove=function(){ //function which removes the checked items
oldlist=lists;
lists=[];
for (i in oldlist){
if(!oldlist[i].done)
lists.push(oldlist[i]);
localStorage.setItem('lists',JSON.stringify(lists));
}
}
$('.removebutton').click(function(){ //function for removing
remove();
refresh(page);
});
$('.editbutton').click(function(){ //function for editing a specific entry
edititem=$(this).parents('.listItems')[0];
$($(edititem).children('.checkbox')[0]).prop('checked',true);
indexp=$(edititem).index()/2;
index=(page-1)*pagelimit + indexp;
text=$('.text');
lists[index].done=true;
$(text[0]).val(lists[index].title);
$(text[1]).val(lists[index].notes);
$(text[1]).focus();
$('.addbutton').attr('value','Update');
});
}
pagelimit=2;
refresh(page);
}
});
});<file_sep>/eventPage.js
var contextMenuItem = {
"id" : "addNotes",
"title" : "Add to NoteMaker",
"contexts" : ["selection"]
};
chrome.contextMenus.create(contextMenuItem);
chrome.contextMenus.onClicked.addListener(function (selectedText) {
if(selectedText.menuItemId=="addNotes" && selectedText.selectionText)
{
var title = prompt("Enter title for the note:");
var lists=[];
if(localStorage.lists!=undefined)
lists=JSON.parse(localStorage.lists);
lists.sort(function(a,b){
return b.date>a.date;
});
var text=selectedText.selectionText;
var d=new Date();
lists.push({title: title, notes: text ,done:false, date: d});
localStorage.setItem('lists',JSON.stringify(lists));
location.reload();
//Was going to use for title of webpage as Title
/*
chrome.tabs.getSelected(null, function(tab) { //<-- "tab" has all the information
console.log(tab.url); //returns the url
console.log(tab.title); //returns the title
});
*/
}
}); | f3a30c31f15a9b0849eead8849dab8c8e412717c | [
"JavaScript"
] | 2 | JavaScript | mehnazyunus/note-maker-initial | f29fe4b2b1f5ea1eb6b075bf4a3519f0f208e377 | 86614449690ca3b1321eb02c2a4f46526de698f8 |
refs/heads/main | <repo_name>layel2/food-api<file_sep>/requirements.txt
cachetools==4.1.1
certifi==2020.6.20
chardet==3.0.4
click==7.1.2
fastapi==0.61.1
geographiclib==1.50
geopy==2.0.0
google-auth==1.21.3
google-auth-oauthlib==0.4.1
gspread==3.6.0
h11==0.9.0
httplib2==0.18.1
httptools==0.1.1
idna==2.10
numpy==1.19.2
oauth2client==4.1.3
oauthlib==3.1.0
pandas==1.1.2
pyasn1==0.4.8
pyasn1-modules==0.2.8
pydantic==1.6.1
python-dateutil==2.8.1
pytz==2020.1
requests==2.24.0
requests-oauthlib==1.3.0
rsa==4.6
six==1.15.0
starlette==0.13.6
urllib3==1.25.10
uvicorn==0.11.8
uvloop==0.14.0
websockets==8.1
<file_sep>/utils.py
import pandas as pd
import numpy as np
from oauth2client.service_account import ServiceAccountCredentials
import geopy.distance as ps
from geopy.geocoders import Nominatim
import gspread
def read_gsheet():
worksheet = get_gsheet("https://docs.google.com/spreadsheets/d/1amqQT5t6WK1pu7FCxn-Gf5cwGxagqOK17TNHVMHYqtY")
results = worksheet.get_all_records()
return pd.DataFrame(results)
def find_dist(src,des_list):
dist = []
for des in des_list :
dist.append(ps.distance(src, des).km)
return np.array(dist)
def locate_cut(locastr):
return float(locastr.split('=')[1].split(')')[0])
def place2location(place:str):
geolocator = Nominatim(user_agent="app1")
return geolocator.geocode(place)[1]
def user_db_update(customer_id,lat,lng,food_cate) :
worksheet = get_gsheet("https://docs.google.com/spreadsheets/d/1QzLXE_VCjXebBCBQX-scbeA9qIUaSmTkEsEwZI9Oiao")
results = worksheet.get_all_records()
df = pd.DataFrame(results)
user_check = df.where(df['uid'] == str(customer_id)).dropna()
if len(user_check) == 1 :
cellRow = user_check.index.values[0] + 2
update_row = 'B'+str(cellRow)+':D'+str(cellRow)
worksheet.update(update_row,[[lat,lng,food_cate]])
else :
cellRow = len(df) + 2
update_row = 'A'+str(cellRow)+':D'+str(cellRow)
worksheet.update(update_row,[[customer_id,lat,lng,food_cate]])
def user_db_res(customer_id):
worksheet = get_gsheet("https://docs.google.com/spreadsheets/d/<KEY>")
results = worksheet.get_all_records()
df = pd.DataFrame(results)
user_check = df.where(df['uid'] == str(customer_id)).dropna()
if len(user_check) == 1 :
return user_check[['lat','lng','food_cate']].values
else :
return None
def get_gsheet(url):
scope = ['https://www.googleapis.com/auth/spreadsheets']
credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)
client = gspread.authorize(credentials)
sheet = client.open_by_url(url)
worksheet = sheet.get_worksheet(0)
return worksheet<file_sep>/main.py
from fastapi import FastAPI
import uvicorn
from utils import *
#from flex import *
from flex2 import *
app = FastAPI()
@app.get("/")
async def index():
return {"message" : "Hello World"}
@app.get("/return")
async def retval(param:str=None):
return{"msg":param}
@app.get("/api/getRes")
async def getRes(place:str,food_cate:str,num:int = 9,customer_id:str=None):
"""
Get data by string place
- **place** Place of location ex.สยามพารากอน
- **food_cate** Food category ex.อาหารญี่ปุ่น, อาหารเจ
- **num** Number of restaurang to return (int)
"""
lat,lng = place2location(place)
data = read_gsheet()
data = data[(data['categories_1']==food_cate) | (data['categories_2']==food_cate) | (data['categories_3']==food_cate)]
dist = find_dist((lat,lng),data[['lat','lng']].values)
min_arg = np.argsort(dist)[:num]
data_out = data.iloc[min_arg]
data_out['dist'] = dist[min_arg]
if customer_id is not None :
user_db_update(customer_id,lat,lng,food_cate)
return get_flex(data_out.reset_index().to_dict(orient='index'),num)
@app.get('/api/getedlocation')
async def getedLocation(p_latitude: str, p_longitude: str):
headers = {'Response-Type': 'intent'}
return_json = {
'intent': "in_getedlocation"
}
#print(p_longitude)
return JSONResponse(content=return_json, headers=headers)
@app.get('/api/getResGPS')
async def getResByShare(p_latitude: str, p_longitude: str, food_cate: str, num: int = 9, customer_id:str=None):
lat = float(p_latitude)
lng = float(p_longitude)
#print(type(lat))
#print(type(lng))
data = read_gsheet()
food_cate = food_cate
data = data[(data['categories_1'] == food_cate) | (
data['categories_2'] == food_cate) | (data['categories_3'] == food_cate)]
dist = find_dist((lat, lng), data[['lat', 'lng']].values)
min_arg = np.argsort(dist)[:num]
data_out = data.iloc[min_arg]
data_out['dist'] = dist[min_arg]
if customer_id is not None :
user_db_update(customer_id,lat,lng,food_cate)
return get_flex(data_out.reset_index().to_dict(orient='index'), num)
@app.get("/api/getRes_location")
def getRes_location(p_latitude:float,p_longitude,food_cate:str,num:int = 9,customer_id:str=None):
return getRes_location_fn(p_latitude=p_latitude,p_longitude=p_longitude,
food_cate=food_cate,num=num,customer_id=customer_id)
def getRes_location_fn(p_latitude:float,p_longitude,food_cate:str,num:int = 9,customer_id:str=None):
lat,lng = p_latitude,p_longitude
data = read_gsheet()
data = data[(data['categories_1']==food_cate) | (data['categories_2']==food_cate) | (data['categories_3']==food_cate)]
dist = find_dist((lat,lng),data[['lat','lng']].values)
min_arg = np.argsort(dist)[:num]
data_out = data.iloc[min_arg]
data_out['dist'] = dist[min_arg]
if customer_id is not None :
user_db_update(customer_id,lat,lng,food_cate)
return get_flex(data_out.reset_index().to_dict(orient='index'),num)
@app.get("/api/getUser_res")
async def getUser_random(customer_id:str):
num = 9
read_data = user_db_res(customer_id)
data = read_gsheet()
if read_data is None :
data = data.sample(frac=1)
return get_flex(data.reset_index().to_dict(orient='index'),num)
lat,lng,food_cate = read_data[0]
dist = find_dist((lat,lng),data[['lat','lng']].values)
min_arg = np.argsort(dist)[:30]
data_out = data.iloc[min_arg].sample(frac=1).iloc[:num]
#data_out['dist'] = dist[min_arg]
return get_flex(data_out.reset_index().to_dict(orient='index'),num)
@app.get("/api/flex")
async def call_flex():
return get_flex_test()
if __name__ == "__main__" :
uvicorn.run("main:app",host="0.0.0.0")
| 729adee510813ebcfde5521b4ca69a3b64806db1 | [
"Python",
"Text"
] | 3 | Text | layel2/food-api | 083dd41fd6d40accb40b8403df6e06df7bbecc05 | dfb2eec13e26f9ef31d444e76ba525fea3302d82 |
refs/heads/master | <file_sep><?php
include "db.php";
$query = "SELECT * FROM `items` ORDER BY `id` DESC";
$execute = mysqli_query($con,$query);
?>
<?php
while($row = mysqli_fetch_assoc($execute)){?>
<div class="cardWrapper">
<div class="card">
<img src="<?php echo $row['img'];?>">
<div class="cardContent">
<p class="name"><?php echo $row['name'];?></p>
<p class="price">Price: <?php echo $row['price'];?> tk</p>
<p class="available">Available: <?php echo $row['available'];?> pieces</p>
</div>
</div>
</div>
<?php
}
?> | 68be73f2ba4d279eadb4cccf13bdf2d0ee3c6cab | [
"PHP"
] | 1 | PHP | khanmdsagar/Php-Product-ShowCase | cfc7070e90177423d29164a7903edb6eafcf3d57 | 1ec2f505022c57bf1aff71697e614d5ad29200b2 |
refs/heads/master | <file_sep>
import java.util.*;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author mridul
*/
public class Word {
public static int countWords(String S)
{
int i,count=0;
String stmp[] = S.trim().split(" ");
for (i = 0;i<stmp.length;i++)
{
if (!stmp[i].equals(""))
count++;
}
return count;
}
public static String reverseWord(String S)
{
int i;
String S2="";
for (i=S.length()-1;i>=0;i--)
{
char ch = S.charAt(i);
S2 = S2.concat(ch + "");
}
return S2;
}
public static boolean isPalindrome(String S)
{
if (S.equals(reverseWord(S)))
return true;
else
return false;
}
public static String WriteDiagonal(String S)
{
String Sr;
int n = S.length(),i;
Sr = S.charAt(0) + "\n";
for (i=1;i<n;i++)
{
char ch = S.charAt(i);
Sr =Sr+ spaceCreate(i) + ch + "\n";
}
return Sr;
}
public static String spaceCreate(int n)
{
String S = "";
int i;
for (i=1;i<=n;i++)
{
S=S + " ";
}
return S;
}
public static String[] getWords(String S)
{
List<String> list = new ArrayList<String>();
for(String s : S.split(" ")) {
if(s != null && s.length() > 0) {
list.add(s);
}
}
return list.toArray(new String[list.size()]);
}
public static String reverseWordsInPosition(String S){
String s[] = getWords(S);
String res="";
for (int i=0;i<s.length;i++)
res+=reverseWord(s[i])+ " ";
return res.trim();
}
public static String reverseWordPlacement(String S){
String s[]=getWords(S);
String res="";
for (int i=s.length-1;i>=0;i--)
res+=s[i]+ " ";
return res.trim();
}
public static int countWordOccurence(String S,String word){
String s[] = getWords(S);
int count=0;
for (String item : s) {
if (item.equals(word)) {
count++;
}
}
return count;
}
/* usage: permutation("",stringToPermute);*/
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0) System.out.println(prefix);
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
}
}
public static void alert(String S)
{
System.out.println(S);
}
public static void alert(int S)
{
System.out.println(S);
}
public static void alert(char S)
{
System.out.println(S);
}
public static void main(String args[]){
System.out.println(reverseWordsInPosition("Testing simple program"));
System.out.println(reverseWordPlacement("Testing simple program"));
System.out.println(countWordOccurence("This is a simple sentence, ans that is cool.","is"));
}
}
<file_sep># WordClass
This is a java class to perform various operations on words and sentences in a string
| 9cea49b125e40b5d3cd955121fbee6598aad6608 | [
"Markdown",
"Java"
] | 2 | Java | mridulganga/WordClass | a70302d0ad630cf92261e93d80dcbc890ba1bb86 | 21280db456f00fbe0943c5ec96f09441dafaf5eb |
refs/heads/master | <repo_name>Calmefils/mailgun-js<file_sep>/dist/lib/lists.d.ts
import Request from "./request";
import {
ListsQuery,
CreateUpdateList,
DestroyedList,
MailingList,
} from "./interfaces/lists";
import { IMailListsMembers } from "./interfaces/mailListMembers";
export default class ListsClient {
baseRoute: string;
request: Request;
members: IMailListsMembers;
constructor(request: Request, members: IMailListsMembers);
list(query?: ListsQuery): Promise<MailingList[]>;
getMailingListMembers(mailListAddress: string): Promise<MailingList[]>;
get(mailListAddress: string): Promise<MailingList>;
create(data: CreateUpdateList): Promise<MailingList>;
update(mailListAddress: string, data: CreateUpdateList): Promise<MailingList>;
destroy(mailListAddress: string): Promise<DestroyedList>;
}
| a06f7ba342548146018bfb41afd15558e1c68bf5 | [
"TypeScript"
] | 1 | TypeScript | Calmefils/mailgun-js | b63e05f07a7245fb17f7459603f576603717c94f | 6d099aa74e34d61c499fe0cc76b2163484851493 |
refs/heads/master | <file_sep>const env = process.env.NODE_ENV || 'development';
const config = require(`${__dirname}/./config/config.json`)[env];
const Promise = require('bluebird');
const initOptions = {
promiseLib: Promise
};
const pgp = require('pg-promise')(initOptions);
// Connection
const connectionString = 'postgres://' + config.username + ':' + config.password + '@localhost:' + config.port + '/' + config.database;
const client = pgp(connectionString);
//Query Functions
function getAll(req, res, next) {
client.any('SELECT * FROM prefeitura')
.then(function (data) {
res.status(200).json(data);
})
.catch(function (err) {
return next(err);
});
}
module.exports = { getAll: getAll };
<file_sep>//Import's
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const query = require('./query');
const app = express();
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.all('/', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.get('/', query.getAll);
module.exports = app; | f2d44b599354e69e7f974cafd9e2cb8300bb6fb4 | [
"JavaScript"
] | 2 | JavaScript | giu7d/PubM-NodeAPI | bc3b8bbd7f2136080571a803df6c911f682027ec | 0aaa21c5f202ed0052fb25602fc4d5dd59a7ddc4 |
refs/heads/master | <file_sep># coding: utf-8
# pylint: skip-file
import os
import subprocess
import tempfile
import unittest
import lightgbm as lgb
import numpy as np
from sklearn.datasets import load_breast_cancer, dump_svmlight_file
from sklearn.model_selection import train_test_split
class TestBasic(unittest.TestCase):
def test(self):
X_train, X_test, y_train, y_test = train_test_split(*load_breast_cancer(True), test_size=0.1, random_state=2)
train_data = lgb.Dataset(X_train, max_bin=255, label=y_train)
valid_data = train_data.create_valid(X_test, label=y_test)
params = {
"objective": "binary",
"metric": "auc",
"min_data": 10,
"num_leaves": 15,
"verbose": -1,
"num_threads": 1
}
bst = lgb.Booster(params, train_data)
bst.add_valid(valid_data, "valid_1")
for i in range(30):
bst.update()
if i % 10 == 0:
print(bst.eval_train(), bst.eval_valid())
bst.save_model("model.txt")
pred_from_matr = bst.predict(X_test)
with tempfile.NamedTemporaryFile() as f:
tname = f.name
with open(tname, "w+b") as f:
dump_svmlight_file(X_test, y_test, f)
pred_from_file = bst.predict(tname)
os.remove(tname)
self.assertEqual(len(pred_from_matr), len(pred_from_file))
for preds in zip(pred_from_matr, pred_from_file):
self.assertAlmostEqual(*preds, places=15)
# check saved model persistence
bst = lgb.Booster(params, model_file="model.txt")
pred_from_model_file = bst.predict(X_test)
self.assertEqual(len(pred_from_matr), len(pred_from_model_file))
for preds in zip(pred_from_matr, pred_from_model_file):
# we need to check the consistency of model file here, so test for exact equal
self.assertEqual(*preds)
# check pmml
subprocess.call(['python', os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../pmml/pmml.py'), 'model.txt'])
<file_sep>// application
#include "../../src/application/application.cpp"
// boosting
#include "../../src/boosting/boosting.cpp"
#include "../../src/boosting/gbdt.cpp"
#include "../../src/boosting/gbdt_prediction.cpp"
// io
#include "../../src/io/bin.cpp"
#include "../../src/io/config.cpp"
#include "../../src/io/dataset.cpp"
#include "../../src/io/dataset_loader.cpp"
#include "../../src/io/metadata.cpp"
#include "../../src/io/parser.cpp"
#include "../../src/io/tree.cpp"
// metric
#include "../../src/metric/dcg_calculator.cpp"
#include "../../src/metric/metric.cpp"
// network
#include "../../src/network/linker_topo.cpp"
#include "../../src/network/linkers_socket.cpp"
#include "../../src/network/network.cpp"
// objective
#include "../../src/objective/objective_function.cpp"
// treelearner
#include "../../src/treelearner/data_parallel_tree_learner.cpp"
#include "../../src/treelearner/feature_parallel_tree_learner.cpp"
#include "../../src/treelearner/serial_tree_learner.cpp"
#include "../../src/treelearner/gpu_tree_learner.cpp"
#include "../../src/treelearner/tree_learner.cpp"
#include "../../src/treelearner/voting_parallel_tree_learner.cpp"
// c_api
#include "../../src/c_api.cpp"
<file_sep>LightGBM FAQ
=======================
### Catalog
- [Python-package](FAQ.md#python-package)
### Python-package
- **Question 1**: I see error messages like this when install from github using `python setup.py install`.
```
error: Error: setup script specifies an absolute path:
/Users/Microsoft/LightGBM/python-package/lightgbm/../../lib_lightgbm.so
setup() arguments must *always* be /-separated paths relative to the
setup.py directory, *never* absolute paths.
```
- **Solution 1**: this error should be solved in latest version. If you still meet this error, try to remove lightgbm.egg-info folder in your python-package and reinstall, or check [this thread on stackoverflow](http://stackoverflow.com/questions/18085571/pip-install-error-setup-script-specifies-an-absolute-path).
- **Question 2**: I see error messages like `Cannot get/set label/weight/init_score/group/num_data/num_feature before construct dataset`, but I already construct dataset by some code like `train = lightgbm.Dataset(X_train, y_train)`, or error messages like `Cannot set predictor/reference/categorical feature after freed raw data, set free_raw_data=False when construct Dataset to avoid this.`.
- **Solution 2**: Because LightGBM constructs bin mappers to build trees, and train and valid Datasets within one Booster share the same bin mappers, categorical features and feature names etc., the Dataset objects are constructed when construct a Booster. And if you set free_raw_data=True (default), the raw data (with python data struct) will be freed. So, if you want to:
+ get label(or weight/init_score/group) before construct dataset, it's same as get `self.label`
+ set label(or weight/init_score/group) before construct dataset, it's same as `self.label=some_label_array`
+ get num_data(or num_feature) before construct dataset, you can get data with `self.data`, then if your data is `numpy.ndarray`, use some code like `self.data.shape`
+ set predictor(or reference/categorical feature) after construct dataset, you should set free_raw_data=False or init a Dataset object with the same raw data
<file_sep>#include "gbdt.h"
#include <LightGBM/utils/openmp_wrapper.h>
#include <LightGBM/utils/common.h>
#include <LightGBM/objective_function.h>
#include <LightGBM/metric.h>
#include <ctime>
#include <sstream>
#include <chrono>
#include <string>
#include <vector>
#include <utility>
namespace LightGBM {
void GBDT::PredictRaw(const double* features, double* output) const {
if (num_threads_ <= num_tree_per_iteration_) {
#pragma omp parallel for schedule(static)
for (int k = 0; k < num_tree_per_iteration_; ++k) {
for (int i = 0; i < num_iteration_for_pred_; ++i) {
output[k] += models_[i * num_tree_per_iteration_ + k]->Predict(features);
}
}
} else {
for (int k = 0; k < num_tree_per_iteration_; ++k) {
double t = 0.0f;
#pragma omp parallel for schedule(static) reduction(+:t)
for (int i = 0; i < num_iteration_for_pred_; ++i) {
t += models_[i * num_tree_per_iteration_ + k]->Predict(features);
}
output[k] = t;
}
}
}
void GBDT::Predict(const double* features, double* output) const {
if (num_threads_ <= num_tree_per_iteration_) {
#pragma omp parallel for schedule(static)
for (int k = 0; k < num_tree_per_iteration_; ++k) {
for (int i = 0; i < num_iteration_for_pred_; ++i) {
output[k] += models_[i * num_tree_per_iteration_ + k]->Predict(features);
}
}
} else {
for (int k = 0; k < num_tree_per_iteration_; ++k) {
double t = 0.0f;
#pragma omp parallel for schedule(static) reduction(+:t)
for (int i = 0; i < num_iteration_for_pred_; ++i) {
t += models_[i * num_tree_per_iteration_ + k]->Predict(features);
}
output[k] = t;
}
}
if (objective_function_ != nullptr) {
objective_function_->ConvertOutput(output, output);
}
}
void GBDT::PredictLeafIndex(const double* features, double* output) const {
int total_tree = num_iteration_for_pred_ * num_tree_per_iteration_;
#pragma omp parallel for schedule(static)
for (int i = 0; i < total_tree; ++i) {
output[i] = models_[i]->PredictLeafIndex(features);
}
}
} // namespace LightGBM<file_sep># coding: utf-8
# pylint: disable = invalid-name, W0105, C0111, C0301
"""Scikit-Learn Wrapper interface for LightGBM."""
from __future__ import absolute_import
import numpy as np
from .basic import Dataset, LightGBMError
from .compat import (SKLEARN_INSTALLED, LGBMClassifierBase, LGBMDeprecated,
LGBMLabelEncoder, LGBMModelBase, LGBMRegressorBase, argc_,
range_)
from .engine import train
def _objective_function_wrapper(func):
"""Decorate an objective function
Note: for multi-class task, the y_pred is group by class_id first, then group by row_id
if you want to get i-th row y_pred in j-th class, the access way is y_pred[j*num_data+i]
and you should group grad and hess in this way as well
Parameters
----------
func: callable
Expects a callable with signature ``func(y_true, y_pred)`` or ``func(y_true, y_pred, group):
y_true: array_like of shape [n_samples]
The target values
y_pred: array_like of shape [n_samples] or shape[n_samples * n_class] (for multi-class)
The predicted values
group: array_like
group/query data, used for ranking task
Returns
-------
new_func: callable
The new objective function as expected by ``lightgbm.engine.train``.
The signature is ``new_func(preds, dataset)``:
preds: array_like, shape [n_samples] or shape[n_samples * n_class]
The predicted values
dataset: ``dataset``
The training set from which the labels will be extracted using
``dataset.get_label()``
"""
def inner(preds, dataset):
"""internal function"""
labels = dataset.get_label()
argc = argc_(func)
if argc == 2:
grad, hess = func(labels, preds)
elif argc == 3:
grad, hess = func(labels, preds, dataset.get_group())
else:
raise TypeError("Self-defined objective function should have 2 or 3 arguments, got %d" % argc)
"""weighted for objective"""
weight = dataset.get_weight()
if weight is not None:
"""only one class"""
if len(weight) == len(grad):
grad = np.multiply(grad, weight)
hess = np.multiply(hess, weight)
else:
num_data = len(weight)
num_class = len(grad) // num_data
if num_class * num_data != len(grad):
raise ValueError("Length of grad and hess should equal to num_class * num_data")
for k in range_(num_class):
for i in range_(num_data):
idx = k * num_data + i
grad[idx] *= weight[i]
hess[idx] *= weight[i]
return grad, hess
return inner
def _eval_function_wrapper(func):
"""Decorate an eval function
Note: for multi-class task, the y_pred is group by class_id first, then group by row_id
if you want to get i-th row y_pred in j-th class, the access way is y_pred[j*num_data+i]
Parameters
----------
func: callable
Expects a callable with following functions:
``func(y_true, y_pred)``,
``func(y_true, y_pred, weight)``
or ``func(y_true, y_pred, weight, group)``
and return (eval_name->str, eval_result->float, is_bigger_better->Bool):
y_true: array_like of shape [n_samples]
The target values
y_pred: array_like of shape [n_samples] or shape[n_samples * n_class] (for multi-class)
The predicted values
weight: array_like of shape [n_samples]
The weight of samples
group: array_like
group/query data, used for ranking task
Returns
-------
new_func: callable
The new eval function as expected by ``lightgbm.engine.train``.
The signature is ``new_func(preds, dataset)``:
preds: array_like, shape [n_samples] or shape[n_samples * n_class]
The predicted values
dataset: ``dataset``
The training set from which the labels will be extracted using
``dataset.get_label()``
"""
def inner(preds, dataset):
"""internal function"""
labels = dataset.get_label()
argc = argc_(func)
if argc == 2:
return func(labels, preds)
elif argc == 3:
return func(labels, preds, dataset.get_weight())
elif argc == 4:
return func(labels, preds, dataset.get_weight(), dataset.get_group())
else:
raise TypeError("Self-defined eval function should have 2, 3 or 4 arguments, got %d" % argc)
return inner
class LGBMModel(LGBMModelBase):
def __init__(self, boosting_type="gbdt", num_leaves=31, max_depth=-1,
learning_rate=0.1, n_estimators=10, max_bin=255,
subsample_for_bin=50000, objective="regression",
min_split_gain=0, min_child_weight=5, min_child_samples=10,
subsample=1, subsample_freq=1, colsample_bytree=1,
reg_alpha=0, reg_lambda=0, scale_pos_weight=1,
is_unbalance=False, seed=0, nthread=-1, silent=True,
sigmoid=1.0, huber_delta=1.0, gaussian_eta=1.0, fair_c=1.0,
poisson_max_delta_step=0.7,
max_position=20, label_gain=None,
drop_rate=0.1, skip_drop=0.5, max_drop=50,
uniform_drop=False, xgboost_dart_mode=False):
"""
Implementation of the Scikit-Learn API for LightGBM.
Parameters
----------
boosting_type : string
gbdt, traditional Gradient Boosting Decision Tree
dart, Dropouts meet Multiple Additive Regression Trees
num_leaves : int
Maximum tree leaves for base learners.
max_depth : int
Maximum tree depth for base learners, -1 means no limit.
learning_rate : float
Boosting learning rate
n_estimators : int
Number of boosted trees to fit.
max_bin : int
Number of bucketed bin for feature values
subsample_for_bin : int
Number of samples for constructing bins.
objective : string or callable
Specify the learning task and the corresponding learning objective or
a custom objective function to be used (see note below).
default: binary for LGBMClassifier, lambdarank for LGBMRanker
min_split_gain : float
Minimum loss reduction required to make a further partition on a leaf node of the tree.
min_child_weight : int
Minimum sum of instance weight(hessian) needed in a child(leaf)
min_child_samples : int
Minimum number of data need in a child(leaf)
subsample : float
Subsample ratio of the training instance.
subsample_freq : int
frequence of subsample, <=0 means no enable
colsample_bytree : float
Subsample ratio of columns when constructing each tree.
reg_alpha : float
L1 regularization term on weights
reg_lambda : float
L2 regularization term on weights
scale_pos_weight : float
Balancing of positive and negative weights.
is_unbalance : bool
Is unbalance for binary classification
seed : int
Random number seed.
nthread : int
Number of parallel threads
silent : boolean
Whether to print messages while running boosting.
sigmoid : float
Only used in binary classification and lambdarank. Parameter for sigmoid function.
huber_delta : float
Only used in regression. Parameter for Huber loss function.
gaussian_eta : float
Only used in regression. Parameter for L1 and Huber loss function.
It is used to control the width of Gaussian function to approximate hessian.
fair_c : float
Only used in regression. Parameter for Fair loss function.
poisson_max_delta_step : float
parameter used to safeguard optimization in Poisson regression.
max_position : int
Only used in lambdarank, will optimize NDCG at this position.
label_gain : list of float
Only used in lambdarank, relevant gain for labels.
For example, the gain of label 2 is 3 if using default label gains.
None (default) means use default value of CLI version: {0,1,3,7,15,31,63,...}.
drop_rate : float
Only used when boosting_type='dart'. Probablity to select dropping trees.
skip_drop : float
Only used when boosting_type='dart'. Probablity to skip dropping trees.
max_drop : int
Only used when boosting_type='dart'. Max number of dropped trees in one iteration.
uniform_drop : bool
Only used when boosting_type='dart'. If true, drop trees uniformly, else drop according to weights.
xgboost_dart_mode : bool
Only used when boosting_type='dart'. Whether use xgboost dart mode.
Note
----
A custom objective function can be provided for the ``objective``
parameter. In this case, it should have the signature
``objective(y_true, y_pred) -> grad, hess``
or ``objective(y_true, y_pred, group) -> grad, hess``:
y_true: array_like of shape [n_samples]
The target values
y_pred: array_like of shape [n_samples] or shape[n_samples * n_class]
The predicted values
group: array_like
group/query data, used for ranking task
grad: array_like of shape [n_samples] or shape[n_samples * n_class]
The value of the gradient for each sample point.
hess: array_like of shape [n_samples] or shape[n_samples * n_class]
The value of the second derivative for each sample point
for multi-class task, the y_pred is group by class_id first, then group by row_id
if you want to get i-th row y_pred in j-th class, the access way is y_pred[j*num_data+i]
and you should group grad and hess in this way as well
"""
if not SKLEARN_INSTALLED:
raise LightGBMError('Scikit-learn is required for this module')
self.boosting_type = boosting_type
self.num_leaves = num_leaves
self.max_depth = max_depth
self.learning_rate = learning_rate
self.n_estimators = n_estimators
self.max_bin = max_bin
self.subsample_for_bin = subsample_for_bin
self.objective = objective
self.min_split_gain = min_split_gain
self.min_child_weight = min_child_weight
self.min_child_samples = min_child_samples
self.subsample = subsample
self.subsample_freq = subsample_freq
self.colsample_bytree = colsample_bytree
self.reg_alpha = reg_alpha
self.reg_lambda = reg_lambda
self.scale_pos_weight = scale_pos_weight
self.is_unbalance = is_unbalance
self.seed = seed
self.nthread = nthread
self.silent = silent
self.sigmoid = sigmoid
self.huber_delta = huber_delta
self.gaussian_eta = gaussian_eta
self.fair_c = fair_c
self.poisson_max_delta_step = poisson_max_delta_step
self.max_position = max_position
self.label_gain = label_gain
self.drop_rate = drop_rate
self.skip_drop = skip_drop
self.max_drop = max_drop
self.uniform_drop = uniform_drop
self.xgboost_dart_mode = xgboost_dart_mode
self._Booster = None
self.evals_result = None
self.best_iteration = -1
self.best_score = {}
if callable(self.objective):
self.fobj = _objective_function_wrapper(self.objective)
else:
self.fobj = None
def fit(self, X, y,
sample_weight=None, init_score=None, group=None,
eval_set=None, eval_names=None, eval_sample_weight=None,
eval_init_score=None, eval_group=None,
eval_metric=None,
early_stopping_rounds=None, verbose=True,
feature_name='auto', categorical_feature='auto',
callbacks=None):
"""
Fit the gradient boosting model
Parameters
----------
X : array_like
Feature matrix
y : array_like
Labels
sample_weight : array_like
weight of training data
init_score : array_like
init score of training data
group : array_like
group data of training data
eval_set : list, optional
A list of (X, y) tuple pairs to use as a validation set for early-stopping
eval_names: list of string
Names of eval_set
eval_sample_weight : List of array
weight of eval data
eval_init_score : List of array
init score of eval data
eval_group : List of array
group data of eval data
eval_metric : str, list of str, callable, optional
If a str, should be a built-in evaluation metric to use.
If callable, a custom evaluation metric, see note for more details.
early_stopping_rounds : int
verbose : bool
If `verbose` and an evaluation set is used, writes the evaluation
feature_name : list of str, or 'auto'
Feature names
If 'auto' and data is pandas DataFrame, use data columns name
categorical_feature : list of str or int, or 'auto'
Categorical features,
type int represents index,
type str represents feature names (need to specify feature_name as well)
If 'auto' and data is pandas DataFrame, use pandas categorical columns
callbacks : list of callback functions
List of callback functions that are applied at each iteration.
See Callbacks in Python-API.md for more information.
Note
----
Custom eval function expects a callable with following functions:
``func(y_true, y_pred)``, ``func(y_true, y_pred, weight)``
or ``func(y_true, y_pred, weight, group)``.
return (eval_name, eval_result, is_bigger_better)
or list of (eval_name, eval_result, is_bigger_better)
y_true: array_like of shape [n_samples]
The target values
y_pred: array_like of shape [n_samples] or shape[n_samples * n_class] (for multi-class)
The predicted values
weight: array_like of shape [n_samples]
The weight of samples
group: array_like
group/query data, used for ranking task
eval_name: str
name of evaluation
eval_result: float
eval result
is_bigger_better: bool
is eval result bigger better, e.g. AUC is bigger_better.
for multi-class task, the y_pred is group by class_id first, then group by row_id
if you want to get i-th row y_pred in j-th class, the access way is y_pred[j*num_data+i]
"""
evals_result = {}
params = self.get_params()
params['verbose'] = -1 if self.silent else 1
if hasattr(self, 'n_classes_') and self.n_classes_ > 2:
params['num_class'] = self.n_classes_
if hasattr(self, 'eval_at'):
params['ndcg_eval_at'] = self.eval_at
if self.fobj:
params['objective'] = 'None' # objective = nullptr for unknown objective
if 'label_gain' in params and params['label_gain'] is None:
del params['label_gain'] # use default of cli version
if callable(eval_metric):
feval = _eval_function_wrapper(eval_metric)
else:
feval = None
params['metric'] = eval_metric
def _construct_dataset(X, y, sample_weight, init_score, group, params):
ret = Dataset(X, label=y, max_bin=self.max_bin, weight=sample_weight, group=group, params=params)
ret.set_init_score(init_score)
return ret
train_set = _construct_dataset(X, y, sample_weight, init_score, group, params)
valid_sets = []
if eval_set is not None:
if isinstance(eval_set, tuple):
eval_set = [eval_set]
for i, valid_data in enumerate(eval_set):
"""reduce cost for prediction training data"""
if valid_data[0] is X and valid_data[1] is y:
valid_set = train_set
else:
def get_meta_data(collection, i):
if collection is None:
return None
elif isinstance(collection, list):
return collection[i] if len(collection) > i else None
elif isinstance(collection, dict):
return collection.get(i, None)
else:
raise TypeError('eval_sample_weight, eval_init_score, and eval_group should be dict or list')
valid_weight = get_meta_data(eval_sample_weight, i)
valid_init_score = get_meta_data(eval_init_score, i)
valid_group = get_meta_data(eval_group, i)
valid_set = _construct_dataset(valid_data[0], valid_data[1], valid_weight, valid_init_score, valid_group, params)
valid_sets.append(valid_set)
self._Booster = train(params, train_set,
self.n_estimators, valid_sets=valid_sets, valid_names=eval_names,
early_stopping_rounds=early_stopping_rounds,
evals_result=evals_result, fobj=self.fobj, feval=feval,
verbose_eval=verbose, feature_name=feature_name,
categorical_feature=categorical_feature,
callbacks=callbacks)
if evals_result:
self.evals_result = evals_result
if early_stopping_rounds is not None:
self.best_iteration = self._Booster.best_iteration
self.best_score = self._Booster.best_score
# free dataset
self.booster_.free_dataset()
del train_set, valid_sets
return self
def predict(self, X, raw_score=False, num_iteration=0):
"""
Return the predicted value for each sample.
Parameters
----------
X : array_like, shape=[n_samples, n_features]
Input features matrix.
num_iteration : int
Limit number of iterations in the prediction; defaults to 0 (use all trees).
Returns
-------
predicted_result : array_like, shape=[n_samples] or [n_samples, n_classes]
"""
return self.booster_.predict(X, raw_score=raw_score, num_iteration=num_iteration)
def apply(self, X, num_iteration=0):
"""
Return the predicted leaf every tree for each sample.
Parameters
----------
X : array_like, shape=[n_samples, n_features]
Input features matrix.
num_iteration : int
Limit number of iterations in the prediction; defaults to 0 (use all trees).
Returns
-------
X_leaves : array_like, shape=[n_samples, n_trees]
"""
return self.booster_.predict(X, pred_leaf=True, num_iteration=num_iteration)
@property
def booster_(self):
"""Get the underlying lightgbm Booster of this model."""
if self._Booster is None:
raise LightGBMError('No booster found. Need to call fit beforehand.')
return self._Booster
@property
def evals_result_(self):
"""Get the evaluation results."""
if self.evals_result is None:
raise LightGBMError('No results found. Need to call fit with eval set beforehand.')
return self.evals_result
@property
def feature_importances_(self):
"""Get normailized feature importances."""
importace_array = self.booster_.feature_importance().astype(np.float32)
return importace_array / importace_array.sum()
@LGBMDeprecated('Use attribute booster_ instead.')
def booster(self):
return self.booster_
@LGBMDeprecated('Use attribute feature_importances_ instead.')
def feature_importance(self):
return self.feature_importances_
class LGBMRegressor(LGBMModel, LGBMRegressorBase):
def __init__(self, boosting_type="gbdt", num_leaves=31, max_depth=-1,
learning_rate=0.1, n_estimators=10, max_bin=255,
subsample_for_bin=50000, objective="regression",
min_split_gain=0, min_child_weight=5, min_child_samples=10,
subsample=1, subsample_freq=1, colsample_bytree=1,
reg_alpha=0, reg_lambda=0,
seed=0, nthread=-1, silent=True,
huber_delta=1.0, gaussian_eta=1.0, fair_c=1.0,
poisson_max_delta_step=0.7,
drop_rate=0.1, skip_drop=0.5, max_drop=50,
uniform_drop=False, xgboost_dart_mode=False):
super(LGBMRegressor, self).__init__(boosting_type=boosting_type, num_leaves=num_leaves,
max_depth=max_depth, learning_rate=learning_rate,
n_estimators=n_estimators, max_bin=max_bin,
subsample_for_bin=subsample_for_bin, objective=objective,
min_split_gain=min_split_gain, min_child_weight=min_child_weight,
min_child_samples=min_child_samples, subsample=subsample,
subsample_freq=subsample_freq, colsample_bytree=colsample_bytree,
reg_alpha=reg_alpha, reg_lambda=reg_lambda,
seed=seed, nthread=nthread, silent=silent,
huber_delta=huber_delta, gaussian_eta=gaussian_eta, fair_c=fair_c,
poisson_max_delta_step=poisson_max_delta_step,
drop_rate=drop_rate, skip_drop=skip_drop, max_drop=max_drop,
uniform_drop=uniform_drop, xgboost_dart_mode=xgboost_dart_mode)
def fit(self, X, y,
sample_weight=None, init_score=None,
eval_set=None, eval_names=None, eval_sample_weight=None,
eval_init_score=None,
eval_metric="l2",
early_stopping_rounds=None, verbose=True,
feature_name='auto', categorical_feature='auto', callbacks=None):
super(LGBMRegressor, self).fit(X, y, sample_weight=sample_weight,
init_score=init_score, eval_set=eval_set,
eval_names=eval_names,
eval_sample_weight=eval_sample_weight,
eval_init_score=eval_init_score,
eval_metric=eval_metric,
early_stopping_rounds=early_stopping_rounds,
verbose=verbose, feature_name=feature_name,
categorical_feature=categorical_feature,
callbacks=callbacks)
return self
class LGBMClassifier(LGBMModel, LGBMClassifierBase):
def __init__(self, boosting_type="gbdt", num_leaves=31, max_depth=-1,
learning_rate=0.1, n_estimators=10, max_bin=255,
subsample_for_bin=50000, objective="binary",
min_split_gain=0, min_child_weight=5, min_child_samples=10,
subsample=1, subsample_freq=1, colsample_bytree=1,
reg_alpha=0, reg_lambda=0, scale_pos_weight=1,
is_unbalance=False, seed=0, nthread=-1,
silent=True, sigmoid=1.0,
drop_rate=0.1, skip_drop=0.5, max_drop=50,
uniform_drop=False, xgboost_dart_mode=False):
self.classes, self.n_classes = None, None
super(LGBMClassifier, self).__init__(boosting_type=boosting_type, num_leaves=num_leaves,
max_depth=max_depth, learning_rate=learning_rate,
n_estimators=n_estimators, max_bin=max_bin,
subsample_for_bin=subsample_for_bin, objective=objective,
min_split_gain=min_split_gain, min_child_weight=min_child_weight,
min_child_samples=min_child_samples, subsample=subsample,
subsample_freq=subsample_freq, colsample_bytree=colsample_bytree,
reg_alpha=reg_alpha, reg_lambda=reg_lambda,
scale_pos_weight=scale_pos_weight, is_unbalance=is_unbalance,
seed=seed, nthread=nthread, silent=silent, sigmoid=sigmoid,
drop_rate=drop_rate, skip_drop=skip_drop, max_drop=max_drop,
uniform_drop=uniform_drop, xgboost_dart_mode=xgboost_dart_mode)
def fit(self, X, y,
sample_weight=None, init_score=None,
eval_set=None, eval_names=None, eval_sample_weight=None,
eval_init_score=None,
eval_metric="logloss",
early_stopping_rounds=None, verbose=True,
feature_name='auto', categorical_feature='auto',
callbacks=None):
self._le = LGBMLabelEncoder().fit(y)
_y = self._le.transform(y)
self.classes = self._le.classes_
self.n_classes = len(self.classes_)
if self.n_classes > 2:
# Switch to using a multiclass objective in the underlying LGBM instance
self.objective = "multiclass"
if eval_metric == 'logloss' or eval_metric == 'binary_logloss':
eval_metric = "multi_logloss"
elif eval_metric == 'error' or eval_metric == 'binary_error':
eval_metric = "multi_error"
else:
if eval_metric == 'logloss' or eval_metric == 'multi_logloss':
eval_metric = 'binary_logloss'
elif eval_metric == 'error' or eval_metric == 'multi_error':
eval_metric = 'binary_error'
if eval_set is not None:
if isinstance(eval_set, tuple):
eval_set = [eval_set]
for i, (valid_x, valid_y) in enumerate(eval_set):
if valid_x is X and valid_y is y:
eval_set[i] = (valid_x, _y)
else:
eval_set[i] = (valid_x, self._le.transform(valid_y))
super(LGBMClassifier, self).fit(X, _y, sample_weight=sample_weight,
init_score=init_score, eval_set=eval_set,
eval_names=eval_names,
eval_sample_weight=eval_sample_weight,
eval_init_score=eval_init_score,
eval_metric=eval_metric,
early_stopping_rounds=early_stopping_rounds,
verbose=verbose, feature_name=feature_name,
categorical_feature=categorical_feature,
callbacks=callbacks)
return self
def predict(self, X, raw_score=False, num_iteration=0):
class_probs = self.predict_proba(X, raw_score, num_iteration)
class_index = np.argmax(class_probs, axis=1)
return self._le.inverse_transform(class_index)
def predict_proba(self, X, raw_score=False, num_iteration=0):
"""
Return the predicted probability for each class for each sample.
Parameters
----------
X : array_like, shape=[n_samples, n_features]
Input features matrix.
num_iteration : int
Limit number of iterations in the prediction; defaults to 0 (use all trees).
Returns
-------
predicted_probability : array_like, shape=[n_samples, n_classes]
"""
class_probs = self.booster_.predict(X, raw_score=raw_score, num_iteration=num_iteration)
if self.n_classes > 2:
return class_probs
else:
return np.vstack((1. - class_probs, class_probs)).transpose()
@property
def classes_(self):
"""Get class label array."""
if self.classes is None:
raise LightGBMError('No classes found. Need to call fit beforehand.')
return self.classes
@property
def n_classes_(self):
"""Get number of classes"""
if self.n_classes is None:
raise LightGBMError('No classes found. Need to call fit beforehand.')
return self.n_classes
class LGBMRanker(LGBMModel):
def __init__(self, boosting_type="gbdt", num_leaves=31, max_depth=-1,
learning_rate=0.1, n_estimators=10, max_bin=255,
subsample_for_bin=50000, objective="lambdarank",
min_split_gain=0, min_child_weight=5, min_child_samples=10,
subsample=1, subsample_freq=1, colsample_bytree=1,
reg_alpha=0, reg_lambda=0, scale_pos_weight=1,
is_unbalance=False, seed=0, nthread=-1, silent=True,
sigmoid=1.0, max_position=20, label_gain=None,
drop_rate=0.1, skip_drop=0.5, max_drop=50,
uniform_drop=False, xgboost_dart_mode=False):
super(LGBMRanker, self).__init__(boosting_type=boosting_type, num_leaves=num_leaves,
max_depth=max_depth, learning_rate=learning_rate,
n_estimators=n_estimators, max_bin=max_bin,
subsample_for_bin=subsample_for_bin, objective=objective,
min_split_gain=min_split_gain, min_child_weight=min_child_weight,
min_child_samples=min_child_samples, subsample=subsample,
subsample_freq=subsample_freq, colsample_bytree=colsample_bytree,
reg_alpha=reg_alpha, reg_lambda=reg_lambda,
scale_pos_weight=scale_pos_weight, is_unbalance=is_unbalance,
seed=seed, nthread=nthread, silent=silent,
sigmoid=sigmoid, max_position=max_position, label_gain=label_gain,
drop_rate=drop_rate, skip_drop=skip_drop, max_drop=max_drop,
uniform_drop=uniform_drop, xgboost_dart_mode=xgboost_dart_mode)
def fit(self, X, y,
sample_weight=None, init_score=None, group=None,
eval_set=None, eval_names=None, eval_sample_weight=None,
eval_init_score=None, eval_group=None,
eval_metric='ndcg', eval_at=1,
early_stopping_rounds=None, verbose=True,
feature_name='auto', categorical_feature='auto',
callbacks=None):
"""
Most arguments like common methods except following:
eval_at : list of int
The evaulation positions of NDCG
"""
"""check group data"""
if group is None:
raise ValueError("Should set group for ranking task")
if eval_set is not None:
if eval_group is None:
raise ValueError("Eval_group cannot be None when eval_set is not None")
elif len(eval_group) != len(eval_set):
raise ValueError("Length of eval_group should equal to eval_set")
elif (isinstance(eval_group, dict) and any(i not in eval_group or eval_group[i] is None for i in range_(len(eval_group)))) \
or (isinstance(eval_group, list) and any(group is None for group in eval_group)):
raise ValueError("Should set group for all eval dataset for ranking task; if you use dict, the index should start from 0")
if eval_at is not None:
self.eval_at = eval_at
super(LGBMRanker, self).fit(X, y, sample_weight=sample_weight,
init_score=init_score, group=group,
eval_set=eval_set, eval_names=eval_names,
eval_sample_weight=eval_sample_weight,
eval_init_score=eval_init_score, eval_group=eval_group,
eval_metric=eval_metric,
early_stopping_rounds=early_stopping_rounds,
verbose=verbose, feature_name=feature_name,
categorical_feature=categorical_feature,
callbacks=callbacks)
return self
<file_sep># coding: utf-8
"""LightGBM, Light Gradient Boosting Machine.
Contributors: https://github.com/Microsoft/LightGBM/graphs/contributors
"""
from __future__ import absolute_import
from .basic import Booster, Dataset
from .callback import (early_stopping, print_evaluation, record_evaluation,
reset_parameter)
from .engine import cv, train
try:
from .sklearn import LGBMModel, LGBMRegressor, LGBMClassifier, LGBMRanker
except ImportError:
pass
try:
from .plotting import plot_importance, plot_metric, plot_tree, create_tree_digraph
except ImportError:
pass
__version__ = 0.1
__all__ = ['Dataset', 'Booster',
'train', 'cv',
'LGBMModel', 'LGBMRegressor', 'LGBMClassifier', 'LGBMRanker',
'print_evaluation', 'record_evaluation', 'reset_parameter', 'early_stopping',
'plot_importance', 'plot_metric', 'plot_tree', 'create_tree_digraph']
<file_sep>GPU Windows Compilation
=========================
This guide is for the MinGW build.
For the MSVC build with GPU, please refer to https://github.com/Microsoft/LightGBM/wiki/Installation-Guide#windows-2
# Install LightGBM GPU version in Windows (CLI / R / Python), using MinGW/gcc
This is for a vanilla installation of Boost, including full compilation steps from source without precompiled libraries.
Installation steps (depends on what you are going to do):
* Install the appropriate OpenCL SDK
* Install MinGW
* Install Boost
* Install Git
* Install cmake
* Create LightGBM binaries
* Debugging LightGBM in CLI (if GPU is crashing or any other crash reason)
If you wish to use another compiler like Visual Studio C++ compiler, you need to adapt the steps to your needs.
For this compilation tutorial, I am using AMD SDK for our OpenCL steps. However, you are free to use any OpenCL SDK you want, you just need to adjust the PATH correctly.
You will also need administrator rights. This will not work without them.
At the end, you can restore your original PATH.
---
## Modifying PATH (for newbies)
To modify PATH, just follow the pictures after going to the `Control Panel`:

Then, go to `Advanced` > `Environment Variables...`:

Under `System variables`, the variable `Path`:

---
### Antivirus Performance Impact
Does not apply to you if you do not use a third-party antivirus nor the default preinstalled antivirus on Windows.
**Windows Defender or any other antivirus will have a significant impact on the speed you will be able to perform the steps.** It is recommended to **turn them off temporarily** until you finished with building and setting up everything, then turn them back on, if you are using them.
---
## OpenCL SDK Installation
Installing the appropriate OpenCL SDK requires you to download the correct vendor source SDK. You need to know on what you are going to use LightGBM!:
* For running on Intel, get Intel SDK for OpenCL: https://software.intel.com/en-us/articles/opencl-drivers
* For running on AMD, get AMD APP SDK: http://developer.amd.com/tools-and-sdks/opencl-zone/amd-accelerated-parallel-processing-app-sdk/
* For running on NVIDIA, get CUDA Toolkit: https://developer.nvidia.com/cuda-downloads
Further reading and correspondnce table (especially if you intend to use cross-platform devices, like Intel CPU with AMD APP SDK): [GPU SDK Correspondence and Device Targeting Table](./GPU-Targets.md).
---
## MinGW correct compiler selection
If you are expecting to use LightGBM without R, you need to install MinGW. Installing MinGW is straightforward, download this: http://iweb.dl.sourceforge.net/project/mingw-w64/Toolchains%20targetting%20Win32/Personal%20Builds/mingw-builds/installer/mingw-w64-install.exe
Make sure you are using the x86_64 architecture, and do not modify anything else. You may choose a version other than the most recent one if you need a previous MinGW version.

Then, add to your PATH the following (to adjust to your MinGW version):
```
C:\Program Files\mingw-w64\x86_64-5.3.0-posix-seh-rt_v4-rev0\mingw64\bin
```
**Warning: R users (even if you do not want LightGBM for R)**
**If you have RTools and MinGW installed, and wish to use LightGBM in R, get rid of MinGW from PATH (to keep: `c:\Rtools\bin;c:\Rtools\mingw_32\bin` for 32-bit R installation, `c:\Rtools\bin;c:\Rtools\mingw_64\bin` for 64-bit R installation).**
You can check which MinGW version you are using by running the following in a command prompt: `gcc -v`:

To check whether you need 32-bit or 64-bit MinGW for R, install LightGBM as usual and check for the following:
```r
* installing *source* package 'lightgbm' ...
** libs
c:/Rtools/mingw_64/bin/g++
```
If it says `mingw_64` then you need the 64-bit version (PATH with `c:\Rtools\bin;c:\Rtools\mingw_64\bin`), otherwise you need the 32-bit version (`c:\Rtools\bin;c:\Rtools\mingw_32\bin`), the latter being a very rare and untested case.
Quick installation of LightGBM can be done using:
```r
devtools::install_github("Microsoft/LightGBM", subdir = "R-package")
```
---
## Boost Compilation
Installing Boost requires to download Boost and to install it. It takes about 10 minutes to several hours depending on your CPU speed and network speed.
We will assume an installation in `C:\boost` and a general installation (like in Unix variants: without versioning and without type tags).
There is one mandatory step to check: the compiler.
* **Warning: if you want the R installation**: If you have already MinGW in your PATH variable, get rid of it (you will link to the wrong compiler otherwise).
* **Warning: if you want the CLI installation**: if you have already Rtools in your PATH variable, get rid of it (you will link to the wrong compiler otherwise).
* R installation must have Rtools in PATH
* CLI / Python installation must have MinGW (not Rtools) in PATH
In addition, assuming you are going to use `C:\boost` for the folder path, you should add now already the following to PATH: `C:\boost\boost-build\bin;C:\boost\boost-build\include\boost`. Adjust `C:\boost` if you install it elsewhere.
We can now start downloading and compiling the required Boost libraries:
* Download Boost here: http://www.boost.org/users/history/version_1_63_0.html (boost_1_63_0.zip).
* Extract the archive to `C:\boost`.
* Open a command prompt, and run `cd C:\boost\boost_1_63_0\tools\build`.
* In command prompt, run `bootstrap.bat gcc`.
* In command prompt, run `b2 install --prefix="C:\boost\boost-build" toolset=gcc`.
* In command prompt, run `cd C:\boost\boost_1_63_0`.
To build the Boost libraries, you have two choices for command prompt:
* If you have only one single core, you can use the default `b2 install --build_dir="C:\boost\boost-build" --prefix="C:\boost\boost-build" toolset=gcc --with=filesystem,system threading=multi --layout=system release`.
* If you want to do a multithreaded library building (faster), add -j N by replacing N by the number of cores/threads you have. For instance, for 2 cores, you would do `b2 install --build_dir="C:\boost\boost-build" --prefix="C:\boost\boost-build" toolset=gcc --with=filesystem,system threading=multi --layout=system release -j 2`
Ignore all the errors popping up, like Python, etc., they do not matter for us.
Your folder should look like this at the end (not fully detailed):
```
- C
|--- boost
|------ boost_1_63_0
|--------- some folders and files
|------ boost-build
|--------- bin
|--------- include
|------------ boost
|--------- lib
|--------- share
```
This is what you should (approximately) get at the end of Boost compilation:

---
## Git Installation
Installing Git for Windows is straightforward, use the following link: https://git-for-windows.github.io/

Then, click on the big Download button, you can't miss it.
Now, we can fetch LightGBM repository for GitHub. Run Git Bash and the following command:
```
cd C:/
mkdir github_repos
cd github_repos
git clone --recursive https://github.com/Microsoft/LightGBM
```
Your LightGBM repository copy should now be under `C:\github_repos\LightGBM`. You are free to use any folder you want, but you have to adapt.
Keep Git Bash open.
---
## cmake Installation, Configuration, Generation
**CLI / Python users only**
Installing cmake requires one download first and then a lot of configuration for LightGBM:

* Download cmake 3.8.0 here: https://cmake.org/download/.
* Install cmake.
* Run cmake-gui.
* Select the folder where you put LightGBM for `Where is the source code`, default using our steps would be `C:/github_repos/LightGBM`.
* Copy the folder name, and add `/build` for "Where to build the binaries", default using our steps would be `C:/github_repos/LightGBM/build`.
* Click `Configure`.


* Lookup for `USE_GPU` and check the checkbox

* Click `Configure`
You should get (approximately) the following after clicking Configure:

```
Looking for CL_VERSION_2_0
Looking for CL_VERSION_2_0 - found
Found OpenCL: C:/Windows/System32/OpenCL.dll (found version "2.0")
OpenCL include directory:C:/Program Files (x86)/AMD APP SDK/3.0/include
Boost version: 1.63.0
Found the following Boost libraries:
filesystem
system
Configuring done
```
* Click `Generate` to get the following message:
```
Generating done
```
This is straightforward, as cmake is providing a large help into locating the correct elements.
---
## LightGBM Compilation (CLI: final step)
### Installation in CLI
**CLI / Python users**
Creating LightGBM libraries is very simple as all the important and hard steps were done before.
You can do everything in the Git Bash console you left open:
* If you closed Git Bash console previously, run this to get back to the build folder: `cd C:/github_repos/LightGBM/build`
* If you did not close the Git Bash console previously, run this to get to the build folder: `cd LightGBM/build`
* Setup MinGW as make using `alias make='mingw32-make'` (otherwise, beware error and name clash!).
* In Git Bash, run `make` and see LightGBM being installing!

If everything was done correctly, you now compiled CLI LightGBM with GPU support!
### Testing in CLI
You can now test LightGBM directly in CLI in a **command prompt** (not Git Bash):
```
cd C:/github_repos/LightGBM/examples/binary_classification
"../../lightgbm.exe" config=train.conf data=binary.train valid=binary.test objective=binary device=gpu
```

Congratulations for reaching this stage!
To learn how to target a correct CPU or GPU for training, please see: [GPU SDK Correspondence and Device Targeting Table](./GPU-Targets.md).
---
## LightGBM Setup and Installation for Python (Python: final step)
### Installation in Python
**Python users, extra steps**
Installing in Python is as straightforward as CLI. Assuming you already have `numpy`, `scipy`, `scikit-learn`, and `setuptools`, run the following in the Git Console:
```
cd C:/github_repos/LightGBM/python-package/
python setup.py install
```

### Testing in Python
You can try to run the following demo script in Python to test if it works:
```python
import lightgbm as lgb
import pandas as pd
import os
# load or create your dataset
print('Load data...')
os.chdir('C:/github_repos/LightGBM/examples/regression')
df_train = pd.read_csv('regression.train', header=None, sep='\t')
df_test = pd.read_csv('regression.test', header=None, sep='\t')
y_train = df_train[0].values
y_test = df_test[0].values
X_train = df_train.drop(0, axis=1).values
X_test = df_test.drop(0, axis=1).values
# create dataset for lightgbm
lgb_train = lgb.Dataset(X_train, y_train)
lgb_eval = lgb.Dataset(X_test, y_test, reference=lgb_train)
# specify your configurations as a dict
params = {
'task': 'train',
'objective': 'regression',
'metric': 'l2',
'verbose': 2,
'device': 'gpu'
}
print('Start training...')
# train
gbm = lgb.train(params,
lgb_train,
num_boost_round=20,
valid_sets=lgb_eval,
early_stopping_rounds=5)
```

Congratulations for reaching this stage!
To learn how to target a correct CPU or GPU for training, please see: [GPU SDK Correspondence and Device Targeting Table](./GPU-Targets.md).
---
## LightGBM Setup and Installation for R (R: final step)
### Preparation for R
**R users**
This gets a bit complicated for this step.
First of all, you need to to find the correct paths for the following, and keep them in a notepad:
* `BOOST_INCLUDE_DIR = "C:/boost/boost-build/include"`: if you followed the instructions, it is `C:/boost/boost-build/include`.
* `BOOST_LIBRARY = "C:/boost/boost-build/lib"`: if you followed the instructions, it is `C:/boost/boost-build/lib`.
* `OpenCL_INCLUDE_DIR = "C:/Program Files (x86)/AMD APP SDK/3.0/include"`: this varies, it must be the OpenCL SDK folder containing the file `CL/CL.h` (caps do not matter). For instance, using AMD APP SDK, it becomes `C:/Program Files (x86)/AMD APP SDK/3.0/include`.
* `OpenCL_LIBRARY = "C:/Program Files (x86)/AMD APP SDK/3.0/lib/x86_64"`: this varies, it must be the OpenCL SDK folder containing the file `OpenCL.lib` (caps do not matter). For instance, using AMD APP SDK, it becomes `C:/Program Files (x86)/AMD APP SDK/3.0/lib/x86_64`.
Second, you need to find out where is `Makeconf`, as it is the essential file you will need to use to specify the PATH for R. Run the following code to get the file path to your `Makeconf` file:
```r
file.path(R.home("etc"), "Makeconf"))
```
For instance, `"C:/PROGRA~1/MIE74D~1/RCLIEN~1/R_SERVER/etc/Makeconf"` means `"C:\Program Files\Microsoft\R_Client\R_SERVER\etc\Makeconf"`.
Third, edit the `Makeconf` file **as an Administrator**. Remember the first step we had to do where we store four different values in a notepad? We apply them right now.
For instance, for this installation and using AMD OpenCL SDK, we are doing the following below `LINKFLAGS`:
```r
BOOST_INCLUDE_DIR = "C:/boost/boost-build/include"
BOOST_LIBRARY = "C:/boost/boost-build/lib"
OpenCL_INCLUDE_DIR = "C:/Program Files (x86)/AMD APP SDK/3.0/include"
OpenCL_LIBRARY = "C:/Program Files (x86)/AMD APP SDK/3.0/lib/x86_64"
```

From there, you have two solutions:
* Installation Method 1 (hard): Use your local LightGBM repository with the latest and recent development features
* Installation Method 2 (easy): Use ez_lgb, [Laurae2/LightGBM 's repository](https://github.com/Laurae2/LightGBM) for installing LightGBM easily, but it might not be up to date. It uses compute to patch boostorg/compute#704 (boostorg/compute@6de7f64)
### Installation Method 1
Edit 1 to do: you need to include proper GPU compilation support to the R package by adding the following to `R-package\src\lightgbm-all.cpp`:
```r
// gpu support
#include "../../src/treelearner/gpu_tree_learner.cpp"
```
The `lightgbm-all.cpp` becomes:
```r
// application
#include "../../src/application/application.cpp"
// boosting
#include "../../src/boosting/boosting.cpp"
#include "../../src/boosting/gbdt.cpp"
// io
#include "../../src/io/bin.cpp"
#include "../../src/io/config.cpp"
#include "../../src/io/dataset.cpp"
#include "../../src/io/dataset_loader.cpp"
#include "../../src/io/metadata.cpp"
#include "../../src/io/parser.cpp"
#include "../../src/io/tree.cpp"
// metric
#include "../../src/metric/dcg_calculator.cpp"
#include "../../src/metric/metric.cpp"
// network
#include "../../src/network/linker_topo.cpp"
#include "../../src/network/linkers_socket.cpp"
#include "../../src/network/network.cpp"
// objective
#include "../../src/objective/objective_function.cpp"
// treelearner
#include "../../src/treelearner/data_parallel_tree_learner.cpp"
#include "../../src/treelearner/feature_parallel_tree_learner.cpp"
#include "../../src/treelearner/serial_tree_learner.cpp"
#include "../../src/treelearner/tree_learner.cpp"
#include "../../src/treelearner/voting_parallel_tree_learner.cpp"
// c_api
#include "../../src/c_api.cpp"
// gpu support
#include "../../src/treelearner/gpu_tree_learner.cpp"
```
Edit 2 to do: you need to edit the `Makevars.win` in `R-package\src` appropriately by overwriting the following flags (`LGBM_RFLAGS`, `PKG_CPPFLAGS`, `PKG_LIBS`) with the following:
```r
LGBM_RFLAGS = -DUSE_SOCKET -DUSE_GPU=1
PKG_CPPFLAGS= -I$(PKGROOT)/include -I$(BOOST_INCLUDE_DIR) -I$(OpenCL_INCLUDE_DIR) -I../compute/include $(LGBM_RFLAGS)
PKG_LIBS = $(SHLIB_OPENMP_CFLAGS) $(SHLIB_PTHREAD_FLAGS) -lws2_32 -liphlpapi -L$(BOOST_LIBRARY) -lboost_filesystem -lboost_system -L$(OpenCL_LIBRARY) -lOpenCL
```
Your `Makevars.win` will look like this:

Or, copy & paste this:
```r
# package root
PKGROOT=../../
ENABLE_STD_THREAD=1
CXX_STD = CXX11
LGBM_RFLAGS = -DUSE_SOCKET -DUSE_GPU=1
PKG_CPPFLAGS= -I$(PKGROOT)/include -I$(BOOST_INCLUDE_DIR) -I$(OpenCL_INCLUDE_DIR) -I../compute/include $(LGBM_RFLAGS)
PKG_CXXFLAGS= $(SHLIB_OPENMP_CFLAGS) $(SHLIB_PTHREAD_FLAGS) -std=c++11
PKG_LIBS = $(SHLIB_OPENMP_CFLAGS) $(SHLIB_PTHREAD_FLAGS) -lws2_32 -liphlpapi -L$(BOOST_LIBRARY) -lboost_filesystem -lboost_system -L$(OpenCL_LIBRARY) -lOpenCL
OBJECTS = ./lightgbm-all.o ./lightgbm_R.o
```
Now, we need to install LightGBM as usual:
* Open an interactive R console.
* Assuming you have the LightGBM folder in `C:/LightGBM`, run `devtools::install("C:/github_repos/LightGBM/R-package")`.

### Installation Method 2
This is very simple, as you only need to open an R interactive console and run:
```r
devtools::install_github("Laurae2/LightGBM", subdir = "R-package")
```
It will install automatically LightGBM for R with GPU support, without the need to edit manually the `Makevars.win` and `lightgbm-all.cpp`.
Laurae's LightGBM has all the steps of installation method 1 done for you. Therefore, this is a GPU-only version. You can check how many days it is behind Microsoft/LightGBM master branch and the latest master branch commit made here:

Self-contained packages are not provided are untested. It might work but it was untested, and requires to modify the `fullcode` files instead of the regular files (`lightgbm-fullcode.cpp` and `Makevars_fullcode.win`).
### Testing in R
When you run LightGBM with a specific amount of bins, it will create the appropriate kernels. This will be obviously leading to poor performance during the first usages of LightGBM. But once the kernels are built for the number of bins you are using, you do not have to care about building them again.
Test GPU support with the following:
```r
library(lightgbm)
data(agaricus.train, package = "lightgbm")
train <- agaricus.train
dtrain <- lgb.Dataset(train$data, label = train$label)
data(agaricus.test, package = "lightgbm")
test <- agaricus.test
dtest <- lgb.Dataset.create.valid(dtrain, test$data, label = test$label)
params <- list(objective = "regression", metric = "l2", device = "gpu")
valids <- list(test = dtest)
model <- lgb.train(params,
dtrain,
100,
valids,
min_data = 1,
learning_rate = 1,
early_stopping_rounds = 10)
```

Congratulations for reaching this stage!
To learn how to target a correct CPU or GPU for training, please see: [GPU SDK Correspondence and Device Targeting Table](./GPU-Targets.md).
## Debugging LightGBM crashes in CLI
Now that you compiled LightGBM, you try it... and you always see a segmentation fault or an undocumented crash with GPU support:

Please check you are using the right device and whether it works with the default `gpu_device_id = 0` and `gpu_platform_id = 0`. If it still does not work with the default values, then you should follow all the steps below.
You will have to redo the compilation steps for LightGBM to add debugging mode. This involves:
* Deleting `C:/github_repos/LightGBM/build` folder
* Deleting `lightgbm.exe`, `lib_lightgbm.dll`, and `lib_lightgbm.dll.a` files

Once you removed the file, go into cmake, and follow the usual steps. Before clicking "Generate", click on "Add Entry":

In addition, click on Configure and Generate:

And then, follow the regular LightGBM CLI installation from there.
Once you have installed LightGBM CLI, assuming your LightGBM is in `C:\github_repos\LightGBM`, open a command prompt and run the following:
`gdb --args "../../lightgbm.exe" config=train.conf data=binary.train valid=binary.test objective=binary device=gpu`

Type `run` and Enter key.
You will probably get something similar to this:
```
[LightGBM] [Info] This is the GPU trainer!!
[LightGBM] [Info] Total Bins 6143
[LightGBM] [Info] Number of data: 7000, number of used features: 28
[New Thread 105220.0x1a62c]
[LightGBM] [Info] Using GPU Device: Oland, Vendor: Advanced Micro Devices, Inc.
[LightGBM] [Info] Compiling OpenCL Kernel with 256 bins...
Program received signal SIGSEGV, Segmentation fault.
0x00007ffbb37c11f1 in strlen () from C:\Windows\system32\msvcrt.dll
(gdb)
```
There, write `backtrace` and Enter key as many times as gdb requests two choices:
```
Program received signal SIGSEGV, Segmentation fault.
0x00007ffbb37c11f1 in strlen () from C:\Windows\system32\msvcrt.dll
(gdb) backtrace
#0 0x00007ffbb37c11f1 in strlen () from C:\Windows\system32\msvcrt.dll
#1 0x000000000048bbe5 in std::char_traits<char>::length (__s=0x0)
at C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/x86_64-w64-mingw32/include/c++/bits/char_traits.h:267
#2 std::operator+<char, std::char_traits<char>, std::allocator<char> > (__rhs="\\", __lhs=0x0)
at C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/x86_64-w64-mingw32/include/c++/bits/basic_string.tcc:1157
#3 boost::compute::detail::appdata_path[abi:cxx11]() () at C:/boost/boost-build/include/boost/compute/detail/path.hpp:38
#4 0x000000000048eec3 in boost::compute::detail::program_binary_path (hash="d27987d5bd61e2d28cd32b8d7a7916126354dc81", create=create@entry=false)
at C:/boost/boost-build/include/boost/compute/detail/path.hpp:46
#5 0x00000000004913de in boost::compute::program::load_program_binary (hash="d27987d5bd61e2d28cd32b8d7a7916126354dc81", ctx=...)
at C:/boost/boost-build/include/boost/compute/program.hpp:605
#6 0x0000000000490ece in boost::compute::program::build_with_source (
source="\n#ifndef _HISTOGRAM_256_KERNEL_\n#define _HISTOGRAM_256_KERNEL_\n\n#pragma OPENCL EXTENSION cl_khr_local_int32_base_atomics : enable\n#pragma OPENC
L EXTENSION cl_khr_global_int32_base_atomics : enable\n\n//"..., context=...,
options=" -D POWER_FEATURE_WORKGROUPS=5 -D USE_CONSTANT_BUF=0 -D USE_DP_FLOAT=0 -D CONST_HESSIAN=0 -cl-strict-aliasing -cl-mad-enable -cl-no-signed-zeros -c
l-fast-relaxed-math") at C:/boost/boost-build/include/boost/compute/program.hpp:549
#7 0x0000000000454339 in LightGBM::GPUTreeLearner::BuildGPUKernels () at C:\LightGBM\src\treelearner\gpu_tree_learner.cpp:583
#8 0x00000000636044f2 in libgomp-1!GOMP_parallel () from C:\Program Files\mingw-w64\x86_64-5.3.0-posix-seh-rt_v4-rev0\mingw64\bin\libgomp-1.dll
#9 0x0000000000455e7e in LightGBM::GPUTreeLearner::BuildGPUKernels (this=this@entry=0x3b9cac0)
at C:\LightGBM\src\treelearner\gpu_tree_learner.cpp:569
#10 0x0000000000457b49 in LightGBM::GPUTreeLearner::InitGPU (this=0x3b9cac0, platform_id=<optimized out>, device_id=<optimized out>)
at C:\LightGBM\src\treelearner\gpu_tree_learner.cpp:720
#11 0x0000000000410395 in LightGBM::GBDT::ResetTrainingData (this=0x1f26c90, config=<optimized out>, train_data=0x1f28180, objective_function=0x1f280e0,
training_metrics=std::vector of length 2, capacity 2 = {...}) at C:\LightGBM\src\boosting\gbdt.cpp:98
#12 0x0000000000402e93 in LightGBM::Application::InitTrain (this=this@entry=0x23f9d0) at C:\LightGBM\src\application\application.cpp:213
---Type <return> to continue, or q <return> to quit---
#13 0x00000000004f0b55 in LightGBM::Application::Run (this=0x23f9d0) at C:/LightGBM/include/LightGBM/application.h:84
#14 main (argc=6, argv=0x1f21e90) at C:\LightGBM\src\main.cpp:7
```
Right-click the command prompt, click "Mark", and select all the text from the first line (with the command prompt containing gdb) to the last line printed, containing all the log, such as:
```
C:\LightGBM\examples\binary_classification>gdb --args "../../lightgbm.exe" config=train.conf data=binary.train valid=binary.test objective=binary device
=gpu
GNU gdb (GDB) 7.10.1
Copyright (C) 2015 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-w64-mingw32".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ../../lightgbm.exe...done.
(gdb) run
Starting program: C:\LightGBM\lightgbm.exe "config=train.conf" "data=binary.train" "valid=binary.test" "objective=binary" "device=gpu"
[New Thread 105220.0x199b8]
[New Thread 105220.0x783c]
[Thread 105220.0x783c exited with code 0]
[LightGBM] [Info] Finished loading parameters
[New Thread 105220.0x19490]
[New Thread 105220.0x1a71c]
[New Thread 105220.0x19a24]
[New Thread 105220.0x4fb0]
[Thread 105220.0x4fb0 exited with code 0]
[LightGBM] [Info] Loading weights...
[New Thread 105220.0x19988]
[Thread 105220.0x19988 exited with code 0]
[New Thread 105220.0x1a8fc]
[Thread 105220.0x1a8fc exited with code 0]
[LightGBM] [Info] Loading weights...
[New Thread 105220.0x1a90c]
[Thread 105220.0x1a90c exited with code 0]
[LightGBM] [Info] Finished loading data in 1.011408 seconds
[LightGBM] [Info] Number of positive: 3716, number of negative: 3284
[LightGBM] [Info] This is the GPU trainer!!
[LightGBM] [Info] Total Bins 6143
[LightGBM] [Info] Number of data: 7000, number of used features: 28
[New Thread 105220.0x1a62c]
[LightGBM] [Info] Using GPU Device: Oland, Vendor: Advanced Micro Devices, Inc.
[LightGBM] [Info] Compiling OpenCL Kernel with 256 bins...
Program received signal SIGSEGV, Segmentation fault.
0x00007ffbb37c11f1 in strlen () from C:\Windows\system32\msvcrt.dll
(gdb) backtrace
#0 0x00007ffbb37c11f1 in strlen () from C:\Windows\system32\msvcrt.dll
#1 0x000000000048bbe5 in std::char_traits<char>::length (__s=0x0)
at C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/x86_64-w64-mingw32/include/c++/bits/char_traits.h:267
#2 std::operator+<char, std::char_traits<char>, std::allocator<char> > (__rhs="\\", __lhs=0x0)
at C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/x86_64-w64-mingw32/include/c++/bits/basic_string.tcc:1157
#3 boost::compute::detail::appdata_path[abi:cxx11]() () at C:/boost/boost-build/include/boost/compute/detail/path.hpp:38
#4 0x000000000048eec3 in boost::compute::detail::program_binary_path (hash="d27987d5bd61e2d28cd32b8d7a7916126354dc81", create=create@entry=false)
at C:/boost/boost-build/include/boost/compute/detail/path.hpp:46
#5 0x00000000004913de in boost::compute::program::load_program_binary (hash="d27987d5bd61e2d28cd32b8d7a7916126354dc81", ctx=...)
at C:/boost/boost-build/include/boost/compute/program.hpp:605
#6 0x0000000000490ece in boost::compute::program::build_with_source (
source="\n#ifndef _HISTOGRAM_256_KERNEL_\n#define _HISTOGRAM_256_KERNEL_\n\n#pragma OPENCL EXTENSION cl_khr_local_int32_base_atomics : enable\n#pragma OPENC
L EXTENSION cl_khr_global_int32_base_atomics : enable\n\n//"..., context=...,
options=" -D POWER_FEATURE_WORKGROUPS=5 -D USE_CONSTANT_BUF=0 -D USE_DP_FLOAT=0 -D CONST_HESSIAN=0 -cl-strict-aliasing -cl-mad-enable -cl-no-signed-zeros -c
l-fast-relaxed-math") at C:/boost/boost-build/include/boost/compute/program.hpp:549
#7 0x0000000000454339 in LightGBM::GPUTreeLearner::BuildGPUKernels () at C:\LightGBM\src\treelearner\gpu_tree_learner.cpp:583
#8 0x00000000636044f2 in libgomp-1!GOMP_parallel () from C:\Program Files\mingw-w64\x86_64-5.3.0-posix-seh-rt_v4-rev0\mingw64\bin\libgomp-1.dll
#9 0x0000000000455e7e in LightGBM::GPUTreeLearner::BuildGPUKernels (this=this@entry=0x3b9cac0)
at C:\LightGBM\src\treelearner\gpu_tree_learner.cpp:569
#10 0x0000000000457b49 in LightGBM::GPUTreeLearner::InitGPU (this=0x3b9cac0, platform_id=<optimized out>, device_id=<optimized out>)
at C:\LightGBM\src\treelearner\gpu_tree_learner.cpp:720
#11 0x0000000000410395 in LightGBM::GBDT::ResetTrainingData (this=0x1f26c90, config=<optimized out>, train_data=0x1f28180, objective_function=0x1f280e0,
training_metrics=std::vector of length 2, capacity 2 = {...}) at C:\LightGBM\src\boosting\gbdt.cpp:98
#12 0x0000000000402e93 in LightGBM::Application::InitTrain (this=this@entry=0x23f9d0) at C:\LightGBM\src\application\application.cpp:213
---Type <return> to continue, or q <return> to quit---
#13 0x00000000004f0b55 in LightGBM::Application::Run (this=0x23f9d0) at C:/LightGBM/include/LightGBM/application.h:84
#14 main (argc=6, argv=0x1f21e90) at C:\LightGBM\src\main.cpp:7
```
And open an issue in GitHub here with that log: https://github.com/Microsoft/LightGBM/issues
<file_sep># Parameters
This is a page contains all parameters in LightGBM.
***List of other Helpful Links***
* [Python API Reference](./Python-API.md)
* [Parameters Tuning](./Parameters-tuning.md)
***External Links***
* [Laurae++ Interactive Documentation](https://sites.google.com/view/lauraepp/parameters)
***Update of 04/13/2017***
Default values for the following parameters have changed:
* min_data_in_leaf = 100 => 20
* min_sum_hessian_in_leaf = 10 => 1e-3
* num_leaves = 127 => 31
* num_iterations = 10 => 100
## Parameter format
The parameter format is `key1=value1 key2=value2 ... ` . And parameters can be set both in config file and command line. By using command line, parameters should not have spaces before and after `=`. By using config files, one line can only contain one parameter. you can use `#` to comment. If one parameter appears in both command line and config file, LightGBM will use the parameter in command line.
## Core Parameters
* `config`, default=`""`, type=string, alias=`config_file`
* path of config file
* `task`, default=`train`, type=enum, options=`train`,`prediction`
* `train` for training
* `prediction` for prediction.
* `application`, default=`regression`, type=enum, options=`regression`,`regression_l1`,`huber`,`fair`,`poisson`,`binary`,`lambdarank`,`multiclass`, alias=`objective`,`app`
* `regression`, regression application
* `regression_l2`, L2 loss, alias=`mean_squared_error`,`mse`
* `regression_l1`, L1 loss, alias=`mean_absolute_error`,`mae`
* `huber`, [Huber loss](https://en.wikipedia.org/wiki/Huber_loss "Huber loss - Wikipedia")
* `fair`, [Fair loss](https://www.kaggle.com/c/allstate-claims-severity/discussion/24520)
* `poisson`, [Poisson regression](https://en.wikipedia.org/wiki/Poisson_regression "Poisson regression")
* `binary`, binary classification application
* `lambdarank`, [lambdarank](https://pdfs.semanticscholar.org/fc9a/e09f9ced555558fdf1e997c0a5411fb51f15.pdf) application
* `multiclass`, multi-class classification application, should set `num_class` as well
* `boosting`, default=`gbdt`, type=enum, options=`gbdt`,`dart`, alias=`boost`,`boosting_type`
* `gbdt`, traditional Gradient Boosting Decision Tree
* `dart`, [Dropouts meet Multiple Additive Regression Trees](https://arxiv.org/abs/1505.01866)
* `goss`, Gradient-based One-Side Sampling
* `data`, default=`""`, type=string, alias=`train`,`train_data`
* training data, LightGBM will train from this data
* `valid`, default=`""`, type=multi-string, alias=`test`,`valid_data`,`test_data`
* validation/test data, LightGBM will output metrics for these data
* support multi validation data, separate by `,`
* `num_iterations`, default=`100`, type=int, alias=`num_iteration`,`num_tree`,`num_trees`,`num_round`,`num_rounds`
* number of boosting iterations
* note: `num_tree` here equal with `num_iterations`. For multi-class, it actually learns `num_class * num_iterations` trees.
* note: For python/R package, cannot use this parameters to control number of iterations.
* `learning_rate`, default=`0.1`, type=double, alias=`shrinkage_rate`
* shrinkage rate
* in `dart`, it also affects normalization weights of dropped trees
* `num_leaves`, default=`31`, type=int, alias=`num_leaf`
* number of leaves in one tree
* `tree_learner`, default=`serial`, type=enum, options=`serial`,`feature`,`data`
* `serial`, single machine tree learner
* `feature`, feature parallel tree learner
* `data`, data parallel tree learner
* Refer to [Parallel Learning Guide](./Parallel-Learning-Guide.md) to get more details.
* `num_threads`, default=OpenMP_default, type=int, alias=`num_thread`,`nthread`
* Number of threads for LightGBM.
* For the best speed, set this to the number of **real CPU cores**, not the number of threads (most CPU using [hyper-threading](https://en.wikipedia.org/wiki/Hyper-threading) to generate 2 threads per CPU core).
* For parallel learning, should not use full CPU cores since this will cause poor performance for the network.
* `device`, default=`cpu`, options=`cpu`,`gpu`
* Choose device for the tree learning, can use gpu to achieve the faster learning.
* Note: 1. Recommend use the smaller `max_bin`(e.g `63`) to get the better speed up. 2. For the faster speed, GPU use 32-bit float point to sum up by default, may affect the accuracy for some tasks. You can set `gpu_use_dp=true` to enable 64-bit float point, but it will slow down the training. 3. Refer to [Installation Guide](https://github.com/Microsoft/LightGBM/wiki/Installation-Guide#with-gpu-support) to build with GPU .
## Learning control parameters
* `max_depth`, default=`-1`, type=int
* Limit the max depth for tree model. This is used to deal with overfit when #data is small. Tree still grow by leaf-wise.
* `< 0` means no limit
* `min_data_in_leaf`, default=`20`, type=int, alias=`min_data_per_leaf` , `min_data`
* Minimal number of data in one leaf. Can use this to deal with over-fit.
* `min_sum_hessian_in_leaf`, default=`1e-3`, type=double, alias=`min_sum_hessian_per_leaf`, `min_sum_hessian`, `min_hessian`
* Minimal sum hessian in one leaf. Like `min_data_in_leaf`, can use this to deal with over-fit.
* `feature_fraction`, default=`1.0`, type=double, `0.0 < feature_fraction < 1.0`, alias=`sub_feature`
* LightGBM will random select part of features on each iteration if `feature_fraction` smaller than `1.0`. For example, if set to `0.8`, will select 80% features before training each tree.
* Can use this to speed up training
* Can use this to deal with over-fit
* `feature_fraction_seed`, default=`2`, type=int
* Random seed for feature fraction.
* `bagging_fraction`, default=`1.0`, type=double, , `0.0 < bagging_fraction < 1.0`, alias=`sub_row`
* Like `feature_fraction`, but this will random select part of data
* Can use this to speed up training
* Can use this to deal with over-fit
* Note: To enable bagging, should set `bagging_freq` to a non zero value as well
* `bagging_freq`, default=`0`, type=int
* Frequency for bagging, `0` means disable bagging. `k` means will perform bagging at every `k` iteration.
* Note: To enable bagging, should set `bagging_fraction` as well
* `bagging_seed` , default=`3`, type=int
* Random seed for bagging.
* `early_stopping_round` , default=`0`, type=int, alias=`early_stopping_rounds`,`early_stopping`
* Will stop training if one metric of one validation data doesn't improve in last `early_stopping_round` rounds.
* `lambda_l1` , default=`0`, type=double
* l1 regularization
* `lambda_l2` , default=`0`, type=double
* l2 regularization
* `min_gain_to_split` , default=`0`, type=double
* The minimal gain to perform split
* `drop_rate`, default=`0.1`, type=double
* only used in `dart`
* `skip_drop`, default=`0.5`, type=double
* only used in `dart`, probability of skipping drop
* `max_drop`, default=`50`, type=int
* only used in `dart`, max number of dropped trees on one iteration. `<=0` means no limit.
* `uniform_drop`, default=`false`, type=bool
* only used in `dart`, true if want to use uniform drop
* `xgboost_dart_mode`, default=`false`, type=bool
* only used in `dart`, true if want to use xgboost dart mode
* `drop_seed`, default=`4`, type=int
* only used in `dart`, used to random seed to choose dropping models.
* `top_rate`, default=`0.2`, type=double
* only used in `goss`, the retain ratio of large gradient data
* `other_rate`, default=`0.1`, type=int
* only used in `goss`, the retain ratio of small gradient data
## IO parameters
* `max_bin`, default=`255`, type=int
* max number of bin that feature values will bucket in. Small bin may reduce training accuracy but may increase general power (deal with over-fit).
* LightGBM will auto compress memory according `max_bin`. For example, LightGBM will use `uint8_t` for feature value if `max_bin=255`.
* `data_random_seed`, default=`1`, type=int
* random seed for data partition in parallel learning(not include feature parallel).
* `output_model`, default=`LightGBM_model.txt`, type=string, alias=`model_output`,`model_out`
* file name of output model in training.
* `input_model`, default=`""`, type=string, alias=`model_input`,`model_in`
* file name of input model.
* for prediction task, will prediction data using this model.
* for train task, will continued train from this model.
* `output_result`, default=`LightGBM_predict_result.txt`, type=string, alias=`predict_result`,`prediction_result`
* file name of prediction result in prediction task.
* `is_pre_partition`, default=`false`, type=bool
* used for parallel learning(not include feature parallel).
* `true` if training data are pre-partitioned, and different machines using different partition.
* `is_sparse`, default=`true`, type=bool, alias=`is_enable_sparse`
* used to enable/disable sparse optimization. Set to `false` to disable sparse optimization.
* `two_round`, default=`false`, type=bool, alias=`two_round_loading`,`use_two_round_loading`
* by default, LightGBM will map data file to memory and load features from memory. This will provide faster data loading speed. But it may out of memory when the data file is very big.
* set this to `true` if data file is too big to fit in memory.
* `save_binary`, default=`false`, type=bool, alias=`is_save_binary`,`is_save_binary_file`
* set this to `true` will save the data set(include validation data) to a binary file. Speed up the data loading speed for the next time.
* `verbosity`, default=`1`, type=int, alias=`verbose`
* `<0` = Fatel, `=0` = Error(Warn), `>0` = Info
* `header`, default=`false`, type=bool, alias=`has_header`
* `true` if input data has header
* `label`, default=`""`, type=string, alias=`label_column`
* specific the label column
* Use number for index, e.g. `label=0` means column_0 is the label
* Add a prefix `name:` for column name, e.g. `label=name:is_click`
* `weight`, default=`""`, type=string, alias=`weight_column`
* specific the weight column
* Use number for index, e.g. `weight=0` means column_0 is the weight
* Add a prefix `name:` for column name, e.g. `weight=name:weight`
* Note: Index start from `0`. And it doesn't count the label column when passing type is Index. e.g. when label is column_0, and weight is column_1, the correct parameter is `weight=0`.
* `query`, default=`""`, type=string, alias=`query_column`,`group`,`group_column`
* specific the query/group id column
* Use number for index, e.g. `query=0` means column_0 is the query id
* Add a prefix `name:` for column name, e.g. `query=name:query_id`
* Note: Data should group by query_id. Index start from `0`. And it doesn't count the label column when passing type is Index. e.g. when label is column_0, and query_id is column_1, the correct parameter is `query=0`.
* `ignore_column`, default=`""`, type=string, alias=`ignore_feature`,`blacklist`
* specific some ignore columns in training
* Use number for index, e.g. `ignore_column=0,1,2` means column_0, column_1 and column_2 will be ignored.
* Add a prefix `name:` for column name, e.g. `ignore_column=name:c1,c2,c3` means c1, c2 and c3 will be ignored.
* Note: Index start from `0`. And it doesn't count the label column.
* `categorical_feature`, default=`""`, type=string, alias=`categorical_column`,`cat_feature`,`cat_column`
* specific categorical features
* Use number for index, e.g. `categorical_feature=0,1,2` means column_0, column_1 and column_2 are categorical features.
* Add a prefix `name:` for column name, e.g. `categorical_feature=name:c1,c2,c3` means c1, c2 and c3 are categorical features.
* Note: Only support categorical with `int` type. Index start from `0`. And it doesn't count the label column.
* `predict_raw_score`, default=`false`, type=bool, alias=`raw_score`,`is_predict_raw_score`
* only used in prediction task
* Set to `true` will only predict the raw scores.
* Set to `false` will transformed score
* `predict_leaf_index `, default=`false`, type=bool, alias=`leaf_index `,`is_predict_leaf_index `
* only used in prediction task
* Set to `true` to predict with leaf index of all trees
* `bin_construct_sample_cnt`, default=`200000`, type=int
* Number of data that sampled to construct histogram bins.
* Will give better training result when set this larger. But will increase data loading time.
* Set this to larger value if data is very sparse.
* `num_iteration_predict`, default=`-1`, type=int
* only used in prediction task, used to how many trained iterations will be used in prediction.
* `<= 0` means no limit
## Objective parameters
* `sigmoid`, default=`1.0`, type=double
* parameter for sigmoid function. Will be used in binary classification and lambdarank.
* `huber_delta`, default=`1.0`, type=double
* parameter for [Huber loss](https://en.wikipedia.org/wiki/Huber_loss "Huber loss - Wikipedia"). Will be used in regression task.
* `fair_c`, default=`1.0`, type=double
* parameter for [Fair loss](https://www.kaggle.com/c/allstate-claims-severity/discussion/24520). Will be used in regression task.
* `poission_max_delta_step`, default=`0.7`, type=double
* parameter used to safeguard optimization
* `scale_pos_weight`, default=`1.0`, type=double
* weight of positive class in binary classification task
* `boost_from_average`, default=`true`, type=bool
* adjust initial score to the mean of labels for faster convergence, only used in Regression task.
* `is_unbalance`, default=`false`, type=bool
* used in binary classification. Set this to `true` if training data are unbalance.
* `max_position`, default=`20`, type=int
* used in lambdarank, will optimize NDCG at this position.
* `label_gain`, default=`0,1,3,7,15,31,63,...`, type=multi-double
* used in lambdarank, relevant gain for labels. For example, the gain of label `2` is `3` if using default label gains.
* Separate by `,`
* `num_class`, default=`1`, type=int, alias=`num_classes`
* only used in multi-class classification
## Metric parameters
* `metric`, default={`l2` for regression}, {`binary_logloss` for binary classification},{`ndcg` for lambdarank}, type=multi-enum, options=`l1`,`l2`,`ndcg`,`auc`,`binary_logloss`,`binary_error`...
* `l1`, absolute loss, alias=`mean_absolute_error`, `mae`
* `l2`, square loss, alias=`mean_squared_error`, `mse`
* `l2_root`, root square loss, alias=`root_mean_squared_error`, `rmse`
* `huber`, [Huber loss](https://en.wikipedia.org/wiki/Huber_loss "Huber loss - Wikipedia")
* `fair`, [Fair loss](https://www.kaggle.com/c/allstate-claims-severity/discussion/24520)
* `poisson`, [Poisson regression](https://en.wikipedia.org/wiki/Poisson_regression "Poisson regression")
* `ndcg`, [NDCG](https://en.wikipedia.org/wiki/Discounted_cumulative_gain#Normalized_DCG)
* `map`, [MAP](https://www.kaggle.com/wiki/MeanAveragePrecision)
* `auc`, [AUC](https://en.wikipedia.org/wiki/Receiver_operating_characteristic#Area_under_the_curve)
* `binary_logloss`, [log loss](https://www.kaggle.com/wiki/LogLoss)
* `binary_error`. For one sample `0` for correct classification, `1` for error classification.
* `multi_logloss`, log loss for mulit-class classification
* `multi_error`. error rate for mulit-class classification
* Support multi metrics, separate by `,`
* `metric_freq`, default=`1`, type=int
* frequency for metric output
* `is_training_metric`, default=`false`, type=bool
* set this to true if need to output metric result of training
* `ndcg_at`, default=`1,2,3,4,5`, type=multi-int, alias=`ndcg_eval_at`,`eval_at`
* NDCG evaluation position, separate by `,`
## Network parameters
Following parameters are used for parallel learning, and only used for base(socket) version.
* `num_machines`, default=`1`, type=int, alias=`num_machine`
* Used for parallel learning, the number of machines for parallel learning application
* Need to set this in both socket and mpi version.
* `local_listen_port`, default=`12400`, type=int, alias=`local_port`
* TCP listen port for local machines.
* Should allow this port in firewall setting before training.
* `time_out`, default=`120`, type=int
* Socket time-out in minutes.
* `machine_list_file`, default=`""`, type=string
* File that list machines for this parallel learning application
* Each line contains one IP and one port for one machine. The format is `ip port`, separate by space.
## GPU parameters
* `gpu_platform_id`, default=`-1`, type=int
* OpenCL platform ID. Usually each GPU vendor exposes one OpenCL platform.
* Default value is -1, using the system-wide default platform.
* `gpu_device_id`, default=`-1`, type=int
* OpenCL device ID in the specified platform. Each GPU in the selected platform has a unique device ID.
* Default value is -1, using the default device in the selected platform.
* `gpu_use_dp`, default=`false`, type=bool
* Set to true to use double precision math on GPU (default using single precision).
## Others
### Continued training with input score
LightGBM support continued train with initial score. It uses an additional file to store these initial score, like the following:
```
0.5
-0.1
0.9
...
```
It means the initial score of first data is `0.5`, second is `-0.1`, and so on. The initial score file corresponds with data file line by line, and has per score per line. And if the name of data file is "train.txt", the initial score file should be named as "train.txt.init" and in the same folder as the data file. And LightGBM will auto load initial score file if it exists.
### Weight data
LightGBM support weighted training. It uses an additional file to store weight data, like the following:
```
1.0
0.5
0.8
...
```
It means the weight of first data is `1.0`, second is `0.5`, and so on. The weight file corresponds with data file line by line, and has per weight per line. And if the name of data file is "train.txt", the weight file should be named as "train.txt.weight" and in the same folder as the data file. And LightGBM will auto load weight file if it exists.
update:
You can specific weight column in data file now. Please refer to parameter `weight` in above.
### Query data
For LambdaRank learning, it needs query information for training data. LightGBM use an additional file to store query data. Following is an example:
```
27
18
67
...
```
It means first `27` lines samples belong one query and next `18` lines belong to another, and so on.(**Note: data should order by query**) If name of data file is "train.txt", the query file should be named as "train.txt.query" and in same folder of training data. LightGBM will load the query file automatically if it exists.
You can specific query/group id in data file now. Please refer to parameter `group` in above.
<file_sep># coding: utf-8
# pylint: disable=invalid-name, exec-used
"""Setup lightgbm package."""
from __future__ import absolute_import
import os
import sys
from setuptools import find_packages, setup
sys.path.insert(0, '.')
CURRENT_DIR = os.path.dirname(__file__)
libpath_py = os.path.join(CURRENT_DIR, 'lightgbm/libpath.py')
libpath = {'__file__': libpath_py}
exec(compile(open(libpath_py, "rb").read(), libpath_py, 'exec'), libpath, libpath)
LIB_PATH = [os.path.relpath(path, CURRENT_DIR) for path in libpath['find_lib_path']()]
print("Install lib_lightgbm from: %s" % LIB_PATH)
setup(name='lightgbm',
version=0.1,
description="LightGBM Python Package",
install_requires=[
'numpy',
'scipy',
],
maintainer='<NAME>',
maintainer_email='<EMAIL>',
zip_safe=False,
packages=find_packages(),
include_package_data=True,
data_files=[('lightgbm', LIB_PATH)],
url='https://github.com/Microsoft/LightGBM')
| d539d36d9075fd8a013ab49c474e561388d301cc | [
"Markdown",
"Python",
"C++"
] | 9 | Python | jfpuget/LightGBM | e984b0d6c5f2c321fabf25d4de0a8f765e4a818b | 64d75cafc01cf85c4edd126fb5f1c27e0bee7c99 |
refs/heads/master | <file_sep>package nl.anhenet.syncres.xml;
import javax.annotation.Nonnull;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@XmlAccessorType(XmlAccessType.FIELD)
public abstract class RsItem<T extends RsItem> {
private String loc;
private ZonedDateTime lastmod;
private String changefreq;
@XmlElement(name = "md", namespace = "http://www.openarchives.org/rs/terms/")
private RsMd rsMd;
@XmlElement(name = "ln", namespace = "http://www.openarchives.org/rs/terms/")
private List<RsLn> rsLnList = new ArrayList<>();
public String getLoc() {
return loc;
}
public T withLoc(@Nonnull String loc) {
this.loc = Objects.requireNonNull(loc);
return (T) this;
}
public Optional<ZonedDateTime> getLastmod() {
return Optional.ofNullable(lastmod);
}
public T withLastmod(ZonedDateTime lastmod) {
this.lastmod = lastmod;
return (T) this;
}
public Optional<String> getChangefreq() {
return Optional.ofNullable(changefreq);
}
public T withChangefreq(String changefreq) {
this.changefreq = changefreq;
return (T) this;
}
public Optional<RsMd> getMetadata() {
return Optional.ofNullable(rsMd);
}
public T withMetadata(RsMd rsMd) {
this.rsMd = rsMd;
return (T) this;
}
public List<RsLn> getLinkList() {
return rsLnList;
}
public T addLink(RsLn rsLn) {
rsLnList.add(rsLn);
return (T) this;
}
}
<file_sep>package nl.anhenet.syncres.discover;
import nl.anhenet.syncres.xml.Capability;
import nl.anhenet.syncres.xml.RsMd;
import nl.anhenet.syncres.xml.RsRoot;
import nl.anhenet.syncres.xml.SitemapItem;
import nl.anhenet.syncres.xml.Sitemapindex;
import nl.anhenet.syncres.xml.UrlItem;
import nl.anhenet.syncres.xml.Urlset;
import java.util.List;
import java.util.stream.Collectors;
/**
* Data summarizations on a ResultIndex.
*/
public class ResultIndexPivot {
private ResultIndex resultIndex;
public ResultIndexPivot(ResultIndex resultIndex) {
this.resultIndex = resultIndex;
}
public List<Throwable> listErrors() {
return resultIndex.getResultMap().values().stream()
.filter(result -> !result.getErrors().isEmpty())
.flatMap(result -> result.getErrors().stream())
.collect(Collectors.toList());
}
public List<Result<?>> listErrorResults() {
return resultIndex.getResultMap().values().stream()
.filter(result -> !result.getErrors().isEmpty())
.collect(Collectors.toList());
}
public List<Result<?>> listResultsWithContent() {
return resultIndex.getResultMap().values().stream()
.filter(result -> result.getContent().isPresent())
.collect(Collectors.toList());
}
public List<Result<?>> listFirstResults() {
return resultIndex.getResultMap().values().stream()
.filter(result -> result.getOrdinal() == 0)
.collect(Collectors.toList());
}
@SuppressWarnings ("unchecked")
public List<Result<Urlset>> listUrlsetResults() {
return resultIndex.getResultMap().values().stream()
.filter(result -> result.getContent().isPresent() && result.getContent().orElse(null) instanceof Urlset)
.map(result -> (Result<Urlset>) result)
.collect(Collectors.toList());
}
@SuppressWarnings ("unchecked")
public List<Result<Urlset>> listUrlsetResults(Capability capability) {
return resultIndex.getResultMap().values().stream()
.filter(result -> result.getContent().isPresent() && result.getContent().orElse(null) instanceof Urlset)
.map(result -> (Result<Urlset>) result)
.filter(result -> result.getContent()
.map(RsRoot::getMetadata)
.flatMap(RsMd::getCapability).orElse("invalid").equals(capability.xmlValue))
.collect(Collectors.toList());
}
@SuppressWarnings ("unchecked")
public List<Result<Urlset>> listUrlsetResultsByLevel(int capabilityLevel) {
return resultIndex.getResultMap().values().stream()
.filter(result -> result.getContent().isPresent() && result.getContent().orElse(null) instanceof Urlset)
.map(result -> (Result<Urlset>) result)
.filter(result -> result.getContent()
.map(RsRoot::getLevel).orElse(-1) == capabilityLevel)
.collect(Collectors.toList());
}
@SuppressWarnings ("unchecked")
public List<Result<Sitemapindex>> listSitemapindexResults() {
return resultIndex.getResultMap().values().stream()
.filter(result -> result.getContent().isPresent() && result.getContent().orElse(null) instanceof Sitemapindex)
.map(result -> (Result<Sitemapindex>) result)
.collect(Collectors.toList());
}
@SuppressWarnings ("unchecked")
public List<Result<Sitemapindex>> listSitemapindexResults(Capability capability) {
return resultIndex.getResultMap().values().stream()
.filter(result -> result.getContent().isPresent() && result.getContent().orElse(null) instanceof Sitemapindex)
.map(result -> (Result<Sitemapindex>) result)
.filter(result -> result.getContent()
.map(RsRoot::getMetadata)
.flatMap(RsMd::getCapability).orElse("invalid").equals(capability.xmlValue))
.collect(Collectors.toList());
}
@SuppressWarnings ("unchecked")
public List<Result<Sitemapindex>> listSitemapindexResultsByLevel(int capabilityLevel) {
return resultIndex.getResultMap().values().stream()
.filter(result -> result.getContent().isPresent() && result.getContent().orElse(null) instanceof Sitemapindex)
.map(result -> (Result<Sitemapindex>) result)
.filter(result -> result.getContent()
.map(RsRoot::getLevel).orElse(-1) == capabilityLevel)
.collect(Collectors.toList());
}
@SuppressWarnings ("unchecked")
public List<Result<RsRoot>> listRsRootResults() {
return resultIndex.getResultMap().values().stream()
.filter(result -> result.getContent().isPresent() && result.getContent().orElse(null) instanceof RsRoot)
.map(result -> (Result<RsRoot>) result)
.collect(Collectors.toList());
}
@SuppressWarnings ("unchecked")
public List<Result<RsRoot>> listRsRootResults(Capability capability) {
return resultIndex.getResultMap().values().stream()
.filter(result -> result.getContent().isPresent() && result.getContent().orElse(null) instanceof RsRoot)
.map(result -> (Result<RsRoot>) result)
.filter(result -> result.getContent()
.map(RsRoot::getMetadata)
.flatMap(RsMd::getCapability).orElse("Invalid capability").equals(capability.xmlValue))
.collect(Collectors.toList());
}
@SuppressWarnings ("unchecked")
public List<Result<RsRoot>> listRsRootResultsByLevel(int capabilityLevel) {
return resultIndex.getResultMap().values().stream()
.filter(result -> result.getContent().isPresent() && result.getContent().orElse(null) instanceof RsRoot)
.map(result -> (Result<RsRoot>) result)
.filter(result -> result.getContent()
.map(RsRoot::getLevel).orElse(-1) == capabilityLevel)
.collect(Collectors.toList());
}
@SuppressWarnings ("unchecked")
public List<Result<LinkList>> listLinkListResults() {
return resultIndex.getResultMap().values().stream()
.filter(result -> result.getContent().isPresent() && result.getContent().orElse(null) instanceof LinkList)
.map(result -> (Result<LinkList>) result)
.collect(Collectors.toList());
}
/**
* List the values of the <loc> element of <url> elements of documents of type urlset with
* the given capability.
* @param capability the capability of the documents from which locations will be extracted
* @return List of values of the <loc> elements
*/
@SuppressWarnings ("unchecked")
public List<String> listUrlLocations(Capability capability) {
return resultIndex.getResultMap().values().stream()
.filter(result -> result.getContent().isPresent() && result.getContent().orElse(null) instanceof Urlset)
.map(result -> (Result<Urlset>) result)
.filter(result -> result.getContent().map(RsRoot::getMetadata)
.flatMap(RsMd::getCapability).orElse("invalid").equals(capability.xmlValue))
.map(urlsetResult -> urlsetResult.getContent().orElse(null))
.map(Urlset::getItemList)
.flatMap(List::stream)
.map(UrlItem::getLoc)
.collect(Collectors.toList());
}
/**
* List the values of the <loc> element of <sitemap> elements of documents of type sitemapindex with
* the given capability.
* @param capability the capability of the documents from which locations will be extracted
* @return List of values of the <loc> elements
*/
@SuppressWarnings ("unchecked")
public List<String> listSitemapLocations(Capability capability) {
return resultIndex.getResultMap().values().stream()
.filter(result -> result.getContent().isPresent() && result.getContent().orElse(null) instanceof Sitemapindex)
.map(result -> (Result<Sitemapindex>) result)
.filter(result -> result.getContent().map(RsRoot::getMetadata)
.flatMap(RsMd::getCapability).orElse("invalid").equals(capability.xmlValue))
.map(sitemapindexResult -> sitemapindexResult.getContent().orElse(null))
.map(Sitemapindex::getItemList)
.flatMap(List::stream)
.map(SitemapItem::getLoc)
.collect(Collectors.toList());
}
}
<file_sep>@XmlSchema(
namespace = "http://www.sitemaps.org/schemas/sitemap/0.9",
xmlns = {
@XmlNs(prefix = "", namespaceURI = "http://www.sitemaps.org/schemas/sitemap/0.9"),
@XmlNs(prefix = "rs", namespaceURI = "http://www.openarchives.org/rs/terms/")
},
elementFormDefault = XmlNsForm.QUALIFIED,
attributeFormDefault = XmlNsForm.UNQUALIFIED)
@XmlJavaTypeAdapters({
@XmlJavaTypeAdapter(type = ZonedDateTime.class, value = ZonedDateTimeAdapter.class)
})
package nl.anhenet.syncres.xml;
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters;
import java.time.ZonedDateTime;
<file_sep>package nl.anhenet.syncres.util;
/**
* Created on 2016-10-05 16:18.
*/
public class LambdaUtil {
@FunctionalInterface
public interface Function_WithExceptions<T, R, E extends Exception> {
R apply(T val) throws E;
}
}
<file_sep># syncres
ResourceSync Framework solution
<file_sep>package nl.anhenet.syncres.view;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import nl.anhenet.syncres.discover.ResultIndex;
import nl.anhenet.syncres.discover.ResultIndexPivot;
import java.util.List;
import java.util.stream.Collectors;
/**
* Base class for viewing a ResultIndex as a tree.
*/
@JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.CLASS)
public class TreeBase {
private List<TreeResultView> roots;
public TreeBase(ResultIndex resultIndex) {
init(resultIndex, new Interpreter());
}
public TreeBase(ResultIndex resultIndex, Interpreter interpreter) {
init(resultIndex, interpreter);
}
private void init(ResultIndex resultIndex, Interpreter interpreter) {
ResultIndexPivot pivot = new ResultIndexPivot(resultIndex);
roots = pivot.listRsRootResultsByLevel(3).stream()
.map(rsRootResult -> new TreeResultView(rsRootResult, interpreter))
.collect(Collectors.toList());
}
public List<TreeResultView> getRoots() {
return roots;
}
}
<file_sep>package nl.anhenet.syncres.discover;
import nl.anhenet.syncres.util.LambdaUtil.Function_WithExceptions;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import java.net.URI;
import java.nio.charset.Charset;
/**
* Execute a request against a server.
*/
public abstract class AbstractUriExplorer {
static String getCharset(HttpResponse response) {
ContentType contentType = ContentType.getOrDefault(response.getEntity());
Charset charset = contentType.getCharset();
return charset == null ? "UTF-8" : charset.name();
}
private final CloseableHttpClient httpClient;
private URI currentUri;
public AbstractUriExplorer(CloseableHttpClient httpClient) {
this.httpClient = httpClient;
}
public abstract Result<?> explore(URI uri, ResultIndex index);
protected CloseableHttpClient getHttpClient() {
return httpClient;
}
protected URI getCurrentUri() {
return currentUri;
}
public <T> Result<T> execute(URI uri, Function_WithExceptions<HttpResponse, T, ?> func) {
currentUri = uri;
Result<T> result = new Result<T>(uri);
HttpGet request = new HttpGet(uri);
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
result.setStatusCode(statusCode);
if (statusCode < 200 || statusCode > 299) {
result.addError(new RemoteException(statusCode, response.getStatusLine().getReasonPhrase(), uri));
} else {
result.accept(func.apply(response));
}
} catch (Exception e) {
result.addError(e);
}
return result;
}
}
<file_sep>package nl.anhenet.syncres.view;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import nl.anhenet.syncres.discover.Result;
import nl.anhenet.syncres.discover.ResultIndex;
import nl.anhenet.syncres.xml.Capability;
import nl.anhenet.syncres.xml.RsMd;
import nl.anhenet.syncres.xml.RsRoot;
import nl.anhenet.syncres.xml.Urlset;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Base class for viewing a ResultIndex as a set list.
*/
@JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.CLASS)
public class SetListBase {
private List<SetItemView> setDetails;
private List<ResultView> explorationAttempts;
private List<ResultView> resultsWithExceptions;
private Set<String> invalidUris;
public SetListBase(ResultIndex resultIndex) {
init(resultIndex, new Interpreter() {});
}
public SetListBase(ResultIndex resultIndex, Interpreter interpreter) {
init(resultIndex, interpreter);
}
@SuppressWarnings("unchecked")
private void init(ResultIndex resultIndex, Interpreter interpreter) {
setDetails = resultIndex.getResultMap().values().stream()
.filter(result -> result.getContent().isPresent() && result.getContent().orElse(null) instanceof Urlset)
.map(result -> (Result<Urlset>) result) // save cast because of previous filter
.filter(result -> result.getContent().map(RsRoot::getMetadata)
.flatMap(RsMd::getCapability).orElse("invalid").equals(Capability.DESCRIPTION.xmlValue))
.map(urlsetResult -> urlsetResult.getContent().orElse(null))
.map(Urlset::getItemList)
.flatMap(Collection::stream)
.map(rsItem -> new SetItemView(rsItem, interpreter))
.collect(Collectors.toList());
explorationAttempts = resultIndex.getResultMap().values().stream()
.filter(result -> result.getOrdinal() == 0)
.map(result -> new ResultView(result, interpreter))
.collect(Collectors.toList());
resultsWithExceptions = resultIndex.getResultMap().values().stream()
.filter(result -> !result.getErrors().isEmpty())
.map(result -> new ResultView(result, interpreter))
.collect(Collectors.toList());
invalidUris = resultIndex.getInvalidUris();
}
public List<SetItemView> getSetDetails() {
return setDetails;
}
public List<ResultView> getExplorationAttempts() {
return explorationAttempts;
}
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public List<ResultView> getResultsWithExceptions() {
return resultsWithExceptions;
}
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public Set<String> getInvalidUris() {
return invalidUris;
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>nl.anhenet</groupId>
<artifactId>syncres</artifactId>
<version>1.0-SNAPSHOT</version>
<prerequisites>
<maven>3.0</maven>
</prerequisites>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<hamcrest-library.version>1.3</hamcrest-library.version>
</properties>
<dependencies>
<!-- ### HttpClient ## -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<!-- ### HTML Parser ## -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.9.2</version>
</dependency>
<!-- Apache Commons -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.module/jackson-module-jaxb-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<version>2.8.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<!-- ## Test dependencies ## -->
<!-- Hamcrest dependency should be on top see http://stackoverflow.com/a/16735373 -->
<!-- Hamcrest library -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>${hamcrest-library.version}</version>
<scope>test</scope>
</dependency>
<!-- mockserver (with bad SAXParser) -->
<dependency>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-netty</artifactId>
<version>3.10.4</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>2.0.1</version>
</dependency>
</dependencies>
</project><file_sep>package nl.anhenet.syncres.xml;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
/**
* Adapter for conversion between a {@link ZonedDateTime} and an ISO 8601 profile know as W3C Datetime format.
* <p>
* The unmarshal proces will convert given datetime strings to UTC (Coordinated Universal Time).
* If a datetime string has no timezone info, we assume that the datetime is in the timezone
* that is returned by the static {@link ZonedDateTimeAdapter#getZoneId()}. This timezone will default to
* {@link ZoneId#systemDefault()}, and can be set with {@link ZonedDateTimeAdapter#setZoneId(ZoneId)}.
* </p>
* The following examples illustrate the conversion of several valid W3C Datetime strings (unmarshal -> marshal).
* Datetimes without timezone info were calculated with an offset of UTC+10:00.
* <pre>
* 2016 -> 2015-12-31T14:00Z
* 2015-08 -> 2015-07-31T14:00Z
* 2014-08-09 -> 2014-08-08T14:00Z
* 2013-03-09T14 -> 2013-03-09T04:00Z
* 2012-03-09T14:30 -> 2012-03-09T04:30Z
* 2011-03-09T14:30:29 -> 2011-03-09T04:30:29Z
* 2010-01-09T14:30:29.1 -> 2010-01-09T04:30:29.100Z
* 2010-03-09T14:30:29.123 -> 2010-03-09T04:30:29.123Z
* 2010-04-09T14:30:29.1234 -> 2010-04-09T04:30:29.123400Z
* 2010-06-09T14:30:29.123456 -> 2010-06-09T04:30:29.123456Z
*
* 2009-03-09T14:30:29.123+01:00 -> 2009-03-09T13:30:29.123Z
* 2008-03-09T14:30:29.123-01:00 -> 2008-03-09T15:30:29.123Z
* 2007-03-09T14:30:29.123Z -> 2007-03-09T14:30:29.123Z
* 2006-03-09T14:30:29.123456789Z -> 2006-03-09T14:30:29.123456789Z
* 2005-03-09T14:30Z -> 2005-03-09T14:30Z
* </pre>
*
* @see
* <a href="https://www.w3.org/TR/1998/NOTE-datetime-19980827">https://www.w3.org/TR/1998/NOTE-datetime-19980827</a>
* <a href="https://tools.ietf.org/html/rfc3339">https://tools.ietf.org/html/rfc3339</a>
*
*/
public class ZonedDateTimeAdapter extends XmlAdapter<String, ZonedDateTime> {
private static ZoneId ZONE_ID;
public static ZoneId getZoneId() {
if (ZONE_ID == null) {
ZONE_ID = ZoneId.systemDefault();
}
return ZONE_ID;
}
public static ZoneId setZoneId(ZoneId zoneId) {
ZoneId oldZoneId = ZONE_ID;
ZONE_ID = zoneId;
return oldZoneId;
}
private DateTimeFormatter localFormat = new DateTimeFormatterBuilder()
.appendPattern("yyyy[-MM[-dd['T'HH[:mm[:ss]]]]]")
.parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.optionalStart()
.appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
.toFormatter();
@Override
public ZonedDateTime unmarshal(String value) throws Exception {
if (value == null) {
return null;
}
if (value.matches(".*([Z]|[+-][0-9]{1,2}:[0-9]{1,2})$")) {
return ZonedDateTime.parse(value).withZoneSameInstant(ZoneOffset.UTC);
} else {
LocalDateTime local = LocalDateTime.parse(value, localFormat);
ZonedDateTime localZ = ZonedDateTime.of(local, getZoneId());
return localZ.withZoneSameInstant(ZoneOffset.UTC);
}
}
@Override
public String marshal(ZonedDateTime value) throws Exception {
if (value == null) {
return null;
}
return value.toString();
}
}
<file_sep>package nl.anhenet.syncres.view;
import nl.anhenet.syncres.xml.RsItem;
import org.apache.commons.lang3.exception.ExceptionUtils;
import java.util.Base64;
import java.util.function.Function;
/**
*
*/
public class Interpreters {
public static Function<RsItem<?>, String> locItemNameInterpreter = RsItem::getLoc;
public static Function<RsItem<?>, String> base64EncodedItemNameInterpreter = (rsItem) -> {
String loc = rsItem.getLoc();
String[] parts = loc.split("/");
String directory = parts[parts.length - 2];
String itemName = null;
try {
itemName = new String(Base64.getUrlDecoder().decode(directory.getBytes())).replace("\n", "");
} catch (IllegalArgumentException e) {
itemName = ">> Error: " + e.getClass().getName() + ": Unable to decode '" + directory + "'. " + e.getMessage();
}
return itemName;
};
public static Function<Throwable, String> messageErrorInterpreter = Throwable::getMessage;
public static Function<Throwable, String> classAndMessageErrorInterpreter = (throwable) -> {
return throwable.getClass().getName() + ": " + throwable.getMessage();
};
public static Function<Throwable, String> stacktraceErrorInterpreter = ExceptionUtils::getStackTrace;
}
<file_sep>package nl.anhenet.syncres.view;
import com.fasterxml.jackson.annotation.JsonInclude;
import nl.anhenet.syncres.xml.RsItem;
import nl.anhenet.syncres.xml.RsLn;
import nl.anhenet.syncres.xml.RsMd;
/**
* Render a RsItem, a <url> or <sitemap> element.
*/
public class SetItemView {
private String name;
private String location;
private String capability;
private String describedBy;
public SetItemView(RsItem<?> rsItem) {
init(rsItem, new Interpreter() {});
}
public SetItemView(RsItem<?> rsItem, Interpreter interpreter) {
init(rsItem, interpreter);
}
private void init(RsItem<?> rsItem, Interpreter interpreter) {
location = rsItem.getLoc();
name = interpreter.getItemNameInterpreter().apply(rsItem);
// a nullItemNameInterpreter as default interpreter not allowed (Function<RsItem, String> returning null).
if (location.equals(name)) {
name = null;
}
capability = rsItem.getMetadata()
.flatMap(RsMd::getCapability)
.orElse(null);
describedBy = rsItem.getLinkList().stream()
.filter(rsLn -> "describedby".equals(rsLn.getRel()))
.findAny()
.map(RsLn::getHref)
.orElse(null);
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public String getName() {
return name;
}
public String getLocation() {
return location;
}
public String getCapability() {
return capability;
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public String getDescribedBy() {
return describedBy;
}
}
<file_sep>package nl.anhenet.syncres.view;
import com.fasterxml.jackson.annotation.JsonInclude;
import nl.anhenet.syncres.discover.Result;
import java.util.List;
import java.util.stream.Collectors;
/**
*
*/
public class TreeResultView extends ResultView {
private List<TreeResultView> children;
public TreeResultView(Result<?> result) {
this(result, new Interpreter());
}
public TreeResultView(Result<?> result, Interpreter interpreter) {
super(result, interpreter);
init(result, interpreter);
}
private void init(Result<?> result, Interpreter interpreter) {
children = result.getChildren().values().stream()
.map(childResult -> new TreeResultView(childResult, interpreter))
.collect(Collectors.toList());
}
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public List<TreeResultView> getChildren() {
return children;
}
}
| f17d026455b2d8a6ebdaefa8cfb199663da6956d | [
"Markdown",
"Java",
"Maven POM"
] | 13 | Java | bhenk/syncres | 051f8c936c2c5cb692587c1ce7f71a7cd7d50295 | ee6f311580b222a264507a6d3f27a64e1f8ddd0e |
refs/heads/master | <file_sep>class Solution():
def threeSum(self, nums, key):
result =[]
for each in nums:
ret = self.twoSum(nums, key, each)
if len(ret) > 0:
result.append(ret)
return result
def twoSum(self, nums, key, each):
nums.sort()
begin = 0
end = len(nums)-1
result = []
while begin < end:
if nums[begin]+nums[end] == key-each:
result = [nums[begin], nums[end], each]
begin += 1
end -= 1
elif nums[begin]+nums[end] < key:
begin += 1
else:
end -= 1
return result
s = Solution()
print s.threeSum([1, 2, 5, 3, 4], 8)<file_sep>
class Solution(object):
def twoSum(self, nums, key):
nums.sort()
begin = 0
end = len(nums)-1
result = []
while begin < end:
if nums[begin]+nums[end] == key:
result.append([nums[begin], nums[end]])
begin += 1
end -= 1
elif nums[begin]+nums[end] < key:
begin += 1
else:
end -= 1
return result
s = Solution()
print s.twoSum([2,4,1,5,6], 6)<file_sep>from itertools import permutations
class Solution(object):
def nextPermutation(self, nums):
length = len(nums)
cnt = 1
for each in permutations(nums, length):
if cnt == 2:
return each
cnt += 1
s = Solution()
print s.nextPermutation([1,2,3])<file_sep>class Solution():
def addBinary(self, str1, str2):
one = int(str1, 2)
two = int(str2, 2)
sum = one + two
sum = bin(sum)
return sum[2:]
s = Solution()
print s.addBinary("11", "1")<file_sep>from collections import OrderedDict
class Solution(object):
def longestConsecutiveSeq(self, num):
seqDic = OrderedDict()
for each in num:
seqDic[each] = each
maxlength = 0
for key in num:
left = key - 1
right = key + 1
cnt = 1
while left in seqDic:
cnt += 1
seqDic.pop(left)
left -= 1
while right in seqDic:
cnt += 1
seqDic.pop(right)
right += 1
if cnt > maxlength:
maxlength = cnt
return maxlength
s = Solution()
print s.longestConsecutiveSeq([1, 2, 3, 4, 5,6,7,8,199, 99, 100])
| 1d84c6ef708afc24bf1ac399610f16bfa7cc5250 | [
"Python"
] | 5 | Python | ly621000/allSort | 9703e078da368630d8c90b7ec38a67f81c683bc6 | b784d7c48398933461cb9fbd6c72a7988d5628ab |
refs/heads/master | <file_sep><?php
echo "Git Test!!";
echo "test3"
| dfa08d7ec7ea1ad504e4959c0f01ddbd973650cc | [
"PHP"
] | 1 | PHP | vividlotus/test | f0e777e957745ac35c55d5658dad4af1dbd37f9a | fab618311f63ac812d4ae060618ee2e7b7826711 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.