branch_name
stringclasses 15
values | target
stringlengths 26
10.3M
| directory_id
stringlengths 40
40
| languages
sequencelengths 1
9
| num_files
int64 1
1.47k
| repo_language
stringclasses 34
values | repo_name
stringlengths 6
91
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
| input
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>EzaiLWade/WWX<file_sep>/pages/music/music.js
Page({
onLoad:function(options){
var that = this;
wx.getSystemInfo({
success: function(res){
that.setData({
scrollHeight: res.windowHeight - 75
})
}
})
},
onReady: function (e) {
// 使用 wx.createAudioContext 获取 audio 上下文 context
this.audioCtx = wx.createAudioContext('myAudio')
},
data: {
music:{
poster:'http://ezailwade.online/music/1.jpg',
name: 'Jam Jam',
author: 'IU',
src: 'http://ezailwade.online/music/1.mp3'
},
musicList:[
{
id:0,
poster:'http://ezailwade.online/music/1.jpg',
name:'Jam Jam',
author:'IU',
src:'http://ezailwade.online/music/1.mp3'
},{
id:1,
poster:'http://ezailwade.online/music/2.jpg',
name:'絶 絶',
author:'Swimy',
src:'http://ezailwade.online/music/2.mp3'
},{
id:2,
poster:'http://ezailwade.online/music/3.jpg',
name:'直到世界尽头',
author:'上杉升',
src:'http://ezailwade.online/music/3.mp3'
},{
id:3,
poster:'http://ezailwade.online/music/4.jpg',
name:'La La Land',
author:'Jax',
src:'http://ezailwade.online/music/4.mp3'
},{
id:4,
poster:'http://ezailwade.online/music/5.jpg',
name:'Humble',
author:'<NAME>',
src:'http://ezailwade.online/music/5.mp3'
},{
id:5,
poster:'http://ezailwade.online/music/6.jpg',
name:'百鬼夜行',
author:'米津玄师',
src:'http://ezailwade.online/music/6.mp3'
}
]
},
playMusic: function(event){
var idx = event.target.dataset.idx;
var that = this;
console.log(this.data.musicList[idx])
that.setData({
music :this.data.musicList[idx]
})
},
audioPlay: function () {
this.audioCtx.play()
},
audioPause: function () {
this.audioCtx.pause()
},
audio14: function () {
this.audioCtx.seek(14)
},
audioStart: function () {
this.audioCtx.seek(0)
},
onShow:function(){
// 页面显示
},
onHide:function(){
// 页面隐藏
},
onUnload:function(){
// 页面关闭
}
}) | 3c6919a989cb30d9cf25b57115be87f0a762ad46 | [
"JavaScript"
] | 1 | JavaScript | EzaiLWade/WWX | ae01ea21541a3cf8822d47361f002c77f2e01047 | ff36e61370c5135b560f18a899c6e9422af0c3c6 | |
refs/heads/master | <repo_name>PaladinHZY/ZYNQ_AXI_Test<file_sep>/build/Makefile
setup:
vivado -mode batch -source ZYBO_AXI_Test.tcl
clean:
rm -rf *.log *.jou project_1
build:
vivado -mode batch -source build.tcl
sdk:
xsct sdk.tcl
<file_sep>/sdk/AXI_Datalink_Test/src/main.c
/*
* main.c
*
* Created on: Jun 8, 2018
* Author: <NAME>
*/
/*
* main.c
*
* Created on: Jun 7, 2018
* Author: <NAME>
*/
#include "main.h"
#define CAN_MODE
//#define UART
//#define ULANDINGC1
#define US_D1
u8 *FramePtr;
int ext_id;
int alt_data;
int snr_data;
int header_index;
int main()
{
// GPIO Initialization
XGpio_Initialize(&gpio, XPAR_AXI_GPIO_0_DEVICE_ID);
XGpio_SetDataDirection(&gpio, 2, 0x00000000); // set LED GPIO channel tristates to All Output
XGpio_SetDataDirection(&gpio, 1, 0xFFFFFFFF); // set BTN GPIO channel tristates to All Input
//
XGpio_Initialize(&gpio_init, XPAR_AXI_GPIO_1_DEVICE_ID);
XGpio_SetDataDirection(&gpio_init, 1, 0x00000000); // set LED GPIO channel tristates to All Output
/// UART_0 Initialization
Config = XUartPs_LookupConfig(XPAR_PS7_UART_0_DEVICE_ID);
XUartPs_CfgInitialize (&UartPs, Config, Config->BaseAddress);
XUartPs_SetBaudRate(&UartPs, 115200);
XUartPs_SelfTest(&UartPs);
XCanPs *CanInstPtr = &canps;
///CAN_0 Initialization
CAN_Config = XCanPs_LookupConfig(XPAR_PS7_CAN_0_DEVICE_ID);
XCanPs_CfgInitialize(CanInstPtr, CAN_Config, CAN_Config->BaseAddr);
XCanPs_SelfTest(CanInstPtr);
XCanPs_EnterMode(CanInstPtr, XCANPS_MODE_CONFIG);
while(XCanPs_GetMode(CanInstPtr) != XCANPS_MODE_CONFIG);
XCanPs_SetBaudRatePrescaler(CanInstPtr, TEST_BRPR_BAUD_PRESCALAR);
XCanPs_SetBitTiming(CanInstPtr, TEST_BTR_SYNCJUMPWIDTH, TEST_BTR_SECOND_TIMESEGMENT, TEST_BTR_FIRST_TIMESEGMENT);
//init en
XGpio_DiscreteWrite(&gpio_init, 1, 0xffffffff);
usleep(100000);
// XGpio_DiscreteWrite(&gpio_init, 1, 0x00000000);
while (1){
xil_printf("Let's begin!");
}
// DEFAULT UART --- UART 1
xil_printf("Let's begin!");
#ifdef CAN_MODE
XCanPs_EnterMode(&canps, XCANPS_MODE_NORMAL);
while(XCanPs_GetMode(&canps) != XCANPS_MODE_NORMAL);
for (int i = 0; i < XCANPS_MAX_FRAME_SIZE_IN_WORDS; i++){
CAN_receiving_data[i] = 0;
}
while (1){
XGpio_DiscreteWrite(&gpio, 2, 0xffffffff);
// CAN Receiver
while (XCanPs_IsRxEmpty(CanInstPtr) == TRUE);
status = XCanPs_Recv(CanInstPtr, CAN_receiving_data);
if (status == 0){
#ifdef US_D1
ext_id = (((int)CAN_receiving_data[0]) >> 1) & 0x00090002;
snr_data = ((((int)CAN_receiving_data[2]) & 0xff000000) >> 24) + ((((int)CAN_receiving_data[2]) & 0x00ff0000) >> 16)*256;
alt_data = ((((int)CAN_receiving_data[2]) & 0x0000ff00) >> 8) + (((int)CAN_receiving_data[2]) & 0x000000ff)*256;
#else
ext_id = (((int)CAN_receiving_data[0]) >> 1) & 0x00090002;
snr_data = ((((int)CAN_receiving_data[2]) & 0xff000000) >> 24) + ((((int)CAN_receiving_data[2]) & 0x00ff0000) >> 16)*256;
alt_data = ((((int)CAN_receiving_data[2]) & 0x0000ff00) >> 8) + (((int)CAN_receiving_data[2]) & 0x000000ff)*256;
#endif
printf("ID: %#.8x, Altitude Data: %d, SNR Data: %d\n\r", ext_id, alt_data, snr_data);
}
}
#endif
#ifdef UART
while(1){
// UART Receiver
for (int i = 0; i < 12; i++){
UART_receiving_data[i] = XUartPs_RecvByte(XPAR_PS7_UART_0_BASEADDR);
}
for (header_index = 0; header_index < 12; header_index++){
if (*(UART_receiving_data + header_index) == 0xfe && *(UART_receiving_data + header_index + 1) == 0x00){
break;
}
}
#ifdef US_D1
alt_data = *(UART_receiving_data+header_index+2) + *(UART_receiving_data+header_index+3) *256;
snr_data = *(UART_receiving_data+header_index+4);
if (snr_data == 0)
printf("Altitude Data: %d, SNR Data: No SNR Available!", alt_data);
else
printf("Altitude Data: %d, SNR Data: %d\n\r", alt_data, snr_data);
#endif
}
#endif
return 0;
}
<file_sep>/sdk/AXI_Datalink_Test/src/CAN_TxRx.c
/*
* CAN_TxRx.c
*
* Created on: Jun 15, 2018
* Author: <NAME>
*/
#include "xparameters.h"
/// CAN bus driver
#include "xcanps.h"
#include "xcanps_hw.h"
#include "main.h"
void CAN_Reconfig(){
CAN_Config = XCanPs_LookupConfig(XPAR_PS7_CAN_0_DEVICE_ID);
XCanPs_CfgInitialize(&canps, CAN_Config, CAN_Config->BaseAddr);
XCanPs_SetBaudRatePrescaler(&canps, TEST_BRPR_BAUD_PRESCALAR);
XCanPs_SetBitTiming(&canps, TEST_BTR_SYNCJUMPWIDTH, TEST_BTR_SECOND_TIMESEGMENT, TEST_BTR_FIRST_TIMESEGMENT);
XCanPs_EnterMode(&canps, XCANPS_MODE_NORMAL);
}
| b88069a4a5d4e38fa106e21bd36d1fee26e76bbc | [
"C",
"Makefile"
] | 3 | Makefile | PaladinHZY/ZYNQ_AXI_Test | 6bd60fffb30f19017470eb37a7c36126e4578fb3 | bbd09ef062a4ad5f5214b527a2736ccf1ac5156e | |
refs/heads/master | <file_sep># vim-neon-dark
A dark theme for vim/neovim based on MattDMo's SublimeText [Neon-color-scheme](https://github.com/MattDMo/Neon-color-scheme).
Please note that this theme has slightly diverged from the parent theme over time as more and more specialized syntax groups were added to the original.

Includes improved syntax highlighting for the following languages using [nvim-treesitter](https://github.com/nvim-treesitter/nvim-treesitter):
- php
- phpdoc
- comment
- javascript
- typescript
Includes improved sytax highlighting for PHP using [StanAngeloff/php.vim](https://github.com/StanAngeloff/php.vim) syntax groups. (If you're using regular vim or neovim without treesitter).
## Installation
#### Recommended
Use a plugin manager and vim should be able to use the colorscheme provided by
this repo (tested with [junegunn/vim-plug](https://github.com/junegunn/vim-plug)).
```vim
" you can select the version with the corresponding tag
Plug 'nonetallt/vim-neon-dark', { 'tag': '2.1.0' }
```
#### Manual
Copy the colorscheme file to your .vim/colors directory.
## Usage
Set the colorscheme in your `.vimrc` (vim) file or `init.vim` (neovim)
```vim
colorscheme neon-dark
```
Enable `termguicolors` if you're using a terminal that [supports the full palette](https://github.com/termstandard/colors).
```vim
set termguicolors
colorscheme neon-dark
```
## Versions
#### 2.1.0
- Add custom treesitter predicates (`none-of?` and `notmatch?`)
- Add treesitter support for comment
- Add syntax highlights for treesitter text groups: (`@text.todo`, `@text.note`, `@text.danger`, `@text.warning`)
#### 2.0.0
- Add treesitter support for php
- Add treesitter support for phpdoc
- Add treesitter support for javascript
- Add treesitter support for typescript
- Remove ctrlp.vim plugin specific highlights
- Remove `neon-dark-256`, it's now merged to `neon-dark`
- Remove discrepancies between terminal and gui colors
#### 1.0.0
The original release version.
<file_sep>#!/usr/bin/env php
<?php
if(! isset($argv[1])) {
echo "Missing required argument 1: input";
exit(1);
}
$filepath = $argv[1];
if(! file_exists($filepath)) {
echo "Could not find file '$filepath'";
exit(1);
}
function find256Color(string $hex) : int
{
$termColors = require dirname(__DIR__) . '/php/256colors.php';
$rgb = array_map(fn($hex2) => hexdec($hex2), str_split($hex, 2));
$lowestDiff = PHP_INT_MAX;
$lowestDiffNum = 0;
foreach($termColors as $number => $color) {
$diff = abs($rgb[0] - $color['r']) + abs($rgb[1] - $color['g']) + abs($rgb[2] - $color['b']);
if($diff < $lowestDiff) {
$lowestDiff = $diff;
$lowestDiffNum = $number;
}
}
return $lowestDiffNum;
}
function generateCtermColor(array $lines, string $pattern, string $selectorString) : string
{
$content = '';
$guiString = "gui$selectorString";
$ctermString = "cterm$selectorString";
foreach($lines as $line) {
$result = preg_match($pattern, $line, $matches, PREG_OFFSET_CAPTURE);
if($result !==1) {
$content .= $line;
continue;
}
[$guiMatch, $guiOffset] = $matches[$guiString];
$ctermColor = find256Color(explode('#', $guiMatch)[1]);
if(isset($matches[$ctermString])) {
[$ctermMatch, $ctermOffset] = $matches[$ctermString];
$line = substr_replace($line, "$ctermString=$ctermColor", $ctermOffset, strlen($ctermMatch));
}
else {
$line = substr_replace($line, "$guiMatch $ctermString=$ctermColor", $guiOffset, -1);
}
$content .= $line;
}
return $content;
}
$fgPattern = '/(?<guifg>guifg=#[0-9a-fA-F]{6})(.+(?<ctermfg>ctermfg=[0-9]{1,3}))?/';
$bgPattern = '/(?<guibg>guibg=#[0-9a-fA-F]{6})(.+(?<ctermbg>ctermbg=[0-9]{1,3}))?/';
$fileContent = generateCtermColor(file($filepath), $fgPattern, 'fg');
$fileContent = generateCtermColor(array_map(fn($line) => $line . PHP_EOL, explode(PHP_EOL, $fileContent)), $bgPattern, 'bg');
file_put_contents($filepath, substr($fileContent, 0, -1));
exit(0);
<file_sep>local query = require "vim.treesitter.query"
local M = {}
local noneof = function(match, _, source, predicate)
local node = match[predicate[2]]
if not node then
return false
end
local node_text = query.get_node_text(node, source)
-- Since 'predicate' will not be used by callers of this function, use it
-- to store a string set built from the list of words to check against.
local string_set = predicate['string_set']
if not string_set then
string_set = {}
for i = 3, #predicate do
---@diagnostic disable-next-line:no-unknown
string_set[predicate[i]] = true
end
predicate['string_set'] = string_set
end
return not string_set[node_text]
end
local notmatch = (function()
local magic_prefixes = { ['\\v'] = true, ['\\m'] = true, ['\\M'] = true, ['\\V'] = true }
---@private
local function check_magic(str)
if string.len(str) < 2 or magic_prefixes[string.sub(str, 1, 2)] then
return str
end
return '\\v' .. str
end
local compiled_vim_regexes = setmetatable({}, {
__index = function(t, pattern)
local res = vim.regex(check_magic(pattern))
rawset(t, pattern, res)
return res
end,
})
return function(match, _, source, pred)
---@cast match TSMatch
local node = match[pred[2]]
if not node then
return false
end
---@diagnostic disable-next-line no-unknown
local regex = compiled_vim_regexes[pred[3]]
return not regex:match_str(query.get_node_text(node, source))
end
end)()
function M.setup()
query.add_predicate('none-of?', noneof, true)
query.add_predicate('notmatch?', notmatch, true)
end
return M
| 1a773bd4bb441b33747c2f1eb2f8d5f9d0d77175 | [
"Markdown",
"PHP",
"Lua"
] | 3 | Markdown | nonetallt/vim-neon-dark | 22d7a6c34aa15b834842b6759d3733fa34622abc | f22befa8fa9341be1ac9bf97d7eb474bb73001de | |
refs/heads/master | <repo_name>KamillaKatz/flickr-gallery<file_sep>/src/components/App/App.js
import React from 'react';
import './App.scss';
import Gallery from '../Gallery';
class App extends React.Component {
static propTypes = {
};
constructor() {
super();
this.fullScreenImage = this.fullScreenImage.bind(this);
this.closeSlider = this.closeSlider.bind(this);
this.nextImage = this.nextImage.bind(this);
this.prevImage = this.prevImage.bind(this);
this.state = {
tag: 'art',
frontImage: null
};
}
closeSlider() {
var temp = document.getElementById('ImageSlider');
temp.style.display = 'none';
}
fullScreenImage(image_com_to_show) {
var Imcmp = document.getElementById(image_com_to_show);
var img = document.getElementById('imshow');
var slider = document.getElementById('ImageSlider');
img.src = Imcmp.children.item(0).src;
slider.style.display = 'block';
this.state.frontImage = Imcmp;
}
nextImage() {
var front = document.getElementById('imshow');
var slider = document.getElementById('ImageSlider');
var nextImage = this.state.frontImage.nextElementSibling;
front.src = nextImage.children.item(0).src;
this.state.frontImage = nextImage;
}
prevImage() {
var front = document.getElementById('imshow');
var slider = document.getElementById('ImageSlider');
var prevImage = this.state.frontImage.previousElementSibling;
front.src = prevImage.children.item(0).src;
this.state.frontImage = prevImage;
}
render() {
return (
<div className="app-root">
<div className="slider" id="ImageSlider">
<a className="close-btn" onClick={this.closeSlider}>×</a>
<a className="prev" onClick={this.prevImage} >❮</a>
<a className="next" onClick={this.nextImage} >❯</a>
<img className="frot-image" id="imshow"/></div>
<div className="app-header">
<h2>Flickr Gallery</h2>
<input className="app-input" onChange={event => this.setState({tag: event.target.value})} value={this.state.tag}/>
</div>
<Gallery Myfunc={this.fullScreenImage} tag={this.state.tag} />
</div>
);
}
}
export default App;
<file_sep>/src/components/Image/Image.js
import React from 'react';
import PropTypes from 'prop-types';
import FontAwesome from 'react-fontawesome';
import './Image.scss';
class Image extends React.Component {
static propTypes = {
dto: PropTypes.object,
galleryWidth: PropTypes.number,
Myfunc: PropTypes.func
};
constructor(props) {
super(props);
this.calcImageSize = this.calcImageSize.bind(this);
this.state = {
size: 200,
angle: 0
};
this.turnImage = this.turnImage.bind(this);
this.deleteImage = this.deleteImage.bind(this);
this.expendImage = this.expendImage.bind(this);
}
calcImageSize() {
const {galleryWidth} = this.props;
const targetSize = 200;
const imagesPerRow = Math.round(galleryWidth / targetSize);
const size = (galleryWidth / imagesPerRow);
this.setState({
size
});
}
componentDidMount() {
this.calcImageSize();
}
urlFromDto(dto) {
return `https://farm${dto.farm}.staticflickr.com/${dto.server}/${dto.id}_${dto.secret}.jpg`;
}
turnImage() {
this.state.angle = (this.state.angle + 90) % 360;
var temp = document.getElementById(this.props.dto.id);
temp.childNodes.item(0).style.transform = 'rotate(' + this.state.angle.toString() + 'deg)';
}
deleteImage() {
var temp = document.getElementById(this.props.dto.id);
temp.style.display = 'none';
}
expendImage() {
//var temp = document.getElementById(this.props.dto.id);
this.props.Myfunc(this.props.dto.id);
}
render() {
return (
<div
id={this.props.dto.id} className="image-root">
<img src={this.urlFromDto(this.props.dto)} style={{
width: this.state.size + 'px',
height: this.state.size + 'px'
}} />
<div>
<FontAwesome onClick={this.turnImage} className="image-icon" name="sync-alt" title="rotate"/>
<FontAwesome onClick={this.deleteImage} className="image-icon" name="trash-alt" title="delete" />
<FontAwesome onClick={this.expendImage} className="image-icon" name="expand" title="expand" />
</div>
</div>
);
}
}
export default Image;
| 990b5ba3a84980e8f4512cfda6a312aea76908b0 | [
"JavaScript"
] | 2 | JavaScript | KamillaKatz/flickr-gallery | 6e867aa7b9dec7f7cd47e018543a6723bc28daf9 | fa8dfe15edb20dd45a908bf5fd3b79ec13957061 | |
refs/heads/main | <repo_name>VSADX/postoffice.js<file_sep>/README.md
# PostOffice
PostOffice helps you create *more* reusable functions.
+ **Powerful**: PostOffice lets you create simple functions, then bind any of the parameters you choose.
Like `.bind` in JavaScript, binding a parameter creates a copy of your function. This way, you can bind
parameters to the same function many times creating new functions (like Dependency Injection or Partial
Application).
+ **Simple**: You don't need to write in a particular style! PostOffice exports just one function. If you
pass in a function to `postoffice()`, you get a new function that support arbitrary parameter binding.
+ **Tiny**: The principles behind this library are so simple, you could do it yourself. However, `postoffice.js`
is only 22 lines of code, so feel free to check out how it works.
<br>
```js
import { postoffice, N } from "postoffice.js"
const subtract = postoffice((first, second) => first - second)
// `subtract` takes two parameters, but we only fill in the `first`
const take_from_100 = subtract(100)
console.log(take_from_100(70)) // 30
console.log(take_from_100(127)) // -27
```
<br>
```js
const subtract = postoffice((first, second) => first - second)
// `subtract` takes two parameters, but we only supply the `second`
// the const `N` tells our function that we don't want to place a value in it yet
const take_away_20 = subtract(N, 20)
console.log(take_away_20(80)) // 60
console.log(take_away_20(13)) // -7
```
<br>
## What's PostOffice doing?
Like a real postoffice, when you fill-out an envelope but forget some of the information, you get your letter back.
You also get instructions on what is missing. Once you add all the missing information, the postoffice delivers your
mail. This is not how most programming languages work. If you try to run a function, but don't supply all the required parameters,
expect an exception or unexpected behavior.
**What does this library do?** When you run a postoffice function, you don't have to supply all the required parameters.
The function will bind all the parameters you added, but return a new function that takes the missing parameters.
When you supply all the missing parameters, the function promptly executes.
**This is more than a debugging tool.** This library is designed to give you more freedom as a function author or API user.
How so? The next code example shows how you can use `N` to add placeholders for any parameters of a function. Also,
PostOffice can create multiple functions from just one original function. Each copied function can have different
parameters bound, or the same one bound but using a different value.
<br>
```js
const sell_food = postoffice((item, price, count) => `${item}: $${price * count}`)
const sell_pizza = sell_food("Pizza", 12.50, N)
const sell_drink = sell_food(N, 1.20, 1)
//////
sell_pizza(3) // "Pizza: $37.50"
sell_drink("Sprite") // "Sprite: $1.20"
sell_drink("Pepsi") // "Pepsi: $1.20"
```
<br>
**FizzBuzz example**
```js
const multiple_of = postoffice((num, multiple, message) =>
num % multiple === 0 ? message : false)
const by3 = multiple_of(N, 3, "Fizz")
const by5 = multiple_of(N, 5, "Buzz")
const by3x5 = multiple_of(N, 3 * 5, "Fizz Buzz")
const all_funcs = [by3x5, by5, by3]
for(let i = 1; i < 20; i++) {
console.log(
all_funcs.map(func => func(i)).find(x => x !== false) || i
)
}
```
<br>
References
XMoñOcci, XBind, Ocxi.js
<file_sep>/postoffice.js
function mailmerge(params, args) {
for(let i = 0, base = 0; i < args.length; i++) {
while(params[base] != N && base < params.length) base++
params[base++] = args[i]
}
return params
}
export const N = Symbol("Nothing") // undefined
export function postoffice(func, declared_count = 0) {
const base_params = Array.from({length: declared_count || func.length}).fill(N)
return function count_params(...args) {
const params = base_params.slice()
mailmerge(params, args)
return (params.some(param => param === N)) ?
(...args) => count_params(...mailmerge(params.slice(), args)) :
func(...params)
}
}
| c06f11ac2fbb04cb00ee8c9841f39a6ef38eee57 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | VSADX/postoffice.js | da5440e4a08b05b4ed8c48dda5febe590e802793 | 4c360cb7e198f72b7dd5a3dbd55c9d2341c87de1 | |
refs/heads/master | <repo_name>lfeitosa/homologator<file_sep>/Homologator.py
import json, requests, os
import sys
import smtplib as s
from email import encoders
from email.mime.text import MIMEText
from email.MIMEMultipart import MIMEMultipart
from dictor import dictor
import requests
def main():
banner()
opcao_menu = int(input('QUAL OPCAO? '))
if (opcao_menu == 1):
os.system('clear') or None
validarPagamento()
if (opcao_menu == 2):
os.system('clear') or None
validarPagamento()
if (opcao_menu == 3):
os.system('clear') or None
gerarAdmToken()
def validarPagamento():
access_token = raw_input('Qual Access_token (Pode inserir ADM TOKEN)? ')
payment = raw_input('Qual Pagamento? ')
try:
# PEDIDO COM MUITOS ITENS
# response = requests.get("https://api.mercadopago.com/v1/payments/5378897871?access_token=*******<PASSWORD>")
# PEDIDO COM ITENS FALTANDO
response = requests.get("https://api.mercadopago.com/v1/payments/"+str(payment)+"?access_token="+str(access_token))
# print response.status_code
comments = json.loads(response.content)
except Exception as e:
os.system('clear') or None
print " VERIFIQUE OS DADOS INSERIDOS"
main()
# VERIFICAR SE TEM ADDITIONAL_INFO
print "_______________________"
print "#### ADDITIONAL_INFO ####"
if (validarAdditional(comments)):
print "Additional_info | OK |"
additional_info = "OK"
else:
# print "Payer - | ERROR|"
additional_info = "ERROR"
print "#### PAYER ####"
# VERIFICAR SE O PAYER ESTA CORRETO
if (validarPayer(comments)):
print "Payer - | OK |"
payer = "OK"
else:
payer = "ERROR"
# VERIFICAR QUAL STATUS ESTA O MODO BINARIO
if (validarBinary(comments)):
print "Binary_mode - | TRUE |"
binary = "TRUE"
else:
print "Binary_mode - | FALSE|"
binary = "FALSE"
# VERIFICAR SE HOUVE HIGH_RISK
if (validarStatus(comments)):
print "Status - | HIGH_RISK |"
status = "HIGH_RISK"
else:
print "Status - | OK |"
status = "OK"
if (pagamentoFluxo(comments)):
print "PNF - | TRUE |"
pnf = "TRUE"
else:
print "PNF - | FALSE|"
pnf = "FALSE"
print "_______________________"
opcao_menu = int(input('DESEJA ENVIAR POR EMAIL (1 - SIM / 2 - NAO)? '))
if (opcao_menu == 1):
textoToString = resultadoToString(additional_info,payer,binary,status,pnf,str(comments["id"]))
email = raw_input('Qual email?')
enviarEmail(email, textoToString)
if (opcao_menu == 2):
os.system('clear') or None
main()
else:
os.system('clear') or None
print "Opcao invalida"
main()
def resultadoToString(additional_info,payer,binary,status,pnf,id):
inicioHtml = ""
texto = "ID - "+ id +"\n\n\nAdditional_info - " + additional_info + "\nPayer - " + payer + "\nBinary_mode - " + binary + "\nStatus - " + status + "\nPNF - " + pnf
return texto
def gerarAdmToken():
os.system('clear') or None
usuarioRede = raw_input('Usuario Rede: ')
senhaRede = raw_input('Senha Rede: ')
d = {'grant_type': "password", 'client_id': 601, 'client_secret': '<KEY> <PASSWORD>', 'username': usuarioRede, 'password': <PASSWORD>}
response = requests.post("https://api.mercadolibre.com/admin/oauth/token", data=d)
comments = json.loads(response.content)
os.system('clear') or None
print comments['access_token']
main()
def validarAdditional(comments):
additional_info = False
# print comments["additional_info"]
if len(comments["additional_info"])!=0:
additional_info = True
# VALIDAR ITEMS
if len(comments["additional_info"]["items"])!=0:
reload(sys)
sys.setdefaultencoding( "latin-1" )
if str(dictor(comments, "additional_info.items.0.category_id"))=="None":
print "- Faltando additional_info.items.category_id"
additional_info = False
if str(dictor(comments, "additional_info.items.0.description"))=="None":
print "- Faltando additional_info.items.description"
additional_info = False
if str(dictor(comments, "additional_info.items.0.id"))=="None":
print "- Faltando additional_info.items.id"
additional_info = False
if str(dictor(comments, "additional_info.items.0.picture_url"))=="None":
print "- Faltando additional_info.items.picture_url"
additional_info = False
if str(dictor(comments, "additional_info.items.0.quantity"))=="None":
print "- Faltando additional_info.items.quantity"
additional_info = False
if str(dictor(comments, "additional_info.items.0.title"))=="None":
print "- Faltando additional_info.items.title"
additional_info = False
if str(dictor(comments, "additional_info.items.0.unit_price"))=="None":
print "- Faltando additional_info.items.unit_price"
additional_info = False
else:
print "- Faltando additional_info.items"
additional_info = False
# VALIDAR PAYER
if len(comments["additional_info"]["payer"])!=0:
if len(comments["additional_info"]["payer"]["first_name"])!=0:
print "- Faltando additional_info.payer.first_name"
if len(comments["additional_info"]["payer"]["last_name"])!=0:
print "- Faltando additional_info.payer.last_name"
if len(comments["additional_info"]["payer"]["phone"])!=0:
print "- Faltando additional_info.payer.phone"
if len(comments["additional_info"]["payer"]["address"])!=0:
if str(dictor(comments, "additional_info.payer.street_name"))=="None":
print "- Faltando additional_info.payer.street_name"
additional_info = False
if str(dictor(comments, "additional_info.payer.street_number"))=="None":
print "- Faltando additional_info.payer.street_number"
additional_info = False
if str(dictor(comments, "additional_info.payer.zip_code"))=="None":
print "- Faltando additional_info.payer.zip_code"
additional_info = False
else:
print "- Faltando additional_info.payer.address"
else:
print "- Faltando additional_info.payer"
additional_info = False
# VALIDAR SHIPMENT
if len(comments["additional_info"]["shipments"])!=0:
if len(comments["additional_info"]["shipments"]["receiver_address"])==0:
print "- Faltando additional_info.shipments"
additional_info = False
else:
print "- Faltando additional_info.shipments"
additional_info = False
else:
print "- Faltando additional_info"
return additional_info
def validarPayer(comments):
payer = False
# print comments["payer"]
if len(comments["payer"])!=0:
payer = True
if str(dictor(comments, "payer.email"))=="None":
payer = False
print "- Faltando payer.email"
if str(dictor(comments, "payer.first_name"))=="None":
payer = False
print "- Faltando payer.first_name"
if len(comments["payer"]["identification"])!=0:
if str(dictor(comments, "payer.identification.number"))=="None":
payer = False
print "- Faltando payer.identification.number"
if str(dictor(comments, "payer.identification.type"))=="None":
payer = False
print "- Faltando payer.identification.type"
return payer
def validarBinary(comments):
binary = False
# print comments["payer"]
if (comments["binary_mode"])==True:
binary = True
return binary
def validarStatus(comments):
status = False
# print comments["payer"]
if (comments["status"])=="rejected":
if (comments["status_detail"])=="cc_rejected_high_risk":
status = True
return status
def pagamentoFluxo(comments):
pagamento = False
if (comments["money_release_schema"])=="payment_in_flow":
pagamento = True
return pagamento
# ENVIO EMAIL PT 1
def enviarEmail(email, comments):
email_user = "<EMAIL>"
email_pass = "<PASSWORD>"
validade,conn = validarEmail(email_user, email_pass)
print comments
if validade == True:
executarEnvio(email_user,conn,comments,email)
else:
print "Erro ao validar conta de envio de email"
main()
# ENVIO EMAIL PT 2
def executarEnvio(email_user,conn,comments,destinatario):
FROM = email_user
TO = destinatario
#Escreve o e-mail
SUBJECT = "Validacao de pagamento"
text = str(comments)
#Formata a mensagem nos padroes de envio SMTP
#Envia o E-mail
message = MIMEMultipart()
message['From'] = FROM
message['To'] = TO
message['Subject'] = SUBJECT
message.attach(MIMEText(text, 'plain'))
email = message.as_string()
try:
conn.sendmail(FROM, TO, email)
os.system('clear') or None
print 'Email enviado com sucesso!'
main()
except:
print 'Fail...'
sys.exit()
#VALIDA O LOGIN E SENHA
def validarEmail(email_user, email_pass):
try:
conn = s.SMTP('smtp.gmail.com', 587)
conn.starttls()
conn.ehlo
conn.login(email_user, email_pass)
return True,conn
except:
print 'FALHA NA CONEXAO'
print '1 - VERIFIQUE SEU USUARIO E SENHA'
print '2 - CERTIFIQUE-SE DE QUE HABILITOU OS APLICATIVOS MENOS SEGUROS'
print 'URL: https://www.google.com/settings/security/lesssecureapps'
return False
def banner():
print """
---| MENU HOMOLOGATOR |-----------------------------------------------------------------------------------
| |
| 1 - VALIDAR UM PAGAMENTO |
| 2 - CONSULTAR COLLECTOR DE UM PAGAMENTO (Nao implementado) |
| 3 - GERAR ADM TOKEN |
| ATENCIOSAMENTE: MSS_IT |
-----------------------------------------------------------------------------------------------------------
"""
return True
main() | d4a20ab5d3c6f17d81ef743c29e5dab048d918bb | [
"Python"
] | 1 | Python | lfeitosa/homologator | bce23f481f8019dd7bc94c1e8d95bbc8ca1b84ff | f6546574be5e5706bd5f72cd2f8ab0f092b7bb67 | |
refs/heads/master | <file_sep>var mongoose = require('mongoose');
// Comment Schema
var CommentSchema = mongoose.Schema({
autor: String,
comentario: String,
data: String,
dataCompleta: String,
email: String,
site: String,
outros: String,
})
module.exports = CommentSchema;<file_sep># Blog template
Template de blog usando roteamento de views do express.<file_sep>let router = require('express').Router();
router.get('/:calc/:x/:y', (req, res) => {
console.log(req.params)
var z = {};
// console.log('x int: ', req.params.x.split('.')[0].length)
// console.log('x dot: ', req.params.x.split('.')[1].length)
// console.log('y int: ', req.params.y.split('.')[0].length)
// console.log('y dot: ', req.params.y.split('.')[1].length)
// console.log(req.params.x.split('.')[0].length / req.params.x.split('.')[1].length)
// console.log(req.params.y.split('.')[0].length / req.params.y.split('.')[1].length)
if (req.params.x.length > 16 ||
req.params.y.length > 16)
z.err = 'Params given are too high, the result is not going to be too accurate'
var x = parseFloat(req.params.x)
var y = parseFloat(req.params.y)
var calc = req.params.calc
console.log(x)
console.log(y)
if (isNaN(x) || isNaN(y)) {
return res.send({
err: 'Params given are not number type'
})
}
switch (calc) {
case '+':
case 'soma':
case 'plus':
case 'add':
z.result = x + y;
break;
case '-':
case 'sub':
case 'minus':
case 'less':
z.result = x - y;
break;
case '*':
case 'multi':
case 'mult':
case 'times':
z.result = x * y;
break;
case ':':
case 'div':
case 'take':
case 'split':
z.result = x / y;
break;
case '√':
case 'root':
case 'raiz':
z.result = Math.pow(x, 1 / y);
break;
case '^':
case 'exp':
z.result = Math.pow(x, y);
break;
default:
z.err = 'Operation \'' + calc + '\' not known';
}
console.log
res.send(z)
})
module.exports = router;<file_sep>$(document).ready(function () {
// Init Modal
$('.modal').modal();
$("select[required]").css({
display: "inline",
height: 0,
padding: 0,
width: 0
});
$('.button-collapse').sideNav();
});<file_sep>let path = require('path');
let express = require('express');
let cors = require('cors')
let bodyParser = require('body-parser');
let mongoose = require('mongoose');
let database = require('./config/database').database
let app = express();
mongoose.Promise = require('bluebird');
mongoose.connect(database, {
useMongoClient: true
}, (err) => {
if (err) return console.log("NÃO FOI POSSIVEL CONECTAR COM O MLAB\n" + err);
console.log("CONEXÃO COM O MLAB EFETUADA\nPORTA 3000");
});
var db = mongoose.connection;
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: false
}));
// parse application/json
app.use(bodyParser.json());
app.use(cors({
origin: "*",
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
preflightContinue: false,
optionsSuccessStatus: 204,
allowedHeaders: ['Origin', 'X-Requested-With', 'xx-access-token', 'Content-Type', 'Accept']
}))
// Load view engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use("/", express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
res.redirect('/articles');
})
var soma = require('./routes/soma');
app.use('/soma', soma);
// Router dos Artigos
var articles = require('./routes/articles');
app.use('/articles', articles);
// Router dos Admins
var admin = require('./routes/admins');
app.use('/admin', admin);
var articlesAPI = require('./routes/api/articles');
app.use('/api/articles', articlesAPI);
var calc = require('./routes/api/calc');
app.use('/api/calc', calc);
app.listen(process.env.PORT || 3000, () => {
var x = {};
x.port = process.env.PORT || 3000;
console.log('running', x.port)
})<file_sep>let router = require('express').Router();
let bcrypt = require('bcrypt');
let Admin = require('../models/admin');
let titulo = require('../config/titulo');
router.post('/', (req, res) => {
console.log('cadastrando...')
bcrypt.hash(req.body.senha, 5, (err, hash) => {
if (err) res.send({
err
});
var admin = new Admin({
username: req.body.username,
senha: hash
})
admin.save(admin, (err) => {
if (err) res.send({
err
});
console.log('cadastrado !!!')
res.send(admin);
})
})
})
router.post('/login/:view', (req, res) => {
Admin.findOne({
username: req.body.username
}, (err, admin) => {
if (err) return res.send({
err
})
if (!admin) return res.redirect('/')
bcrypt.compare(req.body.senha, admin.senha, (err, isMatch) => {
if (err) res.send({err});
if (isMatch) res.render(req.params.view, {
pode: true,
titulo: titulo + 'Adicionar post'
});
else res.redirect('/')
});
});
});
module.exports = router;<file_sep>let router = require('express').Router();
let Article = require('../models/article');
let titulo = require('../config/titulo');
router.get('/', (req, res) => {
Article.find({}).sort({
_id: -1
}).exec((err, artigos) => {
if (err) res.send({
err
});
res.render('blog', {
artigos,
titulo: titulo + "posts"
});
})
})
router.get('/:id', (req, res) => {
Article.findById(req.params.id, (err, artigo) => {
if (err) res.send({
err
});
res.render('artigo', {
artigo,
titulo: titulo + artigo.nome
});
});
});
router.get('/tag/:tag', (req, res) => {
var tag = req.params.tag;
Article.find({
tags: tag
}).sort({
_id: -1
}).exec((err, artigos) => {
if (err) res.send({
err
});
res.render('resultado', {
artigos,
tag,
titulo: titulo + tag,
});
});
});
router.post('/', (req, res) => {
var d = new Date();
var article = new Article({
nome: req.body.nome,
dataCompleta: d.toString(),
data: getDateNow(d),
corpo: req.body.corpo,
tags: getTags(req.body.tags),
});
article.save(article, (err) => {
if (err) res.send({
err
})
res.redirect('/articles');
})
})
router.put('/:id', (req, res) => {
console.log('putando')
if (req.body.tags) var article = new Article({
_id: req.params.id,
nome: req.body.nome,
corpo: req.body.corpo,
tags: getTags(req.body.tags),
})
else var article = new Article({
_id: req.params.id,
nome: req.body.nome,
corpo: req.body.corpo,
})
article.update(article, (err) => {
console.log('updateando')
if (err) res.send({
err
})
res.redirect('/articles');
});
})
router.post('/comment/:post', (req, res) => {
var d = new Date();
Article.findById(req.params.post, (err, postBD) => {
if (err) res.send({
err
});
var comment = {
autor: req.body.autor,
comentario: req.body.comentario,
email: req.body.email,
site: req.body.site,
outros: req.body.outros,
dataCompleta: d.toString(),
data: getDateNow(d)
}
postBD.comentarios.push(comment)
let post = new Article(postBD)
post.save(post, (err) => {
console.log(postBD._id)
var url = '/articles/' + postBD._id.toString();
res.redirect(url)
})
})
})
function getDateNow(d) {
var aux = d.toString().split(' ');
var str = '';
for (var i = 1; i < 4; i++)
str += (i == 3) ? aux[i] : aux[i] + ' ';
return str;
}
function getTags(str) {
var aux = [];
str.split(',').map((tag) => {
aux.push(tag.trim().toLowerCase())
})
aux = aux.filter(function (item, pos) {
return aux.indexOf(item) == pos;
})
return aux;
}
router.get('/test/', (req, res) => {
res.send(teste())
})
function teste() {
Article.findById('5a34a6d3a001a60014c34d23').exec((err, res) => {
if (err) return {err, res};
return res
})
}
module.exports = router;<file_sep>let router = require('express').Router();
router.get('/:x/:y', (req, res) => {
res.render('soma', {
soma: parseInt(req.params.x) + parseInt(req.params.y)
});
})
module.exports = router; | 6c32a2c835a5f4622eebfae089401de5216671f0 | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | wilkerHop/blog | 0904b9559f054f09a38dd2f0e829eb7fb88a8bc7 | 7081ff5aa3c5180cb4046e17abfc0a41e7c12a80 | |
refs/heads/master | <repo_name>danico90/yii2-boilerplate<file_sep>/web/src/js/pages/page.js
/*
* Page
*/
console.log('Page');
<file_sep>/web/src/js/components/component.js
/*
* Components
*/
console.log('components');<file_sep>/db/1.sql
-- phpMyAdmin SQL Dump
-- version 4.6.4
-- https://www.phpmyadmin.net/
--
-- Host: localhost:8889
-- Generation Time: Sep 24, 2016 at 06:37 AM
-- Server version: 5.6.28
-- PHP Version: 7.0.10
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
--
-- Database: `test`
--
-- --------------------------------------------------------
--
-- Table structure for table `appuser`
--
CREATE TABLE `appuser` (
`UserID` int(11) NOT NULL,
`Name` varchar(100) NOT NULL,
`LastName` varchar(100) NOT NULL,
`Active` int(1) NOT NULL,
`Password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `appuser`
--
INSERT INTO `appuser` (`UserID`, `Name`, `LastName`, `Active`, `Password`) VALUES
(1, 'Daniel', 'Jimenez', 1, '<PASSWORD>'),
(2, 'Popin', 'Canessa', 1, 'playo');
-- --------------------------------------------------------
--
-- Table structure for table `Role`
--
CREATE TABLE `Role` (
`RoleID` int(11) NOT NULL,
`Description` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `Role`
--
INSERT INTO `Role` (`RoleID`, `Description`) VALUES
(1, 'Admin'),
(2, 'Puta');
-- --------------------------------------------------------
--
-- Table structure for table `UserRole`
--
CREATE TABLE `UserRole` (
`UserID` int(11) NOT NULL,
`RoleID` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `UserRole`
--
INSERT INTO `UserRole` (`UserID`, `RoleID`) VALUES
(1, 1),
(2, 2);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `appuser`
--
ALTER TABLE `appuser`
ADD PRIMARY KEY (`UserID`);
--
-- Indexes for table `Role`
--
ALTER TABLE `Role`
ADD PRIMARY KEY (`RoleID`);
--
-- Indexes for table `UserRole`
--
ALTER TABLE `UserRole`
ADD PRIMARY KEY (`UserID`,`RoleID`),
ADD KEY `FK_RoleUserRole` (`RoleID`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `appuser`
--
ALTER TABLE `appuser`
MODIFY `UserID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `Role`
--
ALTER TABLE `Role`
MODIFY `RoleID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `UserRole`
--
ALTER TABLE `UserRole`
ADD CONSTRAINT `userrole_ibfk_1` FOREIGN KEY (`UserID`) REFERENCES `appuser` (`UserID`),
ADD CONSTRAINT `userrole_ibfk_2` FOREIGN KEY (`RoleID`) REFERENCES `Role` (`RoleID`);
| 799a7f0a6f034665623fa7c0613b630bd6f20da8 | [
"JavaScript",
"SQL"
] | 3 | JavaScript | danico90/yii2-boilerplate | 0c62653cf6719fc04ab01632e54b512a2d36ae75 | 9eecbe4caefb41a0f623c1b766539778c3e52a45 | |
refs/heads/master | <repo_name>ibanez1/lab-angular-data-binding<file_sep>/starter-code/src/app/food-list/food-list.component.ts
import { Component, OnInit } from '@angular/core';
import foods from '../foods';
@Component({
selector: 'app-food-list',
templateUrl: './food-list.component.html',
styleUrls: ['./food-list.component.css']
})
export class FoodListComponent implements OnInit {
foods: Object[];
newFood: Object = {};
listFood: Object[];
totalCalories: number;
totalQuantity: number;
constructor() {
this.listFood = [];
this.totalCalories = 0;
this.totalQuantity = 0;
}
ngOnInit() {
this.foods = foods;
}
addItem($event, name, calories, image) {
this.foods.unshift({name, calories, image, quantity: 1});
}
addList($event, item, quantity) {
item.quantity = parseInt(quantity);
if( this.listFood.indexOf(item) == -1 ) {
if( this.totalCalories == 0 ) {
this.totalCalories = item.calories * quantity;
} else {
this.totalCalories += item.calories * quantity;
}
this.listFood.push(item);
} else {
this.totalCalories += item.calories * quantity;
}
}
public show:boolean = false;
public buttonName = 'Add new Food';
toggle() {
this.show = !this.show;
// CHANGE THE NAME OF THE BUTTON.
if(this.show)
this.buttonName = "Hide";
else
this.buttonName = "Add new Food";
}
}
| ef23e5b3ed876bca5a423a5eb2a9a9044f248544 | [
"TypeScript"
] | 1 | TypeScript | ibanez1/lab-angular-data-binding | 66af0ff072fd4b576a6326431bec6251d43e4025 | eb0265e9d455ab5cab9cbab0c938830eb00d3168 | |
refs/heads/master | <repo_name>shihanng/gogettext<file_sep>/README.md
# gettext in golang
[](https://travis-ci.org/ojii/gogettext)
## TODO
- [x] parse mofiles
- [x] compile plural forms
- [ ] non-utf8 mo files (possible wontfix)
- [x] gettext
- [x] ngettext
- [ ] managing mo files / sane API
<file_sep>/pluralforms/math.go
package pluralforms
import "fmt"
type Math interface {
Calc(n uint32) uint32
String() string
}
type Mod struct {
Value uint32
}
func (m Mod) Calc (n uint32) uint32 {
return n % m.Value
}
func (m Mod) String() string {
return fmt.Sprintf("<Mod(%d)>", m.Value)
}<file_sep>/pluralforms/compiler.go
package pluralforms
import (
"strings"
"regexp"
"errors"
"fmt"
"strconv"
)
type match struct {
OpenPos int
ClosePos int
}
var pat = regexp.MustCompile(`(\?|:|\|\||&&|==|!=|>=|>|<=|<|%|\d+|n)`)
type expr_token interface {
Compile(tokens []string) (expr Expression, err error)
}
type test_token interface {
Compile(tokens []string) (test Test, err error)
}
type cmp_test_builder func(val uint32, flipped bool) Test
type logic_test_build func(left Test, right Test) Test
var ternary ternary_
type ternary_ struct {}
func (ternary_) Compile(tokens []string) (expr Expression, err error){
main, err := split_tokens(tokens, "?")
if err != nil {
return expr, err
}
test, err := compile_test(strings.Join(main.Left, ""))
if err != nil {
return expr, err
}
actions, err := split_tokens(main.Right, ":")
if err != nil {
return expr, err
}
true_action, err := compile_expression(strings.Join(actions.Left, ""))
if err != nil {
return expr, err
}
false_action, err := compile_expression(strings.Join(actions.Right, ""))
if err != nil {
return expr, nil
}
return Ternary{
Test: test,
True: true_action,
False: false_action,
}, nil
}
var const_val const_val_
type const_val_ struct {}
func (const_val_) Compile(tokens []string) (expr Expression, err error){
if len(tokens) == 0 {
return expr, errors.New("Got nothing instead of constant")
}
if len(tokens) != 1 {
return expr, errors.New(fmt.Sprintf("Invalid constant: %s", strings.Join(tokens, "")))
}
i, err := strconv.Atoi(tokens[0])
if err != nil {
return expr, err
}
return Const{Value: i}, nil
}
func compile_logic_test(tokens []string, sep string, builder logic_test_build) (test Test, err error) {
split, err := split_tokens(tokens, sep)
if err != nil {
return test, err
}
left, err := compile_test(strings.Join(split.Left, ""))
if err != nil {
return test, err
}
right, err := compile_test(strings.Join(split.Right, ""))
if err != nil {
return test, err
}
return builder(left, right), nil
}
var or or_
type or_ struct {}
func (or_) Compile(tokens []string) (test Test, err error){
return compile_logic_test(tokens, "||", build_or)
}
func build_or(left Test, right Test) Test {
return Or{Left: left, Right: right}
}
var and and_
type and_ struct {}
func (and_) Compile(tokens []string) (test Test, err error){
return compile_logic_test(tokens, "&&", build_and)
}
func build_and(left Test, right Test) Test {
return And{Left: left, Right: right}
}
func compile_mod(tokens []string) (math Math, err error){
split, err := split_tokens(tokens, "%")
if err != nil {
return math, err
}
if len(split.Left) != 1 || split.Left[0] != "n" {
return math, errors.New("Modulus operation requires 'n' as left operand")
}
if len(split.Right) != 1 {
return math, errors.New("Modulus operation requires simple integer as right operand")
}
i, err := parse_uint32(split.Right[0])
if err != nil {
return math, err
}
return Mod{Value: uint32(i)}, nil
}
func _pipe(mod_tokens []string, action_tokens []string, builder cmp_test_builder, flipped bool) (test Test, err error){
modifier, err := compile_mod(mod_tokens)
if err != nil {
return test, err
}
if len(action_tokens) != 1 {
return test, errors.New("Can only get modulus of integer")
}
i, err := parse_uint32(action_tokens[0])
if err != nil {
return test, err
}
action := builder(uint32(i), flipped)
return Pipe{
Modifier: modifier,
Action: action,
}, nil
}
func compile_equality(tokens []string, sep string, builder cmp_test_builder) (test Test, err error){
split, err := split_tokens(tokens, sep)
if err != nil {
return test, err
}
if len(split.Left) == 1 && split.Left[0] == "n" {
if len(split.Right) != 1 {
return test, errors.New("test can only compare n to integers")
}
i, err := parse_uint32(split.Right[0])
if err != nil {
return test, err
}
return builder(i, false), nil
} else if len(split.Right) == 1 && split.Right[0] == "n" {
if len(split.Left) != 1 {
return test, errors.New("test can only compare n to integers")
}
i, err := parse_uint32(split.Left[0])
if err != nil {
return test, err
}
return builder(i, true), nil
} else if contains(split.Left, "n") && contains(split.Left, "%") {
return _pipe(split.Left, split.Right, builder, false)
} else {
return test, errors.New("equality test must have 'n' as one of the two tests")
}
}
var eq eq_
type eq_ struct {}
func (eq_) Compile(tokens []string) (test Test, err error){
return compile_equality(tokens, "==", build_eq)
}
func build_eq(val uint32, flipped bool) Test {
return Equal{Value: val}
}
var neq neq_
type neq_ struct {}
func (neq_) Compile(tokens []string) (test Test, err error){
return compile_equality(tokens, "!=", build_neq)
}
func build_neq(val uint32, flipped bool) Test {
return NotEqual{Value: val}
}
var gt gt_
type gt_ struct {}
func (gt_) Compile(tokens []string) (test Test, err error){
return compile_equality(tokens, ">", build_gt)
}
func build_gt(val uint32, flipped bool) Test {
return Gt{Value: val, Flipped: flipped}
}
var gte gte_
type gte_ struct {}
func (gte_) Compile(tokens []string) (test Test, err error){
return compile_equality(tokens, ">=", build_gte)
}
func build_gte(val uint32, flipped bool) Test {
return GtE{Value: val, Flipped: flipped}
}
var lt lt_
type lt_ struct {}
func (lt_) Compile(tokens []string) (test Test, err error){
return compile_equality(tokens, "<", build_lt)
}
func build_lt(val uint32, flipped bool) Test {
return Lt{Value: val, Flipped: flipped}
}
var lte lte_
type lte_ struct {}
func (lte_) Compile(tokens []string) (test Test, err error){
return compile_equality(tokens, "<=", build_lte)
}
func build_lte(val uint32, flipped bool) Test {
return LtE{Value: val, Flipped: flipped}
}
type test_token_def struct {
Op string
Token test_token
}
var precedence = []test_token_def{
test_token_def{Op: "||", Token: or},
test_token_def{Op: "&&", Token: and},
test_token_def{Op: "==", Token: eq},
test_token_def{Op: "!=", Token: neq},
test_token_def{Op: ">=", Token: gte},
test_token_def{Op: ">", Token: gt},
test_token_def{Op: "<=", Token: lte},
test_token_def{Op: "<", Token: lt},
}
type splitted struct {
Left []string
Right []string
}
func index(tokens []string, sep string) int {
for index, token := range tokens {
if token == sep {
return index
}
}
return -1
}
func split_tokens(tokens []string, sep string) (s splitted, err error) {
index := index(tokens, sep)
if index == -1 {
return s, errors.New(fmt.Sprintf("'%s' not found in ['%s']", sep, strings.Join(tokens, "','")))
}
return splitted{
Left: tokens[:index],
Right: tokens[index + 1:],
}, nil
}
func scan(s string) []match {
ret := []match{}
depth := 0
opener := 0
for index, char := range s {
switch char {
case '(':
if depth == 0 {
opener = index
}
depth++
case ')':
depth--
if depth == 0 {
ret = append(ret, match{OpenPos: opener, ClosePos: index + 1})
}
}
}
return ret
}
func split(s string) []string {
s = strings.Replace(s, " ", "", -1)
if !strings.Contains(s, "("){
return []string{s}
}
last := 0
end := len(s)
ret := []string{}
for _, info := range scan(s) {
if last != info.OpenPos {
ret = append(ret, s[last:info.OpenPos])
}
ret = append(ret, s[info.OpenPos:info.ClosePos])
last = info.ClosePos
}
if last != end {
ret = append(ret, s[last:])
}
return ret
}
func tokenize(s string) []string {
/*
TODO: Properly detect if the string starts with a ( and ends with a )
and that those two form a matching pair.
Eg: (foo) -> true; (foo)(bar) -> false;
*/
//if s[0] == '(' && strings.Count(s, "(") == 1 && s[len(s)-1] == ')' {
if s[0] == '(' && s[len(s)-1] == ')' {
s = s[1:len(s)-1]
}
ret := []string{}
for _, chunk := range split(s) {
if len(chunk) != 0 {
if chunk[0] == '(' && chunk[len(chunk)-1] == ')' {
ret = append(ret, chunk)
} else {
for _, token := range pat.FindAllStringSubmatch(chunk, -1){
ret = append(ret, token[0])
}
}
} else {
fmt.Printf("Empty chunk in string '%s'\n", s)
}
}
return ret
}
func Compile(s string) (expr Expression, err error) {
if s == "0" {
return Const{Value: 0}, nil
}
if !strings.Contains(s, "?") {
s += "?1:0"
}
return compile_expression(s)
}
func contains(haystack []string, needle string) bool {
for _, s := range haystack {
if s == needle {
return true
}
}
return false
}
func compile_expression(s string) (expr Expression, err error) {
tokens := tokenize(s)
if contains(tokens, "?") {
return ternary.Compile(tokens)
} else {
return const_val.Compile(tokens)
}
}
func compile_test(s string) (test Test, err error) {
tokens := tokenize(s)
for _, token_def := range precedence {
if contains(tokens, token_def.Op) {
return token_def.Token.Compile(tokens)
}
}
return test, errors.New("Cannot compile")
}
func parse_uint32(s string) (ui uint32, err error){
i, err := strconv.ParseUint(s, 10, 32)
if err != nil {
return ui, err
} else {
return uint32(i), nil
}
}
<file_sep>/pluralforms/ternary.go
package pluralforms
import "fmt"
type Test interface {
Test(n uint32) bool
String() string
}
type Ternary struct {
Test Test
True Expression
False Expression
}
func (t Ternary) Eval (n uint32) int {
if (t.Test.Test(n)){
if t.True == nil {
return -1
}
return t.True.Eval(n)
} else {
if t.False == nil {
return -1
}
return t.False.Eval(n)
}
}
func (t Ternary) String() string {
return fmt.Sprintf("<Ternary(%s?%s:%s)>", t.Test, t.True, t.False)
}
<file_sep>/pluralforms/expression.go
package pluralforms
import (
"fmt"
"strings"
)
type Expression interface {
Eval(n uint32) int
String() string
}
type Const struct {
Value int
}
func (c Const) Eval (n uint32) int {
return c.Value
}
func (c Const) String() string {
return fmt.Sprintf("<Const:%d>", c.Value)
}
func Pformat(expr Expression) string {
ret := ""
s := expr.String()
level := -1
for _, rune := range s {
switch rune {
case '<':
level++
ret += "\n" + strings.Repeat(" ", level)
case '>':
level--
if level >= 0 {
ret += "\n" + strings.Repeat(" ", level)
}
case ':', '?', '|':
default:
ret += fmt.Sprintf("%c", rune)
}
}
return strings.Replace(ret, "\n\n", "\n", -1)
}
| 5f8e82c36de4ef61e043961a00c29d85fc48ff60 | [
"Markdown",
"Go"
] | 5 | Markdown | shihanng/gogettext | 4c4e0aec8eba8f2842e06db9cc7f0a3789666371 | 19b1a1603525efb3ae2f5d59f0dea268700f8b8a | |
refs/heads/main | <file_sep>hIIIIIIIIIIIIIIIIIIIII!!!!
| 02aba9249e4919292b5f419c5aac665091a0be3c | [
"Python"
] | 1 | Python | eshmet/gitinitpython | dc459df3dfd850be06a67f6f558bc8b62d11a8ee | 099ba3e21677eff6c514b483780a256689b6ee71 | |
refs/heads/master | <file_sep>import path from 'path';
import { Request, Response, Router } from 'express';
import http from 'http';
import LoggerFactory from '../util/LoggerFactory';
import { async } from 'q';
const logger = LoggerFactory.getLogger();
export class DispatchController {
/**
* GET /
* Home page.
*/
dispatch(req: Request, res: Response) {
logger.debug('dispatch(): req.url=%s', req.url);
logger.debug('dispatch(): req.query=%o', req.query);
logger.debug('dispatch(): req.params=%o', req.params);
var url = 'http://localhost' + req.url;
logger.debug('dispatch(): url=%s', url);
return (async () => {
try {
var response = await this.get(url);
logger.debug('dispatch(): response=%s', response);
return res.send(response);
} catch (error) {
logger.error(error);
return res.status(500).json({
message: error.message,
x: error.stack,
});
}
})();
// const filePath = path.join(__dirname, '../index.html');
// logger.log('index: __dirname=%s', __dirname);
// logger.log('index: filePath=%s', filePath);
// res.sendFile(filePath);
}
private get(url: string) {
// let body = '';
return new Promise((resolve, reject) => {
http.get(url, res => {
const { statusCode } = res;
const contentType = res.headers['content-type'];
logger.debug('get() on data: statusCode=%s, contentType=%s', statusCode, contentType);
let error;
if (statusCode !== 200 && statusCode !== 302) {
error = new Error('Request Failed.\n' +
`Status Code: ${statusCode}`);
// } else if (!/^application\/json/.test(contentType)) {
// error = new Error('Invalid content-type.\n' +
// `Expected application/json but received ${contentType}`);
}
if (error) {
logger.error(error);
// Consume response data to free up memory
// res.resume();
reject(error);
return;
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', chunk => {
logger.debug('get() on data: chunk=%o', chunk);
rawData += chunk;
});
res.on('end', () => {
var res = JSON.parse(rawData);
try {
const parsedData = JSON.parse(rawData);
logger.debug('parsedDat=%o', parsedData);
resolve(parsedData);
} catch (e) {
logger.error(e);
reject(e);
}
});
}).on('error', err => {
logger.error(err);
reject(err);
});
});
}
}
export const DispatcRouterFactory = {
create: () => {
const controller = new DispatchController();
const router = Router();
router.get('/dispatch', controller.dispatch.bind(controller));
return router;
}
};
| 1c6e5f117d6f75c3598d4387ea3ebd485cadf32e | [
"TypeScript"
] | 1 | TypeScript | tomatono-git/ts-express | 13d39d2989948c9e3404cfaa749cb30943a0d909 | a75a3130ed7c0d269382c100bf0b058f96b178f7 | |
refs/heads/master | <repo_name>GalDude33/SnakeRL<file_sep>/policies/policy_ConvDQN.py
from keras import Sequential
from keras.layers import Flatten, Dense, Conv2D, BatchNormalization
from policies.policy_BaseDQN import BaseDQN, SQUARE, NO, FLIP, SPATIAL, FULL
class ConvDQN(BaseDQN):
"""
A Deep Q-Learning implementation with a Convolutional Network as the Q estimator
"""
def _additional_args(self, policy_args):
self.flatten = NO
self.state_radius = 6
self.step_forward = True
self.state_rep = SQUARE
self.doubleDQN = True
self.gamma = 0.75
# for self
self.batch_norm = False
return policy_args
def _build_model(self):
model = Sequential()
model.add(Conv2D(4, 1, strides=1,
activation='relu',
input_shape=self.input_shape))
model.add(Conv2D(16, 4, strides=2,
activation='relu', padding='same'))
if self.batch_norm:
model.add(BatchNormalization())
model.add(Conv2D(32, 4, strides=2,
activation='relu', padding='same'))
if self.batch_norm:
model.add(BatchNormalization())
model.add(Conv2D(64, 3, strides=1,
activation='relu'))
if self.batch_norm:
model.add(BatchNormalization())
model.add(Flatten())
model.add(Dense(128, activation='relu'))
if self.batch_norm:
model.add(BatchNormalization())
model.add(Dense(3, activation=None))
return model<file_sep>/policies/policy_RadarDQN.py
from keras import Sequential
from keras.engine import InputLayer
from keras.layers import Flatten, Dense, Conv2D, Dropout, LeakyReLU
from policies.policy_BaseDQN import BaseDQN, DIAMOND, SQUARE, RADAR, NO, FLIP, SPATIAL, FULL, NUM_PER_TYPE
class RadarDQN(BaseDQN):
"""
Our attempt at implementing a network that uses only Radar State representation
"""
def _additional_args(self, policy_args):
#self.state_radius = 4
#self.step_forward = True
self.state_rep = RADAR
self.doubleDQN = True
# for self
self.dropout_rate = 0.0
self.activation = LeakyReLU
return policy_args
def _build_model(self):
model = Sequential()
model.add(InputLayer(self.input_shape))
model.add(Conv2D(filters=64, kernel_size=1, data_format='channels_first'))
model.add(self.activation())
model.add(Conv2D(filters=64, kernel_size=1, data_format='channels_first'))
model.add(self.activation())
model.add(Conv2D(filters=16, kernel_size=1, data_format='channels_first'))
model.add(self.activation())
model.add(Flatten())
model.add(Dense(units=256))
model.add(self.activation())
if self.dropout_rate > 0:
model.add(Dropout(self.dropout_rate))
model.add(Dense(units=256))
model.add(self.activation())
if self.dropout_rate > 0:
model.add(Dropout(self.dropout_rate))
model.add(Dense(units=128))
model.add(self.activation())
model.add(Dense(units=3))
return model
<file_sep>/utils/ReplayBuffer.py
from collections import deque
import numpy as np
class ReplayBuffer:
"""
Self-maintaining limited length replay-buffer, with option to append records and sample batches
"""
def __init__(self, maxlen, prefer_new=True, new_range=300, new_rate=0.40):
self.buffer = deque(maxlen=maxlen)
# "prefer new" parameters
self.prefer_new = prefer_new
self.new_range = new_range
self.new_rate = new_rate
def __len__(self):
return self.buffer.__len__()
def record(self, prev, action, reward, new):
self.buffer.append((prev, action, reward, new))
def sample(self, batch_size):
if self.buffer.__len__() > batch_size:
if self.prefer_new:
probs = np.ones(self.buffer.__len__())
probs[-self.new_range:] *= (self.new_rate * self.buffer.__len__())/self.new_range
probs /= probs.sum()
else:
probs = None
batch = np.array(self.buffer)[np.random.choice(self.buffer.__len__(), batch_size, p=probs)]
else:
batch = np.array(list(self.buffer))
prev = np.stack(batch[:, 0])
actions = np.vstack(batch[:, 1]).squeeze()
rewards = np.vstack(batch[:, 2]).squeeze()
new = np.stack(batch[:, 3])
return prev, actions, rewards, new
<file_sep>/policies/policy_ConvDuelDQN.py
from keras import Input, Model
from keras.layers import Flatten, Dense, Conv2D, Lambda, Add, BatchNormalization
import keras.backend as K
from policies.policy_BaseDQN import BaseDQN, SQUARE, NO, FLIP, SPATIAL, FULL
from policies.policy_PriorityBaseDQN import PriorBaseDQN
class ConvDuelDQN(PriorBaseDQN):
"""
A Dueling Deep Q-Learning implementation with a Convolutional Network as the Q estimator
"""
def _additional_args(self, policy_args):
self.flatten = NO
self.epsilon_decay = 0.98
self.min_epsilon = 0.1
self.state_radius = 6
self.step_forward = True
self.state_rep = SQUARE
self.doubleDQN = True
self.gamma = 0.75
# for self
self.batch_norm = False
return policy_args
def _build_model(self):
inputs = Input(self.input_shape)
net = Conv2D(4, 1, strides=1, activation='relu')(inputs)
net = Conv2D(32, 4, strides=2, activation='relu', padding='same')(net)
if self.batch_norm:
net = BatchNormalization()(net)
net = Conv2D(45, 4, strides=2, activation='relu')(net)
if self.batch_norm:
net = BatchNormalization()(net)
net = Flatten()(net)
advt = Dense(128, activation='relu')(net)
if self.batch_norm:
advt = BatchNormalization()(advt)
Advantage = Dense(3)(advt)
value = Dense(128, activation='relu')(net)
if self.batch_norm:
value = BatchNormalization()(value)
Value = Dense(1)(value)
advt = Lambda(lambda advt: advt - K.mean(advt, axis=-1, keepdims=True))(Advantage)
value = Lambda(lambda value: K.tile(value, [1, 3]))(Value)
Q_out = Add()([value, advt])
return Model(inputs=[inputs], outputs=[Q_out])
<file_sep>/nn_utils/losses.py
import tensorflow as tf
def huber_loss(y_true, y_pred):
"""huber loss - supposed to improve stability"""
return tf.losses.huber_loss(y_true, y_pred)
<file_sep>/policies/policy_RadarPlusDQN.py
from keras import Input, Model
from keras.layers import Conv1D, Flatten, Dense, Dropout, LeakyReLU, Concatenate
from policies.policy_RadarBaseDQN import RadarBaseDQN, DIAMOND, SQUARE, RADAR, NO, FLIP, SPATIAL, FULL,\
NUM_PER_TYPE, RADAR_PLUS
class RadarPlusDQN(RadarBaseDQN):
"""
Our attempt at implementing a more advanced network that uses Radar and Square states together
"""
def _additional_args(self, policy_args):
self.flatten = SPATIAL
self.state_radius = 6
self.step_forward = True
self.state_rep = RADAR_PLUS
self.doubleDQN = True
self.batch_size = 96
self.epsilon_decay = 0.98
self.min_epsilon = 0.2
# for self
self.dropout_rate = 0.0
self.activation = LeakyReLU
return policy_args
def _build_model(self):
input_layer = Input(self.input_shape[0])
net = self.activation()(Conv1D(filters=4, kernel_size=1)(input_layer))
net = Flatten()(net)
net = self.dense_layer(net, units=128)
input_layer_radar = Input(self.input_shape[1])
net_radar = Flatten(input_shape=self.input_shape[1])(input_layer_radar)
net_radar = self.dense_layer(net_radar, units=64)
net = Concatenate()([net, net_radar])
net = self.dense_layer(net, units=128)
Q_out = self.dense_layer(net, units=3)
return Model(inputs=[input_layer, input_layer_radar], outputs=[Q_out])
def dense_layer(self, input_layer, units):
net = Dense(units=units)(input_layer)
net = self.activation()(net) # apply activation
if self.dropout_rate > 0:
net = Dropout(self.dropout_rate)(net)
return net
<file_sep>/policies/policy_linear.py
from keras import Sequential
from keras.layers import Dense, Flatten
from policies.policy_BaseDQN import BaseDQN, SQUARE, DIAMOND, NO, FLIP, SPATIAL, FULL, NUM_PER_TYPE
class LinearQL(BaseDQN):
"""
A Deep Q-Learning implementation with a simple linear network as the Q estimator
"""
def _additional_args(self, policy_args):
self.flatten = FULL
self.state_radius = 4
self.step_forward = True
self.state_rep = SQUARE
self.batch_size = 96
self.save_model_round = 200
policy_args['min_epsilon'] = 0.3
policy_args['epsilon'] = 1.0
policy_args['gamma'] = 0.5
return policy_args
def _build_model(self):
model = Sequential()
model.add(Dense(input_shape=self.input_shape, units=3, activation=None, use_bias=True))
return model
<file_sep>/state_utils/State.py
import numpy as np
from keras.utils import to_categorical
from policies import base_policy as bp
MAP_VALUES = np.arange(-1, 9 + 1)
NUM_VALUES = len(MAP_VALUES)
NO = 0
FLIP = 1
ALL = 2
SPATIAL = 1
FULL = 2
NUM_PER_TYPE = 2
def normalize(matrix, direction, normalize):
"""
Normalize direction that snake is facing, either to North only for FULL or to North/East for FLIP, by
rotating the board/matrix
"""
if normalize == NO:
return matrix
rot = 0 # direction is already 'N'
if direction == 'E':
rot = 1 + (1 if normalize == FLIP else 0)
elif direction == 'S':
rot = 2
elif direction == 'W':
rot = (0 if normalize == FLIP else 3)
return np.rot90(matrix, rot)
def augment_after_normaliztion(prev_state_repr, prev_state_dir, prev_action, reward, new_state_repr, new_state_dir,
radius, normalize=FLIP):
""" Augment states to visit more states by exploiting symmetries, even though we didn't actually visit them"""
def flip_state(s, dir):
orig_shape = s.shape
if normalize == ALL:
flip_ax = 1
else:
if dir in {'E', 'W'}:
flip_ax = 0
else: # if dir in {'N', 'S'}
flip_ax = 1
return np.flip(s.reshape((2*radius+1, 2*radius+1, NUM_VALUES)), axis=flip_ax).reshape(orig_shape)
def flip_action(a):
if bp.Policy.ACTIONS[a] == 'R':
return bp.Policy.ACTIONS.index('L')
elif bp.Policy.ACTIONS[a] == 'L':
return bp.Policy.ACTIONS.index('R')
return a
return flip_state(prev_state_repr, prev_state_dir), \
prev_action, \
reward, \
flip_state(new_state_repr, new_state_dir)
class SquareAroundHeadState:
"""
Normalized square around head, l_inf radius
"""
def __init__(self, radius, step_forward=True, flatten=FULL, normalize=FLIP):
self.radius = radius
self.step_forward = step_forward
self.flatten = flatten
self.normalize = normalize
def get_area(self):
return (self.radius * 2 + 1) ** 2
def get_shape(self):
if self.flatten == FULL:
return (self.get_area() * NUM_VALUES,)
elif self.flatten == SPATIAL:
return (self.get_area(), NUM_VALUES)
else: # no flattening
diameter = 1 + 2 * self.radius
return (diameter, diameter, NUM_VALUES)
def get_state_repr(self, state):
board, head = state
head_pos, direction = head
if self.step_forward:
head_pos = head_pos.move(bp.Policy.TURNS[direction]['F'])
x, y = head_pos
# slicing along axes
board = np.take(board, range(x - self.radius, x + self.radius + 1), axis=0, mode='wrap')
output_state = np.take(board, range(y - self.radius, y + self.radius + 1), axis=1, mode='wrap')
# normalize
output_state = normalize(output_state, direction, self.normalize)
output_state = to_categorical(output_state + 1, num_classes=NUM_VALUES)
if self.flatten == FULL:
output_state = output_state.reshape(-1)
elif self.flatten == SPATIAL:
output_state = output_state.reshape(-1, NUM_VALUES)
return output_state
# '''
# l2 radius - euclidean distance
# '''
# class CircleAroundHeadState:
#
# def __init__(self, radius, step_forward=True):
# self.radius = radius
# self.step_forward = step_forward
#
# def get_state_repr(self, state):
# board, head = state
# head_pos, direction = head
#
# n_x, n_y = board.shape
#
# if self.step_forward:
# head_pos = head_pos.move(bp.Policy.TURNS[direction]['F'])
# x, y = head_pos
#
# def get_dists(size, ind):
# all_inds = np.arange(size)
# return np.min([np.abs((all_inds - size) - ind),
# np.abs((all_inds + size) - ind),
# np.abs(all_inds - ind)],
# axis=0)
#
# rows = get_dists(n_x, x)
# cols = get_dists(n_y, y)
# mask = (rows[:, None] ** 2 + cols ** 2 <= self.radius ** 2).astype(bool)
# return to_categorical(board[mask] + 1, num_classes=NUM_VALUES).reshape(-1)
class DiamondAroundHeadState:
"""
Normalized diamond around head, l_1 radius
"""
def __init__(self, radius, step_forward=True, flatten=FULL, normalize=FLIP):
self.radius = radius
self.step_forward = step_forward
self.flatten = flatten
self.square_state = SquareAroundHeadState(radius=radius, step_forward=step_forward, flatten=NO,
normalize=normalize)
def get_area(self):
return round((self.radius * 2 + 1) ** 2 // 2 + 1)
def get_shape(self):
if self.flatten == FULL:
return (self.get_area() * NUM_VALUES,)
elif self.flatten == SPATIAL:
return (self.get_area(), NUM_VALUES)
def get_state_repr(self, state):
board = self.square_state.get_state_repr(state)
output_state = []
for d in range(-self.radius, self.radius + 1):
col_radius = np.abs(self.radius - np.abs(d))
output_state += [board[d + self.radius][(self.radius) - col_radius: (self.radius + 1) + col_radius]]
output_state = np.vstack(output_state).squeeze()
if self.flatten == FULL:
output_state = output_state.reshape(-1)
elif self.flatten == SPATIAL:
output_state = output_state.reshape(-1, NUM_VALUES)
return output_state
def get_dists(size, ind):
return np.abs(get_directions(size, ind))
def get_directions(size, ind):
all_inds = np.arange(size)
all_dirs = np.array([all_inds - size - ind, all_inds + size - ind, (all_inds - ind)])
dirs = all_dirs[np.argmin(np.abs(all_dirs), axis=0), range(size)]
return dirs
class RadarState:
"""
Sort of a radar around the snake's head. Returns directions and distances to num_per_type objects of each type
"""
def __init__(self, num_per_type, polars=True, normalize=FLIP):
self.num_per_type = num_per_type
self.polars = polars
self.normalize = normalize
def get_shape(self):
return [NUM_VALUES, self.num_per_type, 3]
def get_state_repr(self, state):
board, head = state
head_pos, direction = head
board = normalize(board, direction, self.normalize)
x, y = head_pos
n_x, n_y = board.shape
rows_dists = get_dists(n_x, x)
cols_dists = get_dists(n_y, y)
dists = (rows_dists[:, None] + cols_dists)
rows_dirs = get_directions(n_x, x)
cols_dirs = get_directions(n_y, y)
output_state = np.ones(self.get_shape())
for i, v in enumerate(MAP_VALUES):
inds = np.where(board == v)
min_inds = dists[inds].argsort()[:self.num_per_type]
min_inds_x = inds[0][min_inds]
min_inds_y = inds[1][min_inds]
curr_dirs = np.stack([rows_dirs[min_inds_x], cols_dirs[min_inds_y]], axis=1) / max(n_x, n_y)
curr_dirs = np.hstack([curr_dirs, np.linalg.norm(curr_dirs, axis=1)[..., np.newaxis]])
# if self.polars:
# r = np.linalg.norm(curr_dirs, axis=1)
# t = np.arctan2(curr_dirs[..., 0], curr_dirs[..., 1])
# curr_dirs[..., 0] = r
# curr_dirs[..., 1] = t
output_state[i, range(len(min_inds))] = curr_dirs
return output_state
class DoubleStateWrapper:
"""
State wrapper that encapsulates a combination of Square and Radar state representations
"""
def __init__(self, state_square: SquareAroundHeadState, state_radar : RadarState):
self.state_radar = state_radar
self.state_square = state_square
def get_shape(self):
return (self.state_square.get_shape(), self.state_radar.get_shape())
def get_state_repr(self, state):
return [self.state_square.get_state_repr(state), self.state_radar.get_state_repr(state)]
<file_sep>/policies/policy_avoid.py
from policies import base_policy as bp
import numpy as np
EPSILON = 0.05
class Avoid(bp.Policy):
"""
A policy which avoids collisions with obstacles and other snakes. It has an epsilon parameter which controls the
percentag of actions which are randomly chosen.
"""
def cast_string_args(self, policy_args):
policy_args['epsilon'] = float(policy_args['epsilon']) if 'epsilon' in policy_args else EPSILON
return policy_args
def init_run(self):
self.r_sum = 0
def learn(self, round, prev_state, prev_action, reward, new_state, too_slow):
try:
if round % 100 == 0:
if round > self.game_duration - self.score_scope:
self.log("Rewards in last 100 rounds which counts towards the score: " + str(self.r_sum), 'VALUE')
else:
self.log("Rewards in last 100 rounds: " + str(self.r_sum), 'VALUE')
self.r_sum = 0
else:
self.r_sum += reward
except Exception as e:
self.log("Something Went Wrong...", 'EXCEPTION')
self.log(e, 'EXCEPTION')
def act(self, round, prev_state, prev_action, reward, new_state, too_slow):
board, head = new_state
head_pos, direction = head
if np.random.rand() < self.epsilon:
return np.random.choice(bp.Policy.ACTIONS)
else:
for a in list(np.random.permutation(bp.Policy.ACTIONS)):
# get a Position object of the position in the relevant direction from the head:
next_position = head_pos.move(bp.Policy.TURNS[direction][a])
r = next_position[0]
c = next_position[1]
# look at the board in the relevant position:
if board[r, c] > 5 or board[r, c] < 0:
return a
# if all positions are bad:
return np.random.choice(bp.Policy.ACTIONS)
<file_sep>/README.md
# SnakeRL
Deep Reinforcement Learning implementation for the mighty game of Snake
### Agents Implemented:
[Linear Agent](policies/policy_linear.py)
[Basic DQN](policies/policy_DQN.py)
[Dueling DQN](policies/policy_DuelDQN.py)
[Convolutional DQN](policies/policy_ConvDQN.py)
[Convolutional Dueling DQN](policies/policy_ConvDuelDQN.py)
##### Important Paramters:
DoubleDQN - enables double DQN learning.
radius - control the radius of the agent field of view.
### Prioritized Experience Replay
Some experiences may be more important than others for our training, but might occur less frequently. Since the batch is sampled uniformly by default, these rich experiences that occur rarely have practically no chance to be selected.
Changing sampling distribution by using a criterion to define the priority of each tuple of experience (Used the prediction mean absolute difference error) as a priority criterion to give the model more chance to learn from experiences on
which its’ predictin is bad, thus giving it a better chance to improve its’ predictions.
For usage:
Just change the base class for any of the above to [PriorBaseDQN](policies/policy_PriorityBaseDQN.py).
### State Representations
Tried multiple different implementations:
• Square(l∞ distance) of a certain radius around the snake’s head.
• Diamond(l1 distance) of a certain radius around the snake’s head.
• Circle(l2 distance) of a certain radius around the Snake’s head.
• Using sort of a “Radar”, which returned directions and distances to a certain amount of entities of each type from the snake’s head.
### Exploration-Exploitation trade-off:
Used softmax sampling, with a temperature value that decays exponentially with a certain rate, in order to
explore more on early stage and then exploit the agent’s “knowledge” in later stage.
Also have option to use epsilon-greedy.
<file_sep>/Snake.py
import pickle
import time
import datetime
import multiprocessing as mp
import queue
import os
import argparse
import sys
import gzip
import subprocess as sp
import numpy as np
import scipy.signal as ss
from policies import base_policy
from policies import *
EMPTY_VAL = -1
MAX_PLAYERS = 5
OBSTACLE_VAL = 5
REGULAR_RENDER_MAP = {EMPTY_VAL: ' ', OBSTACLE_VAL: '+'}
FOOD_RENDER_MAP = {6: '*', 7: '$', 8: 'X'}
FOOD_VALUE_MAP = {6: 1, 7: 3, 8: 0}
FOOD_REWARD_MAP = {6: 2, 7: 5, 8: -1}
THE_DEATH_PENALTY = -5
ILLEGAL_MOVE = "Illegal Action: the default action was selected instead. Player tried action: "
NO_RESPONSE = "No Response: player took too long to respond with action. This is No Response #"
PLAYER_INIT_TIME = 60
UNRESPONSIVE_PLAYER = "Unresponsive Player: the player hasn't responded in too long... SOMETHING IS WRONG!!"
STATUS_SKIP = 100
TOO_SLOW_THRESHOLD = 3
UNRESPONSIVE_THRESHOLD = 50
LEARNING_TIME = 5
def clear_q(q):
"""
given a queue, empty it.
"""
while not q.empty():
try:
q.get_nowait()
except queue.Empty:
break
def days_hours_minutes_seconds(td):
"""
parse time for logging.
"""
return td.days, td.seconds // 3600, (td.seconds // 60) % 60, td.seconds % 60
def random_partition(num, max_part_size):
parts = []
while num > 0:
parts.append(np.random.randint(1, min(max_part_size, num + 1)))
num -= parts[-1]
return parts
class Position():
def __init__(self, position, board_size):
self.pos = position
self.board_size = board_size
def __getitem__(self, key):
return self.pos[key]
def __add__(self, other):
return Position(((self[0] + other[0]) % self.board_size[0],
(self[1] + other[1]) % self.board_size[1]),
self.board_size)
def move(self, dir):
if dir == 'E': return self + (0, 1)
if dir == 'W': return self + (0, -1)
if dir == 'N': return self + (-1, 0)
if dir == 'S': return self + (1, 0)
raise ValueError('unrecognized direction')
class Agent(object):
SHUTDOWN_TIMEOUT = 60 # seconds until policy is considered unresponsive
def __init__(self, id, policy, policy_args, board_size, logq, game_duration, score_scope):
"""
Construct a new player
:param id: the player id (the value of the player positions in the board
:param policy: the class of the policy to be used by the player
:param policy_args: string (name, value) pairs that the policy can parse to arguments
:param board_size: the size of the game board (height, width)
:param logq: a queue for message logging through the game
:param game_duration: the expected duration of the game in turns
:param score_scope: the amount of rounds at the end of the game which count towards the score
"""
self.id = id
self.len = 0
self.policy_class = policy
self.round = 0
self.unresponsive_count = 0
self.too_slow = False
self.sq = mp.Queue()
self.aq = mp.Queue()
self.mq = mp.Queue()
self.logq = logq
self.policy = policy(policy_args, board_size, self.sq, self.aq, self.mq, logq, id, game_duration, score_scope)
self.policy.daemon = True
self.policy.start()
def handle_state(self, round, prev_state, prev_action, reward, new_state):
"""
given the new state and previous state-action-reward, pass the information
to the policy for action selection and/or learning.
"""
self.round = round
clear_q(self.sq) # remove previous states from queue if they weren't handled yet
self.sq.put((round, prev_state, prev_action, reward, new_state, self.too_slow))
def get_action(self):
"""
get waiting action from the policy's action queue. if there is no action
in the queue, pick 'F' and log the unresponsiveness error.
:return: action from {'R','L','F'}.
"""
try:
round, action = self.aq.get_nowait()
if round != self.round:
raise queue.Empty()
elif action not in base_policy.Policy.ACTIONS:
self.logq.put((str(self.id), "ERROR", ILLEGAL_MOVE + str(action)))
raise queue.Empty()
else:
self.too_slow = False
self.unresponsive_count = 0
except queue.Empty:
self.unresponsive_count += 1
action = base_policy.Policy.DEFAULT_ACTION
if self.unresponsive_count <= UNRESPONSIVE_THRESHOLD:
self.logq.put((str(self.id), "ERROR", NO_RESPONSE + str(self.unresponsive_count) + " in a row!"))
else:
self.logq.put((str(self.id), "ERROR", UNRESPONSIVE_PLAYER))
self.unresponsive_count = TOO_SLOW_THRESHOLD
if self.unresponsive_count > TOO_SLOW_THRESHOLD:
self.too_slow = True
clear_q(self.aq) # clear the queue from unhandled actions
return action
def shutdown(self):
"""
shutdown the agent in the end of the game. the function asks the agent
to save it's model and returns the saved model, which needs to be a data
structure that can be pickled.
:return: the model data structure.
"""
clear_q(self.sq)
clear_q(self.aq)
self.sq.put(None) # shutdown signal
self.policy.join()
return
class Game(object):
@staticmethod
def log(q, file_name, on_screen=True):
start_time = datetime.datetime.now()
logfile = None
if file_name:
logfile = gzip.GzipFile(file_name,
'w') if file_name.endswith(
'.gz') else open(file_name, 'wb')
for frm, type, msg in iter(q.get, None):
td = datetime.datetime.now() - start_time
msg = '%i::%i:%i:%i\t%s\t%s\t%s' % (
days_hours_minutes_seconds(td) + (frm, type, msg))
if logfile: logfile.write((msg + '\n').encode('ascii'))
if on_screen: print(msg)
if logfile: logfile.close()
def _find_empty_slot(self, shape=(1, 3)):
is_empty = np.asarray(self.board == EMPTY_VAL, dtype=int)
match = ss.convolve2d(is_empty, np.ones(shape), mode='same') == np.prod(shape)
if not np.any(match): raise ValueError('no empty slots of requested shape')
r = np.random.choice(np.nonzero(np.any(match, axis=1))[0])
c = np.random.choice(np.nonzero(match[r, :])[0])
return Position((r, c), self.board_size)
def __init__(self, args):
self.__dict__.update(args.__dict__)
# check that the number of players is OK:
self.n = len(self.policies)
assert self.n <= MAX_PLAYERS, "Too Many Players!"
self.round = 0
# check for playback:
self.is_playback = False
if self.playback_from is not None:
self.archive = open(self.playback_from, 'rb')
dict = pickle.load(self.archive)
self.__dict__.update(dict)
self.is_playback = True
self.record_to = None
self.record = False
self.to_render = args.to_render
return
# init logger
self.logq = mp.Queue()
to_screen = not self.to_render
self.logger = mp.Process(target=self.log, args=(self.logq, self.log_file, to_screen))
self.logger.start()
# initialize the board:
self.item_count = 0
self.board = EMPTY_VAL * np.ones(self.board_size, dtype=int)
self.previous_board = None
# initialize obstacles:
for size in random_partition(int(self.obstacle_density * np.prod(self.board_size)), np.min(self.board_size)):
if np.random.rand(1) > 0.5:
pos = self._find_empty_slot(shape=(size, 1))
for i in range(size):
new_pos = pos + (i, 0)
self.board[new_pos[0], new_pos[1]] = OBSTACLE_VAL
else:
pos = self._find_empty_slot(shape=(1, size))
for i in range(size):
new_pos = pos + (i, 0)
self.board[new_pos[0], new_pos[1]] = OBSTACLE_VAL
self.item_count += size
# initialize players:
self.rewards, self.players, self.scores, self.directions, self.actions, self.growing, self.size, self.chains, self.previous_heads = \
[], [], [], [], [], [], [], [], []
for i, (policy, pargs) in enumerate(self.policies):
self.rewards.append(0)
self.actions.append(None)
self.previous_heads.append(None)
self.scores.append([0])
self.players.append(
Agent(i, policy, pargs, self.board_size, self.logq, self.game_duration, self.score_scope))
chain, player_size, growing, direction = self.init_player()
self.chains.append(chain)
self.size.append(player_size)
self.growing.append(growing)
self.directions.append((direction))
for position in chain:
self.board[position[0], position[1]] = i
# configure symbols for rendering
self.render_map = {p.id: chr(ord('1') + p.id) for p in self.players}
self.render_map.update(REGULAR_RENDER_MAP)
self.render_map.update(FOOD_RENDER_MAP)
# finally, if it's a recording, then record
if self.record_to is not None and self.playback_from is None:
self.archive = open(self.record_to, 'wb')
dict = self.__dict__.copy()
del dict['players'] # remove problematic objects that are irrelevant to playback.
del dict['archive']
del dict['logq']
del dict['logger']
del dict['playback_initial_round']
del dict['playback_final_round']
pickle.dump(dict, self.archive)
self.record = self.record_to is not None
# wait for player initialization (Keras loading time):
time.sleep(self.player_init_time)
def init_player(self):
# initialize the position and direction of the player:
dir = np.random.choice(list(base_policy.Policy.TURNS.keys()))
shape = (1, 3) if dir in ['W', 'E'] else (3, 1)
pos = self._find_empty_slot(shape)
# gather stats about the player:
chain = []
chain.append(pos)
chain.append(pos.move(dir))
player_size = 2
growing = self.init_player_size - 2
return chain, player_size, growing, dir
def reset_player(self, id):
positions = np.array(np.where(self.board == id))
for pos in range(positions.shape[1]):
self.board[positions[0, pos], positions[1, pos]] = EMPTY_VAL
# turn parts of the corpse into food:
food_n = np.random.binomial(positions.shape[1], self.food_ratio)
if self.item_count + food_n < self.max_item_density * np.prod(self.board_size):
subidx = np.array(np.random.choice(positions.shape[1], size=food_n, replace=False))
if len(subidx) > 0:
randfood = np.random.choice(list(FOOD_VALUE_MAP.keys()), food_n)
for i, idx in enumerate(subidx):
self.board[positions[0, idx], positions[1, idx]] = randfood[i]
self.item_count += food_n
return self.init_player()
def randomize(self):
if np.random.rand(1) < self.random_food_prob:
if self.item_count < self.max_item_density * np.prod(self.board_size):
randfood = np.random.choice(list(FOOD_VALUE_MAP.keys()), 1)
slot = self._find_empty_slot((1, 1))
self.board[slot[0], slot[1]] = randfood
self.item_count += 1
def move_snake(self, id, action):
# delete the tail if the snake isn't growing:
if self.growing[id] > 0:
self.growing[id] -= 1
self.size[id] += 1
else:
self.board[self.chains[id][0][0], self.chains[id][0][1]] = EMPTY_VAL
del self.chains[id][0]
# move the head:
if action != 'F': # turn in the relevant direction
self.directions[id] = base_policy.Policy.TURNS[self.directions[id]][action]
self.chains[id].append(self.chains[id][-1].move(self.directions[id]))
self.board[self.chains[id][-1][0], self.chains[id][-1][1]] = id
def play_a_round(self):
# randomize the players:
pperm = np.random.permutation([(i, p) for i, p in enumerate(self.players)])
# distribute states and rewards on previous round
for i, p in pperm:
current_head = (self.chains[p.id][-1], self.directions[p.id])
if self.previous_board is None:
p.handle_state(self.round, None, self.actions[p.id], self.rewards[p.id], (self.board, current_head))
else:
p.handle_state(self.round, (self.previous_board, self.previous_heads[p.id]), self.actions[p.id],
self.rewards[p.id], (self.board, current_head))
self.previous_heads[p.id] = current_head
self.previous_board = np.copy(self.board)
# wait and collect actions
time.sleep(self.policy_action_time)
actions = {p: p.get_action() for _, p in pperm}
if self.round % LEARNING_TIME == 0 and self.round > 5:
time.sleep(self.policy_learn_time)
# get the interactions of the players with the board:
for _, p in pperm:
action = actions[p]
self.actions[p.id] = action
move_to = self.chains[p.id][-1].move(base_policy.Policy.TURNS[self.directions[p.id]][action])
# reset the player if he died:
if self.board[move_to[0], move_to[1]] != EMPTY_VAL and self.board[
move_to[0], move_to[1]] not in FOOD_VALUE_MAP:
chain, player_size, growing, dir = self.reset_player(p.id)
self.chains[p.id] = chain
self.size[p.id] = player_size
self.growing[p.id] = growing
self.directions[p.id] = dir
self.rewards[p.id] = THE_DEATH_PENALTY
self.scores[p.id].append(self.rewards[p.id])
for pos in chain:
self.board[pos[0], pos[1]] = p.id
# otherwise, move the player on the board:
else:
self.rewards[p.id] = 0
if self.board[move_to[0], move_to[1]] in FOOD_VALUE_MAP.keys():
self.rewards[p.id] += FOOD_REWARD_MAP[self.board[move_to[0], move_to[1]]]
self.growing[p.id] += FOOD_VALUE_MAP[self.board[move_to[0], move_to[1]]] # start growing
self.item_count -= 1
self.move_snake(p.id, action)
self.scores[p.id].append(self.rewards[p.id])
# update the food on the board:
self.randomize()
self.round += 1
def render(self, r):
if os.name == 'nt':
os.system('cls') # clear screen for Windows
else:
print(chr(27) + "[2J") # clear screen for linux
# print the scores:
print("Time Step: " + str(r) + "/" + str(self.game_duration))
for i in range(len(self.scores)):
scope = np.min([len(self.scores[i]), self.score_scope])
print("Player " + str(i + 1) + ": " + str("{0:.4f}".format(np.mean(self.scores[i][-scope:]))))
# print the board:
horzline = '-' * (self.board.shape[1] + 2)
board = [horzline]
for r in range(self.board.shape[0]):
board.append('|' + ''.join(self.render_map[self.board[r, c]] for c in range(self.board.shape[1])) + '|')
board.append(horzline)
print('\n'.join(board))
def run(self):
try:
r = 0
while r < self.game_duration:
r += 1
if self.to_render:
if not (self.is_playback and (r < self.playback_initial_round or r > self.playback_final_round)):
self.render(r)
time.sleep(self.render_rate)
else:
if r % STATUS_SKIP == 0:
print("At Round " + str(r) + " the scores are:")
for i, s in enumerate(self.scores):
scope = np.min([len(self.scores[i]), self.score_scope])
print("Player " + str(i + 1) + ": " + str(
str("{0:.4f}".format(np.mean(self.scores[i][-scope:])))))
if self.is_playback:
try:
idx, vals, self.scores = pickle.load(self.archive)
self.board[idx] = vals
except EOFError:
break
if r > self.playback_final_round:
break
else:
if self.record:
prev = self.board.copy()
self.play_a_round()
if self.record:
idx = np.nonzero(self.board - prev != 0)
pickle.dump((idx, self.board[idx], self.scores), self.archive)
finally:
if self.record or self.is_playback:
self.archive.close()
if not self.is_playback:
output = [','.join(['game_id', 'player_id', 'policy', 'score'])]
game_id = str(abs(id(self)))
for p, s in zip(self.players, self.scores):
p.shutdown()
pstr = str(p.policy).split('<')[1].split('(')[0]
scope = np.min([len(s), self.score_scope])
p_score = np.mean(s[-scope:])
oi = [game_id, str(p.id), pstr, str("{0:.4f}".format(p_score))]
output.append(','.join(oi))
with open(self.output_file, 'w') as outfile:
outfile.write('\n'.join(output))
self.logq.put(None)
self.logger.join()
def parse_args():
p = argparse.ArgumentParser()
g = p.add_argument_group('I/O')
g.add_argument('--record_to', '-rt', type=str, default=None, help="file path to which game will be recorded.")
g.add_argument('--playback_from', '-p', type=str, default=None,
help='file path from which game will be played-back (overrides record_to)')
g.add_argument('--playback_initial_round', '-pir', type=int, default=0,
help='round in which to start the playback')
g.add_argument('--playback_final_round', '-pfr', type=int, default=1000,
help='round in which to end the playback')
g.add_argument('--log_file', '-l', type=str, default=None,
help="a path to which game events are logged. default: game.log")
g.add_argument('--output_file', '-o', type=str, default=None,
help="a path to a file in which game results are written. default: game.out")
g.add_argument('--to_render', '-r', type=int, default=0, help="whether game should not be rendered")
g.add_argument('--render_rate', '-rr', type=float, default=0.1,
help='frames per second, note that the policy_wait_time bounds on the rate')
g = p.add_argument_group('Game')
g.add_argument('--board_size', '-bs', type=str, default='(20,60)', help='a tuple of (height, width)')
g.add_argument('--obstacle_density', '-od', type=float, default=.04, help='the density of obstacles on the board')
g.add_argument('--policy_wait_time', '-pwt', type=float, default=0.01,
help='seconds to wait for policies to respond with actions')
g.add_argument('--random_food_prob', '-fp', type=float, default=.2,
help='probability of a random food appearing in a round')
g.add_argument('--max_item_density', '-mid', type=float, default=.25,
help='maximum item density in the board (not including the players)')
g.add_argument('--food_ratio', '-fr', type=float, default=.2,
help='the ratio between a corpse and the number of food items it produces')
g.add_argument('--game_duration', '-D', type=int, default=10000, help='number of rounds in the session')
g.add_argument('--policy_action_time', '-pat', type=float, default=0.01,
help='seconds to wait for agents to respond with actions')
g.add_argument('--policy_learn_time', '-plt', type=float, default=0.1,
help='seconds to wait for agents to improve policy')
g.add_argument('--player_init_time', '-pit', type=float, default=PLAYER_INIT_TIME,
help='seconds to wait for agents to initialize in the beginning of the session')
g = p.add_argument_group('Players')
g.add_argument('--score_scope', '-s', type=int, default=1000,
help='The score is the average reward during the last score_scope rounds of the session')
g.add_argument('--init_player_size', '-is', type=int, default=5, help='player length at start, minimum is 3')
g.add_argument('--policies', '-P', type=str, default=None,
help='a string describing the policies to be used in the game, of the form: '
'<policy_name>(<arg=val>,*);+.\n'
'e.g. MyPolicy(layer1=100,layer2=20);YourPolicy(your_params=123)')
args = p.parse_args()
# set defaults
code_path = os.path.split(os.path.abspath(__file__))[0] + os.path.sep
if not args.record_to:
args.__dict__['record_to'] = None
if args.log_file is None:
args.__dict__['log_file'] = code_path + 'game.log'
if args.output_file is None:
args.__dict__['output_file'] = code_path + 'game.out'
if args.playback_from is not None:
args.__dict__['record_to'] = None
args.__dict__['output_file'] = None
args.__dict__['log_file'] = None
args.__dict__['board_size'] = [int(x) for x in args.board_size[1:-1].split(',')]
plcs = []
if args.policies is not None: plcs.extend(args.policies.split(';'))
args.__dict__['policies'] = [base_policy.build(p) for p in plcs]
return args
if __name__ == '__main__':
g = Game(parse_args())
g.run()
<file_sep>/policies/policy_PriorityBaseDQN.py
from abc import abstractmethod
import keras
import numpy as np
from keras import Model
from keras.optimizers import Adam
from sklearn.utils.extmath import softmax
from nn_utils.losses import huber_loss
from policies import base_policy as bp
from state_utils.State import SquareAroundHeadState, DiamondAroundHeadState, RadarState, \
FULL, NUM_PER_TYPE
from utils.replay_buffer import PrioritizedReplayBuffer
EPSILON = 2.0
MIN_EPSILON = 0.33
GAMMA = 0.75
BUFFER_SIZE = 6000
SQUARE = 1
DIAMOND = 2
RADAR = 3
class PriorBaseDQN(bp.Policy):
"""
A different version of the abstract base class that implements Deep Q-Learning and allows for customization -
to be extended by other policies that we wrote. This version was changed to support our attempt at using
prioritized experience replay buffer
"""
def cast_string_args(self, policy_args):
policy_args['epsilon'] = float(policy_args['epsilon']) if 'epsilon' in policy_args else EPSILON
policy_args['gamma'] = float(policy_args['gamma']) if 'gamma' in policy_args else GAMMA
self.huber_loss = False
self.use_softmax_sampling = True
self.epsilon_decay = 0.90
self.min_epsilon = MIN_EPSILON
self.learning_rate = 1e-4
self.batch_size = 96
self.state_radius = 5
self.state_rep = SQUARE
self.step_forward = True
self.flatten = FULL
self.doubleDQN = False
self.save_model_round = 250
self.augment_after_normaliztion = False
policy_args = self._additional_args(policy_args)
return policy_args
def _save_model(self):
self.old_model.set_weights(self.model.get_weights())
def init_run(self):
self.log("Starting init")
self.r_sum = 0
if self.state_rep == SQUARE:
self.state_proc = SquareAroundHeadState(radius=self.state_radius,
step_forward=self.step_forward, flatten=self.flatten)
elif self.state_rep == DIAMOND:
self.state_proc = DiamondAroundHeadState(radius=self.state_radius,
step_forward=self.step_forward, flatten=self.flatten)
elif self.state_rep == RADAR:
self.state_proc = RadarState(num_per_type=NUM_PER_TYPE)
self.input_shape = self.state_proc.get_shape()
self.model = self._build_model()
self.model.summary()
if self.huber_loss:
loss = huber_loss
else:
loss = 'mse'
opt = Adam(self.learning_rate)
self.model.compile(loss=loss, optimizer=opt, metrics=['mae'])
self.old_model = keras.models.clone_model(self.model)
self._save_model()
self.memory = PrioritizedReplayBuffer(BUFFER_SIZE, alpha=0.4)
self.log("Init finished!")
self.num_of_samples = 0
self.sum_of_loss = 0
def learn(self, round, prev_state, prev_action, reward, new_state, too_slow):
try:
if round % 100 == 0:
if round > self.game_duration - self.score_scope:
self.log("Rewards in last 100 rounds which counts towards the score: {}, eps={:.2f}, "
"db_size={}".format(str(self.r_sum), self.epsilon, len(self.memory)), 'VALUE')
else:
total_loss = self.sum_of_loss / self.num_of_samples
self.num_of_samples = self.sum_of_loss = 0
self.log("Rewards in last 100 rounds: {}, eps={:.2f}, db_size={}, loss={:.3f}".format(
str(self.r_sum), self.epsilon, len(self.memory), total_loss), 'VALUE')
self.r_sum = 0
else:
self.r_sum += reward
except Exception as e:
self.log("Something Went Wrong...", 'EXCEPTION')
self.log(e, 'EXCEPTION')
prev, actions, rewards, new, _, sample_weight, idx = self.memory.sample(self.batch_size, beta=0.6)
if self.doubleDQN:
target = rewards + self.gamma * self.old_model.predict(new)[range(len(new)),
np.argmax(self.model.predict(new), axis=1)]
else:
target = rewards + self.gamma * np.amax(self.old_model.predict(new), axis=1)
target_f = self.model.predict(prev)
try:
target_f[range(len(actions)), actions] = target
hist = self.model.fit(prev, target_f, epochs=1, verbose=0, batch_size=len(prev), shuffle=False,
sample_weight=sample_weight)
self.sum_of_loss += np.sum(hist.history['loss'])
self.num_of_samples += len(hist.history['loss'])
mae = np.sum(np.abs(target_f - self.model.predict(prev, verbose=0, batch_size=len(prev))), axis=-1)
prioritized_replay_eps = 1e-6
self.memory.update_priorities(idx, mae + prioritized_replay_eps)
except Exception as e:
print(e)
if round % self.save_model_round == 0 and round > 0:
self._save_model()
if round % 200 == 0 and round > 0 and self.epsilon > 0:
self.epsilon = max(self.epsilon * self.epsilon_decay, self.min_epsilon)
def act(self, round, prev_state, prev_action, reward, new_state, too_slow):
if round > self.game_duration - self.score_scope:
# cancel exploration during "money-time"
self.use_softmax_sampling = False
self.epsilon = 0
new_state_repr = self.state_proc.get_state_repr(new_state)
if prev_state is not None:
prev_state_repr = self.state_proc.get_state_repr(prev_state)
self.memory.add(prev_state_repr, bp.Policy.ACTIONS.index(prev_action), reward, new_state_repr, 0)
if self.use_softmax_sampling:
return np.random.choice(bp.Policy.ACTIONS,
p=softmax(self.model.predict(new_state_repr[np.newaxis]) / self.epsilon).squeeze())
else: # use epsilon-greedy
if np.random.rand() < self.epsilon:
return np.random.choice(bp.Policy.ACTIONS)
else:
prediction = self.model.predict(new_state_repr[np.newaxis])[0]
action = bp.Policy.ACTIONS[np.argmax(prediction)]
return action
@abstractmethod
def _build_model(self) -> Model:
raise NotImplementedError
@abstractmethod
def _additional_args(self, policy_args):
raise NotImplementedError
<file_sep>/policies/policy_DuelDQN.py
from keras import Input, Model
from keras.layers import Conv1D, Flatten, Dense, Dropout, Lambda, Add, LeakyReLU
import keras.backend as K
from policies.policy_BaseDQN import BaseDQN, SQUARE, SPATIAL
class DuelDQN(BaseDQN):
"""
A Dueling Deep Q-Learning implementation with a Multi-Layered Dense network as the Q estimator
"""
def _additional_args(self, policy_args):
self.flatten = SPATIAL
self.state_radius = 5
self.step_forward = True
self.state_rep = SQUARE
self.doubleDQN = True
# for self
self.dropout_rate = 0.0
self.activation = LeakyReLU
return policy_args
def _build_model(self):
input_layer = Input(self.input_shape)
net = self.activation()(Conv1D(input_shape=self.input_shape, filters=4, kernel_size=1)(input_layer))
net = Flatten()(net)
net = self.dense_layer(net, units=128)
streamA = self.dense_layer(net, units=128)
streamV = self.dense_layer(net, units=128)
Advantage = Dense(units=3)(streamA)
Value = Dense(units=1)(streamV)
advt = Lambda(lambda advt: advt - K.mean(advt, axis=-1, keepdims=True))(Advantage)
value = Lambda(lambda value: K.tile(value, [1, 3]))(Value)
Q_out = Add()([value, advt])
return Model(inputs=[input_layer], outputs=[Q_out])
def dense_layer(self, input_layer, units):
net = Dense(units=units)(input_layer)
net = self.activation()(net) # apply activation
if self.dropout_rate > 0:
net = Dropout(self.dropout_rate)(net)
return net<file_sep>/policies/policy_DQN.py
from keras import Sequential
from keras.layers import Conv1D, Flatten, Dense, Dropout, LeakyReLU
from policies.policy_BaseDQN import BaseDQN, SQUARE, SPATIAL
class DQN(BaseDQN):
"""
A Deep Q-Learning implementation with a Multi-Layered Dense network as the Q estimator
"""
def _additional_args(self, policy_args):
self.flatten = SPATIAL
self.state_radius = 6
self.step_forward = True
self.state_rep = SQUARE
self.doubleDQN = True
self.batch_size = 96
self.epsilon_decay = 0.98
self.min_epsilon = 0.1
self.gamma = 0.75
# for self
self.dropout_rate = 0.0
self.activation = LeakyReLU
return policy_args
def _build_model(self):
model = Sequential()
model.add(Conv1D(input_shape=self.input_shape, filters=4, kernel_size=1))
model.add(self.activation())
model.add(Flatten())
model.add(Dense(units=128))
model.add(self.activation())
if self.dropout_rate > 0:
model.add(Dropout(self.dropout_rate))
model.add(Dense(units=128))
model.add(self.activation())
if self.dropout_rate > 0:
model.add(Dropout(self.dropout_rate))
model.add(Dense(units=128))
model.add(self.activation())
model.add(Dense(units=3))
return model
| 843e7dc80b337f0fb4079ae05a08f7daa180ecf5 | [
"Markdown",
"Python"
] | 14 | Python | GalDude33/SnakeRL | e6161f1aad3c8d1ea54975efb0cd7c21b1736867 | c30c0ad799308a244cd0226caaf07890a22ffc90 | |
refs/heads/master | <file_sep>require 'sinatra'
require 'uri'
require 'net/http'
Sinatra.new do
configure :production do
require 'newrelic_rpm'
end
get '/' do
if params[:uri] && params[:callback]
handle_jsonp_request
else
handle_invalid_request
end
end
def handle_jsonp_request
json = Net::HTTP.get_response(URI.parse(params[:uri])).body
content_type :json
"#{params[:callback]}(#{json})"
end
def handle_invalid_request
content_type :text
"Usage: /?callback={insert callback name}&uri={insert JSON URI}"
end
end.run!
<file_sep># Usage
There are two required query parameters:
- `uri`: the URI of the original JSON endpoint
- `callback`: that name of the JSONP callback function. Note: jQuery.ajax automatically adds one for you with `dataType: jsonp`.
# Example
http://jsonpfy.herokuapp.com/?callback=what&uri=http%3A%2F%2Fwww.reddit.com%2F.json
| 202ca124bdc171c46d5b453117dc110457ca6924 | [
"Markdown",
"Ruby"
] | 2 | Ruby | 6/jsonpfy | 101193835f891c5abd054146020eda991e96bdff | f9f25b18bc69a938b8c31b701e50d5353c5a519c | |
refs/heads/master | <file_sep>import { useState } from "react";
const useFetch = (url) => {
const [isLoading, setIsLoading] = useState(false);
const [hasError, setHasError] = useState(false);
const [searchResult, setSearchResult] = useState(null);
const fetchFunction = async () => {
try {
setIsLoading(true);
const response = await fetch(url);
const result = await response.json();
setSearchResult(result);
console.log(result);
} catch {
setHasError(true);
} finally {
setIsLoading(false);
}
};
return [fetchFunction, searchResult, isLoading, hasError];
};
export default useFetch;
<file_sep>import { useEffect } from "react";
import { withRouter } from "react-router-dom";
import OneCountry from "../components/OneCountry";
import useFetch from "../hooks/useFetch";
const Details = (props) => {
const {
params: { alpha3Code },
} = props.match;
const url = `https://restcountries.eu/rest/v2/name/${alpha3Code}`;
const [fetchCountry, country, isLoading, hasError] = useFetch(url);
useEffect(() => {
if (alpha3Code) fetchCountry();
}, [alpha3Code]);
return (
<div>
{isLoading && <div>loading</div>}
{hasError && <div>Error</div>}
{!isLoading && !hasError && country && (
<div>
<OneCountry country={country[0]} />
</div>
)}
</div>
);
};
export default withRouter(Details);
<file_sep># React-Project-class-31<file_sep>import { Link } from "react-router-dom";
export default function Card({ country }) {
const { name, flag } = country;
return (
<div className="card">
<Link to={`/${name}`}>
<img className="countriesListImg" src={flag} alt={""} />
<h3> {name} </h3>
</Link>
</div>
);
}
<file_sep>import { useEffect, useRef, useContext } from "react";
import { CountryContext } from "../contexts/CountryContext";
const Search = () => {
const { searchTerm, setSearchTerm, isLoading, hasError } =
useContext(CountryContext);
const refContainer = useRef(null);
useEffect(() => {
refContainer.current.focus();
});
const handleChange = (event) => {
setSearchTerm(event.target.value);
};
return (
<div className="search">
<input
className="input"
type="text"
name="cityName"
placeholder="Enter Country Name..."
value={searchTerm}
ref={refContainer}
onChange={handleChange}
/>
{isLoading && <p className="loading">Loading....</p>}
{hasError && <p className="error">Something Went Wrong!</p>}
</div>
);
};
export default Search;
<file_sep>import { useContext } from "react";
import Card from "../components/Card";
import { CountryContext } from "../contexts/CountryContext";
import Search from "../components/Search";
export default function Home() {
const { countries, isLoading, hasError } = useContext(CountryContext);
return (
<div>
{isLoading && <div>loading</div>}
{hasError && <div>Error</div>}
{!isLoading && !hasError && (
<>
<Search />
<div className="countryContainer">
{countries.map((country) => {
return <Card country={country} key={country.name} />;
})}
</div>
</>
)}
</div>
);
}
<file_sep>import { createContext, useEffect, useState } from "react";
import useFetch from "../hooks/useFetch";
export const CountryContext = createContext();
export default function CountryContextProvider(props) {
const url = "https://restcountries.eu/rest/v2/all";
const [searchTerm, setSearchTerm] = useState("");
const [fetchAllCountries, countries, isLoading, hasError] = useFetch(url);
useEffect(() => {
fetchAllCountries();
}, []);
let filteredCountries = countries || [];
if (searchTerm) {
filteredCountries = filteredCountries.filter((country) => {
return country.name.toLowerCase().includes(searchTerm.toLowerCase());
});
}
return (
<CountryContext.Provider
value={{
isLoading,
hasError,
searchTerm,
setSearchTerm,
countries: filteredCountries,
fetchAllCountries,
}}
>
{props.children}
</CountryContext.Provider>
);
}
| ae39785f7733fe3f8a96471fa25f870143c56e8c | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | Marwa-kwara/React-Project-class-31 | 6a79bc7c51ebf6e142a0c840334e1ff534dd7fea | afc8fc020e83a3d7e5e0f961584ce95250db7521 | |
refs/heads/master | <file_sep>const mongoose = require("mongoose");
const dbUrl = "mongodb+srv://Waleed:[email protected]/<dbname>?retryWrites=true&w=majority";
mongoose
.connect(dbUrl, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("Database Connect Sucessful");
})
.catch((err) => {
console.log(`Database Not Connect ${err}`);
});
<file_sep>import React, { Component } from "react";
import Header from "../components/hashcraft/Header";
import PageTitle from "../components/hashcraft/PageTitle";
import Footer from "../components/hashcraft/Footer";
import FaqContent from "../components/hashcraft/ContentBody";
import WhyChoose from "../components/hashcraft/WhyChoose";
class ServiceDetails extends Component {
render() {
return (
<React.Fragment>
<Header />
<PageTitle title="Mobile App Development" />
<section className="services-details-area ptb-80">
<div className="container">
<div className="row ">
<div className="col-lg-6 services-details">
<div className="services-details-desc">
<h3>
Robust Mobile Applications For Improved Client And Workforce
Engagement
</h3>
<p>
We employ platform-specific SDKs for Android and iOS,
cross-platform approaches relying on HTML5, and conversion
tools, to develop cost-effective enterprise mobile
solutions.
</p>
<p>
Our iOS applications help you take informed decisions and
give you the flexibility to perform critical tasks with
ease. Our services extend across various domains and skill
sets to help you innovate business processes across
departments.
</p>
<p>
Our expert team can help deliver customized, secure, and
robust native Android applications including e-commerce,
augmented reality and integration applications that help you
meet your business objectives.
</p>
<p>
We have expertise in building mobile solutions that meet
your multiplatform requirements, ensuring a uniform
experience across numerous devices and platforms. Whether a
smartphone, tablet or laptop running on iOS, Android, or
Windows, our developers can build the right solutions.
</p>
<a className="btn btn-primary" href="#proposal">
Request a proposal
</a>
</div>
</div>
<div className="col-lg-6 services-details-image">
<img
src={require("../static/images/home/mobileapp.jpg")}
className="wow fadeInUp"
alt="image"
/>
</div>
</div>
</div>
</section>
<WhyChoose />
<FaqContent />
<Footer />
</React.Fragment>
);
}
}
export default ServiceDetails;
<file_sep>import React, { Component } from "react";
import ModalVideo from "react-modal-video";
import * as Icon from "react-feather";
import "../../../../node_modules/react-modal-video/css/modal-video.min.css";
import Lightbox from "react-image-lightbox";
import "react-image-lightbox/style.css";
const images = [
require("../../../../static/images/home/fotisto1.png"),
require("../../../../static/images/home/fotisto2.png"),
require("../../../../static/images/home/fotisto4.png"),
require("../../../../static/images/home/fotisto3.png"),
];
export default class DetailsBody extends Component {
state = {
isOpen: false,
photoIndex: 0,
isOpenImage: false,
};
openModal = () => {
this.setState({ isOpen: true });
};
render() {
const { photoIndex, isOpenImage } = this.state;
return (
<section className="project-details-area ptb-80">
<div className="container">
<div className="row">
<div className="col-lg-6 col-md-6">
<div
className="project-details-image"
onClick={() => this.setState({ isOpenImage: true })}
>
<img
src={require("../../../../static/images/home/fotisto1.png")}
alt="work"
/>
<Icon.Plus />
</div>
</div>
{isOpenImage && (
<Lightbox
mainSrc={images[photoIndex]}
nextSrc={images[(photoIndex + 1) % images.length]}
prevSrc={
images[(photoIndex + images.length - 1) % images.length]
}
onCloseRequest={() => this.setState({ isOpenImage: false })}
onMovePrevRequest={() =>
this.setState({
photoIndex:
(photoIndex + images.length - 1) % images.length,
})
}
onMoveNextRequest={() =>
this.setState({
photoIndex: (photoIndex + 1) % images.length,
})
}
/>
)}
<div className="col-lg-6 col-md-6">
<div
className="project-details-image"
onClick={() => this.setState({ isOpenImage: true })}
>
<img
src={require("../../../../static/images/home/fotisto2.png")}
alt="work"
/>
<Icon.Plus />
</div>
</div>
<div className="col-lg-12 col-md-12">
<div className="project-details-desc">
<h3>Fotisto</h3>
<p>
At Fotisto, we are committed to provide businesses with
exclusive brand support, and a variety of features in their
content creation process. Simply hire us and get ready for
stress-free content production today!.Fotisto is a marketplace
that uses AI and Cloud-based tools to bridge clients with
photographers & videographers. We have an eye for detail and can
capture special moments the way you imagined. Be it fashion,
wedding, or 360° shoots, we do it all .Initiate the process of
an exquisite content creation personalized for your brand by
selecting from the list of genres from our content types
</p>
<div className="project-details-information">
<div className="single-info-box">
<h4>Happy Client</h4>
<p><NAME></p>
</div>
<div className="single-info-box">
<h4>Category</h4>
<p>Portfolio, Personal</p>
</div>
<div className="single-info-box">
<h4>Date</h4>
<p>February 28, 2019</p>
</div>
<div className="single-info-box">
<h4>Share</h4>
<ul>
<li>
<a href="#">
<Icon.Facebook />
</a>
</li>
<li>
<a href="#">
<Icon.Twitter />
</a>
</li>
<li>
<a href="#">
<Icon.Instagram />
</a>
</li>
<li>
<a href="#">
<Icon.Linkedin />
</a>
</li>
</ul>
</div>
<div className="single-info-box">
<a href="#" className="btn btn-primary">
Live Preview
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
);
}
}
<file_sep>import React, { Component } from "react";
import ModalVideo from "react-modal-video";
import * as Icon from "react-feather";
import "../../../../node_modules/react-modal-video/css/modal-video.min.css";
import Lightbox from "react-image-lightbox";
import "react-image-lightbox/style.css";
const images = [
require("../../../../static/images//home/vonza1.png"),
require("../../../../static/images//home/vonza2.png"),
require("../../../../static/images//home/vonza3.png"),
require("../../../../static/images//home/vonza5.png"),
require("../../../../static/images//home/vonza4.png"),
];
export default class DetailsBody extends Component {
state = {
isOpen: false,
photoIndex: 0,
isOpenImage: false,
};
openModal = () => {
this.setState({ isOpen: true });
};
render() {
const { photoIndex, isOpenImage } = this.state;
return (
<section className="project-details-area ptb-80">
<div className="container">
<div className="row">
<div className="col-lg-6 col-md-6">
<div
className="project-details-image"
onClick={() => this.setState({ isOpenImage: true })}
>
<img
src={require("../../../../static/images/home/vonza1.png")}
alt="work"
/>
<Icon.Plus />
</div>
</div>
{isOpenImage && (
<Lightbox
mainSrc={images[photoIndex]}
nextSrc={images[(photoIndex + 1) % images.length]}
prevSrc={
images[(photoIndex + images.length - 1) % images.length]
}
onCloseRequest={() => this.setState({ isOpenImage: false })}
onMovePrevRequest={() =>
this.setState({
photoIndex:
(photoIndex + images.length - 1) % images.length,
})
}
onMoveNextRequest={() =>
this.setState({
photoIndex: (photoIndex + 1) % images.length,
})
}
/>
)}
<div className="col-lg-6 col-md-6">
<div
className="project-details-image"
onClick={() => this.setState({ isOpenImage: true })}
>
<img
src={require("../../../../static/images//home/vonza2.png")}
alt="work"
/>
<Icon.Plus />
</div>
</div>
<div className="col-lg-12 col-md-12">
<div className="project-details-desc">
<h3>Vonza</h3>
<p>
Vonza is the ultimate platform to build online courses, sell
products, offer services, construct sales funnels, schedule
appointments, launch email marketing campaigns and develop
amazing websites.Vonza makes it seamless for entrepreneurs and
creatives to run a successful online business all in one
place, not all over the place! While saving them time, money
and tech frustrations.Before Vonza, when coaches and
entrepreneurs wanted to share their knowledge, sell a course
online or run their online business, they needed several
different platforms, multiple subscriptions, tools, apps, tech
people, plugins and a ton of duct-tape to run their online
business. Some platforms only provided online courses, some
coaching tools, some email marketing while others sales
funnels - running an online business was complicated and
seemed all over the place! Coaches and business owners were
wasting precious time, money and losing their sanity.
</p>
<p>
After Vonza, you don’t need annoying programmers and plugins.
You don’t need to remember 20 different passwords. You don’t
need to write any code. Your business doesn’t have to be all
over the place. You get to put all your focus on your
customers and in your business. To put the cherry on top, you
also get to save money, time and enjoy the freedom of
entrepreneurship. Within minutes, you will get a fully
functioning online website platform with the features and
tools you need to run a successful online business. One simple
login and the world is your audience. We welcome you to Vonza!
</p>
<div className="project-details-information">
<div className="single-info-box">
<h4>Happy Client</h4>
<p><NAME></p>
</div>
<div className="single-info-box">
<h4>Category</h4>
<p>Portfolio, Personal</p>
</div>
<div className="single-info-box">
<h4>Date</h4>
<p>February 28, 2019</p>
</div>
<div className="single-info-box">
<h4>Share</h4>
<ul>
<li>
<a href="#">
<Icon.Facebook />
</a>
</li>
<li>
<a href="#">
<Icon.Twitter />
</a>
</li>
<li>
<a href="#">
<Icon.Instagram />
</a>
</li>
<li>
<a href="#">
<Icon.Linkedin />
</a>
</li>
</ul>
</div>
<div className="single-info-box">
<a href="#" className="btn btn-primary">
Live Preview
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
);
}
}
<file_sep>import React, { Component } from 'react'
import ModalVideo from 'react-modal-video'
import * as Icon from 'react-feather'
import '../../node_modules/react-modal-video/css/modal-video.min.css'
import Lightbox from 'react-image-lightbox';
import 'react-image-lightbox/style.css';
const images = [
require('../../static/images/works-image/works-image2.jpg'),
require('../../static/images/works-image/works-image4.jpg')
]
export default class DetailsBody extends Component {
state = {
isOpen: false,
photoIndex: 0,
isOpenImage: false,
}
openModal = () => {
this.setState({isOpen: true})
}
render() {
const { photoIndex, isOpenImage } = this.state;
return (
<section className="project-details-area ptb-80">
<div className="container">
<div className="row">
<div className="col-lg-6 col-md-6">
<div className="project-details-image">
<img src={require("../../static/images/works-image/works-image1.jpg")} alt="work" />
<Icon.Play onClick={this.openModal} />
</div>
</div>
<ModalVideo
channel='youtube'
isOpen={this.state.isOpen}
videoId='bk7McNUjWgw'
onClose={() => this.setState({isOpen: false})}
/>
<div className="col-lg-6 col-md-6">
<div className="project-details-image">
<img src={require("../../static/images/works-image/works-image2.jpg")} alt="work" />
<Icon.Plus onClick={() => this.setState({ isOpenImage: true })} />
</div>
</div>
{isOpenImage && (
<Lightbox
mainSrc={images[photoIndex]}
nextSrc={images[(photoIndex + 1) % images.length]}
prevSrc={images[(photoIndex + images.length - 1) % images.length]}
onCloseRequest={() => this.setState({ isOpenImage: false })}
onMovePrevRequest={() =>
this.setState({
photoIndex: (photoIndex + images.length - 1) % images.length,
})
}
onMoveNextRequest={() =>
this.setState({
photoIndex: (photoIndex + 1) % images.length,
})
}
/>
)}
<div className="col-lg-6 col-md-6">
<div className="project-details-image">
<img src={require("../../static/images/works-image/works-image4.jpg")} alt="work" />
<Icon.Plus onClick={() => this.setState({ isOpenImage: true })} />
</div>
</div>
<div className="col-lg-6 col-md-6">
<div className="project-details-image">
<img src={require("../../static/images/works-image/works-image3.jpg")} alt="work" />
<Icon.Play onClick={this.openModal} />
</div>
</div>
<div className="col-lg-12 col-md-12">
<div className="project-details-desc">
<h3>Network Marketing</h3>
<p>Lorem ipsum dolor sit amet, conse cte tuer adipiscing elit, sed diam no nu m nibhie eui smod. Facil isis atve eros et accumsan etiu sto odi dignis sim qui blandit praesen lup ta de er. At molestiae appellantur pro. Vis wisi oportere per ic ula ad, ei latine prop riae na, mea cu purto debitis. Primis nost rud no eos, no impedit dissenti as mea, ea vide labor amus neglegentur vix. Ancillae intellegat vix et. Sit causae laoreet nolu ise. Ad po exerci nusquam eos te. Cu altera expet enda qui, munere oblique theo phrastu ea vix. Ne nec modus civibus modera tius, sit ei lorem doctus. Ne docen di verterem reformidans eos. Cu altera expetenda qui, munere oblique theophr astus ea vix modus civiu mod eratius.</p>
<p>Lorem ipsum dolor sit amet, conse cte tuer adipiscing elit, sed diam no nu m nibhie eui smod. Facil isis atve eros et accumsan etiu sto odi dignis sim qui blandit praesen lup ta de er. At molestiae appellantur pro. Vis wisi oportere per ic ula ad, ei latine prop riae na, mea cu purto debitis. Primis nost rud no eos, no impedit dissenti as mea, ea vide labor amus neglegentur vix. Ancillae intellegat vix et. Sit causae laoreet nolu ise. Ad po exerci nusquam eos te. Cu altera expet enda qui, munere oblique theo phrastu ea vix. Ne nec modus civibus modera tius, sit ei lorem doctus. Ne docen di verterem reformidans eos. Cu altera expetenda qui, munere oblique theophr astus ea vix modus civiu mod eratius.</p>
<div className="project-details-information">
<div className="single-info-box">
<h4>Happy Client</h4>
<p><NAME></p>
</div>
<div className="single-info-box">
<h4>Category</h4>
<p>Portfolio, Personal</p>
</div>
<div className="single-info-box">
<h4>Date</h4>
<p>February 28, 2019</p>
</div>
<div className="single-info-box">
<h4>Share</h4>
<ul>
<li>
<a href="#"><Icon.Facebook/></a>
</li>
<li>
<a href="#"><Icon.Twitter/></a>
</li>
<li>
<a href="#"><Icon.Instagram/></a>
</li>
<li>
<a href="#"><Icon.Linkedin/></a>
</li>
</ul>
</div>
<div className="single-info-box">
<a href="#" className="btn btn-primary">Live Preview</a>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
)
}
}
<file_sep>import React, { Component } from "react";
import Header from "../components/hashcraft/Header";
import PageTitle from "../components/hashcraft/PageTitle";
import Footer from "../components/hashcraft/Footer";
import FaqContent from "../components/hashcraft/ContentBody";
import WhyChoose from "../components/hashcraft/WhyChoose";
class ServiceDetails extends Component {
render() {
return (
<React.Fragment>
<Header />
<PageTitle title='UI/UX Design'/>
<section className="services-details-area ptb-80">
<div className="container">
<div className="row ">
<div className="col-lg-6 services-details">
<div className="services-details-desc">
<h3>
Innovative & User Centered, Delightful Customer Experiences.
</h3>
<p>
Our UX Designers and Software Architects will create an
interactive prototype for the software using Axure RP (Rapid
Prototyping).
</p>
<p>
We can help your product speak for itself. Check out our
projects portfolio, client pages and their websites. You
need designs that your customers will love and a compelling
digital media presence that will cause your competition step
up their game. The right experience cultivates customer
loyalty and builds brand value.
</p>
<p>
A decade in design has allowed our team to perfect the
process of delivering UI andUX services.We follow
established design standards, workflows, and guidelines —
you get the product you need, delivered by expert designers
within the set timeframe.
</p>
<a className="btn btn-primary" href="#proposal">
Request a proposal
</a>
</div>
</div>
<div className="col-lg-6 services-details-image">
<img
src={require("../static/images/home/uiux.png")}
className="wow fadeInUp"
alt="image"
/>
</div>
</div>
</div>
</section>
<WhyChoose />
<FaqContent />
<Footer />
</React.Fragment>
);
}
}
export default ServiceDetails;
<file_sep>import React from "react";
import * as Icon from "react-feather";
import ReactWOW from "react-wow";
import Link from "../common/ActiveLink";
class ServicesArea extends React.Component {
render() {
return (
<React.Fragment>
<section className="services-area ptb-80 ">
<div className="container">
<div className="row h-100 justify-content-center align-items-center">
<div className="col-lg-6 col-md-12 services-content">
<div className="section-title">
<h2>WHAT WE CRAFT</h2>
<div className="bar"></div>
<p>
We’ll help you bring your most complex software vision to
life with our leading custom application development
services.
</p>
</div>
<div className="row">
<Link href="/ui-ux">
<div className="col-lg-6 col-md-6">
<div className="box">
<Icon.Database /> UI/UX Design
</div>
</div>
</Link>
<Link href="/web-app">
<div className="col-lg-6 col-md-6">
<div className="box">
<Icon.File /> Website App Development
</div>
</div>
</Link>
<Link href="/mobile-app">
<div className="col-lg-6 col-md-6">
<div className="box">
<Icon.TrendingUp /> Mobile App Development
</div>
</div>
</Link>
<Link href="/ecommerce">
<div className="col-lg-6 col-md-6">
<div className="box">
<Icon.Folder /> E-commerce Development
</div>
</div>
</Link>
<Link href="/hybrid-app">
<div className="col-lg-6 col-md-6">
<div className="box">
<Icon.Monitor /> Hybrid App Development
</div>
</div>
</Link>
<Link href="/digital-marketing">
<div className="col-lg-6 col-md-6">
<div className="box">
<Icon.Mail /> Digital Marketing
</div>
</div>
</Link>
<Link href="/app-deployment">
<div className="col-lg-6 col-md-6">
<div className="box">
<Icon.Globe /> Application Deployment
</div>
</div>
</Link>
<Link href="/dedicated-team">
<div className="col-lg-6 col-md-6">
<div className="box">
<Icon.Cloud /> Dedicated Team
</div>
</div>
</Link>
</div>
</div>
<div className="col-lg-6 col-md-12 services-right-image">
<ReactWOW delay="0.6s" animation="fadeInDown">
<img
src={require("../../static/images/services-right-image/book-self.png")}
className="wow fadeInDown"
data-wow-delay="0.6s"
alt="book-self"
/>
</ReactWOW>
<ReactWOW delay="0.6s" animation="fadeInUp">
<img
src={require("../../static/images/services-right-image/box.png")}
className="wow fadeInUp"
data-wow-delay="0.6s"
alt="box"
/>
</ReactWOW>
<ReactWOW delay="0.6s" animation="fadeInLeft">
<img
src={require("../../static/images/services-right-image/chair.png")}
className="wow fadeInLeft"
data-wow-delay="0.6s"
alt="chair"
/>
</ReactWOW>
<ReactWOW delay="0.6s" animation="zoomIn">
<img
src={require("../../static/images/services-right-image/cloud.png")}
className="wow zoomIn"
data-wow-delay="0.6s"
alt="cloud"
/>
</ReactWOW>
<ReactWOW delay="0.6s" animation="bounceIn">
<img
src={require("../../static/images/services-right-image/cup.png")}
className="wow bounceIn"
data-wow-delay="0.6s"
alt="cup"
/>
</ReactWOW>
<ReactWOW delay="0.6s" animation="fadeInDown">
<img
src={require("../../static/images/services-right-image/flower-top.png")}
className="wow fadeInDown"
data-wow-delay="0.6s"
alt="flower"
/>
</ReactWOW>
<ReactWOW delay="0.6s" animation="zoomIn">
<img
src={require("../../static/images/services-right-image/head-phone.png")}
className="wow zoomIn"
data-wow-delay="0.6s"
alt="head-phone"
/>
</ReactWOW>
<ReactWOW delay="0.6s" animation="fadeInUp">
<img
src={require("../../static/images/services-right-image/monitor.png")}
className="wow fadeInUp"
data-wow-delay="0.6s"
alt="monitor"
/>
</ReactWOW>
<ReactWOW delay="0.6s" animation="rotateIn">
<img
src={require("../../static/images/services-right-image/mug.png")}
className="wow rotateIn"
data-wow-delay="0.6s"
alt="mug"
/>
</ReactWOW>
<ReactWOW delay="0.6s" animation="fadeInUp">
<img
src={require("../../static/images/services-right-image/table.png")}
className="wow fadeInUp"
data-wow-delay="0.6s"
alt="table"
/>
</ReactWOW>
<ReactWOW delay="0.6s" animation="zoomIn">
<img
src={require("../../static/images/services-right-image/tissue.png")}
className="wow zoomIn"
data-wow-delay="0.6s"
alt="tissue"
/>
</ReactWOW>
<ReactWOW delay="0.6s" animation="zoomIn">
<img
src={require("../../static/images/services-right-image/water-bottle.png")}
className="wow zoomIn"
data-wow-delay="0.6s"
alt="water-bottle"
/>
</ReactWOW>
<ReactWOW delay="0.6s" animation="fadeInLeft">
<img
src={require("../../static/images/services-right-image/wifi.png")}
className="wow fadeInLeft"
data-wow-delay="0.6s"
alt="wifi"
/>
</ReactWOW>
<img
src={require("../../static/images/services-right-image/cercle-shape.png")}
className="bg-image rotateme"
alt="shape"
/>
<ReactWOW delay="0.6s" animation="fadeInUp">
<img
src={require("../../static/images/services-right-image/service-right-main-pic.png")}
className="wow fadeInUp"
data-wow-delay="0.6s"
alt="main-pic"
/>
</ReactWOW>
</div>
</div>
</div>
</section>
</React.Fragment>
);
}
}
export default ServicesArea;
<file_sep>import React, { Component } from "react";
import ModalVideo from "react-modal-video";
import * as Icon from "react-feather";
import "../../../../node_modules/react-modal-video/css/modal-video.min.css";
import Lightbox from "react-image-lightbox";
import "react-image-lightbox/style.css";
const images = [
require("../../../../static/images/home/rapid1.png"),
require("../../../../static/images/home/rapid2.png"),
require("../../../../static/images/home/rapid3.png"),
];
export default class DetailsBody extends Component {
state = {
isOpen: false,
photoIndex: 0,
isOpenImage: false,
};
openModal = () => {
this.setState({ isOpen: true });
};
render() {
const { photoIndex, isOpenImage } = this.state;
return (
<section className="project-details-area ptb-80">
<div className="container">
<div className="row">
<div className="col-lg-6 col-md-6">
<div
className="project-details-image"
onClick={() => this.setState({ isOpenImage: true })}
>
<img
src={require("../../../../static/images/home/rapid1.png")}
alt="work"
/>
<Icon.Plus />
</div>
</div>
{isOpenImage && (
<Lightbox
mainSrc={images[photoIndex]}
nextSrc={images[(photoIndex + 1) % images.length]}
prevSrc={
images[(photoIndex + images.length - 1) % images.length]
}
onCloseRequest={() => this.setState({ isOpenImage: false })}
onMovePrevRequest={() =>
this.setState({
photoIndex:
(photoIndex + images.length - 1) % images.length,
})
}
onMoveNextRequest={() =>
this.setState({
photoIndex: (photoIndex + 1) % images.length,
})
}
/>
)}
<div className="col-lg-6 col-md-6">
<div
className="project-details-image"
onClick={() => this.setState({ isOpenImage: true })}
>
<img
src={require("../../../../static/images/home/rapid2.png")}
alt="work"
/>
<Icon.Plus />
</div>
</div>
<div className="col-lg-12 col-md-12">
<div className="project-details-desc">
<h3>Rapid Solution</h3>
<p>
Founded in 2010, Rapid Solution is headquartered in Lahore
with an active presence in Karachi and Islamabad. Hashcrafts
provides innovatives products and high value-added services
including Print Solutions, Hardware Solutions, Accessories
Parts, Repairs and Services Contracts with focus on
understanding the unique needs of each customer and creating
solutions to match their requirment in a professional and
efficient manner with in the costumer’s budget and a determind
time frame. Hashcrafts has now decided to go Online with
Doorstep Repair Facility named as Rapid Solution. We tend to
use our experience to provide better services to our customers
with professionalism.
</p>
<p>
We always Demonstrate the core values of professionalism
leading to long lasting Business relationships wih Customers.
Doorstep Repair Service Saving customers' time and energy, We
put in ours to ensure your Laptop's fixation at Doorstep and
at earliest. Cost Effective Solutions We also sale parts and
accessories taking into concern our customers that are looking
for Cost Effective Solutions.As we Believe in long lasting
Business Relationships, we focus on maintaining customers'
trust throughout. Experience For the services we provide, we
bring in our 6+ years experience into work to ensure Quality.
Innovation Generating new ideas and implementing them, we
regularly bring in up innovations within our services.
</p>
<div className="project-details-information">
<div className="single-info-box">
<h4>Happy Client</h4>
<p><NAME></p>
</div>
<div className="single-info-box">
<h4>Category</h4>
<p>Portfolio, Personal</p>
</div>
<div className="single-info-box">
<h4>Date</h4>
<p>February 28, 2019</p>
</div>
<div className="single-info-box">
<h4>Share</h4>
<ul>
<li>
<a href="#">
<Icon.Facebook />
</a>
</li>
<li>
<a href="#">
<Icon.Twitter />
</a>
</li>
<li>
<a href="#">
<Icon.Instagram />
</a>
</li>
<li>
<a href="#">
<Icon.Linkedin />
</a>
</li>
</ul>
</div>
<div className="single-info-box">
<a href="#" className="btn btn-primary">
Live Preview
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
);
}
}
<file_sep># Hashcrafts
My Company
<file_sep>import React, { Component } from "react";
import ReactWOW from "react-wow";
class WhyChoose extends Component {
render() {
return (
<section className="why-choose-us ptb-80">
<div className="container">
<div className="row align-items-center">
<div className="col-lg-6 col-md-12">
<div className="section-title">
<h2>Why Choose Us</h2>
<div className="bar"></div>
<p>
We always focus on results. For us it’s all about what adds
value for you and your business
</p>
</div>
<div className="why-choose-us-image">
<ReactWOW animation="fadeInLeft">
<img
src={require("../../static/images/why-choose-us-image/man-stand.png")}
className="wow fadeInLeft"
alt="image"
/>
</ReactWOW>
<ReactWOW animation="fadeInRight">
<img
src={require("../../static/images/why-choose-us-image/database.png")}
className="wow fadeInRight"
alt="image"
/>
</ReactWOW>
<ReactWOW animation="rotateme">
<img
src={require("../../static/images/services-left-image/cercle-shape.png")}
className="rotateme"
alt="image"
/>
</ReactWOW>
<ReactWOW animation="fadeInUp">
<img
src={require("../../static/images/why-choose-us-image/main-static.png")}
className="main-pic"
alt="image"
/>
</ReactWOW>
</div>
</div>
<div className="col-lg-6 col-md-12">
<div className="row">
<div className="col-lg-6 col-md-6">
<div className="single-why-choose-us">
<div className="icon">
<i className="flaticon-team"></i>
</div>
<h3>Proficient & Friendly</h3>
<p>
We're Proficient as well as accountable to our clients and
to each other, and respond to problems with solutions, not
blame.
</p>
</div>
</div>
<div className="col-lg-6 col-md-6">
<div className="single-why-choose-us">
<div className="icon">
<i className="flaticon-rocket"></i>
</div>
<h3>Extremely Fast</h3>
<p>
We build applications with minimalist and sleek design to
give it a performance boost and make it extremely fast.
</p>
</div>
</div>
<div className="col-lg-6 col-md-6">
<div className="single-why-choose-us">
<div className="icon">
<i className="flaticon-shield"></i>
</div>
<h3>100% Safe & Security</h3>
<p>
Give us your most ambitious projects and get in return
meticulous digital products that are fast, secure,
fault-tolerant, scalable, and maintainable.
</p>
</div>
</div>
<div className="col-lg-6 col-md-6">
<div className="single-why-choose-us">
<div className="icon">
<i className="flaticon-diamond"></i>
</div>
<h3>Top-Rated</h3>
<p>
Smart usability sparks at the design and technology,
keeping your audiences delighted which adds extra element
of emotion that our competitors covet.
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
);
}
}
export default WhyChoose;
<file_sep>import React from "react";
import { Preloader, Placeholder } from "react-preloading-screen";
import NoSSR from "react-no-ssr";
import Header from "../components/hashcraft/Header";
import Funfacts from "../components/hashcraft/Funfacts";
import Footer from "../components/hashcraft/Footer";
import GoTop from "../components/hashcraft/GoTop";
import PageTitle from "../components/hashcraft/PageTitle";
import AboutArea from "../components/hashcraft/AboutArea";
import WhyChoose from "../components/hashcraft/WhyChoose";
import CtaArea from "../components/hashcraft/AgencyCtaArea";
const About = () => {
return (
<NoSSR>
<Preloader>
<Placeholder>
<div className="preloader">
<div className="spinner"></div>
</div>
</Placeholder>
<Header />
<PageTitle title="About Us" />
<AboutArea />
<WhyChoose />
<Funfacts />
<CtaArea />
<Footer />
<GoTop scrollStepInPx="50" delayInMs="16.66" />
</Preloader>
</NoSSR>
);
};
export default About;
<file_sep>import React from "react";
import "react-accessible-accordion/dist/fancy-example.css";
import "isomorphic-fetch";
export default class ContentBody extends React.Component {
state = {
submitting: false,
submitted: false,
buttonState: "",
formFields: {
name: "",
email: "",
subject: "",
phone: "",
text: "",
},
};
onSubmit = (e) => {
e.preventDefault();
const data = this.state.formFields;
fetch("/api/contact", {
method: "post",
headers: {
Accept: "application/json, text/plain",
"Content-Type": "application/json",
},
body: JSON.stringify(data),
}).then((res) => {
res.status === 200 ? this.setState({ submitted: true }) : "";
let formFields = Object.assign({}, this.state.formFields);
formFields.name = "";
formFields.email = "";
formFields.phone = "";
formFields.subject = "";
formFields.text = "";
this.setState({ formFields });
});
};
nameChangeHandler = (e) => {
let formFields = Object.assign({}, this.state.formFields);
formFields.name = e.target.value;
this.setState({ formFields });
};
emailChangeHandler = (e) => {
let formFields = Object.assign({}, this.state.formFields);
formFields.email = e.target.value;
this.setState({ formFields });
};
phoneChangeHandler = (e) => {
let formFields = Object.assign({}, this.state.formFields);
formFields.phone = e.target.value;
this.setState({ formFields });
};
subjectChangeHandler = (e) => {
let formFields = Object.assign({}, this.state.formFields);
formFields.subject = e.target.value;
this.setState({ formFields });
};
textChangeHandler = (e) => {
let formFields = Object.assign({}, this.state.formFields);
formFields.text = e.target.value;
this.setState({ formFields });
};
onHideSuccess = () => {
this.setState({ submitted: false });
};
successMessage = () => {
if (this.state.submitted) {
return (
<div className="alert alert-success">
<strong>Thank you!</strong> Your message is send to the owner
<button onClick={this.onHideSuccess} type="button" className="close">
<span aria-hidden="true">×</span>
</button>
</div>
);
}
};
render() {
return (
<section className="faq-area ptb-80">
<div className="container">
<section id="proposal"></section>
<div className="faq-contact">
<h3>Ask Your Question</h3>
<form onSubmit={this.onSubmit}>
<div className="row">
<div className="col-lg-6 col-md-6">
<div className="form-group">
<input
type="text"
name="name"
className="form-control"
required
data-error="Please enter your name"
placeholder="Name"
value={this.state.formFields.name}
onChange={this.nameChangeHandler}
/>
</div>
</div>
<div className="col-lg-6 col-md-6">
<div className="form-group">
<input
type="email"
name="email"
className="form-control"
required
data-error="Please enter your email"
placeholder="Email"
value={this.state.formFields.email}
onChange={this.emailChangeHandler}
/>
</div>
</div>
<div className="col-lg-6 col-md-6">
<div className="form-group">
<input
type="text"
name="phone"
className="form-control"
placeholder="Phone"
value={this.state.formFields.phone}
onChange={this.phoneChangeHandler}
/>
</div>
</div>
<div className="col-lg-6 col-md-6">
<div className="form-group">
<input
type="text"
name="subject"
className="form-control"
placeholder="Subject"
value={this.state.formFields.subject}
onChange={this.subjectChangeHandler}
/>
</div>
</div>
<div className="col-lg-12 col-md-12">
<div className="form-group">
<textarea
name="message"
className="form-control"
id="message"
cols="30"
rows="5"
required
data-error="Write your message"
placeholder="Your Message"
value={this.state.formFields.text}
onChange={this.textChangeHandler}
/>
</div>
</div>
<div className="col-lg-12 col-md-12">
<button className="btn btn-primary" type="submit">
Submit Now!
</button>
</div>
</div>
{this.successMessage()}
</form>
</div>
</div>
</section>
);
}
}
<file_sep>import React, { Component } from "react";
import Header from "../components/hashcraft/Header";
import Footer from "../components/hashcraft/Footer";
import FaqContent from "../components/hashcraft/ContentBody";
import WhyChoose from "../components/hashcraft/WhyChoose";
import PageTitle from "../components/hashcraft/PageTitle";
class ServiceDetails extends Component {
render() {
return (
<React.Fragment>
<Header />
<PageTitle title='Digital Marketing' />
<section className="services-details-area ptb-80">
<div className="container">
<div className="row ">
<div className="col-lg-6 services-details">
<div className="services-details-desc">
<h3>Unique and creative design tailored to each client</h3>
<p>
At <b>Hashcrafts</b>, we provide our clients with written
and visual content using methods that are proven. The right
content can help you to become authoritative, visible and
engaging in a way you couldn’t otherwise imagine. Customers
want to transact with a brand where they can be part of a
conversation online; powerful content can facilitate
meaningful engagement.
</p>
<p>
When it comes to choosing a vendor to help with your digital
marketing plans, you should rely on a company that provides
quality content and helps you make an informed decision.
<b>Hashcrafts</b> has a team of skilled writers, designers,
developers and marketers who can build a meaningful content
marketing plan and can help you become a trusted source for
your target audience. Some of the key reasons we are
different from others in the market is our lifecycle and
workflow.
</p>
<p>
Through our digital services we can begin by focussing the
digital changes that directly influence a client’s business
strategy and where we can easily deliver return on
investment, where we then expand into larger scale digital
initiatives from discovery, to launch and beyond.
</p>
<a className="btn btn-primary" href="#proposal">
Request a proposal
</a>
</div>
</div>
<div className="col-lg-6 services-details-image">
<img
src={require("../static/images/home/digitalmarketing.jpg")}
className="wow fadeInUp"
alt="image"
/>
</div>
</div>
</div>
</section>
<WhyChoose />
<FaqContent />
<Footer />
</React.Fragment>
);
}
}
export default ServiceDetails;
<file_sep>import React, { Component } from "react";
import Link from "next/link";
import * as Icon from "react-feather";
class Services extends Component {
render() {
return (
<section className="iot-services-area ptb-80">
<div className="container">
<div className="section-title">
<h2>Core Modules</h2>
<div className="bar"></div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
</div>
<div className="row">
<div className="col-lg-3 col-md-4">
<div className="single-repair-services">
<div className="icon">
<Icon.Monitor />
</div>
<h3>Front Shop & Dashboard</h3>
</div>
</div>
<div className="col-lg-3 col-md-4">
<div className="single-repair-services">
<div className="icon">
<i>
<Icon.Smile />
</i>
</div>
<h3>User Friendly</h3>
<br />
</div>
</div>
<div className="col-lg-3 col-md-4">
<div className="single-repair-services">
<div className="icon">
<i>
<Icon.Edit />
</i>
</div>
<h3>User Generated Reviews</h3>
</div>
</div>
<div className="col-lg-3 col-md-4">
<div className="single-repair-services">
<div className="icon">
<i>
<Icon.List />
</i>
</div>
<h3>Wish List</h3>
<br />
</div>
</div>
<div className="col-lg-3 col-md-4">
<div className="single-repair-services">
<div className="icon">
<i>
<Icon.Search />
</i>
</div>
<h3>Related Items</h3>
</div>
</div>
<div className="col-lg-3 col-md-4">
<div className="single-repair-services">
<div className="icon">
<i>
<Icon.Award />
</i>
</div>
<h3>Fully Secured</h3>
</div>
</div>
<div className="col-lg-3 col-md-4">
<div className="single-repair-services">
<div className="icon">
<i>
<Icon.CreditCard />
</i>
</div>
<h3>Online Payment</h3>
</div>
</div>
<div className="col-lg-3 col-md-4">
<div className="single-repair-services">
<div className="icon">
<i>
<Icon.Settings />
</i>
</div>
<h3>Fully Customizable</h3>
</div>
</div>
<div className="col-lg-3 col-md-4">
<div className="single-repair-services">
<div className="icon">
<i>
<Icon.Truck />
</i>
</div>
<h3>Order & Shipping Management </h3>
</div>
</div>
<div className="col-lg-3 col-md-4">
<div className="single-repair-services">
<div className="icon">
<i>
<Icon.MoreHorizontal />
</i>
</div>
<h3>& Many More</h3>
<br />
</div>
</div>
</div>
</div>
</section>
);
}
}
export default Services;
<file_sep>import React from 'react'
export default function PageTitle(props) {
return (
<div className="page-title-area">
<div className="d-table">
<div className="d-table-cell">
<div className="container">
<h2>{props.title}</h2>
</div>
</div>
</div>
<div className="shape1"><img src={require("../../static/images/shape1.png")} alt="shape" /></div>
<div className="shape2 rotateme"><img src={require("../../static/images/shape2.svg")} alt="shape" /></div>
<div className="shape3"><img src={require("../../static/images/shape3.svg")} alt="shape" /></div>
<div className="shape4"><img src={require("../../static/images/shape4.svg")} alt="shape" /></div>
<div className="shape5"><img src={require("../../static/images/shape5.png")} alt="shape" /></div>
<div className="shape6 rotateme"><img src={require("../../static/images/shape4.svg")} alt="shape" /></div>
<div className="shape7"><img src={require("../../static/images/shape4.svg")} alt="shape" /></div>
<div className="shape8 rotateme"><img src={require("../../static/images/shape2.svg")} alt="shape" /></div>
</div>
)
}
<file_sep>import React from 'react'
import { Preloader, Placeholder } from 'react-preloading-screen'
import Header from '../components/hashcraft/Header'
import Footer from '../components/hashcraft/Footer'
import GoTop from '../components/hashcraft/GoTop'
import PageTitle from '../components/hashcraft/PageTitle'
import DetailsBody from '../components/hashcraft/portfolio/fotisto/DetailsBody'
import CtaArea from "../components/hashcraft/AgencyCtaArea";
export default () => (
<Preloader>
<Placeholder>
<div className="preloader">
<div className="spinner"></div>
</div>
</Placeholder>
<Header />
<PageTitle title='Fotisto'/>
<DetailsBody />
<CtaArea />
<Footer />
<GoTop scrollStepInPx="50" delayInMs="16.66" />
</Preloader>
)
<file_sep>import React from "react";
import { Preloader, Placeholder } from "react-preloading-screen";
import NoSSR from "react-no-ssr";
import Header from "../components/hashcraft/Header";
import MainBanner from "../components/hashcraft/MainBanner";
import BoxArea from "../components/hashcraft/BoxArea";
import ServicesArea from "../components/hashcraft/ServicesArea";
import Features from "../components/hashcraft/Features";
import RecentWork from "../components/hashcraft/RecentWork";
import Feedback from "../components/hashcraft/Feedback";
import Funfacts from "../components/hashcraft/Funfacts";
import CtaArea from "../components/hashcraft/AgencyCtaArea";
import Footer from "../components/hashcraft/Footer";
import GoTop from "../components/hashcraft/GoTop";
const Index = () => {
return (
<NoSSR>
<Preloader>
<Placeholder>
<div className="preloader">
<div className="spinner"></div>
</div>
</Placeholder>
<Header />
<MainBanner />
<BoxArea />
<ServicesArea />
<Features />
<Funfacts />
<RecentWork />
<Feedback />
<CtaArea />
<Footer />
<GoTop scrollStepInPx="50" delayInMs="16.66" />
</Preloader>
</NoSSR>
);
};
export default Index;
// "start": "NODE_ENV=production node server.js -p $PORT"
<file_sep>import React, { Component } from "react";
import Link from "next/link";
class Services extends Component {
render() {
return (
<section className="ml-services-area ptb-80 bg-f7fafd">
<div className="container">
<div className="row">
<div className="col-lg-4 col-sm-6 col-md-6">
<Link href="/ui-ux">
<div className="single-ml-services-box">
<div className="image">
<img
src={require("../../static/images/home/uiux.png")}
alt="image"
/>
</div>
<h3>
<a>UI/UX Design</a>
</h3>
<p>
Lorem ipsum dolor sit amet elit, adipiscing, sed do eiusmod
tempor incididunt ut labore dolore magna aliqua.
</p>
</div>
</Link>
</div>
<div className="col-lg-4 col-sm-6 col-md-6">
<Link href="/web-app">
<div className="single-ml-services-box">
<div className="image1">
<img
src={require("../../static/images/home/webapp.jpg")}
alt="image"
/>
</div>
<h3>
<a>Web Development</a>
</h3>
<p>
Lorem ipsum dolor sit amet elit, adipiscing, sed do eiusmod
tempor incididunt ut labore dolore magna aliqua.
</p>
</div>
</Link>
</div>
<div className="col-lg-4 col-sm-6 col-md-6">
<Link href="/mobile-app">
<div className="single-ml-services-box">
<div className="image">
<img
src={require("../../static/images/home/mobileapp.jpg")}
alt="image"
/>
</div>
<h3>
<a>Mobile App Development</a>
</h3>
<p>
Lorem ipsum dolor sit amet elit, adipiscing, sed do eiusmod
tempor incididunt ut labore dolore magna aliqua.
</p>
</div>
</Link>
</div>
<div className="col-lg-4 col-sm-6 col-md-6">
<Link href="/ecommerce">
<div className="single-ml-services-box">
<div className="image1">
<img
src={require("../../static/images/home/home.png")}
alt="image"
/>
</div>
<h3>
<a>E-Commerce Development</a>
</h3>
<p>
Lorem ipsum dolor sit amet elit, adipiscing, sed do eiusmod
tempor incididunt ut labore dolore magna aliqua.
</p>
</div>
</Link>
</div>
<div className="col-lg-4 col-sm-6 col-md-6">
<Link href="/digital-marketing">
<div className="single-ml-services-box">
<div className="image1">
<img
src={require("../../static/images/home/digitalmarketing.jpg")}
alt="image"
/>
</div>
<h3>
<a>Digital Marketing</a>
</h3>
<p>
Lorem ipsum dolor sit amet elit, adipiscing, sed do eiusmod
tempor incididunt ut labore dolore magna aliqua.
</p>
</div>
</Link>
</div>
<div className="col-lg-4 col-sm-6 col-md-6">
<Link href="/dedicated-team">
<div className="single-ml-services-box">
<div className="image">
<img
src={require("../../static/images/home/dedicatedteam.jpg")}
alt="image"
/>
</div>
<h3>
<a>Dedicated Team</a>
</h3>
<p>
Lorem ipsum dolor sit amet elit, adipiscing, sed do eiusmod
tempor incididunt ut labore dolore magna aliqua.
</p>
</div>
</Link>
</div>
</div>
</div>
{/* Shape Images */}
<div className="shape1">
<img src={require("../../static/images/shape1.png")} alt="shape" />
</div>
<div className="shape2 rotateme">
<img src={require("../../static/images/shape2.svg")} alt="shape" />
</div>
<div className="shape3">
<img src={require("../../static/images/shape3.svg")} alt="shape" />
</div>
<div className="shape4">
<img src={require("../../static/images/shape4.svg")} alt="shape" />
</div>
<div className="shape7">
<img src={require("../../static/images/shape4.svg")} alt="shape" />
</div>
<div className="shape8 rotateme">
<img src={require("../../static/images/shape2.svg")} alt="shape" />
</div>
</section>
);
}
}
export default Services;
<file_sep>import React from "react";
import Link from "next/link";
export default function ProjectContent() {
return (
<section className="works-area ptb-80 bg-f7fafd">
<div className="container">
<div className="row">
<div className="col-lg-4 col-md-6">
<Link href="/vonza">
<div className="single-works">
<img
src={require("../../../static/images/home/vonza1.png")}
alt="image"
/>
<div className="works-content">
<h3>Vonza</h3>
<p>
Vonza is the ultimate platform to build online courses, sell
products, offer services, construct sales funnels, schedule
appointments, launch email marketing campaigns and develop
amazing websites.
</p>
</div>
</div>
</Link>
</div>
<div className="col-lg-4 col-md-6">
<Link href="/rapidsolution">
<div className="single-works">
<img
src={require("../../../static/images/home/rapid1.png")}
alt="image"
/>
<div className="works-content">
<h3>Rapid Solution</h3>
<p>
Rapid Solution is the first laptop repair service in Lahore
to provide all sort of laptop repair solutions at your
doorstep.
</p>
</div>
</div>
</Link>
</div>
<div className="col-lg-4 col-md-6">
<Link href="/fotisto">
<div className="single-works">
<img
src={require("../../../static/images/home/fotisto1.png")}
alt="image"
/>
<div className="works-content">
<h3>Fotisto</h3>
<p>
Fotisto is a marketplace that uses AI and Cloud-based tools
to bridge clients with photographers/videographers.
</p>
</div>
</div>
</Link>
</div>
<div className="col-lg-4 col-md-6">
<Link href="/psms">
<div className="single-works">
<img
src={require("../../../static/images/home/school1.png")}
alt="image"
/>
<div className="works-content">
<h3>School Information System</h3>
<p>
Our School Management System is specialized to manage
education based organization like school, colleges,
Universities etc
</p>
</div>
</div>
</Link>
</div>
<div className="col-lg-4 col-md-6">
<Link href="/swatrader">
<div className="single-works">
<img
src={require("../../../static/images/home/furniture.png")}
alt="image"
/>
<div className="works-content">
<h3>SWA Trader</h3>
<p>
SWA Trader is one stop online shopping store. Having
all kinds of products from clothing and apparel to
electronics and mobile phones.
</p>
</div>
</div>
</Link>
</div>
</div>
</div>
<div className="shape8 rotateme">
<img src={require("../../../static/images/shape2.svg")} alt="shape" />
</div>
<div className="shape2 rotateme">
<img src={require("../../../static/images/shape2.svg")} alt="shape" />
</div>
<div className="shape7">
<img src={require("../../../static/images/shape4.svg")} alt="shape" />
</div>
<div className="shape4">
<img src={require("../../../static/images/shape4.svg")} alt="shape" />
</div>
</section>
);
}
<file_sep>import React from 'react'
import Link from 'next/link'
import dynamic from 'next/dynamic'
const Odometer = dynamic(import('react-odometerjs'),{
ssr: false,
loading: () => 0
});
import 'odometer/themes/odometer-theme-default.css';
class Funfacts extends React.Component {
state = {
download: 0,
feedback: 0,
worker: 0,
contributor: 0
};
componentDidMount(){
this.setState({
download: 180,
feedback: 250,
worker: 500,
contributor: 70
});
}
render(){
const { download, feedback, worker, contributor } = this.state;
return (
<section className="funfacts-area ptb-80">
<div className="container">
<div className="section-title">
<h2>We always try to understand users expectation</h2>
<div className="bar"></div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>
<div className="row">
<div className="col-lg-3 col-md-3 col-6">
<div className="funfact">
<h3>
<Odometer format="d" duration={500} value={download} />K
</h3>
<p>Downloaded</p>
</div>
</div>
<div className="col-lg-3 col-md-3 col-6">
<div className="funfact">
<h3>
<Odometer format="d" duration="500" value={feedback} />K
</h3>
<p>Feedback</p>
</div>
</div>
<div className="col-lg-3 col-md-3 col-6">
<div className="funfact">
<h3>
<Odometer format="d" duration="500" value={worker} />+
</h3>
<p>Workers</p>
</div>
</div>
<div className="col-lg-3 col-md-3 col-6">
<div className="funfact">
<h3>
<Odometer format="d" duration="500" value={contributor} />+
</h3>
<p>Contributors</p>
</div>
</div>
</div>
<div className="contact-cta-box">
<h3>Have any question about us?</h3>
<p>Don't hesitate to contact us</p>
<Link href="#">
<a className="btn btn-primary">Contact Us</a>
</Link>
</div>
<div className="map-bg">
<img src={require("../../static/images/map.png")} alt="map" />
</div>
</div>
</section>
)
}
}
export default Funfacts<file_sep>import React from "react";
import { withRouter } from "next/router";
import Link from "../common/ActiveLink";
import * as Icon from "react-feather";
class DefaultStyle extends React.Component {
state = {
collapsed: true,
};
toggleNavbar = () => {
this.setState({
collapsed: !this.state.collapsed,
});
};
componentDidMount() {
let elementId = document.getElementById("navbar");
document.addEventListener("scroll", () => {
if (window.scrollY > 170) {
elementId.classList.add("is-sticky");
} else {
elementId.classList.remove("is-sticky");
}
});
window.scrollTo(0, 0);
}
render() {
const { collapsed } = this.state;
const classOne = collapsed
? "collapse navbar-collapse"
: "collapse navbar-collapse show";
const classTwo = collapsed
? "navbar-toggler navbar-toggler-right collapsed"
: "navbar-toggler navbar-toggler-right";
let { pathname } = this.props.router;
let layOutCls = "";
if (pathname == "/home-three") {
layOutCls = "p-relative";
}
return (
<header id="header">
<div id="navbar" className={`startp-nav ${layOutCls}`}>
<div className="container">
<nav className="navbar navbar-expand-md navbar-light">
<Link href="/">
<a
className="navbar-brand"
onClick={() => window.location.refresh()}
>
<img
src={require("../../static/images/logop1.png")}
alt="logo"
/>
</a>
</Link>
<button
onClick={this.toggleNavbar}
className={classTwo}
type="button"
data-toggle="collapse"
data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span className="navbar-toggler-icon"></span>
</button>
<div className={classOne} id="navbarSupportedContent">
<ul className="navbar-nav nav ml-auto">
<li className="nav-item">
<Link activeClassName="active" href="/about">
<a className="nav-link">COMPANY</a>
</Link>
</li>
<li className="nav-item">
<Link activeClassName="active" href="/services">
<a href="#" className="nav-link">
SERVICES <Icon.ChevronDown />
</a>
</Link>
<ul className="dropdown_menu">
<li className="nav-item">
<Link activeClassName="active" href="/ui-ux">
<a className="nav-link">UI/UX Design</a>
</Link>
</li>
<li className="nav-item">
<Link activeClassName="active" href="/web-app">
<a className="nav-link">Web Development</a>
</Link>
</li>
<li className="nav-item">
<Link activeClassName="active" href="/mobile-app">
<a className="nav-link">Mobile App Development</a>
</Link>
</li>
<li className="nav-item">
<Link activeClassName="active" href="/ecommerce">
<a className="nav-link">E-commerce Development</a>
</Link>
</li>
<li className="nav-item">
<Link activeClassName="active" href="/digital-marketing">
<a className="nav-link">Digital Marketing</a>
</Link>
</li>
<li className="nav-item">
<Link activeClassName="active" href="/dedicated-team">
<a className="nav-link">Dedicated Team</a>
</Link>
</li>
</ul>
</li>
<li className="nav-item">
<a href="/solution" className="nav-link">
SOLUTIONS <Icon.ChevronDown />
</a>
<ul className="dropdown_menu">
<li className="nav-item">
<Link activeClassName="active" href="/sms">
<a className="nav-link">School Information System</a>
</Link>
</li>
<li className="nav-item">
<Link activeClassName="active" href="/pos">
<a className="nav-link">Point of Sale</a>
</Link>
</li>
<li className="nav-item">
<Link activeClassName="active" href="/e-commerce">
<a className="nav-link">E Commerce</a>
</Link>
</li>
</ul>
</li>
<li className="nav-item">
<Link activeClassName="active" href="/portfolio">
<a className="nav-link">PORTFOLIO</a>
</Link>
</li>
<li className="nav-item">
<Link activeClassName="active" href="/contact">
<a className="nav-link">CONTACT</a>
</Link>
</li>
</ul>
</div>
<div className="others-option">
<Link href="/contact#quotes">
<a className="btn btn-primary">
Request a quotes
</a>
</Link>
</div>
</nav>
</div>
</div>
</header>
);
}
}
export default withRouter(DefaultStyle);
<file_sep>import React from "react";
export default function About() {
return (
<section className="about-area ptb-80">
<div className="container">
<div className="row">
<div className="col-lg-6 col-md-12">
<div className="about-image">
<img
src={require("../../static/images/home/aboutus.jpg")}
alt="image"
/>
</div>
</div>
<div className="col-lg-6 col-md-12">
<div className="about-content">
<div className="section-title">
<h2>About Us</h2>
<div className="bar"></div>
<p>
Basic service delivery isn't enough to differentiate any web
development firm in today's competitive marketplace.
Understanding not only our client's web needs but their
business needs has propelled <b>Hashcrafts</b> beyond customer
satisfaction to loyalty.
</p>
</div>
<p>
<b>Hashcrafts</b> have established a reputation for consistently
delivering mission critical, technically challenging projects
under tight time lines, while also providing exceptional
customer service and support to our clients. This in turn has
led to extremely positive long-term working relationships with
both clients and solution partners alike.
</p>
<p>
{" "}
The natural benefit for clients is an efficient team that is
driven by the market to produce quality. The best teams win and
the proven engineering processes that have allowed our founders
to exit multiple firms are built into our efforts.{" "}
</p>
<p>
From business process inquiry to systems engineering, we provide
services tailored to your specific needs to enable an enterprise
where all the systems are integrated as work as a whole. We
provide ERP, CRM and custom applications to not only increase
the productivity of your team but also makes managing them a
breeze.
</p>
</div>
</div>
</div>
<div className="about-inner-area">
<div className="row">
<div className="col-lg-6 col-md-6">
<div className="about-text">
<h3>Our Mission</h3>
<p>
Whether it is a consumer-oriented app or a transformative
enterprise-class solution, the company leads the process from
ideation and concept to delivery, and provides ongoing support
through our framework. You’re investing more than money — it’s
also energy, intelligence, brand, and the expanding potential
of your business. Hashcrafts translates this investment into
meaningful impact for you and your audience.
</p>
</div>
</div>
<div className="col-lg-6 col-md-6 offset-lg-0 offset-md-3">
<div className="about-text">
<h3>Who we are</h3>
<p>
We are <b>Hashcrafts</b>, one of the Pakistan’s leading
bespoke software development companies with topranked
professional employees. We design intelligent, cost-effective
and intuitive web applications, desktop applications and
mobile apps that help streamline processes for businesses as
well as create new revenue streams for start-ups and
established businesses alike
</p>
</div>
</div>
</div>
</div>
</div>
</section>
);
}
<file_sep>import React, { Component } from "react";
import Link from "next/link";
class Services extends Component {
render() {
return (
<section className="ml-services-area ptb-80">
<div className="container">
<div className="section-title">
{/* <span className="sub-title">Our Solutions</span> */}
<h2>Our Services</h2>
<div className="bar"></div>
{/* <p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p> */}
</div>
<div className="row">
<div className="col-lg-4 col-sm-6 col-md-6">
<Link href="ui-ux">
<div className="single-ml-services-box">
<div className="image">
<img
src={require("../../static/images/services-image/service-image1.png")}
alt="image"
/>
</div>
<h3>
<a>UI/UX Design</a>
</h3>
<p>
Lorem ipsum dolor sit amet elit, adipiscing, sed do eiusmod
tempor incididunt ut labore dolore magna aliqua.
</p>
</div>
</Link>
</div>
<div className="col-lg-4 col-sm-6 col-md-6">
<Link href="web-app">
<div className="single-ml-services-box">
<div className="image">
<img
src={require("../../static/images/services-image/service-image2.png")}
alt="image"
/>
</div>
<h3>
<a>Web Development</a>
</h3>
<p>
Lorem ipsum dolor sit amet elit, adipiscing, sed do eiusmod
tempor incididunt ut labore dolore magna aliqua.
</p>
</div>
</Link>
</div>
<div className="col-lg-4 col-sm-6 col-md-6">
<Link href="/mobile-app">
<div className="single-ml-services-box">
<div className="image">
<img
src={require("../../static/images/services-image/service-image3.png")}
alt="image"
/>
</div>
<h3>
<a>Mobile App Development</a>
</h3>
<p>
Lorem ipsum dolor sit amet elit, adipiscing, sed do eiusmod
tempor incididunt ut labore dolore magna aliqua.
</p>
</div>
</Link>
</div>
<div className="col-lg-4 col-sm-6 col-md-6">
<Link href="/ecommerce">
<div className="single-ml-services-box">
<div className="image">
<img
src={require("../../static/images/services-image/service-image4.png")}
alt="image"
/>
</div>
<h3>
<a>E-Commerce Development</a>
</h3>
<p>
Lorem ipsum dolor sit amet elit, adipiscing, sed do eiusmod
tempor incididunt ut labore dolore magna aliqua.
</p>
</div>
</Link>
</div>
<div className="col-lg-4 col-sm-6 col-md-6">
<Link href="/hybrid-app">
<div className="single-ml-services-box">
<div className="image">
<img
src={require("../../static/images/services-image/service-image5.png")}
alt="image"
/>
</div>
<h3>
<a>Hybrid App Development</a>
</h3>
<p>
Lorem ipsum dolor sit amet elit, adipiscing, sed do eiusmod
tempor incididunt ut labore dolore magna aliqua.
</p>
</div>
</Link>
</div>
<div className="col-lg-4 col-sm-6 col-md-6">
<Link href="/digital-marketing">
<div className="single-ml-services-box">
<div className="image">
<img
src={require("../../static/images/services-image/service-image6.png")}
alt="image"
/>
</div>
<h3>
<a>Digital Marketing</a>
</h3>
<p>
Lorem ipsum dolor sit amet elit, adipiscing, sed do eiusmod
tempor incididunt ut labore dolore magna aliqua.
</p>
</div>
</Link>
</div>
<div className="col-lg-4 col-sm-6 col-md-6">
<Link href="/app-deployment">
<div className="single-ml-services-box">
<div className="image">
<img
src={require("../../static/images/services-image/service-image6.png")}
alt="image"
/>
</div>
<h3>
<a>Application Deployment</a>
</h3>
<p>
Lorem ipsum dolor sit amet elit, adipiscing, sed do eiusmod
tempor incididunt ut labore dolore magna aliqua.
</p>
</div>
</Link>
</div>
<div className="col-lg-4 col-sm-6 col-md-6">
<Link href="/dedicated-team">
<div className="single-ml-services-box">
<div className="image">
<img
src={require("../../static/images/services-image/service-image6.png")}
alt="image"
/>
</div>
<h3>
<a>Dedicated Team</a>
</h3>
<p>
Lorem ipsum dolor sit amet elit, adipiscing, sed do eiusmod
tempor incididunt ut labore dolore magna aliqua.
</p>
</div>
</Link>
</div>
</div>
</div>
{/* Shape Images */}
<div className="shape1">
<img src={require("../../static/images/shape1.png")} alt="shape" />
</div>
<div className="shape2 rotateme">
<img src={require("../../static/images/shape2.svg")} alt="shape" />
</div>
<div className="shape3">
<img src={require("../../static/images/shape3.svg")} alt="shape" />
</div>
<div className="shape4">
<img src={require("../../static/images/shape4.svg")} alt="shape" />
</div>
<div className="shape7">
<img src={require("../../static/images/shape4.svg")} alt="shape" />
</div>
<div className="shape8 rotateme">
<img src={require("../../static/images/shape2.svg")} alt="shape" />
</div>
</section>
);
}
}
export default Services;
<file_sep>import React from "react";
import Link from "next/link";
import * as Icon from "react-feather";
export default class Footer extends React.Component {
render() {
return (
<footer className="footer-area bg-f7fafd">
<div className="container">
<div className="row">
<div className="col-lg-3 col-md-6">
<div className="single-footer-widget">
<div className="logo">
<Link href="#">
<a>
<img
src={require("../../static/images/logo.png")}
alt="logo"
/>
</a>
</Link>
</div>
<p>
Hashcrafts is a premium IT company that focuses on quality,
innovation, & speed. We utilize technology to bring results to
grow our clients businesses. We pride ourselves in great work
ethic, integrity, and end-results.
</p>
</div>
</div>
<div className="col-lg-3 col-md-6">
<div className="single-footer-widget pl-5">
<h3>Company</h3>
<ul className="list">
<li>
<Link href="/">
<a>Home</a>
</Link>
</li>
<li>
<Link href="/about">
<a>About Us</a>
</Link>
</li>
<li>
<Link href="/services">
<a>Services</a>
</Link>
</li>
<li>
<Link href="/solution">
<a>Solution</a>
</Link>
</li>
<li>
<Link href="/portfolio">
<a>Portfolio</a>
</Link>
</li>
<li>
<Link href="/contact">
<a>Contact Us</a>
</Link>
</li>
</ul>
</div>
</div>
<div className="col-lg-3 col-md-6">
<div className="single-footer-widget">
<h3>Services</h3>
<ul className="list">
<li>
<Link href="/ui-ux">
<a>UI/UX Design</a>
</Link>
</li>
<li>
<Link href="/web-app">
<a>Web Development</a>
</Link>
</li>
<li>
<Link href="/mobile-app">
<a>Mobile App Development</a>
</Link>
</li>
<li>
<Link href="/ecommerce">
<a>E-commerce Development</a>
</Link>
</li>
<li>
<Link href="/digital-marketing">
<a>Digital Marketing</a>
</Link>
</li>
<li>
<Link href="/dedicated-team">
<a>Dedicated Team</a>
</Link>
</li>
</ul>
</div>
</div>
<div className="col-lg-3 col-md-6">
<div className="single-footer-widget">
<h3>Address</h3>
<ul className="footer-contact-info">
<li>
<Icon.MapPin />
IT Tower Gulberg, Lahore
</li>
<li>
<Icon.Mail />
{/* <Link href="#"> */}
<a><EMAIL></a>
{/* </Link> */}
</li>
<li>
<Icon.PhoneCall />
{/* <Link href="#"> */}
<a>+923248402906</a>
<br />
<a>+923224991944</a>
{/* </Link> */}
</li>
</ul>
<ul className="social-links">
<li>
<Link href="#">
<a className="facebook">
<Icon.Facebook />
</a>
</Link>
</li>
<li>
<Link href="#">
<a className="twitter">
<Icon.Twitter />
</a>
</Link>
</li>
<li>
<Link href="#">
<a className="instagram">
<Icon.Instagram />
</a>
</Link>
</li>
<li>
<Link href="#">
<a className="linkedin">
<Icon.Linkedin />
</a>
</Link>
</li>
</ul>
</div>
</div>
<div className="col-lg-12 col-md-12">
<div className="copyright-area">
<p>© Copyright 2020 hashcrafts. All rights reserved</p>
</div>
</div>
</div>
</div>
<img
src={require("../../static/images/map.png")}
className="map"
alt="map"
/>
</footer>
);
}
}
<file_sep>import React, { Component } from "react";
import * as Icon from "react-feather";
import "../../../../node_modules/react-modal-video/css/modal-video.min.css";
import Lightbox from "react-image-lightbox";
import "react-image-lightbox/style.css";
const images = [
require("../../../../static/images/home/dashboard.png"),
require("../../../../static/images/home/bags.png"),
require("../../../../static/images/home/furniture.png"),
require("../../../../static/images/home/checkout.png"),
require("../../../../static/images/home/checkout1.png"),
];
export default class DetailsBody extends Component {
state = {
isOpen: false,
photoIndex: 0,
isOpenImage: false,
};
openModal = () => {
this.setState({ isOpen: true });
};
render() {
const { photoIndex, isOpenImage } = this.state;
return (
<section className="project-details-area ptb-80">
<div className="container">
<div className="row">
<div className="col-lg-6 col-md-6">
<div
className="project-details-image"
onClick={() => this.setState({ isOpenImage: true })}
>
<img
src={require("../../../../static/images/home/dashboard.png")}
alt="work"
/>
<Icon.Plus />
</div>
</div>
{isOpenImage && (
<Lightbox
mainSrc={images[photoIndex]}
nextSrc={images[(photoIndex + 1) % images.length]}
prevSrc={
images[(photoIndex + images.length - 1) % images.length]
}
onCloseRequest={() => this.setState({ isOpenImage: false })}
onMovePrevRequest={() =>
this.setState({
photoIndex:
(photoIndex + images.length - 1) % images.length,
})
}
onMoveNextRequest={() =>
this.setState({
photoIndex: (photoIndex + 1) % images.length,
})
}
/>
)}
<div className="col-lg-6 col-md-6">
<div
className="project-details-image"
onClick={() => this.setState({ isOpenImage: true })}
>
<img
src={require("../../../../static/images/home/bags.png")}
alt="work"
/>
<Icon.Plus />
</div>
</div>
<div className="col-lg-12 col-md-12">
<div className="project-details-desc">
<h3>E-commerce Solution</h3>
<p>
Take your e-commerce efforts to the next level to be the best
in your niche or start your full-on digital transformation. We
can help you be the best online business in your category,
improve existing workflow, analyze visitors’ shopping patterns
and drive value for your business’s digital presence and your
customers. Your e-commerce presence can be the tip of the
spear for customers engaging with your product and your brand.
Tying together inventory management, shipping, billing and
product analytics can materially drive return on investment.
The e-commerce landscape is rapidly evolving and fiercely
competitive. Whether you are implementing a new platform,
updating existing infrastructure, leverage our experienced
team to help you filter out the noise. When you invest in a
robust commerce experience, it powers your sales team to be
more efficient and spend more time fostering customer
relationships. Our eCommerce solution gives your customers the
power to interact with your business how they want, when they
want, and at their moment of relevance.
</p>
<p>
Our super-fast E-commerce template was made to help anyone
start their very own online store at ease. Built with React,
NextJS, TypeScript, GraphQL, Type-GraphQL & Styled-Components,
our template promises to deliver an interface for your
business that is quick and easy to set up! For GraphQL we used
GraphQL and type-graphql, you can build your schema very
easily. GraphQL playground makes its own documentation, your
frontend team will love using it. We have added REST API
integration with SWR for the customers who had already a
REST-based backend for remote data fetching.
</p>
</div>
</div>
</div>
</div>
</section>
);
}
}
<file_sep>import React from "react";
import { Preloader, Placeholder } from "react-preloading-screen";
import Header from "../components/hashcraft/Header";
import Footer from "../components/hashcraft/Footer";
import GoTop from "../components/hashcraft/GoTop";
import PageTitle from "../components/hashcraft/PageTitle";
import ProjectContent from "../components/hashcraft/portfolio/ProjectContent";
import CtaArea from "../components/hashcraft/AgencyCtaArea";
class Project extends React.Component {
render() {
return (
<Preloader>
<Placeholder>
<div className="preloader">
<div className="spinner"></div>
</div>
</Placeholder>
<Header />
<PageTitle title="Our Portfolio" />
<ProjectContent />
<CtaArea />
<Footer />
<GoTop scrollStepInPx="50" delayInMs="16.66" />
</Preloader>
);
}
}
export default Project;
<file_sep>const express = require("express");
const next = require("next");
const path = require("path");
const bodyParser = require("body-parser");
const dev = process.env.NODE_ENV !== "production";
const app = next({ dir: ".", dev });
const handle = app.getRequestHandler();
const UserModel = require("./server/Model/user");
//DB connection
require("./server/Helper/db");
app.prepare().then(() => {
const server = express();
server.use(
"/images",
express.static(path.join(__dirname, "images"), {
maxAge: dev ? "0" : "365d",
})
);
server.use(bodyParser.json());
server.get("*", (req, res) => {
return handle(req, res);
});
server.post("/api/contact", (req, res) => {
const { name, email, phone, subject, text } = req.body;
const user = new UserModel({
name,
email,
phone,
subject,
message: text
});
user
.save()
.then((data) => {
res.status(200).send("success");
console.log(data);
})
.catch((err) => res.send(err));
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, (err) => {
if (err) throw err;
console.log(`> Read on http://localhost:${PORT}`);
});
});
<file_sep>const nodemailer = require('nodemailer')
const sgTransport = require('nodemailer-sendgrid-transport')
const transporter = nodemailer.createTransport(sgTransport({
auth: {
api_key: '<KEY>'
}
}))
const send = ({ name, email, phone, subject, text }) => {
const textBody = `Name: ${name}
Subject: ${subject}
Email: ${email}
Phone: ${phone}
Body: ${text}
This email came from StartP React.js & Next.js template
`
const from = name && email ? `${name} <${email}>` : `${name || email}`
const message = {
from,
to: '<EMAIL>',
subject: subject,
text: textBody,
replyTo: from
}
return new Promise((resolve, reject) => {
transporter.sendMail(message, (error, info) =>
error ? reject(error) : resolve(info)
)
})
}
module.exports = send<file_sep>import React, { Component } from "react";
import ModalVideo from "react-modal-video";
import * as Icon from "react-feather";
import "../../../../node_modules/react-modal-video/css/modal-video.min.css";
import Lightbox from "react-image-lightbox";
import "react-image-lightbox/style.css";
const images = [
require("../../../../static/images/home/school1.png"),
require("../../../../static/images/home/school3.png"),
require("../../../../static/images/home/school4.png"),
require("../../../../static/images/home/school5.png"),
require("../../../../static/images/home/school2.png"),
];
export default class DetailsBody extends Component {
state = {
isOpen: false,
photoIndex: 0,
isOpenImage: false,
};
openModal = () => {
this.setState({ isOpen: true });
};
render() {
const { photoIndex, isOpenImage } = this.state;
return (
<section className="project-details-area ptb-80">
<div className="container">
<div className="row">
<div className="col-lg-6 col-md-6">
<div
className="project-details-image"
onClick={() => this.setState({ isOpenImage: true })}
>
<img
src={require("../../../../static/images/home/school1.png")}
alt="work"
/>
<Icon.Plus />
</div>
</div>
{isOpenImage && (
<Lightbox
mainSrc={images[photoIndex]}
nextSrc={images[(photoIndex + 1) % images.length]}
prevSrc={
images[(photoIndex + images.length - 1) % images.length]
}
onCloseRequest={() => this.setState({ isOpenImage: false })}
onMovePrevRequest={() =>
this.setState({
photoIndex:
(photoIndex + images.length - 1) % images.length,
})
}
onMoveNextRequest={() =>
this.setState({
photoIndex: (photoIndex + 1) % images.length,
})
}
/>
)}
<div className="col-lg-6 col-md-6">
<div
className="project-details-image"
onClick={() => this.setState({ isOpenImage: true })}
>
<img
src={require("../../../../static/images/home/school4.png")}
alt="work"
/>
<Icon.Plus />
</div>
</div>
<div className="col-lg-12 col-md-12">
<div className="project-details-desc">
<h3>School Management System</h3>
<p>
Our School Management System is uses for manage education
based organization like school, collage, Universities etc. It
is a powerful user-friendly System designed as per user's
perspective with multiple MIS reports & multiple login. The
number of schools is multiplying faster. Parents have become
more attentive about their child, their activities & progress
in the school. With our School Management System, parents will
receive complete information of their child their Attendance,
Daily Time table, Progress reports (current as well as
previous) from the comfort of their home.SMS & eMail facility
ensures the parents to remain updated with school activities.
Our school system can process-centric & continues its
functioning with a lesser number of staff. Now no tension
about employee job changing & finding data. Everything is now
electronically preserved.
</p>
<p>
Our School Management system is known for its spotless
structure and design and for its resourceful competence. Our
School Management Software, specifically designed and
developed to simplify the process of educational institutions
meets with all the technological and administrative
requirements of schools. The many tools enable proper workflow
in different departments leaving no room for errors with a
view to encourage and make positive difference in students.
This complete school management system automates and
administers different academic and non-academic tasks in
school making them easy, fast, efficient and accurate, aiding
multiple departments, prospective students, faculties, staff
and others. This school automation system has been created to
help every institution manage all their data in a seamless and
systematic manner. The product ensures to provide quality and
result oriented solutions to all your worries.
</p>
</div>
</div>
</div>
</div>
</section>
);
}
}
<file_sep>import React from 'react'
import { Preloader, Placeholder } from 'react-preloading-screen'
import Header from '../components/hashcraft/Header'
import Footer from '../components/hashcraft/Footer'
import GoTop from '../components/hashcraft/GoTop'
import PageTitle from '../components/hashcraft/PageTitle'
import ProjectContent from '../components/hashcraft/solutions/ProjectContent'
import CtaArea from "../components/hashcraft/AgencyCtaArea";
class Project extends React.Component {
render() {
return (
<Preloader>
<Placeholder>
<div className="preloader">
<div className="spinner"></div>
</div>
</Placeholder>
<Header />
<PageTitle title='Our Solutions'/>
<ProjectContent />
<CtaArea />
<Footer />
<GoTop scrollStepInPx="50" delayInMs="16.66" />
</Preloader>
)
}
}
export default Project<file_sep>import React, { Component } from "react";
import OwlCarousel from "react-owl-carousel3";
const options = {
loop: false,
nav: false,
dots: true,
autoplay: true,
smartSpeed: 1000,
autoplayTimeout: 5000,
items: 1,
};
class Feedback extends Component {
render() {
return (
<section className="feedback-area ptb-80">
<div className="container">
<div className="section-title">
<h2>What clients saying</h2>
<div className="bar"></div>
<p>
We deliver globally, providing result-driven project management
and seamless communication.
</p>
</div>
<OwlCarousel
className="testimonials-slides owl-carousel owl-theme"
{...options}
>
<div className="single-feedback-item">
<div className="client-info align-items-center">
<div className="image">
<img
src={require("../../static/images/client-image/client1.jpg")}
alt="image"
/>
</div>
<div className="title">
<h3><NAME></h3>
<span>Lead Developer at Envato</span>
</div>
</div>
<p>
Quis ipsum suspendisse ultrices gravida. Risus commodo viverra
maecenas accumsan lacus vel facilisis. Lorem ipsum dolor sit
amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua.
</p>
</div>
<div className="single-feedback-item">
<div className="client-info align-items-center">
<div className="image">
<img
src={require("../../static/images/client-image/client2.jpg")}
alt="image"
/>
</div>
<div className="title">
<h3><NAME></h3>
<span>Lead Developer at Envato</span>
</div>
</div>
<p>
Quis ipsum suspendisse ultrices gravida. Risus commodo viverra
maecenas accumsan lacus vel facilisis. Lorem ipsum dolor sit
amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua.
</p>
</div>
<div className="single-feedback-item">
<div className="client-info align-items-center">
<div className="image">
<img
src={require("../../static/images/client-image/client3.jpg")}
alt="image"
/>
</div>
<div className="title">
<h3><NAME></h3>
<span>Lead Developer at Envato</span>
</div>
</div>
<p>
Quis ipsum suspendisse ultrices gravida. Risus commodo viverra
maecenas accumsan lacus vel facilisis. Lorem ipsum dolor sit
amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua.
</p>
</div>
</OwlCarousel>
</div>
<div className="shape5">
<img src={require("../../static/images/shape5.png")} alt="shape" />
</div>
</section>
);
}
}
export default Feedback;
<file_sep>import React from "react";
import Link from "next/link";
import ReactWOW from "react-wow";
import Banner from "../../static/images/home/home.png";
const MainBanner = () => {
return (
<div className="main-banner">
<div className="d-table">
<div className="d-table-cell">
<div className="container">
<div className="row h-100 justify-content-center align-items-center">
<div className="col-lg-5">
<ReactWOW delay="0.5s" animation="fadeInLeft">
<div className="hero-content">
<h1>Craft Your Business With Us</h1>
<p>
We consult, design & engineer successful web, mobile &
custom software solutions, that fuel innovation & increase
business efficiency!
</p>
<Link href="#">
<a className="btn btn-primary">Get Started</a>
</Link>
</div>
</ReactWOW>
</div>
<div className="col-lg-6 offset-lg-1">
<ReactWOW delay="0.5s" animation="fadeInUp">
<img
src={Banner}
className="wow fadeInUp"
data-wow-delay="0"
alt="main-pic"
/>
</ReactWOW>
</div>
</div>
</div>
</div>
</div>
</div>
);
};
export default MainBanner;
<file_sep>import React, { Component } from "react";
import Header from "../components/hashcraft/Header";
import PageTitle from "../components/hashcraft/PageTitle";
import Footer from "../components/hashcraft/Footer";
import FaqContent from "../components/hashcraft/ContentBody";
import WhyChoose from "../components/hashcraft/WhyChoose";
class ServiceDetails extends Component {
render() {
return (
<React.Fragment>
<Header />
<PageTitle title='Web App Development'/>
<section className="services-details-area ptb-80">
<div className="container">
<div className="row ">
<div className="col-lg-6 services-details">
<div className="services-details-desc">
<h3>Productive & Engaging Web Solutions For Your Business</h3>
<p>
We empower our clients with adaptive web applications built
using React, PostgreSQL, Python, MongoDB, Angular, Node.js
to simplify complex business workflows.
</p>
<p>
We strive for efficiency in custom web applications by
subjecting them to accepted design standards and testing.
The agile practices followed by us ensure that the projects
are delivered within the stipulated time and budget.
</p>
<p>
Customized web applications fosters growth in valuation and
intellectual property in the long run. Businesses can better
streamline their daily operations and processes to fulfill
key challenges and achieve targeted goals.
</p>
<p>
We have carved out a niche in web application development,
alongside valued consulting and analysis solutions, to serve
growing businesses and industry leaders
</p>
<a className="btn btn-primary" href="#proposal">
Request a proposal
</a>
</div>
</div>
<div className="col-lg-6 services-details-image">
<img
src={require("../static/images/home/webapp.jpg")}
className="wow fadeInUp"
alt="image"
/>
</div>
</div>
</div>
</section>
<WhyChoose />
<FaqContent />
<Footer />
</React.Fragment>
);
}
}
export default ServiceDetails;
<file_sep>import React from "react";
import Link from "next/link";
import * as Icon from "react-feather";
import OwlCarousel from "react-owl-carousel3";
const slideOptions = {
items: 4,
loop: true,
nav: false,
autoplay: true,
dots: false,
responsive: {
0: {
items: 1,
},
768: {
items: 2,
},
1200: {
items: 3,
},
1500: {
items: 4,
},
},
};
class RecentWork extends React.Component {
render() {
return (
<section className="works-area ptb-80 bg-f7fafd">
<div className="container">
<div className="section-title">
<h2>Our Recent Works</h2>
<div className="bar"></div>
<p>
Some highlights of our favorite projects we've done for forward
thinking clients.
</p>
</div>
</div>
<div className="row m-0">
<OwlCarousel
className="works-slides owl-carousel owl-theme"
{...slideOptions}
>
<div className="item">
<div className="col-lg-12">
<Link href="/vonza">
<div className="single-works">
<img
src={require("../../static/images/home/vonza1.png")}
alt="image"
/>
<div className="works-content">
<h3>Vonza</h3>
<p>
Vonza is the ultimate platform to build online courses,
sell products, offer services, construct sales funnels,
schedule appointments, launch email marketing campaigns
and develop amazing websites.
</p>
</div>
</div>
</Link>
</div>
</div>
<div className="item">
<div className="col-lg-12">
<Link href="/fotisto">
<div className="single-works">
<img
src={require("../../static/images/home/fotisto1.png")}
alt="image"
/>
<div className="works-content">
<h3>Fotisto</h3>
<p>
Fotisto is a marketplace that uses AI and Cloud-based
tools to bridge clients with
photographers/videographers.
</p>
</div>
</div>
</Link>
</div>
</div>
<div className="item">
<div className="col-lg-12">
<Link href="/swatrader">
<div className="single-works">
<img
src={require("../../static/images/home/furniture.png")}
alt="image"
/>
<div className="works-content">
<h3>SWA Trader</h3>
<p>
SWA Trader is one stop online shopping store. Having all
kinds of products from clothing and apparel to
electronics and mobile phones.
</p>
</div>
</div>
</Link>
</div>
</div>
<div className="item">
<div className="col-lg-12">
<Link href="/rapidsolution">
<div className="single-works">
<img
src={require("../../static/images/home/rapid1.png")}
alt="image"
/>
<div className="works-content">
<h3>Rapid Solution</h3>
<p>
Rapid Solution is the first laptop repair service in
Lahore to provide all sort of laptop repair solutions at
your doorstep.
</p>
</div>
</div>
</Link>
</div>
</div>
</OwlCarousel>
</div>
</section>
);
}
}
export default RecentWork;
<file_sep>import React from "react";
import * as Icon from "react-feather";
const BoxArea = (props) => {
return (
<section className="boxes-area">
<div className="container">
<div className="row">
<div className="col-lg-3 col-md-6">
<div className="single-box">
<div className="icon">
<Icon.TrendingUp />
</div>
<h3>Business Strategy</h3>
<p>
We provide latest business specific strategies, identifying
product strengths, adjusting pricing, acquiring new business.
</p>
</div>
</div>
<div className="col-lg-3 col-md-6">
<div className="single-box bg-f78acb">
<div className="icon">
<Icon.Monitor />
</div>
<h3>Engineering monitoring</h3>
<p>
performance evaluation and close watch on developing project so
that project will be in right shape and gives best desired
performance.
</p>
</div>
</div>
<div className="col-lg-3 col-md-6">
<div className="single-box bg-c679e3">
<div className="icon">
<Icon.Settings />
</div>
<h3>Maintenance</h3>
<p>
We assure our customers for satisfactory service and result.
During maintenance we edit, revise, change and bring new content
to the website.
</p>
</div>
</div>
<div className="col-lg-3 col-md-6">
<div className="single-box bg-eb6b3d">
<div className="icon">
<Icon.Pocket />
</div>
<h3>Quality Assurance</h3>
<p>
{" "}
We conduct thorough and rigorous quality checks on all of our
projects to ensure you're getting what you expect from us.
</p>
</div>
</div>
</div>
</div>
</section>
);
};
export default BoxArea;
<file_sep>import React, { Component } from 'react';
import Link from 'next/link';
class MainBanner extends Component {
render() {
return (
<div className="agency-main-banner">
<div className="container-fluid">
<div className="row align-items-center">
<div className="col-lg-6 col-md-12">
<div className="agency-banner-content">
<span className="sub-title">We are creative</span>
<h1>Digital Agency</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore.</p>
<Link href="#">
<a className="btn btn-secondary">Get Started</a>
</Link>
</div>
</div>
<div className="col-lg-6 col-md-12">
<div className="agency-banner-image">
<img src={require("../../static/images/agency-image/agency-banner-img.jpg")} alt="image" />
</div>
</div>
</div>
</div>
{/* Shape Images */}
<div className="shape2 rotateme">
<img src={require("../../static/images/shape2.svg")} alt="shape" />
</div>
<div className="shape8 rotateme">
<img src={require("../../static/images/shape2.svg")} alt="shape" />
</div>
<div className="shape3">
<img src={require("../../static/images/shape3.svg")} alt="shape" />
</div>
<div className="shape4">
<img src={require("../../static/images/shape4.svg")} alt="shape" />
</div>
</div>
);
}
}
export default MainBanner;<file_sep>import React, { Component } from "react";
import * as Icons from "react-feather";
class Features extends Component {
render() {
return (
<section className="hosting-features-area ptb-80 bg-f9f6f6">
<div className="container">
<div className="section-title">
<h2>Our Features</h2>
<div className="bar"></div>
<p>
Sharing our expertise and passion to build solutions that empower
your business
</p>
</div>
<div className="row">
<div className="col-lg-4 col-md-6">
<div className="single-hosting-features">
<div className="icon">
<Icons.Settings />
</div>
<h3>Incredible Infrastructure</h3>
<p>
{" "}
Our team of experienced professionals and proven methodologies
to offer purpose fit infrastructure solutions and deliverables
to meet specific business needs.
</p>
</div>
</div>
<div className="col-lg-4 col-md-6">
<div className="single-hosting-features">
<div className="icon bg-c679e3">
<Icons.TrendingUp />
</div>
<h3>Software Consultancy</h3>
<p>
Consulting with you for a period of time to understand your
business, reviewing your current technology and giving you
recommendation for improvement
</p>
</div>
</div>
<div className="col-lg-4 col-md-6">
<div className="single-hosting-features">
<div className="icon">
<Icons.BarChart2 />
</div>
<h3>Business Analysis</h3>
<p>
{" "}
We always talk to our customers to understand their needs. Our
team can analyze your project's functionality, business logics
& software architecture
</p>
</div>
</div>
<div className="col-lg-4 col-md-6">
<div className="single-hosting-features">
<div className="icon bg-c679e3">
<Icons.Cpu />
</div>
<h3>Dependability</h3>
<p>
We endeavor to always deliver what we promise you, to meet
every deadline, and to communicate proactively
</p>
<br />
</div>
</div>
<div className="col-lg-4 col-md-6">
<div className="single-hosting-features">
<div className="icon">
<Icons.Activity />
</div>
<h3>Empathy</h3>
<p>
We put ourselves in the customers’ shoes to visualize the
world from their perspective, this allows us to create a
product that meets their needs and expectations.
</p>
</div>
</div>
<div className="col-lg-4 col-md-6">
<div className="single-hosting-features">
<div className="icon bg-c679e3">
<Icons.Anchor />
</div>
<h3>Creativity</h3>
<p>
We encourage out-of-the-box thinking. Our teammates
collaborate, throw ideas around, speak with one another, and
clients to get those creative juices flowing.
</p>
</div>
</div>
</div>
</div>
</section>
);
}
}
export default Features;
<file_sep>import React, { Component } from "react";
import Header from "../components/hashcraft/Header";
import Footer from "../components/hashcraft/Footer";
import FaqContent from "../components/hashcraft/ContentBody";
import WhyChoose from "../components/hashcraft/WhyChoose";
import PageTitle from "../components/hashcraft/PageTitle";
class ServiceDetails extends Component {
render() {
return (
<React.Fragment>
<Header />
<PageTitle title='Dedicated Team' />
<section className="services-details-area ptb-80">
<div className="container">
<div className="row ">
<div className="col-lg-6 services-details">
<div className="services-details-desc">
<h3>
Software experts who work exactly where, when, and how you
need them most
</h3>
<p>
For those of our customers desiring complete control of
every aspect of the development process, <b>Hashcrafts</b>{" "}
offers the Dedicated Software Development Team service.
</p>
<p>
Instead of hiring a recruiting agency and spending extra
time and money, cut out the middle man and get immediate
access to expert developers with Hashcrafts.
</p>
<p>
We use a rigorous hiring and training system to ensure that
our engineers are some of the best in the industry. Every
Hashcrafts engineer has expertise with at least two
different technology stacks and versatile development
experience to meet your unique business needs.We offers
fair, transparent pricing at every stage of your project.
And if your business needs change, our Dedicated Development
teams are trained to adjust their performance.
</p>
<p>
we've cultivated a unique company culture that's focused on
customers. All of our employees share common passion for
helping your business thrive by delivering high-quality
software. When you hire a Hashcrafts team, you're gaining a
true technology partner.
</p>
<a className="btn btn-primary" href="#proposal">
Request a proposal
</a>
</div>
</div>
<div className="col-lg-6 services-details-image">
<img
src={require("../static/images/home/dedicatedteam.jpg")}
className="wow fadeInUp"
alt="image"
/>
</div>
</div>
</div>
</section>
<WhyChoose />
<FaqContent />
<Footer />
</React.Fragment>
);
}
}
export default ServiceDetails;
<file_sep>import React, { Component } from 'react';
import Link from 'next/link';
class AboutArea extends Component {
render() {
return (
<section className="agency-about-area">
<div className="container-fluid">
<div className="row align-items-center">
<div className="col-lg-6 col-md-12">
<div className="agency-about-img">
<img src={require("../../static/images/agency-image/agency-about-img.jpg")} alt="image" />
</div>
</div>
<div className="col-lg-6 col-md-12">
<div className="agency-about-content">
<span className="sub-title">About Us</span>
<h2>Engaging New Audiences Through Smart Approach</h2>
<div className="bar"></div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
<p>Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc.Donec vitae sapien ut libero venenatis faucibus tempus.</p>
<Link href="#">
<a className="btn btn-secondary">Discover More</a>
</Link>
</div>
</div>
</div>
</div>
{/* Shape Images */}
<div className="shape2 rotateme">
<img src={require("../../static/images/shape2.svg")} alt="shape" />
</div>
<div className="shape3">
<img src={require("../../static/images/shape3.svg")} alt="shape" />
</div>
<div className="shape6 rotateme">
<img src={require("../../static/images/shape4.svg")} alt="shape" />
</div>
<div className="shape7">
<img src={require("../../static/images/shape4.svg")} alt="shape" />
</div>
<div className="shape8 rotateme">
<img src={require("../../static/images/shape2.svg")} alt="shape" />
</div>
<div className="shape10">
<img src={require("../../static/images/agency-image/agency-shape2.png")} alt="image" />
</div>
</section>
);
}
}
export default AboutArea;<file_sep>import React from "react";
import Link from "next/link";
import * as Icon from "react-feather";
import OwlCarousel from "react-owl-carousel3";
const slideOptions = {
items: 4,
loop: true,
nav: false,
autoplay: true,
dots: false,
responsive: {
0: {
items: 1,
},
768: {
items: 2,
},
1200: {
items: 3,
},
1500: {
items: 4,
},
},
};
class RecentWork extends React.Component {
render() {
return (
<section className="works-area ptb-80 bg-f7fafd">
<div className="container">
<div className="section-title">
<h2>Our Recent Works</h2>
<div className="bar"></div>
<p>
Some highlights of our favorite projects we've done for forward
thinking clients.
</p>
</div>
</div>
<div className="row m-0">
<OwlCarousel
className="works-slides owl-carousel owl-theme"
{...slideOptions}
>
<div className="item">
<div className="col-lg-12">
<div className="single-works">
<img
src={require("../../static/images/works-image/works-image1.jpg")}
alt="image"
/>
<Link href="#">
<a className="icon">
<Icon.Settings />
</a>
</Link>
<div className="works-content">
<h3>
<Link href="#">
<a>Incredible infrastructure</a>
</Link>
</h3>
<p>
Lorem ipsum dolor amet, adipiscing, sed do eiusmod tempor
incididunt ut labore dolore magna aliqua.
</p>
</div>
</div>
</div>
</div>
<div className="item">
<div className="col-lg-12">
<div className="single-works">
<img
src={require("../../static/images/works-image/works-image2.jpg")}
alt="image"
/>
<Link href="#">
<a className="icon">
<Icon.Settings />
</a>
</Link>
<div className="works-content">
<h3>
<Link href="#">
<a>Incredible infrastructure</a>
</Link>
</h3>
<p>
Lorem ipsum dolor amet, adipiscing, sed do eiusmod tempor
incididunt ut labore dolore magna aliqua.
</p>
</div>
</div>
</div>
</div>
<div className="item">
<div className="col-lg-12">
<div className="single-works">
<img
src={require("../../static/images/works-image/works-image3.jpg")}
alt="image"
/>
<Link href="#">
<a className="icon">
<Icon.Settings />
</a>
</Link>
<div className="works-content">
<h3>
<Link href="#">
<a>Incredible infrastructure</a>
</Link>
</h3>
<p>
Lorem ipsum dolor amet, adipiscing, sed do eiusmod tempor
incididunt ut labore dolore magna aliqua.
</p>
</div>
</div>
</div>
</div>
<div className="item">
<div className="col-lg-12">
<div className="single-works">
<img
src={require("../../static/images/works-image/works-image4.jpg")}
alt="image"
/>
<Link href="#">
<a className="icon">
<Icon.Settings />
</a>
</Link>
<div className="works-content">
<h3>
<Link href="#">
<a>Incredible infrastructure</a>
</Link>
</h3>
<p>
Lorem ipsum dolor amet, adipiscing, sed do eiusmod tempor
incididunt ut labore dolore magna aliqua.
</p>
</div>
</div>
</div>
</div>
<div className="item">
<div className="col-lg-12">
<div className="single-works">
<img
src={require("../../static/images/works-image/works-image5.jpg")}
alt="image"
/>
<Link href="#">
<a className="icon">
<Icon.Settings />
</a>
</Link>
<div className="works-content">
<h3>
<Link href="#">
<a>Incredible infrastructure</a>
</Link>
</h3>
<p>
Lorem ipsum dolor amet, adipiscing, sed do eiusmod tempor
incididunt ut labore dolore magna aliqua.
</p>
</div>
</div>
</div>
</div>
</OwlCarousel>
</div>
</section>
);
}
}
export default RecentWork;
| ba028ee8cea4341e12098b386a563f5384a0c309 | [
"JavaScript",
"Markdown"
] | 40 | JavaScript | hamzaasmat/hashcrafts | 9f1c03a40e6c54f91ce5295aea918bdff09e7d74 | d0652fb46a983b5bc209c260cbcf79600a67c4ce | |
refs/heads/main | <file_sep>import React from 'react';
import renderer from 'react-test-renderer';
import { fromJS } from 'immutable';
import { App } from '../App';
import Plot from 'react-plotly.js';
// How to test React components developed using React-Plotly
// https://github.com/plotly/react-plotly.js/issues/176
describe.skip('components', function() {
describe('<App />', function() {
it('renders correctly', function() {
var tree = renderer.create(<App redux={fromJS({})} />).toJSON();
expect(tree).toMatchSnapshot();
});
});
});
<file_sep># redux-refresher
Redux refresher.
<file_sep>import React from 'react';
import './App.css';
import { connect } from 'react-redux';
import Plot from 'react-plotly.js';
import { changeLocation, setSelectedDate, setSelectedTemp, fetchData} from './actions';
//dbe<KEY>
// ${API_KEY}
const API_KEY = process.env.REACT_APP_WEATHER_KEY;
export class App extends React.Component {
shouldComponentUpdate(nextProps) {
const xDataChanged = !this.props.xData.equals(nextProps.xData);
const yDataChanged = !this.props.yData.equals(nextProps.yData);
return xDataChanged || yDataChanged;
}
fetchData = (evt) => {
evt.preventDefault();
let location = encodeURIComponent(this.props.redux.get('location'));
let urlPref = 'https://api.openweathermap.org/data/2.5/forecast?q=';
let urlSuff = `&APPID=${API_KEY}&units=metric`;
let url = urlPref + location + urlSuff;
this.props.dispatch(fetchData(url));
};
onPlotClick = (data) => {
if(data.points) {
let number = data.points[0].pointNumber;
this.props.dispatch(setSelectedDate(this.props.redux.getIn(['dates', number])));
this.props.dispatch(setSelectedTemp(this.props.redux.getIn(['temps', number])));
}
console.log(data);
};
// TO DO: look into onUpdate callback. Possibly can be used to control rerenders
changeLocation = (evt) => {
this.props.dispatch(changeLocation(evt.target.value));
};
render() {
let currTemp = 'Not loaded yet.';
if(this.props.redux.getIn(['data', 'list'])) {
currTemp = this.props.redux.getIn(['data', 'list', '0', 'main', 'temp']);
}
return (
<div style={{margin: '0 auto', textAlign: 'center'}}>
<h1>Weather v1.0</h1>
<form onSubmit={this.fetchData}>
<label htmlFor="usrLocation">
I want to know the weather for
<input
placeholder={"City, Country"}
type="text"
id="usrLocation"
value={this.props.redux.get('location')}
onChange={this.changeLocation}
/>
</label>
</form>
{(this.props.redux.get('data') && this.props.redux.getIn(['data', 'list'])) ? (
<div className="wrapper">
{ (this.props.redux.get('selected') && this.props.redux.getIn(['selected', 'temp'])) ?
<div className="temp-wrapper">
<span className="temp-date">
<p>The temperatures on { (this.props.redux.get('selected') && this.props.redux.getIn(['selected', 'temp'])) ? this.props.redux.getIn(['selected', 'date']) : '' }</p>
</span>
</div>
:
<div className="temp-wrapper">
<p>The current temperature is <span className="temp">{ (this.props.redux.get('selected') && this.props.redux.getIn(['selected', 'temp'])) ? this.props.redux.getIn(['selected', 'temp']) : currTemp }
<span className="temp-symbol">°C!</span></span>
</p>
</div>
}
<h2>Forecast</h2>
<Plot
data={[
{
x: this.props.redux.get('dates'),
y: this.props.redux.get('temps'),
type: 'scatter',
}
]}
layout={{margin: {
t: 0, r: 0, l: 30
},
xaxis: {
gridcolor: 'transparent'
}}}
displayModeBar={false}
onClick={this.onPlotClick}
/>
</div>
)
: null}
</div>
);
}
}
function mapStateToProps(state) {
return {
redux: state
};
}
export default connect(mapStateToProps)(App);
| 8caa67ad74abf27c3f8df65fefc47fbb6a9e0151 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | spialelo/redux-refresher | 8328fb65eeddb6308447a32e864bc3d3b6af5a3b | 47c0f140a95b5b9d7d49579f3773545b26d708ff | |
refs/heads/main | <repo_name>RoniLandau/VimeoQA<file_sep>/Test Suites/UserTestSuite/VimeoQA.ts
<?xml version="1.0" encoding="UTF-8"?>
<TestSuiteEntity>
<description></description>
<name>VimeoQA</name>
<tag></tag>
<isRerun>false</isRerun>
<mailRecipient></mailRecipient>
<numberOfRerun>0</numberOfRerun>
<pageLoadTimeout>30</pageLoadTimeout>
<pageLoadTimeoutDefault>true</pageLoadTimeoutDefault>
<rerunFailedTestCasesOnly>false</rerunFailedTestCasesOnly>
<rerunImmediately>false</rerunImmediately>
<testSuiteGuid>641fffd5-9770-475d-a162-3278d718d992</testSuiteGuid>
<testCaseLink>
<guid>eaad6f8e-7d5d-4d73-a386-845219d429a6</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/User/UserActions</testCaseId>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>4a151d33-4ea9-4b53-9e9b-ada2906140fa</variableId>
</variableLink>
</testCaseLink>
<testCaseLink>
<guid>9a532158-f79a-4f8d-8507-00b69fbff4ed</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/commentCheck/commentVerify</testCaseId>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>b58bbf1d-1b49-420a-89b7-dc9c84824dca</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>4076c266-7e9a-4371-98fa-a830603ba951</variableId>
</variableLink>
</testCaseLink>
<testCaseLink>
<guid>ec5de8fa-d82b-4a4a-a94a-6a43fd1f5be8</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/LikesViews/LikeViews</testCaseId>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>9b6c0da3-41fc-4fb8-8cc0-b57f87e943a0</variableId>
</variableLink>
</testCaseLink>
</TestSuiteEntity>
<file_sep>/README.md
# VimeoQA
Hello,
Please read carefully.
Description:
This project includes 3 Test Cases on Vimeo website.
The Cases: (explaining the main tests)
1. UserActions - Connect Vimeo Api, Login as "<NAME>" and comment on a specific video. Verify the status code of the call.
2. commentVerify - Using WebUI(simulate UI actions) ,Enter Vimeo website, login to "<NAME>" ,navigate to the specific video and verify the text of the comment.
3. LikesViews - Using WebUI , navigate to another video, store the number of likes and views. Verify that the text of the numbers is exist on the page.
Notice:
On every test case there are several test steps, almost on every step there is a simple validation that I didn't mention here but it well documented inside the script.
How to run the tests?
Must install:
Katalon Studio: https://www.katalon.com/download/
Git: https://git-scm.com/download/win
Run the Tests:
Open Katalon Studio.
Inside Katalon Studio:
1. Clone the project from git: on the left you will see "clone git project" press on it and enter on the url "https://github.com/RoniLandau/VimeoQA.git" - no need to authenticate.
2. You may need to update chrome web broswer - press "tools"-> "update web browsers" -> "chrome"
3. Search "VimeoQA" in "TextExplorer" (from the left), it will find you Test Suite with this name, open it.
4. Press the green "Play" button on the upper toolbar (of the right-side of the window). Next to the button there is a small arrow you can choose to run on different browsers.
5. You can see at the bottom the test results. You can see a report on the "reports" folder (on the left-side).
Extras:
1. Changing the specific video you're commenting on:
Open "profiles"-> "default" , change the global variable "video_id" to the your specific video id (you can find it easily at the end of the url of the specific video)
2. Changing the specific video you're checking the likes and views:
The same as before but change the global variable "video_id2".
3. The current comment is "Awesome! Thank you." , if you want to change it: "Object Repository"-> UserAPI -> vimeoComment , enter "HTTP body" tab and change there the text.
| c8f45f26304e3045c5ecf392ce89afc9ef78308b | [
"Markdown",
"TypeScript"
] | 2 | TypeScript | RoniLandau/VimeoQA | 5c17248cc9b4de8754ecaad4c24587393be49d3b | d1e69835a0b250e11fa8239848d5734164888dd0 | |
refs/heads/master | <repo_name>BartoszMakowski/put-various-exercises<file_sep>/mwp-arduino-dht11/termometer.ino
#include "DHT.h"
#define DHTTYPE DHT11
const int LED1 = 8;
const int LED2 = 9;
const int LED3 = 10;
const int BEEP = 11;
const int BUTTON = 7;
const int DHT_DATA = 2;
int F;
float humidity, temp;
bool beep_status;
DHT dht(DHT_DATA, DHTTYPE);
void setup() {
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
pinMode(BEEP, OUTPUT);
digitalWrite(LED1, LOW);
digitalWrite(LED2, LOW);
digitalWrite(LED3, LOW);
digitalWrite(BEEP, LOW);
pinMode(BUTTON, INPUT);
F=0;
beep_status=0;
dht.begin();
Serial.begin(9600);
}
void loop() {
if (F==0){ //
if (digitalRead(BUTTON)){ // PRZYCISK - ?
digitalWrite(LED1, HIGH); // LED1 - ON
F = 1;
}
}
if (F==1){
humidity = dht.readHumidity(); // mierz_wilgotnosc()
Serial.println("\n");
Serial.println(humidity);
if (humidity >=20 and humidity <= 95){ // HUMIDITY_OK ?
digitalWrite(LED2, HIGH); // LED2 - ON
F = 2;
}
delay(250);
}
if (F==2){
temp = dht.readTemperature(); // mierz_temperature()
if (temp >=0 and temp <= 50){ // TEMP_OK ?
digitalWrite(LED3, HIGH); // LED3 - ON
F = 3;
}
delay(250);
}
if (F==3){
delay(300);
beep_status = !beep_status;
digitalWrite(BEEP, beep_status); // BEEP - ON->OFF/OFF->ON
if (!beep_status) {
F = 4;
}
delay(250);
}
if (F==4){
Serial.write("Temperatura: "); // wypisywanie pomiarow
Serial.print(temp);
Serial.write("Wilgotnosc: ");
Serial.print(humidity);
digitalWrite(LED1, LOW); // LED1 - OFF
digitalWrite(LED2, LOW); // LED2 - OFF
digitalWrite(LED3, LOW); // LED3 - OFF
F = 0;
delay(250);
}
Serial.write("\nAktualny etap: "); // dane diagnostyczne
Serial.print(F);
delay(500);
}
| 97f7bf7e0ab730151883596771970e4c960f5037 | [
"C++"
] | 1 | C++ | BartoszMakowski/put-various-exercises | 9cfa5fe4625622a3568f5a39d2d45d3ebfedaced | 3134235c93428c6b9bff9d473b4675ffe7678d6e | |
refs/heads/master | <repo_name>binwick/angularjs-learning<file_sep>/code/041-jquery/app/index.js
var app = angular.module('app', []);
app.controller('firstController', ['$scope', '$filter', '$location', '$anchorScroll', function ($scope, $filter, $location, $anchorScroll) {
$('.multiple_upldprev:last').each(function () {
// alert(1);
});
$scope.color = {};
$scope.color.name = 'x';
var data = [{id: '124', name: 'ttt', MeasureDate: "2015-04-05T18:46:38"},
{id: '589', name: 'mmm', MeasureDate: "2015-05-05T18:46:38"},
{id: '45', name: 'yyy', MeasureDate: "2016-01-05T18:46:38"},
{id: '567', name: 'eee', MeasureDate: "2016-05-05T18:46:38"}];
var sorted = data.sort(function (a, b) {
return Date.parse(b.MeasureDate) - Date.parse(a.MeasureDate);
});
$('li').sort(function (a, b) {
var aDate = $(a).find('.itemDate').text();
var bDate = $(b).find('.itemDate').text();
// return Date.parse(aDate) - Date.parse(bDate);
return new Date(aDate).getTime() - new Date(bDate).getTime();
}).appendTo('ul');
console.log(sorted);
$scope.items = {
1: {
"John": 123,
"Doe": 234
},
2: {
"John": 456,
"Doe": 345
}
};
// $("#btn_click").attr('disabled', true);
$scope.test = function () {
var tmp = JSON.jsonToString($scope.item);
console.log(tmp);
return tmp;
}
var jsonToString=typeof JSON !="undefined"? JSON.stringify :function(obj){
var arr =[];
$.each(obj,function(key, val){
var next = key +": ";
next += $.isPlainObject(val)? jsonToString(val): val;
arr.push( next );
});
return"{ "+ arr.join(", ")+" }";
};
}]);<file_sep>/code/035-Cookie/app/index.js
angular.module('myApp', ['ngCookies'])
.filter('cityFilter', function () {
return function (data, parent) {
var filterData = [];
angular.forEach(data, function (obj) {
if (obj.parent === parent) {
filterData.push(obj);
}
})
return filterData;
}
})
.directive('even', function () {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ngModelController) {
ngModelController.$parsers.push(function (viewValue) {
if (viewValue % 2 === 0) {
ngModelController.$setValidity('even', true);
} else {
ngModelController.$setValidity('even', false);
}
return viewValue;
});
// ngModelController.$formatters.push(function(modelValue){
// return modelValue + 'kittencup';
// })
}
};
})
.directive('customTextArea', function () {
return {
restrict: 'E',
template: '<div contenteditable="true"></div>',
replace: true,
require: 'ngModel',
link: function (scope, elm, attrs, ngModelController) {
// view->model
elm.on('keyup', function () {
scope.$apply(function () {
ngModelController.$setViewValue(elm.html());
});
})
ngModelController.$render = function () {
elm.html(ngModelController.$viewValue);
}
}
};
})
.controller('firstController', ['$scope', '$cookies', '$cookieStore', function ($scope, $cookies, $cookieStore) {
// $cookieStore.put("name", "my name");
// $cookieStore.get("name") == "my name";
// $cookieStore.remove("name");
// $cookieStore.put("person", {
// name: "my name",
// age: 18
// });
//
// $cookieStore.put('person', {
// name: "<NAME>",
// age: 23
// });
// 设置带参数的cookie
var now = new Date(),
expireDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes() + 1, now.getSeconds());
// expireDate.setDate(expireDate.getDate() + 1);
console.log(expireDate.toUTCString());
$cookies.putObject('person', {
name: "new new name",
age: 24
}, {
'expires': expireDate
});
$scope.person = $cookieStore.get("person");
console.log($scope.person);
}]);
<file_sep>/code/029-自定义指令 controller && controllAs属性/app/index.js
angular.module('myApp', [])
.directive('bookList', function () {
return {
restrict: 'ECAM',
controller: ['$scope', function ($scope) {
$scope.books = [
{
name: 'php'
}, {
name: 'javascript'
}, {
name: 'java'
}
];
/**
* 如果这里写$scope.addBook
* 那么调用的时候用scope.addBook
*/
$scope.addBook = function () {
console.log('scope')
};
/**
* 如果用this.addBook
* 调用的时候使用bookListController.addBook
*/
this.addBook = function () {
// ...
console.log('this')
};
}],
controllerAs: 'bookListController',
template: '<ul><li ng-repeat="book in books">{{book.name}}</li></ul>',
replace: true,
link: function (scope, element, attrs, bookListController) {
// 绑定事件
element.on('click', bookListController.addBook)
}
}
})
.controller('firstController', ['$scope', function ($scope) {
// console.log($scope);
}]);<file_sep>/code/002/app/index.js
var app = angular.module('app', ['ng-sortable']);
app.controller('firstController', ['$scope', '$filter', function ($scope, $filter) {
$scope.items = ['zhangSan', 'liSi', 'wangWu'];
$scope.foo = ['foo 1', 'foo 2'];
$scope.bar = ['bar 1', 'bar 2'];
$scope.barConfig1 = {
group: 'foobar',
animation: 150,
//onSort: function (evt) {
// console.log('onSort:', evt);
// console.log('items:', $scope.items);
// console.log('foo:', $scope.foo);
//},
//// Element is removed from the list into another list
onRemove: function (evt) {
// same properties as onUpdate
console.log('onRemove:', evt);
},
onAdd: function (evt) {
console.log('onAdd', evt);
},
//
//// Attempt to drag a filtered element
//onFilter: function (/**Event*/evt) {
// var itemEl = evt.item; // HTMLElement receiving the `mousedown|tapstart` event.
// console.log('onFilter:', itemEl);
//},
// Event when you move an item in the list or between lists
//onMove: function (/**Event*/evt) {
// // Example: http://jsbin.com/tuyafe/1/edit?js,output
// //console.log(evt.dragged); // dragged HTMLElement
// //console.log(evt.draggedRect); // TextRectangle {left, top, right и bottom}
// //console.log(evt.related); // HTMLElement on which have guided
// //console.log(evt.relatedRect); // TextRectangle
// // return false; — for cancel
// console.log('onMove:', evt)
//}
};
$scope.barConfig2 = {
group: 'foobar',
animation: 150,
onRemove: function (evt) {
// same properties as onUpdate
console.log('onRemove:', evt);
},
onAdd: function (evt) {
console.log('onAdd', evt);
},
};
}]);<file_sep>/code/001/app/index.js
var app = angular.module('app', []);
//angular-directive
app // app 模块
.directive('bsDatepicker', function ($filter) {
return {
restrict: 'A',
scope: {
date: "=ngModel"
},
link: function (scope, element, attrs) {
element.parent().datetimepicker({
locale: 'zh-CN',
format: 'YYYY-MM-DD HH:mm:ss',
sideBySide: false,
showClear: false
});
console.log(scope.date);
var format = attrs['dateFormat'];
element.parent().on('dp.change', function (e) {
console.log(scope.date);
if (e.date) {
var newDate = new Date(e.date);
scope.$apply(function () {
scope.date = $filter('date')(newDate, format);
});
}
});
}
}
})
.controller('firstController', ['$scope', '$filter', function ($scope, $filter) {
$scope.date = 'zhangsan';
//angular.element('#datetimepicker1').datetimepicker({
// format: 'YYYY-MM-DD HH:mm:ss',
// locale: 'zh-CN'
//});
//angular.element('#datetimepicker1').on('dp.change', function (e) {
// $scope.$apply(function () {
// $scope.date = $filter('date')(new Date(e.date), 'yyyy-MM-dd HH:mm:ss')
// })
//});
}]);<file_sep>/code/038-$anchorScroll tooltip/app/index.js
var app = angular.module('app', []);
app.run(['$anchorScroll', function ($anchorScroll) {
$anchorScroll.yOffset = -50; // 总是滚动额外的50像素
}]);
app.controller('firstController', ['$scope', '$filter', '$location', '$anchorScroll', function ($scope, $filter, $location, $anchorScroll) {
$scope.gotoBottom = function () {
// 将location.hash的值设置为
// 你想要滚动到的元素的id
$location.hash('bottom');
// 调用 $anchorScroll()
$anchorScroll();
};
$scope.amount = 123456;
$scope.tooltipAmount = '';
var termAmounts = ['', '十', '百', '千', '万', '十万', '百万', '千万', '亿'];
var amount = $scope.amount.toString();
if (amount.lastIndexOf('.') != -1) {
$scope.tooltipAmount = termAmounts[amount.substr(0, amount.lastIndexOf('.')).length - 1];
} else {
$scope.tooltipAmount = termAmounts[amount.length - 1];
}
}]);<file_sep>/code/037-$timeout/app/index.js
//为我们的demo创建一个应用模块
var app = angular.module("Demo", []);
// 定义控制器
app.controller("DemoController", ['$scope', function ($scope) {
$scope.section = "happy";
//在toggle函数中改变section的值,以此在标记中显示/隐藏不同的部分
$scope.toggle = function () {
if ($scope.section === "happy") {
$scope.section = "sad";
} else {
$scope.section = "happy";
}
};
}
]);
//定义指令
app.directive("bnDirective", ['$timeout', function ($timeout) {
//将用户界面的事件绑定到$scope上
function link($scope, element, attributes) {
//当timeout被定义时,它返回一个promise对象
var timer = $timeout(function () {
console.log("Timeout executed", Date.now());
}, 2000);
//将resolve/reject处理函数绑定到timer promise上以确保我们的cancel方法能正常运行
timer.then(function () {
console.log("Timer resolved!", Date.now());
}, function () {
console.log("Timer rejected!", Date.now());
}
);
//当DOM元素从页面中被移除时,AngularJS将会在scope中触发$destory事件。这让我们可以有机会来cancel任何潜在的定时器
$scope.$on("$destroy", function (event) {
$timeout.cancel(timer);
}
);
}
//返回指令的配置
return ({
link: link,
scope: false
});
}]);
//定义指令
app.directive("bnDirectiveAlt", ['$interval', function ($interval) {
//将用户界面的事件绑定到$scope上
function link($scope, element, attributes) {
//当timeout被定义时,它返回一个promise对象
var timer = $interval(function () {
console.log("Interval executed", Date.now());
}, 10 * 1000);
//将resolve/reject处理函数绑定到timer promise上以确保我们的cancel方法能正常运行
timer.then(function () {
console.log("Timer resolved!", Date.now());
}, function () {
console.log("Timer rejected!", Date.now());
}
);
//当DOM元素从页面中被移除时,AngularJS将会在scope中触发$destory事件。这让我们可以有机会来cancel任何潜在的定时器
$scope.$on("$destroy", function (event) {
$interval.cancel(timer);
}
);
}
//返回指令的配置
return ({
link: link,
scope: false
});
}]);<file_sep>/code/028-自定义指令 compile && link属性/app/index.js
var i = 0;
var myApp = angular.module('myApp', [])
.directive('customTags', function () {
return {
restrict: 'ECAM',
template: '<div>{{user.name}}</div>',
replace: true,
compile: function (tElement, tAttrs, transclude) {
tElement.append(angular.element('<div>{{user.name}}{{user.count}}</div>'));
// 编译阶段...
console.log('customTags compile 编译阶段...');
return {
// 表示在编译阶段之后,指令连接到子元素之前运行
pre: function preLink(scope, iElement, iAttrs, controller) {
console.log('customTags preLink..')
},
// 表示在所有子元素指令都连接之后才运行
post: function postLink(scope, iElement, iAttrs, controller) {
iElement.on('click', function () {
scope.$apply(function () {
scope.user.name = 'click after';
scope.user.count = ++i;
// 进行一次 脏检查
});
})
console.log('customTags all child directive link..')
}
}
// 可以直接返回 postLink
// return postLink function(){
// console.log('compile return fun');
//}
},
// 此link表示的就是 postLink
link: function () {
// iElement.on('click',function(){
// scope.$apply(function(){
// scope.user.name = 'click after';
// scope.user.count = ++i;
// // 进行一次 脏检查
// });
// })
}
}
})
.directive('customTags2', function () {
return {
restrict: 'ECAM',
replace: true,
compile: function () {
// 编译阶段...
console.log('customTags2 compile 编译阶段...');
return {
// 表示在编译阶段之后,指令连接到子元素之前运行
pre: function preLink() {
console.log('customTags2 preLink..')
},
// 表示在所有子元素指令都连接之后才运行
post: function postLink() {
console.log('customTags2 all child directive link..')
}
}
}
}
})
.directive('customTags3', function () {
// return postLink;
return function () {
}
})
.controller('firstController', ['$scope', function ($scope) {
$scope.users = [
{
id: 10,
name: '张三'
},
{
id: 20,
name: '李四'
}
];
}]);<file_sep>/code/032-练习 自定义accordion指令/app/index.js
angular.module('myApp', [])
// 数据
.factory('Data', function () {
return [
{
title: 'no1',
content: 'no1-content'
},
{
title: 'no2',
content: 'no2-content'
},
{
title: 'no3',
content: 'no3-content'
}
];
})
// 控制器
.controller('firstController', ['$scope', 'Data', function ($scope, Data) {
$scope.data = Data;
}])
.directive('kittencupGroup', function () {
return {
restrict: 'E',
replace: true,
template: '<div class="panel-group" ng-transclude></div>',
transclude: true,
controllerAs: 'kittencupGroupContrller',
controller: function () {
this.groups = [];
this.closeOtherCollapse = function (nowScope) {
angular.forEach(this.groups, function (scope) {
if (scope !== nowScope) {
scope.isOpen = false;
}
})
}
}
}
})
.directive('kittencupCollapse', function () {
return {
restrict: 'E',
replace: true,
require: '^kittencupGroup',
templateUrl: 'app/tmp/kittencupCollapse.html',
scope: {
heading: '@'
},
transclude: true,
link: function (scope, element, attrs, kittencupGroupContrller) {
scope.isOpen = false;
scope.changeOpen = function () {
scope.isOpen = !scope.isOpen;
kittencupGroupContrller.closeOtherCollapse(scope);
};
// group 放所有的 scope
kittencupGroupContrller.groups.push(scope);
}
}
}); | 41facda0111aa12a6f0123e65f6049facfa01019 | [
"JavaScript"
] | 9 | JavaScript | binwick/angularjs-learning | 162583b2c59faee6c438dded2512d7b177dfeebb | ef2742716b59d9255858f2263f50127ce6419dd1 | |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
import tensorflow as tf
from utility import *
import os
import scipy.io as sio
import numpy as np
import math
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
config = tf.ConfigProto()
#config.gpu_options.per_process_gpu_memory_fraction = 0.9
#config.gpu_options.allow_growth = True
#session = tf.Session(config=config)
def file_name(file_dir, f):
L=[]
for root, dirs, files in os.walk(file_dir):
for file in files:
if os.path.splitext(file)[1] == f:
L.append(os.path.join(root, file))
return L
def cal_psnr(target, ref):
# assume RGB image
target_data = np.array(target, dtype=float)
ref_data = np.array(ref, dtype=float)
diff = ref_data - target_data
diff = diff.flatten('C')
rmse = math.sqrt(np.mean(diff ** 2.))
p = 20 * math.log10(255. / rmse)
return p
if __name__ == '__main__':
database = "Set14"
up = 2
root_path = './DRCN_checkpoint/'
with tf.Session(config=config) as sess:
LR_path = file_name("./" + database + "/LRX" + str(up), ".mat")
Gnd_path = file_name("./" + database + "/Gnd", ".mat")
start_model = 63
step = 1
model_num = 1
recusive = 16
#程序会从 start_model这个文件夹开始,按照step的步长,测试model_num个模型
#result.txt会存放测试的结果,包括每个图片的psnr和集合上的平均值
images = tf.placeholder(tf.float32, [1, None, None, 1], name='images')
pred, _, _ = DRCN(images, recusive)
#with open('result.txt','w') as f:#w这个参数会清空result文件,再写入;若要让内容不清空,则使用参数a
# f.write("******************************")
# f.write("\nwrite now!\n")
for model in range(1, 1+model_num):
p1 = 0.0
p2 = 0.0
check_point_path = root_path + str(start_model + step * (model-1)) + '/'
print('*'*30)
print('epoch : ' + str(start_model + step * (model-1)))
saver = tf.train.Saver()
ckpt = tf.train.get_checkpoint_state(checkpoint_dir=check_point_path)
saver.restore(sess, ckpt.model_checkpoint_path)
#with open('result.txt','a') as f:#设置文件对象
# f.write("\nepoch: %d\n" %(start_model + step * (model-1)))
for i in range(len(LR_path)):
bic = sio.loadmat(LR_path[i])['im_b']
gnd = sio.loadmat(Gnd_path[i])['im_gnd']
shape = bic.shape
img_bic = np.zeros((1, shape[0], shape[1], 1), dtype=float)
img_bic[0, :, :, 0] = bic*255
pred0 = sess.run([pred], feed_dict={images: img_bic})
output = pred0[0]
pre1 = output
pre1[pre1[:] > 255] = 255
pre1[pre1[:] < 0] = 0
img_h = pre1[0, :, :, 0]
img_h = np.round(img_h)
img_h2 = img_h[up:shape[0]-up , up:shape[1]-up]
bic1 = bic * 255
bic1[bic1[:] > 255] = 255
bic1[bic1[:] < 0] = 0
bic1 = np.round(bic1)
bic1 = bic1[up:shape[0]-up , up:shape[1]-up]
gnd1 = gnd * 255.
gnd1[gnd1[:] > 255] = 255
gnd1[gnd1[:] < 0] = 0
gnd1 = np.round(gnd1)
gnd1 = gnd1[up:shape[0]-up , up:shape[1]-up]
pp1 = cal_psnr(bic1, gnd1)
pp2 = cal_psnr(img_h2, gnd1)
print(str(i+1) + ". bicubic: " + str(pp1) + ", DRCN: "+str(pp2))
#with open('result.txt','a') as f:
# f.write("%d. bicubic: %s, srcnn: %s\n" %(i+1, str(pp1), str(pp1)))
p1 = p1 + pp1
p2 = p2 + pp2
print "bicubic psnr = " + str(p1/len(LR_path))
print "DRCN psnr = " + str(p2/len(LR_path))
#with open('result.txt','a') as f:
# f.write("bicubic psnr =%s\n" %(str(p1/len(LR_path))))
# f.write("srcnn psnr = %s\n" %(str(p2/len(LR_path))))<file_sep># -*- coding: utf-8 -*-
from utility import *
import sys
import time
import shutil
import os
import h5py
import numpy as np
import math
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
config = tf.ConfigProto()
#config.gpu_options.per_process_gpu_memory_fraction = 0.9
config.gpu_options.allow_growth = True
session = tf.Session(config=config)
def read_data(path):
with h5py.File(path, 'r') as hf:
data = np.array(hf.get('data'))
label = np.array(hf.get('label'))
train_data = np.transpose(data, (0, 2, 3, 1))
train_label = np.transpose(label, (0, 2, 3, 1))
print(train_data.shape)
print(train_label.shape)
return train_data, train_label
def tf_log10(x):
numerator = tf.log(x)
denominator = tf.log(tf.constant(10, dtype=numerator.dtype))
return numerator / denominator
def PSNR(y_true, y_pred):
max_pixel = 255.0
return 10.0 * tf_log10((max_pixel ** 2) / (tf.reduce_mean(tf.square(y_pred - y_true))))
def DRCN_train(train_data_file,test_data_file,model_save_path):
train_data, train_label = read_data(train_data_file)
test_data, test_label = read_data(test_data_file)
batch_size = 64
iterations = train_data.shape[0]//batch_size//2
#lr = 0.01
momentum_rate = 0.9
image_size = 41
label_size = 41
recusive = 16
is_load = True#是否加载现有模型进行再训练
per_epoch_save = 1
start_epoch = 0
alpha_init = 1.0
alpha_decay = 25
total_epoch = 55 + alpha_decay#这里是指还需要继续训练多少个epoch
beta = 0.0001
images = tf.placeholder(tf.float32, [None, image_size, image_size, 1], name='images')
labels = tf.placeholder(tf.float32, [None, label_size, label_size, 1], name='labels')
learning_rate = tf.placeholder(tf.float32)
alpha = tf.placeholder(tf.float32, shape=[], name="alpha")
pred, recusive_maps, l2_norm = DRCN(images, recusive)
loss1 = tf.reduce_mean(tf.square(labels - pred))
rec_loss = recusive * [None]
for i in range(0, recusive):
rec_loss[i] = tf.reduce_mean(tf.square(labels - recusive_maps[i]))
loss2 = tf.add_n(rec_loss)*(1.0/recusive)
if alpha == 0.0:
beta = 0.0
#这里参考了github上开源项目的设置,原文这里也没有交代清楚
loss = loss1*(1-alpha) + loss2*alpha + l2_norm*beta
psnr = PSNR(labels, pred)
optimizer = tf.train.AdamOptimizer(learning_rate, beta1=0.1, beta2=0.1)#.minimize(loss)#beta1=0.1, beta2=0.1
#train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
#train_step = tf.train.MomentumOptimizer(learning_rate, momentum_rate,use_nesterov=True).minimize(loss)
#前30没有梯度裁剪
grads, variables = zip(*optimizer.compute_gradients(loss))
grads, global_norm = tf.clip_by_global_norm(grads, 1.0 / learning_rate)
train_step = optimizer.apply_gradients(zip(grads, variables))
saver = tf.train.Saver()
with tf.Session(config=config) as sess:
sess.run(tf.global_variables_initializer())
if is_load:
start_epoch = 60
check_point_path = model_save_path + '/' + str(start_epoch) + '/'# 保存好模型的文件路径
ckpt = tf.train.get_checkpoint_state(checkpoint_dir=check_point_path)
saver.restore(sess, ckpt.model_checkpoint_path)
bar_length = 30
for ep in range(1+start_epoch, total_epoch+1):
input_alpha = alpha_init - (ep-1) * (1.0/alpha_decay)
input_alpha = max(0.0, input_alpha)
if ep <= 15 + alpha_decay:
lr = 0.001
elif ep <= 35 + alpha_decay:
lr = 0.0001
else:
lr = 0.00001
start_time = time.time()
pre_index = 0
train_loss = 0.0
train_psnr = 0.0
print("\nepoch %d/%d, lr = %2.5f, alpha = %2.5f:" % (ep, total_epoch, lr, input_alpha))
indices = np.random.permutation(len(train_data))#每次随机打乱数据
train_data = train_data[indices]
train_label = train_label[indices]
for it in range(1, iterations+1):
batch_x = train_data[pre_index:pre_index+batch_size]
batch_y = train_label[pre_index:pre_index+batch_size]
_, batch_loss, batch_psnr = sess.run(
[train_step, loss, psnr], feed_dict={images: batch_x, labels: batch_y,
learning_rate: lr, alpha: input_alpha})
train_loss += batch_loss
train_psnr += batch_psnr
pre_index += batch_size
if it == iterations:
train_loss /= iterations
train_psnr /= iterations
test_loss, test_psnr = sess.run([loss, psnr], feed_dict={images: test_data, labels: test_label,
alpha: input_alpha})
s1 = "\r%d/%d [%s%s] - batch_time = %.2fs - train_loss = %.5f - train_psnr = %.2f" % \
(it, iterations, ">"*(bar_length*it//iterations), "-"*(bar_length-bar_length*it//iterations),
(time.time()-start_time)/it, train_loss, train_psnr)#run_test()
sys.stdout.write(s1)
sys.stdout.flush()
print("\ncost_time: %ds, test_loss: %.5f, test_psnr: %.2f" %(int(time.time()-start_time), test_loss, test_psnr))
'''
这里输出的test_psnr并不是最终Set5的psnr,而是图像块的平均值
'''
else:
s1 = "\r%d/%d [%s%s] - batch_time = %.2fs - train_loss = %.5f - train_psnr = %.2f" % \
(it, iterations, ">"*(bar_length*it//iterations), "-"*(bar_length-bar_length*it//iterations),
(time.time()-start_time)/it, train_loss / it, train_psnr / it)#run_test()
sys.stdout.write(s1)
sys.stdout.flush()
if ep % per_epoch_save == 0:
path = model_save_path + '/save/' + str(ep) + '/'
save_model = saver.save(sess, path + 'DRCN_model')
new_path = model_save_path + '/' + str(ep) + '/'
shutil.move(path, new_path)
'''
模型首先是被保存在save下面的,直接保存的话,前面的epoch对应的文件夹会出现内部文件被删除的情况,原因不明;所以这里用shutil.move把模型所在的文件夹移动了一下
'''
print("\nModel saved in file: %s" % save_model)
path = './final_model/DRCN_model'
save_model = saver.save(sess, path)
print("\nModel saved in file: %s" % save_model)
def main():
train_file = 'train.h5'
test_file = 'test2.h5'
model_save_path = 'DRCN_checkpoint'
if os.path.exists(model_save_path) == False:
print('The ' + '"' + model_save_path + '"' + 'can not find! Create now!')
os.mkdir(model_save_path)
if os.path.exists(model_save_path + '/save') == False:
print('The ' + '"save' + '"' + ' can not find! Create now!')
os.mkdir(model_save_path+'/save')
DRCN_train(train_file, test_file, model_save_path)
if __name__ == '__main__':
main()<file_sep># -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
def weight_variable(shape, name):
weight = tf.get_variable(name, shape, initializer=tf.keras.initializers.he_normal(), dtype=tf.float32)
return weight
def bias_variable(shape, name):
bias = tf.get_variable(name, shape, initializer=tf.zeros_initializer(), dtype=tf.float32)
return bias
def relu(x):
return tf.nn.relu(x)
def lrelu(x, alpha=0.05):
return tf.nn.leaky_relu(x, alpha)
def conv2d(x, shape, name, stride=[1, 1, 1, 1], pad='SAME', act='lrelu', alpha=0.05, use_bias=True):
w_name = name + '_w'
b_name = name + '_b'
weight = weight_variable(shape, w_name)
y = tf.nn.conv2d(x, weight, strides=stride, padding=pad)
if use_bias is True:
bias = bias_variable(shape[3], b_name)
y = y + bias
if act == 'relu':
y = relu(y)
elif act == 'lrelu':
y = lrelu(y, alpha)
return y, weight
def DRCN(input_img, recusive_time):
ksize = 256#原文使用了256
temp, weight_conv1 = conv2d(input_img, [3, 3, 1, ksize], 'conv1', stride=[1, 1, 1, 1], pad='SAME', act='relu', use_bias=True)
temp, weight_conv2 = conv2d(temp, [3, 3, ksize, ksize], 'conv2', stride=[1, 1, 1, 1], pad='SAME', act='relu', use_bias=True)
weight_recursive = weight_variable(shape=[3, 3, ksize, ksize], name='weight_recursive')
bias_recursive = bias_variable(shape=[ksize], name='bias_recursive')
H = recusive_time * [None]
for i in range(recusive_time):
temp = tf.nn.conv2d(temp, weight_recursive, strides=[1, 1, 1, 1], padding='SAME')
temp = temp + bias_recursive
temp = tf.nn.relu(temp)
H[i] = temp
weight_reconstruction1 = weight_variable(shape=[3, 3, ksize, ksize], name='weight_reconstruction1')
bias_reconstruction1 = bias_variable(shape=[ksize], name='bias_reconstruction1')
weight_reconstruction2 = weight_variable(shape=[3, 3, ksize, 1], name='weight_reconstruction2')
bias_reconstruction2 = bias_variable(shape=[1], name='bias_reconstruction2')
W = tf.Variable(np.full(fill_value=1.0 / recusive_time, shape=[recusive_time], dtype=np.float32), name="LayerWeights")
W_sum = tf.reduce_sum(W)
output_list = recusive_time * [None]
for i in range(recusive_time):
temp = tf.nn.conv2d(H[i], weight_reconstruction1, strides=[1, 1, 1, 1], padding='SAME')
temp = temp + bias_reconstruction1
#temp = tf.nn.relu(temp)
#temp = tf.concat([temp, input_img], 3)
temp = tf.nn.conv2d(temp, weight_reconstruction2, strides=[1, 1, 1, 1], padding='SAME')
temp = temp + bias_reconstruction2
#temp = tf.nn.relu(temp)
H[i] = temp# + input_img
#这里怀疑原文的方法或者表述存在问题,
# 1.如果这里用了残差,效果很差 2.如果重建阶段使用relu也会很差(可以去除下面两个+input_img)
#由于原文没有公布训练程序,所以难以考证
output_list[i] = H[i]*W[i]/W_sum
H[i] = H[i] + input_img
output = tf.add_n(output_list)
output = output + input_img
l2_norm = tf.nn.l2_loss(weight_conv1) + tf.nn.l2_loss(weight_conv2) + tf.nn.l2_loss(weight_recursive) + \
tf.nn.l2_loss(weight_reconstruction1) + tf.nn.l2_loss(weight_reconstruction2)
return output, H, l2_norm<file_sep># DRCN_Tensorflow
Tensorflow implementation of "Deeply-Recursive Convolutional Network for Image Super-Resolution"
<br>python 2.7
<br>tensorflow 1.9.0
<br>The training set is '291'
Email: <EMAIL>
| 31b428b72a4c8a1d709b6508f57a89274a58896f | [
"Markdown",
"Python"
] | 4 | Python | nullhty/DRCN_Tensorflow | 9c9c0b7e305125eda01cc6db468f353a1173514f | ecabe6a8994321790c9268b0bd061ef707a7c15e | |
refs/heads/master | <file_sep>const Component = require('./component-files');
const fs = require('fs');
const YAML = require('yaml');
const path = require('path');
class Structure {
folder = "./src"
static isArray(obj) {
return obj.length !== undefined
}
constructor(configFile, folder) {
const file = fs.readFileSync(configFile, 'utf8')
this.structureConfig = YAML.parse(file);
this.folder = folder;
}
_getComponentsPaths(structure, currentPath = this.folder) {
let paths = [];
if (Structure.isArray(structure)) {
paths.push(...structure.map( item => path.join(currentPath, item) ));
} else {
Object.entries(structure).forEach( ([itemName, nextStructure]) => {
paths.push(...this._getComponentsPaths(nextStructure, path.join(currentPath, itemName)));
} )
}
return paths;
}
createComponents() {
const paths = this._getComponentsPaths(this.structureConfig);
paths.map(this.createComponentFiles);
}
createComponentFiles(path) {
fs.mkdirSync(path, {recursive: true});
const component = new Component(path);
component.extrude();
}
}
module.exports = Structure;
<file_sep># Create React Components
This package created to simplify React components structure creation in new React project.
### Warning
Don't use this module in your old React projects, module can cause damage.
You are free to use this in new React project.
### How to use it?
1. Create new React project. Read a [official CRA docs](https://github.com/facebook/create-react-app#creating-an-app) to know how to do this.
2. Create config with name `components.yml`. It can looks like:
```yaml
# components.yml
app: # it is the folder
components: # it is the folder
- App # it is the component
client:
Header:
components:
- Header
- Navbar
- NavbarMenu
shared:
components:
- Button
- Logo
```
3. Run `npx cr-components create-all` to parse and create components from a config.
Every component`s folder will be created with next files: _Component.jsx_, _Component.css_, _index.js_.
Example folder tree:
```
├───app
│ └───components
│ └───App
├───client
│ └───Header
│ └───components
│ ├───Header
│ ├───Navbar
│ └───NavbarMenu
└───shared
└───components
├───Button
└───Logo
```
### Advice
Run ```cr-components create-all -h``` to see more options.
##### To be continued...<file_sep>#!/usr/bin/env node
const {Command} = require('commander');
const Structure = require("./components-structure")
const program = new Command();
program
.version(require('./package.json').version)
.command('create-all')
.description('clone a repository into a newly created directory')
.option('-c, --config <config>', 'components config file', './components.yml')
.option('-f, --folder <folder>', 'output src folder', "./src")
.action((source) => {
const {config, folder} = source;
const structure = new Structure(config, folder);
structure.createComponents();
structure.createComponents();
});
program.parse(process.argv);
| 3cb9b9753b50ea52ae090df2e095fcfd26cf111c | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | leonidpodriz/create-react-components | 097397e6fbb9ea8717db99807825a892c631fbd0 | 5b8832f901d43d66814c9e5f9fa7f6f07795cfdf | |
refs/heads/main | <repo_name>ukun1708/UserInterface<file_sep>/Assets/Scripts/Scrolling.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Scrolling : MonoBehaviour
{
public GameObject scrollContent;
private Coroutine coroutine;
public void scrollVerticalPlus()
{
if (coroutine != null)
{
StopCoroutine(coroutine);
}
coroutine = StartCoroutine(ScrollingVerticalCor(1000f));
}
public void scrollVerticalMinus()
{
if (coroutine != null)
{
StopCoroutine(coroutine);
}
coroutine = StartCoroutine(ScrollingVerticalCor(-1000f));
}
IEnumerator ScrollingVerticalCor(float delta)
{
RectTransform rectTransform = scrollContent.GetComponent<RectTransform>();
float time = 0f;
float timer = 1f;
float targetHeight = rectTransform.anchoredPosition.y + delta;
if (targetHeight < 0f)
{
targetHeight = 0f;
}
if (targetHeight > rectTransform.sizeDelta.y)
{
targetHeight = rectTransform.sizeDelta.y;
}
while (time < timer)
{
time += Time.deltaTime;
rectTransform.anchoredPosition = new Vector2(0f, Mathf.Lerp(rectTransform.anchoredPosition.y, targetHeight, time));
yield return null;
}
}
}
<file_sep>/Assets/Scripts/Demo.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class Demo : MonoBehaviour
{
public ItemView button;
void Start()
{
ItemModel model = GameConfig.StartSer();
for (int i = 0; i < 100; i++)
{
ItemView view = Instantiate(button, transform);
view.model = model;
view.UpdateView();
}
}
}
<file_sep>/Assets/Scripts/ItemModel.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemModel
{
public string avatar;
public string countSubject;
public string playerName;
public string price;
public string productImage;
public string productName;
}
<file_sep>/Assets/Scripts/PopUp.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PopUp : MonoBehaviour
{
public GameObject popPage;
public void Pop()
{
popPage.SetActive(true);
}
public void ClosePop()
{
popPage.SetActive(false);
}
public void AppQuit()
{
Application.Quit();
}
}
<file_sep>/README.md
UserInterface
=============
Практика создания пользовотельского интерфейса под любые соотношения сторон экрана
<img src="Recorder/interface.gif" />
<file_sep>/Assets/Scripts/Clock.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class Clock : MonoBehaviour
{
TextMeshProUGUI textMesh;
float hours = 00f, minut = 00f, second = 00f;
void Start()
{
textMesh = GetComponent<TextMeshProUGUI>();
}
void Update()
{
textMesh.text = hours.ToString("F0") + ":" + minut.ToString("F0") + ":" + second.ToString("F0");
second += Time.deltaTime;
if (second > 59f)
{
minut += 1f;
second = 0f;
}
if (minut > 59f)
{
hours += 1f;
minut = 0f;
second = 0f;
}
if (hours > 23f)
{
hours = 0f;
minut = 0f;
second = 0f;
}
}
}
<file_sep>/Assets/Scripts/ItemView.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
public class ItemView : MonoBehaviour
{
public Image avatarImg;
public TextMeshProUGUI countSub;
public TextMeshProUGUI player_Name;
public TextMeshProUGUI price;
public Image productImg;
public TextMeshProUGUI productName;
public ItemModel model;
public void UpdateView()
{
productName.text = model.productName;
player_Name.text = model.playerName;
price.text = model.price;
countSub.text = model.countSubject;
StartCoroutine(LoadSpriteFromUrl(avatarImg, model.avatar));
var sp = Resources.Load<Sprite>(model.productImage);
productImg.sprite = sp;
}
IEnumerator LoadSpriteFromUrl(Image image, string url)
{
WWW www = new WWW(url);
yield return www;
image.sprite = Sprite.Create(www.texture, new Rect(0, 0, www.texture.width, www.texture.height), new Vector2(0, 0));
}
}
<file_sep>/Assets/Scripts/GameConfig.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameConfig : MonoBehaviour
{
public static ItemModel StartSer()
{
ItemModel model;
string path = Application.streamingAssetsPath + "/item_00.json";
UnityEngine.Networking.UnityWebRequest www = UnityEngine.Networking.UnityWebRequest.Get(path);
www.SendWebRequest();
while (!www.isDone)
{
}
string text = www.downloadHandler.text;
model = JsonUtility.FromJson<ItemModel>(text);
return model;
}
}
| a0f3891e53d749d9ba68fa37fd28fa07da9827de | [
"Markdown",
"C#"
] | 8 | C# | ukun1708/UserInterface | d2b251080bde80fd6bb886fae109dab5be1ec9ca | 1dc8ebfdf4d4f281d18562a94de71eb510b4175b | |
refs/heads/master | <file_sep>// Test away!
import React from 'react';
import * as rtl from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import Controls from './Controls';
afterEach(rtl.cleanup);
let wrapper, toggleLockButton, toggleCloseButton;
const mock = jest.fn();
beforeEach(() => {
wrapper = rtl.render(<Controls />)
})
describe('Control component', () => {
test('Matches the snapshot!', () => {
expect(wrapper.container).toMatchSnapshot();
})
it('Button toggle the closed state', () => {
const wrapper = rtl.render(<Controls locked={false} closed={false} toggleClosed={mock} />)
const toggleCloseButton = wrapper.queryByTestId('toggleCloseButton');
// expect(wrapper.queryByText(/open/i)).toBeInTheDocument();
rtl.fireEvent.click(toggleCloseButton)
expect(mock).toBeCalled()
expect(wrapper.queryByText(/open/i)).not.toBeInTheDocument();
expect(wrapper.queryByText(/closed/i)).toBeInTheDocument();
})
})
| a131d1ebc269ec2b7d9dfbbf0a29b44f07f181c2 | [
"JavaScript"
] | 1 | JavaScript | Funmi7/webtesting-iii-challenge | bc40577d439b20e9f1bb34fb9e080e2dc39f3813 | 409a3d22aa4e48d4102aa44f870896ce1d2ac40a | |
refs/heads/master | <repo_name>Rafael-Soares/ProjetoFinal<file_sep>/DesenvolvimentoBack/apps/institucional/migrations/0017_auto_20210411_2236.py
# Generated by Django 2.2.20 on 2021-04-12 01:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('institucional', '0016_auto_20210411_1949'),
]
operations = [
migrations.RemoveField(
model_name='quemsomos',
name='apresentacao',
),
migrations.RemoveField(
model_name='quemsomos',
name='imageQuemSomos',
),
migrations.RemoveField(
model_name='servicos',
name='imageServico',
),
migrations.AddField(
model_name='portifolio',
name='nome',
field=models.CharField(blank=True, max_length=50, verbose_name='Nome do aluno'),
),
migrations.AddField(
model_name='portifolio',
name='nota',
field=models.IntegerField(blank=True, default=0, verbose_name='Nota'),
),
migrations.AddField(
model_name='quemsomos',
name='oferecimento',
field=models.TextField(blank=True, verbose_name='O que oferecemos'),
),
migrations.AddField(
model_name='quemsomos',
name='oque_fazemos',
field=models.TextField(blank=True, verbose_name='O que fazemos'),
),
migrations.AddField(
model_name='quemsomos',
name='valores',
field=models.TextField(blank=True, verbose_name='Valores'),
),
migrations.AlterField(
model_name='contato',
name='celular',
field=models.CharField(blank=True, max_length=13, verbose_name='Celular'),
),
migrations.AlterField(
model_name='contato',
name='email',
field=models.CharField(blank=True, max_length=255, verbose_name='E-mail'),
),
migrations.AlterField(
model_name='contato',
name='telefone',
field=models.CharField(blank=True, max_length=12, verbose_name='Telefone'),
),
migrations.AlterField(
model_name='painel',
name='sloganPainel',
field=models.CharField(blank=True, max_length=255, verbose_name='Slogan do painel'),
),
migrations.AlterField(
model_name='portifolio',
name='descricaoPortifolio',
field=models.TextField(blank=True, verbose_name='Descrição'),
),
migrations.AlterField(
model_name='quemsomos',
name='titulo',
field=models.CharField(blank=True, max_length=50, verbose_name='Título'),
),
migrations.AlterField(
model_name='servicos',
name='descrição_do_servico',
field=models.TextField(blank=True, verbose_name='Descrição'),
),
migrations.AlterField(
model_name='servicos',
name='nome',
field=models.CharField(blank=True, max_length=50, verbose_name='Nome do serviço'),
),
migrations.AlterField(
model_name='servicos',
name='preço',
field=models.IntegerField(blank=True, default=0, verbose_name='Preço'),
),
]
<file_sep>/DesenvolvimentoBack/requirements.txt
# para instalar as dependências é necessário que execute o seguinte comando: pip install -r requirements.txt
Django==2.2.4 # INSTALAÇÃO DO DJANGO
Pillow==8.2.0 # PARA UTILIZAR O IMAGEFIELD
pylint==2.7.4 # UTILIZADO PARA VERICAÇÃO DE ERROS
pylint-django==2.4.3 # UTILIZADO PARA VERICAÇÃO DE ERROS
psycopg2==2.8.6 # PARA COMUNICAÇÃO COM POSTGRESQL
psycopg2-binary==2.8.6 # PARA COMUNICAÇÃO COM POSTGRESQL<file_sep>/DesenvolvimentoBack/apps/institucional/migrations/0027_auto_20210415_1215.py
# Generated by Django 2.2.20 on 2021-04-15 15:15
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('institucional', '0026_remove_quemsomos_titulo'),
]
operations = [
migrations.RenameField(
model_name='servicos',
old_name='logo_servico',
new_name='logoServico',
),
]
<file_sep>/DesenvolvimentoBack/apps/institucional/migrations/0009_auto_20210408_1628.py
# Generated by Django 3.1.7 on 2021-04-08 19:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('institucional', '0008_auto_20210408_1627'),
]
operations = [
migrations.AlterField(
model_name='painel',
name='imagePainel',
field=models.ImageField(blank=True, upload_to='imagens/'),
),
]
<file_sep>/DesenvolvimentoBack/apps/institucional/admin.py
from django.contrib import admin
from .models import * #esse asteristíco importa todas as classes do models
# Register your models here.
admin.site.register(home)
admin.site.register(quemSomos)
admin.site.register(servicos)
admin.site.register(portifolio)
admin.site.register(pacotes)
#username -> aprenderecrescer
#senha -> <PASSWORD><file_sep>/DesenvolvimentoBack/apps/institucional/models.py
from django.db import models
from datetime import datetime
class home(models.Model):
quantidade_parcelas = models.IntegerField('Quantidade de Parcelas', default=0)
preco_card = models.FloatField('Preço do Card', default=0)
descricao_card = models.TextField('Descrição do Card', blank=True)
data_modificacao = models.DateTimeField('Data de modificação', default=datetime.now, blank=True)
class quemSomos(models.Model):
oferecimento = models.TextField('O que oferecemos', blank=True)
oque_fazemos = models.TextField('O que fazemos', blank=True)
valores = models.TextField('Valores da instituição', blank=True)
data_modificacao = models.DateTimeField('Data de modificação', default=datetime.now, blank=True)
class servicos(models.Model):
logoServico = models.ImageField('Logo do serviço', upload_to='imagens/', blank=True)
nome = models.CharField('Nome do serviço', max_length=50, blank=True)
descrição_do_servico = models.TextField('Descrição', blank=True)
data_modificacao = models.DateTimeField('Data de modificação', default=datetime.now, blank=True)
class portifolio(models.Model):
imagePortifolio = models.ImageField('Imagem', upload_to='imagens/', blank=True)
nome = models.CharField('Nome do aluno', max_length=50, blank=True)
nota = models.IntegerField('Nota', default=0, blank=True)
descricaoPortifolio = models.TextField('Descrição', blank=True)
data_modificacao = models.DateTimeField('Data de modificação', default=datetime.now, blank=True)
class pacotes(models.Model):
duracao_pacote = models.CharField('Duração do Pacote', max_length=30)
quantidade_parcelas = models.IntegerField('Quantidade de parcelas', default=0)
valor_parcela = models.FloatField('Valor da parcela', default= 0)
valor_a_vista = models.FloatField('Valor à vista', default=0)
desconto = models.IntegerField('Porcentagem de desconto', default=0)
data_modificacao = models.DateTimeField('Data de modificação', default=datetime.now, blank=True)
<file_sep>/DesenvolvimentoBack/apps/institucional/forms.py
from django import forms
from django.core.mail import send_mail
from django.conf import settings
from .mail import send_mail_template
class FormContato(forms.Form):
nome = forms.CharField(label = 'Nome', max_length=100, widget=forms.TextInput(attrs={'id':'name', 'type':'text', 'placeholder':'Nome'}))
telefone = forms.IntegerField(label = 'Telefone', widget=forms.TextInput(attrs={'id':'company', 'type':'number', 'placeholder':'Telefone'}))
email = forms.EmailField(label = 'Email', widget=forms.TextInput(attrs={'id':'email', 'type':'email', 'placeholder':'E-mail'}))
assunto = forms.CharField(label = 'Assunto', max_length=50, widget=forms.TextInput(attrs={'id':'phone', 'type':'text', 'placeholder':'Assunto'}))
mensagem = forms.CharField(label = 'Mensagem', widget=forms.Textarea(attrs={'id':'message' , 'type':'text', 'rows':'5' , 'placeholder':'Mensagem'}))
def send_mail(self):
assunto = self.cleaned_data['assunto']
context = {
'nome': self.cleaned_data['nome'],
'telefone': self.cleaned_data['telefone'],
'email': self.cleaned_data['email'],
'mensagem': self.cleaned_data['mensagem']
}
template_html = 'contato.html'
send_mail_template(assunto, template_html, context, [settings.CONTACT_EMAIL])
<file_sep>/DesenvolvimentoBack/apps/institucional/migrations/0015_delete_redessociais.py
# Generated by Django 2.2.20 on 2021-04-11 22:48
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('institucional', '0014_auto_20210411_1352'),
]
operations = [
migrations.DeleteModel(
name='redesSociais',
),
]
<file_sep>/DesenvolvimentoBack/apps/institucional/migrations/0004_auto_20210408_1146.py
# Generated by Django 3.1.7 on 2021-04-08 14:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('institucional', '0003_portifolio'),
]
operations = [
migrations.AlterField(
model_name='contato',
name='id',
field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='portifolio',
name='id',
field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='quemsomos',
name='id',
field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='redessociais',
name='id',
field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='servicos',
name='id',
field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
]
<file_sep>/DesenvolvimentoBack/core/static/js/script.js
/*AQUI FICAM OS CÓDIGOS JAVASCRIPT*/<file_sep>/DesenvolvimentoBack/apps/institucional/migrations/0001_initial.py
# Generated by Django 3.1.7 on 2021-04-07 13:03
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='contato',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('email', models.CharField(max_length=255)),
('telefone', models.CharField(max_length=12)),
('celular', models.CharField(max_length=13)),
('data_modificacao', models.DateTimeField(blank=True, default=datetime.datetime.now)),
],
),
migrations.CreateModel(
name='quemSomos',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('apresentacao', models.TextField()),
('titulo', models.CharField(max_length=30)),
('data_modificacao', models.DateTimeField(blank=True, default=datetime.datetime.now)),
],
),
migrations.CreateModel(
name='redesSociais',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nomeRS', models.CharField(max_length=30)),
('link', models.CharField(max_length=100)),
],
),
migrations.CreateModel(
name='servicos',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nome', models.CharField(max_length=50)),
('descrição_do_servico', models.TextField()),
('preço', models.CharField(max_length=13)),
],
),
]
<file_sep>/DesenvolvimentoBack/apps/institucional/migrations/0020_quemsomos_titulo.py
# Generated by Django 2.2.20 on 2021-04-12 03:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('institucional', '0019_remove_quemsomos_titulo'),
]
operations = [
migrations.AddField(
model_name='quemsomos',
name='titulo',
field=models.CharField(blank=True, max_length=50, verbose_name='Título'),
),
]
<file_sep>/DesenvolvimentoBack/apps/institucional/migrations/0016_auto_20210411_1949.py
# Generated by Django 2.2.20 on 2021-04-11 22:49
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('institucional', '0015_delete_redessociais'),
]
operations = [
migrations.AddField(
model_name='painel',
name='data_modificacao',
field=models.DateTimeField(blank=True, default=datetime.datetime.now, verbose_name='Data de modificação'),
),
migrations.AddField(
model_name='portifolio',
name='data_modificacao',
field=models.DateTimeField(blank=True, default=datetime.datetime.now, verbose_name='Data de modificação'),
),
migrations.AddField(
model_name='servicos',
name='data_modificacao',
field=models.DateTimeField(blank=True, default=datetime.datetime.now, verbose_name='Data de modificação'),
),
]
<file_sep>/DesenvolvimentoBack/apps/institucional/migrations/0005_quemsomos_imageqs.py
# Generated by Django 3.1.7 on 2021-04-08 14:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('institucional', '0004_auto_20210408_1146'),
]
operations = [
migrations.AddField(
model_name='quemsomos',
name='imageQS',
field=models.ImageField(blank=True, upload_to='imagens/'),
),
]
<file_sep>/DesenvolvimentoBack/apps/institucional/migrations/0024_auto_20210413_2228.py
# Generated by Django 2.2.20 on 2021-04-14 01:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('institucional', '0023_auto_20210413_1801'),
]
operations = [
migrations.RemoveField(
model_name='home',
name='imageHome',
),
migrations.RemoveField(
model_name='home',
name='slogan_home',
),
migrations.AddField(
model_name='home',
name='quantidade_parcelas',
field=models.IntegerField(default=0, verbose_name='Quantidade de Parcelas'),
),
migrations.AddField(
model_name='pacotes',
name='valor_a_vista',
field=models.FloatField(default=0, verbose_name='Valor à vista'),
),
migrations.AddField(
model_name='pacotes',
name='valor_parcela',
field=models.FloatField(default=0, verbose_name='Valor da parcela'),
),
]
<file_sep>/DesenvolvimentoBack/apps/institucional/migrations/0019_remove_quemsomos_titulo.py
# Generated by Django 2.2.20 on 2021-04-12 03:12
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('institucional', '0018_auto_20210412_0004'),
]
operations = [
migrations.RemoveField(
model_name='quemsomos',
name='Titulo',
),
]
<file_sep>/DesenvolvimentoBack/apps/institucional/migrations/0023_auto_20210413_1801.py
# Generated by Django 2.2.20 on 2021-04-13 21:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('institucional', '0022_auto_20210412_2215'),
]
operations = [
migrations.AlterField(
model_name='home',
name='preco_card',
field=models.FloatField(default=0, verbose_name='Preço do Card'),
),
]
<file_sep>/DesenvolvimentoBack/apps/institucional/migrations/0018_auto_20210412_0004.py
# Generated by Django 2.2.20 on 2021-04-12 03:04
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('institucional', '0017_auto_20210411_2236'),
]
operations = [
migrations.RenameField(
model_name='quemsomos',
old_name='titulo',
new_name='Titulo',
),
]
<file_sep>/DesenvolvimentoBack/apps/institucional/migrations/0013_merge_0011_auto_20210408_2207_0012_auto_20210409_1009.py
# Generated by Django 3.2 on 2021-04-09 16:04
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('institucional', '0011_auto_20210408_2207'),
('institucional', '0012_auto_20210409_1009'),
]
operations = [
]
<file_sep>/DesenvolvimentoBack/apps/institucional/migrations/0021_auto_20210412_0035.py
# Generated by Django 2.2.20 on 2021-04-12 03:35
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('institucional', '0020_quemsomos_titulo'),
]
operations = [
migrations.RenameField(
model_name='servicos',
old_name='preço',
new_name='preco_servico',
),
]
<file_sep>/DesenvolvimentoBack/apps/institucional/migrations/0006_auto_20210408_1426.py
# Generated by Django 3.1.7 on 2021-04-08 17:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('institucional', '0005_quemsomos_imageqs'),
]
operations = [
migrations.CreateModel(
name='painel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('sloganPainel', models.CharField(max_length=255)),
('imagePainel', models.ImageField(blank=True, upload_to='imagens/')),
],
),
migrations.RenameField(
model_name='portifolio',
old_name='descricao_port',
new_name='descricaoPortifolio',
),
migrations.RenameField(
model_name='quemsomos',
old_name='imageQS',
new_name='imageQuemSomos',
),
migrations.AddField(
model_name='portifolio',
name='imagePortifolio',
field=models.ImageField(blank=True, upload_to='imagens/'),
),
migrations.AddField(
model_name='servicos',
name='imageServico',
field=models.ImageField(blank=True, upload_to='imagens/'),
),
]
<file_sep>/DesenvolvimentoBack/apps/institucional/migrations/0008_auto_20210408_1627.py
# Generated by Django 3.1.7 on 2021-04-08 19:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('institucional', '0007_auto_20210408_1623'),
]
operations = [
migrations.AlterField(
model_name='painel',
name='imagePainel',
field=models.ImageField(blank=True, upload_to='../pagina/static/imagem'),
),
]
<file_sep>/DesenvolvimentoBack/apps/institucional/migrations/0014_auto_20210411_1352.py
# Generated by Django 2.2.20 on 2021-04-11 16:52
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('institucional', '0013_merge_0011_auto_20210408_2207_0012_auto_20210409_1009'),
]
operations = [
migrations.AlterField(
model_name='contato',
name='celular',
field=models.CharField(max_length=13, verbose_name='Celular'),
),
migrations.AlterField(
model_name='contato',
name='data_modificacao',
field=models.DateTimeField(blank=True, default=datetime.datetime.now, verbose_name='Data de modificação'),
),
migrations.AlterField(
model_name='contato',
name='email',
field=models.CharField(max_length=255, verbose_name='E-mail'),
),
migrations.AlterField(
model_name='contato',
name='id',
field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='contato',
name='telefone',
field=models.CharField(max_length=12, verbose_name='Telefone'),
),
migrations.AlterField(
model_name='painel',
name='id',
field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='painel',
name='imagePainel',
field=models.ImageField(blank=True, upload_to='imagens/', verbose_name='Imagem'),
),
migrations.AlterField(
model_name='painel',
name='sloganPainel',
field=models.CharField(max_length=255, verbose_name='Slogan do painel'),
),
migrations.AlterField(
model_name='portifolio',
name='descricaoPortifolio',
field=models.TextField(verbose_name='Descrição'),
),
migrations.AlterField(
model_name='portifolio',
name='id',
field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='portifolio',
name='imagePortifolio',
field=models.ImageField(blank=True, upload_to='imagens/', verbose_name='Imagem'),
),
migrations.AlterField(
model_name='quemsomos',
name='apresentacao',
field=models.TextField(verbose_name='Apresentação'),
),
migrations.AlterField(
model_name='quemsomos',
name='data_modificacao',
field=models.DateTimeField(blank=True, default=datetime.datetime.now, verbose_name='Data de modificação'),
),
migrations.AlterField(
model_name='quemsomos',
name='id',
field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='quemsomos',
name='imageQuemSomos',
field=models.ImageField(blank=True, upload_to='imagens/', verbose_name='Imagem'),
),
migrations.AlterField(
model_name='quemsomos',
name='titulo',
field=models.CharField(max_length=50, verbose_name='Título'),
),
migrations.AlterField(
model_name='redessociais',
name='id',
field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='redessociais',
name='link',
field=models.CharField(max_length=100, verbose_name='Link de aceeso à rede'),
),
migrations.AlterField(
model_name='redessociais',
name='nomeRS',
field=models.CharField(max_length=30, verbose_name='Nome na rede'),
),
migrations.AlterField(
model_name='servicos',
name='descrição_do_servico',
field=models.TextField(verbose_name='Descrição'),
),
migrations.AlterField(
model_name='servicos',
name='id',
field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='servicos',
name='imageServico',
field=models.ImageField(blank=True, upload_to='imagens/', verbose_name='Imagem'),
),
migrations.AlterField(
model_name='servicos',
name='nome',
field=models.CharField(max_length=50, verbose_name='Nome do serviço'),
),
migrations.AlterField(
model_name='servicos',
name='preço',
field=models.CharField(max_length=13, verbose_name='Preço'),
),
]
<file_sep>/DesenvolvimentoBack/apps/institucional/urls.py
from django.urls import path
from . import views
urlpatterns = [
path ('', views.index, name ='index'),
path('notfound', views.notfound, name='notfound')
]<file_sep>/DesenvolvimentoBack/apps/institucional/migrations/0022_auto_20210412_2215.py
# Generated by Django 2.2.20 on 2021-04-13 01:15
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('institucional', '0021_auto_20210412_0035'),
]
operations = [
migrations.CreateModel(
name='home',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('slogan_home', models.CharField(blank=True, max_length=255, verbose_name='Slogan do Home')),
('imageHome', models.ImageField(blank=True, upload_to='imagens/', verbose_name='Imagem')),
('descricao_card', models.TextField(blank=True, verbose_name='Descrição do Card')),
('preco_card', models.IntegerField(default=0, verbose_name='Preço do Card')),
('data_modificacao', models.DateTimeField(blank=True, default=datetime.datetime.now, verbose_name='Data de modificação')),
],
),
migrations.CreateModel(
name='pacotes',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('duracao_pacote', models.CharField(max_length=30, verbose_name='Duração do Pacote')),
('quantidade_parcelas', models.IntegerField(default=0, verbose_name='Quantidade de parcelas')),
('desconto', models.IntegerField(default=0, verbose_name='Porcentagem de desconto')),
('atributos_pacote', models.TextField(blank=True, verbose_name='Atributos do pacote')),
('data_modificacao', models.DateTimeField(blank=True, default=datetime.datetime.now, verbose_name='Data de modificação')),
],
),
migrations.DeleteModel(
name='contato',
),
migrations.DeleteModel(
name='painel',
),
migrations.RemoveField(
model_name='servicos',
name='preco_servico',
),
migrations.AlterField(
model_name='quemsomos',
name='valores',
field=models.TextField(blank=True, verbose_name='Valores da instituição'),
),
]
<file_sep>/DesenvolvimentoBack/apps/institucional/migrations/0026_remove_quemsomos_titulo.py
# Generated by Django 2.2.4 on 2021-04-14 20:16
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('institucional', '0025_auto_20210414_1658'),
]
operations = [
migrations.RemoveField(
model_name='quemsomos',
name='titulo',
),
]
<file_sep>/README.md
# Site Institucional Aprender é Crescer
## Descrição do Projeto
<p align = "center">Esse projeto foi feito para conclusão de um Trainee da EJECT</p>
Tabela de conteúdos
=================
<!--ts-->
* [Sobre](#Sobre)
* [Tabela de Conteudo](#tabela-de-conteudo)
* [Instalação](#instalacao)
* [Como usar](#como-usar)
* [Pre Requisitos](#pre-requisitos)
* [Local files](#local-files)
* [Remote files](#remote-files)
* [Combo](#combo)
* [Tecnologias](#tecnologias)
<!--te-->
<file_sep>/DesenvolvimentoBack/apps/institucional/migrations/0025_auto_20210414_1658.py
# Generated by Django 2.2.4 on 2021-04-14 19:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('institucional', '0024_auto_20210413_2228'),
]
operations = [
migrations.RemoveField(
model_name='pacotes',
name='atributos_pacote',
),
migrations.AddField(
model_name='servicos',
name='logo_servico',
field=models.ImageField(blank=True, upload_to='imagens/', verbose_name='Logo do serviço'),
),
]
<file_sep>/DesenvolvimentoBack/apps/institucional/views.py
from django.shortcuts import render
from django.core.mail import send_mail
from .forms import FormContato
from .models import * #esse asteristíco importa todas as classes do models
#RECUPERANDO VALORES DAS MODELS
def index(request):
Home = home.objects.last()
Quem_Somos = quemSomos.objects.last()
servicosAll = servicos.objects.all()[1:]
Portifolio = portifolio.objects.all()
pacotinho = pacotes.objects.all()
servicos1 = servicos.objects.first()
message = False
# Objetos específicos que ficam nos cards do portifólio
id1 = Portifolio.get(id=2)
id2 = Portifolio.get(id=3)
id3 = Portifolio.get(id=4)
context = {}
if request.method == 'POST':
form = FormContato(request.POST)
if form.is_valid():
message = True
form.send_mail()
form = FormContato()
else:
form = FormContato()
#PASSANDO VALORES PARA UM DICIONÁRIO
context = {
'Home': Home,
'quemSomos' : Quem_Somos,
'servico': servicosAll,
'servico1': servicos1,
'portifolio': Portifolio,
'paco': pacotinho,
'form': form,
'id1': id1,
'id2': id2,
'id3': id3,
'mensagem': message
}
return render(request, 'index.html', context)
def notfound(request):
return render(request, 'notfound.html')<file_sep>/DesenvolvimentoBack/apps/institucional/mail.py
from django.template.loader import render_to_string
from django.template.defaultfilters import strip_tags
from django.core.mail import EmailMultiAlternatives
from django.conf import settings
def send_mail_template(assunto, template_html, context, para_email, de_email=settings.DEFAULT_FROM_EMAIL, fail_silently=False):
mensagem_html = render_to_string(template_html, context)
mensagem_txt = strip_tags(template_html)
#subject, body, from_email e to, são padrões da classe EmailLMultiAlternatives
email = EmailMultiAlternatives(
subject = assunto, body = mensagem_txt, from_email = de_email, to = para_email
)
email.attach_alternative(mensagem_html, "text/html")
email.send(fail_silently=fail_silently) | f2963f08189a832aaf413b7627cbe864fc80c1ee | [
"JavaScript",
"Python",
"Text",
"Markdown"
] | 30 | Python | Rafael-Soares/ProjetoFinal | 604edb949ef91d6482778edab835f427c08e8369 | 4cadfd5fb5af9f628592a7f8d742793631d31cf2 | |
refs/heads/master | <file_sep>package main
import (
"fmt"
_ "github.com/nativeborncitizen/dm/storage"
)
func main() {
fmt.Println(`Date&time management system
v. 0.1b`)
}
<file_sep>package storage
import (
"testing"
"time"
"github.com/nativeborncitizen/dm/storage"
)
func TestNewTask(t *testing.T) {
a := storage.NewTask("AAA")
if a.GetDesc() != "AAA" {
t.Error("Expected AAA, got", a.GetDesc())
}
}
func TestNewTree(t *testing.T) {
n := time.Now()
tree := storage.NewTree()
tree.Add(n, storage.NewTask("AAA"))
res, ok := tree.Find(n)
if !ok {
t.Error("Expected task")
}
if res.GetDesc() != "AAA" {
t.Error("Expected AAA, got", res.GetDesc())
}
}
<file_sep>package storage
import "time"
type timeTree map[time.Time]*task
var tree timeTree
func NewTree() timeTree {
return make(timeTree)
}
func (tree timeTree) Add(time time.Time, t *task) {
tree[time] = t
}
func (tree timeTree) Find(time time.Time) (t *task, ok bool) {
t, ok = tree[time]
return
}
<file_sep>package storage
type task struct {
desc string
}
func NewTask(desc string) *task {
return &task{desc}
}
func (t task) GetDesc() string {
return t.desc
}
| 2d39fa7d29254f44cb98105fa4e3001808b53ce2 | [
"Go"
] | 4 | Go | nativeborncitizen/dm | 6bf53065da17499cd476be5a68e95d0255ed11a3 | bbf477fa56bc21503ebca9cf1301f946af4f692c | |
refs/heads/master | <repo_name>yalov/yalov.github.io<file_sep>/_drafts/example.md
---
layout: post
title: Пример
project: false
post_on_sidebar: false
fullwidth: false
hidden: false
permalink: example # if don't want /year/
tag:
- tag1
- tag2
category: category1
disqus_comments: true
disqus_identifier: 5959e11a-f0e8-5b4e-838d-0302cd6aabd3 # unique for post
#lightbox2:
imgfolder: /images/
images:
- name: image_name.png
thumb: image_name_prev.png # unnecessary, then it's use name:
text: description
width: 1280 # unnecessary, for json-ld
height: 800 # unnecessary, for json-ld
summary: "Summary text"
---
This blog post shows a few different types of content: basic typography, images, and code.
-----
<a href="#">Lorem ipsum</a> dolor sit amet, consectetur adipiscing elit. Maecenas non varius augue. Nulla sed est libero. Aenean fermentum massa sed nulla faucibus semper. Sed vel vulputate mi. Nam convallis turpis id augue blandit, et euismod est aliquam. Vestibulum non odio lacus. Nunc pretium mauris vitae ipsum pretium, at scelerisque tellus tempor. Vestibulum nec erat scelerisque, fermentum lectus vitae, finibus magna. Aenean et lacus eros. Vestibulum eu hendrerit magna, nec posuere nibh. Aliquam pulvinar a justo a luctus.
In id nibh at arcu ultricies tempor. Proin hendrerit posuere metus, nec auctor lorem ultrices nec. In ac est at tortor tincidunt feugiat. Donec ac dolor at arcu auctor tincidunt eu id magna. Sed at placerat nunc. Praesent varius tristique mi sollicitudin efficitur. Nam ac porta arcu. Maecenas in rutrum mi. Maecenas eu ullamcorper ligula, et maximus enim. Aliquam placerat sem in nisi commodo, a consequat est congue. Integer quis nulla vel neque lobortis sagittis nec quis nulla.
<!--more-->
``` text
{% raw %}
{% include lightbox.html %}
{% include lightbox.html height='7rem' %}
{% include lightbox.html height='7rem' width='800px'%}
{% include lightbox_text.html image="image-1.jpg" %}
{% endraw %}
```
> Curabitur blandit tempus porttitor. **Nullam quis risus eget urna mollis** ornare vel eu leo. Nullam id dolor id nibh ultricies vehicula ut id elit.
Etiam porta *sem malesuada magna* mollis euismod. Cras mattis consectetur purus sit amet fermentum. Aenean lacinia bibendum nulla sed consectetur.
## Heading2
Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.
### Heading3
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
{% highlight js %}
// Example can be run directly in your JavaScript console
// Create a function that takes two arguments and returns the sum of those arguments
var adder = new Function("a", "b", "return a + b");
// Call the function
adder(2, 6);
// > 8
{% endhighlight %}
Aenean lacinia bibendum nulla sed consectetur. Etiam porta sem malesuada magna mollis euismod. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa.
### Heading3
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean lacinia bibendum nulla sed consectetur. Etiam porta sem malesuada magna mollis euismod. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.
* Praesent commodo cursus magna, vel scelerisque nisl consectetur et.
* Donec id elit non mi porta gravida at eget metus.
* Nulla vitae elit libero, a pharetra augue.
Donec ullamcorper nulla non metus auctor fringilla. Nulla vitae elit libero, a pharetra augue.
1. Vestibulum id ligula porta felis euismod semper.
2. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
3. Maecenas sed diam eget risus varius blandit sit amet non magna.
Cras mattis consectetur purus sit amet fermentum. Sed posuere consectetur est at lobortis.
<file_sep>/_includes/post-date.html
{%- if post %}
{%- assign date = post.date %}
{%- assign language = post.language %}
{%- elsif page %}
{%- assign date = page.date %}
{%- assign language = page.language %}
{%- endif %}
{%- unless language %}
{%- assign language = 'en' %}
{%- endunless %}
<span class="post-date">
<i class="far fa-calendar-alt"></i>
<time datetime="{{ date | date_to_xmlschema }}">
{{ date | date: "%-d" }}
{% assign month = date | date: '%-m' %}
{% case month %}
{% when '1' %}{{ site.data.ui-text[language].months.January }}
{% when '2' %}{{ site.data.ui-text[language].months.February }}
{% when '3' %}{{ site.data.ui-text[language].months.March }}
{% when '4' %}{{ site.data.ui-text[language].months.April }}
{% when '5' %}{{ site.data.ui-text[language].months.May }}
{% when '6' %}{{ site.data.ui-text[language].months.June }}
{% when '7' %}{{ site.data.ui-text[language].months.July }}
{% when '8' %}{{ site.data.ui-text[language].months.August }}
{% when '9' %}{{ site.data.ui-text[language].months.September }}
{% when '10' %}{{ site.data.ui-text[language].months.October }}
{% when '11' %}{{ site.data.ui-text[language].months.November }}
{% when '12' %}{{ site.data.ui-text[language].months.December }}
{% endcase %}
{{ date | date: "%Y" }}
</time>
</span>
<file_sep>/_collection/eyes-thanks.md
---
layout: post
title: "Eyes’ Thanks"
post_on_sidebar: true
date: 2018-04-17
tag:
- qt
- С++
category:
- projects
sidebar: true
comments: true
summary: "<a class=lightbox-image-link-left href='/images/eyesthanks-2monitors.jpg' data-lightbox='EyesThanks' title='fullscreen image at different-size monitors system'>
<img class='lightbox-image' style= 'width: 10rem;' src='/images/eyesthanks-2monitors.jpg' alt='fullscreen image at different-size monitors system'></a>
The app frequently alerts you to take rest breaks by showing fullscreen image (random image from the folder). It supports multiple monitors system and wide image for all monitors."
#lightbox2:
imgfolder: /images/
images:
- name: eyesthanks-2monitors.jpg
text: Notebook + monitor
- name: eyesthanks-3monitors.jpg
thumb: eyesthanks-3monitors-prev.jpg
text: 3 monitors
- name: eyesthanks-dialog-en1.png
text: setting dialog tab1 (English)
- name: eyesthanks-dialog-en2.png
text: setting dialog tab2 (English)
#- name: eyesthanks-dialog-ru1.png
# text: setting dialog tab1 (Russian)
#- name: eyesthanks-dialog-ru2.png
# text: setting dialog tab2 (Russian)
- name: eyesthanks-tray-en.png
text: tray (English)
#- name: eyesthanks-tray-ru.png
# text: tray (Russian)
---
Staring at a computer screen for hours is not good for your eyes, so Eyes’ Thanks protect them: the app displays a full-screen image on your desktop at regular intervals,
along with an optional message, reminding you to take a break.
{% include lightbox.html height='5rem'%}
<br>
## Download for Windows (portable)
See [Github Releases Page](https://github.com/yalov/eyes-thanks/releases).
<br>
### Background images
While some cool backgrounds can be generated on-the-fly, you can provide a more extensive gallery stored locally.
One of the images in the user-defined folder will be displayed in full-screen mode for the configured duration,
but you can cancel the break if you just can’t afford to interrupt your current activity.
### Multiple monitors system
It supports multiple monitors system, making it possible to display wide pictures across all your monitors.
### Works with any monitor setup
If you sometimes switch between two displays with different aspect ratios (or even between two workplace with different sets of displays),
you can set up an alternative pictures folder that the program should use whenever aspect ratios changed.
For example, if sometimes you disconnect your FullHD notebook from your FullHD monitor, put wide (3860×1080) pictures to “pictures folder” and FullHD (1920×1080) pictures to “alternative pictures folder”.
So, a laptop is connected to a monitor — the app uses wide pictures folder, a laptop isn’t connected anywhere — the app uses FullHD pictures folder.
Languages:
* English
* Russian
Translation to other languages are welcome. [How to.]({% post_url 2018-05-02-qt-linguist %})
### Hotkeys
`delete` — delete the displayed image from folder
`middle-click` tray icon — pause the timer
<br>
<small><small>
[<img class='lightbox-image-right' style= 'width: 4rem;' src='/images/gpl3.svg' alt='GPLv3'>](https://www.gnu.org/licenses/gpl-3.0.html)
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
</small></small>
<small><small>
[<img class='lightbox-image-right' style= 'width: 4rem;' src='/images/softpedia100free.png' alt='Softpedia Labs 100% Free Mark'>](http://www.softpedia.com/get/Desktop-Enhancements/Clocks-Time-Management/Eyes-Thanks.shtml#status)
This product was tested in the Softpedia Labs. Softpedia [guarantees](http://www.softpedia.com/get/Desktop-Enhancements/Clocks-Time-Management/Eyes-Thanks.shtml#status)
that Eyes’ Thanks is 100% Free, which means it does not contain any form of malware, including but not limited to: spyware, viruses, trojans and backdoors.
This software product was tested thoroughly and was found absolutely clean; therefore, it can be installed with no concern by any computer user.
</small></small>
<file_sep>/gem-versions.md
---
layout: page
title: Dependencies of github-pages gem
description: "Dependencies of github-pages gem"
---
<br>
gem | version
:-----| :-----
jekyll | {{site.github.versions.jekyll}}
github-pages | {{site.github.versions.github-pages}}
liquid | {{site.github.versions.liquid}}
{% for version in site.github.versions -%}
{%- unless version[0] == "jekyll" or version[0] == "github-pages" or version[0] == "liquid" -%}
{{version[0]}} | {{version[1]}}
{% endunless -%}
{%- endfor -%}
<file_sep>/_posts/2017-04-04-mouses.md
---
layout: post
title: Светодиодная мышь vs Лазерная мышь
summary: Преимущества и недостатки
post_on_sidebar: false
tag:
- devices
category:
- posts
comments: true
language: ru
---
### Оптическая светодиодная мышь
#### Преимущества:
* низкая цена;
* зазор между мышью и рабочей поверхностью некритичен.
#### Недостатки:
* не работает на зеркальных, стеклянных и глянцевых поверхностях;
* невысокая точность и скорость курсора;
* невысокая чувствительность;
* отвлекающая подсветка;
* высокое потребление энергии в беспроводном исполнении.
### Оптическая лазерная мышь
#### Преимущества:
* работа на любых рабочих поверхностях;
* высокая точность и скорость курсора;
* высокая чувствительность и возможность управления разрешающей способностью;
* отсутствие видимого свечения;
* низкое потребление энергии в беспроводном исполнении;
* возможность использования множества дополнительных функциональных кнопок.
#### Недостатки:
* высокая цена;
* критичность к зазору между мышью и рабочей поверхностью.
<file_sep>/scripts/staticman.js
// Static comments
(function ($) {
var $comments = $('.js-comments');
$('#comment-form').submit(function () {
var form = this;
$(form).addClass('disabled');
$('#comment-form-submit').html('<svg class="icon spin"><use xlink:href="#icon-loading"></use></svg> Loading...');
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
contentType: 'application/x-www-form-urlencoded',
success: function (data) {
$('#comment-form-submit').html('Submitted');
$('.post__comments-form .js-notice').removeClass('notice--danger').addClass('notice--success');
showAlert('<strong>Thanks for your comment!</strong> It will show on the site once it has been approved.');
},
error: function (err) {
console.log(err);
$('#comment-form-submit').html('Submit Comment');
$('.post__comments-form .js-notice').removeClass('notice--success').addClass('notice--danger');
showAlert('<strong>Sorry, there was an error with your submission.</strong> Please make sure all required fields have been completed and try again.');
$(form).removeClass('disabled');
}
});
return false;
});
function showAlert(message) {
$('.post__comments-form .js-notice').removeClass('hidden');
$('.post__comments-form .js-notice-text').html(message);
}
})(jQuery);
<file_sep>/README.md
My user site — https://yalov.github.io/
[Jekyll](http://jekyllrb.com) Theme — [Hyde](http://hyde.getpoole.com/).
<file_sep>/_collection/quotation-mark.md
---
layout: post
title: Апостроф и кавычки
fullwidth: true
hidden: false
date: 2017-04-13
tag:
- кавычки
- апостроф
category:
- posts
#lightbox2:
imgfolder: /images/
images:
- name: yarbur.png
text: Раскладка клавиатуры ЯРБУР
width: 1920
height: 850
- name: yarbur_transparent_gradient.png
text: Схема раскладки ЯРБУР (прозрачный градиент)
width: 1920
height: 850
comments: false
language: ru
permalink: yarbur/:title
---
В посте содержится информация о всех апострофах, одинарных и двойных кавычках, которые есть на [раскладке ЯРБУР]({% link _collection/yarbur.md %}), а также разновидности кавычек в русской (и не только) типографике.
<!--more-->
{%include lightbox.html image="yarbur.png" %}
## Про апострофы
Юникод<br>Ввод c клавиатуры | | Описание
------- |:----:|-----
U+2019<br>_Right Single Quotation Mark_<br>`AltGr` + `ъ`| `’` | Апостроф, **рекомендуется использовать в русских, белорусских, украинских и английских текстах**. (Пример: *Жанна д’Арк*, *you’re*, *з’ява* ). Также используется в английском тексте как закрывающая кавычка внутри других кавычек.
U+0027<br>_Apostrophe_<br>`AltGr` + `Shift` + `ъ`| `'` | Машинописный апостроф. Именно он на первом слое стандартной английской раскладки, стандартной белорусской раскладки. Суррогат, который появился во времена печатных машинок, его использовали вместо всех похожих знаков. Многие приложения и сервисы автоматически заменяют его на `’` (U+2019), поисковики работают с обеими версиями.<br>**Не рекомендуется использовать как апостроф**.
U+02BC<br>_Modifier Letter Apostrophe_<br>`нет на раскладке`| `ʼ` | Апостроф-буква. По виду полностью совпадает с **U+2019** (в правильном шрифте), но относится к [блоку](https://en.wikipedia.org/wiki/Unicode_character_property#General_Category) "Letter (Lm)" юникода, а не "Punctuation (Pf)", как U+2019. Несмотря на строгую позицию консорциума юникода, предписывающую использовать именно U+2019, есть [альтернативное мнение](https://tedclancy.wordpress.com/2015/06/03/which-unicode-character-should-represent-the-english-apostrophe-and-why-the-unicode-committee-is-very-wrong/), и [в дополнение](https://ukrainian.stackexchange.com/questions/40/Який-символ-використовувати-для-позначення-апострофа-в-електронних-текстах-украї). Если у вас есть желание противиться консорциуму, то вы можете самостоятельно добавить на раскладку этот символ.
<br><br>
## Про одинарные и двойные кавычки
### Tl;dr
Почти в каждом языке мира для «кавычек» и «кавычек внутри других кавычек» используются разные обозначения, в том числе в русском.
* **русский:** снаружи «ёлочки» — `AltGr` и `<` `>`, внутри „лапки“ — `AltGr`+`Shift` и `<` `>`
> Эйнштейн писал Э<NAME>: «Слово „бог“ для меня всего лишь проявление и продукт человеческих слабостей».
* **английский:** снаружи “английские двойные”, внутри ‘английские одиночные’. В раскладке снаружи на `Д` `Ж`, а внутри на `Х` `Ъ` aka там, где скобки `[{` `]}`. [ДЖ](https://ru.wikipedia.org/wiki/Джоуль,_Джеймс),[ДЖ](http://ru.elderscrolls.wikia.com/wiki/Дж'дарр),[ДЖ](https://ru.wikipedia.org/wiki/Роулинг,_Джоан).
> The Times wrote, “Drugs and weapons still for sale on ‘dark net.’ ”
### Кавычки на раскладке
Юникод | |Ввод с клавиатуры | Описание
-------| -----| :----: |-----
U+2018<br> _Left Single Quotation Mark_ | `‘` | `AltGr` + `х` | Используется в английском языке как открывающая кавычка внутри других кавычек.
U+2019<br> _Right Single Quotation Mark_ | `’` | `AltGr` + `ъ` | Помимо апострофа (см. таблицу выше) символ используется в английском языке как закрывающая кавычка внутри других кавычек.
U+2032<br> _Prime_ | `′` | `AltGr` + `з` | Штрих. Используется как угловые минуты, производная, знак фута.
U+2033<br> _Double Prime_ | `″` | `AltGr` + `Shift` + `з` | Двойной штрих. Используется как угловые секунды, вторая производная, знак дюйма.
U+201E<br> _Double Low-9 Quotation Mark_ | `„` | `AltGr` + `Shift` + `<`<br>или<br>`AltGr` + `л` | Русский язык — открывающие кавычки внутри других кавычек. <br>Английский язык — не используется.
U+201C<br> _Left Double Quotation Mark_ | `“` | `AltGr` + `Shift` + `>`<br>или<br>`AltGr` + `д` | Русский язык — закрывающие кавычки внутри других кавычек. <br>Английский язык — открывающие кавычки.
U+201D<br> _Right Double Quotation Mark_ | `”` | `AltGr` + `ж` | Русский язык — не используются. <br>Английский язык — закрывающие кавычки.
U+00AB<br> _Left-Pointing Double Angle Quotation Mark_ | `«` | `AltGr` + `<` | Левая французская «кавычка-ёлочка». Стала традиционной открывающей кавычкой в русском языке.
U+00BB<br> _Right-Pointing Double Angle Quotation Mark_ | `»` | `AltGr` + `>` | Правая французская «кавычка-ёлочка». Стала традиционной закрывающей кавычкой в русском языке.
U+0022<br> _Quotation Mark_ | `"` | `AltGr` + `.` | Универсальная двойная кавычка, иногда называется машинописной или программистской. Находится на втором слое стандартной английской раскладки. Суррогат, который появился во времена печатных машинок, его использовали вместо всех двойных кавычек.
### Кавычки в русском языке
Имеют названия следующие виды кавычек:
* Французские кавычки «ёлочки».
* »Шведские кавычки«.
* Немецкие кавычки „лапки“, Внешне похожие на 9966 — двойное 96 — как [U-96](https://ru.wikipedia.org/wiki/U-96_(1940)) и [Ил-96](https://ru.wikipedia.org/wiki/Ил-96).
* Английские “двойные” и ‘одиночные’ кавычки. Внешне похожи на 6699 и 69 — как [Вудсток](https://ru.wikipedia.org/wiki/Вудсток_(фестиваль)).
* „Польские кавычки”. Внешне похожи на 9999 — крупнейшее четырёхзначное десятичное число — [«Poland strong!»](https://upload.wikimedia.org/wikipedia/commons/8/86/Polandball.PNG).
В русском языке традиционно применяются французские «ёлочки», а для кавычек внутри кавычек и при письме от руки — немецкие „лапки“.
> Беляев называл «Голову профессора Доуэля» автобиографической историей, поясняя: «Болезнь уложила меня однажды на три с половиной года в гипсовую кровать.
> Этот период болезни сопровождался параличом нижней половины тела. И хотя руками я владел, всё же моя жизнь сводилась в эти годы к жизни „головы без тела“,
> которого я совершенно не чувствовал — полная анестезия…»
В особом случае, в русских текстах употребляются английские одиночные кавычки.
В такие кавычки берётся текст, указывающий значение некоторого слова или словосочетания (обычно иноязычного).
> Лингвистика, от лат. lingua — ‘язык’.
> В немецком языке элементы frieden ‘мир’ и kampf ‘борьба’ сочетаются как морфемы.
> Пациент не может, например, идентифицировать слово carrot, но без затруднений даёт дефиницию слову knowledge,
> определяя его как ‘making oneself mentally familiar with a subject’.
> Фраза «Вы выходите?» в автобусе или в троллейбусе означает ‘дайте, пожалуйста, пройти’.
При прямой речи в конце предложения точка выносится за кавычки, а вопросительный и восклицательный знаки, многоточие, наоборот, остаются внутри.
В других случаях (не прямая речь — цитаты, названия произведений, слова в ироническом смысле и тому подобное) обычно используются все знаки:
> Пётр спросил у андроида Фёдора: «Мечтают ли андроиды об электроовцах?» Иван вернулся с новыми батарейками. Фёдор ответил Петру: «Возможно».
> Вы прочитали роман «Мечтают ли андроиды об электроовцах?». Лично я прочитал.
### Кавычки в мире
* Начиная с 1960х в британском английском появляется тенденция замены порядка кавычек: ‘вот “так” вот’.
Также в английском языке (особенно в его американском варианте) точка зачастую ставится перед закрывающей кавычкой, а не после, как в русском.
* Традиционно в белорусских и украинских типографиях использовались «французские» и „немецкие“ кавычки.
Сейчас как в частном использовании, так и в СМИ нет единого общепринятого варианта кавычек, однако:
* [«Закон Рэспублiкi Беларусь аб Правiлах беларускай арфаграфii i пунктуацыi»](http://www.academy.edu.by/files/zak_420-3.pdf),
он же [«Правапіс-2008»](https://be.wikiquote.org/wiki/Правапіс-2008) предписывает использовать в белорусском языке
«французские кавычки» снаружи и “английские двойные” внутри.
* [Український Правопис (2015)](http://litopys.org.ua/pravopys/pravopys2015.htm), одобренный национальной академией наук Украины,
предписывает использовать в украинском языке «французские кавычки» снаружи и „немецкие“ внутри.
* В нелегальной, первой белорусской газете «Mużyckaja prauda» ([Мужыцкая праўда](https://be.wikipedia.org/wiki/Мужыцкая_праўда), 1862—1863)
использовались „польские кавычки”. Их, вероятно, и рекомендуется использовать в текстах на латинке.
* „Польские кавычки” помимо Польши используются в румынском и нидерландском языках.
* Во Франции иногда используются ‹французские одиночные›.
* В Финляндии (и Швеции) используются непарные кавычки: ”lainata” или »noteerata»
* »Шведские кавычки« в Швеции уже почти не используются.
* В иероглифических письменностях существуют свои кавычки: — 《...》, 『...』, и 「...」.
* Фонд эсперанто не предписывает какие-то определённые кавычки, а текст может содержать
различные популярные в мире формы кавычек: ‘citaĵo’, “citaĵo”, „citaĵo” и «citaĵo».
* В [Ложбане](https://ru.wikipedia.org/wiki/Ложбан) используются слова lu ... li'u.
### Примеры использования кавычек:
> Станислав Ежи Лец пишет: «Это не фокус сказать: „Я — есмь“. Надо быть». *(русский)*
> Анатоль Анікейчык пісаў пра помнік Янку Купалу ў Аўраў-парку: «У аснову ідэі гэтага помніка я паклаў Купалаўскі верш “Брату на чужыне”». *(белорусский)*
> «Ти дивився кінофільм „Данило — князь галицький“?» — спитав він товариша. *(украинский)*
> Czy można jeszcze wątpić, że „tak naprawdę nie dzieje się nic i nie stanie się nic aż do końca”? *(польский)*
> The Times wrote, “Drugs and weapons still for sale on ‘dark net.’” *(английский)*
> Dies habe, so Meyer, „nichts mit ‚Globalisierung‘ zu tun“. *(немецкий)*
> « L’ouvreuse m’a dit : ‹ Donnez-moi votre ticket. › Je le lui ai donné. » *(французский — да, так отбиваются пробелами)*
{% comment %}
В раскладке на `Л` `Д` aka `K` `L`. ЛДKL — как русский [**л**е**д**о**к**о**л** «Ленин»](https://ru.wikipedia.org/wiki/Ленин_(атомный_ледокол)) — первый в мире ледокол с атомной энергетической установкой.
X⁰¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ⁿ X₀₁₂₃₄₅₆₇₈₉₊₋₌₍₎
Циолковский скептически относился к теории относительности: «Замедление времени в летящих со субсветовой скоростью кораблях по сравнению с земным временем представляет собой либо фантазию, либо одну из очередных ошибок нефилософского ума. … Замедление времени! Поймите же, какая дикая бессмыслица заключена в этих словах!»
{% endcomment %}
<file_sep>/_collection/yarbur.md
---
layout: post
title: Раскладка клавиатуры ЯРБУР
post_on_sidebar: true
date: 2017-04-12
tag:
- keyboard layout
- AltGr
- типографская
- раскладка
category:
- projects
comments: true
language: ru
#lightbox2:
imgfolder: /images/
images:
- name: yarbur.png
text: Раскладка клавиатуры ЯРБУР
width: 1920
height: 660
- name: yarbur_transparent_gradient.png
text: Схема раскладки ЯРБУР (прозрачный градиент)
width: 1920
height: 644
permalink: yarbur/
---
{% include lightbox.html image="yarbur.png" %}
Набор расширенных раскладок, включает русскую и английскую раскладки, и позволяет набирать многие типографские символы, белорусские и украинские буквы через правый Alt.
<!--more-->
<br>
### Скачать ЯРБУР для Windows XP–10 c [Github](https://github.com/yalov/yarbur-keyboard-layouts/releases)
<br>
Символы, доступные через правый Alt (`AltGr`) называют третьим слоем, а через `AltGr` + `Shift` — четвёртым.
* 1 слой — **с** = `с`
* 2 слой — **С** = `Shift` + `с`
* 3 слой — **©** = `AltGr` + `c`
* 4 слой — **¢** = `AltGr` + `Shift` + `c`
Раскладка содержит Тире (**—** = `AltGr` + `-`), символ рубля (**₽** = `AltGr` + `р`), «кавычки», знак градуса, знак копирайта и многие другие.
Раскладка содержит белорусские и украинские буквы: **Ў**, **І**, **Ґ**, **Ї**, **Є** и апостроф. Присутствуют символы гривны и белорусского рубля:
**₴**, **Br**.
Подстрочные₄₊₅ и надстрочные⁴⁺⁵ цифры вводятся через `CapsLock`:
* 5 слой — **₈** = `8` (при включённом `CapsLock`)
* 6 слой — **⁸** = `Shift` + `8` (при включённом `CapsLock`)
### Как установить?
* Для установки последовательно запустить *Install-Yarbur-En.exe* и *Install-Yarbur-Ru.exe*.
Затем в «настройках способов ввода» (*Панель управления/Язык* для Win10) добавьте раскладки ЯРБУР и можно удалять стандартные раскладки. **Перезагрузиться**.
* Иногда стандартные раскладки самоятоятельно востанавливаются после перезагрузки. В таком случае отредактируйте реестр, Подробнее [superuser.com](https://superuser.com/questions/957552/how-to-delete-a-keyboard-layout-in-windows-10)
* Для удаления, сначала убрать из «настроек способов ввода», затем удалить из «установка и удаление программ» (*Панель управления/Программы и компоненты* для Win10).
За основу взята [**Типографская раскладка v3.4**](http://ilyabirman.ru/projects/typography-layout/), на которую были добавлены белорусские и украинские буквы, и прочие полезные символы.
При помощи [**The Microsoft Keyboard Layout Creator**](https://msdn.microsoft.com/keyboardlayouts.aspx) можно создать свою или изменить эту раскладку.
### Про апостроф и кавычки
В качестве апострофа в русских, белорусских, украинских и английских текстах рекомендуется использовать `AltGr` + `ъ` = **’** (U+2019). Пример: *Жанна д’Арк*, *з’ява*, *you’re*.
В качестве кавычек рекомендуется использовать «кавычки-ёлочки» ( `AltGr` + `<` и `AltGr` + `>`).
Подробнее про апострофы, одинарные и двойные кавычки [**тут**]({% link _collection/quotation-mark.md %}).
### Про диакритические знаки
На четвёртом слое можно увидеть различные диакритические знаки, обозначенные пунктирным кружком. Их можно «соединять» с любой буквой русского и английского алфавита.
Есть 2 способа такого соединения:
1. Первый способ работает только если такая буква реально существует в Юникоде, или, точнее, в [этом списке](https://github.com/yalov/yarbur-keyboard-layouts/blob/master/diacritical_mark.txt).
Диактитику нужно ввести **до** необходимой буквы:
* **Schrödinger** — `AltGr` + `Shift` + `:`, `o` → **¨** + **o** → **ö**
Если такой буквы нет в Юникоде, тогда диакритика появится до буквы:
* `AltGr` + `Shift` + `:`, `я` = **¨** + **я** → **¨я**
2. Второй способ работает для любых букв, но вводит «ненастоящие» буквы, с применением «комбинирующей диактирики».
Диакритика будет отдельным символом, но выводящимся на экран на один знак левее, залезая на предыдущую букву. Это легко проверить, если нажать `Backspace` — исчезнет диакритика, но не сама буква. Хотя это не точно, так как второй способ зависит от вашего текстого редактора и реализованного в нём способа отображения «комбинирующей диактирики».
Чтобы ввести такую диакритику, нужно **после** буквы зажимая `AltGr`+`Shift` **дважды** нажать клавишу с необходимым диакритиреским знаком:
* `я`, `AltGr` + `Shift` + `:` + `:` → **я̈**
* `я`, `AltGr` + `Shift` + `/` + `/` → **я́**
* **во́ля** — `в`, `о`, `AltGr`+`Shift`+`/`+`/`, `л`, `я`
Таки́м спо́собом мо́жно расста́вить ударе́ния в слова́х.
### Про десятичный разделитель
Обычно десятичный разделитель на цифровом блоке в русской раскладке — запятая, хотя в английской — точка и нарисована на клавише тоже точка. Из-за этого возникает много путаницы.
Кто-то скажет, что в русской типографике исторически дробная часть отделяется запятой. Это верно, но, во-первых, многие русские авторы уже используют точку, и, во-вторых, ip-адрес и версия программы в любом случае разделяется именно точкой. Поэтому в раскладках клавиатуры ЯРБУР (и в русской, и в английской) **в качестве десятичного разделителя используется точка**, а в третьем слое (`AltGr`) — запятая.
### Про CapsLock
Начиная с версии 2.0 помимо `AltGr` перегружается ещё и `CapsLock`. Можно сказать, что это пятый и шестой слой (шестой — с `Shift`).
На пятом слое находятся подстрочные **₌₁₂₃₄₅₆₇₈₉₀₋₊**, на шестом — надстрочные **⁼¹²³⁴⁵⁶⁷⁸⁹⁰⁻⁺**. Буквы ведут себя КАК ОБЫЧНО.
На третий и четвёртый слой клавиша `CapsLock` не влияет, т.е. © = `AltGr` + `с` = `CapsLock`, `AltGr` + `с`.
### Изображения
<!-- {% include lightbox.html height='10rem' %} -->
* Схема раскладки ЯРБУР — [yarbur.png]({{ site.baseurl }}/images/yarbur.png)
* Схема раскладки ЯРБУР (прозрачный градиент) — [yarbur_transparent_gradient.png]({{ site.baseurl }}/images/yarbur_transparent_gradient.png)
<file_sep>/_posts/2017-07-20-qmake-deployment.md
---
layout: post
title: QMake Deployment
post_on_sidebar: false
tag:
- qt
- qmake
- deployment
category:
- posts
comments: true
language: ru
---
Для автоматической сборки Qt приложений под Windows в папку назначения вместе со всеми нужными библиотеками и
необходимыми файлами в QtCreator'е можно использовать qmake-команды в .pro-файле.
Для начала переносим релизный `.exe` в новую папку:
``` qmake
CONFIG(release, debug|release) {
DESTDIR = $$PWD/../AppName
}
```
И наполняем эту папку библиотеками и файлами, которые нужны для выполнения.
Задаём перенос строки aka переменная разделения команд `RETURN`, и затем наполняем `QMAKE_POST_LINK` необходимыми командами:
<!--more-->
``` qmake
RETURN = $$escape_expand(\n\t)
QMAKE_POST_LINK += $$RETURN command1
QMAKE_POST_LINK += $$RETURN command2
QMAKE_POST_LINK += $$RETURN command3
# export(QMAKE_POST_LINK) # if inside function (exports from the local context to the global.
```
Но лучше для каждой операции ввести отдельную функцию, все функции вынести в отдельный `.pri`-файл, а в `.pro`-файле оставить только вызовы.
``` qmake
# functions.pri
defineTest(func1) {
ARG1 = $$1
ARG2 = $$2
# commands
}
defineTest(func2) {
ARGS = $$1
# commands
}
# ...
# main.pro
include("functions.pri")
func1(arg1, arg2)
func2(arg1)
```
Команда сборки `windeployqt` в qmake будет выглядеть так (сначала используя содержимое переменной `QT` берём модули, которые точно нужны, потом пишем модули которые окажутся лишними):
``` qmake
# windeployqt in $$DESTDIR with some ARGS
defineTest(windeployqtInDESTDIR) {
ARGS = $$1
RETURN = $$escape_expand(\n\t)
QMAKE_POST_LINK += $$RETURN windeployqt $$ARGS $$quote($$shell_path($$DESTDIR))
export(QMAKE_POST_LINK)
}
# ...
PACKAGES = "--compiler-runtime"
for(package,QT){
PACKAGES += "--$${package} "
}
PACKAGES += --no-svg --no-system-d3d-compiler --no-translations --no-opengl-sw --no-angle
windeployqtInDESTDIR($$PACKAGES)
```
### Копирование и удаление файлов
Функция для рекурсивного удаления папки:
``` qmake
# Recursive remove directory
defineTest(removeDirRecursive) {
DIR_TO_DEL = $$shell_path($$1)
RETURN = $$escape_expand(\n\t)
QMAKE_POST_LINK += $$RETURN $$QMAKE_DEL_TREE $$quote($$DIR_TO_DEL)
export(QMAKE_POST_LINK)
}
#....
removeDirRecursive($$DESTDIR/somedir)
```
Функция для удаления файлов из какой-то папки:
``` qmake
# Remove some files from directory (directory_path and file_names)
defineTest(removeFilesInDir) {
PATH = $$shell_path($${1}) # full path to directory
FILENAMES = $${2} # filenames inside directory for remove
RETURN = $$escape_expand(\n\t)
for(FILENAME, FILENAMES){
QMAKE_POST_LINK += $$RETURN $$QMAKE_DEL_FILE $$quote($${PATH}$${FILENAME})
}
export(QMAKE_POST_LINK)
}
# ...
FILENAMES = qlib1.dll qlib2.dll qlib3.dll qlib4.dll
removeFilesInDir($$DESTDIR/somedir/, $$FILENAMES)
```
Функция для удаления файлов (не обязательно из одной папки):
``` qmake
# Remove some files
defineTest(removeFiles) {
FILES_TO_DEL = $$shell_path($$1) # full path (split spaces) or mask *
RETURN = $$escape_expand(\n\t)
for(FILE, FILES_TO_DEL){
QMAKE_POST_LINK += $$RETURN $$QMAKE_DEL_FILE $$quote($$FILE)
}
export(QMAKE_POST_LINK)
}
# ...
FILEPATHES = /path/to/qlib1.dll /path/to/qlib2.dll /path/to/qlib3.dll /path/to/qlib4.dll
removeFiles($$FILENAMES)
```
Функция для создания папки и копирования в неё файлов:
``` qmake
# create directory if not exist, then copy some files to that directory
defineTest(copyFilesToDir) {
FILES = $$shell_path($$1) # full filepath (split spaces) or masks * ?
DIR = $$shell_path($$2) # directory path
RETURN = $$escape_expand(\n\t)
QMAKE_POST_LINK += $$RETURN $$sprintf($$QMAKE_MKDIR_CMD, $$DIR)
for(FILE,FILES){
QMAKE_POST_LINK += $$RETURN $$QMAKE_COPY $$quote($$FILE) $$quote($$DIR)
}
export(QMAKE_POST_LINK)
}
# ...
copyFilesToDir(some/*.dll, $$DESTDIR/other)
# or
copyFilesToDir(path/to/1.dll path/to/2.dll, $$DESTDIR/other)
```
### Дерево файлов проекта
Также стоит вспомнить о команде, которая лечит не-баг-а-фичу дерева папок проекта под windows
(вложенные дополнительные папки debug и release в каждой из build-Qt-Debug и build-Qt-Release):
```
project\
|__build-Qt_x_y_0_32bit_Debug\
|__|__debug\
|__|__|__...files
|__|__release\
|__|__|__...empty
|__build-Qt_x_y_0_32bit_Release\
|__|__debug\
|__|__|__...empty
|__|__release\
|__|__|__...files
```
Вот она:
``` qmake
CONFIG -= debug_and_release
```
После неё:
```
project\
|__build-Qt_x_y_0_32bit_Debug\
|__|__...files
|__build-Qt_x_y_0_32bit_Release\
|__|__...files
```
Можно пойти дальше, и аккуратно разложить файлы в `build-Qt-Debug` и `build-Qt-Release`:
``` qmake
OBJECTS_DIR = $$OUT_PWD/.obj
MOC_DIR = $$OUT_PWD/.moc
RCC_DIR = $$OUT_PWD/.qrc
UI_DIR = $$OUT_PWD/.ui
```
Получим:
```
project\
|__build-Qt_x_y_0_32bit_Debug\
|__|__.obj\
|__|__.moc\
|__|__.qrc\
|__|__.ui\
|__build-Qt_x_y_0_32bit_Release\
|__|__.obj\
|__|__.moc\
|__|__.qrc\
|__|__.ui\
```
### Использование переменных
Чтобы быстро включать и выключать копирование файлов в DEPLOY-сборку, и заодно, отключить в DEPLOY все отладочные сообщения, можно сделать так:
``` qmake
CONFIG += DEPLOY # comment/uncomment this for Usual_release/Deploy
# ...
CONFIG(release, debug|release) {
DEPLOY {
DEFINES += QT_NO_DEBUG_OUTPUT
# ... all necessary commands
}
}
```
Удобной может быть переменная времени сборки:
``` qmake
win32 {
BUILD_TIME = $$system("echo %time:~0,8%")
} else {
BUILD_TIME = $$system("time")
}
message("$$BUILD_TIME projectname.pro")
```
<file_sep>/Gemfile
source 'https://rubygems.org'
gem 'github-pages', group: :jekyll_plugins
# listen (serve) requires an extra gem for compatibility with Windows.
# gem 'wdm', '~> 0.1.0' if Gem.win_platform?
gem 'wdm', '>= 0.1.0' if Gem.win_platform?
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
# gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
<file_sep>/_posts/2018-05-02-qt-linguist.md
---
layout: post
title: Qt Linguist
project: false
post_on_sidebar: false
fullwidth: true
hidden: false
tag:
- qt
- deployment
- linguist
category:
- posts
comments: true
language: en
---
How to localize S-app (someone's Qt app)?
1. You need to find `.ts` localization file. Usually it's separate file for every language in the languages folder in the S-app source repository.
Examples: <!--more-->
`lang_en.ts`-— source English localization file
`lang_en.qm` — compiled English localization file (used by working app)
2. `.ts` file is XML, so you can modify it as plain text, but more convenient is using Qt Linguist. It is included in Qt framework, but you can download it as separate app for Windows [here](https://github.com/thurask/Qt-Linguist/releases) (unofficial).
3. Copy `English.ts`, rename to `your_language.ts`, change the language tag in the begining of the file manually using a notepad.
```
<TS version="2.1" language="en_US">
```
4. Open both file in the Qt linguist, and make a translation.
5. Save `your_language.ts` file
6. You can test your translation: using Qt Linguist, compile `your_language.ts` to `your_language.qm`, and test it with app package (put to S-app `language/` folder)
7. Send `your_language.ts` to S-app author.
More info [here](http://doc.qt.io/qt-5/linguist-translators.html)
<file_sep>/_drafts/feedback-alternatives.md
---
layout: page
title: Feedback2
published: false
---
<!-- Please use the form below to contact us regarding feedback or any questions you may have! We will never use the information given below to spam you and we will never pass on your information to a 3rd party.
As we are using [FormSpree](http://formspree.io) for this form please consult their privacy policy for any questions regarding this matter. -->
<!-- google short -->
<!-- <script type="text/javascript">var submitted=false;</script>
<iframe name="hidden_iframe" id="hidden_iframe" style="display:none;" onload="if(submitted)
{window.location='{{ site.baseurl }}/Feedback_finish.html';}">
</iframe>
<form action="https://docs.google.com/forms/d/e/1FAIpQLSf6ADpCgWAOCPLqwuk4vtSAehpdp2tde16-kqW_O4803D67MQ/formResponse" method="post" target="hidden_iframe" onsubmit="submitted=true;"><input type="text" placeholder="Your name" name="entry.1991378409">
<input type="text" placeholder="Your email" name="entry.1851221112"><br>
<textarea name="entry.1211410705" placeholder="Your message" rows="8" cols="80">
</textarea><br>
<input type="hidden" name="draftResponse" value="[,,"1422419426149312021"]">
<input type="hidden" name="pageHistory" value="0">
<input type="hidden" name="fbzx" value="1422419426149312021">
<input type="submit" name="submit" value="Готово" id="ss-submit" class="jfk-button jfk-button-action "></form> -->
<!-- feedback3 -->
<!-- <link href="http://fonts.googleapis.com/css?family=Lato" rel="stylesheet" type="text/css">
<form id="contact-form">
<p>Dear Alexander,</p>
<p>My
<label for="your-name">name</label> is
<input type="text" name="your-name" id="your-name" minlength="3" placeholder="(your name here)" required=""> and</p>
<p>my
<label for="email">email address</label> is
<input type="email" name="your-email" id="email" placeholder="(your email address)" required=""></p>
<p> I have a
<label for="your-message">message</label> for you,</p>
<p>
<textarea name="your-message" id="your-message" placeholder="(your msg here)" class="expanding" required="">
</textarea>
</p>
<p>
<button type="submit"><svg version="1.1" class="send-icn" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="100px" height="36px" viewBox="0 0 100 36" enable-background="new 0 0 100 36" xml:space="preserve">
<path d="M100,0L100,0 M23.8,7.1L100,0L40.9,36l-4.7-7.5L22,34.8l-4-11L0,30.5L16.4,8.7l5.4,15L23,7L23.8,7.1z M16.8,20.4l-1.5-4.3
l-5.1,6.7L16.8,20.4z M34.4,25.4l-8.1-13.1L25,29.6L34.4,25.4z M35.2,13.2l8.1,13.1L70,9.9L35.2,13.2z">
</path>
</svg>
<small>send</small></button>
</p>
</form>
<small class="website">Vist <a href="http://www.erlen.co.uk/" target="_blank">erlen.co.uk</a> to see my work</small> -->
<!-- feedback5 -->
<!-- <div class="inner contact">
<div class="contact-form">
<form id="contact-us" method="post" action="#">
<div class="col-xs-6 wow animated slideInLeft" data-wow-delay=".5s"><input type="text" name="name" id="name" required="required" class="form" placeholder="Name">
<input type="email" name="mail" id="mail" required="required" class="form" placeholder="Email"></div>
<div class="col-xs-6 wow animated slideInRight" data-wow-delay=".5s">
<textarea name="message" id="message" class="form textarea" placeholder="Message">
</textarea>
</div>
<div class="relative fullwidth col-xs-12">
<button type="submit" id="submit" name="submit" class="form-btn semibold">Send Message</button>
</div>
<div class="clear">
</div>
</form>
<div class="mail-message-area">
<div class="alert gray-bg mail-message not-visible-message"><strong>Thank You !</strong> Your email has been delivered.
</div>
</div>
</div>
</div> -->
<!-- google orig -->
<!-- <iframe src="https://docs.google.com/forms/d/e/1FAIpQLSf6ADpCgWAOCPLqwuk4vtSAehpdp2tde16-kqW_O4803D67MQ/viewform?embedded=true" onload="if(submitted) {window.location='/';}" style="background: #FFFFFF;" width="100%" height="1000" frameborder="0" marginheight="0" marginwidth="0">Загрузка...</iframe> -->
<!-- Simular posts -->
<!--
<div class="related">
<h2>Related Posts</h2>
<ul class="related-posts">
{% for post in site.related_posts limit:3 %}
<li>
<h3>
<a href="{{ post.url }}">
{{ post.title }}
<small>{{ post.date | date_to_string }}</small>
</a>
</h3>
</li>
{% endfor %}
</ul>
</div>
-->
<file_sep>/404.html
---
layout: default
title: "HTTP 404"
permalink: /404.html # this is for https://yalov.github.io/2016/ (https://stackoverflow.com/questions/20973662)
sitemap: false
---
{% capture site_url -%}
{{ site.baseurl | prepend: site.url |replace:'//','/'|replace:'//','/' |replace:'https:/','https://' | replace:'http:/','http://' }}
{%- endcapture %}
<script type="text/javascript">
var totalCount = 7;
function ChangeIt() {
var num = Math.ceil(Math.random() * totalCount);
document.body.background = '{{ site.baseurl }}/images/404/' + num + '.gif';
document.body.style.backgroundRepeat = "repeat"; // Background repeat
}
window.onload = ChangeIt;
</script>
<style>
body {
position: relative;
width: 100%;
height: 100%;
-webkit-font-smoothing: antialiased;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-repeat: no-repeat;
}
form {
color: #777;
background: rgba(255, 255, 255, 0.7);
padding: 25px;
margin: 150px 0;
box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
-webkit-font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
-o-font-smoothing: antialiased;
font-smoothing: antialiased;
text-rendering: optimizeLegibility;
}
.container-form {
width: 70%;
margin: 0 auto;
position: relative;
}
</style>
<div class="container-form">
<form>
<h1>HTTP 404: Not Found</h1>
<p>This page doesn't seem to exist. You might have followed a bad link or mistyped the address.
Not to worry. You can return to the <a href="{{ site_url }}">home page</a> or sit there and procrastinate.</p>
</form>
</div>
</html>
<file_sep>/about.md
---
layout: page
title: About
on_sidebar_bottom: false
---
Man.
<file_sep>/_collection/icalendar-generator.md
---
layout: post
title: Календарь праздников - 2023
post_on_sidebar: true
date: 2023-01-01
tag:
- праздник
- календарь
- iCal
category:
- tools
comments: true
language: ru
---
Cтандартные календари праздников от Google недостаточно полны, и здесь можно найти расширенный календарь праздников.<!--more-->
<iframe src="https://calendar.google.com/calendar/embed?showPrint=0&showTabs=0&showCalendars=0&showTz=0&
height=600&wkst=2&hl=ru&bgcolor=%23FFFFFF&src=ac10bada85f6bedeabfc818c11d156a200c298efad6c3c0150c6515b52c0bc3c%40group.calendar.google.com&
color=%23333333&ctz=Europe%2FMoscow" style="border-width:0" width="100%" height="600" frameborder="0" scrolling="no"></iframe>
### Tl;Dr
Cкопировать календарь праздников с помощью кнопки «**+Google** Календарь» в свой Гугл-аккаунт.
### Чуть подробнее
Сохранить [**ical-favorite-out.ics**]({{ site.baseurl }}/files/iCalendar/ical-favorite-out.ics) с полным описанием каждого праздника, в достаточно популярном формате [iCalendar](https://en.wikipedia.org/wiki/ICalendar) (`iCal`), и делать с ним что угодно, например, импортировать файл в Google Calendar.
Для этого рекомендуется на [calendar.google.com](https://calendar.google.com/) сначала *Cоздать новый календарь* в настройках, в списке «Мои Календари»,
а затем *Импортировать* в него скачанный `iCal`.
### Подробно
На сайте [calend.ru](http://calend.ru) праздники собраны по категориям.
Можно либо скачать по прямой ссылке один из представленных ниже календарей, либо создать на сайте свой календарь праздников и скачать `iCal`.
- [Праздники Международные](http://www.calend.ru/ical/ical-wholeworld.ics)
- [Праздники Еврейские](http://www.calend.ru/ical/ical-jew.ics)
- [Праздники Беларуси](http://www.calend.ru/ical/ical-belorus.ics)
- [Праздники России](http://www.calend.ru/ical/ical-russtate.ics)
- [Праздники Украины](http://www.calend.ru/ical/ical-ukraine.ics)
Однако в этих файлах про каждый праздник написано только одно предложение, хотя
на самом сайте содержится полноценная история и описание каждого праздника.
Следующий python-скрипт заменяет короткое описание праздников в `iCal` на полное описание с сайта, и сохраняет в новый файл.
Скрипт использует [icalendar](http://pypi.python.org/pypi/icalendar) и работает с файлами `iCal` (.ics) через аргумент командной строки.
```bash
pip install icalendar trafilatura colorama
python proceed.py path/to/.ics
```
{% gist 055e636e6bfc35c7d7b096aa8aa26c0d %}
Готовая версия:
- [Избранные праздники с описанием]({{ site.baseurl }}/files/iCalendar/ical-favorite-out.ics)
Именно эту версию можно было скачать ещё по ссылке в начале. В неё включены международные праздники, праздники Беларуси, и различные необычные праздники других стран.
Удалены несколько узких профессиональных праздников сотрудников различных министерств и хозяйств.
Или, как вариант, можно собрать комбинацию отсюда:
- [Международные праздники с описанием]({{ site.baseurl }}/files/iCalendar/ical-wholeworld-out.ics)
- [Праздники Еврейские с описанием]({{ site.baseurl }}/files/iCalendar/ical-jew-out.ics)
- [Праздники Беларуси с описанием]({{ site.baseurl }}/files/iCalendar/ical-belorus-out.ics)
- [Праздники России с описанием]({{ site.baseurl }}/files/iCalendar/ical-russtate-out.ics)
- [Праздники Украины с описанием]({{ site.baseurl }}/files/iCalendar/ical-ukraine-out.ics)
И, наконец, импортировать файл(ы) в, например, Google Calendar.
Для этого рекомендуется на [calendar.google.com](https://calendar.google.com/) сначала *Cоздать новый календарь* для каждого файла в списке «Мои Календари» в настройках, а затем *Импортировать* в него ваш сгенерированный `iCal`.
<file_sep>/_posts/2016-09-25-whats-jekyll.md
---
layout: post
title: Что такое Jekyll?
tag:
- jekyll
category:
- posts
comments: true
language: ru
---
[Jekyll](http://jekyllrb.com) это простой генератор статических сайтов, прекрасно подходящий для использования в качестве быстрой и легкой платформы для ведения блога.<!--more-->
Механизм его работы прост: каталог с текстовыми файлами пропускается через конвертер соответствующего формата (Markdown или Textile), рендерер [Liquid](https://github.com/Shopify/liquid/wiki) и на выходе получается готовый к публикации статический сайт, который может работать на любом сервере. Также Jekyll является движком [GitHub Pages](http://pages.github.com/), а это значит, что вы можете размещать свой сайт или блог на серверах Github бесплатно.
Тема сайта основана на [Hyde](https://github.com/poole/hyde) Марка Отто.
### Windows:
* **Установка**:
* cmd.exe c правами администратора:
`@powershell -NoProfile -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"`
* переоткрыть cmd,
`choco install ruby -y`
* переоткрыть cmd,
`gem install github-pages`
* **Fix github warning**:
добавить переменную окружения: `JEKYLL_GITHUB_TOKEN = {{token_value}}`
* **Fix ssl error**:
добавить переменную окружения: `SSL_CERT_FILE = path\to\cacert.pem`
Не нужно устанавливать последнюю версию OpenSSL!
Перезагрузиться!
* **Использование:**
* `[bundle install]`
* `[bundle exec] jekyll serve [--port=4000]`
<file_sep>/_posts/2017-08-27-star-trek-warp.md
---
layout: post
title: Star Trek Warp Calculator
post_on_sidebar: true
comments: true
math: true
tag:
- calculator
- scifi
category:
- tools
summary: Correspondence between time, distance, velocity, and warp factor for “The Original” series and “The Next Gegeration” series.
---
Select warp scale:
<input type="radio" name="version" value="TOS" > The Original Series (before 2312)
<input type="radio" name="version" value="TNG" checked> The Next Gegeration (after 2312)
------ | -----
Warp factor | <input type="number" class="text-align-right" id="warp" step="any" min="0" value="6">
Distance | <input type="number" class="text-align-right" id="distance" step="any" value="100"> light years
<input type="button" value="Calculate" onclick="cal()">
------ | -----
Velocity | <input type="text" class="text-align-right" id="velocity" readonly> <span id="speed_of_light">c</span>
Time to pass that distance | <input type="text" class="text-align-right" id="time" readonly> <span id="measure"></span>
|
Time to reach the Pluto (33.4 au ≈ 0.0005 ly) | <input type="text" class="text-align-right" id="time_pl" readonly> <span id="measure_pl"></span>
Time to reach the Alpha Centauri (4.3 ly) | <input type="text" class="text-align-right" id="time1" readonly> <span id="measure1" ></span>
Time to reach the Ocampa planet (75000 ly) | <input type="text" class="text-align-right" id="time_oc" readonly> <span id="measure_oc"></span>
Time to cross the Milky Way (100000 ly) | <input type="text" class="text-align-right" id="time2" readonly> <span id="measure2" ></span>
Time to reach the Andromeda galaxy (2000000 ly) | <input type="text" class="text-align-right" id="time3" readonly> <span id="measure3" ></span>
### Description
#### TOS
For Star Trek: The Original Series, the warp equation is generally accepted to be ($$v$$ — velocity through space,
$$c$$ — the speed of light ($$3·10^8$$ m/s) and $$w$$ — the warp factor):
{% raw %}
$$v = w^3 c$$
{% endraw %}
#### TNG
For Star Trek: The Next Generation, the warp scale has changed.
<NAME> stated that he wanted to avoid the ever-increasing warp factors used in the original series
to force added tension to the story, and so imposed the limit of warp 10 as infinite speed.
Scale change occurred in 2312.
Warp factors were established to be based upon the amount of power required to transition from one warp plateau to another.
For example, the power to initially get to warp factor 1 was much more than the power required to maintain it;
likewise warp 2, 3, 4, and so on.
Those transitional power points rather than observed speed were then assigned the integer warp factors.
{% raw %}
$$
v = w^{ \frac{10}{3} + f(w)} c, \\
f(w) =
\begin{cases}
0, & 0 \leqslant w \leqslant 9.0 \\
-0.5 \log_{10}(10 - w), & 9.0 < w \leqslant 10.0 \\
\end{cases}
$$
{% endraw %}
<script>
function isCheck(name) {
return document.querySelector('input[name="' + name + '"]:checked');
}
function cal() {
var w = document.getElementById("warp").value;
var d = document.getElementById("distance").value;
var v;
if (isCheck('version').value === "TOS") {
v = Math.pow(w, 3);
} else { // TNG
if (w>=0 && w<=9)
v = Math.pow(w, 10 / 3);
if (w > 9 && w < 10)
v = Math.pow(w, 10 / 3 + -0.5 * Math.log10(10 - w));
else if (w == 10)
v = Infinity;
else if (w > 10)
{
document.getElementById("warp").value = 10;
alert("Maximal warp factor for TNG series is 10, it's infinite velocity.\
\nA vessel traveling at warp 10 occupied all points in the universe simultaneously.")
v = Infinity;
}
}
var t = d / v;
var t1 = 4.3 / v;
var t2 = 100000 / v;
var t3 = 2000000 / v;
var t_oc = 75000 / v;
var t_pl = 5.281E-4 * 365 * 24 / v;
var measure = "years";
var measure1 = "years";
var measure2 = "years";
var measure3 = "years";
var measure_oc = "years";
var measure_pl = "hours";
var speed_of_light = "c";
if (v == Infinity)
speed_of_light = "";
else
speed_of_light = "c";
if (t < 0.5) {
measure = "days";
t *= 365;
}
if (t1 < 0.5) {
measure1 = "days";
t1 *= 365;
}
if (t2 < 0.5) {
measure2 = "days";
t2 *= 365;
}
if (t3 < 0.5) {
measure3 = "days";
t3 *= 365;
}
if (t_oc < 0.5) {
measure_oc = "days";
t_oc *= 365;
}
if (t_pl < 0.5) {
measure_pl = "minutes";
t_pl *= 60;
}
if (t_pl < 0.5) {
measure_pl = "seconds";
t_pl *= 60;
}
document.getElementById("velocity").value = +v.toFixed(2);
document.getElementById("time").value = +t.toFixed(2);
document.getElementById("time1").value = +t1.toFixed(2);
document.getElementById("time2").value = +t2.toFixed(2);
document.getElementById("time3").value = +t3.toFixed(2);
document.getElementById("time_oc").value = +t_oc.toFixed(2);
document.getElementById("time_pl").value = +t_pl.toFixed(2);
document.getElementById("speed_of_light").innerHTML = speed_of_light;
document.getElementById("measure").innerHTML = measure;
document.getElementById("measure1").innerHTML = measure1;
document.getElementById("measure2").innerHTML = measure2;
document.getElementById("measure3").innerHTML = measure3;
document.getElementById("measure_oc").innerHTML = measure_oc;
document.getElementById("measure_pl").innerHTML = measure_pl;
}
</script>
<file_sep>/_collection/work-schedule.md
---
layout: post
title: Work Schedule
post_on_sidebar: true
date: 2016-09-27
tag:
- qt
- С++
- календарь
category:
- projects
comments: true
summary: "<a class=lightbox-image-link-left href='/images/workschedule-win10-en.png' data-lightbox='workschedule' title=''><img class='lightbox-image' style= 'width: 10rem;' src='/images/workschedule-month-en.jpg' alt='workschedule-month'></a> The app is useful for people with a rotating schedule, like bakery workers, nurses, caretakers, etc. Enter your schedule cycle and the start date of the cycle, and the app will display a calendar with your shifts for the whole year, it supports english, belarusian and russian languages."
#lightbox2:
imgfolder: /images/
images:
- name: workschedule-win10-en.png
text: Win10 workSchedule
- name: workschedule-be.png
text: Belarusian WorkSchedule
- name: workschedule-ru.png
text: Russian WorkSchedule
- name: workschedule-en.png
text: English WorkSchedule
---
**Work Schedule** is software for creating your own rotating shift calendar.
The app is useful for people with a rotating schedule, like bakery workers, nurses, caretakers, etc. Enter your schedule cycle and a start date of a cycle, and the app will display a calendar with your shifts for the whole year. There are customizable display setting: marking shifts by color, letters or images. It also supports English, Belarusian and Russian languages. You can easily create your own calendar, save it or print it.
<br>
### Download WorkSchedule for Windows (portable)
See [Github Releases Page](https://github.com/yalov/work-schedule/releases).
<br>
Screenshots:
{%include lightbox.html height='7rem'%}
<!-- include lightbox_text.html image="image-1.jpg" -->
You can play a little with icons (actually little images) in `{Work Schedule}/shifts/` folder. Images `d.png`, `n.png`, `r.png`,`h.png` are used for day, night, rest, holiday respectively.
Languages:
* English
* Russian
* Belarusian
Translation to other languages are welcome. [How to.]({% post_url 2018-05-02-qt-linguist %})
<br>
<small><small>
[<img class='lightbox-image-right' style= 'width: 4rem;' src='/images/gpl3.svg' alt='GPLv3'>](https://www.gnu.org/licenses/gpl-3.0.html)
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
</small></small>
<small><small>
[<img class='lightbox-image-right' style= 'width: 4rem;' src='/images/softpedia100free.png' alt='Softpedia Labs 100% Free Mark'>](http://www.softpedia.com/get/Desktop-Enhancements/Clocks-Time-Management/Work-Schedule.shtml#status)
This product was tested in the Softpedia Labs. Softpedia [guarantees](http://www.softpedia.com/get/Desktop-Enhancements/Clocks-Time-Management/Work-Schedule.shtml#status)
that Work Schedule is 100% Free, which means it does not contain any form of malware, including but not limited to: spyware, viruses, trojans and backdoors.
This software product was tested thoroughly and was found absolutely clean; therefore, it can be installed with no concern by any computer user.
</small></small>
<file_sep>/_includes/all_posts.html
{%- assign all_posts = '' | split: ',' -%}
{%- for collection in site.collections -%}
{%- for post in collection.docs -%}
{%- assign all_posts = all_posts | push: post -%}
{%- endfor -%}
{%- endfor -%}
{%- assign all_posts = all_posts | sort: 'date' | reverse -%}
| 357f46a25355a57b068f909f01b1dd6373f16bd3 | [
"Markdown",
"JavaScript",
"HTML",
"Ruby"
] | 20 | Markdown | yalov/yalov.github.io | d05e61ed88c6a8da5863cba8d395faf8ebce4d35 | 41470f1be4c41e199fa23ab6ff057155fb7c2391 | |
refs/heads/master | <file_sep>import React, {createContext,useContext, useReducer} from "react";
export const StateContext = createContext();
export const StateProvider = ({reducer,initialState,children}) => (
<StateContext.Provider value={useReducer(reducer, initialState)}>
{children}
</StateContext.Provider>
);
//THIS IS HOW WE USE IT INSIDE THE COMPONENT
export const useStateValue = () => useContext(StateContext);<file_sep>import firebase from "firebase";
const firebaseApp = firebase.initializeApp({
apiKey: "<KEY>",
authDomain: "clone-d6b0d.firebaseapp.com",
databaseURL: "https://clone-d6b0d.firebaseio.com",
projectId: "clone-d6b0d",
storageBucket: "clone-d6b0d.appspot.com",
messagingSenderId: "193511100053",
appId: "1:193511100053:web:dd7b93aefc50637107159c",
measurementId: "G-DZXHDJXB48"
});
export default firebaseApp;<file_sep>import React from "react";
import "./Home.css";
import banner from "./img/banner.png";
import product from "./img/shoes.png";
import mobile from "./img/mobile.png";
import tv from "./img/tv.png";
import speaker from "./img/speaker.png";
import clothe from "./img/clothe.png";
import cabel from "./img/cabel.jpg";
import woman from "./img/woman.png";
import Product from "./Product";
const Home = () =>{
return(
<div className="home">
<img
className="home__image"
src={banner}
alt="banner"
/>
<div className="home__row">
<Product
className="margin"
id="1"
title="HowInovation Creates the products thats an amazasing future"
price={11.69}
rating={5}
image={speaker}
/>
<Product
id="1"
title="HowInovation Creates the products thats an amazasing future"
price={11.69}
rating={5}
image={clothe}
/>
</div>
<div className="home__row">
<Product
id="1"
title="HowInovation Creates the products thats an amazasing future"
price={11.69}
rating={5}
image={mobile}
/>
<Product
id="1"
title="HowInovation Creates the products thats an amazasing future"
price={11.69}
rating={5}
image={woman}
/>
<Product
id="1"
title="HowInovation Creates the products thats an amazasing future"
price={11.69}
rating={5}
image={cabel}
/>
</div>
<div className="home__row">
<Product
id="1"
title="HowInovation Creates the products thats an amazasing future"
price={11.69}
rating={5}
image={tv}
/>
</div>
</div>
);
}
export default Home; | 968e7df25e4d831d92dfd7dc2efd6e6c76ba1147 | [
"JavaScript"
] | 3 | JavaScript | abdulazizcode/amazon-clone | ec35a5f642c1b1e266a922963a599acf5e2951a6 | bb99fc1ac2f51707c781eb373aef33c1274d108e | |
refs/heads/master | <repo_name>goodapiyes/LinuxCmd.Net<file_sep>/LinuxCmd.Net/Models/LinuxVmstatInfo.cs
namespace LinuxCmd.Net.Models
{
public class LinuxVmstatInfo
{
/// <summary>
/// 处于运行的状态的进程数
/// </summary>
public int run { get; set; }
/// <summary>
/// 进程被cpu以外的状态给阻断了,
/// 比如是硬盘,网络,当我们进程发一个数据包,网速快很快就能发完
/// 但是当网速太慢,就会导致b的状态
/// </summary>
public int block { get; set; }
/// <summary>
/// 磁盘读取总量 kb/s
/// </summary>
public int bi { get; set; }
/// <summary>
/// 磁盘写入总量 kb/s
/// </summary>
public int bo { get; set; }
}
}<file_sep>/LinuxCmd.Net.NetWork/NetWorker.cs
using System;
using System.IO;
using System.Threading;
using Microsoft.Extensions.Configuration;
namespace LinuxCmd.Net.NetWork
{
public class NetWorker
{
public MasterHandler Master { get; private set; }
public ClientHandler Client { get; private set; }
public void Start()
{
if (ConfigHander.GetString("type") == "master")
InitMaster();
else if (ConfigHander.GetString("type") == "worker")
InitClient();
}
private void InitMaster()
{
Master = new MasterHandler();
Master.Listening();
}
private void InitClient()
{
Client =new ClientHandler();
Client.Start();
}
public bool Dispose()
{
if (ConfigHander.GetString("type") == "master")
Master.Dispose();
else if (ConfigHander.GetString("type") == "worker")
Client.Dispose();
return true;
}
}
}<file_sep>/LinuxCmd.Net.ZTest/Program.cs
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using LinuxCmd.Net;
using LinuxCmd.Net.Commads;
using LinuxCmd.Net.Models;
namespace LinuxCmd.Net.ZTest
{
class Program
{
//you can’t get to run on Windows
static void Main(string[] args)
{
//string text = File.ReadAllText("text.txt");
//redirect:true 获取服务器命令执行结果
var ls = "ls".LinuxBash().Output;
//redirect:false 将命令执行结果重定向输出到服务器
ls = "ls".LinuxBash(false).Output;
//服务器状态对象
LinuxServerInfo server = new LinuxServerInfo();
//系统信息
var OSName = server.OSName;
$"echo {OSName}".LinuxBash(false);
//运行时长
var RunTime = server.RunTime;
$"echo {RunTime}".LinuxBash(false);
//系统负载
var LoadAverages = server.LoadAverages;
$"echo {LoadAverages}".LinuxBash(false);
//CPU状态: cpu描述,cpu核心数,cpu使用率
var cpuInfo = server.Cpu;
$"echo {cpuInfo.SerializeJSON().Replace('(',' ').Replace(')',' ')}".LinuxBash(false);
//内存状态:内存总容量,实际可用容量,已使用的容量,缓存化的容量,系统缓冲容量
var Mem = server.Mem;
$"echo {Mem.SerializeJSON()}".LinuxBash(false);
//磁盘状态:磁盘总容量,已用容量,可用容量,已用百分比
var Disk = server.Disk;
$"echo {Disk.SerializeJSON()}".LinuxBash(false);
//IO读写状态:读请求数量,写请求数量,读字节数,写字节数
var IO = server.IO;
$"echo {IO.SerializeJSON()}".LinuxBash(false);
//网络状态:接收的数据包数量,发送的数据包数量,接收字节数,发送字节数
var NetWork = server.NetWork;
$"echo {NetWork.SerializeJSON()}".LinuxBash(false);
//网络连接状态: tcp客户端IP,服务器IP,连接状态
var NetworkConnections = server.NetworkConnections;
foreach (var net in NetworkConnections)
{
$"echo {net.SerializeJSON()}".LinuxBash(false);
}
//进程列表:进程id,进程所有者的用户名,虚拟内存使用量,物理内存使用量,进程状态,CPU使用率,进程命令名
var Tasks = server.Tasks;
for (int i = 0; i < 6; i++)
{
$"echo {Tasks[i].SerializeJSON()}".LinuxBash(false);
}
Console.WriteLine("Press any key to exit");
Console.ReadLine();
}
}
public static class JsonHelper
{
public static string SerializeJSON<T>(this T data)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(data);
}
public static T DeserializeJSON<T>(this string json)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
}
}
}
<file_sep>/LinuxCmd.Net/Commads/Sar.cs
using System;
using System.Text.RegularExpressions;
using LinuxCmd.Net.Models;
namespace LinuxCmd.Net.Commads
{
public class Sar
{
public virtual LinuxSarInfo GetLinuxSarInfo(string input)
{
Match match = Regex.Match(input, @"Average:\s+eth0\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)");
if (match.Success)
{
LinuxSarInfo info = new LinuxSarInfo();
info.ReceivedPacket = Convert.ToDouble(match.Groups[1].Value);
info.SentPacket = Convert.ToDouble(match.Groups[2].Value);
info.ReceivedBytes = Convert.ToDouble(match.Groups[3].Value);
info.SentBytes = Convert.ToDouble(match.Groups[4].Value);
return info;
}
return null;
}
}
}<file_sep>/LinuxCmd.Net/Models/LinuxSarInfo.cs
namespace LinuxCmd.Net.Models
{
public class LinuxSarInfo
{
/// <summary>
/// 接收的数据包
/// </summary>
public double ReceivedPacket { get; set; }
/// <summary>
/// 发送的数据包
/// </summary>
public double SentPacket { get; set; }
/// <summary>
/// 接收的字节数 kb/s
/// </summary>
public double ReceivedBytes { get; set; }
/// <summary>
/// 发送的字节数 kb/s
/// </summary>
public double SentBytes { get; set; }
}
}<file_sep>/LinuxCmd.Net/Models/LinuxDfInfo.cs
namespace LinuxCmd.Net.Models
{
public class LinuxDfInfo
{
/// <summary>
/// 文件系统
/// </summary>
public string Filesystem { get; set; }
/// <summary>
/// 容量 MB
/// </summary>
public double Size { get; set; }
/// <summary>
/// 已用 MB
/// </summary>
public double Used { get; set; }
/// <summary>
/// 可用 MB
/// </summary>
public double Avail { get; set; }
/// <summary>
/// 已用%
/// </summary>
public double UseUsage { get; set; }
/// <summary>
/// 挂载点
/// </summary>
public string Mounted { get; set; }
}
}<file_sep>/LinuxCmd.Net/Commads/Vmstat.cs
using System;
using System.Text.RegularExpressions;
using LinuxCmd.Net.Models;
namespace LinuxCmd.Net.Commads
{
public class Vmstat
{
public virtual LinuxVmstatInfo GetLinuxVmstatInfo(string input)
{
Match match = Regex.Match(input, @"(\d+)\s+(\d+)\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+(\d+)\s+(\d+)");
if (match.Success)
{
LinuxVmstatInfo info = new LinuxVmstatInfo();
info.run = Convert.ToInt32(match.Groups[1].Value);
info.block = Convert.ToInt32(match.Groups[2].Value);
info.bi = Convert.ToInt32(match.Groups[3].Value);
info.bo = Convert.ToInt32(match.Groups[4].Value);
return info;
}
return null;
}
}
}<file_sep>/LinuxCmd.Net.NetWork/MasterHandler.cs
using System;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Cowboy.Sockets.Core;
namespace LinuxCmd.Net.NetWork
{
public class MasterHandler
{
public string Ip { get; private set; }
public int? Port { get; private set; }
public TcpSocketServer Server;
public ConcurrentDictionary<string, TcpSocketSession> Sessions { get; private set; }
public MasterHandler()
{
this.Ip = ConfigHander.GetString("master:ip");
this.Port = ConfigHander.GetInt("master:port");
Sessions=new ConcurrentDictionary<string, TcpSocketSession>();
}
public void Listening()
{
if (string.IsNullOrEmpty(Ip) || !Port.HasValue)
{
LogHelper.Logger.Error("ip,port is not available !!!");
throw new Exception("ip,port is not available !!!");
}
var config = new TcpSocketServerConfiguration();
Server = new TcpSocketServer(IPAddress.Parse(Ip), Port.Value, config);
Server.ClientConnected += ClientConnected;
Server.ClientDisconnected += ClientDisconnected;
Server.ClientDataReceived += ClientDataReceived;
Server.Listen();
LogHelper.Logger.Information("Server Listening...");
}
public bool Issue(string ip,string cmd)
{
try
{
foreach (var session in Sessions)
{
if(session.Key.Contains(ip))
Server.SendTo(session.Value.SessionKey,Encoding.UTF8.GetBytes(cmd));
}
}
catch (Exception e)
{
LogHelper.Logger.Error($"Issue {ip},Error:{e.Message},{e.StackTrace}");
return false;
}
return true;
}
private void ClientConnected(object sender, TcpClientConnectedEventArgs e)
{
var key = e.Session.RemoteEndPoint.ToString();
Sessions.AddOrUpdate(key, e.Session, (k, o) => o);
Console.WriteLine($"客户端 {e.Session.RemoteEndPoint} 已连接 {e.Session}.");
}
private void ClientDisconnected(object sender, TcpClientDisconnectedEventArgs e)
{
var key = e.Session.RemoteEndPoint.ToString();
TcpSocketSession removeSession;
if(Sessions.ContainsKey(key))
Sessions.TryRemove(key, out removeSession);
Console.WriteLine($"客户端 {e.Session} 关闭了连接.");
}
private void ClientDataReceived(object sender, TcpClientDataReceivedEventArgs e)
{
var text = Encoding.UTF8.GetString(e.Data, e.DataOffset, e.DataLength);
Console.Write(string.Format("客户端 : {0} {1} --> ", e.Session.RemoteEndPoint, e.Session));
if (e.DataLength < 256)
{
Console.WriteLine(text);
}
else
{
Console.WriteLine("{0} Bytes", e.DataLength);
}
Server.SendTo(e.Session, Encoding.UTF8.GetBytes("ok"));
}
public void Dispose()
{
Server.Shutdown();
Server = null;
}
}
}<file_sep>/LinuxCmd.Net/Commads/Netstat.cs
using System.Collections.Generic;
using System.Text.RegularExpressions;
using LinuxCmd.Net.Models;
namespace LinuxCmd.Net.Commads
{
public class Netstat
{
public virtual List<LinuxNetstatInfo> GetLinuxNetstatInfos(string input)
{
MatchCollection matches = Regex.Matches(input, @"(tcp)\s+\d+\s+\d+\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)");
List<LinuxNetstatInfo> list = new List<LinuxNetstatInfo>();
foreach (Match match in matches)
{
if (match.Success)
{
LinuxNetstatInfo info = new LinuxNetstatInfo();
info.Proto = match.Groups[1].Value;
info.LocalAddress = match.Groups[2].Value;
info.ForeignAddress = match.Groups[3].Value;
info.State = match.Groups[4].Value;
info.ProgramName = match.Groups[5].Value;
list.Add(info);
}
}
return list;
}
}
}<file_sep>/LinuxCmd.Net.NetWork/CommandHandler.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Newtonsoft.Json;
namespace LinuxCmd.Net.NetWork
{
public class CommandHandler
{
public static string HeartBeatCmd()
{
//if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
// return "not support for current os";
LinuxServerInfo info = new LinuxServerInfo();
StringBuilder builder = new StringBuilder();
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
return $"{CommandTag.HeartBeat.GetValue()}|0|End";
//测试
//builder.AppendFormat("|{0}", "CentOS Linux release 7.6.1810");
//builder.AppendFormat("|{0}", "9天 7小时 09分钟");
//builder.AppendFormat("|{0}", "1.13,1.33,1.55");
//builder.AppendFormat("|{0}", "10");
//builder.AppendFormat("|{0}", "3.1");
//builder.AppendFormat("|{0}", "1");
//builder.AppendFormat("|{0}", "7686788,12555555");
//builder.AppendFormat("|End");
builder.AppendFormat("{0}|{1}", CommandTag.HeartBeat.GetValue(),1);
builder.AppendFormat("|{0}", info.OSName);
builder.AppendFormat("|{0}", info.RunTime);
builder.AppendFormat("|{0}", info.LoadAverages);
builder.AppendFormat("|{0}", info.Cpu.CpuUsage);
builder.AppendFormat("|{0}", info.Mem?.MemUsage);
builder.AppendFormat("|{0}", info.Disk?.UseUsage);
builder.AppendFormat("|{0},{1}", info.IO?.ReadBytes, info.IO?.WriteBytes);
builder.AppendFormat("|End");
return builder.ToString();
}
public static string GetCmdName(string data)
{
if (!data.Contains('|'))
return null;
return data.Split('|')[0];
}
public static bool GetCmdValid(string data)
{
if (!data.Contains('|'))
return false;
return data.Split('|')[1].Contains("1");
}
}
public enum CommandTag
{
HeartBeat = 1001
}
public static class Extensions
{
public static int GetValue(this Enum instance)
{
return (int)System.Enum.Parse(instance.GetType(), instance.ToString(), true);
}
public static T ExToObject<T>(this string json)
{
return ToObject<T>(json);
}
public static string ExToJson(this object obj)
{
return ToJson(obj);
}
/// <summary>
/// 将Json字符串转换为对象
/// </summary>
/// <param name="json">Json字符串</param>
public static T ToObject<T>(string json)
{
if (string.IsNullOrWhiteSpace(json))
return default(T);
return JsonConvert.DeserializeObject<T>(json);
}
/// <summary>
/// 将对象转换为Json字符串
/// </summary>
/// <param name="target">目标对象</param>
/// <param name="isConvertToSingleQuotes">是否将双引号转成单引号</param>
public static string ToJson(object target, bool isConvertToSingleQuotes = false)
{
if (target == null)
return "{}";
var result = JsonConvert.SerializeObject(target);
if (isConvertToSingleQuotes)
result = result.Replace("\"", "'");
return result;
}
}
}<file_sep>/LinuxCmd.Net/Models/LinuxTopInfo.cs
using System.Collections.Generic;
namespace LinuxCmd.Net.Models
{
public class LinuxTopInfo
{
#region 运行时间,运行状态,负载
/// <summary>
/// 统计时间
/// </summary>
public string Time { get; set; }
/// <summary>
/// 服务器运行天数
/// </summary>
public int Days { get; set; }
/// <summary>
/// 当前服务器SSH登录人数
/// </summary>
public int Users { get; set; }
/// <summary>
/// 当前服务器负载
/// </summary>
public string Averages { get; set; }
#endregion
#region 进程统计
/// <summary>
/// 进程总数
/// </summary>
public int TaskTotal { get; set; }
/// <summary>
/// 正在运行进程数
/// </summary>
public int RunningCount { get; set; }
/// <summary>
/// 睡眠进程数
/// </summary>
public int SleepingCount { get; set; }
/// <summary>
/// 停止进程数
/// </summary>
public int StoppedCount { get; set; }
/// <summary>
/// 僵尸进程数
/// </summary>
public int ZombieCount { get; set; }
#endregion
#region cpu统计
/// <summary>
/// 用户空间占用CPU百分比
/// </summary>
public double UserCpu { get; set; }
/// <summary>
/// 内核空间占用CPU百分比
/// </summary>
public double SystemCpu { get; set; }
/// <summary>
/// 用户进程空间内改变过优先级的进程占用CPU百分比
/// </summary>
public double NiCpu { get; set; }
/// <summary>
/// 空闲CPU百分比
/// </summary>
public double FreeCpu { get; set; }
/// <summary>
/// 等待输入输出的CPU时间百分比
/// </summary>
public double WaitCpu { get; set; }
#endregion
#region 物理内存统计
/// <summary>
/// 物理内存总量
/// </summary>
public double MemTotal { get; set; }
/// <summary>
/// 空闲内存总量
/// </summary>
public double MemFree { get; set; }
/// <summary>
/// 使用的物理内存总量
/// </summary>
public double MemUsed { get; set; }
/// <summary>
/// 用作内核缓存的内存量
/// </summary>
public double MemCache { get; set; }
#endregion
#region 虚拟内存统计
/// <summary>
/// 交换分区总量
/// </summary>
public double SwapTotal { get; set; }
/// <summary>
/// 空闲交换区总量
/// </summary>
public double SwapFree { get; set; }
/// <summary>
/// 使用的交换区总量
/// </summary>
public double SwapUsed { get; set; }
/// <summary>
/// 缓冲的交换区总量。
/// </summary>
public double SwapCache { get; set; }
#endregion
/// <summary>
/// 进程信息列表
/// </summary>
public List<LinuxTopInfo_TaskDetail> TaskDetails { get; set; }
}
public class LinuxTopInfo_TaskDetail
{
/// <summary>
/// 进程id
/// </summary>
public string Pid { get; set; }
/// <summary>
/// 进程所有者的用户名
/// </summary>
public string User { get; set; }
/// <summary>
/// 进程使用的虚拟内存总量
/// </summary>
public double Virt { get; set; }
/// <summary>
/// 进程使用的、未被换出的物理内存大小
/// </summary>
public double Res { get; set; }
/// <summary>
/// 共享内存大小
/// </summary>
public double Shr { get; set; }
/// <summary>
///进程状态。
///D= 不可中断的睡眠状态
///R= 运行
///S= 睡眠
///T= 跟踪/停止
///Z= 僵尸进程
/// </summary>
public string Status { get; set; }
/// <summary>
/// 上次更新到现在的CPU时间占用百分比
/// </summary>
public double Cpu { get; set; }
/// <summary>
/// 进程使用的物理内存百分比
/// </summary>
public double Mem { get; set; }
/// <summary>
/// 进程使用的CPU时间总计
/// </summary>
public string Time { get; set; }
/// <summary>
/// 命令名/命令行
/// </summary>
public string Commad { get; set; }
}
}
<file_sep>/MySocket-master/README.md
Socket服务端与客户端的封装,支持.NETCore
# 安装
> Install-Package MySocket
# 服务端(多线程)
```csharp
var server = new ServerSocket(19990); //监听0.0.0.0:19990
server.Receive += (a, b) => {
Console.WriteLine("{0} 接受到了消息{1}:{2}", DateTime.Now, b.Receives, b.Messager);
b.AcceptSocket.Write(b.Messager);
};
server.Accepted += (a, b) => {
Console.WriteLine("{0} 新连接:{1}", DateTime.Now, b.Accepts);
};
server.Closed += (a, b) => {
Console.WriteLine("{0} 关闭了连接:{1}", DateTime.Now, b.AcceptSocketId);
};
server.Error += (a, b) => {
Console.WriteLine("{0} 发生错误({1}):{2}", DateTime.Now, b.Errors,
b.Exception.Message + b.Exception.StackTrace);
};
server.Start();
Console.ReadKey();
```
# 服务端(异步),理论上性能最强
```csharp
var server = new ServerSocketAsync(19990); //监听0.0.0.0:19990
server.Receive += (a, b) => {
Console.WriteLine("{0} 接受到了消息{1}:{2}", DateTime.Now, b.Receives, b.Messager);
b.AcceptSocket.Write(b.Messager);
};
server.Accepted += (a, b) => {
Console.WriteLine("{0} 新连接:{1}", DateTime.Now, b.Accepts);
};
server.Closed += (a, b) => {
Console.WriteLine("{0} 关闭了连接:{1}", DateTime.Now, b.AcceptSocketId);
};
server.Error += (a, b) => {
Console.WriteLine("{0} 发生错误({1}):{2}", DateTime.Now, b.Errors,
b.Exception.Message + b.Exception.StackTrace);
};
server.Start();
Console.ReadKey();
```
# 客户端
```csharp
var client = new ClientSocket();
client.Error += (sender, e) => {
Console.WriteLine("[" + DateTime.Now.ToString("MM-dd HH:mm:ss") + "] "
+ e.Exception.Message + e.Exception.StackTrace);
};
client.Receive += (sender, e) => {
switch (e.Messager.Action) {
}
};
client.Connect("localhost", 19990);
SocketMessager messager = new SocketMessager("GetDatabases", 1);
object dbs = null;
//以下代码等于同步,直到服务端响应(会执行委托)或超时
client.Write(messager, (sender2, e2) => {
//服务端正常响应会执行这里
dbs = e2.Messager;
});
Console.WriteLine(dbs);
Console.WriteLine("sldkjglsjdglksdg");
//若不传递第二个委托参数,线程不会等待结果,服务端响应后由 client.Receive 处理
//Console.ReadKey();
client.Close();
```<file_sep>/LinuxCmd.Net.NetWork.Test/Program.cs
using System;
namespace LinuxCmd.Net.NetWork.Test
{
class Program
{
static void Main(string[] args)
{
NetWorker net = new NetWorker();
net.Start();
Console.ReadLine();
}
}
}
<file_sep>/README.md
# LinuxCmd.Net
.net core linux cmd helper.
1. Running Linux CMD.
2. Get linux server status, include CPU, memory, and networking.
## Example
```C#
//redirect:true 获取服务器命令执行结果
var ls = "ls".LinuxBash().Output;
//redirect:false 将命令执行结果重定向输出到服务器
ls = "ls".LinuxBash(false).Output;
//服务器状态对象
LinuxServerInfo server = new LinuxServerInfo();
//系统信息
var OSName = server.OSName;
$"echo {OSName}".LinuxBash(false);
//运行时长
var RunTime = server.RunTime;
$"echo {RunTime}".LinuxBash(false);
//系统负载
var LoadAverages = server.LoadAverages;
$"echo {LoadAverages}".LinuxBash(false);
//CPU状态: cpu描述,cpu核心数,cpu使用率
var cpuInfo = server.Cpu;
$"echo {cpuInfo.SerializeJSON().Replace('(',' ').Replace(')',' ')}".LinuxBash(false);
//内存状态:内存总容量,实际可用容量,已使用的容量,缓存化的容量,系统缓冲容量
var Mem = server.Mem;
$"echo {Mem.SerializeJSON()}".LinuxBash(false);
//磁盘状态:磁盘总容量,已用容量,可用容量,已用百分比
var Disk = server.Disk;
$"echo {Disk.SerializeJSON()}".LinuxBash(false);
//IO读写状态:读请求数量,写请求数量,读字节数,写字节数
var IO = server.IO;
$"echo {IO.SerializeJSON()}".LinuxBash(false);
//网络状态:接收的数据包数量,发送的数据包数量,接收字节数,发送字节数
var NetWork = server.NetWork;
$"echo {NetWork.SerializeJSON()}".LinuxBash(false);
//网络连接状态: tcp客户端IP,服务器IP,连接状态
var NetworkConnections = server.NetworkConnections;
foreach (var net in NetworkConnections)
{
$"echo {net.SerializeJSON()}".LinuxBash(false);
}
//进程列表:进程id,进程所有者的用户名,虚拟内存使用量,物理内存使用量,进程状态,CPU使用率,进程命令名
var Tasks = server.Tasks;
for (int i = 0; i < 6; i++)
{
$"echo {Tasks[i].SerializeJSON()}".LinuxBash(false);
}
```<file_sep>/LinuxCmd.Net/Commads/Top.cs
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using LinuxCmd.Net.Models;
namespace LinuxCmd.Net.Commads
{
/// <summary>
/// top version 3.3.10
/// </summary>
public class Top
{
public virtual LinuxTopInfo GetTop(string input)
{
var rows = input.Split('\n');
if (rows.Length < 5)
return null;
LinuxTopInfo info=new LinuxTopInfo();
//统计时间,服务器负载
var stas = rows[0];
info.Time = Utility.GetSingleByRgx(stas, @"top\s+-\s+(\S+)\s+up");
info.Days = Convert.ToInt32(Utility.GetSingleByRgx(stas, @"(\d+)\s+days"));
info.Users = Convert.ToInt32(Utility.GetSingleByRgx(stas, @"(\d+)\s+user"));
info.Averages = $"{Utility.GetSingleByRgx(stas, @":\s+(\d+\.\d\d),")},{Utility.GetSingleByRgx(stas, @",\s+(\d+\.\d\d),")},{Utility.GetSingleByRgx(stas, @",\s+(\d+\.\d\d)")}";
//进程统计
var tasks = rows[1];
info.TaskTotal = Convert.ToInt32(Utility.GetSingleByRgx(tasks, @"(\d+)\s+total"));
info.RunningCount = Convert.ToInt32(Utility.GetSingleByRgx(tasks, @"(\d+)\s+running"));
info.SleepingCount = Convert.ToInt32(Utility.GetSingleByRgx(tasks, @"(\d+)\s+sleeping"));
info.StoppedCount = Convert.ToInt32(Utility.GetSingleByRgx(tasks, @"(\d+)\s+stopped"));
info.ZombieCount = Convert.ToInt32(Utility.GetSingleByRgx(tasks, @"(\d+)\s+zombie"));
//cpu数值
var cpus = rows[2];
info.UserCpu = Convert.ToDouble(Utility.GetSingleByRgx(cpus, @"(\d+\.\d+)\s+us"));
info.SystemCpu = Convert.ToDouble(Utility.GetSingleByRgx(cpus, @"(\d+\.\d+)\s+sy"));
info.NiCpu = Convert.ToDouble(Utility.GetSingleByRgx(cpus, @"(\d+\.\d+)\s+ni"));
info.FreeCpu = Convert.ToDouble(Utility.GetSingleByRgx(cpus, @"(\d+\.\d+)\s+id"));
info.WaitCpu = Convert.ToDouble(Utility.GetSingleByRgx(cpus, @"(\d+\.\d+)\s+wa"));
var hi = Utility.GetSingleByRgx(cpus, @"(\d+\.\d+)\s+hi");
var si = Utility.GetSingleByRgx(cpus, @"(\d+\.\d+)\s+si");
var st = Utility.GetSingleByRgx(cpus, @"(\d+\.\d+)\s+st");
//内存数值
var mems = rows[3];
info.MemTotal = Convert.ToDouble(Utility.GetSingleByRgx(mems, @"(\d+)\s+total")) / 1024;
info.MemFree = Convert.ToDouble(Utility.GetSingleByRgx(mems, @"(\d+)\s+free")) / 1024;
info.MemUsed = Convert.ToDouble(Utility.GetSingleByRgx(mems, @"(\d+)\s+used")) / 1024;
info.MemCache = Convert.ToDouble(Utility.GetSingleByRgx(mems, @"(\d+)\s+buff/cache")) / 1024;
//虚拟内存数值
var swap = rows[4];
info.SwapTotal = Convert.ToDouble(Utility.GetSingleByRgx(swap, @"(\d+)\s+total")) / 1024;
info.SwapFree = Convert.ToDouble(Utility.GetSingleByRgx(swap, @"(\d+)\s+free")) / 1024;
info.SwapUsed = Convert.ToDouble(Utility.GetSingleByRgx(swap, @"(\d+)\s+used")) / 1024;
info.SwapCache = Convert.ToDouble(Utility.GetSingleByRgx(swap, @"(\d+)\s+avail")) / 1024;
info.TaskDetails= GetTaskDetailsByRgx(input);
return info;
}
public virtual List<LinuxTopInfo_TaskDetail> GetTaskDetailsByRgx(string input)
{
List<LinuxTopInfo_TaskDetail> details= new List<LinuxTopInfo_TaskDetail>();
var matchs = Regex.Matches(input, @"\s+(\d+)\s+(\S+)\s+\d+\s+\d+\s+(\d+)\s+(\d+)\s+(\d+)\s+(\w+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s*");
foreach (Match match in matchs)
{
if (match.Success)
{
var detail = new LinuxTopInfo_TaskDetail();
detail.Pid = match.Groups[1].Value;
detail.User = match.Groups[2].Value;
detail.Virt = Convert.ToDouble(match.Groups[3].Value) / 1024;
detail.Res = Convert.ToDouble(match.Groups[4].Value) / 1024;
detail.Shr = Convert.ToDouble(match.Groups[5].Value) / 1024;
detail.Status = match.Groups[6].Value;
detail.Cpu = Convert.ToDouble(match.Groups[7].Value);
detail.Mem = Convert.ToDouble(match.Groups[8].Value);
detail.Time = match.Groups[9].Value;
detail.Commad = match.Groups[10].Value;
details.Add(detail);
}
}
return details;
}
}
}
<file_sep>/LinuxCmd.Net/LinuxServerInfo.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.IO;
using System.Text.RegularExpressions;
using LinuxCmd.Net.Commads;
using LinuxCmd.Net.Models;
namespace LinuxCmd.Net
{
public class LinuxServerInfo
{
/// <summary>
/// 操作系统信息
/// </summary>
public string OSName => GetOSName();
/// <summary>
/// 累积运行时间
/// </summary>
public string RunTime => GetRunTime();
/// <summary>
/// 系统负载,任务队列的平均长度
/// </summary>
public string LoadAverages => GetLoadAverages();
/// <summary>
/// cpu信息
/// </summary>
public CpuInfo Cpu => GetCpu();
/// <summary>
/// 内存信息
/// </summary>
public MemInfo Mem => GetMem();
/// <summary>
/// 磁盘信息
/// </summary>
public LinuxDfInfo Disk => LinuxHelper.LinuxDisk();
/// <summary>
/// 磁盘IO读写信息
/// </summary>
public IOInfo IO => GetIO();
/// <summary>
/// 网络信息
/// </summary>
public LinuxSarInfo NetWork => LinuxHelper.LinuxSar();
/// <summary>
/// 进程列表信息
/// </summary>
public List<LinuxTopInfo_TaskDetail> Tasks => GetTasks();
/// <summary>
/// 网络连接列表信息
/// </summary>
public List<LinuxNetstatInfo> NetworkConnections => LinuxHelper.LinuxNetstats();
private Top top =new Top();
#region Realize
protected virtual string GetOSName()
{
var os = Utility.GetSingleByRgx("lsb_release -a".LinuxBash().Output, @"Description:\s+(\S+\s+\S+\s+\S+\s+\S+)");
if (string.IsNullOrEmpty(os))
return "NaN";
return os;
}
protected virtual string GetRunTime()
{
var text = Utility.GetSingleByRgx("top -b -n 1".LinuxBash().Output, @"up\s+(\d+\s+days,\s+\d+:\d+),");
if (string.IsNullOrEmpty(text))
return "NaN";
var days = Utility.GetSingleByRgx(text, @"(\d+)\s+days,");
var hours = Utility.GetSingleByRgx(text, @",\s+(\d+):");
var minutes = Utility.GetSingleByRgx(text, @"\d+:(\d+)");
return $"{days}天 {hours}小时 {minutes}分钟";
}
protected virtual string GetLoadAverages()
{
var aver = Utility.GetSingleByRgx("top -b -n 1".LinuxBash().Output, @"load\s+average:\s+(.+)\n");
if (string.IsNullOrEmpty(aver))
return "NaN";
else
return aver.Replace(" ", "");
}
protected virtual CpuInfo GetCpu()
{
CpuInfo info = new CpuInfo();
var cores = Utility.GetSingleByRgx("cat /proc/cpuinfo | grep name | cut -f2 -d: | uniq -c".LinuxBash().Output, @"(\d+)\s+");
if (string.IsNullOrEmpty(cores))
info.CpuCores = -1;
else
info.CpuCores = Convert.ToInt32(cores);
var cpuName = Utility.GetSingleByRgx("cat /proc/cpuinfo | grep name | cut -f2 -d: | uniq -c".LinuxBash().Output, @"\d+\s+(\S+.+)");
if (string.IsNullOrEmpty(cpuName))
info.CpuName = "NaN";
else
info.CpuName = cpuName;
var cpuUsage = Utility.GetSingleByRgx("top -b -n 1".LinuxBash().Output, @"ni,\s*(\S+)\s+id,");
if (string.IsNullOrEmpty(cpuUsage))
info.CpuUsage = -1;
else
{
info.CpuUsage = (100 - Convert.ToDouble(cpuUsage)).MathRound();
}
return info;
}
protected virtual MemInfo GetMem()
{
MemInfo info = new MemInfo();
var total = Utility.GetSingleByRgx("cat /proc/meminfo |grep MemTotal".LinuxBash().Output, @"MemTotal:\s+(\d+)\s+kB");
if (string.IsNullOrEmpty(total))
info.MemTotal = -1;
else
info.MemTotal = Convert.ToInt32(total) / 1024;
var available = Utility.GetSingleByRgx("cat /proc/meminfo |grep MemAvailable".LinuxBash().Output, @"MemAvailable:\s+(\d+)\s+kB");
if (string.IsNullOrEmpty(available))
info.MemAvailable = -1;
else
info.MemAvailable = Convert.ToInt32(available) / 1024;
var used = Utility.GetSingleByRgx("free -m".LinuxBash().Output, @"Mem:\s+\S+\s+(\S+)\s+");
if (string.IsNullOrEmpty(used))
info.MemUsed = -1;
else
info.MemUsed = Convert.ToInt32(used);
var cached = Utility.GetSingleByRgx("cat /proc/meminfo |grep Cached".LinuxBash().Output, @"Cached:\s+(\d+)\s+kB");
if (string.IsNullOrWhiteSpace(cached))
info.MemCached = -1;
else
info.MemCached = Convert.ToInt32(cached) / 1024;
var buffers = Utility.GetSingleByRgx("cat /proc/meminfo |grep Buffers".LinuxBash().Output, @"Buffers:\s+(\d+)\s+kB");
if (string.IsNullOrEmpty(buffers))
info.MemBuffers = -1;
else
info.MemBuffers = Convert.ToInt32(buffers) / 1024;
info.MemUsage = (100 - Convert.ToDouble((info.MemAvailable * 1.00) / (info.MemTotal * 1.00) * 100)).MathRound();
return info;
}
protected virtual IOInfo GetIO()
{
IOInfo info = new IOInfo();
var result = "sar -b 1 1".LinuxBash().Output;
if (string.IsNullOrWhiteSpace(result))
return info;
Match match = Regex.Match(result, @"Average:\s+\S+\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)");
if (match.Success)
{
info.ReadCount = Convert.ToDouble(match.Groups[1].Value).MathRound();
info.WriteCount = Convert.ToDouble(match.Groups[2].Value).MathRound();
info.ReadBytes = Convert.ToDouble(match.Groups[3].Value).MathRound();
info.WriteBytes = Convert.ToDouble(match.Groups[4].Value).MathRound();
}
return info;
}
protected virtual List<LinuxTopInfo_TaskDetail> GetTasks()
{
return top.GetTaskDetailsByRgx("top -b -n 1".LinuxBash().Output);
}
#endregion
}
public class CpuInfo
{
/// <summary>
/// cpu描述
/// </summary>
public string CpuName { get; set; }
/// <summary>
/// cpu核心数
/// </summary>
public int CpuCores { get; set; }
/// <summary>
/// cpu使用率
/// </summary>
public double CpuUsage { get; set; }
}
public class MemInfo
{
/// <summary>
/// 内存总容量
/// </summary>
public int MemTotal { get; set; }
/// <summary>
/// 实际可用内存 MB
/// </summary>
public int MemAvailable { get; set; }
/// <summary>
/// 已使用的内存 MB
/// </summary>
public int MemUsed { get; set; }
/// <summary>
/// 缓存化的内存 MB
/// </summary>
public int MemCached { get; set; }
/// <summary>
/// 系统缓冲 MB
/// </summary>
public int MemBuffers { get; set; }
/// <summary>
/// 内存相对使用率
/// </summary>
public double MemUsage { get; set; }
}
public class IOInfo
{
public double ReadCount { get; set; }
public double WriteCount { get; set; }
public double ReadBytes { get; set; }
public double WriteBytes { get; set; }
}
}<file_sep>/LinuxCmd.Net.NetWork/ClientHandler.cs
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Cowboy.Sockets.Core;
namespace LinuxCmd.Net.NetWork
{
public class ClientHandler
{
public string Ip { get; private set; }
public int? Port { get; private set; }
public int? ReconnectionCount { get; private set; }
public int? TimeOut { get; private set; }
public int? Polling { get; private set; }
public int Reconnectioned { get; private set; }
public System.Threading.Timer PollingTimer { get; private set; }
public TcpSocketClient Client;
public bool downTag = false;
public ClientHandler()
{
LoadConfig();
}
public void Start()
{
LogHelper.Logger.Information("Client Start...");
CreateTcpClient();
PollingTimer = new System.Threading.Timer(Heartbeat, this, Polling.Value * 1000, Polling.Value * 1000);
}
private void LoadConfig()
{
ConfigHander.configuration.Reload();
this.Ip = ConfigHander.GetString("master:ip");
this.Port = ConfigHander.GetInt("master:port");
this.ReconnectionCount = ConfigHander.GetInt("worker:reconnection");
this.TimeOut = ConfigHander.GetInt("worker:timeout");
this.Polling = ConfigHander.GetInt("worker:polling");
}
private void CreateTcpClient()
{
if (string.IsNullOrEmpty(Ip) || !Port.HasValue)
{
LogHelper.Logger.Error("ip,port is not available !!!");
throw new Exception("ip,port is not available !!");
}
var config = new TcpSocketClientConfiguration();
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(Ip), Port.Value);
Client = new TcpSocketClient(ipEndPoint, config);
Client.ServerConnected += ServerConnected;
Client.ServerDisconnected += ServerDisconnected;
Client.ServerDataReceived += ServerDataReceived;
Client.Connect();
}
private void Heartbeat(object obj)
{
try
{
if (Reconnectioned >= ReconnectionCount)
{
//重连熔断降级至24小时一次轮询
if (!downTag)
{
LogHelper.Logger.Error($"{ReconnectionCount}次重连失败,降级轮询频率至24小时一次");
PollingTimer.Change(24 * 60 * 60 * 1000, 24 * 60 * 60 * 1000);
}
return;
}
if (Client == null)
CreateTcpClient();
if (Client.State == TcpSocketConnectionState.Connected)
{
Client.Send(Encoding.UTF8.GetBytes(CommandHandler.HeartBeatCmd()));
Reconnectioned = 0;
//恢复轮询正常状态
downTag = true;
PollingTimer.Change(Polling.Value * 1000, Polling.Value * 1000);
}
else
{
Reconnectioned++;
}
}
catch (Exception ex)
{
LogHelper.Logger.Error($"Heartbeat Error:"+ex.Message+ex.StackTrace);
}
}
private void ServerConnected(object sender, TcpServerConnectedEventArgs e)
{
Console.WriteLine($"服务器 {e.RemoteEndPoint} 已连接.");
}
private void ServerDisconnected(object sender, TcpServerDisconnectedEventArgs e)
{
Console.WriteLine($"服务器 {e.RemoteEndPoint} 断开连接.");
}
private void ServerDataReceived(object sender, TcpServerDataReceivedEventArgs e)
{
var text = Encoding.UTF8.GetString(e.Data, e.DataOffset, e.DataLength);
Console.Write($"服务器 : {e.Client.RemoteEndPoint} --> ");
if (e.DataLength < 256)
{
Console.WriteLine(text);
}
else
{
Console.WriteLine("{0} Bytes", e.DataLength);
}
}
public void Dispose()
{
Client.Close();
Client.Dispose();
Client = null;
PollingTimer.Dispose();
PollingTimer = null;
}
}
}<file_sep>/LinuxCmd.Net.NetWork/ConfigHander.cs
using System;
using Microsoft.Extensions.Configuration;
namespace LinuxCmd.Net.NetWork
{
public class ConfigHander
{
public static IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("app.json")
.Build();
public static string GetString(string key)
{
return configuration[key];
}
public static int GetInt(string key)
{
return Convert.ToInt32(configuration[key]);
}
}
}<file_sep>/LinuxCmd.Net/Models/LinuxNetstatInfo.cs
namespace LinuxCmd.Net.Models
{
public class LinuxNetstatInfo
{
public string Proto { get; set; }
public string LocalAddress { get; set; }
public string ForeignAddress { get; set; }
public string State { get; set; }
public string ProgramName { get; set; }
}
}<file_sep>/LinuxCmd.Net/Commads/Df.cs
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using LinuxCmd.Net.Models;
namespace LinuxCmd.Net.Commads
{
public class Df
{
public virtual List<LinuxDfInfo> GetDfInfos(string input)
{
var matchs = Regex.Matches(input, @"\s*(\S+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\S+)%\s+(\S+)");
List<LinuxDfInfo> list = new List<LinuxDfInfo>();
foreach (Match match in matchs)
{
if (match.Success)
{
LinuxDfInfo info = new LinuxDfInfo();
info.Filesystem = match.Groups[1].Value;
info.Size = Convert.ToDouble(match.Groups[2].Value) /1024;
info.Used = Convert.ToDouble(match.Groups[3].Value) / 1024;
info.Avail = Convert.ToDouble(match.Groups[4].Value) / 1024;
info.UseUsage = Convert.ToDouble(match.Groups[5].Value);
info.Mounted = match.Groups[6].Value;
list.Add(info);
}
}
return list;
}
public virtual LinuxDfInfo GetDiskInfo(string input)
{
return GetDfInfos(input)[0];
}
}
}<file_sep>/LinuxCmd.Net/Utility.cs
using System;
using System.Text.RegularExpressions;
namespace LinuxCmd.Net
{
public static class Utility
{
public static string GetSingleByRgx(string input, string pattern)
{
if (string.IsNullOrWhiteSpace(input))
return "";
var match = Regex.Match(input, pattern);
return match.Success ? match.Groups[1].Value : "";
}
public static double MathRound(this double d)
{
return Math.Round(d, 1);
}
}
}<file_sep>/LinuxCmd.Net.ControlDesk/MainForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LinuxCmd.Net.NetWork;
namespace LinuxCmd.Net.ControlDesk
{
public partial class MainForm : Form
{
private NetWorker net;
public MainForm()
{
InitializeComponent();
net = new NetWorker();
}
private void btnStart_Click(object sender, EventArgs e)
{
net.Start();
}
}
}
<file_sep>/LinuxCmd.Net/LinuxHelper.cs
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using LinuxCmd.Net.Commads;
using LinuxCmd.Net.Models;
namespace LinuxCmd.Net
{
public static class LinuxHelper
{
public static BashResult LinuxBash(this string cmd,bool redirect = true)
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
return new BashResult() { Error = "The current system does not support it!", Success = false, Output = null };
var args = cmd.Replace("\"", "\\\"");
var startInfo = new ProcessStartInfo
{
FileName = "/bin/bash",
Arguments = $"-c \"{args}\"",
RedirectStandardOutput = redirect,
RedirectStandardError = redirect,
UseShellExecute = false,
CreateNoWindow = true,
ErrorDialog = false
};
using (var process = new Process() {StartInfo = startInfo})
{
process.Start();
string result = redirect ? process.StandardOutput.ReadToEnd() : "";
string error = redirect ? process.StandardError.ReadToEnd() : "";
process.WaitForExit();
int code = process.ExitCode;
process.Close();
return new BashResult() {Success = (code == 0), Error = error, Output = result};
}
}
public static LinuxTopInfo LinuxTop()
{
var result = "top -b -n 1".LinuxBash();
return result.Success ? (new Top()).GetTop(result.Output) : null;
}
public static LinuxDfInfo LinuxDisk()
{
var result = "df".LinuxBash();
return result.Success ? (new Df()).GetDiskInfo(result.Output) : null;
}
public static LinuxVmstatInfo LinuxVmstat()
{
var result = "vmstat".LinuxBash();
return result.Success ? (new Vmstat()).GetLinuxVmstatInfo(result.Output) : null;
}
public static LinuxSarInfo LinuxSar()
{
var result = "sar -n DEV 1 1".LinuxBash();
return result.Success ? (new Sar()).GetLinuxSarInfo(result.Output) : null;
}
public static List<LinuxNetstatInfo> LinuxNetstats()
{
var result = "netstat -lntup".LinuxBash();
return result.Success ? (new Netstat()).GetLinuxNetstatInfos(result.Output) : null;
}
}
} | 9544c4bae16fca4e3c7f31f11c494623d3252486 | [
"Markdown",
"C#"
] | 23 | C# | goodapiyes/LinuxCmd.Net | 0d8836dda3d67f0c712540b2da59d2e419123fc9 | d48481808a0536ba6f26ee1d2c1bd6e8518e399e | |
refs/heads/master | <repo_name>jhsziit/wechat<file_sep>/src/router/index.js
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const router = new Router({
routes: [
{
path: '/',
component: r => require.ensure([], () => r(require('../pages/index'))),
children: [{
path: '',
redirect: {
name: 'chat'
}
},
{
path: 'chat',
name: 'chat',
meta: {
title: '微信'
},
component: r => require.ensure([], () => r(require('../pages/chat/chat')))
},
{
path: 'contact',
name: 'contact',
meta: {
title: '联系人'
},
component: r => require.ensure([], () => r(require('../pages/contact/contact')))
},
{
path: 'find',
name: 'find',
meta: {
title: '发现'
},
component: r => require.ensure([], () => r(require('../pages/find/find')))
},
{
path: 'me',
name: 'me',
meta: {
title: '我'
},
component: r => require.ensure([], () => r(require('../pages/me/me')))
}
]
},
{
path: '/new-friends',
name: 'new-friends',
meta: {
title: '新的朋友'
},
component: r => require.ensure([], () => r(require('../pages/contact/new-friends')))
},
{
path: '/personal-details',
name: 'personal-details',
meta: {
title: '个人详情'
},
component: r => require.ensure([], () => r(require('../pages/contact/personal-details')))
},
{
path: '*',
redirect: '/'
}
]
})
export default router
<file_sep>/src/store/mutations-type.js
export const SET_HEAD_TITLE = 'SET_HEAD_TITLE'
export const GET_WECHAT_LIST = 'GET_WECHAT_LIST'
<file_sep>/src/store/mutations.js
import {
SET_HEAD_TITLE,
GET_WECHAT_LIST
} from './mutations-type'
export default {
// 底部导航修改头部标题
[SET_HEAD_TITLE] (state, index) {
// state.headTitle = state.appNavs[index].text;
},
[GET_WECHAT_LIST] (state, list) {
state.wechatList = list
console.log(state.wechatList)
},
}
<file_sep>/src/store/state.js
export default {
// wechat列表
wechatList: {}
}
| 2e11480c96b861545ff8a2dca0f94b42c919c65a | [
"JavaScript"
] | 4 | JavaScript | jhsziit/wechat | a42684dbd3622cab1ca86983c878c962f8ab43d4 | 455faeb08622dbb93c8ed101f69cccfc792541ce | |
refs/heads/master | <repo_name>Damian96/my-configs<file_sep>/shell/ytdl.sh
#!/bin/bash
link="$(youtube-dl --get-url --format bestaudio/best $1)"
ffmpeg -i "$link" -c:a copy out.mkv
wait
unset link
exit 0
<file_sep>/shell/starwars.sh
#!/bin/bash
telnet towel.blinkenlights.nl
exit 0
<file_sep>/shell/sptest.sh
#!/bin/bash
# Installation:
# sudo apt-get install python-pip && pip install speedtest-cli
# sudo cp ~/.local/bin/speedtest-cli /usr/local/bin
# sudo apt-get install speedtest
if [[ ! -f speedtest ]]; then
printf "%s\n" "Required package speedtest-cli not found"
printf "%s\n" "Install it with:"
# printf "%s\n" "sudo apt-get install python-pip && pip install speedtest-cli"
# printf "%s\n" "sudo cp ~/.local/bin/speedtest-cli /usr/local/bin"
printf "%s\n" "sudo apt-get install speedtest"
exit 1
fi
_trapCmd() {
trap 'kill -TERM $PID; exit 130;' TERM
eval "$1" &
PID=$!
wait $PID
}
declare -A servers=( [19078]="Athens" [4201]="Athens" [5188]="Athens")
declare -A providers=( [19078]="Vodafone - Panafon S.A." [4201]="OTE S.A." [5188]="Cosmote S.A." )
printf "%s\n\n" "Press CTRL+C to cancel"
id=19078
# for id in 19078 4201 5188; do
printf "%s\n" "Location: ${servers[$id]}"
printf "%s\n" "Provider: ${providers[$id]}"
# _trapCmd "speedtest --server $id --simple; echo;" -> speedtest-cli
_trapCmd "speedtest --server-id=$id echo;" # -> speedtest (.net)
# done
unset servers
unset providers
unset id
<file_sep>/README.md
# my-configs
A handy repo for my Linux (and not only) configurations
# LICENSE
UNLICENSED
| 7f16162d36d5a42fc3a4cc5e52f0c93ee04b6dc0 | [
"Markdown",
"Shell"
] | 4 | Shell | Damian96/my-configs | ca8c5b09ff3a6dbb264acc1d058620e808a93535 | b95874f2057f538c4f5004abae8092c5484fb156 | |
refs/heads/master | <file_sep><?php
require_once("common.php");
require_once("twitter.php");
$debug=1;
require_once('/www/govalert/streams/interpol/tasks.php');
interpolIzcheznali();
interpolProcessIzcheznali();
?>
<file_sep><?php
/*
links:
0: новини http://www.nek.bg/cgi?d=101
*/
function nekSaobshteniq() {
setSession(6,0);
echo "> Проверявам за съобщения на НЕК\n";
$html = loadURL("http://www.nek.bg/cgi?d=101",0);
if (!$html) return;
$html = mb_convert_encoding($html, "utf8","cp1251");
$items = nek_xpathDoc($html,"//div[@class='subpage']//li");
$query=array();
foreach ($items as $item) {
if (count($query)>15)
break;
$hash = md5($item->textContent);
$date = $item->childNodes->item(0)->textContent;
$date = mb_substr($date,9,4)."-".mb_substr($date,5,2)."-".mb_substr($date,1,2);
if (strtotime($date)<strtotime("-1 month"))
continue;
$url = $item->childNodes->item(2)->getAttribute("href");
$title = $item->childNodes->item(2)->textContent;
$title = mb_ereg_replace("П Р Е С С Ъ О Б Щ Е Н И Е","Прессъобщение",$title,"im");
$title = mb_ereg_replace("О Б Я В Л Е Н И Е","Обявление",$title,"im");
$title = "Съобщение: ".nek_cleanText($title);
$query[]=array($title,null,$date,"http://www.nek.bg$url",$hash);
}
echo "Възможни ".count($query)." нови съобщения\n";
$itemids = saveItems($query);
queueTweets($itemids);
}
/*
-----------------------------------------------------------------
*/
function nek_xpathDoc($html,$q) {
if (!$html)
return array();
$html = mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8");
$doc = new DOMDocument("1.0", "UTF-8");
$doc->preserveWhiteSpace=false;
$doc->strictErrorChecking=false;
$doc->encoding = 'UTF-8';
$doc->loadHTML($html);
$xpath = new DOMXpath($doc);
$items = $xpath->query($q);
return is_null($items)?array():$items;
}
function nek_cleanText($text) {
$text = str_replace(" "," ",$text);
$text = mb_ereg_replace("[\n\r\t ]+"," ",$text);
$text = mb_ereg_replace("(^\s+)|(\s+$)", "", $text);
$text = html_entity_decode($text);
return $text;
}
?>
<file_sep><?php
/*
0: новини http://www.prb.bg/main/bg/News/
1: документи http://www.prb.bg/main/bg/Documents/
2: конкурс http://www.prb.bg/main/bg/konkursi
3: галерия http://www.prb.bg/main/bg/gallery/
*/
function prok_Novini() {
echo "> Проверявам за новини в Прокуратурата\n";
setSession(13,0);
$html = loadURL("http://www.prb.bg/main/bg/News/",0);
if (!$html) return;
$items = prok_xpathDoc($html,"//div[@class='list-inner']");
$query=array();
foreach ($items as $item) {
$hasimage=$item->childNodes->item(1)->nodeName=="a";
$date = trim($item->childNodes->item(3+($hasimage?2:0))->textContent);
$date = mb_substr($date,6,4)."-".mb_substr($date,3,2)."-".mb_substr($date,0,2);
if (strtotime($date)<strtotime("-2 weeks"))
continue;
$description = trim($item->childNodes->item(5+($hasimage?2:0))->textContent);
$description = prok_cleanText($description);
$title = trim($item->childNodes->item(1+($hasimage?2:0))->textContent);
$title = prok_cleanTitle($title);
$title = prok_cleanText($title);
$url = "http://www.prb.bg".$item->childNodes->item(1)->firstChild->getAttribute("href");
$hash = md5($url);
$media = null;
if ($hasimage) {
$imageurl = $item->childNodes->item(1)->firstChild->getAttribute("src");
$imageurl=mb_ereg_replace("logo","big",$imageurl,"im");
$imageurl = "http://www.prb.bg$imageurl";
$imagetitle = trim($item->childNodes->item(3)->textContent);
$imagetitle = prok_cleanTitle($imagetitle);
$imagetitle = prok_cleanText($imagetitle);
$media = array("image" => array(loadItemImage($imageurl),$imagetitle));
}
$query[]=array($title,$description,$date,$url,$hash,$media);
}
echo "Възможни ".count($query)." нови новини\n";
$itemids = saveItems($query);
queueTweets($itemids);
}
function prok_Dokumenti() {
echo "> Проверявам за документи в Прокуратурата\n";
setSession(13,1);
$html = loadURL("http://www.prb.bg/main/bg/Documents/",1);
if (!$html) return;
$items = prok_xpathDoc($html,"//div[@class='list-inner']");
$query=array();
foreach ($items as $item) {
$date = trim($item->childNodes->item(3)->textContent);
$date = mb_substr($date,6,4)."-".mb_substr($date,3,2)."-".mb_substr($date,0,2);
if (strtotime($date)<strtotime("-2 months"))
continue;
$description = trim($item->childNodes->item(5)->textContent);
$description = prok_cleanText($description);
$title = trim($item->childNodes->item(1)->textContent);
$title = prok_cleanTitle($title);
$title = "Документ: ".prok_cleanText($title);
$url = "http://www.prb.bg".$item->childNodes->item(1)->firstChild->getAttribute("href");
$hash = md5($url);
$query[]=array($title,$description,$date,$url,$hash);
}
echo "Възможни ".count($query)." нови документи\n";
$itemids = saveItems($query);
queueTweets($itemids);
}
function prok_Konkursi() {
echo "> Проверявам за конкурси в Прокуратурата\n";
setSession(13,2);
$html = loadURL("http://www.prb.bg/main/bg/konkursi",2);
if (!$html) return;
$items = prok_xpathDoc($html,"//div[@class='list-inner']");
$query=array();
foreach ($items as $item) {
$date = trim($item->childNodes->item(3)->textContent);
$date = mb_substr($date,6,4)."-".mb_substr($date,3,2)."-".mb_substr($date,0,2);
if (strtotime($date)<strtotime("-2 weeks"))
continue;
$description = trim($item->childNodes->item(5)->textContent);
$description = prok_cleanText($description);
$title = trim($item->childNodes->item(1)->textContent);
$title = prok_cleanTitle($title);
$title = "Конкурс: ".prok_cleanText($title);
$url = "http://www.prb.bg".$item->childNodes->item(1+($hasimage?2:0))->firstChild->getAttribute("href");
$hash = md5($url);
$query[]=array($title,$description,$date,$url,$hash);
}
echo "Възможни ".count($query)." нови конкурса\n";
$itemids = saveItems($query);
queueTweets($itemids);
}
function prok_Snimki() {
echo "> Проверявам за галерии в Прокуратурата\n";
setSession(13,3);
$html = loadURL("http://www.prb.bg/main/bg/gallery/",3);
if (!$html) return;
$items = prok_xpathDoc($html,"//div[@class='list-inner']");
$query=array();
foreach ($items as $item) {
$date = trim($item->childNodes->item(5)->textContent);
$date = mb_substr($date,6,4)."-".mb_substr($date,3,2)."-".mb_substr($date,0,2);
if (strtotime($date)<strtotime("-2 weeks"))
continue;
$title = trim($item->childNodes->item(3)->textContent);
$title = prok_cleanTitle($title);
$title = "Снимки: ".$title;
$title = prok_cleanText($title);
$url = "http://www.prb.bg".$item->childNodes->item(1)->getAttribute("href");
$hash = md5($url);
$media = array("image" => array());
$mhtml = loadURL($url);
if (!$mhtml)
continue;
$mitems = prok_xpathDoc($mhtml,"//a[@class='thumb']");
foreach ($mitems as $mitem) {
$imageurl = $mitem->getAttribute("href");
$imageurl = "http://www.prb.bg$imageurl";
$imageurl = str_replace(array("logo","pic"),"big",$imageurl);
$imageurl = loadItemImage($imageurl);
if ($imageurl)
$media["image"][] = array($imageurl);
}
if (count($media["image"])==0)
$media=null;
$query[]=array($title,null,$date,$url,$hash,$media);
}
echo "Възможни ".count($query)." нови галерии\n";
$itemids = saveItems($query);
queueTweets($itemids);
}
/*
-----------------------------------------------------------------
*/
function prok_xpathDoc($html,$q) {
if (!$html)
return array();
$html = mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8");
$doc = new DOMDocument("1.0", "UTF-8");
$doc->preserveWhiteSpace=false;
$doc->strictErrorChecking=false;
$doc->encoding = 'UTF-8';
$doc->loadHTML($html);
$xpath = new DOMXpath($doc);
$items = $xpath->query($q);
return is_null($items)?array():$items;
}
function prok_cleanTitle($title) {
if (mb_substr($title,-1)==".")
$title = mb_substr($title,0,mb_strlen($title)-1);
$title=mb_ereg_replace("Република България","РБ",$title,"im");
$title=mb_ereg_replace("Р България","РБ",$title,"im");
$title=mb_ereg_replace("„|“","",$title,"im");
$title=mb_ereg_replace("Народно(то)? събрание","НС",$title,"im");
$title=mb_ereg_replace("Министерски(ят)? съвет","МС",$title,"im");
$title=mb_ereg_replace("(ИЗБИРАТЕЛНИ КОМИСИИ)|(избирателна комисия)","ИК",$title,"im");
$title=mb_ereg_replace("ОБЯВЛЕНИЕОТНОСНО:?|ОТНОСНО:?|С Ъ О Б Щ Е Н И Е|СЪОБЩЕНИЕ|г\.|ч\.|\\\\|„|\"|'","",$title,"im");
return $title;
}
function prok_cleanText($text) {
$text = text_cleanSpaces($text);
$text = html_entity_decode($text);
return $text;
}
?>
<file_sep><?php
/*
0: съобщения http://www.mh.government.bg/AllMessages.aspx
1: новини http://www.mh.government.bg/News.aspx?pageid=401
2: проекти за нормативни актове http://www.mh.government.bg/Articles.aspx?lang=bg-BG&pageid=393
3: наредби http://www.mh.government.bg/Articles.aspx?lang=bg-BG&pageid=391
4: постановления http://www.mh.government.bg/Articles.aspx?lang=bg-BG&pageid=381
5: отчети http://www.mh.government.bg/Articles.aspx?lang=bg-BG&pageid=532¤tPage=1
*/
function mh_Saobshteniq() {
echo "> Проверявам за съобщения в МЗ\n";
setSession(21,0);
$html = loadURL("http://www.mh.government.bg/AllMessages.aspx",0);
if (!$html) return;
$items = mh_xpathDoc($html,"//table[@id='ctl00_ContentPlaceClient_gvMessages']//a");
$query=array();
foreach ($items as $item) {
$title = $item->textContent;
$title = "Съобщение: ".mh_cleanText($title);
$url = "http://www.mh.government.bg/".$item->getAttribute("href");
$hash = md5($url);
$query[]=array($title,null,'now',$url,$hash);
if (count($query)>=20)
break;
}
echo "Възможни ".count($query)." нови съобщения\n";
$itemids = saveItems($query);
queueTweets($itemids);
}
function mh_Novini() {
echo "> Проверявам за новини в МЗ\n";
setSession(21,1);
$html = loadURL("http://www.mh.government.bg/News.aspx?pageid=401",1);
if (!$html) return;
$items = mh_xpathDoc($html,"//table[@id='ctl00_ContentPlaceClient_ucNewsList_gvwNews']//tr[not(@class)]/td");
$query=array();
foreach ($items as $item) {
$date = $item->childNodes->item(3)->textContent;
$date = mh_cleanText($date);
$date = explode(".",$date);
$date = substr($date[2],0,4)."-".$date[1]."-".$date[0];
if (strtotime($date)<strtotime("-1 month"))
continue;
$title = $item->childNodes->item(1)->textContent;
$title = mh_cleanText($title);
$description = $item->childNodes->item(5)->textContent;
$description = mh_cleanText($description);
if (mb_strlen($title)<25)
$title.=" ".$description;
$url = $item->childNodes->item(1)->getAttribute("href");
$urlstart = strpos($url,'News.aspx');
$url = substr($url,$urlstart,strpos($url,'"',$urlstart)-$urlstart);
$url = "http://www.mh.government.bg/$url";
$hash = md5($url);
$media=null;
if ($item->childNodes->item(5)->childNodes->item(1)->nodeName=="input") {
$imageurl = $item->childNodes->item(5)->childNodes->item(1)->getAttribute("src");
$imageurl = "http://www.mh.government.bg/$imageurl";
$imageurl=mb_ereg_replace("small","large",$imageurl,"im");
$media = array("image" => array(loadItemImage($imageurl),null));
}
$query[]=array($title,$description,$date,$url,$hash,$media);
}
echo "Възможни ".count($query)." нови новини\n";
$itemids = saveItems($query);
queueTweets($itemids);
}
function mh_Normativni() {
echo "> Проверявам за нормативни актове в МЗ\n";
setSession(21,2);
$html = loadURL("http://www.mh.government.bg/Articles.aspx?lang=bg-BG&pageid=393",2);
if (!$html) return;
$items = mh_xpathDoc($html,"//table[@id='ctl00_ContentPlaceClient_ucArticlesList_gvArticles']//tr[not(@class)]/td");
$query=array();
foreach ($items as $item) {
$date = $item->childNodes->item(3)->textContent;
$date = mh_cleanText($date);
$date = explode(".",$date);
$date = substr($date[2],0,4)."-".$date[1]."-".substr($date[0],-2);
if (strtotime($date)<strtotime("-1 month"))
continue;
$title = $item->childNodes->item(1)->textContent;
$title = mh_cleanText($title);
$url = $item->childNodes->item(1)->getAttribute("href");
$urlstart = strpos($url,'Articles.aspx');
$url = substr($url,$urlstart,strpos($url,'"',$urlstart)-$urlstart);
$url = "http://www.mh.government.bg/$url";
$hash = md5($url);
$query[]=array($title,null,$date,$url,$hash);
}
echo "Възможни ".count($query)." нови нормативни актове\n";
$itemids = saveItems($query);
queueTweets($itemids);
}
function mh_Naredbi() {
echo "> Проверявам за наредби в МЗ\n";
setSession(21,3);
$html = loadURL("http://www.mh.government.bg/Articles.aspx?lang=bg-BG&pageid=391",3);
if (!$html) return;
$items = mh_xpathDoc($html,"//table[@id='ctl00_ContentPlaceClient_ucArticlesList_gvArticles']//tr[not(@class)]/td/a[@class='list_article_title']");
$query=array();
foreach ($items as $item) {
$title = $item->textContent;
$title = mh_cleanText($title);
$url = $item->getAttribute("href");
$urlstart = strpos($url,'Articles.aspx');
$url = substr($url,$urlstart,strpos($url,'"',$urlstart)-$urlstart);
$url = "http://www.mh.government.bg/$url";
$hash = md5($url);
$query[]=array($title,null,"now",$url,$hash);
}
echo "Възможни ".count($query)." нови наредби\n";
$itemids = saveItems($query);
queueTweets($itemids);
}
function mh_Postanovleniq() {
echo "> Проверявам за постановления в МЗ\n";
setSession(21,4);
$html = loadURL("http://www.mh.government.bg/Articles.aspx?lang=bg-BG&pageid=381",4);
if (!$html) return;
$items = mh_xpathDoc($html,"//table[@id='ctl00_ContentPlaceClient_ucArticlesList_gvArticles']//tr[not(@class)]/td/a[@class='list_article_title']");
$query=array();
foreach ($items as $item) {
$title = $item->textContent;
$title = mh_cleanText($title);
$url = $item->getAttribute("href");
$urlstart = strpos($url,'Articles.aspx');
$url = substr($url,$urlstart,strpos($url,'"',$urlstart)-$urlstart);
$url = "http://www.mh.government.bg/$url";
$hash = md5($url);
$query[]=array($title,null,"now",$url,$hash);
}
echo "Възможни ".count($query)." нови постановления\n";
$itemids = saveItems($query);
queueTweets($itemids);
}
function mh_Otcheti() {
echo "> Проверявам за отчети в МЗ\n";
setSession(21,5);
$html = loadURL("http://www.mh.government.bg/Articles.aspx?lang=bg-BG&pageid=532",5);
if (!$html) return;
$items = mh_xpathDoc($html,"//table[@id='ctl00_ContentPlaceClient_ucArticlesList_gvArticles']//tr[not(@class)]/td/a[@class='list_article_title']");
$query=array();
foreach ($items as $item) {
$title = $item->textContent;
$title = mh_cleanText($title);
$url = $item->getAttribute("href");
$urlstart = strpos($url,'Articles.aspx');
$url = substr($url,$urlstart,strpos($url,'"',$urlstart)-$urlstart);
$url = "http://www.mh.government.bg/$url";
$hash = md5($url);
$query[]=array($title,null,"now",$url,$hash);
}
echo "Възможни ".count($query)." нови отчети\n";
$itemids = saveItems($query);
queueTweets($itemids);
}
/*
-----------------------------------------------------------------
*/
function mh_xpathDoc($html,$q) {
if (!$html)
return array();
$html = mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8");
$doc = new DOMDocument("1.0", "UTF-8");
$doc->preserveWhiteSpace=false;
$doc->strictErrorChecking=false;
$doc->encoding = 'UTF-8';
$doc->loadHTML($html);
$xpath = new DOMXpath($doc);
$items = $xpath->query($q);
return is_null($items)?array():$items;
}
function mh_cleanText($text) {
$text = html_entity_decode($text);
$text = text_cleanSpaces($text);
$text = text_fixCase($text);
return $text;
}
?>
<file_sep><?php
/*
0: дневен ред http://www.vss.justice.bg/bg/schedule/1.htm
1: протоколи http://www.vss.justice.bg/bg/decisions/2014/1.htm
2: новини http://www.vss.justice.bg/bg/press/2014/2014.htm
*/
function vssDnevenRed() {
echo "> Проверявам за дневен ред на ВСС\n";
setSession(9,0);
$baseurl = vssGetLink("Дневен ред");
$html = loadURL($baseurl,0);
if (!$html) return;
$items = vss_xpathDoc($html,"//td//a[@class='link']");
$baseurl=substr($baseurl,0,strrpos($baseurl,"/")+1);
$query=array();
foreach ($items as $item) {
$date = trim($item->textContent);
$date = "20".mb_substr($date,-2)."-".mb_substr($date,-5,2)."-".mb_substr($date,-8,2);
if (strtotime($date)<strtotime("-1 week"))
continue;
$url = $baseurl.$item->getAttribute("href");
$hash = md5($url);
$html1 = loadURL($url);
if (!$html1) continue;
$html1 = mb_convert_encoding($html1, 'UTF-8', 'cp1251');
mb_ereg_search_init($html1);
mb_ereg_search(">\s+(\d+)\. ");
$points="";
while ($match = mb_ereg_search_regs())
if (count($match)==2)
$points=intval($match[1]);
if ($points!="")
$points="от $points точки ";
$title = $item->textContent;
$title = vss_cleanText($title);
$title = mb_ereg_replace("№ ","№",$title,"im");
$title = mb_ereg_replace(" "," на ",$title,"im");
$title = "Публикуван е дневният ред ".$points."за заседание ".$title;
$query[]=array($title,null,'now',$url,$hash);
}
echo "Възможни ".count($query)." нов запис за дневен ред\n";
$itemids = saveItems($query);
queueTweets($itemids);
}
function vssProtokol() {
echo "> Проверявам за протоколи на ВСС\n";
setSession(9,1);
$baseurl = vssGetLink("Протоколи");
$html = loadURL($baseurl,1);
if (!$html) return;
$items = vss_xpathDoc($html,"//td//a[@class='link']");
$query=array();
foreach ($items as $item) {
$date = trim($item->textContent);
$date = "20".mb_substr($date,-2)."-".mb_substr($date,-5,2)."-".mb_substr($date,-8,2);
if (strtotime($date)<strtotime("-1 month"))
continue;
$title = $item->textContent;
$title = vss_cleanText($title);
$title = mb_ereg_replace("№ ","№",$title,"im");
$title = mb_ereg_replace(" "," на ",$title,"im");
$title = "Публикуван е протокол от заседание ".$title;
$url = $baseurl.$item->getAttribute("href");
$hash = md5($url);
$query[]=array($title,null,'now',$url,$hash);
}
echo "Възможни ".count($query)." нови протоколи\n";
$query=array_reverse($query);
$itemids = saveItems($query);
queueTweets($itemids);
}
function vssNovini() {
echo "> Проверявам за новини на ВСС\n";
setSession(9,2);
$baseurl = "http://www.vss.justice.bg/bg/press/".date("Y")."/";
$mainurl = $baseurl.date("Y").".htm";
$html = loadURL($mainurl,2);
if (!$html) return;
$xpath = vss_xpath($html);
if (!$xpath) return;
$items = $xpath->query("//td/div");
$query=array();
foreach ($items as $item) {
$date = trim($item->childNodes->item(1)->textContent);
$date = vss_cleanText($date);
$date = text_bgMonth($date);
$date = mb_substr($date,6,4)."-".mb_substr($date,3,2)."-".mb_substr($date,0,2);
if (strtotime($date)<strtotime("-1 week"))
continue;
$item->removeChild($item->childNodes->item(1));
$title = $item->textContent;
$title = mb_ereg_replace("“|„|”","",$title);
$title = vss_cleanText($title);
if (mb_strpos($title,'юлетин за дейността')!==false) {
$links = $xpath->query(".//a",$item);
if ($links->length>0) {
$url = $baseurl.$links->item(0)->getAttribute("href");
$hash = md5($url);
$query[]=array($title,null,$date,$url,$hash);
continue;
}
}
$url = $mainurl;
$hash = md5($url.$title);
if (!checkHash($hash))
continue;
$description = trim($item->C14N());
$description = mb_ereg_replace(" </","</",mb_ereg_replace("> ",">",$description));
$description = mb_ereg_replace("\s?(title|name|style|class|id|face|align|img)=[\"'].*?[\"']\s?","",$description);
$description = mb_ereg_replace("<p>[ ]*</p>|<a>[ ]*</a>|<div>[ ]*</div>","",$description);
$description = text_cleanSpaces($description);
$description = html_entity_decode($description);
$media=array("image" => array());
$imgs = $xpath->query(".//img[not(src)]",$item);
if ($imgs->length>0) {
$name=$imgs->item(0)->getAttribute("name");
$name=str_replace("show","images",$name);
if (mb_strpos($html,"$name=new Array(")!==false) {
$medialiststart = mb_strpos($html,"$name=new Array(")+mb_strlen("$name=new Array(");
$medialist=mb_substr($html,$medialiststart,mb_strpos($html,");",$medialiststart)-$medialiststart);
$medialist=explode(",",str_replace(array('"',"'"),"",$medialist));
foreach ($medialist as $mediafile) {
$imageurl = loadItemImage($baseurl.$mediafile);
if ($imageurl)
$media["image"][] = array($imageurl);
}
}
}
if (count($media["image"])==0)
$media=null;
$query[]=array($title,$description,$date,$url,$hash,$media);
}
echo "Възможни ".count($query)." нови новини\n";
$itemids = saveItems($query);
queueTweets($itemids);
}
/*
-----------------------------------------------------------------
*/
function vssGetLink($which) {
$html = loadURL("http://www.vss.justice.bg/bg/sessions.htm");
$html = mb_convert_encoding($html, 'UTF-8', 'cp1251');
$pos = mb_strpos($html,$which."|")+mb_strlen($which)+1;
return "http://www.vss.justice.bg/bg/".mb_substr($html,$pos,mb_strpos($html,"\"",$pos)-$pos);
}
function vss_xpath($html) {
if (!$html)
return null;
$html = mb_convert_encoding($html, 'UTF-8', 'cp1251');
$html = mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8');
$doc = new DOMDocument("1.0", "UTF-8");
$doc->preserveWhiteSpace=false;
$doc->strictErrorChecking=false;
$doc->encoding = 'UTF-8';
$doc->loadHTML($html);
return new DOMXpath($doc);
}
function vss_xpathDoc($html,$q) {
$xpath = vss_xpath($html);
if ($xpath==null)
return array();
$items = $xpath->query($q);
return is_null($items)?array():$items;
}
function vss_cleanText($text) {
$text = text_cleanSpaces($text);
$text = html_entity_decode($text);
return $text;
}
?>
| e4b7d78ba2f1f5af7f1b26a49300750586abe48e | [
"PHP"
] | 5 | PHP | aquilax/GovAlert-framework | ce5b20a4909eba30eca874793b3635e4211ed141 | e61362ace3cd88ceede3f95c3f07ca80087c4515 | |
refs/heads/master | <repo_name>masterdodo/Hoteli<file_sep>/iud/nov_hotel.php
<?php
if (isset ($_POST['submit']))
{
session_start();
//Zahtevam povezavo na bazo
include ('../x/dbconn.php');
//Urejanje slike
$username = $_SESSION['username'];
$hotel_name = $_POST['name'];
$picture_path = "../assets/hotels/";
$target_file = $picture_path . basename($_FILES["picture"]["name"]);
$ext = '.' . strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$newfile1 = $username . $hotel_name . $ext;
$newfile1 = str_replace (' ', '', $newfile1);
$picture_db_path = "https://testing.aristovnik.com/hoteli/assets/hotels/" . $newfile1;
$uploadOk = 1;
$check = getimagesize($_FILES["picture"]["tmp_name"]);
if($check !== false)
{
echo 'Datoteka je slika.';
$uploadOk = 1;
}
else
{
echo 'Datoteka ni slika.';
$uploadOk = 0;
}
if ($uploadOk == 1)
{
$newfile = $picture_path . $username . $hotel_name . $ext;
$newfile = str_replace (' ', '', $newfile);
if (move_uploaded_file($_FILES["picture"]["tmp_name"], $newfile))
{
//Napišem in izvedem INSERT stavek
echo 'Uspešno!';
$sql = 'INSERT INTO hotels(name, address, date_from, date_to, filled_places, all_places, city_id, user_id, picture) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)';
$stmt = $pdo->prepare ($sql)->execute ([$_POST['name'],$_POST['address'],$_POST['date_from'],$_POST['date_to'],0,$_POST['all_places'],$_POST['city'],$_SESSION['user_id'], $picture_db_path]);
header ('location:../');
exit;
}
else
{
echo 'Neuspešno!';
}
}
else
{
echo 'Napaka!';
}
}
?>
<?php
$title = "Dodaj hotel";
$css = "../css/main.css";
include ('../x/header.php');
?>
<form method="post" enctype="multipart/form-data">
<table>
<tr><td class="table-label-hotel"><label for="name">Ime hotela:</label></td><td><input type="text" name="name" placeholder="Ime hotela" class="input-standard" required></td></tr>
<tr><td class="table-label-hotel"><label for="address">Naslov hotela:</label></td><td><input type="text" name="address" placeholder="Naslov hotela" class="input-standard" required></td></tr>
<tr><td class="table-label-hotel"><label for="city">Kraj hotela:</label></td><td><select name="city" class="input-standard">
<?php
include ('../x/dbconn.php');
$stmt = $pdo->query ('SELECT * FROM cities');
foreach ($stmt as $row)
{
echo '<option value="' . $row['id'] . '">' . $row['name'] . '</option>';
}
?>
</select></td></tr>
<tr><td class="table-label-hotel"><label for="all_places">Število prostih mest:</label></td><td><input type="numbers" name="all_places" class="input-standard" placeholder="Število prostih mest" required></td></tr>
<tr><td class="table-label-hotel"><label for="date_from">Datum prihoda:</label></td><td><input type="date" name="date_from" class="input-standard" required></td></tr>
<tr><td class="table-label-hotel"><label for="date_to">Datum odhoda:</label></td><td><input type="date" name="date_to" class="input-standard" required></td></tr>
<tr><td class="table-label-hotel"><label for="picture">Slika hotela:</label></td><td><input type="file" name="picture" class="input-standard" required></td></tr><br />
</table>
<input class="button-standard" type="submit" name="submit" value="Dodaj hotel">
</form>
<?php
include ('../x/footer.php');
?><file_sep>/nastavitve/index.php
<?php
$title = "Uredi profil";
$css = "../css/main.css";
$js = "../js/nastavitve.js";
include ('../x/header.php');
require ('../x/dbconn.php');
?>
<?php
if (isset ($_POST['submit-username']))
{
$sql = $pdo->prepare ("SELECT id FROM users WHERE username = ?");
$sql->execute (array ($_POST['username']));
$result = $sql->fetch();
if ($result)
{
echo 'Uporabniško ime je zasedeno.';
}
else
{
$sql = 'UPDATE users SET username = ? WHERE id = ?';
$stmt = $pdo->prepare ($sql)->execute ([$_POST['username'], $_SESSION['user_id']]);
$_SESSION['username'] = $_POST['username'];
header ('location:./');
echo 'Uporabniško ime spremenjeno';
}
}
else if (isset ($_POST['submit-password']))
{
$sql = 'UPDATE users SET password = ? WHERE id = ?';
$pass_hash = password_hash($_POST['password'], PASSWORD_DEFAULT);
$stmt = $pdo->prepare ($sql)->execute ([$pass_hash, $_SESSION['user_id']]);
header ('location:./');
echo 'Geslo spremenjeno';
}
else if (isset ($_POST['submit-avatar']))
{
$username = $_SESSION['username'];
$avatar_path = "/data/testing.aristovnik.com/www/hoteli/assets/avatars/";
$target_file = $avatar_path . basename($_FILES["avatar"]["name"]);
$ext = '.' . strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$profile_picture_db_path = "https://testing.aristovnik.com/hoteli/assets/avatars/" . $username . $ext;
$uploadOk = 1;
$check = getimagesize($_FILES["avatar"]["tmp_name"]);
if($check !== false)
{
//echo 'Datoteka je slika.';
$uploadOk = 1;
}
else
{
//echo 'Datoteka ni slika.';
$uploadOk = 0;
}
if ($uploadOk == 1)
{
error_reporting (E_ALL);
if (move_uploaded_file($_FILES["avatar"]["tmp_name"], $avatar_path . $username . $ext))
{
echo 'Uspešno!';
$sql = $pdo->prepare ('UPDATE users SET avatar = ? WHERE id = ?');
$sql->execute (array ($profile_picture_db_path, $_SESSION['user_id']));
$_SESSION['avatar'] = $profile_picture_db_path;
}
else
{
echo $avatar_path . $username . $ext;
echo 'Neuspešno!';
}
}
else
{
echo 'Napaka!';
}
}
?>
<form method="post">
<input id="input-nastavitve-username" type="text" name="username" placeholder="Uporabniško ime" class="input-standard" onkeyup="checkInputOnKeUpUser(this.value)" required>
<input id="input-nastavitve-username-submit" type="submit" name="submit-username" value="Spremeni" class="input-submit">
</form>
<br />
<form method="post">
<input id="input-nastavitve-pass" type="password" name="password" placeholder="<PASSWORD>" class="input-standard" onkeyup="checkInputOnKeUpPass(this.value)" required <?php if (isset ($_SESSION['google-user'])){ echo 'disabled';} ?>>
<input id="input-nastavitve-pass-submit" type="submit" name="submit-password" value="<PASSWORD>" class="input-submit" <?php if (isset ($_SESSION['google-user'])){ echo 'disabled';} ?>>
</form>
<br />
<form method="post" enctype="multipart/form-data">
<label class="label-standard" for="avatar">Slika profila</label><br />
<input type="file" name="avatar" class="input-standard" required>
<input type="submit" name="submit-avatar" value="Spremeni" class="input-submit">
</form>
<div class="errors" id="error-user"></div>
<div class="errors" id="error-pass"></div>
<?php
include ('../x/footer.php');
?><file_sep>/js/nastavitve.js
var userWrong = 0;
var passWrong = 0;
function checkInputOnKeUpUser(x)
{
if (x.length < 3)
{
setTimeout(function()
{
document.querySelector('#error-user').style.display = "block";
document.querySelector('#error-user').innerHTML = "Uporabniško ime rabi več<br />kot dva znaka.";
document.querySelector('#input-nastavitve-username').style.background = '#ad2424';
document.querySelector('#input-nastavitve-username-submit').disabled = true;
userWrong = 1;
}, 200);
}
else if (x == "admin")
{
setTimeout(function()
{
document.querySelector('#error-user').style.display = "block";
document.querySelector('#error-user').innerHTML = "Nedovoljeno ime.";
document.querySelector('#input-nastavitve-username').style.background = '#ad2424';
document.querySelector('#input-nastavitve-username-submit').disabled = true;
userWrong = 1;
}, 200);
}
else
{
document.querySelector('#error-user').innerHTML = "";
document.querySelector('#input-nastavitve-username').style.background = '#6faf48';
document.querySelector('#error-user').style.display = "none";
userWrong = 0;
if (userWrong == 0 && passWrong == 0)
{
document.querySelector('#input-nastavitve-username-submit').disabled = false;
}
}
}
function checkInputOnKeUpPass(x)
{
if (x.length < 8)
{
if (document.querySelector('#error-pass').innerHTML == "")
{
setTimeout(function()
{
document.querySelector('#error-pass').style.display = "block";
document.querySelector('#error-pass').innerHTML = "Geslo je prekratko.";
document.querySelector('#input-nastavitve-pass').style.background = '#ad2424';
document.querySelector('#input-nastavitve-pass-submit').disabled = true;
passWrong = 1;
}, 200);
}
}
else
{
document.querySelector('#error-pass').innerHTML = "";
document.querySelector('#input-nastavitve-pass').style.background = '#6faf48';
document.querySelector('#error-pass').style.display = "none";
passWrong = 0;
if (passWrong == 0 && userWrong == 0)
{
document.querySelector('#input-nastavitve-pass-submit').disabled = false;
}
}
}<file_sep>/admin/iud/dodaj_ponudnika.php
<?php
//Zahtevam povezavo na bazo
require_once ('../../x/dbconn.php');
//Preverim če je admin prijavljen
require_once ('../../x/checkadminlogin.php');
//Preverim če so bili podatki poslani
if (isset ($_POST['submit']))
{
//Trim-am vse vrednosti, ki jih dobim iz poslanih podatkov in jih shranim v nove spremenljivke
$email = trim ($_POST['email']);
$username = trim ($_POST['email']);
$password = trim ($_POST['password']);
//V spremenljivko result si zabeležim če epošta že obstaja
$sql = $pdo->prepare ("SELECT * FROM users WHERE email = ?");
$sql->execute (array ($email));
$result = $sql->fetch();
//Nastavim spremenljivko error na 0
$error = 0;
//Preverim če epošta že obstaja
if ($result)
{
echo "Epošta že obstaja.";
$error = 1;
}
//Preverim če je geslo manjše od 8 znakov
if (strlen ($password) < 8)
{
echo "Geslo mora biti večje od 8 znakov.";
$error = 1;
}
//Preverim če ni bilo napak in ga vpišem v tabelo users
if ($error == 0)
{
//Generiram hash gesla in vpišem ponudnika v DB
$pass_hash = password_hash($password, PASSWORD_DEFAULT);
$sql = $pdo->prepare ("INSERT INTO users(username, email, password, edit_hotels) VALUES (?,?,?,1)");
try
{
$sql->execute (array ($email, $email, $pass_hash));
echo "Ponudnik uspešno dodan!";
}
catch ( PDOException $err)
{
echo "Napaka!";
}
}
}
?>
<?php
$title = 'Admin - <NAME>';
$css = '../../css/main.css';
include '../../x/header.php';
?>
<form method="post">
<input class="input-standard" type="text" name="email" placeholder="Epošta" required><br />
<input class="input-standard" type="<PASSWORD>" name="password" placeholder="<PASSWORD>" required><br />
<input class="button-standard" type="submit" name="submit" value="Dodaj">
</form>
<?php
include '../../x/footer.php';
?><file_sep>/js/registracija.js
var emailWrong = 0;
var userWrong = 0;
var passWrong = 0;
var passCheckWrong = 0;
function checkInputOnKeyUpMail(x)
{
if( /(.+)@(.+){2,}\.(.+){2,}/.test(x) )
{
document.querySelector('#error-email').innerHTML = "";
document.querySelector('#input-register-email').style.background = '#6faf48';
document.querySelector('#error-email').style.display = "none";
emailWrong = 0;
if (emailWrong == 0 && userWrong == 0 && passWrong == 0 && passCheckWrong == 0)
{
document.querySelector('#input-register-submit').disabled = false;
}
}
else
{
if (document.querySelector('#error-email').innerHTML == "")
{
setTimeout(function()
{
document.querySelector('#error-email').style.display = "block";
document.querySelector('#error-email').innerHTML = "Napačna e-pošta.";
document.querySelector('#input-register-email').style.background = '#ad2424';
document.querySelector('#input-register-submit').disabled = true;
emailWrong = 1;
}, 500);
}
}
}
function checkInputOnKeyUpUser(x)
{
if (x.length < 3)
{
setTimeout(function()
{
document.querySelector('#error-user').style.display = "block";
document.querySelector('#error-user').innerHTML = "Uporabniško ime rabi več<br />kot dva znaka.";
document.querySelector('#input-register-user').style.background = '#ad2424';
document.querySelector('#input-register-submit').disabled = true;
userWrong = 1;
}, 200);
}
else if (x == "admin")
{
setTimeout(function()
{
document.querySelector('#error-user').style.display = "block";
document.querySelector('#error-user').innerHTML = "Nedovoljeno ime.";
document.querySelector('#input-register-user').style.background = '#ad2424';
document.querySelector('#input-register-submit').disabled = true;
userWrong = 1;
}, 200);
}
else
{
document.querySelector('#error-user').innerHTML = "";
document.querySelector('#input-register-user').style.background = '#6faf48';
document.querySelector('#error-user').style.display = "none";
userWrong = 0;
if (emailWrong == 0 && userWrong == 0 && passWrong == 0 && passCheckWrong == 0)
{
document.querySelector('#input-register-submit').disabled = false;
}
}
}
function checkInputOnKeyUpPass(x)
{
if (x.length < 8)
{
if (document.querySelector('#error-pass').innerHTML == "")
{
setTimeout(function()
{
document.querySelector('#error-pass').style.display = "block";
document.querySelector('#error-pass').innerHTML = "Geslo je prekratko.";
document.querySelector('#input-register-pass').style.background = '#ad2424';
document.querySelector('#input-register-submit').disabled = true;
passWrong = 1;
}, 200);
}
}
else
{
document.querySelector('#error-pass').innerHTML = "";
document.querySelector('#input-register-pass').style.background = '#6faf48';
document.querySelector('#error-pass').style.display = "none";
passWrong = 0;
if (emailWrong == 0 && userWrong == 0 && passWrong == 0 && passCheckWrong == 0)
{
document.querySelector('#input-register-submit').disabled = false;
}
}
}
function checkInputOnKeyUpPassCheck(x)
{
var pass = document.querySelector('#input-register-pass').value;
console.log(pass);
if (pass === x)
{
document.querySelector('#error-passcheck').innerHTML = "";
document.querySelector('#input-register-passcheck').style.background = '#6faf48';
document.querySelector('#error-passcheck').style.display = "none";
passCheckWrong = 0;
if (emailWrong == 0 && userWrong == 0 && passWrong == 0 && passCheckWrong == 0)
{
document.querySelector('#input-register-submit').disabled = false;
}
}
else
{
if (document.querySelector('#error-passcheck').innerHTML == "")
{
setTimeout(function()
{
document.querySelector('#error-passcheck').style.display = "block";
document.querySelector('#error-passcheck').innerHTML = "Gesli se ne ujemata.";
document.querySelector('#input-register-passcheck').style.background = '#ad2424';
document.querySelector('#input-register-submit').disabled = true;
passCheckWrong = 1;
}, 200);
}
}
}<file_sep>/js/prijava.js
var emailWrong = 0;
var passWrong = 0;
function checkInputOnKeyUpMail (x)
{
if( /(.+)@(.+){2,}\.(.+){2,}/.test(x) )
{
document.querySelector('#error-email').innerHTML = "";
document.querySelector('#input-prijava-email').style.background = '#6faf48';
document.querySelector('#error-email').style.display = "none";
emailWrong = 0;
if (emailWrong == 0 && passWrong == 0)
{
document.querySelector('#input-prijava-submit').disabled = false;
}
}
else
{
if (document.querySelector('#error-email').innerHTML == "")
{
setTimeout(function()
{
document.querySelector('#error-email').style.display = "block";
document.querySelector('#error-email').innerHTML = "Napačna e-pošta.";
document.querySelector('#input-prijava-email').style.background = '#ad2424';
document.querySelector('#input-prijava-submit').disabled = true;
emailWrong = 1;
}, 500);
}
}
}
function checkInputOnKeyUpPass (x)
{
if (x.length < 8)
{
if (document.querySelector('#error-pass').innerHTML == "")
{
setTimeout(function()
{
document.querySelector('#error-pass').style.display = "block";
document.querySelector('#error-pass').innerHTML = "<PASSWORD>.";
document.querySelector('#input-prijava-pass').style.background = '#<PASSWORD>';
document.querySelector('#input-prijava-submit').disabled = true;
passWrong = 1;
}, 200);
}
}
else
{
document.querySelector('#error-pass').innerHTML = "";
document.querySelector('#input-prijava-pass').style.background = '#6<PASSWORD>';
document.querySelector('#error-pass').style.display = "none";
passWrong = 0;
if (passWrong == 0 && emailWrong == 0)
{
document.querySelector('#input-prijava-submit').disabled = false;
}
}
}<file_sep>/admin/index.php
<?php
//Nastavim naslov, css pot in dodam header
$title = 'Glavna stran - Admin';
$css = '../css/main.css';
include '../x/header.php';
//Preverim če je admin prijavljen
require_once ('../x/checkadminlogin.php');
?>
<a class="button-standard" href="iud/dodaj_ponudnika.php">Dodaj ponudnika</a><br /><br />
<a class="button-standard" href="iud/odstrani_ponudnika.php">Odstrani ponudnika</a><br />
<?php
include '../x/footer.php';
?><file_sep>/registracija/signup.php
<?php
//Zahtevam povezavo na bazo
require_once ('../x/dbconn.php');
//Preverim če so bili podatki poslani
if (isset ($_POST['submit']))
{
//Trim-am vse vrednosti, ki jih dobim iz poslanih podatkov in jih shranim v nove spremenljivke
$email = trim ($_POST['email']);
$username = trim ($_POST['username']);
$password = trim ($_POST['password']);
$password_check = trim ($_POST['passwordcheck']);
//V spremenljivko result si zabeležim če uporabniško ime že obstaja
$sql = $pdo->prepare ("SELECT * FROM users WHERE username = ?");
$sql->execute (array ($username));
$result = $sql->fetch();
//V spremenljivko result1 si zabeležim če epošta že obstaja
$sql1 = $pdo->prepare ("SELECT * FROM users WHERE email = ?");
$sql1->execute (array ($email));
$result1 = $sql1->fetch();
//Izpraznim session spremenljivko za errorje in nastavim err spremenljivko na 0
session_start();
$_SESSION['err'] = "";
$error = 0;
//Preverim če uporabniško ime že obstaja
if ($result)
{
$_SESSION['err'] = "Uporabniško ime že obstaja.<br />";
$error = 1;
}
//Preverim če epošta že obstaja
if ($result1)
{
$_SESSION['err'] .= "Epošta že obstaja.<br />";
$error = 1;
}
//Preverim če je uporabniško ime admin
if ($username == "admin")
{
$_SESSION['err'] .= "Napačna izbira uporabniškega imena.<br />";
$error = 1;
}
//Uporabniško ime mora biti vsaj 3 znake
$usernamelen = strlen($username);
if ($usernamelen < 3)
{
$_SESSION['err'] .= "Uporabniško ime je prekratko.<br />";
$error = 1;
}
//Preverim če je geslo manjše od 8 znakov
if (strlen ($password) < 8)
{
$_SESSION['err'] .= "Geslo mora biti večje od 8 znakov.<br />";
$error = 1;
}
//Preverim če se geslo ujema
if ($password != $password_check)
{
$_SESSION['err'] .= "Gesli se ne ujemata.";
$error = 1;
}
//Preverim če ni bilo napak in ga vpišem v tabelo users
if ($error == 0)
{
if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0)
{
$avatar_path = "../assets/avatars/";
$target_file = $avatar_path . basename($_FILES["avatar"]["name"]);
$ext = '.' . strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$profile_picture_db_path = "https://testing.aristovnik.com/hoteli/assets/avatars/" . $username . $ext;
$uploadOk = 1;
$check = getimagesize($_FILES["avatar"]["tmp_name"]);
if($check !== false)
{
echo 'Datoteka je slika.';
$uploadOk = 1;
}
else
{
echo 'Datoteka ni slika.';
$uploadOk = 0;
}
if ($uploadOk == 1)
{
if (move_uploaded_file($_FILES["avatar"]["tmp_name"], $avatar_path . $username . $ext))
{
echo 'Uspešno!';
}
else
{
echo 'Neuspešno!';
}
}
else
{
echo 'Napaka!';
}
}
else
{
$profile_picture_db_path = 'https://testing.aristovnik.com/hoteli/assets/avatars/default/profile.png';
}
$pass_hash = password_hash($password, PASSWORD_DEFAULT);
$sql2 = $pdo->prepare ("INSERT INTO users(username, email, password, avatar) VALUES (?,?,?,?)");
try
{
$sql2->execute (array ($username, $email, $pass_hash, $profile_picture_db_path));
header ("Location:../");
}
catch ( PDOException $err)
{
echo "Napaka!";
}
}
//Preverim če je napaka in uporabnika pošljem nazaj na spletno stran s formo in mu izpišem napake
else if ($error == 1)
{
header ("Location: ./");
}
}
//Če podatki niso bili poslani ga preusmerim na stran s formo
else
{
header ("Location: ./");
}
<file_sep>/index.php
<?php
$title = "Hoteli";
$css = "css/main.css";
$js = "js/main.js";
include ('x/header.php');
require ('x/dbconn.php');
//Preverim, če je uporabnik ponudnik hotelov
if ($_SESSION['editor'] == 1)
{
//Prikažem gumb za dodajanje hotelov
echo '<a href="iud/nov_hotel.php" class="button-standard">Nov hotel</a><br /><br />';
}
$stmt = $pdo->query ('SELECT id, name, address, date_from, date_to, filled_places, all_places, user_id, picture, city_id FROM hotels ORDER BY id');
foreach ($stmt as $row)
{
$date_from = $row['date_from'];
$date_to = $row['date_to'];
$date_from = new DateTime($date_from);
$date_to = new DateTime($date_to);
$dateresult_from = $date_from->format("d. m. Y");
$dateresult_to = $date_to->format("d. m. Y");
$sql = $pdo->prepare ("SELECT name FROM cities WHERE id = ?");
$sql->execute (array ($row['city_id']));
$result = $sql->fetch(PDO::FETCH_ASSOC);
$city = $result['name'];
echo '<div class="hotel-box" id="hotel' . $row['id'] . '">
<img class="hotel-picture" src="' . $row['picture'] . '" alt="HOTEL" height="150">
<div class="hotel-content">
<div class="ime-hotela">' . $row['name'] . '</div>
<div class="naslov-hotela">' . $row['address'] . ', ' . $city . '</div>
<div>' . $row['filled_places'] . '/' . $row['all_places'] . '</div>
<div class="datum"><b>Od:</b> ' . $dateresult_from . ' <b>Do:</b> ' . $dateresult_to . '</div>
</div>';
if ($_SESSION['editor'] == 1 && $_SESSION['user_id'] == $row['user_id'])
{
echo '<div class="gumbi">
<a class="button-standard" href="iud/uredi_hotel.php?y=' . $row['id'] . '">Uredi hotel</a>
<a class="button-standard" href="iud/izbrisi_hotel.php?y=' . $row['id'] . '">Izbriši hotel</a>
</div>';
}
else if ($_SESSION['editor'] == 0)
{
$sql = $pdo->prepare("SELECT user_id, hotel_id FROM hotel_logins WHERE user_id = ? AND hotel_id = ?");
$sql->execute([$_SESSION['user_id'], $row['id']]);
$result = $sql->fetch();
if (!$result)
{
echo '<div class="gumbi">';
$sql_prijava = $pdo->prepare("SELECT filled_places, all_places FROM hotels WHERE id = ?");
$sql_prijava->execute([$row['id']]);
$result_prijava = $sql_prijava->fetch();
if ($result_prijava['filled_places'] != $result_prijava['all_places'])
{
echo '<a id="button-prijava" class="button-standard" href="prijava.php?y=' . $row['id'] . '">Prijava na hotel</a>';
}
echo '</div>';
}
else
{
echo '<div id="login-done">Na ta hotel ste že prijavljeni!</div><a id="button-odjava" class="button-standard" href="odjava.php?y=' . $row['id'] . '">Odjava</a>';
}
}
echo '</div><br />';
}
include ('x/footer.php');
?>
<file_sep>/admin/iud/izbrisi_ponudnika.php
<?php
//Preverim če je admin prijavljen
require_once ('../../x/checkadminlogin.php');
//Zahtevam povezavo na bazo
include ('../../x/dbconn.php');
//Preverim, če so poslani podatki
if (isset ($_GET['y']))
{
//Izbrišem vse hotele v lasti tega ponudnika
$sql = 'DELETE FROM hotels WHERE user_id = ?';
$pdo->prepare ($sql)->execute ([$_GET['y']]);
//Izbrišem ponudnika iz uporabnikov
$sql = 'DELETE FROM users WHERE id = ?';
$pdo->prepare ($sql)->execute ([$_GET['y']]);
}
//Na koncu v vsakem primeru preusmerim na prejšnjo stran
header ('location: odstrani_ponudnika.php');
?><file_sep>/admin/iud/odstrani_ponudnika.php
<?php
//Preverim če je admin prijavljen
require_once ('../../x/checkadminlogin.php');
//Dodam header
$title = 'Admin - Odstrani Ponudnika';
$css = '../../css/main.css';
include '../../x/header.php';
?>
<table class="table-standard">
<thead id="table-thead">
<td class="table-td">Epošta</td>
<td class="table-td">Odstrani</td>
</thead>
<tbody>
<?php
//Zahtevam povezavo na bazo
require_once ('../../x/dbconn.php');
//Pripravim SELECT stavek
$stmt = $pdo->query ('SELECT email, id FROM users WHERE edit_hotels = 1');
//Zaženem foreach zanko v kateri izpišem vsakega ponudnika v svojo vrsto
foreach ($stmt as $row)
{
echo '<tr>
<td class="table-td">' . $row['email'] . '</td>
<td class="table-td"><a class="table-button" href="izbrisi_ponudnika.php?y=' . $row['id'] . '">Odstrani</a></td>
</tr>';
}
?>
</tbody>
</table>
<?php
include '../../x/footer.php';
?><file_sep>/registracija/index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<title>Registracija</title>
<link rel="stylesheet" href="../css/main.css">
<script src="../js/registracija.js"></script>
</head>
<body>
<div id="login-wrapper">
<div id="login-subwrapper">
<form action="signup.php" method="POST" enctype="multipart/form-data">
<label for="email">E-pošta:</label><br /><input id="input-register-email" class="input-login-standard" type="text" name="email" placeholder="Epošta" onkeyup="checkInputOnKeyUpMail(this.value)" required><br />
<label for="username">Uporabniško ime:</label><br /><input id="input-register-user" class="input-login-standard" type="text" name="username" placeholder="Uporabniško ime" onkeyup="checkInputOnKeyUpUser(this.value)" required><br />
<label for="password">Geslo:</label><br /><input id="input-register-pass" class="input-login-standard" type="password" name="password" placeholder="<PASSWORD>" onkeyup="checkInputOnKeyUpPass(this.value)" required><br />
<label for="passwordcheck">Potrdite geslo:</label><br /><input id="input-register-passcheck" class="input-login-standard" type="password" name="passwordcheck" placeholder="Potrditev gesla" onkeyup="checkInputOnKeyUpPassCheck(this.value)" required><br />
<label for="avatar">Slika profila (ni obvezno):</label><br />
<input class="input-login-standard" type="file" name="avatar"><br />
<input id="input-register-submit" class="input-login-submit" type="submit" name="submit" value="Registracija">
<div class="errors" id="error-email"></div>
<div class="errors" id="error-user"></div>
<div class="errors" id="error-pass"></div>
<div class="errors" id="error-passcheck"></div>
<?php
//Zaženem sejo in v primeru napak le te izpišem
session_start();
if ((isset ($_SESSION['err'])) && ($_SESSION['err'] != ""))
{
echo '<div id="err">' . $_SESSION['err'] . '</div>';
}
$_SESSION['err'] = "";
?>
</form><br />
<a href="../prijava/" class="button-standard">Prijavi se</a>
</div>
</div>
</body>
</html><file_sep>/prijava.php
<?php
//Odprem sejo in dodam povezavo na bazo
session_start();
include ('x/dbconn.php');
//Dodam prijavo na hotel v podatkovno bazo
$sql = 'INSERT INTO hotel_logins(user_id, hotel_id) VALUES(?, ?)';
$stmt = $pdo->prepare ($sql)->execute ([$_SESSION['user_id'], $_GET['y']]);
$sql = 'UPDATE hotels SET filled_places = filled_places + 1 WHERE id = ?';
$stmt = $pdo->prepare ($sql)->execute ([$_GET['y']]);
header ('location:./');
?><file_sep>/iud/uredi_hotel.php
<?php
if (isset ($_POST['submit']))
{
//Zahtevam povezavo na bazo
include ('../x/dbconn.php');
//Napišem in izvedem UPDATE stavek
$sql = 'UPDATE hotels SET name = ?, address = ?, date_from = ?, date_to = ?, all_places = ?, city_id = ? WHERE id = ?';
$stmt = $pdo->prepare ($sql)->execute ([$_POST['name'],$_POST['address'],$_POST['date_from'],$_POST['date_to'],$_POST['all_places'],$_POST['city'],$_GET['y']]);
header ('location:../');
}
else if (isset ($_POST['submit-picture']))
{
session_start();
//Zahtevam povezavo na bazo
include ('../x/dbconn.php');
//Urejanje slike
$username = $_SESSION['username'];
$hotel_name = $_POST['name'];
$picture_path = "../assets/hotels/";
$target_file = $picture_path . basename($_FILES["picture"]["name"]);
$ext = '.' . strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$newfile1 = $username . $hotel_name . $ext;
$newfile1 = str_replace (' ', '', $newfile1);
$picture_db_path = "https://testing.aristovnik.com/hoteli/assets/hotels/" . $newfile1;
$uploadOk = 1;
$check = getimagesize($_FILES["picture"]["tmp_name"]);
if($check !== false)
{
echo 'Datoteka je slika.';
$uploadOk = 1;
}
else
{
echo 'Datoteka ni slika.';
$uploadOk = 0;
}
if ($uploadOk == 1)
{
$newfile = $picture_path . $username . $hotel_name . $ext;
$newfile = str_replace (' ', '', $newfile);
if (move_uploaded_file($_FILES["picture"]["tmp_name"], $newfile))
{
//Napišem in izvedem UPDATE stavek
echo 'Uspešno!';
$sql = 'UPDATE hotels SET picture = ? WHERE id = ?';
$stmt = $pdo->prepare ($sql)->execute ([$picture_db_path, $_GET['y']]);
header ('location:../');
exit;
}
else
{
echo 'Neuspešno!';
}
}
else
{
echo 'Napaka!';
}
}
?>
<?php
$title = "Uredi hotel";
$css = "../css/main.css";
include ('../x/header.php');
?>
<form method="post">
<?php
//Zahtevam povezavo na bazo
include ('../x/dbconn.php');
//Dobim podatke o hotelu, ki ga rabim
$sql = $pdo->prepare ("SELECT * FROM hotels WHERE id = ?");
$sql->execute (array ($_GET['y']));
$result = $sql->fetch(PDO::FETCH_ASSOC);
//Izpišem obrazec z vpisanimi podatki
echo '<table>
<tr><td><label for="name">Ime hotela: </label></td><td><input type="text" name="name" placeholder="Ime hotela" value="' . $result['name'] . '" class="input-standard" required></td></tr>
<tr><td><label for="address">Naslov hotela: </label></td><td><input type="text" name="address" placeholder="Naslov hotela" value="' . $result['address'] . '" class="input-standard" required></td></tr>
<tr><td><label for="city">Kraj hotela: </label></td><td><select name="city" class="input-standard">';
$stmt = $pdo->query ('SELECT * FROM cities');
foreach ($stmt as $row1)
{
if ($row1['id'] == $result['city_id'])
{
$selected = 'selected';
}
else
{
$selected = '';
}
echo '<option ' . $selected . ' value="' . $row1['id'] . '">' . $row1['name'] . '</option>';
}
$date_from = $result['date_from'];
$date_to = $result['date_to'];
$date_from = new DateTime($date_from);
$date_to = new DateTime($date_to);
$dateresult_from = $date_from->format("Y-m-d");
$dateresult_to = $date_to->format("Y-m-d");
echo '</select></td></tr>
<tr><td><label for="date_from">Datum prihoda: </label></td><td><input type="date" name="date_from" value="' . $dateresult_from . '" class="input-standard" required></td></tr>
<tr><td><label for="date_to">Datum odhoda: </label></td><td><input type="date" name="date_to" value="' . $dateresult_to . '" class="input-standard" required></td></tr>
<tr><td><label for="all_places">Prosta mesta: </label></td><td><input type="numbers" name="all_places" value="' . $result['all_places'] . '" class="input-standard" required></td></tr>';
?>
</table>
<input class="button-standard" type="submit" name="submit" value="Uredi hotel">
</form><br />
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="name" value="<?php echo $result['name'] ?>">
<label for="picture">Spremeni sliko hotela:</label><br />
<input type="file" name="picture" class="input-standard" required><br />
<input class="button-standard" type="submit" name="submit-picture" value="Uredi sliko hotela">
</form>
</body>
</html><file_sep>/baza_model/script.sql
/*
Created 10. 09. 2018
Modified 10. 09. 2018
Project
Model
Company
Author
Version
Database mySQL 5
*/
Create table hotels (
id Int NOT NULL,
city_id Int NOT NULL,
user_id Int NOT NULL,
name Varchar(200) NOT NULL,
address Varchar(200) NOT NULL,
date_from Timestamp NOT NULL,
date_to Timestamp NOT NULL,
insert_date Timestamp NOT NULL,
Primary Key (id)) ENGINE = MyISAM;
Create table users (
id Int NOT NULL,
email Varchar(200) NOT NULL,
username Varchar(200) NOT NULL,
password V<PASSWORD>(200) NOT NULL,
edit_hotels Int NOT NULL DEFAULT 0,
avatar Varchar(200) NOT NULL,
Primary Key (id)) ENGINE = MyISAM;
Create table admin (
id Int NOT NULL,
email Varchar(200) NOT NULL,
username Varchar(200) NOT NULL,
password Varchar(200) NOT NULL,
Primary Key (id)) ENGINE = MyISAM;
Create table hotel_logins (
id Int NOT NULL,
user_id Int NOT NULL,
hotel_id Int NOT NULL,
login_date Timestamp NOT NULL,
Primary Key (id)) ENGINE = MyISAM;
Create table cities (
id Int NOT NULL,
name Varchar(200) NOT NULL,
Primary Key (id)) ENGINE = MyISAM;
<file_sep>/x/header.php
<?php
if (session_status() == PHP_SESSION_NONE)
{
session_start();
}
if (!isset ($_SESSION['username']))
{
header("location:https://testing.aristovnik.com/hoteli/prijava/");
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<?php
echo '<link rel="stylesheet" href="' . $css . '">';
echo '<script src="' . $js . '"></script>';
echo '<title>' . $title . '</title>'; ?>
</head>
<body>
<div id="header">
<img src="<?php echo $_SESSION['avatar']; ?>" height="32" width="32" alt="PP" id="header-profile-picture"> <div id="header-username"><?php echo strtoupper($_SESSION['username']); ?></div>
<div id="header-buttons">
<a class="header-links"
<?php
if ($_SESSION['username'] == 'admin')
{
echo 'href="/hoteli/admin/"';
}
else
{
echo 'href="/hoteli/"';
}
?>
>Glavna stran</a>
<?php
if ($_SESSION['username'] == 'admin')
{
}
else
{
echo '<a class="header-links" href="/hoteli/nastavitve">Uredi profil</a>';
}
?>
<a class="header-links" href="/hoteli/logout.php">Odjava</a>
</div>
</div>
<div id="main-wrapper">
<file_sep>/odjava.php
<?php
//Odprem sejo in dodam povezavo na bazo
session_start();
include ('x/dbconn.php');
//Izbrišem prijavo na hotel iz podatkovno bazo
$sql = 'DELETE FROM hotel_logins WHERE user_id = ? AND hotel_id = ?';
$stmt = $pdo->prepare ($sql)->execute ([$_SESSION['user_id'], $_GET['y']]);
$sql = 'UPDATE hotels SET filled_places = filled_places - 1 WHERE id = ?';
$stmt = $pdo->prepare ($sql)->execute ([$_GET['y']]);
header ('location:./');
?><file_sep>/x/checkadminlogin.php
<?php
if (session_status() == PHP_SESSION_NONE)
{
session_start();
}
if (!isset ($_SESSION['username']) || $_SESSION['username'] != "admin")
{
header("location:/hoteli/prijava/");
exit;
}
else
{
}
?><file_sep>/prijava/index.php
<?php
session_start();
if (isset ($_SESSION['username']) && $_SESSION['username'] == "admin")
{
header ('location:../admin/');
}
else if (isset ($_SESSION['username']))
{
header ('location:../');
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<title>Prijava</title>
<link rel="stylesheet" href="../css/main.css">
<script src="../js/prijava.js"></script>
</head>
<body>
<div id="login-wrapper">
<div id="login-subwrapper">
<form action="checklogin.php" method="POST">
<input id="input-prijava-email" type="text" name="email" placeholder="E-pošta" class="input-login-standard" onkeyup="checkInputOnKeyUpMail(this.value)" required><br />
<input id="input-prijava-pass" type="<PASSWORD>" name="password" placeholder="<PASSWORD>" class="input-login-standard" onkeyup="checkInputOnKeyUpPass(this.value)" required><br />
<input id="input-prijava-submit" type="submit" name="submit" value="Prijava" class="input-login-submit">
<div class="errors" id="error-email"></div>
<div class="errors" id="error-pass"></div>
<?php
if ((isset ($_SESSION['err'])) && ($_SESSION['err'] != ""))
{
echo '<div id="err">' . $_SESSION['err'] . '</div>';
}
$_SESSION['err'] = "";
?>
</form>
<br />
<?php require ('../vendor/autoload.php');
include ('../x/dbconn.php');
$g_client = new Google_Client();
$g_client->setClientId("482990312667-lf56buca4n9gus09mj3scif7h0iqhk5i.apps.googleusercontent.com");
$g_client->setClientSecret("-<KEY>");
$g_client->setRedirectUri("https://testing.aristovnik.com/hoteli/prijava/index.php");
$g_client->setScopes("email");
$auth_url = $g_client->createAuthUrl();
echo "<a href='$auth_url'><img src='../google-buttons/btn_google_signin_dark_normal_web.png'></a><br />";
$code = isset($_GET['code']) ? $_GET['code'] : NULL;
if(isset($code))
{
try
{
$token = $g_client->fetchAccessTokenWithAuthCode($code);
$g_client->setAccessToken($token);
}
catch (Exception $e)
{
echo $e->getMessage();
}
try
{
$pay_load = $g_client->verifyIdToken();
}
catch (Exception $e)
{
echo $e->getMessage();
}
}
else
{
$pay_load = null;
}
if(isset($pay_load))
{
$sql = $pdo->prepare ('SELECT id, username, password, email, avatar FROM users WHERE email = ?');
$sql->execute (array ($pay_load['email']));
$result = $sql->fetch();
if ($result)
{
//Prijava
$hash = $result['password'];
$user_id = $result['id'];
$username = $result['username'];
$email = $result['email'];
$editor = 0;
$avatar = $result['avatar'];
if (password_verify ($pay_load['sub'], $hash))
{
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['editor'] = $editor;
$_SESSION['avatar'] = $avatar;
$_SESSION['google-user'] = 1;
header ('location:../');
}
else
{
echo 'Napačno geslo.';
}
}
else
{
//Registracija
$token_hash = password_hash ($pay_load['sub'], PASSWORD_DEFAULT);
try
{
$sql = $pdo->prepare ('INSERT INTO users(username, email, password, edit_hotels, avatar) VALUES(?, ?, ?, ?, ?)');
$sql->execute (array ($pay_load['email'], $pay_load['email'], $token_hash, 0, 'https://testing.aristovnik.com/hoteli/assets/avatars/default/profile.png'));
$sql1 = $pdo->prepare ('SELECT id, username, email, avatar FROM users WHERE email = ?');
$sql1->execute (array ($pay_load['email']));
$result1 = $sql1->fetch();
$_SESSION['user_id'] = $result1['id'];
$_SESSION['username'] = $result1['username'];
$_SESSION['email'] = $result1['email'];
$_SESSION['editor'] = 0;
$_SESSION['avatar'] = $result1['avatar'];
$_SESSION['google-user'] = 1;
header ('location:../');
}
catch (PDOException $e)
{
echo 'Error: ' . $e->getMessage();
}
}
}
?>
<br />
<a href="../registracija/" class="button-standard">Registriraj se</a>
</div>
</div>
</body>
</html>
<file_sep>/prijava/checklogin.php
<?php
//Zahtevam povezavo na bazo
require_once ('../x/dbconn.php');
//Preverim če so bili podatki poslani
if ( isset ($_POST['submit']))
{
//Trim-am vse vrednosti, ki jih dobim iz poslanih podatkov in jih shranim v nove spremenljivke
$email = trim ($_POST['email']);
$password = trim ($_POST['password']);
//V spremenljivko result si zabeležim geslo, id in uporabniško ime
$sql = $pdo->prepare("SELECT password, id, username, edit_hotels, avatar FROM users WHERE email=?");
$sql->execute(array($email));
$result = $sql->fetch();
//V spremenljivko result si zabeležim geslo, id in uporabniško ime
$sql1 = $pdo->prepare("SELECT password, id, username FROM admin WHERE email=?");
$sql1->execute(array($email));
$result1 = $sql1->fetch();
//Izpraznim session spremenljivko za errorje in nastavim err spremenljivko na 0
session_start();
$_SESSION['err'] = "";
//Preverim če je epošta pravilna
if (!$result && !$result1)
{
$_SESSION['err'] = "Epošta je napačna.";
header ("Location: ./");
exit;
}
//Shranim si vrednosti iz result v nove spremenljivke
if ($result)
{
$hash = $result['password'];
$user_id = $result['id'];
$username = $result['username'];
$editor = $result['edit_hotels'];
$avatar = $result['avatar'];
}
else if ($result1)
{
$hash = $result1['password'];
$user_id = $result1['id'];
$username = $result1['username'];
}
//Preverim, če je geslo pravilno in si nato v sejo shranim id uporabnika, uporabniško ime in epošto
if (password_verify ($password, $hash))
{
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['editor'] = $editor;
$_SESSION['avatar'] = $avatar;
if ($username == "admin")
{
$_SESSION['admin'] = true;
header("Location: ../admin/");
exit;
}
else
{
header("Location: ../");
exit;
}
}
else
{
$_SESSION['err'] .= "Geslo je napačno.";
header ('Location: ./');
exit;
}
}
//Če podatki niso bili poslani ga preusmerim na stran s formo
else
{
header ("Location: ./");
exit;
}
?><file_sep>/iud/izbrisi_hotel.php
<?php
include ('../x/dbconn.php');
$sql = 'DELETE FROM hotel_logins WHERE hotel_id = ?';
$stmt = $pdo->prepare ($sql)->execute ([$_GET['y']]);
$sql = 'DELETE FROM hotels WHERE id = ?';
$stmt = $pdo->prepare ($sql)->execute ([$_GET['y']]);
header ('location:../');
?><file_sep>/README.md
# Hoteli
V tej datoteki bom predstavil spletno aplikacijo te [GitHub](https://github.com) strani.
<br><br>
Ta aplikacija omogoča vnašanje hotelov in prijavo na njih.<br>
### Kazalo:
[Prijava in registracija](#prijava-in-registracija)<br>
[Administrator](#administrator)<br>
[Uporabniki](#uporabniki)<br>
[Upravljanje hotelov](#upravljanje-hotelov)<br>
[Slika baze](#slika-baze)
## Prijava in registracija
### 1. Registracija
V spletno aplikacijo se lahko prijaviš na dva načina:<br>
- preko navadne registracije na spletni strani (datoteke se nahajajo v /registracija)
- preko Google API (z svojim Google računom)
### 2. Prijava
Tako kot registracija, se lahko v to spletno aplikacijo prijavite na dva načina:<br>
- z navadno prijavo (nahaja se v /prijava)
- z Google API (ki shrani podatke, če si se že prijavil kdaj prej)
## Administrator
Administrator je v posebni tabeli in je ločen od ostalega dela podatkovne baze.<br>
Datoteke administratorske strani se nahajajo v /admin .
Funkcija administratorja je da upravlja s ponudniki hotelov.<br>
Ima pa možnost dveh funkcij:<br>
- Dodajanje ponudnikov (vpiše e-naslov in geslo)
- Brisanje ponudnikov (izbere iz seznama ponudnikov (ta funkcija izbriše tudi vse hotele tega ponudnika))
## Uporabniki
Vsi uporabniki, ko so prijavljeni, lahko spreminjajo uporabniško ime in sliko profila, in če niso prijavljeni preko Google API lahko spreminjajo tudi geslo.
### 1. Ponudniki
Ponudniki imajo tri funkcije:<br>
- Dodajanje hotelov
- Urejanje hotelov (le svojih)
- Brisanje hotelov (le svojih)
### 2. Navadni uporabniki
Navadni uporabniki so tisti, ki se registrirajo na normalen način, bodisi preko Google API ali preko /registracija .<br>
Nimajo nobenih posebnih možnosti razen:<br>
- Prijava na hotele, ki so na voljo
## Upravljanje hotelov
Pri upravljanu hotelov obstajajo tri funkcije:
- Dodajanje
- Urejanje
- Brisanje
<br>
Za dodajanje in urejanje je stvar podobna.<br>
Prikaže se nam obrazec, kjer imamo označene vse atribute, ki jih moramo vpisati, ko jih vpišemo/uredimo se to shrani v podatkovno bazo. Te funkcije pa se nahajajo v /iud . <br>
### Slika baze:

| 6ba3545af345a2c1384d4b27578b9a09cc179935 | [
"JavaScript",
"SQL",
"Markdown",
"PHP"
] | 22 | PHP | masterdodo/Hoteli | dacde95f73f8f306175e61be259f72ed8c2a1c93 | b33f2975a95b89d24e08461f065a2e451a156fc2 | |
refs/heads/master | <repo_name>dberman4/TicTacToe<file_sep>/P11.java
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
public class P11 {
private static final int STARTING_MOVE = 4; // the first move of the player X
private static char winner;
private static int numOptimalSolutions = 0;
public static void main(String[] args) {
// contains 'X' or 'O' or '\0'(empty)
char[][] board = new char[3][3];
// put the first 'X' on the board according to the first move
board[STARTING_MOVE/3][STARTING_MOVE%3] = 'X';
// now solve for all optimal solutions of the game given initial state
System.out.println("Printing all optimal solutions:");
minPlayer(new Move(STARTING_MOVE, null), board);
System.out.println("Total # of optimal solutions = " + numOptimalSolutions);
//printBoard(board);
}
/**
* Checks if the game is over a
* @param board
* @return
*/
private static String gameStatus(char[][] board){
for (int i = 0; i < 3; i++){
// check horizontal lines && vertical lines for player x
if ((board[i][0] == 'X' && board[i][1] == 'X' && board[i][2] == 'X') ||
(board[0][i] == 'X' && board[1][i] == 'X' && board[2][i] == 'X')){
winner = 'X';
return "true";
}
}
//check diags for x
if ((board[0][0] == 'X' && board[1][1] == 'X' && board[2][2] == 'X') ||
(board[0][2] == 'X' && board[1][1] == 'X' && board[2][0] == 'X')){
winner = 'X';
return "true";
}
for (int i = 0; i < 3 ; i++) {
// check horizontal and vertical lines for player o
if ((board[i][0] == 'O' && board[i][1] == 'O' && board[i][2] == 'O') ||
(board[0][i] == 'O' && board[1][i] == 'O' && board[2][i] == 'O')){
winner = 'O';
return "true";
}
}
//check diags for o
if ((board[0][0] == 'O' && board[1][1] == 'O' && board[2][2] == 'O') ||
(board[0][2] == 'O' && board[1][1] == 'O' && board[2][0] == 'O')){
winner = 'O';
return "true";
}
// check for tie
int emptyCells = 9;
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
if (board[i][j]!='\0') emptyCells -= 1;
}
}
// if all cells are filled, game is over with a tie
if (emptyCells == 0) return "tie";
// otherwise game is not over and return false
//printBoard(board);
return "false";
}
/**
*
* @param board
* Testing method to print board
*/
private static void printBoard(char[][] board){
for (int i=0; i<3; i++) {
System.out.println(Arrays.toString(board[i]));
}
}
/**
*
* @param board
* @return
* Finds all available moves
*/
private static HashSet<Integer> findPossibleMoves(char[][] board){
HashSet<Integer> possibleMoves = new HashSet<Integer>();
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
if (board[i][j] == '\0') possibleMoves.add(3*i+j);
}
}
return possibleMoves;
}
/**
*
* @param n
* @param board
* Finds the move for the min player
*/
private static void minPlayer(Move n, char[][] board){
// if game is over, print out the optimal path
if (gameStatus(board).equals("true") || gameStatus(board).equals("tie")){
StringBuilder sb = new StringBuilder();
sb.append(String.valueOf(n.getLocation()));
numOptimalSolutions += 1;
// get the entire path for the game
while(n.getBacktracker() != null){
n = n.getBacktracker();
sb.append(n.getLocation());
}
// print out the optimal path to the console
System.out.println(sb.reverse());
return;
}
// else if game isn't over, need to find next optimal move
HashMap<Integer, HashSet<Integer>> Beta = new HashMap<Integer, HashSet<Integer>>();
HashSet<Integer> possibleMoves = findPossibleMoves(board);
for (Integer move: possibleMoves){
char[][] updatedBoard = new char[3][3];
// modifiedBoard should be a copy of the board
for (int row = 0; row < 3; row++){
for (int col = 0; col < 3; col++){
updatedBoard[row][col] = board[row][col];
}
}
// try putting 'O' on the empty cells
updatedBoard[move/3][move%3]='O';
// check the new game set up and find out which moves are optimal
int currentScore = getMaxScore(updatedBoard);
HashSet<Integer> hashSet;
if (!Beta.keySet().contains(currentScore)) hashSet = new HashSet<Integer>();
else hashSet = Beta.get(currentScore);
hashSet.add(move);
Beta.put(currentScore, hashSet);
}
int min_val = 100;
for (Integer key: Beta.keySet()){
if (key < min_val) min_val = key;
}
// get the positions for all optimal moves
HashSet<Integer> optimalActions = Beta.get(min_val);
// try all optimal moves
for (Integer move: optimalActions){
char[][] updatedBoard = new char[3][3];
for (int row = 0; row < 3; row++){
for (int col = 0; col < 3; col++){
updatedBoard[row][col] = board[row][col];
}
}
// make the move
updatedBoard[move/3][move%3] = 'O';
// give a chance to the opponent to play
maxPlayer(new Move(move,n), updatedBoard);
}
}
/**
*
* @param n
* @param board
* Similar to minPlayer method w/ minor changes for max player
*/
private static void maxPlayer(Move n, char[][] board){
// if game is over, print out the optimal path
if (gameStatus(board).equals("true") || gameStatus(board).equals("tie")){
StringBuilder sb = new StringBuilder();
sb.append(String.valueOf(n.getLocation()));
numOptimalSolutions += 1;
while(n.getBacktracker() != null){
n = n.getBacktracker();
sb.append(n.getLocation());
}
System.out.println(sb.reverse());
return;
}
// else if game isn't over, need to find next optimal move
HashMap<Integer, HashSet<Integer>> Alpha = new HashMap<Integer, HashSet<Integer>>();
HashSet<Integer> possibleMoves = findPossibleMoves(board);
for (Integer move: possibleMoves){
char[][] modifiedBoard = new char[3][3];
for (int row = 0; row < 3; row++){
for (int col = 0; col < 3; col++){
modifiedBoard[row][col] = board[row][col];
}
}
// try putting 'X' on an empty cell
modifiedBoard[move/3][move%3]='X';
// check the new game set up and find all optimal moves
int currentScore = getMinScore(modifiedBoard);
HashSet<Integer> hashSet;
if (!Alpha.keySet().contains(currentScore)) hashSet = new HashSet<Integer>();
else hashSet = Alpha.get(currentScore);
hashSet.add(move);
Alpha.put(currentScore, hashSet);
}
int max_val = -100;
for (Integer key: Alpha.keySet()){
if (key > max_val) max_val = key;
}
// get the positions for all optimal moves
HashSet<Integer> optimalActions = Alpha.get(max_val);
// try all optimal moves
for (Integer move: optimalActions){
char[][] updatedBoard = new char[3][3];
for (int row = 0; row < 3; row++){
for (int col = 0; col < 3; col++){
updatedBoard[row][col] = board[row][col];
}
}
// make the move
updatedBoard[move/3][move%3] = 'X';
// give the chance to opponent to make a move
minPlayer(new Move(move,n), updatedBoard);
}
}
/**
*
* @param board
* @return
* Best score possible for min player
*
*/
private static int getMinScore(char[][] board){
String result = gameStatus(board);
if (result.equals("true") && winner == 'X') return 1; //if x won
else if (result.equals("true") && winner == 'O') return -1;//if o won
else if (result.equals("tie")) return 0; //if tie
else {
int bestScore = 10;
HashSet<Integer> possibleMoves = findPossibleMoves(board);
for (Integer move: possibleMoves){
char[][] modifiedBoard = new char[3][3];
for (int row = 0; row < 3; row++){
for (int col = 0; col < 3; col++){
modifiedBoard[row][col] = board[row][col];
}
}
modifiedBoard[move/3][move%3]='O';
int currentScore = getMaxScore(modifiedBoard);
if (currentScore < bestScore) bestScore = currentScore;
}
return bestScore;
}
}
/**
* Gets best possible score for max player
* @param board
* @return
*/
private static int getMaxScore(char[][] board){
String result = gameStatus(board);
if (result.equals("true") && winner == 'X') return 1; //if x won
else if (result.equals("true") && winner == 'O') return -1;//if O won
else if (result.equals("tie")) return 0; //if tie
else {
int bestScore = -10;
HashSet<Integer> possibleMoves = findPossibleMoves(board);
for (Integer move: possibleMoves){
char[][] modifiedBoard = new char[3][3];
for (int row = 0; row < 3; row++){
for (int col = 0; col < 3; col++){
modifiedBoard[row][col] = board[row][col];
}
}
modifiedBoard[move/3][move%3]='X';
int currentScore = getMinScore(modifiedBoard);
if (currentScore > bestScore){
bestScore = currentScore;
}
}
return bestScore;
}
}
}
| d338eed3c4c9f3bf067292225ff8e9342d96a455 | [
"Java"
] | 1 | Java | dberman4/TicTacToe | 815483d928e5cd83a9e102d1734e325666f69e91 | 075def32bb758f89ef469655ea769ac3dcc3dce1 | |
refs/heads/master | <file_sep>import os, sys
lib_path = os.path.abspath(os.path.join('..'))
# cur_dir_path = os.path.abspath(os.path.join('.'))
sys.path.append(lib_path)
# sys.path.append(cur_dir_path)
import unittest
import proj10
import cards1
import cards
import pickle
cards = cards1
class TestProj10(unittest.TestCase):
"""
Tests for CSE 231 Project 10.
Students must have used a main() function in order for this
to work out smoothly. The program was originally interactive
for input and it would intrude on the test process if we
cannot prevent the main loop of the students' code before
running our tests.
An example to a solution for a problem like this can be found
at the bottom of the proj10.py file provided as a sample
with this test. It uses the global __name__ variable.
This way, we can import the module to use the functions like
we have for this test, and run the proj10.py alone for regular
output.
Functions Tested:
- setup_game
- valid_fnd_move
- valid_tab_move
"""
"""
Helper functions
"""
def grab_test_tab_col(self, length=1):
"""
Returns:
Tableau column default initialized with desired length.
Choose a length 1 - 7 inclusive
"""
if not (1 <= length and length <= 7):
raise ValueError("1 - 7 tab length required for grab_test_tab_col.")
return self._tab[length - 1][:]
def setUp(self):
"""
Initialize a game.
"""
# re-route cards to cards1
# grab a few cards
self._heart_two_card = cards.Card(rank=2, suit=3)
self._heart_three_card = cards.Card(rank=3, suit=3)
self._club_two_card = cards.Card(rank=2, suit=1)
self._club_three_card = cards.Card(rank=3, suit=1)
# face down card
self._face_down_card = cards.Card(rank=1, suit=3)
if self._face_down_card.is_face_up():
self._face_down_card.flip_card()
# with open('enbody_game_elements.pckl', 'wb') as outfile:
# (fnd, tab, stock, waste) = proj10.setup_game()
# enbody_game_elements = {'tab': tab, 'fnd':fnd, 'stock': stock, 'waste': waste}
# pickle.dump(enbody_game_elements, outfile)
self._enbody_game_elements_dict = {} # temp
try:
with open('./enbody_game_elements.pckl', 'rb') as infile:
enbody_game_elements_dict = pickle.load(infile)
self._fnd = enbody_game_elements_dict['fnd']
self._tab = enbody_game_elements_dict['tab']
self._waste = enbody_game_elements_dict['waste']
self._stock = enbody_game_elements_dict['stock']
except FileNotFoundError:
raise FileNotFoundError('enbody_game_elements.pckl is required for this test.')
def tearDown(self):
"""
Teardown, nothing to do.
"""
pass
"""
Tests
"""
def testSetupGameFunctionTableau(self):
"""
setup_game() -> tableau
Testing tableau from setup_game.
"""
# grab a test game
fnd, tab, stock, waste = proj10.setup_game()
# tableau
self.assertListEqual(tab, self._tab,
msg='Tableau was not distributed in the correct manner. Check project PDF.\
Are you sure your project is using cards1.py?')
def testSetupGameFunctionStock(self):
"""
setup_game() -> stock
Testing stock from setup_game.
"""
# grab a test game
fnd, tab, stock, waste = proj10.setup_game()
# stock
self.assertEqual(stock, self._stock,
msg='Stock was not setup in the correct manner.\nSize = {}.\nCheck the project PDF.\
Are you sure your project is using cards1.py?'.format(len(stock)))
def testSetupGameFunctionWaste(self):
"""
setup_game() -> waste
Testing waste from setup_game.
"""
# grab a test game
fnd, tab, stock, waste = proj10.setup_game()
# waste
self.assertListEqual(waste, self._waste,
msg='Waste was not setup in the correct manner.\nSize = {}\nIt should have one card. Check the project PDF.\
Are you sure your project is using cards1.py?'.format(len(waste)))
# not used for project scoring
'''
def testSetupGameFunction(self):
"""
setup_game() -> tableau
Tests the setup_game function by checking all of its return values
against the ouput from Dr.Enbody's solution.
"""
# grab a test game
fnd, tab, stock, waste = proj10.setup_game()
# Check all of the elements to ensure the game was setup correctly.
#
# foundation
self.assertListEqual(fnd, self._fnd,
msg='Foundation should be a list containing 4 empty lists initially.')
# tableau
self.assertListEqual(tab, self._tab,
msg='Tableau was not distributed in the correct manner. Check project PDF.\
Are you sure your project is using cards1.py?')
# stock
self.assertListEqual(stock, self._stock,
msg='Stock was not setup in the correct manner. Check the project PDF.\
Are you sure your project is using cards1.py?')
# waste
self.assertListEqual(waste, self._waste,
msg='Waste was not setup in the correct manner. It should have one card Check t eh project PDF.\
Are you sure your project is using cards1.py?')
'''
def testValidFoundationMoveFunction(self):
"""
valid_fnd_move(src_card : cards.Card, dest_Card : cards.Card)
Returns:
True - if move is valid based on requirements below.
Moving one card to a foundation must satisfy these conditions.
- src_card and dest_card be face_up
- src_card and dest_card have the SAME suit.
- src_card.rank() is 1 greater than dest_card.rank()
~ src_card == 11, dest_card == 10, good.
"""
# test face down
self.assertFalse(proj10.valid_fnd_move(self._face_down_card, self._heart_two_card),
msg="A face down src_card is not a valid move.")
# test diff suits
self.assertFalse(proj10.valid_fnd_move(self._heart_three_card, self._club_two_card),
msg="src_card must have same suit as dest_card.")
# test low src_card rank
self.assertFalse(proj10.valid_fnd_move(self._heart_two_card, self._heart_two_card),
msg="src_card must have rank 2 higher than dest_card.")
# test good input
self.assertTrue(proj10.valid_fnd_move(self._heart_three_card, self._heart_two_card),
msg="src_card with rank 1 higher than the dest_card and with same suit as dest_card is valid input.")
def testValidTableauMoveFunction(self):
"""
valid_tab_move(src_card : cards.Card, dest_Card : cards.Card)
Returns:
True - if move is valid based on requirements below.
Moving one card to a tabluea must satisfy these conditions
- src_card and dest_card be face_up
- src_card and dest_card have the DIFF suit.
- src_card.rank() is 1 less than dest_card.rank()
~ src_card == 10, dest_card == 11, good.
"""
# test face down
self.assertFalse(proj10.valid_tab_move(self._face_down_card, self._heart_two_card),
msg="A face down src_card is not a valid move.")
self.assertFalse(proj10.valid_tab_move(self._heart_two_card, self._face_down_card),
msg="A face down dest_card is not a valid move.")
# test same suits
self.assertFalse(proj10.valid_tab_move(self._heart_two_card, self._heart_three_card),
msg="src_card must have different suit than dest_card.")
# test low dest_card rank
self.assertFalse(proj10.valid_tab_move(self._heart_three_card, self._club_two_card),
msg="src_card must have rank 2 higher than dest_card.")
# test good input
self.assertTrue(proj10.valid_tab_move(self._heart_two_card, self._club_three_card),
msg="dest_card with rank 1 higher than the src_card and with diff suit than dest_card is valid input.")
# tableau_to_foundation empty test
def testTableauToFoundationEmptyPushBad(self):
"""
tableau_to_foundation(tab_col : list, fnd_col : list)
Returns:
None
This test ensures pushing a card != ace to an empty fnd fails.
"""
# test empty foundation
with self.assertRaises(RuntimeError, msg="Empty foundation should throw error when passing a card that is not an ace."):
# 2 of clubs
test_card = cards.Card(rank=2, suit=1)
test_tab = self.grab_test_tab_col(1)
test_tab.append(test_card)
proj10.tableau_to_foundation(test_tab, [])
def testTableauToFoundationEmptyPushGood(self):
"""
tableau_to_foundation(tab_col : list, fnd_col : list)
Returns:
None
This test ensures pushing an ace to an empty fnd succeeds.
"""
# test adding ace to empty foundation
#
# ace of clubs
test_card = cards.Card(rank=1, suit=1)
test_tab = self.grab_test_tab_col(1)
test_tab.append(test_card)
test_fnd = []
proj10.tableau_to_foundation(test_tab, test_fnd)
self.assertEqual(test_card, test_fnd[-1],
msg="Pushing ace to an empty fnd should work fine.")
# tableau_to_foundation rank test
def testTableauToFoundationRankBad(self):
"""
tableau_to_foundation(tab_col : list, fnd_col : list)
Returns:
None
Good suit, bad rank.
"""
with self.assertRaises(RuntimeError, msg="Pushing a card to fnd requires it to the cards \
rank to be no more than 1 greater than the dest_card."):
# test source tableau
test_tab_col_src = [cards.Card(rank=3, suit=1)]
# test destination foundation with an ace on top
test_fnd_col_dest = [cards.Card(rank=1, suit=1)]
proj10.tableau_to_foundation(test_tab_col_src, test_fnd_col_dest)
# tableau_to_foundation suit test
def testTableauToFoundationSuitGoodRankGood(self):
"""
tableau_to_foundation(tab_col : list, fnd_col : list)
Returns:
None
Good suit, good rank.
"""
# test source tableau
test_src_card = cards.Card(rank=2, suit=1)
test_tab_col_src = [test_src_card]
# test destination foundation with an ace on top
test_fnd_col_dest = [cards.Card(rank=1, suit=1)]
proj10.tableau_to_foundation(test_tab_col_src, test_fnd_col_dest)
self.assertTrue(test_fnd_col_dest[-1] == test_src_card,
msg="tab_to_fnd should succed if tab[-1] is same suit as dest.")
def testTableauToFoundationSuitBad(self):
"""
tableau_to_foundation(tab_col : list, fnd_col : list)
Returns:
None
Bad suit, good rank.
"""
with self.assertRaises(RuntimeError, msg="Pushing a card to fnd requires it to the cards have same suit."):
# test source tableau
test_tab_col_src = [cards.Card(rank=2, suit=2)]
# test destination foundation with an ace on top
test_fnd_col_dest = [cards.Card(rank=1, suit=1)]
proj10.tableau_to_foundation(test_tab_col_src, test_fnd_col_dest)
# tableau_to_foundation face test
def testTableauToFoundationFaceGood(self):
"""
tableau_to_foundation(tab_col : list, fnd_col : list)
Returns:
None
Good suit, good rank, face up.
"""
# test source tableau
test_src_card = cards.Card(rank=2, suit=1)
if not test_src_card.is_face_up():
test_src_card.flip_card()
test_tab_col_src = [test_src_card]
# test destination foundation with an ace on top
test_fnd_col_dest = [cards.Card(rank=1, suit=1)]
proj10.tableau_to_foundation(test_tab_col_src, test_fnd_col_dest)
self.assertTrue(test_fnd_col_dest[-1] == test_src_card,
msg="tab_to_fnd should succeed if tab[-1] is face up.")
def testTableauToFoundationFaceBad(self):
"""
tableau_to_foundation(tab_col : list, fnd_col : list)
Returns:
None
Bad suit, good rank.
"""
with self.assertRaises(RuntimeError, msg="Pushing a card to fnd requires it to the src_card be face up."):
test_src_card = cards.Card(rank=2, suit=1)
if test_src_card.is_face_up():
test_src_card.flip_card()
# test source tableau
test_tab_col_src = [test_src_card]
# test destination foundation with an ace on top
test_fnd_col_dest = [cards.Card(rank=1, suit=1)]
proj10.tableau_to_foundation(test_tab_col_src, test_fnd_col_dest)
# tableau_to_foundation last card in tableau face up
def testTableauToFoundationFlipLastTabCard(self):
"""
tableau_to_foundation(tab_col : list, fnd_col : list)
Returns:
None
Card at the bottom of the source tab_col should be flipped up.
"""
test_tab_col = self.grab_test_tab_col(2)
# flip the last card and push something that is a valid move
test_tab_col[-1].flip_card()
test_tab_col.append(cards.Card(rank=2, suit=1))
test_fnd = [cards.Card(rank=1, suit=1)]
proj10.tableau_to_foundation(test_tab_col, test_fnd)
self.assertTrue(test_tab_col[-1].is_face_up(),
msg="Card at the bottom of a tableau cannot be face down after valid tab_to_fnd move.")
# waste_to_foundation rank test
def testWasteToFoundationRankBad(self):
"""
waste_to_foundation(waste : list, fnd_col : list)
Returns:
None
Good suit, bad rank.
"""
with self.assertRaises(RuntimeError, msg="Pushing a card to fnd requires it to the cards \
rank to be 1 higher than what is on the top of the fnd."):
# test source waste
test_waste_src = [cards.Card(rank=3, suit=1)]
# test destination foundation with an ace on top
test_fnd_col_dest = [cards.Card(rank=1, suit=1)]
try:
proj10.waste_to_foundation(test_waste_src, test_fnd_col_dest)
except TypeError as e:
# print("Dr. Enbody may have caused some students to add/not add the source parameter to this method. We try both.", str(e))
proj10.waste_to_foundation(test_waste_src, test_fnd_col_dest, [])
# waste_to_foundation suit test
def testWasteToFoundationSuitBad(self):
"""
waste_to_foundation(waste : list, fnd_col : list)
Returns:
None
Bad suit, good rank.
"""
with self.assertRaises(RuntimeError, msg="Pushing a card to fnd requires it to the cards have same suits."):
# test source waste
test_waste_src = [cards.Card(rank=2, suit=2)]
# test destination foundation with an ace on top
test_fnd_col_dest = [cards.Card(rank=1, suit=1)]
try:
proj10.waste_to_foundation(test_waste_src, test_fnd_col_dest)
except TypeError as e:
proj10.waste_to_foundation(test_waste_src, test_fnd_col_dest, [])
def testWasteToFoundationRankGoodSuitGood(self):
"""
waste_to_foundation(waste : list, fnd_col : list, stock : Deck)
Returns:
None
Good suit, good rank.
"""
# test source tableau
test_src_card = cards.Card(rank=2, suit=1)
test_src_waste = [test_src_card]
# test destination foundation with an ace on top
test_fnd_col_dest = [cards.Card(rank=1, suit=1)]
#
try:
proj10.waste_to_foundation(test_src_waste, test_fnd_col_dest)
except TypeError as e:
proj10.waste_to_foundation(test_src_waste, test_fnd_col_dest, [])
self.assertTrue(test_fnd_col_dest[-1] == test_src_card,
msg="tab_to_fnd should succed if tab[-1] is 1 rank higher than dest.")
# waste_to_foundation empty test
def testWasteToFoundationEmptyBad(self):
"""
waste_to_foundation(waste : list, fnd_col : list, stock : Deck)
Returns:
None
Empty waste should throw a runtime error
"""
with self.assertRaises(RuntimeError, msg="If waste is empty, exception should be thrown when used."):
# test waste
test_waste = []
# test destination foundation with an ace on top
test_fnd_col_dest = [cards.Card(rank=1, suit=1)]
proj10.tableau_to_foundation(test_waste, test_fnd_col_dest)
# waste_to_tableau rank/suit tests
def testWasteToTableauRankBad(self):
"""
waste_to_tableau(waste : list, tab_col : list, stock : Deck)
Returns:
None
Good suit, bad rank.
"""
with self.assertRaises(RuntimeError, msg="Pushing a card to fnd that is not one rank lower\
than the rank of what is on the top of the fnd is an error."):
# test source waste
test_waste_src = [cards.Card(rank=1, suit=2)]
# test destination foundation with an ace on top
test_tab_col_dest = [cards.Card(rank=3, suit=1)]
try:
proj10.waste_to_tableau(test_waste_src, test_tab_col_dest)
except TypeError as e:
proj10.waste_to_tableau(test_waste_src, test_tab_col_dest, [])
def testWasteToTableauSuitBad(self):
"""
waste_to_tableau(waste : list, tab_col : list, stock : Deck)
Returns:
None
Bad suit, bad rank.
"""
with self.assertRaises(RuntimeError, msg="Pushing a card to tab with same suit as tab[-1] is an error."):
# test source waste
test_waste_src = [cards.Card(rank=1, suit=1)]
# test destination foundation with an ace on top
test_tab_col_dest = [cards.Card(rank=2, suit=1)]
try:
proj10.waste_to_tableau(test_waste_src, test_tab_col_dest)
except TypeError as e:
proj10.waste_to_tableau(test_waste_src, test_tab_col_dest, [])
def testWasteToTableauRankGoodSuiteGood(self):
"""
waste_to_tableau(waste : list, tab_col : list, stock : Deck)
Returns:
None
Good suit, good rank.
"""
# test source tableau
test_src_card = cards.Card(rank=1, suit=1)
test_src_waste = [test_src_card]
# test destination foundation with an ace on top
test_tab_col_dest = [cards.Card(rank=2, suit=2)]
#
try:
proj10.waste_to_tableau(test_src_waste, test_tab_col_dest)
except TypeError as e:
proj10.waste_to_tableau(test_src_waste, test_tab_col_dest, [])
self.assertTrue(test_tab_col_dest[-1] == test_src_card,
msg="tab_to_fnd should succed if tab[-1] is 1 rank higher than dest and suits are diff")
def testWasteToTableauFaceUp(self):
"""
waste_to_tableau(waste : list, tab_col : list, stock : Deck)
Returns:
None
Good suit, good rank.
"""
# test source tableau
test_src_card = cards.Card(rank=1, suit=1)
if not test_src_card.is_face_up():
test_src_card.flip_card()
test_src_waste = [test_src_card]
# test destination foundation with an ace on top
test_tab_col_dest = [cards.Card(rank=2, suit=2)]
#
try:
proj10.waste_to_tableau(test_src_waste, test_tab_col_dest)
except TypeError as e:
proj10.waste_to_tableau(test_src_waste, test_tab_col_dest, [])
self.assertTrue(test_tab_col_dest[-1] == test_src_card,
msg="tab_to_fnd should succed if source card is face up and valid.")
# stock_to_waste tests
def teststockToWasteEmptyStockBad(self):
"""
stock_to_waste(stock : Deck, waste : list<Card>)
Returns:
None
Empty stock.
"""
with self.assertRaises(RuntimeError, msg="RuntimeError should be thrown when moving from stock to waste and stock is empty."):
empty_stock = cards.Deck()
empty_stock._Deck__deck = []
waste = []
proj10.stock_to_waste(empty_stock, waste)
def teststockToWasteEmptyStockGood(self):
"""
stock_to_waste(stock : Deck, waste : list<Card>)
Returns:
None
Non-empty stock.
"""
non_empty_stock = cards.Deck()
sample_card = non_empty_stock._Deck__deck[-1]
waste = []
proj10.stock_to_waste(non_empty_stock, waste)
self.assertTrue(waste[-1] == sample_card,
msg="Non-Empty stock should move a card to the top of the tableau.")
# tableau_to_tableau empty tabluea
def testTableauToTableauEmptySrcBad(self):
"""
tableau_to_tableau(tab1: list<Card>, tab2: list<Card>, n : int)
Returns:
None
Empty src tableau.
"""
with self.assertRaises(RuntimeError, msg="RuntimeError should be thrown when src_tab is empty."):
test_empty_src_tab = []
test_dest_tab = self.grab_test_tab_col(1)
n = 1
proj10.tableau_to_tableau(test_empty_src_tab, test_dest_tab, n)
def testTableauToTableauEmptyDestGood(self):
"""
tableau_to_tableau(tab1: list<Card>, tab2: list<Card>, n : int)
Returns:
None
Non-empty src tableau and empty dest tableau.
"""
test_src_card = cards.Card(rank=2, suit=2)
test_empty_src_tab = [test_src_card]
test_dest_tab = []
n = 1
proj10.tableau_to_tableau(test_empty_src_tab, test_dest_tab, n)
self.assertTrue(test_dest_tab[-1] == test_src_card,
msg="Non-Empty src_tab should move a card to empty dest_tab.")
# tableau_to_tableau rank test
def testTableauToTableauSuitBad(self):
"""
tableau_to_tableau(tab1: list<Card>, tab2: list<Card>, n : int)
Returns:
None
Bad suit, good rank.
"""
with self.assertRaises(RuntimeError, msg="Pushing a card to tab requires the cards \
have diff suits."):
# test source tableau
test_tab_col_src = [cards.Card(rank=2, suit=1)]
# test destination foundation with an ace on top
test_tab_col_dest = [cards.Card(rank=3, suit=1)]
n = 1
proj10.tableau_to_tableau(test_tab_col_src, test_tab_col_dest, n)
def testTableauToTableauRankBad(self):
"""
tableau_to_tableau(tab1: list<Card>, tab2: list<Card>, n : int)
Returns:
None
Good suit, bad rank.
"""
with self.assertRaises(RuntimeError, msg="Pushing a card to tab requires the src_card \
rank be no more than 1 less than the dest_card."):
# test source tableau
test_tab_col_src = [cards.Card(rank=2, suit=2)]
# test destination foundation with an ace on top
test_tab_col_dest = [cards.Card(rank=1, suit=1)]
n = 1
proj10.tableau_to_tableau(test_tab_col_src, test_tab_col_dest, n)
# tableau_to_foundation suit test
def testTableauToTableauSuitGoodRankMultipleCardsGood(self):
"""
tableau_to_tableau(tab1: list<Card>, tab2: list<Card>, n : int)
Returns:
None
Good suit, good rank.
"""
# test source tableau
test_src_card = cards.Card(rank=2, suit=2)
test_tab_col_src = [test_src_card, test_src_card]
test_tab_col_src_copy = [test_src_card, test_src_card]
# test destination foundation with an ace on top
test_tab_col_dest = [cards.Card(rank=3, suit=1)]
n = 2
proj10.tableau_to_tableau(test_tab_col_src, test_tab_col_dest, n)
self.assertListEqual(test_tab_col_dest[-n:], test_tab_col_src_copy,
msg="tab_to_tab should succeed and move N items if tab[-1] is same suit as dest.")
def testTableauToTableauSuitGoodRankMultipleCardsBadTopCard(self):
"""
tableau_to_tableau(tab1: list<Card>, tab2: list<Card>, n : int)
Returns:
None
Good suit, good rank.
"""
with self.assertRaises(RuntimeError, msg="Card at top of the n stack should be checked and raise RuntimeError if it is not a valid card."):
# test source tableau
test_src_card = cards.Card(rank=2, suit=2)
test_tab_col_src = [cards.Card(rank=8, suit=2), test_src_card]
test_tab_col_src_copy = [test_src_card, test_src_card]
# test destination foundation with an ace on top
test_tab_col_dest = [cards.Card(rank=3, suit=1)]
n = 2
proj10.tableau_to_tableau(test_tab_col_src, test_tab_col_dest, n)
def testTableauToTableauSuitGoodRankGoodOneCard(self):
"""
tableau_to_tableau(tab1: list<Card>, tab2: list<Card>, n : int)
Returns:
None
Good suit, good rank.
"""
# test source tableau
test_src_card = cards.Card(rank=2, suit=2)
test_tab_col_src = [test_src_card]
# test destination foundation with an ace on top
test_tab_col_dest = [cards.Card(rank=3, suit=1)]
n = 1
proj10.tableau_to_tableau(test_tab_col_src, test_tab_col_dest, n)
self.assertTrue(test_tab_col_dest[-1] == test_src_card,
msg="tab_to_tab should succed if tab[-1] is same suit as dest.")
# tableau_to_tableau face test
def testTableauToTableauFaceDown(self):
"""
tableau_to_tableau(tab1: list<Card>, tab2: list<Card>, n : int)
Returns:
None
Good suit, good rank.
"""
with self.assertRaises(RuntimeError, msg="Face down source card should cause an error."):
# test source waste
test_tab_src = [cards.Card(rank=1, suit=2)]
if test_tab_src[-1].is_face_up():
test_tab_src[-1].flip_card()
n = 1
# test destination foundation with an ace on top
test_tab_col_dest = [cards.Card(rank=2, suit=1)]
try:
proj10.tableau_to_tableau(test_tab_src, test_tab_col_dest)
except TypeError as e:
proj10.tableau_to_tableau(test_tab_src, test_tab_col_dest, n)
def testWasteToTableauFaceUp(self):
"""
tableau_to_tableau(tab1: list<Card>, tab2: list<Card>, n : int)
Returns:
None
Good suit, good rank.
"""
# test source tableau
test_src_card = cards.Card(rank=1, suit=1)
if not test_src_card.is_face_up():
test_src_card.flip_card()
test_tab_src = [test_src_card]
n = 1
# test destination foundation with an ace on top
test_tab_col_dest = [cards.Card(rank=2, suit=2)]
#
try:
proj10.tableau_to_tableau(test_tab_src, test_tab_col_dest)
except TypeError as e:
proj10.tableau_to_tableau(test_tab_src, test_tab_col_dest, n)
self.assertTrue(test_tab_col_dest[-1] == test_src_card,
msg="tab_to_tab should succeed if source card is face up and valid.")
def testTableauToTableauFlipLastTabCard(self):
"""
tableau_to_tableau(tab1: list<Card>, tab2: list<Card>, n : int)
Returns:
None
Card at the bottom of the source tab_col should be flipped up.
"""
test_src_card = cards.Card(rank=2, suit=2)
test_tab_col_src = [self._face_down_card, test_src_card, test_src_card]
# test destination foundation with an ace on top
test_tab_col_dest = [cards.Card(rank=3, suit=1)]
n = 2
proj10.tableau_to_tableau(test_tab_col_src, test_tab_col_dest, n)
self.assertTrue(test_tab_col_src[-1].is_face_up(),
msg="Card at the bottom of the src_tab should be flipped when the move succeeds.")
if __name__ == '__main__':
with open('unittest_output.txt', 'w') as out_file:
runner = unittest.TextTestRunner(out_file)
unittest.main(testRunner=runner)
| 9eeb45dd91033ee0f83f12c5eb559a896b6a9f5b | [
"Python"
] | 1 | Python | atbe/CSE-231-Project10-UnitTest | a91c45197a80bc1c78b33d41413c3d6315857130 | 0a0ff6204200f4e16d735ec16cf59b4b5f67bfe1 | |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/// <Summary>
/// This file contains some utilities commonly used.
/// </Summary>
namespace TFSCodeCounter
{
public class CounterConfig
{
public string Tfs { get; set; }
public string Project { get; set; }
public string ServerLocation { get; set; }
public string ClientLocation { get; set; }
public string CurrentRevision { get; set; }
public string PreviousRevision { get; set; }
public string OutputFile { get; set; }
public bool IsRemain { get; set; }
}
}
<file_sep>using System;
using System.Linq;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Configuration;
using System.Windows.Forms;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.TeamFoundation.VersionControl.Client;
namespace TFSCodeCounter
{
/// <summary>
///
/// </summary>
class Program
{
/// <summary>
///
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
CounterConfig config = GetConfig();
DownloadFiles(config, "52100");
DiffCount(config);
Console.WriteLine("Press Any Key to Exit ... ...");
Console.ReadKey();
}
/// <summary>
///
/// </summary>
/// <param name="config"></param>
/// <param name="changsetID"></param>
private static void DownloadFiles(CounterConfig config, string changsetID)
{
try
{
TfsConfigurationServer configurationServer =
TfsConfigurationServerFactory.GetConfigurationServer(new Uri(config.Tfs));
// Get the catalog of team project collections
ReadOnlyCollection<CatalogNode> collectionNodes = configurationServer.CatalogNode.QueryChildren(
new[] { CatalogResourceTypes.ProjectCollection },
false, CatalogQueryOptions.None);
// List the team project collections
VersionControlServer vcs = null;
foreach (CatalogNode collectionNode in collectionNodes)
{
// Use the InstanceId property to get the team project collection
Guid collectionId = new Guid(collectionNode.Resource.Properties["InstanceId"]);
TfsTeamProjectCollection teamProjectCollection = configurationServer.GetTeamProjectCollection(collectionId);
if (!teamProjectCollection.Name.Equals(config.Project))
continue;
vcs = teamProjectCollection.GetService<VersionControlServer>();
break;
}
if (vcs == null)
throw new Exception();
var changesetList = vcs.QueryHistory(
config.ServerLocation,
VersionSpec.Latest,
0,
RecursionType.Full,
null,
null,
VersionSpec.ParseSingleSpec(changsetID, null),
1,
true,
false).Cast<Changeset>();
foreach (var cs in changesetList)
{
var change = cs.Changes;
foreach (var itemList in change)
{
if (itemList.Item == null)
continue;
string ServerItem = itemList.Item.ServerItem;
var itemChgs = vcs.QueryHistory(itemList.Item.ServerItem,
VersionSpec.Latest,
0,
RecursionType.Full,
null,
null,
VersionSpec.ParseSingleSpec(changsetID, null),
2,
true,
false);
int index = 0;
foreach (Changeset itemchg in itemChgs)
{
string revisionpath = (index == 0) ? config.CurrentRevision : config.PreviousRevision;
string localItem = config.ClientLocation + @"\" + revisionpath + @"\" + changsetID;
localItem += ServerItem.Substring(config.ServerLocation.Length);
//public enum ChangeType
//{
// None = 1,
// Add = 2,
// Edit = 4,
// Encoding = 8,
// Rename = 16,
// Delete = 32,
// Undelete = 64,
// Branch = 128,
// Merge = 256,
// Lock = 512,
// Rollback = 1024,
// SourceRename = 2048,
// Property = 8192
//}
if (!itemchg.Changes[0].ChangeType.HasFlag(ChangeType.Delete))
vcs.DownloadFile(ServerItem, 0, VersionSpec.ParseSingleSpec(Convert.ToString(itemchg.ChangesetId), null), localItem);
++index;
}
}
}
}
catch (ChangesetNotFoundException)
{
Console.WriteLine("!! Please check the change set id inside your config file !!");
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private static CounterConfig GetConfig()
{
string file = Application.ExecutablePath;
Configuration config = ConfigurationManager.OpenExeConfiguration(file);
CounterConfig counterCfg = new CounterConfig();
counterCfg.Tfs = config.AppSettings.Settings["Tfs"].Value.ToString();
counterCfg.Project = config.AppSettings.Settings["Project"].Value.ToString();
counterCfg.ServerLocation = config.AppSettings.Settings["ServerLocation"].Value.ToString();
counterCfg.ClientLocation = config.AppSettings.Settings["ClientLocation"].Value.ToString();
counterCfg.CurrentRevision = config.AppSettings.Settings["CurrentRevision"].Value.ToString();
counterCfg.PreviousRevision = config.AppSettings.Settings["PreviousRevision"].Value.ToString();
counterCfg.OutputFile = config.AppSettings.Settings["OutputFile"].Value.ToString();
counterCfg.IsRemain = Convert.ToBoolean(config.AppSettings.Settings["IsRemain"].Value);
return counterCfg;
}
/// <summary>
///
/// </summary>
/// <param name="config"></param>
private static void DiffCount(CounterConfig config)
{
string cmd = "diffcount.exe ";
cmd += config.ClientLocation + @"\" + config.PreviousRevision + " " + config.ClientLocation + @"\" + config.CurrentRevision;
cmd += " > " + config.OutputFile;
Process proc = new Process();
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
proc.StandardInput.WriteLine(cmd);
proc.StandardInput.WriteLine("exit");
proc.Close();
}
}
}
| 94acfd58c80681c8f26a634e159ca855f406630f | [
"C#"
] | 2 | C# | mummily/TFSCodeReviwer | eea9db645a0f083e7e33a6c59d80ff21ccf6bd34 | 398f0d3c0244105623c146a0c6d0bfc22c98abfb | |
refs/heads/master | <repo_name>stackbit-projects/smart-lavender-18342<file_sep>/gatsby-config.js
require('dotenv').config()
module.exports = {
siteMetadata: {
title: `Gatsby Agency Portfolio`,
description: `A portfolio for your creative shop`,
author: `@JacobKnaack`,
},
plugins: [
`gatsby-plugin-eslint`,
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `gatsby-agency-portfolio`,
short_name: `GAP`,
start_url: `/`,
icon: `src/images/gap_logo.svg`,
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
`gatsby-plugin-sass`,
`gatsby-plugin-styled-components`,
{
resolve: `gatsby-plugin-less`,
options: {
javascriptEnabled: true,
}
},
{
resolve: `gatsby-source-cosmicjs`,
options: {
bucketSlug: process.env.COSMIC_BUCKET_SLUG,
objectTypes: [`pages`, `people`, `services`, `projects`, `settings`, `connects`, `skills`, `clients`, `contacts`],
apiAccess: {
read_key: process.env.COSMIC_READ_KEY,
}
}
}
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.dev/offline
// `gatsby-plugin-offline`,
],
}
| 5e6d6833302d00a88a207d3ecc54af29b0c15b86 | [
"JavaScript"
] | 1 | JavaScript | stackbit-projects/smart-lavender-18342 | df2d8fabc24b1cdcf060ba9a8b23da2d42c03b01 | cafcd41064d3d40833122378b796b1d86d1a9ed1 | |
refs/heads/main | <repo_name>nguyenthanhlongcoder/ApplePie<file_sep>/ApplePie/ViewController.swift
//
// ViewController.swift
// ApplePie
//
// Created by Apple on 03/03/2021.
//
import UIKit
class ViewController: UIViewController {
var listOfWords = ["buccaneer", "swift", "glorious", "incandesent", "bug", "program", "hutao", "xiao", "jean", "mona", "zhongli", "CTrerach"]
let incorrectMovesAllowed = 7
var totalWins = 0{
didSet{
newRound()
}
}
var totalLoseses = 0{
didSet{
newRound()
}
}
@IBOutlet weak var treeImageView: UIImageView!
@IBOutlet weak var correctWordLabel: UILabel!
@IBOutlet var letterButtons: [UIButton]!
@IBOutlet weak var scoreLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
newRound()
}
var currentGame : Game!
func newRound() {
if !listOfWords.isEmpty{
let newWord = listOfWords.removeFirst()
currentGame = Game(word: newWord, incorectMovesRemaining: incorrectMovesAllowed, guessedLetters: [])
enableLetterButtons(true)
updateUI()
}else{
enableLetterButtons(false)
}
}
func enableLetterButtons(_ enable: Bool) {
for button in letterButtons{
button.isEnabled = enable
}
}
func updateUI() {
var letters = [String]()
for letter in currentGame.formattedWord{
letters.append(String(letter))
}
let wordWithSpacing = letters.joined(separator: " ")
correctWordLabel.text = wordWithSpacing
scoreLabel.text = "Wins: \(totalWins), Loseses: \(totalLoseses)"
treeImageView.image = UIImage(named: "Tree \(currentGame.incorectMovesRemaining)")
}
@IBAction func letterButtonPressed(_ sender: UIButton) {
sender.isEnabled = false
let letterString = sender.title(for: .normal)!
let letter = Character(letterString.lowercased())
if currentGame.playerGuessed(letter: letter){
sender.setTitleColor(.green, for: .normal)
}else{
sender.setTitleColor(.red, for: .normal)
}
updateGameState()
}
func updateGameState(){
if currentGame.incorectMovesRemaining == 0{
totalLoseses += 1
}else if currentGame.word == currentGame.formattedWord{
totalWins += 1
}else{
updateUI()
}
}
}
| a6dd2cc131c45ef575fe81d9249e64435a89e9b8 | [
"Swift"
] | 1 | Swift | nguyenthanhlongcoder/ApplePie | 52838c40a201f104f83c732d66ff5c98daaba695 | 0b8f37e3bcf93453f128efb7b6eae5c906953afa | |
refs/heads/master | <repo_name>briandixn/python_scrapper<file_sep>/prac.py
"""for the shell . ./venv/bin/activate"""
from bs4 import BeautifulSoup
from mathematicians import simple_get
"""from the blog"""
raw_html = simple_get('https://realpython.com/blog/')
"""----len(raw_html)"""
g_html = simple_get('https://soundcloud.com/theaipodcast')
a_html = simple_get('https://soundcloud.com/a16z')
r_html = simple_get('https://www.reddit.com/r/artificial/')
t_html = simple_get('https://soundcloud.com/techemergence')
ag_html = BeautifulSoup(g_html, 'html.parser')
aa_html = BeautifulSoup(a_html, 'html.parser')
"""ar_html = BeautifulSoup(r_html, 'html.parser')"""
at_html = BeautifulSoup(t_html, 'html.parser')
#only sound cloud works
"""for i, li in enumerate(ag_html.select('li')):"""
""" print (i, li.text)"""
print("a16z")
for i, a in enumerate(aa_html.select('a')):
if i < 20:
print (i, a.text)
print("techemergence")
for i, a in enumerate(at_html.select('a')):
if i < 20:
print (i, a.text)
print("AIpodcast")
for i, a in enumerate(at_html.select('a')):
if i < 20:
print (i, a.text) | efad2ba7044e0fae50040fc6ae144f6acd74fb41 | [
"Python"
] | 1 | Python | briandixn/python_scrapper | ca5cfff8b01c847dfaa6733798532dcd1969e485 | 0f30a25af3beffd9197816fd65e4d56d8ed36dbd | |
refs/heads/master | <file_sep>def calculate_discount(item_cost, relative_discount, absolute_discount):
if item_cost < 0:
raise ValueError("Item cost cannot be negative")
elif item_cost == 0:
raise ValueError("Item cost cannot be zero")
if relative_discount < 0:
raise ValueError("Relative discount cannot be negative")
elif relative_discount > 100:
raise ValueError("Relative discount cannot be more than 100")
if absolute_discount < 0:
raise ValueError("Absolute discount cannot be negative")
elif absolute_discount > item_cost:
raise ValueError("Absolute discount cannot be more than item cost")
final_price = item_cost - (item_cost * relative_discount/100) - absolute_discount
if final_price < 0:
raise ValueError("Final price cannot be negative")
return final_price
<file_sep>import unittest
from discount_calculator import calculate_discount
class DiscountCalculatorTests(unittest.TestCase):
def testNegativeItemCost(self):
with self.assertRaises(ValueError):
final_price = calculate_discount(-200, 10, 30)
def testZeroItemCost(self):
with self.assertRaises(ValueError):
final_price = calculate_discount(0, 10, 30)
def testNegativeRelativeDiscount(self):
with self.assertRaises(ValueError):
final_price = calculate_discount(200, -10, 30)
def testZeroRelativeDiscount(self):
final_price = calculate_discount(200, 0, 30)
self.assertEqual(final_price, 170)
def testLargeRelativeDiscount(self):
with self.assertRaises(ValueError):
final_price = calculate_discount(200, 110, 30)
def testNegativeAbsoluteDiscount(self):
with self.assertRaises(ValueError):
final_price = calculate_discount(200, 10, -30)
def testZeroAbsoluteDiscount(self):
final_price = calculate_discount(200, 10, 0)
self.assertEqual(final_price, 180)
def testLargeAbsoluteDiscount(self):
with self.assertRaises(ValueError):
final_price = calculate_discount(200, 10, 300)
def testNegativeFinalPrice(self):
with self.assertRaises(ValueError):
final_price = calculate_discount(200, 75, 75)
def testZeroFinalPrice(self):
final_price = calculate_discount(200, 50, 100)
self.assertEqual(final_price, 0)
def testCorrectFinalPrice(self):
final_price = calculate_discount(200, 10, 30)
self.assertEqual(final_price, 150)
if __name__ == '__main__':
unittest.main(verbosity=2)
| 2a550660812297e9d11f91af2fa84ad2d13771c3 | [
"Python"
] | 2 | Python | bxb0451/discount_calculator | 6184079dcbcac6aca33de945142e7da5194f22b2 | dbeff1c6c908452710adab489600ec1e58235570 | |
refs/heads/master | <repo_name>smadhumitha11/AutomationFramework<file_sep>/src/main/java/AutomationFramework/pages/LoginPage.java
/*Author : <NAME>
*************************************************************************
Elements of Login Page is identified and Actions for login page defined
*************************************************************************
*/
package AutomationFramework.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import AutomationFramework.Base.BaseTest;
public class LoginPage extends BaseTest {
@FindBy(xpath = "//input[@name='login']")
WebElement signIn;
@FindBy(xpath = "//input[@name='userName']")
WebElement userName;
@FindBy(xpath = "//input[@name='password']")
WebElement passWord;
// Initializing the Page Objects:
public LoginPage() {
PageFactory.initElements(driver, this);
}
//Actions
public void login(String un, String pwd) {
userName.sendKeys(un);
passWord.sendKeys(pwd);
signIn.click();
}
}<file_sep>/README.md
# Page Object model Test automation framework using Selenium with Java, TestNG and Gradle-
#Dependency
Java
Gradle
###libraries used
Selenium
TestNG
Extent Reports
<file_sep>/test-output/old/Amazon Automation Test Suite/Amazon Automation Test Suite.properties
[SuiteResult context=Amazon Automation Test Suite]<file_sep>/src/main/java/AutomationFramework/pages/HomePage.java
/*Author : <NAME>
*************************************************************************
Elements of Home Page is identified and Actions for login page defined
*************************************************************************
*/
package AutomationFramework.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import AutomationFramework.Base.BaseTest;
public class HomePage extends BaseTest {
@FindBy(xpath = "//a[contains(text(),'SIGN')]")
WebElement signIn;
@FindBy(xpath = "//img[contains(@alt,'Mercury Tours')]")
WebElement companyLogo;
@FindBy(xpath = "//a[contains(text(),'your destination')]")
WebElement destinationSearch;
// Initializing the Page Objects:
public HomePage() {
PageFactory.initElements(driver, this);
}
//Actions
public boolean validateCompanyLogo(){
return companyLogo.isDisplayed();
}
public boolean validatedestinationSearch(){
return destinationSearch.isDisplayed();
}
public boolean validateSignInClick(){
return signIn.isDisplayed();
}
public DestinationPage destinationClick(){
destinationSearch.click();
return new DestinationPage();
}
} <file_sep>/build.gradle
/*
* This file was generated by the Gradle 'init' task.
*
* This generated file contains a sample Java Library project to get you started.
* For more details take a look at the Java Libraries chapter in the Gradle
* User Manual available at https://docs.gradle.org/5.6.1/userguide/java_library_plugin.html
*/
plugins {
// Apply the java-library plugin to add support for Java Library
id 'java-library'
}
repositories {
// Use jcenter for resolving dependencies.
// You can declare any Maven/Ivy/file repository here.
jcenter()
}
dependencies {
// https://mvnrepository.com/artifact/commons-io/commons-io
compile group: 'commons-io', name: 'commons-io', version: '2.6'
// https://mvnrepository.com/artifact/org.testng/testng
testCompile group: 'org.testng', name: 'testng', version: '7.0.0'
// https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java
compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.141.59'
// https://mvnrepository.com/artifact/org.apache.poi/poi
compile group: 'org.apache.poi', name: 'poi', version: '4.1.0'
// https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml
compile group: 'org.apache.poi', name: 'poi-ooxml', version: '4.1.0'
// https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas
compile group: 'org.apache.poi', name: 'poi-ooxml-schemas', version: '4.1.0'
// https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad
compile group: 'org.apache.poi', name: 'poi-scratchpad', version: '4.1.0'
// https://mvnrepository.com/artifact/com.relevantcodes/extentreports
compile group: 'com.relevantcodes', name: 'extentreports', version: '2.41.2'
// https://mvnrepository.com/artifact/com.aventstack/extentreports-testng-adapter
compile group: 'com.aventstack', name: 'extentreports-testng-adapter', version: '1.0.3'
}
test { //this is the gradle task to be executed
useTestNG() { //Tells Gradle to use TestNG
useDefaultListeners = true
suites 'src/main/resources/testng.xml'
}
}
| 8bc1957302b0d2fcd8f40c4c84afb09bc8b124e3 | [
"Markdown",
"Java",
"INI",
"Gradle"
] | 5 | Java | smadhumitha11/AutomationFramework | 43bf99556135f3cb2860ae8a4c9ae9b5a721c1bd | c1646e8ed2a82b72f7722a21f4cf9806f84b9723 | |
refs/heads/master | <repo_name>segunAA/tbible<file_sep>/db.py
from sqlalchemy import create_engine
from datetime import datetime
class Bible():
reader = create_engine("sqlite:///ampc.sqlite3")
def __init__(self):
pass
def getBook(self, book):
sql = ''' SELECT osis, human, chapters
FROM books
WHERE human = '{book}' OR osis='{book}'
LIMIT 1
'''.format(book=book)
return self.reader.execute(sql).fetchall()[0].osis if len(self.reader.execute(sql).fetchall()) > 0 else False
def getPassage(self, book, verse):
id = self.getVerseID(book, verse)
sql = ''' SELECT * FROM verses LIMIT {id}, 10
'''.format(id=(id-1))
return self.reader.execute(sql).fetchall()
def getVerseID(self, book, verse):
sql = ''' SELECT id FROM verses WHERE book='{book}' AND verse='{verse}'
'''.format(book=book, verse=verse)
return self.reader.execute(sql).fetchone().id
def finder(self, query):
and_expanded = 'AND'.join([" unformatted LIKE '%{}%' ".format(a.strip()) for a in query.split() if len(a) > 3])
or_expanded = 'OR'.join([" unformatted LIKE '%{}%' ".format(a.strip()) for a in query.split() if len(a) > 3])
and_sql = "SELECT * FROM verses WHERE {query} ORDER BY id LIMIT 10".format(query=and_expanded)
or_sql = "SELECT * FROM verses WHERE {query} ORDER BY id LIMIT 10".format(query=or_expanded)
return dict(
ando=self.reader.execute(and_sql).fetchall(),
oro=self.reader.execute(or_sql).fetchall()
)
class App():
connector = create_engine("sqlite:///tbible.db")
def __init__(self):
sql = ''' CREATE TABLE IF NOT EXISTS
cache (
id INTEGER PRIMARY KEY,
created_at TEXT,
book TEXT,
verse TEXT,
success TEXT
)
'''
self.connector.execute(sql)
sql = ''' CREATE TABLE IF NOT EXISTS
bookmark (
id INTEGER PRIMARY KEY,
created_at TEXT,
book TEXT,
verse TEXT
)
'''
self.connector.execute(sql)
def bookmark(self):
sql = "SELECT book, verse FROM cache ORDER BY id DESC LIMIT 1"
memory = self.connector.execute(sql).fetchone()
#check if book mark exists
sql = "SELECT id FROM bookmark WHERE book='{book}' AND verse='{verse}'".format(book=memory.book, verse=memory.verse)
records = self.connector.execute(sql).fetchall()
recs = len(records)
if recs == 0:
sql = "INSERT INTO bookmark (created_at, book, verse) VALUES ('{now}', '{book}', '{verse}')".format(now=datetime.now(), book=memory.book, verse=memory.verse)
self.connector.execute(sql)
def getBookmarked(self):
sql = "SELECT * FROM bookmark ORDER BY id DESC LIMIT 20"
verses = self.connector.execute(sql).fetchall()
return verses
def logger(self, book, verse):
sql = ''' INSERT INTO cache (created_at, book, verse)
VALUES ('{now}', '{book}', '{verse}')
'''.format(now=datetime.now(), book=book, verse=verse)
self.connector.execute(sql)
<file_sep>/ui.py
from db import Bible, App
class UX():
bible = Bible()
cxn = App()
def __init__(self):
pass
def welcome(self):
print("Welcome to the Terminal Bible App!")
print("==================================\n")
def readVerses(self):
book = input("Please select the book you want to read from: ")
chapter = input("Please select the chapter you want to read from: ")
verse = input("Please select the verse you want to start from: ")
book = self.bible.getBook(book)
verse = "{chapter}.{verse}".format(chapter=chapter, verse=str(verse).zfill(3))
passage = self.bible.getPassage(book, verse)
self.cxn.logger(book, verse)
print("\n")
for v in passage:
print(v)
print("\n")
def bookmarkVerses(self):
self.cxn.bookmark()
def viewBookmarkedVerses(self):
verses = self.cxn.getBookmarked()
for verse in verses:
print(verse)
def search(self):
query = input("Enter search keyword: ")
result = self.bible.finder(query)
for rec in result['ando']:
print(rec)
for rec in result['oro']:
print(rec)
def printHelp(self):
apphelp = '''
Available options:
==================
q - to quit
b - to bookmark the last verse read
v - to view bookmarked verses
h - to repeat this message
s - to search the bible
r - to read verse
'''
print(apphelp)<file_sep>/app.py
from db import Bible, App
from ui import UX
ux = UX()
# bible = Bible()
# passage = bible.reader.execute("SELECT * FROM verses LIMIT 10")
cxn = App()
def app():
# for verse in passage:
# print(verse)
ux.welcome()
while True:
action = input(": ")
if action == "q":
break
elif action == 's':
ux.search()
elif action == 'r':
ux.readVerses()
elif action == 'v':
ux.viewBookmarkedVerses()
elif action == 'b':
ux.bookmarkVerses()
elif action == "h":
ux.printHelp()
else:
ux.printHelp()
if __name__ == "__main__":
app() | 63c7ba726e44afc7c8f200e13e7aa72e26b70390 | [
"Python"
] | 3 | Python | segunAA/tbible | c572717f94230a871a756ae828e5e93686be9ed3 | fbf1c172ac2079e959203980b33f3c530c3ef982 | |
refs/heads/master | <file_sep>import { Component, OnInit,EventEmitter, Output } from '@angular/core';
import { MouseEvent } from '@agm/core';
@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.css']
})
export class MapComponent implements OnInit {
@Output('seleccionarEvent') seleccionar:EventEmitter<any> = new EventEmitter<any>();
latitude = 61;
longitude = 22;
zoom = 7;
constructor() { }
ngOnInit() {
}
mapClicked($event: MouseEvent) {
this.latitude = $event.coords.lat;
this.longitude = $event.coords.lng;
this.seleccionar.emit($event.coords);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
/* mySlideImages = [1,2,3].map((i)=> `https://picsum.photos/640/480?image=${i}`);
myCarouselImages =[1,2,3,4,5,6].map((i)=>`https://picsum.photos/640/480?image=${i}`);
mySlideOptions={items: 1, dots: true, nav: false};
myCarouselOptions={items: 5, dots: true, nav: true};
*/
constructor() { }
ngOnInit() {
}
}
<file_sep>import { Component, OnInit,Input, OnChanges, Sanitizer } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-weather',
templateUrl: './weather.component.html',
styleUrls: ['./weather.component.css']
})
export class WeatherComponent implements OnInit, OnChanges {
@Input() latitude:string;
@Input() longitude:string;
city: string;
temp: number=123;
weatherHourList:any=[];
constructor(
private sanitizer: Sanitizer,
private http: HttpClient
) { }
ngOnChanges(){
this.obtenerClima();
}
ngOnInit() {
this.obtenerClima();
}
obtenerClima() {
//clima de 3 horas varios dias
// api.openweathermap.org/data/2.5/forecast?id=524901&lat=60.15790959006859&lon=7.437744140625&units=metric&lang=es&appid=d590f84d35fcf74bb9f07113d317ffbb
// http://api.openweathermap.org/data/2.5/forecast?id=524901&lat=60.15790959006859&lon=7.437744140625&units=metric&lang=es&appid=d590f84d35fcf74bb9f07113d317ffbb
//Clima en el momento
// http://api.openweathermap.org/data/2.5/weather?lat=60.15790959006859&lon=7.437744140625&units=metric&lang=es&appid=d590f84d35fcf74bb9f07113d317ffbb
let url = 'http://api.openweathermap.org/data/2.5/weather?'
+ 'lat=' + this.latitude
+ '&lon=' + this.longitude
+ '&units=metric'
+ '&lang=es'
+ '&appid=<KEY>'; // your api key here
console.log("url1: "+url);
this.http.get(url).subscribe((data: any) => {
console.log(data);
this.city = data.name;
this.temp = data.main.temp.toFixed(1);
});
url = 'http://api.openweathermap.org/data/2.5/forecast?id=524901&'
+ 'lat=' + this.latitude
+ '&lon=' + this.longitude
+ '&units=metric'
+ '&lang=en'
+ '&appid=<KEY>'; // your api key here
console.log("url2: "+url);
this.http.get(url).subscribe((data: any) => {
this.weatherHourList=data.list;
// this.temp = data.main.temp.toFixed(1);
});
}
public getSantizeUrl(url: string) {
// return this.sanitizer.bypassSecurityTrustUrl(url);
}
}
<file_sep><style>
.logo {
font-size: 150px;
}
@media screen and (max-width: 768px) {
.col-sm-4 {
text-align: center;
margin: 25px 0;
}
}
</style>
<div class="container-fluid">
<div class="row">
<div class="col-sm-8">
<h2>Map-weather implementation in a web application with Angular</h2>
<h4>SISTEMAS BASADOS EN WEB E INTELIGENCIA DE NEGOCIOS</h4>
<p><NAME> </p>
</div>
</div>
</div>
<div class="container-fluid bg-grey">
<h2 class="text-center">CONTACT</h2>
<div class="row">
<div class="col-sm-5">
<p>Contact me.</p>
<p><span class="glyphicon glyphicon-map-marker"></span> Aguascalientes, MX</p>
<p><span class="glyphicon glyphicon-phone"></span> +52 4651030866</p>
<p><span class="glyphicon glyphicon-envelope"></span> <EMAIL></p>
</div>
</div>
</div> | 13f8a2ba6ace50c2d3426cd4e4b153e824c66a41 | [
"TypeScript",
"HTML"
] | 4 | TypeScript | albert0ns/weather-map | 97134807abfadbbc9c413b6a6e69ccb5fb03ca0f | fac4b0551bc832126313f42c956afc318e3fc0d5 | |
refs/heads/master | <repo_name>ericmasiello/stylelint-config-ericmasiello<file_sep>/index.js
module.exports = {
bem: require('./bem'),
cssModules: require('./cssModules'),
};
<file_sep>/.stylelintrcBem.js
const { bem } = require('./');
module.exports = bem;
<file_sep>/__tests__/bem.test.js
const { bem: config } = require('..');
const fs = require('fs');
const stylelint = require('stylelint');
const validSelectorsCss = fs.readFileSync('./__fixtures__/bem-css-valid.css', 'utf-8');
const invalidSelectorsCss = fs.readFileSync('./__fixtures__/bem-css-invalid.css', 'utf-8');
const invalidSpecificityCss = fs.readFileSync('./__fixtures__/specificity-css-invalid.css', 'utf-8');
describe('flags no warnings with valid selectors css', () => {
let result;
beforeEach(() => {
result = stylelint.lint({
code: validSelectorsCss,
config,
});
});
it('did not error', () => {
return result.then(data => expect(data.errored).toBeFalsy());
});
it('flags no warnings', () => {
return result.then(data => expect(data.results[0].warnings.length).toBe(0));
});
});
describe('flags warnings with invalid specificty', () => {
let result;
beforeEach(() => {
result = stylelint.lint({
code: invalidSpecificityCss,
config,
});
});
it('violates selector-max-specificity', () => {
return result.then(data => {
const warnings = data.results[0].warnings.filter(warning => warning.rule === 'selector-max-specificity');
expect(warnings).toHaveLength(3);
expect(warnings[0].line).toBe(1);
expect(warnings[1].line).toBe(5);
expect(warnings[2].line).toBe(9);
});
});
it('violates selector-max-compound-selectors', () => {
return result.then(data => {
const warnings = data.results[0].warnings.filter(
warning => warning.rule === 'selector-max-compound-selectors'
);
expect(warnings).toHaveLength(1);
expect(warnings[0].line).toBe(5);
});
});
});
describe('flags warnings with invalid css', () => {
let result;
beforeEach(() => {
result = stylelint.lint({
code: invalidSelectorsCss,
config,
});
});
it('violates selector-class-pattern', () => {
const erroneousLineNumbers = [3, 7, 11, 15, 19, 23];
return result.then(data => {
const warnings = data.results[0].warnings.filter(warning => warning.rule === 'selector-class-pattern');
expect(warnings).toHaveLength(erroneousLineNumbers.length);
erroneousLineNumbers.forEach((lineNumber, i) => {
expect(warnings[i].line).toBe(lineNumber);
});
});
});
});
<file_sep>/bem.js
module.exports = {
extends: 'stylelint-config-standard',
rules: {
indentation: 4,
'selector-class-pattern': '^([a-z][a-z0-9]*)((__|-{1,2})[a-z0-9]+)*$',
'selector-max-compound-selectors': 3,
'selector-max-specificity': '0,3,3',
'declaration-colon-newline-after': null,
'declaration-empty-line-before': null,
'at-rule-empty-line-before': null,
'at-rule-no-unknown': [true, {
ignoreAtRules: [
'mixin',
'extend',
'include',
'function',
'return',
'if',
'else',
'for',
'while',
'each',
'content',
'at-root',
'debug',
'warn',
'error',
],
}],
},
};
<file_sep>/cssModules.js
const cssmodules = require('stylelint-config-css-modules');
const bemConfig = require('./bem');
module.exports = {
...bemConfig,
extends: [].concat(bemConfig.extends).concat('stylelint-config-css-modules'),
rules: {
...bemConfig.rules,
/*
Enforces camelCase with support BEM style modifiers.
Examples:
.sample {}
.mySample {}
.mySample--error {}
.mySample--specialState {}
*/
'selector-class-pattern': '^([a-z][a-zA-Z0-9]*)((-{2})[a-z][a-zA-Z0-9]+)*$',
'property-no-unknown': [
true,
{
ignoreProperties: [...cssmodules.rules['property-no-unknown'][1].ignoreProperties],
},
],
'at-rule-no-unknown': [
true,
{
ignoreAtRules: [
...bemConfig.rules['at-rule-no-unknown'][1].ignoreAtRules,
...cssmodules.rules['at-rule-no-unknown'][1].ignoreAtRules,
],
},
],
},
}<file_sep>/README.md
## stylelint-config-ericmasiello
`stylelint-config-ericmassielo` is a slightly more opinionated stylelint configuration than `stylelint-config-standard` that emphasizes minimal selector specificity as means toward improved CSS scalability.
The configuration comes in two variants:
1. A BEM (Block Element Modifier) variant that enforces kebab-case selector naming
2. A CSS Module variant that enforces camel case selector naming
For convenience, both configurations also white-list common SCSS directives.
### Install instructions
```shell
# npm
npm install --save-dev stylelint stylelint-config-ericmasiello
# yarn
yarn add -D stylelint stylelint-config-ericmasiello
```
Once installed, create a file in the root of your project named `.stylelintrc.js`.
If you prefer to use the BEM (Block Element Modifier) linting rules, set the contents to:
```js
// .stylelintrc.js
module.exports = {
extends: 'stylelint-config-ericmasiello/bem',
};
```
Alternatively, if you prefer to use CSS Modules linting rules, set the contents to:
```js
// .stylelintrc.js
module.exports = {
extends: 'stylelint-config-ericmasiello/cssModules',
};
```
If you need to ignore any files such as `normalize.css`, create a `.stylelintignore` file in the root of your project and list any files you need stylelint to ignore. For example:
```
normalize.css
normalize.min.css
```
To run the lint configuration, add a `script` to `package.json`.
```json
"scripts": {
"lint:style": "stylelint \"src/**/*.{scss,css}\""
}
```
And then run the script like so:
```shell
# npm
npm run lint:style
# yarn
yarn lint:style
```
| c6b5252b9f543512eb761135cbfdb02054ca4b99 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | ericmasiello/stylelint-config-ericmasiello | edf5b6358c4f05edb51c289f74d7210d1e29de04 | ef0a480669d051bce0e7eaffcda3906f18c6972b | |
refs/heads/main | <file_sep>/* tslint:disable */
/* eslint-disable */
export const memory: WebAssembly.Memory;
export function main(a: number, b: number): number;
export function __wbindgen_malloc(a: number): number;
export function __wbindgen_realloc(a: number, b: number, c: number): number;
export const __wbindgen_export_2: WebAssembly.Table;
export function _dyn_core__ops__function__Fn__A_B_C___Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h1b2d34fa518d1c63(a: number, b: number, c: number, d: number, e: number): void;
export function _dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h865f8314fae12818(a: number, b: number): void;
export function _dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h8def9f92d8da3f0b(a: number, b: number, c: number): void;
export function __wbindgen_exn_store(a: number): void;
export function wasm_bindgen__convert__closures__invoke2_mut__h6a09d8bda3045c96(a: number, b: number, c: number, d: number): void;
export function __wbindgen_start(): void;
<file_sep>+++
title = "demo"
weight = 1
+++
<script type="module">
import init from "./tour.js";
init('./tour_bg.wasm');
</script>
<file_sep># The URL the site will be built for
# base_url = "https://docs.iced.rs"
base_url = "https://iced-rs.github.io/iced-rs-docs"
title = "iced-rs"
description = ""
# Whether to automatically compile all Sass files in the sass directory
compile_sass = true
# Whether to build a search index to be used later on by a JavaScript library
build_search_index = true
# theme = ""
[markdown]
# Whether to do syntax highlighting
# Theme can be customised by setting the `highlight_theme` variable to a theme supported by Zola
highlight_code = true
[extra]
# Put all your custom variables here
code_dir = "git remote add origin [email protected]:iced-rs/iced-rs-docs.git/tree/main/code/"
repo_url = "git remote add origin <EMAIL>:iced-rs/iced-rs-docs.git"
<file_sep>fn main() {
//<test-section>
println!("Hello, friend!");
//</test-section>
println!("Hello, end!");
//<another-section>
let _thing = vec![1, 2, 3];
let _another_thing = vec![1, 2, 3];
let _yup = match 1 {
_ => (),
};
//</another-section>
}
<file_sep># iced.rs docs
## How to get started
- Install [zola](https://www.getzola.org/)
- clone repo
- cd into repo
- `zola serve`
- docs are located in `content/docs`
- every new markdown file in `/content/docs/` should automatically appear on `/docs`.
- any headers should automatically appear automatically in the Table of Contents with anchor tags
## how to add example code to to the docs
- code examples are in `code`
- create `cargo new some-new-example`
- add `some-new-example` to the workspace members in `code/Cargo.toml`
- write your code
- add a comment `//<section-name>` before your example snippet
- add a comment `//</section-name>` after your example snippet
- in your `content/docs/some_feature.md` include your code sample with:
```jinja
{{ code(path="some-new-example/src/main.rs", section="section-name") }}
```
## Issues
- No source for tour
- Tour doesn't work with zola server (should be fixed on next update)
- links are being html escaped
- wasm tour is kind of hacked together
- https://github.com/hecrj/iced/tree/master/web
- then some copy and pasting of a JS lib into the `tour.js` file
## TODOs
<file_sep>+++
title = "hello world"
weight = 1
+++
## Install
`cargo install iced`
## Basic App
An example of a simple `iced` application....
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor
invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et
accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
sanctus est Lorem ipsum dolor sit amet.
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor
invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et
accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
sanctus est Lorem ipsum dolor sit amet.
{{ code(path="hello-world/src/main.rs", section="test-section") }}
Some more text.
{{ code(path="hello-world/src/main.rs", section="another-section") }}
This is the end.
# outro
## thing
### other thing
<file_sep>+++
title = "List of docs."
sort_by = "weight"
template = "docs.html"
page_template = "doc-page.html"
insert_anchor_links = "right"
+++
<file_sep><div class="example-code">
```rust
{% set source_file = "code/" ~ path -%}
{% set open_symbol = "//<" ~ section ~ ">" -%}
{% set close_symbol = "//</" ~ section ~ ">" -%}
{{ load_data(path=source_file) | split(pat=open_symbol) | nth(n=1) | split(pat=close_symbol) | nth(n=0) }}
```
{% set source_code_link = config.extra.code_dir ~ path -%}
<a href="{{ source_code_link }}">link to source</a>
</div>
<file_sep>+++
title = "Demo"
sort_by = "weight"
template = "tour.html"
page_template = "tour-page.html"
+++
<iframe src="./demo" height="800" style="border:1px solid black; width:100%;">
</iframe>
| a7d8d492060ba4d4745b5f99b1db3fc679ff974d | [
"Markdown",
"TOML",
"TypeScript",
"Rust"
] | 9 | TypeScript | cldershem/iced-rs-website | 951ad5e986569bdd05b697b8c9629850b898c7ec | a82125a3d830dd65b53d431e0c6344993fdf72ec | |
refs/heads/master | <repo_name>FultonSlide/ReactRouter<file_sep>/src/reducers/rootReducer.js
const initState = {
posts: [
{id: '1', title: 'Flash Flooding in Melbournes East', body: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'},
{id: '2', title: 'Bushfires on hold but Firies wary', body: 'Sit amet consectetur adipiscing elit ut. Accumsan lacus vel facilisis volutpat est velit egestas dui id. Varius quam quisque id diam. Risus viverra adipiscing at in tellus integer. Ullamcorper dignissim cras tincidunt lobortis feugiat. Posuere sollicitudin aliquam ultrices sagittis orci a scelerisque purus semper. Velit laoreet id donec ultrices.'},
{id: '3', title: 'Egg found smashed behind farmers wall', body: 'Laoreet non curabitur gravida arcu ac tortor dignissim convallis. Tristique nulla aliquet enim tortor. Massa enim nec dui nunc mattis enim ut. Maecenas accumsan lacus vel facilisis volutpat est. Netus et malesuada fames ac turpis egestas integer eget. Lacus sed turpis tincidunt id aliquet risus. Porttitor eget dolor morbi non arcu risus quis varius quam.'}
]
}
const rootReducer = (state = initState, action) => {
if(action.type === 'DELETE_POST'){
let newPosts = state.posts.filter(post => {
return action.id !== post.id
});
return {
...state,
posts: newPosts
}
}
return state;
}
export default rootReducer; | 069b101c89ca593a0a3e631d8dfdcd3b08d5d042 | [
"JavaScript"
] | 1 | JavaScript | FultonSlide/ReactRouter | 0f2e9ed72a7584b5ee7d1e238593c5f34146edd4 | 6a2d66f91224293d63a4e786f4565e9f2370be58 | |
refs/heads/master | <repo_name>phnavarrete/backend_TPN3<file_sep>/tp3_backend.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>TRABAJO PRACTICO Nº3</title>
</head>
<body>
<h1> EJERCICIO 1 </h1>
<h2 style="color:BROWN">
<?php
$n=1;
while ($n <= 100) {
echo "$n</p>";
$n++;
}
?>
</h2>
<hr>
<h1> EJERCICIO 2 </h1>
<h2 style="color:BLUE">
<?php
$n=100;
while ($n <= 100 and $n > 0) {
echo "$n</p>";
$n--;
}
?>
</h2>
<hr>
<h1> EJERCICIO 3 </h1>
<h2 style="color:GREEN">
<?php
$f=2;
while ($f <= 100) {
echo "$f</p>";
$f=$f+2;
}
?>
</h2>
<hr>
<h1> EJERCICIO 4 </h1>
<h2 style="color:RED">
<?php
$f=1;
while ($f <= 100) {
echo "$f</p>";
$f=$f+2;
}
?>
</h2>
<hr>
<h1> EJERCICIO 5 </h1>
<h2 style="color:violet">
<?php
$r=0;
for ($i=1; $i<=20; $i++) {
$r=$i+$r;
echo "$r<br>";
}
?>
</h2>
<hr>
<h1> EJERCICIO 6 </h1>
<h2 style="color:violet">
<?php
$r=0;
for ($i=2; $i<=20; $i=$i+2) {
$r=$i+$r;
echo "$r<br>";
}
?>
</h2>
</body>
</html>
| 64473235f3033090223882fa3342b9817aa38e6e | [
"PHP"
] | 1 | PHP | phnavarrete/backend_TPN3 | 7c43cddcda7635ebcbb2f67041e0abcf59de200d | 9ba6d0be33d147aaacb71d67a811c174c76931f6 | |
refs/heads/master | <file_sep>---
title: hexo_github
date: 2016-11-15 15:13:06
tags:
---
steps:
1.local
============
1.1 download nodejs
https://nodejs.org/dist/v6.9.1/node-v6.9.1-linux-x64.tar.xz
1.2 uncompress
tar -Jxvf
1.3 sudo cp -ar node... /usr/local/
1.4 set node and npm PATH
export NODE="/usr/local/node"
export PATH="${NODE}/bin:$PATH"
1.5 npm install hexo --no-optional
sudo npm install -g hexo-cli
1.6 mkdir blog_stormmg
~~~
cd
hexo init <folder>
cd <folder>
npm install
~~~
or !!
~~~
mkdir <folder>
cd <folder>
hexo init
hexo generate (hexo g)
npm install
hexo server (hexo s)
~~~
browser: http://localhost:4000 //0.0.0.0:4000
1.7 create new file
hexo new "new file"
1.8 generate html js website files
hexo generate
2.githubpages
============
2.1 git clone https://github.com/spartacus429496/spartacus429496.github.io
2.2 cp public containded files to git repo
2.3 browser: spartacus429496.github.io
3.deploy
============
3.1 vim _config.yml
~~~
deploy:
type: git
repository: https://github.com/spartacus429496/spartacus429496.github.io.git
branch: master
~~~
3.2
npm install hexo-deployer-git --save
3.3 new file
~~~
hexo new "newfilename" //in ./source/_posts/
for detailes: markdown
hexo generate
hexo deploy (hexo d)
~~~
3.4 add theme
~~~
view https://hexo.io/themes/
git clone https://github.com/iissnan/hexo-theme-next themes/next
vim _config.yml theme
vim ./themes/next/-config.yml //change attrbutes header etc
~~~
3.5 deploy
hexo clean
hexo generate
hexo deploy
<file_sep>---
title: introduction
date: 2016-11-15 14:05:44
tags:
---
<file_sep>---
title: An essay on man
date: 2016-11-15 15:53:08
tags:
---
2 科学
卡西尔
节自《人论》(上海译文出版社1985年版)。甘阳译。恩斯特·卡西尔(1874—1945),德国哲学家,被誉为百科全书式的学者,是20世纪最重要的哲学家之一。一生著述120多种,在语言哲学、符号美学方面的成就尤其突出。《人论》是卡西尔研究“人的问题”的一部哲学著作,也是他流传最广、影响最大的一本书。
卡西尔在《人论》中提出了一个著名的观点:与其把人称作“理性的动物”,不如称作“符号的动物”。本文节选自《人论》,论证了科学作为人类文化的特点,并给予极高的评价,指出科学“是人类文化最高最独特的成就”“是我们全部人类活动的顶点和极致”“在我们现代世界中,再没有第二种力量可以与科学思想的力量相匹敌”。阅读时,应注意作者在与日常感觉、日常语言的对比中,对科学的起源、发展进行的分析,从而体会科学作为现代人类文化的理性精神。
科学是人的智力发展中的最后一步,并且可以被看成是人类文化最高最独特的成就。它是一种只有在特殊条件下才可能得到发展的非常晚而又非常精致的成果。在伟大的古希腊思想家的时代以前——在毕达哥拉斯派学者、原子论者〔原子论者〕代表人物是留基伯和德谟克利特,认为世界万物都是由不可再分的物质微粒原子组成的,具有朴素的唯物主义观点。、柏拉图和亚里士多德〔亚里士多德(公元前384—前322)〕古希腊哲学家,柏拉图的学生。在哲学的各个方面都广有建树,对西方哲学的发展有重大的影响。主要著作有《工具论》《形而上学》《物理学》《政治学》《诗学》等。以前,甚至连特定意义的科学概念本身都不存在。而且这个最初的概念在以后的若干世纪中似乎被遗忘和遮蔽了,以至在文艺复兴的时代不得不被重新发现、重新建立。在这种重新发现以后,科学的成就看来是圆满得无可非议的了。在我们现代世界中,再没有第二种力量可以与科学思想的力量相匹敌。它被看成是我们全部人类活动的顶点和极致,被看成是人类历史的最后篇章和人的哲学的最重要主题。
我们可以对科学的成果或其基本原理提出质疑,但是它的一般功能似乎是无可怀疑的。正是科学给予我们对一个永恒世界的信念。对于科学,我们可以用阿基米德〔阿基米德(约公元前287—前212)〕古希腊物理学家、数学家,静力学和流体力学的奠基人。在科学上的主要贡献是阐明了杠杆原理、浮力定律。在对物体表面积、体积等的计算方面,也有许多重大成就。的话来说:给我一个支点,我就能推动宇宙。在变动不居的宇宙中,科学思想确立了支撑点,确立了不可动摇的支柱。在古希腊语中,甚至连科学〔episteme〕这个词从词源学上说就是来源于一个意指坚固性和稳定性的词根。科学的进程导向一种稳定的平衡,导向我们的知觉和思想世界的稳定化和巩固化。
但另一方面,科学并不是单独地在完成这个任务。在我们近代认识论中,不管是在经验论派还是在惟理论派那里,我们都常常碰到这种看法:人类经验的原初材料是处在一种全然无秩序的状态之中的。甚至连康德〔康德(1724—1804)〕德国古典哲学的奠基人,也是有重大成就的科学家。在哲学认识论上主张二元论、先验论,在科学上提出了“星云假说”。主要代表作有《自然通史和天体论》《纯粹理性批判》《实践理性批判》《判断力批判》。在《纯粹理性批判》的前面几章中似乎也是从这种前提出发的。他说,经验无疑是我们知性的第一个产物,但它不是一种简单的事实,而是两种相反的要素——质料与形式的合成物。质料的要素是在我们的感知中被给予的,而形式的要素则体现为我们的科学概念。这些概念,这些纯粹知性的概念给予各种现象以综合统一。我们所说的对象的统一,无非就是在综合我们表象的杂多时我们意识的形式统一。只有当我们对直观的杂多进行了综合统一,这时而且只有在这时我们才能说我们认知了一个对象。因此,对康德来说,人类知识的全部客观性问题是与科学的事实不可分割地联结在一起的。他的先验感性论与纯数学的问题相关,而他的先验分析则试图解释精确的自然科学的事实。
但是一种人类文化哲学必须把这个问题往前追溯到更远的根源。人早在他生活在科学的世界中以前,就已经生活在客观的世界中了。即使在人发现通向科学之路以前,人的经验也并不仅仅只是一大堆乱七八糟的感觉印象,而是一种有组织有秩序的经验。它具有一种明确的结构。不过,给予这种世界以综合统一性的概念,与我们的科学概念不是同一种类型,也不是处在同一层次上的。它们是神话的或语言的概念。如果我们分析这些概念的话,就会发现它们绝不是简单的或“原始的”。我们在语言或神话中所看到的对各种现象的最初分类,在某种意义上比我们的科学分类远为复杂、远为精致。科学开端于对简明性的追求。简明标志着真理似乎是它的基本意愿之一。然而,这种逻辑的简明性乃是一个终点,而不是一个起点。人类文化开端于一种远为错综复杂的心智状态。几乎所有的自然科学都不得不通过一个神话阶段。在科学思想的历史上,炼金术先于化学,占星术先于天文学。科学只有靠着引入一种新的尺度,一种不同的逻辑的真理标准,才能超越这些最初阶段。它宣称,只要人把自己局限在他的直接经验——观察事实的狭隘圈子里,真理就不可能被获得。科学不是要描述孤立分离的事实,而是要努力给予我们一种综合观。但是这种观点不可能靠对我们的普通经验进行单纯的扩展、放大和增多而达到,而是需要新的秩序原则,新的理智解释形式。语言是人统一他的感知世界的最初尝试。这种倾向是人类言语的基本特征之一。有些语言学家甚至已经认为必须设想人有一种特殊的分类本能,才能解释人类言语的事实与结构。奥托·叶斯柏森〔奥托·叶斯柏森(1860—1943)〕丹麦语言学家,曾任丹麦哥本哈根大学英语教授、校长。主要著作有《语音学》《语法哲学》。说:
人是分类的动物:在某种意义上可以说,整个讲话过程只不过是把各种现象(没有两种现象在每一方面都是相同的)根据看到的相似点和相异点分成不同的类而已。在命名过程中我们又看到了同样根深蒂固而又非常有用的倾向——识别相像性并且通过名字的相似来表达现象的相似。
但是科学在现象中所寻求的远不止是相似性,而是秩序。我们在人类言语中所看到的最初的分类,没有任何严格的理论目的。对象的名字如果能使我们传达我们的思想并协调我们的实践活动,那就完成了它们的任务。它们具有一种目的论的功能,这种功能慢慢地发展成为一种更为客观的、“表现的”功能。在不同现象之间的每一表面上的相似性都足以用一个共同的名称来表示它们。在有些语言中,一只蝴蝶被叫做一只鸟,一条鲸被叫做一条鱼。当科学开始作最初的分类时,它必须修正和克服这些表面上的相似性。科学的术语不是任意制造的,它们遵循着一定的分类原则。一套首尾一贯的系统的术语的创立绝不是科学的纯粹附加特征,而是它固有的不可缺少的成分之一。当林奈〔林奈(1707—1778)〕瑞典博物学家,现代生物分类学的奠基人,确立了生物分类的双名法。主要著作有《自然系统》《植物种志》。出版他的《植物哲学》时他不得不遭到这种反对理由:这里所给予的只是一种人为的而不是自然的系统。但是,所有的分类系统都是人为的。自然本身只包含个别的多样化的现象。如果我们把这些现象纳入类概念和一般规律之下,那么我们并不是在描述自然的事实。每一种体系都是一种艺术品——是有意识的创造性活动的一种结果。甚至连与林奈的体系相对立的后来的所谓“自然的”生物学体系也必须采用新的概念成分。它们是建立在一般的进化论基础上的。但是进化本身并不是自然史的单纯事实,而是科学的假设,是我们对自然现象进行观察和分类的一种调节性原理。达尔文理论开启了一个新的更广阔的地平线,对有机生命的现象提供了更全面更首尾一致的概念。这决不是对林奈体系的驳斥;事实上林奈始终把他的体系看成是预备步骤,他完全明白,在某种意义上他只是创立了一套新的植物学术语。但是他深信,这套术语不但具有语词上的价值而且有着实在的价值。他曾说:“如果你不知道事物的名字,事物的知识就会死亡。”
就这一点而言,语言与科学之间的连续性似乎没有中止。我们语言学的各种名称和最初的科学的各种名称可以被看成是同一分类本能的结果与产物。在语言中无意识地完成的事也就是在科学过程中有意识地打算做的并且有条理地完成的事。科学在其最初阶段仍然不得不在日常言语的意义上来采用事物的名称。它可以用它们来描述事物的基本成分或性质。在最初的希腊自然哲学体系中,在亚里士多德哲学中,我们发现这些普通名称仍然对科学思维有着巨大的影响。但是在希腊思想中,这种力量不再是惟一的或占优势的了。在毕达哥拉斯及其早期信徒的时代,希腊哲学已经发现了一种新的语言——数的语言。这个发现标志着我们近代科学概念的诞生。
在各种自然事件——天体的运行、日月的升落、四季的变换——之中,存在着一种规律性,存在着某种一致性——这是人类最早的伟大经验之一。甚至在神话思想中,这种经验就已经得到了充分的承认和独特的表达。在这里我们看到了关于自然的一种普遍秩序的观念之最早迹象。而且早在毕达哥拉斯时代以前,这种秩序就已经不仅用神话的术语而且还用数学的符号来描述了。神话语言和数学语言在早期巴比伦占星术体系中以非常奇特的方式互相结合起来,而这种占星术体系一直可以追溯到大约公元前3800年那么早的一段时期。不同星群之间的区分、黄道带的十二重分割〔黄道带的十二重分割〕黄道是地球绕太阳公转的轨道平面与天球相交的大圆。古代巴比伦人将黄道分成12个部分,将一年划分为12个月。,都是由巴比伦天文学家们完成的。如果没有一种新的理论基础的话那就不可能获得这些成果。但是,要创立第一个数的哲学,就必须有更大胆的概括。毕达哥拉斯派思想家们最早把数设想为一种无所不包的真正普遍的要素。它的用处不再局限在某一特殊的研究领域以内,而是扩展到了存在的全部领域。当毕达哥拉斯作出他的第一个伟大发现时——当他发现音调的高度依赖于振动弦的长度时,对哲学和数学思想的未来方向具有决定意义的并不是这种事实本身,而是对这种事实的解释。毕达哥拉斯不可能把这种发现看成是一种孤立的现象。最深奥的神秘之一——美的神秘,似乎在这里被揭示出来了。对希腊精神来说,美始终具有一种完全客观的意义。美就是真,它是实在的一种基本品格。如果我们在音调的和谐中发现的美可以被还原为一种简单的数的比例的话,那么正是数向我们揭示了宇宙秩序的基本结构。毕达哥拉斯派有一句话:“数是人类思想的向导和主人,没有它的力量,万物就都处于昏暗混乱之中。”我们并不是生活在真理的世界中,而是生活在蒙蔽和错觉的世界中。在数中,而且只有在数中,我们才发现了一个可理解的宇宙。
物理学的各分支都趋向于同一个目标——力图使整个自然现象的世界都处于数的管辖之下。在这种总的方法论理想方面,我们看不出古典物理学与近代物理学之间有什么分歧。量子力学在某种意义上是古典的毕达哥拉斯理想的真正复活、更新和证实。但是在这里也必须引入一种更加抽象的符号语言。当德谟克利特描述他的原子结构时,他曾求助于从感觉经验世界中获取的相似性。他给出了原子的一种图像、映像,而这种映像是与我们宏观世界的普通物体相类似的。原子以它们的形状、大小及其各部分的排列而互相区别。它们的连结是用物质的连接来解释的:单独的原子都具有钩和孔、球和窝,从而使它们成为可勾结的。所有这些形象化的描述和比喻式的说明在我们近代原子理论中都已经消失了。在玻尔的原子模型中没有任何这类形象化的语言。科学不再以普通的感觉经验的语言说话,而是采取了毕达哥拉斯的语言。数的纯粹符号体系取代并且取消了日常言语的符号体系。不仅是宏观宇宙而且连微观宇宙——原子内部现象的世界——现在都不可能用这种语言来描述。这已被证明是开启了一种全新的系统解释。
化学的历史是科学语言的这种缓慢变化的最好最显著的例子。化学踏上“科学大道”的时间比物理学晚得多。许多世纪以来阻碍化学思想的发展并使它停留在前科学概念范围内的障碍决不是因为缺乏新的经验证据。如果我们研究一下炼金术的历史,我们就会发现炼金术士们具有令人惊讶的观察天赋。他们积累了大量有价值的事实,没有这些原始材料的话,化学几乎至今也不可能得到发展。但是表现这种原始材料的形式却是极不充分的。当炼金术士开始描述他的观察材料时,他没有任何可供他使用的工具而只有一种充满了意义含糊的术语的半神话语言。他用隐喻和寓言而不是用科学的概念说话。这种含糊的语言在他关于自然的全部概念上都打上了烙印。自然界成了由各种晦涩难懂的性质构成的领域,只有那些领会其秘诀的行家才能理解它。化学思想的新潮流开始于文艺复兴时期。在“医化学”学派中,生物学和医学的思想开始流行。但解决化学问题的真正科学方法直到17世纪才出现。罗伯特·波义耳〔罗伯特·波义耳(1627—1691)〕英国化学家、物理学家和自然哲学家,是近代化学的奠基人。主要著作有《怀疑的化学家》《关于颜色的实验和考察》。的《怀疑的化学家》是以关于自然和自然规律的新的一般概念为基础的近代化学理想的第一个伟大范例。然而即使在这里以及以后的燃素说〔燃素说〕18世纪关于燃烧的一种错误学说,认为可燃物质中存在着燃素,燃烧时燃素以光和热的形式逸出。18世纪末被燃烧的氧化学说取代。的发展中,我们能看到的也只是对化学过程的定性描述。直到18世纪末拉瓦锡〔拉瓦锡(1743—1794)〕法国化学家,近代化学的奠基人之一,阐明了燃烧的氧化学说。的时代,化学才学会了使用定量的语言。
在生物学的历史中我们也能追踪到同样的一般思想趋向。像所有其他的自然科学一样,生物学也不得不从对事实的简单分类开始,而且这种分类也是以我们日常语言的类概念为指导的。科学的生物学给了这些概念更确切的意义。亚里士多德的动物学分类和提奥弗拉斯特〔提奥弗拉斯特〕古希腊科学家,亚里士多德的弟子,在矿物学和植物学方面很有成就。的植物学分类都显示出高度的严密性和方法上的条理性。但是在近代生物学中,所有这些较早的分类形式都被一个不同的理想遮盖了。生物学慢慢地进展到了一个“演绎公式化理论”的新阶段。
科学家知道,仍然有大量领域的现象还无法归之于严格的规律和精确的数的规则。然而他仍然忠于这个一般的毕达哥拉斯派教义——他相信,作为一个整体的自然及其所有特殊领域是“一个数和一种和谐”。面对着无限广大的自然,许多最伟大的科学家或许都会有在牛顿的名言中所表达的那种特殊感情。他们或许都觉得,他们在自己的工作中就像一个沿着无边的海岸散步自娱的儿童一样,偶尔好玩地捡起了一块以其形状或颜色吸引了他的注意力的鹅卵石。这种谦虚的看法是可以理解的,但它并没有对科学家的工作作出真实而充分的描述。科学家如果不严格地服从自然的事实就不可能达到他的目的。但是这种服从并不是被动的顺从。一切伟大的自然科学家如伽利略、牛顿、麦克斯韦〔麦克斯韦(1831—1879)〕英国物理学家,揭示了电磁现象和光现象的统一性,提出的麦克斯韦方程组成为经典电动力学的基础。、赫尔姆霍兹〔赫尔姆霍兹(1821—1894)〕一般译作“亥姆霍兹”,德国物理学家,第一次用数学方法提出了能量守恒定律。、普朗克〔普朗克(1858—1947)〕德国物理学家,量子论的奠基人,提出了黑体辐射公式,即普朗克公式。和爱因斯坦,都不是从事单纯的事实搜集工作,而是从事理论性的工作,而这也就意味着创造性的工作。这种自发性和创造性就是一切人类活动的核心所在。它是人的最高力量,同时也标示了我们人类世界与自然界的天然分界线。在语言、宗教、艺术、科学中,人所能做的不过是建造他自己的宇宙——一个使人类经验能够被他所理解和解释、连结和组织、综合化和普遍化的符号的宇宙。
<file_sep>#include<stdio.h>
typedef unsigned char Byte_t;
int main(int argc, char ** argv)
{
Fd = fopen(argv[1], "r");
while (fgets(String, sizeof(String), Fd)) {
while ((sscanf(String + Offset , "\\x%x%n", &HexVal, &Count)) == 1) {
fclose(Fd);
}
| b429c3085d99ce7258f1f618f7e8e73658f85cd3 | [
"Markdown",
"C"
] | 4 | Markdown | spartacus429496/nature | c77f8d11a91f7d4ab35b7b3f9f045f3ef998d64c | 75ba68c85834abfe8c5a7fda8ae6170ed25fbd48 | |
refs/heads/master | <repo_name>JustynaJPL/ProAngular-SportsStore<file_sep>/src/app/model/order.model.ts
import { Injectable } from "@angular/core";
import { Cart } from "./cart.model";
@Injectable()
export class Order {
public id:number;
public name:string;
public address:string;
public city:string;
public state:string;
public zip:string;
public country:string;
public shipped:boolean = false;
constructor(public cart:Cart){
}
clear(){
this.id = null;
this.name = this.address = this.city = null;
this.state = this.zip = this.country = null;
this.shipped = false;
this.cart.clear();
}
}<file_sep>/src/app/model/rest.datasource.ts
import { Injectable } from "@angular/core";
import { Http, Request, RequestMethod } from "@angular/http";
import { Observable } from "rxjs/Observable";
import { Product } from "./product.model";
import { Cart } from "./cart.model";
import { Order } from "./order.model";
import "rxjs/add/operator/map";
@Injectable()
export class RestDataSource {
baseUrl:string;
auth_token:string;
constructor(private http:Http){
this.baseUrl = 'http://localhost:3500/';
}
authenticate(user:string, pass:string):Observable<boolean>{
return this.http.request(new Request({
method:RequestMethod.Post,
url:this.baseUrl +"login",
body: {name:user, password:<PASSWORD> }
})).map(response => {
let r = response.json();
this.auth_token = r.success ? r.token : null;
return r.success;
});
}
getProducts():Observable<Product[]>{
return this.sendRequest(RequestMethod.Get, "products") as Observable<Product[]>;
}
saveProduct(product:Product):Observable<Product>{
return this.sendRequest(RequestMethod.Post, 'products' , product, true) as Observable<Product>;
}
updateProduct(product):Observable<Product>{
return this.sendRequest(RequestMethod.Put,('products/'+ product.id), product, true) as Observable<Product>;
}
deleteProduct(id:number): Observable<Product>{
return this.sendRequest(RequestMethod.Delete,('products/'+id), null, true) as Observable<Product>;
}
getOrders():Observable<Order[]>{
return this.sendRequest(RequestMethod.Get,'orders', null, true) as Observable<Order[]>;
}
deleteOrder(id:number):Observable<Order>{
return this.sendRequest(RequestMethod.Delete,('orders/'+id), null, true) as Observable<Order>;
}
updateOrder(order:Order):Observable<Order>{
return this.sendRequest(RequestMethod.Put,('orders/'+order.id), order, true) as Observable<Order>;
}
saveOrder(order:Order): Observable<Order>{
return this.sendRequest(RequestMethod.Post,'orders', order) as Observable<Order>;
}
private sendRequest(verb:RequestMethod, url:string, body?:Product | Order, auth:boolean = false):Observable<Product |Product[] | Order| Order[] > {
let request = new Request({
method:verb,
url:this.baseUrl + url,
body:body
});
if(auth && this.auth_token !=null){
request.headers.set("Authorization", 'Bearer<'+ this.auth_token +'>');
}
return this.http.request(request).map(response => response.json());
}
}<file_sep>/src/app/admin/auth.component.ts
import { Component } from "@angular/core";
import { NgForm } from "@angular/forms";
import { Router } from "@angular/router";
import { AuthService } from "../model/auth.service";
@Component({
moduleId: module.id,
templateUrl:"auth.component.html"
})
export class AuthComponent{
public username:string;
public password:string;
public errorMessage:string;
constructor(private router:Router, private auth:AuthService){
}
authenticate(form:NgForm){
if (form.valid) {
this.auth.authenticate(this.username, this.password).subscribe(response => {
if(response){
this.router.navigateByUrl('/admin/main');
}
this.errorMessage = "Uwierzytelnianie zakończyło się niepowodzeniem"
})
}
else{
this.errorMessage = "Nieprawidłowe dane";
}
}
}<file_sep>/data.js
module.exports = function(){
return {
products:[
{id:1, name:"Kajak", category:"Sporty wodne",
description:"Łódka przeznaczona dla jednej osoby", price:275 },
{id:2, name:"<NAME>", category:"Sporty wodne",
description:"Chronii dodaje uroku", price:48.95 },
{id:3, name:"Piłka", category:"Piłka nożna",
description:"Zatwierdzone przez FIFA masa i jakość", price:19.50 },
{id:4, name:"<NAME>", category:"Piłka narożna",
description:"Nadadzą twojemu boisku profesjonalny wygląd", price:34.95 },
{id:5, name:"Stadion", category:"Piłka nożna",
description:"Składany stadion na 35000 osób", price:79500 },
{id:6, name:"Czapka", category:"Szachy",
description:"Zwiększa efektywność mózgu o 75%", price:16 },
{id:7, name:"<NAME>", category:"Szachy",
description:"Zmniejsza szanse przeciwnika", price:29.95 },
{id:8, name:"<NAME>", category:"Szachy",
description:"Przyjemna gra dla całej rodziny", price:75 },
{id:9, name:"<NAME>", category:"Szachy",
description:"Pokryty złotem i wysadzany diamentami król", price:1200},
],
orders:[]
}
}<file_sep>/src/app/store/counter.directive.ts
import {Directive, ViewContainerRef,TemplateRef, Input, Attribute, SimpleChanges } from '@angular/core';
@Directive({
selector:"[counterOf]"
})
export class CounterDirective {
constructor(private container:ViewContainerRef, private template: TemplateRef<Object>){
}
@Input('counterOf')
counter:number;
ngOnChanges(changes:SimpleChanges){
this.container.clear();
for (let i = 0; i < this.counter; i++) {
this.container.createEmbeddedView(this.template,new CounterDirectiveContext(i+1));
}
}
}
class CounterDirectiveContext{
constructor(public $implicit:any){}
}<file_sep>/src/app/admin/productEditor.component.ts
import { Component } from "@angular/core";
import { Router, ActivatedRoute } from "@angular/router";
import { NgForm } from "@angular/forms";
import { Product } from "../model/product.model";
import { ProductRepository } from "../model/product.repository";
@Component({
moduleId: module.id,
templateUrl: "productEditor.component.html"
})
export class ProductEditorComponent{
editing:boolean = false;
product: Product = new Product();
constructor(private repository: ProductRepository, private router: Router, activateRoute:ActivatedRoute){
this.editing = activateRoute.snapshot.params["mode"]== "edit";
if (this.editing) {
Object.assign(this.product, repository.getProduct(activateRoute.snapshot.params["id"]));
}
}
save(form:NgForm){
this.repository.saveProduct(this.product);
this.router.navigateByUrl("/admin/main/products")
}
}<file_sep>/src/app/model/static.datasource.ts
import { Injectable } from "@angular/core";
import { Product } from "./product.model";
import { Observable } from "rxjs/Observable";
import "rxjs/add/observable/from";
import { Order } from "./order.model"
@Injectable()
export class StaticDataSource {
private products: Product[] = [
new Product(1, "Produkt 1", "Kategoria 1", "Produkt 1 (Kategoria 1)", 100),
new Product(2, "Produkt 2", "Kategoria 1", "Produkt 2 (Kategoria 1)", 100),
new Product(3, "Produkt 3", "Kategoria 1", "Produkt 3 (Kategoria 1)", 100),
new Product(4, "Produkt 4", "Kategoria 1", "Produkt 4 (Kategoria 1)", 100),
new Product(5, "Produkt 5", "Kategoria 1", "Produkt 5 (Kategoria 1)", 100),
new Product(6, "Produkt 6", "Kategoria 1", "Produkt 6 (Kategoria 1)", 100),
new Product(7, "Produkt 7", "Kategoria 1", "Produkt 7 (Kategoria 1)", 100),
new Product(8, "Produkt 8", "Kategoria 1", "Produkt 8 (Kategoria 1)", 100),
new Product(9, "Produkt 9", "Kategoria 1", "Produkt 9 (Kategoria 1)", 100),
new Product(10, "Produkt 10", "Kategoria 2", "Produkt 10 (Kategoria 2)", 100),
new Product(11, "Produkt 11", "Kategoria 2", "Produkt 11 (Kategoria 2)", 100),
new Product(12, "Produkt 12", "Kategoria 2", "Produkt 12 (Kategoria 2)", 100),
new Product(13, "Produkt 13", "Kategoria 2", "Produkt 13 (Kategoria 2)", 100),
new Product(14, "Produkt 14", "Kategoria 2", "Produkt 14 (Kategoria 2)", 100),
new Product(15, "Produkt 15", "Kategoria 2", "Produkt 15 (Kategoria 2)", 100),
new Product(16, "Produkt 16", "Kategoria 2", "Produkt 16 (Kategoria 2)", 100),
new Product(17, "Produkt 17", "Kategoria 2", "Produkt 17 (Kategoria 2)", 100),
new Product(18, "Produkt 18", "Kategoria 3", "Produkt 18 (Kategoria 3)", 100),
new Product(19, "Produkt 19", "Kategoria 3", "Produkt 19 (Kategoria 3)", 100),
new Product(20, "Produkt 20", "Kategoria 3", "Produkt 20 (Kategoria 3)", 100),
new Product(21, "Produkt 21", "Kategoria 3", "Produkt 21 (Kategoria 3)", 100),
];
getProducts(): Observable<Product[]>{
return Observable.from([this.products]);
}
saveOrder(order:Order):Observable<Order>{
console.log(JSON.stringify(order));
return Observable.from([order])
}
} | a2f92ff1af00f04890f40cc13b5bc651581cda8f | [
"JavaScript",
"TypeScript"
] | 7 | TypeScript | JustynaJPL/ProAngular-SportsStore | 527650f2ecde1c1998d3e5bb2b1051d25ff28c36 | 08a35dd220673e520792bc63675650c60c3a85ef | |
refs/heads/master | <repo_name>sarthak77/Undo-Logging<file_sep>/20171091_1.py
import sys
def readinput(file):
"""
Returns contents of disk and transactions
"""
Disk,Tran=[{},{}]
with open(file,'r') as f:
#read first line
fl=f.readline()
fl=fl.strip().split()
for i in range(0,len(fl),2):
Disk[fl[i]]=fl[i+1]
# print(Disk)
#read transactions
flag=0
tr=0
for line in f:
line=line.strip().split()
if(len(line)==0):
flag=1
else:
if(flag):
Tran[line[0]]=[]
tr=line[0]
flag=0
else:
Tran[tr].append(line)
# for x in Tran:
# print (x)
# for y in Tran[x]:
# print(y)
return [Disk,Tran]
def str_to_list(tr,v):
"""
Convert string to list
"""
if(v=="r"):
tr=tr[5:]
tr=tr[:-1]
tr=tr.split(",")
return tr
if(v=="w"):
tr=tr[6:]
tr=tr[:-1]
tr=tr.split(",")
return tr
if(v=="o"):
tr=tr[7:]
tr=tr[:-1]
tr=tr.split(",")
return tr
def evalexp(e,var):
"""
Check which op to perform
"""
if(len(e[2].split('+'))==2):
var[e[0]]=evalexp2(e[2],'+',var)
if(len(e[2].split('-'))==2):
var[e[0]]=evalexp2(e[2],'-',var)
if(len(e[2].split('/'))==2):
var[e[0]]=evalexp2(e[2],'/',var)
if(len(e[2].split('*'))==2):
var[e[0]]=evalexp2(e[2],'*',var)
return var
def evalexp2(e,v,var):
"""
perform op in memory
"""
e=e.split(v)
a=int(var[e[0]])
b=int(e[1])
s=str(a)+v+str(b)
return int(eval(s))
def processaction(tr,var,D,M,x):
"""
Perform individual action
"""
cp=tr#for op
tr=tr[0]#for r,w,o
if(tr[0:4]=="READ"):
#split
tr=str_to_list(tr,"r")
#bring to memory if not there
if(tr[0] not in M):
M[tr[0]]=D[tr[0]]
#set val in var
var[tr[1]]=M[tr[0]]
elif(tr[0:5]=="WRITE"):
#split
tr=str_to_list(tr,"w")
#add to log
s="<"+x+", "+str(tr[0])+", "+str(M[tr[0]])+">"
#change in memory
M[tr[0]]=var[tr[1]]
#printlog
printlog(D,M,s)
elif(tr[0:6]=="OUTPUT"):
#split
tr=str_to_list(tr,"o")
#update in disk
D[tr[0]]=M[tr[0]]
else:
var=evalexp(cp,var)
return var,D,M
def runtr(D,T,M,X,start,var):
"""
Run all transactions for X steps
"""
#check if any trans can occur
flag=False
for x in T:
if(len(T[x])>start):
flag=True
break
#break if not
if(flag==False):
return flag,D,M,var
#loop over all transactions
for x in T:
for y in range(start,min(start+X,len(T[x])),1):
t=T[x][y]
#check if tr starts
if(y==0):
s="<START "+x+">"
printlog(D,M,s)
#run transaction
var,D,M=processaction(t,var,D,M,x)
#check if tr ends
if(y==len(T[x])-1):
s="<COMMIT "+x+">"
printlog(D,M,s)
return flag,D,M,var
def printlog(D,M,s):
"""
Print memory and log status in the given format
"""
#print log
print(s)
#sort M and D
Mt=sorted(M.keys())
Dt=sorted(D.keys())
#print M
i=0
for x in Mt:
i+=1
if(i==len(Mt)):
print(x,M[x],end='')
else:
print(x,M[x],end=' ')
print("")
#print D
i=0
for x in Dt:
i+=1
if(i==len(Dt)):
print(x,D[x],end='')
else:
print(x,D[x],end=' ')
print("")
def processtr(D,T,X):
"""
Run transactions in RR fashion
"""
X=int(X)
M={}
start=0
var={}
#run until all transactions are over
while(1):
flag,D,M,var=runtr(D,T,M,X,start,var)
if(flag==False):
break
else:
start+=X
if __name__=="__main__":
F=sys.argv[1]
X=sys.argv[2]
# print(F,X)
Disk,Transactions=readinput(F)
processtr(Disk,Transactions,X)<file_sep>/20171091.sh
#!/bin/bash
if [ "$#" -eq 2 ]
then
python3 20171091_1.py $1 $2 > 20171091_1.txt
elif [ "$#" -eq 1 ]
then
python3 20171091_2.py $1 > 20171091_2.txt
else
echo "Input format for 1st case: bash <input file name> <X>"
echo "Input format for 2nd case: bash <input file name>"
fi
<file_sep>/20171091_2.py
import sys
def readinput(file):
"""
Returns contents of disk and transactions
"""
Disk,Tran=[{},[]]
with open(file,'r') as f:
#read first line
fl=f.readline()
fl=fl.strip().split()
for i in range(0,len(fl),2):
Disk[fl[i]]=fl[i+1]
# print(Disk)
fl=f.readline()
#read transactions
for line in f:
line=line.strip()
line=line[1:-1]
line=line.split()
Tran.append(line)
# for i in Tran:
# print(i)
return [Disk,Tran]
def preprocess(T):
"""
Convert T in a format easy to work
"""
arr=["START","COMMIT","END"]
for i in range(len(T)):
tr=T[i]
#update logs(remove ',')
if(tr[0] not in arr):
s=""
s=s.join(tr)
s=s.split(',')
T[i]=s
#start ckpts
if(tr[1]=="CKPT"):
#remove ()
tr[2]=tr[2][1:]
tr[-1]=tr[-1][:-1]
#remove ','
for j in range(2,len(tr),1):
if(tr[j][-1]==","):
tr[j]=tr[j][:-1]
T[i]=tr
return T
def find_commit(T):
"""
Return list of committed transactions
"""
CT=[]
for i in T:
if(i[0]=="COMMIT"):
CT.append(i[1])
return CT
def remove_commit(T,CT):
"""
Return updated transaction list after removing committed transactions
"""
arr=["START","COMMIT","END","CKPT"]
T_upd=[]
for i in T:
#start
if(i[0]==arr[0]) and (i[1] not in CT) and(i[1] not in arr):
T_upd.append(i)
#update
if(i[0] not in arr) and (i[0] not in CT):
T_upd.append(i)
#commit
if(i[0]==arr[1]) and (i[1] not in CT):
T_upd.append(i)
#ckpt
if(i[1]==arr[3]):
temp=[]
temp.append(i[0])
temp.append(i[1])
for j in range(2,len(i),1):
if(i[j] not in CT):
temp.append(i[j])
T_upd.append(temp)
return T_upd
def findckpt(T):
"""
Return latest ckpt index
"""
start=len(T)
end=len(T)
for i in range(len(T)):
log=T[i]
if(log[1]=="CKPT"):
start=i
if(log[0]=="END"):
end=i
start=len(T)-1-start
end=len(T)-1-end
return [start,end]
def get_end_index(T,start):
"""
Return index till where we have to do recovery
"""
last=start
#find incomplete transactions
incomplete=[]
for i in range(2,len(T[start]),1):
incomplete.append(T[start][i])
for i in incomplete:
for j in range(start,len(T),1):
x=T[j]
if(x[0]=="START" and x[1]==i):
last=max(last,j)
return last
def log_recovery(D,T):
"""
Return recovered values in disk
"""
#preprocessing
T=preprocess(T)
CT=find_commit(T)
T=remove_commit(T,CT)
start,end=findckpt(T)
#reverse the list
T.reverse()
#initialise variables
arr=["START","COMMIT","END"]
last=len(T)
#CASE-1 no start and no end
if(start==-1 and end==-1):
last=len(T)
#CASE-2 no start but end (not possible)
#CASE-3 start and no end
elif(start!=-1 and end==-1):
last=get_end_index(T,start)
#CASE-3 start and end
elif(start!=-1 and end!=-1):
if(end<start):
last=start
else:
last=get_end_index(T,start)
#do recovery
for i in range(last):
tr=T[i]
if(tr[0] not in arr):
D[tr[1]]=tr[2]
return D
def printdisk(D):
"""
Print content of disk in the given format
"""
Dt=sorted(D.keys())
i=0
for x in Dt:
i+=1
if(i==len(Dt)):
print(x,D[x],end='')
else:
print(x,D[x],end=' ')
print("")
if __name__=="__main__":
F=sys.argv[1]
# print(F,X)
Disk,Transactions=readinput(F)
Disk=log_recovery(Disk,Transactions)
printdisk(Disk)<file_sep>/README.md
# Undo-Logging
Implementaion of undo logging and recovery
| 892bc9e9902f2a6e44c727937d24d5e6c1fb5eab | [
"Markdown",
"Python",
"Shell"
] | 4 | Python | sarthak77/Undo-Logging | b0b74a3ffa2f7edcb6d65d355415083533f76374 | a802ba9157a8a43c117f08fb8bd0aada6483cd7a | |
refs/heads/main | <file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
//Nous indiquons au moteur de rendu DOM que nous allons réhydrater l'app une fois qu'un rendu sera obtenu côté serveur.(méthode hydratation)
ReactDOM.hydrate(<App />, document.getElementById('root'));
<file_sep>import path from 'path';
import fs from 'fs';
import React from 'react';
import express from 'express';
import ReactDOMServer from 'react-dom/server';
import App from '../src/App';
const PORT = process.env.PORT || 3006;
const app = express();
app.get('/', (req, res) => {
const app = ReactDOMServer.renderToString(<App />); //Nous utilisons une méthode de ReactDOMServer, renderToString pour obtenir un rendu de notre app sur une chaîne HTML statique.
// Ensuite, nous lisons le fichier statique index.html de l'app client créée, nous injectons le contenu statique de notre app dans le <div> avec un id « root » et envoyons cela sous forme de réponse à la requête.
const indexFile = path.resolve('./build/index.html');
fs.readFile(indexFile, 'utf8', (err, data) => {
if (err) {
console.error('Something went wrong:', err);
return res.status(500).send('Oops, better luck next time!');
}
return res.send(
data.replace('<div id="root"></div>', `<div id="root">${app}</div>`)
);
});
});
app.use(express.static('./build')); //Nous indiquons à Express de desservir le contenu du répertoire build sous forme de fichiers statiques.
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
}); | 260d3184214e22e48db3bd00e5d1cdd49eb86a0a | [
"JavaScript"
] | 2 | JavaScript | Sentelnia/ssr_training | e0b5a2f4acafc289a999122776cecd0db50fe052 | 3f8c97d0460685fc26f77d7993059df9dee9ddf3 | |
refs/heads/master | <repo_name>eastar-dev/EastarOperaXInterceptor<file_sep>/operaxinterceptor/src/androidTest/java/dev/eastar/operaxinterceptor/event/OperaXEventTestKt.kt
package dev.eastar.operaxinterceptor.event
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import dev.eastar.operaxinterceptor.event.OperaXEventObservable.notify
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class OperaXEventTestKt {
@Test
fun useAppContext() {
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
Assert.assertEquals("dev.eastar.operaxinterceptor", appContext.packageName)
}
@Test
fun sendTest() {
notify(OperaXEvents.Exited)
}
}<file_sep>/operaxinterceptor/src/main/java/dev/eastar/operaxinterceptor/interceptor/OperaXInterceptor.kt
/*
* Copyright 2019 copyright <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.eastar.operaxinterceptor.interceptor
import android.app.Activity
import java.util.*
abstract class OperaXInterceptor : OperaXInitializer(), Observer {
override fun onCreate(): Boolean {
super.onCreate()
OperaXInterceptorObserver.addObserver(this)
android.util.Log.d("OperaXInterceptor", javaClass.name)
return true
}
override fun update(observable: Observable, data: Any) {
if ((data as Type).activity.javaClass.getAnnotation(OperaXSkip::class.java) != null) {
return
}
try {
when (data) {
is ON_CREATE -> onCreate(data.activity)
is ON_DESTROY -> onDestroy(data.activity)
is ON_START -> onStart(data.activity)
is ON_STOP -> onStop(data.activity)
is ON_RESUME -> onResume(data.activity)
is ON_PAUSE -> onPause(data.activity)
else -> Unit //Log.e("!undefined message")
}
} catch (e: Exception) {
e.printStackTrace()
}
}
protected open fun onCreate(activity: Activity) {}
protected open fun onDestroy(activity: Activity) {}
protected open fun onStart(activity: Activity) {}
protected open fun onStop(activity: Activity) {}
protected open fun onResume(activity: Activity) {}
protected open fun onPause(activity: Activity) {}
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
annotation class OperaXMain
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
annotation class OperaXSkip
}
<file_sep>/operaxinterceptor/src/main/java/dev/eastar/operaxinterceptor/event/OperaXEventInitializer.kt
/*
* Copyright 2019 copyright <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.eastar.operaxinterceptor.event
import android.app.Activity
import android.app.Application
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentManager.FragmentLifecycleCallbacks
import dev.eastar.operaxinterceptor.interceptor.OperaXInitializer
class OperaXEventInitializer : OperaXInitializer() {
override fun initialize(application: Application) {
application.operaXEventRegister()
}
}
fun Application.operaXEventRegister() {
registerActivityLifecycleCallbacks(
object : Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, bundle: Bundle?) {
if (activity is OperaXEventObserver) OperaXEventObservable.addObserver(activity)
if (activity is AppCompatActivity) registerFragment(activity)
}
override fun onActivityDestroyed(activity: Activity) {
if (activity is OperaXEventObserver) OperaXEventObservable.deleteObserver(activity)
}
fun registerFragment(activity: AppCompatActivity) {
activity.supportFragmentManager.registerFragmentLifecycleCallbacks(object : FragmentLifecycleCallbacks() {
override fun onFragmentCreated(fm: FragmentManager, f: Fragment, savedInstanceState: Bundle?) {
if (f is OperaXEventObserver) OperaXEventObservable.addObserver(f)
}
override fun onFragmentDestroyed(fm: FragmentManager, f: Fragment) {
if (f is OperaXEventObserver) OperaXEventObservable.deleteObserver(f)
}
}, true)
}
override fun onActivityStarted(activity: Activity) {}
override fun onActivityStopped(activity: Activity) {}
override fun onActivityResumed(activity: Activity) {}
override fun onActivityPaused(activity: Activity) {}
override fun onActivitySaveInstanceState(activity: Activity, bundle: Bundle) {}
}
)
}
<file_sep>/operaxinterceptor/src/debug/java/opera/OperaXInterceptorDump.kt
package opera
import android.app.Application
import dalvik.system.DexFile
import dev.eastar.operaxinterceptor.interceptor.OperaXInterceptor
import java.util.concurrent.Executors
fun Application.operaXInterceptorDump() {
Executors.newSingleThreadExecutor().execute {
runCatching {
val parentClass = OperaXInterceptor::class.java
val packageName = parentClass.`package`?.name!!
val thisClass = parentClass.name
DexFile(packageCodePath).entries().toList()
.filter { it.startsWith(packageName) }
.filterNot { it.startsWith(thisClass) }
.filterNot { it.contains('$') }
.map { Class.forName(it) }
.filter { parentClass.isAssignableFrom(it) }
.forEach { android.util.Log.w("OperaXInterceptorDump", it.toString()) }
}
}
}<file_sep>/operaxinterceptor/src/main/java/dev/eastar/operaxinterceptor/event/OperaXEventObservable.kt
/*
* Copyright 2019 copyright <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.eastar.operaxinterceptor.event
import androidx.annotation.MainThread
import java.util.*
object OperaXEventObservable : Observable() {
@MainThread
@JvmStatic
fun notify(obj: Any) {
notifyObservers(obj)
}
override fun notifyObservers(data: Any) {
if (data.javaClass.getAnnotation(OperaXEvent::class.java) == null)
throw UnsupportedOperationException("!event obj must annotation in the ${OperaXEvent::class.java}")
setChanged()
super.notifyObservers(data)
}
}
<file_sep>/operaxinterceptor/src/main/java/dev/eastar/operaxinterceptor/event/OperaXEvent.kt
package dev.eastar.operaxinterceptor.event
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
annotation class OperaXEvent
<file_sep>/operaxinterceptor/src/main/java/dev/eastar/operaxinterceptor/event/OperaXEvents.kt
package dev.eastar.operaxinterceptor.event
@OperaXEvent
enum class OperaXEvents {
Exited, Logouted, Logined;
}
<file_sep>/settings.gradle
include ':operaxinterceptor'
<file_sep>/operaxinterceptor/src/main/java/dev/eastar/operaxinterceptor/interceptor/OperaXInitializer.kt
/*
* Copyright 2019 copyright <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.eastar.operaxinterceptor.interceptor
import android.app.Application
import android.content.ContentProvider
import android.content.ContentValues
import android.database.Cursor
import android.net.Uri
abstract class OperaXInitializer : ContentProvider() {
abstract fun initialize(application: Application)
override fun onCreate(): Boolean {
(context?.applicationContext as? Application)?.let {
android.util.Log.d("OperaXInitializer", javaClass.name);
initialize(it)
}
return true
}
override fun getType(uri: Uri): String? = null
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
override fun query(uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String?): Cursor? = null
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int = 0
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int = 0
}
| 0ce91a1d781f63684966795e693e4a4748624d98 | [
"Kotlin",
"Gradle"
] | 9 | Kotlin | eastar-dev/EastarOperaXInterceptor | 9151bdfb240c4f41fd9c36a6b6c56048d2ecd73e | 4e703b44adbafd82f68f9635af2690613bbab50b | |
refs/heads/master | <file_sep>package com.ceej.controller;
import com.ceej.model.Article;
import org.junit.jupiter.api.*;
import org.mockito.Matchers;
import java.io.File;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class ArticleControllerTest {
DataBaseUtility mock_dbUtil;
FileOperator mock_fileOp;
ArticleController articleController;
@BeforeEach
public void mocksetup(){
mock_dbUtil = mock(DataBaseUtility.class);
mock_fileOp = mock(FileOperator.class);
articleController = new ArticleController(mock_dbUtil, mock_fileOp);
}
// testing for publishAnArticle
@Test
@Disabled
@DisplayName("publishAnArticle: userID不能为空")
public void publishAnArticle_userId_should_not_be_null(){
when(mock_dbUtil.isUserExisted(null)).thenReturn(false);
String jsonBase = "{\n" +
"\t\"content\":\"随便打的\"\n" +
"}";
assertEquals("404", articleController.publishAnArticle(jsonBase).getCode());
}
@Test
@Disabled
@DisplayName("publishAnArticle: content不能为空")
public void publishAnArticle_content_should_not_be_null(){
when(mock_dbUtil.isUserExisted(null)).thenReturn(false);
when(mock_dbUtil.addArticle("1",null,".")).thenReturn(false);
String jsonBase = "{\n" +
"\t\"userID\":\"1\"\n" +
"}";
assertEquals("404", articleController.publishAnArticle(jsonBase).getCode());
}
@Test
@Disabled
@DisplayName("publishAnArticle: img可以为空")
public void publishAnArticle_img_can_be_null(){
when(mock_dbUtil.isUserExisted("1")).thenReturn(true);
when(mock_dbUtil.addArticle("1","随便写写","")).thenReturn(true);
String jsonBase = "{\n" +
"\t\"userID\":\"1\",\n" +
"\t\"content\": \"随便写写\"\n" +
"}";
assertEquals("205", articleController.publishAnArticle(jsonBase).getCode());
}
@Test
@Disabled
@DisplayName("publishAnArticle: imgData不能被解析生成imgUrl")
public void publishAnArticle_imgData_cannot_be_decoded(){
when(mock_dbUtil.isUserExisted("1")).thenReturn(true);
when(mock_dbUtil.addArticle("1","content","")).thenReturn(true);
when(mock_fileOp.getImage(anyString(), anyString())).thenReturn("false");
String jsonBase = "{\n" +
"\t\"userID\":\"1\",\n" +
"\t\"content\": \"content\",\n" +
"\t\"imgData\":\"xxx\"\n" +
"}";
assertEquals("404", articleController.publishAnArticle(jsonBase).getCode());
}
@Test
@Disabled
@DisplayName("publishAnArticle: imgData能被解析生成imgUrl")
public void publishAnArticle_imgData_can_be_decoded(){
when(mock_dbUtil.isUserExisted("1")).thenReturn(true);
when(mock_dbUtil.addArticle(anyString(),anyString(),anyString())).thenReturn(true);
when(mock_fileOp.getImage(anyString(), anyString())).thenReturn("");
String jsonBase = "{\n" +
"\t\"userID\":\"1\",\n" +
"\t\"content\": \"content\",\n" +
"\t\"imgData\":\"xxx\"\n" +
"}";
assertEquals("205", articleController.publishAnArticle(jsonBase).getCode());
}
@Test
@Disabled
@DisplayName("publishAnArticle: 发布的userid存在")
public void publishAnArticle_with_existed_user(){
when(mock_dbUtil.isUserExisted("1")).thenReturn(true);
when(mock_dbUtil.addArticle("1","content","")).thenReturn(true);
String jsonBase = "{\n" +
"\t\"userID\":\"1\",\n" +
"\t\"content\": \"content\"\n" +
"}";
assertEquals("205", articleController.publishAnArticle(jsonBase).getCode());
}
@Test
@Disabled
@DisplayName("publishAnArticle: 发布的userid不存在")
public void publishAnArticle_with_none_existed_user(){
when(mock_dbUtil.isUserExisted("1")).thenReturn(false);
when(mock_dbUtil.addArticle("1","content","")).thenReturn(false);
String jsonBase = "{\n" +
"\t\"userID\":\"1\",\n" +
"\t\"content\": \"content\"\n" +
"}";
assertEquals("404", articleController.publishAnArticle(jsonBase).getCode());
}
//testing for deleteAnArticle
@Test
@Disabled
@DisplayName("deleteAnArticle: ID不能为空")
public void deleteAnArticle_Id_should_not_be_null(){
when(mock_dbUtil.isArticleExisted(null)).thenReturn(false);
String jsonBase = "{}";
assertEquals("404", articleController.deleteAnArticle(jsonBase).getCode());
}
@Test
@Disabled
@DisplayName("deleteAnArticle: 待删除的article存在")
public void deleteAnArticle_with_existed_article(){
when(mock_dbUtil.isArticleExisted("1")).thenReturn(true);
when(mock_dbUtil.deleteArticle("1")).thenReturn(true);
String jsonBase = "{\n" +
"\t\"articleID\":\"1\"\n" +
"}";
assertEquals("205", articleController.deleteAnArticle(jsonBase).getCode());
}
@Test
@Disabled
@DisplayName("deleteAnArticle: 待删除的article不存在")
public void deleteAnArticle_with_none_existed_article(){
when(mock_dbUtil.isArticleExisted("1")).thenReturn(false);
when(mock_dbUtil.deleteArticle("1")).thenReturn(true);
String jsonBase = "{\n" +
"\t\"articleID\":\"1\"\n" +
"}";
assertEquals("404", articleController.deleteAnArticle(jsonBase).getCode());
}
//testing retrieveNewestArticles
@Test
@Disabled
public void retrieveNewestArticles_query_articles_failed_return_num_0() {
when(mock_dbUtil.getCurrentArticles(anyInt(), anyInt())).thenReturn(null);
String jsonBase = "{\n" +
"\t\"front_article_id\":\"0\",\n" +
"\t\"max_num\":\"10\"\n" +
"}";
assertEquals(0, ((ArrayList<Article>)(articleController.retrieveNewestArticles(jsonBase).getData())).size());
}
@Test
@Disabled
public void retrieveNewestArticles_return_correct_number_of_article_which_id_greater_than_front(){
Article a1=new Article(),a2=new Article(),a3=new Article(),a4=new Article(),a5=new Article();
a1.setArticleID("1");
a2.setArticleID("2");
a3.setArticleID("3");
a4.setArticleID("4");
a5.setArticleID("5");
ArrayList<Article> al = new ArrayList<Article>();
al.add(a5);al.add(a4);
when(mock_dbUtil.getCurrentArticles(3, 10)).thenReturn(al);
String jsonBase = "{\n" +
"\t\"front_article_id\":\"3\",\n" +
"\t\"max_num\":\"10\"\n" +
"}";
assertAll(
()->{assertEquals(2,((ArrayList<Article>)(articleController.retrieveNewestArticles(jsonBase).getData())).size());},
()->{assertEquals("5",((ArrayList<Article>)(articleController.retrieveNewestArticles(jsonBase).getData())).get(0).getArticleID());},
()->{assertEquals("4",((ArrayList<Article>)(articleController.retrieveNewestArticles(jsonBase).getData())).get(1).getArticleID());}
);
}
@Test
@Disabled
public void retrieveNewestArticles_return_correct_number_of_article_which_maximum_equals_to_num(){
Article a1=new Article(),a2=new Article(),a3=new Article(),a4=new Article(),a5=new Article();
a1.setArticleID("1");
a2.setArticleID("2");
a3.setArticleID("3");
a4.setArticleID("4");
a5.setArticleID("5");
ArrayList<Article> al = new ArrayList<Article>();
al.add(a5);al.add(a4);
when(mock_dbUtil.getCurrentArticles(1, 2)).thenReturn(al);
String jsonBase = "{\n" +
"\t\"front_article_id\":\"1\",\n" +
"\t\"max_num\":\"2\"\n" +
"}";
assertAll(
()->{assertEquals(2,((ArrayList<Article>)(articleController.retrieveNewestArticles(jsonBase).getData())).size());},
()->{assertEquals("5",((ArrayList<Article>)(articleController.retrieveNewestArticles(jsonBase).getData())).get(0).getArticleID());},
()->{assertEquals("4",((ArrayList<Article>)(articleController.retrieveNewestArticles(jsonBase).getData())).get(1).getArticleID());}
);
}
//testing retrievePreviousArticles
@Test
public void retrievePreviousArticles_query_articles_failed_return_num_0() {
when(mock_dbUtil.getPreviousArticles(anyInt(), anyInt())).thenReturn(null);
String jsonBase = "{\n" +
"\t\"tail_article_id\":\"0\",\n" +
"\t\"max_num\":\"100\"\n" +
"}";
assertEquals(0, ((ArrayList<Article>)(articleController.retrievePreviousArticles(jsonBase).getData())).size());
}
@Test
public void retrievePreviousArticles_return_correct_number_of_article_which_id_greater_than_front(){
Article a1=new Article(),a2=new Article(),a3=new Article(),a4=new Article(),a5=new Article();
a1.setArticleID("1");
a2.setArticleID("2");
a3.setArticleID("3");
a4.setArticleID("4");
a5.setArticleID("5");
ArrayList<Article> al = new ArrayList<Article>();
al.add(a2);al.add(a1);
when(mock_dbUtil.getPreviousArticles(3, 10)).thenReturn(al);
String jsonBase = "{\n" +
"\t\"tail_article_id\":\"3\",\n" +
"\t\"max_num\":\"10\"\n" +
"}";
assertAll(
()->{assertEquals(2,((ArrayList<Article>)(articleController.retrievePreviousArticles(jsonBase).getData())).size());},
()->{assertEquals("2",((ArrayList<Article>)(articleController.retrievePreviousArticles(jsonBase).getData())).get(0).getArticleID());},
()->{assertEquals("1",((ArrayList<Article>)(articleController.retrievePreviousArticles(jsonBase).getData())).get(1).getArticleID());}
);
}
@Test
public void retrievePreviousArticles_return_correct_number_of_article_which_maximum_equals_to_num(){
Article a1=new Article(),a2=new Article(),a3=new Article(),a4=new Article(),a5=new Article();
a1.setArticleID("1");
a2.setArticleID("2");
a3.setArticleID("3");
a4.setArticleID("4");
a5.setArticleID("5");
ArrayList<Article> al = new ArrayList<Article>();
al.add(a4);al.add(a3);
when(mock_dbUtil.getPreviousArticles(5, 2)).thenReturn(al);
String jsonBase = "{\n" +
"\t\"tail_article_id\":\"5\",\n" +
"\t\"max_num\":\"2\"\n" +
"}";
assertAll(
()->{assertEquals(2,((ArrayList<Article>)(articleController.retrievePreviousArticles(jsonBase).getData())).size());},
()->{assertEquals("4",((ArrayList<Article>)(articleController.retrievePreviousArticles(jsonBase).getData())).get(0).getArticleID());},
()->{assertEquals("3",((ArrayList<Article>)(articleController.retrievePreviousArticles(jsonBase).getData())).get(1).getArticleID());}
);
}
}<file_sep># Software Testing Assignment 02
## Timeline
- A vertical social message display
## Testing Goal
- Unit Test
## Team work and individual contribution
- ceej7 - Weijie(10151511103)
- Article transaction and related DB function
- ArticleController Unit Testing
- Timeline frontend
- makise - 郭省吾(10175101106)
- Some modification in the implementation of ArticleController
- DataBaseUtility(Persistent Layer) Unit Testing
- TODO
| 08c9b5c9a069fccb289ed6146dc8138d6fb350ef | [
"Markdown",
"Java"
] | 2 | Java | yuanfeif/Testing-Timeline | d848b872467ffb77e4ffc7bae40ebf273c8b9ecf | c6ea97e4623970d620d2f035978fd3f5595f8e60 | |
refs/heads/master | <file_sep>## test
##test2
| 1c7ad5eef97c6a50941300b00af91e0aecaa985a | [
"Ruby"
] | 1 | Ruby | davehenton/doesitworkwith.js | 4192d1878777040f73d39e4db2bb3761e87cf005 | 5a716e37f26cd5ef577a2c2512aa6508366d7454 | |
refs/heads/master | <repo_name>bmvermeer/jhipster-snyk-examples<file_sep>/src/main/java/io/snyk/bmvermeer/jhipsnyk/web/rest/vm/package-info.java
/**
* View Models used by Spring MVC REST controllers.
*/
package io.snyk.bmvermeer.jhipsnyk.web.rest.vm;
<file_sep>/src/main/java/io/snyk/bmvermeer/jhipsnyk/repository/package-info.java
/**
* Spring Data JPA repositories.
*/
package io.snyk.bmvermeer.jhipsnyk.repository;
<file_sep>/src/main/java/io/snyk/bmvermeer/jhipsnyk/security/package-info.java
/**
* Spring Security configuration.
*/
package io.snyk.bmvermeer.jhipsnyk.security;
<file_sep>/src/main/java/io/snyk/bmvermeer/jhipsnyk/service/package-info.java
/**
* Service layer beans.
*/
package io.snyk.bmvermeer.jhipsnyk.service;
| 930c666293a1e18132f417f0e8f3b4534b5dc052 | [
"Java"
] | 4 | Java | bmvermeer/jhipster-snyk-examples | 9968e0d1efb6de0aa0957dba24391a77e6df3f78 | e401c151c77144e133bf64a125e1c7cd42943c24 | |
refs/heads/master | <file_sep><?php
/**
* Created by <NAME>.
* User: smoqadam <<EMAIL>>
* Date: 8/13/2016
* Time: 8:22 AM
*/
namespace Smoqadam\Js;
use stdClass;
use yii\base\Component;
use yii\helpers\Json;
use yii\web\View;
class Js extends Component
{
/**
* Position in the page
*
* @var int|string
*/
public $pos;
/**
* The namespace to nest JS vars under.
*
* @var string
*/
protected $namespace;
/**
* All transformable types.
*
* @var array
*/
protected $types = [
'String',
'Array',
'Object',
'Numeric',
'Boolean',
'Null'
];
/**
* Create a new JS transformer instance.
*
* @param string $namespace
*/
public function __construct($namespace = 'window', $pos = View::POS_HEAD)
{
$this->namespace = $namespace;
$this->pos = $pos;
}
/**
* Bind the given array of variables to the view.
*
*/
public function put()
{
$arguments = func_get_args();
if (is_array($arguments[0])) {
$variables = $arguments[0];
} elseif (count($arguments) == 2) {
$variables = [$arguments[0] => $arguments[1]];
} else {
throw new \Exception('Try JavaScript::put(["foo" => "bar"]');
}
// First, we have to translate the variables
// to something JS-friendly.
$js = $this->buildJavaScriptSyntax($variables);
// And then we'll actually bind those
// variables to the view.
\Yii::$app->view->registerJs($js, $this->pos);
return $js;
}
/**
* Translate the array of PHP vars to
* the expected JavaScript syntax.
*
* @param array $vars
* @return array
*/
public function buildJavaScriptSyntax(array $vars)
{
$js = $this->buildNamespaceDeclaration();
foreach ($vars as $key => $value) {
$js .= $this->buildVariableInitialization($key, $value);
}
return $js;
}
/**
* Create the namespace to which all vars are nested.
*
* @return string
*/
protected function buildNamespaceDeclaration()
{
if ($this->namespace == 'window') {
return '';
}
return "window.{$this->namespace} = window.{$this->namespace} || {};";
}
/**
* Translate a single PHP var to JS.
*
* @param string $key
* @param string $value
* @return string
*/
protected function buildVariableInitialization($key, $value)
{
return "{$this->namespace}.{$key} = {$this->optimizeValueForJavaScript($value)};";
}
/**
* Format a value for JavaScript.
*
* @param string $value
* @throws \Exception
* @return string
*/
protected function optimizeValueForJavaScript($value)
{
// For every transformable type, let's see if
// it needs to be transformed for JS-use.
foreach ($this->types as $transformer) {
$js = $this->{"transform{$transformer}"}($value);
if (!is_null($js)) {
return $js;
}
}
}
/**
* Transform a string.
*
* @param string $value
* @return string
*/
protected function transformString($value)
{
if (is_string($value)) {
return "'{$this->escape($value)}'";
}
}
/**
* Transform an array.
*
* @param array $value
* @return string
*/
protected function transformArray($value)
{
if (is_array($value)) {
return json_encode($value);
}
}
/**
* Transform a numeric value.
*
* @param mixed $value
* @return mixed
*/
protected function transformNumeric($value)
{
if (is_numeric($value)) {
return $value;
}
}
/**
* Transform a boolean.
*
* @param boolean $value
* @return string
*/
protected function transformBoolean($value)
{
if (is_bool($value)) {
return $value ? 'true' : 'false';
}
}
/**
* @param object $value
* @return string
* @throws \Exception
*/
protected function transformObject($value)
{
if (!is_object($value)) {
return;
}
if ($value instanceof Json || $value instanceof StdClass) {
return json_encode($value);
}
// if the object doesn't even have a
// __toString() method, we can't proceed.
if (!method_exists($value, '__toString')) {
throw new \Exception('Cannot transform this object to JavaScript.');
}
return "'{$value}'";
}
/**
* Transform "null."
*
* @param mixed $value
* @return string
*/
protected function transformNull($value)
{
if (is_null($value)) {
return 'null';
}
}
/**
* Escape any single quotes.
*
* @param string $value
* @return string
*/
protected function escape($value)
{
return str_replace(["\\", "'"], ["\\\\", "\'"], $value);
}
}
<file_sep>## Yii1- PHP Vars to Jacascript
Transform PHP Vars to JavaScript
ported from http://github.com/laracasts/PHP-Vars-To-Js-Transformer
## How to use
Put `Js.php` in `components` directory
and use it like this :
```php
$js = new Js();
$testClass = new \stdClass();
$testClass->aa = 'saeed';
$testClass->test = 'test';
$js->put(['testVars' => $testClass, 'age' => 22, 'amount' => 22.3]);
```
for more information take a look at : https://github.com/laracasts/PHP-Vars-To-Js-Transformer
| 12930d088d2d3e05bbc03409043969f65b374531 | [
"Markdown",
"PHP"
] | 2 | PHP | smoqadam/yii2-php-vars-to-js | 931a9bb946b05717392abe520cea5d3952e02daa | 8fba6198af498633167f4d341193c37c91636e30 | |
refs/heads/master | <file_sep># Surf-forecast
enter a coastal city and get current wave size and water temp.
Buttons to switch from Celcius to Fahrenheit and Meters to Feet.
REPL code: https://repl.it/@rmccorkle46/StunningWateryWebsphere
Link: https://stunningwaterywebsphere--rmccorkle46.repl.co/
<file_sep>
//stormGlass Api will return wave height and water temps for provided lat and long
const CastUrl = "https://api.stormglass.io/forecast";
const key = "06b36a2c-6295-11e8-8b92-0242ac120008-06b36bda-6295-11e8-8b92-0242ac120008";
function callStormGlassApi(long, lat, Loc) {
$.ajax({
url: CastUrl,
data: {
lat: lat,
lng: long
},
headers: {
'Authentication-Token': key
},
dataType: 'json',
type: 'GET',
success: function(data) {
//in renderPage, 'Loc' is passed through to provide name of city when rendered
renderPage(data, Loc);
},
error: renderError
})
}
//getProp function determines if value returned is null (error)
function getProp(object, keys, defaultVal = null) {
keys = Array.isArray(keys) ? keys : keys.replace(/(\[(\d)\])/g, '.$2').split('.');
object = object[keys[0]];
if (object && keys.length > 1) {
return getProp(object, keys.slice(1), defaultVal);
}
return object === undefined ? defaultVal : object;
}
function renderPage(data, Loc) {
//below var to capture wave height data from StormGlass API
const height = getProp(data, 'hours[0].waveHeight[1].value')
//below var to capture water temp data from StormGlass API
const water = getProp(data, 'hours[0].waterTemperature[2].value');
if(height && water) {
$('.outputWrapper').prop('hidden', false);
$('.output-heading').html(`<h2>Today\'s conditions for ${Loc}:</h2>`);
$('.output-heading').removeClass('hidden-element');
$('.output').html(`<div>Wave Height: ${height} meters <button class="buttonOut" data-measure="${height}" data-unitsm="m">Meters/Feet</button></div>`);
$('.waterTemp').html(`<div>Water temp: ${water} celcius <button class="buttonW" data-temp="${water}" data-units="c">Celcius/Fahrenheit</button></div>`);
} else {
renderError()
}
}
//GoogleApi translates Loc into Lat and Long coordinates
function callGoogleApi(Loc) {
$.ajax({
url: 'https://maps.googleapis.com/maps/api/geocode/json',
data: {
key: '<KEY>',
address: Loc
},
success: function(data) {
const long = data.results[0].geometry.location.lng;
const lat = data.results[0].geometry.location.lat;
callStormGlassApi(long, lat, Loc);
},
error: renderError
})
}
function renderError() {
$('.output-heading').empty();
$('.waterTemp').empty();
$('.output').html('<h2 class="error">No info on that location, try another one.</h2>')
}
function convert(temp, units) {
//logic to convert temp from Celcius to Fahrenheit
if(units === "c") {
const output = Number(temp) * 9 / 5 + 32;
const rounded = Math.round(output * 100) / 100
$('.waterTemp').html(`<div>Water temp: ${rounded} fahrenheit <button class="buttonW" data-temp="${rounded}" data-units="f">Celcius/Fahrenheit</button></div>`);
}
//logic to convert from fahrenheit to Celcius
else {
const output = (Number(temp)-32) / 1.8
const rounded = Math.round(output * 100) / 100
$('.waterTemp').html(`<div>Water temp: ${rounded} celcius <button class="buttonW" data-temp="${rounded}" data-units="c">Celcius/Fahrenheit</button></div>`);
}
}
function LengthConverter(height, measure) {
//upon button click, convert from meters to feet
if(measure === "m") {
const output = Number(height) *3.2808;
//below makes decimal to second place
const rounded = Math.round(output * 100) / 100
$('.output').html(`<div>Wave Height: ${rounded} feet <button class="buttonOut" data-measure="${rounded}" data-unitsm="f">Meters/Feet</button></div>`);
}
//feet to meters
else {
console.log(height)
const output = (Number(height) * 0.3048);
//below makes decimal to second place
const rounded = Math.round(output * 100) / 100;
$('.output').html(`<div>Wave Height: ${rounded} meters <button class="buttonOut" data-measure="${rounded}" data-unitsm="m">Meters/Feet</button></div>`);
}
}
function watchSubmit() {
//capture search box value (city) upon submission and send to googleApi to get city longitude and latitude
$('.js-search-form').submit(function(event) {
event.preventDefault();
const queryTarget = $('.js-query');
const query = queryTarget.val();
queryTarget.val("");
callGoogleApi(query);
});
//flip water temps to Fahrenheit\Celcius on button click
$('.waterTemp').on('click', '.buttonW', function(event) {
const temp = $(this).attr('data-temp');
const units = $(this).attr('data-units');
convert(temp, units);
});
//Flip wave heights feet\meters
$('.output').on('click', '.buttonOut', function(event) {
const height = $(this).attr('data-measure');
const measure = $(this).attr('data-unitsm');
//console.log(height, measure)
LengthConverter(height, measure)
})
}
$(watchSubmit); | 18279c8248ad42b2e70b07767aeb3778b8457863 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | Aloha46/Surf-forecast | 84cd218faf5f6d2be1ac3ef5a1c10bfff50fff5d | 70b2e4c7801425c297b5c0d626c81d493a89c3b1 | |
refs/heads/master | <file_sep><?php
/**
* Author: <EMAIL>
* Date: 8/24/15
* Hope this helps you, please at least leave my name in place
*
* Update 2017-05-03
* by <NAME>
* https://github.com/maruisd
*
* Thanks to avenirer, for putting me on this path.
*
* Load it
* $this->load->helper('fonticons');
* or
* autoload['helper'] = array('fonticons');
*
* use it in view
* echo fa_icon('','align-left');
* echo gl_icon('','align-left');
*
* Location: /application/helpers
*
*/
defined('BASEPATH') OR exit('No direct script access allowed');
if ( ! function_exists('fa_icon'))
{
function fa_icon($icon_color='', $icon = '', $attributes = '')
{
if(!$icon_color)
{
$icon_color ='black';
}
return '<span style="color:'.$icon_color.'" class="fa fa-'.$icon.' '.$attributes.' aria-hidden="true">'.'</span>';
}
}
if ( ! function_exists('gl_icon'))
{
function gl_icon($icon_color='', $icon = '', $attributes = '')
{
if(!$icon_color)
{
$icon_color ='black';
}
return '<span style="color:'.$icon_color.'" class="glyphicon glyphicon-'.$icon.' '.$attributes.'" aria-hidden="true">'.'</span>';
}
}
<file_sep># ci-fonticons_helper
A simple codeigniter helper for Font-aweseome and Glyphicons
<p>
//Load it<br>
$this->load->helper('fonticons');<br>
</p>
<p>
//use it<br>
echo fa_icon('color','align-left');<br>
echo gl_icon('color','align-left');
</p>
<p>
//or<br>
echo fa_icon('color','align-left','fa-2x');<br>
If you use Font Awesome, then you can use the fa-2x sizing to change the size of the icon:<br>
echo gl_icon('color','align-left','fa-2x');
</p>
| d5606d09af42d9fa649311bf4ebf59804701644a | [
"Markdown",
"PHP"
] | 2 | PHP | maruisd/ci-fonticons_helper | cd296b0c87e20cf6477e70c6b05c8b3da4cb68b1 | 99937806d01edcd17bd2b973299e3f4047bb7913 | |
refs/heads/master | <file_sep>#include <oss_c_sdk/oss_define.h>
#include "aos_log.h"
#include "aos_util.h"
#include "aos_string.h"
#include "aos_status.h"
#include "oss_auth.h"
#include "oss_util.h"
#include "oss_api.h"
#include "oss_config.h"
#include "oss_sample_util.h"
void create_select_object_metadata(int* rows, int* splits)
{
aos_pool_t *p = NULL;
aos_string_t bucket;
aos_string_t object;
int is_cname = 0;
oss_request_options_t *options = NULL;
aos_table_t *headers = NULL;
aos_table_t *resp_headers = NULL;
aos_status_t *s = NULL;
char *rows_str = NULL;
char *splits_str = NULL;
char *object_type = NULL;
aos_pool_create(&p, NULL);
options = oss_request_options_create(p);
init_sample_request_options(options, is_cname);
aos_str_set(&bucket, BUCKET_NAME);
aos_str_set(&object, OBJECT_NAME);
headers = aos_table_make(p, 0);
csv_format_option csv_format;
csv_format.field_delimiter = ',';
csv_format.field_quote = '"';
aos_str_set(&(csv_format.record_delimiter), "\n");
csv_format.header_info = CSV_HEADER_IGNORE;
select_input_serialization input_serialization;
input_serialization.csv_format = csv_format;
input_serialization.compression_info = NONE;
oss_select_metadata_option option;
option.overwrite = 1;
option.input_serialization = input_serialization;
s = oss_create_select_object_metadata(options, &bucket, &object, &option, headers, &resp_headers);
if (aos_status_is_ok(s)) {
rows_str = (char*)apr_table_get(resp_headers, OSS_SELECT_CSV_ROWS);
if (rows_str != NULL) {
*rows = atol(rows_str);
}
splits_str = (char*)apr_table_get(resp_headers, OSS_SELECT_CSV_SPLITS);
if (splits_str != NULL) {
*splits = atol(splits_str);
}
object_type = (char*)apr_table_get(resp_headers, OSS_OBJECT_TYPE);
printf("csv head object succeeded, object type:%s, csv rows:%ld\n, splits:%ld\n",
object_type, *rows, *splits);
} else {
printf("csv head object failed\n");
}
aos_pool_destroy(p);
}
char* select_object_to_buffer(aos_pool_t *p, const char* sql_str, int start, int end, select_range_option option, int64_t* plen)
{
aos_string_t bucket;
aos_string_t object;
int is_cname = 0;
oss_request_options_t *options = NULL;
aos_table_t *headers = NULL;
aos_table_t *resp_headers = NULL;
aos_status_t *s = NULL;
aos_list_t buffer;
aos_buf_t *content = NULL;
char *buf = NULL;
int64_t len = 0;
int64_t size = 0;
int64_t pos = 0;
options = oss_request_options_create(p);
init_sample_request_options(options, is_cname);
aos_str_set(&bucket, BUCKET_NAME);
aos_str_set(&object, OBJECT_NAME);
aos_list_init(&buffer);
select_input_serialization input_serialization;
input_serialization.csv_format = csv_format_option_default;
input_serialization.compression_info = NONE;
select_output_serialization output_serialization;
output_serialization.csv_format = csv_format_option_default;
output_serialization.keep_all_columns = 1;
oss_select_option select_option;
select_option.input_serialization = input_serialization;
select_option.output_serialization = output_serialization;
select_option.range_option = option;
select_option.range[0] = start;
select_option.range[1] = end;
aos_string_t sql;
aos_str_set(&sql, sql_str);
select_option.expression = sql;
s = oss_select_object_to_buffer(options, &bucket, &object, &select_option,
headers, &buffer, &resp_headers);
if (aos_status_is_ok(s)) {
printf("get object to buffer succeeded\n");
}
else {
printf("get object to buffer failed\n");
}
//get buffer len
aos_list_for_each_entry(aos_buf_t, content, &buffer, node) {
len += aos_buf_size(content);
}
buf = aos_pcalloc(p, (apr_size_t)(len + 1));
buf[len] = '\0';
//copy buffer content to memory
aos_list_for_each_entry(aos_buf_t, content, &buffer, node) {
size = aos_buf_size(content);
memcpy(buf + pos, content->pos, (size_t)size);
pos += size;
}
*plen = len;
return buf;
}
void select_object_to_buffer_sample()
{
int64_t result_len = 0;
aos_pool_t *p=NULL;
aos_pool_create(&p, NULL);
char *buf = select_object_to_buffer(p, "select count(*) from ossobject where _4 > 60 and _1 like 'Tom%'", -1, -1, NO_RANGE, &result_len);
printf(buf);
buf = select_object_to_buffer(p, "select _1,_4 from ossobject where _4 > 60 and _1 like 'Tom%' limit 100", -1, -1, NO_RANGE, &result_len);
printf("\n\n%s", buf);
aos_pool_destroy(p);
}
void select_object_to_buffer_big_file_sample()
{
aos_pool_t *p=NULL;
aos_pool_create(&p, NULL);
int splits;
int lines;
create_select_object_metadata(&lines, &splits);
int blockSize = 3;
int64_t result_len = 0;
printf("------------line range sample-----------\n");
for(int i = 0; i < blockSize; i++){
int start_line = i * lines/blockSize;
int end_line = i == blockSize -1 ? lines - 1 : (i+1) * lines/blockSize - 1;
char *buf = select_object_to_buffer(p, "select count(*) from ossobject where _4 > 50 and _1 like 'Tom%'", start_line, end_line, LINE, &result_len);
printf("%ld\n", atol(buf));
}
printf("------------split range sample-----------\n");
for(int i = 0; i < blockSize; i++){
int start_split = i * splits/blockSize;
int end_split = i == blockSize -1 ? splits - 1 : (i+1) * splits/blockSize - 1;
char *buf = select_object_to_buffer(p, "select count(*) from ossobject where _4 > 50 and _1 like 'Tom%'", start_split, end_split, SPLIT, &result_len);
printf("%ld\n", atol(buf));
}
aos_pool_destroy(p);
} | ec0283fc0dd6b46485adce5bf60034b470edc4a1 | [
"C"
] | 1 | C | qixu001/aliyun-oss-c-sdk | 901c2179638d1c3eaaf995a514b732ed32943dc6 | ac1b1331fe2b6d412e8d2e4d49adbb956bb6f3b7 | |
refs/heads/master | <repo_name>heriyantoliu/codepipeline<file_sep>/main.go
package main
import (
"encoding/json"
"net/http"
"os"
"strconv"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
)
// Movie Entity
type Movie struct {
ID string `json:"id"`
Name string `json:"name"`
}
func findAll(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
size, err := strconv.Atoi(request.Headers["Count"])
if err != nil {
return events.APIGatewayProxyResponse{
StatusCode: http.StatusBadRequest,
Body: "Count Header should be a number",
}, nil
}
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
db := dynamodb.New(sess)
params := &dynamodb.ScanInput{
// TableName: aws.String(os.Getenv("TABLE_NAME")),
TableName: aws.String(os.Getenv("TABLE_NAME")),
Limit: aws.Int64(int64(size)),
}
result, err := db.Scan(params)
if err != nil {
return events.APIGatewayProxyResponse{
StatusCode: http.StatusInternalServerError,
Body: "Error while scanning DynamoDB",
}, nil
}
var movies []Movie
dynamodbattribute.UnmarshalListOfMaps(result.Items, &movies)
response, err := json.Marshal(&movies)
if err != nil {
return events.APIGatewayProxyResponse{
StatusCode: http.StatusInternalServerError,
Body: "Error while decoding to string value",
}, nil
}
return events.APIGatewayProxyResponse{
StatusCode: http.StatusOK,
Headers: map[string]string{
"Content-Type": "application/json",
},
Body: string(response),
}, nil
}
func main() {
lambda.Start(findAll)
}
<file_sep>/go.mod
module codepipeline
go 1.15
| 5547eddef3e8f4fe34de5f4f1b1f9b9d7c6c8f14 | [
"Go Module",
"Go"
] | 2 | Go | heriyantoliu/codepipeline | 4086c3e3d409eb10eeaad2032c9921f068a0483b | ee031d342c73cac85ca2a6eaea6ec5e11716b5ad | |
refs/heads/master | <repo_name>Naincy47/DFS-1<file_sep>/floodfill.py
# Time Complexity : O(m*n)
# Space Complexity : O(m*n) Recusion stack
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : -
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
self.baseColor = image[sr][sc]
return self.helper(image, sr, sc, newColor)
def helper(self, image, sr, sc, newColor):
if sr < 0 or sr > len(image) -1 or sc < 0 or sc > len(image[0]) -1 or image[sr][sc] == newColor or image[sr][sc] != self.baseColor:
return image
if image[sr][sc] == self.baseColor:
image[sr][sc] = newColor
self.helper(image, sr+1, sc, newColor)
self.helper(image, sr-1, sc, newColor)
self.helper(image, sr, sc+1, newColor)
self.helper(image, sr, sc-1, newColor)
return image<file_sep>/updateMatrix.py
# Time Complexity : Brute Force: O(r.c)^2 | Optimized: O(r.c)
# Space Complexity :: Brute Force O(1) | Optimized: O(r.c)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : Thinking the optimized solution
class Solution:
def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
for i in range(len(matrix)):
for j in range(len(matrix[0])):
dist = float('inf')
if matrix[i][j] == 1:
for k in range(len(matrix)):
for l in range(len(matrix[0])):
if matrix[k][l] == 0:
dist = min(dist, (abs(i-k)) + abs(j-l))
matrix[i][j] = dist
return matrix
class Solution:
def updateMatrixTwo(self, matrix: List[List[int]]) -> List[List[int]]:
q = []
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == 0:
q.insert(0, (i,j))
else:
matrix[i][j] = float('inf')
directs = [(0,-1),(0,1),(-1,0),(1,0)]
while q:
curr = q.pop()
for direct in directs:
r = curr[0] + direct[0]
c = curr[1] + direct[1]
if r >= 0 and c >= 0 and r < len(matrix) and c < len(matrix[0]) and matrix[r][c] > matrix[curr[0]][curr[1]] + 1:
matrix[r][c] = matrix[curr[0]][curr[1]] + 1
q.insert(0,(r,c))
return matrix
| c222ed173f9315a1b061de883558c0e9e5ba515d | [
"Python"
] | 2 | Python | Naincy47/DFS-1 | 1aa6430a4c360d15a5a560ff761ff450a6164824 | 655291cf4c2cd73afa0bd53be4eb43a57e13721b | |
refs/heads/master | <file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Bean;
import DAO.PersonaDao;
import DAO.PersonaDaoImplement;
import Model.Persona;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;
/**
*
* @author User
*/
@ManagedBean
@ViewScoped
public class personaBean {
Persona persona;
List<Persona> personas;
/**
* Creates a new instance of personaBean
*/
public personaBean() {
persona = new Persona();
}
public void insertar(){
PersonaDao linkDAO= new PersonaDaoImplement();
linkDAO.insertarPersona(persona);
persona= new Persona();
}
public void modificar(){
PersonaDao linkDAO= new PersonaDaoImplement();
linkDAO.modificarPersona(persona);
persona= new Persona();
}
public void eliminar(){
PersonaDao linkDAO= new PersonaDaoImplement();
linkDAO.eliminarPersona(persona);
persona= new Persona();
}
public Persona getPersona() {
return persona;
}
public void setPersona(Persona persona) {
this.persona = persona;
}
public List<Persona> getPersonas() {
PersonaDao linkDAO= new PersonaDaoImplement();
personas=linkDAO.mostrarPersonas();
return personas;
}
public void setPersonas(List<Persona> personas) {
this.personas = personas;
}
}
| 25efdfc41d0c9c07963e8e7e169ba1f927ab9c7d | [
"Java"
] | 1 | Java | eloppezo/ssh---56a2725f0c1e66d76f00009b-jbosstest-demates.rhcloud.com---git-jbosstest.git- | ec4720cffa7d72d3caadb696befabc647d83e5fb | bbfe5580e8dac9aa2d9f49d9fe0f4fbfb8b03f06 | |
refs/heads/master | <repo_name>jleeisme/arrayOfLight<file_sep>/arrayOfLight.js
function arrayOfLight(x) {
var array = [];
for (var i = 0; i <= x; i++){
array.push(i);
}
return array;
}
console.log(arrayOfLight(5)); | 4841a23334678a62a0fee4c5fc9a846749456120 | [
"JavaScript"
] | 1 | JavaScript | jleeisme/arrayOfLight | 282ba24d2b65f592d636b659b85b0ecf011a934c | c91be81559b972557ddc35ba7fd8a31b5356fafb | |
refs/heads/master | <repo_name>OlaAcademy/microtao<file_sep>/src/main/java/com/xpown/mybatis/BaseMybatisDao.java
package com.xpown.mybatis;
import java.io.Serializable;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class BaseMybatisDao<E,PK extends Serializable> extends MybatisDao implements EntityDao<E,PK> {
private static Logger logger = LoggerFactory.getLogger(BaseMybatisDao.class);
@SuppressWarnings("unchecked")
public E getById(PK primaryKey) {
return (E)getSqlSession().selectOne(getFindByPrimaryKeyStatement(), primaryKey);
}
public void deleteById(PK id) {
getSqlSession().delete(getDeleteStatement(), id);
}
public void save(E entity) {
prepareObjectForSaveOrUpdate(entity);
getSqlSession().insert(getInsertStatement(), entity);
}
public int update(E entity) {
prepareObjectForSaveOrUpdate(entity);
int affectCount = getSqlSession().update(getUpdateStatement(), entity);
return affectCount;
}
/**
* 用于子类覆盖,在insert,update之前调用
* @param o
*/
protected void prepareObjectForSaveOrUpdate(E o) {
logger.info("prepareObjectForSaveOrUpdate...");
// System.out.println("kw...");
}
/*public String getMybatisMapperNamesapce() {
throw new RuntimeException("not yet implement");
}*/
public abstract String getMybatisMapperNamesapce();
public String getFindByPrimaryKeyStatement() {
return getMybatisMapperNamesapce()+".getById";
}
public String getInsertStatement() {
return getMybatisMapperNamesapce()+".insert";
}
public String getUpdateStatement() {
return getMybatisMapperNamesapce()+".updateById";
}
public String getDeleteStatement() {
return getMybatisMapperNamesapce()+".deleteById";
}
public String getFindStatement() {
return getMybatisMapperNamesapce()+".findAll";
}
public List<E> findAll() {
// throw new UnsupportedOperationException();
String statementName = getFindStatement();
return getSqlSession().selectList(statementName);
}
public boolean isUnique(E entity, String uniquePropertyNames) {
throw new UnsupportedOperationException();
}
public void flush() {
//ignore
}
}
<file_sep>/src/main/java/com/xpown/mybatis/MybatisDao.java
package com.xpown.mybatis;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.PropertyUtils;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.util.ReflectionUtils;
import com.xpown.utils.Page;
/**
* Mybatis分页查询工具类,为分页查询增加传递:
* startRow,endRow : 用于oracle分页使用,从1开始
* offset,limit : 用于mysql 分页使用,从0开始
*
*/
@SuppressWarnings("unchecked")
public class MybatisDao extends SqlSessionDaoSupport {
public <T> Page<T> selectPage(Page<T> page, String statementName, Object parameter) {
String countStatementName = statementName + "Count";
return selectPage(page, statementName, countStatementName, parameter);
}
public <T> Page<T> selectPage(Page<T> page, String statementName, String countStatementName, Object parameter) {
Number totalItems = (Number) getSqlSession().selectOne(countStatementName, parameter);
//Number totalItems = 10;
if (totalItems != null && totalItems.longValue() > 0) {
List list = getSqlSession().selectList(statementName, toParameterMap(parameter, page));
page.setResult(list);
page.setTotalCount(totalItems.intValue());
}
return page;
}
protected static Map toParameterMap(Object parameter, Page p) {
Map map = toParameterMap(parameter);
//map.put("startRow", p.getStartRow());
//map.put("startRow", p.getOffset());
//map.put("endRow", p.getEndRow());
map.put("offset", p.getOffset());
map.put("limit", p.getPageSize());
return map;
}
protected static Map toParameterMap(Object parameter) {
if (parameter instanceof Map) {
return (Map) parameter;
} else {
try {
return PropertyUtils.describe(parameter);
} catch (Exception e) {
ReflectionUtils.handleReflectionException(e);
return null;
}
}
}
}<file_sep>/target/m2e-wtp/web-resources/META-INF/maven/com.xpown.microtao/microtao/pom.xml
<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>com.xpown.microtao</groupId>
<artifactId>microtao</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>microtao</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>3.2.0.RELEASE</spring.version>
<json.version>1.9.13</json.version>
<slf4jVersion>1.6.1</slf4jVersion>
</properties>
<dependencies>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>1.8.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.23</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-lgpl</artifactId>
<version>${json.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>${json.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>${json.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-lgpl</artifactId>
<version>${json.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4jVersion}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4jVersion}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.3</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.3</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency>
<!-- optional datasource pool -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.5.5</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.3</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.2</version>
</dependency>
<dependency>
<groupId>com.ning</groupId>
<artifactId>async-http-client</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.3</version>
</dependency>
<!-- 手机短信 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>
<!-- spring定时器 -->
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>jdom</groupId>
<artifactId>jdom</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
</project><file_sep>/src/main/java/com/xpown/utils/Page.java
package com.xpown.utils;
import java.util.ArrayList;
import java.util.List;
/**
* 与具体ORM实现无关的分页参数及查询结果封装.
*
* 注意所有序号从1开始.
*
* @param <T> Page中记录的类型.
*
*
*/
public class Page<T> {
//-- 公共变量 --//
public static final String ASC = "asc";
public static final String DESC = "desc";
//-- 分页参数 --//
protected int pageNo = 1;
protected int pageSize = -1;
//protected String orderBy = null;
//protected String order = null;
//protected boolean autoCount = true;
private int pageCount; //总页数
private int offset = 0; // 起始条数
//-- 返回结果 --//
protected List<T> result = new ArrayList<T>();
protected int totalCount = 0;
//-- 构造函数 --//
/**
private Page() {
}
*/
/**
*
public Page<T> end() {
// 1, 总页码
pageCount = ((int)this.totalCount + pageSize - 1) / pageSize;
// 2, startPageIndex(显示的页码列表的开始索引)与endPageIndex(显示的页码列表的结束索引)
// a, 总页码不大于10页
if (pageCount <= 10) {
startPageIndex = 1;
endPageIndex = pageCount;
}
// b, 总码大于10页
else {
// 在中间,显示前面4个,后面5个
startPageIndex = pageNo - 4;
endPageIndex = pageNo + 5;
// 前面不足4个时,显示前10个页码
if (startPageIndex < 1) {
startPageIndex = 1;
endPageIndex = 10;
}
// 后面不足5个时,显示后10个页码
else if (endPageIndex > pageCount) {
endPageIndex = pageCount;
startPageIndex = pageCount - 10 + 1;
}
}
return this;
}
**/
/*
public Page(int pageSize) {
this.pageSize = pageSize;
}
*/
public Page(int pageNo,int pageSize){
this.pageNo = pageNo;
this.pageSize = pageSize;
this.offset = (pageNo-1) * pageSize;
}
public Page(int pageNo,int pageSize,int totalCount){
this.pageNo = pageNo;
this.pageSize = pageSize;
this.offset = (pageNo-1) * pageSize;
this.totalCount = totalCount;
}
//-- 分页参数访问函数 --//
/**
* 获得当前页的页号,序号从1开始,默认为1.
*/
public int getPageNo() {
return pageNo;
}
/**
* 设置当前页的页号,序号从1开始,低于1时自动调整为1.
*/
public void setPageNo(final int pageNo) {
this.pageNo = pageNo;
if (pageNo < 1) {
this.pageNo = 1;
}
}
/**
* 返回Page对象自身的setPageNo函数,可用于连续设置。
*/
public Page<T> pageNo(final int thePageNo) {
setPageNo(thePageNo);
return this;
}
/**
* 获得每页的记录数量, 默认为-1.
*/
public int getPageSize() {
return pageSize;
}
/**
* 设置每页的记录数量.
*/
public void setPageSize(final int pageSize) {
this.pageSize = pageSize;
}
/**
* 返回Page对象自身的setPageSize函数,可用于连续设置。
*/
public Page<T> pageSize(final int thePageSize) {
setPageSize(thePageSize);
return this;
}
/**
* 根据pageNo和pageSize计算当前页第一条记录在总结果集中的位置,序号从1开始.
*/
public int getFirst() {
return ((pageNo - 1) * pageSize) + 1;
}
//-- 访问查询结果函数 --//
/**
* 获得页内的记录列表.
*/
public List<T> getResult() {
return result;
}
/**
* 设置页内的记录列表.
*/
public void setResult(final List<T> result) {
this.result = result;
}
/**
* 获得总记录数, 默认值为-1.
*/
public long getTotalCount() {
return totalCount;
}
/**
* 设置总记录数.
*/
public void setTotalCount(final int totalCount) {
this.totalCount = totalCount;
this.pageCount = getTotalPages();
}
/**
* 根据pageSize与totalCount计算总页数, 默认值为-1.
*/
public int getTotalPages() {
if (totalCount < 0) {
return -1;
}
int count = totalCount / pageSize;
if (totalCount % pageSize > 0) {
count++;
}
return count;
}
/**
* 是否还有下一页.
*/
public boolean isHasNext() {
return (pageNo + 1 <= getTotalPages());
}
/**
* 取得下页的页号, 序号从1开始.
* 当前页为尾页时仍返回尾页序号.
*/
public int getNextPage() {
if (isHasNext()) {
return pageNo + 1;
} else {
return pageNo;
}
}
/**
* 是否还有上一页.
*/
public boolean isHasPre() {
return (pageNo - 1 >= 1);
}
/**
* 取得上页的页号, 序号从1开始.
* 当前页为首页时返回首页序号.
*/
public int getPrePage() {
if (isHasPre()) {
return pageNo - 1;
} else {
return pageNo;
}
}
/**
* 根据pageNo和pageSize计算当前页第一条记录在总结果集中的位置,序号从0开始.
* 用于Mysql,Hibernate.
*/
public int getOffset() {
return ((pageNo - 1) * pageSize);
//return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
/**
* 根据pageNo和pageSize计算当前页第一条记录在总结果集中的位置,序号从1开始.
* 用于Oracle.
*/
public int getStartRow() {
return getOffset() + 1;
}
/**
* 根据pageNo和pageSize计算当前页最后一条记录在总结果集中的位置, 序号从1开始.
* 用于Oracle.
*/
public int getEndRow() {
return pageSize * pageNo;
}
public int getPageCount() {
//return pageCount;
pageCount = ((int)this.totalCount + pageSize - 1) / pageSize;
return pageCount;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
public int getOffsetFromPageNo(){
return ((pageNo - 1) * pageSize);
}
public int getPageNoFromOffset(){
return offset/pageSize + 1;
}
}
<file_sep>/src/main/java/com/xpown/utils/MapResult.java
package com.xpown.utils;
import java.util.HashMap;
import java.util.Map;
public class MapResult {
public static Map<String, Object> initMap() {
Map<String,Object> map = new HashMap<String, Object>();
map.put("apicode", 10000);
map.put("message", "成功");
return map;
}
public static Map<String, Object> initMap(Integer apicode, String message) {
Map<String,Object> map = new HashMap<String, Object>();
map.put("apicode", apicode);
map.put("message", message);
return map;
}
public static Map<String, Object> failMap() {
Map<String,Object> map = new HashMap<String, Object>();
map.put("apicode", 9999);
map.put("message", "系统错误,请重试");
return map;
}
}
<file_sep>/src/main/java/com/xpown/controller/GoodsController.java
package com.xpown.controller;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.Map;
import javax.annotation.Resource;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xpown.model.Goods;
import com.xpown.service.GoodsService;
import com.xpown.utils.MapResult;
@Controller
@RequestMapping("/goods")
public class GoodsController {
private static Logger logger = LoggerFactory
.getLogger(GoodsController.class);
@Resource
private GoodsService goodsService;
@RequestMapping(value = "getGoodsList", produces = "plain/text;charset=UTF-8")
@ResponseBody
public Map<String, Object> getGoodsList(
@RequestParam(required = true) String appkey,
@RequestParam(required = false) String category,
@RequestParam(required = false) String goodsId,
@RequestParam(defaultValue = "20") int pageSize) {
try {
Map<String, Object> ret = MapResult.initMap();
ret.put("result", goodsService.getGoodsList(appkey,category,goodsId, pageSize));
return ret;
} catch (Exception e) {
logger.error("", e);
return MapResult.failMap();
}
}
/**
* 定时器
*/
@RequestMapping(value = "insertData")
@ResponseBody
public void insertData() {
importGoodsFromTao("5nkulide4r");
importGoodsFromTao("021hjz3v3k");
}
/**
* 从大淘客后台导入数据
* @param appkey
* @return
*/
public void importGoodsFromTao(String appkey) {
try {
String result = getTaoData("http://api.dataoke.com/index.php",
appkey);
JSONObject jsonObj = new JSONObject(result);
JSONObject data = jsonObj.getJSONObject("data");
JSONArray goodsArray = data.getJSONArray("result");
for (int i=0; i<goodsArray.length();i++) {
JSONObject goodsObj = goodsArray.getJSONObject(i);
Goods goods = new Goods();
goods.setGoodsId(goodsObj.getString("GoodsID"));
goods.setTitle(goodsObj.getString("Title"));
goods.setPic(goodsObj.getString("Pic"));
goods.setIntroduce(goodsObj.getString("Introduce"));
goods.setPrice(goodsObj.getString("Org_Price"));
goods.setCategory(goodsObj.getInt("Cid"));
goods.setLink(goodsObj.getString("ali_click"));
goods.setAppkey(appkey);
goods.setCreateTime(new Date());
goodsService.addGoods(goods);
}
} catch (Exception e) {
logger.error("", e);
}
}
/**
* 使用get方式登陆
*
* @param username
* @param password
* @return
*/
public static String getTaoData(String url, String param) {
HttpURLConnection conn = null;
String data = "r=goodsLink/www&type=www_quan&appkey=" + param + "&v=2";
url = url + "?" + data;
try {
URL mURL = new URL(url);
conn = (HttpURLConnection) mURL.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
conn.setConnectTimeout(10000);
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
InputStream is = conn.getInputStream();
String result = getStringFromInputStream(is);
return result;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
return null;
}
/**
* 根据流返回一个字符串信息 *
*
* @param is
* @return
* @throws IOException
*/
private static String getStringFromInputStream(InputStream is)
throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
// 一定要写len=is.read(buffer)
// 如果while((is.read(buffer))!=-1)则无法将数据写入buffer中
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
is.close();
// 把流中的数据转换成字符串,采用的编码是utf-8(模拟器默认编码)
String state = os.toString();
os.close();
return state;
}
}
<file_sep>/src/main/java/com/xpown/model/User.java
package com.xpown.model;
import java.util.Date;
public class User {
private int id;
private String name;
private String account;//淘宝账号
private int unionId; // 微信unionId
private Date createTime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public int getUnionId() {
return unionId;
}
public void setUnionId(int unionId) {
this.unionId = unionId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
<file_sep>/src/main/java/com/xpown/service/UserService.java
package com.xpown.service;
import com.xpown.baseservice.BaseServiceMybatis;
import com.xpown.model.User;
public interface UserService extends BaseServiceMybatis<User, String>{
}
<file_sep>/src/main/resources/log4j.properties
log4j.rootCategory=INFO,stdout,conout,A,C
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Encoding=UTF-8
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{MM-dd HH:mm:ss} %p %l - %m%n
log4j.appender.conout=org.apache.log4j.DailyRollingFileAppender
log4j.appender.conout.Encoding=UTF-8
log4j.appender.conout.file=logs/info.log
log4j.appender.conout.DatePattern='.'yyyyMMdd
log4j.appender.conout.Threshold=INFO
log4j.appender.conout.layout=org.apache.log4j.PatternLayout
log4j.appender.conout.layout.ConversionPattern=%d{MM-dd HH:mm:ss} %p %l - %m%n
log4j.appender.A=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A.Encoding=UTF-8
log4j.appender.A.file=logs/error.log
log4j.appender.A.DatePattern='.'yyyyMMdd
log4j.appender.A.Threshold=error
log4j.appender.A.layout=org.apache.log4j.PatternLayout
log4j.appender.A.layout.ConversionPattern=%d{MM-dd HH:mm:ss} %p %l - %m%n
log4j.appender.C=org.apache.log4j.DailyRollingFileAppender
log4j.appender.C.Encoding=UTF-8
log4j.appender.C.file=logs/debug.log
log4j.appender.C.DatePattern='.'yyyyMMdd
log4j.appender.C.Threshold=debug
log4j.appender.C.layout=org.apache.log4j.PatternLayout
log4j.appender.C.layout.ConversionPattern=%d{MM-dd HH:mm:ss} %p %l - %m%n
log4j.logger.com.xpown=error<file_sep>/src/main/java/com/xpown/utils/ConfigUtil.java
package com.xpown.utils;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
public class ConfigUtil {
private static PropertiesConfiguration config = null;
static {
try {
config = new PropertiesConfiguration();
config.setEncoding("UTF-8");
config.load("app.properties");
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static int getIntValue(final String key) {
int reInt = 0;
try {
reInt = config.getInt(key);
} catch (Exception ex) {
ex.fillInStackTrace();
}
return reInt;
}
public static long getLongValue(final String key) {
long reLong = 0;
try {
reLong = config.getLong(key);
} catch (Exception ex) {
ex.fillInStackTrace();
}
return reLong;
}
public static double getDoubleValue(final String key) {
double reDouble = 0;
try {
reDouble = config.getDouble(key);
} catch (Exception ex) {
ex.fillInStackTrace();
}
return reDouble;
}
public static String getStringValue(String key) {
String str = "";
try {
str = config.getString(key);
} catch (Exception ex) {
ex.fillInStackTrace();
}
return str;
}
public static boolean getBooleanValue(String key) {
boolean flag = false;
try {
flag = config.getBoolean(key);
} catch (Exception ex) {
ex.fillInStackTrace();
}
return flag;
}
public static void save(String key, Object o) {
config.setProperty(key, o);
try {
config.save("app.properties");
config = new PropertiesConfiguration();
config.setEncoding("UTF-8");
config.load("app.properties");
} catch (ConfigurationException e) {
e.printStackTrace();
}
}
}
<file_sep>/src/main/java/com/xpown/utils/AppListener.java
package com.xpown.utils;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class AppListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
ServletContext sc = sce.getServletContext();
sc.setAttribute("wxappid", ConfigUtil.getStringValue("wxappid"));
sc.setAttribute("domain", ConfigUtil.getStringValue("domain"));
}
public void contextDestroyed(ServletContextEvent sce) {
}
}
<file_sep>/src/main/java/com/xpown/model/Goods.java
package com.xpown.model;
import java.util.Date;
public class Goods {
private int id;
private String goodsId;
private String title;
private String introduce;
private String pic;
private String price;
private int category;
private String link; //淘宝购物链接
private String quanlink;
private String appkey;
private Date createTime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGoodsId() {
return goodsId;
}
public void setGoodsId(String goodsId) {
this.goodsId = goodsId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIntroduce() {
return introduce;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public void setIntroduce(String introduce) {
this.introduce = introduce;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public int getCategory() {
return category;
}
public void setCategory(int category) {
this.category = category;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getQuanlink() {
return quanlink;
}
public void setQuanlink(String quanlink) {
this.quanlink = quanlink;
}
public String getAppkey() {
return appkey;
}
public void setAppkey(String appkey) {
this.appkey = appkey;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
<file_sep>/src/main/java/com/xpown/dao/GoodsDao.java
package com.xpown.dao;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.xpown.model.Goods;
import com.xpown.mybatis.BaseMybatisDao;
@Repository
public class GoodsDao<E> extends BaseMybatisDao<Goods, String> {
public String getMybatisMapperNamesapce() {
return "com.xpown.model.GoodsMapper";
}
public List<Goods> getGoodsList(Map<String, Object> param) {
return this.getSqlSession().selectList(this.getMybatisMapperNamesapce() + ".getGoodsList", param);
}
}<file_sep>/src/main/java/com/xpown/serviceImpl/UserServiceImpl.java
package com.xpown.serviceImpl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.xpown.baseservice.BaseServiceMybatisImpl;
import com.xpown.dao.UserDao;
import com.xpown.model.User;
import com.xpown.mybatis.EntityDao;
import com.xpown.service.UserService;
@Service
@Transactional
public class UserServiceImpl extends BaseServiceMybatisImpl<User, String>
implements UserService {
@Resource
private UserDao<?> userDao;
@Override
protected EntityDao<User, Integer> getEntityDao() {
return userDao;
}
}
<file_sep>/src/main/java/com/xpown/service/GoodsService.java
package com.xpown.service;
import java.util.List;
import com.xpown.baseservice.BaseServiceMybatis;
import com.xpown.model.Goods;
public interface GoodsService extends BaseServiceMybatis<Goods, String> {
List<Goods> getGoodsList(String keyword, String goodsId, String category, int pageSize);
void addGoods(Goods goods);
}
<file_sep>/src/main/java/com/xpown/dao/UserDao.java
package com.xpown.dao;
import org.springframework.stereotype.Repository;
import com.xpown.model.User;
import com.xpown.mybatis.BaseMybatisDao;
@Repository("userDao")
public class UserDao<E> extends BaseMybatisDao<User, Integer> {
@Override
public String getMybatisMapperNamesapce() {
return "com.xpown.model.UserMapper";
}
}
| 5f378d732518417ca40f8d3bdfcd2181fc966a7f | [
"Java",
"Maven POM",
"INI"
] | 16 | Java | OlaAcademy/microtao | 762dd8a3dfa8fb2f8bdabb178634f5c3bda022a7 | 9433e802e5661829102c0355f85450277e5513ce | |
refs/heads/master | <repo_name>jinyanroot/cicd-demo<file_sep>/slave-java/change_sshd.sh
#!/bin/bash
echo root:root@123 | chpasswd
sed -i "s/^PermitRootLogin.*/PermitRootLogin yes/" /etc/ssh/sshd_config && /etc/init.d/ssh restart
<file_sep>/cicd-linux.sh
#!/bin/bash
# Start Jenkins Slave
docker run -d \
--name slave-java \
--privileged=true \
--restart=always \
-v /var/run/docker.sock:/var/run/docker.sock \
registry.aliyuncs.com/acs-sample/jenkins-slave-dind-java
if [[ $? -ne 0 ]];then echo 'Start Slave Faild'; exit 1; fi
sleep 3
# Permit root login slave-java
chmod 755 `pwd`/slave-java/change_sshd.sh
docker cp `pwd`/slave-java/change_sshd.sh slave-java:/root
docker exec slave-java "/root/change_sshd.sh"
# Copy jenkins files
rm -rf /var/jenkins_home && cp -r jenkins_home/ /var/
# Start Jenkins
docker run -d -u root \
--name jenkins \
--privileged=true \
--restart=always \
--link=slave-java \
-p 8081:8080 \
-p 50000:50000 \
-v /var/run/docker.sock:/var/run/docker.sock \
-v $(which docker):/bin/docker \
-v /var/jenkins_home:/var/jenkins_home \
registry.aliyuncs.com/acs-sample/jenkins:2.19.2
<file_sep>/README.md
# 介绍
##### 这是一个持续集成和持续发布的Demo,它可以在Windows、Linux环境使用。
```Bash
localdev-windows.bat:本地开发环境,它会编译代码,打包并使用docker启动
cicd-linux.sh:CICD环境,它会部署Jenkins,并内置了一个pipeline Job
```
# 1.本地开发环境
## 1.1 要求
##### a.Windows 10,理论上能兼容其它Windows版本。
##### b.安装Docker。
##### c.安装Winrar。
##### d.安装Maven。
##### e.默认使用E:\demo\company-news作为代码路径,可修改。
## 1.2 使用方法
##### 修改完代码后,双击直接运行windows-use(localdev).bat即可。
##### 如没有报错,会自动打开网址:http://127.0.0.1:8080/company-news/
# 2.CICD环境
## 2.1 要求
##### a. 运行机器为Centos 7,其它Linux发行版本和Windows版本暂未测试,理论上都是可以运行的。
##### b. 安装Docker 17.06.2-ce
##### c. 配置Docker的启动命令:将/usr/lib/systemd/system/docker.service中的ExecStart行改为如下:
```Bash
ExecStart=/usr/bin/dockerd -H tcp://HOST_IP:2375 -H unix:///var/run/docker.sock
```
##### d. 配置Docker的阿里云的加速器:
```Bash
# cat /etc/docker/daemon.json
{
"registry-mirrors": ["https://tgw7pqgq.mirror.aliyuncs.com"]
}
```
## 2.2 准备
##### a. 在机器上执行prepare.sh
##### b. 等待30秒后,在浏览器中访问http://HOST_IP:8081
##### c. 依次点击Jenkins的系统管理-管理节点-新建节点,相关配置如下:
```Bash
Name:slave-java
# of executors:2
远程工作目录:/home/jenkins
标签:slave-java
用法:尽可能的使用这个节点
启动方法:Launch slave agents via SSH
Host:slave-java
Credentials:帐号root,密码<PASSWORD>(即slave-java/change_sshd.sh中设置的)
```
## 2.3 使用
##### a. 开发人员在本地提交代码。示例Demo:https://github.com/jinyanroot/company-news.git
##### b. 根据实际环境,修改相关配置:
```Bash
ansible/host:配置HOST_IP
slave/change_sshd.sh:配置服务器密码
Jenkinsfile:
line 3:配置代码路径
line 28/29/30:配置各环境的IP
```
##### c. 在Jenkins中执行job:company-news-cd,选择需要发布的环境
# 3.待改进
因时间关系,还有不少可以改进的地方,如下:
1. 动态的生成Jenkins slave,用完即销毁。
2. 定制Docker的Jenkins image和Jenkins slave image,以减少脚本优化或避免手动设置。
3. 启动sonar server,让stage 'test'可以做代码静态质量检查等。
4. 完善deploy阶段的test和prod。
5. deploy staging阶段使用jenkins pipeline ansible plugin,以替换shell。
6. 对deploy至test、staging、prod做准入。
7. 完善安全相关配置,例如非root启动程序、不明文存放密码等。
# 4. 特别说明
## 4.1高可用
##### a.如果是公用云,相对简单,可以用云服务提供商的SLB+Nginx机器+应用集群,如有更高要求,可以建不同可用区,甚至用不同区域;
##### b.如果是私用云,需要考虑防火墙、交换机、服务器、存储等所有硬件的高可用,甚至还需要考虑多机房;
## 4.2监控报警
中小规模,可以用Zabbix+插件+脚本,基本能满足对OS、应用、业务的监控和报警
## 4.3日志
可以使用filebeat+logstash+kafka+es+kibana来收集、存储、查询日志
| 54768eea0b9f9f73ece708eed913bf2f3cded7c9 | [
"Markdown",
"Shell"
] | 3 | Shell | jinyanroot/cicd-demo | 43e4a06afda7a6393206e2fd8044bee429a73cb8 | be5ca466b350daac228f3f112c6d36d3ae42ba04 | |
refs/heads/master | <repo_name>dance2die/Book.AspNet.WebApi2.Chapter08<file_sep>/WebApi2Book.Data/QueryProcessors/ITaskByIdQueryProcessor.cs
using WebApi2Book.Data.Entities;
namespace WebApi2Book.Data.QueryProcessors
{
public interface ITaskByIdQueryProcessor
{
Task GetTask(long taskId);
}
}<file_sep>/WebApi2Book.Web.Api/LinkServices/ITaskLinkService.cs
using WebApi2Book.Web.Api.Models;
namespace WebApi2Book.Web.Api.LinkServices
{
public interface ITaskLinkService
{
Link GetAllTasksLink();
void AddSelfLink(Task task);
void AddLinksToChildObjects(Task task);
}
}<file_sep>/WebApi2Book.Web.Api/App_Start/NinjectConfigurator.cs
// NinjectConfigurator.cs
// Copyright <NAME>, <NAME> 2014.
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using log4net.Config;
using NHibernate;
using NHibernate.Context;
using Ninject;
using Ninject.Activation;
using Ninject.Web.Common;
using WebApi2Book.Common;
using WebApi2Book.Common.Logging;
using WebApi2Book.Common.Security;
using WebApi2Book.Common.TypeMapping;
using WebApi2Book.Data.QueryProcessors;
using WebApi2Book.Data.SqlServer.Mapping;
using WebApi2Book.Data.SqlServer.QueryProcessors;
using WebApi2Book.Web.Api.AutoMappingConfiguration;
using WebApi2Book.Web.Api.MaintenanceProcessing;
using WebApi2Book.Web.Api.Security;
using WebApi2Book.Web.Common;
using WebApi2Book.Web.Common.Security;
using WebApi2Book.Web.Api.InquiryProcessing;
using WebApi2Book.Web.Api.LinkServices;
namespace WebApi2Book.Web.Api
{
public class NinjectConfigurator
{
public void Configure(IKernel container)
{
AddBindings(container);
}
private void AddBindings(IKernel container)
{
ConfigureLog4net(container);
ConfigureUserSession(container);
ConfigureNHibernate(container);
ConfigureAutoMapper(container);
container.Bind<IDateTime>().To<DateTimeAdapter>().InSingletonScope();
container.Bind<IAddTaskQueryProcessor>().To<AddTaskQueryProcessor>().InRequestScope();
container.Bind<IAddTaskMaintenanceProcessor>().To<AddTaskMaintenanceProcessor>().InRequestScope();
container.Bind<IBasicSecurityService>().To<BasicSecurityService>().InSingletonScope();
container.Bind<ITaskByIdQueryProcessor>().To<TaskByIdQueryProcessor>().InRequestScope();
container.Bind<IUpdateTaskStatusQueryProcessor>().To<UpdateTaskStatusQueryProcessor>().InRequestScope();
container.Bind<IStartTaskWorkflowProcessor>().To<StartTaskWorkflowProcessor>().InRequestScope();
container.Bind<ICompleteTaskWorkflowProcessor>().To<CompleteTaskWorkflowProcessor>().InRequestScope();
container.Bind<IReactivateTaskWorkflowProcessor>().To<ReactivateTaskWorkflowProcessor>().InRequestScope();
container.Bind<ITaskByIdInquiryProcessor>().To<TaskByIdInquiryProcessor>().InRequestScope();
container.Bind<IUpdateTaskQueryProcessor>().To<UpdateTaskQueryProcessor>().InRequestScope();
container.Bind<ITaskUsersMaintenanceProcessor>().To<TaskUsersMaintenanceProcessor>().InRequestScope();
container.Bind<IUpdateablePropertyDetector>().To<JObjectUpdateablePropertyDetector>().InSingletonScope();
container.Bind<IUpdateTaskMaintenanceProcessor>().To<UpdateTaskMaintenanceProcessor>().InRequestScope();
container.Bind<IPagedDataRequestFactory>().To<PagedDataRequestFactory>().InSingletonScope();
container.Bind<IAllTasksQueryProcessor>().To<AllTasksQueryProcessor>().InRequestScope();
container.Bind<IAllTasksInquiryProcessor>().To<AllTasksInquiryProcessor>().InRequestScope();
container.Bind<ICommonLinkService>().To<CommonLinkService>().InRequestScope();
container.Bind<IUserLinkService>().To<UserLinkService>().InRequestScope();
container.Bind<ITaskLinkService>().To<TaskLinkService>().InRequestScope();
}
private void ConfigureLog4net(IKernel container)
{
XmlConfigurator.Configure();
var logManager = new LogManagerAdapter();
container.Bind<ILogManager>().ToConstant(logManager);
}
private void ConfigureNHibernate(IKernel container)
{
var sessionFactory = Fluently.Configure()
.Database(
MsSqlConfiguration.MsSql2008.ConnectionString(
c => c.FromConnectionStringWithKey("WebApi2BookDb")))
.CurrentSessionContext("web")
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<TaskMap>())
.BuildSessionFactory();
container.Bind<ISessionFactory>().ToConstant(sessionFactory);
container.Bind<ISession>().ToMethod(CreateSession).InRequestScope();
container.Bind<IActionTransactionHelper>().To<ActionTransactionHelper>().InRequestScope();
}
private ISession CreateSession(IContext context)
{
var sessionFactory = context.Kernel.Get<ISessionFactory>();
if (!CurrentSessionContext.HasBind(sessionFactory))
{
var session = sessionFactory.OpenSession();
CurrentSessionContext.Bind(session);
}
return sessionFactory.GetCurrentSession();
}
private void ConfigureUserSession(IKernel container)
{
var userSession = new UserSession();
container.Bind<IUserSession>().ToConstant(userSession).InSingletonScope();
container.Bind<IWebUserSession>().ToConstant(userSession).InSingletonScope();
}
private void ConfigureAutoMapper(IKernel container)
{
container.Bind<IAutoMapper>().To<AutoMapperAdapter>().InSingletonScope();
container.Bind<IAutoMapperTypeConfigurator>()
.To<StatusEntityToStatusAutoMapperTypeConfigurator>()
.InSingletonScope();
container.Bind<IAutoMapperTypeConfigurator>()
.To<StatusToStatusEntityAutoMapperTypeConfigurator>()
.InSingletonScope();
container.Bind<IAutoMapperTypeConfigurator>()
.To<UserEntityToUserAutoMapperTypeConfigurator>()
.InSingletonScope();
container.Bind<IAutoMapperTypeConfigurator>()
.To<UserToUserEntityAutoMapperTypeConfigurator>()
.InSingletonScope();
container.Bind<IAutoMapperTypeConfigurator>()
.To<NewTaskToTaskEntityAutoMapperTypeConfigurator>()
.InSingletonScope();
container.Bind<IAutoMapperTypeConfigurator>()
.To<TaskEntityToTaskAutoMapperTypeConfigurator>()
.InSingletonScope();
}
}
}<file_sep>/WebApi2Book.Data/QueryProcessors/IAddTaskQueryProcessor.cs
using WebApi2Book.Data.Entities;
namespace WebApi2Book.Data.QueryProcessors
{
public interface IAddTaskQueryProcessor
{
void AddTask(Task task);
}
}<file_sep>/WebApi2Book.Web.Api/MaintenanceProcessing/IAddTaskMaintenanceProcessor.cs
using WebApi2Book.Web.Api.Models;
namespace WebApi2Book.Web.Api.MaintenanceProcessing
{
public interface IAddTaskMaintenanceProcessor
{
Task AddTask(NewTask newTask);
}
}<file_sep>/WebApi2Book.Web.Api/LinkServices/IUserLinkService.cs
using WebApi2Book.Web.Api.Models;
namespace WebApi2Book.Web.Api.LinkServices
{
public interface IUserLinkService
{
void AddSelfLink(User user);
}
}<file_sep>/WebApi2Book.Data/QueryProcessors/IAllTasksQueryProcessor.cs
using WebApi2Book.Data.Entities;
namespace WebApi2Book.Data.QueryProcessors
{
public interface IAllTasksQueryProcessor
{
QueryResult<Task> GetTasks(PagedDataRequest requestInfo);
}
}<file_sep>/WebApi2Book.Web.Api/InquiryProcessing/IAllTasksInquiryProcessor.cs
using WebApi2Book.Data;
using WebApi2Book.Web.Api.Models;
namespace WebApi2Book.Web.Api.InquiryProcessing
{
public interface IAllTasksInquiryProcessor
{
PagedDataInquiryResponse<Task> GetTasks(PagedDataRequest requestInfo);
}
}<file_sep>/WebApi2Book.Web.Api/MaintenanceProcessing/ICompleteTaskWorkflowProcessor.cs
using WebApi2Book.Web.Api.Models;
namespace WebApi2Book.Web.Api.MaintenanceProcessing
{
public interface ICompleteTaskWorkflowProcessor
{
Task CompleteTask(long taskId);
}
}<file_sep>/WebApi2Book.Web.Api/LinkServices/TaskLinkService.cs
using System.Net.Http;
using WebApi2Book.Common;
using WebApi2Book.Web.Api.Models;
namespace WebApi2Book.Web.Api.LinkServices
{
public class TaskLinkService : ITaskLinkService
{
private readonly ICommonLinkService _commonLinkService;
private readonly IUserLinkService _userLinkService;
public TaskLinkService(ICommonLinkService commonLinkService,
IUserLinkService userLinkService)
{
_commonLinkService = commonLinkService;
_userLinkService = userLinkService;
}
public void AddLinksToChildObjects(Task task)
{
task.Assignees.ForEach(x => _userLinkService.AddSelfLink(x));
}
public virtual void AddSelfLink(Task task)
{
task.AddLink(GetSelfLink(task.TaskId.Value));
}
public virtual Link GetAllTasksLink()
{
const string pathFragment = "tasks";
return _commonLinkService.GetLink(pathFragment, Constants.CommonLinkRelValues.All,
HttpMethod.Get);
}
public virtual Link GetSelfLink(long taskId)
{
var pathFragment = string.Format("tasks/{0}", taskId);
var link = _commonLinkService.GetLink(pathFragment, Constants.CommonLinkRelValues.Self,
HttpMethod.Get);
return link;
}
}
}<file_sep>/WebApi2Book.Common/Logging/ILogManager.cs
using System;
using log4net;
namespace WebApi2Book.Common.Logging
{
public interface ILogManager
{
ILog GetLog(Type typeAssociatedWithRequestedLog);
}
}<file_sep>/WebApi2Book.Web.Common/IUpdateablePropertyDetector.cs
using System.Collections.Generic;
namespace WebApi2Book.Web.Common
{
public interface IUpdateablePropertyDetector
{
IEnumerable<string> GetNamesOfPropertiesToUpdate<TTargetType>(
object objectContainingUpdatedData);
}
} | 74841baa82b582b0a0a2e7f21f8b33bd3bfc6eec | [
"C#"
] | 12 | C# | dance2die/Book.AspNet.WebApi2.Chapter08 | c3d6cf23f0ae402e13da50e102d366793f7b93d1 | e44e354d790362616950a5ff01f180f75d01c5c7 | |
refs/heads/master | <repo_name>Limych/Rates<file_sep>/server/Loader/MoexLoader.php
<?php
namespace Loader;
use Model;
class MoexLoader extends BaseLoader {
public function load(){
$hash = sha1(date('r'));
$timestamp = time();
$url = "http://www.moex.com/iss/engines/currency/markets/selt/securities.json?iss.meta=off&iss.only=securities%2Cmarketdata&securities=CETS%3AUSD000UTSTOM%2CCETS%3AEUR_RUB__TOM%2CCETS%3AEURUSD000TOM%2CCETS%3ACNYRUB_TOM%2CCETS%3AKZT000000TOM%2CCETS%3AUAH000000TOM%2CCETS%3ABYRRUB_TOM%2CCETS%3AHKDRUB_TOM%2CCETS%3AGBPRUB_TOM&lang=ru&_=$timestamp";
$result = self::wget($url);
// if(DEBUG) var_export($result);
$rates = array();
if( $result['errno'] != 0 ){
// error: bad url, timeout, redirect loop…
}elseif( $result['http_code'] != 200 ){
// error: no page, no permissions, no service…
}else{
$json = preg_replace(array(
'/^[^{]+/',
'/[^}]+$/',
), array(
'',
'',
), $result['content']);
$json = json_decode($json, true);
$ids = $values = array();
foreach($json['securities']['data'] as $val){
if( substr($val[2], -4) == '_TOM' ){
$ids[$val[0]] = $val[2];
$values[$val[0]] = $val[6];
}
}
foreach($json['marketdata']['data'] as $val){
if( isset($ids[$val[20]]) && isset($val[7]) && isset($val[8]) ){
$rates[] = new Model\StockItem(array(
'source' => 'MOEX',
'code' => substr($ids[$val[20]], 0, 3),
'faceValue' => $values[$val[20]],
'currency' => substr($ids[$val[20]], 3, 3),
'open' => $val[7],
'last' => $val[8],
'high' => $val[5],
'low' => $val[6],
'timestamp' => self::makeTimestamp($val[39]),
));
}
}
// if(DEBUG) var_export($rates);
}
return $rates;
}
}
<file_sep>/server/currence_codes.ini
[Currence Codes]
AED="Дирхам ОАЭ"
AFN="Афгани"
ALL="Албанский лек"
AMD="Армянский драм"
ANG="Антильский гульден"
ARS="Аргентинское песо"
AUD="Австралийский доллар"
AZN="Азербайджанский манат"
BAM="Конвертируемая марка"
BBD="Барбадосский доллар"
BDT="Бангладешская така"
BGN="Болгарский лев"
BHD="Бахрейнский динар"
BIF="Бурундийский франк"
BND="Брунейский доллар"
BOB="Боливиано"
BRL="Бразильский реал"
BSD="Багамский доллар"
BTC="Биткойн"
BWP="Ботсванская пула"
BYR="Белорусский рубль"
BZD="Белизский доллар"
CAD="Канадский доллар"
CHF="Швейцарский франк"
CLP="Чилийское песо"
CNY="Китайский юань"
COP="Колумбийское песо"
CRC="Костариканский колон"
CUP="Кубинское песо"
CVE="Эскудо Кабо-Верде"
CZK="Чешская крона"
DJF="Франк Джибути"
DKK="Датская крона"
DOP="Доминиканское песо"
DZD="Алжирский динар"
EGP="Египетский фунт"
ETB="Эфиопский быр"
EUR="Евро"
FJD="Доллар Фиджи"
GBP="Британский фунт"
GEL="Грузинский лари"
GHS="Ганский седи"
GMD="Гамбийский даласи"
GNF="Гвинейский франк"
GTQ="Гватемальский кетсаль"
HKD="Гонконгский доллар"
HNL="Гондурасская лемпира"
HRK="Хорватская куна"
HTG="Гаитянский гурд"
HUF="Венгерский форинт"
IDR="Индонезийская рупия"
ILS="Израильский шекель"
INR="Индийская рупия"
IQD="Иракский динар"
IRR="Иранский риал"
ISK="Исландская крона"
JMD="Ямайский доллар"
JOD="Иорданский динар"
JPY="Японская иена"
KES="Кенийский шиллинг"
KHR="Камбоджийский риель"
KMF="Франк Комор"
KRW="Южнокорейская вона"
KWD="Кувейтский динар"
KYD="Доллар Каймановых островов"
KZT="Казахстанский тенге"
LAK="Лаосский кип"
LBP="Ливанский фунт"
LKR="Шри-Ланкийская рупия"
LSL="Лоти Лесото"
LTC="Лайткоин"
LTL="Литовский лит"
LYD="Ливийский динар"
MAD="Марокканский дирхам"
MDL="Молдавский лей"
MGA="Малагасийский ариари"
MKD="Македонский денар"
MMK="Мьянманский кьят"
MOP="<NAME>"
MRO="Мавританская угия"
MUR="Маврикийская рупия"
MVR="Мальдивская руфия"
MWK="Малавийская квача"
MXN="Мексиканское песо"
MYR="Малазийский ринггит"
MZN="Мозамбикский метикал"
NAD="Доллар Намибии"
NGN="Нигерийская найра"
NIO="Никарагуанская кордоба"
NOK="Норвежская крона"
NPR="Непальская рупия"
NZD="Новозеландский доллар"
OMR="Оманский риал"
PAB="Панамский бальбоа"
PEN="Перуанский новый соль"
PGK="К<NAME> — Новой Гвинеи"
PHP="Филиппинское песо"
PKR="Пакистанская рупия"
PLN="Польский злотый"
PYG="Парагвайский гуарани"
QAR="Катарский риал"
RON="Румынский лей"
RSD="Сербский динар"
RUB="Российский рубль"
RWF="Руандийский франк"
SAR="Саудовский риял"
SCR="Сейшельская рупия"
SDG="Суданский фунт"
SEK="Шведская крона"
SGD="Сингапурский доллар"
SOS="Сомалийский шиллинг"
STD="Добра Сан-Томе и Принсипи"
SVC="Сальвадорский колон"
SYP="Сирийский фунт"
SZL="Свазилендский лилангени"
THB="Тайский бат"
TND="Тунисский динар"
TRY="Турецкая лира"
TTD="Доллар Тринидада и Тобаго"
TWD="Тайваньский доллар"
TZS="Танзанийский шиллинг"
UAH="Украинская гривна"
UGX="Угандийский шиллинг"
USD="Доллар США"
UYU="Уругвайское песо"
UZS="Узбекский сум"
VEF="Венесуэльский боливар"
VND="Вьетнамский донг"
VUV="Вануатский вату"
XAF="Франк КФА BEAC"
XCD="Восточно-карибский доллар"
XOF="Франк КФА BCEAO"
XPF="Французский тихоокеанский франк"
YER="Йеменский риал"
ZAR="Южноафриканский рэнд"
ZMK="Замбийская квача"
<file_sep>/app/src/main/java/com/khrolenok/rates/controller/StockItemsAdapter.java
/*
* Copyright (c) 2015 Andrey “Limych” Khrolenok
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.khrolenok.rates.controller;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.khrolenok.rates.R;
import com.khrolenok.rates.Settings;
import com.khrolenok.rates.model.StockItem;
import com.khrolenok.rates.ui.MainActivity;
import com.khrolenok.rates.ui.RatesFragment;
import com.khrolenok.rates.util.PreferencesManager;
import com.khrolenok.rates.util.StockNames;
import java.util.Date;
import java.util.List;
/**
* Created by Limych on 17.09.2015
*/
public class StockItemsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_FOOTER = Integer.MIN_VALUE + 1;
private List<StockItem> mStockItems;
private final Context mContext;
private final RatesFragment mFragment;
public StockItemsAdapter(Context context, List<StockItem> stockItems, RatesFragment fragment) {
mContext = context;
mFragment = fragment;
setStockItems(stockItems);
}
public void setStockItems(List<StockItem> stockItems) {
this.mStockItems = stockItems;
}
@Override
public int getItemCount() {
return ( mStockItems == null ? 0 : mStockItems.size() + 1 );
}
@Override
public int getItemViewType(int position) {
if( position == getItemCount() - 1 ) return TYPE_FOOTER;
return super.getItemViewType(position);
}
public StockItem getItem(int position) {
if( position < getItemCount() - 1 ) return mStockItems.get(position);
return null;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch( viewType ){
case TYPE_FOOTER:
return new FooterViewHolder(inflater.inflate(R.layout.fragment_rates_footer, parent, false));
default:
return new ViewHolder(inflater.inflate(R.layout.fragment_rates_item, parent, false));
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
if( getItemViewType(position) == TYPE_FOOTER ){
final FooterViewHolder vh = (FooterViewHolder) viewHolder;
Date updateTS = new Date(0);
for( StockItem item : mStockItems ) {
if( item.lastUpdate != null && item.lastUpdate.after(updateTS) )
updateTS.setTime(item.lastUpdate.getTime());
}
vh.setUpdateTS(updateTS);
} else {
final ViewHolder vh = (ViewHolder) viewHolder;
final StockItem stockItem = mStockItems.get(position);
vh.setItemData(position, stockItem);
}
}
public void fillValuesFromMainValue(double mainValue) {
( (MainActivity) mContext ).mainValue = mainValue;
for( StockItem si : mStockItems ) {
si.value = mainValue * si.faceValue / si.lastPrice;
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView symbolTV;
private TextView nameTV;
private TextView priceTV;
private TextView priceChangeDirTV;
private TextView priceChangeTV;
private TextView valueTV;
private ViewGroup valueContainer;
public ViewHolder(View itemView) {
super(itemView);
symbolTV = (TextView) itemView.findViewById(R.id.itemSymbol);
nameTV = (TextView) itemView.findViewById(R.id.itemName);
priceTV = (TextView) itemView.findViewById(R.id.itemPrice);
priceChangeDirTV = (TextView) itemView.findViewById(R.id.itemChangeDirection);
priceChangeTV = (TextView) itemView.findViewById(R.id.itemChange);
valueTV = (TextView) itemView.findViewById(R.id.itemValue);
valueContainer = (ViewGroup) itemView.findViewById(R.id.itemValueContainer);
}
public String getStockExchangeName(Context context, String group) {
if( group == null ){
return "";
}
String stockExchangeName;
switch( group ){
case Settings.Rates.Groups.OFFICIAL:
stockExchangeName = context.getString(R.string.title_official);
break;
case Settings.Rates.Groups.FOREX:
stockExchangeName = context.getString(R.string.title_forex);
break;
case Settings.Rates.Groups.STOCK:
stockExchangeName = context.getString(R.string.title_stock);
break;
default:
stockExchangeName = group;
break;
}
return "(" + stockExchangeName + ") ";
}
public void setItemData(final int position, final StockItem stockItem) {
final Context context = itemView.getContext();
final PreferencesManager prefs = PreferencesManager.getInstance();
final boolean isLongFormat = prefs.getBoolean(PreferencesManager.PREF_LONG_FORMAT, false);
symbolTV.setText(stockItem.symbol);
nameTV.setText(getStockExchangeName(context, stockItem.stockExchange)
+ StockNames.getInstance().getTitle(stockItem.symbol));
valueTV.setText(stockItem.getValueFormatted());
priceChangeTV.setText(stockItem.getPriceChangeFormatted(isLongFormat));
if( stockItem.symbol.equals(stockItem.priceCurrency) ){
priceTV.setVisibility(View.GONE);
priceChangeDirTV.setVisibility(View.GONE);
priceChangeTV.setVisibility(View.GONE);
} else {
priceTV.setVisibility(View.VISIBLE);
priceChangeDirTV.setVisibility(View.VISIBLE);
priceChangeTV.setVisibility(View.VISIBLE);
priceTV.setText(stockItem.getLastPriceFormatted(isLongFormat));
priceChangeDirTV.setText(( !stockItem.hasPriceChange()
? R.string.change_direction_none
: ( stockItem.getPriceChange() > 0 ? R.string.change_direction_up : R.string.change_direction_down ) ));
}
if( stockItem.hasPriceChange() ){
final boolean invertColors = prefs.getBoolean(PreferencesManager.PREF_INVERT_COLORS, false);
final int colorUp = ( !invertColors ? R.color.change_green : R.color.change_red );
final int colorDown = ( !invertColors ? R.color.change_red : R.color.change_green );
final int color = context.getResources().getColor(( stockItem.getPriceChange() > 0
? colorUp : colorDown ));
priceTV.setTextColor(color);
priceChangeDirTV.setTextColor(color);
priceChangeTV.setTextColor(color);
}
valueContainer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mFragment.showCalculatorDialog(position, (String) nameTV.getText(),
stockItem.value, stockItem.symbol);
}
});
}
}
public class FooterViewHolder extends RecyclerView.ViewHolder {
private TextView updateTV;
public FooterViewHolder(View itemView) {
super(itemView);
updateTV = (TextView) itemView.findViewById(R.id.updateTimestamp);
}
public void setUpdateTS(Date updateTS) {
final Context context = itemView.getContext();
final int updateTextFormatFlags = android.text.format.DateUtils.FORMAT_SHOW_DATE
| android.text.format.DateUtils.FORMAT_SHOW_TIME
| android.text.format.DateUtils.FORMAT_ABBREV_ALL;
final String updateText = context.getString(R.string.text_updated) + " "
+ android.text.format.DateUtils.formatDateTime(context, updateTS.getTime(),
updateTextFormatFlags);
updateTV.setText(updateText);
}
}
}
<file_sep>/app/src/main/java/com/khrolenok/rates/Settings.java
/*
* Copyright (c) 2015 Andrey “Limych” Khrolenok
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.khrolenok.rates;
/**
* Created by Limych on 07.07.2015
*/
public class Settings {
public static final String IDEA_SUGGEST_URL = "http://exrates.reformal.ru/";
public interface Display {
double CHANGES_THRESHOLD = 0.1; // Percents
}
public interface Rates {
int reloadDelay = 3 * 60 * 60 * 1000; // every 3 hours
interface Groups {
String OFFICIAL = "CBR";
String STOCK = "STK";
String FOREX = "FRX";
}
interface Columns {
int GROUP = 0;
int GOOD = 1;
int CURRENCY = 2;
int TIMESTAMP = 3;
int FACE_VALUE = 4;
int INITIAL_BID = 5;
int LAST_BID = 6;
int HIGH_BID = 7;
int LOW_BID = 8;
}
}
}
<file_sep>/app/src/main/java/com/khrolenok/rates/ExRatesAdapter.java
//package com.khrolenok.rates;
//
//import android.content.Context;
//import android.text.Editable;
//import android.text.TextWatcher;
//import android.view.LayoutInflater;
//import android.view.View;
//import android.view.ViewGroup;
//import android.widget.BaseAdapter;
//import android.widget.EditText;
//import android.widget.ListView;
//import android.widget.TextView;
//
//import java.text.NumberFormat;
//import java.text.ParseException;
//import java.util.ArrayList;
//import java.util.List;
//
//import com.khrolenok.rates.view.controller.MainActivity;
//
///**
// * Created by Limych on 01.09.2015.
// */
//class ExRatesAdapter extends BaseAdapter {
// private final Context mContext;
// public List<ExRate> exRates;
//
// public ExRatesAdapter(Context mContext) {
// this.mContext = mContext;
// exRates = new ArrayList<ExRate>();
// }
//
// public ExRatesAdapter(Context mContext, List<ExRate> exRates) {
// this.mContext = mContext;
// this.exRates = exRates;
// }
//
// public void add(ExRate exRate){
// if( exRate != null ) {
// exRates.add(exRate);
// }
// }
//
// @Override
// public int getCount() {
// return exRates.size();
// }
//
// @Override
// public Object getItem(int position) {
// return exRates.get(position);
// }
//
// @Override
// public long getItemId(int position) {
// return exRates.get(position).rate_id;
// }
//
// public String getGroupTitle(String groupCode){
// switch (groupCode){
// case Settings.Rates.Groups.OFFICIAL:
// return mContext.getString(R.string.title_official);
// case Settings.Rates.Groups.FOREX:
// return mContext.getString(R.string.title_forex);
// case Settings.Rates.Groups.STOCK:
// return mContext.getString(R.string.title_stock);
//
// default:
// return groupCode;
// }
// }
//
// @Override
// public View getView(final int position, View convertView, ViewGroup parent) {
// View rowView = convertView;
//
// if( rowView == null ) {
// final LayoutInflater inflater = (LayoutInflater) mContext
// .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// rowView = inflater.inflate(R.layout.activity_main_item, parent, false);
// }
//
// if( position % 2 == 0 ) {
// rowView.setBackgroundColor(mContext.getResources().getColor(R.color.list_background_even));
// }
//
// final TextView titleView = (TextView) rowView.findViewById(R.id.item_title);
// final TextView groupView = (TextView) rowView.findViewById(R.id.item_group);
// final TextView rateView = (TextView) rowView.findViewById(R.id.item_price);
// final EditText valueView = (EditText) rowView.findViewById(R.id.item_value);
//
// final ExRate rate = exRates.get(position);
//
// titleView.setText(rate.goodCode);
// groupView.setText(getGroupTitle(rate.groupCode));
// rateView.setText(rate.getLastBidFormatted());
//
// valueView.setTag(rate);
// final double value = ((MainActivity) mContext).mainValue * rate.faceValue / rate.lastBid;
// valueView.setText(ExRate.format(value));
//
// valueView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
// @Override
// public void onFocusChange(View v, boolean hasFocus) {
// ((MainActivity) mContext).focus = (hasFocus ? v : null);
// }
// });
//
// //every time the user adds/removes a character from the edit text, save
// //the current value of the edit text to retrieve later
// valueView.addTextChangedListener(new myTextWatcher(rowView));
//
// return rowView;
// }
//
// private class myTextWatcher implements TextWatcher {
// View view;
//
// public myTextWatcher(View view) {
// this.view = view;
// }
//
// @Override
// public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// // do nothing
// }
//
// @Override
// public void onTextChanged(CharSequence s, int start, int before, int count) {
// // do nothing
// }
//
// @Override
// public void afterTextChanged(Editable s) {
// double value = 0;
// final double mainValue;
// final EditText valueView = (EditText) view.findViewById(R.id.item_value);
//
// if( valueView != ((MainActivity) mContext).focus ){
// return;
// }
//
// final ExRate rate = (ExRate) valueView.getTag();
//
// try {
// value = NumberFormat.getInstance().parse(s.toString()).doubleValue();
// } catch (ParseException ignored) {
// }
//
// if( rate.value != value ) {
// rate.value = value;
//
// mainValue = value * rate.lastBid / rate.faceValue;
// ((MainActivity) mContext).setMainValue(mainValue);
//
// ListView list = (ListView) ((MainActivity) mContext).findViewById(R.id.rates_list);
// final int start = list.getFirstVisiblePosition();
// for (int i = list.getLastVisiblePosition(); i >= start; i--) {
// final View v = list.getChildAt(i - start);
// if( v != view ){
// final EditText v_valueView = (EditText) v.findViewById(R.id.item_value);
// final ExRate v_rate = (ExRate) v_valueView.getTag();
// final double v_value = mainValue * v_rate.faceValue / v_rate.lastBid;
// if( v_rate.value != v_value ){
// v_rate.value = v_value;
// v_valueView.setText(ExRate.format(v_value));
// }
// }
// }
// }
// }
// }
//
//}
<file_sep>/server/Model/StockItem.php
<?php
namespace Model;
class StockItem{
var $source;
var $code;
var $faceValue;
var $currency;
var $open;
var $last;
var $high;
var $low;
var $timestamp;
function __construct($initial = null){
if( gettype($initial) === 'array' || gettype($initial) === 'object' ){
foreach ((array) $initial as $key => $val){
if (!empty($key))
$this->$key = $val;
}
}
}
}
<file_sep>/app/src/main/java/com/khrolenok/rates/ExRatesGroup.java
/*
* Copyright (c) 2015 <NAME>” Khrolenok
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.khrolenok.rates;
import android.content.Context;
import android.content.res.TypedArray;
import android.widget.RemoteViews;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ExRatesGroup {
public String caption;
public List<ExRate> exRates;
public boolean isCompactTitleMode;
public boolean isLongFormat;
public ExRateViewsBounds viewsBounds;
public ExRatesGroup(String caption) {
this.caption = caption;
viewsBounds = new ExRateViewsBounds();
exRates = new ArrayList<>();
}
public ExRatesGroup(String caption, List<String> ratesList, JSONObject ratesJson) {
this.caption = caption;
viewsBounds = new ExRateViewsBounds();
exRates = new ArrayList<>();
for (String rate : ratesList) {
JSONArray ratesArray;
try {
ratesArray = ratesJson.getJSONArray(rate);
} catch (JSONException e) {
continue;
}
add(new ExRate(ratesArray));
}
}
public ExRatesGroup(String caption, String ratesGroup, List<String> ratesList, JSONObject ratesJson) {
this.caption = caption;
viewsBounds = new ExRateViewsBounds();
exRates = new ArrayList<>();
for (String rate : ratesList) {
JSONArray ratesArray;
try {
ratesArray = ratesJson.getJSONArray(rate);
} catch (JSONException e) {
continue;
}
try {
if (!ratesArray.getString(Settings.Rates.Columns.GROUP).equals(ratesGroup)) {
continue;
}
} catch (JSONException e) {
continue;
}
add(new ExRate(ratesArray));
}
}
public void add(ExRate exRate){
if( exRate != null ) {
viewsBounds.updateMaxBounds(exRate.viewsBounds);
exRate.viewsBounds = viewsBounds;
exRates.add(exRate);
}
}
public Date getUpdateTS(){
Date updateTS = null;
for (ExRate exRate : exRates) {
final Date rateTS = exRate.getUpdateTS();
updateTS = ( updateTS == null || rateTS.after(updateTS)
? rateTS
: updateTS );
}
return updateTS;
}
public ExRateViewsBounds calcViewsBounds(int mainFontSize, int changeFontSize){
// if( BuildConfig.DEBUG ) Log.v(Settings.TAG, "ExRatesGroup.calcViewsBounds(" + mainFontSize + ", " + changeFontSize + ")");
for (ExRate exRate : exRates) {
exRate.isCompactTitleMode = isCompactTitleMode;
exRate.isLongFormat = isLongFormat;
exRate.calcViewsBounds(mainFontSize, changeFontSize);
viewsBounds.updateMaxBounds(exRate, mainFontSize, changeFontSize);
}
return viewsBounds;
}
public ExRateViewsBounds calcViewsBounds(Context context){
int mainFontSize, changeFontSize;
final int[] textSizeAttr = new int[] { android.R.attr.textSize };
TypedArray a = context.obtainStyledAttributes(R.style.Theme_Rates_Widget_Body, textSizeAttr);
mainFontSize = a.getDimensionPixelSize(0, -1);
a.recycle();
a = context.obtainStyledAttributes(R.style.Theme_Rates_Widget_Small, textSizeAttr);
changeFontSize = a.getDimensionPixelSize(0, -1);
a.recycle();
final float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
if( mainFontSize <= 0 ) {
mainFontSize = (int) (14 * scaledDensity);
}
if( changeFontSize <= 0 ) {
changeFontSize = (int) (9 * scaledDensity);
}
return calcViewsBounds(mainFontSize, changeFontSize);
}
public RemoteViews buildWidgetViews(Context context, boolean isShowChange, boolean invertColors){
// if( BuildConfig.DEBUG ) Log.v(Settings.TAG, "ExRatesGroup.buildWidgetViews(…)");
RemoteViews ratesGroup = new RemoteViews(context.getPackageName(), R.layout.widget_layout_group);
ratesGroup.removeAllViews(R.id.table_rates);
ratesGroup.setTextViewText(R.id.group_caption, caption);
for (ExRate exRate : exRates) {
exRate.isCompactTitleMode = isCompactTitleMode;
exRate.isLongFormat = isLongFormat;
ratesGroup.addView(R.id.table_rates,
exRate.buildWidgetViews(context, isShowChange, invertColors));
}
return ratesGroup;
}
}
<file_sep>/server/RestApi/HttpUtils.php
<?php
namespace RestApi;
class HttpUtils {
public static function getProtocol(){
return isset($_SERVER['SERVER_PROTOCOL'])
? $_SERVER['SERVER_PROTOCOL']
: 'HTTP/1.0';
}
public static function getHash($data){
return md5(serialize($data));
}
public static function addHeader_ETag($data, $checkIfNoneMatch = false){
$etag = self::getHash($data);
if( $checkIfNoneMatch && isset($_SERVER['HTTP_IF_NONE_MATCH']) ){
$noneMatch = trim($_SERVER['HTTP_IF_NONE_MATCH'], '"');
if ($etag === $noneMatch) {
header(self::getProtocol() . ' 304 Not Modified');
return false;
}
}
header('ETag: "' . $etag . '"');
return true;
}
public static function addHeader_LastModified($mtime, $checkIfModifiedSince = false){
if($checkIfModifiedSince && isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
$modifiedSince = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
if (false !== ($semicolonPos = strpos($modifiedSince, ';'))) {
$modifiedSince = substr($modifiedSince, 0, $semicolonPos);
}
if ($mtime === @strtotime($modifiedSince)) {
header(self::getProtocol() . ' 304 Not Modified');
return false;
}
}
$lastModified = gmdate('D, d M Y H:i:s', $mtime) . ' GMT';
header('Last-Modified: ' . $lastModified);
return true;
}
public static function addHeader_expires($livePeriod){
$expires = gmdate('D, d M Y H:i:s', time() + $livePeriod) . ' GMT';
header('Expires: ' . $expires);
header('Cache-Control: max-age=' . $livePeriod . ', public, must-revalidate');
return true;
}
}
<file_sep>/app/src/main/java/com/khrolenok/rates/ui/SettingsActivity.java
/*
* Copyright (c) 2015 Andrey “Limych” Khrolenok
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.khrolenok.rates.ui;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.khrolenok.rates.ExRatesApplication;
import com.khrolenok.rates.R;
import com.khrolenok.rates.util.AppStore;
import com.khrolenok.rates.util.UpdateService;
/**
* Created by Limych on 03.09.2015
*/
public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
findViewById(R.id.tabLayout).setVisibility(View.GONE);
if( savedInstanceState == null ){
getFragmentManager().beginTransaction()
.add(R.id.contentFrame, new SettingsFragment())
.commit();
}
}
public static class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
if( !ExRatesApplication.isTestDevice ){
getPreferenceScreen().removePreference(findPreference("category_debug"));
} else {
findPreference("device_id").setSummary(ExRatesApplication.deviceId);
findPreference("installer").setSummary(AppStore.installer);
}
}
@Override
public void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
final Context context = getActivity();
context.sendBroadcast(new Intent(ExRatesApplication.ACTION_STOCKS_UPDATE));
// Try to restart update service
UpdateService.notifyUpdateNeeded(context);
}
}
}
<file_sep>/app/src/main/java/com/khrolenok/rates/util/ConnectionMonitor.java
/*
* Copyright (c) 2015 Andrey “Limych” Khrolenok
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.khrolenok.rates.util;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.khrolenok.rates.BuildConfig;
import trikita.log.Log;
/**
* Created by Limych on 18.09.2015
*/
public class ConnectionMonitor extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if( !action.equals(ConnectivityManager.CONNECTIVITY_ACTION) )
return;
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if( !noConnectivity && isNetworkAvailable(context) ){
if( BuildConfig.DEBUG ) Log.d("Network connection detected");
// Restart update service
UpdateService.notifyUpdateNeeded(context);
}
}
public static void setEnabledSetting(Context context, int setting) {
if( BuildConfig.DEBUG ) Log.d("Connection monitor status changed to " + setting);
final ComponentName receiver = new ComponentName(context, ConnectionMonitor.class);
final PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver, setting, 0);
}
public static boolean isNetworkAvailable(Context context) {
final PreferencesManager prefs = PreferencesManager.getInstance();
return isNetworkAvailable(context, prefs.getBoolean(PreferencesManager.PREF_WIFI_ONLY, false));
}
public static boolean isNetworkAvailable(Context context, boolean testForWiFi) {
final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
final boolean isWiFi = ( activeNetwork.getType() == ConnectivityManager.TYPE_WIFI );
if( BuildConfig.DEBUG ) Log.v("testForWiFi = " + testForWiFi + ", isWiFi = " + isWiFi);
final boolean isNetworkAvailable = ( activeNetwork.isConnectedOrConnecting()
&& ( !testForWiFi || isWiFi ) );
if( BuildConfig.DEBUG ) Log.v("isNetworkAvailable = " + isNetworkAvailable);
return isNetworkAvailable;
}
}
<file_sep>/app/src/main/java/com/khrolenok/rates/ExRate.java
/*
* Copyright (c) 2015 Andrey “Limych” Khrolenok
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.khrolenok.rates;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.widget.RemoteViews;
import com.khrolenok.rates.util.StockNames;
import org.json.JSONArray;
import org.json.JSONException;
import java.text.DecimalFormat;
import java.util.Date;
/**
* Created by Limych on 15.08.2015
*/
public class ExRate {
public int rate_id;
public String groupCode;
public String goodCode;
public String currencyCode;
public int faceValue;
public double initialBid;
public double lastBid;
public Date updateTS;
public double value = 0;
public boolean isCompactTitleMode;
public boolean isLongFormat;
public ExRateViewsBounds viewsBounds;
public ExRate(JSONArray rateData) {
viewsBounds = new ExRateViewsBounds();
try{
groupCode = rateData.getString(Settings.Rates.Columns.GROUP);
goodCode = rateData.getString(Settings.Rates.Columns.GOOD);
currencyCode = rateData.getString(Settings.Rates.Columns.CURRENCY);
faceValue = rateData.getInt(Settings.Rates.Columns.FACE_VALUE);
initialBid = rateData.getDouble(Settings.Rates.Columns.INITIAL_BID);
lastBid = rateData.getDouble(Settings.Rates.Columns.LAST_BID);
updateTS = new Date(rateData.getLong(Settings.Rates.Columns.TIMESTAMP) * 1000);
} catch( JSONException ignored ){
}
rate_id = ( groupCode + goodCode + currencyCode ).hashCode();
}
public boolean isEmpty() {
return initialBid == 0 && lastBid == 0;
}
public double bidChange() {
return lastBid - initialBid;
}
public boolean hasBidChange() {
return hasBidChange(Settings.Display.CHANGES_THRESHOLD);
}
public boolean hasBidChange(double changesThreshold) {
return Math.abs(bidChange() * 100 / initialBid) < changesThreshold;
}
public String getTitle() {
return ( isCompactTitleMode
? StockNames.getInstance().getSymbol(goodCode)
: goodCode );
}
public Date getUpdateTS() {
return updateTS;
}
protected String formatValue(double value, boolean isShowSign, boolean isLongFormat) {
int digits = ( isLongFormat ? 4 : 2 );
double tmp = value;
while( digits > 0 && Math.abs(tmp) > 99 ){
tmp /= 10;
digits--;
}
return String.format("%" + ( isShowSign ? "+" : "" ) + "." + digits + "f", value)
.replace('-', '−');
}
public String getLastBidFormatted() {
return formatValue(lastBid, false, isLongFormat);
}
public String getChangeFormatted() {
return formatValue(bidChange(), true, isLongFormat);
}
protected void getTextBounds(String text, int fontSize, Rect bounds) {
Paint p = new Paint();
p.setTypeface(Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL));
p.setTextSize(fontSize);
p.setAntiAlias(true);
p.getTextBounds(text, 0, text.length(), bounds);
bounds.right += bounds.left;
bounds.left = 0;
bounds.bottom += bounds.top;
bounds.top = 0;
}
public Rect getBounds(int mainFontSize) {
return getBounds(mainFontSize, mainFontSize);
}
public Rect getBounds(int mainFontSize, int changeFontSize) {
calcViewsBounds(mainFontSize, changeFontSize);
return new Rect(0, 0, viewsBounds.getSummaryWidth(), viewsBounds.height);
}
public ExRateViewsBounds calcViewsBounds(int mainFontSize, int changeFontSize) {
Rect tb = new Rect();
int height = 0;
getTextBounds(getTitle(), mainFontSize, tb);
int titleWidth = tb.width();
height = Math.max(height, tb.height());
getTextBounds(getLastBidFormatted(), mainFontSize, tb);
int bidWidth = tb.width();
height = Math.max(height, tb.height());
getTextBounds(getChangeFormatted(), changeFontSize, tb);
int changeWidth = tb.width();
height = Math.max(height, tb.height());
viewsBounds.updateMaxBounds(titleWidth, bidWidth, changeWidth, height);
return viewsBounds;
}
public RemoteViews buildWidgetViews(Context context, boolean isShowChange, boolean invertColors) {
int color = R.color.change_none;
final int colorUp = ( !invertColors ? R.color.change_green : R.color.change_red );
final int colorDown = ( !invertColors ? R.color.change_red : R.color.change_green );
RemoteViews ratesItem = new RemoteViews(context.getPackageName(), R.layout.widget_layout_item);
ratesItem.setInt(R.id.itemSymbol, "setMinWidth", viewsBounds.titleWidth);
ratesItem.setInt(R.id.itemPrice, "setMinWidth", viewsBounds.bidWidth);
int[] textSizeAttr = new int[] { android.R.attr.textSize };
TypedArray a = context.obtainStyledAttributes(R.style.Theme_Rates_Widget_Body, textSizeAttr);
final int textSize = a.getDimensionPixelSize(0, -1);
a.recycle();
if( textSize > 0 ){
ratesItem.setInt(R.id.itemChangeDirection, "setMinWidth", textSize);
}
ratesItem.setInt(R.id.itemChange, "setMinWidth", ( isShowChange
? viewsBounds.changeWidth
: 0 ));
ratesItem.setTextViewText(R.id.itemSymbol, getTitle());
if( isEmpty() ){
ratesItem.setTextViewText(R.id.itemPrice, context.getString(R.string.rate_none));
ratesItem.setTextViewText(R.id.itemChangeDirection, context.getString(R.string.change_direction_none));
ratesItem.setTextViewText(R.id.itemChange, "");
} else {
ratesItem.setTextViewText(R.id.itemPrice, getLastBidFormatted());
if( hasBidChange() ){
ratesItem.setTextViewText(R.id.itemChangeDirection, context.getString(R.string.change_direction_none));
} else if( bidChange() > 0 ){
ratesItem.setTextViewText(R.id.itemChangeDirection, context.getString(R.string.change_direction_up));
color = colorUp;
} else {
ratesItem.setTextViewText(R.id.itemChangeDirection, context.getString(R.string.change_direction_down));
color = colorDown;
}
ratesItem.setTextViewText(R.id.itemChange, ( isShowChange ? getChangeFormatted() : "" ));
}
ratesItem.setTextColor(R.id.itemPrice, context.getResources().getColor(color));
ratesItem.setTextColor(R.id.itemChangeDirection, context.getResources().getColor(color));
ratesItem.setTextColor(R.id.itemChange, context.getResources().getColor(color));
return ratesItem;
}
static String format(double rate) {
if( rate == 0 ){
return "0";
} else {
final DecimalFormat df = new DecimalFormat("0.00");
return df.format(rate);
}
}
}
class ExRateViewsBounds {
public int titleWidth;
public int bidWidth;
public int changeWidth;
public int height;
public ExRateViewsBounds() {
// Empty
}
public ExRateViewsBounds(int titleWidth, int bidWidth, int changeWidth, int height) {
set(titleWidth, bidWidth, changeWidth, height);
}
public void set(ExRateViewsBounds viewsBounds) {
this.titleWidth = viewsBounds.titleWidth;
this.bidWidth = viewsBounds.bidWidth;
this.changeWidth = viewsBounds.changeWidth;
this.height = viewsBounds.height;
}
public void set(int titleWidth, int bidWidth, int changeWidth, int height) {
this.titleWidth = titleWidth;
this.bidWidth = bidWidth;
this.changeWidth = changeWidth;
this.height = height;
}
public void updateMaxBounds(int titleWidth, int bidWidth, int changeWidth, int height) {
this.titleWidth = Math.max(this.titleWidth, titleWidth);
this.bidWidth = Math.max(this.bidWidth, bidWidth);
this.changeWidth = Math.max(this.changeWidth, changeWidth);
this.height = Math.max(this.height, height);
}
public void updateMaxBounds(ExRateViewsBounds viewsBounds) {
updateMaxBounds(viewsBounds.titleWidth, viewsBounds.bidWidth, viewsBounds.changeWidth,
viewsBounds.height);
}
public void updateMaxBounds(ExRate exRate, int mainFontSize) {
updateMaxBounds(exRate, mainFontSize, mainFontSize);
}
public void updateMaxBounds(ExRate exRate, int mainFontSize, int changeFontSize) {
updateMaxBounds(exRate.calcViewsBounds(mainFontSize, changeFontSize));
}
public int getSummaryWidth() {
return titleWidth + bidWidth + changeWidth;
}
}
<file_sep>/server/index.php
<?php
use Loader;
define('DEBUG', true); // Uncomment for debug mode
if (defined('DEBUG')){
error_reporting(E_ALL);
ini_set( 'display_errors', 1 );
} else {
define('DEBUG', false);
}
$loader = include __DIR__ . '/vendor/autoload.php';
$loader->add('Loader', __DIR__ . '/');
$loader->add('Model', __DIR__ . '/');
$loader->add('RestApi', __DIR__ . '/');
// $stockItems = Loader\MoexLoader::create()->load();
$stockItems = Loader\CbrfLoader::create()->load();
RestService\Server::create('/api', new RestApi\Rates)
// ->setDebugMode(true) //prints the debug trace, line number and file if a exception has been thrown.
->collectRoutes()
->run();
# http://4map.ru/service/get_rates_to_map.aspx?country=RU&latsw=55.56080032284363&lngsw=37.261019780273514&latne=55.77997579045521&lngne=37.933932377929764&zoom=12&curr1=RUB&curr2=USD&amount=1000&rate_left=-1&rate_right=-1&ww=1280&wh=616&src=1
# http://www.bmsk.ru/<file_sep>/app/src/main/java/com/khrolenok/rates/ui/RatesFragment.java
/*
* Copyright (c) 2015 Andrey “Limych” Khrolenok
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.khrolenok.rates.ui;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.khrolenok.rates.ExRate;
import com.khrolenok.rates.ExRatesApplication;
import com.khrolenok.rates.ExRatesGroup;
import com.khrolenok.rates.R;
import com.khrolenok.rates.controller.StockItemsAdapter;
import com.khrolenok.rates.model.StockItem;
import com.khrolenok.rates.util.PreferencesManager;
import com.khrolenok.rates.util.UpdateService;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Limych on 07.09.2015
*/
public class RatesFragment extends Fragment
implements SwipeRefreshLayout.OnRefreshListener, AppBarLayout.OnOffsetChangedListener {
private BroadcastReceiver mBroadcastReceiver;
private RecyclerView mRatesListView;
private StockItemsAdapter mStockItemsAdapter;
private SwipeRefreshLayout mQuotesRefresher;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_rates, container, false);
mQuotesRefresher = (SwipeRefreshLayout) rootView.findViewById(R.id.srQuotesRefresher);
mQuotesRefresher.setOnRefreshListener(this);
mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
mQuotesRefresher.setRefreshing(false);
if( intent.getAction().equals(ExRatesApplication.ACTION_STOCKS_UPDATE) ){
Toast.makeText(context, R.string.update_loaded, Toast.LENGTH_SHORT).show();
populateRatesListView();
} else if( intent.getAction().equals(ExRatesApplication.ERROR_NO_CONNECTION) ){
Toast.makeText(context, R.string.no_internet_connection, Toast.LENGTH_SHORT).show();
}
}
};
return rootView;
}
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
mQuotesRefresher.setEnabled(( i == 0 ));
}
@Override
public void onResume() {
super.onResume();
// Tracking the screen view
ExRatesApplication.getInstance().trackScreenView("Rates Fragment");
populateRatesListView();
( (MainActivity) getActivity() ).appBarLayout.addOnOffsetChangedListener(this);
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ExRatesApplication.ACTION_STOCKS_UPDATE);
intentFilter.addAction(ExRatesApplication.ERROR_NO_CONNECTION);
getActivity().registerReceiver(mBroadcastReceiver, intentFilter);
}
@Override
public void onPause() {
super.onPause();
( (MainActivity) getActivity() ).appBarLayout.removeOnOffsetChangedListener(this);
getActivity().unregisterReceiver(mBroadcastReceiver);
}
private void populateRatesListView() {
if( mRatesListView == null ){
mRatesListView = (RecyclerView) getActivity().findViewById(R.id.stockRatesList);
mRatesListView.setLayoutManager(new LinearLayoutManager(getActivity()));
}
final PreferencesManager prefs = PreferencesManager.getInstance();
List<String> ratesList = prefs.getStocksList();
if( ratesList.isEmpty() ) return;
JSONObject ratesJson;
try{
ratesJson = new JSONObject(prefs.getStockData());
} catch( JSONException ignored ){
return;
}
final ExRatesGroup exRatesGroup = new ExRatesGroup("", ratesList, ratesJson);
if( mStockItemsAdapter == null ){
mStockItemsAdapter = new StockItemsAdapter(getActivity(),
fromExRates(exRatesGroup.exRates), this);
} else {
mStockItemsAdapter.setStockItems(fromExRates(exRatesGroup.exRates));
mStockItemsAdapter.notifyDataSetChanged();
}
mRatesListView.setAdapter(mStockItemsAdapter);
}
public List<StockItem> fromExRates(List<ExRate> exRates) {
final ArrayList<StockItem> mStockItems = new ArrayList<>();
final double mainValue = ( (MainActivity) getActivity() ).mainValue;
StockItem item = new StockItem();
item.code = "RUR";
item.symbol = "RUR";
item.faceValue = 1;
item.priceCurrency = "RUR";
item.initialPrice = 1;
item.lastPrice = 1;
item.value = mainValue;
mStockItems.add(item);
for( int i = 0, cnt = exRates.size(); i < cnt; i++ ) {
final ExRate exRate = exRates.get(i);
item = new StockItem();
item.code = exRate.groupCode + "_" + exRate.goodCode + "_" + exRate.currencyCode;
item.stockExchange = exRate.groupCode;
item.symbol = exRate.goodCode;
item.faceValue = exRate.faceValue;
item.priceCurrency = exRate.currencyCode;
item.initialPrice = exRate.initialBid;
item.lastPrice = exRate.lastBid;
item.lastUpdate = exRate.updateTS;
item.value = mainValue * item.faceValue / item.lastPrice;
mStockItems.add(item);
}
return mStockItems;
}
public void showCalculatorDialog(int listItemPosition, String title, double value, String currency) {
FragmentManager fm = getActivity().getSupportFragmentManager();
CalculatorDialog calculatorDialog = new CalculatorDialog();
calculatorDialog.setTargetFragment(this, 0);
calculatorDialog.title = title;
calculatorDialog.value = value;
calculatorDialog.currency = currency;
calculatorDialog.listItemPosition = listItemPosition;
calculatorDialog.show(fm, CalculatorDialog.TAG_DIALOG);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if( resultCode == Activity.RESULT_OK ){
final int listItemPosition = data.getIntExtra(CalculatorDialog.TAG_LIST_ITEM_POSITION, -1);
final double value = data.getDoubleExtra(CalculatorDialog.TAG_VALUE, 0);
final StockItem stockItem = mStockItemsAdapter.getItem(listItemPosition);
mStockItemsAdapter.fillValuesFromMainValue(value * stockItem.lastPrice / stockItem.faceValue);
stockItem.value = value;
mStockItemsAdapter.notifyDataSetChanged();
}
}
@Override
public void onRefresh() {
// if( BuildConfig.DEBUG ){
// Track refreshing event
ExRatesApplication.getInstance().trackEvent("Rates", "Forced Refresh");
UpdateService.forceUpdate(getActivity());
// } else {
// mQuotesRefresher.setRefreshing(false);
// Toast.makeText(getActivity(), R.string.force_update_na, Toast.LENGTH_SHORT).show();
// }
}
}
<file_sep>/app/build.gradle
/*
* Copyright (c) 2015 <NAME>” Khrolenok
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
apply plugin: 'com.android.application'
// read secret variables
// IMPORTANT: must be above `android {}` declaration
File secretPropsFile = file('../secret.properties')
if (secretPropsFile.exists()) {
Properties p = new Properties()
p.load(new FileInputStream(secretPropsFile))
p.each { name, value ->
safeLoad name as String, value
}
}
android {
compileSdkVersion 23
buildToolsVersion '22.0.1'
useLibrary 'org.apache.http.legacy'
packagingOptions {
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude '.readme'
}
defaultConfig {
applicationId "com.khrolenok.rates"
minSdkVersion 16
targetSdkVersion 23
versionName VERSION
versionCode getBuildVersion(1)
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
signingConfigs {
release {
storeFile safeGetFile('STORE_FILE')
storePassword safeGet('STORE_PASSWORD')
keyAlias safeGet('KEY_ALIAS')
keyPassword safeGet('KEY_PASSWORD', safeGet('STORE_PASSWORD'))
// notice how STORE_PASSWORD is used as a fallback
}
}
buildTypes {
def BOOLEAN = "boolean"
def TRUE = "true"
def FALSE = "false"
all {
buildConfigField "String", "API_ENDPOINT", project["API_ENDPOINT"]
buildConfigField "String", "SUPPORT_EMAIL", project["SUPPORT_EMAIL"]
}
debug {
buildConfigField BOOLEAN, "SHOW_ADS", TRUE
// buildConfigField BOOLEAN, "SHOW_ADS", FALSE
// buildConfigField BOOLEAN, "STRICT_MODE", TRUE
buildConfigField BOOLEAN, "STRICT_MODE", FALSE
buildConfigField BOOLEAN, "GOOGLE_ANALYTICS", FALSE
// buildConfigField BOOLEAN, "GOOGLE_ANALYTICS", TRUE
}
release {
buildConfigField BOOLEAN, "SHOW_ADS", TRUE
buildConfigField BOOLEAN, "STRICT_MODE", FALSE
buildConfigField BOOLEAN, "GOOGLE_ANALYTICS", TRUE
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release as Object
minifyEnabled true
zipAlignEnabled true
File releasesDir = new File(
safeGet('RELEASES_PARENT_DIR', '~/APKs'),
safeGet('FOLDER_NAME', project.group as String)
)
if (!releasesDir.exists())
releasesDir.mkdirs()
android.applicationVariants.all { variant ->
variant.outputs.each { output ->
if (output.name == "release") {
/* base file name in a form of:
[package]-[versionType]-[versionName]-[versionCode]
ex. com.meedamian.testApp-release-1.0.0-1111
*/
String fileName = [
defaultConfig.applicationId,
project.name,
defaultConfig.versionName,
getBuildVersion(android.defaultConfig.versionCode, true)
].join('-')
//If there's no ZipAlign task it means that our artifact will be unaligned and we need to mark it as such.
if (!output.zipAlign)
fileName = fileName + '-unaligned'
// rename output APK
output.outputFile = new File(releasesDir, fileName + '.apk')
// copy mappings.txt (JIC)
if (variant.getBuildType().isMinifyEnabled()) {
File mappingDir = new File(releasesDir, 'mappings')
if (!mappingDir.exists())
mappingDir.mkdirs()
assemble << {
copy {
from variant.mappingFile
into mappingDir
rename('mapping.txt', "${fileName}-mapping.txt")
}
}
}
}
}
}
}
}
productFlavors {
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.google.android.gms:play-services-ads:7.8.0'
compile 'com.google.android.gms:play-services-analytics:7.8.0'
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:cardview-v7:23.0.1'
compile 'com.android.support:recyclerview-v7:23.0.1'
compile 'com.android.support:design:23.0.1'
compile 'co.trikita:log:1.1.5'
compile 'com.nineoldandroids:library:2.4.0' // Required for com.nhaarman.listviewanimations
compile 'com.nhaarman.listviewanimations:lib-core:3.1.0@aar'
compile 'com.nhaarman.listviewanimations:lib-manipulation:3.1.0@aar'
// compile 'com.github.navasmdc:MaterialDesign:1.5@aar'
// compile 'com.github.PhilJay:MPAndroidChart:v2.1.3'
// compile 'com.daimajia.easing:library:1.0.1@aar'
// compile 'com.daimajia.androidanimations:library:1.1.3@aar'
}
<file_sep>/server/Loader/BaseLoader.php
<?php
namespace Loader;
define('_COOKIE_LIFETIME', 7 * 24 * 60 * 60);
define('_HTTP_CODES_FILE', __DIR__ . '/http_codes.ini');
/**
* @author Limych
*
*/
abstract class BaseLoader {
static $logFile = './loader.log';
static $userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36';
static $cookieFile = './cookies.cache';
static $cookieFileLifetime = _COOKIE_LIFETIME; // One week
static $httpCodesFile = _HTTP_CODES_FILE;
static function log($msg){
error_log(date('Y-m-d H:i:s') . "\t$msg\n", 3, self::$logFile);
}
static function makeTimestamp($datetime, $format = 'Y-m-d H:i:s'){
try {
$date = \DateTime::createFromFormat($format, $datetime);
} catch (Exception $e) {
self::log($e->getMessage());
}
if( empty($date) ){
$date = new \DateTime('today');
}
return $date->getTimestamp();
}
/**
* Get a web file (HTML, XHTML, XML, image, etc.) from a URL. Return an
* array containing the HTTP server response header fields and content.
*/
static function wget( $url ){
// Delete cookie file periodically
if( is_file(self::$cookieFile)
&& time() > filemtime(self::$cookieFile) + self::$cookieFileLifetime ){
unlink(self::$cookieFile);
self::log('Internal cookie file deleted');
}
$options = array(
CURLOPT_CUSTOMREQUEST => 'GET', //set request type post or get
CURLOPT_POST => false, //set to GET
CURLOPT_USERAGENT => self::$userAgent, //set user agent
CURLOPT_COOKIEFILE => self::$cookieFile, //set cookie file
CURLOPT_COOKIEJAR => self::$cookieFile, //set cookie jar
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => '', // handle all encodings
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$result = curl_getinfo( $ch );
curl_close( $ch );
$result['errno'] = $err;
$result['errmsg'] = $errmsg;
$result['content'] = $content;
if( $result['errno'] != 0 ){
// error: bad url, timeout, redirect loop…
self::log("HTTP-Request: $url");
self::log("Error: ({$result[errno]}) {$result[errmsg]}");
}elseif( $result['http_code'] != 200 ){
// error: no page, no permissions, no service…
static $http_codes = null;
if($http_codes == null){
$http_codes = parse_ini_file(self::$httpCodesFile);
}
$http_msg = ( $http_codes != null ? $http_codes[$result['http_code']] : "" );
self::log("HTTP-Request: $url");
self::log("HTTP-Error: ({$result[http_code]}) $http_msg");
}
return $result;
}
/**
* Factory.
*
* @return BaseLoader $this
*/
public static function create() {
$clazz = get_called_class();
return new $clazz();
}
abstract function load();
}
<file_sep>/server/Loader/CbrfLoader.php
<?php
namespace Loader;
use Model;
class CbrfLoader extends BaseLoader {
static function _parseXmlVal($data, $timestamp){
$valute = array();
for ($i=0; $i < count($data); $i++) {
$valute[$data[$i]["tag"]] = $data[$i]["value"];
}
if(DEBUG) var_export($valute);
$price = floatval(str_replace(',', '.', str_replace('.', '', $valute['Value'])));
return new Model\StockItem(array(
'source' => 'CBRF',
'code' => $valute['CharCode'],
'faceValue' => $valute['Nominal'],
'currency' => 'RUB',
'open' => $price,
'last' => $price,
'high' => $price,
'low' => $price,
'timestamp' => $timestamp,
));
}
static function parseXml($xml){
$parser = xml_parser_create ('');
xml_parser_set_option ( $parser, XML_OPTION_CASE_FOLDING, 0 );
xml_parser_set_option ( $parser, XML_OPTION_SKIP_WHITE, 1 );
xml_parse_into_struct ( $parser, $xml, $values, $tags );
xml_parser_free ( $parser );
// if(DEBUG){
// var_export($values);
// var_export($tags);
// die;
// }
$timestamp = 0;
$stockItems = array();
foreach ( $tags as $key => $ranges ) {
if ($key == 'ValCurs') {
$timestamp = self::makeTimestamp($values[$ranges[0]]['attributes']['Date'], '!d.m.Y');
// if(DEBUG) var_export(Date('r', $timestamp));
} elseif ($key == 'Valute') {
for($i = 0; $i < count ( $ranges ); $i += 2) {
$offset = $ranges [$i] + 1;
$len = $ranges [$i + 1] - $offset;
$stockItems[] = self::_parseXmlVal( array_slice ( $values, $offset, $len ), $timestamp );
}
}
}
return $stockItems;
}
public function load(){
$url = 'http://www.cbr.ru/scripts/XML_daily.asp';
$result_last = self::wget($url);
if(DEBUG) var_export($result_last);
$rates = array();
if( $result_last['errno'] != 0 ){
// error: bad url, timeout, redirect loop…
}elseif( $result_last['http_code'] != 200 ){
// error: no page, no permissions, no service…
}else{
$rates = self::parseXml($result_last['content']);
if(DEBUG) var_export($rates);
return ;
$json = preg_replace(array(
'/^[^{]+/',
'/[^}]+$/',
), array(
'',
'',
), $result['content']);
$json = json_decode($json, true);
$ids = $values = array();
foreach($json['securities']['data'] as $val){
if( substr($val[2], -4) == '_TOM' ){
$ids[$val[0]] = $val[2];
$values[$val[0]] = $val[6];
}
}
foreach($json['marketdata']['data'] as $val){
if( isset($ids[$val[20]]) && isset($val[7]) && isset($val[8]) ){
$rates[] = new Model\StockItem(array(
'source' => 'MOEX',
'code' => substr($ids[$val[20]], 0, 3),
'faceValue' => $values[$val[20]],
'currency' => substr($ids[$val[20]], 3, 3),
'open' => $val[7],
'last' => $val[8],
'high' => $val[5],
'low' => $val[6],
'timestamp' => self::makeTimestamp($val[39]),
));
}
}
// if(DEBUG) var_export($rates);
}
return $rates;
}
}
<file_sep>/server/RestApi/Rates.php
<?php
namespace RestApi;
class Rates {
/**
* @return array
*/
public function getLast(){
global $stockItems;
$filter = 'RUB';
$data = array();
$mtime = 0;
if(!empty($stockItems)){
$data['fields'] = array_keys((array) $stockItems[0]);
$data['values'] = array();
foreach ($stockItems as $val){
if( $val->currency === $filter ){
$data['values'][] = array_values((array) $val);
$mtime = max($mtime, $val->timestamp);
}
}
}
if (!HttpUtils::addHeader_LastModified($mtime, true)
// || !HttpUtils::addHeader_expires(5 * 60)
|| !HttpUtils::addHeader_ETag($data, true))
die;
return $data;
}
}<file_sep>/app/src/main/java/com/khrolenok/rates/ui/WidgetProvider.java
/*
* Copyright (c) 2015 <NAME>” Khrolenok
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.khrolenok.rates.ui;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.widget.RemoteViews;
import com.khrolenok.rates.BuildConfig;
import com.khrolenok.rates.ExRatesApplication;
import com.khrolenok.rates.ExRatesGroup;
import com.khrolenok.rates.R;
import com.khrolenok.rates.Settings;
import com.khrolenok.rates.util.PreferencesManager;
import com.khrolenok.rates.util.UpdateService;
import org.json.JSONObject;
import java.util.Date;
import java.util.List;
import trikita.log.Log;
/**
* Implementation of App Widget functionality.
*/
public class WidgetProvider extends AppWidgetProvider {
protected static boolean sIsLongFormat;
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
ExRatesApplication.initApplication(context);
// Try to start update service
UpdateService.notifyUpdateNeeded(context);
}
@Override
public void onUpdate(Context context, AppWidgetManager widgetManager, int[] widgetIds) {
// Track widgets count
ExRatesApplication.getInstance().trackEvent("Widget", "Count", "" + widgetIds.length);
// There may be multiple widgets active, so update all of them
for( int widgetId : widgetIds ) {
final Bundle options = widgetManager.getAppWidgetOptions(widgetId);
widgetManager.updateAppWidget(widgetId, buildLayout(context, widgetId, options));
}
}
@Override
public void onAppWidgetOptionsChanged(Context context, AppWidgetManager widgetManager,
int widgetId, Bundle newOptions) {
// Instruct the widget manager to update the widget
widgetManager.updateAppWidget(widgetId,
buildLayout(context, widgetId, newOptions));
super.onAppWidgetOptionsChanged(context, widgetManager, widgetId, newOptions);
}
@Override
public void onReceive(@NonNull Context context, @NonNull Intent intent) {
if( intent.getAction().equals(ExRatesApplication.ACTION_STOCKS_UPDATE) ){
final AppWidgetManager widgetManager = AppWidgetManager.getInstance(context);
final int[] widgetIds = widgetManager.getAppWidgetIds(new ComponentName(context, WidgetProvider.class));
onUpdate(context, widgetManager, widgetIds);
return;
}
super.onReceive(context, intent);
}
/**
* Returns number of cells needed for given size of the widget.
*
* @param size Widget size in dp.
* @return Size in number of cells.
*/
protected static int getCellsForSize(int size) {
int n = 2;
while( 70 * n - 30 < size ){
++n;
}
return n - 1;
}
/**
* Returns layout for widget.
*
* @param context Application mContext
* @param widgetId Widget ID
* @param options Widget options
* @return Widget layout
*/
public static RemoteViews buildLayout(Context context, int widgetId, Bundle options) {
if( BuildConfig.DEBUG ) Log.v("Rebuilding widget #" + widgetId + " layout");
final int widgetMinWidth = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH);
final int widgetMinHeight = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT);
final int wCells = getCellsForSize(widgetMinWidth);
final int hCells = getCellsForSize(widgetMinHeight);
final int widgetLayout = ( wCells > hCells ? R.layout.widget_layout_h
: R.layout.widget_layout_v );
final boolean isUseCompactView = ( widgetLayout == R.layout.widget_layout_h
? ( wCells <= 3 ) : ( wCells <= 1 ) );
final boolean isShowChange = ( widgetLayout == R.layout.widget_layout_v && wCells >= 2 );
final PreferencesManager prefs = PreferencesManager.getInstance();
final boolean prefsLong = prefs.getBoolean(PreferencesManager.PREF_LONG_FORMAT, false);
sIsLongFormat = prefsLong
&& ( widgetLayout == R.layout.widget_layout_h && wCells >= 4
|| widgetLayout == R.layout.widget_layout_v && wCells >= 2 );
// Track widget settings
ExRatesApplication.getInstance().trackEvent("Widget", "Size", "Width_" + wCells);
ExRatesApplication.getInstance().trackEvent("Widget", "Size", "Height_" + hCells);
ExRatesApplication.getInstance().trackEvent("Widget", "Size", wCells + "×" + hCells);
ExRatesApplication.getInstance().trackEvent("Widget", "NumFormat", (prefsLong ? "Long" : "Short"));
List<String> ratesList = prefs.getStocksList();
if( ratesList.isEmpty() ){
return new RemoteViews(context.getPackageName(), R.layout.widget_layout_loading);
}
JSONObject ratesJson;
try{
ratesJson = new JSONObject(prefs.getStockData());
} catch( Exception ignored ){
return new RemoteViews(context.getPackageName(), R.layout.widget_layout_loading);
}
RemoteViews widget = new RemoteViews(context.getPackageName(), widgetLayout);
widget.removeAllViews(R.id.rates);
Date updateTS = new Date(0);
widget.addView(R.id.rates,
buildRatesGroup(context, context.getString(R.string.title_official) + ":", ratesJson,
ratesList, Settings.Rates.Groups.OFFICIAL, isUseCompactView, isShowChange,
updateTS));
if( wCells >= 2 || hCells >= 2 ){
widget.addView(R.id.rates,
buildRatesGroup(context, context.getString(R.string.title_stock) + ":", ratesJson,
ratesList, Settings.Rates.Groups.STOCK, isUseCompactView, isShowChange,
updateTS));
}
if( wCells >= 3 || hCells >= 2 ){
widget.addView(R.id.rates,
buildRatesGroup(context, context.getString(R.string.title_forex) + ":", ratesJson,
ratesList, Settings.Rates.Groups.FOREX, isUseCompactView, isShowChange,
updateTS));
}
// Show updating timestamp
final String updateTextPrefix = ( wCells >= 2 ? context.getString(R.string.text_updated) : "" );
final int updateTextFormatFlags = android.text.format.DateUtils.FORMAT_SHOW_DATE
| android.text.format.DateUtils.FORMAT_SHOW_TIME
| android.text.format.DateUtils.FORMAT_ABBREV_ALL;
final String updateText = updateTextPrefix + " "
+ android.text.format.DateUtils.formatDateTime(context, updateTS.getTime(),
updateTextFormatFlags);
widget.setTextViewText(R.id.updateTimestamp, updateText);
Intent appIntent = new Intent(context, MainActivity.class);
PendingIntent appPendingIntent = PendingIntent.getActivity(context, 0, appIntent, 0);
widget.setOnClickPendingIntent(R.id.widget, appPendingIntent);
return widget;
}
protected static RemoteViews buildRatesGroup(Context context, String caption,
JSONObject ratesJson, List<String> ratesList, String ratesGroup,
boolean isUseCompactView, boolean isShowChange, Date updateTS) {
if( isUseCompactView ){
isShowChange = false;
}
ExRatesGroup exRatesGroup = new ExRatesGroup(caption, ratesGroup, ratesList, ratesJson);
exRatesGroup.isCompactTitleMode = isUseCompactView;
exRatesGroup.isLongFormat = sIsLongFormat;
exRatesGroup.calcViewsBounds(context);
final Date groupTS = exRatesGroup.getUpdateTS();
if( groupTS.after(updateTS) ){
updateTS.setTime(groupTS.getTime());
}
final PreferencesManager prefs = PreferencesManager.getInstance();
final boolean invertColors = prefs.getBoolean(PreferencesManager.PREF_INVERT_COLORS, false);
return exRatesGroup.buildWidgetViews(context, isShowChange, invertColors);
}
}
<file_sep>/server/exchange_rates.php
<?php
define('BASENAME', preg_replace('/(.+)\..*$/', '$1', basename(__FILE__)));
define('CACHE_FILE', BASENAME . '.hist');
define('CACHE_LIFE', 5 * 60); // 5 min
define('INTERNAL_COOKIE_FILE', 'cookies.txt');
define('INTERNAL_COOKIE_LIFE', 10000);
define('HISTORY_FILE', BASENAME . '.history');
define('HTTP_CODES_FILE', dirname(BASENAME) . '/http_codes.ini');
define('LOG_FILE', BASENAME . '.log');
header('Content-Type: text/plain; charset=UTF-8');
if( isset($_REQUEST['debug']) ){
define('DEBUG', true);
error_reporting(E_ALL);
ini_set('display_errors', true);
// print json_encode($exrates->getLastRates());
die();
}
define('DEBUG', false);
if( file_exists(CACHE_FILE) ){
$exrates = unserialize(file_get_contents(CACHE_FILE));
}else{
$exrates = new ExRates();
}
if( !file_exists(CACHE_FILE) || ( (filemtime(CACHE_FILE) + CACHE_LIFE) < time() ) ){
update_rates();
// if(DEBUG) app_log(var_export($rates, true));
file_put_contents(CACHE_FILE, serialize($exrates));
app_log('Rates updated');
}
$timestamp = filemtime(CACHE_FILE);
$tsstring = gmdate('D, d M Y H:i:s ', $timestamp) . 'GMT';
$etag = md5($timestamp);
$if_modified_since = !isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? false : $_SERVER['HTTP_IF_MODIFIED_SINCE'];
$if_none_match = !isset($_SERVER['HTTP_IF_NONE_MATCH']) ? false : $_SERVER['HTTP_IF_NONE_MATCH'];
if ( ( !$if_none_match || ($if_none_match && $if_none_match == $etag) ) &&
($if_modified_since && $if_modified_since == $tsstring) ) {
header('HTTP/1.1 304 Not Modified');
exit;
} else {
header("Last-Modified: $tsstring");
header("ETag: \"$etag\"");
print json_encode($exrates->getLastRates());
}
class ExRates {
public $rates;
function __construct(){
$this->rates = array();
}
function setRate($timestamp, $group, $currency, $good, $face_value, $bid_open, $bid_last, $bid_high = -1, $bid_low = -1){
$group = strtoupper($group);
$currency = strtoupper($currency);
$good = strtoupper($good);
$date = date('Y_z', $timestamp);
if( !is_array($this->rates) ){
$this->rates = array();
}
if( !isset($this->rates[$group]) || !is_array($this->rates[$group]) ){
$this->rates[$group] = array();
ksort($this->rates);
}
if( !isset($this->rates[$group][$good]) || !is_array($this->rates[$group][$good]) ){
$this->rates[$group][$good] = array();
ksort($this->rates[$group]);
}
if( !isset($this->rates[$group][$good][$currency]) || !is_array($this->rates[$group][$good][$currency]) ){
$this->rates[$group][$good][$currency] = array();
ksort($this->rates[$group][$good]);
}
if( !isset($this->rates[$group][$good][$currency][$date])
|| !is_array($this->rates[$group][$good][$currency][$date])
|| $this->rates[$group][$good][$currency][$date][3] < $timestamp ){
$this->rates[$group][$good][$currency][''] = $date;
$this->rates[$group][$good][$currency][$date] = array(
$group, // 0
$good, // 1
$currency, // 2
$timestamp, // 3
$face_value, // 4
$bid_open, // 5
$bid_last, // 6
$bid_high, // 7
$bid_low, // 8
);
}
}
function getLastRates(){
$last_rates = array();
foreach($this->rates as $group_key => $groups){
foreach($groups as $good_key => $goods){
foreach($goods as $currency_key => $curr){
$last_rates[$group_key.'_'.$good_key.'_'.$currency_key] = $curr[$curr['']];
}
}
}
return $last_rates;
}
}
function make_timestamp($datetime, $format = 'Y-m-d H:i:s'){
try {
$date = DateTime::createFromFormat($format, $datetime);
} catch (Exception $e) {
$msg = $e->getMessage();
app_log($msg);
if(DEBUG) var_export($msg);
}
if( empty($date) ){
$date = new DateTime('today');
}
return $date->getTimestamp();
}
function app_log($msg){
if(DEBUG){
$msg = "DEBUG\t" . $msg;
}
error_log(date('Y-m-d H:i:s') . "\t$msg\n", 3, LOG_FILE);
}
function fix_rates($old_rates){
$values = array();
$rates = $old_rates;
foreach( $old_rates as $key => $val ){
$from = substr($key, 0, 3);
$new_key = substr($key, 3, 3) . $from . substr($key, 6);
if( $from == "RUB" && !isset($rates[$new_key]) ){
$key = $new_key;
$val[3] = 1 / $val[3];
$val[4] = 1 / $val[4];
$rates[$key] = $val;
}
}
foreach( $rates as $key => $val ){
$key = substr($key, 0, 3);
if( $values[$key] < $val[2] )
$values[$key] = $val[2];
}
foreach( $rates as $key => $val ){
$from = substr($key, 0, 3);
if( isset($values[$from]) && ($values[$from] != $val[2]) ){
$val[3] = $val[3] * $values[$from] / $val[2];
$val[4] = $val[4] * $values[$from] / $val[2];
$val[2] = $values[$from];
$rates[$key] = $val;
}
}
return $rates;
}
function update_rates(){
global $exrates;
$update = array();
$update = array_merge($update, get_moex_rates());
$update = array_merge($update, get_cbr_rates());
$update = array_merge($update, get_forex_rates());
$update = array_merge($update, get_commodities_rates());
$update = fix_rates($update);
// app_log(var_export($update, true));
foreach($update as $key => $val){
$exrates->setRate($val[1], $val[0], $val[7], $val[8], $val[2], $val[3], $val[4], $val[5], $val[6]);
}
}
/**
* Get a web file (HTML, XHTML, XML, image, etc.) from a URL. Return an
* array containing the HTTP server response header fields and content.
*/
function get_web_page( $url ){
$user_agent='Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0';
// Delete cookie file periodically
if( rand(0, INTERNAL_COOKIE_LIFE) === 0 ){
unlink(INTERNAL_COOKIE_FILE);
app_log('Internal cookie file deleted');
}
$options = array(
CURLOPT_CUSTOMREQUEST => 'GET', //set request type post or get
CURLOPT_POST => false, //set to GET
CURLOPT_USERAGENT => $user_agent, //set user agent
CURLOPT_COOKIEFILE => INTERNAL_COOKIE_FILE, //set cookie file
CURLOPT_COOKIEJAR => INTERNAL_COOKIE_FILE, //set cookie jar
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => '', // handle all encodings
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$result = curl_getinfo( $ch );
curl_close( $ch );
$result['errno'] = $err;
$result['errmsg'] = $errmsg;
$result['content'] = $content;
// app_log("HTTP-Request: $url");
if( $result['errno'] != 0 ){
// error: bad url, timeout, redirect loop…
app_log("HTTP-Request: $url");
app_log("Error: ({$result[errno]}) {$result[errmsg]}");
}elseif( $result['http_code'] != 200 ){
// error: no page, no permissions, no service…
static $http_codes = null;
if($http_codes == null){
$http_codes = parse_ini_file(HTTP_CODES_FILE);
}
$http_msg = $http_codes[$result['http_code']];
app_log("HTTP-Request: $url");
app_log("HTTP-Error: ({$result[http_code]}) $http_msg");
}
return $result;
}
function get_moex_rates(){
$hash = sha1(date('r'));
$timestamp = time();
$url = "http://www.moex.com/iss/engines/currency/markets/selt/securities.json?iss.meta=off&iss.only=securities%2Cmarketdata&securities=CETS%3AUSD000UTSTOM%2CCETS%3AEUR_RUB__TOM%2CCETS%3AEURUSD000TOM%2CCETS%3ACNYRUB_TOM%2CCETS%3AKZT000000TOM%2CCETS%3AUAH000000TOM%2CCETS%3ABYRRUB_TOM%2CCETS%3AHKDRUB_TOM%2CCETS%3AGBPRUB_TOM&lang=ru&_=$timestamp";
$result = get_web_page($url);
// if(DEBUG) var_export($result);
$rates = array();
if( $result['errno'] != 0 ){
// error: bad url, timeout, redirect loop…
}elseif( $result['http_code'] != 200 ){
// error: no page, no permissions, no service…
}else{
$json = preg_replace(array(
'/^[^{]+/',
'/[^}]+$/',
), array(
'',
'',
), $result['content']);
$json = json_decode($json, true);
// if(DEBUG) var_export($json);
$ids = $values = array();
foreach($json['securities']['data'] as $val){
if( substr($val[2], -4) == '_TOM' ){
$ids[$val[0]] = $val[2];
$values[$val[0]] = $val[6];
}
}
// if(DEBUG) var_export($ids);
foreach($json['marketdata']['data'] as $val){
if( isset($ids[$val[20]]) && isset($val[7]) && isset($val[8]) ){
$rates[$ids[$val[20]]] = array( // Cross name
"STK", // 0 - Cross type
make_timestamp($val[39]), // 1 - Timestamp
$values[$val[20]], // 2 - Face value
$val[7], // 3 - Bid on open
$val[8], // 4 - Last bid
$val[5], // 5 - High bid
$val[6], // 6 - Low bid
substr($ids[$val[20]], 3, 3), // 7 - Cross curr
substr($ids[$val[20]], 0, 3), // 8 - Cross good
);
}
}
// if(DEBUG) var_export($rates);
}
return $rates;
}
function cbr_parse_table($content){
preg_match('|<h2>Центральный банк Российской Федерации установил с ([\d\.]+)|uSis', $content, $m);
// if(DEBUG) var_export($m[0]);
// Convert dd.mm.yyyy to yyyy-mm-dd
$timestamp = make_timestamp($m[1], 'd.m.Y');
preg_match('|<table class="data">.+?</table>|uSis', $content, $m);
// if(DEBUG) var_export($m[0]);
preg_match_all('|<tr><td>.+?</td>\s*<td>(.+?)</td>\s*<td>(.+?)</td>\s*<td>.+?</td>\s*<td>(.+?)</td>\s*|uSis', $m[0], $matches, PREG_SET_ORDER);
// if(DEBUG) var_export($matches);
$rates = array();
foreach($matches as $m){
$rates[$m[1] . 'RUB_CBR'] = array( // Cross name
"CBR", // Cross type
$timestamp, // Timestamp
intval($m[2]), // Face value
floatval(strtr($m[3], ',', '.')), // Bid
);
}
// if(DEBUG) var_export($rates);
// if(DEBUG) app_log(var_export($rates, true));
return $rates;
}
// Альтернатива: http://www.cbr.ru/scripts/XML_daily.asp?date_req=07.09.2015
// и для последней даты http://www.cbr.ru/scripts/XML_daily.asp
function get_cbr_rates(){
$url = "http://www.cbr.ru/currency_base/daily.aspx?date_req=";
$result_open = get_web_page($url . date("d.m.Y"));
$result_last = get_web_page($url . date("d.m.Y", time() + 86400));
// if(DEBUG) var_export($result_open);
// if(DEBUG) var_export($result_last);
$rates = array();
if( $result_open['errno'] != 0 ){
// error: bad url, timeout, redirect loop…
}elseif( $result_open['http_code'] != 200 ){
// error: no page, no permissions, no service…
}else{
$rates = cbr_parse_table($result_open['content']);
// if(DEBUG) var_export($rates);
$tmp = cbr_parse_table($result_last['content']);
foreach($tmp as $key => $val){
// If new CBR rates not set, leave last rates unchanged
if( $rates[$key][1] == $val[1] ){
app_log('Tomorrow CBR rates for ' . $key . ' currently are not set.');
unset($rates[$key]);
}
$rates[$key][4] = $val[3]; // Last bid
$rates[$key][5] = max($val[3], $rates[$key][3]); // High bid
$rates[$key][6] = min($val[3], $rates[$key][3]); // Low bid
$rates[$key][7] = substr($key, 3, 3); // 7 - Cross curr
$rates[$key][8] = substr($key, 0, 3); // 8 - Cross good
}
// if(DEBUG) var_export($rates);
// if(DEBUG) app_log(var_export($rates, true));
}
return $rates;
}
// Альтернатива: http://partners.instaforex.com/ru/quotes_description.php/
function get_forex_rates(){
$url = "http://fxrates.ru.forexprostools.com/index_single_crosses.php?currency=79&bid=hide&ask=hide&last=show&change=hide&change_in_percents=hide&last_update=show";
$result = get_web_page($url);
// if(DEBUG) var_export($result);
$rates = array();
if( $result['errno'] != 0 ){
// error: bad url, timeout, redirect loop…
}elseif( $result['http_code'] != 200 ){
// error: no page, no permissions, no service…
}else{
preg_match('|<table id="cross_rate_1".+?</table>|uSis', $result['content'], $m);
// if(DEBUG) var_export($m[0]);
preg_match_all('|<span class="ftqa11bb arial_11_b">([^<]+)</span></td></nobr><td class="[^>]+>([^<]+)</td><td class="[^>]+>([^<]+)</td><td class="[^>]+>([^<]+)</td><td class="[^>]+>([^<]+)</td><td class="[^>]+>([^<]+)</td></tr>|uSis', $m[0], $matches, PREG_SET_ORDER);
// if(DEBUG) var_export($matches);
// if(DEBUG) app_log(var_export($matches, true));
foreach($matches as $m){
$rates[str_replace('/', '', $m[1]) . '_FRX'] = array( // Cross name
"FRX", // 0 — Cross type
make_timestamp($m[6], 'H:i:s'), // 1 — Timestamp
1, // 2 — Face value
floatval($m[3]), // 3 — Bid on open
floatval($m[2]), // 4 — Last bid
floatval($m[4]), // 5 — High bid
floatval($m[5]), // 6 — Low bid
substr($m[1], 4, 3), // 7 — Cross curr
substr($m[1], 0, 3), // 8 — Cross good
);
}
// if(DEBUG) var_export($rates);
}
return $rates;
}
// Альтернатива: https://www.quandl.com/resources/commodity-data#Commodity-Dashboards
function get_commodities_rates(){
$url = "http://comrates.investing.com/index.php?force_lang=1&pairs_ids=8830;8831;8833;8836;8910;&open=show&month=hide&change=hide&change_in_percents=hide&last_update=show";
$result = get_web_page($url);
// if(DEBUG) var_export($result);
$rates = array();
if( $result['errno'] != 0 ){
// error: bad url, timeout, redirect loop…
}elseif( $result['http_code'] != 200 ){
// error: no page, no permissions, no service…
}else{
preg_match('|<table id="cross_rate_1".+?</table>|uSis', $result['content'], $m);
// if(DEBUG) var_export($m[0]);
preg_match_all('|<span class="ftqa11bb arial_11_b">([^<]+)</span></td></nobr><td class="[^>]+>([^<]+)</td><td class="[^>]+>([^<]+)</td><td class="[^>]+>([^<]+)</td><td class="[^>]+>([^<]+)</td><td class="[^>]+>([^<]+)</td></tr>|uSis', $m[0], $matches, PREG_SET_ORDER);
// if(DEBUG) var_export($matches);
// if(DEBUG) app_log(var_export($matches, true));
static $codes = array(
'Gold' => 'GCZ15',
'Silver' => 'SIQ15',
'Copper' => 'HGQ15',
'Platinum' => 'PLQ15',
'Brent Oil' => 'LCOV5',
);
foreach($matches as $m){
$rates[$codes[$m[1]] . '_CMM'] = array( // Cross name
"CMM", // 0 — Cross type
make_timestamp($m[6], 'H:i:s'), // 1 — Timestamp
1, // 2 — Face value
floatval($m[3]), // 3 — Bid on open
floatval($m[2]), // 4 — Last bid
floatval($m[4]), // 5 — High bid
floatval($m[5]), // 6 — Low bid
'USD', // 7 — Cross curr
$codes[$m[1]], // 8 — Cross good
);
}
// if(DEBUG) var_export($rates);
}
return $rates;
}
<file_sep>/build.gradle
/*
* Copyright (c) 2015 Andrey “Limych” Khrolenok
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.3.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
maven { url "https://jitpack.io" }
}
}
// get variables && prevent crashing if missing
String safeGet(String name, String defaultValue = '') {
hasProperty(name) ? project[name] : defaultValue
}
File safeGetFile(String name) {
String fileName = safeGet(name, null)
fileName != null ? file(fileName) : null
}
// loads variables from a file to `project` so they can be `safeGet`-ed later
def safeLoad(String name, Object value, Boolean override = false) {
if (!hasProperty(name) || override)
project.set name, value
}
Integer getBuildVersion(defaultVersion, Boolean increment = false) {
File verFile = file('version.properties')
if (!verFile.canRead())
verFile.createNewFile()
Properties props = new Properties()
props.load new FileInputStream(verFile)
String currentCodeVersion = props['VERSION_CODE']
if (currentCodeVersion == null)
currentCodeVersion = defaultVersion ?: 1
if (increment) {
Integer bumpedCodeVersion = currentCodeVersion.toInteger() + 1
props['VERSION_CODE'] = bumpedCodeVersion.toString()
props.store verFile.newWriter(), "Build version updated with each release build"
currentCodeVersion = bumpedCodeVersion
}
currentCodeVersion as Integer
}
<file_sep>/app/src/main/java/com/khrolenok/rates/util/PreferencesManager.java
/*
* Copyright (c) 2015 <NAME>” Khrolenok
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.khrolenok.rates.util;
import android.content.Context;
import java.util.ArrayList;
public class PreferencesManager {
// Public preferences
public static final String PREF_STOCKS_LIST = "stocksList";
public static final String PREF_INVERT_COLORS = "invert_colors";
public static final String PREF_LONG_FORMAT = "long_format";
public static final String PREF_WIFI_ONLY = "wifi_only";
// Private preferences
public static final String PREF_STOCKS_DATA = "_stocksData";
public static final String PREF_UPDATE_TIME = "_updateTime";
private static PreferencesManager prefsManager;
private TinyDB tinyDB;
public static synchronized PreferencesManager getInstance() {
if( prefsManager == null ){
prefsManager = new PreferencesManager();
}
return prefsManager;
}
public void init(Context context) {
tinyDB = new TinyDB(context);
}
public boolean contains(String key) {
return tinyDB.contains(key);
}
public void addStockSymbol(String stockSymbol) {
ArrayList<String> stocksList = tinyDB.getListString(PREF_STOCKS_LIST);
stocksList.add(stockSymbol);
tinyDB.putListString(PREF_STOCKS_LIST, stocksList);
}
public void removeStockSymbol(String stockSymbol) {
ArrayList<String> stocksList = tinyDB.getListString(PREF_STOCKS_LIST);
stocksList.remove(stockSymbol);
tinyDB.putListString(PREF_STOCKS_LIST, stocksList);
}
public boolean stocksListContains(String stockSymbol) {
ArrayList<String> stocksList = tinyDB.getListString(PREF_STOCKS_LIST);
return stocksList.contains(stockSymbol);
}
public ArrayList<String> getStocksList() {
return tinyDB.getListString(PREF_STOCKS_LIST);
}
public void setStocksList(ArrayList<String> stocksList) {
tinyDB.putListString(PREF_STOCKS_LIST, stocksList);
}
public void setBoolean(String key, boolean value) {
tinyDB.putBoolean(key, value);
}
public boolean getBoolean(String key, boolean defaultValue) {
return tinyDB.getBoolean(key, defaultValue);
}
public void setStockData(String stocksData) {
tinyDB.putString(PREF_STOCKS_DATA, stocksData);
}
public String getStockData() {
return tinyDB.getString(PREF_STOCKS_DATA);
}
public void setUpdateTime(long value) {
tinyDB.putLong(PREF_UPDATE_TIME, value);
}
public long getUpdateTime() {
return tinyDB.getLong(PREF_UPDATE_TIME, 0);
}
}
| 980f8db780917398ac6d1410a95583616462a396 | [
"Java",
"PHP",
"INI",
"Gradle"
] | 21 | PHP | Limych/Rates | 47d040321e95364abd116a2a7471ce900b24d65b | 9196dcd1fedf6b270f03744b3158cdacf2dac27a | |
refs/heads/master | <file_sep>require "wiringpi_kb_adapter/version"
module WiringpiKbAdapter
begin
require 'wiringpi'
rescue LoadError
require File.expand_path('../wiring_pi', __FILE__)
end
end
<file_sep>require 'spec_helper'
module WiringPi
describe GPIO do
let(:input_pins) { {goal_a: 0, goal_b: 3, start: 4} }
let(:output_pins) { {led: 7} }
let(:subject) { GPIO.new(:input_pins => input_pins, :output_pins => output_pins) }
# attr_readers
%w[input_pins output_pins mode_pins].each do |method|
it { should respond_to method }
end
%w[mode write readAll].each do |method|
it { should respond_to method}
end
describe '#readAll' do
context 'when no key is pressed' do
before { subject.stub :getch => nil }
it { subject.readAll.should be_a Hash }
it 'returns a hash with default values set to 1' do
subject.readAll[:something].should == 1
end
end
context 'when no pin associated character is pressed' do
before { subject.stub :getch => 'A' }
it 'adds no pair to the hash' do
subject.readAll.size.should be_zero
end
end
context 'when a pin associated character is pressed' do
before { subject.stub :getch => '4' }
it 'adds the expected pair to the hash' do
subject.readAll.size.should_not be_zero
end
it 'sets the pin value in the hash to zero' do
h = subject.readAll
puts h.inspect
h[4].should be_zero
end
end
end
end
end<file_sep>source 'https://rubygems.org'
# Specify your gem's dependencies in wiringpi_kb_adapter.gemspec
gemspec
<file_sep>require_relative '../lib/wiringpi_kb_adapter'
<file_sep>INPUT = $stdin
OUTPUT = $stdout
WPI_MODE_PINS = Object.new
require 'curses'
module WiringPi
def puts(message)
Curses.addstr message
end
class Serial
def initialize(*args)
Curses.timeout = 0
Curses.noecho # do not show typed keys
Curses.init_screen
Curses.stdscr.keypad(true) # enable keypad
Curses.setpos(0, 0)
@serial_not_read = true
@serial_count = 0
end
def serialDataAvail
if @finished and !@serial_not_read
@finished = false
@serial_count = 0
@serial_not_read = true
end
@serial_not_read ? 1 : 0
end
def serialGetchar
char = (48..57).to_a.sample
if @serial_count > 4
@serial_not_read = false
@finished = true
end
@serial_count += 1
char
end
end
class GPIO
attr_reader :mode_pins, :input_pins, :output_pins
def initialize(opts={})
@input_pins = opts[:input_pins] or Table::INPUT_PINS
@output_pins = opts[:output_pins] or Table::OUTPUT_PINS
end
def mode(pin_number, io)
# only once
# set the mode operation of the pin, if input or output
end
def readAll
# the returned hash has 1 as value for all its keys by default
hash = Hash.new {|h, k| h[k] = 1}
char = getch
if char =~ /\d/
value = char.to_i
hash[value] = 0 if key = input_pins.key(value)
end
hash
end
def write(pin_number, value)
# puts "pin #{pin_number} is now #{value}"
end
private
def getch
Curses.getch
end
end
end
<file_sep>require 'spec_helper'
module WiringPi
describe GPIO do
let(:input_pins) { {goal_a: 0, goal_b: 3, start: 4} }
let(:output_pins) { {led: 7} }
let(:subject) { GPIO.new(:input_pins => input_pins, :output_pins => output_pins) }
%w[input_pins output_pins mode_pins mode_pins=].each do |method|
it { should respond_to method }
end
end
end | b2f6c47816cab0f603dfa572c752ce792b8a6d4f | [
"Ruby"
] | 6 | Ruby | spaghetticode/wiringpi_kb_adapter | 67da8572f46ad06bfb72c7826c9187a43a6755ea | b5a1d5de39c83c096f74b390cdbbb0d9badd82c1 | |
refs/heads/main | <file_sep>from django.db import models
from django.contrib.auth.models import User
TYPE_1=1
TYPE_2=2
TYPE_3=3
TYPE_4=4
TYPES = (
(TYPE_1, 'Bullet'),
(TYPE_2, 'Food'),
(TYPE_3, 'Travel'),
(TYPE_4, 'Sport'),
)
# Create your models here.
class BookJournalBase(models.Model):
name=models.CharField(max_length=255, verbose_name="название")
price=models.IntegerField(default=0, verbose_name='Стоимость')
description=models.TextField(null=True, blank=True, verbose_name="Описание")
created_at=models.DateTimeField(auto_now_add=True,verbose_name="Добавлен")
class Meta:
abstract = True
class Book(BookJournalBase):
num_pages=models.IntegerField(default=0, verbose_name='Количество страниц')
genre=models.CharField(max_length=255, verbose_name="Жанр")
class Journal(BookJournalBase):
type=models.SmallIntegerField(choices=TYPES, default=TYPE_1)
publisher=models.ForeignKey(User,on_delete=models.CASCADE,verbose_name="Владелец")<file_sep>from django.db import models
from django.contrib.auth.models import User
# Create your models here.
USER_1=1
USER_2=2
USER_ROLES=(
(USER_1, 'SuperAdmin'),
(USER_2, 'Guest'),
)
class Profile(models.Model):
user = models.OneToOneField(User,on_delete= models.CASCADE)
first_name = models.CharField( max_length=30, blank=True)
last_name = models.CharField( max_length=30, blank=True)
date_joined = models.DateTimeField( auto_now_add=True)
role = models.SmallIntegerField(choices=USER_ROLES, default=USER_2)
<file_sep>from django.urls import path
from . import views
from rest_framework import routers
router = routers.SimpleRouter()
router.register('books', views.BookViewSet, basename='book')
router.register('journals', views.JournalViewSet, basename='book')
app_name = "book"
urlpatterns = [
]
urlpatterns += router.urls<file_sep>from django.shortcuts import render
from .models import *
from rest_framework import generics, mixins, viewsets
from .serializers import BookSerializer, JournalSerializer
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.decorators import action
class BookViewSet(mixins.ListModelMixin,
mixins.CreateModelMixin,
mixins.UpdateModelMixin,
mixins.RetrieveModelMixin,
viewsets.ViewSet):
permission_classes = (IsAuthenticated,)
# queryset = Book.objects.all()
serializer_class = BookSerializer
def get_queryset(self):
return Book.objects.all()
def list(self, request):
serializer = BookSerializer(self.get_queryset(), many=True)
return Response(serializer.data)
class JournalViewSet(mixins.ListModelMixin,
mixins.CreateModelMixin,
mixins.UpdateModelMixin,
mixins.RetrieveModelMixin,
viewsets.ViewSet):
permission_classes = (IsAuthenticated,)
# queryset = Book.objects.all()
serializer_class = JournalSerializer
def get_queryset(self):
return Journal.objects.all()
def list(self, request):
serializer = JournalSerializer(self.get_queryset(), many=True)
return Response(serializer.data)<file_sep># Generated by Django 3.1.7 on 2021-03-20 05:46
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Book',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255, verbose_name='название')),
('price', models.IntegerField(default=0, verbose_name='Стоимость')),
('description', models.TextField(blank=True, null=True, verbose_name='Описание')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Добавлен')),
('num_pages', models.IntegerField(default=0, verbose_name='Количество страниц')),
('genre', models.CharField(max_length=255, verbose_name='Жанр')),
],
options={
'verbose_name': 'Книга',
'verbose_name_plural': 'Книги',
'abstract': False,
},
),
migrations.CreateModel(
name='Journal',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255, verbose_name='название')),
('price', models.IntegerField(default=0, verbose_name='Стоимость')),
('description', models.TextField(blank=True, null=True, verbose_name='Описание')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Добавлен')),
('type', models.SmallIntegerField(choices=[(1, 'Bullet'), (2, 'Food'), (3, 'Travel'), (4, 'Sport')], default=1)),
('publisher', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='Владелец')),
],
options={
'verbose_name': 'Книга',
'verbose_name_plural': 'Книги',
'abstract': False,
},
),
]
<file_sep>from django.contrib import admin
from .models import *
# Register your models here.
class BookAdmin(admin.ModelAdmin):
list_display = ['genre']
search_fields = ['genre']
class JournalAdmin(admin.ModelAdmin):
list_display = ['type','publisher']
search_fields = ['publisher']
admin.site.register(Book,BookAdmin)
admin.site.register(Journal,JournalAdmin)
<file_sep>from django.urls import path,include
from django.contrib.auth import views
app_name = 'auth'
urlpatterns = [
path('login/', views.LoginView.as_view(), name='login'),
] | 71fd8c476a9e823aeaf1049ee649ff8e84cf152a | [
"Python"
] | 7 | Python | ArystanIgen/Midterm | 386f0eb94f7d8d130b699b269936b563534a40da | 0a6924e50bf1c3fc6daa876f447f275c11ea279a | |
refs/heads/master | <file_sep>// Copyright (C) 2020 <NAME> <<EMAIL>>
//
// This file is part of libsurakarta.
//
// libsurakarta is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// libsurakarta is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libsurakarta. If not, see <https://www.gnu.org/licenses/>.
//
// Author: <NAME> <<EMAIL>>
#ifndef TEST_SURAKARTA_FACTORY_H_
#define TEST_SURAKARTA_FACTORY_H_
#include <skmodel.h>
#include <vector>
// Used to feed verbose instructions to SurakartaFactory to mock a position.
typedef struct ModelBlock {
sk::Player color;
int row;
int column;
int rowRange;
int columnRange;
ModelBlock(sk::Player color, int row, int column, int rowRange = 1,
int columnRange = 1) {
this->color = color;
this->row = row;
this->column = column;
this->rowRange = rowRange;
this->columnRange = columnRange;
}
} ModelBlock;
sk::Surakarta *createModel(std::vector<ModelBlock *> &arr);
#endif /* TEST_SURAKARTA_FACTORY_H_ */<file_sep>// Copyright (C) 2020 <NAME> <<EMAIL>>
//
// This file is part of libsurakarta.
//
// libsurakarta is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// libsurakarta is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libsurakarta. If not, see <https://www.gnu.org/licenses/>.
//
// Author: <NAME> <<EMAIL>>
#include "position.h"
#include <bit>
#include <vector>
#include "bitboard.h"
namespace sk {
Position::Position(sk::Surakarta& model) : options_(model.options_) {
player_bitboards_ = new sk::Bitboard[2];
player_bitboards_[0] = sk::createPlayerBitboard(model, sk::RED);
player_bitboards_[1] = sk::createPlayerBitboard(model, sk::BLACK);
count_red_ = std::__popcount(this->player_bitboards_[0]);
count_black_ = std::__popcount(this->player_bitboards_[1]);
side_to_move_ = RED;
}
Position::Position(const Position& copy) : options_(copy.options_) {
player_bitboards_ = new sk::Bitboard[2];
player_bitboards_[0] = copy.player_bitboards_[0];
player_bitboards_[1] = copy.player_bitboards_[1];
count_red_ = copy.count_red_;
count_black_ = copy.count_black_;
side_to_move_ = copy.side_to_move_;
}
Value Position::evaluate() {
// Each pebble has a value of 2, except those at corner (value = 1)
return (count_red_ - count_black_) * 2 //
- (player_bitboards_[0] & 1) + (player_bitboards_[1] & 1) //
- ((player_bitboards_[0] >> 5) & 1) +
((player_bitboards_[1] >> 5) & 1) //
- ((player_bitboards_[0] >> 30) & 1) +
((player_bitboards_[1] >> 30) & 1) //
- ((player_bitboards_[0] >> 35) & 1) +
((player_bitboards_[1] >> 35) & 1);
}
void Position::copyFrom(Position& pos) {
player_bitboards_[0] = pos.player_bitboards_[0];
player_bitboards_[1] = pos.player_bitboards_[1];
count_red_ = pos.count_red_;
count_black_ = pos.count_black_;
}
void Position::move(Move move) {
Square start_sq =
CreateSquare(GetMoveStartRow(move), GetMoveStartColumn(move));
Square final_sq =
CreateSquare(GetMoveFinalRow(move), GetMoveFinalColumn(move));
if (HasPlayer(GetRedPlayerBitboard(), start_sq)) {
LiftPlayer(player_bitboards_[0], start_sq);
PutPlayer(player_bitboards_[0], final_sq);
if (HasPlayer(GetBlackPlayerBitboard(), final_sq)) {
--count_black_;
LiftPlayer(player_bitboards_[1], final_sq);
}
side_to_move_ = BLACK;
} else if (HasPlayer(GetBlackPlayerBitboard(), final_sq)) {
LiftPlayer(player_bitboards_[1], start_sq);
PutPlayer(player_bitboards_[1], final_sq);
if (HasPlayer(GetRedPlayerBitboard(), final_sq)) {
--count_red_;
LiftPlayer(player_bitboards_[0], start_sq);
}
side_to_move_ = RED;
}
}
} // namespace sk<file_sep>// Copyright (C) 2020 <NAME> <<EMAIL>>
//
// This file is part of libsurakarta.
//
// libsurakarta is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// libsurakarta is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libsurakarta. If not, see <https://www.gnu.org/licenses/>.
//
// Author: <NAME> <<EMAIL>>
// This file defines all the simple types used in the libsurakarta engine.
#ifndef INCLUDE_SKTYPES_H_
#define INCLUDE_SKTYPES_H_
#include <stdint.h>
namespace sk {
// Bitboard representation of a Surakarta position. The "on" bits indicate
// whether a given type of piece is placed on the corresponding squares.
typedef uint64_t Bitboard;
typedef int Square;
inline Square CreateSquare(int row, int column) { return (row * 6 + column); }
// Evaluation of a given position - +ve values indicate RED has the advantage,
// while -ve values indicate BLACK has the advantage.
typedef int Value;
} // namespace sk
#endif /* INCLUDE_SKTYPES_H_ */<file_sep>// Copyright (C) 2020 <NAME> <<EMAIL>>
//
// This file is part of libsurakarta.
//
// libsurakarta is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// libsurakarta is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libsurakarta. If not, see <https://www.gnu.org/licenses/>.
// Author: <NAME> <<EMAIL>>
#include <skengine.h>
#include <thread>
#include "context.h"
#include "movegen.h"
#include "position.h"
namespace sk {
// simple negamax
int DeepEvaluate(Context& context) {
if (context.depth == kMaxDepth) {
return context.position.evaluate();
}
Position& pos = context.position;
std::vector<Move> move_list = GenerateMoves(pos);
Move best_move = 0;
int best_eval = -1000000;
Context child_cxt;
child_cxt.depth = context.depth + 1;
child_cxt.position.copyFrom(pos);
for (std::vector<Move>::iterator mitr = move_list.begin();
mitr != move_list.end(); mitr++) {
Move move = *mitr;
child_cxt.position.move(move);
int eval = -DeepEvaluate(child_cxt);
child_cxt.position.copyFrom(pos);
if (eval > best_eval) {
best_eval = eval;
best_move = move;
}
}
return best_eval;
}
Move Think(Surakarta& rootModel, EngineOptions& eg_options) {
Context root_context;
Position rootPos(rootModel);
root_context.position.copyFrom(rootPos);
root_context.depth = 0;
int best_move = 0;
int best_eval = -10000;
std::vector<Move> move_list = GenerateMoves(rootPos);
for (std::vector<Move>::iterator mitr = move_list.begin();
mitr != move_list.end(); mitr++) {
Move move = *mitr;
int value = DeepEvaluate(root_context);
if (value > best_eval) {
best_move = move;
best_eval = value;
}
}
return best_move;
}
} // namespace sk<file_sep>[](https://dev.azure.com/SurakartaArcade/Surakarta/_build/latest?definitionId=3&branchName=master)
# libsurakarta
C++ implementation of a Surakarta computer engine
<file_sep>// Copyright (C) 2020 <NAME> <<EMAIL>>
//
// This file is part of libsurakarta.
//
// libsurakarta is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// libsurakarta is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libsurakarta. If not, see <https://www.gnu.org/licenses/>.
// Author: <NAME> <<EMAIL>>
#include "movegen.h"
#include "bitboard.h"
namespace sk {
// Generates a method that will add a Move into a vector if the final
// square is empty (given the initial square). The final square is calculated
// by adding sq_delta (similar for final row & final column)
#define GEN_STEP(name, sq_delta, row_delta, column_delta) \
inline void name(std::vector<Move> bfr, const Bitboard& bb, Square sq, \
int row, int column) { \
if (HasPlayer(bb, sq + sq_delta)) { \
bfr.push_back(CreateMove(row, column, row + row_delta, \
column + column_delta)); \
} \
}
GEN_STEP(StepNorthWest, -7, -1, -1)
GEN_STEP(StepNorth, -6, -1, 0)
GEN_STEP(StepNorthEast, -5, -1, +1)
GEN_STEP(StepWest, -1, 0, -1)
GEN_STEP(StepEast, +1, 0, +1)
GEN_STEP(StepSouthWest, +5, +1, -1)
GEN_STEP(StepSouth, +6, +1, 0)
GEN_STEP(StepSouthEast, +7, +1, +1)
// Generates three Step* calls (used for corners which have 3 freedoms)
#define TOUCH_CORNER(bfr, bb, square, row, column, f1, f2, f3) \
{ \
f1(bfr, bb, square, row, column); \
f2(bfr, bb, square, row, column); \
f3(bfr, bb, square, row, column); \
}
// Generates five Step* calls (used for edge squares which have five freedoms)
#define TOUCH_EDGE(bfr, bb, square, row, column, f1, f2, f3, f4, f5) \
{ \
TOUCH_CORNER(bfr, bb, square, row, column, f1, f2, f3); \
f4(bfr, bb, square, row, column); \
f5(bfr, bb, square, row, column); \
}
inline void GenerateCornerStepMoves(const Bitboard stm_bitboard,
const Bitboard nn_bitboard,
std::vector<Move> buffer) {
// Northwest corner
if (HasPlayer(stm_bitboard, 0))
TOUCH_CORNER(buffer, nn_bitboard, 0, 0, 0, StepEast, StepSouthEast,
StepSouth)
// Northeast corner
if (HasPlayer(stm_bitboard, 5))
TOUCH_CORNER(buffer, nn_bitboard, 5, 0, 5, StepSouth, StepSouthWest,
StepWest)
// Southwest corner
if (HasPlayer(stm_bitboard, 30))
TOUCH_CORNER(buffer, nn_bitboard, 30, 5, 0, StepNorth, StepNorthEast,
StepEast)
// Southeast corner
if (HasPlayer(stm_bitboard, 35))
TOUCH_CORNER(buffer, nn_bitboard, 35, 5, 5, StepWest, StepNorthWest,
StepNorth)
}
inline void GenerateEdgeStepMoves(const Bitboard stm_bitboard,
const Bitboard nn_bitboard,
std::vector<Move> buffer) {
for (int square = 1; square < 5; square++) {
if (!HasPlayer(stm_bitboard, square)) continue;
TOUCH_EDGE(buffer, nn_bitboard, square, 0, square, StepEast,
StepSouthEast, StepSouth, StepSouthWest, StepWest)
}
// West edge
for (int row = 1, square = 11; row < 5; row++, square += 6) {
if (!HasPlayer(stm_bitboard, square)) continue;
TOUCH_EDGE(buffer, nn_bitboard, square, row, 5, StepSouth,
StepSouthWest, StepWest, StepNorthWest, StepNorth)
}
// South edge
for (int column = 1, square = 31; column < 5; column++, square++) {
if (!HasPlayer(stm_bitboard, square)) {
continue;
}
TOUCH_EDGE(buffer, nn_bitboard, square, 5, column, StepWest,
StepNorthWest, StepNorth, StepNorthEast, StepEast)
}
// East edge
for (int row = 1, square = 6; row < 5; row++, square += 6) {
if (!HasPlayer(stm_bitboard, square)) continue;
TOUCH_EDGE(buffer, nn_bitboard, square, row, 0, StepNorth,
StepNorthEast, StepEast, StepSouthEast, StepSouth)
}
}
template <>
void GenerateMoves<STEP>(const Position& pos, std::vector<Move> buffer) {
Bitboard stm_bitboard = pos.GetSideToMoveBitboard();
Bitboard nn_bitboard = pos.GetNonNullBitboard();
GenerateCornerStepMoves(stm_bitboard, nn_bitboard, buffer);
GenerateEdgeStepMoves(stm_bitboard, nn_bitboard, buffer);
/* Loop through non-border squares which have eight freedoms */
for (int row = 1, square = 7; row < 5; row++) {
for (int column = 1; column < 5; column++, square++) {
if (!HasPlayer(stm_bitboard, square)) continue;
StepNorthWest(buffer, nn_bitboard, square, row, column);
StepNorth(buffer, nn_bitboard, square, row, column);
StepNorthEast(buffer, nn_bitboard, square, row, column);
StepWest(buffer, nn_bitboard, square, row, column);
StepEast(buffer, nn_bitboard, square, row, column);
StepSouthWest(buffer, nn_bitboard, square, row, column);
StepSouth(buffer, nn_bitboard, square, row, column);
StepSouthEast(buffer, nn_bitboard, square, row, column);
}
}
}
// Checks whether an attack from a square in a given direction is valid.
inline bool IsAttackValid(const Position& pos, Bid start_bid, int start_row,
int start_column, int& final_row, int& final_column) {
Bitboard bitboard = pos.GetSideToMoveBitboard();
// Check if the player at (start_row, start_column) is the side-to-move
if (HasPlayer(bitboard, start_row, start_column)) {
return false;
}
int row = start_row;
int column = start_column;
Bid bid = start_bid;
bool was_loop_step = false;
int self_cross_count = 0;
int loop_count = 0;
Player turn_player = pos.GetSideToMovePlayer();
while (true) {
sk::calculateAttackPath(row, column, bid, row, column, bid,
was_loop_step);
bool is_self_cross = false;
// The original square is occupied by the moving piece; however, we are
// allowed to jump over it.
if (row == start_row && column == start_column) {
self_cross_count++;
is_self_cross = true;
// Jumping over the original square indicates that the attack will
// result in an infinite loop.
if (self_cross_count > 1) {
return false;
}
}
Player occupant = pos.GetPlayer(row, column);
if (!is_self_cross && occupant == turn_player) {
return false;
}
if (was_loop_step) {
++loop_count;
}
if (occupant && occupant != turn_player) {
if (loop_count == 0) {
return false;
}
break;
}
}
final_row = row;
final_column = column;
return true;
}
// Generates attack moves with toggle for including "non-capturing" ones.
void GenerateAttack(const Position& pos, bool gen_intermediate,
std::vector<Move> buffer) {
int capture_row = 0;
int capture_column = 0;
int path_row = 0;
int path_column = 0;
Bid path_bid = WEST;
bool is_loop = false;
int loop_count = 0;
// Loop through each direction & each square
for (int start_bid = WEST; start_bid <= SOUTH; start_bid++) {
for (int row = 0; row < 6; row++) {
for (int column = 0; column < 6; column++) {
bool attackValid =
IsAttackValid(pos, (Bid)start_bid, row, column, capture_row,
capture_column);
if (!attackValid) {
continue;
}
if (!gen_intermediate || !pos.options_.capture_optional_) {
buffer.push_back(CreateMove(row, column, capture_row,
capture_column, true,
(Bid)start_bid));
continue;
}
path_row = row;
path_column = column;
path_bid = (Bid)start_bid;
loop_count = 0;
while (path_row != capture_row &&
path_column != capture_column) {
calculateAttackPath(path_row, path_column, path_bid,
path_row, path_column, path_bid,
is_loop);
if (is_loop) {
++loop_count;
}
if (loop_count == 0) {
continue; // can land only after looping once
}
buffer.push_back(CreateMove(row, column, path_row,
path_column, true,
(Bid)start_bid));
}
}
}
}
}
// Generates only those attacking moves that capture on an enemy piece.
template <>
void GenerateMoves<CAPTURE>(const Position& pos, std::vector<Move> buffer) {
GenerateAttack(pos, false, buffer);
}
// Generates capturing & non-capturing attack moves. If model-options disallow
// optional capturing, then only the former are included.
template <>
void GenerateMoves<ATTACK>(const Position& pos, std::vector<Move> buffer) {
GenerateAttack(pos, true, buffer);
}
// Generates all possible (legal) moves for the side-to-move.
template <>
void GenerateMoves<LEGAL>(const Position& pos, std::vector<Move> buffer) {
GenerateMoves<ATTACK>(pos, buffer);
GenerateMoves<STEP>(pos, buffer);
}
std::vector<Move> GenerateMoves(const Position& pos) {
std::vector<Move> move_buffer;
GenerateMoves<LEGAL>(pos, move_buffer);
return move_buffer;
}
} // namespace sk<file_sep>// Copyright (C) 2020 <NAME> <<EMAIL>>
//
// This file is part of libsurakarta.
//
// libsurakarta is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// libsurakarta is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libsurakarta. If not, see <https://www.gnu.org/licenses/>.
// Author: <NAME> <<EMAIL>>
// This file defines the game-modelling class Surakarta.
#ifndef INCLUDE_SKMODEL_H_
#define INCLUDE_SKMODEL_H_
#include <stdint.h>
#include "skattack.h"
#include "skmodeloptions.h"
#include "skmove.h"
namespace sk {
enum Player : int {
/// Alias for unknown player
NULL_PLAYER = 0,
/// Player that "generally" will move first. <code>Surakarta</code>'s first
/// side-to-move is <code>RED</code> by default.
RED = 1,
/// Player that is "generally" the second to move.
BLACK = 2
};
class Position;
/// Model class for holding a Surakarta game state. It can be used to supply a
/// position to the Surakarta engine.
class Surakarta {
public:
/// \param no_init - if true, then the board would not have the initial
/// layout of Surakarta (it would be blank).
Surakarta(bool no_init = false);
/// This is the recommended constructor for initializing an application's
/// game-modelling object.
///
/// \param options - configuration of the game rules
Surakarta(ModelOptions &options);
/**
* Copies the given position.
*
* @param surakarta
*/
Surakarta(Surakarta &surakarta);
/**
* @param mv
* @return - whether the given move is legal in the current position
*/
bool isLegal(Move mv);
/**
* @param start_row
* @param start_column
* @param final_row
* @param final_column
* @return - whether moving from (start_row, start_column) to (final_row,
* final_column) is a legal non-attack move.
*/
bool isLegalStep(int start_row, int start_column, int final_row,
int final_column);
/**
* Calculates whether the attack move is legal for the current position.
*
* Hint: If you have provided a "cut" square that does not lie on the attack
* path, then that move is not legal. However, if the move is "legal without
* the cut", then this method will still return true. To check if the attack
* is legal "with the cut", check the equality the final row/column of the
* returned move with the cut row/column.
*
* @param bid - initial bid of attack
* @param start_row - starting square row
* @param start_column - starting square column
* @param [out] out - move holding all start/final squares.
* @param cut_row - (optional) square's row to stop at before capturing
* @param cut_column - (optional) square's column to stop after before
* capturing
* @return - whether the move is legal
*/
bool isLegalAttack(Bid bid, int start_row, int start_column, Move *out = 0,
int cut_row = -1, int cut_column = -1);
/**
* Moves the piece at (start_row, start_column) to (final_row, final_column)
* without checking whether it is valid.
*
* @param start_row
* @param start_column
* @param final_row
* @param final_column
*/
Surakarta *move(int start_row, int start_column, int final_row,
int final_column);
/**
* Expands and applies the given move without checking legality.
*
* @param move
*/
Surakarta *move(Move mv);
/**
* Checks the legality of the attack bid and applies the move. If the cut
* square is not on the attack path, the move will still proceed to capture.
*
* @param bid
* @param start_row
* @param start_column
* @param [out] move - actual move that was executed
* @param cut_row
* @param cut_column
*/
Surakarta *attack(Bid bid, int start_row, int start_column, Move * = 0,
int cut_row = -1, int cut_column = -1);
/**
* @returns - a clone of this position
*/
Surakarta &clone();
/**
* @returns - an array of 36 "players" that can be used to directly edit
* the position.
*/
inline Player *editable() { return this->board_; }
/**
* @param bid
* @param start_row
* @param start_column
* @returns - the attacking move from the start square. 0 if it is illegal.
*/
inline Move getAttack(Bid bid, int start_row, int start_column) {
Move mv = 0;
this->isLegalAttack(bid, start_row, start_column, &mv);
return mv;
}
protected:
Player *board_;
unsigned int move_count_;
ModelOptions &options_;
inline bool isTurn(Player p) { return this->move_count_ % 2 == p; }
inline Player getPlayer(int row, int column) {
return this->board_[row * 6 + column];
}
inline Player getTurnPlayer() {
return (Player)((this->move_count_ % 2) + 1);
}
inline bool canMoveFrom(int start_row, int start_column) {
return this->isTurn(this->board_[start_row * 6 + start_column]);
}
friend class Position;
};
} // namespace sk
#endif /* INCLUDE_SKMODEL_H_ */<file_sep>// Copyright (C) 2020 <NAME> <<EMAIL>>
//
// This file is part of libsurakarta.
//
// libsurakarta is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// libsurakarta is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libsurakarta. If not, see <https://www.gnu.org/licenses/>.
//
// Author: <NAME> <<EMAIL>>
#ifndef INCLUDE_SKMODELOPTIONS_H_
#define INCLUDE_SKMODELOPTIONS_H_
namespace sk {
/// <code>ModelOptions</code> provides options to "tweak" the rules of
/// Surakarta.
struct ModelOptions {
/// Making a capture optional in an attack move allows the attacking piece
/// to stop anywhere after looping once.
bool capture_optional_;
inline ModelOptions() : capture_optional_(false) {}
};
} // namespace sk
#endif /* INCLUDE_SKMODELOPTIONS_H_ */<file_sep>// Copyright (C) 2020 <NAME> <<EMAIL>>
//
// This file is part of libsurakarta.
//
// libsurakarta is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// libsurakarta is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libsurakarta. If not, see <https://www.gnu.org/licenses/>.
//
// Author: <NAME> <<EMAIL>>
// This file defines bitboard helper methods.
#include <skmodel.h>
#ifndef INCLUDE_BITBOARD_H_
#define INCLUDE_BITBOARD_H_
#include "enginetypes.h"
namespace sk {
// Filled rows
constexpr Bitboard BB_ROW_1 = (1 << 7) - 1;
constexpr Bitboard BB_ROW_2 = BB_ROW_1 << (6 * 1);
constexpr Bitboard BB_ROW_3 = BB_ROW_1 << (6 * 2);
constexpr Bitboard BB_ROW_4 = BB_ROW_1 << (6 * 3);
constexpr Bitboard BB_ROW_5 = BB_ROW_1 << (6 * 4);
constexpr Bitboard BB_ROW_6 = BB_ROW_1 << (6 * 5);
// Filled columns
constexpr Bitboard BB_COL_1 =
1 | (1 << 6) | (1 << 12) | (1 << 18) | (1 << 24) | (1 << 30) | (1l << 36);
constexpr Bitboard BB_COL_2 = BB_COL_1 << 1;
constexpr Bitboard BB_COL_3 = BB_COL_1 << 2;
constexpr Bitboard BB_COL_4 = BB_COL_1 << 3;
constexpr Bitboard BB_COL_5 = BB_COL_1 << 4;
constexpr Bitboard BB_COL_6 = BB_COL_1 << 5;
inline Bitboard createPlayerBitboard(Surakarta &model,
Player player = NULL_PLAYER) {
Bitboard board = 0;
for (int i = 0; i < 36; i++) {
if (model.editable()[i] == player) {
board |= (1l << i);
}
}
return board;
}
inline bool IsPlayerAt(const Bitboard &bitboard, int i) {
return (bitboard >> i) & 1;
}
// Returns whether the i-th bit in the bitboard in set.
inline bool HasPlayer(const Bitboard &bitboard, int i) {
return (bitboard >> i) & 1;
}
// Returns whether the bit corresponding to (row, column) is set in the
// bitboard.
inline bool HasPlayer(const Bitboard &bitboard, int row, int column) {
return (bitboard >> (row * 6 + column)) & 1;
}
inline void LiftPlayer(Bitboard &bitboard, int i) { bitboard &= ~(1 << i); }
inline void PutPlayer(Bitboard &bitboard, int i) { bitboard |= (1 << i); }
} // namespace sk
#endif /* INCLUDE_BITBOARD_H_ */
<file_sep>// Copyright (C) 2020 <NAME> <<EMAIL>>
//
// This file is part of libsurakarta.
//
// libsurakarta is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// libsurakarta is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libsurakarta. If not, see <https://www.gnu.org/licenses/>.
//
// Author: <NAME> <<EMAIL>>
#include <skmodel.h>
#include <cassert>
#include <iostream>
#include "factory/surakarta_factory.h"
void testAttackLegalityWhenBlocked() {
std::vector<ModelBlock *> mocker = {new ModelBlock(sk::RED, 0, 0, 3, 3),
new ModelBlock(sk::BLACK, 2, 0)};
sk::Surakarta *model = createModel(mocker);
// Piece is blocked, can't attack
assert(!model->isLegalAttack(sk::NORTH, 2, 2));
// Piece can directly loop and capture
assert(model->isLegalAttack(sk::NORTH, 0, 2));
// Piece is black and can't play on this turn
assert(!model->isLegalAttack(sk::WEST, 2, 0));
}
int main() {
testAttackLegalityWhenBlocked();
return 0;
}<file_sep>// Copyright (C) 2020 <NAME> <<EMAIL>>
//
// This file is part of libsurakarta.
//
// libsurakarta is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// libsurakarta is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libsurakarta. If not, see <https://www.gnu.org/licenses/>.
//
// Author: <NAME> <<EMAIL>>
#include <stdint.h>
#ifndef INCLUDE_SKMOVE_H_
#define INCLUDE_SKMOVE_H_
namespace sk {
/**
* Enumeration of possible directions an attack can go in.
*/
enum Bid : int { WEST = 0, NORTH = 1, EAST = 2, SOUTH = 3, NULL_BID = 7 };
/**
* Types of moves
*/
enum MoveType : int { LEGAL = 0, STEP = 1, CAPTURE = 2, ATTACK = 3 };
/**
* Encodes the start and final square of a move along with attack information.
*
* Bits:
* 0-6: Final row
* 7-12: Final column
* 13-18: Start row
* 19-24: Start column
* 20: Whether it is an attack
* 21-23: Initial direction of attack
*
* @see sk::createMove
*/
typedef uint64_t Move;
/**
* Encodes a move.
*
* @param start_row
* @param start_column
* @param final_row
* @param final_column
* @param is_attack
* @param bid - initial direction of attack
*/
inline Move CreateMove(int start_row, int start_column, int final_row,
int final_column, bool is_attack = false,
sk::Bid bid = NULL_BID) {
return (final_row) | (final_column << 6) | (start_row << 12) |
(start_column << 18) | (is_attack << 19) | (bid << 20);
}
inline int GetMoveStartRow(Move mv) { return mv & ((1 << 6) - 1); }
inline int GetMoveStartColumn(Move mv) { return (mv >> 6) & ((1 << 6) - 1); }
inline int GetMoveFinalRow(Move mv) { return (mv >> 12) & ((1 << 6) - 1); }
inline int GetMoveFinalColumn(Move mv) { return (mv >> 18) & ((1 << 6) - 1); }
inline bool IsMoveAttack(Move mv) { return (mv >> 19) & 1; }
inline Bid GetMoveBid(Move mv) { return (Bid)((mv >> 20) & ((1 << 3) - 1)); }
} // namespace sk
#endif /* INCLUDE_SK_MOVE_H_ */<file_sep>// Copyright (C) 2020 <NAME> <<EMAIL>>
//
// This file is part of libsurakarta.
//
// libsurakarta is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// libsurakarta is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libsurakarta. If not, see <https://www.gnu.org/licenses/>.
//
// Author: <NAME> <<EMAIL>>
// This file defines a bitboard-based modelling class. This is a "lighter
// version" of Surakarta, and is used by the engine internally.
#ifndef ENGINE_POSITION_H_
#define ENGINE_POSITION_H_
#include "../../include/skmodel.h"
#include "bitboard.h"
#include "enginetypes.h"
namespace sk {
// Position models a Surakarta position using one bitboard for each player.
class Position {
public:
Position(Surakarta &surakarta);
Position(const Position &clone);
// Heuristic to evaluate this position
Value evaluate();
Bitboard getBitboard(Player player) {
return player_bitboards_[player - 1];
}
void copyFrom(Position &position);
void move(Move move);
ModelOptions &options_;
protected:
Bitboard *player_bitboards_;
int count_red_;
int count_black_;
public:
Player side_to_move_;
// Player who will move in the current turn.
inline Player GetSideToMovePlayer() const { return side_to_move_; }
// White player's bitboard.
inline Bitboard GetRedPlayerBitboard() const {
return this->player_bitboards_[0];
}
// Black player's bitboard.
inline Bitboard GetBlackPlayerBitboard() const {
return this->player_bitboards_[1];
}
// Bitboard for the side-to-move player
inline Bitboard GetSideToMoveBitboard() const {
return this->player_bitboards_[this->side_to_move_ - 1];
}
// Combined red & black bitboard. It can used to check if any player is at a
// given square.
inline Bitboard GetNonNullBitboard() const {
return this->player_bitboards_[0] | this->player_bitboards_[1];
}
// Returns the player at the given square.
inline Player GetPlayer(int i) const {
if (HasPlayer(GetRedPlayerBitboard(), i)) {
return RED;
}
if (HasPlayer(GetBlackPlayerBitboard(), i)) {
return BLACK;
}
return NULL_PLAYER;
}
// Returns the player at (row, column).
inline Player GetPlayer(int row, int column) const {
return GetPlayer(row * 6 + column);
}
}; // namespace sk
inline bool IsPlayerAt(Bitboard bitboard, Square square) {
return (bitboard >> square) & 1;
}
} // namespace sk
#endif /* ENGINE_POSITION_H_ */<file_sep>// Copyright (C) 2020 <NAME> <<EMAIL>>
//
// This file is part of libsurakarta.
//
// libsurakarta is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// libsurakarta is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libsurakarta. If not, see <https://www.gnu.org/licenses/>.
//
// Author: <NAME> <<EMAIL>>
#include <skmodel.h>
#include <cstdlib>
#include <iostream>
namespace sk {
// Used as a placeholder when ModelOptions is not provided.
ModelOptions kNullOptions;
void WriteInitialLayout(Player *board) {
for (int i = 0; i < 12; i++) {
board[i] = RED;
}
for (int i = 12; i < 24; i++) {
board[i] = NULL_PLAYER;
}
for (int i = 36 - 12; i < 36; i++) {
board[i] = BLACK;
}
}
Surakarta::Surakarta(bool no_init)
: options_(no_init ? kNullOptions : *new ModelOptions()) {
board_ = new Player[36];
move_count_ = 0;
if (!no_init) {
WriteInitialLayout(board_);
}
}
Surakarta::Surakarta(ModelOptions &options) : options_(options) {
board_ = new Player[36];
move_count_ = 0;
WriteInitialLayout(board_);
}
Surakarta::Surakarta(Surakarta ©) : options_(copy.options_) {
board_ = new Player[36];
move_count_ = copy.move_count_;
for (int i = 0; i < 36; i++) {
board_[i] = copy.board_[i];
}
}
bool Surakarta::isLegal(Move mv) {
if (IsMoveAttack(mv)) {
Move actual;
isLegalAttack(GetMoveBid(mv), GetMoveStartRow(mv),
GetMoveStartColumn(mv), &actual, GetMoveFinalRow(mv),
GetMoveFinalColumn(mv));
return (mv & ((1 << 24) - 1)) ==
actual; // move encoding bits are equal
}
return isLegalStep(GetMoveStartRow(mv), GetMoveStartColumn(mv),
GetMoveFinalRow(mv), GetMoveFinalColumn(mv));
}
bool Surakarta::isLegalStep(int start_row, int start_column, int final_row,
int final_column) {
return canMoveFrom(start_row, start_column) &&
getPlayer(final_row, final_column) &&
std::abs(start_row - final_row) <= 1 &&
std::abs(final_row - final_column) <= 1;
}
bool Surakarta::isLegalAttack(Bid start_bid, int start_row, int start_column,
Move *out, int cut_row, int cut_column) {
if (getPlayer(start_row, start_column) != getTurnPlayer()) {
return false; // not player's turn
}
int row = start_row;
int column = start_column;
Bid bid = start_bid;
bool was_loop_step = false;
int self_cross_count =
0; // no. of times we have passed through our initial square
int loop_count = 0; // no. of times we have looped
bool cut_found = false; // whether we passed over cut square
Player turn_player = getTurnPlayer();
while (true) {
calculateAttackPath(row, column, bid, row, column, bid, was_loop_step);
bool is_self_cross = false;
if (row == start_row && column == start_column) {
self_cross_count++;
is_self_cross = true;
if (self_cross_count > 1) {
return false; // indicates infinite loop
}
}
Player occupant = getPlayer(row, column);
if (!is_self_cross && occupant == turn_player) {
return false; // can't land on our own piece
}
if (was_loop_step) {
++loop_count;
}
if (cut_row == row && cut_column == column) {
cut_found = true;
}
if (occupant && occupant != turn_player) {
if (loop_count == 0) {
return false; // must loop once to capture
}
break;
}
}
if (out) {
*out = CreateMove(start_row, start_column, cut_found ? cut_row : row,
cut_found ? cut_column : column, true, start_bid);
}
return true;
}
Surakarta *Surakarta::move(int start_row, int start_column, int final_row,
int final_column) {
int start_square = start_row * 6 + start_column;
int final_square = final_row * 6 + final_column;
board_[final_square] = board_[start_square];
board_[start_square] = NULL_PLAYER;
return this;
}
Surakarta *Surakarta::move(Move move) {
this->move(GetMoveStartRow(move), GetMoveStartColumn(move),
GetMoveFinalRow(move), GetMoveFinalColumn(move));
return this;
}
Surakarta *Surakarta::attack(Bid bid, int start_row, int start_column,
Move *result, int cut_row, int cut_column) {
Move lresult;
if (!result) {
result = &lresult;
}
bool isLegal = isLegalAttack(bid, start_row, start_column, result, cut_row,
cut_column);
if (isLegal) {
move(*result);
} else {
*result = 0;
}
return this;
}
Surakarta &Surakarta::clone() { return *new Surakarta(*this); }
} // namespace sk<file_sep>// Copyright (C) 2020 <NAME> <<EMAIL>>
//
// This file is part of libsurakarta.
//
// libsurakarta is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// libsurakarta is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libsurakarta. If not, see <https://www.gnu.org/licenses/>.
//
// Author: <NAME> <<EMAIL>>
// This file defines helper methods to trace the path of an attacking move.
#include "skmove.h"
#ifndef INCLUDE_SKATTACK_H_
#define INCLUDE_SKATTACK_H_
namespace sk {
// Calculates the radius of the loop emerging from (terminal_row,
// terminal_column)
inline int calculateLoopRadius(int terminal_row, int terminal_column) {
if (terminal_row == 0 || terminal_row == 5) {
return terminal_row < 3 ? terminal_column : 5 - terminal_column;
} else {
return terminal_column < 3 ? terminal_row : 5 - terminal_row;
}
}
// Calculates the bid required to loop from the given loop terminal square.
inline Bid calculateLoopBid(int terminal_row, int terminal_column) {
if (terminal_row == 0) {
return NORTH;
} else if (terminal_row == 5) {
return SOUTH;
} else if (terminal_column == 0) {
return WEST;
} else if (terminal_column == 5) {
return EAST;
}
return NULL_BID;
}
// Calculates the other terminal of the loop emerging from (in_row, in_column).
// It also finds the outgoing bid for a piece.
inline void calculateLoopTerminal(int in_row, int in_column, int &out_row,
int &out_column, Bid &out_bid) {
Bid in_bid = calculateLoopBid(in_row, in_column);
int loop_radius = calculateLoopRadius(in_row, in_column);
switch (in_bid) {
case NORTH:
out_row = loop_radius;
out_column = in_column < 3 ? 0 : 5;
out_bid = in_column < 3 ? EAST : WEST;
return;
case WEST:
out_row = in_row < 3 ? 0 : 5;
out_column = loop_radius;
out_bid = in_row < 3 ? SOUTH : NORTH;
return;
case SOUTH:
out_row = 5 - loop_radius;
out_column = in_column < 3 ? 0 : 5;
out_bid = in_column < 3 ? EAST : WEST;
return;
case EAST:
out_row = in_row < 3 ? 0 : 5;
out_column = 5 - loop_radius;
out_bid = in_row < 3 ? SOUTH : NORTH;
return;
default:
return;
}
}
// Calculates the next square for a piece in an attacking move.
inline void calculateAttackPath(int in_row, int in_column, Bid in_bid,
int &out_row, int &out_column, Bid &out_bid,
bool &is_loop) {
out_bid = in_bid; // if no looping occurs
is_loop = false;
switch (in_bid) {
case NORTH:
if (in_row - 1 > 0) {
out_row = in_row - 1;
out_column = in_column;
return;
}
break;
case WEST:
if (in_column - 1 > 0) {
out_row = in_row;
out_column = in_column - 1;
return;
}
break;
case SOUTH:
if (in_row + 1 < 5) {
out_row = in_row + 1;
out_column = in_column;
return;
}
break;
case EAST:
if (in_column + 1 < 6) {
out_row = in_row;
out_column = in_column + 1;
return;
}
default:
break;
}
// Must loop here!
calculateLoopTerminal(in_row, in_column, out_row, out_column, out_bid);
is_loop = true;
}
} // namespace sk
#endif /* INCLUDE_SKATTACK_H_ */<file_sep>// Copyright (C) 2020 <NAME> <<EMAIL>>
//
// This file is part of libsurakarta.
//
// libsurakarta is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// libsurakarta is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libsurakarta. If not, see <https://www.gnu.org/licenses/>.
//
// Author: <NAME> <<EMAIL>>
#ifndef INCLUDE_SKENGINE_H_
#define INCLUDE_SKENGINE_H_
#include "skmodel.h"
namespace sk {
struct EngineOptions {};
/// Runs the Surakarta engine on the given position.
Move Think(Surakarta &position, EngineOptions &eg_options);
} // namespace sk
#endif /* INCLUDE_SKENGINE_H_ */<file_sep>cmake_minimum_required(VERSION 3.9)
project(libsurakarta
VERSION 1.0.1
DESCRIPTION "Surakarta Engine")
include(GNUInstallDirs)
include(CTest)
enable_testing()
set (CMAKE_CXX_STANDARD 11)
add_library(libsurakarta
SHARED
src/model/surakarta.cc
src/engine/position.cc)
set_target_properties(libsurakarta
PROPERTIES
PREFIX ""
VERSION ${PROJECT_VERSION}
SOVERSION 1
PUBLIC_HEADER include/Surakarta.hpp
DESCRIPTION "C++ implementation of a Surakarta computer engine"
HOMEPAGE_URL https://github.com/SurakartaArcade/libsurakarta
LANGUAGES CXX)
target_include_directories(
libsurakarta
PUBLIC
include)
install(TARGETS libsurakarta
LIBRARY
DESTINATION ${CMAKE_INSTALL_LIBDIR}
PUBLIC_HEADER
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
install(FILES ${CMAKE_BINARY_DIR}/mylib.pc
DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig)
if (BUILD_TESTING)
add_executable(test_skmodel test/skmodel.cc test/factory/surakarta_factory.cc)
target_include_directories(
test_skmodel
PUBLIC
include
)
target_link_libraries(
test_skmodel
libsurakarta
)
add_test(SurakartaModel test_skmodel)
endif()<file_sep>// Copyright (C) 2020 <NAME> <<EMAIL>>
//
// This file is part of libsurakarta.
//
// libsurakarta is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// libsurakarta is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libsurakarta. If not, see <https://www.gnu.org/licenses/>.
//
// Author: <NAME> <<EMAIL>>
#include "surakarta_factory.h"
#include <skmodel.h>
sk::Surakarta *clearModel(sk::Surakarta &model) {
for (int i = 0; i < 36; i++) {
model.editable()[i] = sk::NULL_PLAYER;
}
return &model;
}
sk::Surakarta *createModel(std::vector<ModelBlock *> &arr) {
sk::Surakarta *model = clearModel(*new sk::Surakarta());
for (int i = 0; i < arr.size(); i++) {
ModelBlock *block = arr.at(i);
for (int dr = 0; dr < block->rowRange; dr++) {
for (int dc = 0; dc < block->columnRange; dc++) {
model
->editable()[(block->row + dr) * 6 + (block->column + dc)] =
block->color;
}
}
}
return model;
} | 927e856da25797d04b77d00ddcab2dd3f33056e9 | [
"Markdown",
"CMake",
"C++"
] | 17 | C++ | SurakartaArcade/libsurakarta | 86ce804fbd45e0e258bcf4a1a86271642fa06501 | 12670a374fe0a544708b35468354e6e87f27825f | |
refs/heads/master | <file_sep>import numpy as np
import pandas as pd
from math import exp
import copy
from sklearn import preprocessing
# Feed Forward helper methods
def sigmoid(value):
if value < 0:
return 1 - 1 / (1 + exp(value))
else:
return 1.0/(1+exp(value * (-1)))
def sigma(matrix_weight, matrix_input, bias=0):
# Prereq: len(arr_weight) = len(arr_input)
return matrix_weight.dot(matrix_input.transpose()) + bias
# hidden_layer = int (number of hidden layers)
# nb_nodes = arr[int] (number of nodes per hidden layer)
# len_input_matrix = int (number of features)
# Output: List of Matrixes
# Method: He initialization
# Link: https://towardsdatascience.com/weight-initialization-techniques-in-neural-networks-26c649eb3b78
def initialize_weights(hidden_layer, nb_nodes, len_input_matrix):
arr_weight_this_batch = list()
for i in range(hidden_layer):
if i==0:
nb_nodes_prev = len_input_matrix
else:
nb_nodes_prev = nb_nodes[i-1]
weight_matrix = np.random.randn(nb_nodes[i], nb_nodes_prev) * np.sqrt(2/(nb_nodes_prev+nb_nodes[i]))
arr_weight_this_batch.append(weight_matrix)
return arr_weight_this_batch
def error(feed_forward_output, target_output):
return ((target_output-feed_forward_output)**2)
def err_yes(value):
return (value > 0.15) # 15% fault tolerance
# See function: initialize_errors
def initialize_sigma(hidden_layer, nb_nodes):
list_sigma = list()
for i in range(hidden_layer):
arr_sigma = np.zeros(nb_nodes[i])
list_sigma.append(arr_sigma)
return list_sigma
# Backpropagation and Update Weight helper methods
# hidden_layer = int (number of hidden layers)
# nb_nodes = arr[int] (number of nodes per hidden layer)
# Output: List of Matrixes
def initialize_errors(hidden_layer, nb_nodes):
arr_neuron_errors = list()
for i in range(hidden_layer):
arr_error = np.empty(nb_nodes[i])
arr_neuron_errors.append(arr_error)
return arr_neuron_errors
def propagate_error_output_layer(feed_forward_output, target_output):
return feed_forward_output*(1-feed_forward_output)*(target_output-feed_forward_output)
def propagate_error_hidden_layer_neuron(sigma_output, error_contribution):
return sigmoid(sigma_output) * (1 - sigmoid(sigma_output)) * error_contribution
# error = neuron's error
def update_weight_neuron(weight_prev_prev, weight_prev, learning_rate, momentum, error, input_neuron):
# weight_prev_prev = previous of weight_prev
return weight_prev + weight_prev_prev * learning_rate + momentum*error*input_neuron
# input_matrix = matrix[float] (data) (asumsi, kolom terakhir adalah hasil klasifikasi)
# hidden_layers = int (number of hidden layers)
# nb_nodes = arr[int] (number of nodes per hidden layer)
# nu = float (momentum)
# alfa = float (learning rate)
# epoch = int (number of training loops)
# batch_size = int (mini-batch)
# output = FFNN prediction model (list of matrix)
def mini_batch_gradient_descent(input_matrix, hidden_layer, nb_nodes, nu, alfa, epoch, batch_size=1):
#transpose-slicing, memisah input dan label
col_width = input_matrix.shape[1]
input_col_width = col_width - 1
input_data = (input_matrix.transpose()[0:input_col_width]).transpose()
label_data = (input_matrix.transpose()[input_col_width:col_width]).transpose()
hidden_layer += 1
nb_nodes = np.append(nb_nodes, [1])
arr_neuron_errors = initialize_errors(hidden_layer, nb_nodes)
all_sigma_values = initialize_sigma(hidden_layer, nb_nodes)
arr_weight_this_batch = initialize_weights(hidden_layer, nb_nodes, input_col_width)
for no_epoch in range(epoch):
arr_weight_prev_batch = copy.deepcopy(arr_weight_this_batch) # tracking previous state of weights
batch_count = 0
error_value = 0
for no_input_data in range(len(input_data)):
# Feed Forward
one_sigma_values = list()
for no_hidden_layer in range(hidden_layer):
if no_hidden_layer == 0:
one_sigma_values.append(sigma(arr_weight_this_batch[no_hidden_layer], input_data[no_input_data]))
else:
one_sigma_values.append(sigma(arr_weight_this_batch[no_hidden_layer], one_sigma_values[no_hidden_layer-1]))
for no_rows in range(len(one_sigma_values[no_hidden_layer])):
output_i = sigmoid(one_sigma_values[no_hidden_layer][no_rows])
one_sigma_values[no_hidden_layer][no_rows] = output_i
all_sigma_values[no_hidden_layer][no_rows] += output_i
#Result of sigma will be array with 1 element only, so it's safe to select like this
error_value += error(one_sigma_values[hidden_layer - 1][0], label_data[no_input_data])[0]
batch_count += 1
if (batch_count == batch_size):
error_value /= batch_size
for no_hidden_layer in range(hidden_layer):
for no_neuron in range(len(all_sigma_values[no_hidden_layer])):
all_sigma_values[no_hidden_layer][no_neuron] /= batch_size
if (err_yes(error_value)):
# Back Propagation
output_error = propagate_error_output_layer(all_sigma_values[hidden_layer-1][0], label_data[no_input_data])
arr_neuron_errors[hidden_layer - 1][0] = output_error
for no_hidden_layer in range(hidden_layer-2, -1, -1):
for neuron in range(nb_nodes[no_hidden_layer]):
# pencarian error_contribution
error_contribution = 0
for output_neuron in range(nb_nodes[no_hidden_layer+1]):
error_contribution += arr_weight_this_batch[no_hidden_layer + 1][output_neuron][neuron] * arr_neuron_errors[no_hidden_layer + 1][output_neuron]
arr_neuron_errors[no_hidden_layer][neuron] = propagate_error_hidden_layer_neuron(all_sigma_values[no_hidden_layer][neuron], error_contribution)
# Update Weights
for no_hidden_layer in range(1, hidden_layer):
for neuron in range(nb_nodes[no_hidden_layer]):
for weight in range(len(arr_weight_this_batch[no_hidden_layer][neuron])):
arr_weight_this_batch[no_hidden_layer][neuron][weight] = update_weight_neuron(arr_weight_prev_batch[no_hidden_layer][neuron][weight], arr_weight_this_batch[no_hidden_layer][neuron][weight], nu, alfa, arr_neuron_errors[no_hidden_layer][neuron], all_sigma_values[no_hidden_layer-1][weight])
#khusus hidden layer pertama, masukan dari input data
for neuron in range(nb_nodes[0]):
for weight in range(input_col_width):
arr_weight_this_batch[0][neuron][weight] = update_weight_neuron(arr_weight_prev_batch[0][neuron][weight], arr_weight_this_batch[0][neuron][weight], nu, alfa, arr_neuron_errors[0][neuron], input_data[no_input_data][weight])
all_sigma_values = initialize_sigma(hidden_layer, nb_nodes)
error_value = 0
batch_count = 0
return arr_weight_this_batch
# predictor specifically for dataset that is classified into only 2 classes
def predict_2classes(model, arr_features, label):
all_sigma_values = list()
for no_hidden_layer in range(len(model)):
if (no_hidden_layer == 0):
all_sigma_values.append(sigma(model[no_hidden_layer], arr_features))
else:
all_sigma_values.append(sigma(model[no_hidden_layer], all_sigma_values[no_hidden_layer-1]))
for no_rows in range(len(all_sigma_values[no_hidden_layer])):
all_sigma_values[no_hidden_layer][no_rows] = sigmoid(all_sigma_values[no_hidden_layer][no_rows])
error_value = error(all_sigma_values[len(model) - 1][0], label)[0]
return (error_value < 0.5) #scaling : (0, 1)
def accuracy(model, input_matrix):
#transpose-slicing, memisah input dan label
col_width = input_matrix.shape[1]
input_col_width = col_width - 1
input_data = (input_matrix.transpose()[0:input_col_width]).transpose()
label_data = (input_matrix.transpose()[input_col_width:col_width]).transpose()
true_count = 0
false_count = 0
for no_input_data in range(len(input_data)):
if (predict_2classes(model, input_data[no_input_data], label_data[no_input_data])):
true_count += 1
else:
false_count += 1
return true_count / (true_count + false_count) * 100
# dataset load
csv_string = input("Input .csv filename: ")
try:
df = pd.read_csv(csv_string)
except:
print("File not found.")
###quit()
print("File loaded successfuly.")
# dataset preprocess
def preprocess_dataframe(df):
# transform non-numeric data to numeric data
types = df.dtypes
labels = df.columns.values # because pandas select columns using column names
def transform_to_numeric(matrix_data):
for i in range(matrix_data.shape[1]):
type_i = types[i]
if (type_i == object):
values = matrix_data[labels[i]].unique()
dict_i = dict(zip(values, range(len(values)))) # transform every unique object/string into numbers
matrix_data = matrix_data.replace({labels[i]:dict_i})
elif (type_i == bool):
matrix_data[labels[i]] = matrix_data[labels[i]].astype(int)
return matrix_data
newdf = transform_to_numeric(df)
# scaling
def scale_data(matrix_data, min_val, max_val):
def scaling(value):
return (value - minValue)*(max_val - min_val)/(maxValue - minValue) + min_val
for x in range(matrix_data.shape[1]):
minValue = matrix_data[labels[x]].min()
maxValue = matrix_data[labels[x]].max()
matrix_data[labels[x]] = matrix_data[labels[x]].apply(scaling)
return matrix_data
data_matrix = scale_data(newdf, 0, 1)
data_matrix = data_matrix.to_numpy() #convert pandas dataframe to numpy array
return data_matrix
def split_train_test(matrix_data, test_portion):
total_data = len(matrix_data)
total_data_for_test = int(round(test_portion * total_data, 0))
total_data_for_train = total_data - total_data_for_test
return(matrix_data[0:total_data_for_train], matrix_data[total_data_for_train:total_data])
# input and main program
while True:
hidden_layers = int(input("Input number of hidden layers: "))
if (hidden_layers <= 10 and hidden_layers >= 0):
break
else:
print("# of hidden layers must be a positive integer and no more than 10.")
nb_nodes = np.empty(hidden_layers)
for i in range(hidden_layers):
while True:
nb_nodes[i] = int(input("Input number of nodes for hidden layer %d : " % i))
if (nb_nodes[i] > 0):
break
else:
print("# of nodes must be a positive integer.")
while True:
momentum = float(input("Input momentum: "))
if (momentum <= 1 and momentum >= 0):
break
else:
print("Momentum must be between 0 and 1.")
while True:
learning_rate = float(input("Input learning rate: "))
if (learning_rate <= 1 and learning_rate >= 0):
break
else:
print("Learning rate must be between 0 and 1.")
while True:
epoch = int(input("Input epoch: "))
if (epoch > 0):
break
else:
print("Epoch must be a positive integer.")
while True:
batch_size = int(input("Input the batch size: "))
if (batch_size > 0):
break
else:
print("Batch size must be a positive integer.")
while True:
test_size = float(input("Input the test size: "))
if (test_size > 0 and test_size < 1):
break
else:
print("Test size must be between 0 and 1.")
data_matrix = preprocess_dataframe(df)
train_matrix, test_matrix = split_train_test(data_matrix, test_size)
nb_nodes = nb_nodes.astype(int) #diperlukan karena dianggap float dalam fungsi randn jika tak diubah
custom_model = mini_batch_gradient_descent(train_matrix, hidden_layers, nb_nodes, momentum, learning_rate, epoch, batch_size)
print("Accuracy: ", accuracy(custom_model, test_matrix))
<file_sep># Mini Batch Gradient Descent
| b159703f0c84bdb046676667599a8b24975e64b3 | [
"Markdown",
"Python"
] | 2 | Python | kevinandrianliu/Mini-Batch-Gradient-Descent | c26529d8239e07043c2a3208e45ebbf41a2f5495 | 722f8d61751e256922d3b012e422245c51a1f395 | |
refs/heads/master | <repo_name>kelvin04/basic-phyton<file_sep>/Final-Project/final_project.py
import smtplib
import os
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
final_project_file = "final_project.py"
email_list_file = "receiver_list.txt"
smtp_server = "smtp.gmail.com"
port = 587
server = smtplib.SMTP(smtp_server,port)
def set_txt_data_to_list():
receiver_list = []
try:
list_from_txt = open(email_list_file)
if os.stat(email_list_file).st_size == 0:
print(f"File {email_list_file} tidak memiliki data")
else:
for receiver in list_from_txt.read().split("\n"):
receiver_list.append(receiver)
return receiver_list
except:
print(f"File {email_list_file} tidak ditemukan")
def login_to_gmail_server():
global sender_email
sender_email = str(input("Email : "))
global sender_password
sender_password = str(input("Password: "))
try:
server.starttls()
server.login(sender_email, sender_password)
print("Sukses login")
return True
except Exception:
print("Gagal login, harap periksa kembali email dan password anda")
return False
def set_email_content(email_receiver, email_subject, email_message, with_attachment):
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = email_receiver
message['Subject'] = email_subject
message.attach(MIMEText(email_message, 'plain'))
total_files = get_total_attachments()
if with_attachment.upper() == "Y":
if total_files > 0:
for f in os.listdir():
with open(f, "rb") as file_attachment:
if f != final_project_file and f != email_list_file:
part = MIMEApplication(
file_attachment.read(),
Name=basename(f)
)
part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
message.attach(part)
else:
print("Tidak ada file yang dilampirkan")
return message.as_string()
def send_email(email_receiver, email_content):
try:
print(f"Sedang mengirim email kepada {email_receiver}, harap tunggu")
server.sendmail(sender_email, email_receiver, email_content)
print(f"Email berhasil dikirim kepada {email_receiver}")
except Exception:
print(f"Email kepada {email_receiver} gagal dikirim")
finally:
server.quit()
def get_total_attachments():
total_files= 0
files_list = []
for file_name in os.listdir():
with open(file_name, "rb"):
if file_name != final_project_file and file_name != email_list_file:
files_list.append(file_name)
total_files = total_files + 1
if total_files > 0:
print("File yang akan dilampirkan :", ", ".join(files_list))
return total_files
def final_project_function():
# Menyimpan daftar email ke dalam list
receiver_list = set_txt_data_to_list()
# Mengubah list data type menjadi string dengan koma, untuk pengiriman email dengan banyak tujuan
receiver_list_str_type = ", ".join(receiver_list)
print("Selamat datang di program pengirim pesan!")
print("Silahkan input email dan password gmail anda")
# Login ke gmail server
credential = login_to_gmail_server()
if credential:
# Input dan menyimpan data pesan email
email_subject = str(input("Input subjek email : "))
email_message = str(input("Input pesan email : "))
with_attachment = input("Apakah akan melampirkan file di email? (Y/N) : ")
email_content = set_email_content(receiver_list_str_type, email_subject, email_message, with_attachment)
# Mengirimkan email
send_email(receiver_list, email_content)
final_project_function()
<file_sep>/README.md
# basic-phyton
Basic Phyton Learning From Indonesia AI
<file_sep>/Tugas-1/Soal-1.py
name = str(input("Input nama anda : "))
age = input("Input umur anda : ")
height = float(input("Input tinggi anda :"))
print(f"Nama saya {name}, umur saya {age} tahun dan tinggi saya {height} cm")
<file_sep>/Tugas-1/Soal-2.py
radius = input("Input jari-jari lingkaran : ")
try:
radius_int = int(radius)
area = 22 / 7 * radius_int ** 2
area_float = round(area, 2)
print(f"Luas lingkaran dengan jari-jari {radius} cm adalah {area_float} cm\u00b2.")
except ValueError:
print("Anda harus menginput tipe data integer!")
<file_sep>/Tugas-1/Soal-3.py
theory_scores = int(input("Input nilai ujian teori : "))
practice_scores = int(input("Input nilai ujian praktek : "))
if theory_scores >= 70 and practice_scores >= 70:
print("Selamat, anda lulus!")
elif theory_scores >= 70 and practice_scores < 70:
print("Anda harus mengulang ujian praktek.")
elif theory_scores < 70 and practice_scores >= 70:
print("Anda harus mengulang ujian teori.")
else:
print("Anda harus mengulang ujian teori dan praktek.")<file_sep>/main.py
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
test = "test"
empat = 4
lima = 5
a,b,c = "hi",1,2.5
valid = True
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('test')
print(empat + lima)
print(test + " " + "{}".format(empat))
print(c)
print(valid)
print(type(c))
print(0 % 7)
print(4 ** 2)
print(type(str(4.2)))
print(float('12'))
print("commit2")
print("commit3")
print("commit 4")
print("commit 5")
print("commit 6")
print("commit 7 from development")
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
<file_sep>/Tugas-2/Soal-1.py
contact_dict = {"names": [], "telephones": []}
def show_contact():
contact_size = len(contact_dict["names"])
if contact_size > 0 :
print("\nDaftar kontak:")
for i in range(contact_size):
print("Nama:", contact_dict["names"][i])
print("No Telepon:", contact_dict["telephones"][i])
else:
print("Belum ada kontak yang didaftarkan")
def add_contact():
name = str(input("Nama: "))
while True:
try:
telephone = int(input("No Telepon: "))
break
except ValueError:
print("Anda hanya bisa input angka untuk no telephone")
contact_dict["names"].append(name)
contact_dict["telephones"].append(telephone)
def func_contact_list_menu():
print("Selamat datang!")
while True:
print("\n-- Menu --")
print("1. Daftar Kontak")
print("2. Tambah Kontak")
print("3. Keluar")
menu = int(input("Pilih menu: "))
if menu == 1:
show_contact()
elif menu == 2:
add_contact()
elif menu == 3:
break
else:
print("Menu tidak tersedia")
print("Program selesai, sampai jumpa!")
func_contact_list_menu()
| 12d72f6685de339d3aeb681cb1ae7cba3b4e7d5c | [
"Markdown",
"Python"
] | 7 | Python | kelvin04/basic-phyton | af4a1592f1c9acd2a3779167f5cfe93ec8aa7ef6 | a193e82de991e0f2aea21379413d68ba23d0fd33 | |
refs/heads/master | <repo_name>shiyang07ca/spider<file_sep>/README.md
## 爬虫练习
### 程序说明
编写两个线程对象分别维护两个队列,一个用于保存URL及深度,另一个负责将爬取到的内容存储至本地,
主函数在spider.py中负责初始化两个任务队列。
### 使用说明
终端输入
<code>python3 spider.py -u http://www.yingjiesheng.com -d 2</code>
将自动爬取不同深度的网页及链接(默认为2),输出内容保存至"Downloads"文件夹下,
格式为"A\[B]",
A表示HTML的编号,B表示保存页面的URL深度。
### 参考链接
>1. https://www.metachris.com/2016/04/python-threadpool/
>2. https://www.ibm.com/developerworks/cn/aix/library/au-threadingpython/?ca=drs-tp3008#resources
>3. https://github.com/littlethunder/knowsecSpider2
<file_sep>/spider.py
#!/usr/bin/env python
'''
Version: 0.1
'''
import time
import optparse
from queue import Queue
from CrawlerThread import CrawlerThread
from OutputThread import OutputThread
def parse_options():
parser = optparse.OptionParser()
parser.add_option("-u", "--url", dest="url", type="string")
parser.add_option("-d", "--depth", dest="depth", type="int")
options, _ = parser.parse_args()
return options
# TODO: 编写主调度函数,封装该逻辑
def main(root_url, num_threads=10, depth=2):
start = time.time()
# 初始化两个任务队列,一个存储待爬取URL,一个用来存储待保存的内容
url_queue = Queue()
content_queue = Queue()
for _ in range(num_threads):
cr = CrawlerThread(url_queue, content_queue)
cr.start()
# 存入初始URL及深度的tuple
url_queue.put((root_url, depth))
for _ in range(num_threads):
ot = OutputThread(content_queue)
ot.start()
# 阻塞线程直到任务完成
try:
url_queue.join()
content_queue.join()
except KeyboardInterrupt:
print("Key Interrupt")
else:
print('****ALL DONE****')
print("Elapsed Time: %s" % (time.time() - start))
if __name__ == "__main__":
# root_url = "https://news.ycombinator.com/news"
# root_url = "https://www.zhibo8.cc/"
root_url = "http://www.yingjiesheng.com"
options = parse_options()
root_url = options.url or root_url
depth = options.depth or 2
main(root_url, depth=depth)
<file_sep>/OutputThread.py
import os
from threading import Thread
class OutputThread(Thread):
def __init__(self, content_queue):
Thread.__init__(self)
self.content_queue = content_queue
def run(self):
"""将内容队列取出并保存到本地"""
while True:
# 从content队列取出内容
content_id, depth, content = self.content_queue.get()
# 将id, 深度,content保存至本地HTML
self._save_to_html(str(content_id) + '[' + str(depth) + ']', content)
self.content_queue.task_done()
@staticmethod
def _save_to_html(filename, file):
DEST_DIR = './Downloads/'
path = os.path.join(DEST_DIR, filename+'.html')
with open(path, 'wb') as f:
if file:
f.write(file)<file_sep>/CrawlerThread.py
import re
from threading import Thread
import requests
import bs4
class CrawlerThread(Thread):
"""从URL线程队列取出URL,将返回的响应存入内容队列"""
def __init__(self, url_queue, content_queue):
Thread.__init__(self)
self.url_queue = url_queue # URL队列
self.content_queue = content_queue # 内容队列
self.content_id = 1 # 内容编号,用于给文件命名
self.urls = set() # 用于链接去重
def run(self):
while True:
# 从url队列提取URL及深度,并请求页面内容
url, depth = self.url_queue.get()
content = self._request_data(url)
# 将id,content放入队列
self.content_queue.put((self.content_id, depth, content))
self.content_id += 1
# 如果深度大于零,提取页面链接并存入url_queue(深度为零说明到达最后一层,不再更新链接)
if depth > 0:
for link in self._extract_all_links(content):
if link not in self.urls:
self.urls.add(link)
self.url_queue.put((link, depth-1))
self.url_queue.task_done()
@staticmethod
def _request_data(url):
'''返回指定URL响应对象'''
headers = {
'Connection': 'keep-alive',
'Accept': 'text/html,application/xhtml+xml,\
application/xml;q=0.9,image/webp,*/*;q=0.8',
'User-Agent': 'Mozilla/5.0 (X11; Linux i686)\
AppleWebKit/537.36 (KHTML, like Gecko)\
Chrome/35.0.1916.153 Safari/537.36',
'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6',
}
if url is None:
raise RuntimeWarning('url is None')
try:
resp = requests.get(url, headers=headers, timeout=2)
except Exception as e:
print(e)
else:
if resp.status_code != 200:
resp.raise_for_status()
return resp.content
return None
@staticmethod
def _extract_all_links(content):
'''返回页面内所有连接'''
bs = bs4.BeautifulSoup(content, 'html.parser')
links = []
for item in bs.find_all('a', attrs={"href":re.compile(r'^(https?|www).*$')}):
links.append(item.attrs['href'])
# 将新的链接保存起来(测试用)
with open('links.txt', 'a+') as f:
for l in links:
f.writelines(l)
f.write('\n')
f.write('*' * 20)
return links | 170f668089017a2d4dee6f9cacb55343581e639b | [
"Markdown",
"Python"
] | 4 | Markdown | shiyang07ca/spider | 365d6aded884e002dd22b56b5d1e8136d776da53 | df5e86e42ef6f473b8d5f9f8f3fe4d8dc24ea2c0 | |
refs/heads/master | <repo_name>fernandomarins/pygame<file_sep>/pygame.py
# coding: utf-8
# In[ ]:
import pygame
pygame.init()
screen = pygame.display.set_mode((900, 700))
def checkCollision(x, y, treasureX, treasureY):
global textWin, screen
collisionState = False
if y >= treasureY and y <= treasureY + 40:
if x >= treasureX and x <= treasureX + 35:
y = 650
x = 450 - 35/2
collisionState = True
elif x + 40 >= treasureX and x + 35 <= treasureX + 35:
y = 650
x = 450 - 35/2
collisionState = True
elif y + 40 >= treasureY and y + 40 <= treasureY + 40:
if x + 40 >= treasureX and x + 40 <= treasureX + 35:
y = 650
x = 450 - 35/2
collisionState = True
elif x + 40 >= treasureX and x + 35 <= treasureX + 35:
y = 650
x = 450 - 35/2
collisionState = True
return (x, y, collisionState)
# if the game is finished or not
finished = False
# x and y coordenates
x = 450 - 35/2
y = 650
# adding image
playerImage = pygame.image.load('player.png')
playerImage = pygame.transform.scale(playerImage, (35, 40))
# make sure image is transparent so the background is displayed
playerImage = playerImage.convert_alpha()
# background
backgroundImage = pygame.image.load('background.png')
backgroundImage = pygame.transform.scale(backgroundImage, (900, 700))
screen.blit(backgroundImage, (0, 0))
# teasure
treasureImage = pygame.image.load('treasure.png')
treasureImage = pygame.transform.scale(treasureImage, (35, 40))
treasureImage = treasureImage.convert_alpha()
treasureX, treasureY = 450 - 35/2, 50
screen.blit(treasureImage, (treasureX, treasureY))
collisionTreasure = False
#enemy
enemyImage = pygame.image.load('enemy.png')
enemyImage = pygame.transform.scale(enemyImage, (35, 40))
enenyImage = enemyImage.convert_alpha()
enemyX = 100
enemyY = 580-10
movingRight = True
collisionEenemy = False
enemies = [(enemyX, enemyY, movingRight)]
enemyNames = {0: "Max", 1: "Jill", 2: "Greg", 3: "Diane"}
#adding font
font = pygame.font.SysFont("comicsans", 60)
# level
level = 1
# the frame
frame = pygame.time.Clock()
while finished == False:
for event in pygame.event.get():
# to detect if the game should end
if event.type == pygame.QUIT:
finised = True
enemyIndex = 0
# check if enemy is next to the screen border
for enemyX, enemyY, movingRight in enemies:
if enemyX >= 800 - 35:
movingRight = False
elif enemyX <= 100:
movingRight = True
if movingRight == True:
enemyX += 5 * level
else:
enemyX -= 5 * level
enemies[enemyIndex] = (enemyX, enemyY, movingRight)
enemyIndex += 1
# array containing all the keys pressed by the user
pressedKeys = pygame.key.get_pressed()
# K_SPACE means the space key
if pressedKeys[pygame.K_RIGHT] == 1:
# if the space key is pressed, add 5 to x (move the object)
x += 5
if pressedKeys[pygame.K_DOWN] == 1:
# if the space key is pressed, add 5 to x (move the object)
y += 5
if pressedKeys[pygame.K_LEFT] == 1:
# if the space key is pressed, add 5 to x (move the object)
x -= 5
if pressedKeys[pygame.K_UP] == 1:
# if the space key is pressed, add 5 to x (move the object)
y -= 5
#if pressedKeys[pygame.K_q] == 1:
# pygame.event.post(pygame.QUIT())
white = (255, 255, 255)
screen.blit(backgroundImage, (0, 0))
screen.blit(treasureImage, (treasureX, treasureY))
enemyIndex = 0
for enemyX, enemyY, movingRight in enemies:
screen.blit(enemyImage, (enemyX, enemyY))
x, y, collisionEnemy = checkCollision(x, y, enemyX, enemyY)
if collisionEnemy == True:
name = enemyNames[enemyIndex]
textLose = font.render("You were killed by " + name, True, (255, 0, 0))
screen.blit(textLose, (450 - textLose.get_width()/2, 350 - textLose.get_height()/2))
pygame.display.flip()
frame.tick(1)
frame.tick(30)
enemyIndex += 1
screen.blit(playerImage, (x, y))
x, y, collisionTreasure = checkCollision(x, y, treasureX, treasureY)
if collisionTreasure == True:
level += 1
textWin = font.render("You've reached level " + str(level), True, (0, 0, 0))
enemies.append((enemyX - 50 * level, enemyY - 50 * level, False))
screen.blit(textWin, (450 - textWin.get_width()/2, 350 - textWin.get_height()/2))
pygame.display.flip()
frame.tick(1)
pygame.display.flip()
frame.tick(30)
# In[ ]:
| 3b34a331098365256c3618014329395ea607a1ef | [
"Python"
] | 1 | Python | fernandomarins/pygame | 2e0efd68b2bf76f38a07d339de05d36018a83704 | 2dda745ff2a707fc670b03dabcabd95a038f9d59 | |
refs/heads/master | <file_sep># 学习Spring源码的一些实例、心得
## ioc相关
有2个祖宗级接口:`BeanFactory`、`BeanDefinition`
`BeanFactory`有很多的实现类,`DefaultListableBeanFactory`就是其中之一。
`DefaultListableBeanFactory`里面就有一个`Map<String, BeanDefinition> beanDefinitionMap`, 这个Map对应到`beans.xml`文件,它的key是bean的名字,BeanDefiniton就是bean的定义。Spring容器只要根据这个Map,就能够产生各个bean对象了。<file_sep>package com.changer.log4j.aa.b;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @Project: JdkTest
* @Author: fcjiang
* @Date: 2016-05-12
*/
public class Person {
public static final Logger logger = LoggerFactory.getLogger(Person.class);
private String name;
private int age;
public Person() {
logger.info("[jdLogger] Person constructing...");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
<file_sep>## 在spring-boot中使用log4j2
需要完成一下操作:
1,`pom`中要排除spring-boot默认的日志框架,新增log4j2的依赖。
``` xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--增加log4j2的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
```
2,在`resources/`目录下新增`log4j2.xml`文件。主要的配置如下:
<file_sep>package com.changer.util;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* Created by fcjiang on 15/10/31.
*/
@ConfigurationProperties(prefix = "api")
@Component
public class EnviSettings {
private String server;
private String hzbank;
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
public String getHzbank() {
return hzbank;
}
public void setHzbank(String hzbank) {
this.hzbank = hzbank;
}
}
<file_sep>package com.changer.util.okhttp3;
/**
* @Project: MyUtils
* @Author: fcjiang
* @Date: 2016-06-15
*/
public class OkHttp3Util {
}
<file_sep>## examples from fcjiang
### Srping的事务管理
主要介绍了2种实现方式:1)基于AspectJ的xml配置方式;2)基于```<tx:annotaion-drive >```的注解方式。
<file_sep>//package com.changer.configs;
//
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//import javax.servlet.ServletException;
//import javax.servlet.annotation.WebServlet;
//import javax.servlet.http.HttpServlet;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//
///**
// * @Project: spring-boot-hello
// * @Author: fcjiang
// * @Date: 2016-06-30
// */
//@WebServlet(urlPatterns = {"/*"})
//public class LogServlet extends HttpServlet {
// private static final Logger logger = LoggerFactory.getLogger(LogServlet.class);
//
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// logger.info("进入doGet方法 pathInfo={}", req.getPathInfo());
// super.doGet(req, resp);
// }
//
// @Override
// protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// logger.info("进入doPost方法 pathInfo={}", req.getPathInfo());
// super.doPost(req, resp);
// }
//}
<file_sep>package com.changer.pattern.command;
/**
* @Project: JdkTest
* @Author: fcjiang
* @Date: 2017-06-08
*/
public class TurnOnCommand implements Command {
private TVReceiver tvReceiver;
public TurnOnCommand(TVReceiver tvReceiver) {
this.tvReceiver = tvReceiver;
}
@Override
public void execute() {
tvReceiver.turnOn();
}
}
<file_sep>package com.changer.controller;
import com.changer.model.ApiResp;
import com.changer.service.PersonService;
import com.changer.staticautowiredt.Person;
import com.rabbitmq.client.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeoutException;
/**
* @Project: SpringbootDevTest
* @Author: fcjiang
* @Date: 2016-06-29
*/
@RestController
@RequestMapping("/person")
public class PersonController {
private static final Logger logger = LoggerFactory.getLogger(PersonController.class);
@Autowired
private PersonService personService;
@RequestMapping("/testScope")
public ApiResp testScope() {
System.out.println("person name: " + personService.getName());
System.out.println("personService=" + personService);
System.out.println("personService bean hash code is " + personService.hashCode());
return new ApiResp("0000", "success");
}
@RequestMapping("/all")
public ApiResp<List<Person>> listAll(@RequestParam("normal") boolean normal) {
Person person1 = new Person();
person1.setName("1111");
person1.setAge(11);
Person person2 = new Person();
person2.setName("2222");
person2.setAge(22);
List<Person> persons = Arrays.asList(person1, person2);
if (!normal) {
throw new IllegalArgumentException("参数normal=false");
}
return new ApiResp<>("0000", "success", persons);
}
@RequestMapping("/consume")
public void consume() throws IOException, TimeoutException {
String EXCHANGE_NAME = "hello_exchange";
String QUEUE_NAME = "hello_queue";
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
factory.setPort(5672);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
// channel.queueDeclare(QUEUE_NAME, true, false, false, null);
channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
// String queueName = channel.queueDeclare().getQueue();
String queueName = QUEUE_NAME;
logger.info("exchange_name={}; queueName={}", EXCHANGE_NAME, queueName);
channel.queueBind(queueName, EXCHANGE_NAME, "");
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String message = new String(body, "UTF-8");
logger.info("[消费者] 接收数据={}", message);
}
};
channel.basicConsume(queueName, true, consumer);
}
}
<file_sep>package com.changer.demo4;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
/**
* Created by fcjiang on 15/10/25.
*/
public class AccountService {
private AccountDao accountDao;
private TransactionTemplate transactionTemplate;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
this.transactionTemplate = transactionTemplate;
}
// 方式一:注解式事务
// @Transactional
// public void transfer(String out, String in, Double money){
// accountDao.outMoney(out, money);
// int i = 10/0;
// accountDao.inMoney(in, money);
// }
// 方式二:编程式事务
public boolean transfer(final String out, final String in, final Double money){
return transactionTemplate.execute(new TransactionCallback<Boolean>() {
@Override
public Boolean doInTransaction(TransactionStatus transactionStatus) {
try {
accountDao.outMoney(out, money);
int i = 10/0;
accountDao.inMoney(in, money);
return true;
}
catch (Exception e) {
transactionStatus.setRollbackOnly();
e.printStackTrace();
return false;
}
}
});
}
}
<file_sep>package com.changer.daos.service;
import com.changer.daos.entities.User;
import com.changer.daos.entities.UserCriteria;
import com.changer.daos.mappers.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
/**
* Created by enniu on 16/1/28.
*/
@Repository
public class UserDao {
@Autowired
private UserMapper userMapper;
public List<User> getByName(String name){
if(null != name){
UserCriteria criteria = new UserCriteria();
criteria.createCriteria()
.andNameEqualTo(name);
return userMapper.selectByCriteria(criteria);
}
return new ArrayList<>();
}
public List<User> getAll(){
UserCriteria criteria = new UserCriteria();
criteria.createCriteria()
.andIdGreaterThan(0);
return userMapper.selectByCriteria(criteria);
}
}
<file_sep>package com.changer.jdktest.blockqueue;
/**
* Created by fcjiang on 15/11/27.
*/
public class MainTest {
public static void main(String[] args) {
final Business business = new Business();
new Thread(new Runnable(){
public void run() {
for(int i=0; i<5; i++){
business.sub(i);
}
}
}).start();
new Thread(new Runnable(){
public void run() {
for(int i=0; i<5; i++){
business.main(i);
}
}
}).start();
}
}
<file_sep>package com.changer.aspecj;
/**
* Created by fcjiang on 16/4/18.
*/
public class HelloWorldTest {
public void sayHelloWorld(){
System.out.println("Hello World in sayHelloWorld()");
}
public static void main(String[] args) {
HelloWorldTest helloWorldTest = new HelloWorldTest();
helloWorldTest.sayHelloWorld();
}
}
<file_sep>package com.changer.lambda;
/**
* @Project: Jdk8Test
* @Author: fcjiang
* @Date: 2016-08-06
*/
public class RunnableViaLambda {
public static void main(String[] args) {
new Runnable() {
@Override
public void run() {
System.out.println("通过匿名内部类实现Runnable");
}
};
int i = 30;
Runnable r = () -> {
System.out.println("通过lambda实现Runnable");
// i = i + 20; 不能修改外部方法的值
System.out.println("i = " + i); // i不需要设置final也可以访问.
};
r.run();
}
}
<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>com.changer</groupId>
<artifactId>modules</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>integration</module>
<module>common</module>
<module>datasource</module>
<module>web</module>
</modules>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Angel.SR3</version>
</parent>
<properties>
<build.Directory.war>../output/</build.Directory.war>
<build.Directory.task>../output/</build.Directory.task>
<extracted-resource>extracted-resource</extracted-resource>
</properties>
<dependencies>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>utf-8</encoding>
</configuration>
</plugin>
<!--<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.6</version>
<configuration>
<archive>
<manifest>
<mainClass>com.changer.Application</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>-->
</plugins>
</build>
<!--<build>
<plugins>
<plugin>
<!–
将各个模块中的配置文件单独拿出来,打包的时候发到一起,
以便于部署修改(主要是考虑 web/web-audit/predata/task 等独立部署的模块)
–>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependency-resource</id>
<phase>generate-resources</phase>
<goals>
<goal>unpack-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/${extracted-resource}</outputDirectory>
<includeGroupIds>${project.groupId}</includeGroupIds>
<excludeTransitive>false</excludeTransitive>
<includes>*.xml,*.properties</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>-->
</project><file_sep>package com.changer.configs;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
/**
* Created by enniu on 16/1/27.
*/
@Configuration
public class DatabaseConfig {
@Autowired
private Environment env;
@Autowired
private DataSource dataSource;
@Bean
public DataSource dataSource(){
org.apache.tomcat.jdbc.pool.DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource();
dataSource.setDriverClassName(env.getProperty("db.driver"));
dataSource.setUrl(env.getProperty("db.url"));
dataSource.setUsername(env.getProperty("db.username"));
dataSource.setPassword(env.getProperty("<PASSWORD>"));
return dataSource;
}
@Bean
public SqlSessionFactory getSqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));
return sqlSessionFactoryBean.getObject();
}
@Bean
public PlatformTransactionManager getTransactionManager(DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
}
<file_sep>package com.changer.cglibproxy;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
/**
* @Project: AopTest
* @Author: fcjiang
* @Date: 2017-02-19
*/
public class CGlibProxyFactory implements MethodInterceptor {
private Object targetObject;
public Object createProxy(Object targetObject) {
this.targetObject = targetObject;
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(targetObject.getClass());
enhancer.setCallback(this);
return enhancer.create();
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println(String.format("在intercept方法中... method=%s; object=; targetObject=%s",
method.getName(),
o.getClass().getName(),
targetObject.getClass().getName()));
return method.invoke(targetObject, objects);
}
}
<file_sep>name=fcjiang
age=30
className=com.changer.properties.PropertiesReader<file_sep>## 需要添加swagger2和swagger-ui两个依赖包
## 定义一个SwaggerConfig类,并且使能@EnableSwagger2。指定controller的扫描位置。
## 在MainApp里import进SwaggerConfig类。<file_sep>package com.changer.collectionremove;
import com.alibaba.fastjson.JSON;
import java.util.*;
/**
* Created by fcjiang on 16/2/22.
*/
public class MainApp {
public static void main(String[] args) {
/*Person person = new Person();
System.out.println(JSON.toJSONString(person));
BigDecimal salary2 = new BigDecimal("2.0000000");
person.setSalary(salary2);
System.out.println(JSON.toJSONString(person));*/
Long aa = new Long("1437039915000");
Date bb = new Date(aa);
List<Person> persons = new ArrayList<>();
Person fcjiang = new Person("fcjiang", 100);
Person fcjiang2 = new Person("fcjiang", 99);
Person sszhu = new Person("sszhu", 20);
persons.add(fcjiang);
persons.add(fcjiang2);
persons.add(sszhu);
System.out.println(JSON.toJSONString(persons));
Map<String, Person> tempMap = new HashMap<>();
for (Iterator<Person> iterator = persons.iterator(); iterator.hasNext(); ){
Person person = iterator.next();
tempMap.put(person.getName(), person);
}
System.out.println(JSON.toJSONString(tempMap));
tempMap.remove("sszhu");
tempMap.get("fcjiang").setAge(30);
System.out.println(JSON.toJSONString(tempMap));
System.out.println(JSON.toJSONString(persons));
}
}
<file_sep>package com.changer.kafkatest;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
/**
* Created by fcjiang on 15/11/27.
*/
public class ConsumerMsgTask implements Runnable {
private KafkaStream stream;
private int threadNum;
public ConsumerMsgTask(KafkaStream stream, int threadNum) {
this.stream = stream;
this.threadNum = threadNum;
}
@Override
public void run() {
ConsumerIterator<byte[], byte[]> it = stream.iterator();
while(it.hasNext()){
System.out.println("Thread " + threadNum + ": " + new String(it.next().message()));
System.out.println("Shutting down Thread: " + threadNum);
}
}
}
<file_sep>package com.changer.fileutil;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by fcjiang on 16/3/8.
*/
@Service
public class FileLoader {
public void read() throws IOException {
getResource();
}
public void getResource() throws IOException {
InputStream is = this.getClass().getResourceAsStream("/resource/test.txt");
String fileContent = IOUtils.toString(is);
System.out.println(fileContent);
}
}
<file_sep>package com.changer.pattern.bridge;
/**
* @Project: JdkTest
* @Author: fcjiang
* @Date: 2016-12-10
*/
public abstract class Image {
protected IPlatform platform;
public abstract void parseFile(String fileName);
public void setPlatform(IPlatform platform) {
this.platform = platform;
}
}
<file_sep>package com.changer.okhttp3;
/**
* @Project: HelloWorld
* @Author: fcjiang
* @Date: 2016-08-14
*/
public enum EndpointEnums {
OrdersByUserId("/orders/%s", "查询客户订单"),
OrdersByLoanType("/orders/loanType", "查询产品订单");
private String url;
private String desc;
EndpointEnums(String url, String desc) {
this.url = url;
this.desc = desc;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
<file_sep>package com.changer;
/**
* @Project: JdkTest
* @Author: fcjiang
* @Date: 2016-11-04
*/
public class Demo {
public static void main(String[] args) {
Long aa = new Long(10);
System.out.println(aa.toString());
}
}
<file_sep>## 使用@ConfigurationProperty注解
特别需要注意,在MainApp加入@EnableConfigurationProperties({DataSourceProperty.class, KafkaProperty.class})。
把要用到的每个xxProperty都显示的放到@EnableConfigurationProperties注解中。
更详细的用法可参照[http://wiselyman.iteye.com/blog/2184586](http://wiselyman.iteye.com/blog/2184586)<file_sep>package com.changer.springboot;
import org.springframework.context.ApplicationContext;
/**
* @Project: HelloWorld
* @Author: fcjiang
* @Date: 2016-11-30
*/
public class MyUtil {
private static AccountConfig accountConfig = null;
static {
System.out.println("===进入MyUtil static代码块===");
if (accountConfig == null) {
ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
accountConfig = applicationContext.getBean(AccountConfig.class);
// System.out.println("accountConfig内容" + JSON.toJSONString(accountConfig));
}
}
public static void doSome() {
System.out.println("在静态工具类中获取到了properties文件中的内容");
System.out.println("username=" + accountConfig.getUsername() + "; password=" + accountConfig.getPassword());
}
public static AccountConfig getAccountConfig() {
return accountConfig;
}
public static void setAccountConfig(AccountConfig accountConfig) {
MyUtil.accountConfig = accountConfig;
}
}
<file_sep>package com.changer.pattern.command;
/**
* @Project: JdkTest
* @Author: fcjiang
* @Date: 2017-06-08
* http://blog.csdn.net/jason0539/article/details/45110355
*/
public class App {
public static void main(String[] args) {
TVReceiver tvReceiver = new TVReceiver();
Command command = new TurnOnCommand(tvReceiver);
command.execute();
command = new ChangeRadioCommand(tvReceiver);
command.execute();
command = new TurnOffCommand(tvReceiver);
command.execute();
}
}
<file_sep>package com.changer.configs;
import com.changer.model.ApiResp;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* @Project: SpringbootDevTest
* @Author: fcjiang
* @Date: 2016-06-29
*/
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = {IllegalArgumentException.class})
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public ApiResp handleIllegalArgumentException() {
System.out.println("===我是输出===");
ApiResp apiResp = new ApiResp("1000", "参数错误");
return apiResp;
}
}
<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>com.changer</groupId>
<artifactId>spring-boot-hello</artifactId>
<version>1.0-SNAPSHOT</version>
<!--配置spring-boot需要的依赖-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--配置log4j2依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<!--配置rabRabbitMQ依赖-->
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>3.6.1</version>
</dependency>
<!--配置fastJson依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.5</version>
</dependency>
<!--配置commons-config依赖-->
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.10</version>
</dependency>
</dependencies>
</project><file_sep>package com.changer.log4j.aa.c;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @Project: JdkTest
* @Author: fcjiang
* @Date: 2016-05-12
*/
public class PersonSevice {
public static final Logger paycenterLogger = LoggerFactory.getLogger("paycenterLogger");
public static final Logger logger = LoggerFactory.getLogger(PersonSevice.class);
public void listPerson() {
paycenterLogger.info("[paycenterLogger] come into listPerson method");
com.changer.log4j.aa.b.Person person = new com.changer.log4j.aa.b.Person();
person.setName("fcjiang");
person.setAge(20);
// logger.info("[jdLogger]" + JSON.toJSONString(person));
}
}
<file_sep>http://www.mkyong.com/spring/spring-aop-examples-advice<file_sep>package com.changer.kafkatest;
import kafka.producer.Partitioner;
/**
* Created by fcjiang on 15/11/27.
*/
public class PartitionerDemo implements Partitioner {
@Override
public int partition(Object o, int i) {
return 0;
}
}
<file_sep>account.username=fcjiang
account.password=<PASSWORD><file_sep>package com.changer.cipher.msgencode;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.IOException;
import java.text.MessageFormat;
/**
* Created by fcjiang on 16/3/16.
*/
public class MainApp {
public static void main(String[] args) throws IOException {
String plainMsg = "TodayIsSunday";
BASE64Encoder base64Encoder = new BASE64Encoder();
String cipherMsg = base64Encoder.encode(plainMsg.getBytes());
System.out.println(MessageFormat.format("{0} >>>>BASE64±àÂë>>>> {1}", plainMsg, cipherMsg));
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] resultBytes = base64Decoder.decodeBuffer(cipherMsg);
String plainMsg2 = new String(resultBytes);
System.out.println(MessageFormat.format("{0} >>>>BASE64½âÂë>>>> {1}", cipherMsg, plainMsg2));
}
}
<file_sep>package com.changer.jvmtest.visualvm;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @Project: JVMTest
* @Author: fcjiang
* @Date: 2016-05-19
*/
public class BTraceDemo {
public static void main(String[] args) throws ParseException, InterruptedException {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date targe = sdf.parse("2016-05-19 20:30:00");
while (new Date().before(targe)) {
Thread.sleep(5000);
System.out.println("现在时间: " + sdf.format(new Date()));
double a = Math.random() * 100;
double b = Math.random() * 100;
System.out.println("参数 a = " + a);
System.out.println("参数 b = " + b);
System.out.println("计算结果:" + add(a, b));
}
}
public static double add(double a, double b) {
return a + b;
}
}
<file_sep>package com.changer.configs;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CharacterEncodingFilter;
import javax.servlet.Filter;
/**
* @Project: SpringbootDevTest
* @Author: fcjiang
* @Date: 2016-06-29
*/
@Configuration
public class FilterConfig {
@Bean
public Filter getEncodingFilter() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
return characterEncodingFilter;
}
}
<file_sep>package com.changer.rabbitmq;
import com.rabbitmq.client.*;
import java.io.IOException;
/**
* @Project: HelloWorld
* @Author: fcjiang
* @Date: 2016-11-26
*/
public class RabbitMqConsumer {
/**
* 从配置文件读取
*/
private static String host = "127.0.0.1";
private static int port = 5672;
private static String vhost = "/fdtClearing";
private static String userName = "fdtClearing";
private static String password = "<PASSWORD>";
private static String exchange = "agreement";
private static String bindingKey = "agreement.success";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(host);
factory.setPort(port);
factory.setUsername(userName);
factory.setPassword(<PASSWORD>);
factory.setVirtualHost(vhost);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(exchange, "topic", true);
String queueName = channel.queueDeclare().getQueue();
channel.queueBind(queueName, exchange, bindingKey);
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope,
AMQP.BasicProperties properties, byte[] body) throws IOException {
String message = new String(body, "UTF-8");
// todo 业务逻辑放在这儿
System.out.println(" [x] Received '" + envelope.getRoutingKey() + "':'" + message + "'");
}
};
// 阻塞在这儿监听
channel.basicConsume(queueName, true, consumer);
System.out.println("consumer执行完成");
}
}
<file_sep>package com.changer.cipher.symmetric;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.NoSuchAlgorithmException;
/**
* Created by fcjiang on 16/3/17.
*/
public class SymmetricUtil {
public static byte[] initDESKey() throws NoSuchAlgorithmException {
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
// 初始化秘钥生成器
keyGenerator.init(56);
SecretKey secretKey = keyGenerator.generateKey();
byte[] keyBytes = secretKey.getEncoded();
return keyBytes;
}
public static String encryptByDES(byte[] data, byte[] key) throws Exception {
SecretKey secretKey = new SecretKeySpec(key, "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] resultBytes = cipher.doFinal(data);
// todo 加密时byte数组转换成HEX串
return DatatypeConverter.printHexBinary(resultBytes);
}
public static String decryptByDES(byte[] data, byte[] key) throws Exception {
SecretKey secretKey = new SecretKeySpec(key, "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] resultBytes = cipher.doFinal(data);
// todo 解密时byte数组转成String对象
return new String(resultBytes);
}
}
<file_sep>package com.changer.pattern.observer;
import java.util.Observable;
/**
* @Project: JdkTest
* @Author: fcjiang
* @Date: 2016-05-17
*/
public class ObservableTeacher extends Observable {
public String publishNotice() {
return "[明天下雪,放假一天]";
}
public void watchWeatherReport(String weather) {
System.out.println("老师开始观看天气预报...");
System.out.println("预报: " + weather);
if (weather.equalsIgnoreCase("下雪")) {
// todo 只有setChanged之后,notifyObservers才会真正触发observer去执行update方法
setChanged();
notifyObservers();
}
}
}
<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>com.changer</groupId>
<artifactId>spring-boot-mysql-mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<name>spring-boot-mysql-mybatis</name>
<description>Use Mybatis + MySQL in Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.3.RELEASE</version>
<relativePath />
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<!--Mysql / DataSource-->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--自行添加用于JSON操作-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.7</version>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<start-class>com.changer.Application</start-class>
<java.version>1.7</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.4-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<!--<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>${sqlserver-jtds-driver.version}</version>
</dependency>-->
</dependencies>
</plugin>
</plugins>
</build>
</project><file_sep>package com.changer.demo4;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
/**
* Created by fcjiang on 15/10/25.
*/
public class AccountDao extends JdbcDaoSupport {
public void outMoney(String out, Double money){
String sql = "update account set money = money - ? where name = ?";
this.getJdbcTemplate().update(sql, money, out);
}
public void inMoney(String in, Double money){
String sql = "update account set money = money + ? where name = ?";
this.getJdbcTemplate().update(sql, money, in);
}
}
<file_sep>## 消息编码
用到的类是 `BASE64Encoder` 和 `BASE64Decoder`,这两个类所在的包有点特殊是`sun.misc`
消息编码是`可逆的`,编码之后产生的byte[]可以直接转换为String。`new String(byte[] bytes)`
## 消息摘要
用到的类是`MessageDigest`
```
// 获取实例
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
```
消息摘要是`不可逆的` ,摘要值的byte[]不可以直接转换为String。需要借助JDK自带的`DatatypeConverter`转换为十六进制的hex值。
消息摘要有3种实现方式,一种为`MD5`,一种为`SHA`(安全HASH)。其中,`SHA`又分为`SHA-1`/`SHA-256`/`SHA-384`/`SHA-512`.
还有一种是`Hmac`,它结合了MD5和SHA的优点,需要提供秘钥,然后让秘钥去给内容做消息摘要。`Hmac`常用的形式有`HmacMD5`/`HmacSHA1`/`HmacSHA256`/`HmacSHA384`/`HmacSHA512`
**获取文件的MD5值 不等于 获取文件内容的MD5.**
有一个字符串“helloworld”,还有一个文件aa.txt,文件里的内容也为"helloworld". 字符串的MD5值与aa.txt文件的MD5值不一样。
## 对称加密
加密时用的秘钥和解密时的秘钥相同。
### DES
### 3DES
### AES
## 非对称加密
数据加密:加密时用公钥,解密时用私钥。
`KeyPairGenerator`产生密钥对。
### DH算法
### RSA算法
<file_sep>package com.changer.util;
import com.changer.service.PersonService;
/**
* Created by fcjiang on 15/11/1.
*/
public class MyUtil {
private static PersonService personService;
public static String getPersonServiceName() {
return personService.getName();
}
public void setPersonService(PersonService personService) {
MyUtil.personService = personService;
}
}
<file_sep>package com.changer.queue;
import java.util.concurrent.BlockingQueue;
/**
* @Project: JdkTest
* @Author: fcjiang
* @Date: 2016-11-20
*/
public class Consumer implements Runnable {
private BlockingQueue blockingQueue;
public Consumer(BlockingQueue blockingQueue) {
this.blockingQueue = blockingQueue;
}
@Override
public void run() {
while (blockingQueue.remainingCapacity() > 0) {
try {
Thread.sleep(2 * 1000L);
System.out.println(String.format("队列大小%s, 消费队列中的元素%s", blockingQueue.size(), blockingQueue.take()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
<file_sep>需要引入依赖
```
<!-- joda-time依赖 -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.4</version>
</dependency>
```<file_sep>package com.changer.config;
import com.changer.controller.PersonController;
import com.google.common.base.Predicate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Created by bob on 15/9/20.
*/
@EnableSwagger2
@ComponentScan(basePackageClasses = PersonController.class) // 告诉springboot去该controller同级目录下扫描其它controller
public class SwaggerConfig extends WebMvcConfigurerAdapter {
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.paths(apiPaths())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("swagger测试Demo")
.description("swagger测试Demo,API适用说明。")
.termsOfServiceUrl("http://127.0.0.1:8080/v2/api-docs")
.contact("<EMAIL>")
.license("Apache License Version 2.0")
.licenseUrl("https://github.com/springfox/springfox/blob/master/LICENSE")
.version("2.0")
.build();
}
private Predicate<String> apiPaths() {
return new Predicate<String>() {
@Override
public boolean apply(String input) {
return input.contains("api"); // 适配含“api”关键字的接口
}
};
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
if(!registry.hasMappingForPattern("swagger-ui.html")){
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
}
if(!registry.hasMappingForPattern("/webjars/**")) {
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
}<file_sep>package com.changer.controllers;
import com.alibaba.fastjson.JSON;
import com.changer.models.ApiResp;
import com.changer.models.Person;
import com.changer.utils.RabbitmqUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
/**
* @Project: spring-boot-hello
* @Author: fcjiang
* @Date: 2016-06-30
*/
@RestController
@RequestMapping("/person")
public class PersonController {
private static final Logger logger = LoggerFactory.getLogger(PersonController.class);
@RequestMapping("/all")
public ApiResp listAll() {
Person fcjiang = new Person("fcjiang", 30);
Person sszhu = new Person("sszhu", 18);
List<Person> persons = Arrays.asList(fcjiang, sszhu);
System.out.println("获取persons成功");
ApiResp<List<Person>> apiResp = new ApiResp<>("0000", "成功", persons);
return apiResp;
}
@RequestMapping("/create")
public void creat(@RequestParam("name") String name, @RequestParam("age") int age) {
Person person = new Person(name, age);
String msg = JSON.toJSONString(person);
ConnectionFactory connectionFactory = RabbitmqUtil.getConnectionFactory();
Connection connection = null;
Channel channel = null;
try {
connection = connectionFactory.newConnection();
channel = connection.createChannel();
channel.exchangeDeclare(RabbitmqUtil.getExchange(), "fanout");
channel.basicPublish(RabbitmqUtil.getExchange(), RabbitmqUtil.getQueue(), null, msg.getBytes("UTF-8"));
logger.info("生产:{}", msg);
}
catch (Exception e) {
logger.info("往RabbitMQ中生成内容时异常", e);
}
finally {
try {
if (channel != null)
channel.close();
if (connection != null)
connection.close();
}
catch (Exception e) {
logger.info("关闭channel或者connection时发生异常", e);
}
}
}
}
<file_sep>### 判断字符串中所有字符都为数字
<file_sep>package com.changer.lambda;
import com.alibaba.fastjson.JSON;
import java.util.*;
/**
* @Project: Jdk8Test
* @Author: fcjiang
* @Date: 2016-08-07
*/
public class ComparatorLambdaDemo {
public static void main(String[] args) {
List<Human> humans = new ArrayList<>();
Human sszhu = new Human("sszhu", 18);
Human fcjiang = new Human("fcjiang", 30);
Human wukong = new Human("wukong", 500);
humans.add(sszhu);
humans.add(fcjiang);
humans.add(wukong);
// System.out.println("\n 匿名类方式实现");
// sortByOldWay(humans);
System.out.println("\n lambda方式实现");
sortByOldWay(humans);
}
public static void sortByOldWay(List<Human> humans) {
System.out.println("排序前:" + JSON.toJSONString(humans));
Collections.sort(humans, new Comparator<Human>() {
@Override
public int compare(Human o1, Human o2) {
return o1.getName().compareTo(o2.getName());
}
});
System.out.println("排序后:" + JSON.toJSONString(humans));
}
public static void sortByLambda(List<Human> humans) {
System.out.println("排序前:" + JSON.toJSONString(humans));
humans.sort((h1, h2) -> h1.getName().compareTo(h2.getName()));
System.out.println("排序后:" + JSON.toJSONString(humans));
}
static class Human {
private String name;
private int age;
public Human(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
}
<file_sep># 初次使用srping-boot
在`pom.xml`文件中添加`parent`和`dependency`.
具体如下:
```
<!--配置spring-boot需要的依赖-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
```
# spring-boot各知识点学习
## 全局异常处理
增加一个类,添加注解`@ControllerAdvice`
## 添加`filter`和`servlet`以及执行顺序
添加自定义的filter,主要有3种方式:
- 方式1:
1. 编写自定义的filter类,例如LogFilter.(什么注解都不要加)
2. 将LogFilter在configuration中实例化为bean.
- 方式2:
1. 定义LogFilter(增加注解`@WebFilter`)
2. 在Application类前面增加注解`@ServletComponentScan`(这种情况下无需`@Configuration`注入bean)
- 方式3:
1. 定义LogFilter(无任何注解)
2. 在`@Configuration`中实例化`ServletRegistrationBean`,并且将LogFilter设置到`ServletRegistrationBean`中.
## 添加拦截器`Interceptor`
让application类extends`WebMvcConfigurerAdapter`,
然后重写`addInterceptors()`方法.
如下:
```
registry.addInterceptor(new UserSecurityInterceptor()).addPathPatterns("/user/**");
```<file_sep>package com.changer.jvmtest.memoryallocate;
/**
* 启动参数: -verbose:gc -Xms20M -Xmx20M -Xmn10M -XX:+PrintGCDetails -XX:SurvivorRatio=8
*
* 指定Heap最小20M,最大20M.其中10M是Eden区(-Xmn10M),剩下的10M是老年代. Eden区是Survivor区的8倍, 8x+2x=10M,算出Eden区8M空间.
*
* Created by fcjiang on 16/4/15.
*/
public class EdenMinorGC {
private static final int _1MB = 1024 * 1024;
public static void main(String[] args) {
byte[] allocation1, allocation2, allocation3, allocation4;
allocation1 = new byte[2 * _1MB];
allocation2 = new byte[2 * _1MB];
allocation3 = new byte[2 * _1MB];
allocation4 = new byte[2 * _1MB];
allocation1 = new byte[4 * _1MB]; // 发生一次MinorGC
}
}
<file_sep>package com.changer.cipher.msgdigest;
import javax.xml.bind.DatatypeConverter;
import java.text.MessageFormat;
/**
* Created by fcjiang on 16/3/16.
*/
public class MainApp {
public static void main(String[] args) throws Exception {
String plainMsg = "TodayIsSunday";
System.out.println(MessageFormat.format("{0} >>>>消息摘要 MD5值>>>> {1}", plainMsg, DigestUtil.getMD5(plainMsg)));
String filePath = "/Users/fcjiang/aa.txt";
System.out.println(MessageFormat.format("{0} >>>>文件消息摘要 MD5值>>>> {1}", filePath, DigestUtil.getMD5OfFile(filePath)));
System.out.println(MessageFormat.format("{0} >>>>消息摘要 SHA1值>>>> {1}", plainMsg, DigestUtil.getSHA1(plainMsg)));
System.out.println(MessageFormat.format("{0} >>>>消息摘要 SHA256值>>>> {1}", plainMsg, DigestUtil.getSHA256(plainMsg)));
System.out.println(MessageFormat.format("{0} >>>>消息摘要 SHA384值>>>> {1}", plainMsg, DigestUtil.getSHA384(plainMsg)));
System.out.println(MessageFormat.format("{0} >>>>消息摘要 SHA512值>>>> {1}", plainMsg, DigestUtil.getSHA512(plainMsg)));
byte[] keyBytes = DigestUtil.initHmacKey();
System.out.println(MessageFormat.format(">>>>产生HmacMD5秘钥>>>> {0}", DatatypeConverter.printHexBinary(keyBytes)));
System.out.println(MessageFormat.format("{0} >>>>消息摘要 HmacMD5值>>>> {1}", plainMsg, DigestUtil.getHmacMD5(plainMsg.getBytes(), keyBytes)));
}
}
<file_sep>package com.changer.cipher.asymmetric;
import javax.crypto.Cipher;
import javax.xml.bind.DatatypeConverter;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;
/**
* Created by fcjiang on 16/3/17.
*/
public class AsymmetricUtil {
public static Map<String, Object> initRSAKey() throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024); // 设置秘钥长度 允许范围512-65536 必须是64的倍数
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
Map<String, Object> keyMap = new HashMap<>();
keyMap.put("rsaPublicKey", rsaPublicKey);
keyMap.put("rsaPrivateKey", rsaPrivateKey);
return keyMap;
}
public static String encryptByRSA(byte[] data, RSAPublicKey rsaPublicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);
byte[] resultBytes = cipher.doFinal(data);
// todo 加密时byte数组转换成HEX串
return DatatypeConverter.printHexBinary(resultBytes);
}
public static String decryptByRSA(byte[] data, RSAPrivateKey rsaPrivateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, rsaPrivateKey);
byte[] resultBytes = cipher.doFinal(data);
// todo 解密时byte数组转成String对象
return new String(resultBytes);
}
}
<file_sep>## BlockingQueue 阻塞队列
1. 往队列里塞数据 ```queue.put(xxx)``` 如果队列已经满了,线程会阻塞。
2. 从队列里读取数据 ```queue.take()``` 如果队列里没有可取的数据,线程就会阻塞等在这儿。<file_sep>package com.changer.calendar;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* @Project: JdkTest
* @Author: fcjiang
* @Date: 2016-06-22
*/
public class App {
public static void main(String[] args) throws ParseException {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Date fullAt = sdf.parse("2016-01-31 08:00:00");
Date fullAt = sdf.parse("2016-03-01 08:00:00");
System.out.println("fullAt = " + sdf.format(fullAt));
Date dueAt = calcDueAt(fullAt, 1);
System.out.println("dueAt = " + sdf.format(dueAt));
Date userDueAt = calcUserDueAt(fullAt, 1);
System.out.println("userDueAt = " + sdf.format(userDueAt));
}
public static Date calcDueAt(Date fullAt, int curDivNum) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(fullAt);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
int tDay=calendar.get(Calendar.DAY_OF_MONTH);
// Calendar加月份,如果对日不存在,Calendar就会是该月的最后一天
calendar.add(Calendar.MONTH, curDivNum);
calendar.add(Calendar.DAY_OF_MONTH, -1);
return calendar.getTime();
}
public static Date calcUserDueAt(Date fullAt, int curDivNum) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(fullAt);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
int tDay=calendar.get(Calendar.DAY_OF_MONTH);
// Calendar加月份,如果对日不存在,Calendar就会是该月的最后一天
calendar.add(Calendar.MONTH, curDivNum);
int nTDay = calendar.get(Calendar.DAY_OF_MONTH);
if (nTDay == tDay) { // 对日存在
calendar.add(Calendar.DAY_OF_MONTH, -2);
}
else { // 对日不存在
calendar.add(Calendar.DAY_OF_MONTH, -1);
}
return calendar.getTime();
}
}
<file_sep>package com.changer.pattern.command;
/**
* @Project: JdkTest
* @Author: fcjiang
* @Date: 2017-06-08
*/
public class TVReceiver {
public void turnOn() {
System.out.println("turn on the TV");
}
public void turnOff() {
System.out.println("turn off the TV");
}
public void changeRadio(int channelId) {
System.out.println("change radio to channel " + channelId);
}
}
<file_sep>package com.changer.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by fcjiang on 15/11/19.
*/
@RestController
@RequestMapping("person")
public class PersonController {
@RequestMapping("/sayhello")
public String sayHello(){
return "Hello world";
}
}
<file_sep>package com.changer;
import com.changer.properties.DataSourceProperty;
import com.changer.properties.KafkaProperty;
import com.changer.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by fcjiang on 15/10/31.
*/
@RestController
@SpringBootApplication
@EnableConfigurationProperties({DataSourceProperty.class, KafkaProperty.class})
public class Application {
@Autowired
private PersonService personService22;
@RequestMapping("/")
String hello(){
System.out.println("person name: " + personService22.getName());
System.out.println("personService22=" + personService22);
System.out.println("personService22 bean hash code is " + personService22.hashCode());
return "hello to spring boot";
}
public static void main(String[] args) throws Exception{
System.out.println("begin.......................");
SpringApplication.run(Application.class, args);
//Person.introduce();
}
}
<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>com.changer</groupId>
<artifactId>helloworld</artifactId>
<version>1.0-SNAPSHOT</version>
<!--测试springboot用-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
<!--测试springboot用-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--测试okhttp3需要的依赖-->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.2.0</version>
</dependency>
<!--测试okio需要的依赖-->
<dependency>
<groupId>com.squareup.okio</groupId>
<artifactId>okio</artifactId>
<version>1.8.0</version>
</dependency>
<!-- joda-time依赖 -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.kafka/kafka_2.11 -->
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka_2.11</artifactId>
<version>0.10.0.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.9</version>
</dependency>
<!--以下为slf4j+log4j2依赖-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.6.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.squareup.retrofit2/retrofit -->
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>2.0.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.lmax/disruptor -->
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>3.3.6</version>
</dependency>
<!-- RabbitMQ依赖包 -->
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>3.6.5</version>
</dependency>
<!--google guava库依赖-->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>21.0</version>
</dependency>
</dependencies>
<!--测试springboot用-->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<start-class>com.changer.springboot.Application</start-class>
<java.version>1.7</java.version>
</properties>
<profiles>
<profile>
<id>check-code</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<configuration>
<configLocation>static-analysis/checkstyle.xml</configLocation>
<failsOnError>false</failsOnError>
<consoleOutput>true</consoleOutput>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<configuration>
<targetJdk>1.7</targetJdk>
<rulesets>
<ruleset>../static-analysis/pmdrules.xml</ruleset>
</rulesets>
<excludes>
<exclude>**/target/generated-sources/**</exclude>
</excludes>
<verbose>true</verbose>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project><file_sep>package com.changer.springaopaspectj_fc;
import com.alibaba.fastjson.JSON;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.math.BigDecimal;
/**
* Created by fcjiang on 16/4/21.
*/
public class App {
public static void main(String[] args) {
System.out.println("我是中文");
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext(new String[]{"/springaopaspectj_fc.xml"});
Person person = (Person) classPathXmlApplicationContext.getBean("person");
person.setSalary(new BigDecimal("100.122"));
System.out.println(JSON.toJSONString(person));
}
}
<file_sep>package com.changer.jdkproxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @Project: AopTest
* @Author: fcjiang
* @Date: 2017-02-19
*/
public class JdkProxyFactory implements InvocationHandler {
private Object targetObject;
public Object createProxy(Object targetObject) {
this.targetObject = targetObject;
return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(), targetObject.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("在invoke方法里, 接下来执行method " + method.getName());
return method.invoke(targetObject, args);
}
}
<file_sep>package com.changer.pattern.observer;
import java.text.MessageFormat;
import java.util.Observable;
import java.util.Observer;
/**
* @Project: JdkTest
* @Author: fcjiang
* @Date: 2016-05-17
*/
public class ObserverStudent implements Observer {
private String name;
private int score;
public ObserverStudent() {
}
public ObserverStudent(String name, int score) {
this.name = name;
this.score = score;
}
@Override
public void update(Observable o, Object arg) {
System.out.println(MessageFormat.format("===姓名{0},分数{1}, 接到老师通知{2}", this.name, this.score, ((ObservableTeacher)o).publishNotice()));
}
}
<file_sep>package com.changer.configs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
/**
* @Project: spring-boot-hello
* @Author: fcjiang
* @Date: 2016-06-30
*/
@WebFilter(urlPatterns = {"/*"})
public class LogFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(LogFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
logger.info("logFilter初始化成功");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
logger.info("step into logFilter");
filterChain.doFilter(servletRequest, servletResponse);
logger.info("step out logFilter");
}
@Override
public void destroy() {
logger.info("logFilter注销完成");
}
}
<file_sep>package com.changer.daos.entities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by fcjiang on 16/2/1.
*/
public class User {
private static final Logger logger = LoggerFactory.getLogger(User.class);
private String name;
private int age;
private byte gender;
public String getName() {
return name;
}
public void setName(String name) {
logger.info("开始setName name=" + name);
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public byte getGender() {
return gender;
}
public void setGender(byte gender) {
this.gender = gender;
}
}
<file_sep>package com.changer.pattern.template;
/**
* @Project: JdkTest
* @Author: fcjiang
* @Date: 2016-07-28
*/
public class ICBCBank extends AbstractBank {
@Override
protected String doCalAccountType() {
System.out.println("ICBCBank's account type is 国有商业银行");
return "国有商业银行";
}
@Override
protected double doCalInterestRate() {
System.out.println("ICBCBank's interest rate is 0.01");
return 0.01;
}
@Override
protected double doGetCapital() {
System.out.println("ICBCBank's capital is 10000.00");
return 10000.00;
}
}
<file_sep>package com.changer.pattern.bridge;
/**
* @Project: JdkTest
* @Author: fcjiang
* @Date: 2016-12-10
*/
public class PNGImage extends Image {
@Override
public void parseFile(String fileName) {
//模拟解析PNG文件并获得一个像素矩阵对象m;
Matrix m = new Matrix();
platform.doPaint(m);
System.out.println(fileName + ",格式为PNG。");
}
}
<file_sep>package com.changer.properties;
import java.util.Map;
/**
* @Project: JdkTest
* @Author: fcjiang
* @Date: 2016-11-13
*/
public class Demo {
public static void main(String[] args) {
String fileName = "/myProperties2.properties";
// String fileName = "/myProperties1.properties"; // myProperties1不会成功,原因是编译后,这个文件没有被拷贝到target/classes目录下。
Map<String, String> propertiesMap = new PropertiesReader().getPropertiesMap(fileName);
for (String key : propertiesMap.keySet()) {
System.out.println(String.format("key:%s, value:%s", key, (String)propertiesMap.get(key)));
}
}
}
<file_sep>package com.changer.service;
import com.changer.util.EnviSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
/**
* Created by fcjiang on 15/10/31.
*/
@Service
public class LoadSettingsService {
@Autowired
private EnviSettings enviSettings;
@PostConstruct
public void printSettings(){
System.out.println(enviSettings);
System.out.println(enviSettings.getServer());
}
}
<file_sep>package com.changer.jdkproxy;
import java.math.BigDecimal;
/**
* @Project: AopTest
* @Author: fcjiang
* @Date: 2017-02-19
*/
public class CalMoneyImpl implements ICalMoney {
@Override
public BigDecimal multiply(BigDecimal count, BigDecimal price) {
BigDecimal money = count.multiply(price);
System.out.println(String.format("money = %s * %s = %s", count.toString(), price.toString(), money.toString()));
return money;
}
}
<file_sep>jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/fcjiangDB
jdbc.user=root
jdbc.password=<PASSWORD><file_sep>package com.changer.okio;
import okio.*;
import java.io.File;
import java.io.IOException;
/**
* @Project: HelloWorld
* @Author: fcjiang
* @Date: 2016-05-21
*/
public class App {
public static void main(String[] args) throws IOException {
copyFile("/Users/fcjiang/Code/GitHome/examples/HelloWorld/src/main/resources/aa.txt",
"/Users/fcjiang/Code/GitHome/examples/HelloWorld/src/main/resources/aa-" + System.currentTimeMillis() + ".txt");
}
public static void copyFile(String srcFilePath, String targetFilePath) throws IOException {
// InputStream inputStream = File.class.getResourceAsStream(srcFilePath);
Source source = Okio.source(new File(srcFilePath));
BufferedSource bufferedSource = Okio.buffer(source);
// todo 如果已经读出来了,则bufferedSource中就没数据了.
// String content = bufferedSource.readUtf8();
// System.out.println("conent = " + content);
Sink sink = Okio.sink(new File(targetFilePath));
BufferedSink bufferedSink = Okio.buffer(sink);
bufferedSink.writeAll(bufferedSource);
// bufferedSink.write(ByteString.encodeUtf8(content));
// todo 要输出到文件,一定要记录flush
bufferedSink.flush();
System.out.println("拷贝完成");
}
}
<file_sep>## examples from fcjiang
自己学习、备份的一些小Demo。
<file_sep>package com.changer.jvmtest.memoryallocate;
/**
* 启动参数: -verbose:gc -Xms20M -Xmx20M -Xmn10M -XX:+PrintGCDetails -XX:SurvivorRatio=8 -XX:MaxTenuringThreshold=15 -XX:+PrintTenuringDistribution
*
* 指定Heap最小20M,最大20M.其中10M是Eden区(-Xmn10M),剩下的10M是老年代. Eden区是Survivor区的8倍, 8x+2x=10M,算出Eden区8M空间.
*
* Created by fcjiang on 16/4/15.
*/
public class BigObjectCreateInOldGenerationxxxx {
private static final int _1MB = 1024 * 1024;
public static void main(String[] args) {
byte[] allocation1, allocation2, allocation3, allocation4;
allocation1 = new byte[_1MB / 4];
allocation2 = new byte[4 * _1MB];
allocation3 = new byte[4 * _1MB];
allocation3 = null;
allocation3 = new byte[4 * _1MB];
}
}
<file_sep>package com.changer.properties;
import com.changer.Application;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by fcjiang on 15/11/25.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@IntegrationTest
@ActiveProfiles("dev")
public class KafkaPropertyTest {
@Autowired
KafkaProperty kafkaProperty;
@Test
public void testKafkaProperty(){
System.out.println(kafkaProperty.getName());
System.out.println(kafkaProperty.getIp());
}
}
<file_sep>package com.changer.jdkproxy;
import java.math.BigDecimal;
/**
* @Project: AopTest
* @Author: fcjiang
* @Date: 2017-02-19
*/
public class Demo {
public static void main(String[] args) {
JdkProxyFactory jdkProxyFactory = new JdkProxyFactory();
ICalMoney calMoney = (ICalMoney) jdkProxyFactory.createProxy(new CalMoneyImpl());
BigDecimal count = new BigDecimal("5");
BigDecimal price = new BigDecimal("8.00");
BigDecimal result = calMoney.multiply(count, price);
System.out.printf("计算结果是 " + result.toPlainString());
}
}
<file_sep>package com.changer.configs;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* @Project: SpringbootDevTest
* @Author: fcjiang
* @Date: 2016-06-29
*/
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean
public FilterRegistrationBean getFilterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
filterRegistrationBean.setFilter(characterEncodingFilter);
filterRegistrationBean.addUrlPatterns("/*");
return filterRegistrationBean;
}
}
<file_sep>package com.changer.service;
import com.changer.model.Person;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* Created by fcjiang on 15/11/17.
*/
@Service
public class PersonService {
public List<Person> list(){
List<Person> persons = new ArrayList<>();
Person person = new Person();
person.setName("fcjiang");
person.setAge(20);
persons.add(person);
Person person2 = new Person();
person2.setName("sszhu");
person2.setAge(18);
persons.add(person2);
return persons;
}
}
<file_sep>http://www.mkyong.com/spring3/spring-aop-aspectj-annotation-example/
**编写切面类,必须要加注解**```@Aspect```
但不是创建*.aj文件
<file_sep>package com.changer.main;
import com.changer.utils.MyStringUtil;
/**
* Created by fcjiang on 15/12/24.
*/
public class TestMain {
public static void main(String[] args) {
String src = "123x";
if(MyStringUtil.isNumeric(src)){
System.out.println("all numerical");
}
else {
System.out.println("not all numerical");
}
if(MyStringUtil.isNumeric2(src)){
System.out.println("all numerical");
}
else {
System.out.println("not all numerical");
}
}
}
<file_sep>package com.changer.jvmtest.memoryallocate;
/**
* 启动参数: -verbose:gc -Xms20M -Xmx20M -Xmn10M -XX:+PrintGCDetails -XX:SurvivorRatio=8 -XX:PretenureSizeThreshold=3145728
*
* 指定Heap最小20M,最大20M.其中10M是Eden区(-Xmn10M),剩下的10M是老年代. Eden区是Survivor区的8倍, 8x+2x=10M,算出Eden区8M空间. PretenureSizeThreshold不能写成M的形式
*
* Created by fcjiang on 16/4/15.
*/
public class BigObjectCreateInOldGeneration {
private static final int _1MB = 1024 * 1024;
public static void main(String[] args) {
byte[] allocation;
allocation = new byte[4 * _1MB]; // 直接在老年代分配
}
}
<file_sep>package com.changer.dto;
/**
* Created by fcjiang on 16/3/22.
*/
public class Student extends Person {
private int score;
private String schoole;
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String getSchoole() {
return schoole;
}
public void setSchoole(String schoole) {
this.schoole = schoole;
}
}<file_sep>package com.changer.springaopaspectj_fc;
import java.lang.annotation.*;
/**
* Created by fcjiang on 16/4/21.
*/
@Target({ ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MoneyFormat {
String value() default "";
}
| b98c0a5aa4b8fd475b69a77fdbb9f4c5930204c0 | [
"Markdown",
"Java",
"Maven POM",
"INI"
] | 83 | Markdown | Changer119/examples | e0639e143d0e88a7203d38442eb2819250973cff | 0ddca1da46205e5c0b15b5c42dd572c3c4689603 | |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ChangeScene : MonoBehaviour
{
private List<string> _scenesNames = new List<string>() {"A", "B"};
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
int currentScene = _scenesNames.FindIndex(s => s == SceneManager.GetActiveScene().name);
if (++currentScene >= _scenesNames.Count)
{
currentScene = 0;
}
SceneManager.LoadScene(_scenesNames[currentScene]);
}
}
}
<file_sep># GameGraphicsHomework2
Instructions:
Press the space bar to change scenes while playing.
On the terrain scene, use up and down on the arrow keys to change the water level. Use left and right on the arrow keys to change
the terrain's height.
Scene A:
I used the bloom shader we made in lab here (Assets/Bloom.shader).
For the outline shader I adapted the code from this video: https://www.youtube.com/watch?v=OJkGGuudm38.
My main difference is that the fragment shaders final color is lerped from blue to pink. The more pink it is, the closer the normal
is to being perpendicular to the camera (Assets/Rim1.shader).
I downloaded the car model from a free asset website.
Screenshot: (Assets/AScreenshot.png)
Scene B:
I adapted Angus's code throughout here.
The shader was made by combining his Reflection.shader and his HillFromTexture.shader. My terrain shader (Assets/terrain.shader)
generates the terrain like HillFromTexture, but if the fragment is below the water level, it lerps the reflection from the skybox with
the terrain texture.
The mesh is generated from the MeshController script (Assets/MeshController.cs). It is the same as Angus's CreateMeshSimple script
except I added controls for changing the height of the terrain and the water level in the shader.
I downloaded the skybox from the asset store. I got the water texture from google images.
Screenshot: (Assets/BScreenshot.png)
Download: IanRapoport.com/IanRapoportHomework2.zip
| c60a09b560ab6aadb705bcd8e620e5551946af4c | [
"Markdown",
"C#"
] | 2 | C# | IanGRap/GameGraphicsHomework2 | 3e50e4c61409c42fcf3e1b8e9d2e7133b251c882 | 5c2a3f1619f489f1c7762cf038b59ed2aa8bf369 | |
refs/heads/master | <file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 22 02:28:47 2017
@title: PCW_bot
@author: SimplyAero
"""
import os
import re
import sys
import json
import urllib.request
from telegram import (
InlineQueryResultArticle,
InputTextMessageContent,
ParseMode
)
from telegram.ext import Updater, InlineQueryHandler
PCW = "https://wiki.pokemoncentral.it/api.php?"
TOKEN = os.getenv('TOKEN', sys.argv[-1]) # Retrieve the token either from env or cmd arg
HTML_REGEX = re.compile(r"<[\w/ =\"]+>", re.IGNORECASE)
class PageNotFoundError(Exception):
pass
class Page:
"""
@name: Page
@description: Class representing a wiki page
"""
opensearch = "action=opensearch&"\
"format=json&"\
"search={0}&"\
"namespace=0&"\
"limit=10&"\
"redirects=resolve&"\
"utf8=1&formatversion=2"
extract_query = "action=query&"\
"format=json&"\
"prop=extracts&"\
"indexpageids=1&"\
"titles={0}&"\
"utf8=1&"\
"formatversion=2&"\
"exchars=71&"\
"exsectionformat=raw"
def __init__(self, title: str, url: str):
self.title = title
self.url = url
query = Page.extract_query.format(title)
result_bytes = urllib.request.urlopen(PCW + query).read()
result_json = result_bytes.decode("utf-8")
result = json.loads(result_json)
extract = result["query"]["pages"][0]["extract"]
extract = HTML_REGEX.sub("", extract)
extract = extract.replace(" ", " ")
self.url = self.url.replace("(", "%28")
self.url = self.url.replace(")", "%29")
self.extract = extract
def __str__(self):
to_return = "*{0}*\n" + self.extract + " [(Continua a leggere)]({1})"
return to_return.format(self.title, self.url)
def get_pages(to_search: str) -> list:
query = Page.opensearch.format(to_search)
result_bytes = urllib.request.urlopen(PCW + query).read()
result_json = result_bytes.decode("utf-8")
result = json.loads(result_json)
if len(result[1]) < 1:
raise PageNotFoundError
else:
titles = result[1]
urls = result[3]
pages = []
for index in range(len(titles)):
pages.append(Page(titles[index], urls[index]))
return pages
def inline_pages(bot, update):
query = update.inline_query.query
if query:
results = list()
try:
pages = get_pages(query)
for page in pages:
content = str(page)
new_result = InlineQueryResultArticle(
id=page.title,
title=page.title,
input_message_content=InputTextMessageContent(
content,
parse_mode=ParseMode.MARKDOWN
)
)
results.append(new_result)
except PageNotFoundError:
new_result = InlineQueryResultArticle(
id="Pagina non trovata",
title="Pagina non trovata",
input_message_content=InputTextMessageContent(query)
)
results = [new_result]
bot.answer_inline_query(update.inline_query.id, results)
def main():
print("Starting bot...")
updater = Updater(token=TOKEN)
dispatcher = updater.dispatcher
inline_page_finder = InlineQueryHandler(inline_pages)
dispatcher.add_handler(inline_page_finder)
updater.start_polling()
print("Bot running.")
updater.idle()
if __name__ == "__main__":
main()
| 577221ef7f366fd76907b65ae49a87d07b799d0c | [
"Python"
] | 1 | Python | pokemoncentral/wiki-telegram-bot | 1f4dffa6759e0ecb65f626a89864887245e3f296 | 3f581a26032526c477cd8cb75b0b3fda5fb50ea3 | |
refs/heads/master | <repo_name>Kibaek/Java_project<file_sep>/zJavaProject/src/main/java/java63/servlets/london/ProductListServlet.java
package java63.servlets.london;
import java.io.IOException;
import java.io.PrintWriter;
import java63.servlets.london.dao.ProductDao;
import java63.servlets.london.domain.Product;
import javax.servlet.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
@WebServlet("/london/bookmark/list")
public class ProductListServlet extends GenericServlet {
private static final long serialVersionUID = 1L;
static final int PAGE_DEFAULT_SIZE = 3;
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
int pageNo = 0;
int pageSize = 0;
if (request.getParameter("pageNo") != null) {
pageNo = Integer.parseInt(request.getParameter("pageNo"));
pageSize = PAGE_DEFAULT_SIZE;
}
if (request.getParameter("pageSize") != null) {
pageSize = Integer.parseInt(request.getParameter("pageSize"));
}
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
RequestDispatcher rd =
request.getRequestDispatcher("/common/header");
rd.include(request, response);
out.println("<html>");
out.println("<head>");
//out.println("<meta charset='UTF-8'>");
out.println("<link rel='stylesheet' href='../../css/bootstrap.min.css'>");
out.println("<link rel='stylesheet' href='../../css/bootstrap-theme.min.css'>");
out.println("<link rel='stylesheet' href='../../css/common.css'>");
out.println("<script src='../../js/jquery-1.11.1.js'></script>");
out.println("<script src='../../js/bootstrap.min.js'></script>");
out.println("<script src='../../js/jquery.animate-shadow.js'></script>");
out.println("<title>JD_BookMark</title>");
out.println("</head>");
out.println("<body>");
out.println("<div class='container'>");
out.println(" <header>");
out.println(" <div id='headline'>");
out.println("<img src='https://pbs.twimg.com/profile_images/425962153103745024/9XJste4m.jpeg' width=200px>");
out.println(" </div>");
// <!-- Add_Button trigger modal -->
out.println(" </header>");
out.println(" <div class='boxWrapper'>");
out.println("<center>");
out.println("<form method=get action='http://www.google.co.kr/search' target='_blank' >");
out.println(" <table bgcolor='#FFFFFF'>");
out.println(" <tr>");
out.println(" <td>");
out.println(" <input type=text name=q size=50 maxlength=255 style='text-align:center' placeholder='검색어를 입력하세요!' />");
out.println(" <input type=hidden name=ie value=utf-8 />");
out.println(" <input type=hidden name=oe value=utf-8 />");
out.println(" <input type=hidden name=hl value=utf-8 />");
out.println(" <input type=submit name=btnG value='Search' />");
out.println(" </td>");
out.println(" </tr>");
out.println(" </table>");
out.println("</form>");
out.println("</center>");
ProductDao productDao = (ProductDao)this.getServletContext()
.getAttribute("productDao");
for (Product product : productDao.selectList(pageNo, pageSize)) {
out.println(" <div class='boxList'>");
out.println(" <div class='box' onclick=\"location.href='" + product.getUrl() + "'\" style='cursor:pointer;' \">");
out.println(" <h2>" + product.getName() + " </h2>");
out.println(" </div>");
out.println(" <div class='boxDetail'>");
out.println("<a href='view?dno=" + product.getDno() + "'> ShowDetail</a>");
//out.println(" <button type='button' class='btn btn-primary btn-xs' data-toggle='modal' data-target='#viewModal'>자세히보기</button>");
out.println(" </div>");
out.println(" </div>");
}
out.println(" <div class='boxList' height=250px>");
out.println(" <button type='button' class='btn btn-primary btn-sm' data-toggle='modal' data-target='#myModal'>+</button>");
out.println(" </div>");
out.println(" </div>");
// <!-- end of boxWrapper -->
out.println("</div>");
// <!-- end of container -->
//<!-- Add_Modal -->
out.println("<div class='modal fade' id='myModal' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'>");
out.println("<div class='modal-dialog'>");
out.println("<div class='modal-content'>");
out.println("<div class='modal-header'>");
out.println("<button type='button' class='close' data-dismiss='modal'>");
out.println("<span aria-hidden='true'>×</span><span class='sr-only'>Close</span>");
out.println("</button>");
out.println("<h3 class='modal-title' id='myModalLabel'>Bookmark_Add</h3>");
out.println("</div>");
out.println("<div class='modal-body'>");
out.println("<form class='form-horizontal' role='form' action='add' method='post'>");
out.println("<div class='form-group'>");
out.println("<label for='name' class='col-sm-2 control-label'>Site_Name</label>");
out.println("<div class='col-sm-10'>");
out.println("<input type='text' class='form-control' id='name' name='name' placeholder='이름을 입력해주세요. 예) java'>");
out.println("</div>");
out.println("</div>");
out.println("<div class='form-group'>");
out.println("<label for='url' class='col-sm-2 control-label'>URL</label>");
out.println("<div class='col-sm-10'>");
out.println("<input type='text' class='form-control' id='url' name='url' placeholder='주소를 입력해주세요. 예) http://www.java.com'>");
out.println("</div>");
out.println("</div>");
out.println("<div class='form-group'>");
out.println("<label for='info' class='col-sm-2 control-label'>Version</label>");
out.println("<div class='col-sm-10'>");
out.println("<input type='text' class='form-control' id='info' name='info' placeholder='버전 정보를 입력해주세요. 예) Java SE 8'>");
out.println("</div>");
out.println("</div>");
out.println("<div class='form-group'>");
out.println("<label for='memo' class='col-sm-2 control-label'>Comment</label>");
out.println("<div class='col-sm-10'>");
out.println("<input type='text' class='form-control' id='memo' name='memo' placeholder='메모를 남겨주세요. 예) JDK 7이상부터 switch는 string 가능'>");
out.println("</div>");
out.println("</div>");
// out.println("</form>");
out.println("</div>");
// out.println("<form class='form-horizontal' role='form' action='add' method='post'>");
out.println("<div class='modal-footer'>");
out.println("<button id='btnAdd' type='submit' class='btn btn-primary'>Add</button>");
out.println("<button id='btnCancel' type='button' class='btn btn-default' data-dismiss='modal'>Cancel</button>");
out.println("</div>");
out.println("</form>");
out.println("</div>");
out.println("</div>");
out.println("</div>");
//<!-- end of Add_Modal -->
//<!-- View_Modal -->
out.println("<script>");
out.println("$('#btnAdd').click(function() {");
out.println("if ($('#name').val().length == 0) {");
out.println("alert('이름은 필수 입력 항목입니다.');");
out.println("return false;");
out.println("}");
out.println("if ($('#url').val().length == 0) {");
out.println("alert('URL은 필수 입력 항목입니다.');");
out.println("return false;");
out.println("}");
out.println("});");
out.println("</script>");
out.println("</body>");
out.println("</html>");
System.out.println("service() 실행 완료");
}
}<file_sep>/zJavaWeb02/src/main/java/java63/servlets/test01/Test02.java
package java63.servlets.test01;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
/* 웹 브라우저에게 출력하기
*
*
* ServletRequest => 요청 정보를 다루는 도구
* ServletResponse => 응답 정보를 다루는 도구
*
*/
/*
* 한글 출력할 때 깨지는 문제 해결
*
* 이유 :
* ServletResponse가 준 출력 스트림은
* 기본적으로 출력할 때 ISO-8859-1로 인코딩한다.
* => 한글은 ISO-8859-1 문자집합에 없기 때문에 '?'로 대체하여 출력한다.
*
* 해결책 : ServletResponse로부터 출력 스트림을 얻기 전에,
* 출력할 내용의 타입과 문자집합을 설정한다.
* => response.setContentType("text/plain;charset=UTF-8")
* => response.setCharacterEncoding("UTF-8");
*
* MIME => 콘텐츠의 타입을 표현
*/
@WebServlet("/test01/Test02")
public class Test02 extends GenericServlet{
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
//1. ServletResponse 도구를 사용하여 출력 스트림을 준비한다.
//3. 한글출력 할 수 있게하기
//response.setCharacterEncoding("UTF-8");
//4. 한글출력 할 수 있게하기
response.setContentType("text/plain;charset=UTF-8");
PrintWriter out = response.getWriter();
// 2. 출력 스트림을 사용하여 브라우저로 출력한다.
out.println("아하~~안녕하세여?, 곤니찌와");
}
}
<file_sep>/zJavaProject/src/main/java/java63/servlets/london/HtmlFooterServlet.java
package java63.servlets.london;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
/* Include에 사용할 서블릿
* => HTML 페이지의 권리 안내문 출력을 맡는다.
*/
@WebServlet("/common/footer")
public class HtmlFooterServlet extends GenericServlet {
private static final long serialVersionUID = 1L;
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
/* HTML Entity => HTML의 상수
* & => &
* < => <
* > => >
* © => (C)
* ® => (R)
* ¥ => 엔화
*/
out.println("<address class='copyright'>Copyright©Java63</address>");
}
}
<file_sep>/projectLondon01/src/main/java/java63/servlets/test/DbmListServlet.java
package java63.servlets.test;
import java.io.IOException;
import java.io.PrintWriter;
import java63.servlets.test.dao.DbmDao;
import java63.servlets.test.domain.Dbm;
import javax.servlet.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
@WebServlet("/test/dbm/list")
public class DbmListServlet extends GenericServlet {
private static final long serialVersionUID = 1L;
static final int PAGE_DEFAULT_SIZE = 3;
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
System.out.println("service() 실행 시작");
int pageNo = 0;
int pageSize = 0;
if (request.getParameter("pageNo") != null) {
pageNo = Integer.parseInt(request.getParameter("pageNo"));
pageSize = PAGE_DEFAULT_SIZE;
}
if (request.getParameter("pageSize") != null) {
pageSize = Integer.parseInt(request.getParameter("pageSize"));
}
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
// 다른 서블릿을 실행 => 실행 후 제어권이 되돌아 온다.
//RequestDispatcher rd =
// request.getRequestDispatcher("/common/header");
//rd.include(request, response); // 자기가 받은 리퀘스트와 리스판스를 넘겨줘서 돌아갈 수 있게 만들어 준다.
//out.println("</head>");
out.println("</head>");
out.println("<body>");
out.println("<div class='container'>");
out.println("<h1>개발자 맵</h1>");
out.println("<p><a href='dbm-form.html' class='btn btn-primary'>맵추가</a></p>");
out.println("<table class='table table-hover'>");
out.println("<tr>");
out.println(" <th>#</th><th>이름</th><th>url</th><th>정보</th><th>메모</th>");
out.println("</tr>");
//for (Product product : AppInitServlet.productDao.selectList(pageNo, pageSize)) {
//for (Product product : ContextLoaderListener.productDao.selectList(pageNo, pageSize)) {
// ProductDao를 ServletContext 보관소에서 꺼내는 방식을 사용
// => 단점: 위의 방식보다 코드가 늘었다.
// => 장점: 특정 클래스에 종속되지 않는다. 유지보수에서 더 중요!
DbmDao dbmDao = (DbmDao)this.getServletContext()
.getAttribute("DbmDao");
for (Dbm dbm : dbmDao.selectList(pageNo, pageSize)) {
out.println("<tr>");
out.println(" <td>" + dbm.getName() + "</td>");
out.println(" <td>" + dbm.getUrl() + "</td>");
out.println(" <td>" + dbm.getInfo() + "</td>");
out.println(" <td>" + dbm.getMemo() + "</td>");
out.println("</tr>");
}
out.println("</table>");
out.println("</div>");
out.println("<script src='../../js/jquery-1.11.1.js'></script>");
//다른 서블릿을 실행 => 실행 후 제어권이 되돌아 온다.
//rd = request.getRequestDispatcher("/common/footer");
// rd.include(request, response);
out.println("</body>");
out.println("</html>");
System.out.println("service() 실행 완료");
}
}
<file_sep>/zJavaWeb02/src/main/java/java63/assign01/domain/Product.java
/* Value Object
* => Class 문법을 사용하여 사용자 정의 데이터 타입 만들기
*
* 1) Serializable 인터페이스 구현
* => SerialVersionUID 스태틱 변수 선언
*
* 2) 인스턴스 변수 선언
*
* 3) setter/getter 생성
*
* 4) 기본 생성자와 파라미터 값을 받는 생성자 선언
*
* 5) equals()/hashCode() 메서드 오버라이딩
*
* 6) toString() 오버라이딩
*/
package java63.assign01.domain;
import java.io.Serializable;
public class Product implements Serializable, Cloneable {
private static final long serialVersionUID = 1L;
protected int no;
protected String name;
protected int quantity;
protected int makerNo;
public Product() {}
public Product(int no, String name, int quantity, int makerNo) {
this.no = no;
this.name = name;
this.quantity = quantity;
this.makerNo = makerNo;
}
@Override
public Product clone() throws CloneNotSupportedException {
return (Product) super.clone();
}
@Override
public String toString() {
return "Product [no=" + no + ", name=" + name + ", quantity=" + quantity
+ ", makerNo=" + makerNo + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + makerNo;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + no;
result = prime * result + quantity;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Product other = (Product) obj;
if (makerNo != other.makerNo)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (no != other.no)
return false;
if (quantity != other.quantity)
return false;
return true;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getMakerNo() {
return makerNo;
}
public void setMakerNo(int makerNo) {
this.makerNo = makerNo;
}
}
<file_sep>/zJavaWeb02/src/main/java/java63/servlets/test03/ContextLoaderListener01.java
package java63.servlets.test03;
import java.io.InputStream;
import java63.servlets.test03.dao.ProductDao;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/* ServletContextListener는
* 웹 애플리케이션이 시작하거나 종료하는 이벤트에 대해 작업 수행!
*
* 컨텍스트 파라미터?
* => 웹 애플리케이션에서 사용할 환경 변수 정의할 때 사용
* => 모든 서블릿이 사용할 수 있다.
*
* 설정 방법? web.xml에 다음과 같이 설정한다.
* <context-param>
* <param-name>키</param-name>
* <param-value>값</param-value>
* </context-param>
*
* 사용 방법?
* ServletContext의 getInitParameter(키) 호출
*
*/
//@WebListener
public class ContextLoaderListener01 implements ServletContextListener {
public static ProductDao productDao;
/* 웹 애플리케이션이 시작할 때 호출됨
* => 서블릿이 사용할 공통 자원을 준비
*/
@Override
public void contextInitialized(ServletContextEvent sce) {
try {
ServletContext ctx = sce.getServletContext();
InputStream inputStream = Resources.getResourceAsStream(
ctx.getInitParameter("mybatisConfig"));
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
productDao = new ProductDao();
productDao.setSqlSessionFactory(sqlSessionFactory);
} catch (Exception e) {
e.printStackTrace();
}
}
/* 웹 애플리케이션이 종료할 때 호출됨
* => 서블릿이 사용한 자원을 해제할 때
*/
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
<file_sep>/zJavaWeb02/src/main/java/java63/servlets/test01/Test01.java
package java63.servlets.test01;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
/* 웹 브라우저에게 출력하기
*
*
* ServletRequest => 요청 정보를 다루는 도구
* ServletResponse => 응답 정보를 다루는 도구
*
*/
@WebServlet("/test01/Test01")
public class Test01 extends GenericServlet{
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
//1. ServletResponse 도구를 사용하여 출력 스트림을 준비한다.
PrintWriter out = response.getWriter();
// 2. 출력 스트림을 사용하여 브라우저로 출력한다.
out.println("아하~~안녕하세여?, 곤니찌와");
}
}
<file_sep>/zJavaWeb02/src/main/java/java63/servlets/test03/AppInitServlet.java
package java63.servlets.test03;
import java.io.IOException;
import java.io.InputStream;
import java63.servlets.test03.dao.ProductDao;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/* 서블릿 생성
* => 클라이언트가 요청했을 때 생성된다.
*
* 클라이언트 요청이 없더라도 강제로 서블릿을 생성하는 방법
* => 웹 애플리케이션을 시작할 때 생성된다.
* => 배치 설정에 <load-on-startup>을 추가한다.
* 이 태그에 주는 숫자는 실행 순서를 의미한다.
* 여러 개의 서블릿이 있을 때 작은 수를 갖는 서블릿이 먼저 생성된다.
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>java63.servlets.Hello</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
*
*/
/*
@WebServlet(
loadOnStartup=1
)
*/
public class AppInitServlet extends GenericServlet {
private static final long serialVersionUID = 1L;
public static ProductDao productDao;
public AppInitServlet() {
System.out.println("AppInitServlet 생성됨.");
}
/* 외부 자원을 참조하는 경우,
* 가능한 하드 코딩하지 말고 설정 파일에서 읽어오는 방식으로 처리하라!
*
* 설정 파일? web.xml
*
* 설정하는 방법은?
* <servlet>
* <servlet-name>...</servlet-name>
* <servlet-class>...</servlet-class>
* <init-param>
* <param-name>키</param-name>
* <param-value>값</param-value>
* </init-param>
* <init-param>
* <param-name>키</param-name>
* <param-value>값</param-value>
* </init-param>
* </servlet>
*
* 설정한 값을 꺼내는 방법?
* => ServletConfig의 getInitParameter("키")
*/
@Override
public void init() throws ServletException {
try {
InputStream inputStream = Resources.getResourceAsStream(
this.getInitParameter("mybatisConfig"));
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
productDao = new ProductDao();
productDao.setSqlSessionFactory(sqlSessionFactory);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {}
}
<file_sep>/zJavaWeb02/src/main/java/java63/assign01/servlets/HelpServlet.java
package java63.assign01.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
@WebServlet("/help")
public class HelpServlet extends GenericServlet{
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("list");
out.println("view 제품번호");
out.println("add");
out.println("delete 제품번호");
out.println("update 제품번호");
out.println();
}
}
<file_sep>/zJavaWeb02/src/main/java/java63/servlets/test05/ErrorServlet.java
package java63.servlets.test05;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
@WebServlet("/common/error")
public class ErrorServlet extends GenericServlet {
private static final long serialVersionUID = 1L;
static final int PAGE_DEFAULT_SIZE = 3;
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
// 다른 서블릿을 실행 => 실행 후 제어권이 되돌아 온다.
RequestDispatcher rd =
request.getRequestDispatcher("/common/header");
rd.include(request, response);
out.println("</head>");
out.println("<body>");
out.println("<div class='container'>");
out.println("<p>잠시 후 다시 시도하세요.</p>");
// 다른 서블릿을 실행 => 실행 후 제어권이 되돌아 온다.
rd = request.getRequestDispatcher("/common/footer");
rd.include(request, response);
out.println("</div>");
out.println("</body>");
out.println("</html>");
//오류에 대한 자세한 정보는 콘솔창에 출력하라! (사용자에게는 비밀^^)
Exception e = (Exception)request.getAttribute("error");
e.printStackTrace();
}
}
<file_sep>/zJavaWeb02/src/main/java/java63/assign01/servlets/ProductAddServlet.java
package java63.assign01.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java63.assign01.dao.ProductDao;
import java63.assign01.domain.Product;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
@WebServlet("/product/add")
public class ProductAddServlet extends GenericServlet{
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
ProductDao productDao = null;
try {
productDao = new ProductDao();
} catch (Exception e1) {
e1.printStackTrace();
}
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Product product = new Product();
product.setName((String)request.getParameter("name"));
product.setQuantity(Integer.parseInt((String)request.getParameter("qty")));
product.setMakerNo(Integer.parseInt((String)request.getParameter("mkno")));
productDao.insert(product);
out.println("저장하였습니다.");
out.println();
} catch (Exception e) {
e.printStackTrace();
out.println("서버가 바쁩니다. 잠시 후 다시 시도하세요.");
out.println();
}
}
}
<file_sep>/zJavaWeb02/src/main/webapp/test02/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>도움말</h1>
<h2>제품관리</h2>
<p>
목록조회:<br>
예1) http://localhost:8080/product/list<br>
예2) http://localhost:8080/product/list?pageNo=페이지번호<br>
예3) http://localhost:8080/product/list?pageNo=페이지번호&pageSize=페이지당출력개수<br>
</p>
<p>
제품추가:Create<br>
http://localhost:8080/product/add?name=제품명&qty=수량&mkno=제조사번호
</p>
<p>
제품조회:Retrieve or Read<br>
http://localhost:8080/product/view?no=제품번호
</p>
<p>
제품변경:Update<br>
http://localhost:8080/product/update?no=제품번호&name=제품명&qty=수량&mkno=제조사번호
</p>
<p>
제품삭제:Delete<br>
http://localhost:8080/product/delete?no=제품번호
</p>
</body>
</html><file_sep>/zJavaWeb02/src/main/java/java63/servlets/test05/ProductViewServlet.java
package java63.servlets.test05;
import java.io.IOException;
import java63.servlets.test05.dao.ProductDao;
import java63.servlets.test05.domain.Product;
import javax.servlet.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
@WebServlet("/test05/product/view")
public class ProductViewServlet extends GenericServlet {
private static final long serialVersionUID = 1L;
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
int no = Integer.parseInt(request.getParameter("no"));
//스프링의 ContextLoaderListener가 준비한
//ApplicationContext 객체 꺼내기
ApplicationContext appCtx =
WebApplicationContextUtils.getWebApplicationContext(
this.getServletContext());
ProductDao productDao = (ProductDao)appCtx.getBean("productDao");
Product product = productDao.selectOne(no);
request.setAttribute("product", product);
response.setContentType("text/html;charset=UTF-8");
RequestDispatcher rd =
request.getRequestDispatcher("/test05/product/ProductView.jsp");
rd.include(request, response);
}
}
<file_sep>/projectLondon01/build.gradle
apply plugin: 'java'
apply plugin: 'eclipse-wtp'
apply plugin: 'war'
compileJava{
// 소스의 자바 버전 제한하기
// => 지정된 버전의 문법이 아닌 경우 오류 출력한다.
sourceCompatibility = 1.8
options.encoding = 'UTF-8'
}
eclipse { // 이클립스 설정파일
wtp {
// 설정을 수행하는클로저를 넘긴다
facet { // 함수를 넘긴다
facet name:'jst.web', version:'3.0'
}
}
}
//의존 라이브러리를 받아올 서버 지정.
repositories {
mavenCentral()
}
// 의존 라이브러리 지정
// 의존 라이브러리 검색 사이트 =>
// http://www.mvnrepository.com
dependencies {
providedCompile 'javax.servlet:javax.servlet-api:3.1.0'
compile 'org.springframework:spring-jdbc:4.1.2.RELEASE'
compile 'org.mybatis:mybatis-spring:1.2.2'
compile 'org.springframework:spring-context:4.1.2.RELEASE'
compile 'log4j:log4j:1.2.17'
compile 'mysql:mysql-connector-java:5.1.34'
compile 'org.reflections:reflections:0.9.9'
compile 'org.mybatis:mybatis:3.2.8'
//testCompile group: 'junit', name: 'junit', version: '4.+'
}<file_sep>/zJavaProject/src/main/webapp/js/jquery.animate-shadow.js
/**!
* @preserve Shadow animation 1.11
* http://www.bitstorm.org/jquery/shadow-animation/
* Copyright 2011, 2013 <NAME> <<EMAIL>>
* Contributors: <NAME>, <NAME> and <NAME>
* Released under the MIT and GPL licenses.
*/
jQuery(function($, undefined) {
/**
* Check whether the browser supports RGBA color mode.
*
* Author <NAME> <http://pioupioum.fr>
* @return {boolean} True if the browser support RGBA. False otherwise.
*/
function isRGBACapable() {
var $script = $('script:first'),
color = $script.css('color'),
result = false;
if (/^rgba/.test(color)) {
result = true;
} else {
try {
result = (color !== $script.css('color', 'rgba(0, 0, 0, 0.5)').css('color'));
$script.css('color', color);
} catch (e) {
}
}
$script.removeAttr('style');
return result;
}
$.extend(true, $, {
support: {
'rgba': isRGBACapable()
}
});
/*************************************/
// First define which property to use
var styles = $('html').prop('style');
var boxShadowProperty;
$.each(['boxShadow', 'MozBoxShadow', 'WebkitBoxShadow'], function(i, property) {
var val = styles[property];
if (typeof val !== 'undefined') {
boxShadowProperty = property;
return false;
}
});
// Extend the animate-function
if (boxShadowProperty) {
$['Tween']['propHooks']['boxShadow'] = {
get: function(tween) {
return $(tween.elem).css(boxShadowProperty);
},
set: function(tween) {
var style = tween.elem.style;
var p_begin = parseShadows($(tween.elem)[0].style[boxShadowProperty] || $(tween.elem).css(boxShadowProperty));
var p_end = parseShadows(tween.end);
var maxShadowCount = Math.max(p_begin.length, p_end.length);
var i;
for(i = 0; i < maxShadowCount; i++) {
p_end[i] = $.extend({}, p_begin[i], p_end[i]);
if (p_begin[i]) {
if (!('color' in p_begin[i]) || $.isArray(p_begin[i].color) === false) {
p_begin[i].color = p_end[i].color || [0, 0, 0, 0];
}
} else {
p_begin[i] = parseShadows('0 0 0 0 rgba(0,0,0,0)')[0];
}
}
tween['run'] = function(progress) {
var rs = calculateShadows(p_begin, p_end, progress);
style[boxShadowProperty] = rs;
};
}
};
}
// Calculate an in-between shadow.
function calculateShadows(beginList, endList, pos) {
var shadows = [];
$.each(beginList, function(i) {
var parts = [], begin = beginList[i], end = endList[i];
if (begin.inset) {
parts.push('inset');
}
if (typeof end.left !== 'undefined') {
parts.push(parseFloat(begin.left + pos * (end.left - begin.left)) + 'px '
+ parseFloat(begin.top + pos * (end.top - begin.top)) + 'px');
}
if (typeof end.blur !== 'undefined') {
parts.push(parseFloat(begin.blur + pos * (end.blur - begin.blur)) + 'px');
}
if (typeof end.spread !== 'undefined') {
parts.push(parseFloat(begin.spread + pos * (end.spread - begin.spread)) + 'px');
}
if (typeof end.color !== 'undefined') {
var color = 'rgb' + ($.support['rgba'] ? 'a' : '') + '('
+ parseInt((begin.color[0] + pos * (end.color[0] - begin.color[0])), 10) + ','
+ parseInt((begin.color[1] + pos * (end.color[1] - begin.color[1])), 10) + ','
+ parseInt((begin.color[2] + pos * (end.color[2] - begin.color[2])), 10);
if ($.support['rgba']) {
color += ',' + parseFloat(begin.color[3] + pos * (end.color[3] - begin.color[3]));
}
color += ')';
parts.push(color);
}
shadows.push(parts.join(' '));
});
return shadows.join(', ');
}
// Parse the shadow value and extract the values.
function parseShadows(shadow) {
var parsedShadows = [];
var parsePosition = 0;
var parseLength = shadow.length;
function findInset() {
var m = /^inset\b/.exec(shadow.substring(parsePosition));
if (m !== null && m.length > 0) {
parsedShadow.inset = true;
parsePosition += m[0].length;
return true;
}
return false;
}
function findOffsets() {
var m = /^(-?[0-9\.]+)(?:px)?\s+(-?[0-9\.]+)(?:px)?(?:\s+(-?[0-9\.]+)(?:px)?)?(?:\s+(-?[0-9\.]+)(?:px)?)?/.exec(shadow.substring(parsePosition));
if (m !== null && m.length > 0) {
parsedShadow.left = parseInt(m[1], 10);
parsedShadow.top = parseInt(m[2], 10);
parsedShadow.blur = (m[3] ? parseInt(m[3], 10) : 0);
parsedShadow.spread = (m[4] ? parseInt(m[4], 10) : 0);
parsePosition += m[0].length;
return true;
}
return false;
}
function findColor() {
var m = /^#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/.exec(shadow.substring(parsePosition));
if (m !== null && m.length > 0) {
parsedShadow.color = [parseInt(m[1], 16), parseInt(m[2], 16), parseInt(m[3], 16), 1];
parsePosition += m[0].length;
return true;
}
m = /^#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])/.exec(shadow.substring(parsePosition));
if (m !== null && m.length > 0) {
parsedShadow.color = [parseInt(m[1], 16) * 17, parseInt(m[2], 16) * 17, parseInt(m[3], 16) * 17, 1];
parsePosition += m[0].length;
return true;
}
m = /^rgb\(\s*([0-9\.]+)\s*,\s*([0-9\.]+)\s*,\s*([0-9\.]+)\s*\)/.exec(shadow.substring(parsePosition));
if (m !== null && m.length > 0) {
parsedShadow.color = [parseInt(m[1], 10), parseInt(m[2], 10), parseInt(m[3], 10), 1];
parsePosition += m[0].length;
return true;
}
m = /^rgba\(\s*([0-9\.]+)\s*,\s*([0-9\.]+)\s*,\s*([0-9\.]+)\s*,\s*([0-9\.]+)\s*\)/.exec(shadow.substring(parsePosition));
if (m !== null && m.length > 0) {
parsedShadow.color = [parseInt(m[1], 10), parseInt(m[2], 10), parseInt(m[3], 10), parseFloat(m[4])];
parsePosition += m[0].length;
return true;
}
return false;
}
function findWhiteSpace() {
var m = /^\s+/.exec(shadow.substring(parsePosition));
if (m !== null && m.length > 0) {
parsePosition += m[0].length;
return true;
}
return false;
}
function findComma() {
var m = /^\s*,\s*/.exec(shadow.substring(parsePosition));
if (m !== null && m.length > 0) {
parsePosition += m[0].length;
return true;
}
return false;
}
function normalizeShadow(shadow) {
if ($.isPlainObject(shadow)) {
var i, sColor, cLength = 0, color = [];
if ($.isArray(shadow.color)) {
sColor = shadow.color;
cLength = sColor.length;
}
for(i = 0; i < 4; i++) {
if (i < cLength) {
color.push(sColor[i]);
} else if (i === 3) {
color.push(1);
} else {
color.push(0);
}
}
}
return $.extend({
'left': 0,
'top': 0,
'blur': 0,
'spread': 0
}, shadow);
}
var parsedShadow = normalizeShadow();
while (parsePosition < parseLength) {
if (findInset()) {
findWhiteSpace();
} else if (findOffsets()) {
findWhiteSpace();
} else if (findColor()) {
findWhiteSpace();
} else if (findComma()) {
parsedShadows.push(normalizeShadow(parsedShadow));
parsedShadow = {};
} else {
break;
}
}
parsedShadows.push(normalizeShadow(parsedShadow));
return parsedShadows;
}
});<file_sep>/zJavaWeb02/src/main/java/java63/servlets/test02/ProductDeleteServlet03.java
package java63.servlets.test02;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java63.servlets.test02.dao.ProductDao;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletResponse;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/* Refresh하기
* => <meta> 태그에 refresh 정보 넣기
*
*/
//@WebServlet("/test02/product/delete") // 서블릿으로 등록
public class ProductDeleteServlet03 extends GenericServlet {
private static final long serialVersionUID = 1L;
SqlSessionFactory sqlSessionFactory;
ProductDao productDao;
public ProductDeleteServlet03() {
try {
String resource = "java63/servlets/test02/dao/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
productDao = new ProductDao();
productDao.setSqlSessionFactory(sqlSessionFactory);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
int no = Integer.parseInt(request.getParameter("no"));
productDao.delete(no);
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<meta http-equiv='Refresh' content='3:url=list'>;");
out.println("<link rel='stylesheet' href='../../css/bootstrap.min.css'>");
out.println("<link rel='stylesheet' href='../../css/bootstrap-theme.min.css'>");
out.println("<link rel='stylesheet' href='../../css/common.css'>");
out.println("</head>");
out.println("<body>");
out.println("<div class='container'>");
out.println("<h1>삭제 결과</h1>");
out.println("<p>삭제하였습니다.</p>");
out.println("</div>");
out.println("<script>");
out.println("window.setTimeout(function(){");
out.println(" window.location.href = 'list';");
out.println("},1000);");
out.println("</script>");
out.println("</body>");
out.println("</html>");
}
}
<file_sep>/zJavaWeb02/src/main/java/java63/servlets/test01/Test05.java
package java63.servlets.test01;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
/*
* 연산하기
*
*/
@WebServlet("/test01/Test05")
public class Test05 extends GenericServlet{
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
int a = Integer.parseInt(request.getParameter("a"));
int b = Integer.parseInt(request.getParameter("b"));
String op = request.getParameter("op");
int result = 0;
switch(op) {
case "+": result = a + b; break;
case "-": result = a - b; break;
case "*": result = a * b; break;
case "/": result = a / b; break;
}
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<p>" + a + " " + op + " " + b + " " + " = " + result + "</p>");
out.println("</body>");
out.println("</html>");
}
}
<file_sep>/zJavaWeb02/src/main/java/java63/servlets/test03/dao/ProductDao.java
package java63.servlets.test03.dao;
import java.util.HashMap;
import java.util.List;
import java63.servlets.test03.domain.Product;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class ProductDao {
@Autowired
SqlSessionFactory sqlSessionFactory;
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
public ProductDao() {}
public Product selectOne(int no) {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
return sqlSession.selectOne(
"java02.test19.server.ProductDao.selectOne",
no /* new Integer(no) */);
} finally {
sqlSession.close();
}
}
public void update(Product product) {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
sqlSession.update(
"java02.test19.server.ProductDao.update", product);
sqlSession.commit();
} finally {
sqlSession.close();
}
}
public void delete(int no) {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
sqlSession.delete(
"java02.test19.server.ProductDao.delete", no);
sqlSession.commit();
} finally {
sqlSession.close();
}
}
public List<Product> selectList(int pageNo, int pageSize) {
SqlSession sqlSession = sqlSessionFactory.openSession();
HashMap<String,Object> paramMap = new HashMap<>();
paramMap.put("startIndex", ((pageNo - 1) * pageSize));
paramMap.put("pageSize", pageSize);
try {
return sqlSession.selectList(
// 네임스페이스 + SQL문 아이디
"java02.test19.server.ProductDao.selectList",
paramMap /* SQL문을 실행할 때 필요한 값 전달 */);
} finally {
sqlSession.close();
}
}
public void insert(Product product) {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
sqlSession.insert(
"java02.test19.server.ProductDao.insert", product);
sqlSession.commit();
} finally {
sqlSession.close();
}
}
}
<file_sep>/zJavaWeb02/src/main/java/README.TXT
과제
java03 프로젝트의 test21.server 패키지를
서블릿을 사용하여 바꿔라!
스프링을 사용하지 않고 만들라!
/help => java63.assign01.servlets.HelpServlet -
/product/list => java63.assign01.servlets.ProductListServlet -
/product/add => java63.assign01.servlets.ProductAddServlet -
/product/view => java63.assign01.servlets.ProductViewServlet -
/product/update => java63.assign01.servlets.ProductUpdateServlet
/product/delete => java63.assign01.servlets.ProductDeleteServlet
java63.assign01.dao.ProductDao
java63.assign01.domain.Product
java63.assign01.dao.ProductDao.xml
java63.assign01.dao.mybatis-config.xml
| 889d397c86258c3a0d505c985c2d83d21dd51f7f | [
"HTML",
"JavaScript",
"Gradle",
"Java",
"Text"
] | 19 | Java | Kibaek/Java_project | 40e83ceb829d84e759d454f156c0b540cccd8ad0 | 793e887e7c8dc42ff5688b308c70782092d3d9b1 | |
refs/heads/master | <repo_name>morsssss/amp-ecomm<file_sep>/src/server/server.js
const express = require('express');
const request = require('request');
const path = require('path');
const fs = require('fs');
const productApiManager = require('./ApiManager.js');
const mustache = require("mustache");
const formidableMiddleware = require('express-formidable');
const sessions = require("client-sessions");
const serializer = require('serialize-to-js');
const app = express();
app.use(formidableMiddleware());
app.use(sessions({
cookieName: 'session',
secret: 'eommercedemoofamazigness',
duration: 24 * 60 * 60 * 1000,
activeDuration: 1000 * 60 * 5
}));
app.engine('html', function(filePath, options, callback) {
fs.readFile(filePath, function(err, content) {
if (err)
return callback(err)
var rendered = mustache.to_html(content.toString(), options);
return callback(null, rendered)
});
});
app.set('view engine', 'html');
app.set('views', __dirname + '/../');
const apiManager = new productApiManager();
const port = process.env.PORT || 8080;
const listener = app.listen(port, () => {
console.log('App listening on port ' + listener.address().port);
});
//serve static files
app.use(express.static(path.join(__dirname, '/../')));
//Product Listing Page
app.get('/product-listing', function(req, res) {
// defaults to women shirts
let resProductsGender = 'women';
let resProductsCategory = 'shirts';
let resShirtSelected = true;
let resShortSelected = false;
let productsGender = req.query.gender || resProductsGender;
let productsCategory = req.query.category || resProductsCategory;
let listingUrl = apiManager.getCategoryUrl(productsGender + '-' + productsCategory);
if (!listingUrl.match('categoryId=undefined')) {
resProductsCategory = productsCategory;
resProductsGender = productsGender;
if (!resProductsGender.match('women')) {
resProductsGender = 'men';
}
if (!resProductsCategory.match('shirt')) {
resShirtSelected = false;
resShortSelected = true;
}
}
mustache.tags = ['<%', '%>'];
let responseObj = {
productsCategory: resProductsCategory,
productsGender: resProductsGender
};
if (resShirtSelected) {
responseObj.shirtSelected = true;
} else if (resShortSelected) {
responseObj.shortSelected = true;
}
if (resProductsGender == 'women') {
responseObj.womenSelected = true;
}
res.render('product-listing', responseObj);
});
//Product Page
app.get('/product-details', function(req, res) {
let categoryId = req.query.categoryId;
let productId = req.query.productId;
let productUrl = apiManager.getProductUrl(productId);
const options = {
url: productUrl
};
request(options, (error, response, body) => {
if (!error && body != 'Product not found' && !body.includes('An error has occurred')) {
var productObj = apiManager.parseProduct(body);
productObj.CategoryId = categoryId;
mustache.tags = ['<%', '%>'];
res.render('product-details', productObj);
} else {
res.render('product-not-found');
}
});
});
app.get('/shopping-cart', function(req, res) {
//get related products for the cart page: items belonging to the category of the first item in the cart, excluding the item.
let shoppingCart = req.session.shoppingCart;
let relatedProductsObj = new Object();
if (shoppingCart) {
shoppingCart = serializer.deserialize(shoppingCart);
let cartItems = shoppingCart.cartItems;
if(cartItems.length > 0) {
let firstCartItem = cartItems[0];
relatedProductsObj.Main_Id = firstCartItem.productId;
relatedProductsObj.CategoryId = firstCartItem.categoryId;
}
}
mustache.tags = ['<%', '%>'];
res.render('cart-details', relatedProductsObj);
});
//API
app.post('/api/add-to-cart', function(req, res) {
let productId = req.fields.productId;
let categoryId = req.fields.categoryId;
let name = req.fields.name;
let price = req.fields.price;
let color = req.fields.color;
let size = req.fields.size;
let imgUrl = req.fields.imgUrl;
let origin = req.get('origin');
let quantity = req.fields.quantity;
//If comes from the cache
if (req.headers['amp-same-origin'] !== 'true') {
//transfrom POST into GET and redirect to same url
let queryString = 'productId=' + productId + '&categoryId=' + categoryId + '&name=' + name + '&price=' + price + '&color=' + color + '&size=' + size + '&quantity=' + quantity + '&origin=' + origin + '&imgUrl=' + imgUrl;
res.header("AMP-Redirect-To", origin + "/api/add-to-cart?" + queryString);
} else {
updateShoppingCartOnSession(req, productId, categoryId, name, price, color, size, imgUrl, quantity);
res.header("AMP-Redirect-To", origin + "/shopping-cart");
}
enableCors(req, res);
//amp-form requires json response
res.json({});
});
app.get('/api/add-to-cart', function(req, res) {
let productId = req.query.productId;
let categoryId = req.query.categoryId;
let name = req.query.name;
let price = req.query.price;
let color = req.query.color;
let size = req.query.size;
let imgUrl = req.query.imgUrl;
let quantity = req.query.quantity;
updateShoppingCartOnSession(req, productId, categoryId, name, price, color, size, imgUrl, quantity);
res.redirect('/shopping-cart');
});
app.get('/api/categories', function(req, res) {
let categoryId = req.query.categoryId;
let sort = req.query.sort;
let categoryUrl = apiManager.getCategoryUrl(categoryId, sort);
console.log("Calling Category Url: " + categoryUrl);
const options = {
url: categoryUrl
};
request(options, (error, response, body) => {
if (!error) {
res.send(apiManager.parseCategory(body));
} else {
res.json({ error: 'An error occurred in /api/categories' });
}
});
});
app.get('/api/product', function(req, res) {
let productId = req.query.productId;
let productUrl = apiManager.getProductUrl(productId);
const options = {
url: productUrl
};
request(options, (error, response, body) => {
if (!error && body != 'Product not found' && !body.includes('An error has occurred')) {
var productObj = apiManager.parseProduct(body);
res.send(productObj);
} else {
res.json({ error: 'An error occurred in /api/product: ' + body });
}
});
});
// Wrap the shopping cart into an 'items' array, so it can be consumed with amp-list.
app.get('/api/cart-items', function(req, res) {
let cart = getCartFromSession(req);
let response = { items: [cart] };
enableCors(req, res);
res.send(response);
});
app.get('/api/cart-count', function(req, res) {
let cart = getCartFromSession(req);
let response = { items: [cart.cartItems.length] };
enableCors(req, res);
res.send(response);
});
app.post('/api/delete-cart-item', function(req, res) {
let productId = req.fields.productId;
let color = req.fields.color;
let size = req.fields.size;
let shoppingCartResponse = { items: [] };
let shoppingCart = req.session.shoppingCart;
if (shoppingCart) {
shoppingCart = serializer.deserialize(shoppingCart);
shoppingCart.removeItem(productId, color, size);
req.session.shoppingCart = serializer.serialize(shoppingCart);
shoppingCartResponse.items.push(shoppingCart);
}
enableCors(req, res);
res.send(shoppingCartResponse);
});
app.get('/api/related-products', function(req, res) {
let categoryId = req.query.categoryId;
let productId = req.query.productId;
let categoryUrl = apiManager.getCategoryUrl(categoryId);
//the response will be a 1 element items array, to be able to combine amp-list with amp-mustache
//see: https://github.com/ampproject/amphtml/issues/4405#issuecomment-379696849
let relatedProductsResponse = { items: [] };
const options = {
url: categoryUrl
};
request(options, (error, response, body) => {
if (!error) {
let relatedProducts = apiManager.getRelatedProducts(productId, body);
relatedProductsResponse.items.push(relatedProducts);
res.send(relatedProductsResponse);
} else {
res.json({ error: 'An error occurred in /api/related-products' });
console.log(error);
}
});
});
// If the session contains a cart, then deserialize it and return that!
// Otherwise, create a new cart and add that to the session.
function getCartFromSession(req) {
let sessionCart = req.session.shoppingCart;
if (sessionCart) {
return serializer.deserialize(sessionCart);
} else {
let newCart = apiManager.createCart();
req.session.shoppingCart = serializer.serialize(newCart);
return cart;
}
}
function updateShoppingCartOnSession(req, productId, categoryId, name, price, color, size, imgUrl, quantity) {
let cartProduct = apiManager.createCartItem(productId, categoryId, name, price, color, size, imgUrl, quantity);
let shoppingCartJson = req.session.shoppingCart;
let shoppingCartObj;
if (shoppingCartJson) {
shoppingCartObj = serializer.deserialize(shoppingCartJson);
} else {
shoppingCartObj = apiManager.createCart();
}
shoppingCartObj.addItem(cartProduct);
req.session.shoppingCart = serializer.serialize(shoppingCartObj);
}
function enableCors(req, res) {
//set to all for dev purposes only, change it by configuration to final domain
let sourceOrigin = req.query.__amp_source_origin;
let origin = req.get('origin') || sourceOrigin;
res.header('Access-Control-Allow-Credentials', 'true');
res.header("Access-Control-Allow-Origin", origin);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Expose-Headers", "AMP-Access-Control-Allow-Source-Origin,AMP-Redirect-To");
res.header("AMP-Access-Control-Allow-Source-Origin", sourceOrigin);
}<file_sep>/gulpfile.js
/* Dependencies */
const gulp = require('gulp');
const plumber = require('gulp-plumber');
const autoprefixer = require('gulp-autoprefixer');
const fileinclude = require('gulp-file-include');
const sass = require('gulp-sass');
const filter = require('gulp-filter')
const minimist = require('minimist');
const del = require('del');
const gulpAmpValidator = require('gulp-amphtml-validator');
const bs = require('browser-sync').create();
const autoScript = require('amphtml-autoscript').create();
const reload = bs.reload;
const nodemon = require('gulp-nodemon');
const replace = require('gulp-replace');
const noop = require('gulp-noop');
const mergeMediaQuery = require('gulp-merge-media-queries');
// Build type is configurable such that some options can be changed e.g. whether
// to minimise CSS. Usage 'gulp <task> --env development'.
const knownOptions = {
string: 'env',
default: { env: process.env.NODE_ENV || 'dist' }
};
const options = minimist(process.argv.slice(2), knownOptions);
const paths = {
css: {
src: 'src/sass/**/*.scss',
dest: 'src/css/'
},
html: {
src: 'src/html/pages/*.html',
dest: 'dist/'
},
images: {
src: 'src/img/**/*.{gif,jpg,png,svg}',
dest: 'dist/img'
},
favicon: {
src: 'src/favicon/*',
dest: 'dist/'
},
rootConfig: {
src: 'src/rootConfigFiles/*',
dest: 'dist/'
},
server: {
src: 'src/server/**/*',
dest: 'dist/server'
}
};
/**
* Builds the styles, bases on SASS files taken from src. The resulting CSS is
* used as partials that are included in the final AMP HTML.
* When SASS sees a non-ASCII character in a file, it starts the CSS file it builds with "@charset "UTF-8";".
* That's great in CSS files, but not accepted within <style> tags.
* So unless the SASS team takes on https://github.com/sass/sass/issues/2288, we need to remove it.
*/
gulp.task('styles', function buildStyles() {
const cssEncodingDirective = '@charset "UTF-8";';
return gulp.src(paths.css.src)
.pipe(plumber())
.pipe(sass(options.env === 'dist' ? { outputStyle: 'compressed' } : {}))
.pipe(options.env === 'dev' ? replace(cssEncodingDirective, '') : noop())
.pipe(autoprefixer('last 10 versions'))
.pipe(mergeMediaQuery({log: true}))
.pipe(gulp.dest(paths.css.dest));
});
/**
* Copies the images to the distribution.
*/
gulp.task('images', function buildImages() {
return gulp.src(paths.images.src)
.pipe(gulp.dest(paths.images.dest));
});
/**
* Copies the favicon to the distribution.
*/
gulp.task('favicon', function buildImages() {
return gulp.src(paths.favicon.src)
.pipe(gulp.dest(paths.favicon.dest));
});
/**
* Copies the root config files to the distribution.
*/
gulp.task('rootConfig', function buildImages() {
return gulp.src(paths.rootConfig.src)
.pipe(gulp.dest(paths.rootConfig.dest));
});
/**
* Copies the server and helper classes to the distribution.
*/
gulp.task('server', function buildImages() {
return gulp.src(paths.server.src)
.pipe(gulp.dest(paths.server.dest));
});
/**
* Builds the HTML files. Only files from 'pages' are built, such that partials
* are ignored as targets.
*/
gulp.task('html', gulp.series('styles', function buildHtml() {
const pageFilter = filter(['**/pages/*.html']);
return gulp.src(paths.html.src)
.pipe(pageFilter)
.pipe(fileinclude({
prefix: '%%',
basepath: '@file'
}))
.pipe(autoScript())
.pipe(gulp.dest(paths.html.dest));
}));
/**
* Checks resulting output AMP HTML for validity.
*/
gulp.task('validate', function validate() {
return gulp.src(paths.html.dest + '/**/*.html')
.pipe(gulpAmpValidator.validate())
.pipe(gulpAmpValidator.format())
.pipe(gulpAmpValidator.failAfterError());
});
/**
* Removes all files from the distribution directory, and also the CSS build
* directory.
*/
gulp.task('clean', function clean() {
return del([
paths.html.dest + '/**/*',
paths.css.dest + '/**/*'
]);
});
/**
* Builds the output from sources.
*/
gulp.task('build', gulp.series('images', 'favicon', 'rootConfig', 'html', 'server', 'validate'));
/**
* First rebuilds the output then triggers a reload of the browser.
*/
gulp.task('rebuild', gulp.series('build', function rebuild(done) {
bs.reload();
done();
}));
/**
* Sets up the live browser sync.
*/
/*
gulp.task('serve', function sync(done) {
bs.init({
server: {
baseDir: 'dist/'
}
});
done();
});
*/
gulp.task('browser-sync', function sync(done) {
bs.init(null, {
proxy: "http://localhost:8080", // port of node server
});
done();
});
gulp.task('nodemon', function (cb) {
var callbackCalled = false;
return nodemon({script: './dist/server/server.js'}).on('start', function () {
if (!callbackCalled) {
callbackCalled = true;
cb();
}
});
});
/**
* Sets up live-reloading: Changes to HTML or CSS trigger a rebuild, changes to
* images, favicon, root config files and server only result in images, favicon, root config files, server and helper classes being copied again to dist.
*/
gulp.task('watch', function watch(done) {
gulp.watch(paths.images.src, gulp.series('images'));
gulp.watch(paths.favicon.src, gulp.series('favicon'));
gulp.watch(paths.rootConfig.src, gulp.series('rootConfig'));
gulp.watch(paths.server.src, gulp.series('server'));
gulp.watch('src/html/**/*.html', gulp.series('rebuild'));
gulp.watch(paths.css.src, gulp.series('rebuild'));
done();
});
/**
* Prepares a clean build.
*/
gulp.task('prepare', gulp.series('clean', 'build'));
/**
* Default task is to perform a clean build then set up browser sync for live
* reloading.
*/
gulp.task('default', gulp.series('clean', 'build', 'nodemon', 'browser-sync', 'watch'));<file_sep>/README.md
Note that the templates directory contains files that will be turned into partials and page. It will eventually vanish or be moved.
| 76a1966c2636a687c70c0a23f87d07e42a1ebb25 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | morsssss/amp-ecomm | d264a450e8d3b3e126f5a2afd5087fc521d2ceef | 668471d06a630ba41eb543221934865c380ab665 | |
refs/heads/main | <file_sep>import styled from 'styled-components'
import { Link } from 'react-router-dom'
export const Container = styled.header`
display:flex;
justify-content: space-between;
padding:1em;
align-items:center;
color:#fff;
background: #3c4b4d;
margin-bottom: 0.5em;
font-size:1rem;
`
export const Group = styled.div`
display:flex;
align-items: center;
padding:0.5em;
`
export const Title = styled.h1`
font-size:2rem;
text-transform: uppercase;
@media (max-width: 720px){
font-size:0.9rem;
}
`
export const Text = styled.p`
color: #e11005;
`
export const Button = styled(Link)`
display:flex;
position: relative;
font-weight:700;
border: 0;
border-radius:15px;
color:#fff;
padding: 8px 17px;
cursor: pointer;
text-decoration: none;
text-transform: uppercase;
margin-left:1em;
&:hover {
transform: scale(1.2);
}
@media (max-width:600px){
padding: 4px 8px;
font-size:0.9rem;
}
`
<file_sep>import React from 'react'
import { Container, Form, Label, Input, Text } from './styles/filter'
export default function Filter({ children, ...restProps }) {
return (
<Container {...restProps}>{children}</Container>
)
}
Filter.Form = function FilterForm({ children, ...restProps }) {
return <Form {...restProps}>{children}</Form>
}
Filter.Label = function FormLabel({ children, ...restProps }) {
return <Label {...restProps}>{children}</Label>
}
Filter.Input = function FormInput({ ...restProps }) {
return <Input {...restProps}/>
}
Filter.Text = function FormText({ children, ...restProps }) {
return <Text {...restProps}>{children}</Text>
}
<file_sep>export const filterVars = {
showAll: "",
weakABV: "&abv_lt=4.6",
mediumABV: "&abv_gt=4.5&abv_lt=7.5",
strongABV: "&abv_gt=7.4",
lowIBU: "&ibu=35",
mediumIBU: "&ibu_gt=35&ibu_lt=75",
highIBU: "&ibu_gt=75"
}<file_sep>import React, { useContext } from "react"
import { HeaderContainer } from '../containers/header'
import { CartContainer } from '../containers/cart'
import { FooterContainer } from '../containers/footer'
import { Context } from '../context/context'
export function Cart() {
const { cartItems, setCartItems, removeFromCart, emptyCart } = useContext(Context)
return (
<>
<HeaderContainer />
<CartContainer cartItems={cartItems} setCartItems={setCartItems} removeFromCart={removeFromCart} emptyCart={emptyCart} />
<FooterContainer />
</>
)
}
<file_sep>import React, { useState, useEffect } from "react"
import { HeaderContainer } from '../containers/header'
import { FooterContainer } from '../containers/footer'
import { FilterContainer } from '../containers/filter'
import { CardContainer } from '../containers/card'
import { PaginationContainer } from "../containers/pagination"
export function Store() {
const [beers, setBeers] = useState([])
const [optionsABV, setOptionsABV] = useState("")
const [optionsIBU, setOptionsIBU] = useState("")
const [page, setPage] = useState(1);
useEffect(() => {
getBeers()
}, [page, optionsABV, optionsIBU])
const getBeers = async () => {
let API_URL = `https://api.punkapi.com/v2/beers?page=${page}&per_page=15${optionsABV}${optionsIBU}`
try {
const promise = await fetch(API_URL);
const beersData = await promise.json();
setBeers(beersData)
}
catch (e) {
console.error(e)
}
}
return (
<>
<HeaderContainer />
<FilterContainer
getBeers={getBeers}
setPage={setPage}
optionsIBU={optionsIBU}
optionsABV={optionsABV}
setOptionsABV={setOptionsABV}
setOptionsIBU={setOptionsIBU} />
<CardContainer items={beers} />
<PaginationContainer page={page} setPage={setPage} items={beers} />
<FooterContainer />
</>
)
}
<file_sep>import { createGlobalStyle } from 'styled-components';
export const GlobalStyles = createGlobalStyle`
* {
margin 0;
padding: 0;
box-sizing: border-box;
}
html, body {
font-family: 'Open Sans', sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
scroll-behavior: smooth;
color: #fff;
background: #f2eded;
font-size: 16px;
margin: 0 auto;
padding:0;
max-width:1400px;
letter-spacing:1px;
}
`;<file_sep>import React from 'react'
import { Switch, Route } from "react-router-dom"
import { BrowserRouter as Router } from 'react-router-dom'
import { Store } from './pages/store'
import { Cart } from './pages/cart'
import { ContextProvider } from './context/context'
export default function App() {
return (
<ContextProvider>
<Router>
<Switch>
<Route exact path="/">
<Store />
</Route>
<Route path="/cart">
<Cart />
</Route>
</Switch>
</Router>
</ContextProvider>
);
}
<file_sep>import React from 'react'
import { Filter } from '../components/exports'
import { filterVars } from '../util/filterVars'
export function FilterContainer({ getBeers, setPage, optionsIBU, optionsABV, setOptionsABV, setOptionsIBU }) {
const handleABVChange = (e) => {
e.preventDefault()
const value = e.target.value;
switch (value) {
case 'all':
setOptionsABV(filterVars.showAll)
break
case 'weak':
setOptionsABV(filterVars.weakABV)
break
case 'medium':
setOptionsABV(filterVars.mediumABV)
break
case 'strong':
setOptionsABV(filterVars.strongABV)
break
default: break
}
setPage(1)
}
const handleIBUChange = (e) => {
e.preventDefault()
const value = e.target.value;
switch (value) {
case 'all':
setOptionsIBU(filterVars.showAll)
break
case 'low':
setOptionsIBU(filterVars.lowIBU)
break
case 'medium':
setOptionsIBU(filterVars.mediumIBU)
break
case 'high':
setOptionsIBU(filterVars.highIBU)
break
default: break
}
setPage(1)
}
return (
<Filter>
<Filter.Form>
<Filter.Text color='red'>
Alcohol (ABV):
</Filter.Text>
<Filter.Label htmlFor="abvAll">
<Filter.Input type="radio" value="all" name="filter-abv" checked={optionsABV === filterVars.showAll} onChange={handleABVChange} />
all
</Filter.Label>
<Filter.Label htmlFor="abvWeak">
<Filter.Input type="radio" value="weak" name="filter-abv" checked={optionsABV === filterVars.weakABV} onChange={handleABVChange} />
weak
</Filter.Label>
<Filter.Label htmlFor="abvMedium">
<Filter.Input type="radio" value="medium" name="filter-abv" checked={optionsABV === filterVars.mediumABV} onChange={handleABVChange} />
medium
</Filter.Label>
<Filter.Label htmlFor="abvStrong">
<Filter.Input type="radio" value="strong" name="filter-abv" checked={optionsABV === filterVars.strongABV} onChange={handleABVChange} />
strong
</Filter.Label>
</Filter.Form>
<Filter.Form>
<Filter.Text>
Hoppiness (IBU):
</Filter.Text>
<Filter.Label htmlFor="ibuAll">
<Filter.Input type="radio" value="all" name="filter-ibu" checked={optionsIBU === filterVars.showAll} onChange={handleIBUChange} />
all
</Filter.Label>
<Filter.Label htmlFor="ibuLow">
<Filter.Input type="radio" value="low" name="filter-ibu" checked={optionsIBU === filterVars.lowIBU} onChange={handleIBUChange} />
low
</Filter.Label>
<Filter.Label htmlFor="ibuMedium">
<Filter.Input type="radio" value="medium" name="filter-ibu" checked={optionsIBU === filterVars.mediumIBU} onChange={handleIBUChange} />
medium
</Filter.Label>
<Filter.Label htmlFor="ibuHigh">
<Filter.Input type="radio" value="high" name="filter-ibu" checked={optionsIBU === filterVars.highIBU} onChange={handleIBUChange} />
high
</Filter.Label>
</Filter.Form>
</Filter>
)
}
<file_sep>import styled from 'styled-components'
export const Container = styled.div`
display: grid;
grid-template-columns: ${({ gridType }) => (gridType === 'list' ? 'repeat(auto-fill, minmax(350px, 1fr))' : '200px 1fr')};
grid-gap: 8px;
padding: 1em;
color:#333;
background: #3c4b4d;
margin-bottom:1em;
@media(max-width: 620px){
grid-template-columns: ${({ gridType }) => (gridType === 'list' ? 'repeat(auto-fill, minmax(100%, 1fr))' : '40% 1fr')};
}
`
export const Wrapper = styled.div`
display: ${({ display }) => (display === 'block' ? 'block' : 'flex')};
position: relative;
flex-direction: ${({ flexDirection }) => (flexDirection === 'row' ? 'row' : 'column')};
justify-content: ${({ justifyContent }) => (justifyContent === 'end' ? 'flex-end' : 'space-evenly')};
box-shadow: rgba(50, 50, 93, 0.25) 0px 13px 27px -5px, rgba(0, 0, 0, 0.3) 0px 8px 16px -8px;
background:#ebeded;
padding: 1em;
text-align: ${({ textAlign }) => (textAlign === 'left' ? 'left' : 'center')};
font-size: 1rem;
@media(max-width: 620px){
font-size:0.8rem;
}
`
export const Text = styled.p`
padding: 0.5em;
font-size:0.9rem;
`
export const Image = styled.img`
max-width: 100%;
height: 200px;
object-fit: contain;
margin: 3em 0 1em 0;
@media(max-width: 620px){
height: 150px;
}
`
export const Title = styled.h2`
font-size: 1.2rem;
padding: 0.5em;
@media(max-width: 620px){
font-size: 1rem;
}
`
export const Tagline = styled.p`
font-style: italic;
padding: 0.5em;
`
export const ABV = styled.span`
position: ${({ position }) => (position === 'relative' ? 'relative' : 'absolute')};
color: #FF8D00;
left:0;
top:0;
padding:1em;
font-weight: 700;
`
export const IBU = styled.span`
position: ${({ position }) => (position === 'relative' ? 'relative' : 'absolute')};
color: #28b470 ;
padding:1em;
right:0;
top:0;
font-weight: 700;
`
export const Content = styled.div`
position: ${({ position }) => (position === 'relative' ? 'relative' : 'absolute')};;
top: 0;
left: 0;
padding: 1em;
width: 100%;
height: 100%;
background: #f2eded;
overflow: auto;
cursor: pointer;
border-radius:7px;
text-align: left;
opacity: 0;
transition: opacity .8s ease;
&: hover {
opacity: 0.92;
}
`
export const ContentTitle = styled.h2`
padding: 0.5em 1em 0.5em 0.5em;
`
export const ContentTagline = styled.p`
padding: 0.5em;
font-style: italic;
`
export const ContentDescription = styled.p`
padding: 0.5em;
`
export const Icon = styled.img`
width: 40px;
height: 40px;
position: absolute;
right:1em;
top:1em;
cursor:pointer;
z-index:1000;
&:hover {
width:45px;
height:45px;
}
@media (max-width:720px){
width:30px;
height:30px;
&:hover {
width:35px;
height:35px;
}
}
`
export const Button = styled.button`
display:block;
padding: 1em 2.5em;
background: ${({ color }) => (color === 'red' ? '#dd225b' : '#28b470')};
margin-left:1em;
font-family:inherit;
text-transform: uppercase;
font-weight: 700;
cursor:pointer;
color: #fff;
border:0;
border-radius: 15px;
&:hover {
transform: scale(1.02)
}
@media (max-width: 620px){
font-size:0.8rem;
padding: 0.8em 1.5em;
}
`
<file_sep>import React from 'react'
import { Container, Title, Group, Button, Text } from './styles/header'
export default function Header({ children, ...restProps }) {
return (
<Container {...restProps}>{children}</Container>
)
}
Header.Title = function HeaderTitle({children, ...restProps }) {
return <Title {...restProps}>{children}</Title>
}
Header.Text = function HeaderText({children, ...restProps }) {
return <Text {...restProps}>{children}</Text>
}
Header.Group = function HeaderGroup({children, ...restProps}){
return <Group {...restProps}>{children}</Group>
}
Header.Button = function HeaderButton({children, ...restProps}){
return <Button {...restProps}>{children}</Button>
}
<file_sep>import React, { useState, createContext } from 'react'
export const Context = createContext()
export function ContextProvider({ children }) {
const [cartItems, setCartItems] = useState([])
const [loading, setLoading] = useState(false)
const addToCart = (item) => {
setCartItems(prev => [...prev, item])
}
const removeFromCart = (id) => {
setCartItems(prevItems => prevItems.filter(item => item.id !== id))
}
const emptyCart = () => {
setCartItems([])
}
const checkout = () => {
setLoading(true)
setTimeout(() => {
emptyCart()
setLoading(false)
}, 2000)
}
return (
<Context.Provider value={{
cartItems,
setCartItems,
addToCart,
removeFromCart,
emptyCart,
checkout,
loading
}}>
{children}
</Context.Provider>
)
}<file_sep>import React from 'react';
import { Container, Text, Image, Title, Tagline, ABV, IBU, Content, ContentTitle, ContentTagline, ContentDescription, Icon, Wrapper, Button } from './styles/card'
export default function Card({ children, ...restProps }) {
return (
<Container {...restProps}>{children}</Container>
)
}
Card.Wrapper = function CardWrapper({ children, ...restProps }) {
return <Wrapper {...restProps}>{children}</Wrapper>
}
Card.Title = function CardTitle({ children, ...restProps }) {
return <Title {...restProps}>{children}</Title>
}
Card.Tagline = function CardTagline({ children, ...restProps }) {
return <Tagline {...restProps}>{children}</Tagline>
}
Card.Text = function CardText({ children, ...restProps }) {
return <Text {...restProps}>{children}</Text>
}
Card.Image = function CardImage({ children, ...restProps }) {
return <Image {...restProps} />
}
Card.ABV = function CardABV({ children, ...restProps }) {
return <ABV {...restProps}>{children}</ABV>
}
Card.IBU = function CardABV({ children, ...restProps }) {
return <IBU {...restProps}>{children}</IBU>
}
Card.Content = function CardContent({ children, ...restProps }) {
return <Content {...restProps}>{children}</Content>
}
Card.ContentTitle = function CardContentTitle({ children, ...restProps }) {
return <ContentTitle {...restProps}>{children}</ContentTitle>
}
Card.ContentTagline = function CardContentTagline({ children, ...restProps }) {
return <ContentTagline {...restProps}>{children}</ContentTagline>
}
Card.ContentDescription = function CardContentDescription({ children, ...restProps }) {
return <ContentDescription {...restProps}>{children}</ContentDescription>
}
Card.Icon = function CardIcon({ ...restProps }) {
return <Icon {...restProps} />
}
Card.Button = function CardButton({ children, ...restProps }) {
return <Button {...restProps}>{children}</Button>
}
<file_sep>export { default as Header } from './header/index'
export { default as Footer } from './footer/index'
export { default as Card} from './card/index'
export { default as Pagination} from './pagination/index'
export { default as Filter} from './filter/index'<file_sep># beerium
Beerium is an e-commerce type app built in React while following a compound component design pattern, prioritizing reusability. Styled with styled components.
Used Punk API to receive beer data.
https://beerium-haris588.netlify.app
| 5329a8f19696085fed3a7eb3dd00b2a5c4c74ac6 | [
"JavaScript",
"Markdown"
] | 14 | JavaScript | haris588/React-beerium | f8cd1dbc6d1df6cf42ce1eda5d3bbfe3495be93d | c8d1d4b65afa711b43fe7a71a431c0ad4fe7688b | |
refs/heads/master | <repo_name>shimmer24/SamsungAudioEngine<file_sep>/common/uninstall.sh
#!/sbin/sh
app="SapaAudioConnectionService
SapaMonitor
SplitSoundService";
bin="apaservice
jackd
jackservice
profman
samsungpowersoundplay
media
sae";
etc="apa_settings.cfg
audio_effects.conf
floating_feature.xml
jack_alsa_mixer.json
sapa_feature.xml
SoundAlive_Settings.xml
stage_policy.conf
feature_default.xml
soundalive";
etccacerts="262ba90f.0
b936d1c6.0
31188b5e.0
c2c1704e.0
33ee480d.0
c907e29b.0
583d0756.0
cb1c3204.0
7892ad52.0
d0cddf45.0
7a7c655d.0
d41b5e2a.0
7c302982.0
d5727d6a.0
88950faa.0
dfc0fe80.0
a81e292b.0
fb5fa911.0
ab59055e.0
fd08c599.0";
permissions="com.google.android.media.effects.xml
com.samsung.device.xml
SemAudioThumbnail_library.xml
privapp-permissions-com.sec.android.app.soundalive.xml
platform.xml
com.samsung.feature.device_category_phone_high_end.xml
com.samsung.feature.device_category_phone.xml
android.hardware.audio.pro.xml
android.hardware.audio.low_latency.xml";
framework="SemAudioThumbnail.jar
com.google.android.media.effects.jar
com.samsung.device.jar
media_cmd.jar";
lib="jack
libapa_client.so
libapa_control.so
libapaproxy.so
libapa.so
libaudiosaplus_sec_legacy.so
libcorefx.so
lib_DNSe_EP_ver216c.so
libfloatingfeature.so
libhiddensound.so
libjackserver.so
libjackservice.so
libjackshm.so
liblegacyeffects.so
libmediacapture_jni.so
libmediacaptureservice.so
libmediacapture.so
libmysound_legacy.so
libsamsungearcare.so
libsamsungSoundbooster_plus_legacy.so
libsamsungvad.so
lib_SamsungVAD_v01009.so
libsavsac.so
libsavscmn_jni.media.samsung.so
libsavscmn.so
libsavsff.so
libsavsmeta.so
libsavsvc.so
lib_SoundAlive_AlbumArt_ver105.so
lib_SoundAlive_play_plus_ver210.so
lib_soundaliveresampler.so
lib_SoundAlive_SRC384_ver320.so
libSoundAlive_VSP_ver315b_arm.so
lib_SoundBooster_ver950.so
libsvoicedll.so
libswdap_legacy.so
libwebrtc_audio_preprocessing.so
libdexfile.so
libmultirecord.so
libprofileparamstorage.so
libsecaudiocoreutils.so
libsecaudioinfo.so
libsecnativefeature.so
libutilscallstack.so
libvorbisidec.so
libalsautils.so
libtinyalsa.so
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
libaudioclient.so
libaudiohal.so
libsamsungpowersound.so
libsonic.so
libsonivox.so
libsoundextractor.so
libsoundspeed.so
libspeexresampler.so
soundfx
libasound.so";
lib64="libapa_client.so
libapa_control.so
libapaproxy.so
libapa.so
libcorefx.so
lib_DNSe_EP_ver216c.so
libfloatingfeature.so
libhiddensound.so
libjackshm.so
liblegacyeffects.so
libmediacapture_jni.so
libmediacapture.so
libSamsungAPVoiceEngine.so
libsamsungearcare.so
libsavsac.so
libsavscmn_jni.media.samsung.so
libsavscmn.so
libsavsff.so
libsavsmeta.so
libsavsvc.so
lib_soundaliveresampler.so
libSoundAlive_SRC192_ver205a.so
lib_SoundAlive_SRC384_ver320.so
libSoundAlive_VSP_ver316a_ARMCpp_64bit.so
libswdap_legacy.so
libwebrtc_audio_preprocessing.so
libdexfile.so
libmultirecord.so
libprofileparamstorage.so
libsecaudiocoreutils.so
libsecaudioinfo.so
libsecnativefeature.so
libutilscallstack.so
libvorbisidec.so
libalsautils.so
libtinyalsa.so
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
libaudioclient.so
libaudiohal.so
libsonic.so
libsonivox.so
libsoundextractor.so
libspeexresampler.so
soundfx";
privapp="SoundAlive_54";
vendoretc="abox_debug.xml
mixer_gains.xml
SoundBoosterParam.txt
audio_effects.conf
audio_effects.xml
permissions";
vendorfirmware="cs47l92-dsp1-trace.wmfw
dsm.bin
dsm_tune.bin
SoundBoosterParam.bin";
vendorlib="libaboxpcmdump.so
libapa_jni.so
libcodecdspdump.so
libfloatingfeature.so
libjack.so
librecordalive.so
libSamsungPostProcessConvertor.so
lib_SamsungRec_06006.so
libsavsac.so
libsavscmn.so
libsavsvc.so
lib_SoundAlive_3DPosition_ver202.so
lib_SoundAlive_AlbumArt_ver105.so
lib_SoundAlive_play_plus_ver210.so
lib_soundaliveresampler.so
lib_SoundAlive_SRC384_ver320.so
lib_SoundBooster_ver950.so
libalsautils_sec.so
libaudioproxy.so
libHMT.so
libprofileparamstorage.so
libsecaudioinfo.so
libsecnativefeature.so
soundfx";
vendorlib64="libapa_jni.so
libfloatingfeature.so
libjack.so
libsavsac.so
libsavscmn.so
libsavsvc.so
libprofileparamstorage.so
libsecnativefeature.so
soundfx";
xbin="jack_connect
jack_disconnect
jack_lsp
jack_showtime
jack_simple_client
jack_transport";
property="persist.audio.a2dp_avc
persist.audio.allsoundmute
persist.audio.corefx
persist.audio.effectcpufreq
persist.audio.finemediavolume
persist.audio.globaleffect
persist.audio.headsetsysvolume
persist.audio.hphonesysvolume
persist.audio.k2hd
persist.audio.mpseek
persist.audio.mysound
persist.audio.nxp_lvvil
persist.audio.pcmdump
persist.audio.ringermode
persist.audio.sales_code
persist.audio.soundalivefxsec
persist.audio.stereospeaker
persist.audio.sysvolume
persist.audio.uhqa
persist.audio.voipcpufreq
persist.bluetooth.enableinbandringing
persist.audio.fluence.speaker
persist.audio.fluence.voicecall
persist.audio.fluence.voicerec
persist.audio.fluence.speaker
persist.audio.fluence.voicecall
persist.audio.fluence.voicerec
persist.audio.ras.enabled
persist.vendor.audio.fluence.speaker
persist.vendor.audio.fluence.voicecall
persist.vendor.audio.fluence.voicerec
persist.vendor.audio.ras.enabled";
code_u() {
for F_APP in $app; do rm -rf $APP/$F_APP; done
for F_BIN in $bin; do rm -rf $BIN/$F_BIN; done
for F_ETC in $etc; do rm -rf $ETC/$F_ETC; done
rm -rf $ETC/init/powersnd.rc $ETC/SoundAlive_Settings.xml $ETC/soundalive 2>/dev/null
for F_CACERTS in $etccacerts; do rm -rf $ETC/security/cacerts/$F_CACERTS; done
for F_PERMISSIONS in $permissions; do rm -rf $ETC/permissions/$F_PERMISSIONS; done
rm -rf $ETC/init/powersnd.rc
for F_FRAMEWORK in $framework; do rm -rf $FRAME/$F_FRAMEWORK; done
for F_LIB in $lib; do rm -rf $LIB/$F_LIB; done
rm -rf $LIB/hw/audio.playback_record.default.so \
$LIB/hw/audio.tms.default.so 2>/dev/null
for F_PRIVAPP in $privapp; do rm -rf $PRIV/$F_PRIVAPP; done
for F_XBIN in $xbin; do rm -rf $XBIN/$F_XBIN; done
rm -rf $ETC_VE/audio/audio_effects.xml
for F_VENDORETC in $vendoretc; do rm -rf $ETC_VE/$F_VENDORETC; done
for F_VENDORFIRMWARE in $vendorfirmware; do rm -rf $VENDOR/firmware/$F_VENDORFIRMWARE; done
for F_VENDORLIB in $vendorlib; do rm -rf $LIB_VE/$F_VENDORLIB; done
rm -rf $LIB_VE/hw/audio.* \
$LIB_VE/hw/android.hardware.audio* \
$LIB_VE/hw/android.hardware.soundtrigger* \
$LIB_VE/hw/sound_trigger.* 2>/dev/null
if find $LIB_VE/hw/* ; then echo "" > /dev/null; else rm -rf $LIB_VE/hw; fi
if $IS64BIT; then
for F_LIB64 in $lib64; do rm -rf $LIB64/$F_LIB64; done
rm -rf $LIB64/hw/audio* \
$LIB64/hw/sound_trigger* 2>/dev/null
for F_VENDORLIB64 in $vendorlib64; do rm -rf $LIB64_VE/$F_VENDORLIB64; done
rm -rf $LIB64_VE/hw/audio* \
$LIB64_VE/hw/android.hardware.audio* \
$LIB64_VE/hw/android.hardware.soundtrigger* \
$LIB64_VE/hw/sound_trigger.* 2>/dev/null
if find $LIB64_VE/hw/* ; then echo "" > /dev/null; else rm -rf $LIB64_VE/hw; fi
fi
rm -rf $USR/share/alsa $DATA_M/jack $DATA_M/profman 2>/dev/null
for F_PROPERTY in $property; do rm -rf $PROPERTY/$F_PROPERTY; done
rm -rf $DATA/data/com.samsung.android.sdk.professionalaudio.app.audioconnectionservice $DATA/dalvik-cache/arm*/*SapaAudioConnectionService*
sed -i '/com.samsung.android.sdk.professionalaudio.app.audioconnectionservice/d' $DATA/system/package-cstats.list
sed -i '/SapaAudioConnectionService/d' $DATA/system/package-cstats.list
sed -i '/com.samsung.android.sdk.professionalaudio.app.audioconnectionservice/d' $DATA/system/package-usage.list
sed -i '/com.samsung.android.sdk.professionalaudio.app.audioconnectionservice/d' $DATA/system/packages.list
rm -rf $DATA/data/com.samsung.android.sdk.professionalaudio.utility.jammonitor $DATA/dalvik-cache/arm*/*SapaMonitor*
sed -i '/com.samsung.android.sdk.professionalaudio.utility.jammonitor/d' $DATA/system/package-cstats.list
sed -i '/SapaMonitor/d' $DATA/system/package-cstats.list
sed -i '/com.samsung.android.sdk.professionalaudio.utility.jammonitor/d' $DATA/system/package-usage.list
sed -i '/com.samsung.android.sdk.professionalaudio.utility.jammonitor/d' $DATA/system/packages.list
rm -rf $DATA/data/com.sec.android.splitsound $DATA/dalvik-cache/arm*/*SplitSoundService*
sed -i '/com.sec.android.splitsound/d' $DATA/system/package-cstats.list
sed -i '/SplitSoundService/d' $DATA/system/package-cstats.list
sed -i '/com.sec.android.splitsound/d' $DATA/system/package-usage.list
sed -i '/com.sec.android.splitsound/d' $DATA/system/packages.list
rm -rf $DATA/data/com.sec.android.app.soundalive $DATA/dalvik-cache/arm*/*SoundAlive_54*
sed -i '/com.sec.android.app.soundalive/d' $DATA/system/package-cstats.list
sed -i '/SoundAlive_/d' $DATA/system/package-cstats.list
sed -i '/com.sec.android.app.soundalive/d' $DATA/system/package-usage.list
sed -i '/com.sec.android.app.soundalive/d' $DATA/system/packages.list
}
code_u
pack -xf $BK -C $SYS
rm -rf $BK
<file_sep>/README.md
## Samsung Audio Engine
### Description
The global influence on the sound device, whether it is sound from browser, polyphonic, recording microphone and audio player
Increases the detail, clarity, volume and selection of instruments in the track being played.
The exposed vocal processing becomes more lively, deep and saturated with low frequencies.
With long listening to music there is no discomfort in the ears.
The fix for the audio loss quality.
### The ability to control branded audio with SoundAlive effects
- Clarity
- Bass and treble control
- Vocal and instrumental control
- Concert Hall
- Tube Amp Pro
- Surround
- 3D
- 9 band equalizer with customized presets
- UHQ Upscaler
- UHQ receiver
- Dolby Atmos
### Peculiar properties
- Ported and used HiRes effects, (list above), ie when listening to music 32/384 or 24/192 and so on, the processing will take place at the same bit rate and frequency
- Dolby Atmos has full support for Android 9.0 and below
### Smart installer
- Support installation via Magisk and determine whether it is built into the system
- Support installation directly in the system without disconnecting the device through the terminal emulator if there is no recovery
- Automatic creation of backup, all replaceable and editable files
- Automatic selection of installation on 32 and 64 bit systems
- Completely removed installer, he's Uninstaller to remove it again to install the files in recovery or magik, then go the uninstall process
### Installation order
1. Install "Samsung Audio Engine"
2. Make Wipe dalvik-cache
3. Reboot
4. Install "SA Settings"
5. Reboot
### Uninstallation order:
Flash the archive "Samsung Audio Engine" through magisk or recovery, the removal process will go to the original state of the system
### Contacts
- [Samsung Audio Engine & SA Settings @ 4pda](http://4pda.ru/forum/index.php?showtopic=931217)
- [Samsung Audio Engine & SA Settings @ xda-developers](https://forum.xda-developers.com/android/apps-games/audio-engine-samsung-galaxy-s8s9-t3904527)
<file_sep>/install.sh
##########################################################################################
#
# Magisk Module Installer Script
# by shimmer @ 4pda(xda)
#
##########################################################################################
##########################################################################################
# Config Flags
##########################################################################################
SKIPMOUNT=false
PROPFILE=false
POSTFSDATA=false
LATESTARTSERVICE=false
AUTOWIPE=true
##########################################################################################
# Replace list
##########################################################################################
REPLACE_EXAMPLE="
/system/app/Youtube
/system/priv-app/SystemUI
/system/priv-app/Settings
/system/framework
"
REPLACE="
"
[ ! -f $TMPDIR/util_functions.sh ] && abort "! Unable to extract zip file!" || load() {
[ -f $TMPDIR/util_functions.sh ] && . $TMPDIR/util_functions.sh ;}; load && sa_conf
##########################################################################################
# Function Callbacks
##########################################################################################
block_engine() {
ui_print "- Installing..."; $(usleep 100000);
[ -f $LIB/libfloatingfeature.so ] || abort "Error: Unable to extract files!"
DOLBY_SYSTEM=`grep "libswdap.so" $ETC/audio_effects.conf > /dev/null 2>/dev/null`
DOLBY_VENDOR=`grep "libswdap.so" $ETC_VE/audio_effects.conf > /dev/null 2>/dev/null`
DOLBY_VENDOR_XML=`grep "libswdap.so" $ETC_VE/audio_effects.xml > /dev/null 2>/dev/null`
if [ -f $ECFG ]; then
if grep "DOLBY_DEFAULT=true" $ECFG > /dev/null; then
. $ECFG
if $DOLBY_DEFAULT; then
mkdir -p $TMPDIR/dolby
mkdir -p $TMPDIR/dolby/lib
mkdir -p $TMPDIR/dolby/ve_lib
if $IS64BIT; then
mkdir -p $TMPDIR/dolby64
mkdir -p $TMPDIR/dolby64/lib64
mkdir -p $TMPDIR/dolby64/ve_lib64
fi
if $DOLBY_SYSTEM; then
cp -rfp $SYS/lib/soundfx/libswdap.so $TMPDIR/dolby 2>/dev/null
cp -rfp $SYS/lib/libprofileparamstorage.so $TMPDIR/dolby/lib 2>/dev/null
cp -rfp $VENDOR/lib/soundfx/libswdap.so $TMPDIR/dolby 2>/dev/null
cp -rfp $VENDOR/lib/libprofileparamstorage.so $TMPDIR/dolby/ve_lib 2>/dev/null
if $IS64BIT; then
cp -rfp $SYS/lib64/soundfx/libswdap.so $TMPDIR/dolby64 2>/dev/null
cp -rfp $SYS/lib64/libprofileparamstorage.so $TMPDIR/dolby/lib64 2>/dev/null
cp -rfp $VENDOR/lib64/soundfx/libswdap.so $TMPDIR/dolby64 2>/dev/null
cp -rfp $VENDOR/lib64/libprofileparamstorage.so $TMPDIR/dolby64/ve_lib64 2>/dev/null
fi
elif $DOLBY_VENDOR; then
cp -rfp $SYS/lib/soundfx/libswdap.so $TMPDIR/dolby 2>/dev/null
cp -rfp $SYS/lib/libprofileparamstorage.so $TMPDIR/dolby/lib 2>/dev/null
cp -rfp $VENDOR/lib/soundfx/libswdap.so $TMPDIR/dolby 2>/dev/null
cp -rfp $VENDOR/lib/libprofileparamstorage.so $TMPDIR/dolby/ve_lib 2>/dev/null
if $IS64BIT; then
cp -rfp $SYS/lib64/soundfx/libswdap.so $TMPDIR/dolby64 2>/dev/null
cp -rfp $SYS/lib64/libprofileparamstorage.so $TMPDIR/dolby/lib64 2>/dev/null
cp -rfp $VENDOR/lib64/soundfx/libswdap.so $TMPDIR/dolby64 2>/dev/null
cp -rfp $VENDOR/lib64/libprofileparamstorage.so $TMPDIR/dolby64/ve_lib64 2>/dev/null
fi
elif $DOLBY_VENDOR_XML; then
cp -rfp $VENDOR/lib/soundfx/libswdap.so $TMPDIR/dolby 2>/dev/null
cp -rfp $SYS/lib/libprofileparamstorage.so $TMPDIR/dolby/lib 2>/dev/null
cp -rfp $VENDOR/lib/libprofileparamstorage.so $TMPDIR/dolby/ve_lib 2>/dev/null
if $IS64BIT; then
cp -rfp $VENDOR/lib64/soundfx/libswdap.so $TMPDIR/dolby64 2>/dev/null
cp -rfp $SYS/lib64/libprofileparamstorage.so $TMPDIR/dolby/lib64 2>/dev/null
cp -rfp $VENDOR/lib64/libprofileparamstorage.so $TMPDIR/dolby64/ve_lib64 2>/dev/null
fi
fi
fi
elif grep "DOLBY_DEFAULT=false" $ECFG > /dev/null; then
DOLBY_DEFAULT=false
fi
fi
for F_CONFLICT in $conflict; do rm -rf $F_CONFLICT; done
rm -rf $DATA_M/jack $DATA_M/profman 2>/dev/null
mkdir -m0770 $DATA_M/jack
mkdir -m0770 $DATA_M/profman
chcon "u:object_r:profman_dump_data_file:s0" $DATA_M/profman
rwxrxrx $BIN/apaservice
rwxrxrx $BIN/jackd
rwxrxrx $BIN/jackservice
rwxrxrx $BIN/profman
chcon "u:object_r:profman_exec:s0" $BIN/profman
rwxrxrx $ETC/permissions && rwrr $ETC/permissions/*.xml
rwrr $ETC/apa_settings.cfg
rwrr $ETC/feature_default.xml
rwrr $ETC/floating_feature.xml
rwrr $ETC/sapa_feature.xml
rwrr $ETC/stage_policy.conf
rwrr $ETC/jack_alsa_mixer.json
rwrr $ETC/security/cacerts/*.0
rwrr $FRAME/*.jar 2>/dev/null
rwxrxrx $LIB/hw && rwrr $LIB/hw/*.so
rwxrxrx $LIB/jack && rwrr $LIB/jack/*.so
rwrr $LIB/*.so
rwxrxrx $ETC_VE
rwrr $ETC_VE/SoundBoosterParam.txt
rwrr $ETC_VE/abox_debug.xml
rwrr $ETC_VE/mixer_gains.xml
rwxrxrx $VENDOR/firmware && rwrr $VENDOR/firmware/*.bin
rwxrxrx $VENDOR/lib
rwxrxrx $LIB_VE/hw && rwrr $LIB_VE/hw/*.so
rwrr $LIB_VE/*.so
rwxrxrx $XBIN/jack*
if $IS64BIT; then
[ -d $TMPDIR/is64bit ] && cp -rf $TMPDIR/is64bit/lib64 $SYS
[ -d $TMPDIR/is64bit ] && cp -rf $TMPDIR/is64bit/vendor/lib64 $VENDOR
[ -f $LIB64/libfloatingfeature.so ] || abort "Error: Unable to extract files 64bit!"
rwxrxrx $LIB64 && rwrr $LIB64/*.so
rwxrxrx $LIB64/hw && rwrr $LIB64/hw/*.so
rwxrxrx $VENDOR/lib64 && rwrr $LIB64_VE/*.so
rwxrxrx $LIB64_VE/hw && rwrr $LIB64_VE/hw/*.so
fi
# hw patch
$(rm -rf $DATA/system/package-cstats.list \
$DATA/system/package-usage.list 2>/dev/null
echo "" > $DATA/system/packages.list);
echo "$(echo "" && cat $FEATURE/device.prop)" >> $BUILD
echo "$(echo "" && cat $FEATURE/build_sys.prop)" >> $BUILD
if [ "$API" -ge 28 ]; then echo "$(echo "" && cat $FEATURE/build_vendor.prop)" >> $BUILD_VE;
else echo "$(echo "" && cat $FEATURE/build_sys_api.prop)" >> $BUILD; fi
if getprop | grep "ro.boot.hardware" | grep "qcom" > /dev/null; then
echo "$(echo "" && cat $FEATURE/qcom.prop)" >> $BUILD
if [ "$API" -ge 28 ]; then echo "$(echo "" && cat $FEATURE/qcom_vendor.prop)" >> $BUILD_VE; fi
fi
block_specific
if [ -f $TMPDIR/dolby/libswdap.so ]; then
if [ "$API" -ge 28 ]; then
sed -i 's/libswdap_legacy.so/libswdap.so/' $ETC_VE/audio_effects.xml
cp -rfp $TMPDIR/dolby/libswdap.so $VENDOR/lib/soundfx
cp -rfp $TMPDIR/dolby/lib/libprofileparamstorage.so $SYS/lib
cp -rfp $TMPDIR/dolby/ve_lib/libprofileparamstorage.so $VENDOR/lib
if $IS64BIT; then
cp -rfp $TMPDIR/dolby64/libswdap.so $VENDOR/lib64/soundfx
cp -rfp $TMPDIR/dolby64/lib64/libprofileparamstorage.so $SYS/lib64
cp -rfp $TMPDIR/dolby64/ve_lib64/libprofileparamstorage.so $VENDOR/lib64
fi
else
sed -i 's/libswdap_legacy.so/soundfx\/libswdap.so/' $ETC_VE/audio_effects.conf
cp -rfp $TMPDIR/dolby/libswdap.so $SYS/lib/soundfx
cp -rfp $TMPDIR/dolby/lib/libprofileparamstorage.so $SYS/lib
cp -rfp $TMPDIR/dolby/ve_lib/libprofileparamstorage.so $VENDOR/lib
if $IS64BIT; then
cp -rfp $TMPDIR/dolby64/libswdap.so $SYS/lib64/soundfx
cp -rfp $TMPDIR/dolby64/lib64/libprofileparamstorage.so $SYS/lib64
cp -rfp $TMPDIR/dolby64/ve_lib64/libprofileparamstorage.so $VENDOR/lib64
fi
fi
fi
}
block_specific() {
cd $SPECIFIC
rwrr apa_settings.cfg
rwrr lib/*.*
rwrr lib64/*.*
rwxrxrx bin/*
cp -rfp apa_settings.cfg $DATA_M/jack
# Samsung power sound play
cp -rfp bin/samsungpowersoundplay $BIN
cp -rfp lib/libsamsungpowersound.so $LIB
[ ! -d $ETC/init ] && mkdir -m0755 $ETC/init 2>/dev/null
cp -rf etc/init/powersnd.rc $ETC/init && rwrr $ETC/init/powersnd.rc
cp -rf alsa/alsa $USR/share
$(rwxrxrx $USR/share/alsa && rwrr $USR/share/alsa/alsa.conf);
[ -f $BIN/alsa* ] || $(cp -rf alsa/asound/libasound.so $LIB && rwrr $LIB/libasound.so);
for SUP in libsoundextractor.so libsoundspeed.so libaudioclient.so libaudiohal.so;
do
[ -f $LIB/$SUP ] || cp -rfp lib/$SUP $LIB
if $IS64BIT; then
for SUP64 in libsoundextractor.so libaudioclient.so libaudiohal.so;
do
[ -f $LIB64/$SUP64 ] || cp -rfp lib64/$SUP64 $LIB64
done
fi
done
if board_platform; then
cp -rfp lib/libsonic.so \
libsonivox.so \
libspeexresampler.so $LIB
if $IS64BIT; then
cp -rfp lib64/libsonic.so \
libsonivox.so \
libspeexresampler.so $LIB64
fi
fi
# Core
rwrr $CORE/lib/*.*
cp -rfp $CORE/lib/libprofileparamstorage.so \
#$CORE/lib/libmultirecord.so \
$CORE/lib/libsecaudiocoreutils.so \
$CORE/lib/libsecaudioinfo.so \
$CORE/lib/libsecnativefeature.so $LIB
board_platform && cp -rfp $CORE/lib/libvorbisidec.so $LIB
rwrr $CORE/vendor/lib/*.*
cp -rfp $CORE/vendor/lib/libalsautils_sec.so \
$CORE/vendor/lib/libaudioproxy.so \
$CORE/vendor/lib/libHMT.so \
$CORE/vendor/lib/libprofileparamstorage.so \
$CORE/vendor/lib/libsecaudioinfo.so \
$CORE/vendor/lib/libsecnativefeature.so $LIB_VE
[ -f $TMPDIR/dolby/lib/libprofileparamstorage.so ] || cp -rfp $CORE/lib/libprofileparamstorage.so $LIB
[ -f $TMPDIR/dolby/ve_lib/libprofileparamstorage.so ] || cp -rfp $CORE/vendor/lib/libprofileparamstorage.so $LIB_VE
if $IS64BIT; then
rwrr $CORE/lib64/*.*
cp -rfp $CORE/lib64/libprofileparamstorage.so \
#$CORE/lib64/libmultirecord.so \
$CORE/lib64/libsecaudiocoreutils.so \
$CORE/lib64/libsecaudioinfo.so \
$CORE/lib64/libsecnativefeature.so $LIB64
board_platform && cp -rfp $CORE/lib64/libvorbisidec.so $LIB64
rwrr $CORE/vendor/lib64/*.*
cp -rfp $CORE/vendor/lib64/libprofileparamstorage.so \
$CORE/vendor/lib64/libsecnativefeature.so $LIB64_VE
[ -f $TMPDIR/dolby/lib64/libprofileparamstorage.so ] || cp -rfp $CORE/lib64/libprofileparamstorage.so $LIB64
[ -f $TMPDIR/dolby/ve_lib64/libprofileparamstorage.so ] || cp -rfp $CORE/vendor/lib64/libprofileparamstorage.so $LIB64_VE
fi
if board_platform; then
local DEPENDENCE="$CORE/dependence"
rwrr $DEPENDENCE/lib/*.*
cp -rfp $DEPENDENCE/lib/libtinyalsa.so $DEPENDENCE/lib/libalsautils.so $LIB
if $IS64BIT; then
rwrr $DEPENDENCE/lib64/*.*
cp -rfp $DEPENDENCE/lib64/libtinyalsa.so $DEPENDENCE/lib64/libalsautils.so $LIB64
fi
fi
if [ "$API" -lt 28 ]; then
cp -rfp $CORE/lib/libdexfile.so $LIB
$IS64BIT && cp -rfp $CORE/lib64/libdexfile.so $LIB64
fi
prop_engine_edit=`
echo "1" > $PROPERTY/persist.audio.a2dp_avc
echo "0" > $PROPERTY/persist.audio.allsoundmute
echo "1" > $PROPERTY/persist.audio.corefx
echo "350000" > $PROPERTY/persist.audio.effectcpufreq
echo "1" > $PROPERTY/persist.audio.finemediavolume
echo "1" > $PROPERTY/persist.audio.globaleffect
echo "15" > $PROPERTY/persist.audio.headsetsysvolume
echo "15" > $PROPERTY/persist.audio.hphonesysvolume
echo "1" > $PROPERTY/persist.audio.k2hd
echo "0" > $PROPERTY/persist.audio.mpseek
echo "1" > $PROPERTY/persist.audio.mysound
echo "0" > $PROPERTY/persist.audio.nxp_lvvil
echo "0" > $PROPERTY/persist.audio.pcmdump
echo "1" > $PROPERTY/persist.audio.ringermode
echo "SKT" > $PROPERTY/persist.audio.sales_code
echo "1" > $PROPERTY/persist.audio.soundalivefxsec
echo "1" > $PROPERTY/persist.audio.stereospeaker
echo "15" > $PROPERTY/persist.audio.sysvolume
echo "1" > $PROPERTY/persist.audio.uhqa
echo "585600" > $PROPERTY/persist.audio.voipcpufreq`;
if [ "$API" -ge 28 ]; then
prop_vendor_edit=`
echo "true" > $PROPERTY/persist.vendor.audio.fluence.speaker
echo "true" > $PROPERTY/persist.vendor.audio.fluence.voicecall
echo "false" > $PROPERTY/persist.vendor.audio.fluence.voicerec
echo "false" > $PROPERTY/persist.vendor.audio.ras.enabled`
else
prop_vendor_edit=`
echo "true" > $PROPERTY/persist.audio.fluence.speaker
echo "true" > $PROPERTY/persist.audio.fluence.voicecall
echo "false" > $PROPERTY/persist.audio.fluence.voicerec
echo "false" > $PROPERTY/persist.audio.ras.enabled`
fi
for F_PROP_ENGINE_EDIT in $prop_engine_edit;
do
$F_PROP_ENGINE_EDIT;
done
for F_PROP_VENDOR_EDIT in $prop_vendor_edit;
do
$F_PROP_VENDOR_EDIT;
done
chmod 0600 $PROPERTY/persist.*
rwrr etc/audio_effects.conf
rwrr vendor/etc/audio_effects.conf
rwrr vendor/lib/soundfx/*.*
rwrr vendor/lib64/soundfx/*.*
cp -rfp etc/audio_effects.conf $ETC
cp -rfp vendor/etc/audio_effects.conf $ETC_VE
cp -rfp vendor/lib/soundfx $LIB_VE
$IS64BIT && cp -rfp vendor/lib64/soundfx $LIB64_VE
mkdir -m0755 $APP/SapaAudioConnectionService 2>/dev/null
cp -rf app/SapaAudioConnectionService.* $APP/SapaAudioConnectionService
$(rwxrxrx $APP/SapaAudioConnectionService && rwrr $APP/SapaAudioConnectionService/SapaAudioConnectionService.*);
mkdir -m0755 $APP/SapaMonitor 2>/dev/null
[ "$API" -le 23 ] && cp -rf app/api21/SapaMonitor.* $SYS/app/SapaMonitor || cp -rf app/SapaMonitor.* $APP/SapaMonitor
$(rwxrxrx $APP/SapaMonitor && rwrr $APP/SapaMonitor/SapaMonitor.*);
mkdir -m0755 $APP/SplitSoundService 2>/dev/null
[ "$API" -lt 23 ] && cp -rf app/api21/SplitSoundService.* $APP/SplitSoundService || cp -rf app/SplitSoundService.* $APP/SplitSoundService
$(rwxrxrx $APP/SplitSoundService && rwrr $APP/SplitSoundService/SplitSoundService.*);
mkdir -m0755 $PRIV/SoundAlive_54 2>/dev/null
[ "$API" -le 23 ] && cp -rf app/api21/SoundAlive_54.* $SYS/priv-app/SoundAlive_54 || cp -rf app/SoundAlive_54.* $PRIV/SoundAlive_54
$(rwxrxrx $PRIV/SoundAlive_54 && rwrr $PRIV/SoundAlive_54/SoundAlive_54.*);
# Hardware audio api26
if board_platform; then
if [ "$API" -lt 28 ]; then
if [ "$API" -gt 25 ]; then
cp -rfp lib/android.hardware.*.so $LIB
rwrr vendor/lib/hw/*.so
cp -rfp vendor/lib/hw/android.hardware.*.so $LIB_VE/hw
if $IS64BIT; then
cp -rfp lib64/android.hardware.*.so $LIB64
rwrr vendor/lib64/hw/*.so
cp -rfp vendor/lib64/hw/android.hardware.*.so $LIB64_VE/hw
fi
fi
fi
fi
# Pie
if [ "$API" -ge 28 ]; then
if [ ! -d $LIB_VE/soundfx ]; then
mkdir -m0755 $LIB_VE/soundfx
if $IS64BIT; then
if [ ! -d $LIB64_VE/soundfx ]; then
mkdir -m0755 $LIB64_VE/soundfx
fi
fi
fi
mv $LIB/soundfx/*.so $LIB_VE/soundfx
rwrr $LIB_VE/soundfx/*.so
rm -rf $LIB_VE/libwebrtc_audio_preprocessing.so
mv $LIB/libwebrtc_audio_preprocessing.so $LIB_VE/libwebrtc_audio_preprocessing.so
rwrr $LIB_VE/libwebrtc_audio_preprocessing.so
rwrr vendor/etc/audio_effects.xml
cp -rfp vendor/etc/audio_effects.xml $ETC_VE
if $IS64BIT; then
mv $LIB64/soundfx/*.so $LIB64_VE/soundfx
rwrr $LIB64_VE/soundfx/*.so
rm -rf $LIB64_VE/libwebrtc_audio_preprocessing.so
mv $LIB64/libwebrtc_audio_preprocessing.so $LIB64_VE/libwebrtc_audio_preprocessing.so
rwrr $LIB64_VE/libwebrtc_audio_preprocessing.so
fi
rm -rf $LIB/soundfx \
$LIB64/soundfx \
$ETC_VE/audio_effects.conf 2>/dev/null
fi
# Module path
if $MAGISK; then
if [ "$API" -ge 28 ]; then
echo "$(cat vendor/etc/audio_effects.xml)" > $ETC_VE/audio_effects.xml
else
echo "$(cat vendor/etc/audio_effects.conf)" > $ETC_VE/audio_effects.conf
fi
fi
# Low latency and audio pro
rwrr etc/permissions/*.xml
if [ "$API" -ge 28 ]; then
if [ ! -d $ETC_VE/permissions ]; then
mkdir -m0755 $ETC_VE/permissions
fi
cp -rfp etc/permissions/android.hardware.audio.low_latency.xml $ETC_VE/permissions
cp -rfp etc/permissions/android.hardware.audio.pro.xml $ETC_VE/permissions
rm -rf $ETC/permissions/android.hardware.audio.low_latency.xml \
$ETC/permissions/android.hardware.audio.pro.xml 2>/dev/null
else
cp -rfp etc/permissions/android.hardware.audio.low_latency.xml $ETC/permissions
cp -rfp etc/permissions/android.hardware.audio.pro.xml $ETC/permissions
rm -rf $ETC_VE/permissions/android.hardware.audio.low_latency.xml \
$ETC_VE/permissions/android.hardware.audio.pro.xml 2>/dev/null
fi
PLATFORM=$ETC/permissions/platform.xml
if ! grep "com.sec.android.splitsound" $PLATFORM; then
sed -i '/\<\/permissions\>/d' $PLATFORM && echo '
<!-- Split sound application -->
<allow-in-power-save package="com.sec.android.splitsound"/>
</permissions>' >> $PLATFORM
fi
chcon "u:object_r:audio_data_file:s0" /data/snd
chcon "u:object_r:audio_data_file:s0" /data/snd/*
chcon "u:object_r:audio_device:s0" /dev/snd
chcon "u:object_r:audio_device:s0" /dev/snd/*
chown root:shell $BIN/apaservice
chown root:shell $BIN/jackd
chown root:shell $BIN/jackservice
chown root:shell $BIN/samsungpowersoundplay
chown root:shell $XBIN/jack*
chown root:shell $BIN/profman
chown system:shell $DATA_M/profman
chown system:shell $DATA_M/jack
chown system:shell $DATA_M/jack/apa_settings.cfg
rwrr $FEATURE/*.xml
cp -rfp $FEATURE/com.samsung.feature.device_category_phone_high_end.xml $ETC/permissions
cp -rfp $FEATURE/com.samsung.feature.device_category_phone.xml $ETC/permissions
if [ "$API" -ge 28 ]; then
cp -rf $FEATURE/api28/media_cmd.jar $FRAME
rwrr $FRAME/media_cmd.jar
cp -rf $FEATURE/media $BIN
rwxrxrx $BIN/media
elif [ "$API" -ge 24 ]; then
if [ "$API" -le 25 ]; then
cp -rf $FEATURE/media_cmd.jar $FRAME
rwrr $FRAME/media_cmd.jar
cp -rf $FEATURE/media $BIN
rwxrxrx $BIN/media
fi
fi
chown root:shell $BIN/media
rm -rf $FRAME/com.google.android.media.effects.jar \
$ETC/permissions/com.google.android.media.effects.xml
} > /dev/null 2>/dev/null
block_backup() {
ui_print "- Backup..."; $(usleep 100000);
rm -rf $ENGINE_SV
mkdir -m0755 $ENGINE_SV && cd $ENGINE_SV
$(
mkdir -m0755 app
mkdir -m0755 bin
mkdir -m0755 etc
if [ -d $ETC/init ]; then
mkdir -m0755 etc/init
fi
mkdir -m0755 etc/security
mkdir -m0755 etc/security/cacerts
mkdir -m0755 etc/permissions
mkdir -m0755 framework
mkdir -m0755 lib
mkdir -m0755 lib/hw
mkdir -m0755 priv-app
if [ -d $USR/share/alsa ]; then
mkdir -m0755 usr
mkdir -m0755 usr/share
mkdir -m0755 usr/share/alsa
fi
mkdir -m0755 vendor
if [ -d $ETC_VE ]; then
mkdir -m0755 vendor/etc
fi
if [ -d $VENDOR/firmware ]; then
mkdir -m0755 vendor/firmware
fi
mkdir -m0755 vendor/lib
mkdir -m0755 xbin
)
cp -rfp $BUILD $ENGINE_SV
for F_APP in $app; do cp -rfp $APP/$F_APP $ENGINE_SV/app; done
cp -rfp $APP/Viper4Android* $ENGINE_SV/app
cp -rfp $APP/VIPER4Android* $ENGINE_SV/app
for F_BIN in $bin; do cp -rfp $BIN/$F_BIN $ENGINE_SV/bin; done
for F_ETC in $etc; do cp -rfp $ETC/$F_ETC $ENGINE_SV/etc; done
cp -rfp $ETC/init/powersnd.rc $ENGINE_SV/etc/init
for F_CACERTS in $etccacerts; do cp -rfp $ETC/security/cacerts/$F_CACERTS $ENGINE_SV/etc/security/cacerts; done
for F_PERMISSIONS in $permissions; do cp -rfp $ETC/permissions/$F_PERMISSIONS $ENGINE_SV/etc/permissions; done
for F_FRAMEWORK in $framework; do cp -rfp $FRAME/$F_FRAMEWORK $ENGINE_SV/framework; done
for F_LIB in $lib; do cp -rfp $LIB/$F_LIB $ENGINE_SV/lib; done
cp -rfp $LIB/hw/audio.playback_record.default.so $ENGINE_SV/lib/hw
cp -rfp $LIB/hw/audio.tms.default.so $ENGINE_SV/lib/hw
for F_PRIVAPP in $privapp; do cp -rfp $PRIV/$F_PRIVAPP $ENGINE_SV/priv-app; done
cp -rfp $PRIV/Viper4Android* $ENGINE_SV/app
cp -rfp $PRIV/VIPER4Android* $ENGINE_SV/app
if [ -d $USR/share/alsa ]; then cp -rfp $USR/share/alsa $ENGINE_SV/usr/share; fi
cp -rfp $BUILD_VE $ENGINE_SV/vendor
if [ -f $ETC_VE/audio/audio_effects.xml ]; then
mkdir -m0755 vendor/etc/audio
cp -rfp $ETC_VE/audio/audio_effects.xml $ENGINE_SV/vendor/etc/audio
fi
for F_VENDORETC in $vendoretc; do cp -rfp $ETC_VE/$F_VENDORETC $ENGINE_SV/vendor/etc; done
for F_VENDORFIRMWARE in $vendorfirmware; do cp -rfp $VENDOR/firmware/$F_VENDORFIRMWARE $ENGINE_SV/vendor/firmware; done
for F_VENDORLIB in $vendorlib; do cp -rfp $LIB_VE/$F_VENDORLIB $ENGINE_SV/vendor/lib; done
if [ -d $LIB_VE/hw ]; then
mkdir -m0755 vendor/lib/hw
cp -rfp $LIB_VE/hw/audio.* \
$LIB_VE/hw/android.hardware.audio* \
$LIB_VE/hw/sound_trigger.primary.* \
$LIB_VE/hw/android.hardware.soundtrigger* $ENGINE_SV/vendor/lib/hw
fi
for F_XBIN in $xbin; do cp -rfp $XBIN/$F_XBIN $ENGINE_SV/xbin; done
if $IS64BIT; then
mkdir -m0755 lib64
mkdir -m0755 lib64/hw
mkdir -m0755 vendor/lib64
for F_LIB64 in $lib64; do cp -rfp $LIB64/$F_LIB64 $ENGINE_SV/lib64; done
cp -rfp $LIB64/hw/audio.* $ENGINE_SV/lib64/hw
cp -rfp $LIB64/hw/sound_trigger.* $ENGINE_SV/lib64/hw
for F_VENDORLIB64 in $vendorlib64; do cp -rfp $LIB64_VE/$F_VENDORLIB64 $ENGINE_SV/vendor/lib64; done
if [ -d $LIB64_VE/hw ]; then
mkdir -m0755 vendor/lib64/hw
cp -rfp $LIB64_VE/hw/audio* \
$LIB64_VE/hw/android.hardware.audio* \
$LIB64_VE/hw/android.hardware.soundtrigger* \
$LIB64_VE/hw/sound_trigger.* $ENGINE_SV/vendor/lib64/hw
fi
fi
[ -d $ENGINE_SV ] && pack -czf $BK * ; rm -rf $ENGINE_SV; mv $TMPDIR/uninstall.sh $TMPDIR/restore.sh || abort "Error: Failed to create backup!"
[ ! -f $BK ] && abort "Error: Failed to create backup!"
} 2>/dev/null
block_uninstall() {
ui_print "- Uninstalling..."; $(usleep 200000);
local UNSH="uninstall.sh"
[ -f $TMPDIR/$UNSH ] && launch $TMPDIR/$UNSH > /dev/null 2>/dev/null; rm -rf $TMPDIR/$UNSH || abort "Error: Unable to uninstall!"
}
[ ! -f $BK ] && unzip -oq "$ZIPFILE" specific.txz system.txz -d $TMPDIR 2>/dev/null; $IS64BIT && unzip -oq "$ZIPFILE" is64bit.txz -d $TMPDIR 2>/dev/null
block_check() {
ui_print "- System check..."; $(usleep 100000);
if [ ! -f $BUILD ]; then
ui_print "Error: Failed to mount partitions!"
abort "Try to mount manually "/system", "/vendor" and repeat the installation."
fi
rw_system() { touch /system/rw 2>/dev/null && rm -rf /system/rw; }
rw_system || abort "Error: Not possible to install. Read-only file system!"
for BKP in $LOCAL/backup_s8.pack $LOCAL/aes_v4.dub \
$LOCAL/engine_sv4_b41.dub $LOCAL/engine_sv4_b42.dub \
$DATA/stock_system_v43.arch;
do
[ -f $BKP ] && abort "Error: Not possible to install. Remove the previous version!"
done
mkdir_check() { mkdir -m0755 $LOCAL/mkcheck 2>/dev/null && rm -rf $LOCAL/mkcheck; }
if ! mkdir_check; then
ui_print "Error: Error using binary files!"
abort "Try to update busybox or failed to mount partition "/data""
fi
if [ "$API" -le 20 ]; then
abort "Error: Unable to install, requires minimum version of Android 5.0!"
fi
}
auto_wipe() {
local DIR="$DATA"
local DALVIK="dalvik-cache"
if [ -f $BK ]; then
ui_print "Clearing dalvik-cache and rebooting"; $(usleep 100000);
rm -rf $DIR/$DALVIK/* && reboot
fi
}
on_install() {
[ ! -f $BK ] && proc_var -i || proc_var -u 2>/dev/null
}
print_modname() {
ui_print "-----------------------------------------------"
ui_print "Name: Samsung Audio Engine"
ui_print "Version: 4.4"
ui_print "Author: shimmer"
ui_print "Thanks: Alexmak77, <NAME>, papadim1002"
ui_print " выбермудень, nonamer1990"
ui_print "-----------------------------------------------"; $(usleep 200000);
$MAGISK && pbm
}
pbm() {
ui_print "*******************"
ui_print " Powered by Magisk "
ui_print "*******************"
}
set_permissions() {
set_perm_recursive $MODPATH 0 0 0755 0644
}
# You can add more functions to assist your custom script code
<file_sep>/common/post-fs-data.sh
#!/system/bin/sh
# Do NOT assume where your module will be located.
# ALWAYS use $MODDIR if you need to know where this script
# and module is placed.
# This will make sure your module will still work
# if Magisk change its mount point in the future
MODDIR=${0%/*}
EFFECTS_XML=/system/vendor/audio_effects.xml
EFFECTS=/system/vendor/audio_effects.conf
POSTPROCESS=false
ENFORCE=false
[ -d /sdcard/Android ] && CFGDIR=/sdcard
[ -d /storage/emulated/0/Android ] && CFGDIR=/storage/emulated/0
CFGNAME=engine_s.conf
ECFG=$CFGDIR/$CFGNAME
[ -f $ECFG ] && . $ECFG
if $POSTPROCESS; then
if [ -f $EFFECTS_XML ]; then
sed -i '/\<\/audio_effects_conf\>/d' $EFFECTS_XML && echo '
<postprocess>
<stream type="music">
<apply effect="soundalive"/>
</stream>
<stream type="ring">
<apply effect="soundalive"/>
</stream>
<stream type="alarm">
<apply effect="soundalive"/>
</stream>
</postprocess>
</audio_effects_conf>' >> $EFFECTS_XML
elif [ -f $EFFECTS ]; then
echo "
output_session_processing {
music {
soundalive {}
}
ring {
soundalive {}
}
alarm {
soundalive {}
}
}" >> $EFFECTS
fi
fi
usleep 10000000
if $ENFORCE; then
for MODECHANGE in /sys/fs/selinux/enforce;
do ls $MODECHANGE > /dev/null && MCH=true || MCH=false
&& $MCH && echo "0" > $MODECHANGE || ${ grep "0" $MODECHANGE || setenforce 0 } 2>/dev/null
done
fi
# This script will be executed in post-fs-data mode | 6a5ae8ed5937adf485ddbe303d77bcf1456c46c7 | [
"Markdown",
"Shell"
] | 4 | Shell | shimmer24/SamsungAudioEngine | 80dbe2a8461fc974235c095e1371bc7179e2273a | 9bdf61815320745e9ee00b264408c73261a04481 | |
refs/heads/master | <file_sep>import java.awt.*;
/**
* Created by student on 11/16/17.
*/
public class Game {
private int[][] gr;
public Game(){
gr = new int[3][3];
}
public void draw(Graphics2D g2, int w, int h){
for (int r = 0; r < gr.length; r++) {
for (int c = 0; c < gr[0].length; c++) {
g2.drawRect(w/3*r, h/3*c, w/3, h/3);
// gr[r][c] = 0;
}
}
}
public int[][] getGr() {
return gr;
}
public boolean checkIfWin(){ //DID NOT FINISH!!!!
// for (int r = 0; r < gr.length; r++) {
// for (int c = 0; c < gr[0].length; c++) {
// if(gr[r][c] == gr[r][c+1] && gr[r][c+1] == gr[r][c+2] && gr[r][c] != 0){
//// return gr[r][c];
// return true;
// }else if(gr[r][c] == gr[r+1][c] && gr[r+1][c] == gr[r+2][c] && gr[r][c] != 0){
// return true;
//
// }
// }
for (int r = 0; r < gr.length; r++) {
if (gr[r][0] == gr[r][1] && gr[r][1] == gr[r][2] && gr[r][0] != 0) {
// return gr[r][c];
return true;
}
}
for (int c = 0; c < gr[0].length; c++) {
if (gr[0][c] == gr[1][c] && gr[1][c] == gr[2][c] && gr[0][c] != 0) {
return true;
}
}
if(gr[0][0] == gr[1][1] && gr[1][1] == gr[2][2] && gr[0][0] != 0){
return true;
}
if(gr[0][2] == gr[1][1] && gr[1][1] == gr[2][0] && gr[0][2] != 0){
return true;
}
return false;
}
public boolean checkIfTie(){
for (int r = 0; r < gr.length; r++) {
for (int c = 0; c < gr[0].length; c++) {
if(gr[r][c] == 0){
return false;
}
}
}
return true;
}
}
<file_sep>//import java.awt.*;
//
///**
// * Created by student on 11/17/17.
// */
//public class O {
//
// int width;
// int height;
// int xx;
// int yy;
//
// public O(int w, int h, int x, int y){
// width = w;
// height = h;
// xx = x;
// yy = y;
// }
//
// public void paintComponent(Graphics g){
// Graphics2D g2 = (Graphics2D)g;
//// g2.drawOval(xx, yy, width/3, height/3);
//
// }
//}
| 567fde09c1f5ee13221f99d019b4fe155634ebf9 | [
"Java"
] | 2 | Java | LiangL2020/TicTacToe_ | 11d7f37e1e6f78f5fd5a71e1df8178d5fefdedaf | 8943d4e6923e60eb4c4452eed678f6c6e4717de4 | |
refs/heads/master | <file_sep>/**
* Created by Hunter on 2015-03-08.
*/
public class CalculatorDouble implements CalculatorDoubleImp {
@Override
public double add(double a, double b) {
return a+b;
}
@Override
public double sub(double a, double b) {
return a-b;
}
@Override
public double multi(double a, double b) {
return a*b;
}
@Override
public double div(double a, double b) {
return a/b;
}
@Override
public boolean greater(double a, double b) {
if(a>b) return true;
else return false;
}
}<file_sep>package com.example.mock.test;
import com.example.mock.app.Messenger;
import com.example.mock.messenger.DummyMsgService;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Created by Hunter on 2015-04-15.
*/
public class DummyMsgServiceTest {
private Messenger messenger;
@Before
public void Init() {
messenger = new Messenger(new DummyMsgService());
}
//PASSING TESTS
@Test
public void TestConnectionWithServerForCorrectAdress() {
assertThat(messenger.TestConnection("www.wp.pl"), is(0));
}
@Test
public void SendCommuniqueForCorrectMessageCorrectServer() {
assertThat(messenger.SendMsg("Message for", "www.interia.pl"), is(anyOf(equalTo(1), equalTo(0))));
}
//FAILURE TEST
@Test
public void TestConnectionWithServerForWrongAdress() {
assertThat(messenger.TestConnection("www.wp.gov"), is(1));
}
@Test
public void SendCommuniqueForWrongMessageCorrectServer() {
assertThat(messenger.SendMsg("Ab", "www.interia.pl"), is(anyOf(equalTo(1), equalTo(0))));
}
@Test
public void SendCommuniqueForCorrectMessageWrongServer() {
assertThat(messenger.SendMsg("Message for", "www.interia.gov"), is(1));
}
@Test
public void SendCommuniqueForWrongMessageWrongServer() {
assertThat(messenger.SendMsg("Av", "www.interia.gov"), is(1));
}
}
<file_sep>/**
* Created by Hunter on 2015-03-18.
*/
package com.game.code;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Created by Hunter on 2015-03-10.
*/
public class Psikus implements IPsikus {
@Override
public Integer cyfrokrad(Integer liczba) {
//Split of Integer to string
String number = String.valueOf(liczba);
//List<Integer> digits = new ArrayList<Integer>(); easier way
String[] digits = number.split("(?<=.)");
//return null if only 1 element
if (digits.length <= 1) {
return null;
}
Random random = new Random();
int randomize = random.nextInt(digits.length);
//loop to delete an element(Array list would be easier ArrayList got .remove method)
//adding array to new integer
int i;
int num = 0;
for (i = 0; i < digits.length; i++) {
if(i !=randomize)
num = 10 * num + Integer.valueOf(digits[i]);
}
return num;
}
@Override
public Integer hultajchochla(Integer liczba) throws NieudanyPsikusException {
//Split of Integer to string
String number = String.valueOf(liczba);
//List<Integer> digits = new ArrayList<Integer>(); easier way
String[] digits = number.split("(?<=.)");
Random random = new Random();
int randomize = random.nextInt(digits.length);
int randomize2 = random.nextInt(digits.length);
String pom, pom2;
try {
if (digits.length <= 1) {
throw new NieudanyPsikusException("Wrong Length (it should be above 1)");
}
//switch
pom = digits[randomize];
pom2 = digits[randomize2];
digits[randomize] = pom2;
digits[randomize2] = pom;
} catch (NieudanyPsikusException e) {
System.out.println(e.getMessage());
}
//adding array to new integer
int i;
int num = 0;
for (i = 0; i < digits.length; i++) {
num = 10 * num + Integer.parseInt(digits[i]);
}
return num;
}
@Override
public Integer nieksztaltek(Integer liczba) {
//Split of Integer to string
String number = String.valueOf(liczba);
//List<Integer> digits = new ArrayList<Integer>(); easier way
String[] digits = number.split("(?<=.)");
int i;
List<Integer> three = new ArrayList<Integer>();
List<Integer> six = new ArrayList<Integer>();
List<Integer> seven = new ArrayList<Integer>();
for (i = 0; i < digits.length; i++) {
if (digits[i].equals("3")) {
three.add(i);
}
if (digits[i].equals("6")) {
six.add(i);
}
if (digits[i].equals("7")) {
seven.add(i);
}
}
//if empty return argument
if (three.size() == 0 && six.size() == 0 && seven.size() == 0) {
return liczba;
}
int randomize;
Random random = new Random();
if (three.size() != 0) {
randomize = random.nextInt(three.size());
int val = three.get(randomize);
System.out.print(val);
digits[val] = "8";
}
if (six.size() != 0) {
randomize = random.nextInt(six.size());
int val = three.get(randomize);
System.out.print(val);
digits[val] = "9";
}
if (seven.size() != 0) {
randomize = random.nextInt(seven.size());
int val = three.get(randomize);
System.out.print(val);
digits[val] = "1";
}
//adding array to new integer
int num = 0;
for (i = 0; i < digits.length; i++) {
num = 10 * num + Integer.parseInt(digits[i]);
}
return num;
}
}<file_sep>/**
* Created by Hunter on 2015-03-08.
*/
import org.junit.*;
import org.junit.Test;
import org.junit.rules.ExpectedException;
/**
* Created by student on 25.02.15.
*/
public class CalculatorTest {
private Calculator calculatorImp;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Before
public void setUp() {
calculatorImp = new Calculator();
}
@Test
public void AddTest() {
Assert.assertEquals(20, calculatorImp.add(14, 6));
}
@Test
public void SubTest() {
Assert.assertEquals(19, calculatorImp.sub(20, 1));
}
@Test
public void multiTest() {
Assert.assertEquals(40, calculatorImp.multi(8, 5));
}
@Test
public void divTest() {
Assert.assertEquals(12, calculatorImp.div(36, 3));
}
@Test
public void greaterTest() {
Assert.assertTrue(calculatorImp.greater(20, 12));
}
@Test
public void DivideArithmeticException_Excepted() {
thrown.expect(ArithmeticException.class);
calculatorImp.div(14, 0);
}
//to samo co wyzej
@Test(expected = ArithmeticException.class)
public void DivExp() throws ArithmeticException {
calculatorImp.div(14, 0);
}
}
<file_sep>/**
* Created by Hunter on 2015-04-15.
*/
public class Messenger {
private IMessageService messageService;
public Messenger(IMessageService msgService) {
this.messageService = msgService;
}
public Messenger() {
}
public int TestConnection(String address) {
//FAILURE
if (messageService.checkConnection(address) != ConnectionStatus.SUCCESS)
return 1;
//SUCESS
return 0;
}
public int SendMsg(String msg, String address) {
try {
SendingStatus ss = messageService.send(address, msg);
//SEND ERROR
if (TestConnection(address) != 0 || ss!= SendingStatus.SENT)
return 1;
} catch (MalformedRecipientException e) {
e.printStackTrace();
return 1;
}
//SENT
return 0;
}
}<file_sep>/**
* Created by Hunter on 2015-04-08.
*/
package com.example.mock.messenger;
public enum ConnectionStatus {
SUCCESS, FAILURE
}
<file_sep>/**
* Created by Hunter on 2015-03-08.
*/
public class LiczbaRzymska {
private int liczba;
public LiczbaRzymska(int liczba){
this.liczba = liczba;
}
public static String ToRom(int arabska){
String roman = "";
if(arabska < 1 || arabska > 3999){
return "Insert Integer between 1 and 9999";
}
for(;arabska>=1000;arabska=arabska-1000) {
roman = roman + "M";
}
for(;arabska>=900;arabska=arabska-900) {
roman = roman + "CM";
}
for(;arabska>=500;arabska=arabska-500) {
roman = roman + "D";
}
for(;arabska>=400;arabska=arabska-400) {
roman = roman + "CD";
}
for(;arabska>=100;arabska=arabska-100) {
roman = roman + "C";
}
for(;arabska>=90;arabska=arabska-90) {
roman = roman + "XC";
}
for(;arabska>=50;arabska=arabska-50) {
roman = roman + "L";
}
for(;arabska>=40;arabska=arabska-40) {
roman = roman + "XL";
}
for(;arabska>=10;arabska=arabska-10) {
roman = roman + "X";
}
for(;arabska>=9;arabska=arabska-9) {
roman = roman + "IX";
}
for(;arabska>=5;arabska=arabska-5) {
roman = roman + "V";
}
for(;arabska>=4;arabska=arabska-4) {
roman = roman + "IV";
}
for(;arabska>=1;arabska=arabska-1) {
roman = roman + "I";
}
return roman;
}
@Override
public String toString() {
return ToRom(liczba);
}
}
<file_sep>package com.example.maven.game;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Created by Hunter on 2015-03-10.
*/
public class Psikus implements Ipsikus {
@Override
public Integer cyfrokrad(Integer liczba) {
//Split of Integer to string
String number = String.valueOf(liczba);
List<Integer> digits = new ArrayList<Integer>();
for(int i=0;i<number.length();i++){
digits.add(number.charAt(i)-48);
}
if (digits.size() <=1 ){
return null;
}
Random rand = new Random();
int random = rand.nextInt(digits.size());
digits.remove(random);
int[] array = new int[digits.size()];
for(int i=0;i < array.length ;i++){
array[i] = digits.get(i);
}
int res=0;
for(int i=0;i < array.length ;i++) {
res = 10 * res + array[i];
}
return res;
}
@Override
public Integer hultajchochla(Integer liczba) throws NieudanyPsikusException {
String number = String.valueOf(liczba);
List<Integer> digits = new ArrayList<Integer>();
for(int i=0;i<number.length();i++){
digits.add(number.charAt(i)-48);
}
Random random = new Random();
int randomize = random.nextInt(digits.size());
int randomize2 = random.nextInt(digits.size());
int pom, pom2;
try {
if (digits.size() <= 1) {
throw new NieudanyPsikusException("Wrong Length (it should be above 1)");
}
//switch
pom = digits.get(randomize);
pom2 = digits.get(randomize2);
digits.set(randomize,pom2);
digits.set(randomize2,pom);
} catch (NieudanyPsikusException e) {
System.out.println(e.getMessage());
}
//adding array to new integer
int[] array = new int[digits.size()];
for(int j=0;j < array.length ;j++){
array[j] = digits.get(j);
}
int res=0;
for(int j=0;j < array.length ;j++) {
res = 10 * res + array[j];
}
return res;
}
@Override
public Integer nieksztaltek(Integer liczba) {
//Split of Integer to string
String number = String.valueOf(liczba);
List<Integer> digits = new ArrayList<Integer>();
for(int i=0;i<number.length();i++){
digits.add(number.charAt(i)-48);
}
int i;
List<Integer> three = new ArrayList<Integer>();
List<Integer> six = new ArrayList<Integer>();
List<Integer> seven = new ArrayList<Integer>();
for (i = 0; i < digits.size(); i++) {
if (digits.get(i) == 3) {
three.add(i);
}
if (digits.get(i) == 6) {
six.add(i);
}
if (digits.get(i) == 7) {
seven.add(i);
}
}
//if empty return argument
if (three.size() == 0 && six.size() == 0 && seven.size() == 0) {
return liczba;
}
int randomize;
Random random = new Random();
if (three.size() != 0) {
randomize = random.nextInt(three.size());
digits.set(randomize,8);
}
if (six.size() != 0) {
randomize = random.nextInt(six.size());
digits.set(randomize,9);
}
if (seven.size() != 0) {
randomize = random.nextInt(seven.size());
digits.set(randomize,1);
}
//adding array to new integer
int[] array = new int[digits.size()];
for(int j=0;j < array.length ;j++){
array[j] = digits.get(j);
}
int res=0;
for(int j=0;j < array.length ;j++) {
res = 10 * res + array[j];
}
return res;
}
}
<file_sep>/**
* Created by Hunter on 2015-03-18.
*/
package com.game.test;
import com.game.code.NieudanyPsikusException;
import com.game.code.Psikus;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.hamcrest.core.AnyOf.anyOf;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
public class PsikusTest {
private Psikus psikus = new Psikus();
@Rule
public ExpectedException thrown = ExpectedException.none();
//cyfrokrad Tests
@Test
public void cyfrokradNotNullReturn() {
Assert.assertNotNull(psikus.cyfrokrad(123).intValue());
}
@Test
public void cyfrokradReturnNull() {
Assert.assertNull(psikus.cyfrokrad(5));
}
@Test
public void cyfrokradRemoveofOneNumber() {
Assert.assertEquals(2, psikus.cyfrokrad(169).toString().length());
}
@Test
public void cyfrokradLengthOfThree() {
Assert.assertEquals(3, psikus.cyfrokrad(1694).toString().length());
}
//chujtajchochla Test
// @Test
// public void hultajchochlaException() throws NieudanyPsikusException {
// thrown.expect(NieudanyPsikusException.class);
// psikus.hultajchochla(1);
// }
@Test
public void hultajchochlaDiffNumber() throws NieudanyPsikusException {
Assert.assertNotSame(13246, psikus.hultajchochla(12346).toString());
}
//Nieksztaltek Tests:
@Test
public void nieksztaltekDiffrentResult() {
Assert.assertThat(psikus.nieksztaltek(367).intValue(), is(anyOf(equalTo(867), equalTo(361), equalTo(397))));
}
@Test
public void nieksztaltekSameNumberNothingToSwap() {
Assert.assertEquals(124, psikus.nieksztaltek(124).intValue());
}
@Test
public void nieksztaltekDiffrentNumberSwap() {
Assert.assertNotEquals(136, psikus.nieksztaltek(136).intValue());
}
@Test
public void nieksztaltekOnlySwap() {
Assert.assertNotSame(376, psikus.nieksztaltek(376).intValue());
}
}<file_sep>/**
* Created by Hunter on 2015-03-08.
*/
public interface CalculatorDoubleImp {
double add(double a, double b);
double sub(double a, double b);
double multi(double a, double b);
double div(double a, double b);
boolean greater(double a, double b);
}
<file_sep>package com.game.code;
/**
* Created by Hunter on 2015-03-18.
*/
public interface IPsikus {
Integer cyfrokrad(Integer liczba);
Integer hultajchochla(Integer liczba) throws NieudanyPsikusException;
Integer nieksztaltek(Integer liczba);
}
<file_sep>package com.game.code;
/**
* Created by Hunter on 2015-03-18.
*/
public class NieudanyPsikusException extends Exception{
private static final long serialVersionUID = -4197380075619961717L;
//Parameterless Constructor
//Constructor that accepts a message
public NieudanyPsikusException(String message)
{
super(message);
}
}
<file_sep>package com.example.mock.messenger;
/**
* Created by Hunter on 2015-04-08.
*/
public interface IMessageService {
ConnectionStatus checkConnection(String server);
SendingStatus send(String server, String contents) throws MalformedRecipientException;
}
<file_sep>package com.example.mock.messenger;
/**
* Created by Hunter on 2015-04-08.
*/
public enum SendingStatus {
SENT, SENDING_ERROR
}
<file_sep>/**
* Created by Hunter on 2015-03-08.
*/
public class Calculator implements CalculatorImp {
@Override
public int add(int a, int b) {
return a+b;
}
@Override
public int sub(int a, int b) {
return a-b;
}
@Override
public int multi(int a, int b) {
return a*b;
}
@Override
public int div(int a, int b) {
return a/b;
}
@Override
public boolean greater(int a, int b) {
if(a>b) return true;
else return false;
}
}
<file_sep>/**
* Created by Hunter on 2015-03-10.
*/
public interface PsikusImp {
Integer cyfrokrad(Integer liczba);
Integer hultajchochla(Integer liczba) throws NieudanyPsikusException;
Integer nieksztaltek(Integer liczba);
}
<file_sep>package com.example.mock.messenger;
import java.util.Random;
/**
* Created by Hunter on 2015-04-08.
*/
public class DummyMsgService implements IMessageService {
@Override
public ConnectionStatus checkConnection(String server) {
if(server.matches("www.[A-Za-z]{2,}.pl$")){
return ConnectionStatus.SUCCESS;
}
return ConnectionStatus.FAILURE;
}
@Override
public SendingStatus send(String server, String contents) throws MalformedRecipientException {
if (server.length() < 4 || contents.length() < 2) {
throw new MalformedRecipientException();
}
if(checkConnection(server) == ConnectionStatus.FAILURE) {
return SendingStatus.SENDING_ERROR;
}
Random random = new Random();
boolean x = random.nextBoolean();
if(x){
return SendingStatus.SENT;
}
return SendingStatus.SENDING_ERROR;
}
}
<file_sep>
import org.apache.commons.io.FileUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
/**
* Created by Hunter on 2015-04-22.
*/
public class TelemanTests {
private static WebDriver driver;
WebElement element;
@BeforeClass
public static void driverSetup() {
// ChromeDrirver, FireforxDriver, ...
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Hunter\\Downloads\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
@Test
public void homePage(){
driver.get("http://www.teleman.pl");
assertEquals("Program TV",driver.getTitle());
}
@Test
public void register() throws InterruptedException {
driver.get("http://www.teleman.pl/");
driver.findElement(By.cssSelector("a[href*='/account']")).click();
driver.findElement(By.cssSelector("a[href*='/accounts/signup']")).click();
driver.findElement(By.id("id_username")).sendKeys("test");
driver.findElement(By.id("id_email")).sendKeys("<EMAIL>");
driver.findElement(By.id("id_password")).sendKeys("<PASSWORD>");
driver.findElement(By.xpath(".//*[@id='signupForm']/div[2]/input")).click();
assertEquals("Użytkownik z taką nazwą jest już zarejestrowany.", driver.findElement(By.className("errorlist")).getText());
}
@Test
public void login(){
driver.get("http://www.teleman.pl/");
driver.findElement(By.cssSelector("a[href*='/account']")).click();
driver.findElement(By.id("id_username")).sendKeys("kekeke");
driver.findElement(By.id("id_password")).sendKeys("<PASSWORD>");
driver.findElement(By.xpath(".//*[@id='signupForm']/div[2]/input")).click();
assertEquals("Nieprawidłowa nazwa użytkownika, email lub hasło. Pamietaj, że wielkość liter w haśle jest ważna.",driver.findElement(By.className("errorlist")).getText());
}
@Test
public void search() throws IOException {
driver.get("http://www.teleman.pl/");
driver.findElement(By.xpath("//*[@id=\"search-form\"]/input[1]")).sendKeys("Liga Mistrzow");
driver.findElement(By.xpath("//*[@id=\"search-form\"]/input[1]")).submit();
driver.findElement(By.cssSelector("a[href*='/tv/Pilka-Nozna-Liga-Mistrzow-1305579")).click();
assertEquals("rewanżowy mecz ćwierćfinałowy: Real Madryt - Atletico Madryt",driver.findElement(By.id("showMainInfo")).getText());
assertEquals("CANAL+ Sport", driver.findElement(By.cssSelector("a[href*='/program-tv/stacje/CanalPlus-Sport#prog9974185")).getText());
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\Users\\Hunter\\Desktop\\screenshot.png"));
}
@Test
public void loginAndCheck(){
driver.get("http://www.morele.net/");
driver.findElement(By.className("profile")).click();
driver.findElement(By.name("email")).sendKeys("<EMAIL>");
driver.findElement(By.name("password")).sendKeys("<PASSWORD>");
driver.findElement(By.name("submitLogin")).click();
driver.findElement(By.className("profile")).click();
assertEquals("Patryk", driver.findElement(By.id("firstname")).getAttribute("value"));
assertEquals("Adamaszek", driver.findElement(By.id("lastname")).getAttribute("value"));
assertEquals("691766007", driver.findElement(By.id("phone")).getAttribute("value"));
driver.findElement(By.className("logout")).click();
}
@Test
public void addToCart(){
driver.get("http://www.morele.net/");
driver.findElement(By.className("profile")).click();
driver.findElement(By.name("email")).sendKeys("<EMAIL>");
driver.findElement(By.name("password")).sendKeys("<PASSWORD>");
driver.findElement(By.name("submitLogin")).click();
driver.findElement(By.className("department")).click();
driver.findElement(By.cssSelector("a[href*='/komputer-morele-harcot-asus-gaming-kit-690856/")).click();
driver.findElement(By.xpath(".//*[@id='right']/div/div[2]/p[4]/a/img")).click();
driver.findElement(By.cssSelector("a[href*='/koszyk")).click();
assertEquals("Komputer Morele Harcot Asus Gaming Kit", driver.findElement(By.xpath(".//*[@id='overflow']/form[2]/table/tbody/tr[1]/td[3]/a")).getText());
driver.findElement(By.className("delete")).click();
driver.findElement(By.className("logout")).click();
}
/*@AfterClass
public static void cleanp() {
driver.quit();
}*/
}
| 2464a0f9293a78096026559aada165b44985f38a | [
"Java"
] | 18 | Java | padamaszek/TAJ | de852c11ff1995613c4fbe4fe3a36b899b52cef3 | f248e5c4d4ec27d533feddd0e504cb7806be96b9 | |
refs/heads/master | <file_sep># Meow Tax App Thing
Sister. You can start modifying this app to make it what you wanted to have.
It's very documented. See index.js and the public/ folder.
<file_sep>/*
Sis.
Ok, so. The first thing is to use Express. It's a package for Node that folk made
and it makes servers.
*/
express = require ( 'express' );
/*
When you're hosting it, this is the file that runs on the hosting's server computer,
and Express lets us tell it what to do.
*/
app = express ( );
/*
Since this app will run entirely in the browser, we're just using this to serve
files. The use method adds simple behaviors to the app. Static is the name
of this particular behavior of express and 'public' is the folder where it can
find those files.
*/
app.use( express.static('public') );
/*
This runs the express server. 3000 is the port, which if you want to deploy it
on the web, will be 80. It's a different number for development, since your
computer's already using 80 for browsing the web.
*/
app.listen ( 3000 );
| 280e832f7e8f6c114864bf7eb3e7952aa23fdc96 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | notauid/meow-tax-app-thing | 753e025de9db42df5194fe75cf8a9828d8f56f2f | 1e38f12420fbfe922ced2e8323f3f370335c5088 | |
refs/heads/master | <file_sep># Import packages
import tensorflow as tf
import pandas as pd
import numpy as np
import os
os.chdir('C://Users//vnino//Desktop//CE888 - Assignment 2//Python code//mushrooms//data')
import random
# Fetch the dataset
names=['label', 'cap_shape', 'cap_surface',
'cap_color', 'bruises', 'odor',
'gill_attachment', 'gill_spacing', 'gill_size',
'gill_color', 'stalk_shape', 'stalk_root',
'stalk_surface_above', 'stalk_surface_below',
'stalk_color_above', 'stalk_color_below', 'veil_type',
'veil_color', 'ring_number', 'ring_type',
'spore_print_color', 'population','habitat']
df = pd.read_csv("agaricus-lepiota.csv", names=names)
# Filter missing values
df=df[df.stalk_root!='?']
df=df.drop(columns=['veil_type', 'veil_color'])
data_df=pd.get_dummies(df, prefix=['label', 'cap_shape', 'cap_surface',
'cap_color', 'bruises', 'odor',
'gill_attachment', 'gill_spacing', 'gill_size',
'gill_color', 'stalk_shape', 'stalk_root',
'stalk_surface_above', 'stalk_surface_below',
'stalk_color_above', 'stalk_color_below',
'ring_number', 'ring_type',
'spore_print_color', 'population','habitat'])
data_df=data_df.drop(columns=['label_e'])
data_df=data_df.rename(index=str, columns={'label_p': 'label'})
#Defining labels and features
data_df.reset_index(inplace=True, drop=True)
target=data_df['label']
data=np.asarray(data_df.iloc[:,21:])
n_samples= data.shape[0]
n_clusters=2
# Get the split between training/test set and validation set
random.seed(0)
test_indices = random.sample(range(0, 5644), 1120)
validation_indices = [x for x in range(0, 5644) if x not in test_indices]
# Auto-encoder architecture
input_size = data.shape[1]
hidden_1_size = 500
hidden_2_size = 500
hidden_3_size = 2000
embedding_size = n_clusters
dimensions = [hidden_1_size, hidden_2_size, hidden_3_size, embedding_size, # Encoder layer dimensions
hidden_3_size, hidden_2_size, hidden_1_size, input_size] # Decoder layer dimensions
activations = [tf.nn.relu, tf.nn.relu, tf.nn.relu, None, # Encoder layer activations # None is linear activation
tf.nn.relu, tf.nn.relu, tf.nn.relu, None] # Decoder layer activations # None is linear activation
names = ['enc_hidden_1', 'enc_hidden_2', 'enc_hidden_3', 'embedding', # Encoder layer names
'dec_hidden_1', 'dec_hidden_2', 'dec_hidden_3', 'output'] # Decoder layer names
activations_soft = [tf.nn.relu, tf.nn.relu, tf.nn.relu, tf.nn.softmax, # Encoder layer activations # Uses softmax in last enocder layer
tf.nn.relu, tf.nn.relu, tf.nn.relu, None]
#data_df['label'].value_counts()<file_sep># Import packages
import tensorflow as tf
import pandas as pd
import numpy as np
import os
os.chdir('C://Users//vnino//Desktop//CE888 - Assignment 2//Python code//HAR//data')
import random
# Fetch the dataset
train_df= pd.read_csv("train.csv")
test_df= pd.read_csv("test.csv")
data_df=pd.concat([train_df,test_df], ignore_index=True)
#Defining labels and features
target=data_df['Activity']
data=np.asarray(data_df.iloc[:,0:560])
n_samples= data.shape[0]
n_clusters=6
# Get the split between training/test set and validation set
random.seed(0)
test_indices = random.sample(range(0, 10299), 2060)
validation_indices = [x for x in range(0, 10299) if x not in test_indices]
# Auto-encoder architecture
input_size = data.shape[1]
hidden_1_size = 500
hidden_2_size = 500
hidden_3_size = 2000
embedding_size = n_clusters
dimensions = [hidden_1_size, hidden_2_size, hidden_3_size, embedding_size, # Encoder layer dimensions
hidden_3_size, hidden_2_size, hidden_1_size, input_size] # Decoder layer dimensions
activations = [tf.nn.relu, tf.nn.relu, tf.nn.relu, None, # Encoder layer activations # None uses linear act.
tf.nn.relu, tf.nn.relu, tf.nn.relu, None] # Decoder layer activations # None uses linear act.
names = ['enc_hidden_1', 'enc_hidden_2', 'enc_hidden_3', 'embedding', # Encoder layer names
'dec_hidden_1', 'dec_hidden_2', 'dec_hidden_3', 'output'] # Decoder layer names
activations_soft = [tf.nn.relu, tf.nn.relu, tf.nn.relu, tf.nn.softmax, # Encoder layer activations # Uses softmax in last enocder layer
tf.nn.relu, tf.nn.relu, tf.nn.relu, None]
#data_df['ActivityName'].value_counts()
<file_sep>INSTRUCTIONS FOR RUNNING THE CLUSTERING
-----------------------------------------------------------------------
1. SETTING PATH FOR INPUT DATA:
The input data sets are stored in the input folders:
- digits
- HAR
- mushrooms
Before running the algorithms, you will need to edit the specs files
(HAR_specs.py, mushrooms_specs.py) inside these folders to change the
path of the text files. The text files are stored in the same folders
as the specs files.
2. RUNNING CLUTERING:
Each clustering technique is programmed in a separate .py file:
- kmeans.py
- autoencoder.py
- autoencodersoftmax.py
- deepkmeans.py
You can run each of these programs on your command windows or using
a python IDE. For each run the program will ask to insert the path
where the specs files are stored and to specify the dataset you want
to process.
3. OUTPUT:
The run has 2 files as output written in the folder "results" that can
be found inside of each the input folders. The files are: a .txt file
containing the results (performance scores) of the run and a .png file
containing the confusion matrix for the clusters obtained.
The folders already contain the results of running the codes. Re-running
it, will over write the files.
ADDITIONAL FILES
-----------------------------------------------------------------------
Inside the input folders, you can also found the code used in assignment 1
to make the previous EDA of the three data sets.
<file_sep>import pandas as pd
import numpy as np
def power(sample1, sample2, reps, perm_iterations, alpha):
tobs=np.mean(sample1)-np.mean(sample2)
m=0
for r in range(reps):
n=0
for i in range(perm_iterations):
join_sample=np.append(sample1, sample2)
resample1=np.random.choice(join_sample, size=sample1.shape[0], replace=True)
resample2=np.random.choice(join_sample, size=sample2.shape[0], replace=True)
if (np.mean(resample1)-np.mean(resample2)) > tobs:
n+=1
p_value=n/perm_iterations
print(p_value)
if p_value<alpha:
m+=1
return(m/reps)
sample2=np.arange(0,1000,1)
sample1=np.arange(0,1000,1)
power(sample1,sample2,100,100,0.05)
np.mean(sample1)-np.mean(sample2)
join_sample=np.append(sample1, sample2)
resample1=np.random.choice(join_sample, size=sample1.shape[0], replace=True)
resample2=np.random.choice(join_sample, size=sample2.shape[0], replace=True)
np.mean(resample1)-np.mean(resample2)
<file_sep># LAB 2
## **Exercise 1 - Plotting**
The code for this exercise can be found in the folder Exercise 1 - Plotting, in the file vehicles.py.
First, we create an histogram on the Current Fleet and compute the main descriptive statistics:

Mean: 20.144578
Median: 19.000000
Var: 40.983113
std: 6.401805
MAD: 4.000000
Second, we create an histogram on the New Fleet and compute the main descriptive statistics:

Mean: 30.481013
Median: 32.000000
Var: 36.831918
std: 6.068931
MAD: 4.000000
A scatterplot is also computed:

## **Exercise 2 - Bootstrap**
The code for this exercise can be found in the folder Exercise 2 - Bootstrap, in the file bootstrap.py.
First, the function boostrap() is created.
Then this is used to compare the mean values of the MPG for each Fleet at a 95% CI.
The results of this analysis are:
Current Fleet Mean: 20.161739
Current Fleet Lower: 19.321185
Current Fleet Upper: 20.960040
New Fleet Mean: 30.481823
New Fleet Lower: 29.176899
New Fleet Upper: 31.887025
<file_sep># For creating this code the following sources were used:
# 1. Building autoencoders in Keras. Source: https://blog.keras.io/building-autoencoders-in-keras.html
# 2. Implementation of "Deep k-Means: Jointly Clustering with k-Means and Learning Representations" by <NAME>, <NAME>, and <NAME>. (https://github.com/MaziarMF/deep-k-means)
# 3. In Depth: k-Means Clustering (https://jakevdp.github.io/PythonDataScienceHandbook/05.11-k-means.html)
# IMPORTS PACKAGES ############################################################################################################################
###############################################################################################################################################
import os
import math
import numpy as np
import tensorflow as tf
import sklearn
from sklearn.metrics import silhouette_score, accuracy_score, completeness_score, homogeneity_score
from sklearn.cluster import KMeans
from scipy.stats import mode
import seaborn as sns
sns.set(font_scale=3)
import matplotlib.pyplot as plt
TF_FLOAT_TYPE = tf.float32
from keras.optimizers import SGD, Adam
from keras.layers import Dense, Input
from keras.models import Model
from keras.backend import clear_session
# FUNCTIONS DEFINITION ########################################################################################################################
###############################################################################################################################################
def cluster_acc(y_true, y_pred, n_clusters):
labels = np.zeros_like(y_pred)
for i in range(n_clusters):
mask = (y_pred == i)
labels[mask] = mode(y_true[mask])[0]
if y_true is not None:
acc = np.round(accuracy_score(y_true, labels), 5)
return acc
def save_confusion_matrix(y_true, y_pred, n_clusters, name):
labels = np.zeros_like(y_pred)
for i in range(n_clusters):
mask = (y_pred == i)
labels[mask] = mode(y_true[mask])[0]
confusion_matrix = sklearn.metrics.confusion_matrix(y_true, labels)
plt.figure(figsize=(16, 14))
sns.heatmap(confusion_matrix, annot=True, fmt="d", annot_kws={"size": 20});
plt.title("Confusion matrix", fontsize=30)
plt.ylabel('True label', fontsize=25)
plt.xlabel('Clustering label', fontsize=25)
plt.savefig('./results/'+ name + '.png')
def next_batch(num, data):
indices = np.arange(0, data.shape[0])
np.random.shuffle(indices)
indices = indices[:num]
batch_data = np.asarray([data[i, :] for i in indices])
return indices, batch_data
def create_autoencoder(dims):
input_layer = Input(shape=(dims[0],), name='input')
encoded = Dense(dims[1], activation='relu', name='enc_0')(input_layer)
encoded = Dense(dims[2], activation='relu', name='enc_1')(encoded)
encoded = Dense(dims[3], activation='relu', name='enc_2')(encoded)
encoded = Dense(dims[4], activation='softmax', name='enc_3')(encoded) ##, activation='softmax'
decoded = Dense(dims[3], activation='relu', name='dec_3')(encoded)
decoded = Dense(dims[2], activation='relu', name='dec_2')(decoded)
decoded = Dense(dims[1], activation='relu', name='dec_1')(decoded)
decoded = Dense(dims[0], activation='sigmoid', name='dec_0')(decoded) # activation='sigmoid'
return Model(input_layer, outputs=decoded, name='AE'), Model(input_layer, outputs=encoded, name='encoder')
# MAIN PROGRAM ################################################################################################################################
###############################################################################################################################################
# This program executes DEEP K-means for a chosen dataset.
# It runs the algorithm 10 times, each with different seed.
# It computes the final perfomance metrics selecting the iteration with the
# maximum Accuracy. The performance metrics are printed in the screen as
# they are computed. Also, a txt file is generated with these results
# and 2 png file with the confusion matrices are created.
if __name__=='__main__':
# STEP 0: Setting the directory -------------------------------------------------------------------------------------------------------------
directory = input('Please enter the directory where you have the datasets: ')
os.chdir(directory)
# STEP 1 Importing dataset ------------------------------------------------------------------------------------------------------------------
dataset = input('Select the dataset for which you want to run DEEP K-Means, digits/HAR/mushrooms [d/h/m]: ')
if dataset=='d':
import digits_specs as specs
elif dataset=='h':
import HAR_specs as specs
elif dataset=='m':
import mushrooms_specs as specs
else:
print('Enter a valid dataset [d/h/m]: ')
# STEP 2: Running DEEP K-Means ------------------------------------------------------------------------------------------------------------------
# 2.1. Setting initial parameters------------------------------------------------------------------------------------------------------------
n_train_epochs = 50
batch_size = 256 # Size of the mini-batches used in the stochastic optimizer
seeded = True # Specify if runs are seeded
seeds = [8905, 9129, 291, 4012, 1256, 6819, 4678, 6971, 1362, 575] # Use a fixed seed for this run, as defined in the seed list
# There is randomness in centroids initialization and mini-batch selection
n_runs = 10
dims = [specs.input_size, 500, 500, 2000, specs.embedding_size]
target = specs.target
data = specs.data
dict_acc = dict()
dict_sc = dict()
dict_cs = dict()
dict_hs = dict()
dict_clusterassign= dict()
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.05)
config = tf.ConfigProto(gpu_options=gpu_options)
# 2.2. Running k-means and creating the output files-----------------------------------------------------------------------------------------
if os.path.exists('./results/AEsoft_results.txt'):
os.remove('./results/AEsoft_results.txt') # Removes the text file if exists
with open('./results/AEsoft_results.txt', 'x') as f:
# 2.2.1. Running k-means n_run times-------------------------------------------------------------------------------------------------------
for run in range(n_runs):
clear_session()
if seeded:
tf.reset_default_graph()
tf.set_random_seed(seeds[run])
np.random.seed(seeds[run])
print("Run", run)
f.write("RUN "+ str(run) +'\n'+'\n')
autoencoder, encoder = create_autoencoder(dims)
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
#autoencoder.compile(optimizer='adam', loss='kld')
autoencoder.fit(data, data, batch_size=batch_size, epochs=n_train_epochs)
# Second, run k-means++ on the trained embeddings
print("Running k-means on the learned embeddings...")
f.write("1. K-MEANS ON THE EMBEDDED FEATURES"+'\n'+'\n')
#kmeans_model = KMeans(n_clusters=specs.n_clusters, init="k-means++").fit(embeddings) # n_init=10 initial centroids
kmeans_model = KMeans(n_clusters=specs.n_clusters, init="k-means++").fit(encoder.predict(data))
# Evaluate the clustering performance using the ground-truth labels
sc = silhouette_score(data, kmeans_model.labels_)
print("SC", sc)
f.write("SC: "+ str(sc) +'\n')
acc = cluster_acc(target, kmeans_model.labels_, specs.n_clusters)
print("ACC", acc)
f.write("ACC: "+ str(acc) +'\n')
cs = completeness_score(target, kmeans_model.labels_)
print("CS", cs)
f.write("CS: "+ str(cs) +'\n')
hs = homogeneity_score(target, kmeans_model.labels_)
print("HS", hs)
f.write("HS: "+ str(hs) +'\n')
# Record the clustering performance for the run
dict_acc.update({run : acc})
dict_sc.update({run : sc})
dict_cs.update({run : cs})
dict_hs.update({run : hs})
dict_clusterassign.update({run : kmeans_model.labels_ })
f.write('\n'+'-------------------------------------------------------------'+'\n')
max_acc = max(dict_acc, key=dict_acc.get)
print('Iteration with maximum ACC: '+ str(max_acc))
print("ACC: {:.3f}".format(dict_acc[max_acc]))
print("SC: {:.3f}".format(dict_sc[max_acc]))
print("CS: {:.3f}".format(dict_cs[max_acc]))
print("HS: {:.3f}".format(dict_hs[max_acc]))
f.write('Run with maximum ACC: '+ str(max_acc) +'\n')
f.write("ACC: {:.3f}".format(dict_acc[max_acc]) +'\n')
f.write("SC: {:.3f}".format(dict_sc[max_acc]) +'\n')
f.write("CS: {:.3f}".format(dict_cs[max_acc]) +'\n')
f.write("HS: {:.3f}".format(dict_hs[max_acc]) +'\n')
save_confusion_matrix(target, dict_clusterassign[max_acc], specs.n_clusters, 'AEsoft_CM')
<file_sep># For creating this code the following sources were used:
# 1. Implementation of "Deep k-Means: Jointly Clustering with k-Means and Learning Representations" by <NAME>, <NAME>, and <NAME>. (https://github.com/MaziarMF/deep-k-means)
# 2. In Depth: k-Means Clustering (https://jakevdp.github.io/PythonDataScienceHandbook/05.11-k-means.html)
# IMPORTS PACKAGES ############################################################################################################################
###############################################################################################################################################
import os
import math
import numpy as np
import tensorflow as tf
import sklearn
from sklearn.metrics import silhouette_score, accuracy_score, completeness_score, homogeneity_score
from sklearn.cluster import KMeans
from scipy.stats import mode
import seaborn as sns
sns.set(font_scale=3)
import matplotlib.pyplot as plt
TF_FLOAT_TYPE = tf.float32
# FUNCTIONS DEFINITION ########################################################################################################################
###############################################################################################################################################
def cluster_acc(y_true, y_pred, n_clusters):
labels = np.zeros_like(y_pred)
for i in range(n_clusters):
mask = (y_pred == i)
labels[mask] = mode(y_true[mask])[0]
if y_true is not None:
acc = np.round(accuracy_score(y_true, labels), 5)
return acc
def save_confusion_matrix(y_true, y_pred, n_clusters, name):
labels = np.zeros_like(y_pred)
for i in range(n_clusters):
mask = (y_pred == i)
labels[mask] = mode(y_true[mask])[0]
confusion_matrix = sklearn.metrics.confusion_matrix(y_true, labels)
plt.figure(figsize=(16, 14))
sns.heatmap(confusion_matrix, annot=True, fmt="d", annot_kws={"size": 20});
plt.title("Confusion matrix", fontsize=30)
plt.ylabel('True label', fontsize=25)
plt.xlabel('Clustering label', fontsize=25)
plt.savefig('./results/'+ name + '.png')
def next_batch(num, data):
indices = np.arange(0, data.shape[0])
np.random.shuffle(indices)
indices = indices[:num]
batch_data = np.asarray([data[i, :] for i in indices])
return indices, batch_data
def fc_layers(input, specs):
[dimensions, activations, names] = specs
for dimension, activation, name in zip(dimensions, activations, names):
input = tf.layers.dense(inputs=input, units=dimension, activation=activation, name=name, reuse=False)
return input
def autoencoder(input, specs):
[dimensions, activations, names] = specs
mid_ind = int(len(dimensions)/2)
# Encoder
embedding = fc_layers(input, [dimensions[:mid_ind], activations[:mid_ind], names[:mid_ind]])
# Decoder
output = fc_layers(embedding, [dimensions[mid_ind:], activations[mid_ind:], names[mid_ind:]])
return embedding, output
def f_func(x, y):
return tf.reduce_sum(tf.square(x - y), axis=1)
def g_func(x, y):
return tf.reduce_sum(tf.square(x - y), axis=1)
# COMPUTATION GRAPH FOR DEEP K-MEANS ##########################################################################################################
###############################################################################################################################################
class DkmCompGraph(object):
def __init__(self, ae_specs, n_clusters, val_lambda):
input_size = ae_specs[0][-1]
embedding_size = ae_specs[0][int((len(ae_specs[0])-1)/2)]
# Placeholder tensor for input data
self.input = tf.placeholder(dtype=TF_FLOAT_TYPE, shape=(None, input_size))
# Auto-encoder loss computations
self.embedding, self.output = autoencoder(self.input, ae_specs) # Get the auto-encoder's embedding and output
rec_error = g_func(self.input, self.output) # Reconstruction error based on distance g
# k-Means loss computations
## Tensor for cluster representatives
minval_rep, maxval_rep = -1, 1 # Clusters rep (centroids) are initialized randomly using U(-1,1)
self.cluster_rep = tf.Variable(tf.random_uniform([n_clusters, embedding_size],
minval=minval_rep, maxval=maxval_rep,
dtype=TF_FLOAT_TYPE), name='cluster_rep', dtype=TF_FLOAT_TYPE)
## First, compute the distance f between the embedding and each cluster representative
list_dist = []
for i in range(0, n_clusters):
dist = f_func(self.embedding, tf.reshape(self.cluster_rep[i, :], (1, embedding_size)))
list_dist.append(dist)
self.stack_dist = tf.stack(list_dist)
## Second, find the minimum squared distance for softmax normalization
min_dist = tf.reduce_min(list_dist, axis=0)
## Third, compute exponentials shifted with min_dist to avoid underflow (0/0) issues in softmaxes
self.alpha = tf.placeholder(dtype=TF_FLOAT_TYPE, shape=()) # Placeholder tensor for alpha
list_exp = []
for i in range(n_clusters):
exp = tf.exp(-self.alpha * (self.stack_dist[i] - min_dist))
list_exp.append(exp)
stack_exp = tf.stack(list_exp)
sum_exponentials = tf.reduce_sum(stack_exp, axis=0)
## Fourth, compute softmaxes and the embedding/representative distances weighted by softmax
list_softmax = []
list_weighted_dist = []
for j in range(n_clusters):
softmax = stack_exp[j] / sum_exponentials
weighted_dist = self.stack_dist[j] * softmax
list_softmax.append(softmax)
list_weighted_dist.append(weighted_dist)
stack_weighted_dist = tf.stack(list_weighted_dist)
# Compute the full loss combining the reconstruction error and k-means term
self.ae_loss = tf.reduce_mean(rec_error)
self.kmeans_loss = tf.reduce_mean(tf.reduce_sum(stack_weighted_dist, axis=0))
self.loss = self.ae_loss + val_lambda * self.kmeans_loss
# The optimizer is defined to minimize this loss
optimizer = tf.train.AdamOptimizer()
#optimizer = tf.train.AdadeltaOptimizer()
self.pretrain_op = optimizer.minimize(self.ae_loss) # Pretrain the autoencoder before starting DKM
self.train_op = optimizer.minimize(self.loss) # Train the whole DKM model
# MAIN PROGRAM ################################################################################################################################
###############################################################################################################################################
# This program executes DEEP K-means for a chosen dataset.
# It runs the algorithm 10 times, each with different seed.
# It computes the final perfomance metrics selecting the iteration with the
# maximum Accuracy. The performance metrics are printed in the screen as
# they are computed. Also, a txt file is generated with these results
# and 2 png file with the confusion matrices are created.
if __name__=='__main__':
# STEP 0: Setting the directory -------------------------------------------------------------------------------------------------------------
directory = input('Please enter the directory where you have the datasets: ')
os.chdir(directory)
# STEP 1 Importing dataset ------------------------------------------------------------------------------------------------------------------
dataset = input('Select the dataset for which you want to run DEEP K-Means, digits/HAR/mushrooms [d/h/m]: ')
if dataset=='d':
import digits_specs as specs
elif dataset=='h':
import HAR_specs as specs
elif dataset=='m':
import mushrooms_specs as specs
else:
print('Enter a valid dataset [d/h/m]: ')
# STEP 2: Running DEEP K-Means ------------------------------------------------------------------------------------------------------------------
# 2.1. Setting initial parameters------------------------------------------------------------------------------------------------------------
n_pretrain_epochs = 50
n_finetuning_epochs = 5
lambda_ = 0.1 # Optimal lambda tested on USPS (similar database)
batch_size = 256 # Size of the mini-batches used in the stochastic optimizer
n_batches = int(math.ceil(specs.n_samples / batch_size)) # Number of mini-batches
seeded = True # Specify if runs are seeded
max_n = 20 # Number of alpha values to consider (constant values are used here), 100 epochs in total 20*5
alphas = 1000*np.ones(max_n, dtype=float) # alpha is constant, all epochs take constant alpha of 1000
seeds = [8905, 9129, 291, 4012, 1256, 6819, 4678, 6971, 1362, 575] # Use a fixed seed for this run, as defined in the seed list
# There is randomness in centroids initialization and mini-batch selection
n_runs = 10
target = specs.target
data = specs.data
dict_acc = dict()
dict_sc = dict()
dict_cs = dict()
dict_hs = dict()
dict_clusterassign= dict()
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.05)
config = tf.ConfigProto(gpu_options=gpu_options)
# 2.2. Running k-means and creating the output files-----------------------------------------------------------------------------------------
if os.path.exists('./results/DKM_results.txt'):
os.remove('./results/DKM_results.txt') # Removes the text file if exists
with open('./results/DKM_results.txt', 'x') as f:
# 2.2.1. Running k-means n_run times-------------------------------------------------------------------------------------------------------
for run in range(n_runs):
if seeded:
tf.reset_default_graph()
tf.set_random_seed(seeds[run])
np.random.seed(seeds[run])
print("Run", run)
f.write("RUN "+ str(run) +'\n'+'\n')
# Define the computation graph for DKM
# We need a computation graph that performs the simultaneous minimization of clusters and low-dim representation, so we have to program a specific low-level graph
cg = DkmCompGraph([specs.dimensions, specs.activations, specs.names], specs.n_clusters, lambda_)
# DkmCompGraph([[500, 500, 2000, 10,
# 2000, 500, 500, 64],
# [tf.nn.relu, tf.nn.relu, tf.nn.relu, None,
# tf.nn.relu, tf.nn.relu, tf.nn.relu, None],
# ['enc_hidden_1', 'enc_hidden_2', 'enc_hidden_3', 'embedding',
# 'dec_hidden_1', 'dec_hidden_2', 'dec_hidden_3', 'output'] ],
# 10, 1.0)
# Run the computation graph
with tf.Session(config=config) as sess:
# Initialization
init = tf.global_variables_initializer()
sess.run(init)
# Variables to save tensor content
distances = np.zeros((specs.n_clusters, specs.n_samples))
print("Starting autoencoder pretraining...")
# Variables to save pretraining tensor content
embeddings = np.zeros((specs.n_samples, specs.embedding_size), dtype=float)
# First, pretrain the autoencoder
## Loop over epochs
for epoch in range(n_pretrain_epochs):
print("Pretraining step: epoch {}".format(epoch))
# Loop over the samples
for _ in range(n_batches):
# Fetch a random data batch of the specified size
indices, data_batch = next_batch(batch_size, data)
# Run the computation graph until pretrain_op (only on autoencoder) on the data batch
_, embedding_, ae_loss_ = sess.run((cg.pretrain_op, cg.embedding, cg.ae_loss),
feed_dict={cg.input: data_batch})
# Save the embeddings for batch samples
for j in range(len(indices)):
embeddings[indices[j], :] = embedding_[j, :]
#print("ae_loss_:", float(ae_loss_))
# Second, run k-means++ on the pretrained embeddings
print("Running k-means on the learned embeddings...")
f.write("1. K-MEANS ON THE PRETRAINED FEATURES"+'\n'+'\n')
kmeans_model = KMeans(n_clusters=specs.n_clusters, init="k-means++").fit(embeddings) # n_init=10 initial centroids
# Evaluate the clustering performance using the ground-truth labels
sc = silhouette_score(data, kmeans_model.labels_)
print("SC", sc)
f.write("SC: "+ str(sc) +'\n')
acc = cluster_acc(target, kmeans_model.labels_, specs.n_clusters)
print("ACC", acc)
f.write("ACC: "+ str(acc) +'\n')
cs = completeness_score(target, kmeans_model.labels_)
print("CS", cs)
f.write("CS: "+ str(cs) +'\n')
hs = homogeneity_score(target, kmeans_model.labels_)
print("HS", hs)
f.write("HS: "+ str(hs) +'\n')
# The cluster centers are used to initialize the cluster representatives in DKM
sess.run(tf.assign(cg.cluster_rep, kmeans_model.cluster_centers_))
# Train the full DKM model
if (len(alphas) > 0):
print("Starting DKM training...")
f.write('\n')
f.write("2. DEEP K-MEANS TRAINING"+'\n'+'\n')
## Loop over alpha (inverse temperature), from small to large values
for k in range(len(alphas)):
print("Training step: alpha[{}]: {}".format(k, alphas[k]))
f.write("TRAINING STEP: {}".format(k)+'\n'+'\n')
# Loop over epochs per alpha
for _ in range(n_finetuning_epochs):
# Loop over the samples
for _ in range(n_batches):
#print("Training step: alpha[{}], epoch {}".format(k, i))
# Fetch a random data batch of the specified size
indices, data_batch = next_batch(batch_size, data)
#print(tf.trainable_variables())
#current_batch_size = np.shape(data_batch)[0] # Can be different from batch_size for unequal splits
# Run the computation graph on the data batch
_, loss_, stack_dist_, cluster_rep_, ae_loss_, kmeans_loss_ =\
sess.run((cg.train_op, cg.loss, cg.stack_dist, cg.cluster_rep, cg.ae_loss, cg.kmeans_loss),
feed_dict={cg.input: data_batch, cg.alpha: alphas[k]})
# Save the distances for batch samples
for j in range(len(indices)):
distances[:, indices[j]] = stack_dist_[:, j]
# Evaluate the clustering performance every print_val alpha and for last alpha
print_val = 1
if k % print_val == 0 or k == max_n - 1:
print("loss:", loss_)
f.write("Total loss: "+ str(loss_) +'\n')
print("ae loss:", ae_loss_)
f.write("AE loss: "+ str(ae_loss_) +'\n')
print("kmeans loss:", kmeans_loss_)
f.write("KMeans loss: "+ str(kmeans_loss_) +'\n')
# Infer cluster assignments for all samples
cluster_assign = np.zeros((specs.n_samples), dtype=float)
for i in range(specs.n_samples):
index_closest_cluster = np.argmin(distances[:, i])
cluster_assign[i] = index_closest_cluster
cluster_assign = cluster_assign.astype(np.int64)
# Evaluate the clustering performance using the ground-truth labels
sc = silhouette_score(data, kmeans_model.labels_)
print("SC", sc)
f.write("SC: "+ str(sc) +'\n')
acc = cluster_acc(target, kmeans_model.labels_, specs.n_clusters)
print("ACC", acc)
f.write("ACC: "+ str(acc) +'\n')
cs = completeness_score(target, kmeans_model.labels_)
print("CS", cs)
f.write("CS: "+ str(cs) +'\n')
hs = homogeneity_score(target, kmeans_model.labels_)
print("HS", hs)
f.write("HS: "+ str(hs) +'\n')
f.write('\n')
# Record the clustering performance for the run
dict_acc.update({run : acc})
dict_sc.update({run : sc})
dict_cs.update({run : cs})
dict_hs.update({run : hs})
dict_clusterassign.update({run : kmeans_model.labels_ })
f.write('\n'+'-------------------------------------------------------------'+'\n')
max_acc = max(dict_acc, key=dict_acc.get)
print('Iteration with maximum ACC: '+ str(max_acc))
print("ACC: {:.3f}".format(dict_acc[max_acc]))
print("SC: {:.3f}".format(dict_sc[max_acc]))
print("CS: {:.3f}".format(dict_cs[max_acc]))
print("HS: {:.3f}".format(dict_hs[max_acc]))
f.write('Run with maximum ACC: '+ str(max_acc) +'\n')
f.write("ACC: {:.3f}".format(dict_acc[max_acc]) +'\n')
f.write("SC: {:.3f}".format(dict_sc[max_acc]) +'\n')
f.write("CS: {:.3f}".format(dict_cs[max_acc]) +'\n')
f.write("HS: {:.3f}".format(dict_hs[max_acc]) +'\n')
save_confusion_matrix(target, dict_clusterassign[max_acc], specs.n_clusters, 'DKM_CM')
<file_sep>import pandas as pd
import matplotlib.pyplot as plt
import os
os.chdir('C://Users//vnino//Desktop//CE888 - Assignment 2//Python code//mushrooms')
names=['label', 'cap_shape', 'cap_surface',
'cap_color', 'bruises', 'odor',
'gill_attachment', 'gill_spacing', 'gill_size',
'gill_color', 'stalk_shape', 'stalk_root',
'stalk_surface_above', 'stalk_surface_below',
'stalk_color_above', 'stalk_color_below', 'veil_type',
'veil_color', 'ring_number', 'ring_type',
'spore_print_color', 'population','habitat']
df = pd.read_csv("agaricus-lepiota.csv", names=names)
#Checking shape and head of the data
df.shape
df.head()
# Descriptive stats
df.describe()
#Distribution of categories of the features
for var in df.columns:
print(df[var].value_counts()/8124)
# Plot of classes distribution
plot1=df['label'].value_counts().plot(kind='barh', color='0.75', title='Number of instances by edibility label', figsize=(7,3));
for i, v in enumerate(df['label'].value_counts()):
plot1.text(v + 2, i-0.15 , str(v), fontsize='large')
plot1<file_sep># Import packages
import os
import tensorflow as tf
from sklearn import datasets
os.chdir('C://Users//vnino//Desktop//CE888 - Assignment 2//Python code//digits')
import random
# Fetch the dataset
dataset = datasets.load_digits()
data = dataset.data
target = dataset.target
n_samples = data.shape[0] # Number of obs in the dataset
n_clusters = 10 # Number of clusters to obtain
# Pre-process the dataset
data = data / 16.0 # Normalize the levels of grey between 0 and 1
# Get the split between training/test set and validation set
random.seed(0)
test_indices = random.sample(range(0, 1797), 360)
validation_indices = [x for x in range(0, 1797) if x not in test_indices]
# Auto-encoder architecture
input_size = data.shape[1]
hidden_1_size = 500
hidden_2_size = 500
hidden_3_size = 2000
embedding_size = n_clusters
dimensions = [hidden_1_size, hidden_2_size, hidden_3_size, embedding_size, # Encoder layer dimensions
hidden_3_size, hidden_2_size, hidden_1_size, input_size] # Decoder layer dimensions
activations = [tf.nn.relu, tf.nn.relu, tf.nn.relu, None, # Encoder layer activations # None is linear activation
tf.nn.relu, tf.nn.relu, tf.nn.relu, None] # Decoder layer activations # None is linear activation
names = ['enc_hidden_1', 'enc_hidden_2', 'enc_hidden_3', 'embedding', # Encoder layer names
'dec_hidden_1', 'dec_hidden_2', 'dec_hidden_3', 'output'] # Decoder layer names
activations_soft = [tf.nn.relu, tf.nn.relu, tf.nn.relu, tf.nn.softmax, # Encoder layer activations # Uses softmax in last enocder layer
tf.nn.relu, tf.nn.relu, tf.nn.relu, None]<file_sep>import matplotlib
matplotlib.use('Agg')
import pandas as pd
import seaborn as sns
import numpy as np
## PART 1: Creating the boostrap function
def boostrap(sample, sample_size, iterations,ciparam):
sample_matrix=np.zeros((iterations,sample_size))
data_mean_mx=np.zeros(iterations)
for i in range(iterations):
sample_matrix[i, :]=np.random.choice(sample, size=sample_size, replace=True)
data_mean_mx[i]=np.mean(sample_matrix[i, :])
lower=np.percentile(data_mean_mx,ciparam/2)
upper=np.percentile(data_mean_mx,100-ciparam/2)
data_mean=np.mean(data_mean_mx)
return data_mean, lower, upper
## PART 2 Applying the boostrap function on the vehicles data
vehicles_df = pd.read_csv('./vehicles.csv')
vehicles_df.columns=['Currentfleet','Newfleet']
vehicles_df2=vehicles_df[vehicles_df.Newfleet.notnull()]
current_fleet_data = vehicles_df.values.T[0]
new_fleet_data = vehicles_df2.values.T[1]
cf=boostrap(current_fleet_data, current_fleet_data.shape[0],1000,5)
print(("Current Fleet Mean: %f")%(cf[0]))
print(("Current Fleet Lower: %f")%(cf[1]))
print(("Current Fleet Upper: %f")%(cf[2]))
nf=boostrap(new_fleet_data, new_fleet_data.shape[0],1000,5)
print(("New Fleet Mean: %f")%(nf[0]))
print(("New Fleet Lower: %f")%(nf[1]))
print(("New Fleet Upper: %f")%(nf[2]))
## The New fleet has a higher MPG mean, the 95% CI for the mean of the new fleet
# is between 29.1 MPG and 31.7 MPG, while for the Current Fleet it is between 19.4 and 20.9.
## Plots on salaries using boostrap iterations
if __name__ == "__main__":
df = pd.read_csv('./salaries.csv')
data = df.values.T[1]
boots = []
for i in range(100, 100000, 1000):
boot = boostrap(data, data.shape[0], i, 5)
boots.append([i, boot[0], "mean"])
boots.append([i, boot[1], "lower"])
boots.append([i, boot[2], "upper"])
df_boot = pd.DataFrame(boots, columns=['Boostrap Iterations', 'Mean', "Value"])
sns_plot = sns.lmplot(df_boot.columns[0], df_boot.columns[1], data=df_boot, fit_reg=False, hue="Value")
sns_plot.axes[0, 0].set_ylim(0,)
sns_plot.axes[0, 0].set_xlim(0, 100000)
sns_plot.savefig("bootstrap_confidence.png", bbox_inches='tight')
sns_plot.savefig("bootstrap_confidence.pdf", bbox_inches='tight')
#print ("Mean: %f")%(np.mean(data))
#print ("Var: %f")%(np.var(data))
<file_sep>#Source: https://github.com/srvds/Human-Activity-Recognition/blob/master/HAR_EDA.ipynb
# Import packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import os
os.chdir('C://Users//vnino//Desktop//CE888 - Assignment 2//Python code//HAR')
# Fetch the dataset
train_df= pd.read_csv("train.csv")
test_df= pd.read_csv("test.csv")
data_df=pd.concat([train_df,test_df], ignore_index=True)
#Defining labels and features
target=data_df['Activity']
data=np.asarray(data_df.iloc[:,0:560])
n_samples= data.shape[0]
#Distribution of the mean of Linear Body Acceleration Euclidean Norm (tBodyAccMagmean)
sns.set_palette("Set1", desat=0.80)
facetgrid = sns.FacetGrid(data_df, hue='ActivityName', size=6,aspect=2)
facetgrid.map(sns.distplot,'tBodyAccMagmean', hist=False)\
.add_legend()
plt.annotate("Stationary Activities", xy=(-0.956,17), xytext=(-0.9, 23), size=20,\
va='center', ha='left',\
arrowprops=dict(arrowstyle="simple",connectionstyle="arc3,rad=0.1"))
plt.annotate("Moving Activities", xy=(0,3), xytext=(0.2, 9), size=20,\
va='center', ha='left',\
arrowprops=dict(arrowstyle="simple",connectionstyle="arc3,rad=0.1"))
plt.show()
#Boxplot of the mean of Linear Body Acceleration Euclidean Norm (tBodyAccMagmean)
sns.boxplot(x='ActivityName', y='tBodyAccMagmean', data = data_df, showfliers=False)
plt.xticks(rotation = 40)
plt.axhline(y=-0.22, xmin=0.1, xmax=0.8, dashes=(5,3), c='m')
plt.xticks(rotation=90)
plt.show()
#Boxplot of the mean of Angle Y-Gravity (tBodyAccMagmean)
sns.boxplot(x='ActivityName', y='angleYgravityMean', data = data_df, showfliers=False)
plt.xticks(rotation = 40)
plt.axhline(y=-0.22, xmin=0.1, xmax=0.8, dashes=(5,3), c='m')
plt.xticks(rotation=90)
plt.show()<file_sep>from sklearn import datasets
import pandas as pd
import matplotlib.pyplot as plt
digits = datasets.load_digits()
print(digits.data.shape)
print(digits.data)
print(digits.target)
digits_df=pd.DataFrame(digits.data)
digits_df.describe()
diglab_df=pd.DataFrame(digits.target)
diglab_df.describe()
# Count of the classes
pd.DataFrame(target)[0].value_counts()
# Plot of classes distribution
plot1=diglab_df[0].value_counts().plot(kind='barh', color='0.75', title='Number of instances by digit', figsize=(7,3));
values=diglab_df[0].value_counts()/1797
values_df=values.to_frame()
values_df['Count']= pd.Series(["{0:.2f}%".format(val * 100) for val in values_df[0]], index = values_df.index)
for i, v in enumerate(diglab_df[0].value_counts()):
plot1.text(v + 1, i-0.25 , str(v), fontsize='x-small')
plot1
# Plot of the images of the digits
plt.matshow(digits.images[9], cmap='binary')
<file_sep># For creating this code the following sources were used:
# 1. Implementation of "Deep k-Means: Jointly Clustering with k-Means and Learning Representations" by <NAME>, <NAME>, and <NAME>. (https://github.com/MaziarMF/deep-k-means)
# 2. In Depth: k-Means Clustering (https://jakevdp.github.io/PythonDataScienceHandbook/05.11-k-means.html)
# IMPORTS PACKAGES ############################################################################################################################
###############################################################################################################################################
import os
import numpy as np
import sklearn
from sklearn.metrics import silhouette_score, accuracy_score, completeness_score, homogeneity_score
from sklearn.cluster import KMeans
from scipy.stats import mode
import seaborn as sns
sns.set(font_scale=3)
import matplotlib.pyplot as plt
# FUNCTIONS DEFINITION ########################################################################################################################
###############################################################################################################################################
def cluster_acc(y_true, y_pred, n_clusters):
labels = np.zeros_like(y_pred)
for i in range(n_clusters):
mask = (y_pred == i)
labels[mask] = mode(y_true[mask])[0]
if y_true is not None:
acc = np.round(accuracy_score(y_true, labels), 5)
return acc
def save_confusion_matrix(y_true, y_pred, n_clusters, name):
labels = np.zeros_like(y_pred)
for i in range(n_clusters):
mask = (y_pred == i)
labels[mask] = mode(y_true[mask])[0]
confusion_matrix = sklearn.metrics.confusion_matrix(y_true, labels)
plt.figure(figsize=(16, 14))
sns.heatmap(confusion_matrix, annot=True, fmt="d", annot_kws={"size": 20});
plt.title("Confusion matrix", fontsize=30)
plt.ylabel('True label', fontsize=25)
plt.xlabel('Clustering label', fontsize=25)
plt.savefig('./results/'+ name + '.png')
# MAIN PROGRAM ################################################################################################################################
###############################################################################################################################################
# This program executes the traditional K-means for a chosen dataset.
# It runs the algorithm 10 times, each with different seed.
# It computes the final perfomance metrics selecting the iteration with the
# maximum Accuracy. The performance metrics are printed in the screen as
# they are computed. Also, a txt file is generated with these results
# and 2 png file with the confusion matrices are created.
if __name__=='__main__':
# STEP 0: Setting the directory -------------------------------------------------------------------------------------------------------------
directory = input('Please enter the directory where you have the datasets: ')
os.chdir(directory)
# STEP 1 Importing dataset ------------------------------------------------------------------------------------------------------------------
dataset = input('Select the dataset for which you want to run K-Means, digits/HAR/mushrooms [d/h/m]: ')
if dataset=='d':
import digits_specs as specs
elif dataset=='h':
import HAR_specs as specs
elif dataset=='m':
import mushrooms_specs as specs
else:
print('Enter a valid dataset [d/h/m]: ')
# STEP 2: Running K-Means ------------------------------------------------------------------------------------------------------------------
# 2.1. Setting initial parameters------------------------------------------------------------------------------------------------------------
seeded = True # Specify if runs are seeded
seeds = [8905, 9129, 291, 4012, 1256, 6819, 4678, 6971, 1362, 575] #Specific seeds used
n_runs = 10 # How many times should we run the algorithm
dict_acc = dict()
dict_sc = dict()
dict_cs = dict()
dict_hs = dict()
dict_clusterassign= dict()
target = specs.target
data = specs.data
# 2.2. Running k-means and creating the output files-----------------------------------------------------------------------------------------
if os.path.exists('./results/KM_results.txt'):
os.remove('./results/KM_results.txt') # Removes the text file if exists
with open('./results/KM_results.txt', 'x') as f:
# 2.2.1. Running k-means n_run times-------------------------------------------------------------------------------------------------------
for run in range(n_runs):
np.random.seed(seeds[run])
# Shuffle the dataset
print("Run", run)
f.write("RUN "+ str(run) +'\n'+'\n')
# Run k-means(++) on the original data
kmeans_model = KMeans(n_clusters=specs.n_clusters, init="k-means++").fit(data)
# Evaluate the clustering
cluster_assign = np.asarray(kmeans_model.labels_)
# Evaluate the clustering
sc = silhouette_score(data, cluster_assign)
print("SC", sc)
f.write("SC: "+ str(sc) +'\n')
acc = cluster_acc(target, cluster_assign, specs.n_clusters)
print("ACC", acc)
f.write("ACC: "+ str(acc) +'\n')
cs = completeness_score(target, cluster_assign)
print("CS", cs)
f.write("CS: "+ str(cs) +'\n')
hs = homogeneity_score(target, cluster_assign)
print("HS", hs)
f.write("HS: "+ str(hs) +'\n')
# Save performance scores and predictions
dict_acc.update({run : acc})
dict_sc.update({run : sc})
dict_cs.update({run : cs})
dict_hs.update({run : hs})
dict_clusterassign.update({run : cluster_assign})
f.write('\n'+'-------------------------------------------------------------'+'\n')
# 2.2.2. Getting the iteration with the best Accuracy Score---------------------------------------------------------------------------------
max_acc = max(dict_acc, key=dict_acc.get)
print('Iteration with maximum ACC: '+ str(max_acc))
print("ACC: {:.3f}".format(dict_acc[max_acc]))
print("SC: {:.3f}".format(dict_sc[max_acc]))
print("CS: {:.3f}".format(dict_cs[max_acc]))
print("HS: {:.3f}".format(dict_hs[max_acc]))
f.write('Run with maximum ACC: '+ str(max_acc) +'\n')
f.write("ACC: {:.3f}".format(dict_acc[max_acc]) +'\n')
f.write("SC: {:.3f}".format(dict_sc[max_acc]) +'\n')
f.write("CS: {:.3f}".format(dict_cs[max_acc]) +'\n')
f.write("HS: {:.3f}".format(dict_hs[max_acc]) +'\n')
save_confusion_matrix(target, dict_clusterassign[max_acc], specs.n_clusters, 'KM_CM')
| 7c40f6604e46442ed5d299de9b11eba9cbbde2ec | [
"Markdown",
"Python",
"Text"
] | 13 | Python | vninodez/ce888labs | 898860428720a14d4d7ec9973fb70919638e3855 | 10990207502758d56f422edeb757481eba734933 | |
refs/heads/master | <repo_name>prakhar-agarwal/Google-Street-View-House-Numbers<file_sep>/digit_predict.py
import numpy as np
import tensorflow as tf
import random
sess = tf.InteractiveSession()
x = tf.placeholder(tf.float32, shape=[None, 32, 32, 3])
y_ = tf.placeholder(tf.float32, shape=[None, 5])
y_1 = tf.placeholder(tf.float32, shape=[None, 11])
y_2 = tf.placeholder(tf.float32, shape=[None, 11])
y_3 = tf.placeholder(tf.float32, shape=[None, 11])
y_4 = tf.placeholder(tf.float32, shape=[None, 11])
y_5 = tf.placeholder(tf.float32, shape=[None, 11])
lr = tf.placeholder(tf.float32)
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.01)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
W_conv1 = weight_variable([3, 3, 3, 32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
W_conv2 = weight_variable([3, 3, 32, 32])
b_conv2 = bias_variable([32])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
W_conv3 = weight_variable([3, 3, 32, 64])
b_conv3 = bias_variable([64])
h_conv3 = tf.nn.relu(conv2d(h_pool2, W_conv3) + b_conv3)
W_conv4 = weight_variable([3, 3, 64, 128])
b_conv4 = bias_variable([128])
h_conv4 = tf.nn.relu(conv2d(h_conv3, W_conv4) + b_conv4)
h_pool4 = max_pool_2x2(h_conv4)
h_pool4_flat = tf.reshape(h_pool4, [-1, 4*4*128])
W_fc1 = weight_variable([4 * 4 * 128, 1024])
b_fc1 = bias_variable([1024])
h_fc1 = tf.nn.relu(tf.matmul(h_pool4_flat, W_fc1) + b_fc1)
keep_prob = tf.placeholder(tf.float32)
W_fc3 = weight_variable([1024, 1024])
b_fc3 = bias_variable([1024])
h_fc3 = tf.nn.relu(tf.matmul(h_fc1, W_fc3) + b_fc3)
h_fc3_drop = tf.nn.dropout(h_fc3, keep_prob)
W_fc4 = weight_variable([1024, 5])
b_fc4 = bias_variable([5])
y_conv=tf.nn.softmax(tf.matmul(h_fc3_drop, W_fc4) + b_fc4)
cross_entropy_s = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(tf.clip_by_value(y_conv,1e-10,1.0)), reduction_indices=[1]))
W_fc3_1 = weight_variable([1024, 1024])
b_fc3_1 = bias_variable([1024])
h_fc3_1 = tf.nn.relu(tf.matmul(h_fc1, W_fc3_1) + b_fc3_1)
h_fc3_drop_1 = tf.nn.dropout(h_fc3_1, keep_prob)
W_fc4_1 = weight_variable([1024, 11])
b_fc4_1 = bias_variable([11])
y_conv_1=tf.nn.softmax(tf.matmul(h_fc3_drop_1, W_fc4_1) + b_fc4_1)
cross_entropy_1 = tf.reduce_mean(-tf.reduce_sum(y_1*tf.log(tf.clip_by_value(y_conv_1,1e-10,1.0)), reduction_indices=[1]))
W_fc3_2 = weight_variable([1024, 1024])
b_fc3_2 = bias_variable([1024])
h_fc3_2 = tf.nn.relu(tf.matmul(h_fc1, W_fc3_2) + b_fc3_2)
h_fc3_drop_2 = tf.nn.dropout(h_fc3_2, keep_prob)
W_fc4_2 = weight_variable([1024, 11])
b_fc4_2 = bias_variable([11])
y_conv_2=tf.nn.softmax(tf.matmul(h_fc3_drop_2, W_fc4_2) + b_fc4_2)
cross_entropy_2 = tf.reduce_mean(-tf.reduce_sum(y_2*tf.log(tf.clip_by_value(y_conv_2,1e-10,1.0)), reduction_indices=[1]))
W_fc3_3 = weight_variable([1024, 1024])
b_fc3_3 = bias_variable([1024])
h_fc3_3 = tf.nn.relu(tf.matmul(h_fc1, W_fc3_3) + b_fc3_3)
h_fc3_drop_3 = tf.nn.dropout(h_fc3_3, keep_prob)
W_fc4_3 = weight_variable([1024, 11])
b_fc4_3 = bias_variable([11])
y_conv_3=tf.nn.softmax(tf.matmul(h_fc3_drop_3, W_fc4_3) + b_fc4_3)
cross_entropy_3 = tf.reduce_mean(-tf.reduce_sum(y_3*tf.log(tf.clip_by_value(y_conv_3,1e-10,1.0)), reduction_indices=[1]))
W_fc3_4 = weight_variable([1024, 1024])
b_fc3_4 = bias_variable([1024])
h_fc3_4 = tf.nn.relu(tf.matmul(h_fc1, W_fc3_4) + b_fc3_4)
h_fc3_drop_4 = tf.nn.dropout(h_fc3_4, keep_prob)
W_fc4_4 = weight_variable([1024, 11])
b_fc4_4 = bias_variable([11])
y_conv_4=tf.nn.softmax(tf.matmul(h_fc3_drop_4, W_fc4_4) + b_fc4_4)
cross_entropy_4 = tf.reduce_mean(-tf.reduce_sum(y_4*tf.log(tf.clip_by_value(y_conv_4,1e-10,1.0)), reduction_indices=[1]))
W_fc3_5 = weight_variable([1024, 1024])
b_fc3_5 = bias_variable([1024])
h_fc3_5 = tf.nn.relu(tf.matmul(h_fc1, W_fc3_5) + b_fc3_5)
h_fc3_drop_5 = tf.nn.dropout(h_fc3_5, keep_prob)
W_fc4_5 = weight_variable([1024, 11])
b_fc4_5 = bias_variable([11])
y_conv_5=tf.nn.softmax(tf.matmul(h_fc3_drop_5, W_fc4_5) + b_fc4_5)
cross_entropy_5 = tf.reduce_mean(-tf.reduce_sum(y_5*tf.log(tf.clip_by_value(y_conv_5,1e-10,1.0)), reduction_indices=[1]))
cross_entropy = cross_entropy_1 + cross_entropy_2 + cross_entropy_3 + cross_entropy_4 + cross_entropy_5 + cross_entropy_s
train_step = tf.train.AdamOptimizer(lr).minimize(cross_entropy)
arg_y = tf.argmax(y_conv,1)
arg_y_1 = tf.argmax(y_conv_1,1)
arg_y_2 = tf.argmax(y_conv_2,1)
arg_y_3 = tf.argmax(y_conv_3,1)
arg_y_4 = tf.argmax(y_conv_4,1)
arg_y_5 = tf.argmax(y_conv_5,1)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
correct_prediction_1 = tf.equal(tf.argmax(y_conv_1,1), tf.argmax(y_1,1))
accuracy_1 = tf.reduce_mean(tf.cast(correct_prediction_1, tf.float32))
correct_prediction_2 = tf.equal(tf.argmax(y_conv_2,1), tf.argmax(y_2,1))
accuracy_2 = tf.reduce_mean(tf.cast(correct_prediction_2, tf.float32))
correct_prediction_3 = tf.equal(tf.argmax(y_conv_3,1), tf.argmax(y_3,1))
accuracy_3 = tf.reduce_mean(tf.cast(correct_prediction_3, tf.float32))
correct_prediction_4 = tf.equal(tf.argmax(y_conv_4,1), tf.argmax(y_4,1))
accuracy_4 = tf.reduce_mean(tf.cast(correct_prediction_4, tf.float32))
correct_prediction_5 = tf.equal(tf.argmax(y_conv_5,1), tf.argmax(y_5,1))
accuracy_5 = tf.reduce_mean(tf.cast(correct_prediction_5, tf.float32))
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())
def train_model():
X = np.load('dump/cropped_images')
Y = np.load('dump/one_hot_sequence_len')
Y_1 = np.load('dump/digit1')
Y_2 = np.load('dump/digit2')
Y_3 = np.load('dump/digit3')
Y_4 = np.load('dump/digit4')
Y_5 = np.load('dump/digit5')
train_data_X = X[:30000]
train_data_Y = Y[:30000]
train_data_Y_1 = Y_1[:30000]
train_data_Y_2 = Y_2[:30000]
train_data_Y_3 = Y_3[:30000]
train_data_Y_4 = Y_4[:30000]
train_data_Y_5 = Y_5[:30000]
validation_data_X = X[30000:]
validation_data_Y = Y[30000:]
validation_data_Y_1 = Y_1[30000:]
validation_data_Y_2 = Y_2[30000:]
validation_data_Y_3 = Y_3[30000:]
validation_data_Y_4 = Y_4[30000:]
validation_data_Y_5 = Y_5[30000:]
train_tuple = zip(train_data_X, train_data_Y, train_data_Y_1, train_data_Y_2, train_data_Y_3, train_data_Y_4, train_data_Y_5)
validation_tuple = zip(validation_data_X, validation_data_Y, validation_data_Y_1, validation_data_Y_2, validation_data_Y_3, validation_data_Y_4, validation_data_Y_5)
for i in range(50000):
batch = random.sample(train_tuple, 32)
batch_data = [zz[0] for zz in batch]
batch_labels = [zz[1] for zz in batch]
batch_Y_1 = [zz[2] for zz in batch]
batch_Y_2 = [zz[3] for zz in batch]
batch_Y_3 = [zz[4] for zz in batch]
batch_Y_4 = [zz[5] for zz in batch]
batch_Y_5 = [zz[6] for zz in batch]
if i%500==0:
v_batch = random.sample(validation_tuple, 32)
v_batch_data = [zz[0] for zz in v_batch]
v_batch_labels = [zz[1] for zz in v_batch]
v_batch_Y_1 = [zz[2] for zz in v_batch]
v_batch_Y_2 = [zz[3] for zz in v_batch]
v_batch_Y_3 = [zz[4] for zz in v_batch]
v_batch_Y_4 = [zz[5] for zz in v_batch]
v_batch_Y_5 = [zz[6] for zz in v_batch]
v_acc = accuracy.eval(feed_dict={x: v_batch_data, y_: v_batch_labels, y_1: v_batch_Y_1, y_2: v_batch_Y_2, keep_prob: 1.0})
print "validation acc = ", v_acc
v_acc = accuracy_1.eval(feed_dict={x: v_batch_data, y_: v_batch_labels, y_1: v_batch_Y_1, y_2: v_batch_Y_2, keep_prob: 1.0})
print "validation acc = ", v_acc
v_acc = accuracy_2.eval(feed_dict={x: v_batch_data, y_: v_batch_labels, y_1: v_batch_Y_1, y_2: v_batch_Y_2, keep_prob: 1.0})
print "validation acc = ", v_acc
v_acc = accuracy_3.eval(feed_dict={x: v_batch_data, y_3: v_batch_Y_3, keep_prob: 1.0})
print "validation acc = ", v_acc
v_acc = accuracy_4.eval(feed_dict={x: v_batch_data, y_4: v_batch_Y_4, keep_prob: 1.0})
print "validation acc = ", v_acc
v_acc = accuracy_5.eval(feed_dict={x: v_batch_data, y_5: v_batch_Y_5, keep_prob: 1.0})
print "validation acc = ", v_acc
_, loss_val, acc, acc1, acc2, acc3, acc4, acc5 = sess.run([train_step, cross_entropy, accuracy, accuracy_1, accuracy_2, accuracy_3, accuracy_4, accuracy_5], feed_dict={x:batch_data, y_: batch_labels, keep_prob: 0.5, lr: 2e-4, y_1: batch_Y_1, y_2: batch_Y_2, y_3: batch_Y_3, y_4: batch_Y_4, y_5: batch_Y_5})
if i%50 == 0:
print "step", i, "loss", loss_val, "train_accuracy", acc, acc1, acc2, acc3, acc4, acc5
va = 0
for j in xrange(0, validation_data_X.shape[0], 8):
mx = min(j+8, validation_data_X.shape[0])
va = va + (accuracy.eval(feed_dict={x: validation_data_X[j:mx], y_: validation_data_Y[j:mx], y_1: validation_data_Y_1[j:mx], y_2: validation_data_Y_2[j:mx], keep_prob: 1.0}))*(mx-j)
va /= validation_data_X.shape[0]
print "accuracy", va
va = 0
for j in xrange(0, validation_data_X.shape[0], 8):
mx = min(j+8, validation_data_X.shape[0])
va = va + (accuracy_1.eval(feed_dict={x: validation_data_X[j:mx], y_: validation_data_Y[j:mx], y_1: validation_data_Y_1[j:mx], y_2: validation_data_Y_2[j:mx], keep_prob: 1.0}))*(mx-j)
va /= validation_data_X.shape[0]
print "accuracy", va
va = 0
for j in xrange(0, validation_data_X.shape[0], 8):
mx = min(j+8, validation_data_X.shape[0])
va = va + (accuracy_2.eval(feed_dict={x: validation_data_X[j:mx], y_: validation_data_Y[j:mx], y_1: validation_data_Y_1[j:mx], y_2: validation_data_Y_2[j:mx], keep_prob: 1.0}))*(mx-j)
va /= validation_data_X.shape[0]
print "accuracy", va
va = 0
for j in xrange(0, validation_data_X.shape[0], 8):
mx = min(j+8, validation_data_X.shape[0])
va = va + (accuracy_3.eval(feed_dict={x: validation_data_X[j:mx], y_: validation_data_Y[j:mx], y_1: validation_data_Y_1[j:mx], y_3: validation_data_Y_3[j:mx], keep_prob: 1.0}))*(mx-j)
va /= validation_data_X.shape[0]
print "accuracy", va
va = 0
for j in xrange(0, validation_data_X.shape[0], 8):
mx = min(j+8, validation_data_X.shape[0])
va = va + (accuracy_4.eval(feed_dict={x: validation_data_X[j:mx], y_: validation_data_Y[j:mx], y_1: validation_data_Y_1[j:mx], y_4: validation_data_Y_4[j:mx], keep_prob: 1.0}))*(mx-j)
va /= validation_data_X.shape[0]
print "accuracy", va
va = 0
for j in xrange(0, validation_data_X.shape[0], 8):
mx = min(j+8, validation_data_X.shape[0])
va = va + (accuracy_5.eval(feed_dict={x: validation_data_X[j:mx], y_: validation_data_Y[j:mx], y_1: validation_data_Y_1[j:mx], y_5: validation_data_Y_5[j:mx], keep_prob: 1.0}))*(mx-j)
va /= validation_data_X.shape[0]
print "accuracy", va
saver.save(sess, './model1.ckpt')
def load_model():
saver.restore(sess, './model1.ckpt')
def get_predictions(X):
y, y1, y2, y3, y4, y5 = sess.run([arg_y, arg_y_1, arg_y_2, arg_y_3, arg_y_4, arg_y_5], feed_dict={x:[X], keep_prob: 1.0})
return [y[0], y1[0], y2[0], y3[0], y4[0], y5[0]]
<file_sep>/skeleton.py
import digit_predict
import numpy as np
import pickle
import gzip
from skimage.transform import resize
class SVHN(object):
path = ""
def __init__(self, data_dir):
self.path = data_dir
def train(self):
digit_predict.train_model()
def get_sequence(self, image):
image = resize(image,(32,32,3))
preds = digit_predict.get_predictions(image)
preds = preds[1:preds[0]+2]
return preds
def save_model(self, **params):
file_name = params['name']
pickle.dump(self, gzip.open(file_name, 'wb'))
@staticmethod
def load_model(**params):
digit_predict.load_model()
file_name = params['name']
return pickle.load(gzip.open(file_name, 'rb'))
if __name__ == "__main__":
obj = SVHN('data/')
# obj.train()
obj.save_model(name="svhn.gz")
<file_sep>/read_data.py
import sys
import numpy as np
train_data = dict()
with open('train.csv') as f:
for j in f:
i = j.split(',')
if i[0]!='FileName':
if i[0] not in train_data:
train_data[i[0]] = dict()
train_data[i[0]]['sequence']=[]
train_data[i[0]]['left']=10000
train_data[i[0]]['top']=10000
train_data[i[0]]['right']=0
train_data[i[0]]['bottom']=0
if i[1]=='10':
train_data[i[0]]['sequence'].append(0)
else:
train_data[i[0]]['sequence'].append(int(i[1]))
left = max(0,int(i[2]))
top = max(0,int(i[3]))
right = int(i[4])+left
bottom = int(i[5])+top
if train_data[i[0]]['left'] > left:
train_data[i[0]]['left'] = left
if train_data[i[0]]['top'] > top:
train_data[i[0]]['top'] = top
if train_data[i[0]]['right'] < right:
train_data[i[0]]['right'] = right
if train_data[i[0]]['bottom'] < bottom:
train_data[i[0]]['bottom'] = bottom
from skimage.viewer import ImageViewer
from skimage.io import imread
from skimage.transform import resize
from sklearn.preprocessing import OneHotEncoder
X = []
Y = []
Y_1 = []
Y_2 = []
Y_3 = []
Y_4 = []
Y_5 = []
a=0
for i in train_data:
a=a+1
print a
#
# if a==10:
# break
if len(train_data[i]['sequence'])<6:
left = train_data[i]['left']
top = train_data[i]['top']
bottom = train_data[i]['bottom']
right = train_data[i]['right']
Y.append(len(train_data[i]['sequence']))
if len(train_data[i]['sequence'])>=1:
Y_1.append(train_data[i]['sequence'][0])
else:
Y_1.append(10)
if len(train_data[i]['sequence'])>=2:
Y_2.append(train_data[i]['sequence'][1])
else:
Y_2.append(10)
if len(train_data[i]['sequence'])>=3:
Y_3.append(train_data[i]['sequence'][2])
else:
Y_3.append(10)
if len(train_data[i]['sequence'])>=4:
Y_4.append(train_data[i]['sequence'][3])
else:
Y_4.append(10)
if len(train_data[i]['sequence'])>=5:
Y_5.append(train_data[i]['sequence'][4])
else:
Y_5.append(10)
x = imread('./data/train/'+i)
x = x[top:bottom, left:right]
x = resize(x,(32,32,3))
X.append(x.tolist())
X = np.asarray(X)
Y = np.asarray(Y)
Y_1 = np.asarray(Y_1)
Y_2 = np.asarray(Y_2)
Y_3 = np.asarray(Y_3)
Y_4 = np.asarray(Y_4)
Y_5 = np.asarray(Y_5)
enc1 = OneHotEncoder(sparse=False)
Y = enc1.fit_transform(Y.reshape(-1,1))
enc = OneHotEncoder(n_values=11, sparse=False)
Y_1 = enc.fit_transform(Y_1.reshape(-1,1))
Y_2 = enc.fit_transform(Y_2.reshape(-1,1))
Y_3 = enc.fit_transform(Y_3.reshape(-1,1))
Y_4 = enc.fit_transform(Y_4.reshape(-1,1))
Y_5 = enc.fit_transform(Y_5.reshape(-1,1))
print X.shape
print Y.shape
print Y_1.shape
print Y_2.shape
print Y_3.shape
print Y_4.shape
print Y_5.shape
X.dump('dump/cropped_images')
Y.dump('dump/one_hot_sequence_len')
Y_1.dump('dump/digit1')
Y_2.dump('dump/digit2')
Y_3.dump('dump/digit3')
Y_4.dump('dump/digit4')
Y_5.dump('dump/digit5')
<file_sep>/README.md
# Google-Street-View-House-Numbers
Standard Implementation for classification tasks on Google Street View House Numbers
<file_sep>/skele.py
import digit_predict
import numpy as np
#digit_predict.train_model()
digit_predict.load_model()
X = np.load('dump/cropped_images')
Y = np.load('dump/one_hot_sequence_len')
Y_1 = np.load('dump/digit1')
Y_2 = np.load('dump/digit2')
Y_3 = np.load('dump/digit3')
Y_4 = np.load('dump/digit4')
Y_5 = np.load('dump/digit5')
validation_data_X = X[30000:]
validation_data_Y = Y[30000:]
validation_data_Y_1 = Y_1[30000:]
validation_data_Y_2 = Y_2[30000:]
validation_data_Y_3 = Y_3[30000:]
validation_data_Y_4 = Y_4[30000:]
validation_data_Y_5 = Y_5[30000:]
correct = 0
for i in range(len(validation_data_X)):
print "Processing image", i, "of", len(validation_data_X)
preds = digit_predict.get_predictions(validation_data_X[i])
preds = preds[1:preds[0]+2]
target = [np.argmax(validation_data_Y[i]), np.argmax(validation_data_Y_1[i]), np.argmax(validation_data_Y_2[i]), np.argmax(validation_data_Y_3[i]), np.argmax(validation_data_Y_4[i]), np.argmax(validation_data_Y_5[i])]
target = target[1:target[0]+2]
if preds == target:
correct += 1
print "accuracy = ", correct/float(len(validation_data_X))
<file_sep>/sequence_predictor.py
import numpy as np
import tensorflow as tf
import random
sess = tf.InteractiveSession()
x = tf.placeholder(tf.float32, shape=[None, 32, 32, 3])
y_ = tf.placeholder(tf.float32, shape=[None, 5])
lr = tf.placeholder(tf.float32)
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.01)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
W_conv1 = weight_variable([3, 3, 3, 32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
W_conv2 = weight_variable([3, 3, 32, 32])
b_conv2 = bias_variable([32])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
W_conv3 = weight_variable([3, 3, 32, 64])
b_conv3 = bias_variable([64])
h_conv3 = tf.nn.relu(conv2d(h_pool2, W_conv3) + b_conv3)
W_conv4 = weight_variable([3, 3, 64, 128])
b_conv4 = bias_variable([128])
h_conv4 = tf.nn.relu(conv2d(h_conv3, W_conv4) + b_conv4)
h_pool4 = max_pool_2x2(h_conv4)
h_pool4_flat = tf.reshape(h_pool4, [-1, 4*4*128])
W_fc1 = weight_variable([4 * 4 * 128, 1024])
b_fc1 = bias_variable([1024])
h_fc1 = tf.nn.relu(tf.matmul(h_pool4_flat, W_fc1) + b_fc1)
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
#
# W_fc2 = weight_variable([1024, 1024])
# b_fc2 = bias_variable([1024])
# h_fc2 = tf.nn.relu(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
# h_fc2_drop = tf.nn.dropout(h_fc2, keep_prob)
W_fc3 = weight_variable([1024, 1024])
b_fc3 = bias_variable([1024])
h_fc3 = tf.nn.relu(tf.matmul(h_fc1_drop, W_fc3) + b_fc3)
h_fc3_drop = tf.nn.dropout(h_fc3, keep_prob)
W_fc4 = weight_variable([1024, 5])
b_fc4 = bias_variable([5])
y_conv=tf.nn.softmax(tf.matmul(h_fc3_drop, W_fc4) + b_fc4)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(tf.clip_by_value(y_conv,1e-10,1.0)), reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(lr).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
sess.run(tf.global_variables_initializer())
X = np.load('dump/cropped_images')
Y = np.load('dump/one_hot_sequence_len')
train_data_X = X[:30000]
train_data_Y = Y[:30000]
validation_data_X = X[30000:]
validation_data_Y = Y[30000:]
train_tuple = zip(train_data_X, train_data_Y)
validation_tuple = zip(validation_data_X, validation_data_Y)
for i in range(10000):
batch = random.sample(train_tuple, 64)
batch_data = [zz[0] for zz in batch]
batch_labels = [zz[1] for zz in batch]
if i%500==0:
v_batch = random.sample(validation_tuple, 64)
v_batch_data = [zz[0] for zz in v_batch]
v_batch_labels = [zz[1] for zz in v_batch]
v_acc = accuracy.eval(feed_dict={x: v_batch_data, y_: v_batch_labels, keep_prob: 1.0})
print "validation acc = ", v_acc
_, loss_val, acc = sess.run([train_step, cross_entropy, accuracy], feed_dict={x:batch_data, y_: batch_labels, keep_prob: 0.5, lr: 2e-4})
if i%50 == 0:
print "step", i, "loss", loss_val, "train_accuracy", acc
va = 0
for j in xrange(0, validation_data_X.shape[0], 8):
mx = min(j+8, validation_data_X.shape[0])
va = va + (accuracy.eval(feed_dict={x: validation_data_X[j:mx], y_: validation_data_Y[j:mx], keep_prob: 1.0}))*(mx-j)
va /= validation_data_X.shape[0]
print "accuracy", va
<file_sep>/evaluation.py
from skeleton import SVHN
import numpy as np
import traceback
import math
class Evaluator(object):
def __init__(self, data_dir):
self.path = data_dir
def load_images(self):
self.X = np.load(self.path+'/cropped_images')
self.Y = np.load(self.path+'/one_hot_sequence_len')
self.Y_1 = np.load(self.path+'/digit1')
self.Y_2 = np.load(self.path+'/digit2')
self.Y_3 = np.load(self.path+'/digit3')
self.Y_4 = np.load(self.path+'/digit4')
self.Y_5 = np.load(self.path+'/digit5')
def evaluate(self, model):
correct = 0
for i in range(len(self.X)):
print "Processing image", i, "of", len(self.X)
target = [np.argmax(self.Y[i]), np.argmax(self.Y_1[i]), np.argmax(self.Y_2[i]), np.argmax(self.Y_3[i]), np.argmax(self.Y_4[i]), np.argmax(self.Y_5[i])]
target = target[1:target[0]+2]
try:
preds = model.get_sequence(np.asarray(self.X[i], dtype=np.uint8))
if preds == target:
correct += 1
except Exception as e:
print traceback.print_exc()
accuracy = correct/float(len(self.X))
score = 0
if accuracy <0.5:
score = 15.0 * accuracy
else:
score = 7.5*(math.exp(1.386*(accuracy-0.5)))
print "Accuracy =", accuracy*100
print "Marks =", score
if __name__ == "__main__":
evaluator = Evaluator("dump_test")
evaluator.load_images()
obj = SVHN.load_model(name='svhn.gz')
evaluator.evaluate(obj)
| dcb13ae073dd0ddc9601b764448a6d709b7b1b73 | [
"Markdown",
"Python"
] | 7 | Python | prakhar-agarwal/Google-Street-View-House-Numbers | 0b4019e12c6251abbc93f4958ccae3a485d64ec6 | a3c90e80caa92a9ad1e5f2df143f3d070071e48b | |
refs/heads/master | <file_sep>using UnityEngine;
using System.Collections;
public class id_player : MonoBehaviour {
public Transform player;
public Collider2D [] live;
public GameObject newPlayer;
public GameObject aux;
// Use this for initialization
void Start () {
aux = (GameObject) Instantiate(newPlayer, transform.position, transform.rotation);
player = aux.transform;
}
// Update is called once per frame
void Update () {
live = Physics2D.OverlapCircleAll(this.transform.position, 1f, 1 << LayerMask.NameToLayer ("Player"));
if (live.Length > 0) {
Vector3 newPosition = new Vector3 (player.position.x, player.position.y, transform.position.z);
transform.position = new Vector3 (player.position.x, player.position.y, transform.position.z);
}
else {
this.transform.position = new Vector3(0,-0.9f,0);
aux = (GameObject) Instantiate(newPlayer, transform.position, transform.rotation);
player = aux.transform;
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class enimie : MonoBehaviour
{
// Movimento
public float velocity; // Velocidade do inimigo
public bool forRigth = true; // Indica se direção é a direita
public float runDelay; // Tempo que caminha prara cada direção
private float runningTime; // Tempo de caminhada
private bool running; // Indica se está andando
//Animação
public Transform character; //Personagem jogavel
private Animator anime; //Animação do personagem
public int life;
// Use this for initialization
void Start()
{
// Carrega a animação
anime = character.GetComponent<Animator>();
runningTime = 0;
running = false;
life = 10;
}
// Update is called once per frame
void Update()
{
runningTime += Time.deltaTime;
if (runningTime > runDelay)
{
runningTime = 0;
if (running)
{
anime.SetTrigger("stop");
running = false;
}
else {
forRigth = !forRigth;
anime.SetTrigger("runing");
running = true;
}
}
if (forRigth && running) {
transform.Translate(Vector2.right * velocity * Time.deltaTime);
transform.eulerAngles = new Vector2(0, 0);
}
if (!forRigth && running) {
transform.Translate(Vector2.right * velocity * Time.deltaTime);
transform.eulerAngles = new Vector2(0, 180);
}
if (life <= 0) {
Destroy (gameObject);
}
}
void OnCollisionEnter2D (Collision2D colisor) {
if (colisor.gameObject.tag == "Power1") {
life -= 1;
}
else if (colisor.gameObject.tag == "Power2") {
life -= 5;
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class player : MonoBehaviour {
//Movimento
public float velocity;
public float enterTime = 0.4f; //Tempo de duração do efeito de entrada
//Animação
public Transform character; //Personagem jogavel
private Animator anime; //Animação do personagem
//Pulo
private bool grounded; //Verifica de está na terra
public float force; //Força do pulo
public float jumpTime; //Tempo do pulo
public float jumpDelay = 0.7f; //Tempo da animação
public Transform ground; //Obj abaixo do personagem
// Disparar bola de energia
public GameObject[] shotgun; // Obj energia
private Vector2 shotposition; // Posição do disparo
private bool shotting;
private bool flaming;
private float shotTime = 0;
public GameObject sabre;
// Use this for initialization
void Start () {
// Carrega a animação
anime = character.GetComponent<Animator> ();
}
// Update is called once per frame
void Update () {
// Verifica tempo da animação de entrada
if (enterTime > 0) {
enterTime -= Time.deltaTime;
anime.SetFloat ("enter", enterTime);
}
// Controla movimento
Move ();
// Controla o disparo
Shoting ();
}
// Controla caminhada e pulo
void Move () {
// Verifica se player estrá no chão
grounded = Physics2D.Linecast (this.transform.position, ground.position, 1 << LayerMask.NameToLayer ("Cenary"));
// Verifica se está correndo
anime.SetFloat ("run", Mathf.Abs (Input.GetAxis ("Horizontal")));
// Verifica se está caindo
anime.SetFloat ("force", Mathf.Abs (this.GetComponent<Rigidbody2D>().velocity.y));
// Verifica se seta direita é pressionada
if (Input.GetAxisRaw ("Horizontal") > 0) {
transform.Translate (Vector2.right * velocity * Time.deltaTime);
transform.eulerAngles = new Vector2(0,0);
}
// Verifica se seta esquerda é pressionada
if (Input.GetAxisRaw ("Horizontal") < 0) {
transform.Translate (Vector2.right * velocity * Time.deltaTime);
transform.eulerAngles = new Vector2 (0,180);
}
// Verifica se espaço é pressionado
if (Input.GetButtonDown ("Jump") && grounded) {
GetComponent<Rigidbody2D>().AddForce (force * transform.up);
anime.SetTrigger ("jump");
jumpTime = jumpDelay;
}
// Verifica se voltou para o chão
if (grounded) {
anime.SetTrigger ("ground");
}
// Verifica o tempo de pulo
if (jumpTime > -0.1)
jumpTime -= Time.deltaTime;
}
void OnCollisionEnter2D (Collision2D colisor) {
if (colisor.gameObject.tag == "Enimie") {
// Destroi personagem
Destroy(gameObject);
/*
// reinicia posiçao
transform.position = new Vector3 (0f, -0.9f, 0f);
transform.eulerAngles = new Vector2(0,0);
//Cria novo personagem
Instantiate(gameObject, transform.position, transform.rotation);
*/
}
}
void Shoting (){
// Atualiza a animaçao
anime.SetBool ("shot", (shotting || flaming));
shotposition = transform.position;
if (transform.eulerAngles.y == 0)
shotposition.x += 0.15f;
else
shotposition.x -= 0.15f;
// Dispara o tiro
if (Input.GetKeyDown ("left ctrl") && !flaming) {
shotting = true;
}
if (Input.GetKeyUp("left ctrl") && shotting) {
if (shotTime < 1){
Instantiate(shotgun[1], shotposition, transform.rotation);
}
else {
Instantiate(shotgun[2], shotposition, transform.rotation);
}
shotTime = 0;
shotting = false;
}
// Dispara o sabre de fogo
if (Input.GetKeyDown ("left alt") && !shotting) {
flaming = true;
sabre = (GameObject) Instantiate(shotgun[0], shotposition, transform.rotation);
}
if (Input.GetKeyUp("left alt") && flaming) {
//sabre.;
flaming = false;
}
if (shotting == true)
shotTime += Time.deltaTime;
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class sabre : MonoBehaviour {
public Transform player;
private Vector2 newPosition;
// Use this for initialization
void Start () {
Destroy (gameObject, 1f);
}
// Update is called once per frame
void Update () {
/*
newPosition = player.position;
if (player.eulerAngles.y == 0) {
transform.eulerAngles.y = 180;
newPosition.x += 0.15f;
} else {
transform.eulerAngles.y = 0;
newPosition.x -= 0.15f;
}
transform.position = new Vector3 (newPosition.x, newPosition.y, transform.position.z);
*/
}
void DestroySabre (){
Destroy (gameObject);
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class energy : MonoBehaviour {
private float timeLife;
public float MaxTimeLife;
public float velocity;
// Use this for initialization
void Start () {
timeLife = 0;
}
// Update is called once per frame
void Update () {
timeLife += Time.deltaTime;
if (timeLife > MaxTimeLife) {
Destroy(gameObject);
}
transform.Translate(Vector2.right * velocity * Time.deltaTime);
}
// Destroi objeto ao tocar inimigo
void OnCollisionEnter2D (Collision2D colisor) {
if (colisor.gameObject.tag == "Enimie") {
Destroy(gameObject);
}
}
}
| 025e5dc66f4137e650832e99186021e68598d392 | [
"C#"
] | 5 | C# | artphil7/Unity | d9bd2ddf180ccb97a8368f9729b2ca436282a8a1 | 4e7fd318623d74ee821ea51d9b8d452f967bb771 | |
refs/heads/master | <repo_name>wallabyway/glesjs<file_sep>/jni/Android.mk
LOCAL_PATH := $(call my-dir)
# afaik V8 uses v7a, so we might as well use it
APP_ABI := armeabi-v7a
# First, define local static libraries for use in LOCAL_STATIC_LIBRARIES
# We need all of these for V8 to run.
# We put them in jni/lib, but we could also put them somewhere else.
# The following 3 libraries are copied from:
# <V8_HOME>/out/android_arm.release/obj.host/tools/gyp/libv8_base.a
# stlport is a StdC++ library, copied from:
#<NDK_r9d_HOME>/sources/cxx-stl/stlport/libs/armeabi/libstlport_static.a
include $(CLEAR_VARS)
LOCAL_MODULE := stlport
LOCAL_MODULE_FILENAME := stlport_static
LOCAL_SRC_FILES := lib/libstlport_static.a
include $(PREBUILT_STATIC_LIBRARY)
include $(CLEAR_VARS)
LOCAL_MODULE := v8_base
LOCAL_MODULE_FILENAME := v8_base_static
LOCAL_SRC_FILES := lib/libv8_base.a
include $(PREBUILT_STATIC_LIBRARY)
include $(CLEAR_VARS)
LOCAL_MODULE := v8_nosnapshot
LOCAL_MODULE_FILENAME := v8_nosnapshot_static
LOCAL_SRC_FILES := lib/libv8_nosnapshot.a
include $(PREBUILT_STATIC_LIBRARY)
include $(CLEAR_VARS)
LOCAL_MODULE := v8_libbase
LOCAL_MODULE_FILENAME := v8_libbase_static
LOCAL_SRC_FILES := lib/libv8_libbase.arm.a
include $(PREBUILT_STATIC_LIBRARY)
# Now, compile our code and link everything together as a shared library
# in libs/.
# Note that the order of libraries in LOCAL_STATIC_LIBRARIES is important.
# If you swap the order, it likely won't link anymore.
include $(CLEAR_VARS)
LOCAL_MODULE := glesjs
LOCAL_SRC_FILES := main.cpp
LOCAL_LDLIBS := -llog -landroid -lEGL -lGLESv1_CM -lGLESv2
LOCAL_STATIC_LIBRARIES := android_native_app_glue libv8_base libv8_libbase libv8_nosnapshot libstlport
LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
# hide symbols from included static libraries
LOCAL_CPPFLAGS += -Wl,--exclude-libs,libv8_base
LOCAL_CFLAGS += -Wl,--exclude-libs,libv8_base
LOCAL_LDFLAGS += -Wl,--exclude-libs,libv8_base
include $(BUILD_SHARED_LIBRARY)
$(call import-module,android/native_app_glue)
<file_sep>/README.md
## GLES.JS - Fast and small Android WebGL bindings for V8
Copyright (c) 2015 by <NAME> ( tmtg.net / <EMAIL>).
Released under revised BSD license. See LICENSE for details.
Gles.js provides Android WebGL bindings for the Javascript V8 engine (ARMv7
architecture). WebGL is directly translated to OpenGL ES, providing what is
probably the fastest and smallest engine for running HTML5 games currently
available on Android. APK footprint is about 1.5 Mb.
A minimalist HTML5 API emulation is provided. While only a single Canvas
element is fully emulated, there is limited support for handling HTML and
XML structures and a fake API for the most common things that HTML5 apps do.
### Workflow
1. put your webpage and all resources, like scripts and images, in assets/.
Gles.js expects index.html to be present, from which the rest is loaded.
html5.js must be present in assets/, which is the bootloader for
everything else.
2. compile using the standard Android SDK method, 'ant release'. This will
package everything into an APK, which is found in bin/.
### Setting up (command line)
This assumes you are using the command line to build. To set it up, install
Apache Ant and the Android SDK. Within the Android SDK package manager,
install API level 14 (which is the minimum that guarantees ARMv7
architecture). Then, make sure that the following is in your PATH:
```
[ANT_DIR]/bin
[ANDROIDSDK_DIR]/platform-tools
[ANDROIDSDK_DIR]/tools
```
Also define the following variable:
```
ANDROID_HOME=[ANDROIDSDKROOT]
```
Now, initialise the SDK skeleton by running:
```
android update project --name GlesJSDemo --target android-14 --path .
```
Once you've done this, you should be able to execute step (1) and (2) above.
### Compiling libglesjs.so
The procecure above assumes you just use the compiled object file,
libglesjs.so. If you want to tinker with the gles.js native code, you will
need the Android NDK as well. Download/unzip the NDK (no install is required).
Make sure your PATH points to the NDK root dir.
#### Directory structure
```
/ - Standard Android build files
res/ - Standard Android resources
assets/ - HTML5 bootloader (html5.js) and your webpage resources
src/ - Java classes
jni/ - Main source (main.cpp) and makefiles
jni/include/ - Static include files
jni/gluegen/ - Generated OpenGL ES bindings and definitions used by main.cpp
jni/lib/ - Precompiled V8 linkables
libs/ - Precompiled libs used by SDK, including libglesjs
```
#### Compile procedure
1. Patch and build V8. This is quite a mess, and currently not included in
this package, so you'll have to do with the precompiled V8 binaries in
jni/lib/ for now.
2. Generate the OpenGL ES bindings by running `php jni/gluegen/gluegen.php'.
Yes, PHP is a very useful command-line string processing language, and
is used here for the string processing involved in parsing the OpenGL
header file and generating the bindings files.
3. Run ndk-build to build libs/armeabi/libglesjs.so
4. Run ant release (this is normally the only step) to compile the Java
classes and put everything in an APK.
Depending on how deep you want to dig with development, you can do just the
later steps, using the precompiled and pregenerated stuff already included in
the package.
### Features
- HTML and XML structure manipulation
- OUYA support (controller and payment)
- Multitouch support
- Audio element support. Web audio API NOT supported. For just playing
samples, the Audio element is actually more convenient. Also, JS apps need
to support Audio element anyway, in order to be compatible with IE.
- HTML5 gamepad support. Currently implemented for OUYA only.
- Features a simple JS payment API of my own devising, which should be
conceptually compatible with multiple payment systems. Only OUYA
implementation is currently provided.
See src/net/tmtg/glesjs/PaymentSystem.java for more info.
- runs most Pixi demos, some after minor hacking of the html file
- runs jgame.js (for me, this is its main purpose)
### Known issues
- There is a bug which sometimes produces spurious mouse coordinates
- Pixi XML fonts don't work yet
- Some OpenGL ES functions are not yet implemented, in particular some of the
delete and free functions, and a couple of complex functions for which no
test code is available yet. Generally, OpenGL functions need to be tested
with more test code.
- There are some minor differences between WebGL and individual
implementations of OpenGL ES. Some of these differences are just bugs.
WebGL as featured in Chrome tries to emulate correct WebGL behaviour for
known differences. In contrast, gles.js is designed to work without
emulation layer. This means you will have to test your app on more
devices to make sure it works everywhere.
<file_sep>/examples/ARToolkit/README.md
# example of twgl.js library with glesjs
<file_sep>/examples/helloworld/README.md
# 🛠 helloworld example

### demostrates...
* tiny footprint
* mouse movement
* simple shaderToy example
* small webgl library (twgl.js)
# 🛠 References
* [twgl.js library](http://twgljs.org)
* [gles.js library](https://github.com/borisvanschooten/glesjs)
* [glsl shader sandbox](http://glslsandbox.com/e#28331.0)
<file_sep>/examples/README.md
# 🛠 GLES.js examples

### Basic webGL examples
* [helloworld](./helloworld) (shaderToy example)
* twgl.js (spinning textured cube)
* [pixi.js](./pixi) (bouncing sprites)
* three.js (spinning cube)
### WebVR examples
* stereo panorama (twgl.js, split screen and sensor API)
* ARToolkit - cube
* marker tracking
* throughscreen camera
* piped through webVR camera API
# ⚙ Setup
* download and install the APK
* open your phone browser
* click on the example links above
# 💬 Feedback
[add issues](https://github.com/wallabyway/glesjs)
# 🛠 References
* [webVR spec](https://webvr.info/)
* [ARToolkit](http://artoolkit.org/documentation/doku.php?id=7_Examples:example_simplelite)
# 📱Downloads
* APK pre-built [glesz.apk](https://github.com/wallabyway/glesjs/blob/master/examples/www/glesz.apk?raw=true)
* example [helloworld.zip](webvr://s3-us-west-2.amazonaws.com/pano-raas-au/js/helloworld.zip)
* example [twglcube.zip](webvr://s3-us-west-2.amazonaws.com/pano-raas-au/js/twglcube.zip)<file_sep>/jni/main.cpp
// (c) 2014 <NAME>
//BEGIN_INCLUDE(all)
#include <jni.h>
#include <stdlib.h>
#include <errno.h>
#include <EGL/egl.h>
// at least some defs from gl1 are needed
#include <GLES/gl.h>
#include <GLES2/gl2.h>
#include <android/sensor.h>
#include <android/log.h>
#include <android_native_app_glue.h>
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "glesjs", __VA_ARGS__))
#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "glesjs", __VA_ARGS__))
#include <android/asset_manager.h>
#include <v8.h>
using namespace v8;
// http://engineering.prezi.com/blog/2013/08/27/embedding-v8/
class MallocArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
public:
virtual void* Allocate(size_t length) {
return calloc(length,1);
}
virtual void* AllocateUninitialized(size_t length) {
return malloc(length);
}
// XXX we assume length is not needed
virtual void Free(void*data, size_t length) {
free(data);
}
};
static v8::ArrayBuffer::Contents getRawData(Isolate *isolate,Handle<Value> val) {
v8::Handle<v8::ArrayBuffer> buf = v8::Handle<v8::ArrayBuffer>::Cast(val);
return buf->GetData();
}
//static void enableTypedArrays() {
// v8::internal::FLAG_harmony_array_buffer = true;
// v8::internal::FLAG_harmony_typed_arrays = true;
// V8::SetArrayBufferAllocator(new MallocArrayBufferAllocator());
//}
// -----------------------------------------------
// data defs
// -----------------------------------------------
// -----------------------------------------------
// globals
// -----------------------------------------------
long readAsset(const char *filename, char **output);
int32_t screenwidth;
int32_t screenheight;
class JS {
public:
v8::Persistent<Context> context;
v8::Handle<v8::ObjectTemplate> global;
v8::Isolate *isolate;
JS();
char *run_javascript(char *sourcestr);
void callFunction(const char *funcname,const int argc,Handle<Value> argv[]);
};
JS *js=NULL;
JNIEnv *jnienv = NULL;
jclass utilsClass;
bool app_was_inited=false;
#define NR_PLAYERS 4
#define NR_BUTTONS 17
#define NR_AXES 6
#define PLAYERDATASIZE (1+NR_BUTTONS+NR_AXES)
// static array with all gamepad data
float gamepadvalues[NR_PLAYERS*PLAYERDATASIZE];
// utils
// String data = loadStringAsset(String filename)
void __utils_loadStringAsset(const v8::FunctionCallbackInfo<v8::Value>& args) {
String::Utf8Value _str_assetname(args[0]->ToString());
const char *assetname = *_str_assetname;
char *data;
readAsset(assetname,&data);
LOGI("Loaded string asset '%s'",assetname);
args.GetReturnValue().Set(v8::String::NewFromUtf8(args.GetIsolate(),
data));
}
// void execScript(String source)
void __utils_execScript(const v8::FunctionCallbackInfo<v8::Value>& args) {
String::Utf8Value _str_source(args[0]->ToString());
char *source = *_str_source;
char *ret = js->run_javascript(source);
LOGI("Executed JS");
}
// get gamepad buttons and axes for all players in one go. JS passes a
// Float32Array, into which the data is copied. The Float32Array must be of
// the same size as the data.
// void getGamepadValues(Float32Array buffer)
void __utils_getGamepadValues(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Handle<v8::ArrayBufferView> bufview_data = Handle<ArrayBufferView>::Cast(args[0]);
v8::Handle<v8::ArrayBuffer> buf_data = bufview_data->Buffer();
v8::ArrayBuffer::Contents con_data=buf_data->GetData();
int datalen = con_data.ByteLength();
float * data = (float *)con_data.Data();
// copy our data into the typed array
memcpy(data,gamepadvalues,datalen);
}
// payment
void __paymentSystem_init(const v8::FunctionCallbackInfo<v8::Value>& args) {
LOGI("__paymentSystem_init");
String::Utf8Value _str_secrets(args[0]->ToString());
const char *secrets = *_str_secrets;
jmethodID mid = jnienv->GetStaticMethodID(utilsClass, "paymentInit",
"(Ljava/lang/String;)V");
jstring jnisecrets = jnienv->NewStringUTF(secrets);
jnienv->CallStaticVoidMethod(utilsClass,mid, jnisecrets);
jnienv->DeleteLocalRef(jnisecrets);
}
void __paymentSystem_getType(const v8::FunctionCallbackInfo<v8::Value>& args) {
LOGI("__paymentSystem_getType");
jmethodID mid = jnienv->GetStaticMethodID(utilsClass, "paymentGetType",
"()Ljava/lang/String;");
jstring jniret = (jstring)
jnienv->CallStaticObjectMethod(utilsClass,mid);
if (jniret==NULL) return; // undefined
const char *ret = jnienv->GetStringUTFChars(jniret, 0);
args.GetReturnValue().Set(v8::String::NewFromUtf8(args.GetIsolate(), ret));
jnienv->ReleaseStringUTFChars(jniret, ret);
// not sure if it's necessary
jnienv->DeleteLocalRef(jniret);
}
void __paymentSystem_exit(const v8::FunctionCallbackInfo<v8::Value>& args) {
jmethodID mid = jnienv->GetStaticMethodID(utilsClass, "paymentExit",
"()V");
jnienv->CallStaticVoidMethod(utilsClass,mid);
}
void __paymentSystem_requestPayment(const v8::FunctionCallbackInfo<v8::Value>& args) {
LOGI("__paymentSystem_requestPayment");
String::Utf8Value _str_product_id(args[0]->ToString());
const char *product_id = *_str_product_id;
jmethodID mid = jnienv->GetStaticMethodID(utilsClass,
"paymentRequestPayment", "(Ljava/lang/String;)Z");
jstring jniproduct_id = jnienv->NewStringUTF(product_id);
jboolean jniret = (jboolean)
jnienv->CallStaticBooleanMethod(utilsClass,mid, jniproduct_id);
jnienv->DeleteLocalRef(jniproduct_id);
args.GetReturnValue().Set(v8::Boolean::New(args.GetIsolate(), jniret));
}
void __paymentSystem_checkReceipt(const v8::FunctionCallbackInfo<v8::Value>& args) {
String::Utf8Value _str_product_id(args[0]->ToString());
const char *product_id = *_str_product_id;
jmethodID mid = jnienv->GetStaticMethodID(utilsClass, "paymentCheckReceipt",
"(Ljava/lang/String;)I");
jstring jniproduct_id = jnienv->NewStringUTF(product_id);
jint jniret = (jint)
jnienv->CallStaticIntMethod(utilsClass,mid, jniproduct_id);
jnienv->DeleteLocalRef(jniproduct_id);
args.GetReturnValue().Set(v8::Integer::New(args.GetIsolate(), jniret));
}
// localStorage
void __localStorage_getItem(const v8::FunctionCallbackInfo<v8::Value>& args) {
String::Utf8Value _str_key(args[0]->ToString());
const char *key = *_str_key;
jmethodID mid = jnienv->GetStaticMethodID(utilsClass, "storeGetString",
"(Ljava/lang/String;)Ljava/lang/String;");
jstring jnikey = jnienv->NewStringUTF(key);
jstring jniret = (jstring)
jnienv->CallStaticObjectMethod(utilsClass,mid, jnikey);
jnienv->DeleteLocalRef(jnikey);
if (jniret==NULL) return; // undefined
const char *ret = jnienv->GetStringUTFChars(jniret, 0);
args.GetReturnValue().Set(v8::String::NewFromUtf8(args.GetIsolate(), ret));
jnienv->ReleaseStringUTFChars(jniret, ret);
// not sure if it's necessary
jnienv->DeleteLocalRef(jniret);
}
void __localStorage_setItem(const v8::FunctionCallbackInfo<v8::Value>& args) {
String::Utf8Value _str_key(args[0]->ToString());
const char *key = *_str_key;
String::Utf8Value _str_val(args[1]->ToString());
const char *val = *_str_val;
jmethodID mid = jnienv->GetStaticMethodID(utilsClass, "storeSetString",
"(Ljava/lang/String;Ljava/lang/String;)V");
jstring jnikey = jnienv->NewStringUTF(key);
jstring jnival = jnienv->NewStringUTF(val);
jnienv->CallStaticVoidMethod(utilsClass,mid, jnikey,jnival);
jnienv->DeleteLocalRef(jnikey);
jnienv->DeleteLocalRef(jnival);
}
void __localStorage_removeItem(const v8::FunctionCallbackInfo<v8::Value>& args){
String::Utf8Value _str_key(args[0]->ToString());
const char *key = *_str_key;
jmethodID mid = jnienv->GetStaticMethodID(utilsClass, "storeRemove",
"(Ljava/lang/String;)V");
jstring jnikey = jnienv->NewStringUTF(key);
jnienv->CallStaticVoidMethod(utilsClass,mid, jnikey);
jnienv->DeleteLocalRef(jnikey);
}
// console
void __console_log(const v8::FunctionCallbackInfo<v8::Value>& args) {
String::Utf8Value _str_msg(args[0]->ToString());
const GLchar *msg = *_str_msg;
LOGI("JS.console: %s",msg);
}
// audio
// op - LOAD,PLAY,PAUSE (int)
// assetname - String
// loop - boolean
// id - int
void __audio_handle(const v8::FunctionCallbackInfo<v8::Value>& args) {
int op = (int)args[0]->IntegerValue();
String::Utf8Value _str_assetname(args[1]->ToString());
const char *assetname = *_str_assetname;
int loop = (int)args[2]->IntegerValue();
int id = (int)args[3]->IntegerValue();
//LOGI("audio handle %d %s %d %d",op,assetname,loop,id);
// call method:
//static void handleAudio(int, java.lang.String, boolean, int);
//Signature: (ILjava/lang/String;ZI)V
jmethodID mid = jnienv->GetStaticMethodID(utilsClass, "handleAudio",
"(ILjava/lang/String;ZI)V");
jstring jniassetname = jnienv->NewStringUTF(assetname);
jnienv->CallStaticVoidMethod(utilsClass,mid, (jint)op,jniassetname,
(jboolean)loop, (jint)id);
jnienv->DeleteLocalRef(jniassetname);
}
// gl
// internal functions used by glbinding
#define UNIFORMINT 0
#define UNIFORMFLOAT 1
#define UNIFORMMATRIXFLOAT 2
// vecsize: 1,2,3,4 (for matrices: 2,3,4)
// type: 0 = integer 1 = float 2 = float matrix
// transpose: only relevant for matrices
// uniform:
// args[0]: location
// args[1]: data array (floats or ints)
// uniformmatrix:
// args[0]: location
// args[1]: transpose
// args[2]: data array (floats)
void __uniformv(const v8::FunctionCallbackInfo<v8::Value>& args,int vecsize,
int type) {
HandleScope handle_scope(js->isolate);
GLint location = (unsigned int)args[0]->IntegerValue();
GLboolean transpose=false;
int dataidx = 1;
if (type==UNIFORMMATRIXFLOAT) {
transpose = args[1]->BooleanValue();
dataidx = 2;
}
GLsizei count;
int32_t *data;
//https://github.com/inh3/node-threads/blob/master/src/node-threads/web-worker.cc
if (args[dataidx]->IsArrayBufferView() || args[dataidx]->IsArrayBuffer()) {
// typed array
v8::Handle<v8::ArrayBufferView> bufview_data = Handle<ArrayBufferView>::Cast(args[dataidx]);
v8::Handle<v8::ArrayBuffer> buf_data = bufview_data->Buffer();
v8::ArrayBuffer::Contents con_data=buf_data->GetData();
count = con_data.ByteLength() / 4; // should always be multiple of 4
data = (int32_t *)con_data.Data();
} else if (args[dataidx]->IsArray()) {
// regular array
v8::Handle<v8::Array> array_data = Handle<Array>::Cast(args[dataidx]);
count = array_data->Length();
data = (int32_t *)malloc(count * 4); // float and int32 both 4 bytes
if (type==UNIFORMINT) {
int32_t *data_p = data;
for (int i=0; i<count; i++) {
v8::Handle<v8::Value> value = array_data->Get(i);
*data_p = value->Int32Value();
data_p++;
}
} else { // UNIFORMFLOAT, UNIFORMMATRIXFLOAT
GLfloat *data_p = (GLfloat *)data;
for (int i=0; i<count; i++) {
v8::Handle<v8::Value> value = array_data->Get(i);
*data_p = (GLfloat)value->NumberValue();
//LOGI("### GOT VAL: %f",*data_p);
data_p++;
}
}
}
//LOGI("#### Entered Uniformv %d,%d /%d,%d",vecsize, type, location, count);
//GLfloat *dataf = (GLfloat *)data;
//LOGI("### data val: %f %f %f %f",dataf[0],dataf[1],dataf[2],dataf[3]);
switch (type + 3*vecsize) {
case UNIFORMINT+1*3:
glUniform1iv(location, count, data);
break;
case UNIFORMINT+2*3:
glUniform2iv(location, count/2, data);
break;
case UNIFORMINT+3*3:
glUniform3iv(location, count/3, data);
break;
case UNIFORMINT+4*3:
glUniform4iv(location, count/4, data);
break;
case UNIFORMFLOAT+1*3:
glUniform1fv(location, count, (const GLfloat *)data);
break;
case UNIFORMFLOAT+2*3:
glUniform2fv(location, count/2, (const GLfloat *)data);
break;
case UNIFORMFLOAT+3*3:
glUniform3fv(location, count/3, (const GLfloat *)data);
break;
case UNIFORMFLOAT+4*3:
glUniform4fv(location, count/4, (const GLfloat *)data);
//LOGI("### data val: %f %f %f %f",dataf[0],dataf[1],dataf[2],dataf[3]);
break;
case UNIFORMMATRIXFLOAT+2*3:
glUniformMatrix2fv(location, count/(2*2), transpose,
(const GLfloat *)data);
break;
case UNIFORMMATRIXFLOAT+3*3:
glUniformMatrix3fv(location, count/(3*3), transpose,
(const GLfloat *)data);
break;
case UNIFORMMATRIXFLOAT+4*3:
glUniformMatrix4fv(location, count/(4*4), transpose,
(const GLfloat *)data);
break;
default:
LOGI("uniformv error: illegal type combination %d,%d",type,vecsize);
}
}
// read generated bindings
#include "gluegen/glbindings.h"
// manually coded functions
void __createBuffer(const v8::FunctionCallbackInfo<v8::Value>& args) {
GLuint buffers[1];
glGenBuffers(1,buffers);
args.GetReturnValue().Set(v8::Integer::New(args.GetIsolate(), buffers[0]));
}
void __createRenderbuffer(const v8::FunctionCallbackInfo<v8::Value>& args) {
GLuint buffers[1];
glGenFramebuffers(1,buffers);
args.GetReturnValue().Set(v8::Integer::New(args.GetIsolate(), buffers[0]));
}
void __createFramebuffer(const v8::FunctionCallbackInfo<v8::Value>& args) {
GLuint buffers[1];
glGenFramebuffers(1,buffers);
args.GetReturnValue().Set(v8::Integer::New(args.GetIsolate(), buffers[0]));
}
void __createTexture(const v8::FunctionCallbackInfo<v8::Value>& args) {
GLuint textures[1];
glGenTextures(1,textures);
args.GetReturnValue().Set(v8::Integer::New(args.GetIsolate(), textures[0]));
}
void __getProgramParameter(const v8::FunctionCallbackInfo<v8::Value>& args) {
int param[1];
GLuint program = (GLuint)args[0]->IntegerValue();
GLenum pname = (GLenum)args[1]->IntegerValue();
glGetShaderiv(program,pname,param);
args.GetReturnValue().Set(v8::Integer::New(args.GetIsolate(), param[0]));
}
void __getShaderParameter(const v8::FunctionCallbackInfo<v8::Value>& args) {
int param[1];
GLuint shader = (GLuint)args[0]->IntegerValue();
GLenum pname = (GLenum)args[1]->IntegerValue();
glGetShaderiv(shader,pname,param);
args.GetReturnValue().Set(v8::Integer::New(args.GetIsolate(), param[0]));
}
void __getProgramInfoLog(const v8::FunctionCallbackInfo<v8::Value>& args) {
GLuint program = (GLuint)args[0]->IntegerValue();
int length[1];
GLchar infolog[256];
// we can use glGetProgramiv to get the precise length of the string
// beforehand
glGetShaderInfoLog(program,256,length,infolog);
args.GetReturnValue().Set(v8::String::NewFromUtf8(args.GetIsolate(),
infolog));
}
void __getShaderInfoLog(const v8::FunctionCallbackInfo<v8::Value>& args) {
GLuint shader = (GLuint)args[0]->IntegerValue();
int length[1];
GLchar infolog[256];
// we can use glGetShaderiv to get the precise length of the string
// beforehand
glGetShaderInfoLog(shader,256,length,infolog);
args.GetReturnValue().Set(v8::String::NewFromUtf8(args.GetIsolate(),
infolog));
}
// Trilingual binding JS -> C++ -> Java.
//jni docs:
//http://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html
// We use Java's texImage2D because it parses pngs and jpgs properly.
// No NDK equivalent exists.
// We use GLUtils, which provides (amongst others):
// texImage2D(target,level,image,border);
// We use defaults for format, internalformat, type.
void __texImage2D(const v8::FunctionCallbackInfo<v8::Value>& args) {
// call method:
// (get signature with javap -s [classfile])
// static void Test()
//jmethodID mid = jnienv->GetStaticMethodID(utilsClass, "Test", "()V");
//jnienv->CallStaticVoidMethod(utilsClass,mid);
// call method:
// static void texImage2D(int target,int level,byte [] data,int border)
jmethodID mid = jnienv->GetStaticMethodID(utilsClass, "texImage2D",
"(II[BI)[I");
// get js parameters
int target = (int)args[0]->Int32Value();
int level = (int)args[1]->Int32Value();
if (args.Length()>=8) {
// long version: texImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, ArrayBufferView? pixels)
GLenum internalformat = (int)args[2]->Int32Value();
GLsizei width = (int)args[3]->Int32Value();
GLsizei height = (int)args[4]->Int32Value();
GLint border = (int)args[5]->Int32Value();
GLenum format = (int)args[6]->Int32Value();
GLenum type = (int)args[7]->Int32Value();
// data may be null in the long version, in which case an empty image
// is created
GLvoid *pixels;
if (args.Length()>8 && !(args[8]->IsNull())) {
// TODO get pixels from ArrayBufferView
} else {
// clear buffer. WebGL apparently expects the render texture to be
// empty, while Opengl will have garbage in the buffer when not
// explicity cleared
pixels = (void *)calloc(4,width*height);
}
glTexImage2D(target,level,internalformat,width,height,border,format,
type,pixels);
}
// short version:texImage2D(target,level,format,internalformat,type,image);
// Not sure if border parameter is supported
// and where it should go.
String::Utf8Value _str_assetname(args[5]->ToString());
const char *assetname = *_str_assetname;
// read asset. XXX move this to Java
char *imagedata;
int imagedatalen = readAsset(assetname,&imagedata);
// convert parameters to java
jbyteArray jBuff = jnienv->NewByteArray(imagedatalen);
jnienv->SetByteArrayRegion(jBuff, 0, imagedatalen, (jbyte*) imagedata);
// docs for byte array functions:
//jbyteArray NewByteArray(JNIEnv *env, jsize length);
//void ReleaseByteArrayElements(JNIEnv *env, jbyteArray array, jbyte *elems, jint mode);
//void GetByteArrayRegion(JNIEnv *env, jbyteArray array, jsize start, jsize len, jbyte *buf);
//void SetByteArrayRegion(JNIEnv *env, jbyteArray array, jsize start, jsize len, jbyte *buf);
jintArray retval_j = (jintArray) jnienv->CallStaticObjectMethod(
utilsClass,mid, (jint)target, (jint)level, jBuff, (jint)0);
//http://www.rgagnon.com/javadetails/java-0287.html
jint *retval = jnienv->GetIntArrayElements(retval_j, 0);
int retwidth = retval[0];
int retheight = retval[1];
jnienv->ReleaseIntArrayElements(retval_j, retval, 0);//XXX use JNI_ABORT
jnienv->DeleteLocalRef(retval_j);
jnienv->DeleteLocalRef(jBuff);
// XXX return value no longer used!
// return width, height
// from: https://v8.googlecode.com/svn/trunk/test/cctest/test-api.cc
v8::Handle<v8::Array> jsretval =
v8::Array::New(args.GetIsolate(), 2);
jsretval->Set(0, v8::Integer::New(args.GetIsolate(), retwidth));
jsretval->Set(1, v8::Integer::New(args.GetIsolate(), retheight));
args.GetReturnValue().Set(jsretval);
}
void __getImageDimensions(const v8::FunctionCallbackInfo<v8::Value>& args) {
String::Utf8Value _str_assetname(args[0]->ToString());
const char *assetname = *_str_assetname;
jstring jniassetname = jnienv->NewStringUTF(assetname);
jmethodID mid = jnienv->GetStaticMethodID(utilsClass, "getImageDimensions",
"(Ljava/lang/String;)[I");
jintArray retval_j = (jintArray) jnienv->CallStaticObjectMethod(
utilsClass, mid, jniassetname);
//http://www.rgagnon.com/javadetails/java-0287.html
jint *retval = jnienv->GetIntArrayElements(retval_j, 0);
int retwidth = retval[0];
int retheight = retval[1];
jnienv->ReleaseIntArrayElements(retval_j, retval, 0);//XXX use JNI_ABORT
jnienv->DeleteLocalRef(retval_j);
jnienv->DeleteLocalRef(jniassetname);
// return width, height
// from: https://v8.googlecode.com/svn/trunk/test/cctest/test-api.cc
v8::Handle<v8::Array> jsretval =
v8::Array::New(args.GetIsolate(), 2);
jsretval->Set(0, v8::Integer::New(args.GetIsolate(), retwidth));
jsretval->Set(1, v8::Integer::New(args.GetIsolate(), retheight));
args.GetReturnValue().Set(jsretval);
}
void __getWindowWidth(const v8::FunctionCallbackInfo<v8::Value>& args) {
args.GetReturnValue().Set(v8::Integer::New(args.GetIsolate(),
screenwidth));
}
void __getWindowHeight(const v8::FunctionCallbackInfo<v8::Value>& args) {
args.GetReturnValue().Set(v8::Integer::New(args.GetIsolate(),
screenheight));
}
JS::JS() {
isolate = Isolate::New();
Isolate::Scope isolate_scope(isolate);
// start local scope
HandleScope handlescope(isolate);
// set up global template
v8::Handle<v8::ObjectTemplate> global = ObjectTemplate::New(isolate);
v8::Handle<v8::ObjectTemplate> _gl = v8::ObjectTemplate::New(isolate);
v8::Handle<v8::ObjectTemplate> _audio = v8::ObjectTemplate::New(isolate);
v8::Handle<v8::ObjectTemplate> _utils = v8::ObjectTemplate::New(isolate);
v8::Handle<v8::ObjectTemplate> console = v8::ObjectTemplate::New(isolate);
v8::Handle<v8::ObjectTemplate> storage = v8::ObjectTemplate::New(isolate);
v8::Handle<v8::ObjectTemplate> payment = v8::ObjectTemplate::New(isolate);
global->Set(v8::String::NewFromUtf8(isolate, "_gl"), _gl);
global->Set(v8::String::NewFromUtf8(isolate, "_audio"), _audio);
global->Set(v8::String::NewFromUtf8(isolate, "_utils"), _utils);
global->Set(v8::String::NewFromUtf8(isolate, "console"), console);
global->Set(v8::String::NewFromUtf8(isolate, "localStorage"), storage);
global->Set(v8::String::NewFromUtf8(isolate, "_paymentSystem"), payment);
payment->Set(v8::String::NewFromUtf8(isolate, "init"),
v8::FunctionTemplate::New(isolate, __paymentSystem_init));
payment->Set(v8::String::NewFromUtf8(isolate, "getType"),
v8::FunctionTemplate::New(isolate, __paymentSystem_getType));
payment->Set(v8::String::NewFromUtf8(isolate, "exit"),
v8::FunctionTemplate::New(isolate, __paymentSystem_exit));
payment->Set(v8::String::NewFromUtf8(isolate, "requestPayment"),
v8::FunctionTemplate::New(isolate, __paymentSystem_requestPayment));
payment->Set(v8::String::NewFromUtf8(isolate, "checkReceipt"),
v8::FunctionTemplate::New(isolate, __paymentSystem_checkReceipt));
storage->Set(v8::String::NewFromUtf8(isolate, "getItem"),
v8::FunctionTemplate::New(isolate, __localStorage_getItem));
storage->Set(v8::String::NewFromUtf8(isolate, "setItem"),
v8::FunctionTemplate::New(isolate, __localStorage_setItem));
storage->Set(v8::String::NewFromUtf8(isolate, "removeItem"),
v8::FunctionTemplate::New(isolate, __localStorage_removeItem));
console->Set(v8::String::NewFromUtf8(isolate, "log"),
v8::FunctionTemplate::New(isolate, __console_log));
_utils->Set(v8::String::NewFromUtf8(isolate, "loadStringAsset"),
v8::FunctionTemplate::New(isolate, __utils_loadStringAsset));
_utils->Set(v8::String::NewFromUtf8(isolate, "execScript"),
v8::FunctionTemplate::New(isolate, __utils_execScript));
_utils->Set(v8::String::NewFromUtf8(isolate, "getGamepadValues"),
v8::FunctionTemplate::New(isolate, __utils_getGamepadValues));
_audio->Set(v8::String::NewFromUtf8(isolate, "handle"),
v8::FunctionTemplate::New(isolate, __audio_handle));
_gl->Set(v8::String::NewFromUtf8(isolate, "createRenderbuffer"),
v8::FunctionTemplate::New(isolate, __createRenderbuffer));
_gl->Set(v8::String::NewFromUtf8(isolate, "createFramebuffer"),
v8::FunctionTemplate::New(isolate, __createFramebuffer));
_gl->Set(v8::String::NewFromUtf8(isolate, "createBuffer"),
v8::FunctionTemplate::New(isolate, __createBuffer));
_gl->Set(v8::String::NewFromUtf8(isolate, "createTexture"),
v8::FunctionTemplate::New(isolate, __createTexture));
_gl->Set(v8::String::NewFromUtf8(isolate, "getProgramParameter"),
v8::FunctionTemplate::New(isolate, __getProgramParameter));
_gl->Set(v8::String::NewFromUtf8(isolate, "getShaderParameter"),
v8::FunctionTemplate::New(isolate, __getShaderParameter));
_gl->Set(v8::String::NewFromUtf8(isolate, "getProgramInfoLog"),
v8::FunctionTemplate::New(isolate, __getProgramInfoLog));
_gl->Set(v8::String::NewFromUtf8(isolate, "getShaderInfoLog"),
v8::FunctionTemplate::New(isolate, __getShaderInfoLog));
// the "raw" function takes an asset location string.
// html5.js provides a wrapper that takes Image
_gl->Set(v8::String::NewFromUtf8(isolate, "_texImage2D"),
v8::FunctionTemplate::New(isolate, __texImage2D));
_gl->Set(v8::String::NewFromUtf8(isolate, "_getImageDimensions"),
v8::FunctionTemplate::New(isolate, __getImageDimensions));
_gl->Set(v8::String::NewFromUtf8(isolate, "_getWindowWidth"),
v8::FunctionTemplate::New(isolate, __getWindowWidth));
_gl->Set(v8::String::NewFromUtf8(isolate, "_getWindowHeight"),
v8::FunctionTemplate::New(isolate, __getWindowHeight));
#include "gluegen/glbindinit.h"
// create context
v8::Handle<Context> context_local = v8::Context::New(isolate, NULL, global);
context.Reset(isolate, context_local);
//Persistent<Context> *pc = new Persistent<Context>(isolate,context_local);
//context = new Persistent<Context>(isolate, context_local);
// make context current
//Context::Scope context_scope(context);
}
char *JS::run_javascript(char *sourcestr) {
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
// we have to create a local handle from the persistent handle
// every time, see process.cc example
v8::Handle<Context> context_local =
v8::Local<v8::Context>::New(isolate, context);
Context::Scope context_scope(context_local);
// Compile and run the script
TryCatch try_catch;
Handle<String> source = String::NewFromUtf8(isolate, sourcestr);
Handle<Script> script = Script::Compile(source);
Handle<Value> result = script->Run();
if (result.IsEmpty()) {
String::Utf8Value error(try_catch.Exception());
String::Utf8Value stacktrace(try_catch.StackTrace());
LOGI("Error compiling script: %s:\n%s",*error, *stacktrace);
return strdup("(error)");
} else {
// Convert the result to an UTF8 string
String::Utf8Value utf8(result);
char *ret = *utf8;
//LOGI("V8 says: %s",ret);
// example has bug: ret must be malloced before returning it
return strdup(ret);
}
}
void JS::callFunction(const char *funcname,const int argc,Handle<Value> argv[]){
// init
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
// we have to create a local handle from the persistent handle
// every time, see process.cc example
v8::Handle<Context> context_local =
v8::Local<v8::Context>::New(isolate, context);
Context::Scope context_scope(context_local);
// get function
Handle<String> jsfunc_name = String::NewFromUtf8(isolate,funcname);
Handle<Value> jsfunc_val = context_local->Global()->Get(jsfunc_name);
if (!jsfunc_val->IsFunction()) return;
Handle<Function> jsfunc = Handle<Function>::Cast(jsfunc_val);
// call function, 'this' points to global object
TryCatch try_catch;
Handle<Value> result=jsfunc->Call(context_local->Global(), argc, argv);
if (result.IsEmpty()) {
String::Utf8Value error(try_catch.Exception());
String::Utf8Value stacktrace(try_catch.StackTrace());
LOGI("Error calling %s: %s:\n%s",funcname,*error,*stacktrace);
} else {
//LOGI("%s called",funcname);
}
}
// -----------------------------------------------
// JS handling
// -----------------------------------------------
// output must be freed using free()
long readAsset(const char *filename, char **output) {
LOGI("readAsset %s",filename);
jmethodID mid = jnienv->GetStaticMethodID(utilsClass, "readAsset",
"(Ljava/lang/String;)[B");
jstring jAssetName = jnienv->NewStringUTF(filename);
jbyteArray retval_j = (jbyteArray)
jnienv->CallStaticObjectMethod(utilsClass, mid, jAssetName);
jbyte* retval = jnienv->GetByteArrayElements(retval_j, 0);
long retval_len = jnienv->GetArrayLength(retval_j);
// allocate one zero guard byte to ensure strings are terminated
char* buffer = (char*) calloc (sizeof(char)*(retval_len+1),1);
memcpy(buffer,retval,retval_len);
jnienv->ReleaseByteArrayElements(retval_j, retval, JNI_ABORT);
jnienv->DeleteLocalRef(jAssetName);
jnienv->DeleteLocalRef(retval_j);
*output = buffer;
return retval_len;
}
// init javascript engine
static int init_javascript() {
js = new JS();
V8::SetArrayBufferAllocator(new MallocArrayBufferAllocator());
}
// boot JS and pass window dimensions
static int boot_javascript(int w,int h) {
// execute init scripts on context
char *source1;
// html5 sets up the html5 API and loads the JS
readAsset("html5.js",&source1);
char *ret1 = js->run_javascript(source1);
LOGI("HTML5 bootloader returned: %s",ret1);
// pass width/height to JS
Isolate::Scope isolate_scope(js->isolate);
HandleScope handle_scope(js->isolate);
Handle<Value> js_width = v8::Integer::New(js->isolate, w);
Handle<Value> js_height = v8::Integer::New(js->isolate, h);
const int argc1 = 2;
Handle<Value> argv1[argc1] = { js_width, js_height };
js->callFunction("_documentLoaded",argc1,argv1);
}
/**
* Just the current frame in the display.
*/
static void engine_draw_frame() {
// call drawFrame in JS
const int argc = 0;
Handle<Value> argv[argc] = { };
js->callFunction("_GLDrawFrame",argc,argv);
}
// jni interface
jint JNI_OnLoad(JavaVM* vm, void* reserved) {
JNIEnv* env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
return -1;
}
// Get jclass with env->FindClass.
// Register methods with env->RegisterNatives.
return JNI_VERSION_1_6;
}
#ifdef __cplusplus
extern "C" {
#endif
/* This does double duty as both the init and displaychanged function.
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_tmtg_glesjs_GlesJSLib_onSurfaceChanged
(JNIEnv *env, jclass clas, jint width, jint height) {
LOGI("JNI onSurfaceChanged");
jnienv = env;
utilsClass = jnienv->FindClass("net/tmtg/glesjs/GlesJSUtils");
if (!app_was_inited) {
init_javascript();
for (int i=0; i<NR_PLAYERS*PLAYERDATASIZE; i++) gamepadvalues[i] = 0;
}
screenwidth = width;
screenheight = height;
if (!app_was_inited) {
boot_javascript(width,height);
app_was_inited=true;
}
}
/*
* Class: net_tmtg_glesjs_GlesJSLib
* Method: onDrawFrame
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_net_tmtg_glesjs_GlesJSLib_onDrawFrame
(JNIEnv *env, jclass clas) {
//LOGI("JNI onDrawFrame");
jnienv = env;
utilsClass = jnienv->FindClass("net/tmtg/glesjs/GlesJSUtils");
engine_draw_frame();
}
/*
* Class: net_tmtg_glesjs_GlesJSLib
* Method: onTouchEvent
* Signature: (DDZZZ)V
*/
// NOTE: must be called from the render thread. Multiple threads accessing
// isolate will cause crash.
JNIEXPORT void JNICALL Java_net_tmtg_glesjs_GlesJSLib_onTouchEvent
(JNIEnv *env, jclass clas, jint ptrid, jdouble x, jdouble y,
jboolean press, jboolean release) {
//LOGI("JNI onTouchEvent");
Isolate::Scope isolate_scope(js->isolate);
HandleScope handle_scope(js->isolate);
if (!app_was_inited) return;
jnienv = env;
// pass new coords before passing up/down
// pass coords to JS
Handle<Value> js_ptrid = v8::Integer::New(js->isolate, ptrid);
Handle<Value> js_x = v8::Integer::New(js->isolate, x);
Handle<Value> js_y = v8::Integer::New(js->isolate, y);
const int argc3 = 3;
Handle<Value> argv3[argc3] = { js_ptrid, js_x, js_y };
js->callFunction("_mouseMoveCallback",argc3,argv3);
if (press) {
// start touch
// pass event to JS
const int argc1 = 1;
Handle<Value> argv1[argc1] = { js_ptrid };
js->callFunction("_mouseDownCallback",argc1,argv1);
}
if (release) {
// end touch
// pass event to JS
const int argc2 = 1;
Handle<Value> argv2[argc2] = { js_ptrid };
js->callFunction("_mouseUpCallback",argc2,argv2);
}
}
/*
* Class: net_tmtg_glesjs_GlesJSLib
* Method: onMultitouchCoordinates
* Signature: (IDD)V
*/
JNIEXPORT void JNICALL Java_net_tmtg_glesjs_GlesJSLib_onMultitouchCoordinates
(JNIEnv * env, jclass clas, jint ptrid, jdouble x, jdouble y) {
//LOGI("JNI MultitouchCoordinates");
Isolate::Scope isolate_scope(js->isolate);
HandleScope handle_scope(js->isolate);
if (!app_was_inited) return;
jnienv = env;
// pass coords to JS
Handle<Value> js_ptrid = v8::Integer::New(js->isolate, ptrid);
Handle<Value> js_x = v8::Integer::New(js->isolate, x);
Handle<Value> js_y = v8::Integer::New(js->isolate, y);
const int argc = 3;
Handle<Value> argv[argc] = { js_ptrid, js_x, js_y };
js->callFunction("_touchCoordinatesCallback",argc,argv);
}
/*
* Class: net_tmtg_glesjs_GlesJSLib
* Method: onControllerEvent
* Signature: (IZ[I[F)V
*/
JNIEXPORT void JNICALL Java_net_tmtg_glesjs_GlesJSLib_onControllerEvent
(JNIEnv *env, jclass clas, jint player, jboolean active,
jbooleanArray buttons, jfloatArray axes) {
//LOGI("Controller event %d %d",player,active);
//if (!app_was_inited) return;
jnienv = env;
// store active value
gamepadvalues[PLAYERDATASIZE*player] = active ? 1 : 0;
if (active) {
// if active, store button and axes values
jboolean* buttonsval = jnienv->GetBooleanArrayElements(buttons, 0);
long buttonslen = jnienv->GetArrayLength(buttons);
jfloat* axesval = jnienv->GetFloatArrayElements(axes, 0);
long axeslen = jnienv->GetArrayLength(axes);
//LOGI("######## %ld %ld",buttonslen,axeslen);
for (int i=0; i<buttonslen; i++)
gamepadvalues[PLAYERDATASIZE*player + 1 + i] = buttonsval[i];
for (int i=0; i<axeslen; i++)
gamepadvalues[PLAYERDATASIZE*player + 1+NR_BUTTONS+i] = axesval[i];
jnienv->ReleaseBooleanArrayElements(buttons, buttonsval, JNI_ABORT);
jnienv->ReleaseFloatArrayElements(axes, axesval, JNI_ABORT);
//jnienv->DeleteLocalRef(buttons);
//jnienv->DeleteLocalRef(axes);
}
// if not active, values are null, keep old values
}
#ifdef __cplusplus
}
#endif
//END_INCLUDE(all)
<file_sep>/make-update.sh
android update project --name GlesJSDemo --target android-14 --path .
<file_sep>/src/net/tmtg/glesjs/GlesJSLib.java
// Copyright (c) 2014 by <NAME>, <EMAIL>
package net.tmtg.glesjs;
public class GlesJSLib {
static {
System.loadLibrary("glesjs");
}
public static native void onSurfaceChanged(int width, int height);
public static native void onDrawFrame();
public static native void onTouchEvent(int id,double x,double y,
boolean press,boolean release);
public static native void onMultitouchCoordinates(int id,double x,double y);
public static native void onControllerEvent(int player,boolean active,
boolean [] buttons, float [] axes);
}
<file_sep>/examples/webVR-pano/README.md
# 🛠 webVR example (TBA)
### demostrates...
* load image resources
* use webVR api to get sensor input
* split screen rendering
# 🛠 References
* [webVR spec](https://webvr.info/)
* [twgl.js library](http://twgljs.org)
* [gles.js library](https://github.com/borisvanschooten/glesjs)<file_sep>/jni/include/v8-hacks.h
#define OPEN_HANDLE_LIST(V) \
V(Template, TemplateInfo) \
V(FunctionTemplate, FunctionTemplateInfo) \
V(ObjectTemplate, ObjectTemplateInfo) \
V(Signature, SignatureInfo) \
V(AccessorSignature, FunctionTemplateInfo) \
V(TypeSwitch, TypeSwitchInfo) \
V(Data, Object) \
V(RegExp, JSRegExp) \
V(Object, JSObject) \
V(Array, JSArray) \
V(ArrayBuffer, JSArrayBuffer) \
V(ArrayBufferView, JSArrayBufferView) \
V(TypedArray, JSTypedArray) \
V(Uint8Array, JSTypedArray) \
V(Uint8ClampedArray, JSTypedArray) \
V(Int8Array, JSTypedArray) \
V(Uint16Array, JSTypedArray) \
V(Int16Array, JSTypedArray) \
V(Uint32Array, JSTypedArray) \
V(Int32Array, JSTypedArray) \
V(Float32Array, JSTypedArray) \
V(Float64Array, JSTypedArray) \
V(DataView, JSDataView) \
V(String, String) \
V(Symbol, Symbol) \
V(Script, JSFunction) \
V(UnboundScript, SharedFunctionInfo) \
V(Function, JSFunction) \
V(Message, JSMessageObject) \
V(Context, Context) \
V(External, Object) \
V(StackTrace, JSArray) \
V(StackFrame, JSObject) \
V(DeclaredAccessorDescriptor, DeclaredAccessorDescriptor)
#define DECLARE_OPEN_HANDLE(From, To) \
static inline v8::internal::Handle<v8::internal::To> \
OpenHandle(const From* that, bool allow_empty_handle = false);
OPEN_HANDLE_LIST(DECLARE_OPEN_HANDLE)
#undef DECLARE_OPEN_HANDLE
// Implementations of OpenHandle
#define MAKE_OPEN_HANDLE(From, To) \
v8::internal::Handle<v8::internal::To> Utils::OpenHandle( \
const v8::From* that, bool allow_empty_handle) { \
EXTRA_CHECK(allow_empty_handle || that != NULL); \
EXTRA_CHECK(that == NULL || \
(*reinterpret_cast<v8::internal::Object**>( \
const_cast<v8::From*>(that)))->Is##To()); \
return v8::internal::Handle<v8::internal::To>( \
reinterpret_cast<v8::internal::To**>(const_cast<v8::From*>(that))); \
}
OPEN_HANDLE_LIST(MAKE_OPEN_HANDLE)
#undef MAKE_OPEN_HANDLE
#undef OPEN_HANDLE_LIST
<file_sep>/examples/pixi/README.md
# 🛠 pixi example
### demostrates...
* pixi library
* loading resources
# 🛠 References
* [pixi.js library](http://www.pixijs.com)
| 1a6750f4356be1023db1b142579266480bc9a55b | [
"Markdown",
"Makefile",
"Java",
"C",
"C++",
"Shell"
] | 11 | Makefile | wallabyway/glesjs | 8b1df7882ad89aeaba85ef46ecddf67851bd2168 | 1b5675d073309df1ff17272cee416c57438fd0b3 | |
refs/heads/master | <file_sep>var router = require('express').Router();
const db = require('../models/index').sequelize;
const Products = db.model('store_inventory');
router.get('/', function(req, res){
// var limit = getQueryVariable('limit')
const limit = req.query
console.log("?limit=20", req.query)
Products.findAll(limit).then(
function findAllSuccess(data){
res.json(data)
},
function findAllError(err){
res.send(500, err.message)
}
)
})
module.exports = router;
<file_sep>module.exports = (app) => {
app.use('/api/auth', require('./accountUser'));
app.use('/api/purchase', require('./memberPurchase'));
app.use('/api/allProducts', require('./allProducts'));
} | b4e73c6f5809e8a8d1651b24a5843ffee223b6be | [
"JavaScript"
] | 2 | JavaScript | Thomas-Flynn/JS-1150-Redbadge-Challenge | 1570785be4cee0d647910fcc89a36df11c0d6779 | 0dc26f695f606a5a84592704bd7396fc99168cac | |
refs/heads/master | <file_sep>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QAction>
#include <QString>
#include <QFileDialog>
#include <QMessageBox>
#include <boost/filesystem.hpp>
#include <set>
#include <fstream>
#include <sstream>
#include <string>
#include <QString>
#include <unistd.h>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time.hpp>
#include <QDesktopServices>
#include <QFontComboBox>
#include <QFont>
#include <QDragEnterEvent>
using namespace boost::filesystem;
using namespace std;
using namespace boost::posix_time;
using namespace boost::gregorian;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
saved(0),
ui(new Ui::MainWindow)
{
::system("cd ~ && pwd >> /tmp/filepath");
ifstream pa("/tmp/filepath");
pa >> path;
path = path + "/mysite/source/_posts";
set<string> vec;
directory_iterator end; //迭代器返回的对象是directory_entry
for(directory_iterator pos(path); pos != end; pos++)
{
ifstream in(pos->path().c_str());
string tmp;
getline(in, tmp);
getline(in, tmp);
in >> tmp;
tmp.clear();
in >> tmp;
vec.insert(tmp);
in.close();
}
ui->setupUi(this);
ui->lineEdit_2->setVisible(0);
for(set<string>::iterator i = vec.begin(); i != vec.end(); i++)
{
ui->comboBox->addItem((*i).c_str());
}
ui->comboBox->addItem("新建类别");
connect((ui->action_2), SIGNAL(triggered()), this, SLOT(openfile()));
connect((ui->action_3), SIGNAL(triggered()), this, SLOT(pushfile()));
connect((ui->comboBox), SIGNAL(currentIndexChanged(int)), this, SLOT(changecata()));
connect((ui->Baocun), SIGNAL(triggered()), this, SLOT(savefile()));
connect((ui->action), SIGNAL(triggered()), this, SLOT(newfile()));
connect((ui->pushButton), SIGNAL(clicked()), this, SLOT(newfile()));
connect((ui->pushButton_2), SIGNAL(clicked()), this, SLOT(openfile()));
connect((ui->pushButton_3), SIGNAL(clicked()), this, SLOT(savefile()));
connect((ui->pushButton_4), SIGNAL(clicked()), this, SLOT(pushfile()));
connect((ui->pushButton_5), SIGNAL(clicked()), this, SLOT(openblog()));
changecata();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::openfile()
{
QString path = QFileDialog::getOpenFileName(this, tr("Open paper"), this->path.c_str(), tr("text Files (*.md)"));
if(path.length() == 0)
{
QMessageBox::information(NULL, tr("Path"), tr("You didn't select any files."));
}
else
{
//QMessageBox::information(NULL, tr("Path"), tr("You selected ") + path);
string temp;
ifstream in(path.toStdString().c_str());
getline(in, temp);istringstream str(temp);
str >> temp;temp = str.get();
getline(str, temp);
ui->lineEdit->setText(QString::fromStdString(temp));
in >> temp;
in >> temp;
in >> temp;
temp = in.get();
getline(in, temp);
istringstream str2(temp);
str2 >> temp;temp = str2.get();
getline(str2, temp);
ui->comboBox->setCurrentText(QString::fromStdString(temp));
getline(in, temp);
in >> temp;
char *a = new char[100000];
//in.get(a,1,'\n');
in.get(a, 100000, EOF);
string tmp(a);
tmp.erase(0, 1);
ui->textEdit->setText(QString::fromStdString(tmp));
delete[] a;
}
}
void MainWindow::newfile()
{
ui->lineEdit->setText("");
ui->comboBox->setCurrentText("");
ui->textEdit->setHtml("");
}
void MainWindow::changecata()
{
if(ui->comboBox->currentText() == "新建类别")
{
ui->lineEdit_2->setHidden(0);
}
else
{
ui->lineEdit_2->setHidden(1);
}
}
void MainWindow::savefile()
{
ptime p = second_clock::local_time();
string tags;
if(ui->comboBox->currentText() == "新建类别")
{
tags = ui->lineEdit_2->text().toStdString();
ui->comboBox->addItem(ui->lineEdit_2->text());
}
else
{
tags = ui->comboBox->currentText().toStdString();
}
string tmp = path.c_str() + string("/") + (ui->lineEdit->text().toStdString()) + '-' + tags + ".md";
if(tags.length() != 0 && ui->lineEdit->text().length() != 0 && ui->textEdit->toPlainText().length() != 0)
{
ofstream out(tmp.c_str());
out << "title: " << (ui->lineEdit->text().toStdString()) << '\n' << "date: " << to_iso_extended_string(p.date()) << ' '
<< to_simple_string(p.time_of_day()) << '\n' << "categories: " << tags << endl << "tags: "
<< tags << endl << "---" << endl;
string tmp = (ui->textEdit->toPlainText().toStdString());
/*
for(int i = 0; i != tmp.length() - 3; i++)
{
if((tmp[i] != ' ' || tmp[i + 1] != ' ') && (tmp[i + 2] == '\n' && tmp[i + 3] != '\n'))
tmp.insert(i + 2, 2, ' ');
}
*/
while(tmp.find("file://") != string::npos)
{
string::size_type sib = tmp.find("file://");
string::size_type sie = sib;
for(; ((tmp[sie] != '\n') && (sie <= tmp.length() + 1)) ; sie++);
while(tmp[sie - 1] == ' ' ) {
sie--;
}
string pathtmp(tmp, sib + 7, sie - sib - 7);
boost::filesystem::path dirpath(pathtmp);
boost::filesystem::path endle(this->path);
endle = endle.parent_path() / "img" / dirpath.filename();
try
{
copy_file(pathtmp, endle);
}
catch(...) {}
string picture = ".string() + ")";
tmp.replace((tmp.begin() + sib), (tmp.begin() + sie), picture);
}
out << tmp;
out.close();
QMessageBox msgBox;
msgBox.setText("保存成功,喵~!");
msgBox.exec();
}
else
{
QMessageBox::information(NULL, tr("Path"), tr("请把所有信息填满再保存,笨喵~!"));
}
}
void MainWindow::pushfile()
{
system("source ~/.bash_profile && cd ~/mysite && hexo generate && hexo deploy");
QMessageBox *msgBox = new QMessageBox;
msgBox->setText("提交成功,喵~!");
msgBox->exec();
delete msgBox;
}
void MainWindow::openblog()
{
QDesktopServices::openUrl(QUrl("http://hebei1992.github.io/", QUrl::TolerantMode));
}
void MainWindow::savefilenoerror()
{
ptime p = second_clock::local_time();
string tags;
if(ui->comboBox->currentText() == "新建类别")
{
tags = ui->lineEdit_2->text().toStdString();
ui->comboBox->addItem(ui->lineEdit_2->text());
}
else
{
tags = ui->comboBox->currentText().toStdString();
}
string tmp = path.c_str() + string("/") + (ui->lineEdit->text().toStdString()) + '-' + tags + ".md";
if(tags.length() != 0 && ui->lineEdit->text().length() != 0 && ui->textEdit->toPlainText().length() != 0)
{
ofstream out(tmp.c_str());
out << "title: " << (ui->lineEdit->text().toStdString()) << '\n' << "date: " << to_iso_extended_string(p.date()) << ' '
<< to_simple_string(p.time_of_day()) << '\n' << "categories: " << tags << endl << "tags: "
<< tags << endl << "---" << endl;
string tmp = (ui->textEdit->toPlainText().toStdString());
for(int i = 0; i != tmp.length() - 3; i++)
{
if((tmp[i] != ' ' || tmp[i + 1] != ' ') && (tmp[i + 2] == '\n' && tmp[i + 3] != '\n'))
tmp.insert(i + 2, 2, ' ');
}
while(tmp.find("file://") != string::npos)
{
string::size_type sib = tmp.find("file://");
string::size_type sie = sib;
for(; (tmp[sie] != ' ' && tmp[sie] != '/n') && sie <= tmp.length() + 1 ; sie++);
string pathtmp(tmp, sib + 7, sie - sib - 7);
boost::filesystem::path dirpath(pathtmp);
boost::filesystem::path endle(this->path);
endle = endle.parent_path() / "img" / dirpath.filename();
try
{
copy_file(pathtmp, endle);
}
catch(...) {}
string picture = ".string() + ")";
tmp.replace((tmp.begin() + sib), (tmp.begin() + sie), picture);
}
out << tmp;
out.close();
QMessageBox msgBox;
msgBox.setText("保存成功,喵~!");
msgBox.exec();
}
}
<file_sep>####基于QT实现的一个静态页面推送程序
![[email protected]](/img/[email protected])
![[email protected]](/img/[email protected])
| 22c57b2b8f2a7f4b4a8e3fb5cea57a3edd2b500c | [
"Markdown",
"C++"
] | 2 | C++ | qdore/myblog | 3adc6be422edd9f6baa54873859fa0dc9be20fe0 | e514fbd2480bd355f3d2189a61706d3cf6f66529 | |
refs/heads/master | <repo_name>JoshuaTPereira/rescue-mission<file_sep>/app/controllers/answers_controller.rb
class AnswersController < ApplicationController
def create
@answer = Answer.new(answer_params)
@answer.write_attribute(:question_id, params[:question_id])
if @answer.save
redirect_to Question.find(params[:question_id])
else
flash.now[:errors] = @answer.errors.full_messages.join(', ⚠️').prepend('⚠️')
@question = Question.find(params[:question_id])
@answers = @question.answers
render :'questions/show'
end
end
def edit
@answer = Answer.find(params[:id])
end
def update
if params[:description]
@answer = Answer.find(params[:id])
@answer.description = answer_params[:description]
@question = @answer.question
if @answer.save
flash[:notice] = "Answer was successfully updated"
redirect_to @question
else
flash[:error] = @answer.errors.full_messages.join(', ')
render :edit
end
else
@answer = Answer.find(params[:id])
@question = @answer.question
@selected = Answer.where(question: @question).where(selected: true)
@selected.each do |select|
select.selected = false
select.save
end
@answer.selected = true
@answer.save
redirect_to @question
end
end
def destroy
@answer = Answer.find(params[:id])
@question = @answer.question
@answer.destroy
redirect_to @question
end
private
def answer_params
params.require(:answer).permit(:description)
end
end
<file_sep>/app/controllers/questions_controller.rb
class QuestionsController < ApplicationController
def index
@questions = Question.all
end
def show
@question = Question.find(params[:id])
@answers = @question.answers
selected = @answers.find_by(selected: true)
@answers = @answers.select do |answer|
answer.selected == false
end
# @answers.order(:created_at)
@answers.unshift(selected)
@answer = Answer.new
end
def new
@question = Question.new
end
def create
@question = Question.new(question_params)
if @question.save
redirect_to @question
else
flash.now[:errors] = @question.errors.full_messages.join(', ⚠️').prepend('⚠️')
render :new
end
end
def edit
@question = Question.find(params[:id])
end
def update
@question = Question.find(params[:id])
@question.update_attributes(question_params)
if @question.valid?
flash[:notice] = "Question was successfully updated"
redirect_to @question
else
flash[:error] = @question.errors.full_messages.join(', ')
render :edit
end
end
def destroy
@question = Question.find(params[:id])
@question.destroy
redirect_to '/'
end
private
def question_params
params.require(:question).permit(:title, :description)
end
end
| bb4048da6f72ac86d975514338e4d0ec9468ec68 | [
"Ruby"
] | 2 | Ruby | JoshuaTPereira/rescue-mission | 4f9a88f49af0277fb2a67c47701cdc86efe3be0d | 4c414b66d68b723bbae1b2cd3cedab07e46cd0fa | |
refs/heads/master | <repo_name>rithinsuryasainadh/Connect4<file_sep>/submitted_code/README.txt
# Connect4
NAME : <NAME>
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
UTA ID : 1001365726
------------------------------------------------------------------------------------------------------------------------------------------------------------------
LANUGUAGE : Python
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
INTRODUNCTION
-------------
As part of the assignment I have implemented minimax, alpha beta pruning and depth limited minimax for prediciting the next best move in connect4 game while playing against a human or a bot.
I have implemented the game in two modes which are interactive mode and one-move mode.
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
STRUCTURE OF THE CODE
---------------------
The game uses two python files called maxconnect4.py and MaxConnect4Game.py.
maxconnect4.py has all the functions related to setting up of the game like taking inputs from the user and setting up the board and calling the ai algorithms.
MaxConnect4Game.py has all the functions which involves implementing the above ai game algorithms and implementation of the evaluation function.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Algorithm Usage Instructions
----------------------------
All algorithm implementation is done in a method called aiPlay() between lines 270 and 272. Default it is using minimax with alphabeta pruning and other methods are commented. Other methods can be used by uncommenting.
-------------------------------------------------------------------------------------------------------------------
Sr No | Method | Operation |
1. | self.minimax() | Plain Minimax algorithm implemented |
2. | self.alpha_beta_decision | Minimax with alpha beta pruning |
3. | self.depth_limited_alpha_beta_pruning | Depth limited minimax with alpha beta pruning and specified depth |
-------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
GAME MODES
----------
Interactive Mode Syntax :
$python maxconnect4.py interactive input.txt computer-next/human-next depth
The above code will allow user to give his input and simulate the connect 4 game till all 42 moves are made and it will tell the final result as to who won and who lost.
One-move Mode Syntax :
$python maxconnect4.py one-move input_file output_file depth
The above code will predict the best possible next move and make the move given an input state.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Evaluation Function
-------------------
Partly implemented the evaluation function from what professor explained in class and partly I took the idea from the following link below which is CITED to implement the evaluation function
https://github.com/erikackermann/Connect-Four
Evaluation function for depth limited minimax is implemented to calculate the utility value.
Calculation of Utility Value from the evaluation function :
The higher the utility value then better is the decision of the computer in selecting the respective column.
First it checks for whether it can make a four, then it checks subsequently for threes and then twos. Similarly it checks for the highest possible four of the opponent and the formuala is given below :-
utility_value = (my_fours * 10 + my_threes * 5 + my_twos * 2)- (opp_fours *10 + opp_threes * 5 + opp_twos * 2).
After calculating all utility values, the highest value and the corresponding column mapped to it is selected and then the move is predicted.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
DEPTH VS TIME
-------------
An excel sheet named DepthVsTime has a table containing the time taken and the corresponding depth level. Time is calculated for the corresponding depth till time reaches 1 minute and then it is stopped.
After conducting the above experiment I could observe that time will cross 1 minute at depth 8 and beyond.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
COMPETITION
-----------
Yes I want to participate in the competition.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------<file_sep>/README.md
# Connect4
NAME : <NAME>
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
LANUGUAGE : Python
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
INTRODUNCTION
-------------
As part of the assignment I have implemented minimax, alpha beta pruning and depth limited minimax for prediciting the next best move in connect4 game while playing against a human or a bot.
I have implemented the game in two modes which are interactive mode and one-move mode.
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
STRUCTURE OF THE CODE
---------------------
The game uses two python files called maxconnect4.py and MaxConnect4Game.py.
maxconnect4.py has all the functions related to setting up of the game like taking inputs from the user and setting up the board and calling the ai algorithms.
MaxConnect4Game.py has all the functions which involves implementing the above ai game algorithms and implementation of the evaluation function.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Algorithm Usage Instructions
----------------------------
All algorithm implementation is done in a method called aiPlay() between lines 270 and 272. Default it is using minimax with alphabeta pruning and other methods are commented. Other methods can be used by uncommenting.
-------------------------------------------------------------------------------------------------------------------
Sr No | Method | Operation |
1. | self.minimax() | Plain Minimax algorithm implemented |
2. | self.alpha_beta_decision | Minimax with alpha beta pruning |
3. | self.depth_limited_alpha_beta_pruning | Depth limited minimax with alpha beta pruning and specified depth |
-------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
GAME MODES
----------
Interactive Mode Syntax :
$python maxconnect4.py interactive input.txt computer-next/human-next depth
The above code will allow user to give his input and simulate the connect 4 game till all 42 moves are made and it will tell the final result as to who won and who lost.
One-move Mode Syntax :
$python maxconnect4.py one-move input_file output_file depth
The above code will predict the best possible next move and make the move given an input state.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Evaluation Function
-------------------
Partly implemented the evaluation function from what professor explained in class and partly I took the idea from the following link below to implement the evaluation function
https://github.com/erikackermann/Connect-Four
Evaluation function for depth limited minimax is implemented to calculate the utility value.
Calculation of Utility Value from the evaluation function :
The higher the utility value then better is the decision of the computer in selecting the respective column.
First it checks for whether it can make a four, then it checks subsequently for threes and then twos. Similarly it checks for the highest possible four of the opponent and the formuala is given below :-
utility_value = (my_fours * 10 + my_threes * 5 + my_twos * 2)- (opp_fours *10 + opp_threes * 5 + opp_twos * 2).
After calculating all utility values, the highest value and the corresponding column mapped to it is selected and then the move is predicted.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
DEPTH VS TIME
-------------
An excel sheet named DepthVsTime has a table containing the time taken and the corresponding depth level. Time is calculated for the corresponding depth till time reaches 1 minute and then it is stopped.
After conducting the above experiment I could observe that time will cross 1 minute at depth 8 and beyond.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
<file_sep>/submitted_code/minimax.py
def minimax(self, current_node):
current_state = copy.deepcopy(current_node)
for i in range(0, 6, 1):
if self.playPiece(i) != None:
# print self.gameBoard
if self.pieceCount == 42:
self.gameBoard = copy.deepcopy(current_state)
return i
# return np.argmax(score_list)
else:
# print self.gameBoard
# print "first tree"
# print self.gameBoard
score_list.append(self.min_value(self.gameBoard))
self.gameBoard = copy.deepcopy(current_state)
# for s in score_list:
# print s
# print self.gameBoard
# return np.argmax(score_list)
def max_value(self, current_node):
parent_node = copy.deepcopy(current_node)
v = -infinity
track_of_child_nodes = []
for j in range(0, 6, 1):
current_state = self.playPiece(j)
if current_state != None:
# print j
track_of_child_nodes.append(self.gameBoard)
self.gameBoard = copy.copy(parent_node)
if track_of_child_nodes == []:
# print "This is the score for maximum"
# print self.player1Score
score = self.eval_function(self, self.gameBoard)
self.countScore1(self.dashBoard)
return self.player1Score
else:
max_score_list = []
for child in track_of_child_nodes:
# print self.pieceCount
# print "This is for Max Player"
# print child
self.gameBoard = copy.deepcopy(child)
v = max(v, self.min_value(child))
# print "Value of v from max"
# print v
# max_score_list.append(v)
return v
def min_value(self, current_node):
parent_node = copy.deepcopy(current_node)
if self.currentTurn == 1:
opponent = 2
elif self.currentTurn == 2:
opponent = 1
# if self.pieceCount == 42:
# return self.player1Score
v = infinity
track_of_child_nodes = []
for j in range(0, 6, 1):
current_state = self.checkPiece(j, opponent)
if current_state != None:
track_of_child_nodes.append(self.gameBoard)
self.gameBoard = copy.copy(parent_node)
if track_of_child_nodes == []:
# print "this is the final score for minimum"
self.countScore1(self.gameBoard)
return self.player1Score
else:
for child in track_of_child_nodes:
# print self.pieceCount
# print "This is for opponent"
# print child
self.gameBoard = copy.deepcopy(child)
v = min(v, self.max_value(child))
# print "this is the value of v which will be sent"
# print v
return v | 1b783febaec48af571f024a85ed86dc618ee99e9 | [
"Markdown",
"Python",
"Text"
] | 3 | Text | rithinsuryasainadh/Connect4 | 46ce67af901d81a681b05fc5e424793103fd23c1 | 955b59021656c0f6cf45c09c5d52f2c6ac2d72ac | |
refs/heads/master | <repo_name>moisterrific/FTWProtection<file_sep>/README.md
# FTWProtection
Replaces for the worthy bombs with other projectiles
On for the worthy, skeletron prime bombs will destroy tiles when they explode and bombs can fall out of trees when shaken or when pots are broken.
These are replaced with non-destructive projectiles. In this case, both are hard-coded to use beehives, matching the current dg survival world (drunk + expert + not the bees + ftw flag).
Could use cannonballs for prime bombs with how similar they are. Bombs from the environment could be replaced with an item drop or any other projectile.
<file_sep>/FTWProtection/FTWProtection.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TShockAPI;
using Terraria;
using TerrariaApi.Server;
using Terraria.ID;
namespace FTWProtection
{
[ApiVersion(2, 1)]
public class FTWProtection : TerrariaPlugin
{
public override string Author => "Quinci";
public override string Description => "Prevents explosion griefing in for the worthy";
public override string Name => "For the Worthy Protection";
public override Version Version => new Version(1, 0, 0, 0);
public FTWProtection(Main game) : base(game)
{
Order = 40;
}
public override void Initialize()
{
ServerApi.Hooks.ProjectileSetDefaults.Register(this, OnProjectileSetDefaults);
ServerApi.Hooks.ProjectileAIUpdate.Register(this, OnProjectileAIUpdate);
}
private void OnProjectileSetDefaults(SetDefaultsEventArgs<Projectile, int> args)
{
if (args.Object.type == ProjectileID.BombSkeletronPrime && Main.getGoodWorld) // 102 && ftw flag
{
args.Object.type = ProjectileID.BeeHive; // 655;
args.Object.aiStyle = 25; // Beehive AI, rolls along the ground until crashing
NetMessage.SendData((int)PacketTypes.ProjectileNew, -1, -1, null, args.Object.identity);
}
}
private void OnProjectileAIUpdate(ProjectileAiUpdateEventArgs args)
{
// Only possible via modified client (where there are other issues) as x velocity will always be 5 if y = 0, regardless of tile collision.
if (args.Projectile.type == ProjectileID.Bomb && args.Projectile.timeLeft == 3600 && args.Projectile.oldVelocity.Y == 0f && 0.202f >= Math.Abs(args.Projectile.oldVelocity.X))
{
args.Projectile.type = ProjectileID.BeeHive; // 655;
args.Projectile.aiStyle = 25; // Beehive AI, rolls along the ground until crashing
NetMessage.SendData((int)PacketTypes.ProjectileNew, -1, -1, null, args.Projectile.identity);
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
ServerApi.Hooks.ProjectileSetDefaults.Deregister(this, OnProjectileSetDefaults);
ServerApi.Hooks.ProjectileAIUpdate.Deregister(this, OnProjectileAIUpdate);
}
base.Dispose(disposing);
}
}
} | 6d5b7b9f1c536e67f8346282443bb508eb83affb | [
"Markdown",
"C#"
] | 2 | Markdown | moisterrific/FTWProtection | 10cfdbcda380ce182cf88bf61177885d4134a00f | 0c876f70acb8823b51bacf813cb46ac4da4ee859 | |
refs/heads/master | <repo_name>serge-medvedev/tonos-cli<file_sep>/src/debot/term_signing_box.rs
use crate::crypto::load_keypair;
use super::term_browser::input;
use ton_client::crypto::KeyPair;
use std::io::{self, BufRead, Write};
pub(super) struct TerminalSigningBox {
pub keys: KeyPair
}
impl TerminalSigningBox {
pub fn new() -> Result<Self, String> {
let stdio = io::stdin();
let mut reader = stdio.lock();
let mut writer = io::stdout();
let keys = input_keys(&mut reader, &mut writer, 3)?;
Ok(Self {
keys
})
}
}
pub(super) fn input_keys<R, W>(reader: &mut R, writer: &mut W, tries: u8) -> Result<KeyPair, String>
where
R: BufRead,
W: Write,
{
let enter_str = "enter seed phrase or path to keypair file";
let mut pair = Err("no keypair".to_string());
for _ in 0..tries {
let value = input(enter_str, reader, writer);
pair = load_keypair(&value).map_err(|e| {
println!("Invalid keys: {}. Try again.", e);
e.to_string()
});
if pair.is_ok() {
break;
}
}
pair
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::File;
const PUBLIC: &'static str = "<KEY>";
const PRIVATE: &'static str = "<KEY>";
const SEED: &'static str = "episode polar pistol excite essence van cover fox visual gown yellow minute";
const KEYS_FILE: &'static str = "./keys.json";
fn create_keypair_file(name: &str) {
let mut file = File::create(name).unwrap();
file.write_all(format!(r#"{{
"public": "{}",
"secret": "{}"
}}"#, PUBLIC, PRIVATE).as_bytes()).unwrap();
}
#[test]
fn load_key_from_file() {
let mut in_data = KEYS_FILE.as_bytes();
let mut out_data = vec![];
create_keypair_file(KEYS_FILE);
let keys = input_keys(&mut in_data, &mut out_data, 1).unwrap();
assert_eq!(format!("{}", keys.public), PUBLIC);
assert_eq!(format!("{}", keys.secret), PRIVATE);
}
#[test]
fn load_key_from_seed() {
let mut in_data = SEED.as_bytes();
let mut out_data = vec![];
let keys = input_keys(&mut in_data, &mut out_data, 1).unwrap();
assert_eq!(format!("{}", keys.public), PUBLIC);
assert_eq!(format!("{}", keys.secret), PRIVATE);
}
}<file_sep>/src/config.rs
/*
* Copyright 2018-2020 TON DEV SOLUTIONS LTD.
*
* Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use
* this file except in compliance with the License.
*
* 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 TON DEV software governing permissions and
* limitations under the License.
*/
use serde::{Deserialize, Serialize};
const TESTNET: &'static str = "https://net.ton.dev";
fn default_url() -> String {
TESTNET.to_string()
}
fn default_wc() -> i32 {
0
}
fn default_retries() -> u8 {
5
}
fn default_depool_fee() -> f32 {
0.5
}
fn default_timeout() -> u32 {
60000
}
fn default_false() -> bool {
false
}
#[derive(Serialize, Deserialize, Clone)]
pub struct Config {
#[serde(default = "default_url")]
pub url: String,
#[serde(default = "default_wc")]
pub wc: i32,
pub addr: Option<String>,
pub wallet: Option<String>,
pub abi_path: Option<String>,
pub keys_path: Option<String>,
#[serde(default = "default_retries")]
pub retries: u8,
#[serde(default = "default_timeout")]
pub timeout: u32,
#[serde(default = "default_false")]
pub is_json: bool,
#[serde(default = "default_depool_fee")]
pub depool_fee: f32,
}
impl Config {
pub fn new() -> Self {
Config {
url: default_url(),
wc: default_wc(),
addr: None,
wallet: None,
abi_path: None,
keys_path: None,
retries: default_retries(),
timeout: default_timeout(),
is_json: default_false(),
depool_fee: default_depool_fee(),
}
}
pub fn from_file(path: &str) -> Option<Self> {
let conf_str = std::fs::read_to_string(path).ok()?;
let conf: Config = serde_json::from_str(&conf_str).ok()?;
Some(conf)
}
}
pub fn clear_config(
mut conf: Config,
path: &str,
url: bool,
addr: bool,
wallet: bool,
abi: bool,
keys: bool,
wc: bool,
retries: bool,
timeout: bool,
depool_fee: bool,
) -> Result<(), String> {
if url {
conf.url = default_url();
}
if addr {
conf.addr = None;
}
if wallet {
conf.wallet = None;
}
if abi {
conf.abi_path = None;
}
if keys {
conf.keys_path = None;
}
if retries {
conf.retries = default_retries();
}
if timeout {
conf.timeout = default_timeout();
}
if wc {
conf.wc = default_wc();
}
if depool_fee {
conf.depool_fee = default_depool_fee();
}
if (url || addr || wallet || abi || keys || retries || timeout || wc || depool_fee) == false {
conf = Config {
url: default_url(),
wc: default_wc(),
addr: None,
wallet: None,
abi_path: None,
keys_path: None,
retries: default_retries(),
timeout: default_timeout(),
is_json: default_false(),
depool_fee: default_depool_fee(),
};
}
let conf_str = serde_json::to_string(&conf)
.map_err(|_| "failed to serialize config object".to_string())?;
std::fs::write(path, conf_str).map_err(|e| format!("failed to write config file: {}", e))?;
println!("Succeeded.");
Ok(())
}
pub fn set_config(
mut conf: Config,
path: &str,
url: Option<&str>,
addr: Option<&str>,
wallet: Option<&str>,
abi: Option<&str>,
keys: Option<&str>,
wc: Option<&str>,
retries: Option<&str>,
timeout: Option<&str>,
depool_fee: Option<&str>,
) -> Result<(), String> {
if let Some(s) = url {
conf.url = s.to_string();
}
if let Some(s) = addr {
conf.addr = Some(s.to_string());
}
if let Some(s) = wallet {
conf.wallet = Some(s.to_string());
}
if let Some(s) = abi {
conf.abi_path = Some(s.to_string());
}
if let Some(s) = keys {
conf.keys_path = Some(s.to_string());
}
if let Some(retries) = retries {
conf.retries = u8::from_str_radix(retries, 10)
.map_err(|e| format!(r#"failed to parse "retries": {}"#, e))?;
}
if let Some(timeout) = timeout {
conf.timeout = u32::from_str_radix(timeout, 10)
.map_err(|e| format!(r#"failed to parse "timeout": {}"#, e))?;
}
if let Some(wc) = wc {
conf.wc = i32::from_str_radix(wc, 10)
.map_err(|e| format!(r#"failed to parse "workchain id": {}"#, e))?;
}
if let Some(depool_fee) = depool_fee {
conf.depool_fee = depool_fee.parse::<f32>()
.map_err(|e| format!(r#"failed to parse "depool_fee": {}"#, e))?;
}
if conf.depool_fee < 0.5 {
return Err("Minimal value for depool fee is 0.5".to_string());
}
let conf_str = serde_json::to_string(&conf)
.map_err(|_| "failed to serialize config object".to_string())?;
std::fs::write(path, conf_str).map_err(|e| format!("failed to write config file: {}", e))?;
if !conf.is_json {
println!("Succeeded.");
}
Ok(())
}<file_sep>/src/decode.rs
/*
* Copyright 2018-2020 TON DEV SOLUTIONS LTD.
*
* Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use
* this file except in compliance with the License.
*
* 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 TON DEV software governing permissions and
* limitations under the License.
*/
use crate::{print_args, VERBOSE_MODE};
use crate::config::Config;
use crate::helpers::{decode_msg_body, create_client_local};
use clap::{ArgMatches, SubCommand, Arg, App, AppSettings};
use ton_types::cells_serialization::serialize_tree_of_cells;
use ton_types::Cell;
use std::fmt::Write;
fn match_abi_path(matches: &ArgMatches, config: &Config) -> Option<String> {
matches.value_of("ABI")
.map(|s| s.to_string())
.or(config.abi_path.clone())
}
pub fn create_decode_command<'a, 'b>() -> App<'a, 'b> {
SubCommand::with_name("decode")
.about("Decode commands.")
.setting(AppSettings::AllowLeadingHyphen)
.setting(AppSettings::TrailingVarArg)
.setting(AppSettings::DontCollapseArgsInUsage)
.subcommand(SubCommand::with_name("body")
.arg(Arg::with_name("BODY")
.required(true)
.help("Message body encoded as base64."))
.arg(Arg::with_name("ABI")
.long("--abi")
.takes_value(true)
.help("Path to ABI file.")))
.subcommand(SubCommand::with_name("msg")
.arg(Arg::with_name("MSG")
.required(true)
.help("Path to message boc file."))
.arg(Arg::with_name("ABI")
.long("--abi")
.takes_value(true)
.help("Path to ABI file.")))
}
pub async fn decode_command(m: &ArgMatches<'_>, config: Config) -> Result<(), String> {
if let Some(m) = m.subcommand_matches("body") {
return decode_body_command(m, config).await;
}
if let Some(m) = m.subcommand_matches("msg") {
return decode_message_command(m, config).await;
}
Err("unknown command".to_owned())
}
async fn decode_body_command(m: &ArgMatches<'_>, config: Config) -> Result<(), String> {
let body = m.value_of("BODY");
let abi = Some(
match_abi_path(m, &config)
.ok_or("ABI file not defined. Supply it in config file or command line.".to_string())?
);
if !config.is_json {
print_args!(m, body, abi);
}
println!("{}", decode_body(body.unwrap(), &abi.unwrap(), config.is_json).await?);
Ok(())
}
async fn decode_message_command(m: &ArgMatches<'_>, config: Config) -> Result<(), String> {
let msg = m.value_of("MSG");
let abi = Some(
match_abi_path(m, &config)
.ok_or("ABI file not defined. Supply it in config file or command line.".to_string())?
);
if !config.is_json {
print_args!(m, msg, abi);
}
let msg = msg.map(|f| std::fs::read(f))
.transpose()
.map_err(|e| format!(" failed to read msg boc file: {}", e))?
.unwrap();
println!("{}", decode_message(msg, abi, config.is_json).await?);
Ok(())
}
async fn print_decoded_body(body_vec: Vec<u8>, abi: &str, is_json: bool) -> Result<String, String> {
let ton = create_client_local()?;
let mut empty_boc = vec![];
serialize_tree_of_cells(&Cell::default(), &mut empty_boc).unwrap();
if body_vec.cmp(&empty_boc) == std::cmp::Ordering::Equal {
return Err(format!("body is empty"));
}
let body_base64 = base64::encode(&body_vec);
let mut res = {
match decode_msg_body(ton.clone(), abi, &body_base64, false).await {
Ok(res) => res,
Err(_) => decode_msg_body(ton.clone(), abi, &body_base64, true).await?,
}
};
let output = res.value.take().unwrap();
Ok(if is_json {
format!(" \"BodyCall\": {{\n \"{}\": {}\n }}", res.name, output)
} else {
format!("{}: {}", res.name, serde_json::to_string_pretty(&output).unwrap())
})
}
async fn decode_body(body: &str, abi: &str, is_json: bool) -> Result<String, String> {
let abi = std::fs::read_to_string(abi)
.map_err(|e| format!("failed to read ABI file: {}", e))?;
let body_vec = base64::decode(body)
.map_err(|e| format!("body is not a valid base64 string: {}", e))?;
let mut result = String::new();
let s = &mut result;
if is_json { writeln!(s, "{{").unwrap(); }
writeln!(s, "{}", print_decoded_body(body_vec, &abi, is_json).await?).unwrap();
if is_json { writeln!(s, "}}").unwrap(); }
Ok(result)
}
async fn decode_message(msg_boc: Vec<u8>, abi: Option<String>, is_json: bool) -> Result<String, String> {
let abi = abi.map(|f| std::fs::read_to_string(f))
.transpose()
.map_err(|e| format!("failed to read ABI file: {}", e))?;
let tvm_msg = ton_sdk::Contract::deserialize_message(&msg_boc[..])
.map_err(|e| format!("failed to deserialize message boc: {}", e))?;
let mut printer = msg_printer::MsgPrinter::new(&tvm_msg, is_json);
let mut result = String::new();
let s = &mut result;
write!(s, "{}", printer.print(false)).unwrap();
if abi.is_some() && tvm_msg.body().is_some() {
let abi = abi.unwrap();
let mut body_vec = Vec::new();
serialize_tree_of_cells(&tvm_msg.body().unwrap().into_cell(), &mut body_vec)
.map_err(|e| format!("failed to serialize body: {}", e))?;
writeln!(s, "{}", print_decoded_body(body_vec, &abi, is_json).await?).unwrap();
}
if is_json { writeln!(s, "}}").unwrap(); }
Ok(result)
}
mod msg_printer {
use ton_block::*;
use ton_types::cells_serialization::serialize_tree_of_cells;
use ton_types::Cell;
use std::fmt::Write as FmtWrite;
pub struct MsgPrinter<'a> {
start: &'static str,
off: &'static str,
end: &'static str,
msg: &'a Message,
is_json: bool,
}
impl<'a> MsgPrinter<'a> {
pub fn new(msg: &'a Message, is_json: bool) -> Self {
MsgPrinter {off: " ", start: "\"", end: "\",", msg, is_json }
}
pub fn print(&mut self, close: bool) -> String {
let mut result = String::new();
let s = &mut result;
if self.is_json {
write!(s, "{{\n").unwrap();
}
self.json(s, "Type", &self.print_msg_type());
let hdr = self.print_msg_header();
self.start = "{\n";
self.end = " },";
self.off = " ";
self.json(s, "Header", &hdr);
self.state_init_printer(s);
self.start = "\"";
if close { self.end = "\""; } else { self.end = "\","; }
self.off = " ";
self.json(s, "Body", &tree_of_cells_into_base64(
self.msg.body().map(|slice| slice.into_cell()).as_ref(),
));
if self.is_json && close {
write!(s, "}}\n").unwrap();
}
result
}
fn print_msg_type(&self) -> String {
match self.msg.header() {
CommonMsgInfo::IntMsgInfo(_) => "internal",
CommonMsgInfo::ExtInMsgInfo(_) => "external inbound",
CommonMsgInfo::ExtOutMsgInfo(_) => "external outbound",
}.to_owned() + " message"
}
fn json<T: std::fmt::Display>(&self, s: &mut String, name: &str, value: &T) {
write!(s, "{}\"{}\": {}{}{}\n", self.off, name, self.start, value, self.end).unwrap();
}
fn print_msg_header(&mut self) -> String {
let mut result = String::new();
let s = &mut result;
self.start = "\"";
self.end = "\",";
self.off = " ";
match self.msg.header() {
CommonMsgInfo::IntMsgInfo(header) => {
self.json(s, "ihr_disabled", &header.ihr_disabled);
self.json(s, "bounce", &header.bounce);
self.json(s, "bounced", &header.bounced);
self.json(s, "source", &header.src);
self.json(s, "destination", &header.dst);
self.json(s, "value", &print_cc(&header.value));
self.json(s, "ihr_fee", &print_grams(&header.ihr_fee));
self.json(s, "fwd_fee", &print_grams(&header.fwd_fee));
self.json(s, "created_lt", &header.created_lt);
self.end = "\"";
self.json(s, "created_at", &header.created_at);
},
CommonMsgInfo::ExtInMsgInfo(header) => {
self.json(s, "source", &header.src);
self.json(s, "destination", &header.dst);
self.end = "\"";
self.json(s, "import_fee", &print_grams(&header.import_fee));
},
CommonMsgInfo::ExtOutMsgInfo(header) => {
self.json(s, "source", &header.src);
self.json(s, "destination", &header.dst);
self.json(s, "created_lt", &header.created_lt);
self.end = "\"";
self.json(s, "created_at", &header.created_at);
}
};
result
}
fn state_init_printer(&self, s: &mut String) {
match self.msg.state_init().as_ref() {
Some(x) => {
let init = format!(
"StateInit\n split_depth: {}\n special: {}\n data: {}\n code: {}\n lib: {}\n",
x.split_depth.as_ref().map(|x| format!("{:?}", x)).unwrap_or("None".to_string()),
x.special.as_ref().map(|x| format!("{:?}", x)).unwrap_or("None".to_string()),
tree_of_cells_into_base64(x.data.as_ref()),
tree_of_cells_into_base64(x.code.as_ref()),
tree_of_cells_into_base64(x.library.root())
);
self.json(s, "Init", &init);
},
None => (),
};
}
}
pub fn tree_of_cells_into_base64(root_cell: Option<&Cell>) -> String {
match root_cell {
Some(cell) => {
let mut bytes = Vec::new();
serialize_tree_of_cells(cell, &mut bytes).unwrap();
base64::encode(&bytes)
}
None => "".to_string()
}
}
fn print_grams(grams: &Grams) -> String {
grams.0.to_string()
}
fn print_cc(cc: &CurrencyCollection) -> String {
let mut result = print_grams(&cc.grams);
if !cc.other.is_empty() {
result += " other: {";
cc.other.iterate_with_keys(|key: u32, value| {
result += &format!(" \"{}\": \"{}\",", key, value.0);
Ok(true)
}).ok();
result.pop(); // remove extra comma
result += " }";
}
result
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_decode_msg_json() {
let msg_boc = std::fs::read("tests/samples/wallet.boc").unwrap();
let out = decode_message(msg_boc, Some("tests/samples/wallet.abi.json".to_owned()), true).await.unwrap();
let _ : serde_json::Value = serde_json::from_str(&out).unwrap();
}
#[tokio::test]
async fn test_decode_body_json() {
let body = "te6ccgEBAQEARAAAgwAAALqUCTqWL8OX7JivfJrAAzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMQAAAAAAAAAAAAAAAEeGjADA==";
let out = decode_body(body, "tests/samples/wallet.abi.json", true).await.unwrap();
let _ : serde_json::Value = serde_json::from_str(&out).unwrap();
}
}<file_sep>/src/deploy.rs
/*
* Copyright 2018-2020 TON DEV SOLUTIONS LTD.
*
* Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use
* this file except in compliance with the License.
*
* 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 TON DEV software governing permissions and
* limitations under the License.
*/
use crate::helpers::{create_client_verbose, load_abi, calc_acc_address};
use crate::config::Config;
use crate::crypto::load_keypair;
use ton_client::processing::{ParamsOfProcessMessage};
use ton_client::abi::{Signer, CallSet, DeploySet, ParamsOfEncodeMessage};
pub async fn deploy_contract(conf: Config, tvc: &str, abi: &str, params: &str, keys_file: &str, wc: i32) -> Result<(), String> {
let ton = create_client_verbose(&conf)?;
let abi = std::fs::read_to_string(abi)
.map_err(|e| format!("failed to read ABI file: {}", e))?;
let abi = load_abi(&abi)?;
let keys = load_keypair(keys_file)?;
let tvc_bytes = &std::fs::read(tvc)
.map_err(|e| format!("failed to read smart contract file: {}", e))?;
let tvc_base64 = base64::encode(&tvc_bytes);
let addr = calc_acc_address(
&tvc_bytes,
wc,
keys.public.clone(),
None,
abi.clone()
).await?;
println!("Deploying...");
let dset = DeploySet {
tvc: tvc_base64,
workchain_id: Some(wc),
..Default::default()
};
let params = serde_json::from_str(params)
.map_err(|e| format!("function arguments is not a json: {}", e))?;
let callback = |_event| { async move { } };
ton_client::processing::process_message(
ton.clone(),
ParamsOfProcessMessage {
message_encode_params: ParamsOfEncodeMessage {
abi,
address: Some(addr.clone()),
deploy_set: Some(dset),
call_set: CallSet::some_with_function_and_input("constructor", params),
signer: Signer::Keys{ keys },
..Default::default()
},
send_events: true,
..Default::default()
},
callback,
).await
.map_err(|e| format!("deploy failed: {:#}", e))?;
println!("Transaction succeeded.");
println!("Contract deployed at address: {}", addr);
Ok(())
}<file_sep>/CHANGELOG.md
# CHANGELOG
## v1.0.0
### Breaking changes
- `tonos-cli` now stores its configuration in `./tonos-cli.conf.json`. `tonlabs-cli.conf.json` is now obsolete and can be renamed or deleted.
- Commands `deploy`, `call`, `callex`, `run`, `message` and others now output errors in a different format, compatible with the corresponding changes in the SDK v1.
### Fixes
- Some fixes were made in SDK Debot module that affects running of debots in cli terminal debot browser. The following were fixed:
- invoked debot terminated correctly after error occured during
execution of one of its actions. Initial `prev_state` of invoked debot changed to STATE_EXIT;
- fixed double jumping to current context in invoker debot after
returning control to it from invoked debot;
- fixed conversation of exception codes thrown by debots to their user-friendly description.
- Fixed bug in terminal debot browser. Error in invoked debot doesn't shutdown caller debot.
This fixes affects all debots invoking other debots (e.g. depool debot, mludi debot, DoD debot).
### Miscellaneous
- `tonos-cli` switched to SDK v1. All code using sdk api was refactored.
- `tonos-cli` started to use Debot Engine from SDK Debot Module.
<file_sep>/src/depool.rs
/*
* Copyright 2018-2020 TON DEV SOLUTIONS LTD.
*
* Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use
* this file except in compliance with the License.
*
* 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 TON DEV software governing permissions and
* limitations under the License.
*/
use crate::{print_args, VERBOSE_MODE};
use crate::config::Config;
use crate::convert;
use crate::depool_abi::DEPOOL_ABI;
use crate::helpers::{create_client_local, create_client_verbose, load_abi, load_ton_address, now, TonClient};
use crate::multisig::send_with_body;
use clap::{App, ArgMatches, SubCommand, Arg, AppSettings};
use serde_json;
use ton_client::abi::{ParamsOfEncodeMessageBody, ParamsOfDecodeMessageBody, CallSet};
use ton_client::net::{OrderBy, ParamsOfQueryCollection, ParamsOfWaitForCollection, SortDirection};
pub fn create_depool_command<'a, 'b>() -> App<'a, 'b> {
let wallet_arg = Arg::with_name("MSIG")
.takes_value(true)
.long("--wallet")
.short("-w")
.help("Multisig wallet address.");
let value_arg = Arg::with_name("VALUE")
.takes_value(true)
.long("--value")
.short("-v")
.help("Value in tons.");
let keys_arg = Arg::with_name("SIGN")
.takes_value(true)
.long("--sign")
.short("-s")
.help("Path to keypair file or seed phrase which must be used to sign message to multisig wallet.");
let total_period_arg = Arg::with_name("TPERIOD")
.takes_value(true)
.long("--total")
.short("-t")
.help("Total period of vesting stake (days).");
let withdrawal_period_arg = Arg::with_name("WPERIOD")
.takes_value(true)
.long("--withdrawal")
.short("-i")
.help("Payment period of vesting stake (days).");
let beneficiary_arg = Arg::with_name("BENEFICIARY")
.takes_value(true)
.long("--beneficiary")
.short("-b")
.help("Smart contract address which will own lock stake rewards.");
let donor_arg = Arg::with_name("DONOR")
.takes_value(true)
.long("--donor")
.short("-d")
.help("Donor smart contract address.");
let dest_arg = Arg::with_name("DEST")
.takes_value(true)
.long("--dest")
.short("-d")
.help("Address of destination smart contract.");
SubCommand::with_name("depool")
.about("DePool commands.")
.setting(AppSettings::AllowLeadingHyphen)
.setting(AppSettings::DontCollapseArgsInUsage)
.arg(Arg::with_name("ADDRESS")
.takes_value(true)
.long("--addr")
.help("DePool contract address. if the parameter is omitted, then the value `addr` from the config is used"))
.subcommand(SubCommand::with_name("donor")
.about(r#"Top level command for specifying donor for exotic stakes in depool."#)
.subcommand(SubCommand::with_name("vesting")
.about("Set the address from which participant can receive a vesting stake.")
.setting(AppSettings::AllowLeadingHyphen)
.arg(wallet_arg.clone())
.arg(keys_arg.clone())
.arg(donor_arg.clone()))
.subcommand(SubCommand::with_name("lock")
.about("Set the address from which participant can receive a lock stake.")
.setting(AppSettings::AllowLeadingHyphen)
.arg(wallet_arg.clone())
.arg(keys_arg.clone())
.arg(donor_arg.clone())))
.subcommand(SubCommand::with_name("stake")
.about(r#"Top level command for managing stakes in depool. Uses a supplied multisignature wallet to send internal message with stake to depool."#)
.subcommand(SubCommand::with_name("ordinary")
.about("Deposits ordinary stake in depool from multisignature wallet.")
.setting(AppSettings::AllowLeadingHyphen)
.arg(wallet_arg.clone())
.arg(value_arg.clone())
.arg(keys_arg.clone()))
.subcommand(SubCommand::with_name("vesting")
.about("Deposits vesting stake in depool from multisignature wallet.")
.setting(AppSettings::AllowLeadingHyphen)
.arg(wallet_arg.clone())
.arg(value_arg.clone())
.arg(keys_arg.clone())
.arg(total_period_arg.clone())
.arg(withdrawal_period_arg.clone())
.arg(beneficiary_arg.clone()))
.subcommand(SubCommand::with_name("lock")
.about("Deposits lock stake in depool from multisignature wallet.")
.setting(AppSettings::AllowLeadingHyphen)
.arg(wallet_arg.clone())
.arg(value_arg.clone())
.arg(keys_arg.clone())
.arg(total_period_arg.clone())
.arg(withdrawal_period_arg.clone())
.arg(beneficiary_arg.clone()))
.subcommand(SubCommand::with_name("transfer")
.about("Transfers ownership of wallet stake to another contract.")
.setting(AppSettings::AllowLeadingHyphen)
.arg(wallet_arg.clone())
.arg(value_arg.clone())
.arg(keys_arg.clone())
.arg(dest_arg.clone()))
.subcommand(SubCommand::with_name("remove")
.about("Withdraws ordinary stake from current pooling round of depool to the multisignature wallet.")
.setting(AppSettings::AllowLeadingHyphen)
.arg(wallet_arg.clone())
.arg(value_arg.clone())
.arg(keys_arg.clone()))
.subcommand(SubCommand::with_name("withdrawPart")
.about("Withdraws part of the stake after round completion.")
.setting(AppSettings::AllowLeadingHyphen)
.arg(wallet_arg.clone())
.arg(value_arg.clone())
.arg(keys_arg.clone())))
.subcommand(SubCommand::with_name("replenish")
.about("Transfers funds from the multisignature wallet to the depool contract (NOT A STAKE).")
.setting(AppSettings::AllowLeadingHyphen)
.arg(wallet_arg.clone())
.arg(value_arg.clone())
.arg(keys_arg.clone()))
.subcommand(SubCommand::with_name("ticktock")
.about("Call DePool 'ticktock()' function to update its state. 1 ton is attached to this call (change will be returned).")
.setting(AppSettings::AllowLeadingHyphen)
.arg(wallet_arg.clone())
.arg(keys_arg.clone()))
.subcommand(SubCommand::with_name("withdraw")
.about("Allows to disable auto investment of the stake into next round and withdraw all the stakes after round completion.")
.setting(AppSettings::AllowLeadingHyphen)
.subcommand(SubCommand::with_name("on")
.setting(AppSettings::AllowLeadingHyphen)
.arg(wallet_arg.clone())
.arg(keys_arg.clone()))
.subcommand(SubCommand::with_name("off")
.setting(AppSettings::AllowLeadingHyphen)
.arg(wallet_arg.clone())
.arg(keys_arg.clone())))
.subcommand(SubCommand::with_name("events")
.about("Prints depool events.")
.setting(AppSettings::AllowLeadingHyphen)
.arg(Arg::with_name("SINCE")
.takes_value(true)
.long("--since")
.short("-s")
.help("Prints events since this unixtime."))
.arg(Arg::with_name("WAITONE")
.long("--wait-one")
.short("-w")
.help("Waits until new event will be emitted.")) )
}
struct CommandData<'a> {
conf: Config,
depool: String,
wallet: String,
keys: String,
stake: &'a str,
depool_fee: String,
}
impl<'a> CommandData<'a> {
pub fn from_matches_and_conf(m: &'a ArgMatches, conf: Config, depool: String) -> Result<Self, String> {
let (wallet, stake, keys) = parse_stake_data(m, &conf)?;
let depool_fee = conf.depool_fee.clone().to_string();
Ok(CommandData {conf, depool, wallet, stake, keys, depool_fee})
}
}
fn parse_wallet_data(m: &ArgMatches, conf: &Config) -> Result<(String, String), String> {
let wallet = m.value_of("MSIG")
.map(|s| s.to_string())
.or(conf.wallet.clone())
.ok_or("multisig wallet address is not defined.".to_string())?;
let wallet = load_ton_address(&wallet, conf)
.map_err(|e| format!("invalid multisig address: {}", e))?;
let keys = m.value_of("SIGN")
.map(|s| s.to_string())
.or(conf.keys_path.clone())
.ok_or("keypair is not defined.".to_string())?;
Ok((wallet, keys))
}
fn parse_stake_data<'a>(m: &'a ArgMatches, conf: &Config) -> Result<(String, &'a str, String), String> {
let (wallet, keys) = parse_wallet_data(m, conf)?;
let stake = m.value_of("VALUE")
.ok_or("stake value is not defined.".to_string())?;
Ok((wallet, stake, keys))
}
pub async fn depool_command(m: &ArgMatches<'_>, conf: Config) -> Result<(), String> {
let depool = m.value_of("ADDRESS")
.map(|s| s.to_string())
.or(conf.addr.clone())
.ok_or("depool address is not defined. Supply it in config file or in command line.".to_string())?;
let depool = load_ton_address(&depool, &conf)
.map_err(|e| format!("invalid depool address: {}", e))?;
if let Some(m) = m.subcommand_matches("donor") {
let matches = m.subcommand_matches("vesting").or(m.subcommand_matches("lock"));
if let Some(matches) = matches {
let is_vesting = m.subcommand_matches("vesting").is_some();
let (wallet, keys) = parse_wallet_data(&matches, &conf)?;
return set_donor_command(matches, conf, depool.as_str(), &wallet, &keys, is_vesting).await;
}
}
if let Some(m) = m.subcommand_matches("stake") {
if let Some(m) = m.subcommand_matches("ordinary") {
return ordinary_stake_command(m,
CommandData::from_matches_and_conf(m, conf, depool)?,
).await;
}
if let Some(m) = m.subcommand_matches("vesting") {
return exotic_stake_command(m,
CommandData::from_matches_and_conf(m, conf, depool)?,
true,
).await;
}
if let Some(m) = m.subcommand_matches("lock") {
return exotic_stake_command(m,
CommandData::from_matches_and_conf(m, conf, depool)?,
false,
).await;
}
if let Some(m) = m.subcommand_matches("remove") {
return remove_stake_command(m,
CommandData::from_matches_and_conf(m, conf, depool)?,
).await;
}
if let Some(m) = m.subcommand_matches("withdrawPart") {
return withdraw_stake_command(m,
CommandData::from_matches_and_conf(m, conf, depool)?,
).await;
}
if let Some(m) = m.subcommand_matches("transfer") {
return transfer_stake_command(m,
CommandData::from_matches_and_conf(m, conf, depool)?,
).await;
}
}
if let Some(m) = m.subcommand_matches("withdraw") {
let matches = m.subcommand_matches("on").or(m.subcommand_matches("off"));
if let Some(matches) = matches {
let (wallet, keys) = parse_wallet_data(&matches, &conf)?;
let enable_withdraw = m.subcommand_matches("on").is_some();
return set_withdraw_command(matches, conf, &depool, &wallet, &keys, enable_withdraw).await;
}
}
if let Some(m) = m.subcommand_matches("events") {
return events_command(m, conf, &depool).await
}
if let Some(m) = m.subcommand_matches("replenish") {
return replenish_command(m,
CommandData::from_matches_and_conf(m, conf, depool)?,
).await;
}
if let Some(m) = m.subcommand_matches("ticktock") {
let (wallet, keys) = parse_wallet_data(&m, &conf)?;
return ticktock_command(m, conf, &depool, &wallet, &keys).await;
}
Err("unknown depool command".to_owned())
}
/*
* Events command
*/
async fn events_command(m: &ArgMatches<'_>, conf: Config, depool: &str) -> Result<(), String> {
let since = m.value_of("SINCE");
let wait_for = m.is_present("WAITONE");
let depool = Some(depool);
print_args!(m, depool, since);
if !wait_for {
let since = since.map(|s| {
u32::from_str_radix(s, 10)
.map_err(|e| format!(r#"cannot parse "since" option: {}"#, e))
})
.transpose()?
.unwrap_or(0);
get_events(conf, depool.unwrap(), since).await
} else {
wait_for_event(conf, depool.unwrap()).await
}
}
fn events_filter(addr: &str, since: u32) -> serde_json::Value {
json!({
"src": { "eq": addr },
"msg_type": {"eq": 2 },
"created_at": {"ge": since }
})
}
async fn print_event(ton: TonClient, event: &serde_json::Value) {
println!("event {}", event["id"].as_str().unwrap());
let body = event["body"].as_str().unwrap();
let result = ton_client::abi::decode_message_body(
ton.clone(),
ParamsOfDecodeMessageBody {
abi: load_abi(DEPOOL_ABI).unwrap(),
body: body.to_owned(),
is_internal: false,
..Default::default()
},
).await;
let (name, args) = if result.is_err() {
("unknown".to_owned(), "{}".to_owned())
} else {
let result = result.unwrap();
(result.name, serde_json::to_string(&result.value).unwrap())
};
println!("{} {} ({})\n{}\n",
name,
event["created_at"].as_u64().unwrap(),
event["created_at_string"].as_str().unwrap(),
args
);
}
async fn get_events(conf: Config, depool: &str, since: u32) -> Result<(), String> {
let ton = create_client_verbose(&conf)?;
let _addr = load_ton_address(depool, &conf)?;
let events = ton_client::net::query_collection(
ton.clone(),
ParamsOfQueryCollection {
collection: "messages".to_owned(),
filter: Some(events_filter(depool, since)),
result: "id body created_at created_at_string".to_owned(),
order: Some(vec![OrderBy{ path: "created_at".to_owned(), direction: SortDirection::DESC }]),
..Default::default()
},
).await.map_err(|e| format!("failed to query depool events: {}", e))?;
println!("{} events found", events.result.len());
for event in &events.result {
print_event(ton.clone(), event).await;
}
println!("Done");
Ok(())
}
async fn wait_for_event(conf: Config, depool: &str) -> Result<(), String> {
let ton = create_client_verbose(&conf)?;
let _addr = load_ton_address(depool, &conf)?;
println!("Waiting for a new event...");
let event = ton_client::net::wait_for_collection(
ton.clone(),
ParamsOfWaitForCollection {
collection: "messages".to_owned(),
filter: Some(events_filter(depool, now())),
result: "id body created_at created_at_string".to_owned(),
timeout: Some(conf.timeout),
..Default::default()
},
).await.map_err(|e| println!("failed to query event: {}", e.to_string()));
if event.is_ok() {
print_event(ton.clone(), &event.unwrap().result).await;
}
Ok(())
}
/*
* Stake commands
*/
async fn ordinary_stake_command(
m: &ArgMatches<'_>,
cmd: CommandData<'_>,
) -> Result<(), String> {
let (depool, wallet, stake, keys) =
(Some(&cmd.depool), Some(&cmd.wallet), Some(cmd.stake), Some(&cmd.keys));
print_args!(m, depool, wallet, stake, keys);
add_ordinary_stake(cmd).await
}
async fn replenish_command(
m: &ArgMatches<'_>,
cmd: CommandData<'_>,
) -> Result<(), String> {
let (depool, wallet, stake, keys) =
(Some(&cmd.depool), Some(&cmd.wallet), Some(cmd.stake), Some(&cmd.keys));
print_args!(m, depool, wallet, stake, keys);
replenish_stake(cmd).await
}
async fn ticktock_command(
m: &ArgMatches<'_>,
conf: Config,
depool: &str,
wallet: &str,
keys: &str,
) -> Result<(), String> {
let (depool, wallet, keys) = (Some(depool), Some(wallet), Some(keys));
print_args!(m, depool, wallet, keys);
call_ticktock(conf, depool.unwrap(), wallet.unwrap(), keys.unwrap()).await
}
async fn transfer_stake_command(
m: &ArgMatches<'_>,
cmd: CommandData<'_>,
) -> Result<(), String> {
let dest = Some(m.value_of("DEST")
.ok_or("destination address is not defined.".to_string())?);
let (depool, wallet, stake, keys) =
(Some(&cmd.depool), Some(&cmd.wallet), Some(cmd.stake), Some(&cmd.keys));
print_args!(m, depool, wallet, stake, keys, dest);
transfer_stake(cmd, dest.unwrap()).await
}
async fn set_donor_command(
m: &ArgMatches<'_>,
conf: Config,
depool: &str,
wallet: &str,
keys: &str,
is_vesting: bool,
) -> Result<(), String> {
let (depool, wallet, keys) = (Some(depool), Some(wallet), Some(keys));
let donor = Some(m.value_of("DONOR")
.ok_or("donor is not defined.".to_string())?);
print_args!(m, depool, wallet, keys, donor);
set_donor(conf, depool.unwrap(), wallet.unwrap(), keys.unwrap(), is_vesting, donor.unwrap()).await
}
async fn exotic_stake_command(
m: &ArgMatches<'_>,
cmd: CommandData<'_>,
is_vesting: bool,
) -> Result<(), String> {
let withdrawal_period = Some(m.value_of("WPERIOD")
.ok_or("withdrawal period is not defined.".to_string())?);
let total_period = Some(m.value_of("TPERIOD")
.ok_or("total period is not defined.".to_string())?);
let beneficiary = Some(m.value_of("BENEFICIARY")
.ok_or("beneficiary is not defined.".to_string())?);
let (depool, wallet, stake, keys) = (Some(&cmd.depool), Some(&cmd.wallet), Some(cmd.stake), Some(&cmd.keys));
print_args!(m, depool, wallet, stake, keys, beneficiary, withdrawal_period, total_period);
let period_checker = |v| {
if v > 0 && v <= 36500 {
Ok(v)
} else {
Err(format!("period cannot be more than 36500 days"))
}
};
let wperiod = u32::from_str_radix(withdrawal_period.unwrap(), 10)
.map_err(|e| format!("invalid withdrawal period: {}", e))
.and_then(period_checker)?;
let tperiod = u32::from_str_radix(total_period.unwrap(), 10)
.map_err(|e| format!("invalid total period: {}", e))
.and_then(period_checker)?;
let wperiod = wperiod * 86400;
let tperiod = tperiod * 86400;
add_exotic_stake(cmd, beneficiary.unwrap(), wperiod, tperiod, is_vesting).await
}
async fn remove_stake_command(
m: &ArgMatches<'_>,
cmd: CommandData<'_>,
) -> Result<(), String> {
let (depool, wallet, stake, keys) = (Some(&cmd.depool), Some(&cmd.wallet), Some(cmd.stake), Some(&cmd.keys));
print_args!(m, depool, wallet, stake, keys);
remove_stake(cmd).await
}
async fn withdraw_stake_command(
m: &ArgMatches<'_>,
cmd: CommandData<'_>,
) -> Result<(), String> {
let (depool, wallet, stake, keys) = (Some(&cmd.depool), Some(&cmd.wallet), Some(cmd.stake), Some(&cmd.keys));
print_args!(m, depool, wallet, stake, keys);
withdraw_stake(cmd).await
}
async fn set_withdraw_command(
m: &ArgMatches<'_>,
conf: Config,
depool: &str,
wallet: &str,
keys: &str,
enable: bool,
) -> Result<(), String> {
let (depool, wallet, keys) = (Some(depool), Some(wallet), Some(keys));
let withdraw = Some(if enable { "true" } else { "false" });
print_args!(m, depool, wallet, keys, withdraw);
set_withdraw(conf, depool.unwrap(), wallet.unwrap(), keys.unwrap(), enable).await
}
async fn add_ordinary_stake(cmd: CommandData<'_>) -> Result<(), String> {
let stake = u64::from_str_radix(&convert::convert_token(cmd.stake)?, 10)
.map_err(|e| format!(r#"failed to parse stake value: {}"#, e))?;
let body = encode_add_ordinary_stake(stake).await?;
let fee = u64::from_str_radix(&convert::convert_token(&cmd.depool_fee)?, 10)
.map_err(|e| format!(r#"failed to parse depool fee value: {}"#, e))?;
let value = (fee + stake) as f64 * 1.0 / 1e9;
send_with_body(cmd.conf, &cmd.wallet, &cmd.depool, &format!("{}", value), &cmd.keys, &body).await
}
async fn replenish_stake(cmd: CommandData<'_>) -> Result<(), String> {
let body = encode_replenish_stake().await?;
send_with_body(cmd.conf, &cmd.wallet, &cmd.depool, cmd.stake, &cmd.keys, &body).await
}
async fn call_ticktock(
conf: Config,
depool: &str,
wallet: &str,
keys: &str,
) -> Result<(), String> {
let body = encode_ticktock().await?;
send_with_body(conf, wallet, depool, "1", keys, &body).await
}
async fn add_exotic_stake(
cmd: CommandData<'_>,
beneficiary: &str,
wp: u32,
tp: u32,
is_vesting: bool,
) -> Result<(), String> {
let beneficiary = load_ton_address(beneficiary, &cmd.conf)?;
let stake = u64::from_str_radix(&convert::convert_token(cmd.stake)?, 10)
.map_err(|e| format!(r#"failed to parse stake value: {}"#, e))?;
let body = if is_vesting {
encode_add_vesting_stake(stake, beneficiary.as_str(), tp, wp).await?
} else {
encode_add_lock_stake(stake, beneficiary.as_str(), tp, wp).await?
};
let fee = u64::from_str_radix(&convert::convert_token(&cmd.depool_fee)?, 10)
.map_err(|e| format!(r#"failed to parse depool fee value: {}"#, e))?;
let value = (fee + stake) as f64 * 1.0 / 1e9;
send_with_body(cmd.conf, &cmd.wallet, &cmd.depool, &format!("{}", value), &cmd.keys, &body).await
}
async fn remove_stake(
cmd: CommandData<'_>,
) -> Result<(), String> {
let stake = u64::from_str_radix(
&convert::convert_token(cmd.stake)?, 10,
).unwrap();
let body = encode_remove_stake(stake).await?;
send_with_body(cmd.conf, &cmd.wallet, &cmd.depool, &cmd.depool_fee, &cmd.keys, &body).await
}
async fn withdraw_stake(
cmd: CommandData<'_>,
) -> Result<(), String> {
let stake = u64::from_str_radix(
&convert::convert_token(cmd.stake)?, 10,
).unwrap();
let body = encode_withdraw_stake(stake).await?;
send_with_body(cmd.conf, &cmd.wallet, &cmd.depool, &cmd.depool_fee, &cmd.keys, &body).await
}
async fn transfer_stake(cmd: CommandData<'_>, dest: &str) -> Result<(), String> {
let dest = load_ton_address(dest, &cmd.conf)?;
let stake = u64::from_str_radix(
&convert::convert_token(cmd.stake)?, 10,
).unwrap();
let body = encode_transfer_stake(dest.as_str(), stake).await?;
send_with_body(cmd.conf, &cmd.wallet, &cmd.depool, &cmd.depool_fee, &cmd.keys, &body).await
}
async fn set_withdraw(
conf: Config,
depool: &str,
wallet: &str,
keys: &str,
enable: bool,
) -> Result<(), String> {
let body = encode_set_withdraw(enable).await?;
let value = conf.depool_fee.to_string();
send_with_body(conf, wallet, depool, &value, keys, &body).await
}
async fn set_donor(
conf: Config,
depool: &str,
wallet: &str,
keys: &str,
is_vesting: bool,
donor: &str,
) -> Result<(), String> {
let body = encode_set_donor(is_vesting, donor).await?;
let value = conf.depool_fee.to_string();
send_with_body(conf, wallet, depool, &value, keys, &body).await
}
async fn encode_body(func: &str, params: serde_json::Value) -> Result<String, String> {
let client = create_client_local()?;
ton_client::abi::encode_message_body(
client.clone(),
ParamsOfEncodeMessageBody {
abi: load_abi(DEPOOL_ABI)?,
call_set: CallSet::some_with_function_and_input(func, params).unwrap(),
is_internal: true,
..Default::default()
},
).await
.map_err(|e| format!("failed to encode body: {}", e))
.map(|r| r.body)
}
async fn encode_set_withdraw(flag: bool) -> Result<String, String> {
if flag {
encode_body("withdrawAll", json!({}))
} else {
encode_body("cancelWithdrawal", json!({}))
}.await
}
async fn encode_add_ordinary_stake(stake: u64) -> Result<String, String> {
encode_body("addOrdinaryStake", json!({
"stake": stake
})).await
}
async fn encode_replenish_stake() -> Result<String, String> {
encode_body("receiveFunds", json!({})).await
}
async fn encode_ticktock() -> Result<String, String> {
encode_body("ticktock", json!({})).await
}
async fn encode_add_vesting_stake(
stake: u64,
beneficiary: &str,
tperiod: u32,
wperiod: u32,
) -> Result<String, String> {
encode_body("addVestingStake", json!({
"stake": stake,
"beneficiary": beneficiary,
"withdrawalPeriod": wperiod,
"totalPeriod": tperiod
})).await
}
async fn encode_set_donor(is_vesting: bool, donor: &str) -> Result<String, String> {
if is_vesting {
encode_body("setVestingDonor", json!({
"donor": donor
}))
} else {
encode_body("setLockDonor", json!({
"donor": donor
}))
}.await
}
async fn encode_add_lock_stake(
stake: u64,
beneficiary: &str,
tperiod: u32,
wperiod: u32,
) -> Result<String, String> {
encode_body("addLockStake", json!({
"stake": stake,
"beneficiary": beneficiary,
"withdrawalPeriod": wperiod,
"totalPeriod": tperiod
})).await
}
async fn encode_remove_stake(target_value: u64) -> Result<String, String> {
encode_body("withdrawFromPoolingRound", json!({
"withdrawValue": target_value
})).await
}
async fn encode_withdraw_stake(target_value: u64) -> Result<String, String> {
encode_body("withdrawPart", json!({
"withdrawValue": target_value
})).await
}
async fn encode_transfer_stake(dest: &str, amount: u64) -> Result<String, String> {
encode_body("transferStake", json!({
"dest": dest,
"amount": amount
})).await
}
<file_sep>/src/account.rs
/*
* Copyright 2018-2020 TON DEV SOLUTIONS LTD.
*
* Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use
* this file except in compliance with the License.
*
* 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 TON DEV software governing permissions and
* limitations under the License.
*/
use crate::helpers::create_client_verbose;
use crate::config::Config;
use serde_json::json;
use ton_client::net::{ParamsOfQueryCollection, query_collection};
const ACCOUNT_FIELDS: &str = r#"
acc_type_name
balance(format: DEC)
last_paid
last_trans_lt
data
"#;
pub async fn get_account(conf: Config, addr: &str) -> Result<(), String> {
let ton = create_client_verbose(&conf)?;
if !conf.is_json {
println!("Processing...");
}
let query_result = query_collection(
ton.clone(),
ParamsOfQueryCollection {
collection: "accounts".to_owned(),
filter: Some(json!({ "id": { "eq": addr } })),
result: ACCOUNT_FIELDS.to_string(),
limit: Some(1),
..Default::default()
},
).await.map_err(|e| format!("failed to query account info: {}", e))?;
let accounts = query_result.result;
if !conf.is_json {
println!("Succeeded.");
}
if conf.is_json {
println!("{{");
if accounts.len() == 1 {
let acc = &accounts[0];
let acc_type = acc["acc_type_name"].as_str().unwrap();
if acc_type != "NonExist" {
println!(" \"acc_type\": \"{}\",", acc_type);
let balance_str = &acc["balance"].as_str().unwrap();
println!(" \"balance\": \"{}\",", u64::from_str_radix(balance_str, 10).unwrap());
println!(" \"last_paid\": \"{}\",", acc["last_paid"].as_u64().unwrap());
println!(" \"last_trans_lt\": \"{}\",", acc["last_trans_lt"].as_str().unwrap());
let data_str = acc["data"].as_str();
if data_str.is_some() {
let data_vec = base64::decode(data_str.unwrap()).unwrap();
println!(" \"data(boc)\": \"{}\"", hex::encode(&data_vec));
} else {
println!(" \"data(boc)\": \"null\"");
}
} else {
println!(" \"acc_type\": \"{}\"", acc_type);
}
}
println!("}}");
} else {
if accounts.len() == 1 {
let acc = &accounts[0];
let acc_type = acc["acc_type_name"].as_str().unwrap();
if acc_type != "NonExist" {
println!("acc_type: {}", acc_type);
let balance_str = &acc["balance"].as_str().unwrap();
println!("balance: {}", u64::from_str_radix(balance_str, 10).unwrap());
println!("last_paid: {}", acc["last_paid"].as_u64().unwrap());
println!("last_trans_lt: {}", acc["last_trans_lt"].as_str().unwrap());
let data_str = acc["data"].as_str();
if data_str.is_some() {
let data_vec = base64::decode(data_str.unwrap()).unwrap();
println!("data(boc): {}", hex::encode(&data_vec));
} else {
println!("data(boc): null");
}
} else {
println!("Account does not exist.");
}
} else {
println!("Account not found.");
}
}
Ok(())
}<file_sep>/src/helpers.rs
/*
* Copyright 2018-2020 TON DEV SOLUTIONS LTD.
*
* Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use
* this file except in compliance with the License.
*
* 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 TON DEV software governing permissions and
* limitations under the License.
*/
use crate::config::Config;
use log;
use std::sync::Arc;
use std::time::SystemTime;
use ton_client::abi::{
Abi, AbiConfig, AbiContract, DecodedMessageBody, DeploySet, ParamsOfDecodeMessageBody,
ParamsOfEncodeMessage, Signer,
};
use ton_client::crypto::{CryptoConfig, KeyPair};
use ton_client::error::ClientError;
use ton_client::net::{query_collection, OrderBy, ParamsOfQueryCollection};
use ton_client::{ClientConfig, ClientContext};
const TEST_MAX_LEVEL: log::LevelFilter = log::LevelFilter::Debug;
const MAX_LEVEL: log::LevelFilter = log::LevelFilter::Warn;
pub const HD_PATH: &str = "m/44'/396'/0'/0/0";
pub const WORD_COUNT: u8 = 12;
struct SimpleLogger;
impl log::Log for SimpleLogger {
fn enabled(&self, metadata: &log::Metadata) -> bool {
metadata.level() < MAX_LEVEL
}
fn log(&self, record: &log::Record) {
match record.level() {
log::Level::Error | log::Level::Warn => {
eprintln!("{}", record.args());
}
_ => {
println!("{}", record.args());
}
}
}
fn flush(&self) {}
}
pub fn read_keys(filename: &str) -> Result<KeyPair, String> {
let keys_str = std::fs::read_to_string(filename)
.map_err(|e| format!("failed to read keypair file: {}", e.to_string()))?;
let keys: KeyPair = serde_json::from_str(&keys_str).unwrap();
Ok(keys)
}
pub fn load_ton_address(addr: &str, conf: &Config) -> Result<String, String> {
use std::str::FromStr;
let addr = if addr.find(':').is_none() {
format!("{}:{}", conf.wc, addr)
} else {
addr.to_owned()
};
let _ = ton_block::MsgAddressInt::from_str(&addr)
.map_err(|e| format!("Address is specified in the wrong format. Error description: {}", e))?;
Ok(addr)
}
pub fn now() -> u32 {
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_secs() as u32
}
pub type TonClient = Arc<ClientContext>;
pub fn create_client_local() -> Result<TonClient, String> {
let cli = ClientContext::new(ClientConfig::default())
.map_err(|e| format!("failed to create tonclient: {}", e))?;
Ok(Arc::new(cli))
}
pub fn create_client(conf: &Config) -> Result<TonClient, String> {
let cli_conf = ClientConfig {
abi: AbiConfig {
workchain: conf.wc,
message_expiration_timeout: conf.timeout,
message_expiration_timeout_grow_factor: 1.3,
},
crypto: CryptoConfig {
mnemonic_dictionary: 1,
mnemonic_word_count: WORD_COUNT,
hdkey_derivation_path: HD_PATH.to_string(),
},
network: ton_client::net::NetworkConfig {
server_address: Some(conf.url.to_owned()),
network_retries_count: 3,
message_retries_count: conf.retries as i8,
message_processing_timeout: 30000,
wait_for_timeout: 30000,
out_of_sync_threshold: (conf.timeout / 2),
max_reconnect_timeout: 1000,
..Default::default()
},
boc: Default::default(),
};
let cli =
ClientContext::new(cli_conf).map_err(|e| format!("failed to create tonclient: {}", e))?;
Ok(Arc::new(cli))
}
pub fn create_client_verbose(conf: &Config) -> Result<TonClient, String> {
if !conf.is_json {
println!("Connecting to {}", conf.url);
}
let level = if std::env::var("RUST_LOG")
.unwrap_or_default()
.eq_ignore_ascii_case("debug")
{
TEST_MAX_LEVEL
} else {
MAX_LEVEL
};
log::set_max_level(level);
log::set_boxed_logger(Box::new(SimpleLogger))
.map_err(|e| format!("failed to init logger: {}", e))?;
create_client(conf)
}
pub async fn query(
ton: TonClient,
collection: &str,
filter: serde_json::Value,
result: &str,
order: Option<Vec<OrderBy>>,
) -> Result<Vec<serde_json::Value>, ClientError> {
query_collection(
ton,
ParamsOfQueryCollection {
collection: collection.to_owned(),
filter: Some(filter),
result: result.to_owned(),
order,
..Default::default()
},
)
.await
.map(|r| r.result)
}
pub async fn decode_msg_body(
ton: TonClient,
abi: &str,
body: &str,
is_internal: bool,
) -> Result<DecodedMessageBody, String> {
let abi = load_abi(abi)?;
ton_client::abi::decode_message_body(
ton,
ParamsOfDecodeMessageBody {
abi,
body: body.to_owned(),
is_internal,
..Default::default()
},
)
.await
.map_err(|e| format!("failed to decode body: {}", e))
}
pub fn load_abi(abi: &str) -> Result<Abi, String> {
Ok(Abi::Contract(
serde_json::from_str::<AbiContract>(abi)
.map_err(|e| format!("ABI is not a valid json: {}", e))?,
))
}
pub async fn calc_acc_address(
tvc: &[u8],
wc: i32,
pubkey: String,
init_data: Option<&str>,
abi: Abi,
) -> Result<String, String> {
let ton = create_client_local()?;
let init_data_json = init_data
.map(|d| serde_json::from_str(d))
.transpose()
.map_err(|e| format!("initial data is not in json: {}", e))?;
let dset = DeploySet {
tvc: base64::encode(tvc),
workchain_id: Some(wc),
initial_data: init_data_json,
..Default::default()
};
let result = ton_client::abi::encode_message(
ton.clone(),
ParamsOfEncodeMessage {
abi,
deploy_set: Some(dset),
signer: Signer::External {
public_key: pubkey,
},
..Default::default()
},
)
.await
.map_err(|e| format!("cannot generate address: {}", e))?;
Ok(result.address)
}
| deb18642dc63c46a55b58e20c47fd65998ed3954 | [
"Markdown",
"Rust"
] | 8 | Rust | serge-medvedev/tonos-cli | 28e467fe44306864bcf00d57b2666a771429c0c6 | 45b507fab5bece18cf057e39e3f5530d32e4eee3 | |
refs/heads/main | <repo_name>chaitalijadhav27/Java-Essentials<file_sep>/Employee.java
class Employee
{
String name;
int age;
String city;
Employee(String n, int a, String c)
{
name=n;
age=a;
city=c;
}
void display()
{
System.out.println("The Name is "+name);
System.out.println("The Age is "+age);
System.out.println("The City is "+city);
}
public static void main(String args[])
{
Employee e = new Employee("Chaitali",20,"Pune");
Employee s = new Employee("Aditi",21,"Mumbai");
e.display();
s.display();
}
}
| 1e2f6f42f18dde0548114bc558c8a03c3c5420e4 | [
"Java"
] | 1 | Java | chaitalijadhav27/Java-Essentials | b82fdfe32758f94610ce4f8d9608d56d17356306 | 44132f4981a9c8e02ec452067e1c90dc6035da1e | |
refs/heads/master | <file_sep># To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
A=int(input("ingrese un numero\n"))
B=int(input("ingrese otro numero\n"))
C=int(input("ingrese un nuemero\n"))
if(A > B and A < C or A < B and A > C):
print("El numero intermedio es " + str(A))
else:
if(B > A and B < C or B < A and B > C):
print("El numero intermedio es " + str(B))
else:
if(C > A and B < C or C < A and C > B ):
print("El nuemro intermedio es " + str (C))
else:
print ("No esxiste el nuemro intermedio")
| abf0ffff4618c5e6a50bf1b97638e887c88c56ed | [
"Python"
] | 1 | Python | Alexvaster95/grupo-6 | f476a11c5e99bef901fff01161e507cf8a2b3a44 | 772b71ee5b557fc82ab5f829f036d2994e987a34 | |
refs/heads/master | <file_sep># BingWallPaperAutoDownload
## lower quality image
<file_sep># BingWallPaperAutoDownload
## deprecated

<file_sep>import requests
import json
import urllib.request
import re
import os.path
js_url = "https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US"
try:
js_data = json.loads(requests.get(js_url).text)
image_url_1 = 'http://www.bing.com' + js_data['images'][0]['url']
image_url_2 = 'http://www.bing.com/hpwp/' + js_data['images'][0]['hsh']
image_name = js_data['images'][0]['enddate']
if os.path.exists("./image_1/" + image_name+".jpg") == False:
urllib.request.urlretrieve(
image_url_1, filename="./image_1/" + image_name+".jpg")
else:
print("./image_1/" + image_name+".jpg"+" Already exist.")
if os.path.exists("./image_2/" + image_name+".jpg") == False:
urllib.request.urlretrieve(
image_url_2, filename="./image_2/" + image_name+".jpg")
else:
print("./image_2/" + image_name+".jpg"+" Already exist.")
except:
print("error!")
<file_sep># BingWallPaperAutoDownload
## higher quality image
| e7b6ac211b9a0f95af85cc1dbddb2ae1e316251d | [
"Markdown",
"Python"
] | 4 | Markdown | zyhibook/BingWallPaperAutoDownload | 0efb9176f989bd65540c55af1ca418560232e5dd | bf371eea8ebcc41b09622f7a66d183bdc710e5e1 | |
refs/heads/master | <repo_name>sidharth3000/Burger-Builder-1<file_sep>/src/Container/BurgerBuilder/BurgerBuilder.js
import React, {Component} from 'react';
import Aux from '../../hoc/Auxiliary';
import Burger from '../../Components/Burger/Burger';
import BurgerControls from "../../Components/Burger/BuildControls/BuildControls";
import Modal from '../../Components/UI/Modal/Modal';
import OrderSummary from '../../Components/Burger/OrderSummary/OrderSummary';
const INGREDIENT_PRICES ={
salad: 0.5,
cheese: 0.4,
meat: 1.3,
bacon:0.7
}
class BurgerBuilder extends Component{
state = {
ingredients:{
salad:0,
bacon:0,
cheese:0,
meat:0
},
totalPrice:4,
purhasable:false,
purchasing:false
}
changePurchasing = () =>{
this.setState({purchasing:true})
}
updatePurhaseState = (updateIngredient) => {
const ingredients = updateIngredient;
const sum = Object.keys(ingredients).map(igkey=>{
return ingredients[igkey];
}).reduce((sum,el)=>{
return sum + el;
},0)
this.setState({purhasable:sum>0})
}
addIngredientHandler = (type) =>{
const oldCount = this.state.ingredients[type];
const newCount = oldCount + 1;
const updateIngredient = {
...this.state.ingredients
};
updateIngredient[type] = newCount;
const totalPrice = this.state.totalPrice;
const updateTotalPrice = totalPrice + INGREDIENT_PRICES[type];
this.setState({ingredients:updateIngredient,totalPrice:updateTotalPrice});
this.updatePurhaseState(updateIngredient);
}
removeIngredientHandler = (type) =>{
const oldCount = this.state.ingredients[type];
let newCount = oldCount - 1;
if(oldCount<=0){
return
}
const updateIngredient = {
...this.state.ingredients
};
updateIngredient[type] = newCount;
const totalPrice = this.state.totalPrice;
const updateTotalPrice = totalPrice - INGREDIENT_PRICES[type];
this.setState({ingredients:updateIngredient,totalPrice:updateTotalPrice});
this.updatePurhaseState(updateIngredient);
}
cancelOrder = () =>{
this.setState({purchasing:false})
}
continueOrder = () =>{
alert("YOU CAN CONTINUE")
}
render(){
const disabledInfo = {
...this.state.ingredients
}
for(let key in disabledInfo){
disabledInfo[key] = disabledInfo[key]<=0;
}
return(
<Aux>
<Modal show={this.state.purchasing} cancelOrder={this.cancelOrder}>
<OrderSummary ingredient={this.state.ingredients}
price={this.state.totalPrice}
continueOrder={this.continueOrder}
cancelOrder={this.cancelOrder}/>
</Modal>
<Burger ingredients={this.state.ingredients}/>
<BurgerControls ingredientAdded={this.addIngredientHandler}
totalPrice = {this.state.totalPrice}
disabled = {disabledInfo}
purhasable={this.state.purhasable}
orderd = {this.changePurchasing}
ingredientRemove={this.removeIngredientHandler}/>
</Aux>
);
}
}
export default BurgerBuilder; | ca4007a84f0f45f2b982134fda3896bf64c26fda | [
"JavaScript"
] | 1 | JavaScript | sidharth3000/Burger-Builder-1 | eb11f08092ac553f7be544429c9eff98c35b2e5a | cfd4d94d7607de33ed4b06c4bc93e8f5f7de251a | |
refs/heads/master | <repo_name>99rupali/lab2<file_sep>/where.cpp
#include <iostream>
using namespace std;
class Node{
public:
//data
int data;
//pointer to a next node
Node * next;
//construct that make ptr to NULL
Node(){
next = NULL; }
};
class Linkedlist{
//Head and circles are linked together
public:
//Head-> Node type ptr
Node * head;
Node * tail;
//Construct
Linkedlist(){
head = NULL;
tail = NULL;
}
//Circles linked inside each other
//Rules how circles will be linked
//Insert
void insert(int value){
//1st node is added
Node * temp = new Node;
//Insert data in Node
temp->data = value;
//1st Node only
if(head == NULL){
head = temp;
}
//any another Node only
else{
tail->next = temp;
}
tail = temp;
}
// for inserting a value at a point
void insertAt(int pos, int value){
//reach the place before the pos
Node * current = head;
int i =1;
while(i < pos) {
i++;
current = current->next;
}
}
//Deletion
//delete of last element
void delet(){
//store the tail in the temp
Node*temp = tail;
//before tail has to point the NULL
Node*current = head;
while(current-> next != tail){
current = current->next;}
}
//for deleting an element at a position
void deleteAt(int pos, int value){
//reach the place before the pos
Node * current = head;
int i =1;
while(i < pos) {
i++;
current = current->next;
}
}
//counting the number of Linklist
int count(int search_for)
{
Node * current = head;
int count = 0;
while (current != NULL)
{
count++;
current = current->next;
}
}
//Display
void display(){
Node * current = head;
while(current != NULL){
cout << current -> data << "->";
current = current->next;}
cout <<endl;
}
};
int main(){
Linkedlist l1;
l1.insert(1);
l1.insert(2);
l1.insert(3);
l1.insert(4);
l1.display();
return 0;
}
| ad83e195147dc5b824f4694d606adce34b2852dc | [
"C++"
] | 1 | C++ | 99rupali/lab2 | 38e33236fe2af53d7576463e96d9393436eba5e4 | b288b0a36d654eb360827219ad669d4a63f05dab | |
refs/heads/master | <file_sep>import ExpensesPage from "../frontend/pages/ExpensesPage";
function Index() {
return <ExpensesPage />;
}
export default Index;
<file_sep>import React, { useState } from "react";
import { useSpring, animated } from "react-spring";
import styles from "./ExpenseItem.module.css";
import Button from "./Button";
function ExpenseItem(props) {
console.log(props, " are props");
const [modal, setModal] = useState(false);
const months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
];
let date = null;
date = props.date
.slice(0, 10)
.split("-")
.map((element) => parseInt(element));
const day = date[2];
const month = months[date[1] - 1];
const offset = props.offset ? props.offset : 100;
const animation = useSpring({
from: {
opacity: 0
},
to: { opacity: 1 },
delay: offset
});
const archiveExpense = (thisExpenseId) => {
const newExpenses = props.allExpenses.map((expense) => {
if (expense.purchase_id == thisExpenseId) {
expense.archived = 1;
}
return expense;
});
props.setExpenses(newExpenses);
fetch("/api/setArchive", {
method: "put",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
id: thisExpenseId
})
});
};
const modalStyles = useSpring({
from: {
transform: "scale(0)"
},
to: { transform: `scale(${modal ? 1 : 0})` }
});
return (
<animated.div
style={animation}
className={styles.item}
onClick={() => {
setModal(true);
}}
>
<div className={styles.col}>
<p className={styles.day}>
{day}
<span className={styles.month}> {month}</span>
</p>
</div>
<div className={styles.col}>
<p className={styles.description}>{props.description}</p>
</div>
<div className={styles.col}>
<p className={styles.amount}>
{props.amount}
<span className={styles.euro}>€</span>
</p>
</div>
<animated.div style={modalStyles} className={styles.modal}>
<div className={styles.modal__body}>
<div className={styles.modal__expense}>
<p className={styles.modal__amount}>
{props.amount}
<span className={styles.modal__euro}>€</span>
</p>
<p className={styles.modal__meta}>
{props.description}, {day}. {month}
</p>
</div>
<div className={styles.modal__buttons}>
<Button
text={"Archive expense"}
handleClick={(e) => {
e.stopPropagation();
archiveExpense(props.expense_id);
setModal(false);
}}
/>
<Button
text={"Close modal"}
handleClick={(e) => {
e.stopPropagation();
setModal(false);
}}
/>
</div>
</div>
</animated.div>
</animated.div>
);
}
export default ExpenseItem;
<file_sep>const db = require("../../db");
const sql = require("sql-template-strings");
const express = require("express");
const app = express();
module.exports = app;
app.get("*", async (req, res) => {
const user = await db.query(sql`
SELECT * FROM owners
`);
res.set("Content-Type", "application/json");
res.end(JSON.stringify(user, null, 4));
});
<file_sep>import React from "react";
import App, { Container } from "next/app";
import Page from "../frontend/layout/Page";
import styles from "../frontend/layout/Page.module.css";
import { UserContextProvider } from "../frontend/context/UserContext";
export default class MyApp extends App {
constructor(props) {
super(props);
this.state = {
name: null,
id: null,
otherUsers: [],
selectedUsers: []
};
}
render() {
const { Component, pageProps } = this.props;
return (
<Container>
<UserContextProvider
value={{
name: this.state.name,
id: this.state.id,
otherUsers: this.state.otherUsers,
selectedUsers: this.state.selectedUsers,
switchUser: (name, id) => {
this.setState({
name,
id
});
},
setOtherUsers: (otherUsers) => {
this.setState({
otherUsers
});
},
setSelectedUsers: (selectedUser) => {
const selectedUsers = this.state.selectedUsers;
selectedUsers.push(selectedUser);
this.setState({
selectedUsers
});
}
}}
>
<Page className={styles.main}>
<Component {...pageProps} />
</Page>
</UserContextProvider>
</Container>
);
}
}
<file_sep>import styles from "./index.module.css";
import Link from "next/link";
import SignInPage from "../frontend/pages/SignInPage";
import Form from "../frontend/components/Form";
function Index() {
return <SignInPage />;
}
export default Index;
<file_sep>import React from "react";
import styles from "./Page.module.css";
function Page({ children }) {
return (
<React.Fragment>
<main className={styles.main}>{children}</main>
</React.Fragment>
);
}
export default Page;
<file_sep>import React, { useState } from "react";
import styles from "./MainModal.module.css";
import { useSpring, animated, interpolate } from "react-spring";
function MainModal(props) {
const animationProps = useSpring({
opacity: 1,
transform: `translate3d(${props.isOpen ? 0 : -360}px, 0 ,0)`,
from: {
opacity: props.isOpen ? 1 : 0,
transform: `translate3d(-360px, 0, 0)`
}
});
return (
<animated.div style={animationProps} className={styles.modal}>
<div className={styles.modal__body}>
{props.children}
<button className={styles.main__button} onClick={props.close}>
Close modal
</button>
</div>
</animated.div>
);
}
export default MainModal;
<file_sep>const db = require("../../db");
const sql = require("sql-template-strings");
const express = require("express");
const app = express();
module.exports = app;
app.get("*", async (req, res) => {
let id = req.query.id;
const expenses = await db.query(sql`
SELECT * FROM purchases
LEFT JOIN expenses ON purchases.id = expenses.purchase_id
WHERE owner_id = ${id}
`);
res.set("Content-Type", "application/json");
res.end(JSON.stringify(expenses, null, 4));
});
<file_sep>import React, { useState, useEffect } from "react";
import PartialExpense from "./PartialExpense";
import styles from "./FormSplitExpense.module.css";
import UserChip from "./UserChip";
function FormSplitExpense({
amount,
userdata,
setUserdata,
otherUsers,
selectedUsers
}) {
let usersThatCanBeAdded = otherUsers.map((user, index) => (
<UserChip
key={index}
name={user.name}
handleClick={() => {
const newSelectedUsers = selectedUsers;
// Add this user selectedUsers
newSelectedUsers.push(user);
debugger;
// Split the amount between the selected users
let numberOfUsers = newSelectedUsers.length;
newSelectedUsers.map((user) => {
user.amount = parseInt(amount) / numberOfUsers;
});
// Update state
setUserdata({ ...userdata, selectedUsers: newSelectedUsers });
}}
/>
));
let usersAddedToTheExpense = [];
if (selectedUsers) {
if (selectedUsers.length == 2) {
usersAddedToTheExpense = selectedUsers.map(
(userAddedToExpense, index) => {
return (
<PartialExpense
key={index}
currentUser={userAddedToExpense}
userdata={userdata}
setUserdata={setUserdata}
fullAmount={amount}
/>
);
}
);
}
}
return (
<div>
<div className={styles.selected_users}>{usersAddedToTheExpense}</div>
<div className={styles.split_expense}>
{usersAddedToTheExpense.length !== 2 && usersThatCanBeAdded}
</div>
</div>
);
}
export default FormSplitExpense;
<file_sep>const db = require("../../db");
const sql = require("sql-template-strings");
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
module.exports = app;
app.use(bodyParser.json());
app.put("*", async (req, res) => {
if (req.body == null) {
return res.status(400).send({ error: "no JSON object in the request" });
}
const id = req.body.id;
console.log("id is", id);
const query = await db.query(sql`
UPDATE purchases SET archived = 1 WHERE id = ${id}
`);
console.log("query is", query);
res.set("Content-Type", "application/json");
res.status(200).send(JSON.stringify(query, null, 4));
});
app.all("*", (req, res) => {
res.status(405).send({ error: "only PUT requests are accepted" });
});
<file_sep>import React, { useState } from "react";
import styles from "./Button.module.css";
function Button(props) {
return (
<button className={styles.button} onClick={props.handleClick}>
{props.text}
</button>
);
}
export default Button;
<file_sep>import React, { useState } from "react";
import styles from "./PartialExpense.module.css";
import Input from "./Input";
import { FaPlus, FaMinus } from "react-icons/fa";
function PartialExpense(props) {
console.log(props.userdata);
return (
<div className={styles.main}>
<p>{props.currentUser.name} paid</p>
<div className={styles.input_group}>
<button
className={styles.button}
onClick={() => {
const newSelectedUsers = props.userdata.selectedUsers;
props.userdata.selectedUsers.map((user) => {
if (user == props.currentUser) {
user.amount -= 1;
} else {
user.amount += 1;
}
props.setUserdata({
...props.userdata,
selectedUsers: newSelectedUsers
});
return user;
});
}}
>
<FaMinus />
</button>
<input
className={styles.input}
name={"Amount"}
type={"number"}
onChange={(e) => {
const localSelectedUsers = props.userdata.selectedUsers.map(
(localSelectedUser) => {
const inputAmount = parseInt(e.target.value);
if (localSelectedUser === props.currentUser) {
if (inputAmount <= props.fullAmount && inputAmount >= 0)
localSelectedUser.amount = inputAmount;
} else {
if (inputAmount <= props.fullAmount && inputAmount >= 0)
localSelectedUser.amount = props.fullAmount - inputAmount;
}
return localSelectedUser;
}
);
props.setUserdata({
...props.userdata,
selectedUsers: localSelectedUsers
});
}}
value={props.currentUser.amount}
/>
<button
className={styles.button}
onClick={() => {
const newSelectedUsers = props.userdata.selectedUsers;
props.userdata.selectedUsers.map((user) => {
if (user == props.currentUser) {
user.amount += 1;
} else {
user.amount -= 1;
}
props.setUserdata({
...props.userdata,
selectedUsers: newSelectedUsers
});
return user;
});
}}
>
<FaPlus />
</button>
</div>
</div>
);
}
export default PartialExpense;
<file_sep>// _document is only rendered on the server side and not on the client side
// Event handlers like onClick can't be added to this file
// ./pages/_document.js
import Document, { Html, Head, Main, NextScript } from "next/document";
class MyDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx);
return { ...initialProps };
}
render() {
return (
<Html>
<Head>
<meta
name="viewport"
content="initial-scale=1.0, width=device-width"
/>
<link
href="https://fonts.googleapis.com/css?family=Montserrat:400,700|Raleway:400,700"
rel="stylesheet"
/>
<style>{`
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: Raleway, sans-serif;
color: #424242;
}
`}</style>
</Head>
<body className="custom_class">
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
<file_sep>const db = require("../../db");
const sql = require("sql-template-strings");
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
module.exports = app;
app.use(bodyParser.json());
app.post("*", async (req, res) => {
if (req.body == null) {
return res.status(400).send({ error: "no JSON object in the request" });
}
const insertPurchaseResults = await db.query(sql`
INSERT INTO purchases (description, archived, date) VALUES (${
req.body.description
}, ${req.body.archived}, ${req.body.date});
`);
let insertExpense = null;
if (!req.body.owners) {
insertExpense = await db.query(sql`
INSERT INTO expenses ( amount, owner_id, purchase_id, full_amount) VALUES ( ${
req.body.amount
}, ${req.body.owner}, ${insertPurchaseResults.insertId}, ${req.body.amount})
`);
} else {
let fullAmount = 0;
for (const user of req.body.owners) {
insertExpense = await db.query(sql`
INSERT INTO expenses ( amount, owner_id, purchase_id, full_amount) VALUES ( ${
user.amount
}, ${user.id}, ${insertPurchaseResults.insertId}, ${req.body.amount})
`);
fullAmount += user.amount;
}
}
res.set("Content-Type", "application/json");
res.status(200).send(JSON.stringify(insertExpense, null, 4));
});
app.all("*", (req, res) => {
res.status(405).send({ error: "only POST requests are accepted" });
});
// loon uue kulutuse
// INSERT INTO purchases (description, archived) VALUES ('test', false);
// Võtan viimase kulutuse id kasutades counti
// SELECT COUNT(*) from purchases;
// Leian kasutaja
// SELECT id from owners WHERE name = 'Mart'
// Teen uue expense-i kusjuures väärtused owner_id ja purchase_id tulevad varasematest päringutest
// INSERT INTO expenses ( amount, owner_id, purchase_id) VALUES ( ... , ... , ...)
<file_sep># Next Expenses
This project is created to learn more about Next.js and deploying with Now, not to mention
It was aliased to [https://nextjs.martlepanen.now.sh]. It is now archived. See the repo 'Expenses' for the current "branch" of this project.
https://nextjs.martlepanen.now.sh
## Features
Select your (pre-created) user and log your expenses. You are able to set
the amount, date, and description of your expense. You can also split an
expense in two (between another already created user). Created expenses can
be archived to prevent them from being displayed.
## To Do
- Allow user creation.
- Allow more than two way expense splitting.
- Show archived expenses.
<file_sep>import React, { useState } from "react";
import styles from "./Form.module.css";
import Button from "./Button";
import Input from "./Input";
import FormSplitExpense from "./FormSplitExpense";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker-cssmodules.css";
import { useContext } from "react";
import { UserContext } from "../context/UserContext";
function Form() {
const [form, setForm] = useState({
description: "",
amount: 0,
date: new Date()
});
let { selectedUsers, otherUsers } = useContext(UserContext);
let currentUserId = useContext(UserContext).id;
let currentUserName = useContext(UserContext).name;
const [userdata, setUserdata] = useState({
selectedUsers: [
{
id: currentUserId,
name: currentUserName
}
],
otherUsers
});
const [splitExpense, setSplitExpense] = useState(false);
const handleChange = (event) => {
const target = event.target;
const value = target.type === "checkbox" ? target.checked : target.value;
const name = target.name;
if (target.name === "description") {
setForm({ ...form, description: value });
}
if (target.name === "amount") {
setForm({ ...form, amount: parseInt(value) });
}
};
const handleDateChange = (date) => {
setForm({ ...form, date: date });
};
const handleSubmit = () => {
let expense = {};
if (userdata.selectedUsers.length > 1) {
expense = {
description: form.description,
amount: form.amount,
owners: userdata.selectedUsers,
date: form.date
};
} else {
expense = {
description: form.description,
amount: form.amount,
owner: currentUserName,
date: form.date
};
}
addExpense(expense);
setSplitExpense(false);
const initialSelectedUsers = [
{
id: currentUserId,
name: currentUserName
}
];
setUserdata({ ...userdata, selectedUsers: initialSelectedUsers });
setForm({ ...form, description: "", amount: 0 });
};
const addExpense = (expense) => {
const description = expense.description;
const date = expense.date;
const amount = expense.amount;
const owners = expense.owners ? expense.owners : null;
fetch("/api/postToDb", {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
owner: currentUserId,
owners: owners,
description: description,
amount: amount,
date: date,
archived: false
})
});
};
const discardExpense = () => {
const newDate = new Date();
setForm({ ...form, description: "", amount: 0, date: newD });
};
const handleSplitExpense = () => {
setSplitExpense(true);
};
return (
<div>
<form className={styles.form}>
<div className={styles.inputGroup}>
<Input
name="amount"
type="number"
handleChange={handleChange}
value={form.amount}
/>
</div>
<div className={styles.inputGroup}>
<Input
name="description"
type="text"
handleChange={handleChange}
value={form.description}
/>
</div>
<div>
<label className={styles.row}>
Date:
<DatePicker selected={form.date} onChange={handleDateChange} />
</label>
</div>
</form>
<div className={styles.formButtons}>
{!splitExpense && (
<Button text={"Split expense"} handleClick={handleSplitExpense} />
)}
{splitExpense && (
<FormSplitExpense
amount={form.amount}
userdata={userdata}
setUserdata={setUserdata}
selectedUsers={userdata.selectedUsers}
otherUsers={userdata.otherUsers}
/>
)}
<Button text={"Add expense"} handleClick={handleSubmit} />
<Button text={"Discard expense"} handleClick={discardExpense} />
</div>
</div>
);
}
export default Form;
<file_sep>import styles from "./SignInPage.module.css";
import Button from "../components/Button";
import { useContext } from "react";
import { UserContext } from "../context/UserContext";
import { useState, useEffect } from "react";
import Link from "next/link";
function useEffectUsers() {
const [users, setUsers] = useState({});
useEffect(function() {
// This is from <NAME>,
// https://youtu.be/1C_XpWdbimM?t=1351
// useEffect takes a function, which in turn contains an IIFE
(async () => {
const result = await fetch("http:///api.martpart.ee/getUsers", {
method: "get"
});
console.log({result})
let usersFromDB = await result.json();
setUsers(usersFromDB);
})();
}, []);
if (users.length == undefined) {
return ["Loading"];
} else {
if (process.browser) {
localStorage.setItem("users", JSON.stringify(users));
}
return users;
}
}
export default function SignInPage() {
const { name, switchUser, setOtherUsers } = useContext(UserContext);
let users = null;
let localUsers = null;
// Local Storage
if (process.browser) {
localUsers = localStorage.getItem("users");
}
if (localUsers) {
users = JSON.parse(localUsers);
} else {
users = useEffectUsers();
}
if (name) {
return (
<React.Fragment>
<div className={styles.main}>
<h1>Hello, {name}</h1>
<div>
<Link href="/expenses">
<a>Go to Expenses</a>
</Link>
</div>
</div>
</React.Fragment>
);
} else {
return (
<React.Fragment>
<div className={styles.main}>
<h1>Please choose a user</h1>
<div className={styles.users}>
{users.length > 1 &&
users.map((user, index) => (
<Button
key={index}
handleClick={() => {
const otherUsers = users.filter(
(otherUser) => user !== otherUser
);
switchUser(user.name, user.id);
setOtherUsers(otherUsers);
}}
text={user.name}
/>
))}
</div>
</div>
</React.Fragment>
);
}
}
| 565ee8aa020f38e260937051391b9655315580e6 | [
"JavaScript",
"Markdown"
] | 17 | JavaScript | Martialis39/next-expenses | 60ae3786404af35036c3a268792ee4283ce83e58 | 305b6b5c620e63c8b3ba9d64d8c6da0e2661bb81 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.