branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep>class Game {
constructor () {
this.points = 0;
document.body.addEventListener('click', () => {
++this.points;
this.writePoints();
});
}
writePoints () {
document.getElementById('points').innerText = this.points;
}
}
var game = new Game();
|
897ddd899c2a1dded35545902c2519f7890b4769
|
[
"JavaScript"
] | 1
|
JavaScript
|
abejfehr/startup
|
ea04aed21574cb899b90346a0bf7e00d008c2e73
|
e8d39c7e0db3bb003e5cb811ea71129f48676882
|
refs/heads/master
|
<repo_name>SteveFrank/cython_code_repository<file_sep>/01-c-python/setup.py
from distutils.core import setup
from Cython.Build import cythonize
# 使用打包命令 python3 setup.py build_ext --inplace
setup(
ext_modules=cythonize("helloworld.pyx")
)
<file_sep>/c-python-callingCfuncions/setup.py
from setuptools import setup, Extension
from Cython.Build import cythonize
ext_modules = [
Extension("demo", sources=["demo.pyx"], libraries=["m"])
]
setup(
name="Demos",
ext_modules=cythonize(ext_modules),
)
<file_sep>/03-c-python-primes/setup.py
from setuptools import setup
from Cython.Build import cythonize
# 使用打包命令 python3 setup.py build_ext --inplace
# 打印转化分析 annotate=True
setup(
ext_modules=cythonize("primes.pyx", annotate=True),
)
<file_sep>/02-c-python-fibonacci/setup.py
from setuptools import setup
from Cython.Build import cythonize
# 使用打包命令 python3 setup.py build_ext --inplace
setup(
ext_modules=cythonize("fib.pyx"),
)
|
0fc7b52643025b3fb7440196b8278efb07fb55f6
|
[
"Python"
] | 4
|
Python
|
SteveFrank/cython_code_repository
|
6b9973af6c7d4a63039879bb0630dabb6c8ac426
|
4bdbda34bd2ac154ffe0517e15fcda0b8c723349
|
refs/heads/master
|
<file_sep>/**
*
* @param offset
* @param isPositiveOffset the flag, which determines if the zone has positive or negative offset
* 00:00 is considered a positive zone
* @param s separator
*/
export function isValidZoneOffset(
offset: string,
isPositiveOffset: boolean,
s = ':',
): boolean {
const validator = new RegExp(
isPositiveOffset
? `^(0(?!(2${s}4)|0${s}3)|1(?=([0-1]|2(?=${s}[04])|[34](?=${s}0))))([03469](?=${s}[03])|[17](?=${s}0)|2(?=${s}[04])|5(?=${s}[034])|8(?=${s}[04]))${s}([03](?=0)|4(?=5))[05]$`
: `^(0(?=[^0])|1(?=[0-2]))([39](?=${s}[03])|[0-24-8](?=${s}00))${s}[03]0$`,
);
return validator.test(offset);
}
<file_sep># iso-datestring-validator
## What is it
A simple package for validating strings denoting dates and time, including ISO 8601 format. The package provides the following functions:
1. **Date validation**. YYYY-MM-DD format from 0001-01-01 to 9999-12-31, leap year friendly. Custom digit separators and null separators supported: YYYY/MM/DD or YYYYMMDD is no problem.
2. **Time validation**. HH:mm:ss.fff±hh:mm format, seconds, fractions of seconds and timezone offset being optional. Custom digit separators supported for HHmmss as well (no custom separator for fractions, it is dot).
**Caveat**: do not use '-' and '+' as separators when validating time with timezone. I am reluctant to fix this unless it is an issue.
```
isValidTime('14-45-15.000+00-00', '-', true)
// will yield wrong result
```
3. **Year-month validation**.
4. **ISO 8601 datestring validation** with timezones, with and without separators:
- 2019-07-09T15:03:36.000+00:00
- 2019-07-09T15:03:36Z
- 20190709T150336Z
## Installation
```
npm i --save iso-datestring-validator
```
or
```
yarn add iso-datestring-validator
```
## Import
```
import * as isoDatestringValidator from 'iso-datestring-validator';
```
alternatively you can import the function that you need separately:
```
import {
isValidDate,
isValidISODateString,
isValidTime,
isValidYearMonth,
} from 'iso-datestring-validator';
```
## Usage
### Date validation
Pass a **YYYY-MM-DD** date string to the **isValidDate** function to check it. To validate dates that use a custom digit separator, pass it as the second argument.
```
import { isValidDate } from 'iso-datestring-validator';
isValidDate('2019-01-31');
// true
isValidDate('20190131');
// false, no custom digit separator provided, hyphen separator not found in the string
isValidDate('20190131', '');
// true
isValidDate('2019/01/31', '/');
// true
```
### Time validation
Time string in HH:mm:ss.fff±hh:mm format can be validated with the **isValidTime** function. Seconds and fractions are optional. However, if using fractions min number of numbers is 1 and max is 9. Zone offset is optional as well, its check is switched off by default.
```
import { isValidTime } from 'iso-datestring-validator';
isValidTime('13:00');
// true
isValidTime('13:00:00');
// true
isValidTime('13:00:00.000000000');
// true
// pass time, separator and boolean flag to enable zone offset check
isValidTime('14:45:15.000+00:00', ':', true)
// true
// you can take advantage of default separator if you pass undefined as second param
isValidTime('14:45:15.000+00:00', undefined, true)
// true
isValidTime('144515.000Z', '', true)
// true
```
### Year and month validation
These are validated by the **isValidYearMonth** function. Rules same as in the previous case: a string **YYYY-MM** and a custom digit separator if required.
```
import { isValidYearMonth } from 'iso-datestring-validator';
isValidYearMonth('2019/01', '/');
// true
isValidYearMonth('2019-01');
// true
```
### ISO 8601 datestring validation
Pass a string to **isValidISODateString** to see if it is valid.
```
import { isValidISODateString } from 'iso-datestring-validator';
isValidISODateString('2019-07-09T15:03:36.000+00:00');
// true
isValidISODateString('20190709T150336Z');
// true
```
That's all about this package. Have fun, feel free to contribute with some test :]
<file_sep>import { getStringSeparator } from '../get-string-separator/get-string-separator.function';
import { isValidDate } from '../is-valid-date/is-valid-date.function';
import { isValidTime } from '../is-valid-time/is-valid-time.function';
export function isValidISODateString(dateString: string): boolean {
const [date, timeWithOffset] = dateString.split('T');
const dateSeparator = getStringSeparator(date);
const isDateValid = isValidDate(date, dateSeparator);
if (!timeWithOffset) {
return false;
}
return isDateValid && isValidTime(timeWithOffset, getTimeStringSeparator(timeWithOffset), true);
}
function getTimeStringSeparator(timeString: string): string {
const matches = timeString.match(/[^Z+\-\d]/);
return Array.isArray(matches) ? matches[0] : '';
}
<file_sep>/**
*
* @param date YYYY-MM
* @param s separator between hours and minutes
*/
export function isValidYearMonth(date: string, s = '-'): boolean {
const validator = new RegExp(`^[0-9]{4}${s}(0(?=[^0])|1(?=[0-2]))[0-9]$`);
return validator.test(date);
}
<file_sep>export function getStringSeparator(dateString: string): string {
const separator = /\D/.exec(dateString);
return separator ? separator[0] : '';
}
<file_sep>export * from './is-valid-date/is-valid-date.function';
export * from './is-valid-iso-datestring/is-valid-iso-datestring.function';
export * from './is-valid-time/is-valid-time.function';
export * from './is-valid-year-month/is-valid-year-month.function';
<file_sep>import { NEGATIVE_TIMEZONES } from '../tests/constants/timezones/negative-timezones.const';
import { POSITIVE_TIMEZONES } from '../tests/constants/timezones/positive-timezones.const';
import { pad } from '../tests/utility-functions/pad.function';
import { isValidZoneOffset } from './is-valid-timezone-offset.function';
const maxDigits = 2;
test(`isValidZoneOffset. expect all negative offsets to validate`, () => {
// Arrange
let results: boolean[];
// Act
results = NEGATIVE_TIMEZONES.map((i) => isValidZoneOffset(i, false));
// Assert
expect(results).not.toContain(false);
});
test(`isValidZoneOffset. expect all positive offsets to validate`, () => {
// Arrange
let results: boolean[];
// Act
results = POSITIVE_TIMEZONES.map((i) => isValidZoneOffset(i, true));
// Assert
expect(results).not.toContain(false);
});
test(`isValidZoneOffset. expect all non-existing negative zones to fail validation`, () => {
// Arrange
const negativeResults: boolean[] = [];
// Act
for (let x = 0; x < 100; x++) {
for (let y = 0; y < 100; y++) {
const offset = `${pad(x.toString(), maxDigits)}:${pad(
y.toString(),
maxDigits,
)}`;
if (!NEGATIVE_TIMEZONES.includes(offset)) {
negativeResults.push(isValidZoneOffset(offset, false));
}
}
}
// Assert
expect(negativeResults).not.toContain(true);
});
test(`isValidZoneOffset. expect all non-existing positive zones to fail validation`, () => {
// Arrange
const negativeResults: boolean[] = [];
// Act
for (let x = 0; x < 100; x++) {
for (let y = 0; y < 100; y++) {
const offset = `${pad(x.toString(), maxDigits)}:${pad(
y.toString(),
maxDigits,
)}`;
if (!POSITIVE_TIMEZONES.includes(offset)) {
negativeResults.push(isValidZoneOffset(offset, true));
}
}
}
// Assert
expect(negativeResults).not.toContain(true);
});
<file_sep>/** add extra zeros to number if needed */
export function pad(numberStr: string, max: number): string {
return numberStr.length < max ? pad('0' + numberStr, max) : numberStr;
}
<file_sep>import { SOME_VALID_ISO_DATETIME_STRINGS } from '../tests/constants/some-valid-iso-strings.const';
import { NEGATIVE_TIMEZONES } from '../tests/constants/timezones/negative-timezones.const';
import { POSITIVE_TIMEZONES } from '../tests/constants/timezones/positive-timezones.const';
import { isValidISODateString } from './is-valid-iso-datestring.function';
const noZoneValidISODateTimeString = '2019-07-09T15:03:36';
test(`isValidISODateString. expect all valid ISO 8601 strings to validate`, () => {
// Arrange
let results: boolean[];
// Act
results = SOME_VALID_ISO_DATETIME_STRINGS.map((s) => isValidISODateString(s));
// Assert
expect(results).not.toContain(false);
expect(results).toMatchSnapshot();
});
test(`isValidISODateString. expect a valid ISO string to validate with all negative zone offsets`, () => {
// Arrange
let results: boolean[];
// Act
results = NEGATIVE_TIMEZONES.map((s) =>
isValidISODateString(`${noZoneValidISODateTimeString}-${s}`),
);
// Assert
expect(results).not.toContain(false);
expect(results).toMatchSnapshot();
});
test(`isValidISODateString. expect a valid ISO string to validate with all positive zone offsets`, () => {
// Arrange
let results: boolean[];
// Act
results = POSITIVE_TIMEZONES.map((s) =>
isValidISODateString(`${noZoneValidISODateTimeString}+${s}`),
);
// Assert
expect(results).not.toContain(false);
expect(results).toMatchSnapshot();
});
test('isValidISODateString does not validate date without time', () => {
// Arrange
const date = '2020-12-04';
// Act
const isValid = isValidISODateString(date);
// Assert
expect(isValid).toBeFalsy();
});
<file_sep>/**
*
* @param date YYYY-MM-DD
* @param s separator symbol between years, months and days
*/
export function isValidDate(date: string, s = '-'): boolean {
const validator = new RegExp(
`^(?!0{4}${s}0{2}${s}0{2})((?=[0-9]{4}${s}(((0[^2])|1[0-2])|02(?=${s}(([0-1][0-9])|2[0-8])))${s}[0-9]{2})|(?=((([13579][26])|([2468][048])|(0[48]))0{2})|([0-9]{2}((((0|[2468])[48])|[2468][048])|([13579][26])))${s}02${s}29))([0-9]{4})${s}(?!((0[469])|11)${s}31)((0[1,3-9]|1[0-2])|(02(?!${s}3)))${s}([0-2][0-9]|3[0-1])$`,
);
return validator.test(date);
}
<file_sep>import { getStringSeparator } from '../get-string-separator/get-string-separator.function';
import { isValidZoneOffset } from '../is-valid-timezone-offset/is-valid-timezone-offset.function';
/**
*
* @param timeWithOffset hh:mm:ss(optional)±hh:mm(optional)
* @param s separator between hours, minutes and optional seconds
* @param isTimezoneCheckOn boolean flag, pass true not to check for valid timezone
*/
export function isValidTime(timeWithOffset: string, s = ':', isTimezoneCheckOn = false): boolean {
const validator = new RegExp(
`^([0-1]|2(?=([0-3])|4${s}00))[0-9]${s}[0-5][0-9](${s}([0-5]|6(?=0))[0-9])?(\.[0-9]{1,9})?$`,
);
if (!isTimezoneCheckOn || !/[Z+\-]/.test(timeWithOffset)) {
return validator.test(timeWithOffset);
}
/** Case we got time in Zulu tz */
if (/Z$/.test(timeWithOffset)) {
return validator.test(timeWithOffset.replace('Z', ''));
}
const isPositiveTimezoneOffset = timeWithOffset.includes('+');
const [time, offset] = timeWithOffset.split(/[+-]/);
return validator.test(time) && isValidZoneOffset(offset, isPositiveTimezoneOffset, getStringSeparator(offset));
}
<file_sep>export const SOME_VALID_ISO_DATETIME_STRINGS: Readonly<string[]> = [
'2019-07-09T15:03:36.000+00:00',
'2019-07-09T15:03:36Z',
'20190709T150336Z',
'0001-12-31T00:01:15+00:00',
];
<file_sep>import moment from 'moment';
import { pad } from '../tests/utility-functions/pad.function';
import { isValidDate } from './is-valid-date.function';
function isValidDateAsyncWrapper(date: string, s = '-') {
return Promise.resolve(isValidDate(date, s));
}
test(`${isValidDate.name}. expect all moment dates from 0001 up to year 5000 to be true. also expect all ISO strings to validate`, async () => {
// Arrange
const dateFormat = 'YYYY-MM-DD';
const startDate = '0001-01-01';
const endYear = 5000;
const date = moment(startDate, dateFormat);
const promisedResults: Array<Promise<boolean>> = [];
let results: boolean[];
// Act
while (date.year() < endYear) {
const currentDate = date.format(dateFormat);
promisedResults.push(isValidDateAsyncWrapper(currentDate));
date.add(1, 'd');
}
results = await Promise.all(promisedResults);
// Assert
expect(results).not.toContain(false);
expect(results).toMatchSnapshot();
});
test(`${isValidDate.name}. expect all moment dates from 5000 up to year 10000 to be true. also expect all ISO strings to validate`, async () => {
// Arrange
const dateFormat = 'YYYY-MM-DD';
const startDate = '5000-01-01';
const endYear = 10000;
const date = moment(startDate, dateFormat);
const promisedResults: Array<Promise<boolean>> = [];
let results: boolean[];
// Act
while (date.year() < endYear) {
const currentDate = date.format(dateFormat);
promisedResults.push(isValidDateAsyncWrapper(currentDate));
date.add(1, 'd');
}
results = await Promise.all(promisedResults);
// Assert
expect(results).not.toContain(false);
expect(results).toMatchSnapshot();
});
test(`${isValidDate.name}. expect function to return true, if passed an empty separator with a valid date`, () => {
// Arrange
const date = '20190101';
const separator = '';
let result: boolean;
// Act
result = isValidDate(date, separator);
// Assert
expect(result).toBe(true);
});
test(`${isValidDate.name}. expect function to return false, if a valid date contains an invalid digit separator`, () => {
// Arrange
const date = '2019/01/01';
let result: boolean;
// Act
result = isValidDate(date);
// Assert
expect(result).toBe(false);
});
test(`${isValidDate.name}. expect function to return true, if valid date contains an different digit separator, which is provided as an argument`, () => {
// Arrange
const date = '2019/01/01';
const separator = '/';
let result: boolean;
// Act
result = isValidDate(date, separator);
// Assert
expect(result).toBe(true);
});
test(`${isValidDate.name}. expect 29 February to validate on leap years and fail on non-leap years from year 0001 to year 10000`, () => {
// Arrange
let year = 1;
const maxYear = 10000;
const digits = 4;
const negativeChecks: boolean[] = [];
const positiveChecks: boolean[] = [];
// Act
do {
const decemberDate = `${pad(year.toString(), digits)}-02-29`;
const isLeapYear = moment([year]).isLeapYear();
const result = isValidDate(decemberDate);
isLeapYear ? positiveChecks.push(result) : negativeChecks.push(result);
} while (++year < maxYear);
// Assert
expect(positiveChecks).not.toContain(false);
expect(negativeChecks).not.toContain(true);
expect(positiveChecks).toMatchSnapshot();
expect(negativeChecks).toMatchSnapshot();
});
test(`${isValidDate.name}. expect only 1-12 months to pass validation, 13-99 to fail`, () => {
// Arrange
let month = 1;
const digits = 2;
const negativeChecks: boolean[] = [];
const positiveChecks: boolean[] = [];
// Act
do {
const date = `2019-${pad(month.toString(), digits)}-01`;
const result = isValidDate(date);
month < 13 ? positiveChecks.push(result) : negativeChecks.push(result);
} while (++month < 100);
// Assert
expect(positiveChecks).not.toContain(false);
expect(negativeChecks).not.toContain(true);
expect(positiveChecks).toMatchSnapshot();
expect(negativeChecks).toMatchSnapshot();
});
test(`${isValidDate.name}. expect all dates after 31st to always fail for all months`, () => {
// Arrange
const maxDigits = 2;
const results: boolean[] = [];
// Act
for (let month = 1; month < 13; month++) {
let day = 32;
do {
const date = `2019-${pad(month.toString(), maxDigits)}-${day}`;
results.push(isValidDate(date));
} while (++day < 100);
}
// Assert
expect(results).not.toContain(true);
expect(results).toMatchSnapshot();
});
test(`${isValidDate.name}. September, April, June and November have 30 days, expect false when these months have 31st date`, () => {
// Arrange
const months = ['04', '06', '09', '11'];
let results: boolean[];
// Act
results = months.map((m) => isValidDate(`2019-${m}-31`));
// Assert
expect(results).not.toContain(true);
expect(results).toMatchSnapshot();
});
test(`${isValidDate.name}. February cannot have 30+ days`, () => {
// Arrange
const nonExistentFebruaryDays = ['2019-02-30', '2019-02-31'];
let results: boolean[];
// Act
results = nonExistentFebruaryDays.map((i) => isValidDate(i));
// Assert
expect(results).not.toContain(true);
expect(results).toMatchSnapshot();
});
<file_sep>import { pad } from '../tests/utility-functions/pad.function';
import { isValidYearMonth } from './is-valid-year-month.function';
/** max number of digits in hour/minute */
const maxDigits = 2;
test(`isValidYearMonth. expect months 01-12 to pass, 00 and 13+ to fail`, () => {
// Arrange
const positiveResults: boolean[] = [];
const negativeResults: boolean[] = [];
// Act
for (let month = 0; month < 100; month++) {
const validationResult = isValidYearMonth(
`2019-${pad(month.toString(), maxDigits)}`,
);
month > 0 && month < 13
? positiveResults.push(validationResult)
: negativeResults.push(validationResult);
}
// Assert
expect(positiveResults).not.toContain(false);
expect(negativeResults).not.toContain(true);
});
test(`isValidYearMonth. expect YYYYMM to validate when passed empty separator, else to fail`, () => {
// Arrange
const date = '201901';
const separator = '';
let positiveResult: boolean;
let negativeResult: boolean;
// Act
positiveResult = isValidYearMonth(date, separator);
negativeResult = isValidYearMonth(date);
// Assert
expect(positiveResult).toBe(true);
expect(negativeResult).toBe(false);
});
<file_sep>import { NEGATIVE_TIMEZONES } from '../tests/constants/timezones/negative-timezones.const';
import { POSITIVE_TIMEZONES } from '../tests/constants/timezones/positive-timezones.const';
import { pad } from '../tests/utility-functions/pad.function';
import { isValidTime } from './is-valid-time.function';
/** max number of digits in hour/minute */
const maxDigits = 2;
test(`isValidTime. expect all hours with 0 minutes from 00:00 to 24:00 to validate true, 25+ hours to validate false`, () => {
// Arrange
const negativeResults: boolean[] = [];
const positiveResults: boolean[] = [];
// Act
for (let hour = 0; hour <= 99; hour++) {
const validationResult = isValidTime(
`${pad(hour.toString(), maxDigits)}:00:00`,
);
hour < 25
? positiveResults.push(validationResult)
: negativeResults.push(validationResult);
}
// Assert
expect(positiveResults).not.toContain(false);
expect(negativeResults).not.toContain(true);
expect(positiveResults).toMatchSnapshot();
expect(negativeResults).toMatchSnapshot();
});
test(`isValidTime. expect all minutes to validate beween 0 and 59, and to fail afterwards (from 60 to 99)`, () => {
// Arrange
const negativeResults: boolean[] = [];
const positiveResults: boolean[] = [];
// Act
for (let minute = 0; minute <= 99; minute++) {
const validationResult = isValidTime(
`00:${pad(minute.toString(), maxDigits)}:00`,
);
minute < 60
? positiveResults.push(validationResult)
: negativeResults.push(validationResult);
}
// Assert
expect(positiveResults).not.toContain(false);
expect(negativeResults).not.toContain(true);
expect(positiveResults).toMatchSnapshot();
expect(negativeResults).toMatchSnapshot();
});
test(`isValidTime. expect 24:00 to validate and 24:01-59 to fail`, () => {
// Arrange
const negativeResults: boolean[] = [];
const positiveResults: boolean[] = [];
// Act
for (let minute = 0; minute <= 59; minute++) {
const validationResult = isValidTime(
`24:${pad(minute.toString(), maxDigits)}`,
);
minute === 0
? positiveResults.push(validationResult)
: negativeResults.push(validationResult);
}
// Assert
expect(positiveResults).not.toContain(false);
expect(negativeResults).not.toContain(true);
expect(positiveResults).toMatchSnapshot();
expect(negativeResults).toMatchSnapshot();
});
test(`isValidTime. HH:mm to validate if empty separator is passed`, () => {
// Arrange
const time = '2200';
const separator = '';
let result: boolean;
// Act
result = isValidTime(time, separator);
// Assert
expect(result).toBe(true);
});
test(`isValidSeconds. expect seconds to validate only from 0 to 60, to fail when > 60`, () => {
// Arrange
const negativeResults: boolean[] = [];
const positiveResults: boolean[] = [];
// Act
for (let second = 0; second < 100; second++) {
const validationResult = isValidTime(
`00:00:${pad(second.toString(), maxDigits)}.000`,
);
second <= 60
? positiveResults.push(validationResult)
: negativeResults.push(validationResult);
}
// Assert
expect(positiveResults).not.toContain(false);
expect(negativeResults).not.toContain(true);
expect(positiveResults).toMatchSnapshot();
expect(negativeResults).toMatchSnapshot();
});
test(`isValidTime. expect time to validate when no separator provided`, () => {
// Arrange
const time = '00:00:00.111';
const separator = ':';
let result: boolean;
// Act
result = isValidTime(time, separator);
// Assert
expect(result).toBe(true);
});
test(`isValidTime.expect to validate with timezome`, () => {
// Arrange
const time = '14:45:15Z';
let result: boolean;
// Act
result = isValidTime(time, undefined, true);
// Assert
expect(result).toBe(true);
});
test(`isValidTime.expect to validate with timezome and no separators`, () => {
// Arrange
const time = '144515Z';
let result: boolean;
// Act
result = isValidTime(time, '', true);
// Assert
expect(result).toBe(true);
});
test(`isValidTime.expect to validate with positive timezones`, () => {
// Arrange
const time = '144515';
let results: boolean[];
// Act
results = POSITIVE_TIMEZONES.map((z) => isValidTime(`${time}+${z}`, '', true));
// Assert
expect(results).not.toContain(false);
});
test(`isValidTime.expect to validate with positive timezones which have no separator`, () => {
// Arrange
const time = '144515';
let results: boolean[];
// Act
results = POSITIVE_TIMEZONES.map((z) => isValidTime(`${time}+${z.replace(/\D/g, '')}`, '', true));
// Assert
expect(results).not.toContain(false);
});
test(`isValidTime.expect to validate with negative timezones`, () => {
// Arrange
const time = '144515';
let results: boolean[];
// Act
results = NEGATIVE_TIMEZONES.map((z) => isValidTime(`${time}-${z}`, '', true));
// Assert
expect(results).not.toContain(false);
});
test(`isValidTime.expect to validate with negative timezones which have no separator`, () => {
// Arrange
const time = '144515';
let results: boolean[];
// Act
results = NEGATIVE_TIMEZONES.map((z) => isValidTime(`${time}-${z.replace(/\D/g, '')}`, '', true));
// Assert
expect(results).not.toContain(false);
});
test(`isValidTime.expect to validate with - separators`, () => {
// Arrange
const time = '14-45-15';
let results: boolean;
// Act
results = isValidTime(time, '-', false);
// Assert
expect(results).toBe(true);
});
<file_sep>const glob = require('glob');
const { minify } = require('terser');
const { readFileSync, writeFileSync } = require('fs');
// options is optional
glob('dist/**/*.js', (er, files) => {
files.forEach(async file => {
const code = readFileSync(file, 'utf8');
const res = await minify(code, { mangle: { toplevel: true } });
writeFileSync(file, res.code);
});
});
|
7e4a98d2a7fec1c27568de15a416e592e26a9bf7
|
[
"Markdown",
"TypeScript",
"JavaScript"
] | 16
|
TypeScript
|
joaojmendes/iso-datestring-validator
|
57d4d12f30e3862f1d804212ff47ed8137c59158
|
5fa7d83eb8450d2d43e181474d1f160c239cb97f
|
refs/heads/master
|
<file_sep>// swift-tools-version:4.0
// Copyright (c) 2016 IBM Corp.
//
// 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.
//
import PackageDescription
let package = Package(
name: "SwiftCloudant",
products: [
.library(name: "SwiftCloudant", targets: ["SwiftCloudant"])
],
targets: [
.target(name: "SwiftCloudant", dependencies: [])
]
)
|
a6d6d7b30515eb4fa6d4d3e0640b1e9c2ff140c5
|
[
"Swift"
] | 1
|
Swift
|
timokoenig/swift-cloudant
|
2515897caad6f45fe165b114fedc58e979b4f79c
|
55751daba9faf85efcdaac6fc8e05e668c975e4c
|
refs/heads/master
|
<repo_name>h0tw1r3/php-sharedmemarray<file_sep>/README.md
# SharedMemArray
SharedMemArray is intended to be a simple pattern for quickly creating shared memory arrays with PHP 5.3+.
Should be thread safe but has not been proven under heavy load yet.
Requires shmop, and msgpack.
## Authors and contributors
* [<NAME>](https://github.com/h0tw1r3)
## License
[BSD 2-Clause License](http://www.opensource.org/licenses/bsd-license.php)
## Using SharedMemArray
Singleton, extend class, good times? See example.php.
<file_sep>/example.php
<?php
require_once 'memcache_servers.php';
$servers = MemcacheServers::getInstance();
foreach($servers as $ip => $status) {
if ($servers->isDown($ip)) {
printf("%s DOWN\n", $ip);
} else {
printf("%s %s\n", $ip, var_export($status,1));
}
}
#$servers->down('10.254.30.40:11211');
print_r($servers->array_keys());
print_r($servers->array_values());
<file_sep>/memcache_servers.php
<?php
require_once 'shared_mem_array.php';
class MemcacheServers extends SharedMemArray
{
protected $memsize = 256;
public static $default = array(
'10.254.30.40:11211' => 0,
'10.254.30.41:11211' => 0,
);
public static $expire = 300;
public function isDown($key) {
return ($this[$key] > time());
}
public function down($key = null) {
if ($key) {
return ($this[$key] = $this->down());
}
return time() + static::$expire;
}
public function up($key = null) {
if ($key) {
return ($this[$key] = $this->up());
}
return 0;
}
}
<file_sep>/shared_mem_array.php
<?php
/*
* SharedMemArray
*
* Requires: PHP 5.3+, shmop, sysvsem, msgpack
*
* Author: <NAME> <http://github.com/h0tw1r3>
* License: BSD 2-Clause License
* (http://www.opensource.org/licenses/bsd-license.php)
*/
abstract class SharedMemArray implements ArrayAccess, Iterator, Countable
{
protected $memsize = 16384;
public static $default = array();
public static $locktries = 5;
private $value = array();
private $cache = array();
private $shm_key = null;
private $lock_key = null;
private $lock = null;
protected static $instances = array();
protected function __construct()
{
$reflect = new ReflectionClass(get_called_class());
$this->shm_key = ftok($reflect->getFileName(), 'h');
$this->lock_key = ftok($reflect->getFileName(), 'l');
}
public function __destruct()
{
$this->write();
}
public static function getInstance($name = null)
{
if (is_null($name)) {
$name = get_called_class();
}
if (!array_key_exists($name, self::$instances)) {
self::$instances[$name] = new static($name);
}
return self::$instances[$name];
}
private function refresh()
{
$this->value = static::$default;
if ($this->isLocked()) {
return;
}
$shm = @shmop_open($this->shm_key, 'a', 0660, $this->memsize);
if ($shm !== FALSE) {
$val = @msgpack_unpack(shmop_read($shm, 0, shmop_size($shm)));
if (is_array($val)) {
$this->value = $this->cache = $val;
}
shmop_close($shm);
}
}
private function refreshIfEmpty()
{
if (empty($this->value)) {
$this->refresh();
}
}
private function write()
{
$result = FALSE;
if ($this->value == $this->cache) {
// no change
} elseif (empty($this->cache) && ($this->value === static::$default)) {
// no change
} else {
if ($this->acquireLock()) {
$shm = shmop_open($this->shm_key, 'c', 0660, $this->memsize);
if ($shm !== FALSE) {
$result = (shmop_write($shm, msgpack_pack($this->value), 0) !== FALSE);
shmop_close($shm);
}
$this->releaseLock();
}
}
return $result;
}
private function isLocked()
{
$result = TRUE;
for($tries = static::$locktries; $tries >= 0; $tries--) {
$shm = @shmop_open($this->lock_key, 'a', 0660, 1);
if ($shm == FALSE) {
$result = FALSE;
break;
} else {
shmop_close($shm);
}
usleep(50);
}
return $result;
}
private function acquireLock()
{
$result = FALSE;
if (($this->lock = @shmop_open($this->lock_key, 'n', 0660, 8)) !== FALSE) {
$result = TRUE;
}
return $result;
}
private function releaseLock()
{
$result = FALSE;
if ($this->lock) {
if ($result = shmop_delete($this->lock)) {
$this->lock = null;
}
}
return $result;
}
public function offsetExists($value)
{
$this->refreshIfEmpty();
return isset($this->value[$offset]);
}
public function offsetGet($offset)
{
return isset($this->value[$offset]) ? $this->value[$offset] : null;
}
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->value[] = $value;
} else {
$this->value[$offset] = $value;
}
}
public function offsetUnset($offset)
{
unset($this->value[$offset]);
}
public function rewind()
{
$this->refreshIfEmpty();
reset($this->value);
}
public function current()
{
return current($this->value);
}
public function key()
{
return key($this->value);
}
public function next()
{
return next($this->value);
}
public function valid()
{
return key($this->value) !== null;
}
public function count()
{
$this->refreshIfEmpty();
return count($this->value);
}
public function __call($func, $argv)
{
$this->refreshIfEmpty();
if (!is_callable($func) || substr($func, 0, 6) !== 'array_')
{
throw new BadMethodCallException(__CLASS__.'->'.$func);
}
return call_user_func_array($func, array_merge(array($this->value), $argv));
}
private function __clone() {}
private function __sleep() {}
private function __wakeup() {}
public static function shutdown()
{
foreach (self::$instances as $instance) {
$instance->releaseLock();
}
}
}
register_shutdown_function(array('SharedMemArray', 'shutdown'));
|
937b95c33fb2acfac06ad145afe1273cf0a37d40
|
[
"Markdown",
"PHP"
] | 4
|
Markdown
|
h0tw1r3/php-sharedmemarray
|
a746b671970b5e1e12353b90b988fb859f4b692b
|
ddbc0933fe65ea18c1c2affe8b6c2ea4cb9b394e
|
refs/heads/master
|
<file_sep>using KTE_PMS.MIMIC;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace KTE_PMS
{
public class TagManager
{
private const int TSize = 148;
public cTag[] tt;
public Dictionary<string, cTag> dictionary = new Dictionary<string, cTag>();
DataTable dt = new DataTable();
string directory;
public Dictionary<string, string> htCurrentFault = new Dictionary<string, string>();
Queue<string> qRecvFault = new Queue<string>();
public string[,] FAULT_CODE = {{"46_0", "Black out"}, {"46_1", "Over frequency"}, {"46_2", "Under frequency"}, {"46_3", "Over Voltage"},{"46_4", "Under Voltage"},
{"46_5", "Reserved"}, {"46_6", "Reserved"}, {"46_7", "Reserved"}, {"46_8", "Reserved"}, {"46_9", "Reserved"}, {"46_10", "Reserved"}, {"46_11", "Reserved"},
{"46_12", "Reserved"}, {"46_13", "Reserved"}, {"46_13", "Reserved"}, {"46_14", "Reserved"}, {"46_15", "Reserved"},
{"47_0", "INV_OVR"}, {"47_1", "INV_OCR"}, {"47_2", "GRID_OCR"}, {"47_3", "DC_OCR"}, {"47_4", "DC_UVR"}, {"47_5", "DC_OCR"},
{"47_6", "OT"}, {"47_7", "Door_Open_Fault"}, {"48_8", "PCS Comm Fault"}, {"48_9", "HW Fault"}, {"48_10", "BMS Comm Fault"}};
public string[,] Samsung_BMS_FAULT_CODE = {{"14_15", "Reserved"} , {"14_14", "Reserved"}, {"14_13", "Reserved"},{"14_12", "Reserved"},{"14_11", "Reserved"}, {"14_10", "Reserved"},{"14_9", "Reserved"}, {"14_8", "Reserved"},
{"14_7", "Reserved"}, {"14_6", "Reserved"}, {"14_5", "Reserved"},{"14_4", "Reserved"}, {"14_3", "Reserved"}, {"14_2", "Reserved"},{"14_1", "Reserved"}, {"14_0", "Additional Protection Fail"},{"15_15", "Cell dchg operation limit"},
{"15_14", "Cell chg operation limit"}, {"15_13", "Module pcb ot"}, {"15_12", "Module pcb ut"}, {"15_11", "Dcsw3_fail"}, {"15_10", "Dcsw3_sensing_fail"}, {"15_9", "Dcsw2_sensing_fail"}, {"15_8", "Dcsw1_sensing_fail"}, {"15_7", "Reserved"},
{"15_6", "Reserved"}, {"15_5", "Reserved"}, {"15_4", "Reserved"}, {"15_3", "Reserved"}, {"15_2", "Reserved"}, {"15_1", "Reserved"}, {"15_0", "Reserved"}, {"16_15", "Reserved"}, {"16_14", "Reserved"}, {"16_13", "Reserved"},
{"16_12", "Reserved"}, {"16_11", "Reserved"}, {"16_10", "Reserved"}, {"16_9", "Reserved"}, {"16_8", "Reserved"}, {"16_7", "Reserved"}, {"16_6", "Reserved"},
{"16_5", "Reserved"}, {"16_4", "Reserved"}, {"16_3", "Reserved"}, {"16_2", "Reserved"}, {"16_1", "Rack string I-imb"}, {"16_0", "Rack string V-imb"}, {"17_15", "Permanent uv"}, {"17_14", "Rack fuse fail"}, {"17_13", "Rack I sensor fail"},
{"17_12", "Rack V sensing diff"}, {"17_11", "Rack OV"}, {"17_10", "Rack UV"}, {"17_9", "Rack DchqOC"}, {"17_8", "Rack ChgOC"}, {"17_7", "R-S comm fail"}, {"17_6", "R-M comm fail"}, {"17_5", "Module T-imb"}, {"17_4", "Module V-imb"},
{"17_3", "Module OV"}, {"17_2", "Module UV"}, {"17_1", "Module OT"}, {"17_0", "Module UT"}, {"18_15", "Reserved"}, {"18_14", "Reserved"}, {"18_13", "Reserved"}, {"18_12", "Reserved"}, {"18_11", "Reserved"}, {"18_10", "Reserved"},
{"18_9", "Reserved"}, {"18_8", "Reserved"}, {"18_7", "Reserved"}, {"18_6", "Reserved"}, {"18_5", "Reserved"}, {"18_4", "Reserved"}, {"18_3", "Reserved"}, {"18_2", "Reserved"}, {"18_1", "Reserved"}, {"18_0", "Additional Protection Fail"},
{"19_15", "Cell dchg operation limit"}, {"19_14", "Cell chg operation limit"}, {"19_13", "Module pcb ot"}, {"19_12", "Module pcb ut"}, {"19_11", "Dcsw3_fail"}, {"19_10", "Dcsw3_sensing_fail"}, {"19_9", "Dcsw2_sensing_fail"},
{"19_8", "Dcsw1_sensing_fail"}, {"19_7", "Reserved"}, {"19_6", "Reserved"}, {"19_5", "Reserved"}, {"19_4", "Reserved"}, {"19_3", "Reserved"}, {"19_2", "Reserved"}, {"19_1", "Reserved"}, {"19_0", "Reserved"}, {"20_15", "Reserved"},
{"20_14", "Reserved"}, {"20_13", "Reserved"}, {"20_12", "Reserved"}, {"20_11", "Reserved"}, {"20_10", "Reserved"}, {"20_9", "Reserved"}, {"20_8", "Reserved"}, {"20_7", "Reserved"}, {"20_6", "Reserved"}, {"20_5", "Reserved"},
{"20_4", "Reserved"}, {"20_3", "Reserved"}, {"20_2", "Reserved"}, {"20_1", "Rack string I-imb"}, {"20_0", "Rack string V-imb"}, {"21_15", "Permanent uv"}, {"21_14", "Rack fuse fail"}, {"21_13", "Rack I sensor fail"},
{"21_12", "Rack V sensing diff"}, {"21_11", "Rack OV"}, {"21_10", "Rack UV"}, {"21_9", "Rack DchqOC"}, {"21_8", "Rack ChgOC"}, {"21_7", "R-S comm fail"}, {"21_6", "R-M comm fail"}, {"21_5", "Module T-imb"},
{"21_4", "Module V-imb"}, {"21_3", "Module OV"}, {"21_2", "Module UV"}, {"21_1", "Module OT"}, {"21_0", "Module UT"}};
public string[,,] FAULT_STATUS = new string[256, 17, 3];
public string[,,] BMS_FAULT_STATUS = new string[256, 17, 3];
public TagManager(Repository rep)
{
directory = Application.StartupPath;
// ----------------------------------------------------------------------------------------
// 파일을 읽어서 List에 넣기
// cTag에 저장하기
// 항상 동작하면서 cTag에 있는 값을 해당되는 통신방식에 맞게 값을 읽어오고 주기적으로 쓴다
// ----------------------------------------------------------------------------------------
//cTag 초기화
tt = new cTag[TSize];
for (int i = 0; i < TSize; i++)
{
tt[i] = new cTag();
}
#region FAULT_STATUS_초기화
for (int nFileNo = 14; nFileNo <= 21; nFileNo++)
{
for (int nBit = 0; nBit <= 15; nBit++)
{
if (FAULT_STATUS[nFileNo, nBit, 0] == null)
FAULT_STATUS[nFileNo, nBit, 0] = "0";
}
}
for (int nFileNo = 46; nFileNo <= 48; nFileNo++)
{
for (int nBit = 0; nBit <= 15; nBit++)
{
if (FAULT_STATUS[nFileNo, nBit, 0] == null)
FAULT_STATUS[nFileNo, nBit, 0] = "0";
}
}
#endregion
//Read_AlarmData(ref tt);
}
public string GetFaultText(int nFileNo, int nBit)
{
string szReturn = string.Empty;
if (nFileNo >= 46 || nFileNo <= 48)
{
for (int i = 0; i <= FAULT_CODE.GetLength(0) - 1; i++)
{
string szFileNo = FAULT_CODE[i, 0];
if (szFileNo == string.Format("{0}_{1}", nFileNo, nBit))
{
szReturn = FAULT_CODE[i, 1];
break;
}
}
}
else if (nFileNo >= 14 && nFileNo <= 21)
{
for (int i = 0; i <= Samsung_BMS_FAULT_CODE.GetLength(0) - 1; i++)
{
string szFileNo = Samsung_BMS_FAULT_CODE[i, 0];
if (szFileNo == string.Format("{0}_{1}", nFileNo, nBit))
{
szReturn = Samsung_BMS_FAULT_CODE[i, 1];
break;
}
}
}
return szReturn;
}
public void PCS_Fault_처리_프로시져()
{
ushort ushValue = 0;
// PCS_DataDisplay(szMode, szMessage)
// 46~47 에러 하기 (PCS쪽 Fault)
for (int nFileNo = 46; nFileNo <= 47; nFileNo++)
{
if (nFileNo == 46)
ushValue = Repository.Instance.GnEPS_PCS.PCS_GRID_Status;
else if (nFileNo == 47)
ushValue = Repository.Instance.GnEPS_PCS.PCS_Fault_Status;
else
ushValue = 0;
for (int nBit = 0; nBit <= 15; nBit++)
{
int nStatus = ushValue >> nBit & 0x1;
if (FAULT_STATUS[nFileNo, nBit, 0] != nStatus.ToString())
경보발생및해제(nStatus, nFileNo, nBit);
}
}
}
public void BMS_Fault_처리_프로시져()
{
ushort ushValue = 0;
// 14~15 에러 하기 (BMS쪽 Fault)
for (int nFileNo = 14; nFileNo <= 21; nFileNo++)
{
if (nFileNo == 14)
ushValue = Repository.Instance.samsung_bcs.Protection_Summary4;
else if (nFileNo == 15)
ushValue = Repository.Instance.samsung_bcs.Protection_Summary3;
else if (nFileNo == 16)
ushValue = Repository.Instance.samsung_bcs.Protection_Summary2;
else if (nFileNo == 17)
ushValue = Repository.Instance.samsung_bcs.Protection_Summary1;
else if (nFileNo == 18)
ushValue = Repository.Instance.samsung_bcs.Alarm_Summary4;
else if (nFileNo == 19)
ushValue = Repository.Instance.samsung_bcs.Alarm_Summary3;
else if (nFileNo == 20)
ushValue = Repository.Instance.samsung_bcs.Alarm_Summary2;
else if (nFileNo == 21)
ushValue = Repository.Instance.samsung_bcs.Alarm_Summary1;
else
ushValue = 0;
for (int nBit = 0; nBit <= 15; nBit++)
{
int nStatus = ushValue >> nBit & 0x1;
if (FAULT_STATUS[nFileNo, nBit, 0] != nStatus.ToString())
{
경보발생및해제(nStatus, nFileNo, nBit);
}
}
}
}
private string getDeviceName(int nFileNo)
{
if (nFileNo >= 14 && nFileNo <= 21)
{
return ("BMS");
}
else if (nFileNo >= 46 && nFileNo <= 47)
{
return ("PCS");
}
else if (nFileNo == 48)
{
return ("SYSTEM");
}
else
{
return ("Unexpected Device");
}
}
public void 경보발생및해제(int nStatus, int nFileNo, int nBit)
{
try
{
// heartbit가 동작중에는 flag_PCS_COMMFAULT Flag를 설정시키기 때문에
// Heartbit가 동작중에는 초기화 하는것이 필요하다. Heartbit가 11이 됨으로 부터 정상적인 PCS Alarm 발생을 시작
string szFaultCode = string.Format("{0}_{1}", nFileNo, nBit);
string strDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
// 화면_고장
string szFaultText = GetFaultText(nFileNo, nBit);
string DeviceName = getDeviceName(nFileNo);
DateTime tCurrent = DateTime.Now;
string key;
if (nStatus == 0)
{
// 해제
FAULT_STATUS[nFileNo, nBit, 0] = nStatus.ToString();
FAULT_STATUS[nFileNo, nBit, 1] = string.Empty;
// Ack Bit 여부를 확인하고, Ack면 해제, Ack가 아니라면 UnAcked Normal을 띄워줘야함.
key = nFileNo + "_" + nBit;
// 값을 받아온다.
string szCurrentFault = htCurrentFault[key] + string.Empty;
string[] current_IO = szCurrentFault.Split('|');
// Unacked이면 Acked로, Unacekd Normal이면 삭제.
if (current_IO[4] == "ACK")
{
Repository.Instance.TagManager.htCurrentFault.Remove(key);
szCurrentFault = szCurrentFault.Replace(current_IO[0], strDateTime);
szCurrentFault = szCurrentFault.Replace("ACK", "NORMAL");
Repository.Instance.dbConnector.Insert_Alarm_to_Database(szCurrentFault);
}
// UNACK라면?
else if (current_IO[4] == "UNACK")
{
szCurrentFault = szCurrentFault.Replace(current_IO[0], strDateTime);
szCurrentFault = szCurrentFault.Replace("UNACK", "UNACK NORMAL");
Repository.Instance.TagManager.htCurrentFault.Remove(key);
Repository.Instance.TagManager.htCurrentFault.Add(key, szCurrentFault);
Repository.Instance.dbConnector.Insert_Alarm_to_Database(szCurrentFault);
}
}
else
{
// 180628
// ACK시 PCS로 Fault Reset을 하기 위한 Alarm
// ALARM이 새로 발생하면 PCS_ACK는 다시 False로 한다.
Repository.Instance.GnEPS_PCS.PCS_ACK = false;
/////////////////////////////////////////////////////
//
FAULT_STATUS[nFileNo, nBit, 0] = nStatus.ToString();
FAULT_STATUS[nFileNo, nBit, 1] = tCurrent.ToString("yyyy-MM-dd HH:mm:ss");
string szFault = string.Format("{0}|{1}|{2}|{3}|{4}", tCurrent.ToString("yyyy-MM-dd hh:mm:ss"), string.Format("{0} [0x{1:X2}] ", nFileNo, nBit), DeviceName, szFaultText, "UNACK");
Repository.Instance.dbConnector.Insert_Alarm_to_Database(szFault);
htCurrentFault[szFaultCode] = szFault;
}
}
catch (Exception ex)
{
Console.WriteLine("경보발생및해제(int "+ nStatus +", int " + nFileNo+", int "+nBit+")");
Console.WriteLine(ex.Message);
}
}
public void ALARM_ACK()
{
string strDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
foreach (var key in htCurrentFault.Keys.ToList())
{
// 값을 받아온다.
//string szFault = pDir.Value + "";
string szFault = htCurrentFault[key] + "";
// Unacked이면 Acked로, Unacekd Normal이면 삭제.
string[] current_IO = szFault.Split('|');
if (current_IO[4] == "UNACK NORMAL")
{
htCurrentFault.Remove(key);
szFault = szFault.Replace(current_IO[0], strDateTime);
szFault = szFault.Replace("UNACK NORMAL", "NORMAL");
Repository.Instance.dbConnector.Insert_Alarm_to_Database(szFault);
}
else if (current_IO[4] == "UNACK")
{
szFault = szFault.Replace(current_IO[0], strDateTime);
szFault = szFault.Replace("UNACK", "ACK");
htCurrentFault.Remove(key);
htCurrentFault.Add(key, szFault);
Repository.Instance.dbConnector.Insert_Alarm_to_Database(szFault);
}
}
// ALARM Ack 시 PCS_ACK를 한다.
// 해당 ACK는 Reset 모든 Alarm이 Clear 될 경우 해제된다.
if (htCurrentFault.Count == 0)
{
Repository.Instance.GnEPS_PCS.PCS_ACK = true;
}
DateTime tCurrent = DateTime.Now;
string szEvent = string.Format("{0}|{1}|{2}|{3}|{4}", tCurrent.ToString("yyyy-MM-dd hh:mm:ss"), "SYS", "LEMS", "ALARM ACK IS OCCURED BY USER", "EVENT");
Repository.Instance.dbConnector.Insert_Alarm_to_Database(szEvent);
}
public void ALARM_ACK(int count)
{
string strDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
int i = 0;
foreach (var key in htCurrentFault.Keys.ToList())
{
// 값을 받아온다.
//string szFault = pDir.Value + "";
string szFault = Repository.Instance.TagManager.htCurrentFault[key] + "";
// Unacked이면 Acked로, Unacekd Normal이면 삭제.
string[] current_IO = szFault.Split('|');
if (current_IO[4] == "UNACK NORMAL")
{
htCurrentFault.Remove(key);
szFault = szFault.Replace(current_IO[0], strDateTime);
szFault = szFault.Replace("UNACK NORMAL", "NORMAL");
Repository.Instance.dbConnector.Insert_Alarm_to_Database(szFault);
}
else if (current_IO[4] == "UNACK")
{
szFault = szFault.Replace(current_IO[0], strDateTime);
szFault = szFault.Replace("UNACK", "ACK");
htCurrentFault.Remove(key);
htCurrentFault.Add(key, szFault);
Repository.Instance.dbConnector.Insert_Alarm_to_Database(szFault);
}
i++;
if (i > count) break;
}
// ALARM Ack 시 PCS_ACK를 한다.
// 해당 ACK는 Reset 모든 Alarm이 Clear 될 경우 해제된다.
if (Repository.Instance.TagManager.htCurrentFault.Count == 0)
{
Repository.Instance.GnEPS_PCS.PCS_ACK = true;
}
DateTime tCurrent = DateTime.Now;
string szEvent = string.Format("{0}|{1}|{2}|{3}|{4}", tCurrent.ToString("yyyy-MM-dd hh:mm:ss"), "SYS", "LEMS", "ALARM ACK IS OCCURED BY USER", "EVENT");
Repository.Instance.dbConnector.Insert_Alarm_to_Database(szEvent);
}
public void Alarm_Display(ref DataGridView dataGridView1)
{
dataGridView1.Rows.Clear();
ArrayList alFault = new ArrayList();
foreach (KeyValuePair<String, String> pDir in Repository.Instance.TagManager.htCurrentFault)
{
string szFault = pDir.Value + "";
if (szFault != "")
alFault.Add(pDir.Value);
}
alFault.Sort();
string[] row0 = new string[5];
foreach (string szFaultData in alFault)
{
string[] szFault = szFaultData.Split('|');
row0[0] = szFault[0];
row0[1] = szFault[1];
row0[2] = szFault[2];
row0[3] = szFault[3];
row0[4] = szFault[4];
// row0[4] 는 ACK, UNACK, UNACK_NORMAL로 구성됨
dataGridView1.Rows.Add(row0);
}
}
public void Alarm_Display(ref DataGridView dataGridView1, int count)
{
dataGridView1.Rows.Clear();
ArrayList alFault = new ArrayList();
int i = 0;
foreach (KeyValuePair<String, String> pDir in Repository.Instance.TagManager.htCurrentFault)
{
string szFault = pDir.Value + "";
if (szFault != "")
alFault.Add(pDir.Value);
}
alFault.Sort();
string[] row0 = new string[5];
foreach (string szFaultData in alFault)
{
string[] szFault = szFaultData.Split('|');
row0[0] = szFault[0];
row0[1] = szFault[1];
row0[2] = szFault[2];
row0[3] = szFault[3];
row0[4] = szFault[4];
// row0[4] 는 ACK, UNACK, UNACK_NORMAL로 구성됨
dataGridView1.Rows.Add(row0);
i++;
if (i == count) break;
}
}
public void Read_AlarmData(ref cTag[] tt)
{
#region FILE의 입력을 받아서 ALARM 처리 하는 방법
string filename = "\\TAGLIST.csv";
try
{
FileStream fs = File.OpenRead(directory + filename);
StreamReader r = new StreamReader(fs, System.Text.Encoding.Default);
// 문자 스트림 변환
r.BaseStream.Seek(0, SeekOrigin.Begin);
// Skip First Line //
string temp = r.ReadLine();
foreach (cTag i in tt)
{
// 만약 끝이 아니라면
if (r.Peek() > -1)
{
// 1 Line 을 읽는다.
temp = r.ReadLine();
// 읽은 값을 Parsing 해서 Assign한다.
AssignFromFileToTag(temp, i);
// Assign 한 값을 Dictionary에 넣는다.
// 현재는 Index로 구분하지만 나중에는 TagName으로 구분할 예정으로 수정 필요함
// DataTable로 넣는걸로 하자.
//dictionary.Add(i.Index, i);
}
else
{
// Unexpected Result
throw new Exception();
}
}
r.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Abort");
throw e;
}
#endregion
}
private void AssignFromFileToTag(string temp, cTag i)
{
string[] split = System.Text.RegularExpressions.Regex.Split(temp, ",");
try
{
DataRow dr;
dr = Repository.Instance.Tag_Data_Table.NewRow();
dr["ID"] = split[0];
dr["GroupNo"] = split[1];
dr["Description"] = split[2];
dr["Unit"] = split[4];
dr["Resolution"] = split[7];
dr["InputCH"] = split[8];
dr["Address_bit"] = split[9];
dr["RangeMin"] = split[12];
dr["RangeMax"] = split[13];
Repository.Instance.Tag_Data_Table.Rows.Add(dr);
i.AlrOffValue = false;
i.Index = split[0];
i.grno = split[1];
i.Description = split[2];
i.Unit = split[4];
// 예외처리를 해줘야함
if (split[7] == "")
{
split[7] = "0";
}
i.resolution = Convert.ToSingle(split[7]);
i.Address = split[8];
i.bit_address = split[9];
//i.Min = Convert.ToSingle(split[12]);
//i.Max = Convert.ToSingle(split[13]);
/*
i.LoLimit = Convert.ToSingle(split[14]);
i.HiLimit = Convert.ToSingle(split[15]);
i.LoLo = Convert.ToBoolean(split[24]);
i.Lo = Convert.ToBoolean(split[25]);
i.Hi = Convert.ToBoolean(split[26]);
i.HiHi = Convert.ToBoolean(split[27]);
i.LoLoLimit = Convert.ToSingle(split[29]);
i.HiHiLimit = Convert.ToSingle(split[30]);
*/
return;
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Abort");
throw e;
}
}
public void Run()
{
/*
try
{
foreach (cTag i in tt)
{
if (i.Changed == true)
{
i.Tag_Update(repository);
}
}
return;
}
catch (Exception e)
{
string message;
message = string.Format("Incorrect exception for {0}", e.Message);
}
*/
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace KTE_PMS.MIMIC
{
public partial class AlarmViewer : Viewer
{
Color flashColor;
const int max_row_size = 11;
public AlarmViewer()
{
InitializeComponent();
timer1.Enabled = true;
timer1.Interval = 1000;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
Flashing_Row();
LoadCurrentFault();
Cell_Color_Painting();
}
public void LoadCurrentFault()
{
Repository.Instance.TagManager.Alarm_Display(ref dataGridView1, 0);
}
private void Flashing_Row()
{
if (flashColor == Color.Gray)
{
flashColor = Color.Red;
}
else
{
flashColor = Color.Gray;
}
}
#region ALARM_TEST
private void RiseAlarm(cTag[] tt)
{
foreach (cTag i in Repository.Instance.TagManager.tt)
{
i.HiHi = true;
// ----------------------------------------------------------------------------------------
// 현재 Alarm이 정상적으로 동작하지 않기때문에 i.TimeStamp라는 함수를 둬서 시간을 표시한다
// ----------------------------------------------------------------------------------------
i.TimeStamp = DateTime.Now;
// 상태는 4가지 종류가 있음
// Unack Alarm, Unack normal, Acked Alarm, Acked Normal
// 해당 경우를 다 판단해서 생각
// 일단 Unack Alarm
// 기본은 Acked Normal. 다 사라진 상태.
if (i.AlrOnValue == true)
{
if (i.UnAck == true)
{
// Unacked Alarm
// 빨간색 Flickering
MakeAlarm(Convert.ToString(i.TimeStamp), "COMM", "PCS", i.Description + "Too High");
}
else if (i.UnAck == false)
{
// Acked Alarm
// 빨간색
}
}
else if (i.AlrOnValue == false)
{
// Acked Normal
// 초록색
}
if (i.UnAck == true)
{
if (i.HiHi == true)
{
MakeAlarm(Convert.ToString(i.TimeStamp), "COMM", "PCS", i.Description + "Too High");
}
if (i.Hi == true)
{
MakeAlarm(Convert.ToString(i.TimeStamp), "COMM", "PCS", i.Description + "High");
}
if (i.Lo == true)
{
MakeAlarm(Convert.ToString(i.TimeStamp), "COMM", "PCS", i.Description + "Low");
}
if (i.LoLo == true)
{
MakeAlarm(Convert.ToString(i.TimeStamp), "COMM", "PCS", i.Description + "Too low");
}
}
}
}
private void AlarmTest()
{
string[] row0 = new string[5];
row0[0] = DateTime.Now.ToString();
row0[1] = "COMM";
row0[2] = "PCS";
row0[3] = "PCS FAULT";
// row0[4] 는 ACK, UNACK, UNACK_NORMAL로 구성됨
Random rando = new Random((int)DateTime.Now.Ticks);
int rand = rando.Next(1, 4);
switch (rand)
{
case 1:
row0[4] = "ACK";
break;
case 2:
row0[4] = "UNACK";
break;
case 3:
row0[4] = "UNACK_NORMAL";
break;
}
dataGridView1.Rows.Add(row0);
//DataGridViewTextBoxRow a = new dataGridView1.Rows.DataGridViewTextBoxRow();
// Tag가 있어야한다.
// Tag는 Alarm의 정보 Ack 정보를 가지고 있어야함
// Tag와 받는곳을 같이
// Tag 이름를 추가할 때 이름 Description 연동방법을 정의
// Tag이름 + Protocol 정의
}
private void MakeAlarm(string date, string type, string device, string description)
{
string[] row0 = new string[5];
row0[0] = date;
row0[1] = type;
row0[2] = device;
row0[3] = description;
dataGridView1.DefaultCellStyle.BackColor = Color.LightGray;
dataGridView1.Rows.Add(row0);
}
private void button1_Click(object sender, EventArgs e)
{
AlarmTest();
}
#endregion
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
dataGridView1.Sort(dataGridView1.Columns[0], ListSortDirection.Descending);
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
Cell_Color_Painting();
}
private void Cell_Color_Painting()
{
string type;
for (int i = 0; i < dataGridView1.RowCount; i++)
{
type = dataGridView1.Rows[i].Cells[4].Value.ToString();
switch (type)
{
case "ACK":
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;
break;
case "UNACK":
dataGridView1.Rows[i].DefaultCellStyle.BackColor = flashColor;
break;
case "UNACK NORMAL":
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Green;
break;
}
}
}
private void NEXT_Click(object sender, EventArgs e)
{
if (dataGridView1.FirstDisplayedScrollingRowIndex + max_row_size >= dataGridView1.RowCount - 1)
{
dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.RowCount - 1;
}
else
{
dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.FirstDisplayedScrollingRowIndex + max_row_size;
}
}
private void PREV_Click(object sender, EventArgs e)
{
if (dataGridView1.FirstDisplayedScrollingRowIndex - max_row_size <= 0)
{
dataGridView1.FirstDisplayedScrollingRowIndex = 0;
}
else
{
dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.FirstDisplayedScrollingRowIndex - max_row_size;
}
}
private void btnACK_Click(object sender, EventArgs e)
{
// 일다안~~~ Unacked 인놈을 다 Ack로 변경해야한다.
Repository.Instance.TagManager.ALARM_ACK();
}
private void label2_Click(object sender, EventArgs e)
{
}
private void btn_TO_ALARM_Click(object sender, EventArgs e)
{
Panel p = (Panel)Parent;
p.Controls.Clear();
p.Controls.Add(Repository.Instance.p_alarm);
}
private void btn_TO_HISTORY_Click(object sender, EventArgs e)
{
Panel p = (Panel)Parent;
p.Controls.Clear();
p.Controls.Add(Repository.Instance.p_history);
}
private void AlarmViewer_Load(object sender, EventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
namespace KTE_PMS
{
public class sPCS
{
//internal short Fault_Battery_Voltage;
// System Part Control
public int Stand_Grid_Mode { get; set; }
public int Diesel_Converter_Run_Stop { get; set; }
public int Wind_Converter_Run_Stop { get; set; }
public int Solar_Converter_Run_Stop { get; set; }
public int ESS_Converter_Run_Stop { get; set; }
public int Inverter_Run_Stop { get; set; }
public int System_Run_Stop { get; set; }
public int Mode_Standby { get; set; }
public int Mode_Peak_cut{ get; set; }
public int Mode_Charging { get; set; }
public int Mode_Discharging { get; set; }
public int Mode_Reset { get; set; }
public int Mode_ACKED { get; set; }
public bool PCS_ACK { get; set; }
public bool Authority_PMS { get; set; }
public int GRID_R_Voltage { get; set; }
public int GRID_S_Voltage { get; set; }
public int GRID_T_Voltage { get; set; }
public int GRID_R_Current { get; set; }
public int GRID_S_Current { get; set; }
public int GRID_T_Current { get; set; }
public int GRID_Power { get; set; }
public double GRID_Frequency { get; set; }
public int isTemperatureWarning { get; set; }
public int LOAD_R_Current { get; set; }
public int LOAD_S_Current { get; set; }
public int LOAD_T_Current { get; set; }
public int LOAD_Power { get; set; }
public int INVERTER_Power { get; set; }
public ushort PCS_GRID_Status { get; set; }
public ushort PCS_Fault_Status { get; set; }
public ushort PCS_STANDBY { get; set; }
public int Fault_Battery_Voltage { get; set; }
public int Fault_Battery_Current { get; set; }
public int Fault_System_A_Current { get; set; }
public int Fault_System_B_Current { get; set; }
public int Fault_System_C_Current { get; set; }
public int Fault_Inverter_A_Current { get; set; }
public int Fault_Inverter_B_Current { get; set; }
public int Fault_Inverter_C_Current { get; set; }
public int Fault_Inverter_A_Voltage { get; set; }
public int Fault_Inverter_B_Voltage { get; set; }
public int Fault_Inverter_C_Voltage { get; set; }
public int Fault_Active_Power { get; set; }
public int Control_MODE { get; set; }
public int Fault_System_CB_Status { get; set; }
public int Inverter_Current_Reference { get; set; }
public int Inverter_Q_Current { get; set; }
public int Inverter_D_Current { get; set; }
public int Battery_Voltage { get; set; }
public int Battery_Current { get; set; }
Dictionary<int, string> d;
public sPCS()
{
d = new Dictionary<int, string>();
//d.Add(0, ByteConverterToUInt16(data, 0));
}
/*
GnEPS_PCS.GRID_R_Voltage = ByteConverterToUInt16(data, 0);
GnEPS_PCS.GRID_S_Voltage = ByteConverterToUInt16(data, 1);
GnEPS_PCS.GRID_T_Voltage = ByteConverterToInt16(data, 2);
GnEPS_PCS.GRID_R_Current = ByteConverterToInt16(data, 3);
GnEPS_PCS.GRID_S_Current = ByteConverterToInt16(data, 4);
GnEPS_PCS.GRID_T_Current = ByteConverterToInt16(data, 5);
GnEPS_PCS.GRID_Power = ByteConverterToInt16(data, 6);
power.setPCSPower(GnEPS_PCS.GRID_Power);
GnEPS_PCS.GRID_Frequency = ByteConverterToUInt16(data, 7) * 0.1;
GnEPS_PCS.isTemperatureWarning = ByteConverterToUInt16(data, 8);
GnEPS_PCS.LOAD_R_Current = ByteConverterToInt16(data, 11);
GnEPS_PCS.LOAD_S_Current = ByteConverterToInt16(data, 12);
GnEPS_PCS.LOAD_T_Current = ByteConverterToInt16(data, 13);
GnEPS_PCS.LOAD_Power = ByteConverterToUInt16(data, 14);
GnEPS_PCS.INVERTER_Power = ByteConverterToInt16(data, 15);
GnEPS_PCS.PCS_GRID_Status = ByteConverterToUInt16(data, 16);
GnEPS_PCS.PCS_Fault_Status = ByteConverterToUInt16(data, 17);
GnEPS_PCS.PCS_STANDBY = ByteConverterToUInt16(data, 18);
GnEPS_PCS.Fault_Battery_Voltage = ByteConverterToInt16(data, 19);
GnEPS_PCS.Fault_Battery_Current = ByteConverterToInt16(data, 20);
GnEPS_PCS.Fault_System_A_Current = ByteConverterToInt16(data, 21);
GnEPS_PCS.Fault_System_B_Current = ByteConverterToInt16(data, 22);
GnEPS_PCS.Fault_System_C_Current = ByteConverterToInt16(data, 23);
GnEPS_PCS.Fault_Inverter_A_Current = ByteConverterToInt16(data, 24);
GnEPS_PCS.Fault_Inverter_B_Current = ByteConverterToInt16(data, 25);
GnEPS_PCS.Fault_Inverter_C_Current = ByteConverterToInt16(data, 26);
GnEPS_PCS.Fault_Inverter_A_Voltage = ByteConverterToInt16(data, 27);
GnEPS_PCS.Fault_Inverter_B_Voltage = ByteConverterToInt16(data, 28);
GnEPS_PCS.Fault_Inverter_C_Voltage = ByteConverterToInt16(data, 29);
GnEPS_PCS.Fault_Active_Power = ByteConverterToInt16(data, 30);
*/
}
}
<file_sep>using KTE_PMS.CLASS;
using KTE_PMS.MIMIC;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace KTE_PMS
{
public partial class KTE_PMS : DevExpress.XtraEditors.XtraForm
{
const int MONITOR_OFF = 2;
const int MONITOR_ON = -1;
const int MONITOR_STANBY = 1;
const int SC_MONITORPOWER = 0xF170;
//private MIMIC.VKeyboard vkeyboard = null;
// ---------------------------------------------------------
// KMS_PMS_ Initialize
// ---------------------------------------------------------
// 모니터 On/Off 관련
const int WM_SYSCOMMAND = 0x0112;
Color flashColor;
int prev_minute;
int prev_hour;
int prev_day;
int prev_month;
int prev_year;
public KTE_PMS()
{
InitializeComponent();
CLOCK_TIMER.Enabled = true;
CLOCK_TIMER.Interval = 1000;
}
private void btn_Monitor_OFF_MouseClick(object sender, MouseEventArgs e)
{
SendMessage(this.Handle.ToInt32(), WM_SYSCOMMAND, SC_MONITORPOWER, MONITOR_OFF);
}
private void button1_Click(object sender, EventArgs e)
{
Repository.Instance.TagManager.ALARM_ACK(3);
}
private void Cell_Color_Painting()
{
string type;
for (int i = 0; i < dataGridView1.RowCount; i++)
{
type = dataGridView1.Rows[i].Cells[4].Value.ToString();
switch (type)
{
case "ACK":
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;
break;
case "UNACK":
dataGridView1.Rows[i].DefaultCellStyle.BackColor = flashColor;
break;
case "UNACK NORMAL":
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Green;
break;
}
}
}
private void Display_Current_Alarm_Count()
{
lb_alarm_count.Text = Repository.Instance.TagManager.htCurrentFault.Count() + "개";
}
private void Display_Current_PCS_Mode()
{
switch (Repository.Instance.current_pcs_mode)
{
case 1:
lb_Current_PCS_MODE.Visible = true;
lb_Current_PCS_MODE.Text = "IDLE";
break;
case 2:
lb_Current_PCS_MODE.Visible = true;
lb_Current_PCS_MODE.Text = "메뉴얼모드";
break;
case 3:
lb_Current_PCS_MODE.Visible = true;
lb_Current_PCS_MODE.Text = "스케줄모드";
break;
default:
lb_Current_PCS_MODE.Visible = false;
break;
}
}
private void Display_Current_Time()
{
label6.Text = DateTime.Now.ToString();
}
private void Flashing_Row()
{
if (flashColor == Color.Gray)
{
flashColor = Color.Red;
}
else
{
flashColor = Color.Gray;
}
}
// ---------------------------------------------------------
// KMS_PMS_ Load
// ---------------------------------------------------------
private void KTE_PMS_Load(object sender, EventArgs e)
{
panel1.Controls.Clear();
panel1.Controls.Add(Repository.Instance.p_main);
prev_minute = DateTime.Now.Minute;
prev_hour = DateTime.Now.Hour;
prev_day = DateTime.Now.Day;
prev_month = DateTime.Now.Month;
prev_year = DateTime.Now.Year;
//-----------------------------
// 20180709
// DataTable안에다가 Tag관련 정보를 CSV에서 받아서 넣는다.
// TagManager는 Alarm 관련 항목
//-----------------------------
tag_data tag_data = new tag_data();
Repository.Instance.Tag_Data_Table = tag_data.Tables[0];
Repository.Instance.TagManager.Read_AlarmData(ref Repository.Instance.TagManager.tt);
}
private void NAVI_ALARM_Click(object sender, EventArgs e)
{
// 모든 Button의 Image를 Null로 변경 해서 초기화 //
Navigation_Button_Initialize();
// 클릭한 버튼에 해당되는 이미지만 On Image로 변경한다 //
Button button = (Button)sender;
button.Image = ImageResize.ResizeImage(Properties.Resources.alarm_on, button.Width, button.Height);
panel1.Controls.Clear();
panel1.Controls.Add(Repository.Instance.p_alarm);
}
private void NAVI_CONTROL_Click(object sender, EventArgs e)
{
// 모든 Button의 Image를 Null로 변경 해서 초기화 //
Navigation_Button_Initialize();
// 클릭한 버튼에 해당되는 이미지만 On Image로 변경한다 //
Button button = (Button)sender;
button.Image = ImageResize.ResizeImage(Properties.Resources.control_on, button.Width, button.Height);
panel1.Controls.Clear();
panel1.Controls.Add(Repository.Instance.p_control);
}
// ---------------------------------------------------------
// Mimic 이동을 위한 버튼 함수들
// ---------------------------------------------------------
private void NAVI_MAIN_Click(object sender, EventArgs e)
{
// 모든 Button의 Image를 Null로 변경 해서 초기화 //
Navigation_Button_Initialize();
// 클릭한 버튼에 해당되는 이미지만 On Image로 변경한다 //
Button button = (Button)sender;
button.Image = ImageResize.ResizeImage(Properties.Resources.main_on, button.Width, button.Height);
panel1.Controls.Clear();
panel1.Controls.Add(Repository.Instance.p_main);
}
private void NAVI_MEASURE_Click(object sender, EventArgs e)
{
// 모든 Button의 Image를 Null로 변경 해서 초기화 //
Navigation_Button_Initialize();
// 클릭한 버튼에 해당되는 이미지만 On Image로 변경한다 //
Button button = (Button)sender;
button.Image = ImageResize.ResizeImage(Properties.Resources.measure_on_1, button.Width, button.Height);
panel1.Controls.Clear();
panel1.Controls.Add(Repository.Instance.p_measure);
}
private void NAVI_MIMIC_Click(object sender, EventArgs e)
{
// 모든 Button의 Image를 Null로 변경 해서 초기화 //
Navigation_Button_Initialize();
// 클릭한 버튼에 해당되는 이미지만 On Image로 변경한다 //
Button button = (Button)sender;
button.Image = ImageResize.ResizeImage(Properties.Resources.mimic_on, button.Width, button.Height);
panel1.Controls.Clear();
panel1.Controls.Add(Repository.Instance.p_mimic);
}
private void NAVI_SETTING_Click(object sender, EventArgs e)
{
// 모든 Button의 Image를 Null로 변경 해서 초기화 //
Navigation_Button_Initialize();
// 클릭한 버튼에 해당되는 이미지만 On Image로 변경한다 //
Button button = (Button)sender;
button.Image = ImageResize.ResizeImage(Properties.Resources.setting_on, button.Width, button.Height);
//VKeyboardViewer a = new VKeyboardViewer();
//var password = a.ShowDialogAsync();
VKeyboardViewer a = new VKeyboardViewer();
a.ShowDialog();
//a.Close();
//await data;
if (Repository.Instance.user_level == 5)
{
this.panel1.Controls.Clear();
this.panel1.Controls.Add(Repository.Instance.p_setting);
}
else
{
MessageBox.Show("권한이 없어서 SETTING 화면에 들어갈 수 없습니다");
}
}
private void NAVI_TREND_Click(object sender, EventArgs e)
{
// 모든 Button의 Image를 Null로 변경 해서 초기화 //
Navigation_Button_Initialize();
// 클릭한 버튼에 해당되는 이미지만 On Image로 변경한다 //
Button button = (Button)sender;
button.Image = ImageResize.ResizeImage(Properties.Resources.trend_on, button.Width, button.Height);
panel1.Controls.Clear();
panel1.Controls.Add(Repository.Instance.p_trend);
}
private void Navigation_Button_Initialize()
{
this.NAVI_MAIN.Image = null;
this.NAVI_ALARM.Image = null;
this.NAVI_TREND.Image = null;
this.NAVI_MIMIC.Image = null;
this.NAVI_MEASURE.Image = null;
this.NAVI_CONTROL.Image = null;
this.NAVI_SETTING.Image = null;
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
[System.Runtime.InteropServices.DllImport("User32.dll")]
private static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);
// ---------------------------------------------------------
// Timer 처리를 위한 함수들
// ---------------------------------------------------------
private void timer1_Tick(object sender, EventArgs e)
{
// 1초 Timer에 의해서 수행되는 코드
// 1초마다 Flashing을 하자
// 1초 Timer에 의해서 수행되는 코드
Display_Current_Time();
Display_Current_PCS_Mode();
Display_Current_Alarm_Count();
Flashing_Row();// TOP에 위치한 Alarm의 Flashing을 하기위해서 있는 항목 // 최적화 필요성 있음
LoadCurrentFault(); // TOP에 위치한 Alarm을 표시하기위해서 있는 항목 // 최적화 필요성 있음
Cell_Color_Painting(); // TOP에 위치한 Alarm List의 색상을 표시하기위해서 있는 항목 // 최적화 필요성 있음
Calculate_Power(); // 전력량 계산하기
}
private void Calculate_Power()
{
/////////////////////////////
// 전력량 계산하기
/////////////////////////////
// 매 분마다 전력량을 DB에 저장하자
DateTime today = DateTime.Now;
// 하루가 지날때 마다 전력량을 DB에 또 저장하자. (SELECT문으로 그날 있었던 전력량을 모두 저장해서 하루에 저장)
// 현재는 1분 주기지만 1초든 10초든 다 가능하드아~
if (prev_minute != today.Minute)
{
// 저장된 데이터를 DB에 저장한다.
//Todo : 저장된 데이터를 DB에 저장한다.
Repository.Instance.dbConnector.Insert_Power();
// 처리 완료 후, prev값을 새로 갱신
prev_minute = today.Minute;
}
if (prev_hour != today.Hour)
{
// 저장된 데이터를 DB에 저장한다.
//Todo : 저장된 데이터를 DB에 저장한다.
Repository.Instance.dbConnector.Insert_Power_Hour();
prev_hour = today.Hour;
}
if (prev_day != today.Day)
{
// 저장된 데이터를 DB에 저장한다.
Repository.Instance.dbConnector.Insert_Power_Day();
prev_day = today.Day;
}
if (prev_month != today.Month)
{
Repository.Instance.dbConnector.Insert_Power_Month();
prev_month = today.Month;
}
if (prev_year != today.Year)
{
Repository.Instance.dbConnector.Insert_Power_year();
prev_year = today.Year;
}
}
// ---------------------------------------------------------
// Timer 처리를 위한 함수들
// ---------------------------------------------------------
public void BSC_Control()
{
byte[] data;
// Byte 배열로 받고
data = Repository.Instance.p_control.getTextBox1();
//Trigger로 날려주기.
Repository.Instance.Set_BSC_Control(data);
}
public void LoadCurrentFault()
{
Repository.Instance.TagManager.Alarm_Display(ref dataGridView1, 3);
}
private void lb_alarm_count_Click(object sender, EventArgs e)
{
Repository.Instance.dbConnector.Insert_Power_Hour();
}
private void btn_PCS_STOP_Click(object sender, EventArgs e)
{
if (MessageBox.Show("긴급정지 하시겠습니까?", "확인", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
// PCS Mode 설정
Repository.Instance.current_pcs_mode = 1;
Repository.Instance.pmdviewer.Control_Idle();
}
}
}
}
<file_sep>using KTE_PMS.Observer;
using System;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
namespace KTE_PMS.MIMIC
{
public partial class MeasureViewer4 : Viewer, IUpdate
{
public MeasureViewer4()
{
InitializeComponent();
}
private void Measure_Load(object sender, EventArgs e)
{
}
delegate void CrossThreadSafetySetText(Control ctl, String text);
private void CSafeSetText(Control ctl, String text)
{
/*
* InvokeRequired 속성 (Control.InvokeRequired, MSDN)
* 짧게 말해서, 이 컨트롤이 만들어진 스레드와 현재의 스레드가 달라서
* 컨트롤에서 스레드를 만들어야 하는지를 나타내는 속성입니다.
*
* InvokeRequired 속성의 값이 참이면, 컨트롤에서 스레드를 만들어 텍스트를 변경하고,
* 그렇지 않은 경우에는 그냥 변경해도 아무 오류가 없기 때문에 텍스트를 변경합니다.
*/
if (ctl.InvokeRequired)
ctl.Invoke(new CrossThreadSafetySetText(CSafeSetText), ctl, text);
else
ctl.Text = text;
}
public void ObserverUpdate()
{
// BMS : System용 이다
// 값 써주기
CSafeSetText(lb1, Repository.Instance.GnEPS_PCS.GRID_R_Voltage.ToString() + " " + "V");
CSafeSetText(lb2, Repository.Instance.GnEPS_PCS.GRID_S_Voltage.ToString() + " " + "V");
CSafeSetText(lb3, Repository.Instance.GnEPS_PCS.GRID_T_Voltage.ToString() + " " + "V");
CSafeSetText(lb4, Repository.Instance.GnEPS_PCS.GRID_R_Voltage.ToString() + " " + "A");
CSafeSetText(lb5, Repository.Instance.GnEPS_PCS.GRID_S_Current.ToString() + " " + "A");
CSafeSetText(lb6, Repository.Instance.GnEPS_PCS.GRID_T_Current.ToString() + " " + "A");
CSafeSetText(lb7, Repository.Instance.GnEPS_PCS.GRID_Power.ToString() + " " + "kW");
CSafeSetText(lb8, Repository.Instance.GnEPS_PCS.GRID_Frequency.ToString() + " " + "Hz");
CSafeSetText(lb9, Repository.Instance.GnEPS_PCS.isTemperatureWarning.ToString());
CSafeSetText(lb10, Repository.Instance.GnEPS_PCS.LOAD_R_Current.ToString() + " " + "A");
CSafeSetText(lb11, Repository.Instance.GnEPS_PCS.LOAD_S_Current.ToString() + " " + "A");
CSafeSetText(lb12, Repository.Instance.GnEPS_PCS.LOAD_T_Current.ToString() + " " + "A");
CSafeSetText(lb13, Repository.Instance.GnEPS_PCS.LOAD_Power.ToString() + " " + "kW");
CSafeSetText(lb14, Repository.Instance.GnEPS_PCS.INVERTER_Power.ToString() + " " + "kW");
CSafeSetText(lb15, Repository.Instance.GnEPS_PCS.Mode_Standby.ToString());
CSafeSetText(lb16, Repository.Instance.GnEPS_PCS.Control_MODE .ToString());
CSafeSetText(lb17, Repository.Instance.GnEPS_PCS.Inverter_Current_Reference.ToString() + " " + "A");
CSafeSetText(lb18, Repository.Instance.GnEPS_PCS.Inverter_Q_Current.ToString() + " " + "A");
CSafeSetText(lb19, Repository.Instance.GnEPS_PCS.Inverter_D_Current.ToString() + " " + "A");
CSafeSetText(lb20, Repository.Instance.GnEPS_PCS.Battery_Voltage.ToString() + " " + "V");
CSafeSetText(lb21, Repository.Instance.GnEPS_PCS.Battery_Current.ToString() + " " + "A");
}
private void btn_Move_To_BMS_System_MouseClick(object sender, MouseEventArgs e)
{
Panel p = (Panel)Parent;
p.Controls.Clear();
p.Controls.Add(Repository.Instance.p_measure);
}
private void btn_Move_To_BMS_Rack_MouseClick(object sender, MouseEventArgs e)
{
Panel p = (Panel)Parent;
p.Controls.Clear();
p.Controls.Add(Repository.Instance.p_measure_BMS_Rack);
}
private void btn_Move_To_PCS_Data_MouseClick(object sender, MouseEventArgs e)
{
Panel p = (Panel)Parent;
p.Controls.Clear();
p.Controls.Add(Repository.Instance.p_measure_PCS);
}
private void btn_Move_To_PCS_Fault_MouseClick(object sender, MouseEventArgs e)
{
Panel p = (Panel)Parent;
p.Controls.Clear();
p.Controls.Add(Repository.Instance.p_measure_PCS_Fault);
}
}
}
<file_sep>using System;
using System.Linq;
namespace KTE_PMS.Singleton
{
public abstract class SingleTonBase<T> where T : SingleTonBase<T>
{
private static volatile T _instance;
private static object syncRoot = new object();
public static T Instance
{
get
{
if (_instance == null)
{
lock (syncRoot)
{
_instance = Activator.CreateInstance(typeof(T), true) as T;
}
}
return _instance;
}
}
}
}
<file_sep>using KTE_PMS.CLASS;
using System;
using System.Drawing;
using System.Windows.Forms;
namespace KTE_PMS.MIMIC
{
public partial class ControlViewer : Viewer
{
private int index = 0;
public int grid_run = 0;
public int grid_stop = 0;
public int gen_run = 0;
public int gen_stop = 0;
public int bat_run = 0;
public int bat_stop = 0;
public int pv_run = 0;
public int pv_stop = 0;
public ControlViewer()
{
InitializeComponent();
ControlTimer.Enabled = true;
ControlTimer.Interval = 2000;
ControlTimer.Start();
}
private void ControlTimer_Tick(object sender, EventArgs e)
{
// 현재 상태를 보고 BTN의 불을 켤것인지 말것인지 결정하자.
// 값을 써주자.
if (Repository.Instance.samsung_bcs.Mode_Charging == 1)
{
lb_System_Status.Text = "CHARGING";
}
else if (Repository.Instance.samsung_bcs.Mode_Discharging == 1)
{
lb_System_Status.Text = "DISCHARGING";
}
else if (Repository.Instance.samsung_bcs.Mode_Offline == 1)
{
lb_System_Status.Text = "OFFLINE";
}
else if (Repository.Instance.samsung_bcs.Mode_Idle == 1)
{
lb_System_Status.Text = "IDLE";
}
else if (Repository.Instance.samsung_bcs.Mode_Ready == 1)
{
lb_System_Status.Text = "READY";
}
else
{
lb_System_Status.Text = "UNEXPECTED";
}
int common_warning = Repository.Instance.samsung_bcs.Alarm_Summary1 +
Repository.Instance.samsung_bcs.Alarm_Summary2 +
Repository.Instance.samsung_bcs.Alarm_Summary3 +
Repository.Instance.samsung_bcs.Alarm_Summary4;
int common_alarm = Repository.Instance.samsung_bcs.Protection_Summary1 +
Repository.Instance.samsung_bcs.Protection_Summary2 +
Repository.Instance.samsung_bcs.Protection_Summary3 +
Repository.Instance.samsung_bcs.Protection_Summary4;
if (common_alarm > 0)
{
lb_Common_Alarm_Status.Text = "PROTECTION";
}
else if (common_warning > 0)
{
lb_Common_Alarm_Status.Text = "ALARM";
}
else
{
lb_Common_Alarm_Status.Text = "NORMAL";
}
if (Repository.Instance.GnEPS_PCS.Mode_Standby == 1)
{
lb_PCS_System_Status.Text = "STANDBY";
ImageResize.ResizeImage(Properties.Resources.STOP_003, btn_IDLE.Width, btn_IDLE.Height);
btn_Charging.Image = null;
btn_Discharging = null;
}
else if (Repository.Instance.GnEPS_PCS.Mode_Charging == 1)
{
lb_PCS_System_Status.Text = "CHARGING";
ImageResize.ResizeImage(Properties.Resources.RUN_003, btn_Charging.Width, btn_Charging.Height);
btn_IDLE = null;
btn_Discharging = null;
}
else if (Repository.Instance.GnEPS_PCS.Mode_Discharging == 1)
{
lb_PCS_System_Status.Text = "DISCHARGING";
ImageResize.ResizeImage(Properties.Resources.RUN_003, btn_Discharging.Width, btn_Discharging.Height);
btn_IDLE = null;
btn_Charging.Image = null;
}
else
{
lb_PCS_System_Status.Text = "NO STANDBY";
}
if (Repository.Instance.bmsviewer.Connected() > 0)
{
// BCS가 끊어진것이 아닌 상태에서, 값이 올라올때만 버튼을 표시하자.
if (Repository.Instance.samsung_bcs.Mode_Idle == 1 ||
Repository.Instance.samsung_bcs.Mode_Offline == 1)
{
btn_Grid_ON.Image = null;
btn_Grid_OFF.Image = ImageResize.ResizeImage(Properties.Resources.STOP_003, btn_Grid_OFF.Width, btn_Grid_OFF.Height);
}
else if (Repository.Instance.samsung_bcs.Mode_Ready == 1 ||
Repository.Instance.samsung_bcs.Mode_Charging == 1 ||
Repository.Instance.samsung_bcs.Mode_Discharging == 1)
{
btn_Grid_ON.Image = ImageResize.ResizeImage(Properties.Resources.RUN_003, btn_Grid_ON.Width, btn_Grid_ON.Height);
btn_Grid_OFF.Image = null;
}
}
else
{
btn_Grid_ON.Image = null;
btn_Grid_OFF.Image = null;
}
int PCS_alarm = Repository.Instance.GnEPS_PCS.PCS_GRID_Status +
Repository.Instance.GnEPS_PCS.PCS_Fault_Status;
if (PCS_alarm > 0)
{
lb_PCS_Common_Alarm.Text = "ALARM";
}
else
{
lb_PCS_Common_Alarm.Text = "NORMAL";
}
if (Repository.Instance.bmsviewer.Connected() > 0)
{
lb_Batt_Comm_Status.Text = "NORMAL";
}
else
{
lb_Batt_Comm_Status.Text = "FAULT";
}
if (Repository.Instance.pmdviewer.Connected() > 0)
{
lb_PCS_Comm_Status.Text = "NORMAL";
}
else
{
lb_PCS_Comm_Status.Text = "FAULT";
}
// 버튼 색상 정하기.
// Local Remote 상태를 보고 결정하기
if (Repository.Instance.GnEPS_PCS.Authority_PMS)
{
btn_Control_uPMS.Image = null;
btn_Control_LPMS.Image = ImageResize.ResizeImage(Properties.Resources.RUN_003, btn_Control_LPMS.Width, btn_Control_LPMS.Height);
btn_Charging.Enabled = true;
btn_Discharging.Enabled = true;
btn_Grid_ON.Enabled = true;
btn_Grid_OFF.Enabled = true;
btn_IDLE.Enabled = true;
btn_Manual_Mode.Enabled = true;
btn_Scheduling_Mode.Enabled = true;
tb_Power_Set.Enabled = true;
}
else
{
btn_Control_uPMS.Image = ImageResize.ResizeImage(Properties.Resources.RUN_003, btn_Control_uPMS.Width, btn_Control_uPMS.Height);
btn_Control_LPMS.Image = null;
btn_Charging.Enabled = false;
btn_Discharging.Enabled = false;
btn_Grid_ON.Enabled = false;
btn_Grid_OFF.Enabled = false;
btn_IDLE.Enabled = false;
btn_Manual_Mode.Enabled = false;
btn_Scheduling_Mode.Enabled = false;
tb_Power_Set.Enabled = false;
}
index++;
if (index == 5)
{
index = 0;
}
}
private void btn_Grid_ON_MouseDown(object sender, MouseEventArgs e)
{
//Button button = (Button)sender;
// button.Image = ImageResize.ResizeImage(Properties.Resources.RUN_003, button.Width, button.Height);
}
private void btn_Grid_ON_MouseClick(object sender, MouseEventArgs e)
{
if (MessageBox.Show("GRID ON 하시겠습니까?", "확인", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Repository.Instance.bmsviewer.GRID_ON();
}
}
private void btn_Grid_OFF_MouseDown(object sender, MouseEventArgs e)
{
//Button button = (Button)sender;
// button.Image = ImageResize.ResizeImage(Properties.Resources.RUN_003, button.Width, button.Height);
}
private void btn_Grid_OFF_MouseClick(object sender, MouseEventArgs e)
{
if (MessageBox.Show("GRID OFF 하시겠습니까?", "확인", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Repository.Instance.bmsviewer.GRID_OFF();
}
}
private void btn_IDLE_Click(object sender, EventArgs e)
{
if (MessageBox.Show("정지모드로 변경 하시겠습니까?", "확인", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
// PCS Mode 설정
Repository.Instance.current_pcs_mode = 1;
Repository.Instance.pmdviewer.Control_Idle();
}
}
private void btn_Charging_Click(object sender, EventArgs e)
{
if (Repository.Instance.current_pcs_mode == 3)
{
MessageBox.Show("스케줄모드일때는 사용할 수 없습니다", "확인", MessageBoxButtons.OK);
return;
}
if (MessageBox.Show("충전모드로 변경 하시겠습니까?", "확인", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Repository.Instance.pmdviewer.Control_Charge();
}
}
private void btn_Discharging_Click(object sender, EventArgs e)
{
if (Repository.Instance.current_pcs_mode == 3)
{
MessageBox.Show("스케줄모드일때는 사용할 수 없습니다", "확인", MessageBoxButtons.OK);
return;
}
if (MessageBox.Show("방전모드로 변경 하시겠습니까?", "확인", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Repository.Instance.pmdviewer.Control_Discharge();
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void tb_Power_Set_TextChanged(object sender, EventArgs e)
{
Check_Active_Power_Input();
}
private void tb_Power_Set_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
{
if (tb_Power_Set.MaskFull)
{
tb_Power_Set.Enabled = false;
tb_Power_Set.Enabled = true;
//MessageBox.Show("모든 사항이 입력되었습니다. 추가입력이 불가합니다");
}
else if (e.Position == tb_Power_Set.Mask.Length)
{
MessageBox.Show("마스크 위치를 넘어섰습니다. 입력이 불가합니다");
}
else
{
MessageBox.Show("숫자만 입력해야 합니다. 입력이 불가합니다");
}
}
private void btn_Manual_Mode_Click(object sender, EventArgs e)
{
if (MessageBox.Show("메뉴얼모드로 변경 하시겠습니까?", "확인", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
System.Windows.Forms.Button button = (System.Windows.Forms.Button)sender;
Repository.Instance.current_pcs_mode = 2; // 2 indicates Manual Mode
btn_Manual_Mode.Image = ImageResize.ResizeImage(Properties.Resources.RUN_003, button.Width, button.Height);
btn_Scheduling_Mode.Image = null;
}
}
private void btn_Scheduling_Mode_Click(object sender, EventArgs e)
{
if (MessageBox.Show("스케줄모드로 변경 하시겠습니까?", "확인", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
System.Windows.Forms.Button button = (System.Windows.Forms.Button)sender;
btn_Manual_Mode.Image = null;
btn_Scheduling_Mode.Image = ImageResize.ResizeImage(Properties.Resources.RUN_003, button.Width, button.Height);
Repository.Instance.current_pcs_mode = 3; // 3 indicates Scheduling Mode
}
}
private void tb_Power_Set_Leave(object sender, EventArgs e)
{
if (MessageBox.Show("해당 설정을 적용하시겠습니까?", "확인", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Check_Active_Power_Input();
}
}
// ----------------------------------------------
// 2018-07-10
// Parameter로 설정된 Active_Power값을 검사하고
// 적당할 값일 경우 데이터를 변수안에 집어넣는 함수이다
// Check_Active_Power_Input
// ----------------------------------------------
private void Check_Active_Power_Input()
{
try
{
double a = Convert.ToSingle(tb_Power_Set.Text);
if (a > Repository.Instance.p_setting.Limit_Active_Power)
{
a = Repository.Instance.p_setting.Limit_Active_Power;
MessageBox.Show("Power를 " + Repository.Instance.p_setting.Limit_Active_Power + "kW 이상 설정할 수 없습니다");
}
Repository.Instance.remote_power = Convert.ToUInt16(a * 10);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
// -----------------------------------------------
// KeyChar이 Enter가 들어오면 Enable의 Positive Edge를
// 만들어줌으로 써, Focus를 잃게 만든다
// -----------------------------------------------
private void tb_Power_Set_KeyPress(object sender, KeyPressEventArgs e)
{
switch (e.KeyChar)
{
case (char)Keys.Enter:
tb_Power_Set.Enabled = false;
tb_Power_Set.Enabled = true;
break;
}
}
private void tb_Power_Set_Validated(object sender, EventArgs e)
{
}
private void btn_Control_LPMS_Click(object sender, EventArgs e)
{
if (MessageBox.Show("LEMS 제어모드로 변경하시겠습니까?", "확인", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Repository.Instance.GnEPS_PCS.Authority_PMS = true;
}
}
private void btn_Control_uPMS_Click(object sender, EventArgs e)
{
if (MessageBox.Show("uPMS 제어모드로 변경하시겠습니까?", "확인", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Repository.Instance.GnEPS_PCS.Authority_PMS = false;
}
}
private void ControlViewer_Load(object sender, EventArgs e)
{
Repository.Instance.p_setting.Set_Current_PCS_Operating_Mode(Repository.Instance.p_setting.Charging_StartTime, Repository.Instance.p_setting.Charging_EndTime, Repository.Instance.p_setting.Discharging_StartTime, Repository.Instance.p_setting.Discharging_EndTime);
Repository.Instance.p_setting.Set_Scheduler_Setting(Repository.Instance.p_setting.Charging_StartTime, Repository.Instance.p_setting.Charging_EndTime, Repository.Instance.p_setting.Discharging_StartTime, Repository.Instance.p_setting.Discharging_EndTime);
Set_Scheduler_Color();
}
public void Set_Scheduler_Color()
{
foreach (Control gb in this.Controls)
{
if (gb_scheduler is GroupBox)
{
foreach (Control btn in gb.Controls)
{
if (btn is Button)
{
string[] parse = btn.Name.Split('_');
int index = Convert.ToInt16(parse[2]);
if (Repository.Instance.scheduler[index] == 1)
{
btn.BackColor = Color.Red;
}
else if (Repository.Instance.scheduler[index] == 2)
{
btn.BackColor = Color.Blue;
}
else
{
btn.BackColor = Color.Gray;
}
}
}
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KTE_PMS
{
public class sPower
{
public double PCS_CHARGE_POWER { get; set; }
public double PCS_DISCHARGE_POWER { get; set; }
public double BMS_CHARGE_POWER { get; set; }
public double BMS_DISCHARGE_POWER { get; set; }
public bool setBMSPower(double power)
{
if (power > 0)
{
BMS_CHARGE_POWER = BMS_CHARGE_POWER + power;
}
else if (power < 0)
{
BMS_DISCHARGE_POWER = -1 * BMS_DISCHARGE_POWER + power;
}
return true;
}
public bool setPCSPower(double power)
{
if (power > 0)
{
PCS_CHARGE_POWER = PCS_CHARGE_POWER + power;
}
else if (power < 0)
{
PCS_DISCHARGE_POWER = -1 * PCS_DISCHARGE_POWER + power;
}
return true;
}
public static sPower operator+ (sPower a, sPower b)
{
sPower newPower = new sPower();
newPower.BMS_CHARGE_POWER = a.BMS_CHARGE_POWER + b.BMS_CHARGE_POWER;
newPower.BMS_DISCHARGE_POWER = a.BMS_DISCHARGE_POWER + b.BMS_DISCHARGE_POWER;
newPower.PCS_CHARGE_POWER = a.PCS_CHARGE_POWER + b.PCS_CHARGE_POWER;
newPower.PCS_DISCHARGE_POWER = a.PCS_DISCHARGE_POWER + b.PCS_DISCHARGE_POWER;
return newPower;
}
}
}
<file_sep>using KTE_PMS.Observer;
using ModbusTCP;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
namespace KTE_PMS.MIMIC
{
public partial class BMSViewer : Form
{
public ModbusTCP.Master MBmaster;
public byte[] BSC_Rack_Data { get; set; }
public byte[] BSC_Module_Data { get; set; }
public byte[] BSC_Rack_Version { get; set; }
public byte[] BSC_Controller_Data { get; set; }
public byte[] BSC1 { get; set; }
public byte[] BSC2 { get; set; }
DateTime tLastRecv;
public byte[] WriteValueBuffers { get; set; }
public BMSViewer()
{
InitializeComponent();
WriteValueBuffers = new byte[64];
tLastRecv = new DateTime();
tLastRecv = DateTime.Now;
if (Properties.Settings.Default.DEBUG) return;
MBmaster = new Master();
BSC_Controller_Data = new Byte[14];
BSC1 = new Byte[60];
// For test. IP 설정창을 그린 후 해당 내용으로 교체할 예정임
// Samsung Battery로 변경함
if (Properties.Settings.Default.DEBUG)
{
txtIP1.Text = "127";
txtIP2.Text = "0";
txtIP3.Text = "0";
txtIP4.Text = "1";
}
else
{
txtIP1.Text = "17";
txtIP2.Text = "91";
txtIP3.Text = "30";
txtIP4.Text = "246";
}
//-----------------------------
// Modbus TCP - BMS 통신 시도 //
//-----------------------------
// 1. File에서 설정값 읽어오기
//Read_BSC_Configuration();
// 2. 연결하기
Connect_to_BSC();
timer.Enabled = true;
timer.Interval = 1000;
timer.Start();
}
private void txtIP1_TextChanged(object sender, EventArgs e)
{
}
public void ReadFromBSC(ushort ID)
{
//MBmaster.ReadHoldingRegister((ushort)0, (Byte)3, (ushort)40000, (Byte)3);
//ushort ID = 1;
byte unit = Convert.ToByte(0);
ushort temp_startaddr = new ushort();
ushort temp_length = new ushort();
if (ID == 1)
{
temp_startaddr = 0;
temp_length = 40;
}
else if (ID == 2)
{
temp_startaddr = 40;
temp_length = 51;
}
else if (ID == 3)
{
temp_startaddr = 100;
temp_length = 51;
}
ushort StartAddress = ReadStartAdr(temp_startaddr);
byte Length = Convert.ToByte(temp_length);
MBmaster.ReadInputRegister(ID, unit, StartAddress, Length);
}
public void WriteToBSC(byte value)
{
ushort ID = 8;
byte unit = Convert.ToByte(0);
ushort StartAddress = ReadStartAdr(0);
byte Length = Convert.ToByte(1);
WriteValueBuffers[0] = 0;
WriteValueBuffers[1] = value;
// Samsung Battery
MBmaster.WriteSingleRegister(ID, unit, StartAddress, WriteValueBuffers);
}
public void GRID_ON()
{
WriteToBSC(5);
}
public void GRID_OFF()
{
WriteToBSC(3);
}
public void WATCHDOG(short value)
{
ushort ID = 8;
byte unit = Convert.ToByte(0);
ushort StartAddress = ReadStartAdr(2);
byte Length = Convert.ToByte(1);
WriteValueBuffers[0] = Convert.ToByte(value / 256);
WriteValueBuffers[1] = Convert.ToByte(value % 256);
// Samsung Battery
MBmaster.WriteSingleRegister(ID, unit, StartAddress, WriteValueBuffers);
}
// ------------------------------------------------------------------------
// Event for response data
// ------------------------------------------------------------------------
private void MBmaster_OnResponseData(ushort ID, byte unit, byte function, byte[] values)
{
// ------------------------------------------------------------------
// Seperate calling threads
if (this.InvokeRequired)
{
this.BeginInvoke(new Master.ResponseData(MBmaster_OnResponseData), new object[] { ID, unit, function, values });
return;
}
// ------------------------------------------------------------------------
// Identify requested data
switch (ID)
{
case 1:
// ---------------------------------------------------------
// 30000~30100
// ---------------------------------------------------------
Repository.Instance.Get_BSC(values);
tLastRecv = DateTime.Now;
Notify();
break;
case 2:
Repository.Instance.Insert_Rack(ref Repository.Instance.samsung_bcs.Rack1, values, 1);
tLastRecv = DateTime.Now;
Notify();
break;
case 3:
Repository.Instance.Insert_Rack(ref Repository.Instance.samsung_bcs.Rack2, values, 2);
tLastRecv = DateTime.Now;
Notify();
break;
case 8:
//grpData.Text = "Write multiple register";
break;
}
}
// ------------------------------------------------------------------------
// Modbus TCP slave exception
// ------------------------------------------------------------------------
private void MBmaster_OnException(ushort id, byte unit, byte function, byte exception)
{
string exc = "Modbus says error: ";
switch (exception)
{
case Master.excIllegalFunction: exc += "Illegal function!"; break;
case Master.excIllegalDataAdr: exc += "Illegal data adress!"; break;
case Master.excIllegalDataVal: exc += "Illegal data value!"; break;
case Master.excSlaveDeviceFailure: exc += "Slave device failure!"; break;
case Master.excAck: exc += "Acknoledge!"; break;
case Master.excGatePathUnavailable: exc += "Gateway path unavailbale!"; break;
case Master.excExceptionTimeout: exc += "Slave timed out!"; break;
case Master.excExceptionConnectionLost: exc += "Connection is lost!"; break;
case Master.excExceptionNotConnected: exc += "Not connected!"; break;
}
System.Diagnostics.Debug.WriteLine(exc);
//MessageBox.Show(exc, "Modbus slave exception");
}
public void Connect_to_BSC()
{
try
{
// Create new modbus master and add event functions
string ip_address = txtIP1.Text + "." + txtIP2.Text + "." + txtIP3.Text + "." + txtIP4.Text;
//string ip_address = "127.0.0.1";
ushort port_number = 502;
MBmaster = new Master(ip_address, port_number);
// Setting response data and exception
MBmaster.OnResponseData += new Master.ResponseData(MBmaster_OnResponseData);
MBmaster.OnException += new Master.ExceptionData(MBmaster_OnException);
//flag_BSC_Connection = 1;
}
catch (SystemException error)
{
MessageBox.Show(error.Message + "다시 접속해 주세요");
System.Diagnostics.Debug.WriteLine(error.Message + "다시 접속해 주세요");
//flag_BSC_Connection = 0;
}
}
public byte get_BSC1(int i)
{
return BSC1[i];
}
public void Connect_to_PCS()
{
//modbus_rtu = new Modbus_Setup();
}
private ushort ReadStartAdr(UInt16 StartAddress)
{
return StartAddress;
}
private void Read_BSC_Configuration()
{
string directory = System.Windows.Forms.Application.StartupPath;
string filename = "\\Configs.dat";
// ----------------------------------------------------------------------------------------
// 파일을 읽어서 List에 넣기
// cTag에 저장하기
// 항상 동작하면서 cTag에 있는 값을 해당되는 통신방식에 맞게 값을 읽어오고 주기적으로 쓴다
// ----------------------------------------------------------------------------------------
try
{
FileStream fs = File.OpenRead(directory + filename);
StreamReader r = new StreamReader(fs, System.Text.Encoding.Default);
// 문자 스트림 변환
r.BaseStream.Seek(0, SeekOrigin.Begin);
// 일단 찾고
// 하기
// Skip First Line //
string temp = r.ReadLine();
// 만약 끝이 아니라면
while (r.Peek() > -1)
{
// 1 Line 을 읽는다.
temp = r.ReadLine();
// 2. BSC 관련 값을 찾는다. BSC가 아니라면 다음 라인을 읽는다
if (temp.Contains("BSC Setting"))
{
///type = LG
///ip_address = 172.31.110.33
///port = 504
///
string[] split;
// Read ////////////
temp = r.ReadLine();
split = System.Text.RegularExpressions.Regex.Split(temp, "=");
// Manufacture of BSC
temp = r.ReadLine();
split = System.Text.RegularExpressions.Regex.Split(temp, "=");
// Read Ip address
temp = r.ReadLine();
split = System.Text.RegularExpressions.Regex.Split(temp, "=");
string kk = split[1].Trim();
string[] split2 = split[1].Split(new char[] { '.' });
txtIP1.Text = split2[0].ToString().Trim();
txtIP2.Text = split2[1].ToString().Trim();
txtIP3.Text = split2[2].ToString().Trim();
txtIP4.Text = split2[3].ToString().Trim();
// Read Port
temp = r.ReadLine();
split = System.Text.RegularExpressions.Regex.Split(temp, "=");
txtPort.Text = split[1].ToString().Trim();
break;
}
}
r.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Abort");
throw e;
}
}
public List<IUpdate> observers = new List<IUpdate>();
public void AddObserver(IUpdate observer)
{
observers.Add(observer);
}
public void RemoveObserver(IUpdate observer)
{
observers.Remove(observer);
}
public void Notify()
{
foreach (IUpdate observer in observers)
{
observer.ObserverUpdate();
}
}
public int Connected()
{
DateTime dt_now;
dt_now = DateTime.Now;
TimeSpan span = dt_now - tLastRecv;
if (span.TotalSeconds < 10)
{
if (Repository.Instance.TagManager.FAULT_STATUS[48, 10, 0] != "0")
Repository.Instance.TagManager.경보발생및해제(0, 48, 10);
return 1;
}
else
{
if (Repository.Instance.TagManager.FAULT_STATUS[48, 10, 0] != "1")
Repository.Instance.TagManager.경보발생및해제(1, 48, 10);
//MBmaster.Dispose();
//Connect_to_BSC();
//if (Properties.Settings.Default.DEBUG ) Console.WriteLine("재접속 시도합니다");
return 0;
}
}
private void timer_Tick(object sender, EventArgs e)
{
// 1초 Timer에 의해서 수행되는 코드
//-----------------------------------------------------------
// Read From BSC
// BSC와 연결되어있다면 Read 시도, 그렇지 않다면 재접속 시도.
//-----------------------------------------------------------
//-----------------------------------------------------------
// Read From BSC
// BSC와 연결되어있다면 Read 시도, 그렇지 않다면 재접속 시도.
//-----------------------------------------------------------
ReadFromBSC(Convert.ToUInt16(((DateTime.Now.Second % 3) + 1)));
}
}
}
<file_sep>using DevExpress.XtraCharts;
using KTE_PMS;
using System;
using System.Linq;
using System.Windows.Forms;
namespace Test_Trend
{
public partial class Form1 : Form
{
Series[] series = new Series[2];
DateTime[] cdatetTime;
Double[] cVoltage;
public DBConnector dbConnector;
public Form1()
{
InitializeComponent();
dbConnector = new DBConnector();
series[0] = new Series("time1", ViewType.Line);
cdatetTime = new DateTime[10];
cVoltage = new double[10];
/*
chartControl1.Series.Add(series[0]);
series[0].ArgumentDataMember = "DATETIME";
series[0].ArgumentScaleType = ScaleType.DateTime;
series[0].ValueDataMembers.AddRange(new string[] { "VOLTAGE" });
series[0].ValueScaleType = ScaleType.Numerical;
*/
//chartControl1.Series[0].ValueDataMembers[0].
// Set some properties to get a nice-looking chart.
((XYDiagram)chartControl1.Diagram).AxisY.Visibility = DevExpress.Utils.DefaultBoolean.False;
chartControl1.Legend.Visibility = DevExpress.Utils.DefaultBoolean.False;
SetDiagramTimeRange((XYDiagram)chartControl1.Diagram, 1440);
timer1.Interval = 400; // 0.4초
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Start();
// This line of code is generated by Data Source Configuration Wizard
// Fill a SqlDataSource
sqlDataSource1.Fill();
}
private void SetDiagramTimeRange(XYDiagram diagram, int diff)
{
//DateTime dt1 = DateTime.Now.AddHours(1);
//DateTime dt2 = DateTime.Now.AddHours(-1);
if (diff != 0)
{
DateTime dt1 = DateTime.Now.AddMinutes(diff);
DateTime dt2 = DateTime.Now.AddMinutes(-1 * diff);
/*
//DateTime dt = Convert.ToDateTime(diagram.AxisX.VisualRange.MaxValue);
maskedTextBox1.Text = dt1.Year.ToString("D4") + "년" + dt1.Month.ToString("D2") + "월" + dt1.Day.ToString("D2") + "일 " + dt1.Hour.ToString("D2") + "시" + dt1.Minute.ToString("D2") + "분";
//dt = Convert.ToDateTime(diagram.AxisX.VisualRange.MinValue);
maskedTextBox2.Text = dt2.Year.ToString("D4") + "년" + dt2.Month.ToString("D2") + "월" + dt2.Day.ToString("D2") + "일 " + dt2.Hour.ToString("D2") + "시" + dt2.Minute.ToString("D2") + "분";
*/
maskedTextBox1.Text = dt1.Year.ToString("D4") + "년" + dt1.Month.ToString("D2") + "월" + dt1.Day.ToString("D2") + "일 " + dt1.Hour.ToString("D2") + "시" + dt1.Minute.ToString("D2") + "분";
maskedTextBox2.Text = dt2.Year.ToString("D4") + "년" + dt2.Month.ToString("D2") + "월" + dt2.Day.ToString("D2") + "일 " + dt2.Hour.ToString("D2") + "시" + dt2.Minute.ToString("D2") + "분";
}
/*
diagram.AxisX.WholeRange.Auto = false;
diagram.AxisX.VisualRange.Auto = false;
diagram.AxisX.VisualRange.AutoSideMargins = false;
diagram.AxisX.WholeRange.AutoSideMargins = false;
*/
DateTime t_Datetime_Maxvalue = DateTime.Parse(maskedTextBox1.Text.Trim());
diagram.AxisX.VisualRange.MaxValue = t_Datetime_Maxvalue;
diagram.AxisX.WholeRange.MaxValue = t_Datetime_Maxvalue;
DateTime t_Datetime_Minvalue = DateTime.Parse(maskedTextBox2.Text.Trim());
diagram.AxisX.VisualRange.MinValue = t_Datetime_Minvalue;
diagram.AxisX.WholeRange.MinValue = t_Datetime_Minvalue;
}
private void button1_Click(object sender, EventArgs e)
{
dbConnector.Insert_Voltage();
}
void timer1_Tick(object sender, EventArgs e)
{
dbConnector.GetProduct();
sqlDataSource1.Fill();
//chartControl1.RefreshData();
}
private void 적용(object sender, EventArgs e)
{
try
{
SetDiagramTimeRange((XYDiagram)chartControl1.Diagram, 0);
}
catch (Exception)
{
}
}
private void maskedTextBox2_MaskInputRejected(object sender, System.Windows.Forms.MaskInputRejectedEventArgs e)
{
if (maskedTextBox2.MaskFull)
{
MessageBox.Show("모든 사항이 입력되었습니다. 추가입력이 불가합니다");
}
else if (e.Position == maskedTextBox2.Mask.Length)
{
MessageBox.Show("마스크 위치를 넘어섰습니다. 입력이 불가합니다");
}
else
{
MessageBox.Show("숫자만 입력해야 합니다. 입력이 불가합니다");
}
}
private void maskedTextBox1_MaskInputRejected(object sender, System.Windows.Forms.MaskInputRejectedEventArgs e)
{
if (maskedTextBox1.MaskFull)
{
MessageBox.Show("모든 사항이 입력되었습니다. 추가입력이 불가합니다");
}
else if (e.Position == maskedTextBox1.Mask.Length)
{
MessageBox.Show("마스크 위치를 넘어섰습니다. 입력이 불가합니다");
}
else
{
MessageBox.Show("숫자만 입력해야 합니다. 입력이 불가합니다");
}
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox a = (CheckBox)sender;
XYDiagram diagram = (XYDiagram)chartControl1.Diagram;
if (a.Checked)
{
diagram.AxisX.DateTimeScaleOptions.ScaleMode = ScaleMode.Automatic;
}
else
{
diagram.AxisX.DateTimeScaleOptions.ScaleMode = ScaleMode.Manual;
}
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
CheckBox a = (CheckBox)sender;
XYDiagram diagram = (XYDiagram)chartControl1.Diagram;
if (a.Checked)
{
diagram.AxisX.DateTimeScaleOptions.ScaleMode = ScaleMode.Continuous ;
}
else
{
diagram.AxisX.DateTimeScaleOptions.ScaleMode = ScaleMode.Manual;
}
}
private void checkBox4_CheckedChanged(object sender, EventArgs e)
{
CheckBox a = (CheckBox)sender;
XYDiagram diagram = (XYDiagram)chartControl1.Diagram;
if (a.Checked)
{
diagram.AxisX.WholeRange.AutoSideMargins = true;
diagram.AxisX.VisualRange.AutoSideMargins = true;
}
else
{
diagram.AxisX.WholeRange.AutoSideMargins = false;
diagram.AxisX.VisualRange.AutoSideMargins = false;
}
}
private void checkBox5_CheckedChanged(object sender, EventArgs e)
{
CheckBox a = (CheckBox)sender;
XYDiagram diagram = (XYDiagram)chartControl1.Diagram;
if (a.Checked)
{
diagram.AxisX.WholeRange.Auto = true;
diagram.AxisX.VisualRange.Auto = true;
}
else
{
diagram.AxisX.WholeRange.Auto = false;
diagram.AxisX.VisualRange.Auto = false;
}
}
private void button3_Click(object sender, EventArgs e)
{
SetDiagramTimeRange((XYDiagram)chartControl1.Diagram, 10);
}
private void button4_Click(object sender, EventArgs e)
{
SetDiagramTimeRange((XYDiagram)chartControl1.Diagram, 60);
}
private void button5_Click(object sender, EventArgs e)
{
SetDiagramTimeRange((XYDiagram)chartControl1.Diagram, 1440);
}
}
}
<file_sep>using KTE_PMS.Observer;
using System;
using System.Windows.Forms;
namespace KTE_PMS.MIMIC
{
public partial class MainViewer : Viewer, IUpdate
{
private int index;
//private System.Threading.Timer threadingtimer; // 1초 타이머를 위한 함수(Main Timer)
public MainViewer()
{
InitializeComponent();
timer1.Enabled = true;
timer1.Interval = 1000;
timer1.Start();
}
delegate void CrossThreadSafetySetText(Control ctl, String text);
private void CSafeSetText(Control ctl, String text)
{
/*
* InvokeRequired 속성 (Control.InvokeRequired, MSDN)
* 짧게 말해서, 이 컨트롤이 만들어진 스레드와 현재의 스레드가 달라서
* 컨트롤에서 스레드를 만들어야 하는지를 나타내는 속성입니다.
*
* InvokeRequired 속성의 값이 참이면, 컨트롤에서 스레드를 만들어 텍스트를 변경하고,
* 그렇지 않은 경우에는 그냥 변경해도 아무 오류가 없기 때문에 텍스트를 변경합니다.
*/
if (ctl.InvokeRequired)
ctl.Invoke(new CrossThreadSafetySetText(CSafeSetText), ctl, text);
else
ctl.Text = text;
}
private void timer1_Tick(object sender, EventArgs e)
{
Display_Animation();
Display_Textbox_Power();
}
private void Display_Textbox_Power()
{
}
private void Display_Animation()
{
// Status Check
// Reverse Mode가 있어야한다.
int reverse_index = new int();
switch (index)
{
case 0:
reverse_index = 0;
break;
case 1:
reverse_index = 4;
break;
case 2:
reverse_index = 3;
break;
case 3:
reverse_index = 2;
break;
case 4:
reverse_index = 1;
break;
default:
reverse_index = 0;
break;
}
////////////////////////////////////////////////////////////
// Depending a status, Determine a direction of signal //
////////////////////////////////////////////////////////////
if (Repository.Instance.samsung_bcs.Mode_Charging == 1)
{
pb_Battery_to_PCS.Image = Battery_to_PCS.Images[reverse_index];
lb_Current_Status.Text = "배터리 충전 중";
lb_Current_Status.Visible = true;
}
else if (Repository.Instance.samsung_bcs.Mode_Discharging == 1)
{
pb_Battery_to_PCS.Image = Battery_to_PCS.Images[index];
lb_Current_Status.Text = "배터리 방전 중";
lb_Current_Status.Visible = true;
}
else
{
pb_Battery_to_PCS.Image = Battery_to_PCS.Images[0];
lb_Current_Status.Text = "배터리 방전 중";
lb_Current_Status.Visible = false;
}
if (Repository.Instance.GnEPS_PCS.Mode_Standby == 1)
{
pb_PCS_to_Grid.Image = Battery_to_PCS.Images[0];
}
else if (Repository.Instance.GnEPS_PCS.Mode_Charging == 1)
{
pb_PCS_to_Grid.Image = Battery_to_PCS.Images[index];
}
else if (Repository.Instance.GnEPS_PCS.Mode_Discharging == 1)
{
pb_PCS_to_Grid.Image = Battery_to_PCS.Images[reverse_index];
}
else
{
pb_PCS_to_Grid.Image = Battery_to_PCS.Images[0];
}
// Index가 4 이상이라면(5라면) Index를 0으로 초기화해준다.
index++;
if (index > 4) index = 0;
}
public void ObserverUpdate()
{
// Battery SIde middle of left
CSafeSetText(lb1, Repository.Instance.samsung_bcs.System_Voltage.ToString());
CSafeSetText(lb2, Repository.Instance.samsung_bcs.System_Current.ToString());
CSafeSetText(lb3, Repository.Instance.samsung_bcs.System_Power.ToString());
CSafeSetText(lb4, Repository.Instance.samsung_bcs.System_SOC.ToString());
// Grid Side at bottom of right
double Grid_Voltage = (Repository.Instance.GnEPS_PCS.GRID_R_Voltage + Repository.Instance.GnEPS_PCS.GRID_S_Voltage + Repository.Instance.GnEPS_PCS.GRID_T_Voltage) / 3;
double Grid_Current = (Repository.Instance.GnEPS_PCS.GRID_R_Current + Repository.Instance.GnEPS_PCS.GRID_S_Current + Repository.Instance.GnEPS_PCS.GRID_T_Current) / 3;
CSafeSetText(lb5, Grid_Voltage.ToString());
CSafeSetText(lb6, Grid_Current.ToString());
CSafeSetText(lb7, Repository.Instance.GnEPS_PCS.GRID_Power.ToString());
CSafeSetText(lb8, Repository.Instance.GnEPS_PCS.GRID_Frequency.ToString());
CSafeSetText(lb9, Repository.Instance.p_setting.power_day.BMS_CHARGE_POWER.ToString()); // 배터리 일별 충전
CSafeSetText(lb12, Repository.Instance.p_setting.power_day.BMS_DISCHARGE_POWER.ToString()); // 배터리 일별 방전
CSafeSetText(lb15, Repository.Instance.p_setting.power_day.PCS_CHARGE_POWER.ToString()); // PCS 일별 충전
CSafeSetText(lb18, Repository.Instance.p_setting.power_day.PCS_DISCHARGE_POWER.ToString()); // PCS 일별 방전
CSafeSetText(lb10, Repository.Instance.p_setting.power_month.BMS_CHARGE_POWER.ToString()); // 배터리 월별 충전
CSafeSetText(lb13, Repository.Instance.p_setting.power_month.BMS_DISCHARGE_POWER.ToString()); // 배터리 월별 방전
CSafeSetText(lb16, Repository.Instance.p_setting.power_month.PCS_CHARGE_POWER.ToString()); // PCS 일별 월전
CSafeSetText(lb19, Repository.Instance.p_setting.power_month.PCS_DISCHARGE_POWER.ToString()); // PCS 월별 방전
CSafeSetText(lb11, Repository.Instance.p_setting.power_year.BMS_CHARGE_POWER.ToString()); // 배터리 년별 충전
CSafeSetText(lb14, Repository.Instance.p_setting.power_year.BMS_DISCHARGE_POWER.ToString()); // 배터리 년별 방전
CSafeSetText(lb17, Repository.Instance.p_setting.power_year.PCS_CHARGE_POWER.ToString()); // PCS 년별 충전
CSafeSetText(lb20, Repository.Instance.p_setting.power_year.PCS_DISCHARGE_POWER.ToString()); // PCS 년별 방전
}
private void MainViewer_Load(object sender, EventArgs e)
{
}
private void btn_PeakCutMode_Click(object sender, EventArgs e)
{
if (MessageBox.Show("피크저감 모드로 변경하시겠습니까?", "확인", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
// -------------------------------------------------------------------------------------
// 180710
// 현재 피크저감 모드는 어떤 식으로 할지 명확하게 정의가 안되어서 주석처리를 해놨음
// -------------------------------------------------------------------------------------
/*
Repository.Instance.p_setting.Charging_StartTime = new TimeSpan(08, 00, 00);
Repository.Instance.p_setting.Charging_EndTime = new TimeSpan(12, 00, 00);
Repository.Instance.p_setting.Discharging_StartTime = new TimeSpan(16, 00, 00);
Repository.Instance.p_setting.Discharging_EndTime = new TimeSpan(20, 00, 00);
*/
Repository.Instance.p_setting.Set_Scheduler_Setting
(
Repository.Instance.p_setting.Charging_StartTime,
Repository.Instance.p_setting.Charging_EndTime,
Repository.Instance.p_setting.Discharging_StartTime,
Repository.Instance.p_setting.Discharging_EndTime
);
Repository.Instance.p_control.Set_Scheduler_Color();
}
}
private void btn_CustomMode_Click(object sender, EventArgs e)
{
if (MessageBox.Show("사용자 정의 모드로 변경하시겠습니까?", "확인", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
// -------------------------------------------------------------------------------------
// 180710
// 현재 사용자 정의 모드는 어떤 식으로 할지 명확하게 정의가 안되어서 주석처리를 해놨음
// -------------------------------------------------------------------------------------
/*
Repository.Instance.p_setting.Charging_StartTime = new TimeSpan(08, 00, 00);
Repository.Instance.p_setting.Charging_EndTime = new TimeSpan(12, 00, 00);
Repository.Instance.p_setting.Discharging_StartTime = new TimeSpan(16, 00, 00);
Repository.Instance.p_setting.Discharging_EndTime = new TimeSpan(20, 00, 00);
*/
Repository.Instance.p_setting.Set_Scheduler_Setting(
Repository.Instance.p_setting.Charging_StartTime,
Repository.Instance.p_setting.Charging_EndTime,
Repository.Instance.p_setting.Discharging_StartTime,
Repository.Instance.p_setting.Discharging_EndTime);
Repository.Instance.p_control.Set_Scheduler_Color();
}
}
private void btn_ChargingMode_Click(object sender, EventArgs e)
{
if (MessageBox.Show("사용자 정의 모드로 변경하시겠습니까?", "확인", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Repository.Instance.p_setting.Charging_StartTime = new TimeSpan(00, 00, 00);
Repository.Instance.p_setting.Charging_EndTime = new TimeSpan(24, 00, 00);
Repository.Instance.p_setting.Discharging_StartTime = new TimeSpan(00, 00, 00);
Repository.Instance.p_setting.Discharging_EndTime = new TimeSpan(00, 00, 00);
Repository.Instance.p_setting.Set_Scheduler_Setting(
Repository.Instance.p_setting.Charging_StartTime,
Repository.Instance.p_setting.Charging_EndTime,
Repository.Instance.p_setting.Discharging_StartTime,
Repository.Instance.p_setting.Discharging_EndTime);
Repository.Instance.p_control.Set_Scheduler_Color();
}
}
private void btn_DisChargingMode_Click(object sender, EventArgs e)
{
Repository.Instance.p_setting.Charging_StartTime = new TimeSpan(00, 00, 00);
Repository.Instance.p_setting.Charging_EndTime = new TimeSpan(00, 00, 00);
Repository.Instance.p_setting.Discharging_StartTime = new TimeSpan(00, 00, 00);
Repository.Instance.p_setting.Discharging_EndTime = new TimeSpan(24, 00, 00);
Repository.Instance.p_setting.Set_Scheduler_Setting(
Repository.Instance.p_setting.Charging_StartTime,
Repository.Instance.p_setting.Charging_EndTime,
Repository.Instance.p_setting.Discharging_StartTime,
Repository.Instance.p_setting.Discharging_EndTime);
Repository.Instance.p_control.Set_Scheduler_Color();
}
}
}
<file_sep>using KTE_PMS.Observer;
using System;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
namespace KTE_PMS.MIMIC
{
public partial class MeasureViewer3 : Viewer, IUpdate
{
public MeasureViewer3()
{
InitializeComponent();
}
private void Measure_Load(object sender, EventArgs e)
{
}
delegate void CrossThreadSafetySetText(Control ctl, String text);
private void CSafeSetText(Control ctl, String text)
{
/*
* InvokeRequired 속성 (Control.InvokeRequired, MSDN)
* 짧게 말해서, 이 컨트롤이 만들어진 스레드와 현재의 스레드가 달라서
* 컨트롤에서 스레드를 만들어야 하는지를 나타내는 속성입니다.
*
* InvokeRequired 속성의 값이 참이면, 컨트롤에서 스레드를 만들어 텍스트를 변경하고,
* 그렇지 않은 경우에는 그냥 변경해도 아무 오류가 없기 때문에 텍스트를 변경합니다.
*/
if (ctl.InvokeRequired)
ctl.Invoke(new CrossThreadSafetySetText(CSafeSetText), ctl, text);
else
ctl.Text = text;
}
public void ObserverUpdate()
{
// BMS : System용 이다
// 값 써주기
CSafeSetText(lb1, Repository.Instance.GnEPS_PCS.Fault_Battery_Voltage.ToString() + " " + "V");
CSafeSetText(lb2, Repository.Instance.GnEPS_PCS.Fault_Battery_Current.ToString() + " " + "V");
CSafeSetText(lb3, Repository.Instance.GnEPS_PCS.Fault_System_A_Current.ToString() + " " + "A");
CSafeSetText(lb4, Repository.Instance.GnEPS_PCS.Fault_System_B_Current.ToString() + " " + "A");
CSafeSetText(lb5, Repository.Instance.GnEPS_PCS.Fault_System_C_Current.ToString() + " " + "A");
CSafeSetText(lb6, Repository.Instance.GnEPS_PCS.Fault_Inverter_A_Current.ToString() + " " + "A");
CSafeSetText(lb7, Repository.Instance.GnEPS_PCS.Fault_Inverter_B_Current.ToString() + " " + "A");
CSafeSetText(lb8, Repository.Instance.GnEPS_PCS.Fault_Inverter_C_Current.ToString() + " " + "A");
CSafeSetText(lb9, Repository.Instance.GnEPS_PCS.Fault_Inverter_A_Voltage .ToString() + " " + "V");
CSafeSetText(lb10, Repository.Instance.GnEPS_PCS.Fault_Inverter_B_Voltage.ToString() + " " + "V");
CSafeSetText(lb11, Repository.Instance.GnEPS_PCS.Fault_Inverter_C_Voltage.ToString() + " " + "V");
CSafeSetText(lb12, Repository.Instance.GnEPS_PCS.Fault_Active_Power.ToString());
CSafeSetText(lb13, Repository.Instance.GnEPS_PCS.Fault_System_CB_Status.ToString() + " " + "V");
}
private void btn_Move_To_BMS_System_MouseClick(object sender, MouseEventArgs e)
{
Panel p = (Panel)Parent;
p.Controls.Clear();
p.Controls.Add(Repository.Instance.p_measure);
}
private void btn_Move_To_BMS_Rack_MouseClick(object sender, MouseEventArgs e)
{
Panel p = (Panel)Parent;
p.Controls.Clear();
p.Controls.Add(Repository.Instance.p_measure_BMS_Rack);
}
private void btn_Move_To_PCS_Data_MouseClick(object sender, MouseEventArgs e)
{
Panel p = (Panel)Parent;
p.Controls.Clear();
p.Controls.Add(Repository.Instance.p_measure_PCS);
}
private void btn_Move_To_PCS_Fault_MouseClick(object sender, MouseEventArgs e)
{
Panel p = (Panel)Parent;
p.Controls.Clear();
p.Controls.Add(Repository.Instance.p_measure_PCS_Fault);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace UDP
{
class Program
{
static void Main(string[] args)
{
int buffer_size;
byte[] t_data;
const int port = 5000;
string input;
//string input2;
int vv = new int();
IPEndPoint serverEP = new IPEndPoint(IPAddress.Parse("172.31.110.204"), port);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, port);
EndPoint remoteEP = (EndPoint)sender;
client.Bind(sender);
while (true)
{
Console.Write("send data : ");
input = Console.ReadLine();
if (input == "exit")
break;
/*Console.Write("value : ");
input2 = Console.ReadLine();
if (input2 == "exit")
break;
*/
//buffer_size = Convert.ToInt16(input);
buffer_size = 2048;
vv++;
vv = vv % 6;
t_data = new byte[buffer_size];
for (int i = 0; i < buffer_size / 2; i = i + 2)
{
byte[] dat = new byte[2];
//dat = BitConverter.GetBytes((short)System.Net.IPAddress.HostToNetworkOrder((short)Convert.ToInt16(vv)));
dat = BitConverter.GetBytes((short)System.Net.IPAddress.HostToNetworkOrder((short)Convert.ToInt16(vv)));
t_data[i] = dat[0];
t_data[i+1] = dat[1];
}
//client.SendTo(t_data, buffer_size, SocketFlags.None, serverEP);
Delay(100);
}
Console.WriteLine("Stopping client");
client.Close();
}
static private byte[] HostToNetworkOrder(int word)
{
byte[] data = new Byte[2];
byte[] dat = BitConverter.GetBytes((short)System.Net.IPAddress.HostToNetworkOrder((short)word));
data[0] = dat[0];
data[1] = dat[1];
return data;
}
private static DateTime Delay(int MS)
{
DateTime ThisMoment = DateTime.Now;
TimeSpan duration = new TimeSpan(0, 0, 0, 0, MS);
DateTime AfterWards = ThisMoment.Add(duration);
while (AfterWards >= ThisMoment)
{
//System.Windows.Forms.Application.DoEvents();
ThisMoment = DateTime.Now;
}
return DateTime.Now;
}
}
}
<file_sep>using KTE_PMS.Observer;
using System;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
namespace KTE_PMS.MIMIC
{
public partial class MeasureViewer2 : Viewer, IUpdate
{
public MeasureViewer2()
{
InitializeComponent();
}
private void Measure_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = Repository.Instance.Tag_Data_Table;
}
delegate void CrossThreadSafetySetText(Control ctl, String text);
private void CSafeSetText(Control ctl, String text)
{
/*
* InvokeRequired 속성 (Control.InvokeRequired, MSDN)
* 짧게 말해서, 이 컨트롤이 만들어진 스레드와 현재의 스레드가 달라서
* 컨트롤에서 스레드를 만들어야 하는지를 나타내는 속성입니다.
*
* InvokeRequired 속성의 값이 참이면, 컨트롤에서 스레드를 만들어 텍스트를 변경하고,
* 그렇지 않은 경우에는 그냥 변경해도 아무 오류가 없기 때문에 텍스트를 변경합니다.
*/
if (ctl.InvokeRequired)
ctl.Invoke(new CrossThreadSafetySetText(CSafeSetText), ctl, text);
else
ctl.Text = text;
}
public void ObserverUpdate()
{
#region Temp
/*
int Module;
int Cell;
// BMS : System용 이다
// 값 써주기
CSafeSetText(lb1, Repository.Instance.samsung_bcs.Rack1.Max1_Cell_Voltage_Value.ToString() + " " + "V");
Module = Repository.Instance.samsung_bcs.Rack1.Max1_Cell_Voltage_Position >> 8 & 0xFF;
Cell = Repository.Instance.samsung_bcs.Rack1.Max1_Cell_Voltage_Position & 0xFF;
CSafeSetText(lb2, Module.ToString());
CSafeSetText(lbb2, Cell.ToString());
CSafeSetText(lb3, Repository.Instance.samsung_bcs.Rack1.Min1_Cell_Voltage_Value.ToString() + " " + "V");
Module = Repository.Instance.samsung_bcs.Rack1.Min1_Cell_Voltage_Position >> 8 & 0xFF;
Cell = Repository.Instance.samsung_bcs.Rack1.Min1_Cell_Voltage_Position & 0xFF;
CSafeSetText(lb4, Module.ToString());
CSafeSetText(lbb4, Cell.ToString());
CSafeSetText(lb5, Repository.Instance.samsung_bcs.Rack1.Max1_Cell_Temp_Value.ToString() + " " + "°C");
Module = Repository.Instance.samsung_bcs.Rack1.Max1_Cell_Temp_Position >> 8 & 0xFF;
Cell = Repository.Instance.samsung_bcs.Rack1.Max1_Cell_Temp_Position & 0xFF;
CSafeSetText(lb6, Module.ToString());
CSafeSetText(lbb6, Cell.ToString());
CSafeSetText(lb7, Repository.Instance.samsung_bcs.Rack1.Min1_Cell_Temp_Value.ToString() + " " + "°C");
Module = Repository.Instance.samsung_bcs.Rack1.Min1_Cell_Temp_Position >> 8 & 0xFF;
Cell = Repository.Instance.samsung_bcs.Rack1.Min1_Cell_Temp_Position & 0xFF;
CSafeSetText(lb8, Module.ToString());
CSafeSetText(lbb8, Cell.ToString());
CSafeSetText(lb9, Repository.Instance.samsung_bcs.Rack1.Average_Cell_Voltage_Value.ToString() + " " + "V");
CSafeSetText(lb10, Repository.Instance.samsung_bcs.Rack1.Rack_Discharge_Current_Limit_of_Rack.ToString() + " " + "A");
CSafeSetText(lb11, Repository.Instance.samsung_bcs.Rack1.Rack_Charge_Current_Limit_of_Rack.ToString() + " " + "A");
CSafeSetText(lb12, Repository.Instance.samsung_bcs.Rack1.Module_Comm_Fault_Position.ToString());
CSafeSetText(lb13, Repository.Instance.samsung_bcs.Rack1.Max2_Cell_Voltage_Value.ToString() + " " + "V");
Module = Repository.Instance.samsung_bcs.Rack1.Max2_Cell_Voltage_Position >> 8 & 0xFF;
Cell = Repository.Instance.samsung_bcs.Rack1.Max2_Cell_Voltage_Position & 0xFF;
CSafeSetText(lb14, Module.ToString());
CSafeSetText(lbb14, Cell.ToString());
CSafeSetText(lb15, Repository.Instance.samsung_bcs.Rack1.Min2_Cell_Voltage_Value.ToString() + " " + "V");
Module = Repository.Instance.samsung_bcs.Rack1.Min2_Cell_Voltage_Position >> 8 & 0xFF;
Cell = Repository.Instance.samsung_bcs.Rack1.Min2_Cell_Voltage_Position & 0xFF;
CSafeSetText(lb16, Module.ToString());
CSafeSetText(lbb16, Cell.ToString());
CSafeSetText(lb17, Repository.Instance.samsung_bcs.Rack1.Max2_Cell_Temp_Value.ToString() + " " + "°C");
Module = Repository.Instance.samsung_bcs.Rack1.Max2_Cell_Temp_Position >> 8 & 0xFF;
Cell = Repository.Instance.samsung_bcs.Rack1.Max2_Cell_Temp_Position & 0xFF;
CSafeSetText(lb18, Module.ToString());
CSafeSetText(lbb18, Cell.ToString());
CSafeSetText(lb19, Repository.Instance.samsung_bcs.Rack1.Min2_Cell_Temp_Value.ToString() + " " + "°C");
Module = Repository.Instance.samsung_bcs.Rack1.Min2_Cell_Temp_Position >> 8 & 0xFF;
Cell = Repository.Instance.samsung_bcs.Rack1.Min2_Cell_Temp_Position & 0xFF;
CSafeSetText(lb20, Module.ToString());
CSafeSetText(lbb20, Cell.ToString());
CSafeSetText(lb21, Repository.Instance.samsung_bcs.Rack1.Average_Cell_Temp_Value.ToString() + " " + "°C");
CSafeSetText(lb22, Repository.Instance.samsung_bcs.Rack1.Rack_Switch_Control_Info.ToString());
CSafeSetText(lb23, Repository.Instance.samsung_bcs.Rack1.Rack_Switch_Sensor_Info.ToString());
CSafeSetText(lb24, Repository.Instance.samsung_bcs.Rack1.Rack_External_Sensor_Info.ToString());
*/
#endregion
}
private void btn_Move_To_BMS_System_MouseClick(object sender, MouseEventArgs e)
{
Panel p = (Panel)Parent;
p.Controls.Clear();
p.Controls.Add(Repository.Instance.p_measure);
}
private void btn_Move_To_BMS_Rack_MouseClick(object sender, MouseEventArgs e)
{
Panel p = (Panel)Parent;
p.Controls.Clear();
p.Controls.Add(Repository.Instance.p_measure_BMS_Rack);
}
private void btn_Move_To_PCS_Data_MouseClick(object sender, MouseEventArgs e)
{
Panel p = (Panel)Parent;
p.Controls.Clear();
p.Controls.Add(Repository.Instance.p_measure_PCS);
}
private void btn_Move_To_PCS_Fault_MouseClick(object sender, MouseEventArgs e)
{
Panel p = (Panel)Parent;
p.Controls.Clear();
p.Controls.Add(Repository.Instance.p_measure_PCS_Fault);
}
}
}
<file_sep>using MySql.Data.MySqlClient;
using System;
using System.Data;
namespace KTE_PMS
{
public class DBConnector
{
private static string connStr;
private static MySqlConnection conn;
public DBConnector()
{
try
{
connStr = "DATABASE=mysql; server = localhost; port = 3306; user id = root; password = <PASSWORD>; database = mysql; persist security info = true; CharSet = utf8; SslMode = none";
conn = new MySqlConnection(connStr);
Console.WriteLine("Connecting to MySQL...");
conn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
//conn.Close();
Console.WriteLine("Done.");
}
public void Insert_Voltage()
{
string strDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
//String sql = "INSERT INTO trend_data (DATETIME, VOLTAGE) " + "VALUES ('" + strDateTime + "','" + rand_num.Next(100) + "')";
//MySqlCommand cmd = new MySqlCommand(sql, conn);
//cmd.ExecuteNonQuery();
}
public DataSet GetProduct()
{
DataSet ds = new DataSet();
String sql = "SELECT * FROM alarm_data ORDER BY DATETIME desc";
MySqlDataAdapter adpt = new MySqlDataAdapter(sql, conn);
adpt.Fill(ds);
return ds;
}
}
}
<file_sep>using System;
using System.Drawing;
using System.Windows.Forms;
namespace KTE_PMS.MIMIC
{
public partial class HistoryViewer : Viewer
{
const int max_row_size = 11;
Color flashColor;
private int diff;
public HistoryViewer()
{
InitializeComponent();
timer1.Enabled = true;
timer1.Interval = 1000;
timer1.Start();
}
private void btn_TO_ALARM_Click(object sender, EventArgs e)
{
Panel p = (Panel)Parent;
p.Controls.Clear();
p.Controls.Add(Repository.Instance.p_alarm);
}
private void btn_TO_HISTORY_Click(object sender, EventArgs e)
{
Panel p = (Panel)Parent;
p.Controls.Clear();
p.Controls.Add(Repository.Instance.p_history);
}
private void timer1_Tick(object sender, EventArgs e)
{
Cell_Color_Painting();
}
public void LoadCurrentFault()
{
try
{
if (dataGridView1.Rows.Count > 0)
{
dataSet1.Clear();
}
if (diff == 0)
{
dataSet1 = Repository.Instance.dbConnector.Get_Product();
}
else
{
DateTime arg1 = DateTime.Parse(tb_startTime.Text.Trim());
DateTime arg2 = DateTime.Parse(tb_endTime.Text.Trim());
dataSet1 = Repository.Instance.dbConnector.Get_Product(arg1.ToString(), arg2.ToString());
}
dataGridView1.DataSource = dataSet1.Tables[0];
dataGridView1.Columns[0].DefaultCellStyle.Format = "yyyy/MM/dd HH:mm:ss";
dataGridView1.Columns[0].Width = 180;
dataGridView1.Columns[0].ReadOnly = true;
dataGridView1.Columns[1].Width = 85;
dataGridView1.Columns[1].ReadOnly = true;
dataGridView1.Columns[2].Width = 80;
dataGridView1.Columns[2].ReadOnly = true;
dataGridView1.Columns[3].Width = 270;
dataGridView1.Columns[3].ReadOnly = true;
dataGridView1.Columns[4].Width = 180;
dataGridView1.Columns[4].ReadOnly = true;
// dataGridView1.AutoResizeColumns();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void Cell_Color_Painting()
{
string type;
for (int i = 0; i < dataGridView1.RowCount; i++)
{
type = dataGridView1.Rows[i].Cells[4].Value.ToString();
switch (type)
{
case "ACK":
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;
break;
case "UNACK":
dataGridView1.Rows[i].DefaultCellStyle.BackColor = flashColor;
break;
case "UNACK NORMAL":
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Green;
break;
}
}
}
private void Flashing_Row()
{
if (flashColor == Color.Gray)
{
flashColor = Color.Red;
}
else
{
flashColor = Color.Gray;
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
LoadCurrentFault();
}
private void HistoryViewer_Load(object sender, EventArgs e)
{
dataGridView1.Rows.Clear();
Set_TimeTextBox(diff);
LoadCurrentFault();
}
private void Set_TimeTextBox(int diff)
{
DateTime dt1 = new DateTime();
DateTime dt2 = new DateTime();
if (diff == 1440)
{
dt1 = DateTime.Now.AddDays(-1);
dt2 = DateTime.Now;
}
else if (diff == 43200)
{
dt1 = DateTime.Now.AddMonths(-1);
dt2 = DateTime.Now;
}
else
{
dt1 = DateTime.Now.AddMinutes(-1 * diff);
dt2 = DateTime.Now;
}
tb_startTime.Text = dt1.Year.ToString("D4") + "년" + dt1.Month.ToString("D2") + "월" + dt1.Day.ToString("D2") + "일 " + dt1.Hour.ToString("D2") + "시" + dt1.Minute.ToString("D2") + "분";
tb_endTime.Text = dt2.Year.ToString("D4") + "년" + dt2.Month.ToString("D2") + "월" + dt2.Day.ToString("D2") + "일 " + dt2.Hour.ToString("D2") + "시" + dt2.Minute.ToString("D2") + "분";
}
private void tb_startTime_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
{
MaskedTextBox tb = (MaskedTextBox)sender;
if (tb.MaskFull)
{
System.Windows.MessageBox.Show("모든 사항이 입력되었습니다. 추가입력이 불가합니다");
}
else if (e.Position == tb.Mask.Length)
{
System.Windows.MessageBox.Show("마스크 위치를 넘어섰습니다. 입력이 불가합니다");
}
else
{
System.Windows.MessageBox.Show("숫자만 입력해야 합니다. 입력이 불가합니다");
}
}
private void btn_Update_1Day_Click(object sender, EventArgs e)
{
diff = 1440;
Set_TimeTextBox(diff);
LoadCurrentFault();
}
private void btn_Update_1Month_Click(object sender, EventArgs e)
{
diff = 43200;
Set_TimeTextBox(diff);
LoadCurrentFault();
}
private void btn_Update_Manual_Click(object sender, EventArgs e)
{
diff = -1;
LoadCurrentFault();
}
private void btn_Update_Total(object sender, EventArgs e)
{
diff = 0;
LoadCurrentFault();
}
}
}
<file_sep>using System;
using System.Linq;
namespace KTE_PMS
{
public class sPMD
{
#region PCS variable declaration
public byte[] PCS_Request { get; set; }
public byte[] PCS_Monitoring { get; set; }
#endregion
#region PMD variable declaration
public byte[] Status { get; set; }
public double DateTime { get; set; }
public float Frequency { get; set; }
public byte[] DI_Status { get; set; }
public float Voltage_A { get; set; }
public float Voltage_B { get; set; }
public float Voltage_C { get; set; }
public float DC_Voltage { get; set; }
public float Current_A { get; set; }
public float Current_B { get; set; }
public float Current_C { get; set; }
public float DC_Current { get; set; }
public float Phase_VA { get; set; }
public float Phase_VB { get; set; }
public float Phase_VC { get; set; }
public float Phase_IA { get; set; }
public float Phase_IB { get; set; }
public float Phase_IC { get; set; }
public float ActivePower { get; set; }
public float ReactivePower { get; set; }
public float PowerFactor { get; set; }
public float DCPower { get; set; }
public float Day_power_passive { get; set; }
public float Day_power_trans { get; set; }
public float Month_power_passiver { get; set; }
public float Month_power_trans { get; set; }
public float Accumulate_power_passive { get; set; }
public float Accumulate_power_trans { get; set; }
#endregion
}
}
<file_sep>using DevExpress.CodeParser;
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KTE_PMS.MIMIC
{
public partial class VKeyboardViewer : Form
{
private string Status;
public VKeyboardViewer()
{
InitializeComponent();
Repository.Instance.user_level = 1;
lb_STATUS.Text = "비밀번호를 입력해 주십시오.";
}
public VKeyboardViewer(string s)
{
InitializeComponent();
Status = s;
Repository.Instance.user_level = 1;
if (Status == "새로운 비밀번호")
{
lb_STATUS.Text = "변경하고자 하는 비밀번호를 입력해 주십시오.";
}
else if (Status == "비밀번호 확인")
{
lb_STATUS.Text = "확인을 위해 변경하고자 하는 비밀번호를 다시 한번 더 입력해 주십시오.";
}
}
private void BTN0_Click(object sender, EventArgs e)
{
tb_Password.Text = tb_Password.Text + "0";
}
private void BTN1_Click(object sender, EventArgs e)
{
tb_Password.Text = tb_Password.Text + "1";
}
private void BTN2_Click(object sender, EventArgs e)
{
tb_Password.Text = tb_Password.Text + "2";
}
private void BTN3_Click(object sender, EventArgs e)
{
tb_Password.Text = tb_Password.Text + "3";
}
private void BTN4_Click(object sender, EventArgs e)
{
tb_Password.Text = tb_Password.Text + "4";
}
private void BTN5_Click(object sender, EventArgs e)
{
tb_Password.Text = tb_Password.Text + "5";
}
private void BTN6_Click(object sender, EventArgs e)
{
tb_Password.Text = tb_Password.Text + "6";
}
private void BTN7_Click(object sender, EventArgs e)
{
tb_Password.Text = tb_Password.Text + "7";
}
private void BTN8_Click(object sender, EventArgs e)
{
tb_Password.Text = tb_Password.Text + "8";
}
private void BTN9_Click(object sender, EventArgs e)
{
tb_Password.Text = tb_Password.Text + "9";
}
private void BTN_CLEAR_Click(object sender, EventArgs e)
{
tb_Password.Text = "";
}
private void BTN_ENTER_Click(object sender, EventArgs e)
{
if (Status == "새로운 비밀번호")
{
Repository.Instance.first_password = <PASSWORD>;
tb_Password.Text = "";
this.Dispose();
}
else if (Status == "비밀번호 확인")
{
if (Repository.Instance.first_password == <PASSWORD>)
{
Repository.Instance.password = <PASSWORD>.Instance.<PASSWORD>;
MessageBox.Show("비밀번호가 성공적으로 변경되었습니다.");
this.Dispose();
}
else
{
MessageBox.Show("비밀번호가 일치하지 않습니다. 다시 한번 시도해주시길 바랍니다.");
this.Dispose();
}
tb_Password.Text = "";
}
else
{
if (tb_Password.Text == Repository.Instance.password)
{
// Success
//MessageBox.Show("올바른 비밀번호를 입력하였습니다.");
tb_Password.Text = "";
Repository.Instance.user_level = 5;
this.Dispose();
}
else
{
// Wrong Password
MessageBox.Show("비밀번호가 잘못되었습니다. 다시 확인해주시길 바랍니다.");
tb_Password.Text = "";
Repository.Instance.user_level = 1;
}
}
}
private void tb_Password_TextChanged(object sender, EventArgs e)
{
// 자리수 검사.
// if 4자리 이상이면 경고 Message 띄움
if (tb_Password.Text.Length > 4)
{
tb_Password.Text.Remove(4, 1);
}
}
}
}
/*
private void BTN0_Click(object sender, EventArgs e)
{
tb_Password.Focus();
keybd_event(0, MapVirtualKey((int)Keys.D0, 0), 0x00, 0);
keybd_event(0, MapVirtualKey((int)Keys.D0, 0), 0x02, 0);
}
private void BTN1_Click(object sender, EventArgs e)
{
tb_Password.Focus();
keybd_event(0, MapVirtualKey((int)Keys.D1, 0), 0x00, 0);
keybd_event(0, MapVirtualKey((int)Keys.D1, 0), 0x02, 0);
}
private void BTN2_Click(object sender, EventArgs e)
{
tb_Password.Focus();
keybd_event(0, MapVirtualKey((int)Keys.D2, 0), 0x00, 0);
keybd_event(0, MapVirtualKey((int)Keys.D2, 0), 0x02, 0);
}
private void BTN3_Click(object sender, EventArgs e)
{
tb_Password.Focus();
keybd_event(0, MapVirtualKey((int)Keys.D3, 0), 0x00, 0);
keybd_event(0, MapVirtualKey((int)Keys.D3, 0), 0x02, 0);
}
private void BTN4_Click(object sender, EventArgs e)
{
tb_Password.Focus();
keybd_event(0, MapVirtualKey((int)Keys.D4, 0), 0x00, 0);
keybd_event(0, MapVirtualKey((int)Keys.D4, 0), 0x02, 0);
}
private void BTN5_Click(object sender, EventArgs e)
{
tb_Password.Focus();
keybd_event(0, MapVirtualKey((int)Keys.D5, 0), 0x00, 0);
keybd_event(0, MapVirtualKey((int)Keys.D5, 0), 0x02, 0);
}
private void BTN6_Click(object sender, EventArgs e)
{
tb_Password.Focus();
keybd_event(0, MapVirtualKey((int)Keys.D6, 0), 0x00, 0);
keybd_event(0, MapVirtualKey((int)Keys.D6, 0), 0x02, 0);
}
private void BTN7_Click(object sender, EventArgs e)
{
tb_Password.Focus();
keybd_event(0, MapVirtualKey((int)Keys.D7, 0), 0x00, 0);
keybd_event(0, MapVirtualKey((int)Keys.D7, 0), 0x02, 0);
}
private void BTN8_Click(object sender, EventArgs e)
{
tb_Password.Focus();
keybd_event(0, MapVirtualKey((int)Keys.D8, 0), 0x00, 0);
keybd_event(0, MapVirtualKey((int)Keys.D8, 0), 0x02, 0);
}
private void BTN9_Click(object sender, EventArgs e)
{
tb_Password.Focus();
keybd_event(0, MapVirtualKey((int)Keys.D9, 0), 0x00, 0);
keybd_event(0, MapVirtualKey((int)Keys.D9, 0), 0x02, 0);
}
private void BTNDOT_Click(object sender, EventArgs e)
{
tb_Password.Focus();
keybd_event(0, MapVirtualKey((int)Keys.Separator, 0), 0x00, 0);
keybd_event(0, MapVirtualKey((int)Keys.Separator, 0), 0x02, 0);
}
private void BTN_CLEAR_Click(object sender, EventArgs e)
{
tb_Password.Focus();
keybd_event(0, MapVirtualKey((int)Keys.Back, 0), 0x00, 0);
keybd_event(0, MapVirtualKey((int)Keys.Back, 0), 0x02, 0);
}
private void BTN_MINUS_Click(object sender, EventArgs e)
{
keybd_event(0, MapVirtualKey((int)Keys.OemMinus, 0), 0x00, 0);
keybd_event(0, MapVirtualKey((int)Keys.OemMinus, 0), 0x02, 0);
}
*/
<file_sep>namespace KTE_PMS
{
public class sSamsungBCS
{
#region BSC variable declaration
// BSC -> Controller (Monitoring)
// Address 40000 ~ 40049
public ushort Controler_Status { get; set; }
public ushort ReqtoControl_AllContactors { get; set; }
public ushort Reset { get; set; }
public ushort Manual_Mode_Request_Ack { get; set; }
public ushort Request_Sleep { get; set; }
public ushort Request_Connection { get; set; }
public ushort Protocol_Version { get; set; } //0
public double System_Voltage { get; set; } // 1 0.1
public short System_Current { get; set; } // 2 Signed /256
public double System_SOC { get; set; } // 3 Resolution 0.1
public double System_SOH { get; set; } // 4 Resolution 0.1
public ushort System_Mode { get; set; } // 5
public double System_Max_Voltage { get; set; } // 6
public double System_Min_Voltage { get; set; } // 7
public double System_Max_Temp { get; set; } //8
public double System_Min_Temp { get; set; } // 9
public int Mode_Charging { get; set; }
public int Mode_Discharging { get; set; }
public int Mode_Offline { get; set; }
public int Mode_Idle { get; set; }
public int Mode_Ready { get; set; }
public int Mode_InputSignal4 { get; set; }
public int Mode_InputSignal3 { get; set; }
public int Mode_InputSignal2 { get; set; }
public int Mode_InputSIgnal1 { get; set; }
public int Mode_OutputControl2 { get; set; }
public int Mode_OutputControl1 { get; set; }
public ushort Protection_Summary4 { get; set; } // 14
public ushort Protection_Summary3 { get; set; } // 15
public ushort Protection_Summary2 { get; set; } // 16
public ushort Protection_Summary1 { get; set; } // 17
public ushort Alarm_Summary4 { get; set; } // 18
public ushort Alarm_Summary3 { get; set; } // 19
public ushort Alarm_Summary2 { get; set; } // 20
public ushort Alarm_Summary1 { get; set; } // 21
public double Discharge_Current_Limit_of_Rack { get; set; } // 22
public double Charge_Current_Limit { get; set; } // 23
public short Watchdog_Response { get; set; } // 24
public ushort System_Heartbit { get; set; } // 25
public ushort Connecting_Status { get; set; } // 26
public double Service_Voltage { get; set; } // 27
public double Service_SOC { get; set; } // 28
public double Ambient_Temp { get; set; } // 30
public ushort System_Alarm_Status { get; set; } // 31
public double System_Power { get; set; } // calculated
#endregion
public Samsung_BMS_Rack Rack1;
public Samsung_BMS_Rack Rack2;
public sSamsungBCS()
{
Rack1 = new Samsung_BMS_Rack();
Rack2 = new Samsung_BMS_Rack();
}
}
}
<file_sep>using System;
using System.Linq;
namespace KTE_PMS.MIMIC
{
public class cTag
{
public string grno {set; get; }
public float resolution { set; get; }
public string Address { set; get; }
public string bit_address { set; get; }
public Boolean AlrAckValue { set; get; }
public string AlrDisable { set; get; }
public Boolean AlrOffValue { set; get; }
public Boolean AlrOnValue { set; get; }
public string AlrStatus { set; get; }
public string CommType { set; get; }
public string CommUrl { set; get; }
public string Description { set; get; }
public string DevM { set; get; }
public string DevMLimit { set; get; }
public string DevP { set; get; }
public string DevPLimit { set; get; }
public string DevSetpoint { set; get; }
public string DisplayMax { set; get; }
public string DisplayMin { set; get; }
public string DisplayUnit { set; get; }
public string DisplayValue { set; get; }
public Boolean Hi { set; get; }
public Boolean HiHi { set; get; }
public float HiHiLimit { set; get; }
public float HiLimit { set; get; }
public string Index { set; get; }
public Boolean Lo { set; get; }
public float LoLimit { set; get; }
public Boolean LoLo { set; get; }
public float LoLoLimit { set; get; }
public float Max { set; get; }
public string MemberName { set; get; }
public float Min { set; get; }
public string Name { set; get; }
public string OriginalTag { set; get; }
public string Quality { set; get; }
public string Rate { set; get; }
public string RateLimit { set; get; }
public string Size { set; get; }
public string Source { set; get; }
public DateTime TimeStamp { set; get; }
public Boolean UnAck { set; get; }
public string Unit { set; get; }
public string UnitAdd { set; get; }
public string UnitDiv { set; get; }
public string Used { set; get; }
public float value;
public cTag()
{
//Address =
//Description = "";
}
public bool Changed;
public void Tag_Update(Repository rep)
{
// Repository에 있는 값을
// Address를 통해서 값을 읽어오기
GetData(rep);
// TimeStamp 설정
TimeStamp = DateTime.Now;
// Alarm 설정
SetAlarm();
}
private void GetData(Repository rep)
{
//value = rep.get_BSC1(Convert.ToInt32(Address));
}
private void SetAlarm()
{
/*/////////////////////////////
// Alarm에 대한 처리 //
////////////////////////////*/
// LoLo에 대한 Alarm 처리
if (LoLoLimit > value) LoLo = true;
else LoLo = false;
// Low에 대한 Alarm 처리
if (LoLimit > value) Lo = true;
else Lo = false;
// HiHi에 대한 Alarm 처리
if (HiHiLimit < value)
{
HiHi = true;
}
else
{
HiHi = false;
}
// Hi에 대한 Alarm 처리
if (HiLimit < value)
{
Hi = true;
}
else
{
Hi = false;
}
}
}
}
<file_sep>using KTE_PMS.Observer;
using System;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
namespace KTE_PMS.MIMIC
{
public partial class MeasureViewerV2 : Viewer, IUpdate
{
public MeasureViewerV2()
{
InitializeComponent();
}
delegate void CrossThreadSafetySetText(Control ctl, String text);
private void CSafeSetText(Control ctl, String text)
{
/*
* InvokeRequired 속성 (Control.InvokeRequired, MSDN)
* 짧게 말해서, 이 컨트롤이 만들어진 스레드와 현재의 스레드가 달라서
* 컨트롤에서 스레드를 만들어야 하는지를 나타내는 속성입니다.
*
* InvokeRequired 속성의 값이 참이면, 컨트롤에서 스레드를 만들어 텍스트를 변경하고,
* 그렇지 않은 경우에는 그냥 변경해도 아무 오류가 없기 때문에 텍스트를 변경합니다.
*/
if (ctl.InvokeRequired)
ctl.Invoke(new CrossThreadSafetySetText(CSafeSetText), ctl, text);
else
ctl.Text = text;
}
public void ObserverUpdate()
{
}
private void button4_Click(object sender, EventArgs e)
{
}
private void MeasureViewerV2_Load(object sender, EventArgs e)
{
gridControl1.DataSource = Repository.Instance.Tag_Data_Table;
}
}
}
<file_sep>using DevExpress.Utils;
using DevExpress.XtraCharts;
using System;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows;
using System.Windows.Forms;
namespace KTE_PMS
{
public partial class TrendViewer : MIMIC.Viewer
{
public TrendViewer()
{
InitializeComponent();
XYDiagram diagram = (XYDiagram)chartControl1.Diagram;
XYDiagram diagram1 = (XYDiagram)chartControl2.Diagram;
XYDiagram diagram2 = (XYDiagram)chartControl3.Diagram;
diagram.AxisX.Label.TextPattern = "{A: yy/MM/dd hh:mm}";
diagram1.AxisX.Label.TextPattern = "{A: yy/MM/dd hh:mm}";
diagram2.AxisX.Label.TextPattern = "{A: yy/MM/dd hh:mm}";
diagram.AxisX.DateTimeScaleOptions.ScaleMode = ScaleMode.Continuous;
diagram1.AxisX.DateTimeScaleOptions.ScaleMode = ScaleMode.Continuous;
diagram2.AxisX.DateTimeScaleOptions.ScaleMode = ScaleMode.Continuous;
sqlDataSource1.Fill();
timer1.Interval = 1000; // 1초
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Start();
// This line of code is generated by Data Source Configuration Wizard
// Fill a SqlDataSource
}
private void timer1_Tick(object sender, EventArgs e)
{
sqlDataSource1.Fill();
chartControl1.RefreshData();
if (Properties.Settings.Default.DEBUG)
{
// AugoGenerating
Random rand = new Random();
Repository.Instance.dbConnector.Insert_Value_to_Database(rand.Next(800,1000) / 10, rand.Next(100,200)/10 ,rand.Next(300,400)/10);
}
}
private void button1_Click(object sender, EventArgs e)
{
Repository.Instance.dbConnector.Insert_Value_to_Database();
}
private void 적용(object sender, EventArgs e)
{
SetDiagramTimeRange((XYDiagram)chartControl1.Diagram, 0);
SetDiagramTimeRange((XYDiagram)chartControl2.Diagram, 0);
SetDiagramTimeRange((XYDiagram)chartControl3.Diagram, 0);
}
private void maskedTextBox2_MaskInputRejected(object sender, System.Windows.Forms.MaskInputRejectedEventArgs e)
{
if (maskedTextBox2.MaskFull)
{
System.Windows.MessageBox.Show("모든 사항이 입력되었습니다. 추가입력이 불가합니다");
}
else if (e.Position == maskedTextBox2.Mask.Length)
{
System.Windows.MessageBox.Show("마스크 위치를 넘어섰습니다. 입력이 불가합니다");
}
else
{
System.Windows.MessageBox.Show("숫자만 입력해야 합니다. 입력이 불가합니다");
}
}
private void maskedTextBox1_MaskInputRejected(object sender, System.Windows.Forms.MaskInputRejectedEventArgs e)
{
if (maskedTextBox1.MaskFull)
{
System.Windows.MessageBox.Show("모든 사항이 입력되었습니다. 추가입력이 불가합니다");
}
else if (e.Position == maskedTextBox1.Mask.Length)
{
System.Windows.MessageBox.Show("마스크 위치를 넘어섰습니다. 입력이 불가합니다");
}
else
{
System.Windows.MessageBox.Show("숫자만 입력해야 합니다. 입력이 불가합니다");
}
}
private void SetDiagramTimeRange(XYDiagram diagram, int diff)
{
try
{
if (diff != 0)
{
DateTime dt1 = DateTime.Now.AddMinutes(diff);
DateTime dt2 = DateTime.Now.AddMinutes(-1 * diff);
maskedTextBox1.Text = dt1.Year.ToString("D4") + "년" + dt1.Month.ToString("D2") + "월" + dt1.Day.ToString("D2") + "일 " + dt1.Hour.ToString("D2") + "시" + dt1.Minute.ToString("D2") + "분";
maskedTextBox2.Text = dt2.Year.ToString("D4") + "년" + dt2.Month.ToString("D2") + "월" + dt2.Day.ToString("D2") + "일 " + dt2.Hour.ToString("D2") + "시" + dt2.Minute.ToString("D2") + "분";
}
DateTime t_Datetime_Maxvalue = DateTime.Parse(maskedTextBox1.Text.Trim());
diagram.AxisX.VisualRange.MaxValue = t_Datetime_Maxvalue;
diagram.AxisX.WholeRange.MaxValue = t_Datetime_Maxvalue;
DateTime t_Datetime_Minvalue = DateTime.Parse(maskedTextBox2.Text.Trim());
diagram.AxisX.VisualRange.MinValue = t_Datetime_Minvalue;
diagram.AxisX.WholeRange.MinValue = t_Datetime_Minvalue;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void button5_Click(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox a = (CheckBox)sender;
XYDiagram diagram = (XYDiagram)chartControl1.Diagram;
XYDiagram diagram1 = (XYDiagram)chartControl2.Diagram;
XYDiagram diagram2 = (XYDiagram)chartControl3.Diagram;
if (a.Checked)
{
diagram.AxisX.DateTimeScaleOptions.ScaleMode = ScaleMode.Automatic;
diagram1.AxisX.DateTimeScaleOptions.ScaleMode = ScaleMode.Automatic;
diagram2.AxisX.DateTimeScaleOptions.ScaleMode = ScaleMode.Automatic;
}
else
{
diagram.AxisX.DateTimeScaleOptions.ScaleMode = ScaleMode.Manual;
diagram1.AxisX.DateTimeScaleOptions.ScaleMode = ScaleMode.Manual;
diagram2.AxisX.DateTimeScaleOptions.ScaleMode = ScaleMode.Manual;
}
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
CheckBox a = (CheckBox)sender;
XYDiagram diagram = (XYDiagram)chartControl1.Diagram;
XYDiagram diagram1 = (XYDiagram)chartControl2.Diagram;
XYDiagram diagram2 = (XYDiagram)chartControl3.Diagram;
if (a.Checked)
{
diagram.AxisX.DateTimeScaleOptions.ScaleMode = ScaleMode.Continuous;
diagram1.AxisX.DateTimeScaleOptions.ScaleMode = ScaleMode.Continuous;
diagram2.AxisX.DateTimeScaleOptions.ScaleMode = ScaleMode.Continuous;
}
else
{
diagram.AxisX.DateTimeScaleOptions.ScaleMode = ScaleMode.Manual;
diagram1.AxisX.DateTimeScaleOptions.ScaleMode = ScaleMode.Manual;
diagram2.AxisX.DateTimeScaleOptions.ScaleMode = ScaleMode.Manual;
}
}
private void checkBox4_CheckedChanged(object sender, EventArgs e)
{
CheckBox a = (CheckBox)sender;
XYDiagram diagram = (XYDiagram)chartControl1.Diagram;
XYDiagram diagram1 = (XYDiagram)chartControl2.Diagram;
XYDiagram diagram2 = (XYDiagram)chartControl3.Diagram;
if (a.Checked)
{
diagram.AxisX.WholeRange.AutoSideMargins = true;
diagram.AxisX.VisualRange.AutoSideMargins = true;
diagram1.AxisX.WholeRange.AutoSideMargins = true;
diagram1.AxisX.VisualRange.AutoSideMargins = true;
diagram2.AxisX.WholeRange.AutoSideMargins = true;
diagram2.AxisX.VisualRange.AutoSideMargins = true;
}
else
{
diagram.AxisX.WholeRange.AutoSideMargins = false;
diagram.AxisX.VisualRange.AutoSideMargins = false;
diagram1.AxisX.WholeRange.AutoSideMargins = false;
diagram1.AxisX.VisualRange.AutoSideMargins = false;
diagram2.AxisX.WholeRange.AutoSideMargins = false;
diagram2.AxisX.VisualRange.AutoSideMargins = false;
}
}
private void checkBox5_CheckedChanged(object sender, EventArgs e)
{
CheckBox a = (CheckBox)sender;
XYDiagram diagram = (XYDiagram)chartControl1.Diagram;
XYDiagram diagram1 = (XYDiagram)chartControl2.Diagram;
XYDiagram diagram2 = (XYDiagram)chartControl3.Diagram;
if (a.Checked)
{
diagram.AxisX.WholeRange.Auto = true;
diagram.AxisX.VisualRange.Auto = true;
diagram1.AxisX.WholeRange.Auto = true;
diagram1.AxisX.VisualRange.Auto = true;
diagram2.AxisX.WholeRange.Auto = true;
diagram2.AxisX.VisualRange.Auto = true;
}
else
{
diagram.AxisX.WholeRange.Auto = false;
diagram.AxisX.VisualRange.Auto = false;
diagram1.AxisX.WholeRange.Auto = false;
diagram1.AxisX.VisualRange.Auto = false;
diagram2.AxisX.WholeRange.Auto = false;
diagram2.AxisX.VisualRange.Auto = false;
}
}
private void button3_Click_1(object sender, EventArgs e)
{
SetDiagramTimeRange((XYDiagram)chartControl1.Diagram, 10);
SetDiagramTimeRange((XYDiagram)chartControl2.Diagram, 10);
SetDiagramTimeRange((XYDiagram)chartControl3.Diagram, 10);
}
private void button4_Click_1(object sender, EventArgs e)
{
SetDiagramTimeRange((XYDiagram)chartControl1.Diagram, 60);
SetDiagramTimeRange((XYDiagram)chartControl2.Diagram, 60);
SetDiagramTimeRange((XYDiagram)chartControl3.Diagram, 60);
}
private void button5_Click_1(object sender, EventArgs e)
{
SetDiagramTimeRange((XYDiagram)chartControl1.Diagram, 1440);
SetDiagramTimeRange((XYDiagram)chartControl2.Diagram, 1440);
SetDiagramTimeRange((XYDiagram)chartControl3.Diagram, 1440);
}
private void button1_Click_1(object sender, EventArgs e)
{
if (DialogResult.Yes == System.Windows.Forms.MessageBox.Show("Are you sure to export trending data?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation))
{
Repository.Instance.dbConnector.Export_Data();
}
}
private void TrendViewer_Load(object sender, EventArgs e)
{
}
}
}
<file_sep>using System;
using System.IO;
using System.IO.Ports;
using System.Timers;
using System.Windows.Forms;
namespace KTE_PMS
{
public partial class Modbus_Setup : Form
{
Modbus_RTU mb = new Modbus_RTU();
SerialPort sp = new SerialPort();
System.Timers.Timer timer = new System.Timers.Timer();
string dataType;
bool isPolling = false;
int pollCount;
#region GUI Delegate Declarations
public delegate void GUIDelegate(string paramString);
public delegate void GUIClear();
public delegate void GUIStatus(string paramString);
#endregion
private string pcs_port;
private string pcs_baudrate;
private string pcs_parity;
private string pcs_stopbit;
private int pcs_readtimeout;
private int pcs_writetimeout;
private string directory = System.Windows.Forms.Application.StartupPath;
private string filename = "\\Configs.dat";
public Modbus_Setup()
{
InitializeComponent();
LoadListboxes();
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
// Parameter 값을 미리 설정하고 생성하자 마자 바로 연결 시도 //
StartPoll();
//-----------------------------
// Modbus RTU - PCS 통신 시도 //
//-----------------------------
// 1. File에서 설정값 읽어오기
// Not Yet
Read_PCS_Configuration();
// 2. 연결하기
//Connect_to_PCS();
}
public Modbus_Setup(string port, string baudrate, string parity, string stopbit, int readtimeout, int writetimeout)
{
InitializeComponent();
LoadListboxes();
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
lstPorts.SelectedIndex = lstPorts.FindString(port);
lstBaudrate.SelectedIndex = lstPorts.FindString(baudrate);
txtSampleRate.Text = readtimeout.ToString();
// Parameter 값을 미리 설정하고 생성하자 마자 바로 연결 시도 //
StartPoll();
//-----------------------------
// Modbus RTU - PCS 통신 시도 //
//-----------------------------
// 1. File에서 설정값 읽어오기
// Not Yet
//Read_PCS_Configuration();
// 2. 연결하기
//Connect_to_PCS();
}
#region Delegate Functions
public void DoGUIClear()
{
if (this.InvokeRequired)
{
GUIClear delegateMethod = new GUIClear(this.DoGUIClear);
this.Invoke(delegateMethod);
}
else
this.lstRegisterValues.Items.Clear();
}
public void DoGUIStatus(string paramString)
{
if (this.InvokeRequired)
{
GUIStatus delegateMethod = new GUIStatus(this.DoGUIStatus);
this.Invoke(delegateMethod, new object[] { paramString });
}
else
this.lblStatus.Text = paramString;
}
public void DoGUIUpdate(string paramString)
{
if (this.InvokeRequired)
{
GUIDelegate delegateMethod = new GUIDelegate(this.DoGUIUpdate);
this.Invoke(delegateMethod, new object[] { paramString });
}
else
this.lstRegisterValues.Items.Add(paramString);
}
#endregion
#region Timer Elapsed Event Handler
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
PollFunction();
}
#endregion
#region Load Listboxes
private void LoadListboxes()
{
//Three to load - ports, baudrates, datetype. Also set default textbox values:
//1) Available Ports:
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
lstPorts.Items.Add(port);
}
//lstPorts.SelectedIndex = 0;
//2) Baudrates:
string[] baudrates = { "230400", "115200", "57600", "38400", "19200", "9600" };
foreach (string baudrate in baudrates)
{
lstBaudrate.Items.Add(baudrate);
}
lstBaudrate.SelectedIndex = 1;
//3) Datatype:
string[] dataTypes = { "Decimal", "Hexadecimal", "Float", "Reverse" };
foreach (string dataType in dataTypes)
{
lstDataType.Items.Add(dataType);
}
lstDataType.SelectedIndex = 0;
//Textbox defaults:
txtRegisterQty.Text = "20";
txtSampleRate.Text = "1000";
txtSlaveID.Text = "1";
txtStartAddr.Text = "0";
}
#endregion
#region Start and Stop Procedures
private void StartPoll()
{
pollCount = 0;
try
{
//Open COM port using provided settings:
if (mb.Open(lstPorts.SelectedItem.ToString(), Convert.ToInt32(lstBaudrate.SelectedItem.ToString()),
8, Parity.None, StopBits.One))
{
//Disable double starts:
btnStart.Enabled = false;
dataType = lstDataType.SelectedItem.ToString();
//Set polling flag:
isPolling = true;
//Start timer using provided values:
timer.AutoReset = true;
if (txtSampleRate.Text != string.Empty)
timer.Interval = Convert.ToDouble(txtSampleRate.Text);
else
timer.Interval = 1000;
timer.Start();
}
lblStatus.Text = mb.modbusStatus;
}
catch (Exception e)
{
Console.Write(e.Message);
}
}
private void StopPoll()
{
//Stop timer and close COM port:
isPolling = false;
timer.Stop();
mb.Close();
btnStart.Enabled = true;
lblStatus.Text = mb.modbusStatus;
}
private void btnStart_Click(object sender, EventArgs e)
{
StartPoll();
}
private void btnStop_Click(object sender, EventArgs e)
{
StopPoll();
}
#endregion
#region Poll Function
private void PollFunction()
{
//Update GUI:
DoGUIClear();
pollCount++;
DoGUIStatus("Poll count: " + pollCount.ToString());
//Create array to accept read values:
short[] values = new short[Convert.ToInt32(txtRegisterQty.Text)];
ushort pollStart;
ushort pollLength;
if (txtStartAddr.Text != string.Empty)
pollStart = Convert.ToUInt16(txtStartAddr.Text);
else
pollStart = 0;
if (txtRegisterQty.Text != string.Empty)
pollLength = Convert.ToUInt16(txtRegisterQty.Text);
else
pollLength = 20;
//Read registers and display data in desired format:
try
{
while (!mb.SendFc3(Convert.ToByte(txtSlaveID.Text), pollStart, pollLength, ref values)) ;
}
catch (Exception err)
{
DoGUIStatus("Error in modbus read: " + err.Message);
}
string itemString;
switch (dataType)
{
case "Decimal":
for (int i = 0; i < pollLength; i++)
{
itemString = "[" + Convert.ToString(pollStart + i + 40001) + "] , MB[" +
Convert.ToString(pollStart + i) + "] = " + values[i].ToString();
DoGUIUpdate(itemString);
}
break;
case "Hexadecimal":
for (int i = 0; i < pollLength; i++)
{
itemString = "[" + Convert.ToString(pollStart + i + 40001) + "] , MB[" +
Convert.ToString(pollStart + i) + "] = " + values[i].ToString("X");
DoGUIUpdate(itemString);
}
break;
case "Float":
for (int i = 0; i < (pollLength / 2); i++)
{
int intValue = (int)values[2 * i];
intValue <<= 16;
intValue += (int)values[2 * i + 1];
itemString = "[" + Convert.ToString(pollStart + 2 * i + 40001) + "] , MB[" +
Convert.ToString(pollStart + 2 * i) + "] = " +
(BitConverter.ToSingle(BitConverter.GetBytes(intValue), 0)).ToString();
DoGUIUpdate(itemString);
}
break;
case "Reverse":
for (int i = 0; i < (pollLength / 2); i++)
{
int intValue = (int)values[2 * i + 1];
intValue <<= 16;
intValue += (int)values[2 * i];
itemString = "[" + Convert.ToString(pollStart + 2 * i + 40001) + "] , MB[" +
Convert.ToString(pollStart + 2 * i) + "] = " +
(BitConverter.ToSingle(BitConverter.GetBytes(intValue), 0)).ToString();
DoGUIUpdate(itemString);
}
break;
}
// 값 넣고
// Notification
}
#endregion
#region Write Function
private void WriteFunction()
{
StopPoll();
if (txtWriteRegister.Text != string.Empty && txtWriteValue.Text != string.Empty && txtSlaveID.Text != string.Empty)
{
byte address = Convert.ToByte(txtSlaveID.Text);
ushort start = Convert.ToUInt16(txtWriteRegister.Text);
short[] value = new short[1];
value[0] = Convert.ToInt16(txtWriteValue.Text);
try
{
while (!mb.SendFc16(address, start, (ushort)1, value)) ;
}
catch (Exception err)
{
DoGUIStatus("Error in write function: " + err.Message);
}
DoGUIStatus(mb.modbusStatus);
}
else
DoGUIStatus("Enter all fields before attempting a write");
//StartPoll();
}
private void btnWrite_Click(object sender, EventArgs e)
{
WriteFunction();
}
#endregion
#region Data Type Event Handler
private void lstDataType_SelectedIndexChanged(object sender, EventArgs e)
{
//restart the data poll if datatype is changed during the process:
if (isPolling)
{
StopPoll();
dataType = lstDataType.SelectedItem.ToString();
StartPoll();
}
}
#endregion
private void Read_PCS_Configuration()
{
// ----------------------------------------------------------------------------------------
// 파일을 읽어서 List에 넣기
// cTag에 저장하기
// 항상 동작하면서 cTag에 있는 값을 해당되는 통신방식에 맞게 값을 읽어오고 주기적으로 쓴다
// ----------------------------------------------------------------------------------------
try
{
FileStream fs = File.OpenRead(directory + filename);
StreamReader r = new StreamReader(fs, System.Text.Encoding.Default);
// 문자 스트림 변환
r.BaseStream.Seek(0, SeekOrigin.Begin);
// 일단 찾고
// 하기
// Skip First Line //
string temp = r.ReadLine();
// 만약 끝이 아니라면
while (r.Peek() > -1)
{
// 1 Line 을 읽는다.
temp = r.ReadLine();
// 2. BSC 관련 값을 찾는다. BSC가 아니라면 다음 라인을 읽는다
if (temp.Contains("PCS Setting"))
{
try
{
string[] split;
//Read ////////////////
temp = r.ReadLine();
//split = System.Text.RegularExpressions.Regex.Split(temp, "=");
///Read ID=1_enable = 0
temp = r.ReadLine();
//split = System.Text.RegularExpressions.Regex.Split(temp, "=");
///Read ID = 1
temp = r.ReadLine();
//split = System.Text.RegularExpressions.Regex.Split(temp, "=");
///port =
///baudrate =
/////////parity =
///stopbit
///readtimeout =
///writetimeout =
// read Port
temp = r.ReadLine();
split = System.Text.RegularExpressions.Regex.Split(temp, "=");
pcs_port = split[1].Trim();
// read baudrate
temp = r.ReadLine();
split = System.Text.RegularExpressions.Regex.Split(temp, "=");
pcs_baudrate = split[1].Trim();
// read parity bit
temp = r.ReadLine();
split = System.Text.RegularExpressions.Regex.Split(temp, "=");
pcs_parity = split[1].Trim();
// Read stopbit
temp = r.ReadLine();
split = System.Text.RegularExpressions.Regex.Split(temp, "=");
pcs_stopbit = split[1].Trim();
// Read readtimeout
temp = r.ReadLine();
split = System.Text.RegularExpressions.Regex.Split(temp, "=");
pcs_readtimeout = Convert.ToInt16(split[1].ToString().Trim());
// Read writetimeout
temp = r.ReadLine();
split = System.Text.RegularExpressions.Regex.Split(temp, "=");
pcs_writetimeout = Convert.ToInt16(split[1].ToString().Trim());
break;
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Abort");
//throw e;
}
}
}
r.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Abort");
//throw e;
}
}
}
}
<file_sep>using System;
using System.Linq;
namespace KTE_PMS
{
public class sBCS
{
#region BSC variable declaration
// BSC -> Controller (Monitoring)
// Address 40000 ~ 40049
public byte Controler_Status { get; set; }
public byte ReqtoControl_AllContactors { get; set; }
public byte Reset { get; set; }
public byte Manual_Mode_Request_Ack { get; set; }
public byte Request_Sleep { get; set; }
public byte Request_Connection { get; set; }
#endregion
}
}
<file_sep>using System;
using System.Linq;
namespace KTE_PMS.Observer
{
public interface IUpdate
{
void ObserverUpdate();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KTE_PMS
{
public class sAlarm
{
public string Address { set; get; }
public DateTime time;
}
}
<file_sep>namespace KTE_PMS
{
partial class mssql_dataset
{
}
}
<file_sep>using System.Windows.Forms;
using KTE_PMS.MIMIC;
namespace KTE_PMS
{
public partial class aha : UserControl
{
public aha()
{
InitializeComponent();
}
}
}
<file_sep>using KTE_PMS.Observer;
using KTE_PMS.Singleton;
using System;
using System.Data;
using System.Threading;
using System.Windows.Forms;
namespace KTE_PMS
{
public sealed class Repository : SingleTonBase<Repository>
{
#region Variable Initialize
//----------------------------------
// Modbus TCP Controller - Master
//----------------------------------
public MIMIC.BMSViewer bmsviewer;
public MIMIC.PMDViewer pmdviewer;
public MIMIC.MainViewer p_main = null;
public MIMIC.AlarmViewer p_alarm = null;
public MIMIC.HistoryViewer p_history = null;
public MIMIC.ControlViewer p_control = null;
public MIMIC.MeasureViewer p_measure { set; get; }
public MIMIC.MeasureViewer2 p_measure_BMS_Rack { set; get; }
public MIMIC.MeasureViewer3 p_measure_PCS_Fault { set; get; }
public MIMIC.MeasureViewer4 p_measure_PCS { set; get; }
public MIMIC.MeasureViewerV2 p_measure_PCSV2 { set; get; }
public MIMIC.MimicViewer p_mimic = null;
public MIMIC.Setting_PageViewer p_setting = null;
public TrendViewer p_trend = null;
//----------------------------------
// Modbus RTU Controller - Master
//----------------------------------
public Modbus_Setup modbus_rtuviewer;
public sPCS GnEPS_PCS;
public sPMD pmd;
public sBCS bsc;
public sSamsungBCS samsung_bcs;
public TagManager TagManager { get; set; }
public DBConnector dbConnector;
IUpdate observers;
public ushort remote_power;
public ushort current_pcs_mode;
//세파포어 선언
private static Semaphore bms_resourcePool; //한번에 허용할 수 있는 최대 쓰레드 수
private static int bms_maximumThreads = 1;
private static Semaphore pcs_resourcePool; //한번에 허용할 수 있는 최대 쓰레드 수
private static int pcs_maximumThreads = 1;
public int user_level;
public string password;
public string first_password;
public int[] scheduler;
public DataTable Tag_Data_Table = new DataTable();
#endregion
// ---------------------------------------------------------
// 생성자
// ---------------------------------------------------------
private Repository() //단일체로 구현하기 위해 private으로 접근 지정
{
// 20180628
// 해당 SW에서 사용하는 항목은 GnEPS PCS, pCS 그리고 삼성 BCS가 있다.
// 각각의 장비에서 받아온 데이터값들을 저장 할 Structure 선언하는 항목들.
GnEPS_PCS = new sPCS(); // GnEPS_PCS
pmd = new sPMD(); // GnEPS_PCS
samsung_bcs = new sSamsungBCS(); // Samsung BCS
// 20180628
// BMSViewer 할당
// BMS Viewer는 BMS 통신과 관련된 모든 행위를 하는 Class이다.
// 선언하는 순간, BMS와 통신을 하고 Structure samsung_bcs에 데이터를 집어 넣는다.
bmsviewer = new MIMIC.BMSViewer();
// 20180628
// PMDViewer 할당
// PMD Viewer는 PCS 통신과 관련된 모든 행위를 하는 Class이다.
// 선언하는 순간, PCS와 통신을 하고 Structure GnEPS_PCS에 데이터를 집어 넣는다.
pmdviewer = new MIMIC.PMDViewer();
// 20180628
// Mimic Panel들을 Initialize 하는 항목
Initialize_Mimic();
// 20180628
// 현재 시작 시 Password의 값은 0000이다. 변경된 DB값을 유지하기 위해서는
// File이나 DB에 password를 저장하고, 이를 읽어오도록 한다.
password = "<PASSWORD>";
// 20180628 Observer 할당
// BMS값을 받아올 경우 갱신이 되어야 할 항목들,과
// PMS 값을 받아올 경우 갱신이 되어야 할 항목들을 OBserver에 넣는다.
Allocate_Observer_to_Mimic();
// 20180628 Semaphore 할당
// 현재 Semaphore를 사용할지, 사용하지 않을지에 대해서 고민중임
// TODO : Semaphore 처리
Initialize_Semaphore();
// 20180628 Parameter Setting 초기화
// Parameter Setting에서 사용하는 값들을 초기화 하기 위한 항목이다
// 현재 강제적으로 데이터를 넣고있으나, 설정한 값들의 보존을 위해서는 File이나 DB로 저장하도록 변경해야 한다.
// TODO : Parameter Settings
scheduler = new int[24];
//-----------------------------
// 20180628
// Class TagManager 생성
// TagManager는 Alarm 관련 항목들을 맡아서 처리하는 Class이다.
// 현재는 알람을 단순하게 처리하지만, 나중에 ALARM 에 전시할 항목이 늘어날 경우
//-----------------------------
try
{
TagManager = new TagManager(this);
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Abort");
throw e;
}
}
private void Initialize_Mimic()
{
p_main = new MIMIC.MainViewer();
p_alarm = new MIMIC.AlarmViewer();
p_history = new MIMIC.HistoryViewer();
p_control = new MIMIC.ControlViewer();
p_measure = new MIMIC.MeasureViewer();
p_measure_BMS_Rack = new MIMIC.MeasureViewer2();
p_measure_PCS_Fault = new MIMIC.MeasureViewer3();
p_measure_PCS = new MIMIC.MeasureViewer4();
p_measure_PCSV2 = new MIMIC.MeasureViewerV2();
p_mimic = new MIMIC.MimicViewer();
p_trend = new TrendViewer();
p_setting = new MIMIC.Setting_PageViewer();
}
private void Initialize_Semaphore()
{
bms_resourcePool = new Semaphore(0, bms_maximumThreads);
bms_resourcePool.Release();
pcs_resourcePool = new Semaphore(0, pcs_maximumThreads);
pcs_resourcePool.Release();
dbConnector = new DBConnector();
}
private void Allocate_Observer_to_Mimic()
{
observers = p_measure;
bmsviewer.AddObserver(observers);
observers = p_measure_BMS_Rack;
bmsviewer.AddObserver(observers);
observers = p_mimic;
bmsviewer.AddObserver(observers);
observers = p_mimic;
pmdviewer.AddObserver(observers);
observers = p_main;
bmsviewer.AddObserver(observers);
observers = p_main;
pmdviewer.AddObserver(observers);
observers = p_measure_PCS_Fault;
pmdviewer.AddObserver(observers);
observers = p_measure_PCS;
pmdviewer.AddObserver(observers);
}
// ---------------------------------------------------------
// Controller Tag
// ---------------------------------------------------------
public void Set_BSC_Control(byte[] data)
{
bsc.Controler_Status = data[0];
bsc.ReqtoControl_AllContactors = data[1];
bsc.Reset = data[2];
bsc.Manual_Mode_Request_Ack = data[3];
bsc.Request_Sleep = data[4];
bsc.Request_Connection = data[5];
}
public void Get_UMD(byte[] data)
{
pmd.Voltage_A = BitConverter.ToSingle(data, 16);
pmd.Voltage_B = BitConverter.ToSingle(data, 20);
pmd.Voltage_C = BitConverter.ToSingle(data, 24);
pmd.DC_Voltage = BitConverter.ToSingle(data, 28);
pmd.Current_A = BitConverter.ToSingle(data, 32);
pmd.Current_B = BitConverter.ToSingle(data, 36);
pmd.Current_C = BitConverter.ToSingle(data, 40);
pmd.DC_Current = BitConverter.ToSingle(data, 44);
pmd.Phase_VA = BitConverter.ToSingle(data, 48);
pmd.Phase_VB = BitConverter.ToSingle(data, 52);
pmd.Phase_VC = BitConverter.ToSingle(data, 56);
pmd.Phase_IA = BitConverter.ToSingle(data, 60);
pmd.Phase_IB = BitConverter.ToSingle(data, 64);
pmd.Phase_IC = BitConverter.ToSingle(data, 68);
pmd.ActivePower = BitConverter.ToSingle(data, 72);
pmd.ReactivePower = BitConverter.ToSingle(data, 76);
pmd.PowerFactor = BitConverter.ToSingle(data, 80);
pmd.DCPower = BitConverter.ToSingle(data, 84);
pmd.Day_power_passive = BitConverter.ToSingle(data, 88);
pmd.Day_power_trans = BitConverter.ToSingle(data, 92);
pmd.Month_power_passiver = BitConverter.ToSingle(data, 96);
pmd.Month_power_trans = BitConverter.ToSingle(data, 100);
pmd.Accumulate_power_passive = BitConverter.ToSingle(data, 104);
pmd.Accumulate_power_trans = BitConverter.ToSingle(data, 108);
/*
*/
// F050
//순시 사고 개수
//페이저 사고 개수
//순시 사고 인덱스 페이저 사고 인덱스
//보드 개수(F050-1)
//상태정보1(F050 - 2)
//상태정보2(F050 - 3)
//예약
//PMD_Status
// F051
//년/월/일 시/분/초 를 초 단위로 표시함.
//0: 2014 / 01 / 01 00:00:00 의미, 86399: 2014 / 01 / 01 23:59:59
DateTime baseTime = new DateTime(2018, 4, 1, 0, 0, 0);
TimeSpan timeDiff = DateTime.Now.Subtract(baseTime);
pmd.DateTime = timeDiff.TotalSeconds;
pmd.Frequency = BitConverter.ToInt16(data, 8) / 1000;
// F052
//PMD_DI_Status
}
#region GnEPS PCS의 데이터 획득
public void Get_PCS(byte[] data)
{
/*
GnEPS_PCS.Stand_Grid_Mode = (BitConverter.ToInt16(data, 0) & 0x80) >> 7;
GnEPS_PCS.Diesel_Converter_Run_Stop = (BitConverter.ToInt16(data, 0) & 0x10) >> 5;
GnEPS_PCS.Wind_Converter_Run_Stop = (BitConverter.ToInt16(data, 0) & 0x0F) >> 4;
GnEPS_PCS.Solar_Converter_Run_Stop = (BitConverter.ToInt16(data, 0) & 0x08) >> 3;
GnEPS_PCS.ESS_Converter_Run_Stop = (BitConverter.ToInt16(data, 0) & 0x04) >> 2;
GnEPS_PCS.Inverter_Run_Stop = (BitConverter.ToInt16(data, 0) & 0x02) >> 1;
GnEPS_PCS.System_Run_Stop = (BitConverter.ToInt16(data, 0) & 0x01) >> 0;
*/
//pcs_resourcePool.WaitOne();
//Mode_Standby
GnEPS_PCS.GRID_R_Voltage = ByteConverterToUInt16(data, 0);
GnEPS_PCS.GRID_S_Voltage = ByteConverterToUInt16(data, 1);
GnEPS_PCS.GRID_T_Voltage = ByteConverterToInt16(data, 2);
GnEPS_PCS.GRID_R_Current = ByteConverterToInt16(data, 3);
GnEPS_PCS.GRID_S_Current = ByteConverterToInt16(data, 4);
GnEPS_PCS.GRID_T_Current = ByteConverterToInt16(data, 5);
GnEPS_PCS.GRID_Power = ByteConverterToInt16(data, 6);
p_setting.power.setPCSPower(GnEPS_PCS.GRID_Power);
GnEPS_PCS.GRID_Frequency = ByteConverterToUInt16(data, 7) * 0.1;
GnEPS_PCS.isTemperatureWarning = ByteConverterToUInt16(data, 8);
GnEPS_PCS.LOAD_R_Current = ByteConverterToInt16(data, 11);
GnEPS_PCS.LOAD_S_Current = ByteConverterToInt16(data, 12);
GnEPS_PCS.LOAD_T_Current = ByteConverterToInt16(data, 13);
GnEPS_PCS.LOAD_Power = ByteConverterToUInt16(data, 14);
GnEPS_PCS.INVERTER_Power = ByteConverterToInt16(data, 15);
GnEPS_PCS.PCS_GRID_Status = ByteConverterToUInt16(data, 16);
GnEPS_PCS.PCS_Fault_Status = ByteConverterToUInt16(data, 17);
GnEPS_PCS.PCS_STANDBY = ByteConverterToUInt16(data, 18);
GnEPS_PCS.Fault_Battery_Voltage = ByteConverterToInt16(data, 19);
GnEPS_PCS.Fault_Battery_Current = ByteConverterToInt16(data, 20);
GnEPS_PCS.Fault_System_A_Current = ByteConverterToInt16(data, 21);
GnEPS_PCS.Fault_System_B_Current = ByteConverterToInt16(data, 22);
GnEPS_PCS.Fault_System_C_Current = ByteConverterToInt16(data, 23);
GnEPS_PCS.Fault_Inverter_A_Current = ByteConverterToInt16(data, 24);
GnEPS_PCS.Fault_Inverter_B_Current = ByteConverterToInt16(data, 25);
GnEPS_PCS.Fault_Inverter_C_Current = ByteConverterToInt16(data, 26);
GnEPS_PCS.Fault_Inverter_A_Voltage = ByteConverterToInt16(data, 27);
GnEPS_PCS.Fault_Inverter_B_Voltage = ByteConverterToInt16(data, 28);
GnEPS_PCS.Fault_Inverter_C_Voltage = ByteConverterToInt16(data, 29);
GnEPS_PCS.Fault_Active_Power = ByteConverterToInt16(data, 30);
GnEPS_PCS.Control_MODE = ByteConverterToInt16(data, 31);
GnEPS_PCS.Mode_Standby = (GnEPS_PCS.Control_MODE >> 0) & 0x01;
GnEPS_PCS.Mode_Peak_cut = (GnEPS_PCS.Control_MODE >> 2) & 0x01;
GnEPS_PCS.Mode_Charging = (GnEPS_PCS.Control_MODE >> 6) & 0x01;
GnEPS_PCS.Mode_Discharging = (GnEPS_PCS.Control_MODE >> 7) & 0x01;
GnEPS_PCS.Mode_Reset = (GnEPS_PCS.Control_MODE >> 8) & 0x01;
GnEPS_PCS.Mode_ACKED = (GnEPS_PCS.Control_MODE >> 10) & 0x01;
GnEPS_PCS.Fault_System_CB_Status = ByteConverterToInt16(data, 32);
GnEPS_PCS.Inverter_Current_Reference = ByteConverterToInt16(data, 33);
GnEPS_PCS.Inverter_Q_Current = ByteConverterToInt16(data, 34);
GnEPS_PCS.Inverter_D_Current = ByteConverterToInt16(data, 35);
GnEPS_PCS.Battery_Voltage = ByteConverterToInt16(data, 50);
GnEPS_PCS.Battery_Current = ByteConverterToInt16(data, 51);
TagManager.PCS_Fault_처리_프로시져();
//pcs_resourcePool.Release();
//-----------------------------------------------
// 20180709 DataTable안에 데이터를 넣는 로직.
// 43~80은 Battery System의 항목이기에 ID 필터링 이후 값을 넣도록 한다.
// 그리고 InputCH는 동일하다.
//-----------------------------------------------
Insert_To_DataTable(data, 1, 42, 0);
}
#endregion
public void Get_BSC(byte[] data)
{
//bms_resourcePool.WaitOne();
byte[] temp_byte = new byte[2];
samsung_bcs.Protocol_Version = ByteConverterToUInt16(data, 0);
samsung_bcs.System_Voltage = ByteConverterToUInt16(data, 1) * 0.1;
samsung_bcs.System_Current = ByteConverterToInt16(data, 2);
samsung_bcs.System_Power = samsung_bcs.System_Voltage * samsung_bcs.System_Current / 1000;
//t_dr[0]["Value"] = ByteConverterToUInt16(data, 1) * 0.1;
// Charging과 DisCHarging을 나누기 위해서 만듬
p_setting.power.setBMSPower(samsung_bcs.System_Power);
if (!(samsung_bcs.System_SOC == ByteConverterToUInt16(data, 3) * 0.1))
{
pmdviewer.flag_WriteSOCBuffers_isChanged = true;
samsung_bcs.System_SOC = ByteConverterToUInt16(data, 3) * 0.1;
}
if (!(samsung_bcs.System_SOH == ByteConverterToUInt16(data, 4) * 0.1))
{
pmdviewer.flag_WriteSOCBuffers_isChanged = true;
samsung_bcs.System_SOH = ByteConverterToUInt16(data, 4) * 0.1;
}
if (!(samsung_bcs.System_Mode == ByteConverterToUInt16(data, 5)))
{
pmdviewer.flag_WriteSOCBuffers_isChanged = true;
samsung_bcs.System_Mode = ByteConverterToUInt16(data, 5);
}
// SOC
pmdviewer.WriteSOCBuffers[0] = data[6];
pmdviewer.WriteSOCBuffers[1] = data[7];
// 전압
pmdviewer.WriteVoltageBuffers[0] = data[2];
pmdviewer.WriteVoltageBuffers[1] = data[3];
// 전류
pmdviewer.WriteCurrentBuffers[0] = data[4];
pmdviewer.WriteCurrentBuffers[1] = data[5];
// Heartbit
pmdviewer.WriteHeartBitBuffers[0] = data[50];
pmdviewer.WriteHeartBitBuffers[1] = data[51];
samsung_bcs.Mode_Charging = (samsung_bcs.System_Mode >> 15) & 0x01;
samsung_bcs.Mode_Discharging = (samsung_bcs.System_Mode >> 14) & 0x01;
samsung_bcs.Mode_Offline = (samsung_bcs.System_Mode >> 10) & 0x01;
samsung_bcs.Mode_Idle = (samsung_bcs.System_Mode >> 9) & 0x01;
samsung_bcs.Mode_Ready = (samsung_bcs.System_Mode >> 8) & 0x01;
samsung_bcs.Mode_InputSignal4 = (samsung_bcs.System_Mode >> 7) & 0x01;
samsung_bcs.Mode_InputSignal3 = (samsung_bcs.System_Mode >> 6) & 0x01;
samsung_bcs.Mode_InputSignal2 = (samsung_bcs.System_Mode >> 5) & 0x01;
samsung_bcs.Mode_InputSIgnal1 = (samsung_bcs.System_Mode >> 4) & 0x01;
samsung_bcs.Mode_OutputControl2 = (samsung_bcs.System_Mode >> 1) & 0x01;
samsung_bcs.Mode_OutputControl1 = (samsung_bcs.System_Mode >> 0) & 0x01;
samsung_bcs.System_Max_Voltage = ByteConverterToUInt16(data, 6) * 0.001;
samsung_bcs.System_Min_Voltage = ByteConverterToUInt16(data, 7) * 0.001;
samsung_bcs.System_Max_Temp = ByteConverterToInt16(data, 8) * 0.01;
samsung_bcs.System_Min_Temp = ByteConverterToInt16(data, 9) * 0.01;
samsung_bcs.Protection_Summary4 = ByteConverterToUInt16(data, 14);
samsung_bcs.Protection_Summary3 = ByteConverterToUInt16(data, 15);
samsung_bcs.Protection_Summary2 = ByteConverterToUInt16(data, 16);
samsung_bcs.Protection_Summary1 = ByteConverterToUInt16(data, 17);
samsung_bcs.Alarm_Summary4 = ByteConverterToUInt16(data, 18);
samsung_bcs.Alarm_Summary3 = ByteConverterToUInt16(data, 19);
samsung_bcs.Alarm_Summary2 = ByteConverterToUInt16(data, 20);
samsung_bcs.Alarm_Summary1 = ByteConverterToUInt16(data, 21);
samsung_bcs.Discharge_Current_Limit_of_Rack = ByteConverterToUInt16(data, 22) * 0.1;
samsung_bcs.Charge_Current_Limit = ByteConverterToUInt16(data, 23) * 0.1;
samsung_bcs.Watchdog_Response = ByteConverterToInt16(data, 24);
samsung_bcs.System_Heartbit = ByteConverterToUInt16(data, 25);
samsung_bcs.Connecting_Status = ByteConverterToUInt16(data, 26);
samsung_bcs.Service_Voltage = ByteConverterToUInt16(data, 27) * 0.1;
samsung_bcs.Service_SOC = ByteConverterToUInt16(data, 28) * 0.1;
samsung_bcs.System_Alarm_Status = ByteConverterToUInt16(data, 30);
dbConnector.Insert_Value_to_Database();
TagManager.BMS_Fault_처리_프로시져();
//bms_resourcePool.Release();
Insert_To_DataTable(data,43,80, 0 );
}
private void Insert_To_DataTable(byte[] data, int start, int end , int offset)
{
//-----------------------------------------------
//20180709 DataTable안에 데이터를 넣는 로직.
// 43~80은 Battery System의 항목이기에 ID 필터링 이후 값을 넣도록 한다.
// 그리고 InputCH는 동일하다.
//-----------------------------------------------
DataRow[] t_dr = Tag_Data_Table.Select();
foreach (DataRow dr in t_dr)
{
try
{
if (dr["InputCH"].ToString() == "")
{
// Nothing to do
}
else
{
int temp_InputCH = (Convert.ToUInt16(dr["InputCH"])) - offset;
int temp_ID = Convert.ToInt16(dr["ID"]);
int temp_value = new int();
float temp_resolution = new float();
if (temp_ID >= start && temp_ID <= end)
{
//1. Resolution 처리를 해야함
if (dr["Resolution"].ToString() == "")
{
// nothing to do
temp_resolution = 1;
}
else
{
temp_resolution = Convert.ToSingle(dr["Resolution"]);
}
//2. 부호 처리를 해야함
//3. Bit값일 경우에는 Bit를 처리해야함.
temp_value = ByteConverterToUInt16(data, temp_InputCH);
dr["Value"] = Convert.ToString(temp_value * temp_resolution);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
public void Insert_Rack(ref Samsung_BMS_Rack Rack, byte[] data, int num_of_Rack)
{
//int offset = num_of_Rack * 60 - 40;
int offset = -40;
Rack.Rack_Voltage = ByteConverterToUInt16(data, 40+ offset) * 0.1;
Rack.String1_Rack_Voltage = ByteConverterToUInt16(data, 41+ offset) * 0.1;
Rack.String2_Rack_Voltage = ByteConverterToUInt16(data, 42+ offset) * 0.1;
Rack.String1_Cell_Summation_Voltage = ByteConverterToUInt16(data, 43 + offset) * 0.1;
Rack.String2_Cell_Summation_Voltage = ByteConverterToUInt16(data, 44 + offset) * 0.1;
Rack.Rack_Current = ByteConverterToInt16(data, 45 + offset) * 0.1;
Rack.String1_Rack_Current = ByteConverterToInt16(data, 46 + offset) * 0.1;
Rack.String2_Rack_Current = ByteConverterToInt16(data, 47 + offset) * 0.1;
Rack.Rack_Current_Average = ByteConverterToInt16(data, 48 + offset) * 0.1;
Rack.Rack_Mode = ByteConverterToUInt16(data, 49 + offset);
Rack.Rack_SOC = ByteConverterToInt16(data, 50 + offset) * 0.1;
Rack.Rack_SOH = ByteConverterToInt16(data, 51 + offset) * 0.1;
Rack.Max1_Cell_Voltage_Value = ByteConverterToInt16(data, 64 + offset) * 0.001;
Rack.Max1_Cell_Voltage_Position = ByteConverterToInt16(data, 65 + offset);
Rack.Max2_Cell_Voltage_Value = ByteConverterToInt16(data, 66 + offset) * 0.001;
Rack.Max2_Cell_Voltage_Position = ByteConverterToInt16(data, 67 + offset);
Rack.Average_Cell_Voltage_Value = ByteConverterToInt16(data, 68 + offset) * 0.001;
Rack.Min2_Cell_Voltage_Value = ByteConverterToInt16(data, 69 + offset) * 0.001;
Rack.Min2_Cell_Voltage_Position = ByteConverterToInt16(data, 70 + offset);
Rack.Min1_Cell_Voltage_Value = ByteConverterToInt16(data, 71 + offset) * 0.001;
Rack.Min1_Cell_Voltage_Position = ByteConverterToInt16(data, 72 + offset);
Rack.Max1_Cell_Temp_Value = ByteConverterToInt16(data, 73 + offset) * 0.01;
Rack.Max1_Cell_Temp_Position = ByteConverterToInt16(data, 74 + offset);
Rack.Max2_Cell_Temp_Value = ByteConverterToInt16(data, 75 + offset) * 0.01;
Rack.Max2_Cell_Temp_Position = ByteConverterToInt16(data, 76 + offset);
Rack.Average_Cell_Temp_Value = ByteConverterToInt16(data, 77 + offset) * 0.01;
Rack.Min2_Cell_Temp_Value = ByteConverterToInt16(data, 78 + offset) * 0.01;
Rack.Min2_Cell_Temp_Position = ByteConverterToInt16(data, 79 + offset);
Rack.Min1_Cell_Temp_Value = ByteConverterToInt16(data, 80 + offset) * 0.01;
Rack.Min1_Cell_Temp_Position = ByteConverterToInt16(data, 81 + offset);
Rack.Rack_Discharge_Current_Limit_of_Rack = ByteConverterToUInt16(data, 82 + offset) * 0.1;
Rack.Rack_Charge_Current_Limit_of_Rack = ByteConverterToUInt16(data, 83 + offset) * 0.1;
Rack.Rack_Switch_Control_Info = ByteConverterToUInt16(data, 84 + offset);
Rack.Rack_Switch_Sensor_Info = ByteConverterToUInt16(data, 85 + offset);
Rack.Rack_External_Sensor_Info = ByteConverterToUInt16(data, 86 + offset);
Rack.Module_Comm_Fault_Position = (ByteConverterToUInt16(data, 86 + offset) >> 8) & 0xFF;
if (num_of_Rack == 1)
{
Insert_To_DataTable(data, 81, 114, 40);
}
else if (num_of_Rack == 2)
{
Insert_To_DataTable(data, 115, 148, 100);
}
}
private ushort ByteConverterToUInt16(byte[] data, int offset)
{
return BitConverter.ToUInt16(swapbyte(data, offset * 2), 0);
}
private short ByteConverterToInt16(byte[] data, int offset)
{
return BitConverter.ToInt16(swapbyte(data, offset * 2), 0);
}
private byte[] swapbyte(byte[] word, int offset)
{
//BSC_Controller_Data[0] = BSC1[0] * 256 + data[1];
byte[] data = new Byte[2];
data[0] = word[offset + 1];
data[1] = word[offset];
return data;
}
}
}
<file_sep>using MySql.Data.MySqlClient;
using System;
using System.Data;
namespace KTE_PMS
{
public class DBConnector
{
private static string connStr;
private static MySqlConnection conn;
public DBConnector()
{
try
{
connStr = "DATABASE=mysql; server = localhost; port = 3306; user id = root; password = <PASSWORD>; database = mysql; persist security info = true; CharSet = utf8; SslMode = none";
conn = new MySqlConnection(connStr);
Console.WriteLine("Connecting to MySQL...");
conn.Open();
Insert_START_PMS();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
//conn.Close();
Console.WriteLine("Done.");
}
public DataSet Get_Product()
{
String sql = "SELECT * FROM alarm_data ORDER BY DATETIME desc";
DataSet ds = new DataSet();
MySqlDataAdapter adpt = new MySqlDataAdapter(sql, conn);
adpt.Fill(ds);
return ds;
}
public void Export_Data()
{
try
{
string directory = System.Windows.Forms.Application.StartupPath;
string filename = "\\DB_Data_" + DateTime.Now.ToString("yyyyMMddHHmmss")+ ".csv";
//string directory = "";
//string filename = "DB_Data_" + DateTime.Now.ToString("yyyyMMddHHmmss")+ ".csv";
String sql = "SELECT * INTO OUTFILE '" + directory + filename + "' "
+ "fields terminated by '\t' "
+ "lines terminated by '\r\n' "
+ "FROM power_data_hour";
sql = sql.Replace("\\", "\\\\");
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public DataSet Get_Product(string strstartTime,string strendTime)
{
String sql = "SELECT * FROM alarm_data WHERE DATETIME BETWEEN '" + strstartTime + "' and '" + strendTime + "' ORDER BY DATETIME desc";
DataSet ds = new DataSet();
MySqlDataAdapter adpt = new MySqlDataAdapter(sql, conn);
adpt.Fill(ds);
return ds;
}
public void Insert_Value_to_Database()
{
try
{
string strDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
double voltage;
double current;
double power;
voltage = Repository.Instance.samsung_bcs.System_Voltage;
current = Repository.Instance.samsung_bcs.System_Current;
power = Repository.Instance.samsung_bcs.System_Power;
String sql = "INSERT INTO trend_data (DATETIME, VOLTAGE, CURRENT, POWER) " + "VALUES ('"
+ strDateTime + "','"
+ voltage.ToString() + "','"
+ current.ToString() + "','"
+ power.ToString() + "')";
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public void Insert_Value_to_Database(double voltage, double current, double power)
{
try
{
string strDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
String sql = "INSERT INTO trend_data (DATETIME, VOLTAGE, CURRENT, POWER) " + "VALUES ('"
+ strDateTime + "','"
+ voltage.ToString() + "','"
+ current.ToString() + "','"
+ power.ToString() + "')";
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public void Insert_Alarm_to_Database(string sz)
{
try
{
string[] szFault = sz.Split('|');
String sql = "INSERT INTO alarm_data (DATETIME, CLASS, DEVICE, DESCRIPTION, IO) " + "VALUES ('"
+ szFault[0] + "','"
+ szFault[1] + "','"
+ szFault[2] + "','"
+ szFault[3] + "','"
+ szFault[4] + "')";
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public void Insert_START_PMS()
{
try
{
string strDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
String sql = "INSERT INTO alarm_data (DATETIME, CLASS, DEVICE, DESCRIPTION, IO) " + "VALUES ('"
+ strDateTime + "','"
+ "SYSTEM" + "','"
+ "PMS" + "','"
+ "PMS TURN ON" + "','"
+ "NORMAL" + "')";
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public void Insert_EXIT_PMS()
{
try
{
string strDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
String sql = "INSERT INTO alarm_data (DATETIME, CLASS, DEVICE, DESCRIPTION, IO) " + "VALUES ('"
+ strDateTime + "','"
+ "SYSTEM" + "','"
+ "PMS" + "','"
+ "PMS TURN OFF" + "','"
+ "NORMAL" + "')";
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public void Insert_Power()
{
try
{
string strDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:00");
String sql = "INSERT INTO power_data_minute (DATETIME, PCS_CHARGE_POWER, PCS_DISCHARGE_POWER, BMS_CHARGE_POWER, BMS_DISCHARGE_POWER) " + "VALUES ('"
+ strDateTime + "','"
+ Repository.Instance.p_setting.power.PCS_CHARGE_POWER + "','"
+ Repository.Instance.p_setting.power.PCS_DISCHARGE_POWER + "','"
+ Repository.Instance.p_setting.power.BMS_CHARGE_POWER + "','"
+ Repository.Instance.p_setting.power.BMS_DISCHARGE_POWER + "')";
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public void Insert_Power_Hour()
{
try
{
string strYesterday = DateTime.Now.AddHours(-1).ToString("yyyy-MM-dd HH:00:00");
string strToday = DateTime.Now.ToString("yyyy-MM-dd HH:00:00");
String sql = "SELECT * FROM power_data_minute WHERE DATETIME BETWEEN '"+ strYesterday + "' and '"+ strToday + "' ORDER BY DATETIME desc";
DataSet ds = new DataSet();
MySqlDataAdapter adpt = new MySqlDataAdapter(sql, conn);
adpt.Fill(ds);
sPower total_power = GetPowerFromDatabase(ds);
sql = "INSERT INTO power_data_hour (DATETIME, PCS_CHARGE_POWER, PCS_DISCHARGE_POWER, BMS_CHARGE_POWER, BMS_DISCHARGE_POWER) " + "VALUES ('"
+ strYesterday + "','"
+ total_power.PCS_CHARGE_POWER + "','"
+ total_power.PCS_DISCHARGE_POWER + "','"
+ total_power.BMS_CHARGE_POWER + "','"
+ total_power.BMS_DISCHARGE_POWER + "')";
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public void Insert_Power_Day()
{
try
{
string strYesterday = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 00:00:00");
string strToday = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
String sql = "SELECT * FROM power_data_hour WHERE DATETIME BETWEEN '" + strYesterday + "' and '" + strToday + "' ORDER BY DATETIME desc";
DataSet ds = new DataSet();
MySqlDataAdapter adpt = new MySqlDataAdapter(sql, conn);
adpt.Fill(ds);
sPower total_power = GetPowerFromDatabase(ds);
sql = "INSERT INTO power_data_day (DATETIME, PCS_CHARGE_POWER, PCS_DISCHARGE_POWER, BMS_CHARGE_POWER, BMS_DISCHARGE_POWER) " + "VALUES ('"
+ strYesterday + "','"
+ total_power.PCS_CHARGE_POWER + "','"
+ total_power.PCS_DISCHARGE_POWER + "','"
+ total_power.BMS_CHARGE_POWER + "','"
+ total_power.BMS_DISCHARGE_POWER + "')";
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public void Insert_Power_Month()
{
try
{
string strYesterday = DateTime.Now.AddMonths(-1).ToString("yyyy-MM-01 00:00:00");
string strToday = DateTime.Now.ToString("yyyy-MM-01 00:00:00");
String sql = "SELECT * FROM power_data_day WHERE DATETIME BETWEEN '" + strYesterday + "' and '" + strToday + "' ORDER BY DATETIME desc";
DataSet ds = new DataSet();
MySqlDataAdapter adpt = new MySqlDataAdapter(sql, conn);
adpt.Fill(ds);
sPower total_power = GetPowerFromDatabase(ds);
sql = "INSERT INTO power_data_month (DATETIME, PCS_CHARGE_POWER, PCS_DISCHARGE_POWER, BMS_CHARGE_POWER, BMS_DISCHARGE_POWER) " + "VALUES ('"
+ strYesterday + "','"
+ total_power.PCS_CHARGE_POWER + "','"
+ total_power.PCS_DISCHARGE_POWER + "','"
+ total_power.BMS_CHARGE_POWER + "','"
+ total_power.BMS_DISCHARGE_POWER + "')";
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public void Insert_Power_year()
{
try
{
string strYesterday = DateTime.Now.AddYears(-1).ToString("yyyy-01-01 00:00:00");
string strToday = DateTime.Now.ToString("yyyy-01-01 00:00:00");
String sql = "SELECT * FROM power_data_month WHERE DATETIME BETWEEN '" + strYesterday + "' and '" + strToday + "' ORDER BY DATETIME desc";
DataSet ds = new DataSet();
MySqlDataAdapter adpt = new MySqlDataAdapter(sql, conn);
adpt.Fill(ds);
sPower total_power = GetPowerFromDatabase(ds);
sql = "INSERT INTO power_data_year (DATETIME, PCS_CHARGE_POWER, PCS_DISCHARGE_POWER, BMS_CHARGE_POWER, BMS_DISCHARGE_POWER) " + "VALUES ('"
+ strYesterday + "','"
+ total_power.PCS_CHARGE_POWER + "','"
+ total_power.PCS_DISCHARGE_POWER + "','"
+ total_power.BMS_CHARGE_POWER + "','"
+ total_power.BMS_DISCHARGE_POWER + "')";
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private sPower GetPowerFromDatabase(DataSet ds)
{
sPower power = new sPower();
int total_count = new int();
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
power.PCS_CHARGE_POWER = power.PCS_CHARGE_POWER + Convert.ToDouble(dr["PCS_CHARGE_POWER"]);
power.PCS_DISCHARGE_POWER = power.PCS_DISCHARGE_POWER + Convert.ToDouble(dr["PCS_DISCHARGE_POWER"]);
power.BMS_CHARGE_POWER = power.BMS_CHARGE_POWER + Convert.ToDouble(dr["BMS_CHARGE_POWER"]);
power.BMS_DISCHARGE_POWER = power.BMS_DISCHARGE_POWER + Convert.ToDouble(dr["BMS_DISCHARGE_POWER"]);
total_count = total_count + 1;
}
}
if (total_count == 0) total_count = 1; // To protect zero-division Exception
power.PCS_CHARGE_POWER = power.PCS_CHARGE_POWER / ds.Tables.Count;
power.PCS_DISCHARGE_POWER = power.PCS_DISCHARGE_POWER / ds.Tables.Count;
power.BMS_CHARGE_POWER = power.BMS_CHARGE_POWER / ds.Tables.Count;
power.BMS_DISCHARGE_POWER = power.BMS_DISCHARGE_POWER / ds.Tables.Count;
return power;
}
public void Select_Power()
{
try
{
string str_start = DateTime.Now.ToString("yyyy-mm-dd 00:00:00");
string str_end = DateTime.Now.ToString("yyyy-mm-dd HH:mm:ss");
String sql = "SELECT * FROM power_data_hour WHERE DATETIME BETWEEN '" + str_start + "' and '" + str_end + "' ORDER BY DATETIME desc";
DataSet ds = new DataSet();
MySqlDataAdapter adpt = new MySqlDataAdapter(sql, conn);
adpt.Fill(ds);
Repository.Instance.p_setting.power_day = GetPowerFromDatabase(ds);
//
str_start = DateTime.Now.ToString("yyyy-mm-01 00:00:00");
str_end = DateTime.Now.ToString("yyyy-mm-dd 00:00:00");
sql = "SELECT * FROM power_data_day WHERE DATETIME BETWEEN '" + str_start + "' and '" + str_end + "' ORDER BY DATETIME desc";
ds.Clear();
adpt.Dispose();
adpt = new MySqlDataAdapter(sql, conn);
adpt.Fill(ds);
Repository.Instance.p_setting.power_month = Repository.Instance.p_setting.power_day + GetPowerFromDatabase(ds);
//
str_start = DateTime.Now.ToString("yyyy-01-01 00:00:00");
str_end = DateTime.Now.ToString("yyyy-mm-dd 00:00:00");
sql = "SELECT * FROM power_data_month WHERE DATETIME BETWEEN '" + str_start + "' and '" + str_end + "' ORDER BY DATETIME desc";
ds.Clear();
adpt.Dispose();
adpt = new MySqlDataAdapter(sql, conn);
adpt.Fill(ds);
Repository.Instance.p_setting.power_year = Repository.Instance.p_setting.power_month + GetPowerFromDatabase(ds);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
<file_sep>using KTE_PMS.Observer;
using ModbusTCP;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace KTE_PMS.MIMIC
{
public partial class PMDViewer : Form
{
public ModbusTCP.Master master;
public byte[] WriteValueBuffers { get; set; }
public byte[] WriteHeartBitBuffers { get; set; }
public byte[] WriteSOCBuffers { get; set; }
public byte[] WriteVoltageBuffers { get; set; }
public byte[] WriteCurrentBuffers { get; set; }
/* 180625
* 부하를 줄이기 위해서 이전값과 비교해서 값이 바뀌었을때만 PCS로 보내주도록 한다.
* */
public bool flag_WriteValueBuffers_isChanged { get; set; }
public bool flag_WriteHeartBitBuffers_isChanged { get; set; }
public bool flag_WriteSOCBuffers_isChanged { get; set; }
public bool flag_WriteVoltageBuffers_isChanged { get; set; }
public bool flag_WriteCurrentBuffers_isChanged { get; set; }
private byte[] data;
DateTime tLastRecv;
public PMDViewer()
{
InitializeComponent();
tLastRecv = new DateTime();
tLastRecv = DateTime.Now;
if (Properties.Settings.Default.DEBUG) return;
master = new Master();
WriteValueBuffers = new byte[2];
WriteHeartBitBuffers = new byte[2];
WriteSOCBuffers = new byte[2];
WriteVoltageBuffers = new byte[2];
WriteCurrentBuffers = new byte[2];
// For test. IP 설정창을 그린 후 해당 내용으로 교체할 예정임
txtIP1.Text = "17";
txtIP2.Text = "91";
txtIP3.Text = "30";
txtIP4.Text = "10";
//-----------------------------
// Modbus TCP - uPMD 통신 시도 //
//-----------------------------
// 1. File에서 설정값 읽어오기
// Not Yet
//Read_PMD_Configuration();
// 2. 연결하기
Connect_to_PMD();
timer.Interval = 1500;
timer.Enabled = true;
timer.Start();
}
private void timer_Tick(object sender, EventArgs e)
{
// Mode에 따라서 동작하도록 코드 수정
if (DateTime.Now.Second % 2 == 1)
{
ReadFromPCS();
}
else
{
if (Repository.Instance.current_pcs_mode == 2)
{
//Manual Mode
}
else if (Repository.Instance.current_pcs_mode == 3)
{
// 충전모드라면 충전신호를 보낸다. 충전모드가 아니라면 충전신호를 지속적으로 보낸다
// 방전모드라면 방전신호를 보낸다. 방전모드가 아니라면 방전신호를 지속적으로 보낸다.
// 단 방전/충전 정지 SOC, 방전/충전 시작 SOC등을 확인해서 신호를 보낸다.
// Charging시간이 아니더라도 Charging 조건은 가장 우선시해야한다.
if (Repository.Instance.p_setting.flag_Charging_Time)
{
// 충전 정지 SOC를 확인하자, 그리고 현재 상태도 확인.
if (!(Repository.Instance.GnEPS_PCS.Mode_Charging == 1))
{
if (Repository.Instance.samsung_bcs.System_SOC < Repository.Instance.p_setting.Charging_Stop_SOC)
{
Repository.Instance.pmdviewer.Control_Charge();
}
}
}
else if (Repository.Instance.p_setting.flag_DisCharging_Time)
{
// 충전 정지 SOC를 확인하자, 그리고 현재 상태도 확인.
if (!(Repository.Instance.GnEPS_PCS.Mode_Discharging == 1))
{
if (Repository.Instance.samsung_bcs.System_SOC > Repository.Instance.p_setting.Discharging_Stop_SOC)
{
Repository.Instance.pmdviewer.Control_Discharge();
}
}
}
else
{
// nothing to do
// 만약 충전신호나 방전신호가 가고있다면 0으로 바꿔준다.
if (Repository.Instance.samsung_bcs.System_SOC <= Repository.Instance.p_setting.Charging_Limit_Voltage)
{
if (!(Repository.Instance.GnEPS_PCS.Mode_Charging == 1))
{
Repository.Instance.pmdviewer.Control_Charge();
}
}
else if (Repository.Instance.samsung_bcs.System_SOC >= Repository.Instance.p_setting.Discharging_Limit_Voltage)
{
if (!(Repository.Instance.GnEPS_PCS.Mode_Discharging == 1))
{
Repository.Instance.pmdviewer.Control_Discharge();
}
}
else if ((Repository.Instance.GnEPS_PCS.Mode_Discharging == 1) || (Repository.Instance.GnEPS_PCS.Mode_Charging == 1))
{
Repository.Instance.pmdviewer.Control_Idle();
}
else
{
// nothing to do
//Console.WriteLine("Unexpected Situtation. Need to Check");
}
}
}
}
/* 변경이 있을때만 보내도록 하자 */
if (flag_WriteHeartBitBuffers_isChanged)
{
WriteHeartBit();
flag_WriteHeartBitBuffers_isChanged = false;
}
if (flag_WriteSOCBuffers_isChanged)
{
WriteSOC();
flag_WriteSOCBuffers_isChanged = false;
}
if (flag_WriteVoltageBuffers_isChanged)
{
WriteVoltage();
flag_WriteVoltageBuffers_isChanged = false;
}
if (flag_WriteCurrentBuffers_isChanged)
{
WriteCurrent();
flag_WriteCurrentBuffers_isChanged = false;
}
}
private void Connect_to_PMD()
{
try
{
// Create new modbus master and add event functions
string ip_address = "192.168.127.12";
ushort port_number = 502;
master = new Master(ip_address, port_number);
// Setting response data and exception
master.OnResponseData += new Master.ResponseData(MBmaster_OnResponseData);
master.OnException += new Master.ExceptionData(MBmaster_OnException);
}
catch (SystemException error)
{
//MessageBox.Show(error.Message + "다시 접속해 주세요");
System.Diagnostics.Debug.WriteLine(error.Message + "다시 접속해 주세요");
}
}
public void ReadFromPCS()
{
ushort ID = 4;
byte unit = Convert.ToByte(1);
ushort StartAddress = ReadStartAdr(30);
byte Length = Convert.ToByte(52);
master.ReadHoldingRegister(ID, unit, StartAddress, Length);
}
public void WriteHeartBit()
{
byte unit = Convert.ToByte(1);
ushort StartAddress = ReadStartAdr(5);
master.WriteSingleRegister(8, unit, StartAddress, WriteHeartBitBuffers);
}
public void WriteVoltage()
{
byte unit = Convert.ToByte(1);
ushort StartAddress = ReadStartAdr(3);
master.WriteSingleRegister(8, unit, StartAddress, WriteVoltageBuffers);
}
public void WriteCurrent()
{
byte unit = Convert.ToByte(1);
ushort StartAddress = ReadStartAdr(4);
master.WriteSingleRegister(8, unit, StartAddress, WriteCurrentBuffers);
}
public void WriteSOC()
{
byte unit = Convert.ToByte(1);
ushort StartAddress = ReadStartAdr(2);
master.WriteSingleRegister(8, unit, StartAddress, WriteSOCBuffers);
}
public void Control_INV_Control_MODE(int value)
{
byte unit = Convert.ToByte(1);
ushort StartAddress = ReadStartAdr(0);
byte[] buffer = new byte[2];
// 20180628
//Reset 신호와 Remote Local 신호를 구분하기 위해서
// Value에 제어 값과 And를 해서 보내도록 한다
int final_control = new int();
if (Repository.Instance.GnEPS_PCS.PCS_ACK)
{
final_control = value + 256;
}
if (Repository.Instance.GnEPS_PCS.Authority_PMS)
{
// Authority_PMS가 1인 경우에는 LEMS에서 제어를 하고
// Authority_PMS가 0인 경우에는 u_PMS에서 제어를 한다.
final_control = value + 512;
}
buffer[0] = Convert.ToByte(final_control / 256);
buffer[1] = Convert.ToByte(final_control % 256);
try
{
// ID = 8, Unit = 1, StartAddress = 0
master.WriteSingleRegister(8, unit, StartAddress, buffer);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public void Control_Power_Active_Set()
{
byte unit = Convert.ToByte(1);
ushort StartAddress = ReadStartAdr(1);
ushort power = Repository.Instance.remote_power;
if (power > 500)
{
power = 500;
}
byte[] buffer = new byte[2];
buffer[0] = Convert.ToByte(power / 256);
buffer[1] = Convert.ToByte(power % 256);
try
{
master.WriteSingleRegister(8, unit, StartAddress, buffer);
}
catch (Exception exc)
{
Console.WriteLine(exc.Message);
}
}
// 180628 Reset과 Control 신호의 Add를 위해서 Control_INV_Control_Mode를 변경해야할 필요성이 있음
public void Control_Charge()
{
Control_Power_Active_Set();
Control_INV_Control_MODE(69);
}
public void Control_Discharge()
{
Control_Power_Active_Set();
Control_INV_Control_MODE(133);
}
public void Control_Idle()
{
Control_Power_Active_Set();
Control_INV_Control_MODE(1);
}
// ------------------------------------------------------------------------
// Event for response data
// ------------------------------------------------------------------------
private void MBmaster_OnResponseData(ushort ID, byte unit, byte function, byte[] values)
{
// ------------------------------------------------------------------
// Seperate calling threads
if (this.InvokeRequired)
{
this.BeginInvoke(new Master.ResponseData(MBmaster_OnResponseData), new object[] { ID, unit, function, values });
return;
}
// PCS Timeout을 체크하기 위해서 필요한 항목
tLastRecv = DateTime.Now;
// ------------------------------------------------------------------------
// Identify requested data
switch (ID)
{
case 1:
// ---------------------------------------------------------
// 40000 ~ 40049
// ---------------------------------------------------------
//BSC1 = values;
break;
case 2:
//grpData.Text = "Read discrete inputs";
//data = values;
//값을 받아와야함
break;
case 3:
//grpData.Text = "Read holding register";
data = values;
break;
case 4:
//grpData.Text = "Read input register";
data = values;
Repository.Instance.Get_PCS(data);
Notify();
break;
}
}
// ------------------------------------------------------------------------
// Modbus TCP slave exception
// ------------------------------------------------------------------------
private void MBmaster_OnException(ushort id, byte unit, byte function, byte exception)
{
string exc = "Modbus says error: ";
switch (exception)
{
case Master.excIllegalFunction: exc += "Illegal function!"; break;
case Master.excIllegalDataAdr: exc += "Illegal data adress!"; break;
case Master.excIllegalDataVal: exc += "Illegal data value!"; break;
case Master.excSlaveDeviceFailure: exc += "Slave device failure!"; break;
case Master.excAck: exc += "Acknoledge!"; break;
case Master.excGatePathUnavailable: exc += "Gateway path unavailbale!"; break;
case Master.excExceptionTimeout: exc += "Slave timed out!"; break;
case Master.excExceptionConnectionLost: exc += "Connection is lost!"; break;
case Master.excExceptionNotConnected: exc += "Not connected!"; break;
}
//MessageBox.Show(exc, "Modbus slave exception");
System.Diagnostics.Debug.WriteLine(exc);
}
private ushort ReadStartAdr(UInt16 StartAddress)
{
return StartAddress;
}
public List<IUpdate> observers = new List<IUpdate>();
public void AddObserver(IUpdate observer)
{
observers.Add(observer);
}
public void RemoveObserver(IUpdate observer)
{
observers.Remove(observer);
}
public void Notify()
{
foreach (IUpdate observer in observers)
{
observer.ObserverUpdate();
}
}
public int Connected()
{
DateTime dt_now;
dt_now = DateTime.Now;
TimeSpan span = dt_now - tLastRecv;
if (span.TotalSeconds < 10)
{
if (Repository.Instance.TagManager.FAULT_STATUS[48, 8, 0] != "0")
Repository.Instance.TagManager.경보발생및해제(0, 48, 8);
return 1;
}
else
{
if (Repository.Instance.TagManager.FAULT_STATUS[48, 8, 0] != "1")
Repository.Instance.TagManager.경보발생및해제(1, 48, 8);
return 0;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KTE_PMS
{
public class Samsung_BMS_Rack
{
public double Rack_Voltage { get; set; }
public double String1_Rack_Voltage { get; set; }
public double String2_Rack_Voltage { get; set; }
public double String1_Cell_Summation_Voltage { get; set; }
public double String2_Cell_Summation_Voltage { get; set; }
public double Rack_Current { get; set; }
public double String1_Rack_Current { get; set; }
public double String2_Rack_Current { get; set; }
public double Rack_Current_Average { get; set; }
public ushort Rack_Mode { get; set; }
public double Rack_SOC { get; set; }
public double Rack_SOH { get; set; }
public double Max1_Cell_Voltage_Value { get; set; }
public int Max1_Cell_Voltage_Position { get; set; }
public double Min1_Cell_Voltage_Value { get; set; }
public int Min1_Cell_Voltage_Position { get; set; }
public double Max2_Cell_Voltage_Value { get; set; }
public int Max2_Cell_Voltage_Position { get; set; }
public double Min2_Cell_Voltage_Value { get; set; }
public int Min2_Cell_Voltage_Position { get; set; }
public double Max1_Cell_Temp_Value { get; set; }
public int Max1_Cell_Temp_Position { get; set; }
public double Min1_Cell_Temp_Value { get; set; }
public int Min1_Cell_Temp_Position { get; set; }
public double Max2_Cell_Temp_Value { get; set; }
public int Max2_Cell_Temp_Position { get; set; }
public double Min2_Cell_Temp_Value { get; set; }
public int Min2_Cell_Temp_Position { get; set; }
public double Average_Cell_Voltage_Value { get; set; }
public double Average_Cell_Temp_Value { get; set; }
public double Rack_Discharge_Current_Limit_of_Rack { get; set; }
public double Rack_Charge_Current_Limit_of_Rack { get; set; }
public double Rack_Switch_Control_Info { get; set; }
public double Rack_Switch_Sensor_Info { get; set; }
public double Rack_External_Sensor_Info { get; set; }
public double Module_Comm_Fault_Position { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
namespace KTE_PMS.MIMIC
{
public partial class myTextBox : DevExpress.XtraEditors.XtraUserControl
{
public myTextBox()
{
InitializeComponent();
}
/*
this.myTextBox1.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("myTextBox1.BackgroundImage")));
this.myTextBox1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
this.myTextBox1.Location = new System.Drawing.Point(897, 195);
this.myTextBox1.Name = "myTextBox1";
this.myTextBox1.Size = new System.Drawing.Size(150, 150);
this.myTextBox1.TabIndex = 50;
*/
}
}
<file_sep>using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace UDP_SERVER
{
class Program
{
static void Main(string[] args)
{
int port = 5000;
string strIP = "172.31.110.33";
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress ip = IPAddress.Parse(strIP);
IPEndPoint endPoint = new IPEndPoint(ip, port);
socket.Bind(endPoint);
//데이터 받기
byte[] rBuffer = new byte[1024];
while (true)
{
int length = socket.Receive(rBuffer, 0, rBuffer.Length, SocketFlags.None);
Console.WriteLine(rBuffer.Length);
//디코딩
//string result = Encoding.UTF8.GetString(rBuffer);
for (int i = 0; i < rBuffer.Length; i++)
{
Console.Write(rBuffer[i] + " " );
}
Console.WriteLine("");
}
}
}
}
<file_sep>using System;
using System.Linq;
using System.Windows.Forms;
namespace KTE_PMS
{
public partial class Test : Form
{
public Test()
{
InitializeComponent();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KTE_PMS.MIMIC
{
public partial class Calculate_Power_Prices : Form
{
public Calculate_Power_Prices()
{
InitializeComponent();
}
private void maskedTextBox1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
{
MaskedTextBox masktedTextBox = (MaskedTextBox)sender;
if (masktedTextBox.MaskFull)
{
MessageBox.Show("모든 사항이 입력되었습니다. 추가입력이 불가합니다");
}
else if (e.Position == masktedTextBox.Mask.Length)
{
MessageBox.Show("마스크 위치를 넘어섰습니다. 입력이 불가합니다");
}
else
{
MessageBox.Show("숫자만 입력해야 합니다. 입력이 불가합니다");
}
}
private void btn_OK_Click(object sender, EventArgs e)
{
if (MessageBox.Show("해당 설정을 적용 하시겠습니까?", "확인", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
// 전력 * REC 가중치 / 1000
// REC 입찰수익
// 연간 총 수익 = REC 입찰수익 + 연간 SMP 수익
float power = Repository.Instance.p_setting.total_power;
//--- Debugging을 위해서 임시로 넣어놓은 것
power = 127750.0f;
float REC = power * Convert.ToSingle(tb_REC_ratio.Text) / 1000;
float REC_Prices = REC * Convert.ToSingle(tb_REC_Prices.Text);
float SMP_Prices = power * Convert.ToSingle(tb_SMP_Prices.Text);
float total_prices = SMP_Prices + REC_Prices;
Repository.Instance.p_setting.SetPowerPrices(total_prices / power);
this.Dispose();
}
}
private void btn_Cancel_Click(object sender, EventArgs e)
{
if (MessageBox.Show("취소하시겠습니까?", "확인", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
this.Dispose();
}
}
private void Calculate_Power_Prices_Load(object sender, EventArgs e)
{
}
private void label5_Click(object sender, EventArgs e)
{
}
private void label4_Click(object sender, EventArgs e)
{
}
}
}
<file_sep>using KTE_PMS.Observer;
using System;
using System.Linq;
using System.Windows.Forms;
namespace KTE_PMS.MIMIC
{
public partial class MimicViewer : Viewer, IUpdate
{
public MimicViewer()
{
InitializeComponent();
}
delegate void CrossThreadSafetySetText(Control ctl, String text);
private void CSafeSetText(Control ctl, String text)
{
/*
* InvokeRequired 속성 (Control.InvokeRequired, MSDN)
* 짧게 말해서, 이 컨트롤이 만들어진 스레드와 현재의 스레드가 달라서
* 컨트롤에서 스레드를 만들어야 하는지를 나타내는 속성입니다.
*
* InvokeRequired 속성의 값이 참이면, 컨트롤에서 스레드를 만들어 텍스트를 변경하고,
* 그렇지 않은 경우에는 그냥 변경해도 아무 오류가 없기 때문에 텍스트를 변경합니다.
*/
if (ctl.InvokeRequired)
ctl.Invoke(new CrossThreadSafetySetText(CSafeSetText), ctl, text);
else
ctl.Text = text;
}
public void ObserverUpdate()
{
// 값 써주기
CSafeSetText(lbGRID_R_VOLTAGE, Repository.Instance.GnEPS_PCS.GRID_R_Voltage.ToString());
CSafeSetText(lbGRID_S_VOLTAGE, Repository.Instance.GnEPS_PCS.GRID_S_Voltage.ToString());
CSafeSetText(lbGRID_T_VOLTAGE, Repository.Instance.GnEPS_PCS.GRID_T_Voltage.ToString());
CSafeSetText(lbGRID_R_CURRENT, Repository.Instance.GnEPS_PCS.GRID_R_Current.ToString());
CSafeSetText(lbGRID_S_CURRENT, Repository.Instance.GnEPS_PCS.GRID_S_Current.ToString());
CSafeSetText(lbGRID_T_CURRENT, Repository.Instance.GnEPS_PCS.GRID_T_Current.ToString());
CSafeSetText(lbGRID_POWER, Repository.Instance.GnEPS_PCS.GRID_Power.ToString());
CSafeSetText(lbGRID_Frequency, Repository.Instance.GnEPS_PCS.GRID_Frequency.ToString());
if (Repository.Instance.GnEPS_PCS.isTemperatureWarning == 1)
{
CSafeSetText(lbisTemperatureWarning, "WARNING");
}
else
{
CSafeSetText(lbisTemperatureWarning, "NORMAL");
}
CSafeSetText(lbLOAD_R_CURRENT, Repository.Instance.GnEPS_PCS.LOAD_R_Current.ToString());
CSafeSetText(lbLOAD_S_CURRENT, Repository.Instance.GnEPS_PCS.LOAD_S_Current.ToString());
CSafeSetText(lbLOAD_T_CURRENT, Repository.Instance.GnEPS_PCS.LOAD_T_Current.ToString());
CSafeSetText(lbLOAD_POWER, Repository.Instance.GnEPS_PCS.LOAD_Power.ToString());
CSafeSetText(lbINVERTER_POWER, Repository.Instance.GnEPS_PCS.INVERTER_Power .ToString());
}
}
}
<file_sep>using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace KTE_PMS.MIMIC
{
public partial class Setting_PageViewer : Viewer
{
public TimeSpan Charging_StartTime { get; set; }
public TimeSpan Charging_EndTime { get; set; }
public TimeSpan Discharging_StartTime { get; set; }
public TimeSpan Discharging_EndTime { get; set; }
public sPower power { get; set; }
public sPower power_day { get; set; }
public sPower power_month { get; set; }
public sPower power_year { get; set; }
public float total_power { get; set; }
public float Charging_Stop_SOC { get; set; }
public float Discharging_Stop_SOC { get; set; }
public float Discharging_Limit_Voltage { get; set; }
public float Charging_Limit_Voltage { get; set; }
public float Limit_Active_Power { get; set; }
public bool flag_Charging_Time { get; set; }
public bool flag_DisCharging_Time { get; set; }
public Setting_PageViewer()
{
InitializeComponent();
Initialize_Parameter_Settings();
}
private void Initialize_Parameter_Settings()
{
Charging_StartTime = new TimeSpan(08, 00, 00);
Charging_EndTime = new TimeSpan(12, 00, 00);
Discharging_StartTime = new TimeSpan(16, 00, 00);
Discharging_EndTime = new TimeSpan(20, 00, 00);
power = new sPower();
power_day = new sPower();
power_month = new sPower();
power_year = new sPower();
Charging_Stop_SOC = 80.0F;
Discharging_Stop_SOC = 30.0F;
Discharging_Limit_Voltage = 85.0F;
Charging_Limit_Voltage = 30.0F;
Limit_Active_Power = 50.0F;
}
private void btn_Access_To_Operating_System_Click(object sender, EventArgs e)
{
if (DialogResult.Yes == MessageBox.Show("Are you sure to finish the program?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation))
{
// exit program
Application.Exit();
}
else
{
// nothing happened
}
}
private void btn_Export_Data_Click(object sender, EventArgs e)
{
try
{
//Pass the file path and file name to the StreamReader constructor
string directory = System.Windows.Forms.Application.StartupPath;
string fn = "\\Configs.dat";
StreamWriter sw = new StreamWriter(directory + fn);
sw.WriteLine("// PCS Setting\r\n");
sw.WriteLine("ID = 1\r\n");
sw.WriteLine("port = COM1\r\n");
sw.WriteLine("baudrate = 9600\r\n");
sw.WriteLine("parity = ODD\r\n");
sw.WriteLine("stopbit = 1bit\r\n");
sw.WriteLine("readtimeout = 1000\r\n");
sw.WriteLine("writetimeout = 1000\r\n");
sw.WriteLine("// BSC Setting\r\n");
sw.WriteLine("type = Samsung\r\n");
sw.WriteLine("ip_address = 172.31.110.33\r\n");
sw.WriteLine("port = 504)\r\n");
sw.WriteLine("//PMD Setting\\\rn;");
sw.WriteLine("ID = 1\r\n");
sw.WriteLine("ip_address = 172.31.110.33");
sw.WriteLine("port = 1004");
//close the file
sw.Close();
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
}
private void btn_Import_Data_Click(object sender, EventArgs e)
{
//Import 할 데이터들을 정하자?
// 사실 생각해보면 Import는 의미가 없는데?
// 어차피 읽어오는 것을 데이터 파일에서 읽어온다면 Import의 의미가 없다. Export의 의미는 있음
}
private void btn_Password_Change_Click(object sender, EventArgs e)
{
VKeyboardViewer viewer = new VKeyboardViewer();
// ShowDialog
// Password 확인
viewer.ShowDialog();
if (Repository.Instance.user_level == 5)
{
VKeyboardViewer viewer2 = new VKeyboardViewer("새로운 비밀번호");
// Password 새로 입력
viewer2.ShowDialog();
VKeyboardViewer viewer3 = new VKeyboardViewer("비밀번호 확인");
// Password 추가 확인
viewer3.ShowDialog();
}
}
private void SOC_TextBox_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
{
MaskedTextBox masktedTextBox = (MaskedTextBox)sender;
if (masktedTextBox.MaskFull)
{
MessageBox.Show("모든 사항이 입력되었습니다. 추가입력이 불가합니다");
}
else if (e.Position == masktedTextBox.Mask.Length)
{
MessageBox.Show("마스크 위치를 넘어섰습니다. 입력이 불가합니다");
}
else
{
MessageBox.Show("숫자만 입력해야 합니다. 입력이 불가합니다");
}
}
private void SOC_TextBox_TextChanged(object sender, EventArgs e)
{
try
{
MaskedTextBox masktedTextBox = (MaskedTextBox)sender;
masktedTextBox.Text = masktedTextBox.Text.Replace("_", string.Empty);
if (Convert.ToDouble(masktedTextBox.Text) > 100)
{
MessageBox.Show("SOC는 100을 초과할 수 없습니다. 입력이 불가합니다");
masktedTextBox.Text = "100.0";
}
else if (Convert.ToDouble(masktedTextBox.Text) < 0)
{
MessageBox.Show("SOC는 음수가 될 수 없습니다. 입력이 불가합니다");
masktedTextBox.Text = "000.0";
}
else
{
if (masktedTextBox.Name == "tb_Charging_Stop_SOC")
{
Charging_Stop_SOC = Convert.ToSingle(masktedTextBox.Text);
}
else if (masktedTextBox.Name == "tb_Discharging_Stop_SOC")
{
Discharging_Stop_SOC = Convert.ToSingle(masktedTextBox.Text);
}
}
}
catch (Exception exc)
{
MessageBox.Show("올바르지 않은 데이터가 들어갔습니다, 다시 확인해주시길 바랍니다 이유 : " + exc.Message);
}
}
private void Voltage_TextBox_TextChanged(object sender, EventArgs e)
{
try
{
MaskedTextBox masktedTextBox = (MaskedTextBox)sender;
masktedTextBox.Text = masktedTextBox.Text.Replace("_", string.Empty);
if (Convert.ToDouble(masktedTextBox.Text) > 1000)
{
MessageBox.Show("전압은 1000V을 초과할 수 없습니다. 입력이 불가합니다");
masktedTextBox.Text = "1000.0V";
}
else if (Convert.ToDouble(masktedTextBox.Text) < 0)
{
MessageBox.Show("전압은 음수가 될 수 없습니다. 입력이 불가합니다");
masktedTextBox.Text = "000.0";
}
else
{
if (masktedTextBox.Name == "tb_Charging_Limit_Voltage")
{
Charging_Limit_Voltage = Convert.ToSingle(masktedTextBox.Text);
}
else if (masktedTextBox.Name == "tb_Discharging_Limit_Voltage")
{
Discharging_Limit_Voltage = Convert.ToSingle(masktedTextBox.Text);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void Setting_PageViewer_Load(object sender, EventArgs e)
{
tb_Charging_Stop_SOC.Text = String.Format("{0:000.0}", Charging_Stop_SOC);
tb_Discharging_Stop_SOC.Text = String.Format("{0:000.0}", Discharging_Stop_SOC);
tb_Charging_Limit_Voltage.Text = String.Format("{0:000.0}", Discharging_Limit_Voltage);
tb_Discharging_Limit_Voltage.Text = String.Format("{0:000.0}", Charging_Limit_Voltage);
tb_Charging_Period_Start.Text = Charging_StartTime.Hours.ToString("D2") + "시" + Charging_StartTime.Minutes.ToString("D2") + "분";
tb_Charging_Period_End.Text = Charging_EndTime.Hours.ToString("D2") + "시" + Charging_EndTime.Minutes.ToString("D2") + "분";
tb_Discharging_Period_Start.Text = Discharging_StartTime.Hours.ToString("D2") + "시" + Discharging_StartTime.Minutes.ToString("D2") + "분";
tb_Discharging_Period_End.Text = Discharging_EndTime.Hours.ToString("D2") + "시" + Discharging_EndTime.Minutes.ToString("D2") + "분";
}
private void tb_Charging_Stop_SOC_Leave(object sender, EventArgs e)
{
SOC_TextBox_TextChanged(sender, e);
}
private void btn_Apply_Click(object sender, EventArgs e)
{
try
{
if (MessageBox.Show("해당 설정을 적용 하시겠습니까?", "확인", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Set_Current_PCS_Operating_Mode();
TimeSpan current = DateTime.Now.TimeOfDay;
TimeSpan StartTime1 = Convert_From_MaskedTextBox_To_TimeSpan(tb_Charging_Period_Start);
TimeSpan EndTime1 = Convert_From_MaskedTextBox_To_TimeSpan(tb_Charging_Period_End);
TimeSpan StartTime2 = Convert_From_MaskedTextBox_To_TimeSpan(tb_Discharging_Period_Start);
TimeSpan EndTime2 = Convert_From_MaskedTextBox_To_TimeSpan(tb_Discharging_Period_End);
Charging_StartTime = Convert_From_MaskedTextBox_To_TimeSpan(tb_Charging_Period_Start);
Charging_EndTime = Convert_From_MaskedTextBox_To_TimeSpan(tb_Charging_Period_End);
Discharging_StartTime = Convert_From_MaskedTextBox_To_TimeSpan(tb_Discharging_Period_Start);
Discharging_EndTime = Convert_From_MaskedTextBox_To_TimeSpan(tb_Discharging_Period_End);
Set_Scheduler_Setting(StartTime1, EndTime1, StartTime2, EndTime2);
if ((StartTime1 < StartTime2) && (StartTime2 < EndTime1))
{
MessageBox.Show("방전 시간과 충전 시간이 겹칩니다. 다시 설정하여 주십시오");
return;
}
else if ((StartTime1 < EndTime2) && (EndTime2 < EndTime1))
{
MessageBox.Show("방전 시간과 충전 시간이 겹칩니다. 다시 설정하여 주십시오");
return;
}
Charging_Stop_SOC = Convert_From_MaskedTextBox_To_Single(tb_Charging_Stop_SOC);
Discharging_Stop_SOC = Convert_From_MaskedTextBox_To_Single(tb_Discharging_Stop_SOC);
Charging_Limit_Voltage = Convert_From_MaskedTextBox_To_Single(tb_Discharging_Limit_Voltage);
Discharging_Limit_Voltage = Convert_From_MaskedTextBox_To_Single(tb_Discharging_Limit_Voltage);
Charging_StartTime = Convert_From_MaskedTextBox_To_TimeSpan(tb_Charging_Period_Start);
Charging_EndTime = Convert_From_MaskedTextBox_To_TimeSpan(tb_Charging_Period_End);
Discharging_StartTime = Convert_From_MaskedTextBox_To_TimeSpan(tb_Discharging_Period_Start);
Discharging_EndTime = Convert_From_MaskedTextBox_To_TimeSpan(tb_Discharging_Period_End);
Set_Current_PCS_Operating_Mode(StartTime1, EndTime1, StartTime2, EndTime2);
}
}
catch (Exception exc)
{
MessageBox.Show("올바르지 않은 데이터가 들어갔습니다, 다시 확인해주시길 바랍니다 이유 : " + exc.Message);
}
}
public void Set_Current_PCS_Operating_Mode(TimeSpan StartTime1, TimeSpan EndTime1, TimeSpan StartTime2, TimeSpan EndTime2)
{
TimeSpan current = DateTime.Now.TimeOfDay;
// Scheduling Mode
// 현재시간이 방전모드인지, 충전모드인지를 먼저 확인한다.
if (StartTime1 > EndTime1 && (StartTime1 <= current || current < EndTime1))
{
//충전시간이다
flag_Charging_Time = true;
flag_DisCharging_Time = false;
}
else if (StartTime1 < EndTime1 && (StartTime1 <= current && current < EndTime1))
{
// 충전시간이다
flag_Charging_Time = true;
flag_DisCharging_Time = false;
}
else if (StartTime2 > EndTime2 && (StartTime2 <= current || current < EndTime2))
{
flag_Charging_Time = false;
flag_DisCharging_Time = true;
}
else if (StartTime2 < EndTime2 && (StartTime2 <= current && current < EndTime2))
{
flag_Charging_Time = false;
flag_DisCharging_Time = true;
}
else
{
flag_Charging_Time = false;
flag_DisCharging_Time = false;
}
}
public void Set_Scheduler_Setting(TimeSpan StartTime1, TimeSpan EndTime1, TimeSpan StartTime2, TimeSpan EndTime2)
{
for (int i = 0; i < 24; i++)
{
TimeSpan tempTime = new TimeSpan(i, 0, 0);
if (StartTime1 > EndTime1 && (StartTime1 <= tempTime || tempTime < EndTime1))
{
//충전시간이다
Repository.Instance.scheduler[i] = 1;
}
else if (StartTime1 < EndTime1 && (StartTime1 <= tempTime && tempTime < EndTime1))
{
// 충전시간이다
Repository.Instance.scheduler[i] = 1;
}
else if (StartTime2 > EndTime2 && (StartTime2 <= tempTime || tempTime < EndTime2))
{
Repository.Instance.scheduler[i] = 2;
}
else if (StartTime2 < EndTime2 && (StartTime2 <= tempTime && tempTime < EndTime2))
{
Repository.Instance.scheduler[i] = 2;
}
else
{
Repository.Instance.scheduler[i] = 0;
}
}
}
private void Set_Current_PCS_Operating_Mode()
{
}
private float Convert_From_MaskedTextBox_To_Single(MaskedTextBox maskedTextBox)
{
string temp;
temp = maskedTextBox.Text.Replace("_", "0");
temp = temp.Trim();
return Convert.ToSingle(temp);
}
private TimeSpan Convert_From_MaskedTextBox_To_TimeSpan(MaskedTextBox maskedTextBox)
{
string temp;
temp = maskedTextBox.Text.Trim();
temp = temp.Replace("시", ":");
temp = temp.Replace("분", "");
TimeSpan time;
if (!TimeSpan.TryParse(temp, out time))
{
MessageBox.Show("올바르지 않은 데이터가 들어갔습니다, 다시 확인해주시길 바랍니다");
}
return time;
}
private void btn_DateTime_Setup_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("rundll32.exe", "shell32.dll,Control_RunDLL TimeDate.cpl");
}
private void btn_Comm_Setup_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("rundll32.exe", "shell32.dll,Control_RunDLL ncpa.cpl");
}
private void btn_Power_Setup_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("rundll32.exe", "shell32.dll,Control_RunDLL powercfg.cpl");
}
private void btn_Language_Setup_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("rundll32.exe", "shell32.dll,Control_RunDLL intl.cpl");
}
private void tb_Power_Prices_Click(object sender, EventArgs e)
{
Calculate_Power_Prices a = new Calculate_Power_Prices();
a.ShowDialog();
}
public void SetPowerPrices(float total_prices)
{
tb_Power_Prices.Text = total_prices.ToString();
}
}
}
<file_sep>using KTE_PMS.Observer;
using System;
using System.Windows.Forms;
namespace KTE_PMS.MIMIC
{
public partial class MeasureViewer : Viewer, IUpdate
{
public MeasureViewer()
{
InitializeComponent();
}
private void Measure_Load(object sender, EventArgs e)
{
}
delegate void CrossThreadSafetySetText(Control ctl, String text);
private void CSafeSetText(Control ctl, String text)
{
/*
* InvokeRequired 속성 (Control.InvokeRequired, MSDN)
* 짧게 말해서, 이 컨트롤이 만들어진 스레드와 현재의 스레드가 달라서
* 컨트롤에서 스레드를 만들어야 하는지를 나타내는 속성입니다.
*
* InvokeRequired 속성의 값이 참이면, 컨트롤에서 스레드를 만들어 텍스트를 변경하고,
* 그렇지 않은 경우에는 그냥 변경해도 아무 오류가 없기 때문에 텍스트를 변경합니다.
*/
if (ctl.InvokeRequired)
ctl.Invoke(new CrossThreadSafetySetText(CSafeSetText), ctl, text);
else
ctl.Text = text;
}
public void ObserverUpdate()
{
ObserverUpdate_BMS_System();
CSafeSetText(lb1, Repository.Instance.samsung_bcs.System_Voltage.ToString() + " " + "V");
CSafeSetText(lb3, Repository.Instance.samsung_bcs.System_SOC.ToString() + " " + "%");
CSafeSetText(lb5, Repository.Instance.samsung_bcs.Rack1.Rack_Voltage.ToString() + " " + "V");
}
private void ObserverUpdate_BMS_System()
{
// BMS : System용 이다
// 값 써주기
CSafeSetText(lb1, Repository.Instance.samsung_bcs.System_Voltage.ToString() + " " + "V");
CSafeSetText(lb3, Repository.Instance.samsung_bcs.System_SOC.ToString() + " " + "%");
CSafeSetText(lb5, Repository.Instance.samsung_bcs.Rack1.Rack_Voltage.ToString() + " " + "V");
CSafeSetText(lb7, Repository.Instance.samsung_bcs.Rack1.String1_Rack_Voltage.ToString() + " " + "V");
CSafeSetText(lb9, Repository.Instance.samsung_bcs.Rack1.String2_Rack_Voltage.ToString() + " " + "V");
CSafeSetText(lb11, Repository.Instance.samsung_bcs.Rack1.String1_Cell_Summation_Voltage.ToString() + " " + "V");
CSafeSetText(lb13, Repository.Instance.samsung_bcs.Rack1.String2_Cell_Summation_Voltage.ToString() + " " + "V");
CSafeSetText(lb15, Repository.Instance.samsung_bcs.Rack1.Rack_Current.ToString() + " " + "A");
CSafeSetText(lb17, Repository.Instance.samsung_bcs.Rack1.String1_Rack_Current.ToString() + " " + "A");
CSafeSetText(lb19, Repository.Instance.samsung_bcs.Rack1.String2_Rack_Current.ToString() + " " + "A");
CSafeSetText(lb21, Repository.Instance.samsung_bcs.Rack1.Rack_Current_Average.ToString() + " " + "A");
CSafeSetText(lb23, Repository.Instance.samsung_bcs.Rack1.Rack_SOC.ToString() + " " + "%");
CSafeSetText(lb22, Repository.Instance.samsung_bcs.Rack1.Rack_SOH.ToString() + " " + "%");
CSafeSetText(lb2, Repository.Instance.samsung_bcs.System_Current.ToString() + " " + "A");
CSafeSetText(lb4, Repository.Instance.samsung_bcs.System_SOH.ToString() + " " + "%");
CSafeSetText(lb6, Repository.Instance.samsung_bcs.System_Mode.ToString());
CSafeSetText(lb8, Repository.Instance.samsung_bcs.System_Max_Voltage.ToString() + " " + "V");
CSafeSetText(lb10, Repository.Instance.samsung_bcs.System_Min_Voltage.ToString() + " " + "V");
CSafeSetText(lb12, Repository.Instance.samsung_bcs.System_Max_Temp.ToString() + " " + "°C");
CSafeSetText(lb14, Repository.Instance.samsung_bcs.System_Min_Temp.ToString() + " " + "°C");
CSafeSetText(lb24, Repository.Instance.samsung_bcs.Discharge_Current_Limit_of_Rack.ToString() + " " + "A");
CSafeSetText(lb25, Repository.Instance.samsung_bcs.Charge_Current_Limit.ToString() + " " + "A");
CSafeSetText(lb26, Repository.Instance.samsung_bcs.Watchdog_Response.ToString());
CSafeSetText(lb27, Repository.Instance.samsung_bcs.System_Heartbit.ToString());
}
private void TBO24_Click(object sender, EventArgs e)
{
}
private void label11_Click(object sender, EventArgs e)
{
}
private void TBO19_Click(object sender, EventArgs e)
{
}
private void btn_Move_To_BMS_System_MouseClick(object sender, MouseEventArgs e)
{
Panel p = (Panel)Parent;
p.Controls.Clear();
p.Controls.Add(Repository.Instance.p_measure);
}
private void btn_Move_To_BMS_Rack_MouseClick(object sender, MouseEventArgs e)
{
Panel p = (Panel)Parent;
p.Controls.Clear();
p.Controls.Add(Repository.Instance.p_measure_BMS_Rack);
}
private void btn_Move_To_PCS_Data_MouseClick(object sender, MouseEventArgs e)
{
Panel p = (Panel)Parent;
p.Controls.Clear();
p.Controls.Add(Repository.Instance.p_measure_PCS);
}
private void btn_Move_To_PCS_Fault_MouseClick(object sender, MouseEventArgs e)
{
Panel p = (Panel)Parent;
p.Controls.Clear();
p.Controls.Add(Repository.Instance.p_measure_PCS_Fault);
}
private void button1_MouseClick(object sender, MouseEventArgs e)
{
Panel p = (Panel)Parent;
p.Controls.Clear();
p.Controls.Add(Repository.Instance.p_measure_PCSV2);
}
}
}
<file_sep>using System;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
namespace KTE_PMS.MIMIC
{
public partial class Viewer : UserControl
{
public Viewer()
{
InitializeComponent();
}
}
}
|
c3485fcfbb4a69a0dfad7e4e8e016a0bef410195
|
[
"C#"
] | 40
|
C#
|
superinchur/KTE_PMS_V3
|
723713420b6bab19798a5301df4d03d414843a81
|
fa6c99346bb56b8fc23eb9a565f24c641f14554b
|
refs/heads/master
|
<repo_name>AlineDominique/API_IHC<file_sep>/disciplina.php
<?php
function ListaDisciplinas($id){
include("conectar.php");
$resposta = array();
$id = mysqli_real_escape_string($conexao,$id);
//Consulta Disciplina no banco
if($id == 0){
$query = mysqli_query($conexao,"SELECT idDisciplina, Nome FROM Disciplina ORDER BY Nome ASC") or die(mysqli_error($conexao));
}else{
$query = mysqli_query($conexao,"SELECT idDisciplina, Nome FROM Disciplina WHERE idDisciplina = " .$id . " ORDER BY Nome ASC") or die(mysqli_error($conexao));
}
//faz um looping e cria um array com os campos da consulta
while($dados = mysqli_fetch_array($query))
{
$resposta[] = array('idDisciplina' => $dados['idDisciplina'],
'Nome' => $dados['Nome']);
}
return $resposta;
}
function InsereDisciplina(){
//Recupera conteudo recebido na request
$conteudo = file_get_contents("php://input");
$resposta = array();
//Verifica se o conteudo foi recebido
if(empty($conteudo)){
$resposta = mensagens(2);
}
else{
//Converte o json recebido pra array
$dados = json_decode($conteudo,true);
//Verifica se as infromações esperadas foram recebidas
if(!isset($dados["Nome"]))
{
$resposta = mensagens(3);
}
else{
include("conectar.php");
//Evita SQL injection
$Nome = mysqli_real_escape_string($conexao,$dados["Nome"]);
//Recupera idDisciplina para incrementar 1
$idDisciplina = 0;
$query = mysqli_query($conexao, "SELECT idDisciplina FROM Disciplina ORDER BY idDisciplina DESC LIMIT 1") or die(mysqli_error($conexao));
while($dados = mysqli_fetch_array($query)){
$idDisciplina = $dados["idDisciplina"];
}
$idDisciplina++;
//Insere Disciplina
$query = mysqli_query($conexao,"INSERT INTO Disciplina VALUES(" .$idDisciplina .",'" .$Nome ."')") or die(mysqli_error($conexao));
$resposta = mensagens(4);
}
}
return $resposta;
}
function AtualizaDisciplina($id){
//Recupera conteudo recebido na request
$conteudo = file_get_contents("php://input");
$resposta = array();
//Verifica se o id foi recebido
if($id == 0){
$resposta = mensagens(5);
}
else{
//Verifica se o conteudo foi recebido
if(empty($conteudo)){
$resposta = mensagens(2);
}
else{
//Converte o json recebido pra array
$dados = json_decode($conteudo,true);
//Verifica se as infromações esperadas foram recebidas
if(!isset($dados["Nome"]))
{
$resposta = mensagens(3);
}
else
{
include("conectar.php");
//Evita SQL injection
$Nome = mysqli_real_escape_string($conexao,$dados["Nome"]);
$update = "UPDATE Disciplina SET Nome = '" .$Nome ."' WHERE idDisciplina = ".$id;
//Atualiza Professor no banco
$query = mysqli_query($conexao, $update) or die(mysqli_error($conexao));
$resposta = mensagens(6);
}
}
}
return $resposta;
}
function ExcluiDisciplina($id){
//Recupera conteudo recebido na request
$resposta = array();
//Verifica se o id foi recebido
if($id == 0){
$resposta = mensagens(5);
}
else{
include("conectar.php");
//Evita SQL injection
$id = mysqli_real_escape_string($conexao,$id);
//Exclui Professor
$query = mysqli_query($conexao, "DELETE FROM Disciplina WHERE idDisciplina=" .$id) or die(mysqli_error($conexao));
$resposta = mensagens(7);
}
return $resposta;
}
?><file_sep>/README.md
# API_IHC
API em php de requisições dos bancos de dados para um aplicação de agendamento de laboratórios da faculdade.
<file_sep>/index.php
<?php
//Inclui arquivos com as funções da API.
include('mensagem.php');
include('professor.php');
include('disciplina.php');
include('sala.php');
include('aula.php');
//Recupera os valores da URL
$metodo = $_SERVER['REQUEST_METHOD'];
$caminho = $_SERVER['PATH_INFO'];
$array = explode("/",$caminho);
$funcao = $array[1];
$id = 0;
if(isset($array[2])){
$id = $array[2];
}
$resposta = array();
//Verifica se o método utilizado na request é POST
if($metodo == "POST"){
//Verifica se a função informada existe.
if(function_exists($funcao)){
//Chama função.
$resposta = $funcao($id);
}
else{
//Caso a função nao exista retorna erro.
$resposta = mensagens(1);
}
}
else
{
$resposta = mensagens(1);
}
//Retorna a resposta
header('Content-Type: application/json; charset=utf-8');
echo json_encode($resposta);
?><file_sep>/aula.php
<?php
function ListaAulasPorProfessor($id){
include("conectar.php");
$resposta = array();
$id = mysqli_real_escape_string($conexao,$id);
//Consulta Aula no banco
if($id == 0){
$query = mysqli_query($conexao,"SELECT a.idAula, a.Dia, a.HoraInicio, a.HoraFim, a.Semestre, b.idDisciplina, b.Nome as 'Disciplina', c.idProfessor, c.Nome as 'Professor', d.idSala, d.Numero as 'Sala' FROM Aula as a INNER JOIN Disciplina as b on a.idDisciplina = b.idDisciplina INNER JOIN Professor as c on a.idProfessor = c.idProfessor INNER JOIN Sala as d on a.idSala = d.idSala ORDER BY a.Dia, Professor ASC") or die(mysqli_error($conexao));
}else{
$query = mysqli_query($conexao,"SELECT a.idAula, a.Dia, a.HoraInicio, a.HoraFim, a.Semestre, b.idDisciplina, b.Nome as 'Disciplina', c.idProfessor, c.Nome as 'Professor', d.idSala, d.Numero as 'Sala' FROM Aula as a INNER JOIN Disciplina as b on a.idDisciplina = b.idDisciplina INNER JOIN Professor as c on a.idProfessor = c.idProfessor INNER JOIN Sala as d on a.idSala = d.idSala WHERE c.idProfessor = " .$id ." ORDER BY a.Dia, Professor ASC") or die(mysqli_error($conexao));
}
//faz um looping e cria um array com os campos da consulta
while($dados = mysqli_fetch_array($query))
{
$resposta[] = array('idAula' => $dados['idAula'],
'Dia' => $dados['Dia'],
'HoraInicio' => $dados['HoraInicio'],
'HoraFim' => $dados['HoraFim'],
'Semestre' => $dados['Semestre'],
'idDisciplina' => $dados['idDisciplina'],
'Disciplina' => $dados['Disciplina'],
'idProfessor' => $dados['idProfessor'],
'Professor' => $dados['Professor'],
'idSala' => $dados['idSala'],
'Sala' => $dados['Sala']);
}
return $resposta;
}
function ListaAulasPorSala($id){
include("conectar.php");
$resposta = array();
$id = mysqli_real_escape_string($conexao,$id);
//Consulta Aula no banco
if($id == 0){
$query = mysqli_query($conexao,"SELECT a.idAula, a.Dia, a.HoraInicio, a.HoraFim, a.Semestre, b.idDisciplina, b.Nome as 'Disciplina', c.idProfessor, c.Nome as 'Professor', d.idSala, d.Numero as 'Sala' FROM Aula as a INNER JOIN Disciplina as b on a.idDisciplina = b.idDisciplina INNER JOIN Professor as c on a.idProfessor = c.idProfessor INNER JOIN Sala as d on a.idSala = d.idSala ORDER BY a.Dia, Sala ASC") or die(mysqli_error($conexao));
}else{
$query = mysqli_query($conexao,"SELECT a.idAula, a.Dia, a.HoraInicio, a.HoraFim, a.Semestre, b.idDisciplina, b.Nome as 'Disciplina', c.idProfessor, c.Nome as 'Professor', d.idSala, d.Numero as 'Sala' FROM Aula as a INNER JOIN Disciplina as b on a.idDisciplina = b.idDisciplina INNER JOIN Professor as c on a.idProfessor = c.idProfessor INNER JOIN Sala as d on a.idSala = d.idSala WHERE d.idSala = " .$id ." ORDER BY a.Dia, Sala ASC") or die(mysqli_error($conexao));
}
//faz um looping e cria um array com os campos da consulta
while($dados = mysqli_fetch_array($query))
{
$resposta[] = array('idAula' => $dados['idAula'],
'Dia' => $dados['Dia'],
'HoraInicio' => $dados['HoraInicio'],
'HoraFim' => $dados['HoraFim'],
'Semestre' => $dados['Semestre'],
'idDisciplina' => $dados['idDisciplina'],
'Disciplina' => $dados['Disciplina'],
'idProfessor' => $dados['idProfessor'],
'Professor' => $dados['Professor'],
'idSala' => $dados['idSala'],
'Sala' => $dados['Sala']);
}
return $resposta;
}
function PesquisaAulaPorSala(){
//Recupera conteudo recebido na request
$conteudo = file_get_contents("php://input");
$resposta = array();
//Verifica se o conteudo foi recebido
if(empty($conteudo)){
$resposta = mensagens(2);
}
else{
//Converte o json recebido pra array
$dados = json_decode($conteudo,true);
//Verifica se as infromações esperadas foram recebidas
if(!isset($dados["Numero"]) || !isset($dados["Dia"]))
{
$resposta = mensagens(3);
}
else{
include("conectar.php");
//Evita SQL injection
$Numero = mysqli_real_escape_string($conexao,$dados["Numero"]);
$Dia = mysqli_real_escape_string($conexao,$dados["Dia"]);
//Consulta Aula no banco
$query = mysqli_query($conexao,"SELECT a.idAula, a.Dia, a.HoraInicio, a.HoraFim, a.Semestre, b.idDisciplina, b.Nome as 'Disciplina', c.idProfessor, c.Nome as 'Professor', d.idSala, d.Numero as 'Sala' FROM Aula as a INNER JOIN Disciplina as b on a.idDisciplina = b.idDisciplina INNER JOIN Professor as c on a.idProfessor = c.idProfessor INNER JOIN Sala as d on a.idSala = d.idSala WHERE d.Numero = '" .$Numero ."' AND a.Dia = '" .$Dia ."' ORDER BY a.Dia, Sala ASC") or die(mysqli_error($conexao));
//faz um looping e cria um array com os campos da consulta
while($dados = mysqli_fetch_array($query))
{
$resposta[] = array('idAula' => $dados['idAula'],
'Dia' => $dados['Dia'],
'HoraInicio' => $dados['HoraInicio'],
'HoraFim' => $dados['HoraFim'],
'Semestre' => $dados['Semestre'],
'idDisciplina' => $dados['idDisciplina'],
'Disciplina' => $dados['Disciplina'],
'idProfessor' => $dados['idProfessor'],
'Professor' => $dados['Professor'],
'idSala' => $dados['idSala'],
'Sala' => $dados['Sala']);
}
return $resposta;
}
}
}
function PesquisaAulaPorProfessor(){
//Recupera conteudo recebido na request
$conteudo = file_get_contents("php://input");
$resposta = array();
//Verifica se o conteudo foi recebido
if(empty($conteudo)){
$resposta = mensagens(2);
}
else{
//Converte o json recebido pra array
$dados = json_decode($conteudo,true);
//Verifica se as infromações esperadas foram recebidas
if(!isset($dados["Nome"]) || !isset($dados["Dia"]))
{
$resposta = mensagens(3);
}
else{
include("conectar.php");
//Evita SQL injection
$Nome = mysqli_real_escape_string($conexao,$dados["Nome"]);
$Dia = mysqli_real_escape_string($conexao,$dados["Dia"]);
//Consulta Aula no banco
$query = mysqli_query($conexao,"SELECT a.idAula, a.Dia, a.HoraInicio, a.HoraFim, a.Semestre, b.idDisciplina, b.Nome as 'Disciplina', c.idProfessor, c.Nome as 'Professor', d.idSala, d.Numero as 'Sala' FROM Aula as a INNER JOIN Disciplina as b on a.idDisciplina = b.idDisciplina INNER JOIN Professor as c on a.idProfessor = c.idProfessor INNER JOIN Sala as d on a.idSala = d.idSala WHERE c.Nome = '" .$Nome ."' AND a.Dia = '" .$Dia ."' ORDER BY a.Dia, Sala ASC") or die(mysqli_error($conexao));
//faz um looping e cria um array com os campos da consulta
while($dados = mysqli_fetch_array($query))
{
$resposta[] = array('idAula' => $dados['idAula'],
'Dia' => $dados['Dia'],
'HoraInicio' => $dados['HoraInicio'],
'HoraFim' => $dados['HoraFim'],
'Semestre' => $dados['Semestre'],
'idDisciplina' => $dados['idDisciplina'],
'Disciplina' => $dados['Disciplina'],
'idProfessor' => $dados['idProfessor'],
'Professor' => $dados['Professor'],
'idSala' => $dados['idSala'],
'Sala' => $dados['Sala']);
}
return $resposta;
}
}
}
function InsereAula(){
//Recupera conteudo recebido na request
$conteudo = file_get_contents("php://input");
$resposta = array();
//Verifica se o conteudo foi recebido
if(empty($conteudo)){
$resposta = mensagens(2);
}
else{
//Converte o json recebido pra array
$dados = json_decode($conteudo,true);
//Verifica se as infromações esperadas foram recebidas
if(!isset($dados["Dia"]) || !isset($dados["HoraInicio"]) || !isset($dados["HoraFim"]) ||
!isset($dados["Semestre"]) || !isset($dados["idDisciplina"]) || !isset($dados["idProfessor"]) ||
!isset($dados["idSala"]))
{
$resposta = mensagens(3);
}
else{
include("conectar.php");
//Evita SQL injection
$Dia = mysqli_real_escape_string($conexao,$dados["Dia"]);
$HoraInicio = mysqli_real_escape_string($conexao,$dados["HoraInicio"]);
$HoraFim = mysqli_real_escape_string($conexao,$dados["HoraFim"]);
$Semestre = mysqli_real_escape_string($conexao,$dados["Semestre"]);
$idDisciplina = mysqli_real_escape_string($conexao,$dados["idDisciplina"]);
$idProfessor = mysqli_real_escape_string($conexao,$dados["idProfessor"]);
$idSala = mysqli_real_escape_string($conexao,$dados["idSala"]);
//Recupera idAula para incrementar 1
$idAula = 0;
$query = mysqli_query($conexao, "SELECT idAula FROM Aula ORDER BY idAula DESC LIMIT 1") or die(mysqli_error($conexao));
while($dados = mysqli_fetch_array($query)){
$idAula = $dados["idAula"];
}
$idAula++;
//Insere Aula
$query = mysqli_query($conexao,"INSERT INTO Aula VALUES(" .$idAula .",'" .$Dia ."','" .$HoraInicio ."','" .$HoraFim ."'," .$Semestre ."," .$idDisciplina ."," .$idProfessor ."," .$idSala .")") or die(mysqli_error($conexao));
$resposta = mensagens(4);
}
}
return $resposta;
}
function AtualizaAula($id){
//Recupera conteudo recebido na request
$conteudo = file_get_contents("php://input");
$resposta = array();
//Verifica se o id foi recebido
if($id == 0){
$resposta = mensagens(5);
}
else{
//Verifica se o conteudo foi recebido
if(empty($conteudo)){
$resposta = mensagens(2);
}
else{
//Converte o json recebido pra array
$dados = json_decode($conteudo,true);
//Verifica se as informações esperadas foram recebidas
if(!isset($dados["Dia"]) || !isset($dados["HoraInicio"]) || !isset($dados["HoraFim"]) ||
!isset($dados["Semestre"]) || !isset($dados["idDisciplina"]) || !isset($dados["idProfessor"]) ||
!isset($dados["idSala"]))
{
$resposta = mensagens(3);
}
else
{
include("conectar.php");
//Evita SQL injection
$Dia = mysqli_real_escape_string($conexao,$dados["Dia"]);
$HoraInicio = mysqli_real_escape_string($conexao,$dados["HoraInicio"]);
$HoraFim = mysqli_real_escape_string($conexao,$dados["HoraFim"]);
$Semestre = mysqli_real_escape_string($conexao,$dados["Semestre"]);
$idDisciplina = mysqli_real_escape_string($conexao,$dados["idDisciplina"]);
$idProfessor = mysqli_real_escape_string($conexao,$dados["idProfessor"]);
$idSala = mysqli_real_escape_string($conexao,$dados["idSala"]);
$update = "UPDATE Aula SET Dia = '" .$Dia ."', HoraInicio = '" .$HoraInicio ."', HoraFim = '" .$HoraFim ."', Semestre = " .$Semestre .", idDisciplina = " .$idDisciplina .", idProfessor = " .$idProfessor .", idSala = " .$idSala ." WHERE idAula = ".$id;
//Atualiza Aula no banco
$query = mysqli_query($conexao, $update) or die(mysqli_error($conexao));
$resposta = mensagens(6);
}
}
}
return $resposta;
}
function ExcluiAula($id){
//Recupera conteudo recebido na request
$resposta = array();
//Verifica se o id foi recebido
if($id == 0){
$resposta = mensagens(5);
}
else{
include("conectar.php");
//Evita SQL injection
$id = mysqli_real_escape_string($conexao,$id);
//Exclui Professor
$query = mysqli_query($conexao, "DELETE FROM Aula WHERE idAula=" .$id) or die(mysqli_error($conexao));
$resposta = mensagens(7);
}
return $resposta;
}
?><file_sep>/mensagem.php
<?php
function mensagens($codigo){
$mensagens = array(
array(
"Codigo"=>1
,"Mensagem"=>"Caminho especificado nao encontrado"
)
,array(
"Codigo"=>2
,"Mensagem"=>"Nenhum dado recebido"
)
,array(
"Codigo"=>3
,"Mensagem"=>"Estrutura de dados diferente do esperado"
)
,array(
"Codigo"=>4
,"Mensagem"=>"Inserido com sucesso!"
)
,array(
"Codigo"=>5
,"Mensagem"=>"Código inválido"
)
,array(
"Codigo"=>6
,"Mensagem"=>"Atualizado com sucesso"
)
,array(
"Codigo"=>7
,"Mensagem"=>"Excluído com sucesso"
)
);
$retorno = array();
//Busca pelo erro com o codigo informado de parâmetro
foreach($mensagens as $item){
if($item["Codigo"] == $codigo){
$retorno = $item;
break;
}
}
return $retorno;
}
?><file_sep>/conectar.php
<?php
$ServerBD = $_SERVER['SERVER_NAME'];
if(!isset($PortaBD)){
$conexao = mysqli_connect($ServerBD, "root", "");
}else{
$conexao = mysqli_connect($ServerBD .":" .$PortaBD, "root", "");
}
//$conect = mysqli_connect('localhost', "root", "");
// Caso a conexão seja reprovada, exibe na tela uma mensagem de erro
if (!$conexao) die ('<div id="erro2">Falha na coneco com o Banco de Dados!</div>');
// Caso a conexão seja aprovada, então conecta o Banco de Dados.
$db = mysqli_select_db($conexao,"BDHorarioAula");
?><file_sep>/professor.php
<?php
function ListaProfessores($id){
include("conectar.php");
$resposta = array();
$id = mysqli_real_escape_string($conexao,$id);
//Consulta Professores no banco
if($id == 0){
$query = mysqli_query($conexao,"SELECT idProfessor, Nome FROM Professor ORDER BY Nome ASC") or die(mysqli_error($conexao));
}else{
$query = mysqli_query($conexao,"SELECT idProfessor, Nome FROM Professor WHERE idProfessor = " .$id . " ORDER BY Nome ASC") or die(mysqli_error($conexao));
}
//faz um looping e cria um array com os campos da consulta
while($dados = mysqli_fetch_array($query))
{
$resposta[] = array('idProfessor' => $dados['idProfessor'],
'Nome' => $dados['Nome']);
}
return $resposta;
}
function InsereProfessor(){
//Recupera conteudo recebido na request
$conteudo = file_get_contents("php://input");
$resposta = array();
//Verifica se o conteudo foi recebido
if(empty($conteudo)){
$resposta = mensagens(2);
}
else{
//Converte o json recebido pra array
$dados = json_decode($conteudo,true);
//Verifica se as infromações esperadas foram recebidas
if(!isset($dados["Nome"]))
{
$resposta = mensagens(3);
}
else{
include("conectar.php");
//Evita SQL injection
$Nome = mysqli_real_escape_string($conexao,$dados["Nome"]);
//Recupera idProfessor para incrementar 1
$idProfessor = 0;
$query = mysqli_query($conexao, "SELECT idProfessor FROM Professor ORDER BY idProfessor DESC LIMIT 1") or die(mysqli_error($conexao));
while($dados = mysqli_fetch_array($query)){
$idProfessor = $dados["idProfessor"];
}
$idProfessor++;
//Insere Professor
$query = mysqli_query($conexao,"INSERT INTO Professor VALUES(" .$idProfessor .",'" .$Nome ."')") or die(mysqli_error($conexao));
$resposta = mensagens(4);
}
}
return $resposta;
}
function AtualizaProfessor($id){
//Recupera conteudo recebido na request
$conteudo = file_get_contents("php://input");
$resposta = array();
//Verifica se o id foi recebido
if($id == 0){
$resposta = mensagens(5);
}
else{
//Verifica se o conteudo foi recebido
if(empty($conteudo)){
$resposta = mensagens(2);
}
else{
//Converte o json recebido pra array
$dados = json_decode($conteudo,true);
//Verifica se as infromações esperadas foram recebidas
if(!isset($dados["Nome"]))
{
$resposta = mensagens(3);
}
else
{
include("conectar.php");
//Evita SQL injection
$Nome = mysqli_real_escape_string($conexao,$dados["Nome"]);
$update = "UPDATE Professor SET Nome = '" .$Nome ."' WHERE idProfessor = ".$id;
//Atualiza Professor no banco
$query = mysqli_query($conexao, $update) or die(mysqli_error($conexao));
$resposta = mensagens(6);
}
}
}
return $resposta;
}
function ExcluiProfessor($id){
//Recupera conteudo recebido na request
$resposta = array();
//Verifica se o id foi recebido
if($id == 0){
$resposta = mensagens(5);
}
else{
include("conectar.php");
//Evita SQL injection
$id = mysqli_real_escape_string($conexao,$id);
//Exclui Professor
$query = mysqli_query($conexao, "DELETE FROM Professor WHERE idProfessor=" .$id) or die(mysqli_error($conexao));
$resposta = mensagens(7);
}
return $resposta;
}
?>
<file_sep>/sala.php
<?php
function ListaSalas($id){
include("conectar.php");
$resposta = array();
$id = mysqli_real_escape_string($conexao,$id);
//Consulta Sala no banco
if($id == 0){
$query = mysqli_query($conexao,"SELECT idSala, Numero FROM Sala ORDER BY Numero ASC") or die(mysqli_error($conexao));
}else{
$query = mysqli_query($conexao,"SELECT idSala, Numero FROM Sala WHERE idSala = " .$id . " ORDER BY Numero ASC") or die(mysqli_error($conexao));
}
//faz um looping e cria um array com os campos da consulta
while($dados = mysqli_fetch_array($query))
{
$resposta[] = array('idSala' => $dados['idSala'],
'Numero' => $dados['Numero']);
}
return $resposta;
}
function InsereSala(){
//Recupera conteudo recebido na request
$conteudo = file_get_contents("php://input");
$resposta = array();
//Verifica se o conteudo foi recebido
if(empty($conteudo)){
$resposta = mensagens(2);
}
else{
//Converte o json recebido pra array
$dados = json_decode($conteudo,true);
//Verifica se as infromações esperadas foram recebidas
if(!isset($dados["Numero"]))
{
$resposta = mensagens(3);
}
else{
include("conectar.php");
//Evita SQL injection
$Numero = mysqli_real_escape_string($conexao,$dados["Numero"]);
//Recupera idSala para incrementar 1
$idSala = 0;
$query = mysqli_query($conexao, "SELECT idSala FROM Sala ORDER BY idSala DESC LIMIT 1") or die(mysqli_error($conexao));
while($dados = mysqli_fetch_array($query)){
$idSala = $dados["idSala"];
}
$idSala++;
//Insere Sala
$query = mysqli_query($conexao,"INSERT INTO Sala VALUES(" .$idSala .",'" .$Numero ."')") or die(mysqli_error($conexao));
$resposta = mensagens(4);
}
}
return $resposta;
}
function AtualizaSala($id){
//Recupera conteudo recebido na request
$conteudo = file_get_contents("php://input");
$resposta = array();
//Verifica se o id foi recebido
if($id == 0){
$resposta = mensagens(5);
}
else{
//Verifica se o conteudo foi recebido
if(empty($conteudo)){
$resposta = mensagens(2);
}
else{
//Converte o json recebido pra array
$dados = json_decode($conteudo,true);
//Verifica se as infromações esperadas foram recebidas
if(!isset($dados["Numero"]))
{
$resposta = mensagens(3);
}
else
{
include("conectar.php");
//Evita SQL injection
$Numero = mysqli_real_escape_string($conexao,$dados["Numero"]);
$update = "UPDATE Sala SET Numero = '" .$Numero ."' WHERE idSala = ".$id;
//Atualiza Professor no banco
$query = mysqli_query($conexao, $update) or die(mysqli_error($conexao));
$resposta = mensagens(6);
}
}
}
return $resposta;
}
function ExcluiSala($id){
//Recupera conteudo recebido na request
$resposta = array();
//Verifica se o id foi recebido
if($id == 0){
$resposta = mensagens(5);
}
else{
include("conectar.php");
//Evita SQL injection
$id = mysqli_real_escape_string($conexao,$id);
//Exclui Sala
$query = mysqli_query($conexao, "DELETE FROM Sala WHERE idSala=" .$id) or die(mysqli_error($conexao));
$resposta = mensagens(7);
}
return $resposta;
}
?>
|
3fe7e410d0d7ec82f1d34097840a506f87a424a3
|
[
"Markdown",
"PHP"
] | 8
|
PHP
|
AlineDominique/API_IHC
|
00e0c4e741aa390bdfe024100869df1a71ce4b49
|
a22de6f23db631e8dc3ead6e525d7d1f7a5d7473
|
refs/heads/master
|
<repo_name>hzyzhdmz/demo1<file_sep>/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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>demo</groupId>
<artifactId>demo-1</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>demo-1 Maven Webapp</name>
<url>http://maven.apache.org</url>
<!--<repository>-->
<!--<id>jsi.sourceforge.net</id>-->
<!--<name>sourceforge jsi repository</name>-->
<!--<url>http://sourceforge.net/projects/jsi/files/m2_repo</url>-->
<!--</repository>-->
<dependencies>
<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1201-jdbc41</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.hbase/hbase-client -->
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>1.2.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>demo-1</finalName>
</build>
</project>
<file_sep>/src/main/FileTest.java
package main;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Administrator on 2017/3/14 0014.
*/
public class FileTest {
public static void main(String[] args) {
String path = "F:\\Traj_10000.txt";
StringBuffer lines = null;
Map<String,StringBuffer> map = new HashMap<String, StringBuffer>();
Map<String,Integer> map_num = new HashMap<String, Integer>();
try {
File file = new File(path);
InputStreamReader reader = new InputStreamReader(
new FileInputStream(file));
BufferedReader br = new BufferedReader(reader); // 建立一个对象,它把文件内容转成计算机能读懂的语言
String [] line_arr ;
String line ;
while ((line =br.readLine())!= null) {
line_arr= line.split(",");
String car_id = line_arr[0];
String newstr = null;
System.out.println("("+line_arr[5]+line_arr[9]+" "+line_arr[1]+")");
if(map.containsKey(car_id)) {
if(map_num.get(car_id)%2==0){
newstr = "("+line_arr[5]+line_arr[9]+" "+line_arr[1]+",";
lines = map.get(car_id).append(newstr);
} else {
newstr =line_arr[5]+line_arr[9]+" "+line_arr[1]+"),";
lines = map.get(car_id).append(newstr);
}
int j = map_num.get(car_id)+1;
map.put(car_id,lines);
map_num.put(car_id,j);
} else {
lines = new StringBuffer("\"MULTILINESTRING (");
newstr = "("+line_arr[5]+line_arr[9]+" "+line_arr[1]+",";
lines = lines.append(newstr);
map.put(car_id,lines);
map_num.put(car_id,1);
}
}
List<String> num1 = new ArrayList<String>(); /* 存储数据中只有一个轨迹记录点的车的集合*/
for(Map.Entry<String, StringBuffer> entry : map.entrySet()) {
StringBuffer rep = new StringBuffer(entry.getValue());
System.out.println(entry.getKey());
System.out.println(map_num.get(entry.getKey()));
int i = map_num.get(entry.getKey());
if (i==1) {
num1.add(entry.getKey()); /*将数据中只有一个轨迹点的车辆的id放入集合*/
continue;
}
if(i%2==0) {
rep.setCharAt(rep.length()-1,')');
rep.append("\"");
map.put(entry.getKey(),rep);
} else {
// System.out.println(map_num.get("1046529"));
int n = rep.lastIndexOf(")");
rep.deleteCharAt(n);
n = rep.lastIndexOf("(");
rep.deleteCharAt(n);
rep.setCharAt(rep.length()-1,')');
rep.append(")\"");
map.put(entry.getKey(),rep);
}
}
for(String numm:num1) {
map.remove(numm); //删除map中存储的轨迹只有一个点的数据
}
File outfile = new File("D:/OUT3.txt");
FileOutputStream fop = new FileOutputStream(outfile);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fop));
for(Map.Entry<String, StringBuffer> entry : map.entrySet()) {
StringBuffer outline = entry.getValue();
String yyy = outline.toString();
bw.write(yyy);
bw.newLine();
}
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
<file_sep>/README.md
# demo1 毕业设计相关
<file_sep>/src/main/FileCreate.java
package main;
import java.io.*;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Created by Administrator on 2017/3/20 0020.
*/
public class FileCreate {
public static void main(String[] args) {
String path = "F:\\ShenZhen_FCD_MM_100.txt";
//StringBuffer lines = null;
Map<Integer,String> map = new LinkedHashMap<Integer, String>();
int i = 1;
try {
File file = new File(path);
InputStreamReader reader = new InputStreamReader(
new FileInputStream(file));
BufferedReader br = new BufferedReader(reader); // 建立一个对象,它把文件内容转成计算机能读懂的语言
String line ;
while ((line =br.readLine())!= null) {
line = ","+line;
map.put(i++,line);
}
File outfile = new File("D:/OUT1.txt");
FileOutputStream fop = new FileOutputStream(outfile);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fop));
for(Map.Entry<Integer, String> entry : map.entrySet()) {
String outline = entry.getValue();
// byte[] contentInBytes = outline.toString().getBytes();
String yyy = entry.getKey().toString()+outline;
bw.write(yyy);
bw.newLine();
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
a862c172469642603f80957cf5e9393c08627360
|
[
"Markdown",
"Java",
"Maven POM"
] | 4
|
Maven POM
|
hzyzhdmz/demo1
|
9b15f8df93c0fd509e32566caf3f4e423d123db4
|
20d6dbd69ac9675d4733a12ceb8923a5212de8fb
|
refs/heads/master
|
<file_sep>gumoniter
===
GPU user moniter, a collection of python scripts to collect gpu usages
Environment Setup
---
- This script runs on admin node, slave nodes should have `gpustat` installed.
```bash
pip install gpustat
```
- slave nodes must be able to ssh without password, it can be achieved by `ssh-key-copy`
Configure
---
This script can be configured in file 'config'.
- `interval`: collects data for every *interval* minutes
- `hosts`: a list of hostname or ip_address (`ssh`able)
- `log_path`: log files path. One file for one day.
Architecture
---
- moniter.py: a data collector that queries GPUs and processes information from nodes.
- report.py: a post-process script that compute and report the desired metrics from collected data.
<file_sep>"""Process the log file to get statistics for every user in cluster
This is file serves as an example getting the overall GPU usages for user
"""
import json
filename = './logs/all.log'
class OverallReporter(object):
"""A reporter class
Properties:
- filename: log file to load
- interval: log file interval
- user2usage: a dictionary from user to usage
"""
def __init__(self, filename):
self.filename = filename
self.interval = 600
self.user2usage = {}
self.process()
def process(self):
"""Process the log file line by line
One line in log is a timeslot defined before
"""
for line in open(self.filename, 'r'):
data = json.loads(line)
self.add_timeslot(data)
def add_timeslot(self, data):
"""Process one timeslot
The data in one timeslot consists of multi-machines,
each has multi-gpus, gpu has multi-tasks"""
machines = data['data']
for machine in machines:
gpus = machine['gpus']
for gpu in gpus:
tasks = gpu['processes']
utilization = int(gpu['utilization.gpu'])
for task in tasks:
user = task['user']
memory = task['used_memory']
self.add_usage(user, utilization)
def add_usage(self, user, utilization):
if user not in self.user2usage:
self.user2usage[user] = []
self.user2usage[user].append(utilization)
def report_occupy(self):
"""report the usages for user sorted by overall usages"""
time_occupy = {}
for k,v in self.user2usage.iteritems():
time_occupy[k] = len(v)
print('-'*89)
print('User\t-->\tGPU*minutes')
for user, time in sorted(time_occupy.items(), key=lambda x:x[1], reverse=True):
print('%s\t-->\t%d' % (user, time*10))
print('-'*89)
def report_avg_util(self):
"""report the average gpu utilization among users"""
avg_util = {}
for k,v in self.user2usage.iteritems():
avg_util[k] = sum(v) / len(v)
print('-'*89)
print('User\t-->\tutils')
for user, util in sorted(avg_util.items(), key=lambda x:x[1], reverse=True):
print('%s\t-->\t%d' % (user, util))
print('-'*89)
reporter = OverallReporter(filename=filename)
reporter.report_occupy()
reporter.report_avg_util()
<file_sep>#!/usr/bin/env python
# encoding: utf-8
import configargparse
import subprocess
import json
from datetime import datetime
import time
import sys
import os
def get_gpu_stat(hostname):
try:
cmd_args = ['ssh', hostname, 'gpustat', '--json']
result = subprocess.check_output(cmd_args)
return result
except subprocess.CalledProcessError as e:
return None
if __name__ == '__main__':
parser = configargparse.ArgParser(default_config_files=['./config'])
parser.add('-c', required=False, is_config_file=True)
parser.add('--hosts', action='append')
parser.add('--interval', type=int)
parser.add('--log_path')
args = parser.parse_args()
if not os.path.exists(args.log_path):
os.makedirs(args.log_path)
while True:
try:
now = datetime.now()
date = str(now).split()[0]
results = []
print(str(now))
for hostname in args.hosts:
result = get_gpu_stat(hostname)
if result is not None:
result = json.loads(result)
results.append(result)
print('get result from {}'.format(hostname))
else:
print('get error from {}'.format(hostname))
print '=' * 89
output_json = {'time': str(now), 'data': results}
with open(args.log_path + '/' + date + '.log', 'a') as f:
f.write(json.dumps(output_json) + '\n')
sys.stdout.flush()
time.sleep(args.interval)
except KeyboardInterrupt:
print('-' * 89)
print('Exiting from keyboard interrupt')
break
|
9adddd1dc4dba30add6a92f3c6c0c896977341c9
|
[
"Markdown",
"Python"
] | 3
|
Markdown
|
Stonesjtu/gumoniter
|
01e20f034b4ada6423495779db0e83fa990acc6b
|
e35760ae66f349f492606ef82153c9730632bb5c
|
refs/heads/master
|
<repo_name>LandenStephenss/K4<file_sep>/src/cmds/about.js
const { Discord, RichEmbed } = require('discord.js')
const { EmbedColor } = require('../settings.json');
exports.run = (client, message, paramaters) => {
const AboutMe = new RichEmbed()
.setTitle('About Me!')
.addField('General Usage', `You can use **${client.prefix.get(message.guild.id).prefix}help** to view all of my commands. k³ is based off of permissions instead of roles, so to use ban for example you must have the **BAN_MEMBERS** permission.`)
.addField('Features', '- Moderation Commands\n- Informational Commands\m- Utility Commands\n- Leveling/Currency System\n- Per-Server Configuration')
.setFooter('Version: V4')
.setColor(EmbedColor)
message.channel.send(AboutMe)
}
exports.info = {
name: 'about',
category: 'information',
aliases: [],
usage: 'about',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/src/cmds/rps.js
const { Discord, RichEmbed } = require('discord.js')
const { EmbedColor } = require('../settings.json');
exports.run = (client, message, paramaters) => {
const choices = ["paper", "rock", "scissors"]
const choice = paramaters[0]
const botChoice = choices[Math.floor(Math.random() * choices.length)]
const key = `${message.author.id}`;
client.RPSWins.ensure(`${message.author.id}`, {
user: message.author.id,
rpsWins: 0
});
function rps(input, botInput) {
if(input === botInput) {
return `I choose **${botInput}**, It looks like its a tie!`
} if(input === "paper" && botInput === "rock") {
client.RPSWins.inc(key, "rpsWins");
return `I choose **${botInput}**, It looks like you win this time :cry:. You now have **${client.RPSWins.get(key, "rpsWins")}** Wins!`
} if(input === "paper" && botInput === "scissors") {
return `I choose **${botInput}**, I win!`
} if(input === "rock" && botInput === "paper") {
return `I choose **${botInput}**, I win!`
} if(input === "rock" && botInput === "scissors") {
client.RPSWins.inc(key, "rpsWins");
return `I choose **${botInput}**, It looks like you win this time :cry:. You now have **${client.RPSWins.get(key, "rpsWins")}** Wins!`
} if(input === "scissors" && botInput === "rock") {
return `I choose **${botInput}**, I win!`
} if(input === "scissors" && botInput === "paper") {
client.RPSWins.inc(key, "rpsWins");
return `I choose **${botInput}**, It looks like you win this time :cry:. You now have **${client.RPSWins.get(key, "rpsWins")}** Wins!`
}
}
if(!choice || choices.includes(choice) === false) {
const NoArgsEmbed = new RichEmbed()
.setColor(EmbedColor)
.setTitle('No Arguments!')
.addField(`Please provide one of the following!`, `**${choices.join("**, **")}**`)
.addField(`Wins`, `**${client.RPSWins.get(key, "rpsWins")}**`)
message.channel.send(NoArgsEmbed)
//message.channel.send(`Please select one of the following **${choices.join("**, **")}**, You have **${client.RPSWins.get(key, "rpsWins")}** Wins!`)
} else {
message.channel.send(rps(choice, botChoice))
}
}
exports.info = {
name: 'rps',
category: 'fun',
aliases: [],
usage: 'rps \'choice\'',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/src/cmds/howgay.js
const {
Discord,
RichEmbed
} = require('discord.js')
const {
EmbedColor
} = require('../settings.json');
exports.run = (client, message, paramaters) => {
let User = message.mentions.members.first() || message.member
let gayLevelPer = Math.floor(Math.random() * 100)
client.howgay.ensure(User.id, gayLevelPer)
const gayLevel = new RichEmbed().setTitle(`How gay is ${User.user.username}?`).setDescription(`:gay_pride_flag: ${User.user.username} is ${client.howgay.get(User.id)}% gay! :gay_pride_flag: `).setColor(EmbedColor)
message.channel.send(gayLevel)
}
exports.info = {
name: 'howgay',
category: 'fun',
aliases: [],
usage: 'howgay \'user\'',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/src/cmds/bet.js
const { Discord, RichEmbed } = require('discord.js')
const { EmbedColor, errors } = require('../settings.json');
exports.run = (client, message, paramaters) => {
let bet = parseInt(paramaters[0])
if(!paramaters[0] || isNaN(paramaters[0]) || bet < 0) {
return message.channel.send(errors.MissingArgs)
}
if((client.Currency.get(message.author.id).balance - bet) < 0 === true) {
return message.channel.send('You do not have enough coins for that!')
}
const chance = Math.floor(Math.random() * 6)
const embed = new RichEmbed()
if(chance % 2 === 0) {
embed.setTitle('You win!')
embed.setDescription(`You rolled a ${chance}`)
embed.addField('Bet', bet, true)
embed.setColor(EmbedColor)
embed.addField('Won', bet * 2, true)
message.channel.send(embed)
client.Currency.set(message.author.id, {balance: (client.Currency.get(message.author.id).balance - bet) + (bet * 2), lastUsed: client.Currency.get(message.author.id).lastUsed, SecSys: client.Currency.get(message.author.id).SecSys})
} else {
embed.setTitle('You win!')
embed.setDescription(`You rolled a ${chance}`)
embed.addField('Bet', bet, true)
embed.setColor(EmbedColor)
embed.addField('Lost', bet, true)
message.channel.send(embed)
client.Currency.set(message.author.id, {balance: client.Currency.get(message.author.id).balance - (bet), lastUsed: client.Currency.get(message.author.id).lastUsed, SecSys: client.Currency.get(message.author.id).SecSys})
}
}
exports.info = {
name: 'bet',
category: 'fun',
aliases: ['gamble'],
usage: 'bet \'amount\'',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/src/cmds/discriminator.js
const {
Discord,
RichEmbed
} = require('discord.js')
const {
EmbedColor
} = require('../settings.json');
exports.run = (client, message, paramaters) => {
const discrimInput = paramaters[0] || message.author.discriminator
const discrims = client.users.filter(f => f.discriminator === discrimInput).first(10)
const embed = new RichEmbed().setTitle(`Here are the users with the discriminator **${discrimInput}**`).setColor(EmbedColor).setDescription(discrims.map(f => f.tag).join('\n')).setFooter(`Showing the first 10 users. ${client.users.filter(f => f.discriminator === discrimInput).size} total users with that discriminator`)
message.channel.send(embed)
}
exports.info = {
name: 'discriminator',
category: 'information',
aliases: ['discrim'],
usage: 'discriminator \'user\'',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/src/cmds/ping.js
const { Discord, RichEmbed } = require('discord.js')
const { EmbedColor } = require('../settings.json');
exports.run = async (client, message, paramaters) => {
const ping = await message.channel.send('My ping is.')
await ping.edit('My ping is..')
await ping.edit('My ping is...')
await ping.edit(`My ping is **${Math.floor(client.ping)}**ms`)
}
exports.info = {
name: 'ping',
category: 'information',
aliases: [],
usage: 'ping',
botPermissions: ['SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/src/cmds/prefix.js
const { Discord, RichEmbed } = require('discord.js')
const { EmbedColor } = require('../settings.json');
exports.run = (client, message, paramaters) => {
if(!paramaters[0]) {
message.channel.send(`Your prefix is currently ${client.prefix.get(message.guild.id).prefix}. To change it use \`>prefix >\`.`)
} else if(paramaters[0].length > 2) {
message.channel.send('Prefixs cannot be over 2 characters')
} else if(paramaters[0] === client.prefix.get(message.guild.id).prefix) {
message.channel.send(`${message.guild.name}'s prefix is already \`${client.prefix.get(message.guild.id).prefix}\``)
} else if(paramaters[0]) {
message.channel.send(`My prefix is now \`${paramaters[0]}\``)
client.prefix.set(message.guild.id, {prefix: paramaters[0]})
}
}
exports.info = {
name: 'prefix',
category: 'settings',
aliases: [],
usage: 'prefix \'prefix\'',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: ['ADMINISTRATOR'],
}<file_sep>/src/cmds/daily.js
const {
Discord,
RichEmbed
} = require('discord.js')
const {
EmbedColor
} = require('../settings.json');
exports.run = (client, message, paramaters) => {
const user = message.member
const key = user.id
client.Currency.ensure(key, {
balance: 500,
lastUsed: null,
SecSys: false
})
if (message.createdTimestamp - client.Currency.get(key).lastUsed >= 86400000) {
client.Currency.set(key, {
balance: client.Currency.get(key).balance + 100,
lastUsed: message.createdTimestamp,
SecSys: client.Currency.get(key).SecSys,
})
const newBal = new RichEmbed().setColor(EmbedColor).addField(`You have claimed your 100 daily credits!`, `Your balance is now ${client.Currency.get(key).balance}`)
message.channel.send(newBal)
}
else {
message.channel.send(`Command can only be used every **24 Hours**`)
}
}
exports.info = {
name: 'daily',
category: 'currency',
aliases: [],
usage: 'daily',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/README.md
# About
K4 is a bot designed with everyone in mind. With its simplistic features and looks.
# Features
- Moderation
- Information
- Utility
- Leveling System
- Currency System
- NSFW
# Upcoming Features
- Music
- Per-Guild Configuration
# Setup
- If you decide to not use a package manager you can use the following to start the bot, but when you use the restart command you will have to manually start the bot again.
```bash
node app.js
```
- If you are using a package manager like pm2 you can use this to start the bot, once started it will restart when it crashes.
```bash
pm2 start app.js --name K4
```
- __settings.json__ should look something like this.
```json
{
"token" : "YourToken",
"prefix" : ">",
"EmbedColor" : 5521613,
"ownerID" : "ID",
"errors" : {
"MissingArgs" : "You are missing an argument!",
"Error" : "It seems an error occured.",
"MissingMention" : "Please mention a user!",
"NoUser" : "I could not find that user.",
"MissingPermission" : "I do not have permission to do that.",
"UserPerm" : "You do not have permission to do that."
}
}
```
# FAC
- Can i add custom commands?
Yes! But you will need to know some Discord.JS
<file_sep>/app.js
const Discord = require('discord.js');
const client = new Discord.Client();
require('./src/util/eventLoader')(client);
require('./src/util/enmapLoad')(client)
require('./commandLoader')(client)
const { token, prefix, EmbedColor } = require('./src/settings.json');
client.login(token);
client.reload = command => {
return new Promise((resolve, reject) => {
try {
delete require.cache[require.resolve(`./src/cmds/${command}`)];
let cmd = require(`./src/cmds/${command}`);
client.cmds.delete(command);
client.cmds.set(command, cmd);
resolve();
} catch (e){
reject(e);
}
});
};
<file_sep>/src/cmds/gay.js
const {
Discord,
RichEmbed
} = require('discord.js')
const {
EmbedColor
} = require('../settings.json');
const Pornsearch = require('pornsearch').search('gay porn');
exports.run = (client, message, paramaters) => {
var gif;
const embed = new RichEmbed().setTitle(`Gays!`).setColor(EmbedColor)
Pornsearch.gifs().then(gifs => {
var gif = gifs[Math.floor(Math.random() * gifs.length)].url
embed.setImage(`${gif}`)
embed.setDescription(`[Go To](${gif})`)
message.channel.send(embed)
});
}
exports.info = {
name: 'gay',
category: 'nsfw',
aliases: [],
usage: 'gay',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/src/cmds/coinflip.js
const {
Discord,
RichEmbed
} = require('discord.js')
const {
EmbedColor
} = require('../settings.json');
exports.run = (client, message, paramaters) => {
let sides = ['heads', 'tails']
let choice = sides[Math.floor(Math.random() * sides.length)]
message.channel.send(`The coin landed on **${choice}**!`)
}
exports.info = {
name: 'coinflip',
category: 'fun',
aliases: [],
usage: 'coinflip',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/src/cmds/avatar.js
const {
Discord,
RichEmbed
} = require('discord.js')
const {
EmbedColor
} = require('../settings.json');
exports.run = (client, message, paramaters) => {
const user = message.mentions.members.first() || message.guild.members.find(f => f.user.username.toLowerCase() === paramaters[0]) || message.member
const embed = new RichEmbed().setColor(EmbedColor).setTitle(`${user.user.username}'\s Avatar!`).setImage(user.user.displayAvatarURL)
message.channel.send(embed)
}
exports.info = {
name: 'avatar',
category: 'information',
aliases: ['pfp', 'icon'],
usage: 'avatar \'user\'',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/src/cmds/removerole.js
const { Discord, RichEmbed } = require('discord.js')
const { EmbedColor, errors } = require('../settings.json');
exports.run = (client, message, paramaters) => {
const user = message.mentions.members.first()
const role = message.guild.roles.find(f => f.name === paramaters[1])
try {
if(!user) {
message.channel.send(errors.MissingArgs)
} else if(!role) {
message.channel.send(errors.MissingArgs)
} else if(message.guild.roles.has(role.id)) {
if(!user.roles.has(role.id)) {
message.channel.send({embed: {description: `${user.user.tag} does not have <@&${role.id}>`, color: EmbedColor}})
} else {
message.channel.send({embed: {description: `${user.user.tag} was taken away <@&${role.id}>`, color: EmbedColor}})
user.removeRole(role.id)
}
}
} catch(err) {
message.channel.send(`I could not find that role!`)
}
}
exports.info = {
name: 'removerole',
category: 'moderation',
aliases: ['delrole'],
usage: 'removerole \'user\' \'role\'',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: ["MANAGE_ROLES"],
}<file_sep>/commandLoader.js
const Discord = require('discord.js')
module.exports = client => {
client.cmds = new Discord.Collection();
client.aliases = new Discord.Collection();
const fs = require('fs')
fs.readdir('./src/cmds/', (err, files) => {
if(err) console.error(err);
console.log(`${files.length} commands loaded.`);
files.forEach(f => {
const cmd = require(`./src/cmds/${f}`)
client.cmds.set(cmd.info.name, cmd)
cmd.info.aliases.forEach(alias => {
client.aliases.set(alias, cmd.info.name)
})
})
})
}<file_sep>/src/cmds/unmute.js
const { errors } = require('../settings.json');
exports.run = (client, message, paramaters) => {
const user = message.mentions.members.first()
const Role = message.guild.roles.find(f => f.name === 'Muted')
if(!user) {
message.channel.send(errors.MissingArgs)
}
try {
if(user.roles.has(Role.id)) {
message.channel.send(`${user.user.tag} was unmuted.`)
user.send(`You were unmuted in ${message.guild.name}`)
user.removeRole(Role.id)
} else if(!user.roles.has(Role.id)) {
message.channel.send(`${user.user.tag} has not been muted.`)
}
} catch(err) {
message.channel.send(`Could not mute this user. Make sure you have a **Muted** role!`)
}
}
exports.info = {
name: 'unmute',
category: 'moderation',
aliases: [],
usage: 'unmute \'user\'',
botPermissions: ['MANAGE_ROLES', 'EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: ['MANAGE_ROLES'],
}<file_sep>/src/cmds/eval.js
const {
Discord,
RichEmbed
} = require('discord.js')
const {
EmbedColor,
token
} = require('../settings.json');
exports.run = (client, message, paramaters) => {
const code = paramaters.join(" ");
const util = require("util");
if (code < 1) {
message.channel.send("Please input some code!")
}
else
if (code.includes("client.token")) {
message.channel.send("Unable to eval that code!");
}
else {
const hrStart = process.hrtime();
new Promise(r => r(eval(code))).then(async (evaled) => {
if(evaled !== undefined && typeof evaled.then === 'function') {
evaled = await evaled
type = `Promise <${evaled != null ? evaled.constructor.name : 'void'}>`
} else {
type = evaled != null ? evaled.constructor.name : 'void';
}
if (util.inspect(evaled, {
depth: 0
}).includes(client.token) || util.inspect(evaled, {
depth: 0
}).includes(client.token.toLowerCase()) || util.inspect(evaled, {
depth: 0
}).includes(client.token.toUpperCase())) {
message.channel.send("Unable to eval that code!");
}
else {
hrDiff = process.hrtime(hrStart);
const evalEmbed = new RichEmbed()
.setTitle(`Success! || Evaled in ${hrDiff[0] > 0 ? `${hrDiff[0]}s ` : ''}${hrDiff[1] / 1000000}ms`)
.setColor(1048335)
.addField('📥 Input:', `\`\`\`js\n${code}\`\`\``)
.addField('📤 Output: ', `\`\`\`js\n${util.inspect(evaled, {compact: true, depth: 0})}\`\`\``)
.setFooter(`Type: ${type}`)
message.channel.send(evalEmbed);
}
}).catch(err => {
hrDiff = process.hrtime(hrStart);
const evalFail = new RichEmbed()
.setTitle(`Error! || Evaled in ${hrDiff[0] > 0 ? `${hrDiff[0]}s ` : ''}${hrDiff[1] / 1000000}ms`)
.setColor(16715535)
.addField('📥 Input:', `\`\`\`js\n${code}\`\`\``)
.addField('📤 Output: ', `\`\`\`js\n${err}\`\`\``)
message.channel.send(evalFail);
});
}
}
exports.info = {
name: 'eval',
category: 'developer',
aliases: ['code', 'run'],
usage: 'eval \'code\'',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/src/cmds/restart.js
const { Discord, RichEmbed } = require('discord.js')
const { EmbedColor } = require('../settings.json');
exports.run = (client, message, paramaters) => {
message.channel.send('Restarting...').then(q => process.kill(0))
}
exports.info = {
name: 'restart',
category: 'developer',
aliases: ['r', 'kys'],
usage: 'restart',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/src/cmds/invite.js
const {
Discord,
RichEmbed
} = require('discord.js')
const {
EmbedColor
} = require('../settings.json')
exports.run = (client, message, paramaters) => {
const Invite = new RichEmbed()
Invite.setDescription(`Invite me [here](https://discordapp.com/oauth2/authorize?client_id=${client.user.id}&scope=bot&permissions=268545094)`)
Invite.setColor(EmbedColor)
message.channel.send(Invite)
}
exports.info = {
name: 'invite',
category: 'misc',
aliases: [],
usage: 'invite',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/src/cmds/ban.js
const {
Discord,
RichEmbed
} = require('discord.js')
const {
EmbedColor,
errors
} = require('../settings.json');
exports.run = (client, message, paramaters) => {
const user = message.mentions.members.first() || message.guild.members.get(paramaters[0])
if (!user) {
message.channel.send(errors.MissingMention)
}
else if (!message.guild.members.has(user.id)) {
message.channel.send(errors.NoUser)
}
else if (user.bannable === false) {
message.channel.send(`That user could not be banned!`)
}
else {
const Ban = new RichEmbed()
Kick.setTitle(`${user.user.tag} was banned!`)
Kick.setColor(EmbedColor)
Kick.addField('By:', `<@${message.author.id}>`)
Kick.setFooter(`Time: ${message.createdAt.toLocaleString()}`)
message.channel.send(Ban)
user.ban()
}
}
exports.info = {
name: 'ban',
category: 'moderation',
aliases: [],
usage: 'ban \'user\'',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES', 'KICK_MEMBERS'],
userPermissions: ['BAN_MEMBERS'],
}<file_sep>/src/cmds/softban.js
const { Discord, RichEmbed } = require('discord.js')
const { EmbedColor, errors } = require('../settings.json');
exports.run = (client, message, paramaters) => {
const user = message.guild.get(paramaters[0]) || message.mentions.members.first()
if(!user) {
message.channel.send(errors.MissingArgs)
}
}
exports.info = {
name: 'softban',
category: 'moderation',
aliases: [],
usage: 'softban \'user\'',
botPermissions: ['BAN_MEMBERS', 'EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: ['BAN_MEMBERS'],
}<file_sep>/src/cmds/rank.js
const { Discord, RichEmbed } = require('discord.js')
const { EmbedColor } = require('../settings.json');
exports.run = (client, message, paramaters) => {
const user = message.mentions.members.first() || message.member
const Level = new RichEmbed()
Level.setTitle(`${user.user.tag}'s rank!`)
Level.addField('Level', `${client.points.get(user.id).level}`, true)
Level.addField('Points', `${client.points.get(user.id).points}`, true)
Level.setColor(EmbedColor)
message.channel.send(Level)
}
exports.info = {
name: 'rank',
category: 'levels',
aliases: ['level'],
usage: 'rank \'user\'',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/src/cmds/dice.js
const {
Discord,
RichEmbed
} = require('discord.js')
const {
EmbedColor
} = require('../settings.json');
exports.run = (client, message, paramaters) => {
const embed = new RichEmbed().setColor(EmbedColor).setTitle(`<:d20:591231078044401665> You rolled a **${Math.floor(Math.random() * 6)}** and a **${Math.floor(Math.random() * 6)}** <:d20:591231078044401665>`)
message.channel.send(embed)
}
exports.info = {
name: 'dice',
category: 'fun',
aliases: [],
usage: 'dice',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/src/cmds/pussy.js
const { Discord, RichEmbed } = require('discord.js')
const { EmbedColor } = require('../settings.json');
const Pornsearch = require('pornsearch').search('pussy');
exports.run = (client, message, paramaters) => {
var gif;
const embed = new RichEmbed()
.setTitle(`Pussy!`)
.setColor(EmbedColor)
Pornsearch.gifs()
.then(gifs => { var gif = gifs[Math.floor(Math.random() * gifs.length)].url
embed.setImage(`${gif}`)
embed.setDescription(`[Go To](${gif})`)
message.channel.send(embed) });
}
exports.info = {
name: 'pussy',
category: 'nsfw',
aliases: [],
usage: 'pussy',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/src/cmds/userinfo.js
const Discord = require("discord.js");
const moment = require("moment");
require("moment-duration-format");
const status = {
online: "Online",
idle: "Idle",
dnd: "Do Not Disturb",
offline: "Offline/Invisible"
};
const { EmbedColor } = require('../settings.json');
exports.run = (client, msg, args) => {
const member = msg.mentions.members.first() || msg.guild.members.get(args[0]) || msg.member;
let bot;
if(member.user.bot === true) {
bot = "Yes";
} else {
bot = "No";
}
function checkDays(date) {
let now = new Date();
let diff = now.getTime() - date.getTime();
let days = Math.floor(diff / 86400000);
return days + (days == 1 ? " day" : " days") + " ago";
};
const type = {
0: "Playing",
1: "Streaming",
2: "Listening to",
3: "Watching"
};
let playing;
if(member.presence.status === 'offline' || member.presence.game === null) {
playing = 'Playing'
} else {
playing = type[member.presence.game.type]
}
let lastMessage;
if(member.lastMessage === null) {
lastMessage = 'None'
} else {
lastMessage = `[Jump To](https://discordapp.com/channels/${msg.guild.id}/${msg.channel.id}/${member.lastMessage.id})`
}
const embed = new Discord.RichEmbed()
.setColor(EmbedColor)
.setThumbnail(`${member.user.displayAvatarURL}`)
.setAuthor(`${member.user.tag} (${member.id})`, `${member.user.displayAvatarURL}`)
.addField("Nickname", `${member.nickname !== null ? `${member.nickname}` : "No nickname"}`, true)
.addField("Bot?", `${bot}`, true).addField("Status", `${status[member.user.presence.status]}`, true)
.addField(`${playing}`, `${member.user.presence.game ? `${member.user.presence.game.name}`: "None!"}`, true)
.addField("Roles", `${member.roles.size}`, true)
.addField("Last Message", `${lastMessage}`, true)
.addField("Joined At", `${member.joinedAt.toLocaleString().split(",")[0]} (${checkDays(member.joinedAt)})`, true)
.addField("Created On", `${member.user.createdAt.toLocaleString().split(",")[0]} (${checkDays(member.user.createdAt)})`, true);
msg.channel.send({
embed
});
};
exports.info = {
name: 'userinfo',
category: 'information',
aliases: [],
usage: 'userinfo \'user\'',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/src/cmds/mute.js
const { Discord, RichEmbed } = require('discord.js')
const { EmbedColor, errors } = require('../settings.json');
exports.run = (client, message, paramaters) => {
const user = message.mentions.members.first()
const Role = message.guild.roles.find(f => f.name === 'Muted')
if(!user) {
return message.channel.send(errors.MissingArgs)
}
try {
if(user.roles.has(Role.id)) {
message.channel.send(`${user.user.tag} is already muted!`)
} else if(!user.roles.has(Role.id)) {
message.channel.send(`${user.user.tag} has been muted!`)
user.send(`You were muted in ${message.guild.name}`)
user.addRole(Role.id)
}} catch(err) {
message.channel.send(`Could not mute this user. Make sure you have a **Muted** role!`)
}
}
exports.info = {
name: 'mute',
category: 'moderation',
aliases: [],
usage: 'mute \'user\'',
botPermissions: ['MANAGE_ROLES', 'EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: ["KICK_MEMBERS"],
}<file_sep>/src/cmds/lmgtfy.js
const { Discord, RichEmbed } = require('discord.js')
const { EmbedColor, errors } = require('../settings.json');
exports.run = (client, message, paramaters) => {
const link = 'http://lmgtfy.com/?q='
if(!paramaters[0]) {
message.channel.send(errors.MissingArgs)
} else {
message.channel.send(`Here you go!\n${link}${paramaters.join("+")}`)
}
}
exports.info = {
name: 'lmgtfy',
category: 'fun',
aliases: ['google'],
usage: 'lmgtfy \'content\'',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/src/cmds/say.js
const { Discord, RichEmbed } = require('discord.js')
const { EmbedColor, errors } = require('../settings.json');
exports.run = (client, message, paramaters) => {
if(paramaters.includes('@everyone') || paramaters.includes('@here')) {
return message.channel.send('You cannot ping everyone/here.')
}
const messageToSay = paramaters.join(" ")
if(!messageToSay) {
message.channel.send(errors.MissingArgs)
} else {
message.channel.send(messageToSay)
}
}
exports.info = {
name: 'say',
category: 'fun',
aliases: [],
usage: 'say \'text\'',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/src/events/message.js
const {
errors,
ownerID
} = require('../settings.json')
module.exports = message => {
const client = message.client;
if (message.author.id === client.user.id || message.author.bot) return
if (message.channel.type === 'dm') return
const key = `${message.author.id}`
client.prefix.ensure(message.guild.id, {
prefix: '>'
})
client.points.ensure(key, {
user: message.author.id,
points: 0,
level: 0,
})
const currentLevel = Math.floor(.09 * Math.sqrt(client.points.get(key, 'points')))
client.points.set(key, {
points: client.points.get(key).points + Math.floor(Math.random() * 8),
level: currentLevel
})
if (!message.content.startsWith(client.prefix.get(message.guild.id).prefix)) return
const command = message.content.split(" ")[0].slice(client.prefix.get(message.guild.id).prefix.length).toLowerCase()
const params = message.content.split(" ").slice(1)
if (client.cmds.has(client.aliases.get(command)) || client.cmds.has(command)) {
const cmd = client.cmds.get(command) || client.cmds.get(client.aliases.get(command))
const UserPerms = cmd.info.userPermissions
const BotPerms = cmd.info.botPermissions
if (!UserPerms.every(f => message.member.hasPermission(f))) {
return message.channel.send(errors.UserPerm)
} else if (!BotPerms.every(f => message.guild.me.hasPermission(f))) {
return message.channel.send(errors.MissingPermission)
} else if (cmd.info.category === 'developer' && message.author.id !== ownerID) {
message.channel.send('You cannot use **developer only** commands!')
} else if (cmd.info.category === 'nsfw' && message.channel.nsfw === false) {
message.channel.send('You cannot use **NSFW** commands in a non-NSFW channel!')
} else {
cmd.run(client, message, params)
client.commandsUsed++
}
}
}<file_sep>/src/events/ready.js
module.exports = client => {
client.commandsUsed = 0
console.log(`I'm now online. Serving ${client.users.size} users in ${client.guilds.size} guilds.`)
client.user.setActivity(`${client.users.size} Users`, { type: 'WATCHING' })
setInterval(function() {
client.guilds.get('592100762826309673').channels.get("592104987816099890").setName(`Users: ${client.users.size}`)
client.user.setActivity(`${client.users.size} Users`, { type: 'WATCHING' })
}, 10000)
}<file_sep>/src/cmds/purge.js
exports.run = async (client, message, paramaters) => {
const amount = paramaters[0]
if(!amount) {
message.channel.send(client.settings.err.NoArgs)
} else if(parseInt(amount) > 100 || parseInt(amount) < 1) {
message.channel.send(`Please select a number between 1 and 100`)
} else {
await message.delete()
await message.channel.bulkDelete(parseInt(amount))
}
}
exports.info = {
name: 'purge',
category: 'moderation',
aliases: ['clear', 'bulkdelete'],
usage: 'purge \'amount\'',
botPermissions: ['MANAGE_MESSAGES', 'SEND_MESSAGES'],
userPermissions: ['MANAGE_MESSAGES'],
}<file_sep>/src/cmds/deposit.js
const { Discord, RichEmbed } = require('discord.js')
const { EmbedColor, errors } = require('../settings.json');
exports.run = async (client, message, paramaters) => {
const key = message.author.id
const amount = parseInt(paramaters[0])
if(!amount || isNaN(amount)) {
message.channel.send(errors.MissingArgs)
} else if(client.Currency.get(message.author.id).balance < amount) {
return message.channel.send('You cannot deposit more than you have!')
}
const fee = amount * .02
await client.Bank.set(message.author.id, {balance: Math.floor(client.Bank.get(message.author.id).balance + (amount - fee))})
client.Currency.set(key, {balance: Math.floor(client.Currency.get(key).balance - amount), lastUsed: client.Currency.get(key).lastUsed, SecSys: client.Currency.get(key).SecSys})
const embed = new RichEmbed()
.setTitle('Deposit Successful')
.setFooter(`You have been charged a fee of ${fee} (2%)`)
.addField('Bank Balance', client.Bank.get(message.author.id).balance + ' Coins')
.setColor(EmbedColor)
message.channel.send(embed)
}
exports.info = {
name: 'deposit',
category: 'currency',
aliases: [],
usage: 'deposit \'amount\'',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/src/cmds/help.js
const {
RichEmbed
} = require('discord.js')
const {
EmbedColor,
ownerID
} = require('../settings.json');
exports.run = (client, message, paramaters) => {
function GatherCommands(cmdCategory) {
let cmds = []
client.cmds.forEach(c => {
if (c.info.category === cmdCategory.toLowerCase()) {
cmds.push(`${c.info.name}`)
}
})
if (cmds.length === 0) {
return ["No commands!"]
}
else if (cmds.length > 0) {
return cmds
}
}
if (!paramaters[0]) {
const Help = new RichEmbed()
Help.setFooter(`Prefix for ${message.guild.name} is ${client.prefix.get(message.guild.id).prefix}`)
Help.setTitle(`Commands (${client.cmds.size})`)
Help.setURL('https://discord.gg/wnrcsU7')
if (message.author.id === ownerID) {
Help.addField(`Developer 👎(${GatherCommands('developer').length})`, `\`${GatherCommands('developer').join("\`, \`")}\``)
}
if (message.member.hasPermission('ADMINISTRATOR')) {
Help.addField(`Settings ⚙ (${GatherCommands('settings').length})`, `\`${GatherCommands('settings').join("\`, \`")}\``)
}
if (message.member.hasPermission('KICK_MEMBERS')) {
Help.addField(`Moderation 🚓 (${GatherCommands('moderation').length})`, `\`${GatherCommands('moderation').join("\`, \`")}\``)
}
Help.addField(`Information 📁 (${GatherCommands('information').length})`, `\`${GatherCommands('information').join("\`,\`")}\``)
Help.addField(`Fun 🎲 (${GatherCommands('fun').length})`, `\`${GatherCommands('fun').join("\`, \`")}\``)
if (message.channel.nsfw) {
Help.addField(`NSFW 🔞 (${GatherCommands('nsfw').length})`, `\`${GatherCommands('nsfw').join("\`, \`")}\``)
}
Help.addField(`Levels 🎚 (${GatherCommands('levels').length})`, `\`${GatherCommands('levels').join("\`, \`")}\``)
Help.addField(`Curreny 💸 (${GatherCommands('currency').length})`, `\`${GatherCommands('currency').join("\`, \`")}\``)
Help.setColor(EmbedColor)
Help.addField(`Misc ✴(${GatherCommands('misc').length})`, `\`${GatherCommands('misc').join("\`, \`")}\``)
message.channel.send(Help)
}
else if (paramaters[0]) {
if (!client.cmds.has(paramaters[0] || !client.cmds.has(client.aliases.get(paramaters[0])))) {
message.channel.send(`I do not have the command **${client.prefix.get(message.guild.id).prefix}${paramaters[0]}**`)
}
else {
const cmd = client.cmds.get(paramaters[0])
var aliases;
if (cmd.info.aliases.length === 0) {
aliases = 'None'
}
else {
aliases = cmd.info.aliases.join("\`, `")
}
const Help = new RichEmbed()
Help.setFooter(`Prefix for ${message.guild.name} is ${client.prefix.get(message.guild.id).prefix}`)
Help.setTitle(`Information For ${cmd.info.name}`)
Help.setColor(EmbedColor)
Help.addField('Usage', cmd.info.usage)
Help.addField('Aliases', `\`${aliases}\``)
message.channel.send(Help)
}
}
}
exports.info = {
name: 'help',
category: 'information',
aliases: ['?', 'h'],
usage: 'help \'command\'',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/src/cmds/shop.js
const { Discord, RichEmbed } = require('discord.js')
const { EmbedColor } = require('../settings.json');
exports.run = (client, message, params) => {
const key = message.author.id
client.Currency.ensure(key, {
balance: 500,
lastUsed: null,
SecSys: false
})
if(!params[0]) {
const Shop = new RichEmbed()
.setColor(EmbedColor)
.setTitle('Shop!')
.addField(`Security System - 10,000`, 'Never get robbed again! __Run **>shop Security** to buy__')
message.channel.send(Shop)
} if(params[0].toLowerCase() === "security") {
if(client.Currency.get(key).SecSys === true) {
message.channel.send(`You already have a **Security System**`)
} else if(client.Currency.get(key).balance < 10000) {
message.channel.send(`You do not have enough money to buy this!`)
} else if(client.Currency.get(key).SecSys === true) {
message.channel.send(`You already have this item!`)
} else {
client.Currency.set(key, {balance: client.Currency.get(key).balance, lastUsed: client.Currency.get(key).lastUsed, SecSys: true})
message.channel.send(`You bought the **Security System**`)
}
} else {
message.channel.send('Invalid option, try using `>shop` to view the list of items.')
}
}
exports.info = {
name: 'shop',
category: 'currency',
aliases: ['store'],
usage: 'shop \'item\'',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/src/cmds/meme.js
const { RichEmbed } = require('discord.js')
const { EmbedColor } = require('../settings.json');
const got = require('got')
exports.run = (client, message, paramaters) => {
got('https://www.reddit.com/r/meme/random/.json').then(response => {
let content = JSON.parse(response.body);
var title = content[0].data.children[0].data.title;
var image = content[0].data.children[0].data.url;
const sent = new RichEmbed()
.setTitle(title)
.setImage(image)
.setColor(EmbedColor)
message.channel.send(sent)
//msg.channel.send(image)
}).catch(console.error);
}
exports.info = {
name: 'meme',
category: 'fun',
aliases: [],
usage: 'meme',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/src/cmds/rob.js
const { Discord, RichEmbed } = require('discord.js')
const { EmbedColor } = require('../settings.json');
exports.run = (client, message, paramaters) => {
const user = message.mentions.members.first()
if(!user) {
message.channel.send(client.settings.err.NoArgs)
return
} else if(user.id === message.author.id) {
message.channel.send(`You cant rob yourself!`)
return
}
const key = user.id
client.Currency.ensure(key, {
balance: 500,
lastUsed: null,
SecSys: false
})
if(client.Currency.get(user.id).balance <= 500) {
message.channel.send(`This user does not have enough credits`)
} else {
const amountTaken = Math.floor(Math.random() * 500)
const robChance = Math.random() * 1
if(client.Currency.get(key).SecSys === true) {
message.channel.send(`This user has a **Security System** and you were caught!`)
} else if(robChance > .5) {
const robbed = new RichEmbed()
.setTitle(`Success!`)
.setColor(EmbedColor)
.setDescription(`You took **${amountTaken}** credits from <@${user.id}>`)
message.channel.send(robbed)
client.Currency.set(user.id, {balance: client.Currency.get(user.id).balance - amountTaken, lastUsed: client.Currency.get(user.id).lastUsed,
SecSys: client.Currency.get(user.id).SecSys})
client.Currency.set(message.author.id, {balance: client.Currency.get(message.author.id).balance + amountTaken, lastUsed: client.Currency.get(user.id).lastUsed,
SecSys: client.Currency.get(user.id).SecSys})
} else if(robChance < .5) {
const notRobbed = new RichEmbed()
.setTitle(`You got caught and escaped with nothing!`)
.setColor(EmbedColor)
message.channel.send(notRobbed)
}
}
}
exports.info = {
name: 'rob',
category: 'currency',
aliases: ['steal'],
usage: 'rob \'user\'',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/src/cmds/weather.js
const { Discord, RichEmbed } = require('discord.js')
const { EmbedColor, errors } = require('../settings.json');
const weather = require('weather-js')
exports.run = (client, message, paramaters) => {
const location = paramaters.join(" ")
var type = 'F'
if(!location) {
return message.channel.send(errors.MissingArgs)
} else if(location.toLowerCase().includes('-c')) {
type = 'C'
} else if(location.toLowerCase().includes('-f')) {
type = 'F'
}
weather.find({search: location, degreeType: type}, function(err, result) {
if(err) {
return message.channel.send('I could not find any data.')
}
try {
const weatherEmbed = new RichEmbed
weatherEmbed.setColor(EmbedColor)
weatherEmbed.setTitle(`Weather For: ${result[0].location.name}`)
weatherEmbed.addField('Temperature', `${result[0].current.temperature} ${type} (Feels Like ${result[0].current.feelslike} ${type})`, true)
weatherEmbed.addField('Forecast', `${result[0].current.skytext}`, true)
weatherEmbed.addField('Wind', `${result[0].current.winddisplay}`, true)
weatherEmbed.addField('Humidity', `${result[0].current.humidity}%`, true)
weatherEmbed.setFooter(`Date: ${result[0].current.date}`)
weatherEmbed.setThumbnail(result[0].current.imageUrl)
message.channel.send(weatherEmbed)
} catch(err) {
message.channel.send('I could not find any data.')
}
})
}
exports.info = {
name: 'weather',
category: 'information',
aliases: [],
usage: 'weather \'location\'',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}<file_sep>/src/cmds/status.js
const { Discord, RichEmbed } = require('discord.js')
const moment = require('moment')
require('moment-duration-format')
const { EmbedColor } = require('../settings.json');
exports.run = (client, message, paramaters) => {
const duration = moment.duration(client.uptime).format(" D [days], H [hrs], m [mins], s [secs]");
const embed = new RichEmbed()
.setColor(EmbedColor)
.setTitle(`Bot's status!`)
.addField("Mem Usage", `**${ (process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2)} MB**`, true)
.addField("Commands Used", `**${client.commandsUsed}**`, true)
.addField("Uptime", `**${duration}**`, true)
.addBlankField()
.addField("Users", `**${client.users.size - 1}**`, true)
.addField(`Servers`, `**${client.guilds.size.toLocaleString()}**`, true)
.addField(`Channels`, `**${client.channels.size.toLocaleString()}**`, true)
message.channel.send(embed);
}
exports.info = {
name: 'status',
category: 'information',
aliases: ['stats'],
usage: 'status',
botPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'],
userPermissions: [],
}
|
1e23ec686b011e43cef6b321d17f0b9009c3b60f
|
[
"JavaScript",
"Markdown"
] | 38
|
JavaScript
|
LandenStephenss/K4
|
bf37487f9bcba30f19de3972cb143db413591f9d
|
012d1086ca9723398c37bbc0a3fa13aef8ebcb4a
|
refs/heads/master
|
<file_sep>// printf
#include <stdio.h>
// close
#include <unistd.h>
// AF_INET?
#include <sys/types.h>
// socket/bind
#include <sys/socket.h>
// sockaddr_in
#include <netinet/in.h>
int main() {
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (-1 == fd) {
perror("socket");
return 1;
}
struct sockaddr_in serv_addr = {};
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(13337);
int bound = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
if (-1 == bound) {
perror("bind");
close(fd);
return 2;
}
int heard = listen(fd, 5);
if (-1 == heard) {
perror("listen");
close(fd);
return 3;
}
int accepted = accept(fd, NULL, NULL);
if (-1 == accepted) {
perror("accept");
return 4;
}
int written = write(accepted, "hello\n", 6);
if (6 != written) {
if (-1 == written) {
perror("write");
}
printf("warning: partial write\n");
}
if (-1 == close(accepted)) {
perror("close client");
}
if (-1 == close(fd)) {
perror("close server");
}
printf("spoke to a client; quitting\n");
}
<file_sep>all: target
virus.so: virus.c
$(CC) -D_GNU_SOURCE -fPIC -shared -o virus.so -ldl $<
virus.dylib: virus.c
$(CC) -dynamiclib -o virus.dylib $<
help:
@echo 'Going to start the app; run "nc localhost 13337" to quit it.'
bad: help target
./target
linux: help target virus.so
env LD_PRELOAD=/lib/x86_64-linux-gnu/libdl.so.2:./virus.so ./target
osx: help target virus.dylib
env DYLD_FORCE_FLAT_NAMESPACE=1 DYLD_INSERT_LIBRARIES=./virus.dylib ./target
<file_sep>// perror
#include <stdio.h>
// setsockopt
#include <sys/socket.h>
// dlsym
#include <dlfcn.h>
int socket(int socket_family, int socket_type, int protocol) {
int (*original_socket) (int, int, int) = dlsym(RTLD_NEXT, "socket");
int found = original_socket(socket_family, socket_type, protocol);
if (-1 == found) {
return -1;
}
int opt = 1;
int set = setsockopt(found, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(int));
if (-1 == set) {
perror("setsockopt (ignoring)");
}
return found;
}
|
f087b7d06c5bc845b0f5dc9c43a6623fe5289788
|
[
"C",
"Makefile"
] | 3
|
C
|
FauxFaux/preloadbind
|
790bf7a40218c895e7c91baec760b843d14768e5
|
b2d444fb1c58157db92fc4a68dcc7c29ddbb15a0
|
refs/heads/master
|
<file_sep><?php
if (is_file('../ErrorHandler/ErrorHandler.php')){
require_once '../ErrorHandler/ErrorHandler.php';
}
else {
exit("No ../ErrorHandler/ErrorHandler.php available");
}
class XpathParser {
private $credentialsVeysato;
public function __construct() {
if (is_file('../common/db_credentials_sandbox_rw.php')){
include '../common/db_credentials_sandbox_rw.php';
}
else {
try {
$erLogData = new ErLogData
(
'No ../common/db_credentials_sandbox_rw.php is available',
64,
get_class($e),
__FILE__,
__CLASS__,
__FUNCTION__,
__LINE__,
date('Y-m-d H:i:s')
);
$erLog = ErLogFactory::create($erLogData, $e);
$response = json_encode(array('response' => array('error' => ['message' => $erLog->_user_message, 'code' => $erlog->_code])), JSON_UNESCAPED_UNICODE);
throw $erLog;
}
catch (ErLog $ee) {
ErLog::full_log_v1($ee);
return $response;
}
exit ('No ../common/db_credentials_sandbox_rw.php is available');
}
$this->credentialsVeysato = [
'host' => $host,
'db' => $db,
'user' => $user,
'pass' => $pass,
];
//echo json_encode($this->credentialsVeysato);
}
/**
* do query to BD
* @version actual
* @param string $credentials
* @param type $queryString
* @return string
* @throws type
*/
private function selectWrapper($credentials, $queryString) {
try {
$host = $credentials['host'];
$db = $credentials['db'];
$user = $credentials['user'];
$pass = $credentials['pass'];
$dbconn = pg_connect("host=$host port=5432 dbname=$db user=$user password=$pass")
or die("Could not connect" . "</br>");
$query = $queryString;
//$query = pg_escape_string($queryString);
//echo $query;
$result = pg_query($dbconn, $query);
$resultData = '';
if (!$result) {
echo "An error occurred while requesting data.\n";
pg_close($dbconn);
exit;
}
while ($row = pg_fetch_row($result)) {
$resultData = $resultData . $row[0];
}
pg_close($dbconn);
return $resultData;
} catch (Exception $e) {
pg_close($dbconn);
if (!is_set($credentials) || is_null($credentials)) {
$credentials = ['credentials' => 'null'];
}
$erLogData = new ErLogData('Report Request Log SQL error', ErLogCodes::PG_QUERY_ERROR, get_class($e), $e->getFile(), __CLASS__, __FUNCTION__, $e->getLine(), date('Y-m-d H:i:s'), null, '{"credentials":' . json_encode($credentials, JSON_UNESCAPED_UNICODE) . ', "queryString:"' . $queryString . '}');
throw ErLogFactory::create($erLogData, $e);
}
}
/**
* return result of Xpath query from site
* @todo all work
* @version actual
* @param array $array
* @param string $html web page from cache
* @return array
* @version 15.09.16
*/
private function newGoXpath($array,$html) {
$query['site'] = $array['site'];
$query['url'] = $array['url'];
$query['type'] = $array['type'];
$query['xpath'] = $array['xpath'];
$query['task_id'] = $array['task_id'];
$query['field_type']= $array['field_type'];
//echo json_encode($query, JSON_UNESCAPED_UNICODE);
$result = [];
$test = new DOMDocument();
/*
$opts = array('http'=>array('header' => "User-Agent:MyAgent/1.0\r\n"));
$context = stream_context_create($opts);
$html = file_get_contents($site,false,$context);
*
*/
//$html = file_get_contents($query['url']);
//заменил на новую фунцкию
//$html=$this->getWebPage($query['url']);
libxml_use_internal_errors(true);
$test->loadHTML($html);
libxml_clear_errors();
$xpath = new DomXPath($test);
if (strlen($query['xpath']) > 1) {
$list = $xpath->query($query['xpath']);
if($list->length==0){
$result[0]['result']=[];
}
elseif ($query['type'] == 'Url') {
foreach ($list as $counter => $obj) {
$urlResult['link_name'] = $obj->nodeValue;
$urlResult['link_address'] = $obj->getAttribute('href');
$result[$counter]['result']= json_encode($urlResult, JSON_UNESCAPED_UNICODE);
$result[$counter]['counter'] = $counter;
}
} else {
foreach ($list as $counter => $obj) {
$result[$counter]['result'] = $obj->nodeValue;
$result[$counter]['counter'] = $counter;
}
}
$result['type'] = $query['field_type'];
$result['site'] = $query['site'];
$result['task_id'] = $query['task_id'];
}
else {
$result[0]['result']=[];
$result['type'] = $query['field_type'];
$result['site'] = $query['site'];
$result['task_id'] = $query['task_id'];
}
return $result;
}
/**
* return result of Xpath query from site
* @version temp
* @todo all work
* @param type $array
* @return type
* @version 15.09.16
*/
private function newGoXpathForTest($array,$html) {
$query['site'] = $array['site'];
$query['url'] = $array['url'];
$query['type'] = $array['type'];
$query['xpath'] = $array['xpath'];
$query['task_id'] = $array['task_id'];
$query['field_type']= $array['field_type'];
//echo json_encode($query, JSON_UNESCAPED_UNICODE);
$result = [];
$test = new DOMDocument();
/*
$opts = array('http'=>array('header' => "User-Agent:MyAgent/1.0\r\n"));
$context = stream_context_create($opts);
$html = file_get_contents($site,false,$context);
*
*/
//$html = file_get_contents($query['url']);
//заменил на новую фунцкию
//$html=$this->getWebPage($query['url']);
libxml_use_internal_errors(true);
$test->loadHTML($html);
libxml_clear_errors();
$xpath = new DomXPath($test);
if (strlen($query['xpath']) > 1) {
$list = $xpath->query($query['xpath']);
if($list->length==0){
$result[0]['result']=[];
}
elseif ($query['type'] == 'Url') {
foreach ($list as $counter => $obj) {
$urlResult['link_name'] = $obj->nodeValue;
$urlResult['link_address'] = $obj->getAttribute('href');
$result[$counter]['result']= json_encode($urlResult, JSON_UNESCAPED_UNICODE);
$result[$counter]['counter'] = $counter;
}
} else {
foreach ($list as $counter => $obj) {
$result[$counter]['result'] = $obj->nodeValue;
$result[$counter]['counter'] = $counter;
}
}
$result['type'] = $query['field_type'];
$result['site'] = $query['site'];
$result['task_id'] = $query['task_id'];
}
else {
$result[0]['result']=[];
$result['type'] = $query['field_type'];
$result['site'] = $query['site'];
$result['task_id'] = $query['task_id'];
}
return $result;
}
/**
* update status task for site
* @version actual
* @param int $task_id
*/
private function updateParser_task($task_id){
$queryString="UPDATE news.parser_task
SET
is_processed=TRUE,
result_status_id=2
WHERE id=$task_id";
$this->selectWrapper($this->credentialsVeysato, $queryString);
}
/**
* update status task for site
* @version actual
* @param int $task_id
*/
private function updateFailedParser_task($task_id){
$queryString="UPDATE news.parser_task
SET
is_processed=FALSE,
process_date=now(),
result_status_id=4
WHERE id=$task_id;";
$this->selectWrapper($this->credentialsVeysato, $queryString);
}
/**
* update status task for site
* @version actual
* @param int $task_id
*/
private function updateSuccessParser_task($task_id){
$queryString="UPDATE news.parser_task
SET
is_processed=FALSE,
process_date=now(),
result_status_id=3
WHERE id=$task_id;";
$this->selectWrapper($this->credentialsVeysato, $queryString);
}
/**
* insert new actual task for actual markup
* @version actual
* @param int $task_id
*/
public function insertNewParser_task($task_id){
$queryString='INSERT INTO news.parser_task (markup_id, page_id)
SELECT
"id",
page_id
FROM
news.parser_markup
WHERE is_actual=true';
$this->selectWrapper($this->credentialsVeysato, $queryString);
}
/**
* add result of task
* @version actual
* @param type $result
*/
private function addParser_result($result){
//echo json_encode($result, JSON_UNESCAPED_UNICODE);
if($result[0]['result']==[]){
echo 'WARNING!!! task_id='.$result['task_id'].' failed!<br>';
$this->updateFailedParser_task($result['task_id']);
}
else {
foreach ($result as $row => $rowValue) {
if(is_array($rowValue)){
//echo json_encode($rowValue, JSON_UNESCAPED_UNICODE);
//$task_id=$result['task_id'];
$task_id = pg_escape_string($result['task_id']);
//$results=$rowValue['result'];
$results = pg_escape_string($rowValue['result']);
//$counter=$rowValue['counter'];
$counter = pg_escape_string($rowValue['counter']);
//$field_type=$result['field_type'];
$field_type = pg_escape_string($result['type']);
$queryString="INSERT INTO news.parser_result (task_id, result, counter, field_type) SELECT
$task_id,
'$results',
$counter,
$field_type";
$this->selectWrapper($this->credentialsVeysato, $queryString);
}
else{
//do nothing
}
}
$this->updateSuccessParser_task($result['task_id']);
echo 'success insert task_id='.$task_id.', counter='.$counter.'<br>';
}
}
/**
* add error from task
* @todo вынести логирование ошибок по таскам в отдельную таблицу из общей (public)
*/
private function addParser_error(){
return;
}
/**
* получение всех записей запросов для всех сайтов
* @version actual
* @todo work properly
* @param string $type type of fields for example 'xpath'
* @return string result in json
* @version update 07.06.2016
*/
public function getAllQueriesForAllSite($type='xpath'){
$query="SELECT
TO_JSON(ARRAY_AGG(e))
FROM
(
SELECT
ttt.link as site,
json_agg (ttt) AS xpath
FROM
(
SELECT
q.page_id as site_id,
q.\"id\" as markup_id,
w.url as link,
e.title as \"type\",
q.field_markup as $type
FROM
\"news\".\"parser_markup\" AS q
LEFT JOIN news.parser_page AS w ON (w.\"id\" = q.page_id)
LEFT JOIN news.parser_markup_fields AS e ON (e.\"id\" = q.field_type_id)
LEFT JOIN news.parser_markup_types AS r ON (r.\"id\" = q.markup_type_id)
WHERE
q.is_actual = TRUE
AND
r.title='$type'
) AS ttt
GROUP BY
ttt.link)e";
$json=$this->selectWrapper($this->credentialsVeysato, $query);
return $json;
}
/**
* получение всех записей запросов для конкретного сайта на вход принимает url или id сайта
* @version actual
* @todo work properly
* @param string $type type of fields for example 'xpath'
* @param string or int $site
* @return string result in json
* @version update 07.06.2016
*/
public function getAllQueriesForSite($site,$type='xpath'){
if(gettype($site)=="string"){
$query="SELECT
TO_JSON(ARRAY_AGG(e))
FROM
(
SELECT
ttt.link as site,
json_agg (ttt) AS xpath
FROM
(
SELECT
q.page_id as site_id,
q.\"id\" as markup_id,
w.url as link,
e.title as \"type\",
q.field_markup as $type
FROM
\"news\".\"parser_markup\" AS q
LEFT JOIN news.parser_page AS w ON (w.\"id\" = q.page_id)
LEFT JOIN news.parser_markup_fields AS e ON (e.\"id\" = q.field_type_id)
LEFT JOIN news.parser_markup_types AS r ON (r.\"id\" = q.markup_type_id)
WHERE
q.is_actual = TRUE
AND
w.url='$site'
AND
r.title='$type'
) AS ttt
GROUP BY
ttt.link)e";
}
elseif(gettype($site)=="int"||gettype($site)=="integer"){
$query="SELECT
TO_JSON(ARRAY_AGG(e))
FROM
(
SELECT
ttt.link as site,
json_agg (ttt) AS xpath
FROM
(
SELECT
q.page_id as site_id,
q.\"id\" as markup_id,
w.url as link,
e.title as \"type\",
q.field_markup as $type
FROM
\"news\".\"parser_markup\" AS q
LEFT JOIN news.parser_page AS w ON (w.\"id\" = q.page_id)
LEFT JOIN news.parser_markup_fields AS e ON (e.\"id\" = q.field_type_id)
LEFT JOIN news.parser_markup_types AS r ON (r.\"id\" = q.markup_type_id)
WHERE
q.is_actual = TRUE
AND
q.page_id=$site
AND
r.title='$type'
) AS ttt
GROUP BY
ttt.link)e";
}
else{
echo 'No correct input available';
return null;
}
$json=$this->selectWrapper($this->credentialsVeysato, $query);
return $json;
}
/**
* получение всех тасков для всех сайтов
* @version actual
* @todo work properly
* @param string $type type of fields for example 'xpath'
* @return string result in json
* @version update 07.06.2016
*/
public function getAllTaskForAllSite($type='xpath'){
$query="SELECT
TO_JSON(ARRAY_AGG(e))
FROM
(
SELECT
ttt.site AS site,
json_agg (ttt) AS xpath
FROM
(
SELECT
q.\"id\" AS task_id,
q.is_processed AS is_progress,
w.url AS site,
e.field_markup AS $type,
r.title as \"type\"
FROM
\"news\".\"parser_task\" q
LEFT JOIN news.parser_page AS w ON (q.page_id = w.\"id\")
LEFT JOIN news.parser_markup AS e ON (e.\"id\" = q.markup_id)
LEFT JOIN news.parser_markup_fields AS r ON (e.field_type_id = r.\"id\")
LEFT JOIN news.parser_markup_types AS y ON (e.markup_type_id = y.\"id\")
WHERE
w.is_actual = TRUE
AND y.title='$type'
) AS ttt
GROUP BY
ttt.site)e";
$json=$this->selectWrapper($this->credentialsVeysato, $query);
return $json;
}
/**
* получение всех не запущенных тасков для всех сайтов limit
* @version actual
* @todo work properly
* @param string $type type of fields for example 'xpath'
* @param int $limit How many site?
* @return string result in json
* @version update 07.06.2016
*/
public function getAllNotProceedTaskForAllSite($type='xpath',$limit){
$query="SELECT
TO_JSON(ARRAY_AGG(e))
FROM
(
SELECT
ttt.site AS site,
json_agg (ttt) AS xpath
FROM
(
SELECT
q.\"id\" AS task_id,
w.url AS site,
e.field_markup AS $type,
r.title as \"type\",
r.id as field_type
FROM
\"news\".\"parser_task\" q
LEFT JOIN news.parser_page AS w ON (q.page_id = w.\"id\")
LEFT JOIN news.parser_markup AS e ON (e.\"id\" = q.markup_id)
LEFT JOIN news.parser_markup_fields AS r ON (e.field_type_id = r.\"id\")
LEFT JOIN news.parser_markup_types AS y ON (e.markup_type_id = y.\"id\")
WHERE
w.is_actual = TRUE
AND y.title='$type'
AND q.is_processed=FALSE
AND q.result_status_id=1
) AS ttt
GROUP BY
ttt.site
LIMIT $limit)e";
$json=$this->selectWrapper($this->credentialsVeysato, $query);
return $json;
}
/**
* получение всех тасков для для конкретного сайта на вход принимает url или id сайта
* @version actual
* @todo work properly
* @param string $type type of fields for example 'xpath'
* @param string or int $site
* @return string result in json
* @version update 07.06.2016
*/
public function getAllTaskForSite($site,$type='xpath'){
if(gettype($site)=="string"){
$query="SELECT
TO_JSON(ARRAY_AGG(e))
FROM
(
SELECT
ttt.site AS site,
json_agg (ttt) AS xpath
FROM
(
SELECT
q.\"id\" AS task_id,
q.is_processed AS is_progress,
w.url AS site,
e.field_markup AS $type,
r.title as \"type\"
FROM
\"news\".\"parser_task\" q
LEFT JOIN news.parser_page AS w ON (q.page_id = w.\"id\")
LEFT JOIN news.parser_markup AS e ON (e.\"id\" = q.markup_id)
LEFT JOIN news.parser_markup_fields AS r ON (e.field_type_id = r.\"id\")
LEFT JOIN news.parser_markup_types AS y ON (e.markup_type_id = y.\"id\")
WHERE w.is_actual = TRUE
AND y.title='$type'
AND w.url='$site'
) AS ttt
GROUP BY
ttt.site)e";
}
elseif(gettype($site)=="int"||gettype($site)=="integer"){
$query="SELECT
TO_JSON(ARRAY_AGG(e))
FROM
(
SELECT
ttt.site AS site,
json_agg (ttt) AS xpath
FROM
(
SELECT
q.\"id\" AS task_id,
q.is_processed AS is_progress,
w.url AS site,
e.field_markup AS $type,
r.title as \"type\"
FROM
\"news\".\"parser_task\" q
LEFT JOIN news.parser_page AS w ON (q.page_id = w.\"id\")
LEFT JOIN news.parser_markup AS e ON (e.\"id\" = q.markup_id)
LEFT JOIN news.parser_markup_fields AS r ON (e.field_type_id = r.\"id\")
LEFT JOIN news.parser_markup_types AS y ON (e.markup_type_id = y.\"id\")
WHERE w.is_actual = TRUE
AND y.title='$type'
AND w.\"id\"=$site
) AS ttt
GROUP BY
ttt.site)e";
}
else{
echo 'No correct input available';
return null;
}
$json=$this->selectWrapper($this->credentialsVeysato, $query);
return $json;
}
/**
* получение всех не запущенных тасков для для конкретного сайта на вход принимает url или id сайта LIMIT 10
* @version actual
* @todo work properly
* @param string $type type of fields for example 'xpath'
* @param string or int $site
* @return string result in json
* @version update 07.06.2016
*/
public function getAllNotProceedTaskForSite($site,$type='xpath'){
if(gettype($site)=="string"){
$query="SELECT
TO_JSON(ARRAY_AGG(e))
FROM
(
SELECT
ttt.site AS site,
json_agg (ttt) AS xpath
FROM
(
SELECT
q.\"id\" AS task_id,
w.url AS site,
e.field_markup AS $type,
r.title as \"type\",
r.id as field_type
FROM
\"news\".\"parser_task\" q
LEFT JOIN news.parser_page AS w ON (q.page_id = w.\"id\")
LEFT JOIN news.parser_markup AS e ON (e.\"id\" = q.markup_id)
LEFT JOIN news.parser_markup_fields AS r ON (e.field_type_id = r.\"id\")
LEFT JOIN news.parser_markup_types AS y ON (e.markup_type_id = y.\"id\")
WHERE w.is_actual = TRUE
AND y.title='$type'
--AND q.is_processed=FALSE
AND q.result_status_id=1 or q.result_status_id=4
) AS ttt
WHERE
site='$site'
GROUP BY
ttt.site)e
LIMIT 10";
}
elseif(gettype($site)=="int"||gettype($site)=="integer"){
$query="SELECT
TO_JSON(ARRAY_AGG(e))
FROM
(
SELECT
ttt.site AS site,
json_agg (ttt) AS xpath
FROM
(
SELECT
q.\"id\" AS task_id,
q.is_processed AS is_progress,
w.url AS site,
e.field_markup AS $type,
r.title as \"type\",
r.id as field_type
FROM
\"news\".\"parser_task\" q
LEFT JOIN news.parser_page AS w ON (q.page_id = w.\"id\")
LEFT JOIN news.parser_markup AS e ON (e.\"id\" = q.markup_id)
LEFT JOIN news.parser_markup_fields AS r ON (e.field_type_id = r.\"id\")
LEFT JOIN news.parser_markup_types AS y ON (e.markup_type_id = y.\"id\")
WHERE w.is_actual = TRUE
AND y.title='$type'
AND w.\"id\"=$site
AND q.is_processed=FALSE
) AS ttt
GROUP BY
ttt.site)e
LIMIT 10";
}
else{
echo 'No correct input available';
return null;
}
$json=$this->selectWrapper($this->credentialsVeysato, $query);
return $json;
}
/** получение юзера по id
* @version actual
* @todo work good
* @param type $userSession
* @return type
* @throws type
*/
public function getUserIdBySession ($userSession) {
if (is_file('../common/db_credentials_ro.php')){
include '../common/db_credentials_ro.php';
}
else {
exit("No database credentials available");
}
$credentialsForSpot =
[
'host' => $host,
'db' => $db,
'user' => $user,
'pass' => $pass,
];
$userId = '';
try {
$queryString =
"
SELECT DISTINCT
au.\"id\" as user_id
FROM
jtransport_session sesh
JOIN admin_user au ON sesh.\"user\" = au.\"id\"
WHERE sesh.\"session\" = '".$userSession."'
LIMIT 1
";
} catch (Exception $e){
try{
$erLogData = new ErLogData(
'Query construction error',
ErLogCodes::PG_QUERY_CONSTRUCTION_ERROR,
get_class($e),
$e->getFile(),
__CLASS__,
__FUNCTION__,
$e->getLine(),
date('Y-m-d H:i:s')
);
throw ErLogFactory::create($erLogData, $e);
}
catch (ErLog $ee){
ErLog::full_log_v1($ee);
}
}
$result = $this -> selectWrapper ($credentialsForSpot, $queryString);
if(json_decode($result)) {
$userId = (json_decode($result,true));
} else {
$userId = null;
echo 'User not found!';
return null;
}
return $userId;
}
/**
* приведение и запуск тасков
* @version actual
* @todo сделать масштабируемым для любого количества типов(по имени типа вызывать соостветствующий метод)
* @param string $json
*/
public function prepareTask($json){
if($json!=''){
$array= json_decode($json, TRUE);
foreach ($array as $site){
foreach ($site as $name=>$type){
if(is_array($type)){
//echo $name; //имя метода
if($name=='xpath'){
$this->prepareXpathTask($type);
}
elseif ($name='qqq') {
}
}
}
}
}
else{
echo 'Empty SELECT from DB! Finishing...';
}
}
/**
* для каждого таска xpath вызываем метод для форматирования входа в goXpath
* @version actual
* @param array $tasks
* @version 15.09.16
*/
private function prepareXpathTask($tasks){
//echo json_encode($tasks, JSON_UNESCAPED_UNICODE);
$html=$this->getWebPage('http://'.$tasks[0]['site']);//загружаю страницу 1 раз для 1 сайта а не как раньше для каждого xpath выражения
foreach ($tasks as $task){
$task['url'] = 'http://'.$task['site'];//временно по идее урл в базе долже быть а я его потераял где то
$this->updateParser_task($task['task_id']);
$result=$this->newGoXpath($task,$html);
$this->addParser_result($result);
}
}
/**
* для каждого таска xpath вызываем метод для форматирования входа в goXpath
* @version test
* @param array $tasks
* @version 15.09.16
*/
private function prepareXpathTaskTest($tasks){
//echo json_encode($tasks, JSON_UNESCAPED_UNICODE);
$html=$this->getWebPage('http://'.$tasks[0]['site']);
foreach ($tasks as $task){
$task['url'] = 'http://'.$task['site'];//временно по идее урл в базе долже быть а я его пот ераял где то
//$this->updateParser_task($task['task_id']);
$result=$this->newGoXpathForTest($task,$html);
echo json_encode($result, JSON_UNESCAPED_UNICODE);
//$this->addParser_result($result);
}
}
/**
* приведение и запуск тасков
* @version test
* @todo сделать масштабируемым для любого количества типов(по имени типа вызывать соостветствующий метод)
* @param string $json
*/
public function prepareTaskTest($json){
if($json!=''){
$array= json_decode($json, TRUE);
foreach ($array as $site){
foreach ($site as $name=>$type){
if(is_array($type)){
//echo $name; //имя метода
if($name=='xpath'){
$this->prepareXpathTaskTest($type);
}
elseif ($name='qqq') {
}
}
}
}
}
else{
echo 'Empty SELECT from DB! Finishing...';
}
}
/**
* возращает страницу html в строке с учетом юзерагента и т.п.
* @version actual
* @param string $url
* @return string
*/
public function getWebPage( $url ){
$user_agent='Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0';
$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 =>"cookie.txt", //set cookie file
//CURLOPT_COOKIEJAR =>"cookie.txt", //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 );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['content'] = $content;
return $header['content'];
}
/**
* проверяет результаты и расставляет флаги у тасков в колонке has_problem
* @version actual
* @param int $limit
* @todo на самом деле ее надо переписать, но она существует только ради быстрого отсеивания результатов. + надо дописать дату последнего прогона а не просто все результаты
*/
public function checkResult($limit,$date){
$selectQuery="SELECT
TO_JSON(ARRAY_AGG(eeee))
FROM
(
SELECT
ttt.url AS url,
json_agg (ttt) AS xpath
FROM
(
SELECT
q.id AS task_id,
w.url AS url,
e.field_markup AS xpath,
r.title AS \"type\",
ooo.result
FROM
news.parser_task q
LEFT JOIN news.parser_page AS w ON (q.page_id = w.id)
LEFT JOIN news.parser_markup AS e ON (e.id = q.markup_id)
LEFT JOIN news.parser_markup_fields AS r ON (e.field_type_id = r.id)
LEFT JOIN
(
SELECT
ppp.task_id,
json_agg (ppp) AS result
FROM
(
SELECT
task_id,
id,
result,
counter,
creation_date
FROM
news.parser_result
) AS ppp
GROUP BY
ppp.task_id
) AS ooo ON (q.id=ooo.task_id)
WHERE
w.is_actual = TRUE
AND e.markup_type_id=1
AND q.is_processed = FALSE
AND q.result_status_id = 3
AND q.has_problem='not checked'
AND e.is_actual=TRUE
--AND q.process_date>'$date'
) AS ttt
--WHERE ttt.url='dedoox.com/news/'
GROUP BY
ttt.url
LIMIT $limit
)eeee";
$selectJson=$this->selectWrapper($this->credentialsVeysato,$selectQuery);
if($selectJson!=''){
$answer= json_decode($selectJson, TRUE);
foreach ($answer as $site){
$counter=Null;
$taskId=Null;
//echo count($site['xpath']),'<br>';
if(count($site['xpath'])>1){
foreach ($site['xpath'] as $numberOfResult=>$oneResult){
$counter[$numberOfResult]=count($oneResult['result']);
$taskId[]=$oneResult['task_id'];
}
}else{
$counter[0]=1;
$taskId[]=$site['xpath'][0]['task_id'];
//иначе ставлю статус "мало данных"
}
echo json_encode($taskId, JSON_UNESCAPED_UNICODE),'<br>';
echo array_sum($counter)/ count($counter),'<br>';
if(array_sum($counter)/ count($counter)==$counter[0]){
echo 'Win!!! result is good<br>';
foreach ($taskId as $task){
$this->updateCheckResult($task, 'No problem');
}
}
else{
echo 'You lose... result is bad<br>';
foreach ($taskId as $task){
$this->updateCheckResult($task, 'Has problem');
}
}
}
}
else {
echo 'Empty SELECT from DB! Finishing...';
}
}
/**
* проверяет результаты и расставляет флаги у тасков в колонке has_problem
* @version test работоспособность не проверял, старая слишком, кандидат на удаление
* @param int $limit
*
*/
public function checkResultMan($selectJson){
if($selectJson!=''){
$answer= json_decode($selectJson, TRUE);
foreach ($answer as $site){
$counter;
$taskId;
//echo count($site['xpath']),'<br>';
if(count($site['xpath'])>1){
foreach ($site['xpath'] as $numberOfResult=>$oneResult){
$counter[$numberOfResult]=count($oneResult['result']);
$taskId[]=$oneResult['task_id'];
}
}else{
$counter[0]=1;
$taskId[]=$site['xpath'][0]['task_id'];
//иначе ставлю статус "мало данных"
}
//echo array_sum($counter)/ count($counter);
if(array_sum($counter)/ count($counter)==$counter[0]){
echo 'Win!!! result is good<br>';
foreach ($taskId as $task){
//$this->updateCheckResult($task, 'No problem');
}
}
else{
echo 'You lose... result is bad<br>';
foreach ($taskId as $task){
//$this->updateCheckResult($task, 'Has problem');
}
}
}
}
else {
echo 'Empty SELECT from DB! Finishing...';
}
}
/**
* апдейтит в базе результаты предыдущей функции
* @version actual
* @param type $task_id
* @param type $result
*/
private function updateCheckResult($task_id,$result){
$query="UPDATE news.parser_task
SET
has_problem='$result'
WHERE id=$task_id";
$this->selectWrapper($this->credentialsVeysato,$query);
}
/**
* переводит через пых результаты в старый формат
* @version test
* @return type
* @todo кандидат на удаление так как не используется, и запросы на выгзуку переписаны полностью
*/
public function importResultIntoOldSheme(){
$query="SELECT
TO_JSON(ARRAY_AGG(eeee))
FROM
(
SELECT
ttt.url AS url,
json_agg (ttt) AS xpath
FROM
(
SELECT
q.id AS task_id,
w.url AS url,
e.field_markup AS xpath,
r.title AS \"type\",
ooo.result
FROM
news.parser_task q
LEFT JOIN news.parser_page AS w ON (q.page_id = w.id)
LEFT JOIN news.parser_markup AS e ON (e.id = q.markup_id)
LEFT JOIN news.parser_markup_fields AS r ON (e.field_type_id = r.id)
LEFT JOIN
(
SELECT
ppp.task_id,
json_agg (ppp) AS result
FROM
(
SELECT
task_id,
id,
result,
counter,
date_trunc('hour', creation_date)
FROM
news.parser_result
) AS ppp
GROUP BY
ppp.task_id
) AS ooo ON (q.id=ooo.task_id)
WHERE
w.is_actual = TRUE
AND e.markup_type_id=1
AND q.is_processed = FALSE
AND q.result_status_id = 3
AND q.has_problem='No problem'
AND e.is_actual=TRUE
--AND q.process_date>'2016-07-25 14:59:16.601467'
) AS ttt
WHERE NOT EXISTS
(
SELECT 1 FROM
result_copy2
WHERE result_copy2.url=ttt.url
)
GROUP BY
ttt.url
LIMIT 1
)eeee
";
$json=$this->selectWrapper($this->credentialsVeysato, $query);
if($json!=''){
$result= json_decode($json, TRUE);
$arrayForImport;
foreach ($result[0]['xpath'] as $type) {
foreach ($type['result'] as $counter=>$answer){
$arrayForImport[$answer['counter']][$type['type']]=$answer['result'];
$arrayForImport[$answer['counter']]['url']=$type['url'];
$arrayForImport[$answer['counter']]['time']=$answer['date_trunc'];
}
}
//echo json_encode($arrayForImport, JSON_UNESCAPED_UNICODE);
foreach ($arrayForImport as $row){
$url= pg_escape_string($row['url']);
$xdate=pg_escape_string($row['Date']);
$xtitle=pg_escape_string($row['Title']);
$xpost=pg_escape_string($row['Post']);
$xurl=pg_escape_string($row['Url']);
$time=pg_escape_string($row['time']);
$importQuery="INSERT INTO result_copy2 (url, xdate,xtitle,xpost,xurl,time)
SELECT
'$url',
'$xdate',
'$xtitle',
'$xpost',
'$xurl',
'$time'
";
$this->selectWrapper($this->credentialsVeysato, $importQuery);
echo 'Import succsefully!<br>';
}
return;
}
else {
echo 'Empty SELECT from DB! Finishing...';
return;
}
}
/**
* переводит через пых результаты в старый формат для плохих результатов
* @version test
* @return type
* @todo кандидат на удаление так как не используется, и запросы на выгзуку переписаны полностью
*/
public function importResultIntoOldShemeBad(){
$query="SELECT
TO_JSON(ARRAY_AGG(eeee))
FROM
(
SELECT
ttt.url AS url,
json_agg (ttt) AS xpath
FROM
(
SELECT
q.id AS task_id,
w.url AS url,
e.field_markup AS xpath,
r.title AS \"type\",
ooo.result
FROM
news.parser_task q
LEFT JOIN news.parser_page AS w ON (q.page_id = w.id)
LEFT JOIN news.parser_markup AS e ON (e.id = q.markup_id)
LEFT JOIN news.parser_markup_fields AS r ON (e.field_type_id = r.id)
LEFT JOIN
(
SELECT
ppp.task_id,
json_agg (ppp) AS result
FROM
(
SELECT
task_id,
id,
result,
counter,
date_trunc('hour', creation_date)
FROM
news.parser_result
) AS ppp
GROUP BY
ppp.task_id
) AS ooo ON (q.id=ooo.task_id)
WHERE
w.is_actual = TRUE
AND e.markup_type_id=1
AND q.is_processed = FALSE
AND q.result_status_id = 3
AND q.has_problem='Has problem'
AND e.is_actual=TRUE
--AND q.process_date>'2016-07-25 14:59:16.601467'
) AS ttt
WHERE NOT EXISTS
(
SELECT 1 FROM
result_copy2
WHERE result_copy2.url=ttt.url
)
GROUP BY
ttt.url
LIMIT 1
)eeee
";
$json=$this->selectWrapper($this->credentialsVeysato, $query);
if($json!=''){
$result= json_decode($json, TRUE);
$arrayForImport;
foreach ($result[0]['xpath'] as $type) {
foreach ($type['result'] as $counter=>$answer){
$arrayForImport[$answer['counter']][$type['type']]=$answer['result'];
$arrayForImport[$answer['counter']]['url']=$type['url'];
$arrayForImport[$answer['counter']]['time']=$answer['date_trunc'];
}
}
//echo json_encode($arrayForImport, JSON_UNESCAPED_UNICODE);
foreach ($arrayForImport as $row){
$url= pg_escape_string($row['url']);
$xdate=pg_escape_string($row['Date']);
$xtitle=pg_escape_string($row['Title']);
$xpost=pg_escape_string($row['Post']);
$xurl=pg_escape_string($row['Url']);
$time=pg_escape_string($row['time']);
$importQuery="INSERT INTO result_copy2 (url, xdate,xtitle,xpost,xurl,time)
SELECT
'$url',
'$xdate',
'$xtitle',
'$xpost',
'$xurl',
'$time'
";
$this->selectWrapper($this->credentialsVeysato, $importQuery);
echo 'Import succsefully!<br>';
}
return;
}
else {
echo 'Empty SELECT from DB! Finishing...';
return;
}
}
/**
* выгрузка результатов по сайту
* @version actual
* @param string $url
* @return string
* @todo кандидат на удаление так как не используется
*/
public function checkSite($url){
$query="SELECT
TO_JSON(ARRAY_AGG(eeee))
FROM
(
SELECT
ttt.url AS url,
json_agg (ttt) AS xpath
FROM
(
SELECT
q.id AS task_id,
w.url AS url,
e.field_markup AS xpath,
r.title AS \"type\",
ooo.result
FROM
news.parser_task q
LEFT JOIN news.parser_page AS w ON (q.page_id = w.id)
LEFT JOIN news.parser_markup AS e ON (e.id = q.markup_id)
LEFT JOIN news.parser_markup_fields AS r ON (e.field_type_id = r.id)
LEFT JOIN
(
SELECT
ppp.task_id,
json_agg (ppp) AS result
FROM
(
SELECT
task_id,
id,
result,
counter,
creation_date
FROM
news.parser_result
) AS ppp
GROUP BY
ppp.task_id
) AS ooo ON (q.id=ooo.task_id)
WHERE
w.is_actual = TRUE
AND e.markup_type_id=1
AND q.is_processed = FALSE
--AND q.result_status_id = 3
--AND q.has_problem<>'not checked'
AND q.process_date>'2016-08-04 09:59:16.601467'
AND q.creation_date>'2016-08-04 09:59:16.601467'
AND e.is_actual=TRUE
) AS ttt
WHERE ttt.url='$url'
GROUP BY
ttt.url
--LIMIT 5
)eeee";
$json=$this->selectWrapper($this->credentialsVeysato, $query);
return $json;
}
/**
* create new task if old parsing have ended
*/
public function insertNewTask(){
$query="
WITH last_start AS (
SELECT DISTINCT
creation_date AS last_time
FROM
news.parser_task
ORDER BY
creation_date DESC
LIMIT 1
),
last_finish AS (
SELECT
COUNT (*)
FROM
news.parser_task,
last_start
WHERE
process_date IS NULL
AND creation_date > last_start.last_time - '1 minute' :: INTERVAL
),
insert_rule AS (
SELECT
now() - last_start.last_time AS diff,
now() - last_start.last_time > '6 hour' :: INTERVAL AND last_finish. COUNT = 0 AS is_time_to_insert
FROM
last_start,
last_finish
)
INSERT INTO news.parser_task (markup_id, page_id) SELECT
\"id\",
page_id
FROM
news.parser_markup,insert_rule
WHERE
is_actual = TRUE
AND insert_rule.is_time_to_insert = TRUE
";
$this->selectWrapper($this->credentialsVeysato, $query);
}
}
<file_sep><?php
// run every minute
//require_once '../Xpath/ClassXpath.php';
//$x= new XpathParser;
//$json=$x->getAllNotProceedTaskForAllSite('xpath',2);
//$x->prepareTask($json);
//$x->checkResult(50,'2016-08-19 01:59:16.601467');
echo 'start<br>';
exec("php -f XpathParseForCron.php &");
exec("php -f XpathParseForCron.php &");
echo 'finish<br>';
?>
<file_sep>CREATE TABLE parser_error
(
id INTEGER DEFAULT nextval('parser_error_id_seq'::regclass) PRIMARY KEY NOT NULL,
task_id INTEGER NOT NULL,
creation_date TIMESTAMP(6) NOT NULL,
error_type_id INTEGER NOT NULL,
result VARCHAR NOT NULL
);
CREATE TABLE parser_error_types
(
id INTEGER DEFAULT nextval('parser_error_types_id_seq'::regclass) PRIMARY KEY NOT NULL,
title VARCHAR NOT NULL,
description VARCHAR NOT NULL
);
CREATE TABLE parser_markup
(
id INTEGER DEFAULT nextval('parser_markup_id_seq'::regclass) PRIMARY KEY NOT NULL,
markup_type_id INTEGER NOT NULL,
page_id INTEGER NOT NULL,
is_actual BOOLEAN DEFAULT true,
creation_date TIMESTAMP(6) DEFAULT now() NOT NULL,
creation_user INTEGER NOT NULL,
field_type_id INTEGER NOT NULL,
field_markup TEXT
);
CREATE TABLE parser_markup_fields
(
id INTEGER DEFAULT nextval('parser_markup_fields_id_seq'::regclass) PRIMARY KEY NOT NULL,
title VARCHAR NOT NULL,
description VARCHAR NOT NULL,
report_title VARCHAR NOT NULL
);
CREATE TABLE parser_markup_types
(
id INTEGER DEFAULT nextval('parser_markup_types_id_seq'::regclass) PRIMARY KEY NOT NULL,
title VARCHAR,
description VARCHAR
);
CREATE TABLE parser_page
(
id INTEGER DEFAULT nextval('parser_website_id_seq'::regclass) PRIMARY KEY NOT NULL,
url TEXT NOT NULL,
is_actual BOOLEAN DEFAULT true,
creation_date TIMESTAMP DEFAULT now() NOT NULL,
creation_user INTEGER NOT NULL,
title VARCHAR(255),
description TEXT,
type_id INTEGER
);
CREATE TABLE parser_page_copy
(
id INTEGER DEFAULT nextval('news.parser_website_id_seq'::regclass) PRIMARY KEY NOT NULL,
url TEXT NOT NULL,
is_actual BOOLEAN DEFAULT true,
creation_date TIMESTAMP(6) DEFAULT now() NOT NULL,
creation_user INTEGER NOT NULL,
title VARCHAR(255),
description TEXT,
type_id INTEGER
);
CREATE TABLE parser_page_types
(
id INTEGER DEFAULT nextval('parser_page_types_id_seq'::regclass) PRIMARY KEY NOT NULL,
title VARCHAR NOT NULL,
description VARCHAR NOT NULL
);
CREATE TABLE parser_result
(
id INTEGER DEFAULT nextval('parser_result_id_seq'::regclass) PRIMARY KEY NOT NULL,
task_id INTEGER NOT NULL,
creation_date TIMESTAMP(6) DEFAULT now() NOT NULL,
result TEXT NOT NULL,
counter INTEGER NOT NULL,
field_type INTEGER
);
CREATE TABLE parser_task
(
id INTEGER DEFAULT nextval('parser_task_id_seq'::regclass) PRIMARY KEY NOT NULL,
markup_id INTEGER NOT NULL,
page_id INTEGER NOT NULL,
is_processed BOOLEAN DEFAULT false,
creation_date TIMESTAMP(6) DEFAULT now() NOT NULL,
process_date TIMESTAMP(6),
result_status_id INTEGER DEFAULT 1 NOT NULL,
has_problem VARCHAR(255) DEFAULT 'not checked'::character varying NOT NULL,
status_id INTEGER DEFAULT 1,
similar_task_id INTEGER
);
CREATE TABLE parser_task_result_statuses
(
id INTEGER DEFAULT nextval('parser_task_result_statuses_id_seq'::regclass) PRIMARY KEY NOT NULL,
title VARCHAR NOT NULL,
description VARCHAR NOT NULL
);
CREATE TABLE parser_task_status
(
id INTEGER DEFAULT nextval('parser_task_status_id_seq'::regclass) PRIMARY KEY NOT NULL,
title VARCHAR NOT NULL,
description VARCHAR(255) NOT NULL
);
ALTER TABLE parser_error ADD FOREIGN KEY (task_id) REFERENCES parser_task (id);
ALTER TABLE parser_error ADD FOREIGN KEY (error_type_id) REFERENCES parser_error_types (id);
ALTER TABLE parser_markup ADD FOREIGN KEY (markup_type_id) REFERENCES parser_markup_types (id);
ALTER TABLE parser_markup ADD FOREIGN KEY (page_id) REFERENCES parser_page (id);
ALTER TABLE parser_markup ADD FOREIGN KEY (field_type_id) REFERENCES parser_markup_fields (id);
ALTER TABLE parser_page ADD FOREIGN KEY (type_id) REFERENCES parser_page_types (id);
ALTER TABLE parser_page_copy ADD FOREIGN KEY (type_id) REFERENCES parser_page_types (id);
ALTER TABLE parser_result ADD FOREIGN KEY (task_id) REFERENCES parser_task (id);
ALTER TABLE parser_result ADD FOREIGN KEY (field_type) REFERENCES parser_markup_fields (id);
ALTER TABLE parser_task ADD FOREIGN KEY (markup_id) REFERENCES parser_markup (id);
ALTER TABLE parser_task ADD FOREIGN KEY (result_status_id) REFERENCES parser_task_result_statuses (id);
ALTER TABLE parser_task ADD FOREIGN KEY (status_id) REFERENCES parser_task_status (id)CREATE FUNCTION get_all_news_json() RETURNS TABLE(JSON JSON);
CREATE FUNCTION get_clear_news_json() RETURNS TABLE(JSON JSON);
CREATE FUNCTION tf_on_parser_markup_insert() RETURNS TRIGGER;
CREATE FUNCTION tf_on_parser_page_insert() RETURNS TRIGGER;
CREATE FUNCTION tf_on_parser_result_insert() RETURNS TRIGGER;
<file_sep><?php
require_once '../Xpath/ClassXpath.php';
$x= new XpathParser;
$json=$x->getAllNotProceedTaskForAllSite('xpath',1);
$x->prepareTask($json);
$x->checkResult(50,'2016-08-19 01:59:16.601467');
echo 'ok';
?>
|
cdc6937579fa1c6c3b9c6711250e90ac6b884ade
|
[
"SQL",
"PHP"
] | 4
|
PHP
|
Kozloff/xpath_parser
|
fac0407e05a5837f9d11a9a2050fb0af946fc44a
|
dc2c87751bfcc5bc894a9360748b939af8ef28a7
|
refs/heads/master
|
<file_sep>package se.lexicon.javagroup30.model;
public class Person {
// private int personId=0;
final int personId; // final was made but with initiallization???
String firstName;
String lastName;
// Constructor
// Problem is that it is not letting define constructor
// Eric says ONLY Getter is needed for ID
// Have to check the lecture of Pet when he creates ID
// and create constructors etc. likewise
public Person(int personId)
{
this.personId= personId;
}
public Person(int personId, String firstName, String lastName)
{
this.personId = personId;
this.firstName = firstName;
this.lastName = lastName;
}
// public Person() { } // Bycreating this constructor, we can use both constructors Person(), Person(firstName, lastName) in App and testing
//Getters and Setters
// No setter for personId since it is index
public int getPersonId() {
return personId;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
}
<file_sep>package se.lexicon.javagroup30.model;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import se.lexicon.javagroup30.data.PersonSequencer;
import se.lexicon.javagroup30.data.TodoSequencer;
import static org.junit.Assert.assertEquals;
public class PersonTest {
private Person testObjectPerson;
@Before
public void setUp() throws Exception {
// testObject = new Person("a","b"); // In this scenario, assigning Nadeem vaxjo value will not create any effect.
//Eftersom in third and last line, the values are set with ”Test” and ”Test LastName”.
testObjectPerson = new Person( PersonSequencer.nextPersonId(),"Test","Test Last Name");
/*
testObjectPerson.
testObjectPerson.setFirstName("Test");
testObjectPerson.setLastName("Test Last Name");
*/
}
@Test //For testing Person Class
public void testobject_for_Peson_class_That_either_correct_fieldsare_OK_for_FIRST_ID_incremen() {
assertEquals(1,testObjectPerson.getPersonId());
assertEquals("Test", testObjectPerson.getFirstName());
assertEquals("Test Last Name", testObjectPerson.getLastName());
}
@Test //For testing Person Class
public void testobject_for_Peson_class_That_either_correct_fieldsare_OK_for_FIRST_ID_increment_for_Incrementing_Second_Time() {
assertEquals(2,testObjectPerson.getPersonId());
assertEquals("Test", testObjectPerson.getFirstName());
assertEquals("Test Last Name", testObjectPerson.getLastName());
}
/*
@After
public static void afterClass() throws Exception {
PersonSequencer.reset();
}
*/
}
<file_sep>package se.lexicon.javagroup30.data;
import com.sun.xml.internal.bind.v2.TODO;
import se.lexicon.javagroup30.model.Person;
import se.lexicon.javagroup30.model.Todo;
import java.util.Arrays;
public class TodoItems {
private static Todo[] Todos = new Todo[0];
public int size() {
return Todos.length;
}
public Todo[] findAll() {
return Todos;
}
public Todo findById(int TodoId) {
Todo[] newarray = new Todo[0];
Todo send = null;
for (Todo name : Todos) {
if (name.getTodoid() == TodoId)
send = name;
}
return send;
}
public Todo addTodo(String todoName, String todolastName, String tododesc,Boolean todoDone) {
Todo todothing = new Todo(TodoSequencer.nextTodoId(), tododesc, todoDone, new Person(PersonSequencer.nextPersonId(),todoName, todolastName));
Todos = Arrays.copyOf(Todos, Todos.length + 1);
Todos[Todos.length - 1] = todothing;
return todothing;
}
public void clear() {
Todos = new Todo[0];
}
public Todo[] findByDoneStatus(boolean doneStatus){
Todo[] newDonearray = new Todo[0];
for(int i=0;i<Todos.length;i++)
{
if(Todos[i].getDone()==true)
{
newDonearray[i]=Todos[i];
}
}
return newDonearray;
}
public Todo[] findByAssignee(int personId){
for(int i=0;i<Todos.length;i++)
if(Todos[i].getTodoid()==personId)
{
return Todos;
}
return null;
}
public Todo[] findByAssignee(Person assignee)
{
for(int i=0;i<Todos.length;i++)
if(Todos[i].getAssignee()==assignee) // Is it Persons in Todos
{
return Todos;
}
return null;
}
public Todo[] findUnassignedTodoItems(){
Todo[] checkAssignees = new Todo[0];
for(int i=0;i<Todos.length;i++)
//if(Todos[i].s
{
// checkAssignees[i]=Todos[i].getAssignee();
}
return checkAssignees;
}
public boolean remove(int ToId){
// boolean isremoved=false;
//3 Rana
//4 Mustansar
//5 Hamid
boolean flagTD=false;
int TDsize = Todos.length;
//System.out.println("o edhar"+TDsize);
Todo[] toremoveTD = new Todo[0];
Todo[] before = new Todo[TDsize];
Todo[] after = new Todo[TDsize];
Todo[] after1 = Arrays.copyOf(after,after.length+1);
Todo[] combined = new Todo[TDsize-1];
int index=0;
int beforeind=0;
int afterind=0;
int combindex=0;
for(int i=0;i<Todos.length;i++)
{
if(Todos[i]==null)
System.out.println("No element found in the TodoItems array");
else if(Todos[i].getTodoid()==ToId)
index=i;
}
for(int i=0;i<Todos.length;i++)
{
if(i<index)
{
before[i] = Todos[i];
beforeind++;
combindex++;
}
else
{
if(i==2) {
after1[i] = Todos[i];
}
else
after1[i] = Todos[i + 1];
//System.out.println(after1[i].getFirstName());
// System.out.println(persons[i].getFirstName());
afterind++;
combindex++;
}
}
//Person[] combined1 = Arrays.copyOf(combined,combined.length+1);
for(int i=0;i<combindex-1;i++) {
if(i<beforeind)
combined[i]=before[i];
else
{combined[i]=after1[i];
flagTD=true;
}
}
//for(int i=0;i<any.length;i++) //Todo-> Person-> fields
// System.out.println((any[i].getAssignee().getFirstName()));
for(int i=0;i<TDsize-1;i++)
System.out.println(combined[i].getAssignee().getFirstName());
return flagTD;
}
}
<file_sep>package se.lexicon.javagroup30.data;
import se.lexicon.javagroup30.model.Person;
import java.util.Arrays;
public class People {
private static Person[] persons = new Person[0];
//Person[] perarr = new Person();
//Person perarr = new Person(1,"a","b");
// People personarrvar = new Person[];
public int size() {
return persons.length;
}
public Person[] findAll() {
return persons;
}
public Person findById(int personId) {
Person[] newarray = new Person[0];
Person send = null;
for (Person name : persons) {
if (name.getPersonId() == personId)
send = name;
}
return send;
}
public Person addPerson(String personName, String lastName) {
Person person = new Person(PersonSequencer.nextPersonId(), personName, lastName);
persons = Arrays.copyOf(persons, persons.length + 1);
persons[persons.length - 1] = person;
return person;
}
public void clear() {
persons = new Person[0];
}
public boolean remove(int personId) {
// boolean isremoved=false;
//6 Rana //Kanske 3 också
//4 Mustansar
//5 Hamid
Boolean flag = false;
int persize = persons.length;
Person[] toremovearr = new Person[0];
Person[] before = new Person[persize];
Person[] after = new Person[persize];
Person[] after1 = Arrays.copyOf(after, after.length + 1);
Person[] combined = new Person[persize - 1];
int index = 0;
int beforeind = 0;
int afterind = 0;
int combindex = 0;
for (int i = 0; i < persons.length; i++) { // Loop to find person (to be removed) index
if (persons[i] == null)
System.out.println("No element found in the People array");
else if (persons[i].getPersonId() == personId)
index = i;
}
for (int i = 0; i < persons.length; i++) { // Before and after are two arrays used to remove the person
if (i < index) { //Combined is the final array
before[i] = persons[i];
beforeind++;
combindex++;
} else {
if (i == 2) {
after1[i] = persons[i];
} else
after1[i] = persons[i + 1];
//System.out.println(after1[i].getFirstName());
// System.out.println(persons[i].getFirstName());
afterind++;
combindex++;
}
}
//Person[] combined1 = Arrays.copyOf(combined,combined.length+1);
for (int i = 0; i < combindex - 1; i++) {
if (i < beforeind)
combined[i] = before[i];
else {
combined[i] = after1[i];
flag = true;
}
}
//for(int i=0;i<any.length;i++) //Todo-> Person-> fields
// System.out.println((any[i].getAssignee().getFirstName()));
System.out.println("Persons left in the persons array after removing a person");
for (int i = 0; i < persize - 1; i++) {
System.out.print(combined[i].getPersonId() + " ");
System.out.println(combined[i].getFirstName());
}
return flag;
}
}
<file_sep>package se.lexicon.javagroup30.dataTest;
import org.junit.Assert;
import org.junit.Test;
import se.lexicon.javagroup30.data.PersonSequencer;
public class PersonSequencerTest {
@Test
public void Test_Method_to_check_Person_counter_sequencer_is_generating_ID() {
Assert.assertEquals(PersonSequencer.nextPersonId(),1);
}
@Test
public void Test_Method_to_check_Person_counter_sequencer_is_generating_I888D() {
Assert.assertEquals(PersonSequencer.nextPersonId(),2);
}
@Test
public void Test_to_ensure_that_Person_counter_sequencer_is_set_to_null() {
int num2=0;
//PersonSequencer.reset();
// Assert.assertEquals(PersonSequencer.reset(),0);
}
}
<file_sep>package se.lexicon.javagroup30;
import se.lexicon.javagroup30.data.People;
import se.lexicon.javagroup30.data.PersonSequencer;
import se.lexicon.javagroup30.data.TodoItems;
import se.lexicon.javagroup30.data.TodoSequencer;
import se.lexicon.javagroup30.model.Person;
import se.lexicon.javagroup30.model.Todo;
import java.util.Arrays;
/**
* TODO IT Work
*/
public class App {
public static void main(String[] args) {
System.out.println("\n");
System.out.println("\n");
System.out.println("A single Person Ref. Person ");
Person person1 = new Person(PersonSequencer.nextPersonId(), "Muhammad", "Yousuf");
Person person2 = new Person(PersonSequencer.nextPersonId(), "Muhammad", "Salah-Ud-Din");
Person person3 = new Person(PersonSequencer.nextPersonId(), "Amer", "Rasheed");
Person person4 = new Person(PersonSequencer.nextPersonId(), "Erk", "Svensson");
Person person5 = new Person(PersonSequencer.nextPersonId(), "Tobias", "Johnsson");
System.out.print(person1.getPersonId() + " ");
System.out.print(person1.getFirstName() + " ");
System.out.print(person1.getLastName() + "\n"); //Output 1 Muhammad Yousuf
System.out.print(person2.getPersonId() + " ");
System.out.print(person2.getFirstName() + " ");
System.out.print(person2.getLastName() + "\n"); //2 Muhammad Salah-Ud-Din
System.out.print(person3.getPersonId() + " ");
System.out.print(person3.getFirstName() + " ");
System.out.print(person3.getLastName() + "\n"); //Output 1 Muhammad Yousuf
System.out.print(person4.getPersonId() + " ");
System.out.print(person4.getFirstName() + " ");
System.out.print(person4.getLastName() + "\n"); //2 <NAME>-Ud-Din
System.out.print(person5.getPersonId() + " ");
System.out.print(person5.getFirstName() + " ");
System.out.print(person5.getLastName() + "\n"); //2 <NAME>-Ud-Din
System.out.println("\n");
System.out.println("\n");
System.out.println("People Ref. People (Array of persons ");
People p = new People();
Person var0 = p.addPerson("Rana", "Waqas"); /*p.addPerson ==== In which person is being called with TWO parameters eftersom addPerson method has two parameters */
System.out.print(var0.getPersonId() + " ");
System.out.println(var0.getFirstName());
System.out.println("Adding Persons to People Ref. Q.8 e ");
Person var1 = p.addPerson("Mustansar", "Khan");
System.out.print(var1.getPersonId() + " ");
System.out.println(var1.getFirstName());
Person var2 = p.addPerson("Hamid", "Pia");
System.out.print(var2.getPersonId() + " ");
System.out.println(var2.getFirstName());
System.out.println("Size of People array is " + p.size());
System.out.println("\n");
System.out.println("\n");
System.out.println("Removing Person Ref. Q.11");
boolean removal = p.remove(8);
if (removal)
System.out.println("The person is successfully removed ");
//System.out.println("Size of People array AFTER is "+p.size());
System.out.println("\n");
System.out.println("\n");
System.out.println("Adding more persons to PEOPLE array");
Person var3 = p.addPerson("Asad", "Ullah");
System.out.print(var3.getPersonId() + " ");
System.out.println(var3.getFirstName());
Person var4 = p.addPerson("Uffe", "Kock");
System.out.print(var4.getPersonId() + " ");
System.out.println(var4.getFirstName());
System.out.println("\n");
System.out.println("\n");
System.out.println("Finding all persons in People Ref. Q.8 c");
Person[] peopleArray = p.findAll();
for (int i = 0; i < peopleArray.length; i++) {
System.out.print((peopleArray[i].getPersonId()));
System.out.print(" " + peopleArray[i].getFirstName());
System.out.println(" " + peopleArray[i].getLastName());
}
System.out.println("Size of People array is " + p.size());
System.out.println("\n");
System.out.println("\n");
System.out.println("To do Assginees Ref. TodoItems");
TodoItems td = new TodoItems();
td.addTodo("Handla", "Willys", "<NAME>", true);
td.addTodo("Byta", "<NAME>", "på helgen", false);
td.addTodo("Listen", "Lecture", "Udemi", false);
System.out.println("Removing TodoItems Ref.Q.11");
Todo[] any = td.findByAssignee(3);
System.out.println("The assignees tasks before removal of an object are ");
if (any != null)
for (int i = 0; i < any.length; i++) //Todo-> Person-> fields
{
System.out.print(any[i].getTodoid()+" ");
System.out.print((any[i].getAssignee().getFirstName()) + " ");
System.out.print((any[i].getAssignee().getLastName()) + " ");
System.out.println((any[i].getDescription()));
}
System.out.println("\n");
System.out.println("The assignees tasks after removal of an object are ");
// System.out.println(td.size());
boolean removeTDitem = td.remove(4);
if(removeTDitem)
System.out.println("The person is successfully removed ");
System.out.println("\n");
//System.out.println("Size of People array AFTER is "+p.size());
// System.out.println(td.size());
System.out.println("Addng more TodoItems to the array");
td.addTodo("Sluta", "TodoIT", "på helgen", true);
td.addTodo("Boka", "Billjet", "Perth", false);
td.addTodo("Deliver", "Schedule", "Nästa vecka", true);
Todo[] any1 = td.findByAssignee(3);
System.out.println("The assignees tasks are ");
if (any1 != null)
for (int i = 0; i < any1.length; i++) //Todo-> Person-> fields
{
System.out.print(any1[i].getTodoid()+" ");
System.out.print((any1[i].getAssignee().getFirstName()) + " ");
System.out.print((any1[i].getAssignee().getLastName()) + " ");
System.out.println((any1[i].getDescription()));
}
System.out.println("The size of TodoItems array now becomes "+td.size());
System.out.println("\n");
System.out.println("\n");
System.out.println("Things to do Ref. Todo ");
//Printing first line of Todo(Things to do)
Todo thingTodo1 = new Todo(TodoSequencer.nextTodoId(), "First task done", true, person1);
Todo thingTodo2 = new Todo(TodoSequencer.nextTodoId(), "Second task done", false, person2);
Todo thingTodo3 = new Todo(TodoSequencer.nextTodoId(), "Third task done", true, person3);
Todo thingTodo4 = new Todo(TodoSequencer.nextTodoId(), "Fourth task done", false, person4);
System.out.print(thingTodo1.getAssignee().getPersonId() + " ");
System.out.print(thingTodo1.getAssignee().getFirstName() + " ");
System.out.print(thingTodo1.getAssignee().getLastName() + " "); //2 <NAME>
System.out.print(" (" + thingTodo1.getTodoid() + ") ");
System.out.print(thingTodo1.getDescription() + " ");
System.out.print(thingTodo1.getDone() + " "); //1 First thing done true
System.out.print("(" + thingTodo2.getTodoid() + ") ");
System.out.print(thingTodo2.getDescription() + " ");
System.out.print(thingTodo2.getDone() + "\n"); //2 Second thing done true
//Printing second line of Todo(Things to do)
System.out.print(thingTodo2.getAssignee().getPersonId() + " ");
System.out.print(thingTodo2.getAssignee().getFirstName() + " ");
System.out.print(thingTodo2.getAssignee().getLastName() + " "); //2 <NAME>
System.out.print(" (" + thingTodo2.getTodoid() + ") ");
System.out.print(thingTodo2.getDescription() + " ");
System.out.print(thingTodo2.getDone() + " "); //1 First thing done true
System.out.print("(" + thingTodo1.getTodoid() + ") ");
System.out.print(thingTodo1.getDescription() + " ");
System.out.print(thingTodo1.getDone() + "\n"); //2 Second thing done true
//Printing THIRD line of Todo(Things to do)
System.out.print(thingTodo3.getAssignee().getPersonId() + " ");
System.out.print(thingTodo3.getAssignee().getFirstName() + " ");
System.out.print(thingTodo3.getAssignee().getLastName() + " "); //2 <NAME>
System.out.print(" (" + thingTodo3.getTodoid() + ") ");
System.out.print(thingTodo3.getDescription() + " ");
System.out.print(thingTodo3.getDone() + " "); //1 First thing done true
System.out.print("(" + thingTodo1.getTodoid() + ") ");
System.out.print(thingTodo1.getDescription() + " ");
System.out.print(thingTodo1.getDone() + "\n"); //2 Second thing done true
//Printing FOURT line of Todo(Things to do)
System.out.print(thingTodo4.getAssignee().getPersonId() + " ");
System.out.print(thingTodo4.getAssignee().getFirstName() + " ");
System.out.print(thingTodo4.getAssignee().getLastName() + " "); //2 <NAME>-Ud-Din
System.out.print(" (" + thingTodo3.getTodoid() + ") ");
System.out.print(thingTodo3.getDescription() + " ");
System.out.print(thingTodo3.getDone() + " "); //1 First thing done true
System.out.print("(" + thingTodo4.getTodoid() + ") ");
System.out.print(thingTodo4.getDescription() + " ");
System.out.print(thingTodo4.getDone() + "\n"); //2 Second thing done trueSystem.out.println("\n");
System.out.println("\n");
}
}
<file_sep>package se.lexicon.javagroup30.model;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import se.lexicon.javagroup30.data.TodoSequencer;
import static org.junit.Assert.assertEquals;
public class TodoTest {
private Todo testObjectTodo;
@Before
public void setUp() throws Exception {
testObjectTodo = new Todo(TodoSequencer.nextTodoId(),"Todo description",true, new Person(TodoSequencer.nextTodoId(),"Amer","Rasheed"));
/*Here tricky part was to pass Person type class parameters */
/*Here Todosequencer is generating ID*/
/*"Amer" is the firstName and "Rasheed" is the lastName (From Person type)*/
/*
testObjectTodo.setTodoid(50);
testObjectTodo.setDescription("Todo description");
testObjectTodo.setDone(true);
testObjectTodo.setAssignee();
*/
}
@Test
public void testing_whether_Todo_class_fields_are_correct() {
//assertEquals(1,"Todo description",true,Muhammad,TodoSequencer.nextTodoId(),testObjectTodo.getDescription(),testObjectTodo.getDone(),testObjectTodo.getAssignee());
//
assertEquals(1,testObjectTodo.getTodoid());
assertEquals("Todo description",testObjectTodo.getDescription());
assertEquals(true, testObjectTodo.getDone());
assertEquals("Amer", testObjectTodo.getAssignee().getFirstName()); /*Here "Amer" is being compared with Person type variable assignee
and then with firstName of Peson
The sequence is testobject->
get Todo class+Person class variable assignee ->
Person class firstName variable */
assertEquals("Rasheed",testObjectTodo.getAssignee().getLastName());
}
}
|
74d8f34a3f118367e8eb9de6f9c1f4f899d54395
|
[
"Java"
] | 7
|
Java
|
AmerRasheed/Todo-First-Week-Work-
|
8b6726ad4c8ebb1084acb9f8fa38d4f978f7c1f0
|
f41958980fafdd20ca47858aabfd47432ceeedec
|
refs/heads/master
|
<file_sep>const cassandra = require('cassandra-driver');
const client = new cassandra.Client({
contactPoints: [process.env.CASS_CONTACT],
localDataCenter: process.env.CASS_DATACENTER,
keyspace: process.env.CASS_KEYSPACE,
});
module.exports = function runQuery(strings, ...args) {
const query = strings.map(str => str.replace(/\n/gi, '').trim()).join(' ? ');
return client.execute(query, args, { prepare: true });
};
<file_sep>module.exports = function rowsToArticles(rows) {
return rows.map(row => ({
id: row.id,
created: row.created,
title: row.title,
next: row.next || null,
prev: row.prev || null,
content: JSON.parse(row.content),
}));
};
<file_sep>import { useCallback, useRef } from 'react';
const useAttachableCallback = <F extends Function>(): [
React.MutableRefObject<F | null>,
(fn: F) => void,
] => {
const cb = useRef<null | F>(null);
const attach = useCallback((fn: F) => {
cb.current = fn;
}, []);
return [cb, attach];
};
export default useAttachableCallback;
<file_sep>import { useCallback, useEffect, useRef } from 'react';
import useAttachableCallback from './useAttachableCallback';
const useVisible = <E extends Element>() => {
const nodeToPosition = useRef(new Map<E, number>());
const nodeToVisibleState = useRef(new Map<E, boolean>());
// instantiate the observer and create a method for observing new elements
const observer = useRef<null | IntersectionObserver>(null);
const addNode = useCallback((newNode: E, index: number) => {
if (observer.current && !nodeToPosition.current.has(newNode)) {
observer.current.observe(newNode);
nodeToPosition.current.set(newNode, index);
nodeToVisibleState.current.set(newNode, false);
}
}, []);
// set up the callbacks for when the first and last visible items change
const [firstVisibleCallback, onFirstVisibleChange] = useAttachableCallback<
(node: E, index: number) => void
>();
const [visibleChangeCallback, onVisibleChange] = useAttachableCallback<
(visibleIdxs: number[]) => void
>();
useEffect(() => {
type ElementWithPosition = [number, E];
observer.current = new IntersectionObserver(
entries => {
const newlyVisibleEntries = entries
.filter(node => node.isIntersecting)
.map(
({ target }) =>
[
nodeToPosition.current.get(target as E),
target,
] as ElementWithPosition,
)
.sort((a, b) => a[0] - b[0]);
const newlyHiddenEntries = entries
.filter(node => !node.isIntersecting)
.map(
({ target }) =>
[
nodeToPosition.current.get(target as E),
target,
] as ElementWithPosition,
)
.sort((a, b) => a[0] - b[0]);
// mark the appropriate visible/hidden states
newlyVisibleEntries.forEach(([_, el]) =>
nodeToVisibleState.current.set(el, true),
);
newlyHiddenEntries.forEach(([_, el]) =>
nodeToVisibleState.current.set(el, false),
);
const firstNewlyVisible = newlyVisibleEntries[0];
if (firstNewlyVisible && firstVisibleCallback.current) {
firstVisibleCallback.current(
firstNewlyVisible[1],
firstNewlyVisible[0],
);
}
if (visibleChangeCallback.current) {
const visibleIdxs = Array.from(nodeToVisibleState.current.entries())
.reduce((acc, [el, isVisble]) => {
const idx = nodeToPosition.current.get(el);
if (isVisble && idx !== undefined) {
acc.push(idx);
}
return acc;
}, [] as number[])
.sort((a, b) => a - b);
visibleChangeCallback.current(visibleIdxs);
}
},
{ threshold: 0.25 },
);
return () => {
observer.current && observer.current.disconnect();
};
}, [firstVisibleCallback, visibleChangeCallback]);
return {
addNode,
onFirstVisibleChange,
onVisibleChange,
};
};
export default useVisible;
<file_sep>const rowsToArticles = require('../../helpers/rowsToArticles');
const queries = require('../../db/queries');
module.exports = ({ id }) =>
queries
.getArticle(id)
.then(data => rowsToArticles(data.rows)[0] || null)
.catch(error => {
console.error(error);
throw error;
});
<file_sep>const bodyParser = require('body-parser');
const cors = require('cors');
const express = require('express');
const gql = require('./gql');
const app = express();
const VALID_ORIGINS = new Set(['www.niranjan.me', 'niranjan.me']);
// enable CORS
app.use(
cors({
origin: (origin, callback) =>
VALID_ORIGINS.has(origin) || process.env.NODE_ENV !== 'production'
? callback(null, true)
: callback(new Error('Not Allowed (CORS)')),
}),
);
// attach gql
app.use(bodyParser.json());
app.get('/', gql);
app.post('/', (req, res, next) => {
const { query } = req.body;
if (query) {
if (query.includes('mutation')) {
console.log('\n\033[0;35m[mutation]\033[0m');
console.log(query);
} else {
console.log('\n\033[0;32m[query]\033[0m');
console.log(query);
}
}
next();
});
app.use(gql);
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log('GQL server running on', port);
});
<file_sep># Articles
```
create table articles (
partition_key int,
created double,
id int,
title text,
next int,
prev int,
content text,
PRIMARY KEY (partition_key, id)
);
```
<file_sep>const runQuery = require('./runQuery');
module.exports = {
createArticle: (title, content, id, created, prev) => runQuery`
INSERT INTO articles (
partition_key,
id,
created,
title,
content,
prev
) values (
1,
${id},
${created},
${title},
${content},
${prev}
)
`,
createFirstArticle: (title, content, created) => runQuery`
INSERT INTO articles (
partition_key,
id,
created,
title,
content
) values (
1,
1,
${created},
${title},
${content}
)
`,
getArticle: id => runQuery`
SELECT id, created, title, next, prev, content
FROM articles
WHERE id = ${id} AND partition_key = 1
`,
getLatestArticles: count => runQuery`
SELECT id, created, title, next, prev, content
FROM articles
WHERE partition_key = 1
ORDER BY id
DESC
LIMIT ${count}
`,
getLastestArticlesAfter: (count, after) => runQuery`
SELECT id, created, title, next, prev, content
FROM articles
WHERE partition_key = 1 AND id < ${after}
ORDER BY id
DESC
LIMIT ${count}
`,
updateArticleNextPointer: (id, next) => runQuery`
UPDATE articles
SET next = ${next}
WHERE id = ${id} AND partition_key = 1
`,
};
<file_sep>module.exports = {
createArticle: require('./createArticle'),
getArticle: require('./getArticle'),
getLatestArticles: require('./getLatestArticles'),
};
<file_sep>import { useContext, useState } from 'react';
import { pipe, subscribe } from 'wonka';
import { Context, createRequest } from 'urql';
import { Node } from '../components/display/RichText';
import useIsMounted from './useIsMounted';
interface Article {
content: Node[];
created: number;
id: number;
title: string;
}
interface State {
articles: Article[];
error: any;
pending: boolean;
}
const getArticles = `
query ArticleListing($count: Int!, $after: ID) {
getLatestArticles(count: $count, after: $after) {
created
id
title
content {
...child
children {
...child
children {
...child
children {
...child
}
}
}
}
}
}
fragment child on Node {
bold
code
italic
text
type
underline
}
`;
interface Options {
count?: number;
startingId?: number;
}
const useArticles = (options: Options = {}) => {
const [state, setState] = useState<State>({
articles: [],
error: null,
pending: false,
});
const client = useContext(Context);
const isMounted = useIsMounted();
const loadMore = () => {
if (state.pending) return;
setState(prev => ({ ...prev, pending: true }));
const lastArticle = state.articles[state.articles.length - 1];
// Ids are sequential, with older items having a lower Id than a newer item.
// If we want to include the article that the startingId represents, we need
// to use an `after` that is slightly larger than the startingId.
const after = lastArticle
? lastArticle.id
: options.startingId
? options.startingId + 1
: undefined;
const request = createRequest(getArticles, {
after,
count: options.count || 1,
});
pipe(
client.executeQuery(request),
subscribe(({ data, error }) => {
const articles = state.articles.concat(
(data && data.getLatestArticles) || [],
);
if (isMounted.current) {
setState({
articles,
error: error || null,
pending: false,
});
}
}),
);
};
return { ...state, loadMore };
};
export default useArticles;
<file_sep>const nacl = require('tweetnacl');
const equals = require('ramda/src/equals');
const getLatestArticles = require('./getLatestArticles');
const queries = require('../../db/queries');
const pkeyStr = process.env.PUBLIC_KEY || '';
const publicKey = new Uint8Array(pkeyStr.split(','));
module.exports = async ({ boxedContent, boxedTitle, content, title }) => {
const contentStr = JSON.stringify(content);
const created = Date.now();
const [latestArticle] = await getLatestArticles(1);
const decoder = new TextDecoder();
const unboxedContent = JSON.parse(
decoder.decode(
nacl.sign.open(new Uint8Array(boxedContent.split(',')), publicKey),
),
);
const unboxedTitle = decoder.decode(
nacl.sign.open(new Uint8Array(boxedTitle.split(',')), publicKey),
);
if (!equals(unboxedContent, content) || unboxedTitle !== title) {
console.log('Not Authorized');
throw new Error('Not Authorized');
}
if (latestArticle) {
const prev = latestArticle.id;
const id = prev + 1;
return queries
.createArticle(title, contentStr, id, created, prev)
.then(() => {
// if we successfully created the article, update the previous latest
// article to point to this one.
return queries.updateArticleNextPointer(prev, id).then(() => true);
})
.catch(error => {
console.error(error);
throw error;
});
}
return queries
.createFirstArticle(title, contentStr, created)
.then(() => true)
.catch(error => {
console.error(error);
throw error;
});
};
<file_sep>import { useRef, useEffect } from 'react';
const useIsMounted = () => {
const mountState = useRef(false);
useEffect(() => {
mountState.current = true;
return () => {
mountState.current = false;
};
}, []);
return mountState;
};
export default useIsMounted;
<file_sep>const rowsToArticles = require('../../helpers/rowsToArticles');
const queries = require('../../db/queries');
module.exports = ({ count, after }) =>
(after
? queries.getLastestArticlesAfter(count, after)
: queries.getLatestArticles(count)
)
.then(data => rowsToArticles(data.rows))
.catch(error => {
console.error(error);
throw error;
});
<file_sep>export enum Type {
Blockquote = 'block-quote',
Bold = 'bold',
Code = 'code',
H1 = 'heading-one',
H2 = 'heading-two',
Italic = 'italic',
ListItem = 'list-item',
OL = 'numbered-list',
Paragraph = 'paragraph',
UL = 'bulleted-list',
Underline = 'underline',
}
export type ElementType =
| Type.Blockquote
| Type.H1
| Type.H2
| Type.OL
| Type.ListItem
| Type.Paragraph
| Type.UL;
export type LeafType = Type.Bold | Type.Code | Type.Italic | Type.Underline;
export const Lists = new Set([Type.UL, Type.OL]);
<file_sep>const { buildSchema } = require('graphql');
module.exports = buildSchema(`
type Node {
bold: Boolean
children: [Node]
code: Boolean
italic: Boolean
text: String
type: String
underline: Boolean
}
type Article {
id: ID!
title: String!
created: Float!
next: String
prev: String
content: [Node]
}
type Query {
getArticle(id: ID!): Article
getLatestArticles(count: Int!, after: ID): [Article]
}
input ContentNode {
bold: Boolean
children: [ContentNode]
code: Boolean
italic: Boolean
text: String
type: String
underline: Boolean
}
type Mutation {
createArticle(title: String!, content: [ContentNode]!, boxedContent: String!, boxedTitle: String!): Boolean
}
`);
|
66f475a3196bb08e3d7765d383a930590dbf788f
|
[
"JavaScript",
"TypeScript",
"Markdown"
] | 15
|
JavaScript
|
nramadas/niranjan
|
a9a01c59ad729d07c1fc1147455b1d3eb37d62fe
|
7c44cedc23a73fa94e03e4ab2085858a67bb0b1b
|
refs/heads/master
|
<repo_name>CliffRegis/postit_temp<file_sep>/app/helpers/application_helper.rb
module ApplicationHelper
def display_url(str)
str.starts_with?('http://') ? str : "http://#{str}"
end
end
<file_sep>/app/controllers/posts_controller.rb
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :vote]
before_action :require_user, except: [:index, :show]
before_action :require_same_user, only:[:edit, :update]
def index
@posts = Post.all.sort_by{|x| x.total_votes}.reverse
end
def show
@comment = Comment.new
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
@post.creator = current_user
if @post.save(post_params)
flash[:notice] = "Your post was saved"
redirect_to posts_path
else
render "new"
end
end
def edit
end
def update
if @post.update(post_params)
flash[:notice] = "Your post was updated"
redirect_to post_path
else
render "edit"
end
end
def vote
@vote = Vote.create(voteable: @post, creator: current_user, vote: params[:vote])
if @vote.valid?
flash[:error] = "You voted!"
redirect_to :back
else
flash[:notice] = "Something went wrong!"
redirect_to root_path
end
end
private
def post_params # SO YOU CAN USE THE FIELD ON THE FORMS
params.require(:post).permit(:url, :name, :body, :comment, :category, :creator, :username, :title, :description, category_ids: [])
end
def set_post
@post = Post.find(params[:id])
end
def require_same_user
@user = User.find(params[:id])
if current_user != @user
flash[:error] = "you cannot do that!"
redirect_to posts_path
end
end
end
<file_sep>/config/routes.rb
PostitTemplate::Application.routes.draw do
root to: 'posts#index'
# resources :posts, except:[:destroy] do
# #resources :comments, only:[:create]
# end
resources :posts, except:[:destroy] do
member do
post 'vote'
end
resources :comments, only:[:create]
end
resources :comments, only:[:show] do
member do
post 'vote'
end
end
# resources :posts, except:[:destroy] do
# member do
# post :votes, only:[:create]
# end
# end
resources :categories, only:[:new, :create, :show]
resources :users, except:[:index, :destroy]
get '/login', to: "sessions#new"
post '/login', to: "sessions#create"
delete '/logout', to: "sessions#destroy"
end
# get '/register', to: "users#new"
# post '/register', to: "users#create"
# get '/profile', to: "users#show"
# get '/edit_profile', to: "users#edit"
# patch '/profile', to: "users#update"<file_sep>/app/models/user.rb
class User < ActiveRecord::Base
has_many :posts
has_many :comments
has_many :votes
has_secure_password validations: false
validates :username, uniqueness: true
validates :password, on: :create, length: {minimum:5}
end
|
6c57c2bef0aafa2cd051a187fe3b798c54c083f9
|
[
"Ruby"
] | 4
|
Ruby
|
CliffRegis/postit_temp
|
6cc43cf29838af782769ea75889dc435080ab218
|
88057d60276d5d14d92c59f24f7506ac9fe8620d
|
refs/heads/master
|
<repo_name>EagleKiev/JScript<file_sep>/js/objects_obertki.js
//Объекты в языке JavaScript являются составными значениями: они представляют собой коллекции свойств, или
//именованных значений. Обращение к свойствам мы будем выполнять с использованием точечной нотации. Свойства,
//значениями которых являются функции, мы будем называть методами. Чтобы вызвать метод m объекта o, следует
//использовать инструкцию o.m().
//Мы уже видели, что строки обладают свойствами и методами:
var s = "hello world!"; // Строка
var word = s.substring(s.indexOf(" ")+1, s.length); // Использование свойств строки
//Однако строки не являются объектами, так почему же они обладают свойствами?
//Всякий раз когда в программе предпринимается попытка обратиться к свойству строки s, интерпретатор JavaScript
//преобразует строковое значение в объект, как если бы был выполнен вызов new String(s). Этот объект наследует
//строковые методы и используется интерпретатором для доступа к свойствам. После обращения к свойству вновь
//созданный объект уничтожается. (От реализаций не требуется фактически создавать и уничтожать этот промежуточный
//объект, но они должны вести себя так, как если бы объект действительно создавался и уничтожался.)
//Наличие методов у числовых и логических значений объясняется теми же причинами: при обращении к какому-либо методу
//создается временный объект вызовом конструктора Number() или Boolean(), после чего производится вызов метода
//этого объекта. Значения null и undefined не имеют объектов-оберток: любые попытки обратиться к свойствам этих
//значений будет вызывать ошибку TypeError.
//Рассмотрим следующий фрагмент и подумаем, что происходит при его выполнении:
var s = "test"; // Начальное строковое значение.
s.len = 4; // Установить его свойство.
var t = s.len; // Теперь запросить значение свойства.
//В начале этого фрагмента переменная t имеет значение undefined. Вторая строка создает временный объект String,
//устанавливает его свойство len равным 4 и затем уничтожает этот объект. Третья строка создает из оригинальной
//(неизмененной) строки новый объект String и пытается прочитать значение свойства len.
//Строки не имеют данного свойства, по-этому выражение возвращает значение undefined. Данный фрагмент показывает,
//что при попытке прочитать значение какого-либо свойства (или вызвать метод) строки числа и логические значения
//ведут себя подобно объектам. Но если попытаться установить значение свойства, эта попытка будет просто
//проигнорирована: изменение затронет только временный объект и не будет сохранено. Временные объекты, которые
//создаются при обращении к свойству строки, числа или логического значения, называются объектами-обертками, и
//иногда может потребоваться отличать строки от объектов String или числа и логические значения от объектов
//Number и Boolean. Однако обычно объекты-обертки можно рассматривать просто как особенность реализации и вообще
//не думать о них. Вам достаточно будет знать, что строки, числа и логические значения отличаются от объектов
//тем, что их свойства доступны только для чтения и что вы не можете определять для них новые свойства.
//Обратите внимание, что существует возможность (но в этом почти никогда нет необходимости или смысла) явно создавать
//объекты-обертки вызовом конструктора String(), Number() или Boolean():
var s = "test", n = 1, b = true; //Строка, число и логическое значение.
var S = new String(s); //Объект String
var N = new Number(n); //Объект Number
var B = new Boolean(b); //Объект Boolean
//При необходимости интерпретатор JavaScript обычно автоматически преобразует объекты-обертки, т. е. объекты
//S, N и B в примере выше, в обертываемые ими простые значения, но они не всегда ведут себя точно так же, как
//значения s, n и b.
//Оператор равенства == считает равными значения и соответствующие им объекты-обертки, но оператор
//идентичности === отличает их. Оператор typeof также обнаруживает отличия между простыми значениями и их
//объектами-обертками.
var N = new Number(423*3.456745);
console.log(typeof N);
console.log(N.toFixed(6));
var n = 5000;
console.log("");
console.log(typeof n);
console.log(n);<file_sep>/js/visibility_variable.js
//Область видимости переменной
//Область видимости (scope) переменной – это та часть программы, для которой эта переменная определена.
//Глобальная переменная имеет глобальную область видимости – она определена для всей JavaScript-программы.
//В то же время переменные, объявленные внутри функции, определены только в ее теле. Они называются локальными и
//имеют локальную область видимости. Параметры функций также считаются локальными переменными, определенными только
//в теле этой функции.
//Внутри тела функции локальная переменная имеет преимущество перед глобальной переменной с тем же именем. Если
//объявить локальную переменную или параметр функции с тем же именем, что у глобальной переменной, то фактически
//глобальная переменная будет скрыта:
var scope = "global"; // Объявление глобальной переменной
function checkscope() {
var scope = "local"; // Объявление локальной переменной с тем же именем
return scope; // Вернет локальное значение, а не глобальное
}
checkscope() // => "local"
//Объявляя переменные с глобальной областью видимости, инструкцию var можно опустить, но при объявлении локальных
//переменных всегда следует использовать инструкцию var. Посмотрите, что получается, если этого не сделать:
scope = "global"; // Объявление глобальной переменной, даже без var.
function checkscope2() {
scope = "local"; // Ой! Мы изменили глобальную переменную.
myscope = "local"; // Неявно объявляется новая глоб. переменная.
return [scope, myscope]; // Вернуть два значения.
}
checkscope2() // => ["local", "local"]: имеется побочный эффект!
scope // => "local": глобальная переменная изменилась.
myscope // => "local": нарушен порядок в глобальном пространстве имен.
//Определения функций могут быть вложенными. Каждая функция имеет собственную локальную область видимости, поэтому
//может быть несколько вложенных уровней локальных областей видимости. Например:
var scope = "global scope"; // Глобальная переменная
function checkscope() {
var scope = "local scope"; // Локальная переменная
function nested() {
var scope = "nested scope"; // Вложенная область видимости локальных переменных
return scope; // Вернет значение этой переменной scope
}
return nested();
}
checkscope() // => "nested scope"
<file_sep>/js/variables.js
//Преже чем использовать переменную в JavaScript, ее необходимо объявить. Переменные объявляются с помощью ключевого
//слова var следующим образом:
var i;
var sum;
//Один раз использовав ключевое слово var, можно объявить несколько переменных:
var i, sum;
//Объявление переменных можно совмещать с их инициализацией:
var message = "hello";
var i = 0, j = 0, k = 0;
//Если начальное значение в инструкции var не задано, то переменная объявляется, но ее начальное значение остается
//неопределенным (undefined), пока не будет изменено программой. Обратите внимание, что инструкция var также может
//включаться в циклы for и for/in, что позволяет объявлять переменную цикла непосредственно в самом цикле.
// Например:
for(var i = 0; i < 10; i++) console.log(i);
for(var i = 0, j=10; i < 10; i++,j--) console.log(i*j);
for(var p in o) console.log(p);
//Если вы имеете опыт использования языков программирования со статическими типами данных, таких как C или Java,
//то можете заметить, что в объявлениях переменных в языке JavaScript отсутствует объявление типа. Переменные в
//языке JavaScript могут хранить значения любых типов. Например, в JavaScript допускается присвоить некоторой
//переменной число, а затем этой же переменной присвоить строку:
var i = 10;
i = "ten";
//С помощью инструкции var можно объявить одну и ту же переменную несколько раз. Если повторное объявление содержит
//инициализатор, то оно действует как обычная инструкция присваивания. Если попытаться прочитать значение
//необъявленной переменной, JavaScript сгенерирует ошибку. В строгом режиме, предусмотренном стандартом
//ECMAScript 5, ошибка также возбуждается при попытке присвоить значение необъявленной переменной. Однако
//исторически и при выполнении не в строгом режиме, если присвоить значение переменной, не объявленной с помощью
//инструкции var, то JavaScript создаст эту переменную как свойство глобального объекта, и она будет действовать
//практически так же, как корректно объявленная переменная. Это означает, что глобальные переменные можно не
//объявлять. Однако это считается дурной привычкой и может явиться источником ошибок, поэтому всегда старайтесь
//объявлять свои переменные с помощью var.<file_sep>/js/stroki.js
/*//Работа со строками
//Одной из встроенных возможностей JavaScript является способность конкатенировать строки. Если оператор +
//применяется к числам, они складываются, а если к строкам – они объединяются, при этом вторая строка добавляется
//в конец первой. Например:
msg = "Hello, " + "world"; // Получается строка "Hello, world"
greeting = "Добро пожаловать на мою домашнюю страницу," + " " + name;
//Для определения длины строки – количества содержащихся в ней 16-битных значений – используется свойство строки
//length. Например, длину строки s можно получить следующим образом:
s.length
//Кроме того, в дополнение к свойству length строки имеют множество методов (как обычно, более полную информацию
//ищите в справочном разделе):
var s = "hello, world" // Начнем с того же текста.
s.charAt(0) // => "h": первый символ.
s.charAt(s.length-1) // => "d": последний символ.
s.substring(1,4) // => "ell": 2-й, 3-й и 4-й символы.
s.slice(1,4) // => "ell": то же самое
s.slice(-3) // => "rld": последние 3 символа
s.indexOf("l") // => 2: позиция первого символа l.
s.lastIndexOf("l") // => 10: позиция последнего символа l.
s.indexOf("l", 3) // => 3: позиция первого символа "l", следующего
// за 3 символом в строке
s.split(", ") // => ["hello", "world"] разбивает на подстроки
s.replace("h", "H") // => "Hello, world": замещает все вхождения подстроки
s.toUpperCase() // => "HELLO, WORLD"
//Не забывайте, что строки в JavaScript являются неизменяемыми. Такие методы, как replace() и toUpperCase()
//возвращают новые строки: они не изменяют строку, относительно которой были вызваны.
//В стандарте ECMAScript 5 строки могут интерпретироваться как массивы, доступные только для чтения, и вместо
//использования метода charAt() к отдельным символам (16-битным значениям) строки можно обращаться с помощью
//индексов в квадратных скобках:
s = "hello, world";
s[0] // => "h"
s[s.length-1] // => "d"*/
console.log("Some string");
console.log('Some string1');
console.log('Some "Long" string');
console.log("Some 'Long' string");
console.log("hello Eagleeeeeeeeeeeee".length);
console.log("hello \Eagleee \eeeee \eeeee");
console.log("hello \nEagleee \neeeee \neeeee");
console.log("hello \n\tEagleee \n\t\teeeee \n\t\t\teeeee");
console.log("hello \\ Eagleee \"eeeee\" eeeee");
var string = "Privet i chto tipa tam..."
console.log(string.charAt(0));
console.log(string.charAt(string.length - 1));
console.log(string.substring(5));
console.log(string.substring(10,17));
console.log(string.slice(-10));
console.log(string.substr(14,7));
console.log(string.indexOf("tam"));
console.log(string.lastIndexOf("tam"));
console.log(string.replace("chto","CHTO!!!"));
console.log("");
string = string.replace("chto","CHTO!!!");
console.log(string);
console.log("");
console.log(string.split(" "));
console.log("");
console.log(string.toUpperCase());
console.log(string.toLocaleLowerCase());
console.log(string[7])<file_sep>/js/change_values.js
//Между простыми значениями (undefined, null, логическими значениями, числами и строками) и объектами (включая
// массивы и функции) в языке JavaScript имеются фундаментальные отличия. Простые значения являются неизменяемыми:
// простое значение невозможно изменить (или «трансформировать»). Это очевидно для чисел и логических значений –
// нет никакого смысла изменять значение числа. Однако для строк это менее очевидно. Поскольку строки являются
// массивами символов, вполне естественно было бы ожидать наличие возможности изменять символы в той или иной
// позиции в строке. В действительности JavaScript не позволяет сделать это, и все строковые методы, которые,
// на первый взгляд, возвращают измененную строку, на самом деле возвращают новое строковое значение.
//Например:
var s = "hello"; // Изначально имеется некоторый текст из строчных символов
s.toUpperCase(); // Вернет "HELLO", но значение s при этом не изменится
s // => "hello": оригинальная строка не изменилась
//Кроме того, величины простых типов сравниваются по значению: две величины считаются одинаковыми, если они имеют
// одно и то же значение. Для чисел, логических значений, null и undefined это выглядит очевидным: нет никакого
// другого способа сравнить их. Однако для строк это утверждение не выглядит таким очевидным. При сравнении двух
// строковых значений JavaScript считает их одинаковыми тогда и только тогда, когда они имеют одинаковую длину и
// содержат одинаковые символы в соответствующих позициях.
//Объекты отличаются от простых типов. Во-первых, они являются изменяемыми – их значения можно изменять:
var o = { x:1 }; // Начальное значение объекта
o.x = 2; // Изменить, изменив значение свойства
o.y = 3; // Изменить, добавив новое свойство
var a = [1,2,3] // Массивы также являются изменяемыми объектами
a[0] = 0; // Изменить значение элемента массив
a[3] = 4; // Добавить новый элемент
//Объекты не сравниваются по значению: два объекта не считаются равными, даже если они будут иметь одинаковые
// наборы свойств с одинаковыми значениями.И два массива не считаются равными, даже если они имеют один и тот же
// набор элементов, следующих в том же порядке:
var o = {x:1}, p = {x:1}; //Два объекта с одинаковыми свойствами
o === p //=> false: разные объекты не являются равными
var a = [], b = []; //Два различных пустых массива
a === b //=> false: различные массивы не являются равными
//Чтобы подчеркнуть отличие от простых типов JavaScript, объекты иногда называют ссылочными типами. Если следовать
// этой терминологии, значениями объектов являются ссылки, и можно сказать, что объекты сравниваются по ссылке:
//значения двух объектов считаются равными тогда и только тогда, когда они ссылаются на один и тот же объект в
// памяти.
var a = []; //Переменная a ссылается на пустой массив.
var b = a; //Теперь b ссылается на тот же массив.
b[0] = 1; //Изменение массива с помощью ссылки в переменной b.
a[0] //=> 1: изменение можно наблюдать в переменной a.
a === b //=> true: a и b ссылаются на один и тот же объект, поэтому они равны.
//Как следует из примера выше, операция присваивания объекта (или массива) переменной фактически присваивает
// ссылку: она не создает новую копию объекта. Если в программе потребуется создать новую копию объекта или массива,
// необходимо будет явно скопировать свойства объекта или элементы массива. Следующий пример демонстрирует такое
// копирование с помощью цикла for.
var a = ['a','b','c']; //Копируемый массив
var b = []; //Массив, куда выполняется копирование
for(var i = 0; i < a.length; i++) { //Для каждого элемента в массиве a[]
b[i] = a[i]; //Скопировать элемент a[] в b[]
}
//Точно так же, если потребуется сравнить два отдельных объекта или массива, необходимо будет сравнить значения
// их свойств или элементов. Ниже приводится определение функции, сравнивающей два массива:
function equalArrays(a,b) {
if (a.length != b.length) return false; //Массивы разной длины не равны
for(var i = 0; i < a.length; i++) //Цикл по всем элементам
if (a[i] !== b[i]) return false; //Если хоть один элемент
//отличается, массивы не равны
return true; //Иначе они равны
}
<file_sep>/js/object_window.js
<script>
function moveon() {
//Вывести модальный диалог, чтобы получить ответ пользователя
var answer = confirm("Ready to move on?");
//Если пользователь щелкнул на кнопке "OK", заставить броузер загрузить новую страницу
if (answer) window.location = "http://google.com";
}
//Запустить функцию, объявленную выше, через 1 минуту (60000 миллисекунд).
setTimeout(moveon, 60000);
</script>
<file_sep>/js/Js_Math.js
'use strict';
/*Math.pow(2,53) //=> 9007199254740992: 2 в степени 53
Math.round(.6) //=> 1.0: округление до ближайшего целого
Math.ceil(.6) //=> 1.0: округление вверх
Math.floor(.6) //=> 0.0: округление вниз
Math.abs(-5) //=> 5: абсолютное значение
Math.max(x,y,z) //Возвращает наибольший аргумент
Math.min(x,y,z) //Возвращает наименьший аргумент
Math.random() //Псевдослучайное число x, где 0 <= x < 1.0
Math.PI //π: длина окружности / диаметр (число Пи)
Math.E //e: Основание натурального логарифма
Math.sqrt(3) //Корень квадратный из 3
Math.pow(3, 1/3) //Корень кубический из 3
Math.sin(0) //Тригонометрия: имеются также Math.cos, Math.atan и другие.
Math.log(10) //Натуральный логарифм 10
Math.log(100)/Math.LN10 //Логарифм 100 по основанию 10 (десятичный)
Math.log(512)/Math.LN2 //Логарифм 512 по основанию 2
Math.exp(3) //Math.E в кубе
//В JavaScript имеются предопределенные глобальные переменные Infinity и NaN,хранящие значения положительной
// бесконечности и «не число». В стандарте ECMAScript 3 эти переменные доступны для чтения/записи и могут
// изменяться в программах. Стандарт ECMAScript 5 исправляет эту оплошность и требует, чтобы эти переменные были
// доступны только для чтения. Объект Number предоставляет альтернативные представления некоторых значений,
// доступные только для чтения даже в ECMAScript 3. Например:
Infinity //Переменная, доступная для чтения/записи,
//инициализированная значением Infinity
Number.POSITIVE_INFINITY //То же значение, доступное только для чтения.
1/0 //То же самое значение.
Number.MAX_VALUE + 1 //Это выражение также возвращает Infinity.
Number.NEGATIVE_INFINITY // Возвращают отрицательную бесконечность.
-Infinity
-1/0
-Number.MAX_VALUE - 1
NaN //Переменная, доступная для чтения/записи,
//инициализированная значением NaN.
Number.NaN //Свойство, доступное только для чтения, с тем же значением.
0/0 //Возвращает NaN
Number.MIN_VALUE/2 // Потеря значащих разрядов: возвращает 0
-Number.MIN_VALUE/2 // Отрицательный ноль
-1/Infinity // Также отрицательный ноль
-0
//Значение «не число» в JavaScript обладает одной необычной особенностью: операция проверки на равенство всегда
// возвращает отрицательный результат, даже если сравнить его с самим собой. Это означает, что нельзя использовать
// проверку x == NaN, чтобы определить, является значение переменной x значением NaN. Вместо этого следует выполнять
// проверку x != x. Эта проверка вернет true тогда и только тогда, когда x имеет значение NaN. Аналогичную проверку
// можно выполнить с помощью функции isNaN(). Она возвращает true, если аргумент имеет значение NaN или если аргумент
// является нечисловым значением, таким как строка или объект. Родственная функция isFinite() возвращает true, если
// аргумент является числом, отличным от NaN, Infinity или -Infinity. Отрицательный ноль также имеет свои характерные
// особенности. В операциях сравнения (даже в операции строгой проверки на равенство) он признается равным
// положительному нулю, что делает эти два значения практически неотличимыми, за исключением случаев, когда они
// выступают в роли делителей:
var zero = 0; //Обычный ноль
var negz = -0; //Отрицательный ноль
zero === negz //=> true: ноль и отрицательный ноль равны
1/zero === 1/negz //=> false: Infinity и -Infinity не равны
//Точность представления вещественных чисел в JavaScript достаточно высока и позволяет обеспечить очень близкое
// представление числа 0.1. Но тот факт, что это число не может быть представлено точно, может приводить к
// проблемам. Взгляните на следующий фрагмент:
// вычесления нельзя сравнивать!!!!!!*/
let a = .9 - .8;
let b = .8 - .7;
let c = .7 - .6;
let d = .6 - .5;
let e = .5 - .4;
let f = .4 - .3;
let g = .2 - .1; //тридцать копеек минус двадцать копеек
//двадцать копеек минус 10 копеек
//x == y; //=> false: получились два разных значения!
//x == .1; //=> false: .3-.2 не равно .1
//y == .1; //=> true: .2-.1 равно .1
//Изза ошибок округления разность между аппроксимациями чисел .3 и .2 оказалась не равной разности между
// аппроксимациями чисел .2 и .1.
// Важно понимать, что эта проблема не является чемто характерным для JavaScript: она проявляется во всех языках
// программирования, где используется двоичное представление вещественных чисел. Кроме того, обратите внимание,
// что значения x и y в примере выше очень близки друг к другу и к истинному значению. Точность округления вполне
// приемлема для большинства применений: проблема возникает лишь при попытках проверить значения на равенство. В
// будущих версиях JavaScript может появиться поддержка десятичных чисел, лишенная описанных недостатков, связанных
// с округлением. Но до тех пор для важных финансовых расчетов предпочтительнее будет использовать масштабируемые
// целые числа. Например, финансовые расчеты можно производить в копейках, а не в долях рублей.
console.log(a)
console.log(b)
console.log(c)
console.log(d)
console.log(e)
console.log(f)
console.log(g)
//console.log(typeof x)
//console.log(typeof y)
//console.log(x - y)
//console.log(x == .1)
//console.log(y == .1)
console.log(a+b+c+d+e+f+g)
console.log('');
let i = 10;
console.log(++i);
<file_sep>/js/offJS.js
'use strict'
/*let who = 'admin';
if (who) {
} else if (){
} else {
}
let access = (age > 14) ? true : false;
let access = (age > 14) && true;
let user0bj = {
name: options.name && options.name;
};
var age = prompt('возраст')
*/
var arr = [];
var arr = ["1", "2", "3", "4"];
console.log( arr[0] );
console.log( arr[1] );
console.log( arr[2] );
console.log( arr[3] );
/*var arr = ["1", "2", "3", "4"];
if i = 3
console.log( arr[0] );
console.log( arr[1] );
console.log( arr[2] );
console.log( arr[3] );
*/
<file_sep>/js/main1.js
'use strict';
let a = 0/0;
//let b = 1000;
//let c = false;
// Все, что следует за двумя символами слэша, является комментарием.
// Внимательно читайте комментарии: они описывают программный код JavaScript.
// Переменная - это символическое имя некоторого значения.
// Переменные объявляются с помощью ключевого слова var:
var x; // Объявление переменной с именем x.
// Присваивать значения переменным можно с помощью знака =
x = 0; // Теперь переменная x имеет значение 0
// => 0: В выражениях имя переменной замещается ее значением.
// JavaScript поддерживает значения различных типов
x = 1; // Числа.
x = 0.01; // Целые и вещественные числа представлены одним типом.
x = "hello world"; // Строки текста в кавычках.
x = 'JavaScript'; // Строки можно также заключать в апострофы.
x = true; // Логические значения.
x = false; // Другое логическое значение.
x = null; // null - особое значение, обозначающее "нет значения".
x = undefined; // Значение undefined подобно значению null.
// Наиболее важным типом данных в JavaScript являются объекты.
// Объект - это коллекция пар имя/значение или отображение строки в значение.
var book = { // Объекты заключаются в фигурные скобки.
topic: "JavaScript", // Свойство "topic" имеет значение "JavaScript".
fat: true // Свойство "fat" имеет значение true.
}; // Фигурная скобка отмечает конец объекта.
// Доступ к свойствам объектов выполняется с помощью . или []:
book.topic // => "JavaScript"
book["fat"] // => true: другой способ получить значение свойства.
book.author = "Flanagan"; // Создать новое свойство присваиванием.
book.contents = {}; // {} - пустой объект без свойств.
// JavaScript поддерживает массивы (списки с числовыми индексами) значений:
var primes = [2, 3, 5, 7]; // Массив из 4 значений, ограничивается [ и ].
primes[0] // => 2: первый элемент (с индексом 0) массива.
primes.length // => 4: количество элементов в массиве.
primes[primes.length-1] // => 7: последний элемент массива.
primes[4] = 9; // Добавить новый элемент присваиванием.
primes[4] = 11; // Или изменить значение имеющегося элемента.
var empty = []; // [] - пустой массив без элементов.
empty.length // => 0
// Массивы и объекты могут хранить другие массивы и объекты:
var points = [ // Массив с 2 элементами.
{x:0, y:0}, // Каждый элемент - это объект.
{x:1, y:1}
];
var data = { // Объект с 2 свойствами
trial1: [[1,2], [3,4]], // Значение каждого свойства - это массив.
trial2: [[2,3], [4,5]] // Элементами массива являются массивы.
};
//for (let line = '@'; line.length < 58; line += '#')
//console.log(line);
console.log(a);
//console.log(b)
console.log(typeof a);
//console.log(typeof b)
console.log(NaN == NaN);
console.log(2 >= 1);
//console.log(c);
//console.log(typeof c);
//console.log(a+b);
console.log(x);
<file_sep>/js/kursSite.js
"use strict";
let now = new Date();
function kursEuro(x,y) {
console.log("");
console.log("");
console.log("Курс евро на " + now.toLocaleDateString() + " ---> " + (x / y).toFixed(8));
// console.log(Math.round((x / y)*1000000000000)/1000000000000);
}
function kursDollar(x,y) {
console.log("___________________________________________");
console.log("");
console.log("Курс $доллара на " + now.toLocaleDateString() + " ---> " + (x / y).toFixed(8));
// console.log(Math.round((x / y)*1000000)/1000000);
console.log("");
console.log("");
console.log("");
}
kursEuro(1,31.4);
kursDollar(1,26.5);<file_sep>/js/literaly.js
/*12 //Число двенадцать
1.2 //Число одна целая две десятых
"hello world" //Строка текста
'Hi' //Другая строка
true //Логическое значение
false //Другое логическое значение
/javascript/gi //Литерал "регулярного выражения" (для поиска по шаблону)
null //Пустой объект
{ x:1, y:2 } //Инициализатор объекта
[1,2,3,4,5] //Инициализатор массива
//Идентификатор – это просто имя. В JavaScript идентификаторы выступают в качестве имен переменных и функций,
// а также меток некоторых циклов. Идентификаторы в JavaScript должны начинаться с буквы, с символа
// подчеркивания (_) или знака доллара ($). Далее могут следовать любые буквы, цифры, символы подчеркивания или
// знаки доллара. (Цифра не может быть первым символом, так как тогда интерпретатору трудно будет отличать
// идентификаторы от чисел.) Примеры допустимых идентификаторов:
i
my_variable_name
v13
_dummy
$str
var sí = true;
var π = 3.14;
//JavaScript резервирует ряд идентификаторов, которые играют роль ключевых слов самого языка. Эти ключевые слова не
// могут служить идентификаторами в программах:
break
case
catch
continue
debugger
default
delete
do
else
false
finally
for
function
if
in
instanceof
new
null
return
switch
this
throw
true
try
typeof
var
void
while
with
//JavaScript также резервирует некоторые ключевые слова, которые в настоящее время не являются частью языка, но
// которые могут войти в его состав в будущих версиях. Стандарт ECMAScript 5 резервирует следующие слова:
class
const
enum
export
extends
import
super
//Ниже приводится дополнительный список слов, которые допустимы в обычном программном коде JavaScript и являются
// зарезервированными в строгом режиме:
implements
let
private
public
interface
package
protected
static
yield
//В строгом режиме также вводится ограничение на использование следующих идентификаторов. Они не являются
// зарезервированными словами в полном понимании, но они не могут использоваться в качестве имен переменных,
// функций или параметров:
arguments
eval
//Стандарт ECMAScript 3 резервирует все ключевые слова языка Java, и, хотя это требование было ослаблено в
// стандарте ECMAScript 5, тем не менее следует избегать использования этих идентификаторов, если необходимо
// обеспечить работоспособность JavaScript-кода при использовании реализаций JavaScript, соответствующих стандарту
// ECMAScript 3:
abstract
double
goto
native
static
boolean
enum
implements
package
super
byte
export
import
private
synchronized
char
extends
int
protected
throws
class
final
interface
public
transient
const
float
long
short
volatile
//В языке JavaScript имеется множество предопределенных глобальных переменных и функций, имена которых не следует
// использовать для создания своих собственных переменных и функций:
arguments
encodeURI
Infinity
Number
RegExp
Array
encodeURIComponent
isFinite
Object
String
Boolean
Error
isNaN
parseFloat
SyntaxError
Date
eval
JSON
parseInt
TypeError
decodeURI
EvalError
Math
RangeError
undefined
decodeURIComponent
Function
NaN
ReferenceError
URIError
//Помимо десятичных целых литералов JavaScript распознает шестнадцатеричные значения (по основанию 16).
// Шестнадцатеричные литералы начинаются с последовательности символов «0x» или «0X», за которой следует строка
// шестнадцатеричных цифр. Шестнадцатеричная цифра – это одна из цифр от 0 до 9 или букв от a (или A) до f (или F),
// представляющих значения от 10 до 15. Ниже приводятся примеры шестнадцатеричных целых литералов:
0xff // 15*16 + 15 = 255 (по основанию 10)
0xCAFE911
//Хотя стандарт ECMAScript не поддерживает представление целых литералов в восьмеричном формате (по основанию 8),
// некоторые реализации JavaScript допускают подобную возможность. Восьмеричный литерал начинается с цифры 0,
// за которой могут следовать цифры от 0 до 7. Например:
0377 // 3*64 + 7*8 + 7 = 255 (по основанию 10)
3.14
2345.789
.333333333333333333
6.02e23 // 6.02 × 10 23
1.4738223E-32 // 1.4738223 × 10 -32*/
<file_sep>/js/switchCase&while&for.js
var x = 3;
switch (x) {
case 1:
console.log(x);
break;
case 2:
console.log(x+2);
break;
default:
console.log(x+5);
}
var color = "yellow";
switch (color) {
case "blue":
console.log("This is blue");
break;
case "red":
console.log("This is red");
break;
case "green":
console.log("This is green");
break;
case "orange":
console.log("This is orange");
break;
default:
console.log("Color not found");
}
console.log("")
for (i=1; i<=5; i++) {
console.log(i + "<br />");
}
console.log("")
for (i=1, text=""; i<=5; i++) {
text = i;
console.log(i + "<br />");
}
console.log("")
var i = 0;
for (; i < 10; ) {
console.log(i);
i++;
}
console.log("")
var x = 0; //vivesti vse chetnie chisla ot 0 do 20
for (; x<=20; x+=2 ) {
console.log(x);//vivesti vse chetnie chisla ot 0 do 20
}
console.log("")
var i = 0; //vivesti vse chisla ot 0 do 10
while (i<=10) {
console.log(i+" ");
i++
}
console.log("")
var i = 20;//vivesti vse chisla ot 20 do 25
do {
console.log(i + " ");
i++;
}
while (i<=25);
console.log("")
for (i = 0; i<= 10; i++) {//kak tolko i budet ravno 5 - vihod iz cikla
if (i == 5) {
break;
}
console.log(i + " ");
}
console.log("")
for (i = 0; i<= 10; i++) {//kak tolko i budet ravno 5 - ostanavlivaet odnu iteraciyu i prodolzhaet so sled iteracii
if (i == 5) {
continue;
}
console.log(i + " ");
}
console.log("")
var sum = 0;
for (i = 4; i< 8; i++) {
if (i == 6) {
continue;
}
sum += i;
}
console.log(sum + " ");
console.log("")
var x = 0;
while (x<6) {
x++;
}
console.log(x);<file_sep>/js/main2.js
'use strict';
// Операторы выполняют действия со значениями (операндами) и воспроизводят новое значение.
// Наиболее часто используемыми являются арифметические операторы:
3 + 2 // => 5: сложение
3 - 2 // => 1: вычитание
3 * 2 // => 6: умножение
3 / 2 // => 1.5: деление
points[1].x - points[0].x // => 1: можно использовать более сложные операнды
"3" + "2" // => "32": + складывает числа, объединяет строки
// В JavaScript имеются некоторые сокращенные формы арифметических операторов
var count = 0; // Объявление переменной
count++; // Увеличение значения переменной на 1
count--; // Уменьшение значения переменной на 1
count += 2; // Добавить 2: то же, что count = count + 2;
count *= 3; // Умножить на 3: то же, что count = count * 3;
count // => 6: имена переменных сами являются выражениями
// Операторы сравнения позволяют проверить два значения на равенство
// или неравенство, выяснить, какое значение меньше или больше, и т. д.
// Они возвращают значение true или false.
var x = 2, y = 3; // Знаки = выполняют присваивание, а не сравнение
x == y // => false: равенство
x != y // => true: неравенство
x < y // => true: меньше
x <= y // => true: меньше или равно
x > y // => false: больше
x >= y // => false: больше или равно
"two" == "three" // => false: две разных строки
"two" > "three" // => true: при упорядочении по алфавиту строка "tw" больше, чем "th"
false == (x > y) // => true: false равно false
// Логические операторы объединяют или инвертируют логические значения
(x == 2) && (y == 3) // => true: оба сравнения истинны. && - "И"
(x > 3) || (y < 3) // => false: оба сравнения ложны. || - "ИЛИ"
!(x == y) // => true: ! инвертирует логическое значение
// Функции - это параметризованные блоки программного кода JavaScript, которые можно вызывать многократно.
function plus1(x) { // Определить функцию с именем "plus1" и с параметром "x"
return x+1; // Вернуть значение на 1 больше полученного
} // Функции заключаются в фигурные скобки
plus1(y) // => 4: y имеет значение 3, поэтому этот вызов вернет 3+1
var square = function(x) { // Функции можно присваивать переменным
return x*x; // Вычислить значение функции
}; // Точка с запятой отмечает конец присваивания.
square(plus1(y)) // => 16: вызов двух функций в одном выражении
// Функции, присвоенные свойствам объектов, называются методами.
// Все объекты в JavaScript имеют методы:
var a = []; // Создать пустой массив
a.push(1,2,3); // Метод push() добавляет элементы в массив
a.reverse(); // Другой метод: переставляет элементы в обратном порядке
// Можно определять собственные методы. Ключевое слово "this" ссылается на объект,
// в котором определен метод: в данном случае на массив points.
points.dist = function() { // Метод вычисления расстояния между точками
var p1 = this[0]; // Первый элемент массива, относительно которого вызван метод
var p2 = this[1]; // Второй элемент объекта "this"
var a = p2.x-p1.x; // Разность координат X
var b = p2.y-p1.y; // Разность координат Y
return Math.sqrt(a*a + // Теорема Пифагора
b*b); //Math.sqrt() вычисляет корень квадратный
};
points.dist() //=> 1.414: расстояние между 2-мя точками
// В JavaScript имеются условные инструкции и инструкции циклов, синтаксически похожие на аналогичные инструкции
// C, C++, Java и в других языках.
function abs(x) { // Функция, вычисляющая абсолютное значение
if (x >= 0) { // Инструкция if ...
return x; // выполняет этот код, если сравнение дает true.
} // Конец предложения if.
else { // Необязательное предложение else выполняет свой код,
return -x; // если сравнение дает значение false.
} // Фигурные скобки можно опустить, если предложение
// содержит 1 инструкцию.
} // Обратите внимание на инструкции return внутри if/else.
function factorial(n) { //Функция, вычисляющая факториал
var product = 1; //Начать с произведения, равного 1
while(n > 1) { //Повторять инструкции в {}, пока выраж. в () истинно
product *= n; //Сокращенная форма выражения product = product * n;
n--; //Сокращенная форма выражения n = n - 1
} //Конец цикла
return product; //Вернуть произведение
}
factorial(4) // => 24: 1*4*3*2
function factorial2(n) { // Другая версия, использующая другой цикл
var i, product = 1; // Начать с 1
for(i=2; i <= n; i++) // i автоматически увеличивается с 2 до n
product *= i; // Выполнять в каждом цикле. {} можно опустить,
// если тело цикла состоит из 1 инструкции
return product; // Вернуть факториал
}
factorial2(5) // => 120: 1*2*3*4*5
// Определение функции-конструктора для инициализации нового объекта Point
function Point(x,y) { // По соглашению имя конструкторов начинается с заглавного символа
this.x = x; // this - ссылка на инициализируемый объект
this.y = y; // Сохранить аргументы в свойствах объекта
} // Ничего возвращать не требуется
// Чтобы создать новый экземпляр, необходимо вызвать функцию-конструктор с ключевым словом "new"
var p = new Point(1, 1); // Точка на плоскости с координатами (1,1)
// Методы объектов Point определяются за счет присваивания функций свойствам объекта прототипа, ассоциированного
// с функцией-конструктором.
Point.prototype.r = function() {
return Math.sqrt( // Вернуть корень квадратный от x 2 + y 2
this.x * this.x + // this - это объект Point, относительно которого...
this.y * this.y // ...вызывается метод.
);
};
// Теперь объект p типа Point (и все последующие объекты Point) наследует метод r()
p.r() // => 1.414...
<file_sep>/js/switchCase.js
var day = 1;
switch (day) {
case 1:
document.write("Monday");
break;
case 2:
document.write("Tuesday");
break;
case 3:
document.write("Wednesday");
break;
default:
document.write("Another day");
}
<file_sep>/js/Js_off3.js
'use strict';
var a = NaN;
console.log(typeof (a) === 'number' && a !==a); {
};
|
c7c421d6a7437d968d7485f5a39ade10668d419a
|
[
"JavaScript"
] | 15
|
JavaScript
|
EagleKiev/JScript
|
0d1d8607c1f0e63d6d0abae36605ce8d97f0925c
|
5a38b07e2743e343887f3350557b2826f93e4b40
|
refs/heads/master
|
<repo_name>NHungate/the-sandwich-book<file_sep>/src/recipes-list/recipe-item/RecipeItem.js
import React from 'react';
import { Link } from 'react-router';
const RecipeItem = (props) => {
return (
<div className="column is-one-third">
<Link to={`sandwich/${props.recipeId}`}>
<div className="card">
<div className="card-image">
<figure className="image is-square">
<img src={props.recipeThumbnail} alt={`${props.recipeName}`} />
</figure>
</div>
<div className="card-content">
<div className="media">
<div className="media-content">
<p className="title is-4">{props.recipeName}</p>
</div>
</div>
</div>
</div>
</Link>
</div>
)
};
RecipeItem.propTypes = {
recipeId: React.PropTypes.number.isRequired,
recipeName: React.PropTypes.string.isRequired,
recipeThumbnail: React.PropTypes.string.isRequired
};
export default RecipeItem;
<file_sep>/src/home/actions.js
export const FETCH_SANDWICHES = 'FETCH_SANDWICHES';
export const FETCH_SANDWICHES_RECEIVED = 'FETCH_SANDWICHES_RECEIVED';
export function getSandwiches() {
return { type: FETCH_SANDWICHES }
}
<file_sep>/src/recipes-list/recipe-item/RecipeItem.spec.js
import React from 'react';
import { shallow } from 'enzyme';
import RecipeItem from './RecipeItem';
import { Link } from 'react-router';
function setup() {
const props = {
recipeId: 0,
recipeThumbnail: '',
recipeName: 'Name',
};
const wrapper = shallow(<RecipeItem {...props} />);
return { props, wrapper };
}
it('renders without crashing', () => {
setup();
});
it('displays a <Link>', () => {
const { wrapper } = setup();
expect(wrapper.find(Link)).toHaveLength(1);
});
<file_sep>/src/recipes-list/RecipesList.spec.js
import React from 'react';
import { shallow } from 'enzyme';
import RecipesList from './RecipesList';
import RecipeItem from './recipe-item/RecipeItem';
function setup(props) {
const newProps = props || [{
id: 1,
image: {},
ingredients: [],
instructions: '',
name: '',
}];
const wrapper = shallow(<RecipesList {...newProps} />);
return { wrapper, newProps };
}
it('renders without crashing', () => {
setup();
});
it('should display a loading <p> when not provided recipes', () => {
const { wrapper } = setup();
expect(wrapper.find('p')).toHaveLength(1);
});
it('should display two <RecipeItem />s when provided with recipes', () => {
const props = {
recipes: [{
id: 0,
image: { thumbnail: '' },
name: ''
},
{
id: 1,
image: { thumbnail: '' },
name: ''
}
]
};
const { wrapper } = setup(props);
expect(wrapper.find(RecipeItem)).toHaveLength(2);
});
<file_sep>/src/config/configureFirebase.js
export default {
apiKey: "<KEY>",
authDomain: "the-sandwich-book.firebaseapp.com",
databaseURL: "https://the-sandwich-book.firebaseio.com",
storageBucket: "the-sandwich-book.appspot.com",
messagingSenderId: "542600145026"
};
<file_sep>/src/recipe-details/RecipeDetails.spec.js
import React from 'react';
import { RecipeDetails } from './RecipeDetails';
import { shallow } from 'enzyme';
function setup() {
const initialState = {
name: 'Name',
ingredients: ['4 Slices of cheese'],
instructions: 'Hello\n\n\nWorld',
image: {
}
};
const props = {
params: { id: 0 },
selectedSandwich: initialState
};
const enzymeWrapper = shallow(
<RecipeDetails {...props} />
);
return {
props,
enzymeWrapper
}
}
it('renders without crashing', () => {
setup();
});
it('should render <section>', () => {
const { enzymeWrapper } = setup();
expect(enzymeWrapper.find('section')).toHaveLength(1);
});
it('should return two <p>', () => {
const { enzymeWrapper } = setup();
const instructionsElements = enzymeWrapper.instance().renderInstructions('Hello\n\n\n\nWorld');
expect(instructionsElements).toHaveLength(2);
});
<file_sep>/src/footer/Footer.js
import React from 'react';
export default () => (
<footer className="footer">
<div className="container">
<div className="content has-text-centered">
<p>Built by <a href="http://www.nhungate.me"><NAME></a></p>
<a href="https://github.com/NHungate">
<i className="fa fa-github"></i>
</a>
</div>
</div>
</footer>
)
<file_sep>/src/home/actions.spec.js
it('fetches an array of sandwiches', () => {
});
<file_sep>/src/home/sagas.js
import { call, put, fork, takeEvery } from 'redux-saga/effects';
import Firebase from 'firebase';
export function* getSandwiches() {
const ref = Firebase.database().ref('sandwiches');
const data = yield call([ref, ref.once], 'value');
yield put({ type: 'FETCH_SANDWICHES_RECEIVED', payload: data.val() });
}
export function* watchGetSandwiches() {
yield takeEvery('FETCH_SANDWICHES', getSandwiches);
}
export default function* rootSaga() {
yield [
fork(watchGetSandwiches)
]
}
<file_sep>/src/home/Home.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import RecipesList from '../recipes-list/RecipesList';
import * as Actions from './actions';
export class Home extends Component {
componentDidMount() {
this.props.actions.getSandwiches();
}
render() {
return (
<section>
<section className="hero is-primary">
<div className="hero-body">
<div className="columns">
<div className="column">
<p className="title">Delicious Sandwiches</p>
</div>
</div>
</div>
</section>
<section className="section">
<RecipesList recipes={this.props.recipes} />
</section>
</section>
)
}
}
const mapStateToProps = (state) => {
return {
recipes: state.recipes
};
}
const mapDispatchToProps = (dispatch) => {
return {
actions: bindActionCreators(Actions, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Home);
<file_sep>/src/config/configureStore.js
import { createStore, compose, applyMiddleware } from 'redux';
import rootReducer from '../rootReducer';
import createSagaMiddleware from 'redux-saga';
import saga from '../sagas';
import Firebase from 'firebase';
import firebaseConfig from './configureFirebase';
Firebase.initializeApp(firebaseConfig);
export default function configureStore(initialState) {
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const sagaMiddleware = createSagaMiddleware();
const store = createStore(
rootReducer,
initialState,
composeEnhancers(
applyMiddleware(sagaMiddleware),
)
);
sagaMiddleware.run(saga);
if (module.hot) {
module.hot.accept('../rootReducer', () => {
const nextRootReducer = require('../rootReducer').default;
store.replaceReducer(nextRootReducer);
});
}
return store;
}
<file_sep>/src/recipe-details/sagas.js
import { call, put, fork, takeEvery } from 'redux-saga/effects';
import { FETCH_SANDWICH, FETCH_SANDWICH_RECEIVED } from './actions';
import Firebase from 'firebase';
export function* getSandwich(action) {
const id = action.payload;
const ref = Firebase.database().ref(`sandwiches/${id}`);
const data = yield call([ref, ref.once], 'value');
yield put({ type: FETCH_SANDWICH_RECEIVED, payload: data.val() })
}
export function* watchGetSandwich() {
yield takeEvery(FETCH_SANDWICH, getSandwich)
}
export default function* rootSaga() {
yield [
fork(watchGetSandwich)
]
}
<file_sep>/src/recipe-details/actions.js
export const FETCH_SANDWICH = 'FETCH_SANDWICH';
export const FETCH_SANDWICH_RECEIVED = 'FETCH_SANDWICH_RECEIVED';
export const fetchSandwich = (id) => {
return {
type: FETCH_SANDWICH,
payload: id
};
};
<file_sep>/src/rootReducer.js
import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';
import recipesListReducer from './home/reducer';
import recipeDetailsReducer from './recipe-details/reducer';
const rootReducer = combineReducers({
recipes: recipesListReducer,
selectedSandwich: recipeDetailsReducer,
routing: routerReducer
});
export default rootReducer;
|
6253a932ba70f62db23b1b164e65c0d70b848e7f
|
[
"JavaScript"
] | 14
|
JavaScript
|
NHungate/the-sandwich-book
|
b415da539868434d09bdfa1ec65425274d62633d
|
36f7caa6deba6c7c25893c0682b0595ee2cd9eca
|
refs/heads/master
|
<repo_name>lifeiyang2010/train_ticket<file_sep>/requirements.txt
-i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
appdirs==1.4.3
beautifulsoup4==4.7.0
bs4==0.0.1
certifi==2018.11.29
chardet==3.0.4
Click==7.0
cssselect==1.0.3
fake-useragent==0.1.11
Flask==1.0.2
Flask-JWT-Extended==3.15.0
idna==2.8
itsdangerous==1.1.0
Jinja2==2.10
lxml==4.3.0
MarkupSafe==1.1.0
parse==1.9.0
pyee==5.0.0
PyJWT==1.7.1
pyppeteer==0.0.25
pyquery==1.4.0
redis==3.0.1
requests==2.21.0
requests-html==0.9.0
six==1.12.0
soupsieve==1.6.2
tqdm==4.28.1
urllib3==1.24.1
w3lib==1.19.0
websockets==7.0
Werkzeug==0.14.1
DingtalkChatbot==1.3.0
lightpush==0.1.3
PyYAML==5.1.1
Pillow
wrapcache==1.0.8
ntplib==0.3.3
sklearn
opencv-python
keras>=2.2.4
tensorflow
matplotlib>=3.0.2
numpy>=1.14.6
scipy>=1.1.0<file_sep>/py12306/helpers/OCR.py
import math
import random
from py12306.config import Config
from py12306.verify.localVerifyCode import verify
from py12306.helpers.api import API_FREE_CODE_QCR_API
from py12306.helpers.request import Request
from py12306.log.common_log import CommonLog
from py12306.vender.ruokuai.main import RKClient
class OCR:
"""
图片识别
"""
session = None
def __init__(self):
self.session = Request()
@classmethod
def get_img_position(cls, img):
"""
获取图像坐标
:param img_path:
:return:
"""
self = cls()
if Config().AUTO_CODE_PLATFORM == 'free_1':
return self.get_image_by_free_site(img)
elif Config().AUTO_CODE_PLATFORM == 'free_2':
return self.get_image_by_local_verify(img)
return self.get_img_position_by_ruokuai(img)
def get_img_position_by_ruokuai(self, img):
ruokuai_account = Config().AUTO_CODE_ACCOUNT
soft_id = '119671'
soft_key = '6839cbaca1f942f58d2760baba5ed987'
rc = RKClient(ruokuai_account.get('user'), ruokuai_account.get('pwd'), soft_id, soft_key)
result = rc.rk_create(img, 6113)
if "Result" in result:
return self.get_image_position_by_offset(list(result['Result']))
CommonLog.print_auto_code_fail(result.get("Error", CommonLog.MESSAGE_RESPONSE_EMPTY_ERROR))
return None
def get_image_position_by_offset(self, offsets):
positions = []
width = 75
height = 75
for offset in offsets:
random_x = random.randint(-5, 5)
random_y = random.randint(-5, 5)
offset = int(offset)
x = width * ((offset - 1) % 4 + 1) - width / 2 + random_x
y = height * math.ceil(offset / 4) - height / 2 + random_y
positions.append(int(x))
positions.append(int(y))
return positions
def get_image_by_free_site(self, img):
data = {
'img': img
}
response = self.session.post(API_FREE_CODE_QCR_API, data=data)
result = response.json()
if result.get('msg') == 'success':
pos = result.get('result')
return self.get_image_position_by_offset(pos)
CommonLog.print_auto_code_fail(CommonLog.MESSAGE_GET_RESPONSE_FROM_FREE_AUTO_CODE)
return None
def get_image_by_local_verify(self, img):
with open('./tkcode.png', 'rb') as f:
result = f.read()
result = verify(result)
print(result)
return self.codexy(Ofset=result, is_raw_input=False)
def codexy(self, Ofset=None, is_raw_input=True):
"""
获取验证码
:return: str
"""
if is_raw_input:
print(u"""
*****************
| 1 | 2 | 3 | 4 |
*****************
| 5 | 6 | 7 | 8 |
*****************
""")
print(u"验证码分为8个,对应上面数字,例如第一和第二张,输入1, 2 如果开启cdn查询的话,会冲掉提示,直接鼠标点击命令行获取焦点,输入即可,不要输入空格")
print(u"如果是linux无图形界面,请使用自动打码,is_auto_code: True")
print(u"如果没有弹出验证码,请手动双击根目录下的tkcode.png文件")
Ofset = input(u"输入对应的验证码: ")
if isinstance(Ofset, list):
select = Ofset
else:
Ofset = Ofset.replace(",", ",")
select = Ofset.split(',')
post = []
offsetsX = 0 # 选择的答案的left值,通过浏览器点击8个小图的中点得到的,这样基本没问题
offsetsY = 0 # 选择的答案的top值
for ofset in select:
if ofset == '1':
offsetsY = 77
offsetsX = 40
elif ofset == '2':
offsetsY = 77
offsetsX = 112
elif ofset == '3':
offsetsY = 77
offsetsX = 184
elif ofset == '4':
offsetsY = 77
offsetsX = 256
elif ofset == '5':
offsetsY = 149
offsetsX = 40
elif ofset == '6':
offsetsY = 149
offsetsX = 112
elif ofset == '7':
offsetsY = 149
offsetsX = 184
elif ofset == '8':
offsetsY = 149
offsetsX = 256
else:
pass
post.append(offsetsX)
post.append(offsetsY)
# randCode = str(post).replace(']', '').replace('[', '').replace("'", '').replace(' ', '')
print(u"验证码识别坐标为{0}".format(post))
# return randCode
return post
if __name__ == '__main__':
pass
# code_result = AuthCode.get_auth_code()
|
7de73dc5664fc2984c5336fa3929467505971695
|
[
"Python",
"Text"
] | 2
|
Text
|
lifeiyang2010/train_ticket
|
825e6997f476239e2572ec0a68313f7deef9e002
|
a2122af5135a361bd4c8d5f63438ff6570c5aa3a
|
refs/heads/master
|
<file_sep>CCX=g++
CXXFLAGS=-Wall -Wextra -O3
all: SmithWaterman.cpp
$(CXX) -o smwt $(CXXFLAGS) SmithWaterman.cpp
<file_sep>CCX=g++
CXXFLAGS=-Wall -Wextra -O3
OMPFLAGS=-fopenmp
EXTRAFLAGS=-march=native -mfpmath=sse
all: smwt-paral.cpp
$(CXX) -o smwt-paral $(CXXFLAGS) $(OMPFLAGS) $(EXTRAFLAGS) smwt-paral.cpp
<file_sep>#include <fstream>
#include <cstdlib>
#include <string>
#include <cmath>
#include <unistd.h>
#include <sys/time.h>
#include <limits>
#include <omp.h>
#include <x86intrin.h>
#define __SIMD__ 1
// Fine tuning constants
#if __SIMD__
const int I = 128, p = 2;
#else
const int I = 64, p = 4;
#endif
// Alignment constants
#define _AVX_ALLIGN_ 32
#define _CACHE_ALLIGN_ 64
#define _FLP_LINE_ (_CACHE_ALLIGN_ / sizeof(float))
#define _FFLP_REG_ (_AVX_ALLIGN_ / sizeof(float))
#define _MSCORE_ 1.
#define MIN(a,b) ((a)<(b)?(a):(b))
using namespace std;
// Blocking size
int Bw, Bh, N_a, N_b;
const int minBw = 4 * _FLP_LINE_,
minBh = 4;
// Some global vars
string seq_a, seq_b;
float mu, delta, **H;
float *seq_b_floats;
// Point type declaration
typedef struct {
int row, col;
} Point;
// Dynamic alloc functions
void freeMemory(int);
void allocateMemory(int, int);
// Read from file function
string read_sequence_from_file(char *);
// Computational - helper functions
Point movePoint(Point);
void computeBlock(Point);
inline float find_max_score(float []);
inline float similarity_score(char, char);
int main (int argc, char** argv) {
// Input arguments check
if( argc != 5 ) {
printf("Give me the propen number of input arguments:\n");
printf("1 : mu\n");
printf("2 : delta\n");
printf("3 : filename sequence A\n");
printf("4 : filename sequence B\n");
exit(1);
}
mu = atof(argv[1]);
delta = atof(argv[2]);
char *nameof_seq_a = argv[3];
char *nameof_seq_b = argv[4];
struct timeval StartTime, EndTime;
// Read the sequences into strings
seq_a = read_sequence_from_file(nameof_seq_a);
N_a = seq_a.length();
seq_b = read_sequence_from_file(nameof_seq_b);
N_b = seq_b.length();
printf("First sequence has length : %6d\n", N_a);
printf("Second sequence has length : %6d\n\n", N_b);
// Allocate dynamic memory - exit on failure
allocateMemory(N_a + 1, N_b + 1);
Point upper = { 0, 0 },
lower = upper, tmp;
int newRows, newCols, numOfDiags;
// Declare reduction such it will work in serial execution.
// Maximum values found first would be set as the best score for the algorithm
struct Comparator { float val; Point p; } max;
#pragma omp declare reduction(max : struct Comparator : omp_out = (omp_in.val > omp_out.val || \
(omp_in.val == omp_out.val && (omp_in.p.row < omp_out.p.row || omp_in.p.col < omp_out.p.col))) ? omp_in : omp_out)
// Set max staring val as -Inf
max.val = -numeric_limits<float>::infinity();
// Start counting
gettimeofday(&StartTime, NULL);
#if __SIMD__
const char *char_seqb = seq_b.c_str();
#endif
// Create threads
#pragma omp parallel
{
#if __SIMD__
// Initialize seq_b_flaots to contain seq_b
#pragma omp for schedule(static, 16)
for (int i = 0; i < N_b; ++i) {
seq_b_floats[i] = char_seqb[i];
}
#endif
#pragma omp single
{
// Get the number of working threads
char T = omp_get_num_threads();
Bh = (int)ceil(((double)N_a)/(T * I));
Bw = (int)(((double)N_b)/(T * p));
Bw += _FLP_LINE_ - Bw % _FLP_LINE_;
// If the blocks are really small set a constant size
if (Bh < minBh) Bh = minBh;
if (Bw < minBw) Bw = minBw;
// Calculate blocks total
newRows = (int)ceil(((double)N_a) / Bh);
newCols = (int)ceil(((double)N_b) / Bw);
numOfDiags = newRows + newCols - 1;
// Create all blocks
for (int i = 0; i < numOfDiags; ++i) {
tmp = lower;
while (tmp.row >= upper.row && tmp.col <= upper.col) {
// Create a new task per block
#pragma omp task firstprivate(tmp)
computeBlock(tmp);
--tmp.row;
++tmp.col;
}
#pragma omp taskwait
// Execute the increments only when tasks have finished
if (upper.col < newCols - 1) ++upper.col; else ++upper.row;
if (lower.row < newRows - 1) ++lower.row; else ++lower.col;
}
}
// Threads wait here, at the implied barrier, while they complete tasks
// Search H for the maximal score
#pragma omp for reduction(max: max)
for (int i = 1; i <= N_a; ++i) {
for (int j = 1; j <= N_b; ++j) {
if( H[i][j] > max.val ) {
max.val = H[i][j];
max.p.row = i;
max.p.col = j;
}
}
}
}
Point curr = { max.p.row, max.p.col },
next = movePoint(curr);
int tick = 0;
char consensus_a[ N_a + N_b + 2 ],
consensus_b[ N_a + N_b + 2 ];
// Backtracking from H_max
while (((curr.row!=next.row) || (curr.col!=next.col)) && (next.row!=0) && (next.col!=0)) {
if ( next.row == curr.row ) {
consensus_a[tick] = '-'; // deletion in A
} else {
consensus_a[tick] = seq_a[curr.row - 1]; // match/mismatch in A
}
if ( next.col == curr.col ) {
consensus_b[tick] = '-'; // deletion in B
} else {
consensus_b[tick] = seq_b[curr.col - 1]; // match/mismatch in B
}
++tick;
curr = next;
next = movePoint(next);
}
gettimeofday(&EndTime, NULL);
printf("\n***********************************************\n");
printf("The alignment of the sequences\n\n");
for(int i = 0; i < N_a; ++i) {
printf("%c", seq_a[i]);
}
printf(" and\n");
for(int i = 0; i < N_b; ++i) {
printf("%c", seq_b[i]);
}
printf("\n\nis for the parameters mu = %.2lf and delta = %.2lf given by\n\n", mu, delta);
for(int i = tick - 1; i >= 0; --i) {
printf("%c", consensus_a[i]);
}
printf("\n");
for(int j = tick - 1; j >= 0; --j) {
printf("%c", consensus_b[j]);
}
printf("\n");
if (EndTime.tv_usec < StartTime.tv_usec) {
int nsec = (StartTime.tv_usec - EndTime.tv_usec) / 1000000 + 1;
StartTime.tv_usec -= 1000000 * nsec;
StartTime.tv_sec += nsec;
}
if (EndTime.tv_usec - StartTime.tv_usec > 1000000) {
int nsec = (EndTime.tv_usec - StartTime.tv_usec) / 1000000;
StartTime.tv_usec += 1000000 * nsec;
StartTime.tv_sec -= nsec;
}
printf("\n\nParallel calculation time: %ld.%.6ld seconds\n", EndTime.tv_sec - StartTime.tv_sec, EndTime.tv_usec - StartTime.tv_usec);
// Release dynamic memory
freeMemory(N_a + 1);
return 0;
}
/******************************************************************************/
/* Computational - helper functions */
/******************************************************************************/
Point movePoint(Point old) {
int row = old.row,
col = old.col;
float Val = H[row][col];
if ( Val == H[row-1][col-1] + similarity_score(seq_a[row-1], seq_b[col-1])) {
--old.row;
--old.col;
}
else if ( Val == H[row-1][col] - delta) {
--old.row;
}
else if ( Val == H[row][col-1] - delta ) {
--old.col;
}
return old;
}
/**
* Computes the given block int the array
**/
void computeBlock(Point block) {
int i, j;
const int row = block.row * Bh,
col = block.col * Bw;
int Rows = MIN(N_a, row + Bh),
Cols = MIN(N_b, col + Bw);
float tp, tmp[3];
#if __SIMD__
float constants[] = { _MSCORE_, -mu, delta, 0.f };
float __attribute__((aligned(_AVX_ALLIGN_))) max_mem[_FFLP_REG_];
const int unrolled = Cols / _FFLP_REG_ * _FFLP_REG_,
remainder = Cols - Cols % _FFLP_REG_;
__m256 seqa, seqb, mask, diag, up, max,
mscore = _mm256_broadcast_ss( constants ), // matching score
nscore = _mm256_broadcast_ss(constants+1), // not-matching score
dvect = _mm256_broadcast_ss(constants+2), // delta vector
zvect = _mm256_broadcast_ss(constants+3); // zero vector
#else
const int remainder = col;
#endif
for (i = row + 1; i <= Rows; ++i)
{
tp = H[i][col];
#if __SIMD__
// Load seq_a to register
seqa = _mm256_set1_ps(seq_a[i-1]);
for (j = col + 1; j <= unrolled; j += _FFLP_REG_)
{
// Load seq_b to register
seqb = _mm256_load_ps(&seq_b_floats[j-1]);
// Perform the similarity ifs
mask = _mm256_cmp_ps(seqa, seqb, _CMP_EQ_OQ);
diag = _mm256_or_ps(_mm256_and_ps(mask, mscore),
_mm256_andnot_ps(mask, nscore));
// Calculate diag, up scores
diag = _mm256_add_ps(_mm256_loadu_ps(&H[i-1][j-1]), diag);
up = _mm256_sub_ps(_mm256_loadu_ps(&H[i-1][ j ]), dvect);
// Find max score beetween diag, up, 0.f
max = _mm256_max_ps(diag, _mm256_max_ps(up, zvect));
// Store max back to memory
_mm256_store_ps(max_mem, max);
// Depedent data max here
H[i][ j ] = tp = (tp - delta > max_mem[0]) ? tp - delta : max_mem[0];
H[i][j+1] = tp = (tp - delta > max_mem[1]) ? tp - delta : max_mem[1];
H[i][j+2] = tp = (tp - delta > max_mem[2]) ? tp - delta : max_mem[2];
H[i][j+3] = tp = (tp - delta > max_mem[3]) ? tp - delta : max_mem[3];
H[i][j+4] = tp = (tp - delta > max_mem[4]) ? tp - delta : max_mem[4];
H[i][j+5] = tp = (tp - delta > max_mem[5]) ? tp - delta : max_mem[5];
H[i][j+6] = tp = (tp - delta > max_mem[6]) ? tp - delta : max_mem[6];
H[i][j+7] = tp = (tp - delta > max_mem[7]) ? tp - delta : max_mem[7];
}
#endif
// Loop for the reminder
for (j = remainder + 1; j <= Cols; ++j)
{
tmp[0] = H[i-1][j-1] + similarity_score(seq_a[i-1], seq_b[j-1]);
tmp[1] = H[i-1][ j ] - delta;
tmp[2] = tp - delta;
// Compute action that produces maximum score
H[i][j] = tp = find_max_score(tmp);
}
}
}
/**
* Returns the similarity score
*
**/
inline float similarity_score(char a, char b) {
return ((a == b) ? _MSCORE_ : -mu);
}
/**
* Calculates max between 3 input scores and zero
* Returns the index of max in values[]
**/
inline float find_max_score(float values[]) {
float max = (values[0] > values[1]) ? values[0] : values[1];
if (values[2] > max) max = values[2];
return ((max > 0.) ? max : 0.);
}
/******************************************************************************/
/* auxiliary functions used by main */
/******************************************************************************/
/**
* Allocates memory for the Dynamic Arrays
* int rows Rows of arrays
* int cols Columns
**/
void allocateMemory(int rows, int cols) {
int i;
printf("Allocating memory for matrix H\n");
H = (float **)aligned_alloc(_CACHE_ALLIGN_, rows * sizeof(float *));
if (H == NULL) {
fprintf(stderr, "Could not allocate memory for matrix H\n");
exit(1);
}
for (i = 0; i < rows; ++i) {
H[i] = (float *)aligned_alloc(_CACHE_ALLIGN_, cols * sizeof(float));
if (H[i] == NULL) {
fprintf(stderr, "Could not allocate memory for matrix H[%6d]\n", i);
exit(1);
}
}
printf("Memory for matrix H allocated\n\n");
printf("Initializing matrix H\n");
for (i = 0; i < rows; ++i) {
H[i][0] = 0.;
}
for (i = 0; i < rows; ++i) {
H[0][i] = 0.;
}
printf("Matrix H initialized\n\n");
#if __SIMD__
printf("Allocating memory for vector seq_b_floats\n");
seq_b_floats = (float *)aligned_alloc(_AVX_ALLIGN_, cols * sizeof(float));
if (seq_b_floats == NULL) {
fprintf(stderr, "Could not allocate memory for vector seq_b_floats\n");
exit(1);
}
printf("Memory for matrix H allocated\n\n");
#endif
}
/**
* Deallocates dynamic memory
**/
void freeMemory(int rows) {
if ( H ) {
for ( int i = 0; i < rows; ++i ) {
if ( H[i] ) free(H[i]);
}
free(H);
}
#if __SIMD__
if ( seq_b_floats ) {
free(seq_b_floats);
}
#endif
}
/**
* Reads sting sequence from file and retturns
* it to a new string
**/
string read_sequence_from_file(char *filename) {
ifstream file(filename);
if (file) {
printf("Opened file \"%s\"\n", filename);
} else {
fprintf(stderr, "Error: Can't open the file %s\n", filename);
exit(1);
}
printf("Reading file \"%s\"\n", filename);
string seq;
char line[20000];
while(file.good())
{
file.getline(line, 20000);
if( line[0] == 0 || line[0]== '#' )
continue;
for( int i = 0; line[i] != 0; ++i )
{
int c = toupper(line[i]);
if( c != 'A' && c != 'G' && c != 'C' && c != 'T' )
continue;
seq.push_back(char(c));
}
}
printf("File \"%s\" read\n\n", filename);
return seq;
}
<file_sep># Which test to run from 0..2
test="$1"
# Test sequence pairs
file1[0]="data/LITMUS28i.gbk.txt"
file2[0]="data/LITMUS28i-mal.gbk.txt"
file1[1]="data/M13KE.gbk.txt"
file2[1]="data/M13KO7.gbk.txt"
file1[2]="data/Adenovirus-C.txt"
file2[2]="data/Enterobacteria-phage-T7.txt"
# Make executables
cd smwt-org
make all
cd ../smwt-paral
make all
cd ../
# Run executables
./smwt-org/smwt 0.33 1.33 ${file1[test]} ${file2[test]} > org.txt
./smwt-paral/smwt-paral 0.33 1.33 ${file1[test]} ${file2[test]} > paral.txt
# Compare outputs
diff org.txt paral.txt
<file_sep># <NAME> - local sequence alignment
A simple parallel implementation of the [<NAME>man](https://en.wikipedia.org/wiki/Smith%E2%80%93Waterman_algorithm)'s algorithm, created as a university assignment. Parallelism was achieved using the [OpenMp](http://openmp.org/wp/) API for multi-threaded applications and AVX vectorization for finer tuning.
## Algorithm Design
This implementation uses the wave-front method, for anti-diagonal calculation of the score matrix. The last, is a `NxM` float matrix, where `N,M` are the lengths of the two input sequences. The score matrix calculation, happens in blocks of variable size. The blocking size, is determined by the number of threads available, as well as the sequences' size and other fine-tuned constants defined through benchmarking on our machine.
The computational phase follows a consumer producer pattern. The master thread, produces OpenMP Tasks for each block in the score matrix, which are later consumed by working threads using AVX vectorization instructions, when applicable, to speed-up the calculations. For more information on the decisions of this design and overall walk-through on the development check the project's [report](./report.pdf).
## Results
Each of these implementation were tested with no optimization `-O0` and all optimizations `-O3` flags, using one to four threads (systems maximum). The table bellow contains the speed-up measurement against the simple serial implementation:
| # Threads | 1 | 2 | 4 |
| --- | :-: |:-: | :-: |
| OpenMP-O0 | 1.15 | 2.12 | 2.63 |
| OpenMP-O3 | 1.58 | 3.00 | 3.67 |
| OpenMP-O0 + AVX | 2.93 | 5.41 | 6.74 |
| OpenMP-O3 + AVX | 3.48 | 6.18 | 8.14 |
## Testing
Input test sequences are provided, in the [data](./data) directory of this project. To compare the execution of the original and the parallel implementation, simply run the `compare.sh` script from the root directory, of this project. This script, takes as argument a number #`0-2`, which represent small, medium and a large test cases.
``` shell
# Test on a medium length sequence
$ ./compare.sh 1
```
## Compiling
To compile each implementation, simply run the `make` command. The build requirements are listed below:
* g++ compiler with OpenMp v4.0 or greater
* AVX enabled CPU
> Troubleshooting: setting the `__SIMD__` flag to zero, will resolve vectorization related errors, on systems which don't support [Intel AVX Intrinsics](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#techs=AVX).
## Disclaimer
This is not a "great" implementation to be used for real purposes. There are really faster and more flexible implementations out there. This is just a university project, heavily optimized to run on a specific machine.
|
3f1953a3738979cb4bde83d18c1473ccf3a071a5
|
[
"Markdown",
"Makefile",
"C++",
"Shell"
] | 5
|
Makefile
|
xu842251462/sequence-alignment
|
8cf9431c6407bffcceade0fd4c4062e99e91d5d9
|
5987da52fbdc22b4d56686a07b6124532431cd25
|
refs/heads/master
|
<file_sep><?php
require_once 'File.php';
include_once 'Log.php';
//include 'CVS.php';
//include 'XML.php';
<file_sep><?php
namespace s10Core\MyFile;
/**
* @todo Write to Log file of s10 App Project
* @version 1.2
*
* @author <NAME> <<EMAIL>> Phone: +84 1282 303 100
* @copyright (c) 2016, <NAME>
*/
class Log {
/**
* @todo write log message
* @param $message string
*/
private static $path = null;
private static $fileLog = null;
private static $content = null;
static function write($message = null, $app = 'API', $fnc = 'api') {
if (!file_exists($_SERVER['DOCUMENT_ROOT'] . '/.s10AppsLog/' . $app)) {
mkdir($_SERVER['DOCUMENT_ROOT'] . '/.s10AppsLog/' . $app, 0777, true);
}
self::$path = $_SERVER['DOCUMENT_ROOT'] . '/.s10AppsLog/' . $app . '/';
self::$fileLog = '[' . date('Y.m.d') . '] - ' . $app . '@' . $fnc . '.txt';
self::$content = '[' . date('Y-m-d H:i:s') . '] - ' . $message . PHP_EOL . '--------------' . PHP_EOL;
File::write(self::$path . '/' . self::$fileLog, self::$content, true);
}
function __destruct() {
unset(self::$path);
unset(self::$fileLog);
unset(self::$content);
}
}
<file_sep><?php
/**
* Global Constants for API Slim App
* Store reused object, variable, array in app.
* Array of constants, array of table lables and many other logic.
* TODO can this way easy to implement multi-langual, use class instead of return array.
* These general data can be use anywhere in application.
*/
/** ---- Define for single special type variable: DEFINDED string, numbers in PHP ---- **/
if (!defined('JSON_OPTIONS')){
define('JSON_OPTIONS', JSON_NUMERIC_CHECK | JSON_HEX_TAG | JSON_HEX_APOS |
JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);
}
/** ---- Define for list, array, hash, normal string, number ... ---- **/
class ApiConstant {
public static $JSON_ERROR_STATIC = ['error' => true];
public static $JSON_ERROR_NOT_FOUND = ['error' => true, 'message' => 'Item not found.'];
public static $JSON_ERROR_WRONG_FORMAT = ['error' => true, 'message' => 'Input format wrong.'];
}<file_sep><?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
namespace s10Core;
/**
* @todo Define class Default Template Slim Application for s10API
* @version 1.2
*
* @author <NAME> <<EMAIL>> Phone: +84 1282 303 100
* @copyright (c) 2016, <NAME>
*/
class DefaultApi {
/**
* public properties
*/
public static $isWriteLog = TRUE; // Set write log enable
public static $logMessage = 'Running OK.'; // Use for write log
public static $isDebug = TRUE; // Set Debug Turn ON
public static $appName = 'API'; // Set App Name
// Set Database Configuration
public static $arrDatabaseConfigIdiOrm = [
'connection_string' => 'mysql:host=localhost;dbname=my_database',
'username' => 'database_user',
'password' => '<PASSWORD>'
];
// Set Slim Application Configuration
public static $arrSlimContainer = [];
/**
* @todo For override __construct class App
* @tutorial Re-define all
*
*/
public function __construct() {
// $this->addApiSlimContainer();
$this->app = new \Slim\App(self::$arrSlimContainer);
$this->enableMethods();
$this->generateRouterList();
$this->app->run();
}
/**
* @todo set Slim method get, map, ...
*/
public function enableMethods() {}
/**
* @todo Generation Router List into root(index) page.
*/
private function generateRouterList(){
foreach ($this->app->getContainer()->get('router')->getRoutes() as $route){
if($route->getPattern() === '/'){
echo("ERROR: Route '/' are really taken. Please choose another route!");die;
}
}
$this->app->get('/', function ($request, $response) {
$routers = array_slice($this->get('router')->getRoutes(), 0, -1);
// Will be fix soon...
ddd($routers);
return $response;
});
}
/**
* Write to log file (find in folder .s10AppsLog)
*/
public function __destruct() {
if (self::$isWriteLog) {
MyFile\Log::write(self::$logMessage, self::$appName, 'LogApi');
}
}
public function addApiSlimContainer() {
// Register service provider with the container
$container = new \Slim\Container;
$container['cache'] = function () {
return new \Slim\HttpCache\CacheProvider();
};
self::$arrSlimContainer = $container;
}
}
<file_sep><?php
/**
* Define debug mode for apis application
* set FALSE to turn off debug
*/
//define("DEBUG_MODE", FALSE);
define("DEBUG_MODE", TRUE);
/**
* REQUIRE for run APIs
* DO NOT Touch this file if must needed
*/
define('ROOT', __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR);
require(ROOT . 'config' . DIRECTORY_SEPARATOR . 'bootstrapSlimApi.php');
/**
* SET SHOW ERROR
*/
//error_reporting(0);
error_reporting(E_ERROR);
/**
*
* Define name of api application choose what ever you want
*/
$classApplication = 'BkMusic';
require_once($classApplication . '.php');
/**
* Function call to start Slim APIs application
*
* @return void
*/
function startApp($classApplication) {
new $classApplication();
}
/*
* Run Slim app in mode defined
*/
if (!DEBUG_MODE) {
startApp($classApplication);
} else {
$bench = new Ubench();
$bench->start();
startApp($classApplication);
$bench->end();
$str = PHP_EOL . 'Time: ' . $bench->getTime(true) . ' microsecond -> ' . $bench->getTime(false, '%d%s');
$str .= PHP_EOL . 'MemoryPeak: ' . $bench->getMemoryPeak(true) . ' bytes -> ' . $bench->getMemoryPeak(false, '%.3f%s');
$str .= PHP_EOL . 'MemoryUsage: ' . $bench->getMemoryUsage(true);
s10Core\MyFile\Log::write($str, $classApplication, "TestBenchmark" . $classApplication);
unset($str);
}
<file_sep><?php
namespace s10Core\MyFile;
/**
* @todo Generate XML From Array
* @version 1.2
*
* @author <NAME> <<EMAIL>> Phone: +84 1282 303 100
* @copyright (c) 2016, <NAME>
*/
class XML {
function generate_xml_from_array($array, $node_name) {
$xml = '';
if (is_array($array) || is_object($array)) {
foreach ($array as $key => $value) {
if (is_numeric($key)) {
$key = $node_name;
}
$xml .= '<' . $key . '>' . self::generate_xml_from_array($value, $node_name) . '</' . $key . '>';
}
} else {
$xml = htmlspecialchars($array, ENT_QUOTES);
}
return $xml;
}
static function generate_valid_xml_from_array($array, $node_block = 'nodes', $node_name = 'node') {
$xml = '<?xml version="1.0" encoding="UTF-8" ?>';
$xml .= '<' . $node_block . '>';
$xml .= self::generate_xml_from_array($array, $node_name);
$xml .= '</' . $node_block . '>';
return $xml;
}
}
<file_sep><?php
namespace s10Core;
/**
* Description of parserData
*
* @author TienGiang
*/
class ParserData {
/**
*
* @param type $url
* @return type Description
*/
public static function getByCURL($url) {
}
/**
*
* @param type $url
* @return type Description
*/
public static function getHmltBySimpleDomParse($url, $postData = null) {
try {
$context = null;
if(!is_null($postData)){
$postString = !is_null($postData) ? http_build_query($postData) : '';
$opts = [
'http' => [
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postString
]
];
$context = stream_context_create($opts);
}
return file_get_html($url, false, $context);
unset($postData);
unset($postString);
unset($context);
} catch (Exception $exc) {
}
}
}
<file_sep><?php
/**
* For API Autoload
*
* @author <NAME> <<EMAIL>>
*/
define('DS', DIRECTORY_SEPARATOR);
define('ROOT_DIR', __DIR__ . DS . '..' . DS);
require_once ROOT_DIR . 'vendor' . DS . 'autoload.php';
require_once ROOT_DIR . 'plugins' . DS . 's10Core' . DS .'autoloadApi.php';
include_once 'ApiConstant.php';
<file_sep><?php
use s10Core\DefaultApi;
use s10Core\ParserData;
use Valitron\Validator as V;
error_reporting(-1);
/**
* BkMusic Application
*/
class BkMusic extends DefaultApi {
private $sqlLocal = 'sqlite:BkMusic.db';
private $mySqlSetting = [
'connection_string' => 'mysql:host=localhost;dbname=BkMusic',
'username' => 'root',
'password' => '',
'return_result_sets' => true,
'driver_options' => [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'],
];
/**
* Re-define public properties in __construct() method (except $logMessage for WRITE TO LOG)
*/
public function __construct() {
self::$isWriteLog = TRUE;
self::$isDebug = DEBUG_MODE;
self::$appName = get_class($this);
self::$arrDatabaseConfigIdiOrm = $this->sqlLocal;
self::$arrSlimContainer = [];
// Write magic method __construct() of parent(defaultApp) after re-define public properties
// $this->container = new \Slim\Container(['settings' => ['displayErrorDetails' => true]]);
parent::__construct();
}
/**
* define request methods here
*
*/
public function enableMethods() {
$this->app->get('/GetCategories', self::$appName . '::getCategories')->setName('Category');
$this->app->get('/GetNhacHot[/{playlistId}[/{page}]]', self::$appName . '::parserNhacHot')->setName('NhacHot');
$this->app->get('/GetAlbum[/{albumListId}[/{page}]]', self::$appName . '::parserAlbum')->setName('Album');
$this->app->get('/GetChart[/{chartId}]', self::$appName . '::parserChart')->setName('MusicChart');
$this->app->get('/GetSongs', self::$appName . '::parserSongs')->setName('Songs');
$this->app->get('/GetSinger', self::$appName . '::parserSinger')->setName('Singer');
}
public static function getCategories($request, $response, $args) {
ORM::configure(self::$arrDatabaseConfigIdiOrm);
$getCategories = ORM::for_table('Categories')
->select(['id', 'name', 'img', 'parentId'])
->where_not_equal(['parentId' => 0, 'isDelete' => 1])
->find_many();
$categories = [];
foreach ($getCategories as $cateItem) {
array_push($categories, [
"categoryCode" => $cateItem->id,
"name" => $cateItem->name,
"img" => $cateItem->img,
"parentId" => $cateItem->parentId
]);
}
return $response->withJson($categories, 200, JSON_OPTIONS);
}
public static function parserNhacHot($request, $response, $args) {
$playlistId = isset($args['playlistId']) ? $args['playlistId'] : '1';
$page = (isset($args['page']) && $args['page'] != 1) ? intval($args['page']) : '';
ORM::configure(self::$arrDatabaseConfigIdiOrm);
$categories = ORM::for_table('Categories')
->where(['isDelete' => 0, 'parentId' => 1])
->find_one($playlistId);
if (!$categories) {
return $response->withJson(ApiConstant::$JSON_ERROR_NOT_FOUND, 404);
}
$url = $categories->url;
$url .= ((is_numeric($page)) ? $page . '.' : '') . 'html';
$arrSongs = [];
$html = ParserData::getHmltBySimpleDomParse($url);
$liElements = $html->find('ul[class=list_item_music] li');
foreach ($liElements as $liElement) {
$contentSong = $liElement->find('div[class=item_content]');
array_push($arrSongs, [
'songName' => trim($liElement->find('div[class=item_content] a[class=name_song]', 0)->plaintext),
'songUrl' => trim($liElement->find('div[class=item_content] a[class=name_song]', 0)->href),
'singer' => trim($liElement->find('div[class=item_content] a[class=name_singer]', 0)->plaintext),
'singerUrl' => trim($liElement->find('div[class=item_content] a[class=name_singer]', 0)->href),
]);
}
unset($liElements);
$html->clear();
unset($html);
$appResponse = $response->withJson($arrSongs);
return $appResponse;
}
public static function parserAlbum($request, $response, $args) {
$albumId = isset($args['albumListId']) ? $args['albumListId'] : '29';
$page = (isset($args['page']) && $args['page'] != 1) ? intval($args['page']) : '';
ORM::configure(self::$arrDatabaseConfigIdiOrm);
$categories = ORM::for_table('Categories')
->where(['isDelete' => 0, 'parentId' => 2])
->find_one($albumId);
if (!$categories) {
return $response->withJson(ApiConstant::$JSON_ERROR_NOT_FOUND, 404);
}
$url = $categories->url;
$url .= ((is_numeric($page)) ? $page . '.' : '') . 'html';
$arrAlbums = [];
$html = ParserData::getHmltBySimpleDomParse($url);
$liElements = $html->find('div[class=list_album] div[class=fram_select] ul li');
foreach ($liElements as $liElement) {
array_push($arrAlbums, [
'albumArt' => trim(array_shift($liElement->find('div[class=box-left-album] span[class=avatar] img'))->getAttribute('data-src')),
'albumName' => trim(array_shift($liElement->find('div[class=info_album] a[class=name_song]'))->plaintext),
'albumUrl' => trim(array_shift($liElement->find('div[class=info_album] a[class=name_song]'))->href),
'singer' => trim(array_shift($liElement->find('div[class=info_album] a[class=name_singer]'))->plaintext),
'singerUrl' => trim(array_shift($liElement->find('div[class=info_album] a[class=name_singer]'))->href),
]);
}
unset($liElements); $html->clear(); unset($html);
$appResponse = $response->withJson($arrAlbums);
return $appResponse;
}
public static function parserChart($request, $response, $args) {
$albumId = isset($args['chartId']) ? $args['chartId'] : '45';
ORM::configure(self::$arrDatabaseConfigIdiOrm);
$categories = ORM::for_table('Categories')
->where(['isDelete' => 0, 'parentId' => 3])
->find_one($albumId);
if (!$categories) {
return $response->withJson(ApiConstant::$JSON_ERROR_NOT_FOUND, 404);
}
$url = $categories->url;
$arrSongs = [];
$html = ParserData::getHmltBySimpleDomParse($url);
$playlistUrl = array_shift($html->find('div[class=box_view_week] a[class=active_play]'))->href;
$liElements = $html->find('div[class=list_chart_page] ul[class=list_show_chart] li');
foreach ($liElements as $liElement) {
array_push($arrSongs, [
'albumArt' => trim(array_shift($liElement->find('div[class=box_info_field] a img'))->getAttribute('src')),
'songName' => trim(array_shift($liElement->find('div[class=box_info_field] a[class=name_song]'))->plaintext),
'songUrl' => trim(array_shift($liElement->find('div[class=box_info_field] a[class=name_song]'))->href),
'singer' => trim($liElement->find('div[class=box_info_field] a[class=name_singer]', 0)->plaintext),
'singerUrl' => trim($liElement->find('div[class=box_info_field] a[class=name_singer]', 0)->href),
]);
}
$arrChart = [
'playAllUrl' => $playlistUrl,
'songs' => $arrSongs
];
unset($liElements);
$html->clear();
unset($html);
$appResponse = $response->withJson($arrChart);
return $appResponse;
}
public static function parserSongs($request, $response, $args) {
$params = $request->getQueryParams('urlSong', null);
// validate URL
$v = new V($params);
$v->rule('required', ['urlSong']);
$v->rule('url', ['urlSong']);
if(!$v->validate()){
return $response->withJson(ApiConstant::$JSON_ERROR_STATIC + ['message' => $v->errors()], 200);
}
$arrListTrack = self::extractTracklist($params['urlSong']);
$appResponse = $response->withJson($arrListTrack);
return $appResponse;
}
public static function parserSinger($request, $response, $args) {
$params = $request->getQueryParams('urlSinger', null);
// validate URL
$v = new V($params);
$v->rule('required', ['urlSinger']);
$v->rule('url', ['urlSinger']);
if(!$v->validate()){
return $response->withJson(ApiConstant::$JSON_ERROR_STATIC + ['message' => $v->errors()], 200);
}
$html = ParserData::getHmltBySimpleDomParse($params['urlSinger']);
$arrAlbums = [];
$liAlbums = $html->find('div[class=list_album] div[class=fram_select] ul li');
foreach ($liAlbums as $itemAlbum) {
$albumArt = trim(array_shift($itemAlbum->find('div[class=box-left-album] span[class=avatar] img'))->getAttribute('data-src'));
$albumName = trim(array_shift($itemAlbum->find('div[class=info_album] a[class=name_song]'))->plaintext);
$albumUrl = trim(array_shift($itemAlbum->find('div[class=info_album] a[class=name_song]'))->href);
array_push($arrAlbums, [
'albumArt' => $albumArt,
'albumName' => $albumName,
'albumUrl' => $albumUrl,
]);
}
$arrSongs = [];
$liSongs = $html->find('ul[class=list_item_music] li');
foreach ($liSongs as $itemSong) {
$songName = trim(array_shift($itemSong->find('div[class=item_content] a[class=name_song]'))->plaintext);
$songUrl = trim(array_shift($itemSong->find('div[class=item_content] a[class=name_song]'))->href);
array_push($arrSongs, [
'songName' => $songName,
'songUrl' => $songUrl
]);
}
$arrInfoSinger = [
'albums' => $arrAlbums,
'songs' => $arrSongs,
];
$appResponse = $response->withJson($arrInfoSinger);
return $appResponse;
}
//Search http://www.nhaccuatui.com/ajax/search?q=noo%20phu
private static function extractStringInfoPlaylist($str) {
$strExtract = trim($str);
$arrReplace = [
'<![CDATA[' => '',
']]>' => ''
];
return str_replace(array_keys($arrReplace), array_values($arrReplace), $strExtract);
}
private static function extractTracklist($url) {
// Get javascript content
$html = ParserData::getHmltBySimpleDomParse($url);
$srciptString = $html->find('div[class=playing_absolute]');//new
$scriptContent = array_shift($srciptString)->innertext;
$arrScriptContent = explode('player.peConfig.xmlURL = "', $scriptContent);
$arrSplited = explode('";', $arrScriptContent[1]);
// cut string get flash xml file
$urlPlaylist = $arrSplited[0];
// unset html for Memory leak!
$html->clear(); unset($html); unset($arrScriptContent); unset($arrSplited);
//Get xml url
$htmlTracks = ParserData::getHmltBySimpleDomParse($urlPlaylist);
$tracks = $htmlTracks->find('tracklist track');
$arrListTrack = [];
foreach ($tracks as $track) {
$title = $track->find('title');
$creator = $track->find('creator');
$newtab = $track->find('newtab');
$bgimage = $track->find('bgimage');
$avatar = $track->find('avatar');
$key = $track->find('key');
$location = $track->find('location');
$info = $track->find('info');
array_push($arrListTrack, [
'songName' => self::extractStringInfoPlaylist(array_shift($title)->plaintext),
'singer' => self::extractStringInfoPlaylist(array_shift($creator)->plaintext),
'singerUrl' => self::extractStringInfoPlaylist(array_shift($newtab)->plaintext),
'bgimage' => self::extractStringInfoPlaylist(array_shift($bgimage)->plaintext),
'avatar' => self::extractStringInfoPlaylist(array_shift($avatar)->plaintext),
'keyMp3' => self::extractStringInfoPlaylist(array_shift($key)->plaintext),
'mp3Url' => self::extractStringInfoPlaylist(array_shift($location)->plaintext),
'songUrl' => self::extractStringInfoPlaylist(array_shift($info)->plaintext),
]);
}
unset($tracks); $htmlTracks->clear(); unset($htmlTracks);
return $arrListTrack;
}
}<file_sep><?php
/**
* @todo set autoloading for s10Core
* @version 1.2
*
* @author <NAME> <<EMAIL>> Phone: +84 1282 303 100
* @copyright (c) 2016, <NAME>
*/
include_once 'DefaultApi.php';
include_once 'ParserData.php';
include_once 'MyFile/load.php';
if(!DEBUG_MODE){
Kint::enabled(FALSE);
}
<file_sep><?php
namespace s10Core\MyFile;
/**
* @todo Working with CSV file type
* @version 1.0
*
* @author <NAME> <<EMAIL>> Phone: +84 1282 303 100
* @copyright (c) 2016, <NAME>
*/
class CSV {
static function write($data, $path) {
$result = 0;
$outstream = fopen($path, 'a+');
foreach ($data as $fields) {
fputcsv($outstream, $fields);
}
rewind($outstream);
$csv = fgets($outstream);
fclose($outstream);
if (!empty($csv)) {
$result = 1;
}
return $result;
}
static function read($path) {
$csvarray = array();
if (file_exists($path)) {
try {
# Open the File.
if (($handle = fopen($path, "r")) !== FALSE) {
# Set the parent multidimensional array key to 0.
$nn = 0;
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
# Count the total keys in the row.
$c = count($data);
# Populate the multidimensional array.
for ($x = 0; $x < $c; $x++) {
$csvarray[$nn][$x] = $data[$x];
}
$nn++;
}
# Close the File.
fclose($handle);
}
} catch (Exception $exc) {
//File::write(AppURL::logFolder('CSV@FileFolder') . 'log.' . date('Y_m_d') . '.txt', '[' . date('Y-m-d H:i:s') . '] - ' . $exc->getMessage() . '.' . PHP_EOL);
Log::write($exc->getMessage());
}
}
# Return the contents of the multidimensional array.
return $csvarray;
}
}
|
bc0e53408347289dbd16ddaf9b55702c49e1ae36
|
[
"PHP"
] | 11
|
PHP
|
nguyentiengiang/BkMusicBackend
|
3c97defa9ed456cb17e849b5c9f2ad34dd83101c
|
c6de7648fa4ed63e681e6ca379bd39dc0b3a6c26
|
refs/heads/master
|
<repo_name>cd-in-practice/ansible-in-practice<file_sep>/2-deploy-java/README.md
## 任务列表
1. 执行 `ansible-playbook -i hosts.yaml playbook.yaml` 成功
2. 创建用户 apps 及用户组 apps:
* user 模块: https://docs.ansible.com/ansible/2.9/modules/user_module.html
* group 模块: https://docs.ansible.com/ansible/2.9/modules/group_module.html
3. 创建以下文件夹,并设置文件夹的用户和组为 apps:
/apps,/apps/hello,/apps/hello/bin,/apps/hello/logs
* file 模块: https://docs.ansible.com/ansible/2.9/modules/file_module.html
4. 将 helloworld-0.0.2.jar copy 到 /apps/hello/bin 目录下,设置该 jar 文件的用户和用户组为 apps
* copy 模块: https://docs.ansible.com/ansible/2.9/modules/copy_module.html
5. 使用 template 模块将 app.service copy 到目标服务器的 /etc/systemd/system 中,并重命名 hello.service :
* template 模块: https://docs.ansible.com/ansible/2.9/modules/template_module.html
6. 启动 hello 服务
* service 模块: https://docs.ansible.com/ansible/2.9/modules/service_module.html
7. 监听 hello 服务是否启动成功
* wait_for 模块: https://docs.ansible.com/ansible/2.9/modules/wait_for_module.html
8. 为目标机器安装 JDK 1.8:
1. 在本地仓库中创建 roles 目录
2. clone 代码:https://github.com/geerlingguy/ansible-role-java 到 roles 目录中
3. 在 playbook.yml 文件中加入 ansible-role-java 的role
9. 创建自定义 role: hello role
1. 进入 roles 目录:cd roles
2. 使用命令生成 role 模板:`ansible-galaxy init hello`
3. 将 hello 的部署逻辑(在 playbook.yml 中)写入到 hello role 中
10. 将 hello 部署到多台机器
* 需要修改 hosts 文件
11. 多环境部署<file_sep>/1-introduce/Vagrantfile
IMAGE_NAME = "bento/ubuntu-18.04"
Vagrant.configure("2") do |config|
config.ssh.insert_key = false
config.vm.provider "virtualbox" do |v|
v.memory = 1024
v.cpus = 1
end
config.vm.define "app" do |config|
config.vm.box = IMAGE_NAME
config.vm.network "private_network", ip: "192.168.51.10"
config.vm.hostname = "app"
config.vm.provision :shell, :inline => "sudo sed -i 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config; sudo systemctl restart sshd;", run: "always"
# master.vm.provision "ansible" do |ansible|
# ansible.playbook = "playbook.yml"
# end
end
config.vm.define "db" do |config|
config.vm.box = IMAGE_NAME
config.vm.network "private_network", ip: "192.168.51.100"
config.vm.hostname = "db"
config.vm.network :forwarded_port, guest: 22, host: 1234
config.vm.provision :shell, :inline => "sudo sed -i 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config; sudo systemctl restart sshd;", run: "always"
# config.vm.provision "ansible" do |ansible|
# ansible.playbook = "nfs-playbook.yml"
# end
end
end
|
bde424d1ed4e41c3a53add3f428f6616fc06add4
|
[
"Markdown",
"Ruby"
] | 2
|
Markdown
|
cd-in-practice/ansible-in-practice
|
b47b238fe6631edddec056118e9c8d19fb07c6f0
|
c35242985b10807dbb704266172607c45912a6ae
|
refs/heads/master
|
<file_sep>package com.school;
import com.school.infrastructure.repository.FluentJdbcRepository;
import com.school.infrastructure.restapi.StudentController;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
@AutoConfigureTest
@RunWith(SpringRunner.class)
public class MainApplicationIntegrationTest {
@Autowired
private StudentController studentController;
@Autowired
private FluentJdbcRepository fluentJdbcRepository;
@Test
public void should_create_an_controller() {
assertThat(studentController).isNotNull();
}
@Test
public void should_create_an_repository() {
assertThat(fluentJdbcRepository).isNotNull();
}
}
<file_sep>package com.school.infrastructure.restapi;
import com.school.domain.SchoolService;
import com.school.domain.StudentCommand;
import lombok.val;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public class StudentControllerTest {
@Mock
private SchoolService service;
@InjectMocks
StudentController controller;
@Test
public void should_call_service_to_save_when_controller_is_invoked() {
val request = new StudentRequest("<NAME>", 404, "Winterfell");
controller.create(request);
verify(service).create(any(StudentCommand.class));
}
@Test
public void should_call_service_to_get_student_by_roll() {
controller.find(1234);
verify(service).get(1234);
}
}
<file_sep>package com.school.config;
import liquibase.integration.spring.SpringLiquibase;
import lombok.val;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class LiquibaseConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.liquibase")
public DataSource dataSource(){
return DataSourceBuilder.create().build();
}
@Bean
public SpringLiquibase schemaLiquibase(){
val schemaLiquibase = new SpringLiquibase();
schemaLiquibase.setDataSource(dataSource());
schemaLiquibase.setChangeLog("classpath:/liquibase/db.changelog.json");
return schemaLiquibase;
}
}
<file_sep>package com.school.config;
import org.codejargon.fluentjdbc.api.FluentJdbc;
import org.codejargon.fluentjdbc.api.FluentJdbcBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class PersistenceConfig {
@Autowired
private DataSource dataSource;
@Bean
public FluentJdbc fluentJdbc(){
return new FluentJdbcBuilder()
.connectionProvider(dataSource)
.build();
}
}
<file_sep>package com.school.domain;
import com.school.domain.entities.Student;
public interface SchoolRepository {
void save(Student student);
Student findOne(Integer id);
}
<file_sep>package com.school.infrastructure.repository;
import com.school.domain.SchoolRepository;
import com.school.domain.entities.Student;
import org.codejargon.fluentjdbc.api.FluentJdbc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class FluentJdbcRepository implements SchoolRepository {
@Autowired
private FluentJdbc fluentJdbc;
@Override
public void save(Student student) {
fluentJdbc.query()
.update("INSERT INTO T_STUDENT VALUES (? ,? ,?) ")
.params(student.getName(), student.getId(), student.getAddress())
.run();
System.out.println("In repo");
return;
}
@Override
public Student findOne(Integer id) {
return fluentJdbc.query().select("SELECT * FROM T_STUDENT WHERE ID = ?")
.params(id)
.firstResult(it -> new Student(it.getString("NAME"), it.getInt("ID"), it.getString("ADDRESS")))
.orElse(null);
}
}
<file_sep>package com.school.infrastructure.restapi;
import com.school.domain.StudentCommand;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public class StudentRequest {
private String name;
private Integer id;
private String address;
public StudentCommand toCommand() {
return new StudentCommand(name, id, address);
}
}
<file_sep>package com.school.domain;
import com.school.domain.entities.Student;
import lombok.val;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public class SchoolServiceTest {
@Mock
private SchoolRepository repository;
@InjectMocks
private SchoolService service;
@Test
public void should_call_repository_to_save_student_details() {
val argumentCapture = ArgumentCaptor.forClass(Student.class);
val command = new StudentCommand("<NAME>", 404, "Winterfell");
service.create(command);
verify(repository).save(argumentCapture.capture());
assertThat(argumentCapture.getValue()).isEqualToComparingFieldByField(new Student("<NAME>", 404, "Winterfell"));
}
}
<file_sep>package com.school.infrastructure.restapi;
import com.school.domain.StudentCommand;
import lombok.val;
import org.junit.Test;
import static org.assertj.core.api.Java6Assertions.assertThat;
public class StudentRequestTest {
@Test
public void should_return_studentCommand_when_called() {
val request = new StudentRequest("<NAME>", 404, "Winterfell");
val actual = request.toCommand();
assertThat(actual).isEqualToComparingFieldByField(new StudentCommand("<NAME>", 404, "Winterfell"));
}
}
<file_sep>package com.school.domain.entities;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Student {
private String name;
private Integer id;
private String address;
}
<file_sep># hexagonal-school
Simple application with HEXAGONAL architecture. Details: https://blog.ndepend.com/hexagonal-architecture/
Domain: All the business logic will be in the domain. It will have no dependency on any framework.
Infrastructure: Infrastructure contains all the dependency on spring, fluent-jdbc, etc.
Bootstrap: All the spring-boot configurations are in bootstrap which does the wiring of the application.
<file_sep>package com.school.config;
import com.school.domain.SchoolService;
import com.school.infrastructure.repository.FluentJdbcRepository;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DomainConfig {
private final FluentJdbcRepository repository;
public DomainConfig(FluentJdbcRepository repository) {
this.repository = repository;
}
@Bean
public SchoolService schoolService() {
return new SchoolService(repository);
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.private.arch</groupId>
<artifactId>hexagonal-school</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>bootstrap</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.private.arch</groupId>
<artifactId>infrastructure</artifactId>
<version>${project.version}</version>
</dependency>
<!-- ALL STARTERS SHOULD BE ADDED HERE -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
<version>${liquibase.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<!-- Test -->
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-spring</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>${basedir}/src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/application.yml</include>
</includes>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/features</directory>
<targetPath>features</targetPath>
</testResource>
<testResource>
<directory>src/test/resources</directory>
</testResource>
</testResources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
<configuration>
<requiresUnpack>
<dependency>
<groupId>com.private.arch</groupId>
<artifactId>infrastructure</artifactId>
</dependency>
</requiresUnpack>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<configuration>
<additionalClasspathElements>
<additionalClasspathElement>${basedir}/target/classes</additionalClasspathElement>
</additionalClasspathElements>
</configuration>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project><file_sep>package com.school;
import com.school.domain.entities.Student;
import com.school.infrastructure.repository.FluentJdbcRepository;
import lombok.val;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@AutoConfigureTest
@RunWith(SpringRunner.class)
public class StudentControllerIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private FluentJdbcRepository repository;
@Test
public void should_create_student_details_when_post_request() throws Exception {
val request = post("/v1.0/student")
.contentType(APPLICATION_JSON)
.content("{ \"name\": \"Thanos\", \"id\": 1001, \"address\": \"Earth\" }");
// When
mockMvc.perform(request)
.andExpect(status().isCreated())
.andReturn()
.getResponse()
.getContentAsString();
// Then
val created = repository.findOne(1001);
assertThat(created.getName()).isEqualTo("Thanos");
}
@Test
public void should_get_student_details_when_find() throws Exception {
repository.save(new Student("<NAME>", 101, "Hell"));
val request = get("/v1.0/student?rollNumber="+101)
.contentType(APPLICATION_JSON);
// When
val response = mockMvc.perform(request)
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
// Then
assertThat(response).isEqualTo("{\"name\":\"<NAME>\",\"id\":101,\"address\":\"Hell\"}");
}
}
<file_sep>package com.school.domain;
import com.school.domain.entities.Student;
import lombok.val;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class StudentCommandTest {
@Test
public void should_convert_to_entity_when_called(){
val command = new StudentCommand("<NAME>", 404, "Winterfell");
val actual = command.toEntity();
assertThat(actual).isEqualToComparingFieldByField(new Student("<NAME>", 404, "Winterfell"));
}
}
|
616b01b4d6cb379c81b05a1995f2598f0774d9ed
|
[
"Markdown",
"Java",
"Maven POM"
] | 15
|
Java
|
soubhik93/hexagonal-school
|
d6d04810ecfb2980a6d24def5db3e59d4a0b61dc
|
ab430d2f147faa769c672fe62a60faa7db145458
|
refs/heads/master
|
<repo_name>tppkdch123/hello-world<file_sep>/graduationProject/src/main/java/cn/yellow/test/Main.java
package cn.yellow.test;
import javafx.application.Application;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@EnableAutoConfiguration
@SpringBootApplication
public class Main {
public static void main(String[] args){
SpringApplication.run(Main.class,args);
}
}
<file_sep>/graduationProject/src/main/resources/application.properties
mybatis.datasource.url=jdbc:mysql://10.72.226.8:3306/DianPingCscPacific?user=dianpingcscpacif
mybatis.datasource.username=dianpingcscpacif
mybatis.datasource.password=
zebra.jdbcref=dianpingcscpacific
zebra.pooltype=tomcat-jdbc
<file_sep>/graduationProject/src/main/java/cn/yellow/test/bootDemo.java
package cn.yellow.test;
import cn.yellow.entity.huangShiZhe;
import cn.yellow.entity.huangShiZheExample;
import cn.yellow.mappers.huangShiZheMapper;
import cn.yellow.service.testService;
import com.dianping.zebra.dao.AsyncDaoCallback;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
@Controller
public class bootDemo {
@Autowired
private huangShiZheMapper hsz;
@RequestMapping("/")
@ResponseBody
public String testdeom() {
return "hello world";
}
@ResponseBody
@RequestMapping("/mybatis")
public String testMybatis() {
huangShiZheExample huangShiZheExample = new huangShiZheExample();
huangShiZheExample.Criteria criteria = huangShiZheExample.createCriteria();
criteria.andIdIsNotNull();
List<huangShiZhe> L = hsz.selectByExample(huangShiZheExample);
return new Gson().toJson(L);
}
@ResponseBody
@RequestMapping("/zebra-dao")
public String testAsync() {
huangShiZhe g=hsz.selectByPrimaryKey(1);
hsz.selectByPrimaryKey(1, new AsyncDaoCallback<huangShiZhe>() {
@Override
public void onSuccess(huangShiZhe huangShiZhe) {
System.out.println(huangShiZhe == null);
System.out.println(huangShiZhe.toString());
System.out.println("===========================");
System.out.println(huangShiZhe.getName() + " " + huangShiZhe.getSex());
}
@Override
public void onException(Exception e) {
System.out.println("o20CKp*?XZfp?");
}
});
System.out.println(g.toString());
return "ok";
}
@ResponseBody
@RequestMapping("/future")
public String selecetAll() {
huangShiZheExample example = new huangShiZheExample();
Future<List<huangShiZhe>> future = hsz.selectAll(example);
String x = "";
try {
List<huangShiZhe> list = future.get();
for (huangShiZhe h : list) {
x += h.getName() + h.getSex() + h.getId();
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return x;
}
}
<file_sep>/graduationProject/src/main/java/cn/yellow/mappers/huangShiZheMapper.java
package cn.yellow.mappers;
import cn.yellow.entity.huangShiZhe;
import cn.yellow.entity.huangShiZheExample;
import java.util.List;
import java.util.concurrent.Future;
import com.dianping.zebra.dao.AsyncDaoCallback;
import com.dianping.zebra.dao.annotation.TargetMethod;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component;
public interface huangShiZheMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table huangshizhe
*
* @mbggenerated Tue Dec 19 18:24:13 CST 2017
*/
int countByExample(huangShiZheExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table huangshizhe
*
* @mbggenerated Tue Dec 19 18:24:13 CST 2017
*/
int deleteByExample(huangShiZheExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table huangshizhe
*
* @mbggenerated Tue Dec 19 18:24:13 CST 2017
*/
int deleteByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table huangshizhe
*
* @mbggenerated Tue Dec 19 18:24:13 CST 2017
*/
int insert(huangShiZhe record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table huangshizhe
*
* @mbggenerated Tue Dec 19 18:24:13 CST 2017
*/
int insertSelective(huangShiZhe record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table huangshizhe
*
* @mbggenerated Tue Dec 19 18:24:13 CST 2017
*/
List<huangShiZhe> selectByExample(huangShiZheExample example);
@TargetMethod(name = "selectByExample")
Future<List<huangShiZhe>> selectAll(huangShiZheExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table huangshizhe
*
* @mbggenerated Tue Dec 19 18:24:13 CST 2017
*/
huangShiZhe selectByPrimaryKey(@Param("id") Integer id);
@TargetMethod(name="selectByPrimaryKey")
void selectByPrimaryKey(@Param("id") Integer id, AsyncDaoCallback<huangShiZhe> callback);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table huangshizhe
*
* @mbggenerated Tue Dec 19 18:24:13 CST 2017
*/
int updateByExampleSelective(@Param("record") huangShiZhe record, @Param("example") huangShiZheExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table huangshizhe
*
* @mbggenerated Tue Dec 19 18:24:13 CST 2017
*/
int updateByExample(@Param("record") huangShiZhe record, @Param("example") huangShiZheExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table huangshizhe
*
* @mbggenerated Tue Dec 19 18:24:13 CST 2017
*/
int updateByPrimaryKeySelective(huangShiZhe record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table huangshizhe
*
* @mbggenerated Tue Dec 19 18:24:13 CST 2017
*/
int updateByPrimaryKey(huangShiZhe record);
}
|
a360cc752434fbcd2bf14a75beb38bb6d556691e
|
[
"Java",
"INI"
] | 4
|
Java
|
tppkdch123/hello-world
|
6c56198ec75d24b87c75557a893c812c07abf536
|
86c82d7d4fe7cfc7bed1c62e29caef63ddd3c959
|
refs/heads/master
|
<repo_name>albelka/pdx-solar-system<file_sep>/js/scripts.js
//frontend
$(document).ready(function() {
myMap = function() {
var mapOptions = {
center: new google.maps.LatLng(45.5244733, -122.6513304),
zoom: 11,
mapTypeId: google.maps.MapTypeId.HYBRID
}
//create map object
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
//OMSI marker object
var markerOMSI = new google.maps.Marker({
position: new google.maps.LatLng(45.5084, -122.666),
map: map,
title: "OMSI",
icon: "img/big-icons/sun-icon.png"
});
var omsiString = "I was up all night wondering where the Sun had gone… then it dawned on me."
var omsiInfoWindow = new google.maps.InfoWindow({
content: omsiString
});
markerOMSI.addListener("click", function() {
omsiInfoWindow.open(map, markerOMSI)
});
// Mercury marker object
var markerMercury = new google.maps.Marker({
position: new google.maps.LatLng(45.5094, -122.666916),
map: map,
title: "Mercury",
icon: "img/big-icons/mercury-icon.png",
anchor: new google.maps.Point(12, 12),
});
var mercuryString = "";
var mercuryInfoWindow = new google.maps.InfoWindow({
content: mercuryString
});
markerMercury.addListener("click", function() {
mercuryInfoWindow.open(map, markerMercury)
});
// Venus marker object
var markerVenus = new google.maps.Marker({
position: new google.maps.LatLng(45.5102973, -122.66655),
map: map,
title: "Venus",
icon: "img/big-icons/venus-icon.png"
});
var venusString = "I'm Venus and I am the hottest planet in the solar system.";
var venusInfoWindow = new google.maps.InfoWindow({
content: venusString
});
markerVenus.addListener("click", function() {
venusInfoWindow.open(map, markerVenus)
});
// Earth marker object
var markerEarth = new google.maps.Marker({
position: new google.maps.LatLng(45.5108753, -122.6670293),
map: map,
title: "Earth",
icon: "img/big-icons/earth-icon.png"
});
var earthString = "";
var earthInfoWindow = new google.maps.InfoWindow({
content: earthString
});
markerEarth.addListener("click", function() {
earthInfoWindow.open(map, markerEarth)
});
// Mars marker object
var markerMars = new google.maps.Marker({
position: new google.maps.LatLng(45.5121377, -122.6679734),
map: map,
title: "Mars",
icon: "img/big-icons/mars-icon.png"
});
var marsString = "";
var marsInfoWindow = new google.maps.InfoWindow({
content: marsString
});
markerMars.addListener("click", function() {
marsInfoWindow.open(map, markerMars)
});
// Jupiter marker object
var markerJupiter = new google.maps.Marker({
position: new google.maps.LatLng(45.5218451, -122.6660479),
map: map,
title: "Jupiter",
icon: "img/big-icons/jupiter-icon.png"
});
var jupiterString = "Q: How does Jupiter hold up his trousers? <br>A: With an asteroid belt.";
var jupiterInfoWindow = new google.maps.InfoWindow({
content: jupiterString
});
markerJupiter.addListener("click", function() {
jupiterInfoWindow.open(map, markerJupiter)
});
// Saturn marker object
var markerSaturn = new google.maps.Marker({
position: new google.maps.LatLng(45.4755784, -122.6685779),
map: map,
title: "Saturn",
icon: "img/big-icons/saturn-icon.png"
});
var saturnString = "Q: What did Mars say to Saturn? <br>A: Give me a ring sometime!";
var saturnInfoWindow = new google.maps.InfoWindow({
content: saturnString
});
markerSaturn.addListener("click", function() {
saturnInfoWindow.open(map, markerSaturn)
});
// Ismene marker object
var markerIsmene = new google.maps.Marker({
position: new google.maps.LatLng(45.5177771, -122.6537634),
map: map,
title: "Ismene",
icon: "img/big-icons/ismene-icon.png"
});
var ismeneString = "";
var ismeneInfoWindow = new google.maps.InfoWindow({
content: ismeneString
});
markerIsmene.addListener("click", function() {
ismeneInfoWindow.open(map, markerIsmene)
});
// Uranus marker object
var markerUranus = new google.maps.Marker({
position: new google.maps.LatLng(45.5125688, -122.5933671),
map: map,
title: "Uranus",
icon: "img/big-icons/uranus-icon.png"
});
var uranusString = "I am an ice giant.";
var uranusInfoWindow = new google.maps.InfoWindow({
content: uranusString
});
markerUranus.addListener("click", function() {
uranusInfoWindow.open(map, markerUranus)
});
// Neptune marker object
var markerNeptune = new google.maps.Marker({
position: new google.maps.LatLng(45.5467316, -122.5660408),
map: map,
title: "Neptune",
icon: "img/big-icons/neptune-icon.png"
});
var neptuneString = "What kind of music do planets listen to? ...Nep-tunes.";
var neptuneInfoWindow = new google.maps.InfoWindow({
content: neptuneString
});
markerNeptune.addListener("click", function() {
neptuneInfoWindow.open(map, markerNeptune)
});
// Pluto marker object
var markerPluto = new google.maps.Marker({
position: new google.maps.LatLng(45.570384, -122.726872),
map: map,
title: "Pluto",
icon: "img/big-icons/pluto-icon.png"
});
var plutoString = "I was not discovered until 1930.";
var plutoInfoWindow = new google.maps.InfoWindow({
content: plutoString
});
markerPluto.addListener("click", function() {
plutoInfoWindow.open(map, markerPluto)
});
} //function myMap
//frontend
//planet navbar
$("#sun-navbar").click(function() {
$(".planets-hidden").hide();
$(".directions-hidden").hide();
$(".intro").hide();
$("#map").hide();
$("#sun-hidden, #sun-hidden-img").fadeIn(2000);
});
$("#mercury-navbar").click(function() {
$(".planets-hidden").hide();
$(".directions-hidden").hide();
$(".intro").hide();
$("#map").hide();
$("#mercury-hidden").fadeIn(2000);
$("#mercury-hidden-img").fadeIn(2000);
});
$("#venus-navbar").click(function() {
$(".planets-hidden").hide();
$(".directions-hidden").hide();
$(".intro").hide();
$("#map").hide();
$("#venus-hidden").fadeIn(2000);
$("#venus-hidden-img").fadeIn(2000);
});
$("#earth-navbar").click(function() {
$(".planets-hidden").hide();
$(".directions-hidden").hide();
$(".intro").hide();
$("#map").hide();
$("#earth-hidden").fadeIn(2000);
$("#earth-hidden-img").fadeIn(2000);
});
$("#mars-navbar").click(function() {
$(".planets-hidden").hide();
$(".directions-hidden").hide();
$(".intro").hide();
$("#map").hide();
$("#mars-hidden").fadeIn(2000);
$("#mars-hidden-img").fadeIn(2000);
});
$("#jupiter-navbar").click(function() {
$(".planets-hidden").hide();
$(".directions-hidden").hide();
$(".intro").hide();
$("#map").hide();
$("#jupiter-hidden").fadeIn(2000);
$("#jupiter-hidden-img").fadeIn(2000);
});
$("#saturn-navbar").click(function() {
$(".planets-hidden").hide();
$(".directions-hidden").hide();
$(".intro").hide();
$("#map").hide();
$("#saturn-hidden").fadeIn(2000);
$("#saturn-hidden-img").fadeIn(2000);
});
$("#uranus-navbar").click(function() {
$(".planets-hidden").hide();
$(".directions-hidden").hide();
$(".intro").hide();
$("#map").hide();
$("#uranus-hidden").fadeIn(2000);
$("#uranus-hidden-img").fadeIn(2000);
});
$("#neptune-navbar").click(function() {
$(".planets-hidden").hide();
$(".directions-hidden").hide();
$(".intro").hide();
$("#map").hide();
$("#neptune-hidden").fadeIn(2000);
$("#neptune-hidden-img").fadeIn(2000);
});
$("#pluto-navbar").click(function() {
$(".planets-hidden").hide();
$(".directions-hidden").hide();
$(".intro").hide();
$("#map").hide();
$("#pluto-hidden").fadeIn(2000);
$("#pluto-hidden-img").fadeIn(2000);
});
$("#ismene-navbar").click(function() {
$(".planets-hidden").hide();
$(".directions-hidden").hide();
$(".intro").hide();
$("#map").hide();
$("#ismene-hidden").fadeIn(2000);
$("#ismene-hidden-img").fadeIn(2000);
});
$("#map-navbar").click(function() {
$(".planets-hidden").hide();
$(".directions-hidden").hide();
$(".intro").hide();
$("#map").fadeIn(2000);
myMap();
});
//map buttons
$("#button-sun").click(function() {
$("#sun-hidden-img").hide();
$("#sun-hidden").hide();
$("#sun-directions-hidden").fadeIn(2000);
$("#map").fadeIn(2000);
myMap();
});
$("#button-mercury").click(function() {
$("#mercury-hidden-img").hide();
$("#mercury-hidden").hide();
$("#mercury-directions-hidden").fadeIn(2000);
$("#map").fadeIn(2000);
myMap();
});
$("#button-venus").click(function() {
$("#venus-hidden-img").hide();
$("#venus-hidden").hide();
$("#venus-directions-hidden").fadeIn(2000);
$("#map").fadeIn(2000);
myMap();
});
$("#button-earth").click(function() {
$("#earth-hidden-img").hide();
$("#earth-hidden").hide();
$("#earth-directions-hidden").fadeIn(2000);
$("#map").fadeIn(2000);
myMap();
});
$("#button-mars").click(function() {
$("#mars-hidden-img").hide();
$("#mars-hidden").hide();
$("#mars-directions-hidden").fadeIn(2000);
$("#map").fadeIn(2000);
myMap();
});
$("#button-jupiter").click(function() {
$("#jupiter-hidden-img").hide();
$("#jupiter-hidden").hide();
$("#jupiter-directions-hidden").fadeIn(2000);
$("#map").fadeIn(2000);
myMap();
});
$("#button-saturn").click(function() {
$("#saturn-hidden-img").hide();
$("#saturn-hidden").hide();
$("#saturn-directions-hidden").fadeIn(2000);
$("#map").fadeIn(2000);
myMap();
});
$("#button-uranus").click(function() {
$("#uranus-hidden-img").hide();
$("#uranus-hidden").hide();
$("#uranus-directions-hidden").fadeIn(2000);
$("#map").fadeIn(2000);
myMap();
});
$("#button-neptune").click(function() {
$("#neptune-hidden-img").hide();
$("#neptune-hidden").hide();
$("#neptune-directions-hidden").fadeIn(2000);
$("#map").fadeIn(2000);
myMap();
});
$("#button-pluto").click(function() {
$("#pluto-hidden-img").hide();
$("#pluto-hidden").hide();
$("#pluto-directions-hidden").fadeIn(2000);
$("#map").fadeIn(2000);
myMap();
});
$("#button-ismene").click(function() {
$("#ismene-hidden-img").hide();
$("#ismene-hidden").hide();
$("#ismene-directions-hidden").fadeIn(2000);
$("#map").fadeIn(2000);
myMap();
});
});
<file_sep>/readme.md
# _PDX Solar System Website_
#### _An informative site that helps the user explore Portland while learning about the solar system, 11.8.16_
#### By _**<NAME>, <NAME>, <NAME>, and <NAME>**_
## Description
_Back in the day, the Oregon Museum of Science and Industry built a scale model of the solar system, with planets spread across the Portland city limits. We have created a new site to document what remains of these models, along with information on the originals.
Published at _
## Specifications
* _The program should have attractive content_
* _Example in: User opens page_
* _Example out: User says "neat!"_
* _The program should be media responsive_
* _Example in: User opens website on phone_
* _Example out: Website looks good_
* _The program should have cross browser compatibility_
* _Example in: User opens website in FireFox_
* _Example out: Website looks good_
* _Navbar made up of planets_
* _Navbar planets bring up info and large picture when clicked_
* _click something to bring up full map with all planets and_
* _Maps API_
* _a marker for each planet_
* _name on hover for each planet_
* _infowindow on click for each planet_
* _orbits shown_
* _The program should have clickable icons overlaid on top of a map of portland_
* _Example in: User clicks sun icon_
* _Example out: Page displays sun image and text_
* _The program should have a hover effect that shows quick info about a planet_
* _Example in: User hovers over sun icon_
* _Example out: Page displays basic stats in a small pop-up_
## Known Bugs
_No known bugs_
## Support and contact details
_For questions and comments, contact any of the contributors through Github._
## Technologies Used
_Written with Jquery 3.1.1, bootstrap 3, and CSS3_
### License
*MIT*
Copyright (c) 2016 **_Michael Andrade, <NAME>, <NAME>, <NAME>_**
|
2fd8c6b9a556372bf18353582dfb5c261878e2e7
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
albelka/pdx-solar-system
|
2ac782e45c3c76d439720d16bd2724c9bb966510
|
558e75f2efd7725e39dab651736040869833a88d
|
refs/heads/master
|
<repo_name>stmalk/stmalk.github.io<file_sep>/README.md
<b>Here be my projects!</b>
<file_sep>/port/index.js
$(document).ready(function()
{
$(window).scroll(function() {
var y = $(this).scrollTop();
if (y > 600) {
$(".backtotopplank").show("slide", { direction: "up" }, 100);
} else {
$(".backtotopplank").hide("slide", { direction: "up" }, 100);
}
});
});
$(window).load(function(){
$('.protectiveshield').show();
//menu buttons start animations
$('#topstickpart').delay(300).show("slide", { direction: "up" }, 700);
$('#topstickpart').effect( "bounce",{distance:6}, {times:3}, 600 );
$('#bottomstickpart').delay(500).show("slide", { direction: "down" }, 700);
$('#bottomstickpart').effect( "bounce",{distance:6}, {times:3}, 600 );
$('#biobutton').delay(300).show("slide", { direction: "left" }, 700);
$('#biobutton').effect( "bounce",{distance:6}, {times:3}, 600 );
$('#contactbutton').delay(500).show("slide", { direction: "left" }, 700);
$('#contactbutton').effect( "bounce",{distance:6}, {times:3}, 600 );
$('#portfoliobutton').delay(200).show("slide", { direction: "left" }, 700);
$('#resumebutton').delay(600).show("slide", { direction: "left" }, 700);
$('#screeners').delay(20).show("slide", { direction: "up" }, 700);
$('#biowindow').hide();
$('#screeners').effect( "bounce",{distance:10}, {times:3}, 10 );
$('.mainpanel').delay(50).animate({width:"400px", height:"345px"}, function(){
$('.protectiveshield').show(function(){
$('.screencontainer').delay(10).animate({width:"400px", height:"345px"},function(){
$('#biowindow').fadeIn(function(){
$('.protectiveshield').hide();
$(this).dequeue();
});
});
});
});
$( "#biobutton").hover(
function() {
$('#topstickpart').animate({top:"-15px"}, 150);
},
function() {
$('#topstickpart').animate({top:"0px"}, 150);
}
);
$( "#contactbutton").hover(
function() {
$('#bottomstickpart').animate({bottom:"-1587px"}, 150);
},
function() {
$('#bottomstickpart').animate({bottom:"-1567px"}, 150);
}
);
//onclick functionality
$('#biobutton').click(function(){
$('.protectiveshield').show(function(){
$('.mainscreen').hide(0,function(){
$('.topscreen').clearQueue().animate({top:"-120px"},400);
$('.mainpanel').clearQueue().animate({width:"100px", height:"400px",left:"300px"}, function(){
$('.screencontainer').animate({height:"300px", width:"100px"}, 0, function(){
$('.mainpanel').animate({height:"345px", width:"400px", paddingTop:"298px"}, function(){
$('.screencontainer').delay(10).animate({height:"345px", width:"400px"}, 0, function(){
$('#biowindow').fadeIn(function(){
$('.protectiveshield').hide();
$(this).dequeue();
});
});
});
});
});
});
});
$('.dplank').hide("slide", { direction: "up" }, 200, function(){
$('.designsplank').clearQueue().hide("slide", { direction: "up" }, 100, function(){
$('.videoplank').hide("slide", { direction: "up" }, 100, function(){
$('.webplank').hide("slide", { direction: "up" }, 100);
});
});
});
});
function clearjQueryCache(){
for (var x in jQuery.cache){
delete jQuery.cache[x];
}
}
$('#resumebutton').click(function(){
$('.protectiveshield').show(function(){
$('.mainscreen').hide(0,function(){
$('.topscreen').clearQueue().animate({top:"-397px"},420);
$('.mainpanel').clearQueue().animate({width:"100px",height:"300px", left:"300px"}, function(){
$('.screencontainer').animate({height:"300px",width:"100px"}, 0, function(){
$('.mainpanel').animate({height:"820px", width:"660px", paddingTop:"20px"}, function(){
$('.screencontainer').animate({height:"820px", width:"660px"},0,function(){
$('#resumewindow').fadeIn(function(){
$('.protectiveshield').hide();
$(this).dequeue();
});
});
});
});
});
});
});
$('.dplank').hide("slide", { direction: "up" }, 200, function(){
$('.designsplank').clearQueue().hide("slide", { direction: "up" }, 100, function(){
$('.videoplank').hide("slide", { direction: "up" }, 100, function(){
$('.webplank').hide("slide", { direction: "up" }, 100);
});
});
});
});
$('#portfoliobutton').click(function(){
$('.protectiveshield').show(function(){
$('.mainscreen').hide(0,function(){
$('.topscreen').clearQueue().animate({top:"-121px"},420);
$('.mainpanel').clearQueue().animate({width:"100px",height:"400px", left:"300px"}, function(){
$('.screencontainer').animate({height:"300px", width:"100px"}, 0, function(){
$('.mainpanel').animate({height:"366px", width:"800px", paddingTop:"298px"}, function(){
$('.screencontainer').delay(10).animate({height:"366px", width:"800px"},0,function(){
$('#dworkswindow').fadeIn(function(){
$('.protectiveshield').hide();
$(this).dequeue();
});
$('.dplank').delay(30).show("slide", { direction: "up" }, 100, function(){
$('.designsplank').delay(80).show("slide", { direction: "up" }, 80, function(){
$('.videoplank').delay(40).show("slide", { direction: "up" }, 90, function(){
$('.webplank').delay(30).show("slide", { direction: "up" }, 110);
});
});
});
});
});
});
});
});
});
});
$('#contactbutton').click(function(){
$('.protectiveshield').show(function(){
$('.mainscreen').hide(0,function(){
$('.topscreen').clearQueue().animate({top:"-120px"},420);
$('.mainpanel').clearQueue().animate({width:"100px",height:"400px", left:"300px"}, function(){
$('.screencontainer').animate({height:"300px",width:"100px"}, 0, function(){
$('.mainpanel').animate({height:"209px", width:"360px", paddingTop:"298px"}, function(){
$('.screencontainer').delay(10).animate({height:"209px", width:"360px"},0,function(){
$('#contactwindow').fadeIn(function(){
$('.protectiveshield').hide();
$(this).dequeue();
});
});
});
});
});
});
});
$('.dplank').hide("slide", { direction: "up" }, 200, function(){
$('.designsplank').clearQueue().hide("slide", { direction: "up" }, 100, function(){
$('.videoplank').hide("slide", { direction: "up" }, 100, function(){
$('.webplank').hide("slide", { direction: "up" }, 100);
});
});
});
});
$('#dbutton').click(function(){
$('.protectiveshield').show(function(){
$('.mainscreen').hide(0,function(){
$('.topscreen').clearQueue().animate({top:"-120px"},400);
$('.mainpanel').clearQueue().animate({width:"100px",height:"400px", left:"300px"}, function(){
$('.screencontainer').animate({height:"300px", width:"100px"}, 0, function(){
$('.mainpanel').animate({height:"369px", width:"800px", paddingTop:"298px"}, function(){
$('.screencontainer').delay(10).animate({height:"369px", width:"800px"},0,function(){
$('#dworkswindow').fadeIn(function(){
$('.protectiveshield').hide();
$(this).dequeue();
});
});
});
});
});
});
});
});
$('.logoclass').click(function(){
$('.protectiveshield').show(function(){
$('.mainscreen').hide(0,function(){
$('.topscreen').clearQueue().animate({top:"-121px"},400);
$('.mainpanel').clearQueue().animate({width:"100px",height:"400px", left:"300px"}, function(){
$('.screencontainer').animate({height:"300px", width:"100px"}, 0, function(){
$('.mainpanel').animate({height:"366px", width:"800px", paddingTop:"298px"}, function(){
$('.screencontainer').delay(10).animate({height:"366px", width:"800px"},0,function(){
$('#dworkswindow').fadeIn(function(){
$('.protectiveshield').hide();
$(this).dequeue();
});
$('.dplank').delay(30).show("slide", { direction: "up" }, 100, function(){
$('.designsplank').delay(80).show("slide", { direction: "up" }, 80, function(){
$('.videoplank').delay(40).show("slide", { direction: "up" }, 90, function(){
$('.webplank').delay(30).show("slide", { direction: "up" }, 110);
});
});
});
});
});
});
});
});
});
});
$('#videobutton').click(function(){
$('.protectiveshield').show(function(){
$('.mainscreen').hide(0,function(){
$('.topscreen').clearQueue().animate({top:"-120px"},400);
$('.mainpanel').clearQueue().animate({width:"100px",height:"400px", left:"300px"}, function(){
$('.screencontainer').animate({height:"300px", width:"100px"}, 0, function(){
$('.mainpanel').animate({height:"198px", width:"400px", paddingTop:"298px"}, function(){
$('.screencontainer').delay(10).animate({height:"198px", width:"400px"},0,function(){
$('#videowindow').fadeIn(function(){
$('.protectiveshield').hide();
$(this).dequeue();
});
});
});
});
});
});
});
});
$('#webbutton').click(function(){
$('.protectiveshield').show(function(){
$('.mainscreen').hide(0,function(){
$('.topscreen').stop(true,true).animate({top:"-120px"},120);
$('.mainpanel').clearQueue().animate({width:"100px",height:"400px",left:"300px"}, function(){
$('.screencontainer').animate({height:"300px", width:"100px"}, 0, function(){
$('.mainpanel').animate({height:"369px", width:"800px", paddingTop:"298px"}, function(){
$('.screencontainer').delay(10).animate({height:"369px", width:"800px"},0,function(){
$('#webwindow').fadeIn(function(){
$('.protectiveshield').hide();
$(this).dequeue();
});
});
});
});
});
});
});
});
$('#designsbutton').click(function(){
$('.protectiveshield').show(function(){
$('.mainscreen').hide(0,function(){
$('.topscreen').clearQueue().animate({top:"-120px"},400);
$('.mainpanel').clearQueue().animate({width:"100px",height:"400px", left:"300px"}, function(){
$('.screencontainer').animate({height:"300px", width:"100px"}, 0, function(){
$('.mainpanel').animate({height:"369px", width:"800px", paddingTop:"298px"}, function(){
$('.screencontainer').delay(10).animate({height:"369px", width:"800px"},0,function(){
$('#designswindow').fadeIn(function(){
$('.protectiveshield').hide();
$(this).dequeue();
});
});
});
});
});
});
});
});
var count = 0;
$('body').click(function() {
count++;
$("#counter").html(+count);
});
});
//menu buttons start animations
//onclick functionality
<file_sep>/ajax/loadingpages/mirmidon.js
$(document).ready(function(){
$('#centralbutton > a').click(function(e){
e.preventDefault();
var page = e.target.id + ".html";
$( "div" ).promise().done(function(){
$('.insides').hide('slide', {direction: 'left'}, 600, function(){
$(this).load(page, function(){
$(this).clearQueue().show('slide', {direction: 'right'}, 600);
});
});
});
});
});
<file_sep>/slideshow/index.js
var slideshow = {
directory: "images/",
photos:[
{ "photor": "aurelius.jpg", "captionr" : "<NAME>"},
{ "photor": "cesar.png", "captionr" : "<NAME>"},
{ "photor": "couple.jpg", "captionr" : "Greek Couple"},
{ "photor": "flavian.jpg", "captionr" : "Flavian Woman"},
{ "photor": "lucius.jpg", "captionr" : "<NAME>"},
{ "photor": "lupe.jpg", "captionr" : "<NAME>"},
{ "photor": "sabina.jpg", "captionr" : "Sabina"}
],
currentPhoto: 0,
getPrevious: function(){
if (this.currentPhoto == 0)
this.currentPhoto = this.photos.length-1;
else
this.currentPhoto--;
var photo = this.directory + this.photos[this.currentPhoto].photor;
var caption = this.photos[this.currentPhoto].captionr;
return { "photo": photo, "caption": caption };
},
getNext: function(){
if (this.currentPhoto == this.photos.length-1)
this.currentPhoto = 0;
else
this.currentPhoto++;
var photo = this.directory + this.photos[this.currentPhoto].photor;
var caption = this.photos[this.currentPhoto].captionr;
return { "photo": photo, "caption": caption };
}
};
function next(){
var image = slideshow.getNext();
document.getElementById("currentPhoto").src = image.photo;
document.getElementById("currentCaption").innerHTML = image.caption;
}
function previous(){
var image = slideshow.getPrevious();
document.getElementById("currentPhoto").src = image.photo;
document.getElementById("currentCaption").innerHTML = image.caption;
}
|
03a680e274d9d4c6f70f56defbd720c413e84092
|
[
"Markdown",
"JavaScript"
] | 4
|
Markdown
|
stmalk/stmalk.github.io
|
476015e96aaecf61d93fa651428a66a26ee68e1a
|
0c1193c1b54acd08c6cdc7079c515ab6b056ceab
|
refs/heads/master
|
<file_sep><!DOCTYPE html>
<html>
<head>
<title>Job Board</title>
<!-- RESPONSIVE TAG -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap CSS -->
<link rel="stylesheet" type="text/css" href="./lib/bootstrap/css/bootstrap.min.css">
<style>
.panel-body{
padding: 5px;
}
.h2{
margin-top: 0;
margin-bottom: 10px;
color: #1c3f94;
}
p {
font-family: "Times New Roman", Times, serif;
}
</style>
</head>
<body>
<!-- Start HTML Here -->
<div id="main">
<section class="site-section">
<div class="container">
<div class="row mb-5 justify-content-center">
<div class="col-md-7 text-center">
<h2 class="section-title mb-2">Job Listed</h2>
</div>
</div>
<?php
require_once("db.php");
$query = "SELECT * FROM jobs";
$result = mysqli_query($db,$query);
while($row = mysqli_fetch_assoc($result)){
echo "<div class='mb-5'>
<div class='row align-items-start job-item border-bottom pb-3 mb-3 pt-3'>
<div class='col-md-2'>
<a href='job-single.html'></a>
</div>
<div class='col-md-4'>
<h2><a href='job-single.html'>".$row["title"]."</a> </h2>
<strong>".$row["company_name"]."</strong>
</div>
<div class='col-md-3 text-left'>
<span class='meta'>".$row["location"]."</span>
</div>
<div class='col-md-3 text-md-right'>
<button type='btn btn-info'><a href='details.php?id=".$row["id"]."'>See More Details</button></a>
</div>
</div>";
}
?>
<div class="row pagination-wrap">
<div class="col-md-6 text-center text-md-left">
<div class="custom-pagination ml-auto">
<a href="#" class="prev">Previous</a>
<div class="d-inline-block">
<a href="#" class="active">1</a>
<a href="#">2</a>
<a href="#">3</a>
<a href="#">4</a>
</div>
<a href="#" class="next">Next</a>
</div>
</div>
</div>
</div>
</section>
</div>
<!-- END HTML Here -->
<!-- Jquery Plugin -->
<script type="text/javascript" src="./lib/jquery/jquery.min.js"></script>
<!-- Bootstrap Plugin -->
<script type="text/javascript" src="./lib/bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
|
cef421551e6d70219f9807e0ae4eb58f6f115175
|
[
"PHP"
] | 1
|
PHP
|
dextersigue/job-board-ksa
|
836c1ac515b941cf4918a5251f1cd1e662c7343f
|
b309f883078f9ed49b763bf872e797141bdbd7fa
|
refs/heads/master
|
<repo_name>tiancaohz/caffe-tensorflow<file_sep>/inference_tf.py
import tensorflow as tf
import cv2
import numpy as np
def load_graph(frozen_graph_filename):
# We load the protobuf file from the disk and parse it to retrieve the
# unserialized graph_def
with tf.gfile.GFile(frozen_graph_filename, "rb") as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
# Then, we can use again a convenient built-in function to import a graph_def into the
# current default Graph
with tf.Graph().as_default() as graph:
tf.import_graph_def(
graph_def,
input_map=None,
return_elements=None,
name="prefix",
op_dict=None,
producer_op_list=None
)
return graph
if __name__ == '__main__':
graph = load_graph('./standalonehybrid.pb')
x = graph.get_tensor_by_name('prefix/data:0')
y = graph.get_tensor_by_name('prefix/prob:0')
im = cv2.imread('/Users/tiancao/data/caffe_model/places365_vgg/12.jpg')
WIDTH, HEIGHT = 224, 224
im = cv2.resize(im, (WIDTH, HEIGHT))
# Places was using batches of 10 images
batch = np.array([im for i in range(10)])
with tf.Session(graph=graph) as sess:
y_out = sess.run(y, feed_dict={x: batch})
print(y_out.argmax(axis=1))
|
efe912a95995db4f7b4ce92576d69cdfc2e8ec95
|
[
"Python"
] | 1
|
Python
|
tiancaohz/caffe-tensorflow
|
f29800952c148635c2e1c7c739293c809bb882b1
|
fd15ef6e55f04ac04ed4cbf69f4a1cf4a66bf56a
|
refs/heads/master
|
<repo_name>prostornet/Other_Scripts<file_sep>/README.md
# Other_Scripts
sub_pars.sh - parsing subscription csv files
team.sh - creating teaming or bonding from two device (Bonding only with LACP, ActiveBackup build as teaming)
<file_sep>/team.sh
#!/bin/bash
FDEVTMP=$(mktemp)
FDEVTEAM=/etc/sysconfig/network-scripts/ifcfg-team0
FDEVBOND=/etc/sysconfig/network-scripts/ifcfg-bond0
ip a | grep -B 1 'link/ether' | grep -e '^[1-9]' | awk -F':' '{print $2}' >> ${FDEVTMP}
cr_tm_ports() {
count=1
while read line; do
nmcli con add type team-slave con-name port${count} ifname ${line} master team0
nmcli con del ${line} > /dev/null 2>&1
count=$(( count+=1 ))
done < ${FDEVTMP}
}
cr_bd_ports() {
count=1
while read line; do
nmcli con add type bond-slave con-name port${count} ifname ${line} master bond0
nmcli con del ${line} > /dev/null 2>&1
count=$(( count+=1 ))
done < ${FDEVTMP}
}
read -p "Select Bonding(B) or Teaming(T): " TYP
read -p "Select mode Active-Backup(AB) or LACP(LA): " MOD
read -p "Set ip addres with mask prefix: " IPADDR
read -p "Set gw addres: " GWADDR
if [ -e ${FDEVTEAM} ]; then exit 0; fi
if [ -e ${FDEVBOND} ]; then exit 0; fi
if [ ${TYP} = "B" ]; then
if [ ${MOD} = "AB" ]; then
echo "Bonding in Active-Backup mode is deprecated, we are going to build Team Active-Backup"
nmcli con add type team con-name team0 ifname team0 ip4 ${IPADDR} gw4 ${GWADDR} ipv4.dns 'dns_addr1 dns_addr2 dns_addr3' ipv4.method manual ipv6.method ignore
echo "TEAM_CONFIG='{\"runner\":{\"name\":\"activebackup\"},\"link_watch\":{\"name\":\"ethtool\"}}'" >> ${FDEVTEAM}
cr_tm_ports
elif [ ${MOD} = "LA" ]; then
nmcli con add type bond con-name bond0 ifname bond0 ip4 ${IPADDR} gw4 ${GWADDR} ipv4.dns 'dns_addr1 dns_addr2 dns_addr3' ipv4.method manual ipv6.method ignore
sed -i '/BONDING_OPTS/d' ${FDEVBOND}
echo "BONDING_OPTS=\"miimon=100 mode=802.3ad lacp_rate=1\"" >> ${FDEVBOND}
cr_bd_ports
else
echo "It seems you do not understand what you are going to do. Think about it"
exit 0
fi
elif [ ${TYP} = "T" ]; then
if [ ${MOD} = "AB" ]; then
nmcli con add type team con-name team0 ifname team0 ip4 ${IPADDR} gw4 ${GWADDR} ipv4.dns 'dns_addr1 dns_addr2 dns_addr3' ipv4.method manual ipv6.method ignore
echo "TEAM_CONFIG='{\"runner\":{\"name\":\"activebackup\"},\"link_watch\":{\"name\":\"ethtool\"}}'" >> ${FDEVTEAM}
cr_tm_ports
elif [ ${MOD} = "LA" ]; then
nmcli con add type team con-name team0 ifname team0 ip4 ${IPADDR} gw4 ${GWADDR} ipv4.dns 'dns_addr1 dns_addr2 dns_addr3' ipv4.method manual ipv6.method ignore
echo "TEAM_CONFIG='{\"runner\":{\"name\":\"lacp\",\"active\":true,\"fast_rate\":true,\"tx_hash\":[\"eth\",\"ipv4\",\"ipv6\"]},\"link_watch\":{\"name\":\"ethtool\"},\"ports\":{\"port1\":{},\"port2\":{}}}'" >> ${FDEVTEAM}
cr_tm_ports
else
echo "It seems you do not understand what you are going to do. Think about it"
exit 0
fi
else
echo "It seems you do not understand what you are going to do. Think about it"
exit 0
fi
rm -f ${FDEVTMP}
systemctl restart network
exit 0
<file_sep>/sub_pars.sh
#!/bin/bash
# Base varibles
D_BASE=/srv/www/subs/report_`date +%Y%m%d`
F_VC=vc_report.csv
F_SUB=sub_report.csv
F_2SUB=01_doublesub.csv
F_1SUB=02_onesub.csv
F_NOSUB=03_nosub.csv
F_OKSUB=04_oksub.csv
F_ERRH=05_errhdd.csv
F_ERRR=05_errram.csv
F_ERRC=05_errcpu.csv
F_ERR=00_err.csv
TMPFILE1=$(mktemp)
USAGE="\n\nUsage: $(basename "$0") <vc_report_[date].csv> <sub_report_[date].csv>\n\n\t- you should specify two files which we are going to parse as parametr\n\n"
if [ ! $# == 2 ]; then
echo -e ${USAGE}
exit 1
fi
for F in ${F_VC} ${F_SUB} ${F_2SUB} ${F_1SUB} ${F_NOSUB} ${F_OKSUB} ${F_ERRH} ${F_ERRR} ${F_ERRC} ${F_ERR}; do
:>${F}
done
#Fix export files
for i in $1 $2; do
dos2unix ${i}
sed -i '1,2d;s/"//g;s/,/;/g;s/.*/\L&/g' ${i}
done
mv -f $1 $(echo $1|sed -E 's/(^.([a-z]+)_([a-z]+))_([0-9]+)/\1/')
mv -f $2 $(echo $2|sed -E 's/(^.([a-z]+)_([a-z]+))_([0-9]+)/\1/')
#First step, checking file for double subscription
for srv in $(cut -d";" -f1 ${F_SUB} | uniq -d); do
grep "^${srv}" ${F_SUB} >> ${F_2SUB}
echo "" >> ${F_2SUB}
done
#Second step, single subscriptions
sort -t';' -k1,1 -u ${F_SUB} >> ${F_1SUB}
#Third step,
cut -d';' -f1 ${F_VC}| sort | grep -P -v '(^hcptwr-([0-9]+)|^cldtst([a-z0-9]+)|guest\ introspection)' >> ${TMPFILE1}
while read line; do
result_sub=`grep -E "^${line}" ${F_SUB}`
result_vc=`grep -E "^${line}" ${F_VC}`
if [[ -z ${result_sub} ]]; then
echo ${line}";No subscription" >> ${F_NOSUB}
else
vc_c=`echo ${result_vc}|awk -F';' '{print $2}'`
vc_r=`echo ${result_vc}|awk -F';' '{print $3}'`
vc_h=`echo ${result_vc}|awk -F';' '{print int($4)}'`
sub_c=`echo ${result_sub}|awk -F';' '{print $2}'`
sub_r=`echo ${result_sub}|awk -F';' '{print int($3/1024)}'`
sub_h=`echo ${result_sub}|awk -F';' '{print $4}'`
if [[ "${vc_c}" -eq "${sub_c}" && "${vc_r}" -eq "${sub_r}" && "${vc_h}" -eq "${sub_h}" ]]; then
echo "Server ${line};we have equal subscription" >> ${F_OKSUB}
elif [[ "${vc_c}" -eq "${sub_c}" && "${vc_r}" -eq "${sub_r}" ]]; then
echo "Server ${line};HDD_VC=${vc_h};HDD_SUB=${sub_h};NOT EQUAL" >> ${F_ERRH}
elif [[ "${vc_c}" -eq "${sub_c}" && "${vc_h}" -eq "${sub_h}" ]]; then
echo "Server ${line};RAM_VC=${vc_r};RAM_SUB=${sub_r};NOT EQUAL" >> ${F_ERRR}
elif [[ "${vc_r}" -eq "${sub_r}" && "${vc_h}" -eq "${sub_h}" ]]; then
echo "Server ${line};CPU_VC=${vc_c};CPU_SUB=${sub_c};NOT EQUAL" >> ${F_ERRC}
elif [[ "${vc_c}" -ne "${sub_c}" && "${vc_r}" -ne "${sub_r}" ]]; then
echo "Server ${line};CPU_VC=${vc_c};CPU_SUB=${sub_c};RAM_VC=${vc_r};RAM_SUB=${sub_r}" >> ${F_ERR}
elif [[ "${vc_c}" -ne "${sub_c}" && "${vc_h}" -ne "${sub_h}" ]]; then
echo "Server ${line};CPU_VC=${vc_c};CPU_SUB=${sub_c};HDD_VC=${vc_h};HDD_SUB=${sub_h}" >> ${F_ERR}
elif [[ "${vc_c}" -ne "${sub_c}" && "${vc_r}" -ne "${sub_r}" ]]; then
echo "Server ${line};CPU_VC=${vc_c};CPU_SUB=${sub_c};RAM_VC=${vc_r};RAM_SUB=${sub_r}" >> ${F_ERR}
elif [[ "${vc_h}" -ne "${sub_h}" && "${vc_r}" -ne "${sub_r}" ]]; then
echo "Server ${line};HDD_VC=${vc_h};HDD_SUB=${sub_h};RAM_VC=${vc_r};RAM_SUB=${sub_r}" >> ${F_ERR}
else
echo "Server ${line};ZHOPA"
fi
fi
done <${TMPFILE1}
#Finishing our scripts
rm -f ${TMPFILE1}
if [[ ! -d ${D_BASE} ]]; then
mkdir -p ${D_BASE}
fi
for F in ${F_2SUB} ${F_1SUB} ${F_NOSUB} ${F_OKSUB} ${F_ERRH} ${F_ERRR} ${F_ERRC} ${F_ERR}; do
cp -f ${F} ${D_BASE}/
done
exit 0
|
a44be99fc3fe0644cd020ac1d4eaa9a2e7e9dfd2
|
[
"Markdown",
"Shell"
] | 3
|
Markdown
|
prostornet/Other_Scripts
|
cd5df60a664c4d9dd333afdd29c92d0a1cd025e8
|
8a0fbebec84c8cd06db0bd3a098f999a9958f2d3
|
refs/heads/master
|
<repo_name>aditi592/village-temple-min-cost<file_sep>/src/module-info.java
module VillageTempleMinimumCost {
}
|
9f4e0fb9976f0d1cb0d1556e8ec9cd59c61baaa9
|
[
"Java"
] | 1
|
Java
|
aditi592/village-temple-min-cost
|
821593ff32d8a43641f879cb4ae3d8659c76b4bf
|
b3ba331ce30f870de58422846ab17f4119e17297
|
refs/heads/master
|
<file_sep># Simple CNN model for CIFAR-10
import numpy
import matplotlib.pyplot as plt
from time import time
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.constraints import maxnorm
from keras.optimizers import SGD
from keras.layers.convolutional import Convolution2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils
from sklearn.metrics import confusion_matrix
import imageDataExtract as dataset
# For recording
import cv2
from PIL import Image
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
while True:
print 'Press [p] for path or [v] for video'
mode = raw_input()
if mode == 'p' or mode == 'v':
break
# load data
imgPath = 'images/sad/anthony_0_9.png'
num_classes = 3
output = ['Sad','Happy','Angry']
img = dataset.pathToVector(imgPath)
# normalize inputs from 0-255 to 0.0-1.0
img = img.astype('float32')
print img.shape
img = img / 255.0
# Create the model
model = Sequential()
model.add(Convolution2D(32, 3, 3, input_shape=(1, 32, 32), border_mode='same', activation='relu', W_constraint=maxnorm(3)))
model.add(Dropout(0.2))
model.add(Convolution2D(32, 3, 3, activation='relu', border_mode='same', W_constraint=maxnorm(3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(512, activation='relu', W_constraint=maxnorm(3)))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
model.load_weights("models/model-0.h5")
#model.load_weights("checkpoint/weights-improvement-75-0.1966-bigger.hdf5")
# Compile model
epochs = 25
lrate = 0.01
decay = lrate/epochs
sgd = SGD(lr=lrate, momentum=0.9, decay=decay, nesterov=False)
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
# Final evaluation of the model
pred = model.predict_classes(img, 1, verbose=0)
#print output[pred[0]]
#print ''
#print ''
#print ''
if mode == 'p':
while True:
print 'Type in another path to make a prediction:'
path = raw_input()
img = dataset.pathToVector(path)
# normalize inputs from 0-255 to 0.0-1.0
img = img.astype('float32')
# Final evaluation of the model
pred = model.predict_classes(img, 1, verbose=0)
print output[pred[0]]
print ''
print ''
print ''
elif mode == 'v':
tar_height = 32
tar_width = 32
face_classifier = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
i = 0
while True:
print 'Press enter to start recording: '
temp = raw_input()
while True:
ret, old_frame = cap.read()
'''
cv2.imshow('Video', old_frame)
if cv2.waitKey(1) & 0xFF==ord('q'):
break
'''
old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)
face = face_classifier.detectMultiScale(old_frame, 1.2, 4)
if len(face) == 0:
continue
else:
print 'Detected'
for (x,y,w,h) in face:
#focused_face = old_frame[y: y+h, x: x+w]
img = old_gray[y: y+h, x: x+w]
#cv2.rectangle(old_frame, (x,y), (x+w, y+h), (0,255,0),2)
pil_im = Image.fromarray(img)
img2 = pil_im.resize((32, 32), Image.ANTIALIAS)
img2.save('1.png')
cvimg = numpy.array(img2.convert('RGB'))
img = cv2.cvtColor(cvimg[:, :, ::-1].copy(), cv2.COLOR_BGR2GRAY)
print img.shape
img = numpy.array([numpy.array([img])])
# normalize inputs from 0-255 to 0.0-1.0
img = img.astype('float32')
# Final evaluation of the model
json = open("./test.json", "w")
pred = model.predict_classes(img, 1, verbose=0)
print i, ' ', output[pred[0]]
print ''
print ''
print ''
strTemp = '{\n "classification": "' + output[pred[0]] + '"\n}\n'
json.write(strTemp)
json.close()
i = i + 1
<file_sep># machine-learning-experiments
Experimenting with machine learning
|
ee46a846263ef30f5266cf81aaee1b9eb19c8d34
|
[
"Markdown",
"Python"
] | 2
|
Python
|
vanstorm9/machine-learning-experiments
|
a7b4477d13efa8a4be048feff1cf43634b59a055
|
4a3f2d89fd4910d271b6caf8603b61f46bd707dd
|
refs/heads/main
|
<file_sep>p = 2.70610
a = [1.00, 0.95, 0.90, 0.85, 0.80]
b = [round((i**(1/3))*p, 5) for i in a]
print(b)
for i in range(5):
InputFile = open("input.in", "rt")
GenFile = open("input-%d.in" % i, "wt")
for line in InputFile:
c = line.replace(str(p), str(b[i]))
GenFile.write(c)
InputFile.close()
GenFile.close()
<file_sep>import numpy as n
import matplotlib.pyplot as p
from scaled import a
from scipy.optimize import curve_fit
energy = []
for i in range(5):
F = open("output-%d.out" % i, "rt")
for line in F:
a1 = " ".join(line.split())
if a1.find("! total energy") != -1:
a2 = a1.replace("! total energy =", "")
a3 = a2.replace("Ry", "")
energy.append(float(a3))
F.close()
print(energy)
V = n.array([n.sqrt(8)*i**3 for i in a])
E = n.array(energy)
p.plot(V, E, "--Db")
p.xlabel("Volume ($a_0^3$)")
p.ylabel("E (Ry)")
p.grid("on")
p.show()
<file_sep>A full geometry optimization of letharge performed on QE using a PBE XC functional.
<file_sep># How to create your own CIF files
***This tutorial is largely based on <NAME>'s course: [Computational Materials Physics](https://compmatphys.epotentia.com/), and can be treated as my personal lecture notes of the course.***
- Use the following template making the necessary adjustments:
```
#===============================================================================
# General-purpose P1 CIF
#===============================================================================
data_global
_chemical_name '<NAME>'
_cell_length_a 3.99
_cell_length_b 3.99
_cell_length_c 5.01
_cell_angle_alpha 90.
_cell_angle_beta 90.
_cell_angle_gamma 90.
_symmetry_space_group_name_H-M 'P 1'
_symmetry_Int_Tables_number 1
loop_
_atom_site_label
_atom_site_type_symbol
_atom_site_symmetry_multiplicity
_atom_site_Wyckoff_symbol
_atom_site_fract_x
_atom_site_fract_y
_atom_site_fract_z
O1 O 1 a 0.0 0.0 0.0
O2 O 1 a 0.5 0.5 0.5
Pb1 Pb 1 a 0.5 0.0 0.77
Pb2 Pb 1 a 0.0 0.5 0.23
```
- The problem with this file is that it does not include the symmetery information of the crystal, which is necessary for your DFT calculation. The crystal is defined using the P1 space group, which is the space group of least symmetry.
- To overcome this problem you need to use the [FINDSYM](https://stokes.byu.edu/iso/findsym.php) tool. In principle, it takes a P1 CIF file and return a CIF file with the "highest symmetry" of the crystal. However, FINDSYM is quite picky when it comes to CIF files. If you upload this template, it returns an error. To circumvent this difficulty, upload the template to the [Bilbao Crystallographic Server](https://www.cryst.ehu.es/).
- From the Bilbao Crystallographic Server home page, choose `Structure Utilities`, and then choose `VISUALIZE`.
- Upload your template, and click `Show`. The crystal will be viewed using `Jmol`.
- Scroll down and download the CIF file. It will look like this:
```
data_generated_by_bilbao_crystallographic_server
_cell_length_a 3.99
_cell_length_b 3.99
_cell_length_c 5.01
_cell_angle_alpha 90.
_cell_angle_beta 90.
_cell_angle_gamma 90.
_symmetry_space_group_name_H-M 'P1'
_symmetry_Int_Tables_number 1
loop_
_symmetry_equiv_pos_site_id
_symmetry_equiv_pos_as_xyz
1 'x,y,z'
loop_
_atom_site_label
_atom_site_type_symbol
_atom_site_symmetry_multiplicity
_atom_site_Wyckoff_symbol
_atom_site_fract_x
_atom_site_fract_y
_atom_site_fract_z
O1 O ? 1a 0.00000 0.00000 0.00000
O2 O ? 1a 0.50000 0.50000 0.50000
Pb1 Pb ? 1a 0.50000 0.00000 0.77000
Pb2 Pb ? 1a 0.00000 0.50000 0.23000
```
A bit different than your previous file, but readable by `FINDSYM`.
- Go back to [FINDSYM](https://stokes.byu.edu/iso/findsym.php), upload the new CIF file, scroll down and clik `OK` to submit data.
- The new CIF file will show up. Scroll down and download it. Change the file's extension from `.txt` to `.cif`. It looks like this:
```
# CIF file created by FINDSYM, version 7.1
data_findsym-output
_audit_creation_method FINDSYM
_cell_length_a 3.9900000000
_cell_length_b 3.9900000000
_cell_length_c 5.0100000000
_cell_angle_alpha 90.0000000000
_cell_angle_beta 90.0000000000
_cell_angle_gamma 90.0000000000
_cell_volume 79.7597010000
_symmetry_space_group_name_H-M "P -4 m 2"
_symmetry_Int_Tables_number 115
_space_group.reference_setting '115:P -4 -2'
_space_group.transform_Pp_abc a,b,c;0,0,0
loop_
_space_group_symop_id
_space_group_symop_operation_xyz
1 x,y,z
2 -x,-y,z
3 -y,-x,-z
4 y,x,-z
5 -x,y,z
6 x,-y,z
7 y,-x,-z
8 -y,x,-z
loop_
_atom_site_label
_atom_site_type_symbol
_atom_site_symmetry_multiplicity
_atom_site_Wyckoff_label
_atom_site_fract_x
_atom_site_fract_y
_atom_site_fract_z
_atom_site_occupancy
_atom_site_fract_symmform
O1 O 1 a 0.00000 0.00000 0.00000 1.00000 0,0,0
O2 O 1 c 0.50000 0.50000 0.50000 1.00000 0,0,0
Pb1 Pb 2 g 0.00000 0.50000 0.23000 1.00000 0,0,Dz
# end of cif
```
Notice that the space group has changed to `P -4 m 2`.
# Using the CIF file with CIF2Cell
- If you used this last CIF file with `cif2cell`:
```
$ cif2cell TiPt1.cif -p quantum-espresso -o TiPt.in
```
it will return an error:
```
Traceback (most recent call last):
File "/usr/local/bin/cif2cell", line 1574, in <module>
docstring = StandardDocstring()
File "/usr/local/bin/cif2cell", line 1021, in StandardDocstring
tmpstring2 += ". Reference number : "+ref.databasecode
TypeError: must be str, not NoneType
```
- To tackle this last problem, change the following lines in the CIF file:
```
data_findsym-output
_audit_creation_method FINDSYM
```
to:
```
data_findsym-output
_audit_creation_method FINDSYM
_cod_database_code None
```
- Also, change the following lines:
```
_symmetry_space_group_name_H-M "P -4 m 2"
_symmetry_Int_Tables_number 115
_space_group.reference_setting '115:P -4 -2'
_space_group.transform_Pp_abc a,b,c;0,0,0
```
to:
```
_space_group_name_Hall '-P 2a 2a'
_symmetry_Int_Tables_number 51
```
- Notice that it is `_space_group_name_Hall` not `_symmetry_space_group_name_Hall`. The latter is supended in recent CIF file formats and shouldn't be used.
- To be able to change the last four lines related to the space group, you need to know the name of the space group `P -4 m 2` in the Hall notation.
- Go to [http://cci.lbl.gov/sginfo/hall_symbols.html](http://cci.lbl.gov/sginfo/hall_symbols.html).
- Search the space group by its number in the **Internation Tables for Crystallography, Vol. A**, which is 51 in our case.
- Scroll down to find the following:
```
51 P m m a -P 2a 2a
51:ba-c P m m b -P 2b 2
51:cab P b m m -P 2 2b
51:-cba P c m m -P 2c 2c
51:bca P m c m -P 2c 2
51:a-cb P m a m -P 2 2a
```
- There are 6 possibilities to the 51st space group. To know which one to choose, look at the line: `_space_group.transform_Pp_abc a,b,c;0,0,0`.
- The letter combiniation is `a,b,c` which is not present in the 6 possibilities because it is the default choice. That is, `51` is equivalent to `51:abc`.
- Thus, the correct space group to choose is `-P 2a 2a`. Yo may use either single or double quotes in the CIF file.
Congratulations, you have created a *working* CIF file without knowing much about crystallography.
<file_sep># DFT
This is where I upload some basic DFT calculations I performed using `Quantum Espresso` and `exciting`. Nothing fancy.
This repository is licensed under The Unlicense; a license with no conditions whatsoever which dedicates all code here to the public domain.
<file_sep>A simple energy convergence test performed for an Ag FCC crystal using the `exciting` code. Being lazy to upload all 45 calculations, only the first converging calculation is included, i.e., `ngridk_06-rgkmax_08`.

<file_sep>#!/bin/bash
touch record.txt
for i in {1..15}
do
pw.x -input input-$i.in > output-$i.out
echo $i | python3 conv-test.py
done
<file_sep>Calculation of the total energy of a silicon crystal performed by Quantum Espresso.
<file_sep>#!/bin/bash
python3 scaled.py
for i in {0..4}
do
pw.x -input input-$i.in > output-$i.out
done
python energy.py
<file_sep>Calculation of the total energy of a diamond crystal using the `exciting` code.
<file_sep>This is an automated convergence test for QE that is written in both Bash and Python.
It is a bit messy but gets the job done.
To use it run `conv-test.sh`.
<file_sep>An automated volume optimization DFT calculation using QE.
A Bash/Python code is written to:
- Generate QE input files with different cell volumes,
- Run them,
- Extract the total energy from the output files, and
- Plot total energy as a function of volume to get the optimum lattice parameter.
Just run `loop.sh` to get the whole thing done.
<file_sep># How to use XCrySDen to visualize exciting input files
`exciting` is a DFT code that is based on the LAPW method, and is only available for Linux platforms.
Read [<NAME>'s excellent lecture notes](http://www.attaccalite.com/wp-content/uploads/2017/04/pdf_DFT4beginners.pdf) on DFT if you are into functional calculus, or read <NAME>'s [Computational Materials Science: An Introduction](https://www.routledge.com/Computational-Materials-Science-An-Introduction-Second-Edition/Lee/p/book/9781498749732) if you want a gentle, though comprehensive, introduction.
Download `exciting nitrogen 14` [here](http://exciting-code.org/nitrogen-14).
Follow the installation instructions found [here](http://exciting-code.org/nitrogen-download-and-compile-exciting).
Follow [these instructions](http://exciting-code.org/nitrogen-tutorial-scripts-and-environment-variables) to add `exciting` to your [`PATH` environment variables](https://en.wikipedia.org/wiki/Environment_variable).
`exciting` uses Python 2.7, and runs on Linux which uses Python 3.x as the official version, while using Python 2.7 for some tasks. While Linux knows which version should be assigned some task, third-party programs, e.g., `exciting` don't, and this often leads to errors like `SyntaxError` and `ImportError`. A common `ImportError` is faced with the `lxml` package which can be installed for Python 3 but not for Python 2.
In my experience, the best solution is to define a [`conda` Python 2 environment](https://docs.anaconda.com/anaconda/user-guide/tasks/switch-environment/), do all your `exciting` calculations there, and then deactivate it when you are done. In principle, this can also be done using [Python virtual environments](https://docs.python.org/3/tutorial/venv.html), but this is far more complex and I don't recommend it.
It is assumed that you already have Anaconda installed on your machine. Here is how to [download](https://www.anaconda.com/products/individual) and [install](https://docs.anaconda.com/anaconda/install/) Anaconda if you don't have it.
Enough prerequisites, and now to the main topic of this tutorial: Using [XCrySDen](http://www.xcrysden.org/XCrySDen.html) to visualize `exciting` input files.
[Steps found in the documentation](http://exciting-code.org/xcrysdenexcitingsetup) won't work for you because they are incomptable with the current (and any future) version of XCrySDen, so follow the steps in this tutorial instead. The dollar sign, `$`, only clarifies things you should write in the terminal. Don't paste it.
* Install XCrySDen:
```
$ sudo apt install xcrysden
```
* Go to your home directory:
```
$ cd
```
* Create the hidden folder `.xcrysden` and move inside it:
```
$ mkdir .xcrysden
```
In Linux, the dot before a folder or file's name indicates that it is hidden.
* Use your preferred text editor to create and open the file `custom-definitions`:
```
$ xed .xcrysden/custom-definitions
```
I used `xed`, but `nano` or `gedit` or any text editor would do.
* Paste the following lines of code into `custom-definitions`:
```
addOption --exciting $env(EXCITINGTOOLS)/ex2xsf {
load structure from exciting input.xml format
}
```
`EXCITINGTOOLS` is one of the `PATH` environment variables you defined, and `ex2xsf` is a program that transforms `XML` files to `XSF` files readable by XCrySDen.
* You are now ready to visualize your input. Just go to the folder where your input is and type the following in the terminal:
```
$ xcrysden --exciting input.xml &
```
Congratulations.
<file_sep>***This method is partly by [<NAME>](https://www.researchgate.net/profile/Mohammad-Ali-Mohebpour).***
1. Upload the QE input/output file to XCrySDen: `File` > `Open PWscf...`.
3. Export the file to the XSF format: `File` > `Save XSF Structure`.
4. Upload the XSF file to Vesta.
5. Save the file as a CIF file.
6. The generated CIF files lacks any symmetry information, so use [this tutorial](https://github.com/MohamedAbdulHameed/DFT/tree/main/CIF-Tutorial) to make it contain all the symmetry information of the crystal.
<file_sep>record = open("record.txt", "r+")
stress = []
for line in record:
stress.append(float(line.strip()))
record.close()
I = input("Iteration number: ")
print(I)
i = int(I)
F1 = open("output-%d.out" %i, "r+")
for line in F1:
a0 = line.strip()
a1 = " ".join(a0.split())
if a1.find("total stress") != -1:
a2 = a1.replace("total stress (Ry/bohr**3) (kbar) P= ", "")
stress.append(float(a2))
F1.close()
if len(stress) >= 1:
record = open("record.txt", "a+")
record.write(str(stress[len(stress)-1])+"\n")
record.close()
# Add the value of stress for this iteration to record.txt
try:
if len(stress) <= 1:
F1 = open("input-%d.in" %i, "r+")
NewContent = ""
for line in F1:
NewLine = line.replace("%d %d %d" %(i, i, i), "%d %d %d" %(i+1, i+1, i+1))
NewContent += NewLine + "\n"
F1.close()
F2 = open("input-%d.in" %(i+1), "w+")
F2.write(NewContent)
F2.close()
elif round(stress[len(stress)-1], 2) - round(stress[len(stress)-2], 2) <= 0.001:
F1 = open("input-%d.in" %i, "r+")
NewContent = ""
for line in F1:
NewLine = line.replace("%d %d %d" %(i, i, i), "%d %d %d" %(i+1, i+1, i+1))
NewContent += NewLine + "\n"
F1.close()
F2 = open("input-%d.in" %(i+1), "w+")
F2.write(NewContent)
F2.close()
else:
print("Covergence is achieved.")
print(stress)
except:
print("Program is terminated.")
exit()
<file_sep>A learn-by-doing Quantum Espresso tutorial. The input file `halite.in` contains a comprehensive explanation of each card and how it relates to the other cards. The input was tested for convergence by observing variation in pressure, which is the most sensitive variable to numerics.
|
317461fe9490fb291f208e2513fd2e5bb4bd8c58
|
[
"Markdown",
"Python",
"Shell"
] | 16
|
Python
|
MohamedAbdulHameed/DFT
|
090dcb5f6715bd559e68ceddeedcce31aec57a17
|
2a15cca73625c7c52e8064e17e9f646f1c28b7f5
|
refs/heads/master
|
<repo_name>JungBok-Cho/Bully-Algorithm<file_sep>/lab2.py
"""
Course: CPSC 5520-01, Seattle University
Author: <NAME>
Version: 1.0
I created this program based on the template offered by Professor <NAME>.
I did both Extra Credits. To check the PROBE Message Extra Credit, please remove
the comment of self.probing() in the run() function. To check the Feigning
Failure Extra Credit, please remove the comment of self.check_timeouts()
in the run() function.
"""
import selectors
from datetime import datetime, timedelta
import time as t
from enum import Enum
import pickle
import socket
import sys
import random
BUF_SZ = 1024 # TCP receive buffer size
DEFAULT_BOD = '1995-01-20' # Default date of birth
PEER_DIGITS = 100 # Max Socket number
BACKLOG = 100 # Number of backlog
CHECK_INTERVAL = 0.2 # To wait until some registered file objects
# become ready
ASSUME_FAILURE_TIMEOUT = 2000 # In milliseconds. If it takes less than 2 seconds
# to receive message, it will take the message.
# If it takes longer than 2 seconds, it will
# reject the message
class State(Enum):
"""
Enumeration of states a peer can be in for the Lab2 class.
"""
QUIESCENT = 'QUIESCENT' # Erase any memory of this peer
# Outgoing message is pending
SEND_ELECTION = 'ELECTION'
SEND_VICTORY = 'COORDINATOR'
SEND_OK = 'OK'
PROBE = 'PROBE'
# Incoming message is pending
WAITING_FOR_OK = 'WAIT_OK' # When I've sent them an ELECTION message
WAITING_FOR_VICTOR = 'WHO IS THE WINNER?' # This one only applies to myself
WAITING_FOR_ANY_MESSAGE = 'WAITING' # When I've done an accept on their
# connect to my server
def is_incoming(self):
"""Categorization helper."""
return self not in (State.SEND_ELECTION, State.SEND_VICTORY,
State.SEND_OK, State.PROBE)
class Lab2(object):
"""
Dynamically elect the biggest bully from a group of distributed
computer processes. The process with the highest DOB from amongst
the non-failed processes is selected as the bully. If some has the
same highest DOB, it will check which one has the highest SU ID.
"""
def __init__(self, gcd_address, next_birthday, su_id):
"""
Constructs a Lab2 object to talk to the given Group Coordinator
and initialize instance variables
:param gcd_address: GCD address to contact - (host, port)
:param next_birthday: User's next birthday
:param su_id: User's unique SU ID
"""
self.gcd_address = (gcd_address[0], int(gcd_address[1]))
days_to_birthday = (next_birthday - datetime.now()).days
self.pid = (days_to_birthday, int(su_id)) # To compare between users
self.connectedMembers = {} # Store only connected members
self.members = {} # Store every member
self.states = {} # Store a state of each member
self.bully = None # Biggest bully
self.nextFailureTime = timedelta(0, random.randint(0, 10000) / 1000)
self.startTime = datetime.now() # Starting time for timeout
self.endTime = datetime.now() # Ending time for timeout
self.ignoreIfOkExpired = False # Check if time for ok message is expired
self.selector = selectors.DefaultSelector()
self.listener, self.listener_address = self.start_a_server()
def run(self):
"""Start to find the biggest bully"""
print('STARTING WORK for pid {} on {}'.format(self.pid, self.listener_address))
self.join_group()
self.selector.register(self.listener, selectors.EVENT_READ)
self.start_election('at startup')
while True:
events = self.selector.select(CHECK_INTERVAL)
for key, mask in events:
if key.fileobj == self.listener:
self.accept_peer()
elif mask == selectors.EVENT_READ:
self.receive_message(key.fileobj)
else:
self.send_message(key.fileobj)
# self.check_timeouts() # Feigning Failure
# self.probing() # PROBE Message
def accept_peer(self):
"""Accept if peers wants to connect"""
try:
conn, addr = self.listener.accept()
self.set_state(State.WAITING_FOR_ANY_MESSAGE, conn)
except Exception as err:
print(err)
def send_message(self, peer):
"""
Send the queued message to the given peer (based on its current state)
:param peer: The socket to send a message
"""
state = self.get_state(peer)
print('{}: sending {} [{}]'.format(self.pr_sock(peer), state.value, self.pr_now()))
try:
if state.value == 'COORDINATOR':
# If we found a leader, we send connected members only
self.send(peer, state.value, self.connectedMembers)
elif state.value == 'PROBE':
self.send(peer, state.value, None)
else:
self.send(peer, state.value, self.members)
except ConnectionError as err:
print(err)
except Exception as err:
print(err)
if state == state.SEND_ELECTION:
self.set_state(State.WAITING_FOR_OK, peer, switch_mode=True)
else:
self.set_quiescent(peer)
@staticmethod
def findWinner(connectedMembers):
"""
Find the leader among the connect members
:param connectedMembers: Dictionary of connected members
:return: Return the largest pid
"""
keys = list(connectedMembers.keys())
largest = keys[0]
for member in keys:
if largest < member:
largest = member
return largest
def receive_message(self, peer):
"""
Receive the queued message from the given peer (based on its current state)
:param peer: The socket to receive a message
"""
try:
message_name = self.receive(peer)
except Exception as err:
print(err)
if self.ignoreIfOkExpired: # Check if time for ok message is expired
print('self: No Returned OK Message - Keep the current leader')
self.ignoreIfOkExpired = False
self.set_quiescent(peer)
return
if message_name[0] != 'OK' and message_name[0] != 'PROBE':
self.update_members(message_name[1]) # Update members
if self.is_expired(peer): # Operate this if time is expired
if message_name[0] == 'OK':
self.ignoreIfOkExpired = True
self.declare_victory('No Returned OK Message')
if len(self.states) != 0:
self.set_quiescent(peer)
return
if message_name[0] == 'COORDINATOR':
self.start_election('No Returned Victory Message')
if len(self.states) != 0:
self.set_quiescent(peer)
return
# Check the Message
if message_name[0] == 'ELECTION':
self.set_state(State.SEND_OK, peer)
if not self.is_election_in_progress():
self.start_election('Got a VOTE card from lower-pid peer')
elif message_name[0] == 'COORDINATOR':
self.set_leader(self.findWinner(message_name[1]))
print('self: Received COORDINATOR message')
self.set_quiescent(peer)
if len(self.states) != 0: # Remove remaining states
self.set_quiescent()
keysStates = self.states.keys()
for member in list(keysStates):
self.set_quiescent(member)
elif message_name[0] == 'OK':
print('self: Received OK message')
if self.get_state() == State.WAITING_FOR_OK:
self.set_state(State.WAITING_FOR_VICTOR)
self.set_quiescent(peer)
elif message_name[0] == 'PROBE':
print('self: Probing received')
self.set_state(State.SEND_OK, peer)
def check_timeouts(self):
"""Check timeouts"""
self.endTime = datetime.now()
self.nextFailureTime -= (self.endTime - self.startTime)
if self.nextFailureTime < timedelta(0, 0):
sleepDuration = random.randint(1000, 4000)
t.sleep(sleepDuration/1000)
self.nextFailureTime = timedelta(0, random.randint(0, 10000) / 1000)
self.startTime = datetime.now()
def probing(self):
"""Check if the bully is still alive"""
if self.bully is not None and self.bully != self.pid:
peer = self.get_connection(self.bully)
if peer is None: # Start election if bully got disconnected
self.start_election('bully got disconnected')
else:
randomNum = random.randint(500, 3000)
t.sleep(randomNum/1000)
self.set_state(State.PROBE, peer)
print('self: Probing sent after waiting', randomNum/1000, 'seconds')
def get_connection(self, member):
"""
Get a connection of the member
:param member: The member to connect
:return: Return a socket if connected. Otherwise, return None
"""
try:
peer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
peer.connect(self.members[member])
except Exception as err:
print('failed to connect to {}: {}'.format(member, err))
return None
else:
return peer
def is_election_in_progress(self):
"""
Check if it is in Quiescent state
:return: Return True if quiescent. Otherwise, return False
"""
return self.get_state() != State.QUIESCENT
def is_expired(self, peer=None, threshold=ASSUME_FAILURE_TIMEOUT):
"""
Check if the time is expired
:param peer: The peer socket to check
:param threshold: It is in seconds. Need to convert to milliseconds
:return: Return True if time is expired. Otherwise, return False
"""
return datetime.now() - self.states[peer][1] > timedelta(0, threshold / 1000)
def set_leader(self, new_leader):
"""
Set a new Leader
:param new_leader: New Leader to set
"""
self.bully = new_leader
def get_state(self, peer=None, detail=False):
"""
Look up current state in state table.
:param peer: Socket connected to peer process (None means self)
:param detail: If True, then the state and timestamp are both returned
:return: Return either the state or (state, timestamp) depending on detail
(not found gives (QUIESCENT, None))
"""
if peer is None:
peer = self
status = self.states[peer] if peer in self.states else (State.QUIESCENT, None)
return status if detail else status[0]
def set_state(self, state, peer=None, switch_mode=False):
"""
Change the current state in the state table
:param state: The state to set
:param peer: The peer to change the state
:param switch_mode: If True, it will modify mask in the peer's selector
:return: After a peer is set to quiescent, stop this function.
Return nothing.
"""
print('{}: {}'.format(self.pr_sock(peer), state.name))
if peer is None:
peer = self
if state.is_incoming():
mask = selectors.EVENT_READ
else:
mask = selectors.EVENT_WRITE
# Set to Quiescent state
if state == state.QUIESCENT:
if peer in self.states:
if peer != self:
self.selector.unregister(peer)
del self.states[peer]
if len(self.states) == 0:
print('{} (leader: {})\n'.format(self.pr_now(), self.pr_leader()))
return
# If it is new, register the peer
if peer != self and peer not in self.states:
peer.setblocking(False)
self.selector.register(peer, mask)
elif switch_mode: # If already registered, modify the mask
self.selector.modify(peer, mask)
self.states[peer] = (state, datetime.now())
# Send message if the peer is Event_Write mode
if mask == selectors.EVENT_WRITE:
self.send_message(peer)
def set_quiescent(self, peer=None):
"""
Set the peer's state to Quiescent
:param peer: The peer to be set quiescent
"""
self.set_state(State.QUIESCENT, peer)
def start_election(self, reason):
"""
Start an election
:param reason: The reason why it starts the election
"""
print('Starting an election {}'.format(reason))
self.set_leader(None)
self.set_state(State.WAITING_FOR_OK)
i_am_highest_bully = True
for member in self.members:
# Find higher bully
if member > self.pid:
peer = self.get_connection(member)
if peer is None:
continue
self.set_state(State.SEND_ELECTION, peer)
i_am_highest_bully = False
# Declare victory if I am the highest bully
if i_am_highest_bully:
self.declare_victory('no one is greater bully than me')
def declare_victory(self, reason):
"""
Declare victory. Initialize a dictionary of connected members
:param reason: The reason why I declare victory
"""
print('Victory by {} {}'.format(self.pid, reason))
self.set_leader(self.pid)
self.connectedMembers[self.pid] = self.listener_address
for member in self.members:
if member < self.pid:
peer = self.get_connection(member)
if peer is None:
continue
self.connectedMembers[member] = self.members[member]
self.set_state(State.SEND_VICTORY, peer)
self.set_quiescent()
def update_members(self, their_idea_of_membership):
"""
Update members. It it is a new member, add to the members. If it is
existing member, update the socket. Never delete members.
:param their_idea_of_membership: Dictionary of members to use to update
"""
for newMem in their_idea_of_membership:
self.members[newMem] = their_idea_of_membership[newMem]
print('Update members: ', self.members)
@classmethod
def send(cls, peer, message_name, message_data=None,
wait_for_reply=False, buffer_size=BUF_SZ):
"""
Send message helper
:param peer: The socket to send message
:param message_name: The Message Title
:param message_data: Dictionary of members
:param wait_for_reply: Check if it requires reply message
:param buffer_size: Buffer size for message
:return: Return receive message if wait_for_reply is True.
Otherwise, return nothing
"""
message = message_name if message_data is None else (message_name, message_data)
peer.sendall(pickle.dumps(message))
if wait_for_reply: # Operate it if it requires any reply
return cls.receive(peer, buffer_size)
@staticmethod
def receive(peer, buffer_size=BUF_SZ):
"""
Receive message helper
:param peer: The socket to receive message
:param buffer_size: Buffer size for message
:return: Return the received date
(message_name, dictionary of updated member)
"""
recvMessage = peer.recv(buffer_size)
if not recvMessage:
raise ValueError('socket closed')
data = pickle.loads(recvMessage)
if type(data) == str:
data = (data, None)
return data
@staticmethod
def start_a_server():
"""
Start a server
:return: Return server socket and its socket address
"""
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.bind(('localhost', 0))
listener.listen(BACKLOG)
return listener, listener.getsockname()
def join_group(self):
"""Connect to GCD2 to get a dictionary of members"""
gcd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
gcd.connect(self.gcd_address)
self.members = self.send(gcd, 'JOIN', (self.pid, self.listener_address), True)
print('Members: {}'.format(self.members))
@staticmethod
def pr_now():
"""
Printing helper for current timestamp
:return: Return current time
"""
return datetime.now().strftime('%H:%M:%S.%f')
def pr_sock(self, sock):
"""
Printing helper for given socket
:param sock: The socket to check
:return: Return self if sock is None or self or equals to listener.
Otherwise, return the cpr_sock function
"""
if sock is None or sock == self or sock == self.listener:
return 'self'
return self.cpr_sock(sock)
@staticmethod
def cpr_sock(sock):
"""
Static version of helper for printing given socket
:param sock: The socket to check
:return: Return a string that shows a connection between sockets
"""
l_port = sock.getsockname()[1] % PEER_DIGITS
try:
r_port = sock.getpeername()[1] % PEER_DIGITS
except OSError:
r_port = '???'
return '{}->{} ({})'.format(l_port, r_port, id(sock))
def pr_leader(self):
"""Printing helper for current leader's name"""
return 'unknown' if self.bully is None \
else ('self' if self.bully == self.pid else self.bully)
def setDOB():
"""
Get the next birth day
:return: Return the next birth day
"""
now = datetime.now()
if len(sys.argv) == 4:
myDOB = datetime(now.year + 1, 1, 1)
else:
pieces = sys.argv[4].split('-')
myDOB = datetime(now.year, int(pieces[1]), int(pieces[2]))
if myDOB < now: # if already passed, get birthday in the next year
myDOB = datetime(myDOB.year + 1, int(pieces[1]), int(pieces[2]))
return myDOB
if __name__ == '__main__':
if not 4 <= len(sys.argv) <= 5:
print("Usage: python lab2.py GCDHOST GCDPORT SUID [DOB]")
exit(1)
DOB = setDOB()
print('Next Birthday: ', DOB)
host, port, SUID = sys.argv[1:4]
print('SU ID: ', SUID)
lab2 = Lab2((host, port), DOB, int(SUID))
lab2.run()
|
b42386a56bf01192fe3f9057407fe8cd5b606866
|
[
"Python"
] | 1
|
Python
|
JungBok-Cho/Bully-Algorithm
|
42276383dca72ee3db9a341e227fe099b469cca5
|
2590b9a9cd48a91fbc34514dcc1044d4541a989a
|
refs/heads/master
|
<file_sep># simple-wordlist-generator-v-1.0
Generatore di wordlist con opzione nome cognome e data di nascita
<file_sep>import sys
print "####################################"
print "# #"
print "# SIMPLE WORDLIST GENERATOR V 0.1 #"
print "# ARTIST_00 #"
print "# #"
print "####################################"
global file1, richiesta
var1 = raw_input("Inserisci il nome: ")
var2 = raw_input("Inserisci il cognome: ")
var3 = raw_input("Inserisci l'anno di nascita: ")
var4 = raw_input("Inserisci il giorno (es 01) di nascita: ")
var5 = raw_input("Inserisci il mese di nascita: ")
special = raw_input("Inserisci le ultime 2 cifre dell'anno di nascita: ")
def crea():
var6 = var1.title() + var2.title()
var7 = var2.title() + var1.title()
var8 = var1 + var2
var9 = var2 + var1
var10 = var1.title() + var2.title() + var3
var11 = var1.title() + var3
var12 = var1 + var3
var13= var1 + var2 + var3
var14= var4 + var5 + var3
var15= var3 + var5 + var4
var16 = var4 + var5 + special
var17 = var1.title()+"_"+ var3
var18 = var1 +"_"+ var3
var19= var1 + "_" + var2 + var3
var20 = var1.title()+"_"+ special
var21 = var1.title() + var2 + var3
var22 = var1 + " " + var2
var23 = var1 + var2 + var4 + var5 + var3
var24 = var1 + var4 + var5 + var3
var25= var1.title() + var4 + var5 + var3
var26 = var1.title() + "_" + var4 + var5 + var3
var27 = var1 + var4 + var5 + special
var28 = var1.title() + var4 + var5 + special
var29 = var1.title()+ var2 + var4 + var5 + var3
var30= var1.title()+ var2 + var4 + var5 + special
var31 = var1.upper() + var3
var32 = var1.upper() + "_" + var3
var33 = var1.upper() + var2.upper()
var34= var1.upper() + var2.upper() + var3
var35 = var1.upper() + var2.upper() + "_"+ var3
var36 = var1.upper() + "_" + var2.upper() + "_" + var3
file1 = open("wordlist.lst", "w")
file1.write(var6+"\n")
file1.write(var7+"\n")
file1.write(var8+"\n")
file1.write(var9+"\n")
file1.write(var10+"\n")
file1.write(var11+"\n")
file1.write(var12+"\n")
file1.write(var13+"\n")
file1.write(var14+"\n")
file1.write(var15+"\n")
file1.write(var16+"\n")
file1.write(var17+"\n")
file1.write(var18+"\n")
file1.write(var19+"\n")
file1.write(var20+"\n")
file1.write(var21+"\n")
file1.write(var22+"\n")
file1.write(var23+"\n")
file1.write(var24+"\n")
file1.write(var25+"\n")
file1.write(var26+"\n")
file1.write(var27+"\n")
file1.write(var28+"\n")
file1.write(var29+"\n")
file1.write(var30+"\n")
file1.write(var31+"\n")
file1.write(var32+"\n")
file1.write(var33+"\n")
file1.write(var34+"\n")
file1.write(var35+"\n")
file1.write(var36+"\n")
file1.close()
def aggiungi():
parola = raw_input(" Parola da aggiungere: ")
file1.append(parola)
file1.close()
crea()
print "La wordlist è stata creata e nominata wordlist.lst"
while (1 == 1):
richiesta = raw_input("Vuoi aggiungere altre parole? [s\n]")
if richiesta=="s":
aggiungi()
continue
if richiesta=="n":
print "Ok esco..."
break
sys.exit()
|
112e39039d4404a229c600c7b280650efdb5848a
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
0000THEARTIST0000/simple-wordlist-generator-v-1.0
|
9cf1751a04a348f8a366eceb448ef6d748104f2c
|
37ee77e4058ca7e744fc26e595f00674715ae5d5
|
refs/heads/master
|
<repo_name>yunik4/doorly<file_sep>/doorbot.py
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# import RPi.GPIO as GPIO
import requests
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import sensors
from time import sleep
# Bot token receieved from BotFather
TOKEN = '<KEY>'
# Luis application setup
LUIS_KEY = ''
ENDPOINT = 'https://westeurope.api.cognitive.microsoft.com/luis/v2.0/apps/c3ecb7e9-9c34-4bba-9fbe-ccdab583141a?verbose=true&timezoneOffset=0&subscription-key=9b6dc17ab7d84af6abafefbd324f579f&q='
# Global parameters
##################################################### Command Handlers ##########################################################
def start(update, context):
"""Send a message when the command /start is issued."""
update.message.reply_text('Hi!')
def lock(update, context):
# sensors.lock()
update.message.reply_text('The door is closed!')
def unlock(update, context):
# sensors.unlock()
update.message.reply_text('The door is open!')
def take_pic(update, context):
# pic_path = sensors.take_picture()
# update.message.sendPhoto(photo=open(pic_path, 'rb'))
update.message.reply_text('Should I open??')
def limit_access(update, context):
update.message.reply_text("Ok, only family is allowed. I wonder what you're hiding (-;")
###################################################### Language Understanding ###################################################
# Parse the message and call the right command handler
def hadle_text_message(update, context):
print(update.message.text)
intent = get_intent(update.message.text)
print(intent)
if (intent == "close"):
lock(update, context)
elif (intent == "open"):
unlock(update, context)
elif (intent == "limit"):
limit_access(update, context)
elif(intent == "picture"):
take_pic(update, context)
elif (intent == "limit"):
limit_access(update, context)
else:
update.messae.reply_text("Sorry I didn't understand you")
# Send the receieved message to the LUIS application and get the top scoring intent
def get_intent(message):
# Set up the request headers
headers = {
'Ocp-Apim-Subscription-Key': LUIS_KEY,
}
try:
# Send the request to the Luis application endpoint
r = requests.get(ENDPOINT + message, headers=headers)
# Get the top scoring intent from the possible intents list
print(r.json())
return r.json()['topScoringIntent']['intent']
except Exception:
return None
#################################################################################################################################
def main():
# Set up the bot updater with the bot Token
updater = Updater(TOKEN, use_context=True)
dp = updater.dispatcher
# Set up a commnad handler for each command
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("open", unlock))
dp.add_handler(CommandHandler("close", lock))
dp.add_handler(CommandHandler("picture", take_pic))
dp.add_handler(CommandHandler("limit", limit_access))
# Set up a message handler for text messages
dp.add_handler(MessageHandler(Filters.text, hadle_text_message))
# Start listen for incoming messages
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
|
3156d4cdd479557aee8355e3fd502a358fb9d44e
|
[
"Python"
] | 1
|
Python
|
yunik4/doorly
|
85a0faa9fac2a3993f74eeff22989fd16f2feb8f
|
b7b396ac0e388360fc7c12b9cc482ed58c9c4981
|
refs/heads/master
|
<file_sep># getting-started-fastify
<file_sep>async function routes(fastify, options) {
const collection = fastify.mongo.db.collection('pizzas');
fastify.get('/pizzas', async function (request, reply) {
const result = await collection.find().toArray();
if (result.length === 0) {
throw new Error('No documents found');
}
return result;
});
fastify.get('/pizzas/:id', async function (request, reply) {
const result = await collection.findOne({
_id: fastify.mongo.ObjectId(request.params.id),
});
if (result === null) {
throw new Error('Invalid value');
}
return result;
});
fastify.post('/pizzas', async function (request, reply) {
const result = await collection.insertOne(request.body);
if (result === null) {
throw new Error('Unexpected error');
}
return result;
});
fastify.put('/pizzas/:id', async function (request, reply) {
const query = { _id: fastify.mongo.ObjectId(request.params.id) };
const update = { $set: request.body };
const options = { upsert: true };
const result = await collection.updateOne(query, update, options);
if (result === null) {
throw new Error('Unexpected error');
}
return result;
});
fastify.delete('/pizzas/:id', async function (request, reply) {
const result = await collection.deleteOne({
_id: fastify.mongo.ObjectId(request.params.id),
});
if (result === null) {
throw new Error('Invalid value');
}
return result;
});
}
module.exports = routes;
<file_sep>const fastifyPlugin = require('fastify-plugin');
async function dbConnector(fastify, options) {
fastify.register(require('fastify-mongodb'), {
url: 'mongodb://localhost:27017/fastify_db',
});
}
module.exports = fastifyPlugin(dbConnector);
|
9178839b71028e0c00ec5848cad721781f6bf780
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
resparzasoto/getting-started-fastify
|
a893e80fe1bbfca8428e3011a04895f859db36c9
|
0b3abcc9a8a372f48b1bfac13ec5a0b429307fef
|
refs/heads/master
|
<file_sep>---
layout: layouts/layout.erb
---
# Say What?!
## Error 404 - We Couldn't Find the Page You're Looking For.
<file_sep>---
layout: layouts/layout.erb
---
# ISRC - International Standard Recording Code
After mastering songs, a master should be assigned a unique ISRC that helps track it's ownership and use.
When I assign a unique ISRC to a master, it will begin with the code QZ-AYA.
Each master will be assigned a unique code and any changes to the master (re-mastering, re-mixing, fades longer than 10 sec. etc') will result in a new ISRC code being assigned.
On this page you can find the ISRC codes I publicly assigned and the master's current copyright holder (their artist name).
This doesn't necessarily reflect copyright for the song or composition, as mechanical rights are different than compositional rights.
## QZ-AYA-17-XXXXX
| **ISRC** | **Track Name** | **Owner** | **Comments** |
|-----------------|--------------------------|-----------------------|-----------------------|
| QZ-AYA-17-00010 | It's Me | Bo Wild (me) | |
| QZ-AYA-17-00011 | It's Me (retouched) | Bo Wild (me) | |
| QZ-AYA-17-00021 | Lost Soul (Remix) | Bo Wild (me) | |
## QZ-AYA-18-XXXXX
| **ISRC** | **Track Name** | **Owner** | **Comments** |
|-----------------|--------------------------|-----------------------|-----------------------|
| QZ-AYA-18-12001 | Hunger and Need | Bo Wild (me) | (yanked) |
| QZ-AYA-18-12002 | Hunger and Need | Bo Wild (me) | |
| QZ-AYA-18-12003 | The Warlords Lament | Bo Wild (me) | String Quintet |
| QZ-AYA-18-12004 | To a New World | Bo Wild (me) | Orchestral |
| QZ-AYA-18-12005 | Silver Dreams | Bo Wild (me) | |
## QZ-AYA-19-XXXXX
| **ISRC** | **Track Name** | **Owner** | **Comments** |
|-----------------|--------------------------|-----------------------|-----------------------|
| QZ-AYA-19-10001 | Hunger and Need | Bo Wild (me) | (78 BPM) |
## QZ-AYA-20-XXXXX
| **ISRC** | **Track Name** | **Owner** | **Comments** |
|-----------------|--------------------------|-----------------------|-----------------------|
| QZ-AYA-20-10001 | Hunger and Need | Bo Wild (me) | (82+ BPM) |
| QZ-AYA-20-10002 | Broken Rings (demo) | Bo Wild (me) | (72 BPM) |
## QZ-AYA-21-XXXXX
| **ISRC** | **Track Name** | **Owner** | **Comments** |
|-----------------|--------------------------|-----------------------|-----------------------|
| QZ-AYA-21-12310 | Broken Rings | Bo Wild (me) | (74+ BPM) |
<file_sep>---
layout: layouts/layout.erb
---
# The Price of Bread and Honey
My pricing scheme is designed to follow common industry practices and minimize your overhead expenses when possible.
I'm aware that much like music itself, there aren't any "one size fits all" solutions here and our actual agreement might look different.
Of course, until we reach an actual agreement that we're both happy with, you will not be able to use any work I may have completed.
To all my USA clients, my current visa status (I'm in the USA with a student visa and without a green card) means that I won't be accepting any work in the USA.
<!--
---
The following price details are a good representation of what I would expect you to offer (for work outside the USA).
* *Songwriting*:
Once we sit in the room and start songwriting, I expect to receive an equal share as a songwriter (which is also the law when a split-sheet doesn't state otherwise).
However, song critique and any minor suggestions that result from the song critique are free as part of my production services.
* *Production*
Production prices in the industry vary and are often a mix between up-front payments and co-ownership of the master and recordings.
I split the production pricing into two models.
The *Demo* model is designed for budding artists that need something for their artist portfolio to help them promote themselves and the song.
The *Master* model is designed for more established artists that wish to release a song, an EP or an album.
* *Master Production*:
Prices start at a $1,500 advance and 3% co-ownership of the master (payed as "record one" royalties). When record labels are involved, we might agree that royalty payments would be due only after the label's expenses have been recouped, so you, as the artist, don't suffer out-of-pocket expenses.
Production of a final master might require an external recording studio (not my home studio), session players, backing vocalists and the like. These external expenses aren't included in the price you will need to pay for them.
* *Demo Production*:
Producing a demo is similar to producing the actual song, only often the mixing process and the complexity of the song will be simpler.
Often, when I believe in a song, I'll be willing to produce the *Demo* without any up-front payments (except external expenses). However, I will expect 1% "record one" royalties (SLRP) from the released version in exchange for fronting my personal work and expenses.
Other possible fee arrangements can be reached, including a flat fee for projects based on a small number of virtual instruments, a single vocal and a single live instrument (a Piano or a Guitar).
*Notice*: a Demo can't be publicly released and I retain all ownership of the mechanical rights. Demos can only be used as part of an artist portfolio (not resale). For example, you can use them to promote either yourself or your song to record labels and as a draft for the final production. These limitations are mutual (I won't use the Demo except as part of my artist portfolio, same as you).
*External expenses** include session players, external studio time (not my home studio) and the like. These do not include my own time, equipment, licensing fees etc'.
* *Sync / Scoring*:
There's a big difference between writing and producing a jingle and scoring a dramatic piece with a live orchestra (or a digital mockup).
Prices start at $250 per minute (or part of a minute) and depend on specific details such as the requested style(s), instrumentation, delivery requirements, etc' - i.e., do you need a printed score? a mockup? do you expect a fully produced mix? is it an instrumental piece or a song?
These fees are licensing fees and the do *not* include copyright buyout fees. Unless buyout fees are agreed upon, I retain any and all copyrights.
-->
<file_sep>---
layout: layouts/layout.erb
---
# I Believe Music can Change the World
### I Believe Music Can Set Us Free

I spent my life trying out different professions, different countries, different identities... an ex-soldier, a Buddhist, a lawyer, a tantric - but **all roads lead inwards**, into the person we truly are.
So I became a **musician**.
I believe **we all have our own unique voice**, that we have an inner truth that we yearn to express and it is unique to who we are.
Music speaks to me, to all of us. The stories we share through music **speak to the heart**, they bring us together and they move us in **wonderful and mysterious ways**.
As a [Producer](producer), [Composer](composer) and [Songwriter](songwriter), I am **honored** to help you share your story and express your truth through music.
As an [Artist](artist), I strive to do the same.
Find my music @ [](https://music.apple.com/us/artist/bo-wild/1602428458) [](https://open.spotify.com/artist/06LFekW9oLivQ96QMf2RcH) [](https://music.youtube.com/playlist?list=OLAK5uy_mk6iRCKmpjBGdbjl3oaRKNTM7iFuLbxNo) [](https://music.yandex.com/artist/15535336)
<file_sep>---
layout: /layouts/layout.erb
title: Bo Wild - Composer
---
## Speaking through Music

I believe that music speaks directly to our hearts and touches our very soul.
## Tailored for Your Story
Music tells a story. Just like the colors and the images on screen, it sets a mood, just like the body language of the actors, it communicates.
Bespoke music is completely different than library music - exactly like shooting your own videos is completely different than using clips you found on YouTube.
Sure, you **can** make your movie, TV show or commercial using library and YouTube videos - but **would** you?
## Instrumental
##### To a New World
[To a New World](/media/to_a_new_world.m4a "score: To a New World") is a heroic journey to the great unknown, where danger lurks at every turn and magical beauty inspires the heart.
##### The Warlord's Lament
Warlords don't really expect to age, they don't often reflect on their life's accomplishments and they rarely live long enough to get the chance.
Allow us to listen to the Strings as they follow an aging warlord's musing in [The Warlord's Lament](/media/the%20warlords%20lament.m4a "score: The Warlord's Lament"). Let us march along the footsteps of empty victories and lost friends.
## Sync
I had fun scoring these commercials and I hope you enjoy the score.
The iPad commercial is probably my favorite, since I felt it was am improvement on the original score - check it out and let me know what you think.
##### iPad
I love drums and rhythm... there's something raw and powerful.
And this commercial just screamed to me "big bang", where music emerges from chaos.
<p class="p4video"><iframe src="https://www.youtube-nocookie.com/embed/fe_fmv08qNs?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen style='display: inline-block; margin: 0.4em;'></iframe></p>
<p> </p>
##### Westworld (HBO) Competition
HBO make amazing TV shows and Spitfire Audio makes amazing virtual instruments for composers. Together they teamed up and came up with an amazing composition competition.
I really had fun trying out new ideas for this competition and scored this cue in two very different - it really changes in the middle in a way that was both challenging and fun. I hope you enjoy it.
<p class="p4video"><iframe src="https://www.youtube-nocookie.com/embed/Wi29OWe8piY" frameborder="0" allow="autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen style='display: inline-block; margin: 0.4em;'></iframe></p>
<p> </p>
##### Rebook
I found this commercial a bit of a challenge. I wanted the sounds to be organic, but fresh and young, like running shoes - they are a technology that let's us go running in nature.
Eventually I think I managed to find a balance between the digital and nature, using both orchestral and synth sounds. An interesting mix.
<p class="p4video"><iframe src="https://www.youtube-nocookie.com/embed/MKI2EKgV8n0?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen style='display: inline-block; margin: 0.4em;'></iframe></p>
<p> </p>
##### Purina
Purina is a household name for dog food... but I fell in love with their concept the moment I got to see the commercial.
Even without sound, the sweetness of heroic dreams and the innocence of youth were oozing from the concept. Now I just had to figure out how to draw these qualities out and make them shine.
I decided on a balance between a bit of humor and a touch of drama to bring the heroic and playful puppy dreams to life, which brought me up to orchestral sounds and a sprinkle of corny voicings in fourths.
<p class="p4video"><iframe src="https://www.youtube-nocookie.com/embed/2CA8BR_boqo?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen style='display: inline-block; margin: 0.4em;'></iframe></p>
<p> </p>
##### Cheetos
I really love detective films. Something about the film-noir calls to me... but I'm a real sucker for spy films with Jazzy big band scores. I just can't get enough of them.
So when I saw this old Cheetos commercial, I has to give a shot at scoring it.
Sadly, this one has no sound design. I was focused on learning the Jazzy sound and wasn't too concerned about the polish.
<p class="p4video"><iframe src="https://www.youtube-nocookie.com/embed/sa4cFCnTn2c?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen style='display: inline-block; margin: 0.4em;'></iframe></p>
<p> </p>
##### Japp
This hilarious commercial was re-scored as a school assignment. I ended up writing a song which I really enjoyed and I hope you enjoy it as well.
After the first time, feel free to follow along with [the score](/media/together.pdf) if you like.
<p class="p4video"><iframe src="https://www.youtube-nocookie.com/embed/OWtjESI2RsM?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen style='display: inline-block; margin: 0.4em;'></iframe></p>
<p> </p>
##### West 40
I was asked by a friend for a 40 second musical piece that matched the famous mood and feel in [the theme for Westworld](https://youtu.be/rYelEUVQ50g).
[West 40](/media/west40.m4a "play: West 40") was written as a simplified mood version that leaves more room for the video than the theme that inspired it.
Now, Westworld's theme is beautiful and smart. <NAME> wrote a wonderful piece. It's multi-layered and moving and full of story. I wondered - how could I compress that into 40 seconds?
Moreover, the piece of music was for a class and they would edit to my music (instead of the other way around), which meant I didn't have any picture to start with. Also, I didn't have enough time to find a Dobro for that beautiful metallic sound.
I must say, it was a fun challenge and I hope you enjoy it too.
<file_sep>---
layout: layouts/layout.erb
---
# Patriarch's Party
[](/images/party.ics)
#### Let's party!
Welcome to my house warming / new year party. Let's celebrate new beginnings 🎉
[Save the date!](/images/party.ics)
## Where?
улица Малая Бронная 10с1 (подъезд 3)
КВ 24, Этаж 4
[Yandex Maps](https://yandex.com/maps/?text=55.760548%2C37.596607) / [Google Maps](https://goo.gl/maps/6xTtJLkq9R1F1bXw8) / [Apple Maps](https://maps.apple.com/?address=Malaya%20Bronnaya%20Street,%2010%D1%811,%20Moscow,%20Russia&ll=55.760672,37.596687&q=Malaya%20Bronnaya%20Street,%2010%D1%811&_ext=EiQp8nIi/NrVS0AxZMZLEfG3QkA5ZEm3otnsS0BBbCxjac/gQkA%3D)
## When?
Saturday January 16 @ 19:00
## Why?
Why not?
<file_sep>---
layout: layouts/layout.erb
---
# Portfolio
Welcome to my private portfolio where you can enjoy a sample of my work.
Most of the work in this portfolio was never published, so feel free to contact me about cuts or sync licenses.
There's much more not listed here, feel free to contact me for details.
## Songs
The following are some rough demos for songs I enjoyed writing.
I hope you enjoy listening to these songs as much as I enjoyed writing them.
##### Hunger and Need
Some stories are hard to talk about, but, somehow, they leak into my music and come out in song.
This song is dedicated to all the people out there who want to overcome their own misfortune through their own effort, and to the people watching from the sideline wishing they could help.
[**Hunger and Need (a Smile at a Time)** / Me](/media/hunger_and_need.m4a "score: Hunger and Need")
Guitar: [<NAME>](https://soundcloud.com/weijun-yang)
Drums: [<NAME>](https://taikimiyazawa727.wixsite.com/mysite)
Percussion, Piano, Vocals: Bo Wild
> **V.1**
>
> She cooks for me with flames of passion,
>
> She knows just what I need to taste,
>
> Truth is hard to swallow,
>
> I taste the price of our disgrace.
>
> **V.2**
>
> To save our hearts I sell for dollars
>
> My slice of life per day and night
>
> Even god can't save me
>
> If other men can steal her light
>
> **Pre.**
>
> From the shadows I watch her dance,
>
> She’s not dancing for me
>
> **Ch.**
>
> Selling our souls, a smile at a time
>
> She suffers it all, a smile at a time
>
> I'm losing my mind, a smile at a time
>
> A slave to my hunger and need
>
> **V.3**
>
> With every breathe she's loosing thunder
>
> Her laughing eyes are turning gray
>
> I'm losing all I ever wanted
>
> I cry as she slips away
>
> **Pre.**
>
> From the shadows I watch her dance,
>
> She’s not dancing for me
>
> **Ch.**
>
> Selling our souls, a smile at a time
>
> She suffers it all, a smile at a time
>
> I'm losing my mind, a smile at a time
>
> A slave to my hunger and need
>
> **Br.**
>
> I blame the skies and curse the heavens,
>
> Their judgment cruel with righteous pride
>
> They judge the way she sold her body,
>
> But I’m the one who can’t provide
>
> Yes, I’m the one who can’t provide
>
> **Ch.**
>
> Selling our souls, a smile at a time
>
> She suffers it all, a smile at a time
>
> I'm losing my mind, a smile at a time
>
> A slave to my hunger
>
> It's taking it's toll, a smile at a time
>
> A dollar and pole, a smile at a time
>
> She's breaking my heart, a smile at a time
>
> A slave to my hunger and need
>
> A slave to my hunger and need
>
##### It's Me
For years I was in love with a girl who couldn't care enough to acknowledge my existence. I was 6 years old when she stole my heart and more than 13 years old before I reclaimed it.
I think we all go through that at some point in our lives. I just had to do it more than once... High school was much the same with a different girl and my adult life took a while to improve.
I was luck enough to analyze the works of the Beatles and their amazing songwriting skills with Prof. <NAME>.
During our work, I wrote this song inspired by my own story and some of the techniques employed by <NAME> and <NAME>.
[**It's Me** / Me](/media/its_me.m4a "score: It's Me")
> **V.1.**
>
> I guess it’s true,
>
> what they all said,
>
> He wasn’t true, he made you sad
>
> But don’t you know there’s someone
>
> that you can always count on
>
> Oh don’t you know? It's me.
> **V.2.**
>
> So many years I loved you, but I never said
>
> These hopes and fears inside me, and all the tears I shed
>
> Oh, all this time together
>
> And still you don’t know better
>
> How don’t you know? It's me. It's ...
> **Br.**
>
> Me that hears your cries, in the silence of the night
>
> I share your sighs, your lows, your highs
>
> and you should know,
>
> I loved you, since I met you, on that night in New Years Eve,
>
> This love will never fade or leave
> **Br.2.**
>
> This love, this love, this love, this love
>
> This love will never die
> **V.3.**
>
> The day will come and you will see,
>
> That this old heart is all you need
>
> One day we'll be together
>
> And things will just get better
>
> The day you'll know, it's me.
##### Turned Gray
I love animation movies, like Finding Nemo and Toy Story. I don't know what it is, but somehow the adult in me is torn be these little stories.
And the opening of the film Up was one I couldn't easily let go of... and this is how this song was born.
[**Turned Gray** / Me](/media/turned_gray.m4a "score: Turned Gray")
> **V.1.**
>
> Small broken dreams, we left by the stream,
>
> With our childhood and younger days
>
> Promises made, were stolen away,
>
> Time flowing on it’s way
>
> By time twisting years that stray.
>
> Sitting right here, as days turn to years,
>
> I wonder you never say,
>
> That all the dreams we promised, turned gray
> **V.2.**
>
> Holding our hands, through decades that bend
>
> I still have so much to say
>
> Our old childhood dreams, are torn at the seams
>
> I doubt if we'll see them one day
>
> Worn kitchen chairs, slumped wooden stairs,
>
> Consumed by an old routine.
> **Br.**
>
> On slow afternoons at home (Home with you)
>
> Curled by the TV screen (You’re in my arms)
>
> It's better than any dream or adventure I'd known,
>
> Oh...
> **V.3.**
>
> Christmas tree lights, still shining bright,
>
> We bought them so long ago
>
> You gift me this book, of peter and hook
>
> Wrapped in your love and a bow
>
> Though we grow old, walking this road
>
> Please know that for me it's okay
>
> That all the dreams we promised, turned gray
##### Lost Soul
[Lost Soul](/media/lost_soul.m4a "score: Lost Soul") is one I am quietly in love with. There's a million songs about "_boy meets girl at bar and never sees here again_", but this story is my story, which makes it a bit more personal... at least for me.
[**Lost Soul** / Me](/media/lost_soul.m4a "score: Lost Soul")
> **V.1.**
>
> She stood in the spotlight, with an old stained guitar
>
> Teasing a song
>
> as I watched from the bar
>
> She was clouds on the horizon,
>
> Trouble on the breeze
>
> And she had me
>
> on my knees
> **Ch.**
>
> She was a lost soul
>
> Shouldn’t give my heart
>
> Knew it from the start
>
> She was a lost soul
>
> Lost soul
>
> Lost Soul
> **V.2.**
>
> Her shattered breath
>
> Went under my guard
>
> With her soft voice
>
> She hit me quite hard
>
> She was the cry of thunder drums
>
> Lightning on high seas
>
> And she had me
>
> on my knees
> **Ch.**
>
> She was a lost soul...
> **Br.**
>
> I had this need to save her,
>
> Saving her just might save me,
>
> But I heard it in that moment,
>
> in her graceful movement,
>
> I knew that it could never be
> **Ch.**
>
> She was a lost soul...
> **V.3.**
>
> She broke my heart
>
> And left me that night
>
> It's been a while
>
> But I still crave her light
>
> She was summer dream in winter
>
> A kiss of fire as I freeze
>
> And she had me
>
> on my knees
> **Ch.**
>
> She was a lost soul...
##### Morning Sunshine
Some songs I never got to record properly... but when I have some free time, I would love to take them back in to the studio and make a proper demo.
Morning Sunshine is definitely one of the songs I want to record.
It's sweet and honest and I wrote it during one of those magical moods when I was beginning to fall in love, just before loosing my balance and crashing.
Anyway, I even [have a score](/media/morning_sunshine.pdf), ready for when I can record it.
[**Morning Sunshine** / Me](/media/morning_sunshine.pdf)
> **V.1**
>
> Sunday morning,
>
> we’re still in bed
>
> I hear her mumble
>
> Her curls all tumble on my chest
> If I'm dreaming? (is he dreaming?)
>
> If she’s not here
>
> Oh morning sunshine, (morning sun_shine)
>
> please disappear
> **V.2**
>
> If she wakes up
>
> Oh, if she leaves
>
> I’ll be lonely (so lonely___)
>
> Oh, I would plainly lose my mind
> Now she’s sleeping,
>
> So don’t come near,
>
> Oh morning sunshine, (oh ooo___)
>
> please disappear (disappear)
> **Br.**
>
> Before I met her
>
> My nights were always blue
>
> Empty evenings,
>
> Each time with someone new
> The day I met her
>
> She stole away my heart
>
> I damn the daytime
>
> That's keeping us apart
> **V.3**
>
> Monday morning,
>
> I’m off to work
>
> She said she’ll meet me (oh yeah)
>
> I’ll pick her up right after dark
> I can’t wait, no
>
> To see my dear (at night together)
>
> Oh morning sunshine,
>
> please disappear
## Instrumental
##### To a New World
[To a New World](/media/to_a_new_world.m4a "score: To a New World") is a heroic journey to the great unknown, where danger lurks at every turn and magical beauty inspires the heart.
##### The Warlord's Lament
Warlords don't really expect to age, they don't often reflect on their life's accomplishments and they rarely live long enough to get the chance.
Allow us to listen to the Strings as they follow an aging warlord's musing in [The Warlord's Lament](/media/the%20warlords%20lament.m4a "score: The Warlord's Lament"). Let us march along the footsteps of empty victories and lost friends.
## Sync
I had fun scoring these commercials and I hope you enjoy the score.
The iPad commercial is probably my favorite, since I felt it was am improvement on the original score - check it out and let me know what you think.
##### iPad
I love drums and rhythm... there's something raw and powerful.
And this commercial just screamed to me "big bang", where music emerges from chaos.
<div style="text-align: center"><iframe width="560" height="316" src="https://www.youtube-nocookie.com/embed/fe_fmv08qNs?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen style='display: inline-block; margin: 0.4em;'></iframe></div>
<p> </p>
##### Rebook
I found this commercial a bit of a challenge. I wanted the sounds to be organic, but fresh and young, like running shoes - they are a technology that let's us go running in nature.
Eventually I think I managed to find a balance between the digital and nature, using both orchestral and synth sounds. An interesting mix.
<div style="text-align: center"><iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/MKI2EKgV8n0?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen style='display: inline-block; margin: 0.4em;'></iframe></div>
<p> </p>
##### Purina
Purina is a household name for dog food... but I fell in love with their concept the moment I got to see the commercial.
Even without sound, the sweetness of heroic dreams and the innocence of youth were oozing from the concept. Now I just had to figure out how to draw these qualities out and make them shine.
I decided on a balance between a bit of humor and a touch of drama to bring the heroic and playful puppy dreams to life, which brought me up to orchestral sounds and a sprinkle of corny voicings in fourths.
<div style="text-align: center"><iframe width="560" height="316" src="https://www.youtube-nocookie.com/embed/2CA8BR_boqo?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen style='display: inline-block; margin: 0.4em;'></iframe></div>
<p> </p>
##### Cheetos
I really love detective films. Something about the film-noir calls to me... but I'm a real sucker for spy films with Jazzy big band scores. I just can't get enough of them.
So when I saw this old Cheetos commercial, I has to give a shot at scoring it.
Sadly, this one has no sound design. I was focused on learning the Jazzy sound and wasn't too concerned about the polish.
<div style="text-align: center"><iframe width="560" height="316" src="https://www.youtube-nocookie.com/embed/sa4cFCnTn2c?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen style='display: inline-block; margin: 0.4em;'></iframe></div>
<p> </p>
##### Japp
This hilarious commercial was re-scored as a school assignment. I ended up writing a song which I really enjoyed and I hope you enjoy it as well.
After the first time, feel free to follow along with [the score](/media/together.pdf) if you like.
<div style="text-align: center"><iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/OWtjESI2RsM?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen style='display: inline-block; margin: 0.4em;'></iframe></div>
<p> </p>
##### West 40
I was asked by a friend for a 40 second musical piece that matched the famous mood and feel in [the theme for Westworld](https://youtu.be/rYelEUVQ50g).
[West 40](/media/west40.m4a "play: West 40") was written as a simplified mood version that leaves more room for the video than the theme that inspired it.
Now, Westworld's theme is beautiful and smart. <NAME> wrote a wonderful piece. It's multi-layered and moving and full of story. I wondered - how could I compress that into 40 seconds?
Moreover, the piece of music was for a class and they would edit to my music (instead of the other way around), which meant I didn't have any picture to start with. Also, I didn't have enough time to find a Dobro for that beautiful metallic sound.
I must say, it was a fun challenge and I hope you enjoy it too.
## Notes
When playing the songs or videos, it might take a bit for the player to load the data.
If you want to play a song directly, right click and open the link in a new tab.
<file_sep>---
layout: layouts/layout.erb
---
# <NAME> - When a Student turns 40

Now a Singer/Songwriter and producer, I was a scuba diving instructor, a lawyer, a tantric, a soldier and a Buddhist. I traveled all the continents except the warmest (Africa) and the coldest (Antarctica)... Music is my home.
Through it all there was one thing I learned - when we follow our inner voice, when we listen closely to the whispering of our hearts, we increase our capacity for compassion, happiness and a meaningful life.
I believe musical expression can bring our innermost truths to light.
I’m happy to share my music with you. I hope my music and experiences give you insight into your own journey.
## My Music
I haven't published any of the music I perform with. However, here's a few private artist demos (demos I made for band members), click to play:
* [Silver Dreams (original, solo)](/media/silver_dreams.m4a "play: Silver Dreams")
* [It's Me (original, production)](/media/its_me.m4a "play: It's Me")
* [Lost Soul (original, band)](/media/lost_soul.m4a "play: Lost Soul")
* [While My Guitar Gently Weeps (cover, production)](/media/whilemyguitar.m4a "play: While My Guitar Gently Weeps")
## Contact:
I'm available at [<EMAIL>](mailto:<EMAIL>) and [(617) 642-5815](tel:6176425815)
I do my best to respond promptly to emails, texts and phone calls.
If I'm in the studio or otherwise engaged, I will do my best to get back to you as soon as the session is over.
<file_sep>---
layout: layouts/layout.erb
---
# Bo Wild - When a Student turns 40

I believe the best songs are the ones that **express our true inner voice in the most authentic way.**
Now a Singer/Songwriter and producer, I was a scuba diving instructor, a lawyer, a tantric, a soldier, a Buddhist and more things than I care to remember...
I traveled all the continents except the warmest (Africa) and the coldest (Antarctica).
This is what I learned:
#### **when we follow our inner voice, when we listen closely to the whispering of our hearts, we increase our capacity for compassion, happiness and a meaningful life**.
I’m happy to share my music with you. I hope my music and experiences give you insight into your own journey.
## Sample Songs
Here are a few private links in case you wonder about what I've been working on.
Thank you for listening to my vocals. I'm no vocalist by any stretch, but I chose to attempt the vocal lines so I could better understand the vocalist's perspective.
**Originals** (100% me: written, played, sung and mixed):
* [It's Me (original, production demo)](/media/its_me.m4a "play: It's Me")
* [Turned Gray (original, mock-up demo)](/media/turned_gray.m4a "play: Turned Gray")
* [Lost Soul (original, studio band)](/media/lost_soul.m4a "play: Lost Soul")\*
<div style='font-size:0.8em'>* Recorded with Hinako Sato (Piano), Yoshihi Yamada (Bass) and Renato Milone (Drums).</div>
**Co-Writes**:
[<NAME>](https://www.facebook.com/alida.mckeon) is a wonderful singer/songwriter enamored with the Jazzy style of the American Songbook.
In our co-writing session I couldn't help but connect to her love for the style and an AABA standard style song was born.
* [The Note You Left (original, piano-vocal from the room)](/media/the_note_you_left.m4a "play: The Note You Left")
**Piano Demos**:
I usually don't show my earlier sketches, but this one is a little special to me:
* [Silver Dreams (original, piano demo)](/media/silver_dreams.m4a "play: Silver Dreams")
**Covers** (100% me: arranged, composed and mixed):
* [While My Guitar Gently Weeps (cover, production)](/media/whilemyguitar.m4a "play: While My Guitar Gently Weeps")\*
<div style='font-size:0.8em'>* Written by <NAME> (The Beatles), vocals by <a href='https://www.facebook.com/ami.michalp'><NAME></a>.</div>
## Sample Commercial Scores
The following links are to commercial scores that I composed and produced during my studies at Berklee (class assignments)
They all sound different, showcasing my approach to discovering the inner voice of the artists I work with (in this case, the inner voice behind the products).
<iframe width="280" height="158" src="https://www.youtube-nocookie.com/embed/fe_fmv08qNs?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen style='display: inline-block; margin: 0.4em;'></iframe><iframe width="280" height="158" src="https://www.youtube-nocookie.com/embed/lG8oFVgCxc0?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen style='display: inline-block; margin: 0.4em;'></iframe><iframe width="280" height="158" src="https://www.youtube-nocookie.com/embed/2CA8BR_boqo?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen style='display: inline-block; margin: 0.4em;'></iframe><iframe width="280" height="158" src="https://www.youtube-nocookie.com/embed/sa4cFCnTn2c?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen style='display: inline-block; margin: 0.4em;'></iframe>
[iPad Commercial](https://youtu.be/fe_fmv08qNs) | [Rebook Commercial](https://youtu.be/lG8oFVgCxc0) | [Purina Commercial](https://youtu.be/2CA8BR_boqo) | [Cheetos Commercial](https://youtu.be/sa4cFCnTn2c)
## Contact:
I'm available at [<EMAIL>](mailto:<EMAIL>) and [(617) 642-5815](tel:6176425815)
I do my best to respond promptly to emails, texts and phone calls.
If I'm in the studio or otherwise engaged, I will do my best to get back to you as soon as the session is over.
Please note I might be abroad during May and June and allow for a response time of up to a two days.
---
## CV (Curriculum Vitae)
I know you asked for one, but it's quite hard to cover more than 20 years of wondering. Besides, none of the official information is music related since music was a hobby until I decided to liquidate my law firm and leave the country of my ancestors (Israel).
My longest stretch at a single profession was a 10 year haul as a Lawyer. Between 2004 and 2014 I worked as a paralegal, an intern, a lawyer and eventually a managing partner at a litigation firm in Tel Aviv... although I worked a number of jobs during that time as well as spent a number of months in China and Thailand to study Yoga and eastern meditation techniques.
I used to code for a while (mostly in C, Ruby and JavaScript). I only mention this because it's something I did on and off for a long time. I am still [active in the community](https://stackoverflow.com/users/4025095/myst) and I still [manage a number of open source projects](https://github.com/boazsegev).
I had other professions, some more honorable than others, but I was rarely employed. I was almost always a freelancer.
I spent 1996-1998 in the IDF (Israeli Defense Force) and spent the year after re-learning to walk due to a spinal injury. Fun times... but I left with a solid understanding of the energetic body and spiritual healing practices (I refused to have an army doctor cut me open and mess with my spine).
I always thought that once I made enough money (which, as my parents explained, wasn't something artists do), I will retire and devote my life to music and arts.
I guess I got here earlier than anyone thought... yet I bemoan my lost years. Money is a beautiful facilitator, but it isn't a goal onto itself.
---
<file_sep>---
layout: layouts/layout.erb
---
# Piano Stories - Bo Wild

I believe music can change the world. Music can set us free.
Music is the language of our souls. The stories we share through music speak to the heart.
The stories we share through music bring people together and fill us with compassion, happiness and joy.
I’m excited to share my music with you.
## My Music
As a singer / songwriter my music focuses on stories. Influenced by The Beatles, the Blues, and American Country music, my style is easy to listen to and relaxed. Here are examples from songs I might sing:
* [Hunger and Need (original)](/media/hunger_and_need.m4a "play: Hunger and Need")
* [Silver Dreams (original, solo)](/media/silver_dreams.m4a "play: Silver Dreams")
* [Don't Fly (original)](/media/dont_fly.m4a "play: Don't Fly")
* [Lost Soul (original, band)](/media/lost_soul.m4a "play: Lost Soul")
## Contact:
I'm available at [<EMAIL>](mailto:<EMAIL>), [Telegram](https://t.me/bo_wild) and [WhatsApp](https://wa.me/16176425815), as well as on my US number: [+1 (617) 642-5815](tel:+16176425815)
I do my best to respond promptly to texts, emails, and phone calls.
If I'm in the studio or otherwise engaged, I will do my best to get back to you as soon as the session is over.
<file_sep># Bo Wild Website repo
This repo is used to publish the [bowild.com](https://bowild.com) website. It is governed by the same terms and conditions (and license) as the website.
Thank you.
<file_sep>---
layout: layouts/layout.erb
---
# Oops...
## It seems that something went wrong. Can you try again?
<file_sep>---
layout: /layouts/layout.erb
title: Bo Wild - Producer
---
## Your Style
I believe we all have our own unique voice and style, our own unique expression.
Let's find yours.
## Your Sound
Music production is half science and half art. Also, from my experience, there's always a little dance we do at the beginning as we get to know each other and I learn more about your voice and your vision.
I was lucky enough to have amazing teachers to help me discover both the science and the art behind music production and composition. I owe much of my knowledge to amazing people such as <NAME>, <NAME>, <NAME>, <NAME>, <NAME> and many more amazing teachers.
However, my greatest teacher will be you. As we explore your voice and discover the sound you want, we will embark on a journey together where we both learn more about how we are and how we've grown.
## You Journey
My hope is that the song we produce together will be a song that expresses your growth as a musician and an artist.
I don't want to repeat what you did for your last album, I want to help you take your next step in your journey in a way that is authentic and true to your own voice.
## Your Roots
Before we can start exploring your next step as an artist, I will need to learn more about the artist you are, your inspirations, the music of your youth, your past albums and favorite songs.
I will ask that you send me a playlist of the songs that inspired you. This can be anything, from Beatles to Metallica or anything in between.
My intention isn't just to learn who you are right now.
My I wish is to look at the arc of your journey as an artist so the production is custom tailored to your growing voice and vision.
It's a wonderful thing to start close to an artist you love and learn from them (I [wrote this one](/media/its_me.m4a "play: It's Me") as a Beatles influenced song), but it's important to me to write something that grows beyond your beginnings into the artist you are becoming.
<file_sep>---
layout: /layouts/layout.erb
title: Bo Wild - Songwriter
---
## Honoring Your Truth

I believe we all have our own unique voice, that we have an inner truth that we yearn to express and it is unique to who we are.
Songs I wrote for myself can be heard on [](https://music.apple.com/us/artist/bo-wild/1602428458) [](https://open.spotify.com/artist/06LFekW9oLivQ96QMf2RcH) [](https://music.youtube.com/playlist?list=OLAK5uy_mk6iRCKmpjBGdbjl3oaRKNTM7iFuLbxNo) [](https://music.yandex.com/artist/15535336)
## Focusing Your Expression
There is something very intimate about writing a song.
I was lucky and privileged enough to spend a few years learning with amazing teachers and songwriting masters such as <NAME>, <NAME>, <NAME>, Scarlet Keys and many more that I hold dear and close to my heart.
I am thrilled to be the humble vessel through which their knowledge and tools can be shared during our time together.
These amazing ideas and tools offer a wonderful opportunity to focus your lyrics and melody and to help the telling of your story.
I will never force my opinions - after all, **I'm here to serve your vision**. However, I am very happy to share these tools with you.
## Songs
The following are some rough demos for songs I enjoyed writing.
I hope you enjoy listening to these songs as much as I enjoyed writing them.
##### Hunger and Need
Some stories are hard to talk about, but, somehow, they leak into my music and come out in song.
This song is dedicated to all the people out there who want to overcome their own misfortune through their own effort, and to the people watching from the sideline wishing they could help.
[**Hunger and Need (a Smile at a Time)** / Me](/media/hunger_and_need.m4a "score: Hunger and Need")
Lyrics, Composition, Production and Performance: Bo Wild
> **V.1**
>
> She cooks for me with flames of passion,
>
> She knows just what I need to taste,
>
> Truth is hard to swallow,
>
> I taste the price of our disgrace.
> **V.2**
>
> To save our hearts I sell for dollars
>
> My slice of life per day and night
>
> Even god can't save me
>
> If other men can steal her light
> **Pre.**
>
> From the shadows I watch her dance,
>
> She’s not dancing for me
> **Ch.**
>
> Selling our souls, a smile at a time
>
> She suffers it all, a smile at a time
>
> I'm losing my mind, a smile at a time
>
> A slave to my hunger and need
> **V.3**
>
> With every breathe she's loosing thunder
>
> Her laughing eyes are turning gray
>
> I'm losing all I ever wanted
>
> I cry as she slips away
> **Pre.**
>
> From the shadows I watch her dance,
>
> She’s not dancing for me
> **Ch.**
>
> Selling our souls, a smile at a time
>
> She suffers it all, a smile at a time
>
> I'm losing my mind, a smile at a time
>
> A slave to my hunger and need
> **Br.**
>
> I blame the skies and curse the heavens,
>
> Their judgment cruel with righteous pride
>
> They judge the way she sold her body,
>
> But I’m the one who can’t provide
>
> Yes, I’m the one who can’t provide
> **Ch.**
>
> Selling our souls, a smile at a time
>
> She suffers it all, a smile at a time
>
> I'm losing my mind, a smile at a time
>
> A slave to my hunger
>
> It's taking it's toll, a smile at a time
>
> A dollar and pole, a smile at a time
>
> She's breaking my heart, a smile at a time
>
> A slave to my hunger and need
>
> A slave to my hunger and need
>
##### More Than I Can Say (Words I Learned)
Some emotions don't fit inside the words we learned to say.
[**More Than I Can Say** / Me](/media/more_than_i_can_say.m4a "play: More Than I Can Say")
Lyrics, Composition, Production and Performance: Bo Wild
> **V.1**
>
> Girl tonight I'll take you by the hand and make you shine
>
> Dancing in the park with summer stars
>
> Sitting on a wooden bench and swimming in your eyes
>
> Watching while the world just strolls on by
> **Ch.**
>
> Don't you know I love you more than I could say, love
>
> Words I learned refuse to say enough.
>
> Don't you know I love you more than I could say
>
> Let me whisper with my touch
> **V.2**
>
> Move a little closer I don't want to say goodbye
>
> Let me heal my scars in your embrace
>
> Let me taste your kindness with my hands around your waist
>
> Can't you feel us falling in to grace?
> **Ch.**
>
> Don't you know I love you more than I could say, love
>
> Words I learned refuse to say enough.
>
> Don't you know I love you more than I could say
>
> Let me whisper with my touch
> **Br.**
>
> I never thought you'd love me
>
> You're more than I deserve.
> **Ch.**
>
> Don't you know I love you more than I could say, love
>
> Words I learned refuse to say enough.
>
> Don't you know I love you more than I could say
>
> Let me whisper with my touch
>
> I love you
##### It's Me
For years I was in love with a girl who couldn't care enough to acknowledge my existence. I was 6 years old when she stole my heart and more than 13 years old before I reclaimed it.
I think we all go through that at some point in our lives. I just had to do it more than once... High school was much the same with a different girl and my adult life took a while to improve.
I was luck enough to analyze the works of the Beatles and their amazing songwriting skills with Prof. <NAME>.
During our work, I wrote this song inspired by my own story and some of the techniques employed by <NAME> and <NAME>.
[**It's Me** / Me](/media/its_me.m4a "score: It's Me")
Lyrics, Composition, Production and Performance: Bo Wild
> **V.1.**
>
> I guess it’s true,
>
> what they all said,
>
> He wasn’t true, he made you sad
>
> But don’t you know there’s someone
>
> that you can always count on
>
> Oh don’t you know? It's me.
> **V.2.**
>
> So many years I loved you, but I never said
>
> These hopes and fears inside me, and all the tears I shed
>
> Oh, all this time together
>
> And still you don’t know better
>
> How don’t you know? It's me. It's ...
> **Br.**
>
> Me that hears your cries, in the silence of the night
>
> I share your sighs, your lows, your highs
>
> and you should know,
>
> I loved you, since I met you, on that night in New Years Eve,
>
> This love will never fade or leave
> **Br.2.**
>
> This love, this love, this love, this love
>
> This love will never die
> **V.3.**
>
> The day will come and you will see,
>
> That this old heart is all you need
>
> One day we'll be together
>
> And things will just get better
>
> The day you'll know, it's me.
##### I Close my Eyes (broken on the floor)
It so hard for me to give up on relationships.
I know, in my __head__, that sometimes it just doesn't fit... but in my __heart__, it's so hard to let go.
[**I Close my Eyes (broken on the floor)** / Me (demo)](/media/i_close_my_eyes_demo.m4a "play: I Close My Eyes")
> **V.1**
>
> Sweet, sweat on cotton sheets
>
> I lost my heart in winter storms
>
> Outside snow, inside we felt the heat
>
> Now it's broken on the floor
> **V.2**
>
> Scrambled eggs and little lies
>
> Monday mornings in the spring
>
> Stolen flowers you kissed along the way
>
> Left us broken on the floor
>
> Broken on the floor
> **Ch.**
>
> I close my eyes
>
> Don't wanna see no lies
>
> They keep me here, still holding on
>
> I close my eyes
>
> (and) Watch as our love dies
>
> I know it's time to let it go
>
> Should let it go
> **V.3**
>
> Desperate heat through summer nights
>
> On repeat we'd kiss and fight
>
> I should have gone but hope still held me tight
>
> Now it's broken on the floor
>
> Broken on the floor
> **Ch.**
>
> I close my eyes
>
> Don't wanna see no lies
>
> They keep me here, still holding on
>
> I close my eyes
>
> (and) Watch as our love dies
>
> I know it's time to let it go
>
> Should let it go
> **Br.**
>
> No this was never meant to last
>
> Still I gave it all I got
>
> God, this love of mine
>
> I wish we had more time
> **Ch.**
>
> I close my eyes
>
> Don't wanna see no lies
>
> They keep me here, still holding on
>
> I close my eyes
>
> (and) Watch as our love dies
>
> I know it's time to let it go
>
> Should let it go
> **Ch.Alt.**
>
> I close my eyes
>
> Cut away these ties
>
> Admit what our heart already know
>
> I close my eyes
>
> (and) Whisper my goodbyes
>
> I’m brave enough to let it go
>
> I let it go
##### Don't Fly
Inspired by the amazing, soul shattering, and highly recommended book ["All the Bright Places" by <NAME>](https://en.wikipedia.org/wiki/All_the_Bright_Places).
[**Don't Fly** / Me](/media/dont_fly.m4a "play: Don't Fly")
Lyrics, Composition, Production and Performance: Bo Wild
> **V.1**
>
> Standing on this roof top, arms that spread like wings
>
> Fighting this desire to take that final flight
>
> I beg for her to hear me over the sound of all our fears
> **Pre.1**
>
> I sing away the darkness
>
> Try to hold the sky
>
> The world is too big
>
> She holds me as she cries
> **Ch**
>
> Please, don't fly
>
> Please, don't fly
>
> Please, don't fly
>
> Don't fly
>
> Don't
> **V.2**
>
> There 're days when we are golden, rainbow footsteps where we run
>
> There 're days when we are fearless, lifting fists against the sun
>
> But now the smiles are failing, there's a wall behind these eyes.
> **Pre.2**
>
> I sing away the darkness
>
> Try to hold the sky
>
> Never show my weakness
>
> And struggle as she cries
> **Ch**
>
> Please, don't fly
>
> Please, don't fly
>
> Please, don't fly
>
> Don't fly
>
> Don’t
> **Br.1**
>
> God, I don't know what I'm doing.
>
> This pain is written in my bones.
>
> I don't want my pain to touch her.
>
> Can't she see I'm not that strong?
>
> As she whispers to hold on
> **V.3**
>
> I'm standing in this shadow, where pain and troubles hum and ring
>
> And my shadow's tilting falling, she wants to fight but she can't win
>
> I'm bending on this rooftop, my arms are golden wings
> **Br.2**
>
> I am different
>
> I’m an outcast
>
> My only home is in her smile
>
> She’s my shelter
>
> She’s my heart beat
>
> I hear it's rhythm, soft and wild
>
> Whispering
> **Ch**
>
> Please, don't fly
>
> Please, don't fly
>
> Please, don't fly
>
> Don't fly
>
> Don’t
>
> Please, don't fly
>
> Please, don't fly
>
> Please, don't fly
>
> Don't fly
>
> Don’t
>
> Fly
##### Turned Gray
I love animation movies, like Finding Nemo and Toy Story. I don't know what it is, but somehow the adult in me is torn be these little stories.
And the opening of the film Up was one I couldn't easily let go of... and this is how this song was born.
[**Turned Gray** / Me](/media/turned_gray.m4a "score: Turned Gray")
Lyrics, Composition, Production and Performance: Bo Wild
> **V.1.**
>
> Small broken dreams, we left by the stream,
>
> With our childhood and younger days
>
> Promises made, were stolen away,
>
> Time flowing on it’s way
>
> By time twisting years that stray.
>
> Sitting right here, as days turn to years,
>
> I wonder you never say,
>
> That all the dreams we promised, turned gray
> **V.2.**
>
> Holding our hands, through decades that bend
>
> I still have so much to say
>
> Our old childhood dreams, are torn at the seams
>
> I doubt if we'll see them one day
>
> Worn kitchen chairs, slumped wooden stairs,
>
> Consumed by an old routine.
> **Br.**
>
> On slow afternoons at home (Home with you)
>
> Curled by the TV screen (You’re in my arms)
>
> It's better than any dream or adventure I'd known,
>
> Oh...
> **V.3.**
>
> Christmas tree lights, still shining bright,
>
> We bought them so long ago
>
> You gift me this book, of peter and hook
>
> Wrapped in your love and a bow
>
> Though we grow old, walking this road
>
> Please know that for me it's okay
>
> That all the dreams we promised, turned gray
##### Lost Soul
[Lost Soul](/media/lost_soul.m4a "score: Lost Soul") is one I am quietly in love with. There's a million songs about "_boy meets girl at bar and never sees here again_", but this story is my story, which makes it a bit more personal... at least for me.
[**Lost Soul** / Me](/media/lost_soul.m4a "score: Lost Soul")
**Piano**: [Hinako Sato](https://www.hinakosato.com)
**Bass**: <NAME>
**Drums**: [Renato Milone](https://www.renatomilone.com)
Lyrics, Composition, Production and Performance: Bo Wild
> **V.1.**
>
> She stood in the spotlight, with an old stained guitar
>
> Teasing a song
>
> as I watched from the bar
>
> She was clouds on the horizon,
>
> Trouble on the breeze
>
> And she had me
>
> on my knees
> **Ch.**
>
> She was a lost soul
>
> Shouldn’t give my heart
>
> Knew it from the start
>
> She was a lost soul
>
> Lost soul
>
> Lost Soul
> **V.2.**
>
> Her shattered breath
>
> Went under my guard
>
> With her soft voice
>
> She hit me quite hard
>
> She was the cry of thunder drums
>
> Lightning on high seas
>
> And she had me
>
> on my knees
> **Ch.**
>
> She was a lost soul...
> **Br.**
>
> I had this need to save her,
>
> Saving her just might save me,
>
> But I heard it in that moment,
>
> in her graceful movement,
>
> I knew that it could never be
> **Ch.**
>
> She was a lost soul...
> **V.3.**
>
> She broke my heart
>
> And left me that night
>
> It's been a while
>
> But I still crave her light
>
> She was summer dream in winter
>
> A kiss of fire as I freeze
>
> And she had me
>
> on my knees
> **Ch.**
>
> She was a lost soul...
##### Morning Sunshine
Some songs I never got to record properly... but when I have some free time, I would love to take them back in to the studio and make a proper demo.
Morning Sunshine is definitely one of the songs I want to record.
It's sweet and honest and I wrote it during one of those magical moods when I was beginning to fall in love, just before loosing my balance and crashing.
Anyway, I even [have a score](/media/morning_sunshine.pdf), ready for when I can record it.
[**Morning Sunshine** / Me](/media/morning_sunshine.pdf)
> **V.1**
>
> Sunday morning,
>
> we’re still in bed
>
> I hear her mumble
>
> Her curls all tumble on my chest
> If I'm dreaming? (is he dreaming?)
>
> If she’s not here
>
> Oh morning sunshine, (morning sun_shine)
>
> please disappear
> **V.2**
>
> If she wakes up
>
> Oh, if she leaves
>
> I’ll be lonely (so lonely___)
>
> Oh, I would plainly lose my mind
> Now she’s sleeping,
>
> So don’t come near,
>
> Oh morning sunshine, (oh ooo___)
>
> please disappear (disappear)
> **Br.**
>
> Before I met her
>
> My nights were always blue
>
> Empty evenings,
>
> Each time with someone new
> The day I met her
>
> She stole away my heart
>
> I damn the daytime
>
> That's keeping us apart
> **V.3**
>
> Monday morning,
>
> I’m off to work
>
> She said she’ll meet me (oh yeah)
>
> I’ll pick her up right after dark
> I can’t wait, no
>
> To see my dear (at night together)
>
> Oh morning sunshine,
>
> please disappear
<file_sep>---
layout: layouts/layout.erb
---
# Terms and Conditions
By visiting and/or viewing and/or listening to this website (website herein: including any content, media, music, video, words, etc' and/or part thereof, and including the servers and/or services storing this website and/or part thereof), you agree that:
1. You are either a friend or a potential client.
1. All the content of this website is presented to you for your critique and/or review, as part of my personal portfolio, and only for this purpose and as part of this context.
1. No part of this website presented will be considered as a "public performance" of said content.
1. This website does **not** change the status of any media presented (for example, the songs and creative content remain unpublished unless they were published elsewhere).
1. You will respect all the copyrights, performance rights and any other rights related to this website (and/or any of it's content) and/or the people who have created it.
1. You will not download any content from (or copies of) this website (in part or in whole) except as temporary copies to be used in accordance with these terms and conditions and in accordance with the law.
Thank you for your understanding.
© Copyright <NAME> (aka. Bo Wild), 2017-2020.
<file_sep>---
layout: /layouts/layout.erb
title: Holy Wine (Unplugged Recital) - Bo Wild
background: /images/recital.jpg
---
# Holy Wine / Bo Wild
## [March 28th, 2017, 7:00pm EST](holy_wine.ics)
<div style='text-align:left; padding:0 0 0 10%;' data-play:"go">
There was sweetness in your journey,<BR />
But there was sour sadness too.<BR />
For a moment rest your burden,<BR />
Though your journey isn't through.
</div>
* [Live: <NAME>vin Recital Hall, 1140 Boylston Street, Boston, MA](https://maps.google.com/maps?q=1140+Boylston+Street,+Boston,+MA,+02215,+United+States).
* [Streamed: <EMAIL>](http://www.ustream.tv/channel/berklee-colvin)
I [invite you](holy_wine.ics) to a bitter sweet evening for slow reflection and slower songs.
There will be solo acoustic versions for [old favorits](/media/lost_soul2.m4a "play: Lost Soul") as well as some younger (newer) songs.
## Unplugged
On stage it will just be me. Open, exposed, with no one to hide behind, playing the acoustic piano or my steel string guitar.
I'm as Wild as a summer breeze on winter shores - uncultivated and kind.
My name is <NAME>, but you can call me Bo.
## With a little help from...
Off stage, wonderful and kind, you, my friends, rooting for me from the crowd and behind computer screens across the globe. You are the shining, bright souls that made this world the amazing place it is.
With special thanks to The Berklee College Of Music.
## Extra Credits
The teaser song you're listening to was recorded with <NAME> (Piano), <NAME> (Bass) and <NAME> (Drums).
The recital will start with a guest performance of the song "The Note You Left", performed by <NAME> with whom I co-wrote the song.
During the recital, I will probably perform the song "Anneanne", co-written with <NAME>.
During the recital, I might also perform the song "Nightmare", co-written with Alec (<NAME>.
<a href='https://www.berklee.edu/events/bo-wild-holy-wine' style='font-size: 0.7em'>The official Berklee event page</a>
<file_sep>---
layout: /layouts/layout.erb
title: Bo Wild - Artist - Piano Stories
_background: /images/recital.jpg
---
## Piano Stories
### Music is Love

Now a Singer/Songwriter and producer, I was a scuba diving instructor, a lawyer, a tantric, a soldier and a Buddhist. I traveled all the continents except the warmest (Africa) and the coldest (Antarctica)... **Music is my home**.
Through it all there was one thing I learned - **when we follow our inner voice, when we listen closely to the whispering of our hearts, we increase our capacity for compassion, happiness and a meaningful life**.
I believe musical expression can bring our innermost truths to light.
Find my music @ [](https://music.apple.com/us/artist/bo-wild/1602428458) [](https://open.spotify.com/artist/06LFekW9oLivQ96QMf2RcH) [](https://music.youtube.com/playlist?list=OLAK5uy_mk6iRCKmpjBGdbjl3oaRKNTM7iFuLbxNo) [](https://music.yandex.com/artist/15535336)
Here are examples of my work:
* [I Close My Eyes (original, band)](/media/i_close_my_eyes_demo.m4a "play: I Close My Eyes")
* [Hunger and Need (original)](/media/hunger_and_need.m4a "play: Hunger and Need")
* [Silver Dreams (original, solo)](/media/silver_dreams.m4a "play: Silver Dreams")
* [Don't Fly (original)](/media/dont_fly.m4a "play: Don't Fly")
* [Lost Soul (original, band)](/media/lost_soul.m4a "play: Lost Soul")
<file_sep>/*
Copyright: <NAME>, 2017
License: MIT
Feel free to copy, use and enjoy according to the license provided.
*/
/**
The BoPlayer is a simple audio player that utilizes the HTML5 audio object
using a circular GUI player instead of the OS's player.
BoPlayer displays controls for volume (outer ring), position (middle ring) and
play / pause (inner circle).
Volume and seeking are controlled clicking / touching the BoPlayer and moving
the cursor (or finger). Double click / tap will skip forward and a triple click
/ tap will skip backwards. Keyboard control is also available.
Multiple BoPlayer instances can be initialized on a single page, allowing
multiple streams to play at the same time. However, keyboard control is limited
to a single BoPlayer instance and must be initialized for that object.
On Safari and iOS, it's impossible to control volume (seeking still works) or to
start in autoplay mode. Also only one BoPlayer instance can play at a time.
On iOS, these limitations are imposed by the OS, where volume is controlled by
the physical device and autoplay requires the user's interaction to confirm
playback (a security measure).
================================================================================
To create a BoPlayer, a "parent" DOM object is required. The player will be
drawn over the parent element matching the element's size.
After the player had been created it's possible to set the source urls for audio
playback.
Audio will begin playing automatically when enough data was downloaded, unless
the `autoplay` property was set to `false`.
i.e.
<html>
<head>
<script type="text/javascript" src='javascript/BoPlayer.js'></script>
</head>
<body>
<div id='player' style='width:100px; height:100px;'></div>
<script>
var player = new BoPlayer('player');
player.set_sources(["source.mp3", "source.ogg"]);
</script>
</body>
</html>
It's possible to add audio media to a player's playlist. Any urls added to the
playlist will be played automatically (if the file format is supported by the
player and `autoplay` wasn't disabled). i.e.:
player.playlist.push("song2.mp3");
// or, including an ogg fallback
player.playlist.push(["song2.mp3", "song2.ogg"]);
It's possible to access the undelying HTML5 audio object using the `player`
property. i.e.:
player.player.pause();
Evey time a song starts to play, the `on_play` callback is called. i.e.
player.on_play = (p) => { console.log(p.player.currentSrc); };
Once playback stops, the `on_stop` callback is called. i.e.
player.on_stop = (p) => { p.set_sources("repeat_me.mp3"); };
It's possible to enable keyboard controls using the `enable_keyboard` method.
Only one player can have control of the keyboard.
player.enable_keyboard();
*/
function BoPlayer(obj_id) {
/** Player settings. */
this.vol_background = "#557";
this.vol_color = "#99f";
this.time_background = "#756";
this.time_color = "#f9a";
this.background = "rgba(85,85,120,0.5)";
this.color = "rgba(255,120,255,0.5)";
this.on_stop = false;
this.on_play = false;
this.autoplay = false;
/** History and Playlist objects. */
this.playlist = [];
this.history = [];
/** control, double click / tap support. */
this._center_xy = {};
this._canvas_offset = {};
this._tap_count = 0;
this._state = 0;
/** Attaching the BoPlayer to the DOM. */
this.obj_id = obj_id;
this.container = document.getElementById(obj_id);
this.container.owner = this;
/** The canvas object. */
this.canvas = document.createElement('canvas');
this.canvas.owner = this;
if (!(typeof this.canvas.getContext === "function"))
alert("This web page requires an updated browser with support for HTML5.");
this.canvas.style.position = "absolute";
this.canvas.style.top = "0";
this.canvas.style.left = "0";
this.canvas.style.width = "100%";
this.canvas.style.height = "100%";
this.canvas.style.transition = "transform 0.25s";
this.canvas.style.transform = "translate(0px, 0px)";
this.container.appendChild(this.canvas);
/** The HTML5 audio player. */
this.player = document.createElement('audio');
this.player.owner = this;
this.player.controls = false;
this.player.autoplay = false;
this.player.style.position = "absolute";
this.player.style.display = "hidden";
this.player.style.top = "0";
this.player.style.left = "0";
this.player.style.width = "0px";
this.player.style.height = "0px";
this.player.volume = 0.5;
if (this.player.volume == 0.5)
this.volume_control_enabled = true;
else
this.volume_control_enabled = false;
this.player.volume = 1;
this.container.appendChild(this.player);
/** Audio event handlers. */
this.player.addEventListener("timeupdate", this.event_handlers.redraw);
this.player.addEventListener("seeked", this.event_handlers.redraw);
this.player.addEventListener("volumechange", this.event_handlers.redraw);
this.player.addEventListener("loadedmetadata", function(e) {
// console.log(e);
// e.target.owner.container.title = "";
});
this.player.addEventListener("canplaythrough", function(e) {
e.target.autoplay = e.target.owner.autoplay;
e.target.owner.can_play = true;
if (e.target.owner.autoplay) {
e.target.owner.play();
}
});
this.player.addEventListener("play", function(e) {
e.target.owner.redraw();
if (e.target.owner.on_play) {
try {
e.target.owner.on_play(e.target.owner);
} catch (err) {
console.error(err.message);
}
}
});
this.player.addEventListener("pause", function(e) {
e.target.owner.redraw();
if (e.target.owner.on_pause) {
try {
e.target.owner.on_pause(e.target.owner);
} catch (err) {
console.error(err.message);
}
}
});
this.player.addEventListener("ended", function(e) {
e.target.owner.redraw();
if (!(e.target.owner.autoplay && e.target.owner.next()) &&
e.target.owner.on_stop) {
try {
e.target.owner.on_stop(e.target.owner);
} catch (err) {
console.error(err.message);
}
}
});
/** The controller DOM layer (fullscreen event collecting). */
this.controller = document.createElement('div');
this.controller.owner = this;
this.controller.style.position = "fixed";
this.controller.style.display = "none";
this.controller.style.top = "0";
this.controller.style.left = "0";
this.controller.style.width = "100%";
this.controller.style.height = "100%";
this.controller.style["z-index"] = "99999";
document.body.appendChild(this.controller);
/** The container-controller events. */
this.canvas.addEventListener("scroll", function(e) {
console.log(e);
e.returnValue = false;
return false;
});
this.container.onmousedown = this.event_handlers.control_start;
this.container.ontouchstart = this.event_handlers.control_start;
this.container.onmouseup = this.event_handlers.control_end;
this.container.ontouchmove = this.event_handlers.control_change;
this.container.ontouchend = this.event_handlers.control_end;
this.controller.onmousedown = this.event_handlers.control_end;
this.controller.onmouseup = this.event_handlers.control_end;
this.controller.onmouseout = function(e) {
if (e.target.owner._state)
e.target.owner.event_handlers.control_end(e);
};
this.controller.onmousemove = this.event_handlers.control_change;
/** Handling the resize event when the container is device-responsive. */
if (window.javascript_player_objects == undefined) {
window.javascript_player_objects = [];
}
window.javascript_player_objects.push(this);
window.addEventListener("resize", function(e) {
var len = window.javascript_player_objects.length;
for (var i = 0; i < len; i++) {
window.javascript_player_objects[i].redraw();
}
});
/** Draw the Player. */
this.redraw();
this;
};
/** Holds the event handlers. Some are used for both touch and mouse events. */
BoPlayer.prototype.event_handlers = {};
/** a simple handler of events that only require a redraw. */
BoPlayer.prototype.event_handlers.redraw = function(
e) { e.target.owner.redraw(); };
/** When the mouse / touch starts. */
BoPlayer.prototype.event_handlers.control_start = function(e) {
e.target.owner._state = 0;
e.target.owner._vol_step = 0;
e.target.owner._seek_step = 0;
e.target.owner._center_xy.x = e.pageX;
e.target.owner._center_xy.y = e.pageY;
var box = e.target.owner.canvas.getBoundingClientRect();
e.target.owner._canvas_offset.y =
e.pageY -
Math.floor(
(e.target.owner.canvas.height / 2) + box.top +
(window.pageYOffset || document.documentElement.scrollTop ||
document.body.scrollTop) -
(document.documentElement.clientTop || document.body.clientTop || 0));
e.target.owner._canvas_offset.x =
e.pageX -
Math.floor((e.target.owner.canvas.width / 2) + box.left +
(window.pageXOffset || document.documentElement.scrollLeft ||
document.body.scrollLeft) -
(document.documentElement.clientLeft ||
document.body.clientLeft || 0));
e.target.owner.canvas.style.transform =
"translate(" + e.target.owner._canvas_offset.x + "px, " +
e.target.owner._canvas_offset.y + "px)";
window.setTimeout(function(
pl) { pl.canvas.style.transition = "transform 0s"; },
250, e.target.owner);
// make sure the player is active before allowing control state.
if (!e.target.owner.can_play) {
e.returnValue = false;
return false;
}
e.target.owner.controller.style.display = "block";
if (!e.target.owner._ctrl_interval)
e.target.owner._ctrl_interval = window.setInterval(
e.target.owner.event_handlers.control_review, 50, e.target.owner);
if (e.target.owner._last_tap && e.timeStamp - e.target.owner._last_tap < 420)
e.target.owner._tap_count++;
else
e.target.owner._tap_count = 1;
e.target.owner._last_tap = e.timeStamp;
if (e.target.owner._last_tap_timeout) {
window.clearTimeout(e.target.owner._last_tap_timeout);
e.target.owner._last_tap_timeout = false;
}
e.target.owner._last_tap_timeout = window.setTimeout(function(pl) {
if (pl._state)
return;
switch (pl._tap_count) {
case 2:
pl.next();
pl._state = 8;
pl.play();
break;
case 3:
pl.prev();
pl._state = 8;
pl.play();
break;
}
pl._tap_count = 0;
pl._last_tap_timeout = false;
}, 420, e.target.owner);
e.target.owner.redraw();
e.returnValue = false;
return false;
};
/** When the mouse / touch stops. */
BoPlayer.prototype.event_handlers.control_end = function(e) {
e.target.owner._vol_step = 0;
e.target.owner._seek_step = 0;
e.target.owner._center_xy.x = 0;
e.target.owner._center_xy.y = 0;
e.target.owner.canvas.style.transition = "transform 0.25s";
window.setTimeout(
function(pl) { pl.canvas.style.transform = "translate(0px, 0px)"; }, 10,
e.target.owner);
if (e.target.owner._ctrl_interval) {
window.clearInterval(e.target.owner._ctrl_interval)
e.target.owner._ctrl_interval = false;
}
e.target.owner.controller.style.display = "none";
if (e.target.owner._state) {
e.target.owner.play();
} else
e.target.owner.play_or_pause();
e.target.owner._state = 0;
e.returnValue = false;
return false;
};
/** Volume / seek control */
BoPlayer.prototype.event_handlers.control_change = function(e) {
e.target.owner._seek_step = (e.pageX - e.target.owner._center_xy.x) / 32.0;
if (e.target.owner.volume_control_enabled)
e.target.owner._vol_step = (e.target.owner._center_xy.y - e.pageY) / 2048.0;
e.target.owner.canvas.style.transform =
"translate(" +
(e.target.owner._canvas_offset.x +
Math.round((e.pageX - e.target.owner._center_xy.x) / 2)) +
"px, " +
(e.target.owner._canvas_offset.y +
Math.round((e.pageY - e.target.owner._center_xy.y) / 2)) +
"px)";
e.target.owner.redraw();
e.returnValue = false;
return false;
};
BoPlayer.prototype.event_handlers.control_review = function(pl) {
/** Volume control */
if (pl._vol_step >= 0.0075) {
pl._state |= 4;
pl._state |= 8;
pl.volume_up(pl._vol_step);
} else if (pl._vol_step <= -0.0075) {
pl._state |= 4;
pl._state |= 8;
pl.volume_down(0 - pl._vol_step);
} else {
pl._state &= ~4;
};
/** Seek control */
if (pl._seek_step >= 0.4) {
pl._state |= 2;
pl._state |= 8;
pl.pause();
// pl.play();
pl.step_forward(pl._seek_step);
} else if (pl._seek_step <= -0.4) {
pl._state |= 2;
pl._state |= 8;
pl.pause();
// pl.play();
pl.step_back(0 - pl._seek_step);
} else if (pl._state & 2) {
pl._state &= ~2;
pl.play();
};
};
/** Draws the volume (outer ring). */
BoPlayer.prototype.draw_volume = function() {
var context = this.canvas.getContext('2d');
var radius_limit = Math.min(this.canvas.height, this.canvas.width);
// Draw background
context.beginPath();
context.strokeStyle = this.vol_background;
context.lineWidth = Math.floor(radius_limit * 0.05);
context.arc(this.canvas.width * 0.5, this.canvas.height * 0.5,
radius_limit * 0.4, 0.75 * Math.PI,
0.75 * Math.PI + (2 * Math.PI * 1));
context.stroke();
// Draw volume value
if (this.player.volume > 1)
this.player.volume = 1;
if (this.player.volume < 0)
this.player.volume = 0;
context.beginPath();
context.strokeStyle = this.vol_color;
context.lineWidth = Math.floor(radius_limit * 0.04);
context.arc(this.canvas.width * 0.5, this.canvas.height * 0.5,
radius_limit * 0.4, 0.75 * Math.PI,
0.75 * Math.PI + (2 * Math.PI * this.player.volume * 0.75));
context.stroke();
};
/** Draws the playhead position (middle ring). */
BoPlayer.prototype.draw_time = function() {
var context = this.canvas.getContext('2d');
var radius_limit = Math.min(this.canvas.height, this.canvas.width);
var time = 0.0;
if (!isNaN(this.player.duration) && this.player.duration > 0) {
time = player.player.currentTime / this.player.duration;
}
// Draw background
context.beginPath();
context.strokeStyle = this.time_background;
context.lineWidth = Math.floor(radius_limit * 0.05);
context.arc(this.canvas.width * 0.5, this.canvas.height * 0.5,
radius_limit * 0.3, 0.75 * Math.PI,
0.75 * Math.PI + (2 * Math.PI * 1));
context.stroke();
// Draw time value
context.beginPath();
context.strokeStyle = this.time_color;
context.lineWidth = Math.floor(radius_limit * 0.04);
context.arc(this.canvas.width * 0.5, this.canvas.height * 0.5,
radius_limit * 0.3, 0.75 * Math.PI,
0.75 * Math.PI + (2 * Math.PI * time * 0.75));
context.stroke();
};
/** Draws the Play / Pause state (inner circle). */
BoPlayer.prototype.draw_state = function() {
var context = this.canvas.getContext('2d');
var radius_limit = Math.min(this.canvas.height, this.canvas.width);
// Clear & Draw background
// clear current frame
context.clearRect(0, 0, this.canvas.width, this.canvas.height);
context.beginPath();
context.strokeStyle = this.background;
context.fillStyle = this.background;
context.lineWidth = radius_limit * 0.05;
context.arc(this.canvas.width * 0.5, this.canvas.height * 0.5,
radius_limit * 0.25, 0.75 * Math.PI,
0.75 * Math.PI + (2 * Math.PI * 1));
// context.stroke();
context.fill();
// Draw content
if (this._center_xy.x) {
// draw controls
if (this._state == 0) {
// pause / play control
context.beginPath();
context.strokeStyle = this.color;
context.fillStyle = this.color;
context.lineWidth = radius_limit * 0.03;
context.arc(this.canvas.width * 0.5, this.canvas.height * 0.5,
radius_limit * 0.1, 0.75 * Math.PI,
0.75 * Math.PI + (2 * Math.PI * 1));
context.fill();
}
if (this._vol_step >= 0.0075) {
// volume up
context.beginPath();
context.strokeStyle = this.vol_color;
context.fillStyle = this.vol_color;
context.lineWidth = radius_limit * 0.05;
context.arc(this.canvas.width * 0.5, this.canvas.height * 0.5,
radius_limit * 0.25, 1.25 * Math.PI,
1.25 * Math.PI + (2 * Math.PI * 0.25));
context.lineTo(this.canvas.width * 0.5, this.canvas.height * 0.5);
context.fill();
} else if (this._vol_step <= -0.0075) {
// volume down
context.beginPath();
context.strokeStyle = this.vol_color;
context.fillStyle = this.vol_color;
context.lineWidth = radius_limit * 0.05;
context.arc(this.canvas.width * 0.5, this.canvas.height * 0.5,
radius_limit * 0.25, 0.25 * Math.PI,
0.25 * Math.PI + (2 * Math.PI * 0.25));
context.lineTo(this.canvas.width * 0.5, this.canvas.height * 0.5);
context.fill();
};
if (this._seek_step >= 0.4) {
// seek forward
context.beginPath();
context.strokeStyle = this.time_color;
context.fillStyle = this.time_color;
context.lineWidth = radius_limit * 0.05;
context.arc(this.canvas.width * 0.5, this.canvas.height * 0.5,
radius_limit * 0.25, 1.75 * Math.PI,
1.75 * Math.PI + (2 * Math.PI * 0.25));
context.lineTo(this.canvas.width * 0.5, this.canvas.height * 0.5);
context.fill();
} else if (this._seek_step <= -0.4) {
// seek backward
context.beginPath();
context.strokeStyle = this.time_color;
context.fillStyle = this.time_color;
context.lineWidth = radius_limit * 0.05;
context.arc(this.canvas.width * 0.5, this.canvas.height * 0.5,
radius_limit * 0.25, 0.75 * Math.PI,
0.75 * Math.PI + (2 * Math.PI * 0.25));
context.lineTo(this.canvas.width * 0.5, this.canvas.height * 0.5);
context.fill();
};
} else if (this.is_playing()) {
// draw "playing" state
context.beginPath();
context.strokeStyle = this.color;
context.moveTo(radius_limit * 0.4, radius_limit * 0.65);
context.lineTo(radius_limit * 0.4, radius_limit * 0.35);
context.stroke();
context.beginPath();
context.strokeStyle = this.color;
context.moveTo(radius_limit * 0.6, radius_limit * 0.65);
context.lineTo(radius_limit * 0.6, radius_limit * 0.35);
context.stroke();
} else {
// draw "paused" state
context.beginPath();
context.strokeStyle = this.color;
context.moveTo(radius_limit * 0.4, radius_limit * 0.65);
context.lineTo(radius_limit * 0.6, radius_limit * 0.5);
context.lineTo(radius_limit * 0.4, radius_limit * 0.35);
context.stroke();
};
};
/** sets playback volume within the range of 0..1 (i.e. 0.75).*/
BoPlayer.prototype.set_volume = function(volume) {
if (volume > 1)
volume = 1;
if (volume < 0)
volume = 0;
this.player.volume = volume;
this.draw_volume();
};
/** returns the playback volume within the range of 0..1.*/
BoPlayer.prototype.get_volume = function(volume) { return this.player.volume; };
/**
Sets the current source for playback and resumes playback (if playing).
It's possible to set fallback sources by passing an array of strings instead of
a single string.
*/
BoPlayer.prototype.set_sources = function(sources) {
// clear existing sources.
while (this.player.firstChild) {
this.player.removeChild(this.player.firstChild);
}
if (!sources) {
this.player.src = "";
this.player.load();
return;
}
// set playback flag
this.can_play = false;
// add requested sources.
if (typeof (sources) == typeof (""))
sources = [ sources ];
else if (typeof (sources) == typeof ([]) && (sources instanceof Array)) {
console.error(
"player sources should be either a string or an array, but got",
sources);
}
var unset = true;
for (var i = 0; i < sources.length; i++) {
if (typeof (sources[i]) == typeof ('')) {
var tmp = document.createElement('source')
tmp.src = sources[i];
this.player.appendChild(tmp);
if (unset) {
this.player.src = sources[i];
unset = false;
}
}
}
// clear title
this.container.title = '';
// load
this.player.autoplay = this.autoplay;
this.player.load();
if (this.autoplay)
this.player.play();
};
/** returns the playback state. */
BoPlayer.prototype.is_playing = function() { return (!this.player.paused); };
/** a flag indicating if enough data was downloaded for continuous playback. */
BoPlayer.prototype.can_play = false;
/** Starts playback. Uses playlist / history data if available. */
BoPlayer.prototype.play = function() {
this.autoplay = true;
this.player.autoplay = true;
if (this.player.childElementCount == 0) {
if (this.playlist.length > 0) {
return this.next();
} else if (this.history.length > 0) {
var tmp = this.playlist;
this.playlist = this.history;
this.history = tmp;
return this.next();
}
return false;
}
this.player.play();
this.redraw();
return true;
};
/** pauses playback. */
BoPlayer.prototype.pause = function() {
this.player.pause();
this.autoplay = false;
this.player.autoplay = false;
this.redraw();
};
/** inverts the playback state. */
BoPlayer.prototype.play_or_pause = function() {
if (this.player.paused)
this.play();
else
this.pause();
};
/** nudges the volume up. */
BoPlayer.prototype.volume_up = function(step) {
if (!step || step >= 1)
step = 0.1;
if (this.player.volume > (1 - step))
this.player.volume = 1;
else
this.player.volume += step;
};
/** nudges the volume down. */
BoPlayer.prototype.volume_down = function(step) {
if (!step || step >= 1)
step = 0.1;
if (this.player.volume < step)
this.player.volume = 0;
else
this.player.volume -= step;
};
/** nudges the playhead forward. */
BoPlayer.prototype.step_forward = function(step) {
if (!step)
step = 5;
var time = player.player.currentTime
var dur = this.player.duration;
if (dur == 0)
return;
if (dur - time <= step)
time = dur - 0.1;
else
player.player.currentTime = time + step;
};
/** nudges the playhead backwards. */
BoPlayer.prototype.step_back = function(step) {
if (!step)
step = 5;
var time = player.player.currentTime
var dur = this.player.duration;
if (dur == 0)
return;
if (time <= step)
player.player.currentTime = 0;
else
player.player.currentTime = time - step;
};
/** plays the previous source, if available. */
BoPlayer.prototype.prev = function() {
if (this.player.currentSrc)
this.playlist.unshift(this.player.currentSrc);
this.set_sources(this.history.pop());
this.redraw();
return (this.player.childElementCount > 0);
};
/** plays the next source, if available. */
BoPlayer.prototype.next = function() {
if (this.player.currentSrc)
this.history.push(this.player.currentSrc);
this.set_sources(this.playlist.shift());
this.redraw();
return (this.player.childElementCount > 0);
};
/** enables keyboard control for the player. */
BoPlayer.prototype.enable_keyboard = function() {
document.BoPlayer_keyboard_control = this;
if (document.BoPlayer_keyboard_control_enabled)
return;
document.BoPlayer_keyboard_control_enabled = true;
document.addEventListener('keydown', function(e) {
if (!document.BoPlayer_keyboard_control ||
document.activeElement.tagName == 'INPUT' ||
document.activeElement.tagName == 'TEXTAREA')
return true;
switch (e.keyCode) {
case 32: // space - play / pause
document.BoPlayer_keyboard_control.play_or_pause();
e.preventDefault();
break;
case 78: // "n"
document.BoPlayer_keyboard_control.next();
break;
case 80: // "p"
document.BoPlayer_keyboard_control.prev();
break;
}
if (!document.BoPlayer_keyboard_control.is_playing())
return true;
switch (e.keyCode) {
case 13: // enter - seek to top
document.BoPlayer_keyboard_control.step_back(10000);
break;
case 37: // right arrow
document.BoPlayer_keyboard_control.step_back();
break;
case 39: // left arrow
document.BoPlayer_keyboard_control.step_forward();
break;
case 38: // up arrow
document.BoPlayer_keyboard_control.volume_up();
break;
case 40: // down arrow
document.BoPlayer_keyboard_control.volume_down();
break;
}
e.preventDefault();
return false;
});
};
/** disables keyboard controls. */
BoPlayer.prototype.disable_keyboard =
function() { document.BoPlayer_keyboard_control = false; };
/** redraws the player. */
BoPlayer.prototype.redraw = function() {
// set the correct size
this.canvas.width = this.canvas.offsetWidth;
this.canvas.height = this.canvas.offsetHeight;
// draw details
this.draw_state();
this.draw_volume();
this.draw_time();
};
<file_sep>---
layout: layouts/layout.erb
title: Sprout Recital - Bo Wild
background: /images/recital.jpg
---
# The Sprout Recital
## Oct. 19th, 2017, 4pm EST
<div style='text-align:left; padding:0 0 0 10%;' data-play:"go">
Before the tall oaks could kiss the clouds,<BR />
Before their roots ever entered the earth's womb,<BR />
They were all just little sprouts,<BR />
Shorter than a flower's bloom.
</div>
* [Live: <NAME>vin Recital Hall, 1140 Boylston Street, Boston, MA](https://maps.google.com/maps?q=1140+Boylston+Street,+Boston,+MA,+02215,+United+States).
* [Streamed: <EMAIL>](http://www.ustream.tv/channel/berklee-colvin)
Every musician has an origin story, the first time they took a step into the spotlights of center stage and played their hearts to the world.
This October, my origin story begins.
I will step into the [spotlight](/media/lost_soul.m4a "play: Lost Soul") to share with you original songs of my life untold and it's buried secrets.
### With a little help from...
Oaks need the softness of sunlight and the kindness of rain before they sprout. Me? I need my friends.
On stage with me you will listen to (in order of score notation):
* The Amazing Leanne Moser - vocals, guitar and joy.
* The Great Weijun Yang - guitar and soul.
* The Brilliant Gai Trax - bass and heart.
* The Distinguished Taiki Miyazawa - drums and kindness.
Off stage, wonderful and kind, are my friends, rooting for me from the crowd and behind computer screens across the globe. You will recognize them by their shine, they are all bright souls.
With sepcial thanks to The Berklee College Of Music.
## And Me
My name is <NAME>, which is a jaw breaker of a name, so people call me Bo.
I'm as Wild as a summer breeze on winter shores - uncultivated and kind.
## Extra Credits
The teaser song you're listening to was recorded with Hinako Sato (Piano), Yoshihi Yamada (Bass) and Renato Milone (Drums).
During the recital, I will probably perform the song "Nightmare", co-written with Alec (<NAME>.
<a href='https://www.berklee.edu/events/boaz-segev-bo-wild' style='font-size: 0.7em'>The official Berklee event page</a>
|
2d56b748d023397739732c623975ad7cdefcdf85
|
[
"Markdown",
"JavaScript"
] | 19
|
Markdown
|
boazsegev/website_host_wild
|
a209464e5eb083c41667814840d42b8d51aeb871
|
78661eca20ace82be7b9fd140355745bb08e49a8
|
refs/heads/master
|
<file_sep>--PARTE 1
--Crear Base de datos posts
CREATE DATABASE posts;
--Crear tabla post, con los atributos id, nombre de usuario, fecha de creación, contenido,
--descripción
CREATE TABLE post
(
id_post SERIAL PRIMARY KEY,
user_name_post VARCHAR(25),
date_of_creation_post DATE,
content_post VARCHAR(50),
description_post VARCHAR(50)
);
--Insertar 3 post, 2 para el usuario "Pamela" y uno para "Carlos"
INSERT INTO post(user_name_post, content_post, description_post) VALUES('Pamela', 'lorem ipsum...', 'lorem ipsum...'), ('Pamela', 'lorem ipsum...', 'lorem ipsum...');
INSERT INTO post(user_name_post, content_post, description_post) VALUES('Carlos', 'lorem ipsum...', 'lorem ipsum...');
--Modificar la tabla post, agregando la columna título
ALTER TABLE post ADD COLUMN title_post VARCHAR(25);
--Agregar título a las publicaciones ya ingresadas
UPDATE post SET titulo='Pamela first post' WHERE id=1;
UPDATE post SET titulo='Pamela second post' WHERE id=2;
UPDATE post SET titulo='Carlos first post' WHERE id=3;
--Insertar 2 post para el usuario "Pedro"
INSERT INTO post(user_name_post, content_post, description_post, title_post) VALUES('Pedro', 'lorem ipsum...', 'lorem ipsum...', 'pedro first post'), ('pedro', 'lorem ipsum...', 'lorem ipsum...', 'Pedro second post');
--Eliminar el post de Carlos
DELETE FROM post WHERE user_name_post='Carlos';
--Ingresar un nuevo post para el usuario "Carlos"
INSERT INTO post(user_name_post, content_post, description_post, title_post) VALUES('Carlos', 'lorem ipsum...', 'lorem ipsum...', 'carlos new post');
--PARTE 2
--Crear una nueva tabla, llamada comentarios, con los atributos id, fecha y hora de creación,
--contenido, que se relacione con la tabla posts.
CREATE TABLE comments
(
id_comments SERIAL PRIMARY KEY,
date_of_creation_comments DATE,
time_of_creation_comments TIME,
content_comments VARCHAR(50),
FOREIGN KEY (id_comments) REFERENCES post(id_post)
);
--Crear 2 comentarios para el post de "Pamela" y 4 para "Carlos"
INSERT INTO comments(id_comments, content_comments) VALUES(1, 'pame first comment'), (1, 'pame second commment');
INSERT INTO comments(id_comments, content_comments) VALUES(5, 'carlos first comment'), (5, 'carlos second comment'), (5, 'carlos third comment'), (5, 'carlos fourth comment');
--Crear un nuevo post para "Margarita"
INSERT INTO post(user_name_post, content_post, description_post, title_post) VALUES('Margarita', 'lorem ipsum...', 'lorem ipsum...', 'margarita first post'), ('margarita', 'lorem ipsum...', 'lorem ipsum...', 'margarita first post');
--Ingresar 5 comentarios para el post de Margarita
INSERT INTO comments(id_comments, content_comments) VALUES(6, 'margarita first comment'), (6, 'margarita second comment'), (6, 'margarita third comment'), (6, 'margarita fourth comment'), (6, 'margarita fifth comment');
|
a7c1fb99c1d5c9c3e4d855a3ec6d86c5412697b8
|
[
"SQL"
] | 1
|
SQL
|
Pablofuenza7/Operaciones_en_una_tabla
|
124f30a786f584d0aa6f41a9e3c64238ed587369
|
3b5b587d46ca7634c414390c21321891d98881e4
|
refs/heads/master
|
<file_sep>let express = require('express')
let fs = require("fs")
let app = express()
let data = fs.readFileSync('data.json')
app.get('/cooke.json', function(req, res) {
var result = {}
var jsonContent = JSON.parse(data);
result = jsonContent
result.list.forEach(function(s) {
var result = []
s.ellipsis.forEach(function(j) {
var random = (Math.random() * 35).toFixed(2)
j = { 'food': `${j}`, 'price': `${random}`, 'isBought': 'false' }
result.push(j)
})
s.isBought = true
s.ellipsis = result
})
res.send(result)
})
app.use('/', express.static('public'))
// app.use('/static', express.static(path.join(__dirname, 'public')))
app.listen(3000, function() {
console.log('Example app listening on port 3000!')
})
<file_sep># shop-cart
#模拟购物
- 用express修改了数据结构
## 执行项目
> 安装依赖
> npm install
> 启动服务
> node app.js
<file_sep>let name = {
template: ` <div class="section">
<div class='name-wrap'>
<div class="food-name" v-for="(lists,index) in listl" v-on:click="Bought(index)" :class='{default: lists.isBought,bought: !lists.isBought }' >
{{lists.name}}
</div>
</div>
</div>`,
data: function() {
return {};
},
props: ['listl'],
methods: {
Bought: function(index) {
this.$emit('iss', index);
}
}
}
let food = {
template: `<div class="section"><div class="group-wrap">
<div class="food-group" v-for='(item,i) in arrl' v-on:click="food(i)" :class='{default1: item.isBought,bought1: !item.isBought }'>
{{item.food }}
</div>
</div>
</div>`,
props: ['arrl'],
methods: {
food: function(i) {
this.$emit('food', i);
}
}
}
let cart = {
template: `<div class="section"> <div class="cart-wrap">
<div class="shopping-cart" v-for='(items,j) in cart1 ' >
<span class="food ">{{items.food}}</span> <span class="food ">{{items.price | monny}}</span> <span class="food iconfont" v-on:click='cart(j)'></span>
</div>
</div>
</div>`,
props: ['cart1'],
methods: {
cart: function(j) {
this.$emit('cart', j)
}
}
}
let title = {
template: `<div class="title">
<h2><span class="iconfont name-title" > 菜单</span> </h2>
<h2><span class="iconfont food-title"> 食材 </span></h2>
<h2><span class="iconfont cart-title"> 购物车</span> </h2>
</div>`
}
let delAll = {
template: `<div class="allprice">
<span class="total-price">总价</span><span class="total-price">{{result1 |monny}}</span>
<span class="total-price"><input class="total-price btn" type="button" value="清空" v-on:click='del()'/></span>
</div>`,
methods: {
del: function() {
this.$emit('del')
}
},
props: ['result1']
}
Vue.filter('monny', function(value) {
return value + '¥'
})
Vue.component('nameWrap', name)
Vue.component('foodWrap', food)
Vue.component('shoppingCart', cart)
Vue.component('clear', delAll)
Vue.component('tit', title)
let app = new Vue({
el: '#app',
data: {
list: [{
name: '',
ellipsis: [{
food: '',
price: '',
isBought: ''
}],
isBought: ''
}],
arr: [],
cart: []
},
mounted() {
this.getName()
},
methods: {
getName: function() {
let that = this
axios.get('../cooke.json').then(function(data) {
that.list = data.data.list
})
},
clickName: function(index) {
var a = this.list[index].isBought
this.list.forEach(function(j) {
j.isBought = true
})
var ell = this.list[index].ellipsis
this.list[index].isBought = a
if (this.list[index].isBought) {
this.arr = ell
this.list[index].isBought = !this.list[index].isBought
} else {
this.arr = []
this.list[index].isBought = !this.list[index].isBought
}
},
clickFood: function(i, j) {
if (this.cart.indexOf(this.arr[i]) === -1) {
this.arr[i].isBought = j || false
this.arr[i].id = i
this.cart.push(this.arr[i])
$('.total-price').css({
display: 'inline-block'
})
} else {
this.arr[i].isBought = j || false
}
},
delFood: function(j) {
var id = this.cart[j].id
this.clickFood(id, true)
this.cart.splice(j, 1)
if (this.cart.length == 0) {
$('.total-price').css({
display: 'none'
});
}
},
delAll: function() {
this.cart = [];
$('.total-price').css({
display: 'none'
});
this.arr.forEach(function(i) {
i.isBought = true
})
}
},
computed: {
result: function() {
var res = 0
this.cart.forEach(function(i) {
res -= (-i.price)
res = res.toFixed(2)
})
return res
}
}
})
|
64f5dc9e79aca59d11e18fdbef5d4ef7290175ea
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
nycaozhongshe/shop-cart
|
7410833bdd40d1195326b40be2e9a4455981e157
|
433900a6f66bab228d102a1ffb7893c5c9755894
|
refs/heads/master
|
<repo_name>metric-collective/quickscan<file_sep>/src/main/java/co/deepthought/quickscan/server/Validated.java
package co.deepthought.quickscan.server;
/**
* An abstract class providing the ability to validate input.
*/
public abstract class Validated {
public abstract void validate() throws ServiceFailure;
protected void validateNonNull(final Object value, final String name) throws ServiceFailure {
if(value == null) {
throw new ServiceFailure(name + " must be non-null");
}
}
}
<file_sep>/src/test/java/co/deepthought/quickscan/index/IndexMapperTest.java
package co.deepthought.quickscan.index;
import co.deepthought.quickscan.store.Document;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
public class IndexMapperTest {
private IndexMapper mapper;
@Before
public void setUp() {
this.mapper = new IndexMapper();
for(int i = 0; i < 100; i++) {
final Document document = new Document("r-" + i, "a", null);
this.addTags("rtag-", i, document);
document.addField("field-1", 20);
document.addField("field-2", i);
document.addScore("score-1", false, i);
document.addScore("score-2", (i % 4) == 0, i);
this.mapper.inspect(document);
}
}
@Test
public void testFieldMapping() {
final Set<String> expected = new HashSet<>();
expected.add("field-1");
expected.add("field-2");
Assert.assertEquals(expected, this.mapper.getDistinctFields());
}
@Test
public void testTagMapping() {
final Set<String> tags = this.mapper.getDistinctTags();
Assert.assertEquals(100, tags.size());
Assert.assertTrue(tags.contains("rtag-0"));
Assert.assertTrue(tags.contains("rtag-99"));
Assert.assertFalse(tags.contains("fake"));
}
@Test
public void testScoreMapping() {
final Set<String> expected = new HashSet<>();
expected.add("score-1");
expected.add("score-2");
Assert.assertEquals(expected, this.mapper.getDistinctScores());
final Collection<Double> score1s = this.mapper.getScores().get("score-1");
Assert.assertEquals(100, score1s.size());
final Collection<Double> score2s = this.mapper.getScores().get("score-2");
Assert.assertEquals(75, score2s.size());
}
private void addTags(final String prefix, final int count, final Document target) {
for(int j = 0; j <= count; j++) {
target.addTag(prefix + j);
}
}
}
<file_sep>/src/test/java/co/deepthought/quickscan/store/DocumentTest.java
package co.deepthought.quickscan.store;
import com.google.gson.Gson;
import org.junit.*;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
public class DocumentTest {
public static Document[] mock() {
final Document r1 = new Document("a", "a", null); // 0
final Document r2 = new Document("b", "a", null); // 1
r2.addTag("0");
r2.addField("field-1", 10);
r2.addField("field-2", 11);
r2.addScore("score-3", false, 15);
r2.addScore("score-1", false, 6);
final Document r3 = new Document("c", "a", null); // 3
r3.addTag("1");
r3.addTag("128");
r3.addField("field-0", 100);
r3.addScore("score-0", false, 2);
r3.addScore("score-1", false, 8);
final Document r4 = new Document("d", "a", null); // 5
r4.addTag("2");
r4.addTag("100");
r4.addTag("baby");
r4.addField("field-FAKE", 100);
r4.addScore("FAKE", false, 0.4);
r4.addScore("score-1", false, 8);
return new Document[] {r1, r2, r3, r4};
}
private Document[] documents;
@Before
public void setUp() {
this.documents = DocumentTest.mock();
}
@Test
public void testAddField() {
final Document document = this.documents[0];
document.addField("baby", 0.2);
document.addField("cats", 0.4);
assertEquals(0.2, document.getFieldValue("baby"), 0);
assertEquals(0.4, document.getFieldValue("cats"), 0);
assertNull(document.getFieldValue("fragrance"));
}
@Test
public void testAddScore() {
final Document document = this.documents[0];
document.addScore("baby", false, 0.2);
document.addScore("cats", false, 0.4);
assertEquals(0.2, document.getScoreValue("baby"), 0);
assertEquals(0.4, document.getScoreValue("cats"), 0);
assertNull(document.getScoreValue("fragrance"));
}
@Test
public void testAddTags() {
final Document document = this.documents[0];
document.addTag("baby");
document.addTag("cats");
assertTrue(document.hasTag("baby"));
assertTrue(document.hasTag("cats"));
assertFalse(document.hasTag("fragrance"));
}
@Test
public void testGetFieldValues() {
final Document document = this.documents[1];
final Map<String, Double> fieldValues = document.getFieldValues();
assertEquals(2, fieldValues.size());
assertEquals(10, fieldValues.get("field-1"), 0);
assertEquals(11., fieldValues.get("field-2"), 0);
}
@Test
public void testGetScoreValues() {
final Document document = this.documents[1];
final Map<String, Double> values = document.getScoreValues();
assertEquals(2, values.size());
assertEquals(6, values.get("score-1"), 0);
assertEquals(15, values.get("score-3"), 0);
}
@Test
public void testGetTagNames() {
final Document document = this.documents[2];
final List<String> expected = Arrays.asList("1", "128");
assertEquals(expected, document.getTagNames());
}
@Test
public void testGson() {
final Document document = this.documents[3];
final Gson gson = new Gson();
final String serialized = gson.toJson(document);
final Document deserialized = gson.fromJson(serialized, Document.class);
assertEquals("d", deserialized.getId());
}
}<file_sep>/src/main/java/co/deepthought/quickscan/server/ServiceFailure.java
package co.deepthought.quickscan.server;
/**
* JSON-serializable class to indicate a failure.
*/
public class ServiceFailure extends Exception {
private final String message;
public ServiceFailure(final String message) {
this.message = message;
}
public String getMessage() {
return this.message;
}
}<file_sep>/README.md
quickscan
=========
scan-based denormalized search
<file_sep>/src/test/java/co/deepthought/quickscan/service/UpsertServiceTest.java
package co.deepthought.quickscan.service;
import co.deepthought.quickscan.server.ServiceFailure;
import co.deepthought.quickscan.server.UpsertService;
import co.deepthought.quickscan.store.Document;
import co.deepthought.quickscan.store.DocumentStore;
import co.deepthought.quickscan.store.DocumentTest;
import com.sleepycat.je.DatabaseException;
import org.junit.Before;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
public class UpsertServiceTest {
private UpsertService service;
private DocumentStore store;
@Before
public void setUp() throws DatabaseException {
this.store = new DocumentStore(":tmp");
this.service = new UpsertService(this.store);
}
@Test
public void testUpsert() throws ServiceFailure, DatabaseException {
final UpsertService.Input input = new UpsertService.Input();
input.document = DocumentTest.mock()[3];
this.service.handle(input);
final Document document = this.store.getById("d");
assertEquals("d", document.getId());
assertTrue(document.hasTag("2"));
assertTrue(document.hasTag("100"));
assertTrue(document.hasTag("baby"));
assertFalse(document.hasTag("jack"));
}
}<file_sep>/src/test/java/co/deepthought/quickscan/index/SearcherTest.java
package co.deepthought.quickscan.index;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class SearcherTest {
private Searcher searcher;
@Before
public void setUp() {
final IndexMap map = IndexMapTest.getMockMapper();
this.searcher = new Searcher(map, null, null);
}
@Test
public void testNormalizeDisjunctiveTags() {
final List<List<String>> tagSets = new ArrayList<>();
final List<String> tags1 = new ArrayList<>();
tagSets.add(tags1);
tags1.add("0");
tags1.add("128");
tags1.add("baby");
final List<String> tags2 = new ArrayList<>();
tagSets.add(tags2);
tags2.add("1");
tags2.add("129");
final long[][] normalized = this.searcher.normalizeDisjunctiveTags(tagSets);
assertEquals(2, normalized.length);
assertEquals(0x1L, normalized[0][0]);
assertEquals(0x0L, normalized[0][1]);
assertEquals(0x5L, normalized[0][2]);
assertEquals(0x2L, normalized[1][0]);
assertEquals(0x0L, normalized[1][1]);
assertEquals(0x2L, normalized[1][2]);
}
}
<file_sep>/src/main/java/co/deepthought/quickscan/index/Percentiler.java
package co.deepthought.quickscan.index;
import java.util.Arrays;
import java.util.Collection;
/**
* Given a collection of numbers, estimate the percentile for new incoming values.
*/
public class Percentiler {
private final double[] breakpoints;
public Percentiler(final Collection<Double> samples) {
final double[] sampleArray = Percentiler.sort(samples);
this.breakpoints = Percentiler.computeBreakpoints(sampleArray);
}
public double percentile(double value) {
if(value < this.breakpoints[0]) {
return 0.01;
}
else {
for(int i = 1; i < 99; i++) {
final double next = this.breakpoints[i];
if(next > value) {
final double previous = this.breakpoints[i-1];
final double width = next - previous;
final double offset = value - previous;
final double proportion = offset / width;
return (i/100.) + (0.01 * proportion);
}
}
// no breakpoint greater
return 0.99;
}
}
public static double[] computeBreakpoints(final double[] sortedSamples) {
final double[] breakpoints = new double[99];
for(int i = 1; i < 100; i++) {
breakpoints[i-1] = Percentiler.interpolate(sortedSamples, i / 100.);
}
return breakpoints;
}
public static double interpolate(final double[] samples, final double location) {
final double width = (samples.length - 1.0);
final double x1 = Math.floor(location * width);
final double x2 = Math.ceil(location * width);
final double xD = (location * width) - x1;
final double y1 = samples[(int)x1];
final double y2 = samples[(int)x2];
final double yD = y2 - y1;
return y1 + yD * xD;
}
public static double[] sort(final Collection<Double> samples) {
final double[] sampleArray = new double[samples.size()];
int index = 0;
for(final Double sample :samples) {
sampleArray[index] = sample;
index++;
}
Arrays.sort(sampleArray);
return sampleArray;
}
}
<file_sep>/src/main/java/co/deepthought/quickscan/store/Document.java
package co.deepthought.quickscan.store;
import com.sleepycat.persist.model.Entity;
import com.sleepycat.persist.model.PrimaryKey;
import com.sleepycat.persist.model.Relationship;
import com.sleepycat.persist.model.SecondaryKey;
import org.apache.commons.collections.ListUtils;
import java.util.*;
@Entity
public class Document {
@PrimaryKey
private String id;
@SecondaryKey(relate = Relationship.MANY_TO_ONE)
private String shardId;
private boolean deprecated;
private List<Field> fields;
private List<Score> scores;
private List<Tag> tags;
private String payload;
private Document() {}
public Document(final String id, final String shardId, final String payload) {
this.id = id;
this.shardId = shardId;
this.fields = new ArrayList<>();
this.scores = new ArrayList<>();
this.tags = new ArrayList<>();
this.payload = payload;
this.deprecated = false;
}
public void addField(final String fieldName, final double value) {
final Field field = new Field(fieldName, value);
this.fields.add(field);
}
public void addTag(final String tagName) {
final Tag tag = new Tag(tagName);
this.tags.add(tag);
}
public void addScore(final String scoreName, final boolean phantom, final double value) {
final Score score = new Score(scoreName, phantom, value);
this.scores.add(score);
}
public List<Field> getFields() {
return this.fields;
}
public boolean getDeprecated() {
return this.deprecated;
}
public Double getFieldValue(final String fieldName) {
for(final Field field : this.fields) {
if(field.getName().equals(fieldName)) {
return field.getValue();
}
}
return null;
}
public Map<String, Double> getFieldValues() {
final Map<String, Double> fieldValues = new HashMap<>();
for(final Field field : this.fields) {
fieldValues.put(field.getName(), field.getValue());
}
return fieldValues;
}
public List<Score> getScores() {
return this.scores;
}
public Double getScoreValue(final String scoreName) {
for(final Score score : this.scores) {
if(score.getName().equals(scoreName)) {
return score.getValue();
}
}
return null;
}
public Map<String, Double> getScoreValues() {
final Map<String, Double> scoreValues = new HashMap<>();
for(final Score score : this.scores) {
scoreValues.put(score.getName(), score.getValue());
}
return scoreValues;
}
public List<Tag> getTags() {
return this.tags;
}
public List<String> getTagNames() {
final List<String> tagNames = new ArrayList<>();
for(final Tag tag : this.tags) {
tagNames.add(tag.getName());
}
return tagNames;
}
public boolean hasTag(final String tagName) {
for(final Tag tag : this.tags) {
if(tag.getName().equals(tagName)) {
return true;
}
}
return false;
}
public String getId() {
return this.id;
}
public String getPayload() {
return this.payload;
}
public String getShardId() {
return this.shardId;
}
public void setDeprecated(final boolean deprecated) {
this.deprecated = deprecated;
}
}
<file_sep>/src/main/java/co/deepthought/quickscan/index/SearcherManager.java
package co.deepthought.quickscan.index;
import co.deepthought.quickscan.store.Document;
import co.deepthought.quickscan.store.DocumentStore;
import com.sleepycat.je.DatabaseException;
import java.util.HashMap;
import java.util.Map;
/**
* Maintains a synchronized mapping of the various searchers. This class is thread-safe.
*/
public class SearcherManager {
final private DocumentStore store;
final private Indexer indexer;
final private Map<String, Searcher> searchers;
public SearcherManager(final DocumentStore store) {
this.store = store;
this.indexer = new Indexer(store);
this.searchers = new HashMap<>();
}
public SearchResult getSearchResult(final String resultId) throws DatabaseException {
final Document document = this.store.getById(resultId);
if(document == null) {
return null;
}
final Searcher searcher = this.getSearcher(document.getShardId());
if(searcher == null) {
return null;
}
return searcher.getSearchResult(document);
}
public synchronized Searcher getSearcher(final String shardId) {
return this.searchers.get(shardId);
}
public void index() throws DatabaseException {
for(final String shardId : this.store.getDistinctShardIds()) {
System.out.println("Indexing: " + shardId);
final long start = System.currentTimeMillis();
final int count = this.indexShard(shardId);
final long end = System.currentTimeMillis();
System.out.println("Indexed " + count + " documents in " + (end-start));
}
}
public int indexShard(final String shardId) throws DatabaseException {
final Searcher searcher = this.indexer.index(shardId);
this.setSearcher(shardId, searcher);
return searcher.getSize();
}
private synchronized void setSearcher(final String shardId, final Searcher searcher) {
this.searchers.put(shardId, searcher);
}
}<file_sep>/src/test/java/co/deepthought/quickscan/store/DocumentStoreTest.java
package co.deepthought.quickscan.store;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.persist.EntityCursor;
import org.junit.Before;
import org.junit.Test;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.*;
public class DocumentStoreTest {
private Document[] documents;
private DocumentStore store;
@Before
public void setUp() throws DatabaseException {
this.store = new DocumentStore(":tmp");
this.documents = DocumentTest.mock();
}
@Test
public void testClean() throws DatabaseException {
this.store.persist(this.documents[0]);
this.store.persist(this.documents[1]);
this.store.persist(this.documents[2]);
this.store.persist(this.documents[3]);
this.store.clean();
assertNull(this.store.getById("a"));
assertNull(this.store.getById("b"));
assertNull(this.store.getById("c"));
assertNull(this.store.getById("d"));
}
@Test
public void testGetByShardId() throws DatabaseException {
this.store.persist(this.documents[0]);
this.store.persist(this.documents[1]);
this.store.persist(this.documents[2]);
this.store.persist(this.documents[3]);
final Document rb = new Document("twa", "b", null);
this.store.persist(rb);
final EntityCursor<Document> cursor = this.store.getByShardId("a");
try {
final Set<String> actual = new HashSet<>();
for(final Document document : cursor) {
actual.add(document.getId());
}
final Set<String> expected = new HashSet<>();
expected.add("a");
expected.add("b");
expected.add("c");
expected.add("d");
assertEquals(expected, actual);
}
finally {
cursor.close();
}
}
@Test
public void testGetDistinctShardIds() throws DatabaseException {
this.store.persist(this.documents[0]);
this.store.persist(this.documents[1]);
this.store.persist(this.documents[2]);
this.store.persist(this.documents[3]);
final Document rb = new Document("twa", "b", null);
this.store.persist(rb);
final Set<String> expected = new HashSet<>();
expected.add("a");
expected.add("b");
assertEquals(expected, this.store.getDistinctShardIds());
}
@Test
public void testPersistence() throws DatabaseException {
this.store.persist(this.documents[0]);
final Document r1 = this.store.getById("a");
assertFalse(r1 == this.documents[0]);
assertEquals("a", r1.getId());
}
@Test
public void testPersistenceNotFound() throws DatabaseException {
final Document r2 = this.store.getById("?");
assertNull(r2);
}
}
<file_sep>/src/main/java/co/deepthought/quickscan/Tester.java
package co.deepthought.quickscan;
import java.util.*;
public class Tester {
public static void main(String[] args) {
final Random random = new Random();
final List<Double> numbers = new ArrayList<>();
for(int i = 0; i < 400; i++) {
numbers.add(random.nextDouble());
}
long total = 0;
for(int i = 0; i < 1000; i++) {
final List newList = new ArrayList<>(numbers);
final long start = System.nanoTime();
Collections.sort(newList);
final long end = System.nanoTime();
total += (end-start);
}
System.out.println(total/1000);
total = 0;
for(int i = 0; i < 1000; i++) {
final long start = System.nanoTime();
final int size = 128;
final List[] buckets = new List[size];
for(int j = 0; j < size; j++) {
buckets[j] = new ArrayList();
}
for(final Double number : numbers) {
final int position = (int) ((1.0-number) * size);
buckets[position].add(number);
}
final long end = System.nanoTime();
total += (end-start);
}
System.out.println(total/1000);
}
}
<file_sep>/src/main/java/co/deepthought/quickscan/server/DeprecateService.java
package co.deepthought.quickscan.server;
import co.deepthought.quickscan.store.Document;
import co.deepthought.quickscan.store.DocumentStore;
import com.sleepycat.je.DatabaseException;
import java.util.List;
/**
* A service deleting documents from the store.
*/
public class DeprecateService
extends BaseService<DeprecateService.Input, ServiceSuccess> {
public static class Input extends Validated {
public List<String> ids;
@Override
public void validate() throws ServiceFailure {
this.validateNonNull(this.ids, "ids");
}
}
private final DocumentStore documentStore;
public DeprecateService(final DocumentStore documentStore) {
this.documentStore = documentStore;
}
@Override
public Class<Input> getInputClass() {
return Input.class;
}
@Override
public ServiceSuccess handle(final Input input) throws ServiceFailure {
try {
for(final String id : input.ids) {
final Document document = this.documentStore.getById(id);
if(document != null) {
document.setDeprecated(true);
this.documentStore.persist(document);
}
}
return new ServiceSuccess();
} catch (DatabaseException e) {
// this is unlikely, why would this be a checked exception?
throw new ServiceFailure("database error");
}
}
}<file_sep>/src/main/java/co/deepthought/quickscan/server/SearchService.java
package co.deepthought.quickscan.server;
import co.deepthought.quickscan.index.PaginatedResults;
import co.deepthought.quickscan.index.SearchResult;
import co.deepthought.quickscan.index.Searcher;
import co.deepthought.quickscan.index.SearcherManager;
import com.sleepycat.je.DatabaseException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* A service inserting or updating documents to the store.
*/
public class SearchService
extends BaseService<SearchService.Input, SearchService.Output> {
public static class Input extends Validated {
public String shardId;
public List<String> conjunctiveTags;
public List<List<String>> disjunctiveTags;
public Map<String, Double> minFilters;
public Map<String, Double> maxFilters;
public Map<String, Double> preferences;
public int limit;
public int skip;
@Override
public void validate() throws ServiceFailure {
this.validateNonNull(this.shardId, "shardId");
this.validateNonNull(this.conjunctiveTags, "conjunctiveTags");
this.validateNonNull(this.disjunctiveTags, "disjunctiveTags");
this.validateNonNull(this.minFilters, "minFilters");
this.validateNonNull(this.maxFilters, "maxFilters");
this.validateNonNull(this.preferences, "preferences");
}
public Input() {}
}
public static class Output {
public String status = "success";
public Collection<SearchResult> results;
public int total;
public Output() {}
}
private final SearcherManager manager;
public SearchService(final SearcherManager manager) {
this.manager = manager;
}
@Override
public Class<Input> getInputClass() {
return Input.class;
}
@Override
public Output handle(final Input input) throws ServiceFailure {
final Searcher searcher = this.manager.getSearcher(input.shardId);
if(searcher == null) {
throw new ServiceFailure("shard not indexed, or has no data");
}
final PaginatedResults<SearchResult> results;
try {
results = searcher.search(
input.conjunctiveTags,
input.disjunctiveTags,
input.minFilters,
input.maxFilters,
input.preferences,
input.limit,
input.skip
);
final Output output = new Output();
output.results = results.getResults();
output.total = results.getTotal();
return output;
} catch (DatabaseException e) {
throw new ServiceFailure("database error");
}
}
}<file_sep>/src/main/java/co/deepthought/quickscan/index/IndexShard.java
package co.deepthought.quickscan.index;
import org.apache.log4j.Logger;
import java.util.*;
/**
* Stores a normalized dataset and provides scanning/sorting functionality.
*/
public class IndexShard {
final static Logger LOGGER = Logger.getLogger(IndexShard.class.getCanonicalName());
public static final long ALL_HOT = ~0L;
public static final int SORTING_RESOLUTION = 256;
private final int size;
private final String[] resultIds;
private final long[][] tags;
private final double[][] minFields;
private final double[][] maxFields;
private final double[][] scores;
public IndexShard(
final String[] resultIds,
final long[][] tags,
final double[][] minFields,
final double[][] maxFields,
final double[][] scores
) {
this.resultIds = resultIds;
this.tags = tags;
this.minFields = minFields;
this.maxFields = maxFields;
this.scores = scores;
this.size = this.resultIds.length;
}
public boolean[] filter(
final long[] conjunctiveTags,
final long[][] disjunctiveTags,
final double[] minFilters,
final double[] maxFilters
) {
final boolean[] nonmatches = new boolean[this.size];
for(int i = 0; i < disjunctiveTags.length; i++) {
this.filterDisjunctive(nonmatches, disjunctiveTags[i]);
}
for(int i = 0; i < this.tags.length; i++) {
this.filterConjunctive(nonmatches, i, conjunctiveTags[i]);
}
for(int i = 0; i < this.minFields.length; i++) {
this.filterMin(nonmatches, i, minFilters[i]);
}
for(int i = 0; i < this.maxFields.length; i++) {
this.filterMax(nonmatches, i, maxFilters[i]);
}
return nonmatches;
}
public void filterConjunctive(final boolean[] nonmatches, final int index, final long comparison) {
if(comparison != 0) {
final long mask = ~comparison;
final long[] values = this.tags[index];
for(int i = 0; i < this.size; i++) {
nonmatches[i] |= ((values[i] | mask) != IndexShard.ALL_HOT);
}
}
}
public void filterDisjunctive(final boolean[] nonmatches, final long[] comparison) {
// because two disjunctive tags can spread multiple pages, we need all pages to make this reasonable
final boolean[] submatches = new boolean[this.size];
for(int page = 0; page < this.tags.length; page++) {
final long mask = comparison[page];
if(mask != 0L) {
final long[] values = this.tags[page];
for(int i = 0; i < this.size; i++) {
submatches[i] |= ((values[i] & mask) != 0L);
}
}
}
for(int i = 0; i < this.size; i++) {
nonmatches[i] |= !(submatches[i]);
}
}
public void filterMax(final boolean[] nonmatches, final int index, final double comparison) {
if(!Double.isNaN(comparison)) {
final double[] values = this.maxFields[index];
for(int i = 0; i < this.size; i++) {
nonmatches[i] |= (values[i] > comparison);
}
}
}
public void filterMin(final boolean[] nonmatches, final int index, final double comparison) {
if(!Double.isNaN(comparison)) {
final double[] values = this.minFields[index];
for(int i = 0; i < this.size; i++) {
nonmatches[i] |= (values[i] < comparison);
}
}
}
public List[] getBuckets() {
final List[] buckets = new List[IndexShard.SORTING_RESOLUTION];
for(int i = 0; i < IndexShard.SORTING_RESOLUTION; i++) {
buckets[i] = new ArrayList();
}
return buckets;
}
public int getSize() {
return this.size;
}
public PaginatedResults<String> scan(
final long[] conjunctiveTags,
final long[][] disjunctiveTags,
final double[] minFilters,
final double[] maxFilters,
final double[] preferences,
final int number
) {
final long start = System.nanoTime();
final boolean[] nonmatches = this.filter(conjunctiveTags, disjunctiveTags, minFilters, maxFilters);
final long filtered = System.nanoTime();
LOGGER.info("filter in " + ((filtered-start)/1000) + "us");
final List[] buckets = this.getBuckets();
this.sortToBuckets(buckets, nonmatches, preferences);
final PaginatedResults<String> results = this.trimBuckets(buckets, number);
final long scored = System.nanoTime();
LOGGER.info("score in " + ((scored-filtered)/1000) + "us");
return results;
}
public void sortToBuckets(final List[] buckets, final boolean[] nonmatches, final double[] preferences) {
for(int i = 0; i < this.size; i++) {
if(!nonmatches[i]) {
double total = 0;
double weight = 0;
final double[] score = scores[i];
for(int j = 0; j < score.length; j++) {
if(score[j] >= 0) {
total += preferences[j] * score[j];
weight += preferences[j];
}
}
if(weight > 0) {
final int position = (int) ((1.0-total/weight) * IndexShard.SORTING_RESOLUTION);
buckets[position].add(this.resultIds[i]);
}
}
}
}
public PaginatedResults<String> trimBuckets(final List[] buckets, final int number) {
int count = 0;
final List<String> resultIds = new ArrayList<>();
for(final List bucket : buckets) {
count += bucket.size();
for(final Object item : bucket) {
if(resultIds.size() < number) {
resultIds.add((String)item);
}
}
}
return new PaginatedResults<>(resultIds, count);
}
}<file_sep>/src/main/java/co/deepthought/quickscan/index/Indexer.java
package co.deepthought.quickscan.index;
import co.deepthought.quickscan.store.Document;
import co.deepthought.quickscan.store.DocumentStore;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.persist.EntityCursor;
import org.apache.log4j.Logger;
/**
* Can produce Searchers for various shards.
*/
public class Indexer {
final static Logger LOGGER = Logger.getLogger(Indexer.class.getCanonicalName());
final private DocumentStore store;
public Indexer(final DocumentStore store) {
this.store = store;
}
public Searcher index(final String shardId) throws DatabaseException {
final long start = System.currentTimeMillis();
final IndexMap indexMap = this.map(shardId);
final IndexShard shard = this.normalize(indexMap, shardId);
final long end = System.currentTimeMillis();
LOGGER.info("indexed " + shardId + " in " + (end-start) + "ms");
return new Searcher(indexMap, shard, this.store);
}
private IndexMap map(final String shardId) throws DatabaseException {
final IndexMapper indexMapper = new IndexMapper();
final EntityCursor<Document> cursor = this.store.getByShardId(shardId);
try {
for(final Document document : cursor) {
if(!document.getDeprecated()) {
indexMapper.inspect(document);
}
}
}
finally {
cursor.close();
}
return indexMapper.map();
}
private IndexShard normalize(final IndexMap indexMap, final String shardId) throws DatabaseException {
final IndexNormalizer normalizer = new IndexNormalizer(indexMap);
final EntityCursor<Document> cursor = this.store.getByShardId(shardId);
try {
for(final Document document : cursor) {
if(!document.getDeprecated()) {
normalizer.index(document);
}
}
}
finally {
cursor.close();
}
return normalizer.normalize();
}
}<file_sep>/src/test/java/co/deepthought/quickscan/index/IndexMapTest.java
package co.deepthought.quickscan.index;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class IndexMapTest {
private IndexMap map;
public static IndexMap getMockMapper() {
final Set<String> tags = new LinkedHashSet<>();
for(int i = 0 ;i < 130; i++) {
tags.add(Integer.toString(i));
}
final Set<String> fields = new LinkedHashSet<>();
for(int i = 0 ;i < 5; i++) {
fields.add("field-" + Integer.toString(i));
}
final Set<String> scores = new LinkedHashSet<>();
for(int i = 0; i < 5; i++) {
scores.add("score-" + Integer.toString(i));
}
final Multimap<String, Double> scoreSamples = ArrayListMultimap.create();
for(int i = 0; i < 5; i++) {
for(double value = 0.0; value <= i * 10.0; value += 1.0) {
scoreSamples.put("score-" + Integer.toString(i), value);
}
}
return new IndexMap(tags, fields, scores, scoreSamples);
}
@Before
public void setUp() {
this.map = IndexMapTest.getMockMapper();
}
@Test
public void testGetTagPage() {
assertEquals(0, IndexMap.getTagPage(0));
assertEquals(0, IndexMap.getTagPage(1));
assertEquals(0, IndexMap.getTagPage(63));
assertEquals(1, IndexMap.getTagPage(64));
assertEquals(1, IndexMap.getTagPage(127));
assertEquals(2, IndexMap.getTagPage(128));
}
@Test
public void testGetTagMask() {
assertEquals(0x1L, IndexMap.getTagMask(0));
assertEquals(0x2L, IndexMap.getTagMask(1));
assertEquals(0x8L, IndexMap.getTagMask(3));
assertEquals(0x8000000000000000L, IndexMap.getTagMask(63));
assertEquals(0x1L, IndexMap.getTagMask(64));
}
@Test
public void testMapNames() {
final Set<String> names = new HashSet<>();
names.add("a");
names.add("b");
names.add("c");
final Map<String, Integer> nameMap = IndexMap.mapNames(names);
assertEquals(names, nameMap.keySet());
assertTrue(nameMap.values().contains(0));
assertTrue(nameMap.values().contains(1));
assertTrue(nameMap.values().contains(2));
}
@Test
public void testNormalizeFields() {
final Map<String, Double> fields = new HashMap<>();
fields.put("field-0", 1.2);
fields.put("field-3", 0.5);
fields.put("field-FAKE", 99.0);
final double[] normalized = this.map.normalizeFields(fields, -1);
assertArrayEquals(new double[] {1.2, -1, -1, 0.5, -1}, normalized, 0);
}
@Test
public void testNormalizeScores() {
final Map<String, Double> fields = new HashMap<>();
fields.put("score-0", 0.0);
fields.put("score-1", 5.0);
fields.put("score-3", 7.5);
fields.put("score-100", 0.2);
final double[] normalized = this.map.normalizeScores(fields, 0, true);
assertArrayEquals(new double[] {0.99, 0.5, 0, 0.25, 0}, normalized, 0);
}
@Test
public void testNormalizeTags() {
final List<String> tags = Arrays.asList("0", "10", "80", "121", "129", "babyfat");
final long[] normalized = this.map.normalizeTags(tags);
assertEquals(3, normalized.length);
assertEquals(0x0000000000000401L, normalized[0]);
assertEquals(0x0200000000010000L, normalized[1]);
assertEquals(0x0000000000000006L, normalized[2]);
}
}<file_sep>/src/main/java/co/deepthought/quickscan/index/IndexMapper.java
package co.deepthought.quickscan.index;
import co.deepthought.quickscan.store.*;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import java.util.*;
/**
* Inspects documents one-at-a-time to produce an IndexMap
*/
public class IndexMapper {
final private Set<String> distinctFields;
final private Set<String> distinctScores;
final private Set<String> distinctTags;
final private Multimap<String, Double> scores;
public IndexMapper() {
this.distinctFields = new HashSet<>();
this.distinctScores = new HashSet<>();
this.distinctTags = new HashSet<>();
this.scores = ArrayListMultimap.create();
}
protected Set<String> getDistinctFields() {
return this.distinctFields;
}
protected Set<String> getDistinctScores() {
return this.distinctScores;
}
protected Set<String> getDistinctTags() {
return this.distinctTags;
}
protected Multimap<String, Double> getScores() {
return this.scores;
}
public void inspect(final Document document) {
for(final Field field : document.getFields()) {
this.distinctFields.add(field.getName());
}
for(final Tag tag : document.getTags()) {
this.distinctTags.add(tag.getName());
}
for(final Score score: document.getScores()) {
this.distinctScores.add(score.getName());
if(!score.getPhantom()) {
this.scores.put(score.getName(), score.getValue());
}
}
}
public IndexMap map() {
return new IndexMap(
this.distinctTags,
this.distinctFields,
this.distinctScores,
this.scores
);
}
}<file_sep>/resources/config.properties
dbfile=/home/rentenna/quickscanindex
port=5400<file_sep>/src/test/java/co/deepthought/quickscan/service/IndexServiceTest.java
package co.deepthought.quickscan.service;
import co.deepthought.quickscan.index.SearcherManager;
import co.deepthought.quickscan.server.IndexService;
import co.deepthought.quickscan.server.ServiceFailure;
import co.deepthought.quickscan.store.Document;
import co.deepthought.quickscan.store.DocumentStore;
import co.deepthought.quickscan.store.DocumentTest;
import com.sleepycat.je.DatabaseException;
import org.junit.Before;
import org.junit.Test;
import static junit.framework.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
public class IndexServiceTest {
private SearcherManager manager;
private IndexService service;
@Before
public void setUp() throws DatabaseException {
final DocumentStore store = new DocumentStore(":tmp");
for(final Document document : DocumentTest.mock()) {
store.persist(document);
}
store.persist(new Document("e", "e", null));
this.manager = new SearcherManager(store);
this.service = new IndexService(this.manager);
}
@Test
public void testIndexing() throws DatabaseException, ServiceFailure {
final IndexService.Input input = new IndexService.Input();
this.service.handle(input);
assertNotNull(this.manager.getSearcher("a"));
assertNotNull(this.manager.getSearcher("e"));
}
@Test
public void testIndexingForShard() throws DatabaseException, ServiceFailure {
final IndexService.Input input = new IndexService.Input();
input.shardId = "e";
this.service.handle(input);
assertNull(this.manager.getSearcher("a"));
assertNotNull(this.manager.getSearcher("e"));
}
}
|
c919c40a72f72ba9af4772fc1388144027529f51
|
[
"Markdown",
"Java",
"INI"
] | 20
|
Java
|
metric-collective/quickscan
|
d524f1692d8ebd4dc716a28838658f2f580d0831
|
a3cb6259a72ac3d3cbf98918e1463f02e44c9d19
|
refs/heads/master
|
<repo_name>cprokopiak/solidfire-sdk-golang<file_sep>/sfapi/element.go
package sfapi
import (
"github.com/solidfire/solidfire-sdk-golang/sftypes"
"log"
)
func (c *Client) AddAccount(request sftypes.AddAccountRequest) (sftypes.AddAccountResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("AddAccount", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.AddAccountResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) AddClusterAdmin(request sftypes.AddClusterAdminRequest) (sftypes.AddClusterAdminResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("AddClusterAdmin", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.AddClusterAdminResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) AddDrives(request sftypes.AddDrivesRequest) (sftypes.AddDrivesResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("AddDrives", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.AddDrivesResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) AddInitiatorsToVolumeAccessGroup(request sftypes.AddInitiatorsToVolumeAccessGroupRequest) (sftypes.ModifyVolumeAccessGroupResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("AddInitiatorsToVolumeAccessGroup", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ModifyVolumeAccessGroupResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) AddLdapClusterAdmin(request sftypes.AddLdapClusterAdminRequest) (sftypes.AddLdapClusterAdminResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("AddLdapClusterAdmin", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.AddLdapClusterAdminResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) AddNodes(request sftypes.AddNodesRequest) (sftypes.AddNodesResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("AddNodes", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.AddNodesResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) AddVirtualNetwork(request sftypes.AddVirtualNetworkRequest) (sftypes.AddVirtualNetworkResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("AddVirtualNetwork", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.AddVirtualNetworkResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) AddVolumesToVolumeAccessGroup(request sftypes.AddVolumesToVolumeAccessGroupRequest) (sftypes.ModifyVolumeAccessGroupResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("AddVolumesToVolumeAccessGroup", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ModifyVolumeAccessGroupResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) CancelClone(request sftypes.CancelCloneRequest) (sftypes.CancelCloneResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("CancelClone", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.CancelCloneResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) CancelGroupClone(request sftypes.CancelGroupCloneRequest) (sftypes.CancelGroupCloneResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("CancelGroupClone", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.CancelGroupCloneResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ClearClusterFaults(request sftypes.ClearClusterFaultsRequest) (sftypes.ClearClusterFaultsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ClearClusterFaults", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ClearClusterFaultsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) CloneMultipleVolumes(request sftypes.CloneMultipleVolumesRequest) (sftypes.CloneMultipleVolumesResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("CloneMultipleVolumes", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.CloneMultipleVolumesResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) CloneVolume(request sftypes.CloneVolumeRequest) (sftypes.CloneVolumeResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("CloneVolume", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.CloneVolumeResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) CompleteClusterPairing(request sftypes.CompleteClusterPairingRequest) (sftypes.CompleteClusterPairingResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("CompleteClusterPairing", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.CompleteClusterPairingResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) CompleteVolumePairing(request sftypes.CompleteVolumePairingRequest) (sftypes.CompleteVolumePairingResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("CompleteVolumePairing", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.CompleteVolumePairingResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) CopyVolume(request sftypes.CopyVolumeRequest) (sftypes.CopyVolumeResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("CopyVolume", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.CopyVolumeResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) CreateBackupTarget(request sftypes.CreateBackupTargetRequest) (sftypes.CreateBackupTargetResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("CreateBackupTarget", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.CreateBackupTargetResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) CreateCluster(request sftypes.CreateClusterRequest) (sftypes.CreateClusterResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("CreateCluster", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.CreateClusterResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) CreateGroupSnapshot(request sftypes.CreateGroupSnapshotRequest) (sftypes.CreateGroupSnapshotResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("CreateGroupSnapshot", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.CreateGroupSnapshotResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) CreateInitiators(request sftypes.CreateInitiatorsRequest) (sftypes.CreateInitiatorsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("CreateInitiators", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.CreateInitiatorsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) CreateSchedule(request sftypes.CreateScheduleRequest) (sftypes.CreateScheduleResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("CreateSchedule", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.CreateScheduleResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) CreateSnapshot(request sftypes.CreateSnapshotRequest) (sftypes.CreateSnapshotResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("CreateSnapshot", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.CreateSnapshotResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) CreateStorageContainer(request sftypes.CreateStorageContainerRequest) (sftypes.CreateStorageContainerResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("CreateStorageContainer", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.CreateStorageContainerResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) CreateSupportBundle(request sftypes.CreateSupportBundleRequest) (sftypes.CreateSupportBundleResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("CreateSupportBundle", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.CreateSupportBundleResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) CreateVolume(request sftypes.CreateVolumeRequest) (sftypes.CreateVolumeResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("CreateVolume", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.CreateVolumeResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) CreateVolumeAccessGroup(request sftypes.CreateVolumeAccessGroupRequest) (sftypes.CreateVolumeAccessGroupResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("CreateVolumeAccessGroup", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.CreateVolumeAccessGroupResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) DeleteAllSupportBundles() (sftypes.DeleteAllSupportBundlesResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("DeleteAllSupportBundles", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.DeleteAllSupportBundlesResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) DeleteGroupSnapshot(request sftypes.DeleteGroupSnapshotRequest) (sftypes.DeleteGroupSnapshotResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("DeleteGroupSnapshot", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.DeleteGroupSnapshotResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) DeleteInitiators(request sftypes.DeleteInitiatorsRequest) (sftypes.DeleteInitiatorsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("DeleteInitiators", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.DeleteInitiatorsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) DeleteSnapshot(request sftypes.DeleteSnapshotRequest) (sftypes.DeleteSnapshotResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("DeleteSnapshot", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.DeleteSnapshotResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) DeleteStorageContainers(request sftypes.DeleteStorageContainersRequest) (sftypes.DeleteStorageContainerResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("DeleteStorageContainers", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.DeleteStorageContainerResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) DeleteVolume(request sftypes.DeleteVolumeRequest) (sftypes.DeleteVolumeResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("DeleteVolume", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.DeleteVolumeResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) DeleteVolumeAccessGroup(request sftypes.DeleteVolumeAccessGroupRequest) (sftypes.DeleteVolumeAccessGroupResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("DeleteVolumeAccessGroup", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.DeleteVolumeAccessGroupResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) DeleteVolumes(request sftypes.DeleteVolumesRequest) (sftypes.DeleteVolumesResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("DeleteVolumes", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.DeleteVolumesResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) DisableEncryptionAtRest() (sftypes.DisableEncryptionAtRestResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("DisableEncryptionAtRest", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.DisableEncryptionAtRestResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) DisableLdapAuthentication() (sftypes.DisableLdapAuthenticationResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("DisableLdapAuthentication", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.DisableLdapAuthenticationResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) DisableSnmp() (sftypes.DisableSnmpResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("DisableSnmp", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.DisableSnmpResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) EnableEncryptionAtRest() (sftypes.EnableEncryptionAtRestResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("EnableEncryptionAtRest", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.EnableEncryptionAtRestResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) EnableFeature(request sftypes.EnableFeatureRequest) (sftypes.EnableFeatureResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("EnableFeature", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.EnableFeatureResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) EnableLdapAuthentication(request sftypes.EnableLdapAuthenticationRequest) (sftypes.EnableLdapAuthenticationResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("EnableLdapAuthentication", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.EnableLdapAuthenticationResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) EnableSnmp(request sftypes.EnableSnmpRequest) (sftypes.EnableSnmpResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("EnableSnmp", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.EnableSnmpResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetAPI() (sftypes.GetAPIResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetAPI", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetAPIResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetAccountByID(request sftypes.GetAccountByIDRequest) (sftypes.GetAccountResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetAccountByID", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetAccountResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetAccountByName(request sftypes.GetAccountByNameRequest) (sftypes.GetAccountResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetAccountByName", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetAccountResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetAccountEfficiency(request sftypes.GetAccountEfficiencyRequest) (sftypes.GetEfficiencyResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetAccountEfficiency", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetEfficiencyResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetAsyncResult(request sftypes.GetAsyncResultRequest) (interface{}, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetAsyncResult", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result interface{}
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetBackupTarget(request sftypes.GetBackupTargetRequest) (sftypes.GetBackupTargetResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetBackupTarget", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetBackupTargetResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetBootstrapConfig() (sftypes.GetBootstrapConfigResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetBootstrapConfig", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetBootstrapConfigResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetClusterCapacity() (sftypes.GetClusterCapacityResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetClusterCapacity", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetClusterCapacityResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetClusterConfig() (sftypes.GetClusterConfigResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetClusterConfig", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetClusterConfigResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetClusterFullThreshold() (sftypes.GetClusterFullThresholdResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetClusterFullThreshold", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetClusterFullThresholdResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetClusterHardwareInfo(request sftypes.GetClusterHardwareInfoRequest) (sftypes.GetClusterHardwareInfoResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetClusterHardwareInfo", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetClusterHardwareInfoResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetClusterInfo() (sftypes.GetClusterInfoResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetClusterInfo", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetClusterInfoResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetClusterMasterNodeID() (sftypes.GetClusterMasterNodeIDResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetClusterMasterNodeID", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetClusterMasterNodeIDResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetClusterState(request sftypes.GetClusterStateRequest) (sftypes.GetClusterStateResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetClusterState", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetClusterStateResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetClusterStats() (sftypes.GetClusterStatsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetClusterStats", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetClusterStatsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetClusterVersionInfo() (sftypes.GetClusterVersionInfoResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetClusterVersionInfo", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetClusterVersionInfoResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetCompleteStats() (interface{}, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetCompleteStats", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result interface{}
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetConfig() (sftypes.GetConfigResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetConfig", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetConfigResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetCurrentClusterAdmin() (sftypes.GetCurrentClusterAdminResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetCurrentClusterAdmin", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetCurrentClusterAdminResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetDefaultQoS() (sftypes.VolumeQOS, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetDefaultQoS", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.VolumeQOS
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetDriveConfig() (sftypes.GetDriveConfigResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetDriveConfig", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetDriveConfigResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetDriveHardwareInfo(request sftypes.GetDriveHardwareInfoRequest) (sftypes.GetDriveHardwareInfoResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetDriveHardwareInfo", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetDriveHardwareInfoResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetDriveStats(request sftypes.GetDriveStatsRequest) (sftypes.GetDriveStatsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetDriveStats", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetDriveStatsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetFeatureStatus(request sftypes.GetFeatureStatusRequest) (sftypes.GetFeatureStatusResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetFeatureStatus", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetFeatureStatusResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetHardwareConfig() (sftypes.GetHardwareConfigResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetHardwareConfig", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetHardwareConfigResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetHardwareInfo() (sftypes.GetHardwareInfoResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetHardwareInfo", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetHardwareInfoResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetIpmiConfig(request sftypes.GetIpmiConfigRequest) (sftypes.GetIpmiConfigResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetIpmiConfig", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetIpmiConfigResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetIpmiInfo(request sftypes.GetIpmiInfoRequest) (sftypes.GetIpmiInfoResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetIpmiInfo", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetIpmiInfoResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetLdapConfiguration() (sftypes.GetLdapConfigurationResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetLdapConfiguration", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetLdapConfigurationResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetLimits() (sftypes.GetLimitsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetLimits", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetLimitsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetLoginSessionInfo() (sftypes.GetLoginSessionInfoResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetLoginSessionInfo", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetLoginSessionInfoResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetNetworkConfig() (sftypes.GetNetworkConfigResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetNetworkConfig", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetNetworkConfigResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetNodeHardwareInfo(request sftypes.GetNodeHardwareInfoRequest) (sftypes.GetNodeHardwareInfoResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetNodeHardwareInfo", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetNodeHardwareInfoResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetNodeStats(request sftypes.GetNodeStatsRequest) (sftypes.GetNodeStatsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetNodeStats", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetNodeStatsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetNtpInfo() (sftypes.GetNtpInfoResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetNtpInfo", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetNtpInfoResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetNvramInfo() (sftypes.GetNvramInfoResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetNvramInfo", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetNvramInfoResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetOrigin(request sftypes.GetOriginRequest) (sftypes.GetOriginResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetOrigin", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetOriginResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetPendingOperation() (sftypes.GetPendingOperationResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetPendingOperation", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetPendingOperationResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetRawStats() (interface{}, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetRawStats", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result interface{}
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetRemoteLoggingHosts() (sftypes.GetRemoteLoggingHostsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetRemoteLoggingHosts", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetRemoteLoggingHostsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetSchedule(request sftypes.GetScheduleRequest) (sftypes.GetScheduleResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetSchedule", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetScheduleResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetSnmpACL() (sftypes.GetSnmpACLResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetSnmpACL", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetSnmpACLResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetSnmpInfo() (sftypes.GetSnmpInfoResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetSnmpInfo", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetSnmpInfoResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetSnmpState() (sftypes.GetSnmpStateResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetSnmpState", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetSnmpStateResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetSnmpTrapInfo(request sftypes.GetSnmpTrapInfoRequest) (sftypes.GetSnmpTrapInfoResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetSnmpTrapInfo", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetSnmpTrapInfoResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetStorageContainerEfficiency(request sftypes.GetStorageContainerEfficiencyRequest) (sftypes.GetStorageContainerEfficiencyResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetStorageContainerEfficiency", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetStorageContainerEfficiencyResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetSystemStatus() (sftypes.GetSystemStatusResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetSystemStatus", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetSystemStatusResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetVirtualVolumeCount() (sftypes.GetVirtualVolumeCountResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetVirtualVolumeCount", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetVirtualVolumeCountResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetVolumeAccessGroupEfficiency(request sftypes.GetVolumeAccessGroupEfficiencyRequest) (sftypes.GetEfficiencyResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetVolumeAccessGroupEfficiency", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetEfficiencyResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetVolumeAccessGroupLunAssignments(request sftypes.GetVolumeAccessGroupLunAssignmentsRequest) (sftypes.GetVolumeAccessGroupLunAssignmentsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetVolumeAccessGroupLunAssignments", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetVolumeAccessGroupLunAssignmentsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetVolumeCount() (sftypes.GetVolumeCountResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetVolumeCount", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetVolumeCountResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetVolumeEfficiency(request sftypes.GetVolumeEfficiencyRequest) (sftypes.GetVolumeEfficiencyResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetVolumeEfficiency", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetVolumeEfficiencyResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) GetVolumeStats(request sftypes.GetVolumeStatsRequest) (sftypes.GetVolumeStatsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("GetVolumeStats", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.GetVolumeStatsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) InvokeSFApi(request sftypes.InvokeSFApiRequest) (interface{}, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("InvokeSFApi", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result interface{}
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListAccounts(request sftypes.ListAccountsRequest) (sftypes.ListAccountsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListAccounts", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListAccountsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListActiveNodes() (sftypes.ListActiveNodesResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListActiveNodes", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListActiveNodesResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListActivePairedVolumes(request sftypes.ListActivePairedVolumesRequest) (sftypes.ListActivePairedVolumesResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListActivePairedVolumes", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListActivePairedVolumesResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListActiveVolumes(request sftypes.ListActiveVolumesRequest) (sftypes.ListActiveVolumesResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListActiveVolumes", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListActiveVolumesResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListAllNodes() (sftypes.ListAllNodesResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListAllNodes", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListAllNodesResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListAsyncResults(request sftypes.ListAsyncResultsRequest) (sftypes.ListAsyncResultsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListAsyncResults", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListAsyncResultsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListBackupTargets() (sftypes.ListBackupTargetsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListBackupTargets", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListBackupTargetsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListBulkVolumeJobs() (sftypes.ListBulkVolumeJobsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListBulkVolumeJobs", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListBulkVolumeJobsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListClusterAdmins(request sftypes.ListClusterAdminsRequest) (sftypes.ListClusterAdminsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListClusterAdmins", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListClusterAdminsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListClusterFaults(request sftypes.ListClusterFaultsRequest) (sftypes.ListClusterFaultsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListClusterFaults", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListClusterFaultsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListClusterPairs() (sftypes.ListClusterPairsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListClusterPairs", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListClusterPairsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListDeletedVolumes() (sftypes.ListDeletedVolumesResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListDeletedVolumes", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListDeletedVolumesResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListDriveHardware(request sftypes.ListDriveHardwareRequest) (sftypes.ListDriveHardwareResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListDriveHardware", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListDriveHardwareResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListDriveStats(request sftypes.ListDriveStatsRequest) (sftypes.ListDriveStatsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListDriveStats", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListDriveStatsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListDrives() (sftypes.ListDrivesResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListDrives", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListDrivesResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListEvents(request sftypes.ListEventsRequest) (sftypes.ListEventsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListEvents", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListEventsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListFibreChannelPortInfo() (sftypes.ListFibreChannelPortInfoResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListFibreChannelPortInfo", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListFibreChannelPortInfoResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListFibreChannelSessions() (sftypes.ListFibreChannelSessionsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListFibreChannelSessions", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListFibreChannelSessionsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListGroupSnapshots(request sftypes.ListGroupSnapshotsRequest) (sftypes.ListGroupSnapshotsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListGroupSnapshots", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListGroupSnapshotsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListISCSISessions() (sftypes.ListISCSISessionsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListISCSISessions", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListISCSISessionsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListInitiators(request sftypes.ListInitiatorsRequest) (sftypes.ListInitiatorsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListInitiators", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListInitiatorsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListNetworkInterfaces() (sftypes.ListNetworkInterfacesResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListNetworkInterfaces", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListNetworkInterfacesResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListNodeFibreChannelPortInfo() (sftypes.ListNodeFibreChannelPortInfoResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListNodeFibreChannelPortInfo", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListNodeFibreChannelPortInfoResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListNodeStats() (sftypes.ListNodeStatsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListNodeStats", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListNodeStatsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListPendingActiveNodes() (sftypes.ListPendingActiveNodesResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListPendingActiveNodes", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListPendingActiveNodesResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListPendingNodes() (sftypes.ListPendingNodesResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListPendingNodes", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListPendingNodesResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListProtocolEndpoints(request sftypes.ListProtocolEndpointsRequest) (sftypes.ListProtocolEndpointsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListProtocolEndpoints", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListProtocolEndpointsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListSchedules() (sftypes.ListSchedulesResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListSchedules", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListSchedulesResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListServices() (sftypes.ListServicesResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListServices", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListServicesResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListSnapshots(request sftypes.ListSnapshotsRequest) (sftypes.ListSnapshotsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListSnapshots", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListSnapshotsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListStorageContainers(request sftypes.ListStorageContainersRequest) (sftypes.ListStorageContainersResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListStorageContainers", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListStorageContainersResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListSyncJobs() (sftypes.ListSyncJobsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListSyncJobs", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListSyncJobsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListTests() (sftypes.ListTestsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListTests", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListTestsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListUtilities() (sftypes.ListUtilitiesResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListUtilities", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListUtilitiesResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListVirtualNetworks(request sftypes.ListVirtualNetworksRequest) (sftypes.ListVirtualNetworksResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListVirtualNetworks", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListVirtualNetworksResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListVirtualVolumeBindings(request sftypes.ListVirtualVolumeBindingsRequest) (sftypes.ListVirtualVolumeBindingsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListVirtualVolumeBindings", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListVirtualVolumeBindingsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListVirtualVolumeHosts(request sftypes.ListVirtualVolumeHostsRequest) (sftypes.ListVirtualVolumeHostsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListVirtualVolumeHosts", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListVirtualVolumeHostsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListVirtualVolumeTasks(request sftypes.ListVirtualVolumeTasksRequest) (sftypes.ListVirtualVolumeTasksResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListVirtualVolumeTasks", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListVirtualVolumeTasksResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListVirtualVolumes(request sftypes.ListVirtualVolumesRequest) (sftypes.ListVirtualVolumesResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListVirtualVolumes", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListVirtualVolumesResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListVolumeAccessGroups(request sftypes.ListVolumeAccessGroupsRequest) (sftypes.ListVolumeAccessGroupsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListVolumeAccessGroups", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListVolumeAccessGroupsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListVolumeStats(request sftypes.ListVolumeStatsRequest) (sftypes.ListVolumeStatsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListVolumeStats", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListVolumeStatsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListVolumeStatsByAccount() (sftypes.ListVolumeStatsByAccountResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListVolumeStatsByAccount", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListVolumeStatsByAccountResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListVolumeStatsByVirtualVolume(request sftypes.ListVolumeStatsByVirtualVolumeRequest) (sftypes.ListVolumeStatsByVirtualVolumeResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListVolumeStatsByVirtualVolume", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListVolumeStatsByVirtualVolumeResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListVolumeStatsByVolume() (sftypes.ListVolumeStatsByVolumeResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListVolumeStatsByVolume", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListVolumeStatsByVolumeResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListVolumeStatsByVolumeAccessGroup(request sftypes.ListVolumeStatsByVolumeAccessGroupRequest) (sftypes.ListVolumeStatsByVolumeAccessGroupResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListVolumeStatsByVolumeAccessGroup", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListVolumeStatsByVolumeAccessGroupResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListVolumes(request sftypes.ListVolumesRequest) (sftypes.ListVolumesResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListVolumes", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListVolumesResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ListVolumesForAccount(request sftypes.ListVolumesForAccountRequest) (sftypes.ListVolumesForAccountResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ListVolumesForAccount", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ListVolumesForAccountResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ModifyAccount(request sftypes.ModifyAccountRequest) (sftypes.ModifyAccountResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ModifyAccount", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ModifyAccountResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ModifyBackupTarget(request sftypes.ModifyBackupTargetRequest) (sftypes.ModifyBackupTargetResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ModifyBackupTarget", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ModifyBackupTargetResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ModifyClusterAdmin(request sftypes.ModifyClusterAdminRequest) (sftypes.ModifyClusterAdminResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ModifyClusterAdmin", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ModifyClusterAdminResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ModifyClusterFullThreshold(request sftypes.ModifyClusterFullThresholdRequest) (sftypes.ModifyClusterFullThresholdResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ModifyClusterFullThreshold", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ModifyClusterFullThresholdResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ModifyGroupSnapshot(request sftypes.ModifyGroupSnapshotRequest) (sftypes.ModifyGroupSnapshotResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ModifyGroupSnapshot", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ModifyGroupSnapshotResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ModifyInitiators(request sftypes.ModifyInitiatorsRequest) (sftypes.ModifyInitiatorsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ModifyInitiators", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ModifyInitiatorsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ModifySchedule(request sftypes.ModifyScheduleRequest) (sftypes.ModifyScheduleResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ModifySchedule", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ModifyScheduleResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ModifySnapshot(request sftypes.ModifySnapshotRequest) (sftypes.ModifySnapshotResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ModifySnapshot", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ModifySnapshotResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ModifyStorageContainer(request sftypes.ModifyStorageContainerRequest) (sftypes.ModifyStorageContainerResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ModifyStorageContainer", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ModifyStorageContainerResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ModifyVirtualNetwork(request sftypes.ModifyVirtualNetworkRequest) (sftypes.AddVirtualNetworkResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ModifyVirtualNetwork", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.AddVirtualNetworkResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ModifyVolume(request sftypes.ModifyVolumeRequest) (sftypes.ModifyVolumeResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ModifyVolume", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ModifyVolumeResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ModifyVolumeAccessGroup(request sftypes.ModifyVolumeAccessGroupRequest) (sftypes.ModifyVolumeAccessGroupResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ModifyVolumeAccessGroup", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ModifyVolumeAccessGroupResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ModifyVolumeAccessGroupLunAssignments(request sftypes.ModifyVolumeAccessGroupLunAssignmentsRequest) (sftypes.ModifyVolumeAccessGroupLunAssignmentsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ModifyVolumeAccessGroupLunAssignments", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ModifyVolumeAccessGroupLunAssignmentsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ModifyVolumePair(request sftypes.ModifyVolumePairRequest) (sftypes.ModifyVolumePairResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ModifyVolumePair", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ModifyVolumePairResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ModifyVolumes(request sftypes.ModifyVolumesRequest) (sftypes.ModifyVolumesResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ModifyVolumes", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ModifyVolumesResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) PurgeDeletedVolume(request sftypes.PurgeDeletedVolumeRequest) (sftypes.PurgeDeletedVolumeResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("PurgeDeletedVolume", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.PurgeDeletedVolumeResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) PurgeDeletedVolumes(request sftypes.PurgeDeletedVolumesRequest) (sftypes.PurgeDeletedVolumesResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("PurgeDeletedVolumes", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.PurgeDeletedVolumesResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) RemoveAccount(request sftypes.RemoveAccountRequest) (sftypes.RemoveAccountResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("RemoveAccount", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.RemoveAccountResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) RemoveBackupTarget(request sftypes.RemoveBackupTargetRequest) (sftypes.RemoveBackupTargetResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("RemoveBackupTarget", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.RemoveBackupTargetResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) RemoveClusterAdmin(request sftypes.RemoveClusterAdminRequest) (sftypes.RemoveClusterAdminResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("RemoveClusterAdmin", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.RemoveClusterAdminResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) RemoveClusterPair(request sftypes.RemoveClusterPairRequest) (sftypes.RemoveClusterPairResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("RemoveClusterPair", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.RemoveClusterPairResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) RemoveDrives(request sftypes.RemoveDrivesRequest) (sftypes.AsyncHandleResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("RemoveDrives", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.AsyncHandleResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) RemoveInitiatorsFromVolumeAccessGroup(request sftypes.RemoveInitiatorsFromVolumeAccessGroupRequest) (sftypes.ModifyVolumeAccessGroupResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("RemoveInitiatorsFromVolumeAccessGroup", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ModifyVolumeAccessGroupResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) RemoveNodes(request sftypes.RemoveNodesRequest) (sftypes.RemoveNodesResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("RemoveNodes", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.RemoveNodesResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) RemoveVirtualNetwork(request sftypes.RemoveVirtualNetworkRequest) (sftypes.RemoveVirtualNetworkResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("RemoveVirtualNetwork", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.RemoveVirtualNetworkResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) RemoveVolumePair(request sftypes.RemoveVolumePairRequest) (sftypes.RemoveVolumePairResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("RemoveVolumePair", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.RemoveVolumePairResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) RemoveVolumesFromVolumeAccessGroup(request sftypes.RemoveVolumesFromVolumeAccessGroupRequest) (sftypes.ModifyVolumeAccessGroupResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("RemoveVolumesFromVolumeAccessGroup", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ModifyVolumeAccessGroupResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ResetDrives(request sftypes.ResetDrivesRequest) (sftypes.ResetDrivesResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ResetDrives", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ResetDrivesResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) ResetNode(request sftypes.ResetNodeRequest) (sftypes.ResetNodeResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("ResetNode", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ResetNodeResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) RestartNetworking(request sftypes.RestartNetworkingRequest) (interface{}, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("RestartNetworking", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result interface{}
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) RestartServices(request sftypes.RestartServicesRequest) (interface{}, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("RestartServices", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result interface{}
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) RestoreDeletedVolume(request sftypes.RestoreDeletedVolumeRequest) (sftypes.RestoreDeletedVolumeResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("RestoreDeletedVolume", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.RestoreDeletedVolumeResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) RollbackToGroupSnapshot(request sftypes.RollbackToGroupSnapshotRequest) (sftypes.RollbackToGroupSnapshotResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("RollbackToGroupSnapshot", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.RollbackToGroupSnapshotResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) RollbackToSnapshot(request sftypes.RollbackToSnapshotRequest) (sftypes.RollbackToSnapshotResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("RollbackToSnapshot", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.RollbackToSnapshotResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) SecureEraseDrives(request sftypes.SecureEraseDrivesRequest) (sftypes.AsyncHandleResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("SecureEraseDrives", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.AsyncHandleResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) SetClusterConfig(request sftypes.SetClusterConfigRequest) (sftypes.SetClusterConfigResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("SetClusterConfig", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.SetClusterConfigResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) SetConfig(request sftypes.SetConfigRequest) (sftypes.SetConfigResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("SetConfig", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.SetConfigResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) SetDefaultQoS(request sftypes.SetDefaultQoSRequest) (sftypes.SetDefaultQoSResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("SetDefaultQoS", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.SetDefaultQoSResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) SetLoginSessionInfo(request sftypes.SetLoginSessionInfoRequest) (sftypes.SetLoginSessionInfoResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("SetLoginSessionInfo", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.SetLoginSessionInfoResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) SetNetworkConfig(request sftypes.SetNetworkConfigRequest) (sftypes.SetNetworkConfigResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("SetNetworkConfig", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.SetNetworkConfigResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) SetNtpInfo(request sftypes.SetNtpInfoRequest) (sftypes.SetNtpInfoResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("SetNtpInfo", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.SetNtpInfoResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) SetRemoteLoggingHosts(request sftypes.SetRemoteLoggingHostsRequest) (sftypes.SetRemoteLoggingHostsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("SetRemoteLoggingHosts", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.SetRemoteLoggingHostsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) SetSnmpACL(request sftypes.SetSnmpACLRequest) (sftypes.SetSnmpACLResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("SetSnmpACL", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.SetSnmpACLResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) SetSnmpInfo(request sftypes.SetSnmpInfoRequest) (sftypes.SetSnmpInfoResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("SetSnmpInfo", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.SetSnmpInfoResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) SetSnmpTrapInfo(request sftypes.SetSnmpTrapInfoRequest) (sftypes.SetSnmpTrapInfoResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("SetSnmpTrapInfo", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.SetSnmpTrapInfoResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) Shutdown(request sftypes.ShutdownRequest) (sftypes.ShutdownResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("Shutdown", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.ShutdownResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) SnmpSendTestTraps() (sftypes.SnmpSendTestTrapsResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("SnmpSendTestTraps", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.SnmpSendTestTrapsResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) StartBulkVolumeRead(request sftypes.StartBulkVolumeReadRequest) (sftypes.StartBulkVolumeReadResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("StartBulkVolumeRead", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.StartBulkVolumeReadResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) StartBulkVolumeWrite(request sftypes.StartBulkVolumeWriteRequest) (sftypes.StartBulkVolumeWriteResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("StartBulkVolumeWrite", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.StartBulkVolumeWriteResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) StartClusterPairing() (sftypes.StartClusterPairingResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("StartClusterPairing", nil)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.StartClusterPairingResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) StartVolumePairing(request sftypes.StartVolumePairingRequest) (sftypes.StartVolumePairingResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("StartVolumePairing", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.StartVolumePairingResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) TestConnectEnsemble(request sftypes.TestConnectEnsembleRequest) (sftypes.TestConnectEnsembleResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("TestConnectEnsemble", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.TestConnectEnsembleResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) TestConnectMvip(request sftypes.TestConnectMvipRequest) (sftypes.TestConnectMvipResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("TestConnectMvip", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.TestConnectMvipResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) TestConnectSvip(request sftypes.TestConnectSvipRequest) (sftypes.TestConnectSvipResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("TestConnectSvip", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.TestConnectSvipResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) TestDrives(request sftypes.TestDrivesRequest) (sftypes.TestDrivesResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("TestDrives", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.TestDrivesResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) TestLdapAuthentication(request sftypes.TestLdapAuthenticationRequest) (sftypes.TestLdapAuthenticationResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("TestLdapAuthentication", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.TestLdapAuthenticationResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) TestPing(request sftypes.TestPingRequest) (sftypes.TestPingResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("TestPing", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.TestPingResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
func (c *Client) UpdateBulkVolumeStatus(request sftypes.UpdateBulkVolumeStatusRequest) (sftypes.UpdateBulkVolumeStatusResult, error) {
// Get a list of all active volumes on the Cluster
response, err := c.SendRequest("UpdateBulkVolumeStatus", request)
if err != nil {
log.Fatal("Err: %v", err)
}
var result sftypes.UpdateBulkVolumeStatusResult
decoder, err := GetDecoder(&result)
if err != nil {
log.Fatal("Err: %v", err)
}
err = decoder.Decode(response["result"])
if err != nil {
log.Fatal("Err: %v", err)
}
return result, nil
}
|
fda9c5117d1915a57dcbe4a5abc107f33a993c43
|
[
"Go"
] | 1
|
Go
|
cprokopiak/solidfire-sdk-golang
|
63703745da6ce173c1b5679014234b417bbb3d5a
|
fc83172936c14fdf36e0de78abb4dbe499e3c355
|
refs/heads/master
|
<file_sep>// Code your solution here:
function driversWithRevenueOver(drivers, revenue) {
return drivers.filter(function(driver) {
return parseInt(driver.revenue, 10) > parseInt(revenue, 10);
});
}
function driverNamesWithRevenueOver(drivers, revenue) {
const relevantDrivers = driversWithRevenueOver(drivers, revenue);
return relevantDrivers.map(function(driver) {return driver.name});
}
function exactMatch(drivers, obj) {
const keys = Object.keys(obj);
const value =obj[keys[0]];
return drivers.filter(function(driver) {
return driver[keys[0]] == value;
});
}
function exactMatchToList(drivers, obj) {
const keys = Object.keys(obj);
const value =obj[keys[0]];
const relevantDrivers = drivers.filter(function(driver) {
return driver[keys[0]] == value;
});
return relevantDrivers.map(function(driver) {return driver.name});
}
|
4b084e6f3d2aa0d828a6d2bd183da47933373350
|
[
"JavaScript"
] | 1
|
JavaScript
|
johneckert/js-looping-and-iteration-filter-and-map-lab-web-121117
|
97606c550c250cb34351a9ca7816b0523b934eab
|
e5783c009a8e68d965713741da2138c28822f799
|
refs/heads/master
|
<file_sep>#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofSetLogLevel(OF_LOG_VERBOSE);
ofBackground(0,0,0);
ofEnableSmoothing();
ofEnableBlendMode(OF_BLENDMODE_ADD);
ofSetFrameRate(30);
camWidth = 1280;
camHeight = 720;
vidGrabber.setDeviceID(0);
vidGrabber.setDesiredFrameRate(30);
vidGrabber.setVerbose(true);
vidGrabber.initGrabber(camWidth, camHeight);
ofTrueTypeFont::setGlobalDpi(72);
ofTrueTypeFontSettings settings("HiraginoSans.ttf", 15);
settings.addRanges(ofAlphabet::Japanese);
settings.addRange(ofUnicode::MathOperators);
settings.addRange(ofUnicode::Latin1Supplement);
font.load(settings);
font.setLineHeight(12);
font.setLetterSpacing(1.0);
}
//--------------------------------------------------------------
void ofApp::update() {
ofSeedRandom(39);
vidGrabber.update();
}
//--------------------------------------------------------------
void ofApp::draw(){
ofSetColor(0xffffff);
ofDrawCircle(100, 100, 209);
vidGrabber.draw(0, 0, camWidth, camHeight);
ofPixels pixels = vidGrabber.getPixels();
for (int i = 0; i < camWidth; i += 15) {
for (int j = 0; j < camHeight; j+= 15) {
unsigned char r = pixels[(j * camWidth + i) * 3];
unsigned char g = pixels[(j * camWidth + i) * 3 + 1];
unsigned char b = pixels[(j * camWidth + i) * 3 + 2];
std::string chars[] = {".", "鷲", "_", "+", "%", "#", "@", "一"};
int stringDepth = r + g + b;
int idx = 0;
if (stringDepth > 600) {
idx = 0;
} else if (stringDepth > 500) {
idx = 1;
} else if (stringDepth > 400) {
idx = 2;
} else if(stringDepth > 300) {
idx = 3;
} else if(stringDepth > 200) {
idx = 4;
} else if(stringDepth > 100) {
idx = 5;
} else if(stringDepth > 50) {
idx = 6;
} else {
idx = 7;
}
std::string s = chars[idx];
font.drawString(s, 10 + i, 10 + j);
}
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<file_sep>#pragma once
#include "ofMain.h"
class Tori {
public:
void setup();
void draw();
ofBoxPrimitive boxes[3];
};
<file_sep>#include "dog.h"
void Dog::bark(){
cout << name << " bow " << endl;
}
<file_sep>#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofSetFrameRate(30);
ofEnableDepthTest();
ofBackground(39);
ofSetColor(39);
ofEnableBlendMode(ofBlendMode::OF_BLENDMODE_ADD);
soundPlayer.load("feelGoodInc.mp3");
soundPlayer.setLoop(true);
soundPlayer.play();
ofSetLineWidth(1);
// soundPlayer.setPosition(0.791f);
soundPlayer.setPosition(0.416f);
for (int i = 0; i < this->numberOfTarget; i++) {
ofPoint noiseSeed = ofPoint(ofRandom(10), ofRandom(10), ofRandom(10));
this->noiseSeeds.push_back(noiseSeed);
deque<ofPoint> log;
this->logs.push_back(log);
}
// #23049d
// #aa2ee6
// #ff79cd
glitchColors.push_back(glm::vec3(63, 251, 240));
glitchColors.push_back(glm::vec3(170, 42, 246));
glitchColors.push_back(glm::vec3(225, 255, 255));
plane.set(ofGetWidth(), ofGetHeight(), 10, 10);
plane.setResolution(16, 16);
plane.setPosition(0, -250, 0);
plane.rotate(90, 1, 0, 0);
ofSetSmoothLighting(true);
light.setSpotlight();
light.enable();
light.setPosition(0, 50, 800);
bOrbit = bRoll = true;
angleH = roll = 0.0f;
distance = 500.f;
cam.setPosition(0, 0, 1000);
for (int i = 0; i < 30; i++) {
centerLineWidth[i] = 2000 + ofRandom(10 * i, 10 * i + 20);
}
int tileSize = 50;
for (int i = 0; i < 20; i++) {
for(int j = 0; j < 5; j++) {
int x = -200 + ((tileSize + 10) * i);
int y = -200 + ((tileSize + 10) * j);
int z = -520;
tiles[i][j].set(tileSize, tileSize, 4);
tiles[i][j].setPosition(x, y, z);
tilesR[i][j].set(tileSize, tileSize, 4);
tilesR[i][j].setPosition(x, y, -z);
tilesB[i][j].set(tileSize, tileSize, 4);
tilesB[i][j].setPosition(z, y, x);
tilesF[i][j].set(tileSize, tileSize, 4);
tilesF[i][j].setPosition(-z, y, x);
}
}
tileMaterial.setAmbientColor(ofColor(30, 63, 1));
tileMaterial.setDiffuseColor(ofColor(20, 27, 5));
tileMaterial.setSpecularColor(ofColor(5, 10, 35, 255));
tileMaterial.setShininess(1);
tileMaterial.setEmissiveColor(ofColor(37, 30, 30));
}
//--------------------------------------------------------------
void ofApp::update() {
ofSeedRandom(39);
float* rawSoundVolume = ofSoundGetSpectrum(1);
float soundVolume = rawSoundVolume[0] * 300.0;
bool isLowVolume;
if (soundVolume < 3.8) {
isLowVolume = true;
soundVolume *= 0.02;
} else {
isLowVolume = false;
soundVolume *= 0.95;
}
for (int i = 0; i < 20; i++) {
for(int j = 0; j < 5; j++) {
if (soundVolume < 3.7) {
float rX = (float)(i + j) * 7.0 * timingE + soundVolume;
float rZ = (float)(i + j) * 8.0 * timingE + soundVolume;
float rY = ofRandom(0, 42) + (float)(i + j) * 5.0 * timingE + soundVolume;
int idxShine = ((5 * i) + (10 * j)) % 155;
if (rX > 40) {
tileMaterial.setShininess(((5 * i) + (10 * j)) % 5);
tileMaterial.setAmbientColor(ofColor(idxShine, 63, 31));
tileMaterial.setSpecularColor(ofColor(idxShine, 250, 125, 155));
tileMaterial.setDiffuseColor(ofColor(idxShine, 27, 5));
rX = 50;
rZ = 50;
}
if (rY > 33) {
tileMaterial.setAmbientColor(ofColor(idxShine, idxShine, idxShine));
tileMaterial.setSpecularColor(ofColor(idxShine, idxShine, idxShine, 255));
tileMaterial.setDiffuseColor(ofColor(idxShine, idxShine, idxShine));
tileMaterial.setShininess(idxShine);
rY = 50;
}
tiles[i][j].set(rX,rY + soundVolume, rZ);
tilesR[i][j].set(rX, rY + soundVolume, rZ);
tilesB[i][j].set(rX, rY, rZ);
tilesF[i][j].set(rX, rY + soundVolume, rZ);
} else {
tiles[i][j].set((timingE * ofRandom(20, 40)) + soundVolume, ofRandom(5, 50) + timingE + soundVolume, 1);
tilesR[i][j].set((timingE * ofRandom(20, 30)) + soundVolume, ofRandom(5, 50) + timingE + soundVolume, 1);
tilesB[i][j].set((timingE * ofRandom(20, 60)) + soundVolume, ofRandom(5, 50) + timingE + soundVolume, 1);
tilesF[i][j].set((timingE * ofRandom(20, 50)) + soundVolume, ofRandom(5, 50) + timingE + soundVolume, 1);
}
}
}
// 角丸に
float seedX = ofNoise(5, ofGetFrameNum() * 0.003) * ((timingE + soundVolume) / 50.0);
float seedY = ofNoise(5, ofGetFrameNum() * 0.003) * ((timingE + soundVolume) / 50.0);
float seedZ = ofNoise(5, ofGetFrameNum() * 0.003) * ((timingE + soundVolume) / 50.0);
for (int i = 0; i < this->numberOfTarget; i++) {
float noiseX = ofNoise(this->noiseSeeds[i].x);
float noiseY = ofNoise(this->noiseSeeds[i].y);
float noiseZ = ofNoise(this->noiseSeeds[i].z);
ofPoint point(ofMap(noiseX, 0, 1, -100, 100), ofMap(noiseY, 0, 1, -100, 100), ofMap(noiseZ, 0, 1, -100, 150));
this->logs[i].push_front(point);
while (this->logs[i].size() > 10) {
this->logs[i].pop_back();
}
// 移動にeasing
this->noiseSeeds[i].x += seedX;
this->noiseSeeds[i].y += seedY;
this->noiseSeeds[i].z += seedZ;
}
if (bOrbit) {
angleH += 1.f;
if (angleH > 360.f) angleH = 0.f;
}
if (bRoll) roll += 0.5f;
float vFac = sin(angleV * M_PI / 180.f) * 90.f;
cam.orbit(angleH, vFac, distance);
linesSize += (int)(sin(timingE * 30)) * (soundVolume * 2);
}
//--------------------------------------------------------------
// TODO: render beam
void ofApp::draw(){
this->cam.begin();
timingE = abs(sin(ofGetElapsedTimef() * 7.34));
int rows = 5;
ofSetColor(255, 255, 255);
plane.drawWireframe();
// ffdf6b
// ofSetColor(255, 234, 106);
ofSetColor(255, 223, 233);
int boxHeight = 1;
int boxDepth = 1;
int boxPosY = -250;
ofBoxPrimitive box;
ofSetColor(255, 255, 255);
ofRotateYDeg(80);
tileMaterial.begin();
for (int i = 0; i < 20; i++) {
for(int j = 0; j < 5; j++) {
int deg = ofRandom(1, 2);
ofRotateYDeg(deg);
tiles[i][j].drawWireframe();
ofRotateYDeg(-deg);
ofRotateYDeg(deg);
tilesR[i][j].drawWireframe();
ofRotateYDeg(-deg);
ofRotateYDeg(deg);
tilesB[i][j].drawWireframe();
ofRotateYDeg(-deg);
tilesF[i][j].drawWireframe();
}
}
tileMaterial.end();
ofRotateYDeg(-80);
ofSetColor(55, 55, 55);
for (int i = 0; i < linesSize; i++) {
box.set(centerLineWidth[i % linesSize] + ofRandom(-20, 20), boxHeight, boxDepth);
box.setPosition(50, boxPosY, 30 + ofRandom(-200, 200));
box.draw();
}
for (int i = 0; i < linesSize; i++) {
box.set(boxDepth, boxHeight, centerLineWidth[i % linesSize] + ofRandom(-20, 20));
box.setPosition(ofRandom(-200, 200), boxPosY, 30 + 0);
box.draw();
}
for (int i = 0; i < linesSize; i++) {
box.set(centerLineWidth[i % linesSize] + ofRandom(-20, 20), boxHeight, boxDepth);
box.setPosition(50, boxPosY * -1, 30 + ofRandom(-200, 200));
box.draw();
}
for (int i = 0; i < linesSize; i++) {
box.set(boxDepth, boxHeight, centerLineWidth[i % linesSize] + ofRandom(-20, 20));
box.setPosition(ofRandom(-200, 200), boxPosY * -1, 30 + 0);
box.draw();
}
for (int i = 0; i < this->numberOfTarget; i++) {
ofPushMatrix();
int posX = i % 16;
int posY = i % rows;
int x = ofGetWidth() * -0.15 + (20.0 * (posX));
int y = ofGetHeight() * -0.15 + (20.0 * (posY));
int z = -200 + 25.0 * (i % 16);
ofTranslate(x, y, z);
ofNoFill();
ofBeginShape();
glm::vec3 currentColor = glitchColors[0];
ofSetColor(currentColor.x * timingE, currentColor.y * timingE, currentColor.z * timingE);
for (int l = 0; l < this->logs[i].size(); l++) {
ofPoint basePoint = this->logs[i][l];
ofVertex(basePoint);
}
ofEndShape();
ofFill();
ofSetColor(currentColor.x * timingE + 30, currentColor.y * timingE + 30, currentColor.z * timingE + 30);
// 先端
ofDrawSphere(this->logs[i][0], 2);
ofPopMatrix();
}
this->cam.end();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key) {
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<file_sep>#include "ofApp.h"
static const int PARTICLES = 1000;
//--------------------------------------------------------------
void ofApp::setup(){
ofSetFrameRate(60);
ofEnableDepthTest();
ofBackground(0);
ofSetSmoothLighting(true);
light.setSpotlight();
light.setPosition(0, 200, 250);
light.enable();
plane.set(800, 800);
plane.setPosition(0, -150, 125);
for (int i = 0; i < PARTICLES; i++) {
particles[i].set(2, 8);
particles[i].setPosition(ofRandom(-250, 250), ofRandom(-20, 0), ofRandom(-400, 0));
}
tori.setup();
}
//--------------------------------------------------------------
void ofApp::update() {
}
//--------------------------------------------------------------
void ofApp::draw(){
cam.begin();
for (int i = 0; i < PARTICLES; i++) {
light.setSpecularColor(ofColor(255, 255, 255));
light.setDiffuseColor(ofColor(172, 172, 172));
light.setAmbientColor(ofColor(39));
ofSetColor(255);
particles[i].draw();
}
ofSetColor(0);
light.setSpecularColor(ofColor(0, 0, 0));
light.setDiffuseColor(ofColor(0, 0, 0));
light.setAmbientColor(ofColor(0));
tori.draw();
ofRotateXDeg(90);
plane.draw();
cam.end();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<file_sep>#pragma once
#include "ofMain.h"
#include "tori.h"
class ofApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void keyPressed(int key);
void keyReleased(int key);
void mouseMoved(int x, int y);
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void mouseEntered(int x, int y);
void mouseExited(int x, int y);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
ofEasyCam cam;
ofLight light;
ofPlanePrimitive plane;
ofBoxPrimitive tiles[20][5];
ofBoxPrimitive tilesR[20][5];
ofBoxPrimitive tilesB[20][5];
ofBoxPrimitive tilesF[20][5];
int numberOfTarget = 512;
vector<ofPoint> noiseSeeds;
vector<deque<ofPoint>> logs;
// line
vector<glm::vec3> glitchColors;
ofSoundPlayer soundPlayer;
float speedX;
float speedY;
float timingE;
float angle;
bool bOrbit, bRoll;
float angleH, roll, distance;
float angleV = -9.0f;
int centerLineWidth[30];
int linesSize = 30;
ofMaterial tileMaterial;
};
<file_sep>#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofSetFrameRate(60);
ofBackground(239);
ofSetColor(39);
this->font.loadFont("fonts/HiraginoSans.ttf", 28, true, true, true);
}
//--------------------------------------------------------------
void ofApp::update(){
ofSeedRandom(39);
}
//--------------------------------------------------------------
void ofApp::draw(){
cam.begin();
ofRotateX(ofGetFrameNum() * 0.25 * sin(ofGetElapsedTimef() * 0.1));
ofRotateY(ofGetFrameNum() * 0.5);
for (int i = 0; i < 1000; i++) {
ofPushMatrix();
auto location = glm::vec3(ofRandom(-ofGetWidth(), ofGetWidth()), ofRandom(-ofGetHeight(), ofGetHeight()), ofRandom(-720, 720));
ofTranslate(location);
ofRotateX(ofMap(ofNoise(ofRandom(10000), ofGetFrameNum() * 0.005), 0, 1, -180, 180));
ofRotateY(ofMap(ofNoise(ofRandom(10000), ofGetFrameNum() * 0.005), 0, 1, -180, 180));
ofRotateZ(ofMap(ofNoise(ofRandom(10000), ofGetFrameNum() * 0.005), 0, 1, -180, 180));
char noise_value = ofMap(ofNoise(location.x * 0.008, location.y * 0.008, location.z * 0.008, ofGetFrameNum() * 0.004), 0, 1, 'D', 'Z');
this->font.drawString({ noise_value }, -14, -14);
ofPopMatrix();
}
cam.end();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<file_sep>#include "tori.h"
void Tori::setup() {
// 上辺
boxes[0].set(50, 50, 400);
boxes[0].setPosition(0, 300, -100);
// 上辺奥
boxes[1].set(50, 400, 50);
boxes[1].setPosition(0, 75, -275);
// 上辺手前
boxes[2].set(50, 400, 50);
boxes[2].setPosition(0, 75, 75);
}
void Tori::draw() {
for (int i = 0; i < 3; i++) {
boxes[i].draw();
}
}
<file_sep>#pragma once
#include "ofApp.h"
class Dog {
public:
string name;
void bark();
};
|
14065d4562a8aa6e9ebb5331c6c14396f64ec827
|
[
"C++"
] | 9
|
C++
|
OdaDaisuke/of-sandbox
|
4895e32dd28cbe6273124d283208876773d6446e
|
7e6eecf6fa64d24974989fc69a13a7521a968b79
|
refs/heads/master
|
<repo_name>SwiftWinds/HorizonNet<file_sep>/train.py
import os
import argparse
import numpy as np
from tqdm import trange
from tensorboardX import SummaryWriter
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import optim
from torch.utils.data import DataLoader
from model import HorizonNet, ENCODER_RESNET, ENCODER_DENSENET
from dataset import PanoCorBonDataset
from misc.utils import group_weight, adjust_learning_rate, save_model, load_trained_model
from inference import inference
from eval_general import test_general
def feed_forward(net, x, y_bon, y_cor):
x = x.to(device)
y_bon = y_bon.to(device)
y_cor = y_cor.to(device)
losses = {}
y_bon_, y_cor_ = net(x)
losses['bon'] = F.l1_loss(y_bon_, y_bon)
losses['cor'] = F.binary_cross_entropy_with_logits(y_cor_, y_cor)
losses['total'] = losses['bon'] + losses['cor']
return losses
if __name__ == '__main__':
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--id', required=True,
help='experiment id to name checkpoints and logs')
parser.add_argument('--ckpt', default='./ckpt',
help='folder to output checkpoints')
parser.add_argument('--logs', default='./logs',
help='folder to logging')
parser.add_argument('--pth', default=None,
help='path to load saved checkpoint.'
'(finetuning)')
# Model related
parser.add_argument('--backbone', default='resnet50',
choices=ENCODER_RESNET + ENCODER_DENSENET,
help='backbone of the network')
parser.add_argument('--no_rnn', action='store_true',
help='whether to remove rnn or not')
# Dataset related arguments
parser.add_argument('--train_root_dir', default='data/layoutnet_dataset/train',
help='root directory to training dataset. '
'should contains img, label_cor subdirectories')
parser.add_argument('--valid_root_dir', default='data/layoutnet_dataset/valid',
help='root directory to validation dataset. '
'should contains img, label_cor subdirectories')
parser.add_argument('--no_flip', action='store_true',
help='disable left-right flip augmentation')
parser.add_argument('--no_rotate', action='store_true',
help='disable horizontal rotate augmentation')
parser.add_argument('--no_gamma', action='store_true',
help='disable gamma augmentation')
parser.add_argument('--no_pano_stretch', action='store_true',
help='disable pano stretch')
parser.add_argument('--num_workers', default=6, type=int,
help='numbers of workers for dataloaders')
# optimization related arguments
parser.add_argument('--freeze_earlier_blocks', default=-1, type=int)
parser.add_argument('--batch_size_train', default=4, type=int,
help='training mini-batch size')
parser.add_argument('--batch_size_valid', default=2, type=int,
help='validation mini-batch size')
parser.add_argument('--epochs', default=300, type=int,
help='epochs to train')
parser.add_argument('--optim', default='Adam',
help='optimizer to use. only support SGD and Adam')
parser.add_argument('--lr', default=1e-4, type=float,
help='learning rate')
parser.add_argument('--lr_pow', default=0.9, type=float,
help='power in poly to drop LR')
parser.add_argument('--warmup_lr', default=1e-6, type=float,
help='starting learning rate for warm up')
parser.add_argument('--warmup_epochs', default=0, type=int,
help='numbers of warmup epochs')
parser.add_argument('--beta1', default=0.9, type=float,
help='momentum for sgd, beta1 for adam')
parser.add_argument('--weight_decay', default=0, type=float,
help='factor for L2 regularization')
parser.add_argument('--bn_momentum', type=float)
# Misc arguments
parser.add_argument('--no_cuda', action='store_true',
help='disable cuda')
parser.add_argument('--seed', default=594277, type=int,
help='manual seed')
parser.add_argument('--disp_iter', type=int, default=1,
help='iterations frequency to display')
parser.add_argument('--save_every', type=int, default=25,
help='epochs frequency to save state_dict')
args = parser.parse_args()
device = torch.device('cpu' if args.no_cuda else 'cuda')
np.random.seed(args.seed)
torch.manual_seed(args.seed)
os.makedirs(os.path.join(args.ckpt, args.id), exist_ok=True)
# Create dataloader
dataset_train = PanoCorBonDataset(
root_dir=args.train_root_dir,
flip=not args.no_flip, rotate=not args.no_rotate, gamma=not args.no_gamma,
stretch=not args.no_pano_stretch)
loader_train = DataLoader(dataset_train, args.batch_size_train,
shuffle=True, drop_last=True,
num_workers=args.num_workers,
pin_memory=not args.no_cuda,
worker_init_fn=lambda x: np.random.seed())
if args.valid_root_dir:
dataset_valid = PanoCorBonDataset(
root_dir=args.valid_root_dir, return_cor=True,
flip=False, rotate=False, gamma=False,
stretch=False)
# Create model
if args.pth is not None:
print('Finetune model is given.')
print('Ignore --backbone and --no_rnn')
net = load_trained_model(HorizonNet, args.pth).to(device)
else:
net = HorizonNet(args.backbone, not args.no_rnn).to(device)
assert -1 <= args.freeze_earlier_blocks and args.freeze_earlier_blocks <= 4
if args.freeze_earlier_blocks != -1:
b0, b1, b2, b3, b4 = net.feature_extractor.list_blocks()
blocks = [b0, b1, b2, b3, b4]
for i in range(args.freeze_earlier_blocks + 1):
print('Freeze block%d' % i)
for m in blocks[i]:
for param in m.parameters():
param.requires_grad = False
if args.bn_momentum:
for m in net.modules():
if isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d)):
m.momentum = args.bn_momentum
# Create optimizer
if args.optim == 'SGD':
optimizer = optim.SGD(
filter(lambda p: p.requires_grad, net.parameters()),
lr=args.lr, momentum=args.beta1, weight_decay=args.weight_decay)
elif args.optim == 'Adam':
optimizer = optim.Adam(
filter(lambda p: p.requires_grad, net.parameters()),
lr=args.lr, betas=(args.beta1, 0.999), weight_decay=args.weight_decay)
else:
raise NotImplementedError()
# Create tensorboard for monitoring training
tb_path = os.path.join(args.logs, args.id)
os.makedirs(tb_path, exist_ok=True)
tb_writer = SummaryWriter(log_dir=tb_path)
# Init variable
args.warmup_iters = args.warmup_epochs * len(loader_train)
args.max_iters = args.epochs * len(loader_train)
args.running_lr = args.warmup_lr if args.warmup_epochs > 0 else args.lr
args.cur_iter = 0
args.best_valid_score = 0
# Start training
for ith_epoch in trange(1, args.epochs + 1, desc='Epoch', unit='ep'):
# Train phase
net.train()
if args.freeze_earlier_blocks != -1:
b0, b1, b2, b3, b4 = net.feature_extractor.list_blocks()
blocks = [b0, b1, b2, b3, b4]
for i in range(args.freeze_earlier_blocks + 1):
for m in blocks[i]:
m.eval()
iterator_train = iter(loader_train)
for _ in trange(len(loader_train),
desc='Train ep%s' % ith_epoch, position=1):
# Set learning rate
adjust_learning_rate(optimizer, args)
args.cur_iter += 1
x, y_bon, y_cor = next(iterator_train)
losses = feed_forward(net, x, y_bon, y_cor)
for k, v in losses.items():
k = 'train/%s' % k
tb_writer.add_scalar(k, v.item(), args.cur_iter)
tb_writer.add_scalar('train/lr', args.running_lr, args.cur_iter)
loss = losses['total']
# backprop
optimizer.zero_grad()
loss.backward()
nn.utils.clip_grad_norm_(net.parameters(), 3.0, norm_type='inf')
optimizer.step()
# Valid phase
net.eval()
if args.valid_root_dir:
valid_loss = {}
for jth in trange(len(dataset_valid),
desc='Valid ep%d' % ith_epoch, position=2):
x, y_bon, y_cor, gt_cor_id = dataset_valid[jth]
x, y_bon, y_cor = x[None], y_bon[None], y_cor[None]
with torch.no_grad():
losses = feed_forward(net, x, y_bon, y_cor)
# True eval result instead of training objective
true_eval = dict([
(n_corner, {'2DIoU': [], '3DIoU': [], 'rmse': [], 'delta_1': []})
for n_corner in ['4', '6', '8', '10+', 'odd', 'overall']
])
try:
dt_cor_id = inference(net, x, device, force_cuboid=False)[0]
dt_cor_id[:, 0] *= 1024
dt_cor_id[:, 1] *= 512
except:
dt_cor_id = np.array([
[k//2 * 1024, 256 - ((k%2)*2 - 1) * 120]
for k in range(8)
])
test_general(dt_cor_id, gt_cor_id, 1024, 512, true_eval)
losses['2DIoU'] = torch.FloatTensor([true_eval['overall']['2DIoU']])
losses['3DIoU'] = torch.FloatTensor([true_eval['overall']['3DIoU']])
losses['rmse'] = torch.FloatTensor([true_eval['overall']['rmse']])
losses['delta_1'] = torch.FloatTensor([true_eval['overall']['delta_1']])
for k, v in losses.items():
valid_loss[k] = valid_loss.get(k, 0) + v.item() * x.size(0)
for k, v in valid_loss.items():
k = 'valid/%s' % k
tb_writer.add_scalar(k, v / len(dataset_valid), ith_epoch)
# Save best validation loss model
now_valid_score = valid_loss['3DIoU'] / len(dataset_valid)
print('Ep%3d %.4f vs. Best %.4f' % (ith_epoch, now_valid_score, args.best_valid_score))
if now_valid_score > args.best_valid_score:
args.best_valid_score = now_valid_score
save_model(net,
os.path.join(args.ckpt, args.id, 'best_valid.pth'),
args)
# Periodically save model
if ith_epoch % args.save_every == 0:
save_model(net,
os.path.join(args.ckpt, args.id, 'epoch_%d.pth' % ith_epoch),
args)
<file_sep>/misc/gen_txt_structured3d.py
'''
Help generate txt for train.py
Please contact https://github.com/bertjiazheng/Structured3D for dataset.
'''
import os
import glob
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--root', required=True,
help='path to the dataset directory')
parser.add_argument('--train_txt', required=True,
help='path to save txt for train')
parser.add_argument('--valid_txt', required=True,
help='path to save txt for valid')
parser.add_argument('--test_txt', required=True,
help='path to save txt for test')
args = parser.parse_args()
train_scene = ['scene_%05d' % i for i in range(0, 3000)]
valid_scene = ['scene_%05d' % i for i in range(3000, 3250)]
test_scene = ['scene_%05d' % i for i in range(3250, 3500)]
# Simple check: all directories exist
for path in train_scene + valid_scene + test_scene:
assert os.path.isdir(os.path.join(args.root, path)), '%s not found' % path
def gen_pairs(scene_id_lst):
pairs = []
for scene_id in scene_id_lst:
for fname in os.listdir(os.path.join(args.root, scene_id, 'rgb')):
room_id = os.path.split(fname)[1].split('_')[0]
img_k = os.path.join(os.path.join(scene_id, 'rgb', fname))
layout_k = os.path.join(os.path.join(scene_id, 'layout', room_id + '_layout.txt'))
assert os.path.isfile(os.path.join(args.root, img_k))
assert os.path.isfile(os.path.join(args.root, layout_k))
pairs.append((img_k, layout_k))
return pairs
with open(args.train_txt, 'w') as f:
pairs = gen_pairs(train_scene)
f.write('\n'.join([' '.join(p) for p in pairs]))
with open(args.valid_txt, 'w') as f:
pairs = gen_pairs(valid_scene)
f.write('\n'.join([' '.join(p) for p in pairs]))
with open(args.test_txt, 'w') as f:
pairs = gen_pairs(test_scene)
f.write('\n'.join([' '.join(p) for p in pairs]))
<file_sep>/README_ST3D.md
# Results on Structured3D dataset
References:
- [Structured3D: A Large Photo-realistic Dataset for Structured 3D Modeling](https://arxiv.org/abs/1908.00222)
- [Structured3D project page](http://structured3d-dataset.org)
- [Structured3D github](https://github.com/bertjiazheng/Structured3D)
## Dataset preparation
- Please contact [Structured3D](http://structured3d-dataset.org) to get the datas.
- Download all zip files under `{YOUR_DIR}`. Don't extract them.
- Run below to extract rgb and layout with original furniture and lighting setting only:
```bash
python misc/structured3d_extract_zip.py --zippath {YOUR_DIR}/Structured3D_0.zip --outdir {TARGET_DIR_EXTRACT}
python misc/structured3d_extract_zip.py --zippath {YOUR_DIR}/Structured3D_1.zip --outdir {TARGET_DIR_EXTRACT}
# ... for all Structured3D_?.zip
```
- Run below to create `data/st3d_[train|valid|test]_full_raw_light` following HorizonNet training and testing dataset format. (This will use soft link instead of copy a new one.)
```bash
python misc/structured3d_prepare_dataset.py --in_root {TARGET_DIR_EXTRACT}
```
## Training
```bash
python train.py --train_root_dir data/st3d_train_full_raw_light/ --valid_root_dir data/st3d_valid_full_raw_light/ --id resnet50_rnn__st3d --lr 3e-4 --batch_size_train 24 --epochs 50
```
See `python train.py -h` or [README.md#training](https://github.com/sunset1995/HorizonNet#training) for more detail.
Download the trained model: [resnet50_rnn__st3d.pth](https://drive.google.com/open?id=16v1nhL9C2VZX-qQpikCsS6LiMJn3q6gO).
- Trained on Structured3D 18362 pano images with setting of original furniture and lighting.
- Trained for 50 epoch.
- Select 50th epoch according to loss function on validation set.
## Testing
Generating layout for testing set:
```bash
python inference.py --pth ckpt/resnet50_rnn__st3d.pth --img_glob "data/st3d_test_full_raw_light/img/*" --output_dir ./output/st3d/resnet50_rnn/ --visualize
```
- `--output_dir`: a directory you want to dump the extracted layout
- `--visualize`: visualize raw output (without post-processing) from HorizonNet.
## Quantitative evaluatation:
```bash
python eval_general.py --dt_glob "./output/st3d/resnet50_rnn/*json" --gt_glob "data/st3d_test_full_raw_light/label_cor/*"
```
:clipboard: Below is the quantitative result on Structured3D testing set.
| # of corners | instances | 3D IoU | 2D IoU |
| :----------: | :-------: | :----: | :----: |
| 4 | 1067 | `94.14` | `95.50` |
| 6 | 290 | `90.34` | `91.54` |
| 8 | 130 | `87.98` | `89.43` |
| 10+ | 202 | `79.95` | `81.10` |
| odd | 4 | `88.62` | `89.80` |
| overall | 1693 | `91.31` | `92.63` |
- The `odd` row mean non-even number of corners (ground truth is obviously non-manhattan layout while model output is the approximation of it)
#### Invalid Ground Truth
Four instances are skip by `eval_general.py` as the ground truth is self-intersecting. The top-down view of the four skipped instance are illutrated below where the red dot line are estimated by HorizonNet and the green solid line is the self-intersected ground truth.
| `scene_03327_315045` | `scene_03376_800900` | `scene_03399_337` | `scene_03478_2193` |
| :--: | :--: | :--: | :--: |
|  |  |  |  |
## Qualitative Results
##### From Structured3D testing set `scene_03300_[190736,190737,190738]`:



##### Model pretrained on Structured3D and directly testing on PanoContext:












<file_sep>/preprocess.py
'''
This script preprocess the given 360 panorama image under euqirectangular projection
and dump them to the given directory for further layout prediction and visualization.
The script will:
- extract and dump the vanishing points
- rotate the equirect image to align with the detected VP
- extract the VP aligned line segments (for further layout prediction model)
The dump files:
- `*_VP.txt` is the vanishg points
- `*_aligned_rgb.png` is the VP aligned RGB image
- `*_aligned_line.png` is the VP aligned line segments images
Author: <NAME>
Email : <EMAIL>
'''
import os
import glob
import argparse
import numpy as np
from PIL import Image
from misc.pano_lsd_align import panoEdgeDetection, rotatePanorama
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter)
# I/O related arguments
parser.add_argument('--img_glob', required=True,
help='NOTE: Remeber to quote your glob path.')
parser.add_argument('--output_dir', required=True)
parser.add_argument('--rgbonly', action='store_true',
help='Add this if use are preparing customer dataset')
# Preprocessing related arguments
parser.add_argument('--q_error', default=0.7, type=float)
parser.add_argument('--refine_iter', default=3, type=int)
args = parser.parse_args()
paths = sorted(glob.glob(args.img_glob))
if len(paths) == 0:
print('no images found')
# Check given path exist
for path in paths:
assert os.path.isfile(path), '%s not found' % path
# Check target directory
if not os.path.isdir(args.output_dir):
print('Output directory %s not existed. Create one.')
os.makedirs(args.output_dir)
# Process each input
for i_path in paths:
print('Processing', i_path, flush=True)
# Load and cat input images
img_ori = np.array(Image.open(i_path).resize((1024, 512), Image.BICUBIC))[..., :3]
# VP detection and line segment extraction
_, vp, _, _, panoEdge, _, _ = panoEdgeDetection(img_ori,
qError=args.q_error,
refineIter=args.refine_iter)
panoEdge = (panoEdge > 0)
# Align images with VP
i_img = rotatePanorama(img_ori / 255.0, vp[2::-1])
l_img = rotatePanorama(panoEdge.astype(np.float32), vp[2::-1])
# Dump results
basename = os.path.splitext(os.path.basename(i_path))[0]
if args.rgbonly:
path = os.path.join(args.output_dir, '%s.png' % basename)
Image.fromarray((i_img * 255).astype(np.uint8)).save(path)
else:
path_VP = os.path.join(args.output_dir, '%s_VP.txt' % basename)
path_i_img = os.path.join(args.output_dir, '%s_aligned_rgb.png' % basename)
path_l_img = os.path.join(args.output_dir, '%s_aligned_line.png' % basename)
with open(path_VP, 'w') as f:
for i in range(3):
f.write('%.6f %.6f %.6f\n' % (vp[i, 0], vp[i, 1], vp[i, 2]))
Image.fromarray((i_img * 255).astype(np.uint8)).save(path_i_img)
Image.fromarray((l_img * 255).astype(np.uint8)).save(path_l_img)
<file_sep>/README.md
# HorizonNet
This is the implementation of our CVPR'19 "[
HorizonNet: Learning Room Layout with 1D Representation and Pano Stretch Data Augmentation](https://arxiv.org/abs/1901.03861)" ([project page](https://sunset1995.github.io/HorizonNet/)).
**News, June 15, 2019** - Critical bug fix for general layout (`dataset.py`, `inference.py` and `misc/post_proc.py`)\
**News, Aug 19, 2019** - Report results on [Structured3D dataset](https://structured3d-dataset.org/). (See [the report :clipboard: on ST3D](README_ST3D.md)).

This repo is a **pure python** implementation that you can:
- **Inference on your images** to get cuboid or general shaped room layout
- **3D layout viewer**
- **Correct pose** for your panorama images
- **Pano Stretch Augmentation** copy and paste to apply on your own task
- **Quantitative evaluatation** (3D IoU, Corner Error, Pixel Error)
- cuboid shape
- general shape
- **Your own dataset** preparation and training
**Method Pipeline overview**:

## Requirements
- Python 3
- pytorch>=1.0.0
- numpy
- scipy
- sklearn
- Pillow
- tqdm
- tensorboardX
- opencv-python>=3.1 (for pre-processing) (also can't be too new, the latest opencv removed a key algorithm due to patent, 3.1.0.5 works. )
- open3d>=0.7 (for layout 3D viewer)
- shapely
- torchvision
### Download
#### Dataset
- PanoContext/Stanford2D3D Dataset
- [Download preprocessed pano/s2d3d](https://drive.google.com/open?id=1e-MuWRx3T4LJ8Bu4Dc0tKcSHF9Lk_66C) for training/validation/testing
- Put all of them under `data` directory so you should get:
```
HorizonNet/
├──data/
| ├──layoutnet_dataset/
| | |--finetune_general/
| | |--test/
| | |--train/
| | |--valid/
```
- `test`, `train`, `valid` are processed from [LayoutNet's cuboid dataset](https://github.com/zouchuhang/LayoutNet).
- `finetune_general` is re-annotated by us from `train` and `valid`. It contains 65 general shaped rooms.
- Structured3D Dataset
- See [the tutorial](https://github.com/sunset1995/HorizonNet/blob/master/README_ST3D.md#dataset-preparation) to prepare training/validation/testing for HorizonNet.
#### Pretrained Models
- [resnet50_rnn__panos2d3d.pth](https://drive.google.com/open?id=1aieMd61b-3BoOeTRv2pKu9yTk5zEinn0)
- Trained on PanoContext/Stanford2d3d 817 pano images.
- Trained for 300 epoch
- [resnet50_rnn__st3d.pth](https://drive.google.com/open?id=16v1nhL9C2VZX-qQpikCsS6LiMJn3q6gO)
- Trained on Structured3D 18362 pano images with setting of original furniture and lighting.
- Trained for 50 epoch.
- Select 50th epoch according to loss function on validation set.
## Inference on your images
In below explaination, I will use `assets/demo.png` for example.
-  (modified from PanoContext dataset)
### 1. Pre-processing (Align camera rotation pose)
- **Execution**: Pre-process the above `assets/demo.png` by firing below command.
```bash
python preprocess.py --img_glob assets/demo.png --output_dir assets/preprocessed/
```
- `--img_glob` telling the path to your 360 room image(s).
- support shell-style wildcards with quote (e.g. `"my_fasinated_img_dir/*png"`).
- `--output_dir` telling the path to the directory for dumping the results.
- See `python preprocess.py -h` for more detailed script usage help.
- **Outputs**: Under the given `--output_dir`, you will get results like below and prefix with source image basename.
- The aligned rgb images `[SOURCE BASENAME]_aligned_rgb.png` and line segments images `[SOURCE BASENAME]_aligned_line.png`
- `demo_aligned_rgb.png` | `demo_aligned_line.png`
:--------------------: | :---------------------:
 | 
- The detected vanishing points `[SOURCE BASENAME]_VP.txt` (Here `demo_VP.txt`)
```
-0.002278 -0.500449 0.865763
0.000895 0.865764 0.500452
0.999999 -0.001137 0.000178
```
### 2. Estimating layout with HorizonNet
- **Execution**: Predict the layout from above aligned image and line segments by firing below command.
```bash
python inference.py --pth ckpt/resnet50_rnn__st3d.pth --img_glob assets/preprocessed/demo_aligned_rgb.png --output_dir assets/inferenced --visualize
```
- `--pth` path to the trained model.
- `--img_glob` path to the preprocessed image.
- `--output_dir` path to the directory to dump results.
- `--visualize` optinoal for visualizing model raw outputs.
- `--force_cuboid` add this option if you want to estimate cuboid layout (4 walls).
- **Outputs**: You will get results like below and prefix with source image basename.
- The 1d representation are visualized under file name `[SOURCE BASENAME].raw.png`
- The extracted corners of the layout `[SOURCE BASENAME].json`
```
{"z0": 50.0, "z1": -59.03114700317383, "uv": [[0.029913906008005142, 0.2996523082256317], [0.029913906008005142, 0.7240479588508606], [0.015625, 0.3819984495639801], [0.015625, 0.6348703503608704], [0.056027885526418686, 0.3881891965866089], [0.056027885526418686, 0.6278984546661377], [0.4480381906032562, 0.3970482349395752], [0.4480381906032562, 0.6178648471832275], [0.5995567440986633, 0.41122356057167053], [0.5995567440986633, 0.601679801940918], [0.8094607591629028, 0.36505699157714844], [0.8094607591629028, 0.6537724137306213], [0.8815288543701172, 0.2661873996257782], [0.8815288543701172, 0.7582473754882812], [0.9189453125, 0.31678876280784607], [0.9189453125, 0.7060701847076416]]}
```
### 3. Layout 3D Viewer
- **Execution**: Visualizing the predicted layout in 3D using points cloud.
```bash
python layout_viewer.py --img assets/preprocessed/demo_aligned_rgb.png --layout assets/inferenced/demo_aligned_rgb.json --ignore_ceiling
```
- `--img` path to preprocessed image
- `--layout` path to the json output from `inference.py`
- `--ignore_ceiling` prevent showing ceiling
- See `python layout_viewer.py -h` for usage help.
- **Outputs**: In the window, you can use mouse and scroll wheel to change the viewport
- 
## Your own dataset
See [tutorial](README_PREPARE_DATASET.md) on how to prepare it.
## Training
To train on a dataset, see `python train.py -h` for detailed options explaination.\
Example:
```bash
python train.py --id resnet50_rnn
```
- Important arguments:
- `--id` required. experiment id to name checkpoints and logs
- `--ckpt` folder to output checkpoints (default: ./ckpt)
- `--logs` folder to logging (default: ./logs)
- `--pth` finetune mode if given. path to load saved checkpoint.
- `--backbone` backbone of the network (default: resnet50)
- other options: `{resnet18,resnet34,resnet50,resnet101,resnet152,resnext50_32x4d,resnext101_32x8d,densenet121,densenet169,densenet161,densenet201}`
- `--no_rnn` whether to remove rnn (default: False)
- `--train_root_dir` root directory to training dataset. (default: `data/layoutnet_dataset/train`)
- `--valid_root_dir` root directory to validation dataset. (default: `data/layoutnet_dataset/valid/`)
- If giveng, the epoch with best 3DIoU on validation set will be saved as `{ckpt}/{id}/best_valid.pth`
- `--batch_size_train` training mini-batch size (default: 4)
- `--epochs` epochs to train (default: 300)
- `--lr` learning rate (default: 0.0001)
## Quantitative Evaluation - Cuboid Layout
To evaluate on PanoContext/Stanford2d3d dataset, first running the cuboid trained model for all testing images:
```bash
python inference.py --pth ckpt/resnet50_rnn__panos2d3d.pth --img_glob "data/layoutnet_dataset/test/img/*" --output_dir output/panos2d3d/resnet50_rnn/ --force_cuboid
```
- `--img_glob` shell-style wildcards for all testing images.
- `--output_dir` path to the directory to dump results.
- `--force_cuboid` enfoce output cuboid layout (4 walls) or the PE and CE can't be evaluated.
To get the quantitative result:
```bash
python eval_cuboid.py --dt_glob "output/panos2d3d/resnet50_rnn/*json" --gt_glob "data/layoutnet_dataset/test/label_cor/*txt"
```
- `--dt_glob` shell-style wildcards for all the model estimation.
- `--gt_glob` shell-style wildcards for all the ground truth.
If you want to:
- just evaluate PanoContext only `python eval_cuboid.py --dt_glob "output/panos2d3d/resnet50_rnn/*json" --gt_glob "data/layoutnet_dataset/test/label_cor/pano*txt"`
- just evaluate Stanford2d3d only `python eval_cuboid.py --dt_glob "output/panos2d3d/resnet50_rnn/*json" --gt_glob "data/layoutnet_dataset/test/label_cor/camera*txt"`
:clipboard: The quantitative result for the released `resnet50_rnn__panos2d3d.pth` is shown below:
| Testing Dataset | 3D IoU(%) | Corner error(%) | Pixel error(%) |
| :-------------: | :-------: | :------: | :--------------: |
| PanoContext | `83.39` | `0.76` | `2.13` |
| Stanford2D3D | `84.09` | `0.63` | `2.06` |
| All | `83.87` | `0.67` | `2.08` |
## Quantitative Evaluation - General Layout
- See [the report :clipboard: on ST3D](README_ST3D.md) for more detail.
- See [the report :clipboard: on MP3D](README_MP3D.md) for more detail.
## TODO
- Faster pre-processing script (top-fron alignment) (maybe cython implementation or [fernandez2018layouts](https://github.com/cfernandezlab/Lines-and-Vanishing-Points-directly-on-Panoramas))
## Acknowledgement
- Credit of this repo is shared with [ChiWeiHsiao](https://github.com/ChiWeiHsiao).
- Thanks [limchaos](https://github.com/limchaos) for the suggestion about the potential boost by fixing the non-expected behaviour of Pytorch dataloader. (See [Issue#4](https://github.com/sunset1995/HorizonNet/issues/4))
## Citation
Please cite our paper for any purpose of usage.
```
@inproceedings{SunHSC19,
author = {<NAME> and
Chi{-}<NAME> and
<NAME> and
Hwann{-}<NAME>},
title = {HorizonNet: Learning Room Layout With 1D Representation and Pano Stretch
Data Augmentation},
booktitle = {{IEEE} Conference on Computer Vision and Pattern Recognition, {CVPR}
2019, Long Beach, CA, USA, June 16-20, 2019},
pages = {1047--1056},
year = {2019},
}
```
<file_sep>/README_PREPARE_DATASET.md
# How to prepare your dataset?
**TLDR;**
- Aligned images in `your_dataset/img/*.png` and ground truth in `your_dataset/label_cor/*.txt`
- Image in `1024 x 512` resolution
- Ground truth format:
```
x_0 y_ceiling_0
x_0 y_floor_0
x_1 y_ceiling_1
x_1 y_floor_1
...
```
which follows the order of layout.
----
The dataset should be organized as below format for `train.py` to use it:
```
your_dataset/
|--img/
| |--AAAA.png
| |--BBBB.png
| |--...
|--label_cor/
| |--AAAA.txt
| |--BBBB.txt
| |--...
```
Please also note that:
- Your imaages should be aligned. If not, run `python preprocess.py --img_glob "your_dataset/rawimg/*png" --output_dir your_dataset/img --rgbonly`.
- All prefix names between images and grond truth should match. I.e if there is a `ASDF.png` in `your_dataset/img/` directory, there should be a `ASDF.txt` in `your_dataset/label_cor/`.
- All images have to be in the resolution of `1024 width x 512 height` for current implementation.
- Check your dataset is proper and ready for training by `python dataset.py --root_dir your_dataset/ --ith -1 --out_dir your_dataset/visualize`. Please check the ground truth visualization in `your_dataset/visualize` to make sure all thing go right.
### More notes about ground truth
- Each line of the txt is a corners in image coordinate (top-left is origin)
- x in range 0~1023
- y in range 0~511
- Format:
```
x_0 y_ceiling_0
x_0 y_floor_0
x_1 y_ceiling_1
x_1 y_floor_1
...
```
- Odd lines are ceiling corners; even lines are floor corners.
- Note that `x` values have NOT to be monotonically increasing but have to follow the order of layout (see below example).
- One example of image and ground truth pair:
- ```
158 186
158 329
353 185
353 330
594 154
594 363
713 100
713 415
692 77
692 438
965 150
965 367
```
- Please note that `713 100` and it floor correspondent `713 415` are occluded.
- 
<file_sep>/misc/pano_lsd_align.py
'''
This script is helper function for preprocessing.
Most of the code are converted from LayoutNet official's matlab code.
All functions, naming rule and data flow follow official for easier
converting and comparing.
Code is not optimized for python or numpy yet.
Author: <NAME>
Email : <EMAIL>
'''
import sys
import numpy as np
from scipy.ndimage import map_coordinates
import cv2
def computeUVN(n, in_, planeID):
'''
compute v given u and normal.
'''
if planeID == 2:
n = np.array([n[1], n[2], n[0]])
elif planeID == 3:
n = np.array([n[2], n[0], n[1]])
bc = n[0] * np.sin(in_) + n[1] * np.cos(in_)
bs = n[2]
out = np.arctan(-bc / (bs + 1e-9))
return out
def computeUVN_vec(n, in_, planeID):
'''
vectorization version of computeUVN
@n N x 3
@in_ MN x 1
@planeID N
'''
n = n.copy()
if (planeID == 2).sum():
n[planeID == 2] = np.roll(n[planeID == 2], 2, axis=1)
if (planeID == 3).sum():
n[planeID == 3] = np.roll(n[planeID == 3], 1, axis=1)
n = np.repeat(n, in_.shape[0] // n.shape[0], axis=0)
assert n.shape[0] == in_.shape[0]
bc = n[:, [0]] * np.sin(in_) + n[:, [1]] * np.cos(in_)
bs = n[:, [2]]
out = np.arctan(-bc / (bs + 1e-9))
return out
def xyz2uvN(xyz, planeID=1):
ID1 = (int(planeID) - 1 + 0) % 3
ID2 = (int(planeID) - 1 + 1) % 3
ID3 = (int(planeID) - 1 + 2) % 3
normXY = np.sqrt(xyz[:, [ID1]] ** 2 + xyz[:, [ID2]] ** 2)
normXY[normXY < 0.000001] = 0.000001
normXYZ = np.sqrt(xyz[:, [ID1]] ** 2 + xyz[:, [ID2]] ** 2 + xyz[:, [ID3]] ** 2)
v = np.arcsin(xyz[:, [ID3]] / normXYZ)
u = np.arcsin(xyz[:, [ID1]] / normXY)
valid = (xyz[:, [ID2]] < 0) & (u >= 0)
u[valid] = np.pi - u[valid]
valid = (xyz[:, [ID2]] < 0) & (u <= 0)
u[valid] = -np.pi - u[valid]
uv = np.hstack([u, v])
uv[np.isnan(uv[:, 0]), 0] = 0
return uv
def uv2xyzN(uv, planeID=1):
ID1 = (int(planeID) - 1 + 0) % 3
ID2 = (int(planeID) - 1 + 1) % 3
ID3 = (int(planeID) - 1 + 2) % 3
xyz = np.zeros((uv.shape[0], 3))
xyz[:, ID1] = np.cos(uv[:, 1]) * np.sin(uv[:, 0])
xyz[:, ID2] = np.cos(uv[:, 1]) * np.cos(uv[:, 0])
xyz[:, ID3] = np.sin(uv[:, 1])
return xyz
def uv2xyzN_vec(uv, planeID):
'''
vectorization version of uv2xyzN
@uv N x 2
@planeID N
'''
assert (planeID.astype(int) != planeID).sum() == 0
planeID = planeID.astype(int)
ID1 = (planeID - 1 + 0) % 3
ID2 = (planeID - 1 + 1) % 3
ID3 = (planeID - 1 + 2) % 3
ID = np.arange(len(uv))
xyz = np.zeros((len(uv), 3))
xyz[ID, ID1] = np.cos(uv[:, 1]) * np.sin(uv[:, 0])
xyz[ID, ID2] = np.cos(uv[:, 1]) * np.cos(uv[:, 0])
xyz[ID, ID3] = np.sin(uv[:, 1])
return xyz
def warpImageFast(im, XXdense, YYdense):
minX = max(1., np.floor(XXdense.min()) - 1)
minY = max(1., np.floor(YYdense.min()) - 1)
maxX = min(im.shape[1], np.ceil(XXdense.max()) + 1)
maxY = min(im.shape[0], np.ceil(YYdense.max()) + 1)
im = im[int(round(minY-1)):int(round(maxY)),
int(round(minX-1)):int(round(maxX))]
assert XXdense.shape == YYdense.shape
out_shape = XXdense.shape
coordinates = [
(YYdense - minY).reshape(-1),
(XXdense - minX).reshape(-1),
]
im_warp = np.stack([
map_coordinates(im[..., c], coordinates, order=1).reshape(out_shape)
for c in range(im.shape[-1])],
axis=-1)
return im_warp
def rotatePanorama(img, vp=None, R=None):
'''
Rotate panorama
if R is given, vp (vanishing point) will be overlooked
otherwise R is computed from vp
'''
sphereH, sphereW, C = img.shape
# new uv coordinates
TX, TY = np.meshgrid(range(1, sphereW + 1), range(1, sphereH + 1))
TX = TX.reshape(-1, 1, order='F')
TY = TY.reshape(-1, 1, order='F')
ANGx = (TX - sphereW/2 - 0.5) / sphereW * np.pi * 2
ANGy = -(TY - sphereH/2 - 0.5) / sphereH * np.pi
uvNew = np.hstack([ANGx, ANGy])
xyzNew = uv2xyzN(uvNew, 1)
# rotation matrix
if R is None:
R = np.linalg.inv(vp.T)
xyzOld = np.linalg.solve(R, xyzNew.T).T
uvOld = xyz2uvN(xyzOld, 1)
Px = (uvOld[:, 0] + np.pi) / (2*np.pi) * sphereW + 0.5
Py = (-uvOld[:, 1] + np.pi/2) / np.pi * sphereH + 0.5
Px = Px.reshape(sphereH, sphereW, order='F')
Py = Py.reshape(sphereH, sphereW, order='F')
# boundary
imgNew = np.zeros((sphereH+2, sphereW+2, C), np.float64)
imgNew[1:-1, 1:-1, :] = img
imgNew[1:-1, 0, :] = img[:, -1, :]
imgNew[1:-1, -1, :] = img[:, 0, :]
imgNew[0, 1:sphereW//2+1, :] = img[0, sphereW-1:sphereW//2-1:-1, :]
imgNew[0, sphereW//2+1:-1, :] = img[0, sphereW//2-1::-1, :]
imgNew[-1, 1:sphereW//2+1, :] = img[-1, sphereW-1:sphereW//2-1:-1, :]
imgNew[-1, sphereW//2+1:-1, :] = img[0, sphereW//2-1::-1, :]
imgNew[0, 0, :] = img[0, 0, :]
imgNew[-1, -1, :] = img[-1, -1, :]
imgNew[0, -1, :] = img[0, -1, :]
imgNew[-1, 0, :] = img[-1, 0, :]
rotImg = warpImageFast(imgNew, Px+1, Py+1)
return rotImg
def imgLookAt(im, CENTERx, CENTERy, new_imgH, fov):
sphereH = im.shape[0]
sphereW = im.shape[1]
warped_im = np.zeros((new_imgH, new_imgH, 3))
TX, TY = np.meshgrid(range(1, new_imgH + 1), range(1, new_imgH + 1))
TX = TX.reshape(-1, 1, order='F')
TY = TY.reshape(-1, 1, order='F')
TX = TX - 0.5 - new_imgH/2
TY = TY - 0.5 - new_imgH/2
r = new_imgH / 2 / np.tan(fov/2)
# convert to 3D
R = np.sqrt(TY ** 2 + r ** 2)
ANGy = np.arctan(- TY / r)
ANGy = ANGy + CENTERy
X = np.sin(ANGy) * R
Y = -np.cos(ANGy) * R
Z = TX
INDn = np.nonzero(np.abs(ANGy) > np.pi/2)
# project back to sphere
ANGx = np.arctan(Z / -Y)
RZY = np.sqrt(Z ** 2 + Y ** 2)
ANGy = np.arctan(X / RZY)
ANGx[INDn] = ANGx[INDn] + np.pi
ANGx = ANGx + CENTERx
INDy = np.nonzero(ANGy < -np.pi/2)
ANGy[INDy] = -np.pi - ANGy[INDy]
ANGx[INDy] = ANGx[INDy] + np.pi
INDx = np.nonzero(ANGx <= -np.pi); ANGx[INDx] = ANGx[INDx] + 2 * np.pi
INDx = np.nonzero(ANGx > np.pi); ANGx[INDx] = ANGx[INDx] - 2 * np.pi
INDx = np.nonzero(ANGx > np.pi); ANGx[INDx] = ANGx[INDx] - 2 * np.pi
INDx = np.nonzero(ANGx > np.pi); ANGx[INDx] = ANGx[INDx] - 2 * np.pi
Px = (ANGx + np.pi) / (2*np.pi) * sphereW + 0.5
Py = ((-ANGy) + np.pi/2) / np.pi * sphereH + 0.5
INDxx = np.nonzero(Px < 1)
Px[INDxx] = Px[INDxx] + sphereW
im = np.concatenate([im, im[:, :2]], 1)
Px = Px.reshape(new_imgH, new_imgH, order='F')
Py = Py.reshape(new_imgH, new_imgH, order='F')
warped_im = warpImageFast(im, Px, Py)
return warped_im
def separatePano(panoImg, fov, x, y, imgSize=320):
'''cut a panorama image into several separate views'''
assert x.shape == y.shape
if not isinstance(fov, np.ndarray):
fov = fov * np.ones_like(x)
sepScene = [
{
'img': imgLookAt(panoImg.copy(), xi, yi, imgSize, fovi),
'vx': xi,
'vy': yi,
'fov': fovi,
'sz': imgSize,
}
for xi, yi, fovi in zip(x, y, fov)
]
return sepScene
def lsdWrap(img, LSD=None, **kwargs):
'''
Opencv implementation of
<NAME>, <NAME>, <NAME>, and <NAME>,
LSD: a Line Segment Detector, Image Processing On Line, vol. 2012.
[Rafael12] http://www.ipol.im/pub/art/2012/gjmr-lsd/?utm_source=doi
@img
input image
@LSD
Constructing by cv2.createLineSegmentDetector
https://docs.opencv.org/3.0-beta/modules/imgproc/doc/feature_detection.html#linesegmentdetector
if LSD is given, kwargs will be ignored
@kwargs
is used to construct LSD
work only if @LSD is not given
'''
if LSD is None:
LSD = cv2.createLineSegmentDetector(**kwargs)
if len(img.shape) == 3:
img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
lines, width, prec, nfa = LSD.detect(img)
if lines is None:
return np.zeros_like(img), np.array([])
edgeMap = LSD.drawSegments(np.zeros_like(img), lines)[..., -1]
lines = np.squeeze(lines, 1)
edgeList = np.concatenate([lines, width, prec, nfa], 1)
return edgeMap, edgeList
def edgeFromImg2Pano(edge):
edgeList = edge['edgeLst']
if len(edgeList) == 0:
return np.array([])
vx = edge['vx']
vy = edge['vy']
fov = edge['fov']
imH, imW = edge['img'].shape
R = (imW/2) / np.tan(fov/2)
# im is the tangent plane, contacting with ball at [x0 y0 z0]
x0 = R * np.cos(vy) * np.sin(vx)
y0 = R * np.cos(vy) * np.cos(vx)
z0 = R * np.sin(vy)
vecposX = np.array([np.cos(vx), -np.sin(vx), 0])
vecposY = np.cross(np.array([x0, y0, z0]), vecposX)
vecposY = vecposY / np.sqrt(vecposY @ vecposY.T)
vecposX = vecposX.reshape(1, -1)
vecposY = vecposY.reshape(1, -1)
Xc = (0 + imW-1) / 2
Yc = (0 + imH-1) / 2
vecx1 = edgeList[:, [0]] - Xc
vecy1 = edgeList[:, [1]] - Yc
vecx2 = edgeList[:, [2]] - Xc
vecy2 = edgeList[:, [3]] - Yc
vec1 = np.tile(vecx1, [1, 3]) * vecposX + np.tile(vecy1, [1, 3]) * vecposY
vec2 = np.tile(vecx2, [1, 3]) * vecposX + np.tile(vecy2, [1, 3]) * vecposY
coord1 = [[x0, y0, z0]] + vec1
coord2 = [[x0, y0, z0]] + vec2
normal = np.cross(coord1, coord2, axis=1)
normal = normal / np.linalg.norm(normal, axis=1, keepdims=True)
panoList = np.hstack([normal, coord1, coord2, edgeList[:, [-1]]])
return panoList
def _intersection(range1, range2):
if range1[1] < range1[0]:
range11 = [range1[0], 1]
range12 = [0, range1[1]]
else:
range11 = range1
range12 = [0, 0]
if range2[1] < range2[0]:
range21 = [range2[0], 1]
range22 = [0, range2[1]]
else:
range21 = range2
range22 = [0, 0]
b = max(range11[0], range21[0]) < min(range11[1], range21[1])
if b:
return b
b2 = max(range12[0], range22[0]) < min(range12[1], range22[1])
b = b or b2
return b
def _insideRange(pt, range):
if range[1] > range[0]:
b = pt >= range[0] and pt <= range[1]
else:
b1 = pt >= range[0] and pt <= 1
b2 = pt >= 0 and pt <= range[1]
b = b1 or b2
return b
def combineEdgesN(edges):
'''
Combine some small line segments, should be very conservative
OUTPUT
lines: combined line segments
ori_lines: original line segments
line format [nx ny nz projectPlaneID umin umax LSfov score]
'''
arcList = []
for edge in edges:
panoLst = edge['panoLst']
if len(panoLst) == 0:
continue
arcList.append(panoLst)
arcList = np.vstack(arcList)
# ori lines
numLine = len(arcList)
ori_lines = np.zeros((numLine, 8))
areaXY = np.abs(arcList[:, 2])
areaYZ = np.abs(arcList[:, 0])
areaZX = np.abs(arcList[:, 1])
planeIDs = np.argmax(np.stack([areaXY, areaYZ, areaZX], -1), 1) + 1 # XY YZ ZX
for i in range(numLine):
ori_lines[i, :3] = arcList[i, :3]
ori_lines[i, 3] = planeIDs[i]
coord1 = arcList[i, 3:6]
coord2 = arcList[i, 6:9]
uv = xyz2uvN(np.stack([coord1, coord2]), planeIDs[i])
umax = uv[:, 0].max() + np.pi
umin = uv[:, 0].min() + np.pi
if umax - umin > np.pi:
ori_lines[i, 4:6] = np.array([umax, umin]) / 2 / np.pi
else:
ori_lines[i, 4:6] = np.array([umin, umax]) / 2 / np.pi
ori_lines[i, 6] = np.arccos((
np.dot(coord1, coord2) / (np.linalg.norm(coord1) * np.linalg.norm(coord2))
).clip(-1, 1))
ori_lines[i, 7] = arcList[i, 9]
# additive combination
lines = ori_lines.copy()
for _ in range(3):
numLine = len(lines)
valid_line = np.ones(numLine, bool)
for i in range(numLine):
if not valid_line[i]:
continue
dotProd = (lines[:, :3] * lines[[i], :3]).sum(1)
valid_curr = np.logical_and((np.abs(dotProd) > np.cos(np.pi / 180)), valid_line)
valid_curr[i] = False
for j in np.nonzero(valid_curr)[0]:
range1 = lines[i, 4:6]
range2 = lines[j, 4:6]
valid_rag = _intersection(range1, range2)
if not valid_rag:
continue
# combine
I = np.argmax(np.abs(lines[i, :3]))
if lines[i, I] * lines[j, I] > 0:
nc = lines[i, :3] * lines[i, 6] + lines[j, :3] * lines[j, 6]
else:
nc = lines[i, :3] * lines[i, 6] - lines[j, :3] * lines[j, 6]
nc = nc / np.linalg.norm(nc)
if _insideRange(range1[0], range2):
nrmin = range2[0]
else:
nrmin = range1[0]
if _insideRange(range1[1], range2):
nrmax = range2[1]
else:
nrmax = range1[1]
u = np.array([[nrmin], [nrmax]]) * 2 * np.pi - np.pi
v = computeUVN(nc, u, lines[i, 3])
xyz = uv2xyzN(np.hstack([u, v]), lines[i, 3])
l = np.arccos(np.dot(xyz[0, :], xyz[1, :]).clip(-1, 1))
scr = (lines[i,6]*lines[i,7] + lines[j,6]*lines[j,7]) / (lines[i,6]+lines[j,6])
lines[i] = [*nc, lines[i, 3], nrmin, nrmax, l, scr]
valid_line[j] = False
lines = lines[valid_line]
return lines, ori_lines
def icosahedron2sphere(level):
# this function use a icosahedron to sample uniformly on a sphere
a = 2 / (1 + np.sqrt(5))
M = np.array([
0, a, -1, a, 1, 0, -a, 1, 0,
0, a, 1, -a, 1, 0, a, 1, 0,
0, a, 1, 0, -a, 1, -1, 0, a,
0, a, 1, 1, 0, a, 0, -a, 1,
0, a, -1, 0, -a, -1, 1, 0, -a,
0, a, -1, -1, 0, -a, 0, -a, -1,
0, -a, 1, a, -1, 0, -a, -1, 0,
0, -a, -1, -a, -1, 0, a, -1, 0,
-a, 1, 0, -1, 0, a, -1, 0, -a,
-a, -1, 0, -1, 0, -a, -1, 0, a,
a, 1, 0, 1, 0, -a, 1, 0, a,
a, -1, 0, 1, 0, a, 1, 0, -a,
0, a, 1, -1, 0, a, -a, 1, 0,
0, a, 1, a, 1, 0, 1, 0, a,
0, a, -1, -a, 1, 0, -1, 0, -a,
0, a, -1, 1, 0, -a, a, 1, 0,
0, -a, -1, -1, 0, -a, -a, -1, 0,
0, -a, -1, a, -1, 0, 1, 0, -a,
0, -a, 1, -a, -1, 0, -1, 0, a,
0, -a, 1, 1, 0, a, a, -1, 0])
coor = M.T.reshape(3, 60, order='F').T
coor, idx = np.unique(coor, return_inverse=True, axis=0)
tri = idx.reshape(3, 20, order='F').T
# extrude
coor = list(coor / np.tile(np.linalg.norm(coor, axis=1, keepdims=True), (1, 3)))
for _ in range(level):
triN = []
for t in range(len(tri)):
n = len(coor)
coor.append((coor[tri[t, 0]] + coor[tri[t, 1]]) / 2)
coor.append((coor[tri[t, 1]] + coor[tri[t, 2]]) / 2)
coor.append((coor[tri[t, 2]] + coor[tri[t, 0]]) / 2)
triN.append([n, tri[t, 0], n+2])
triN.append([n, tri[t, 1], n+1])
triN.append([n+1, tri[t, 2], n+2])
triN.append([n, n+1, n+2])
tri = np.array(triN)
# uniquefy
coor, idx = np.unique(coor, return_inverse=True, axis=0)
tri = idx[tri]
# extrude
coor = list(coor / np.tile(np.sqrt(np.sum(coor * coor, 1, keepdims=True)), (1, 3)))
return np.array(coor), np.array(tri)
def curveFitting(inputXYZ, weight):
'''
@inputXYZ: N x 3
@weight : N x 1
'''
l = np.linalg.norm(inputXYZ, axis=1, keepdims=True)
inputXYZ = inputXYZ / l
weightXYZ = inputXYZ * weight
XX = np.sum(weightXYZ[:, 0] ** 2)
YY = np.sum(weightXYZ[:, 1] ** 2)
ZZ = np.sum(weightXYZ[:, 2] ** 2)
XY = np.sum(weightXYZ[:, 0] * weightXYZ[:, 1])
YZ = np.sum(weightXYZ[:, 1] * weightXYZ[:, 2])
ZX = np.sum(weightXYZ[:, 2] * weightXYZ[:, 0])
A = np.array([
[XX, XY, ZX],
[XY, YY, YZ],
[ZX, YZ, ZZ]])
U, S, Vh = np.linalg.svd(A)
outputNM = Vh[-1, :]
outputNM = outputNM / np.linalg.norm(outputNM)
return outputNM
def sphereHoughVote(segNormal, segLength, segScores, binRadius, orthTolerance, candiSet, force_unempty=True):
# initial guess
numLinesg = len(segNormal)
voteBinPoints = candiSet.copy()
voteBinPoints = voteBinPoints[~(voteBinPoints[:,2] < 0)]
reversValid = (segNormal[:, 2] < 0).reshape(-1)
segNormal[reversValid] = -segNormal[reversValid]
voteBinUV = xyz2uvN(voteBinPoints)
numVoteBin = len(voteBinPoints)
voteBinValues = np.zeros(numVoteBin)
for i in range(numLinesg):
tempNorm = segNormal[[i]]
tempDots = (voteBinPoints * tempNorm).sum(1)
valid = np.abs(tempDots) < np.cos((90 - binRadius) * np.pi / 180)
voteBinValues[valid] = voteBinValues[valid] + segScores[i] * segLength[i]
checkIDs1 = np.nonzero(voteBinUV[:, [1]] > np.pi / 3)[0]
voteMax = 0
checkID1Max = 0
checkID2Max = 0
checkID3Max = 0
for j in range(len(checkIDs1)):
checkID1 = checkIDs1[j]
vote1 = voteBinValues[checkID1]
if voteBinValues[checkID1] == 0 and force_unempty:
continue
checkNormal = voteBinPoints[[checkID1]]
dotProduct = (voteBinPoints * checkNormal).sum(1)
checkIDs2 = np.nonzero(np.abs(dotProduct) < np.cos((90 - orthTolerance) * np.pi / 180))[0]
for i in range(len(checkIDs2)):
checkID2 = checkIDs2[i]
if voteBinValues[checkID2] == 0 and force_unempty:
continue
vote2 = vote1 + voteBinValues[checkID2]
cpv = np.cross(voteBinPoints[checkID1], voteBinPoints[checkID2]).reshape(1, 3)
cpn = np.linalg.norm(cpv)
dotProduct = (voteBinPoints * cpv).sum(1) / cpn
checkIDs3 = np.nonzero(np.abs(dotProduct) > np.cos(orthTolerance * np.pi / 180))[0]
for k in range(len(checkIDs3)):
checkID3 = checkIDs3[k]
if voteBinValues[checkID3] == 0 and force_unempty:
continue
vote3 = vote2 + voteBinValues[checkID3]
if vote3 > voteMax:
lastStepCost = vote3 - voteMax
if voteMax != 0:
tmp = (voteBinPoints[[checkID1Max, checkID2Max, checkID3Max]] * \
voteBinPoints[[checkID1, checkID2, checkID3]]).sum(1)
lastStepAngle = np.arccos(tmp.clip(-1, 1))
else:
lastStepAngle = np.zeros(3)
checkID1Max = checkID1
checkID2Max = checkID2
checkID3Max = checkID3
voteMax = vote3
if checkID1Max == 0:
print('[WARN] sphereHoughVote: no orthogonal voting exist', file=sys.stderr)
return None, 0, 0
initXYZ = voteBinPoints[[checkID1Max, checkID2Max, checkID3Max]]
# refine
refiXYZ = np.zeros((3, 3))
dotprod = (segNormal * initXYZ[[0]]).sum(1)
valid = np.abs(dotprod) < np.cos((90 - binRadius) * np.pi / 180)
validNm = segNormal[valid]
validWt = segLength[valid] * segScores[valid]
validWt = validWt / validWt.max()
refiNM = curveFitting(validNm, validWt)
refiXYZ[0] = refiNM.copy()
dotprod = (segNormal * initXYZ[[1]]).sum(1)
valid = np.abs(dotprod) < np.cos((90 - binRadius) * np.pi / 180)
validNm = segNormal[valid]
validWt = segLength[valid] * segScores[valid]
validWt = validWt / validWt.max()
validNm = np.vstack([validNm, refiXYZ[[0]]])
validWt = np.vstack([validWt, validWt.sum(0, keepdims=1) * 0.1])
refiNM = curveFitting(validNm, validWt)
refiXYZ[1] = refiNM.copy()
refiNM = np.cross(refiXYZ[0], refiXYZ[1])
refiXYZ[2] = refiNM / np.linalg.norm(refiNM)
return refiXYZ, lastStepCost, lastStepAngle
def findMainDirectionEMA(lines):
'''compute vp from set of lines'''
# initial guess
segNormal = lines[:, :3]
segLength = lines[:, [6]]
segScores = np.ones((len(lines), 1))
shortSegValid = (segLength < 5 * np.pi / 180).reshape(-1)
segNormal = segNormal[~shortSegValid, :]
segLength = segLength[~shortSegValid]
segScores = segScores[~shortSegValid]
numLinesg = len(segNormal)
candiSet, tri = icosahedron2sphere(3)
ang = np.arccos((candiSet[tri[0,0]] * candiSet[tri[0,1]]).sum().clip(-1, 1)) / np.pi * 180
binRadius = ang / 2
initXYZ, score, angle = sphereHoughVote(segNormal, segLength, segScores, 2*binRadius, 2, candiSet)
if initXYZ is None:
print('[WARN] findMainDirectionEMA: initial failed', file=sys.stderr)
return None, score, angle
# iterative refine
iter_max = 3
candiSet, tri = icosahedron2sphere(5)
numCandi = len(candiSet)
angD = np.arccos((candiSet[tri[0, 0]] * candiSet[tri[0, 1]]).sum().clip(-1, 1)) / np.pi * 180
binRadiusD = angD / 2
curXYZ = initXYZ.copy()
tol = np.linspace(4*binRadius, 4*binRadiusD, iter_max) # shrink down ls and candi
for it in range(iter_max):
dot1 = np.abs((segNormal * curXYZ[[0]]).sum(1))
dot2 = np.abs((segNormal * curXYZ[[1]]).sum(1))
dot3 = np.abs((segNormal * curXYZ[[2]]).sum(1))
valid1 = dot1 < np.cos((90 - tol[it]) * np.pi / 180)
valid2 = dot2 < np.cos((90 - tol[it]) * np.pi / 180)
valid3 = dot3 < np.cos((90 - tol[it]) * np.pi / 180)
valid = valid1 | valid2 | valid3
if np.sum(valid) == 0:
print('[WARN] findMainDirectionEMA: zero line segments for voting', file=sys.stderr)
break
subSegNormal = segNormal[valid]
subSegLength = segLength[valid]
subSegScores = segScores[valid]
dot1 = np.abs((candiSet * curXYZ[[0]]).sum(1))
dot2 = np.abs((candiSet * curXYZ[[1]]).sum(1))
dot3 = np.abs((candiSet * curXYZ[[2]]).sum(1))
valid1 = dot1 > np.cos(tol[it] * np.pi / 180)
valid2 = dot2 > np.cos(tol[it] * np.pi / 180)
valid3 = dot3 > np.cos(tol[it] * np.pi / 180)
valid = valid1 | valid2 | valid3
if np.sum(valid) == 0:
print('[WARN] findMainDirectionEMA: zero line segments for voting', file=sys.stderr)
break
subCandiSet = candiSet[valid]
tcurXYZ, _, _ = sphereHoughVote(subSegNormal, subSegLength, subSegScores, 2*binRadiusD, 2, subCandiSet)
if tcurXYZ is None:
print('[WARN] findMainDirectionEMA: no answer found', file=sys.stderr)
break
curXYZ = tcurXYZ.copy()
mainDirect = curXYZ.copy()
mainDirect[0] = mainDirect[0] * np.sign(mainDirect[0,2])
mainDirect[1] = mainDirect[1] * np.sign(mainDirect[1,2])
mainDirect[2] = mainDirect[2] * np.sign(mainDirect[2,2])
uv = xyz2uvN(mainDirect)
I1 = np.argmax(uv[:,1])
J = np.setdiff1d(np.arange(3), I1)
I2 = np.argmin(np.abs(np.sin(uv[J,0])))
I2 = J[I2]
I3 = np.setdiff1d(np.arange(3), np.hstack([I1, I2]))
mainDirect = np.vstack([mainDirect[I1], mainDirect[I2], mainDirect[I3]])
mainDirect[0] = mainDirect[0] * np.sign(mainDirect[0,2])
mainDirect[1] = mainDirect[1] * np.sign(mainDirect[1,1])
mainDirect[2] = mainDirect[2] * np.sign(mainDirect[2,0])
mainDirect = np.vstack([mainDirect, -mainDirect])
return mainDirect, score, angle
def multi_linspace(start, stop, num):
div = (num - 1)
y = np.arange(0, num, dtype=np.float64)
steps = (stop - start) / div
return steps.reshape(-1, 1) * y + start.reshape(-1, 1)
def assignVanishingType(lines, vp, tol, area=10):
numLine = len(lines)
numVP = len(vp)
typeCost = np.zeros((numLine, numVP))
# perpendicular
for vid in range(numVP):
cosint = (lines[:, :3] * vp[[vid]]).sum(1)
typeCost[:, vid] = np.arcsin(np.abs(cosint).clip(-1, 1))
# infinity
u = np.stack([lines[:, 4], lines[:, 5]], -1)
u = u.reshape(-1, 1) * 2 * np.pi - np.pi
v = computeUVN_vec(lines[:, :3], u, lines[:, 3])
xyz = uv2xyzN_vec(np.hstack([u, v]), np.repeat(lines[:, 3], 2))
xyz = multi_linspace(xyz[0::2].reshape(-1), xyz[1::2].reshape(-1), 100)
xyz = np.vstack([blk.T for blk in np.split(xyz, numLine)])
xyz = xyz / np.linalg.norm(xyz, axis=1, keepdims=True)
for vid in range(numVP):
ang = np.arccos(np.abs((xyz * vp[[vid]]).sum(1)).clip(-1, 1))
notok = (ang < area * np.pi / 180).reshape(numLine, 100).sum(1) != 0
typeCost[notok, vid] = 100
I = typeCost.min(1)
tp = typeCost.argmin(1)
tp[I > tol] = numVP + 1
return tp, typeCost
def refitLineSegmentB(lines, vp, vpweight=0.1):
'''
Refit direction of line segments
INPUT:
lines: original line segments
vp: vannishing point
vpweight: if set to 0, lines will not change; if set to inf, lines will
be forced to pass vp
'''
numSample = 100
numLine = len(lines)
xyz = np.zeros((numSample+1, 3))
wei = np.ones((numSample+1, 1))
wei[numSample] = vpweight * numSample
lines_ali = lines.copy()
for i in range(numLine):
n = lines[i, :3]
sid = lines[i, 4] * 2 * np.pi
eid = lines[i, 5] * 2 * np.pi
if eid < sid:
x = np.linspace(sid, eid + 2 * np.pi, numSample) % (2 * np.pi)
else:
x = np.linspace(sid, eid, numSample)
u = -np.pi + x.reshape(-1, 1)
v = computeUVN(n, u, lines[i, 3])
xyz[:numSample] = uv2xyzN(np.hstack([u, v]), lines[i, 3])
xyz[numSample] = vp
outputNM = curveFitting(xyz, wei)
lines_ali[i, :3] = outputNM
return lines_ali
def paintParameterLine(parameterLine, width, height):
lines = parameterLine.copy()
panoEdgeC = np.zeros((height, width))
num_sample = max(height, width)
for i in range(len(lines)):
n = lines[i, :3]
sid = lines[i, 4] * 2 * np.pi
eid = lines[i, 5] * 2 * np.pi
if eid < sid:
x = np.linspace(sid, eid + 2 * np.pi, num_sample)
x = x % (2 * np.pi)
else:
x = np.linspace(sid, eid, num_sample)
u = -np.pi + x.reshape(-1, 1)
v = computeUVN(n, u, lines[i, 3])
xyz = uv2xyzN(np.hstack([u, v]), lines[i, 3])
uv = xyz2uvN(xyz, 1)
m = np.minimum(np.floor((uv[:,0] + np.pi) / (2 * np.pi) * width) + 1,
width).astype(np.int32)
n = np.minimum(np.floor(((np.pi / 2) - uv[:, 1]) / np.pi * height) + 1,
height).astype(np.int32)
panoEdgeC[n-1, m-1] = i
return panoEdgeC
def panoEdgeDetection(img, viewSize=320, qError=0.7, refineIter=3):
'''
line detection on panorama
INPUT:
img: image waiting for detection, double type, range 0~1
viewSize: image size of croped views
qError: set smaller if more line segment wanted
OUTPUT:
oLines: detected line segments
vp: vanishing point
views: separate views of panorama
edges: original detection of line segments in separate views
panoEdge: image for visualize line segments
'''
cutSize = viewSize
fov = np.pi / 3
xh = np.arange(-np.pi, np.pi*5/6, np.pi/6)
yh = np.zeros(xh.shape[0])
xp = np.array([-3/3, -2/3, -1/3, 0/3, 1/3, 2/3, -3/3, -2/3, -1/3, 0/3, 1/3, 2/3]) * np.pi
yp = np.array([ 1/4, 1/4, 1/4, 1/4, 1/4, 1/4, -1/4, -1/4, -1/4, -1/4, -1/4, -1/4]) * np.pi
x = np.concatenate([xh, xp, [0, 0]])
y = np.concatenate([yh, yp, [np.pi/2., -np.pi/2]])
sepScene = separatePano(img.copy(), fov, x, y, cutSize)
edge = []
LSD = cv2.createLineSegmentDetector(_refine=cv2.LSD_REFINE_ADV, _quant=qError)
for i, scene in enumerate(sepScene):
edgeMap, edgeList = lsdWrap(scene['img'], LSD)
edge.append({
'img': edgeMap,
'edgeLst': edgeList,
'vx': scene['vx'],
'vy': scene['vy'],
'fov': scene['fov'],
})
edge[-1]['panoLst'] = edgeFromImg2Pano(edge[-1])
lines, olines = combineEdgesN(edge)
clines = lines.copy()
for _ in range(refineIter):
mainDirect, score, angle = findMainDirectionEMA(clines)
tp, typeCost = assignVanishingType(lines, mainDirect[:3], 0.1, 10)
lines1 = lines[tp==0]
lines2 = lines[tp==1]
lines3 = lines[tp==2]
lines1rB = refitLineSegmentB(lines1, mainDirect[0], 0)
lines2rB = refitLineSegmentB(lines2, mainDirect[1], 0)
lines3rB = refitLineSegmentB(lines3, mainDirect[2], 0)
clines = np.vstack([lines1rB, lines2rB, lines3rB])
panoEdge1r = paintParameterLine(lines1rB, img.shape[1], img.shape[0])
panoEdge2r = paintParameterLine(lines2rB, img.shape[1], img.shape[0])
panoEdge3r = paintParameterLine(lines3rB, img.shape[1], img.shape[0])
panoEdger = np.stack([panoEdge1r, panoEdge2r, panoEdge3r], -1)
# output
olines = clines
vp = mainDirect
views = sepScene
edges = edge
panoEdge = panoEdger
return olines, vp, views, edges, panoEdge, score, angle
if __name__ == '__main__':
# disable OpenCV3's non thread safe OpenCL option
cv2.ocl.setUseOpenCL(False)
import os
import argparse
import PIL
from PIL import Image
import time
parser = argparse.ArgumentParser()
parser.add_argument('--i', required=True)
parser.add_argument('--o_prefix', required=True)
parser.add_argument('--qError', default=0.7, type=float)
parser.add_argument('--refineIter', default=3, type=int)
args = parser.parse_args()
# Read image
img_ori = np.array(Image.open(args.i).resize((1024, 512)))
# Vanishing point estimation & Line segments detection
s_time = time.time()
olines, vp, views, edges, panoEdge, score, angle = panoEdgeDetection(img_ori,
qError=args.qError,
refineIter=args.refineIter)
print('Elapsed time: %.2f' % (time.time() - s_time))
panoEdge = (panoEdge > 0)
print('Vanishing point:')
for v in vp[2::-1]:
print('%.6f %.6f %.6f' % tuple(v))
# Visualization
edg = rotatePanorama(panoEdge.astype(np.float64), vp[2::-1])
img = rotatePanorama(img_ori / 255.0, vp[2::-1])
one = img.copy() * 0.5
one[(edg > 0.5).sum(-1) > 0] = 0
one[edg[..., 0] > 0.5, 0] = 1
one[edg[..., 1] > 0.5, 1] = 1
one[edg[..., 2] > 0.5, 2] = 1
Image.fromarray((edg * 255).astype(np.uint8)).save('%s_edg.png' % args.o_prefix)
Image.fromarray((img * 255).astype(np.uint8)).save('%s_img.png' % args.o_prefix)
Image.fromarray((one * 255).astype(np.uint8)).save('%s_one.png' % args.o_prefix)
<file_sep>/misc/structured3d_prepare_dataset.py
import os
import argparse
from zipfile import ZipFile
from tqdm import tqdm
import imageio
'''
Assume datas is extracted by `misc/structured3d_extract_zip.py`.
That is to said, assuming following structure:
- {in_root}/scene_xxxxx
- rgb/
- *png
- layout/
- *txt
The reorganized structure as follow:
- {out_train_root}
- img/
- scene_xxxxx_*png (softlink)
- label_cor/
- scene_xxxxx_*txt (softlink)
- {out_valid_root} ...
- {out_test_root} ...
'''
TRAIN_SCENE = ['scene_%05d' % i for i in range(0, 3000)]
VALID_SCENE = ['scene_%05d' % i for i in range(3000, 3250)]
TEST_SCENE = ['scene_%05d' % i for i in range(3250, 3500)]
parser = argparse.ArgumentParser()
parser.add_argument('--in_root', required=True)
parser.add_argument('--out_train_root', default='data/st3d_train_full_raw_light')
parser.add_argument('--out_valid_root', default='data/st3d_valid_full_raw_light')
parser.add_argument('--out_test_root', default='data/st3d_test_full_raw_light')
args = parser.parse_args()
def prepare_dataset(scene_ids, out_dir):
root_img = os.path.join(out_dir, 'img')
root_cor = os.path.join(out_dir, 'label_cor')
os.makedirs(root_img, exist_ok=True)
os.makedirs(root_cor, exist_ok=True)
for scene_id in tqdm(scene_ids):
source_img_root = os.path.join(args.in_root, scene_id, 'rgb')
source_cor_root = os.path.join(args.in_root, scene_id, 'layout')
for fname in os.listdir(source_cor_root):
room_id = fname.split('_')[0]
source_img_path = os.path.join(args.in_root, scene_id, 'rgb', room_id + '_rgb_rawlight.png')
source_cor_path = os.path.join(args.in_root, scene_id, 'layout', room_id + '_layout.txt')
target_img_path = os.path.join(root_img, '%s_%s.png' % (scene_id, room_id))
target_cor_path = os.path.join(root_cor, '%s_%s.txt' % (scene_id, room_id))
assert os.path.isfile(source_img_path)
assert os.path.isfile(source_cor_path)
os.symlink(source_img_path, target_img_path)
os.symlink(source_cor_path, target_cor_path)
prepare_dataset(TRAIN_SCENE, args.out_train_root)
prepare_dataset(VALID_SCENE, args.out_valid_root)
prepare_dataset(TEST_SCENE, args.out_test_root)
<file_sep>/model.py
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
import functools
ENCODER_RESNET = [
'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152',
'resnext50_32x4d', 'resnext101_32x8d'
]
ENCODER_DENSENET = [
'densenet121', 'densenet169', 'densenet161', 'densenet201'
]
def lr_pad(x, padding=1):
''' Pad left/right-most to each other instead of zero padding '''
return torch.cat([x[..., -padding:], x, x[..., :padding]], dim=3)
class LR_PAD(nn.Module):
''' Pad left/right-most to each other instead of zero padding '''
def __init__(self, padding=1):
super(LR_PAD, self).__init__()
self.padding = padding
def forward(self, x):
return lr_pad(x, self.padding)
def wrap_lr_pad(net):
for name, m in net.named_modules():
if not isinstance(m, nn.Conv2d):
continue
if m.padding[1] == 0:
continue
w_pad = int(m.padding[1])
m.padding = (m.padding[0], 0)
names = name.split('.')
root = functools.reduce(lambda o, i: getattr(o, i), [net] + names[:-1])
setattr(
root, names[-1],
nn.Sequential(LR_PAD(w_pad), m)
)
'''
Encoder
'''
class Resnet(nn.Module):
def __init__(self, backbone='resnet50', pretrained=True):
super(Resnet, self).__init__()
assert backbone in ENCODER_RESNET
self.encoder = getattr(models, backbone)(pretrained=pretrained)
del self.encoder.fc, self.encoder.avgpool
def forward(self, x):
features = []
x = self.encoder.conv1(x)
x = self.encoder.bn1(x)
x = self.encoder.relu(x)
x = self.encoder.maxpool(x)
x = self.encoder.layer1(x); features.append(x) # 1/4
x = self.encoder.layer2(x); features.append(x) # 1/8
x = self.encoder.layer3(x); features.append(x) # 1/16
x = self.encoder.layer4(x); features.append(x) # 1/32
return features
def list_blocks(self):
lst = [m for m in self.encoder.children()]
block0 = lst[:4]
block1 = lst[4:5]
block2 = lst[5:6]
block3 = lst[6:7]
block4 = lst[7:8]
return block0, block1, block2, block3, block4
class Densenet(nn.Module):
def __init__(self, backbone='densenet169', pretrained=True):
super(Densenet, self).__init__()
assert backbone in ENCODER_DENSENET
self.encoder = getattr(models, backbone)(pretrained=pretrained)
self.final_relu = nn.ReLU(inplace=True)
del self.encoder.classifier
def forward(self, x):
lst = []
for m in self.encoder.features.children():
x = m(x)
lst.append(x)
features = [lst[4], lst[6], lst[8], self.final_relu(lst[11])]
return features
def list_blocks(self):
lst = [m for m in self.encoder.features.children()]
block0 = lst[:4]
block1 = lst[4:6]
block2 = lst[6:8]
block3 = lst[8:10]
block4 = lst[10:]
return block0, block1, block2, block3, block4
'''
Decoder
'''
class ConvCompressH(nn.Module):
''' Reduce feature height by factor of two '''
def __init__(self, in_c, out_c, ks=3):
super(ConvCompressH, self).__init__()
assert ks % 2 == 1
self.layers = nn.Sequential(
nn.Conv2d(in_c, out_c, kernel_size=ks, stride=(2, 1), padding=ks//2),
nn.BatchNorm2d(out_c),
nn.ReLU(inplace=True),
)
def forward(self, x):
return self.layers(x)
class GlobalHeightConv(nn.Module):
def __init__(self, in_c, out_c):
super(GlobalHeightConv, self).__init__()
self.layer = nn.Sequential(
ConvCompressH(in_c, in_c//2),
ConvCompressH(in_c//2, in_c//2),
ConvCompressH(in_c//2, in_c//4),
ConvCompressH(in_c//4, out_c),
)
def forward(self, x, out_w):
x = self.layer(x)
assert out_w % x.shape[3] == 0
factor = out_w // x.shape[3]
x = torch.cat([x[..., -1:], x, x[..., :1]], 3)
x = F.interpolate(x, size=(x.shape[2], out_w + 2 * factor), mode='bilinear', align_corners=False)
x = x[..., factor:-factor]
return x
class GlobalHeightStage(nn.Module):
def __init__(self, c1, c2, c3, c4, out_scale=8):
''' Process 4 blocks from encoder to single multiscale features '''
super(GlobalHeightStage, self).__init__()
self.cs = c1, c2, c3, c4
self.out_scale = out_scale
self.ghc_lst = nn.ModuleList([
GlobalHeightConv(c1, c1//out_scale),
GlobalHeightConv(c2, c2//out_scale),
GlobalHeightConv(c3, c3//out_scale),
GlobalHeightConv(c4, c4//out_scale),
])
def forward(self, conv_list, out_w):
assert len(conv_list) == 4
bs = conv_list[0].shape[0]
feature = torch.cat([
f(x, out_w).reshape(bs, -1, out_w)
for f, x, out_c in zip(self.ghc_lst, conv_list, self.cs)
], dim=1)
return feature
'''
HorizonNet
'''
class HorizonNet(nn.Module):
x_mean = torch.FloatTensor(np.array([0.485, 0.456, 0.406])[None, :, None, None])
x_std = torch.FloatTensor(np.array([0.229, 0.224, 0.225])[None, :, None, None])
def __init__(self, backbone, use_rnn):
super(HorizonNet, self).__init__()
self.backbone = backbone
self.use_rnn = use_rnn
self.out_scale = 8
self.step_cols = 4
self.rnn_hidden_size = 512
# Encoder
if backbone.startswith('res'):
self.feature_extractor = Resnet(backbone, pretrained=True)
elif backbone.startswith('dense'):
self.feature_extractor = Densenet(backbone, pretrained=True)
else:
raise NotImplementedError()
# Inference channels number from each block of the encoder
with torch.no_grad():
dummy = torch.zeros(1, 3, 512, 1024)
c1, c2, c3, c4 = [b.shape[1] for b in self.feature_extractor(dummy)]
c_last = (c1*8 + c2*4 + c3*2 + c4*1) // self.out_scale
# Convert features from 4 blocks of the encoder into B x C x 1 x W'
self.reduce_height_module = GlobalHeightStage(c1, c2, c3, c4, self.out_scale)
# 1D prediction
if self.use_rnn:
self.bi_rnn = nn.LSTM(input_size=c_last,
hidden_size=self.rnn_hidden_size,
num_layers=2,
dropout=0.5,
batch_first=False,
bidirectional=True)
self.drop_out = nn.Dropout(0.5)
self.linear = nn.Linear(in_features=2 * self.rnn_hidden_size,
out_features=3 * self.step_cols)
self.linear.bias.data[0*self.step_cols:1*self.step_cols].fill_(-1)
self.linear.bias.data[1*self.step_cols:2*self.step_cols].fill_(-0.478)
self.linear.bias.data[2*self.step_cols:3*self.step_cols].fill_(0.425)
else:
self.linear = nn.Sequential(
nn.Linear(c_last, self.rnn_hidden_size),
nn.ReLU(inplace=True),
nn.Dropout(0.5),
nn.Linear(self.rnn_hidden_size, 3 * self.step_cols),
)
self.linear[-1].bias.data[0*self.step_cols:1*self.step_cols].fill_(-1)
self.linear[-1].bias.data[1*self.step_cols:2*self.step_cols].fill_(-0.478)
self.linear[-1].bias.data[2*self.step_cols:3*self.step_cols].fill_(0.425)
self.x_mean.requires_grad = False
self.x_std.requires_grad = False
wrap_lr_pad(self)
def _prepare_x(self, x):
if self.x_mean.device != x.device:
self.x_mean = self.x_mean.to(x.device)
self.x_std = self.x_std.to(x.device)
return (x[:, :3] - self.x_mean) / self.x_std
def forward(self, x):
if x.shape[2] != 512 or x.shape[3] != 1024:
raise NotImplementedError()
x = self._prepare_x(x)
conv_list = self.feature_extractor(x)
feature = self.reduce_height_module(conv_list, x.shape[3]//self.step_cols)
# rnn
if self.use_rnn:
feature = feature.permute(2, 0, 1) # [w, b, c*h]
output, hidden = self.bi_rnn(feature) # [seq_len, b, num_directions * hidden_size]
output = self.drop_out(output)
output = self.linear(output) # [seq_len, b, 3 * step_cols]
output = output.view(output.shape[0], output.shape[1], 3, self.step_cols) # [seq_len, b, 3, step_cols]
output = output.permute(1, 2, 0, 3) # [b, 3, seq_len, step_cols]
output = output.contiguous().view(output.shape[0], 3, -1) # [b, 3, seq_len*step_cols]
else:
feature = feature.permute(0, 2, 1) # [b, w, c*h]
output = self.linear(feature) # [b, w, 3 * step_cols]
output = output.view(output.shape[0], output.shape[1], 3, self.step_cols) # [b, w, 3, step_cols]
output = output.permute(0, 2, 1, 3) # [b, 3, w, step_cols]
output = output.contiguous().view(output.shape[0], 3, -1) # [b, 3, w*step_cols]
# output.shape => B x 3 x W
cor = output[:, :1] # B x 1 x W
bon = output[:, 1:] # B x 2 x W
return bon, cor
<file_sep>/misc/structured3d_extract_zip.py
import os
import argparse
from zipfile import ZipFile
from tqdm import tqdm
import imageio
'''
Zipfile format assumption:
Structured3D
-- [scene_xxxxx]
-- other something
-- 2D_rendering
-- [image_id]
-- panorama
-- camera_xyz.txt
-- layout.txt
-- [empty|simple|full]
-- depth.png
-- rgb_rawlight.png
-- rgb_coldlight.png
-- rgb_warmlight.png
-- other something
Output format
outdir
-- [scene_xxxxx]
-- img
-- layout
'''
parser = argparse.ArgumentParser()
parser.add_argument('--zippath', required=True)
parser.add_argument('--style', default='full')
parser.add_argument('--outdir', default='structured3d')
args = parser.parse_args()
path_format = 'Structured3D/%s/2D_rendering/%s/panorama/%s'
with ZipFile(args.zippath) as zipf:
id_set = set()
for path in zipf.namelist():
assert path.startswith('Structured3D')
if path.endswith('camera_xyz.txt'):
path_lst = path.split('/')
scene_id = path_lst[1]
image_id = path_lst[3]
id_set.add((scene_id, image_id))
for scene_id, image_id in tqdm(id_set):
path_img = path_format % (scene_id, image_id, '%s/rgb_rawlight.png' % args.style)
path_layout = path_format % (scene_id, image_id, 'layout.txt')
os.makedirs(os.path.join(args.outdir, scene_id, 'rgb'), exist_ok=True)
os.makedirs(os.path.join(args.outdir, scene_id, 'layout'), exist_ok=True)
with zipf.open(path_img) as f:
rgb = imageio.imread(f)[..., :3]
imageio.imwrite(os.path.join(args.outdir, scene_id, 'rgb', image_id + '_rgb_rawlight.png'), rgb)
with zipf.open(path_layout) as f:
with open(os.path.join(args.outdir, scene_id, 'layout', image_id + '_layout.txt'), 'w') as fo:
fo.write(f.read().decode())
<file_sep>/requirements.txt
attrs==19.3.0
backcall==0.1.0
bleach==3.1.4
decorator==4.4.2
defusedxml==0.6.0
entrypoints==0.3
glfw==1.11.0
importlib-metadata==1.6.0
ipykernel==5.2.0
ipython==7.13.0
ipython-genutils==0.2.0
ipywidgets==7.5.1
jedi==0.16.0
Jinja2==2.11.1
joblib==0.14.1
jsonschema==3.2.0
jupyter-client==6.1.2
jupyter-core==4.6.3
MarkupSafe==1.1.1
mistune==0.8.4
nbconvert==5.6.1
nbformat==5.0.4
notebook==6.0.3
numpy==1.18.2
open3d==0.9.0.0
opencv-python==3.1.0.5
pandocfilters==1.4.2
parso==0.6.2
pexpect==4.8.0
pickleshare==0.7.5
Pillow==7.0.0
prometheus-client==0.7.1
prompt-toolkit==3.0.5
ptyprocess==0.6.0
Pygments==2.6.1
pyrsistent==0.16.0
python-dateutil==2.8.1
pyzmq==19.0.0
scikit-learn==0.22.2.post1
scipy==1.4.1
Send2Trash==1.5.0
Shapely==1.7.0
six==1.14.0
sklearn==0.0
style==1.1.0
terminado==0.8.3
testpath==0.4.4
torch==1.4.0
torchvision==0.5.0
tornado==6.0.4
tqdm==4.44.0
traitlets==4.3.3
update==0.0.1
wcwidth==0.1.9
webencodings==0.5.1
widgetsnbextension==3.5.1
zipp==3.1.0
|
24b91386d7f7e7c02442c6e8fcf3c1b69af30928
|
[
"Markdown",
"Python",
"Text"
] | 11
|
Python
|
SwiftWinds/HorizonNet
|
31d4c5dff48da783b424d5e240638b23a582181f
|
cb9b8a646058ca1994fb0cfc06b4df8b65ba2388
|
refs/heads/master
|
<file_sep># rough-and-tumble<file_sep>import React from 'react'
import { Link } from 'react-router-dom'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import SignupForm from '../forms/SignupForm'
import { signup } from '../../redux/actions/auth'
class SignupPage extends React.Component {
submit = data =>
this.props.signup(data).then(() => this.props.history.push('/contacts'))
render() {
return (
<div>
<h1>Sign Up</h1>
<SignupForm submit={this.submit} />
<Link to="/">Back</Link> or <Link to="/login">Login</Link>
</div>
)
}
}
SignupPage.propTypes = {
signup: PropTypes.func.isRequired,
history: PropTypes.shape({ push: PropTypes.func.isRequired }).isRequired
}
export default connect(null, { signup })(SignupPage)
<file_sep>import React from 'react'
import { Link } from 'react-router-dom'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import VerifyEmailMessage from '../messages/VerifyEmailMessage'
const ContactsPage = ({ isVerified }) => (
<div>
<h1>Contacts</h1>
{!isVerified && <VerifyEmailMessage />}
<div>
<Link to="/">Back</Link> or <Link to="/signup">Sign up</Link>
</div>
</div>
)
ContactsPage.propTypes = {
isVerified: PropTypes.bool.isRequired
}
const mapStateToProps = state => ({
isVerified: state.user.isVerified
})
export default connect(mapStateToProps, null)(ContactsPage)
|
e95fa51b00b448fd86fa75543fc1c1700298c561
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
ktrygub/rough-and-tumble
|
f4c7bd709341b5758ab1bcc32153a9720adff557
|
55bb7fd214c867a37acf46a994bb89b9f18de4a0
|
refs/heads/master
|
<file_sep>package com.nuzul.caffein;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.nuzul.caffein.dbSQLite.DataHelper;
public class SugestionInActivity extends AppCompatActivity {
EditText etNama, etEmail, etSaran;
Button btnKirim, btnReset;
DataHelper dHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sugestion_in);
dHelper = new DataHelper(this);
etNama = findViewById(R.id.etNama);
etEmail = findViewById(R.id.etEmail);
etSaran = findViewById(R.id.etSaran);
btnKirim = findViewById(R.id.btnKirim);
btnReset = findViewById(R.id.btnReset);
btnKirim.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String nama = etNama.getText().toString();
String email = etEmail.getText().toString();
String saran = etSaran.getText().toString();
SQLiteDatabase db = dHelper.getWritableDatabase();
db.execSQL("INSERT INTO tb_saran(nama, email, saran) VALUES ('"+nama+"','"+email+"','"+saran+"')");
Toast.makeText(SugestionInActivity.this, "Pesan dari "+nama+", berhasil disimpan !", Toast.LENGTH_SHORT).show();
startActivity(new Intent(SugestionInActivity.this, SugestionActivity.class));
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
etNama.setText("");
etEmail.setText("");
etSaran.setText("");
}
});
}
}<file_sep>package com.nuzul.caffein.Model;
import com.google.gson.annotations.SerializedName;
public class Dessert {
@SerializedName("name_dessert")
private String name_dessert;
@SerializedName("price_dessert")
private String price_dessert;
@SerializedName("photo_id")
private String photo_id;
private String action;
public Dessert(){}
public Dessert(String name_dessert, String price_dessert, String photo_id, String action) {
this.name_dessert = name_dessert;
this.price_dessert = price_dessert;
this.photo_id = photo_id;
this.action = action;
}
public String getName_dessert() {
return name_dessert;
}
public void setName_dessert(String name_dessert) {
this.name_dessert = name_dessert;
}
public String getPrice_dessert() {
return price_dessert;
}
public void setPrice_dessert(String price_dessert) {
this.price_dessert = price_dessert;
}
public String getPhoto_id() {
return photo_id;
}
public void setPhoto_id(String photo_id) {
this.photo_id = photo_id;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
}
<file_sep>package com.nuzul.caffein.Model;
import com.google.gson.annotations.SerializedName;
public class Food {
@SerializedName("id_food")
private String id_food;
@SerializedName("name_food")
private String name_food;
@SerializedName("price_food")
private String price_food;
@SerializedName("photo_id")
private String photo_id;
private String action;
public Food() {
}
public Food(String id_food, String name_food, String price_food, String photo_id, String action) {
this.id_food = id_food;
this.name_food = name_food;
this.price_food = price_food;
this.photo_id = photo_id;
this.action = action;
}
public String getId_food() {
return id_food;
}
public void setId_food(String id_food) {
this.id_food = id_food;
}
public String getName_food() {
return name_food;
}
public void setName_food(String name_food) {
this.name_food = name_food;
}
public String getPrice_food() {
return price_food;
}
public void setPrice_food(String price_food) {
this.price_food = price_food;
}
public String getPhoto_id() {
return photo_id;
}
public void setPhoto_id(String photo_id) {
this.photo_id = photo_id;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
}<file_sep>package com.nuzul.caffein.Adapter;
import android.annotation.SuppressLint;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.nuzul.caffein.Model.Drink;
import com.nuzul.caffein.R;
import com.nuzul.caffein.Rest.ApiClient;
import com.nuzul.caffein.dbSQLite.DataHelper;
import com.squareup.picasso.Picasso;
import java.util.List;
public class DrinkAdapter extends RecyclerView.Adapter<DrinkAdapter.DrinkViewHolder> {
int qty=0;
List<Drink> listDrink;
public DrinkAdapter(List<Drink> listDrink) {
this.listDrink = listDrink;
}
@Override
public DrinkAdapter.DrinkViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_drink, parent,false);
DrinkViewHolder mHolder = new DrinkViewHolder(view);
return mHolder;
}
public class DrinkViewHolder extends RecyclerView.ViewHolder {
ImageView ivDrink, ivMin, ivPlus;
TextView tvNameDrink, tvPriceDrink, tvQty;
Button btnPesanDrink;
public DrinkViewHolder(View itemView) {
super(itemView);
ivDrink = itemView.findViewById(R.id.ivDrink);
tvNameDrink = itemView.findViewById(R.id.tvNameDrink);
tvPriceDrink = itemView.findViewById(R.id.tvPriceDrink);
ivMin = itemView.findViewById(R.id.ivMin);
ivPlus = itemView.findViewById(R.id.ivPlus);
tvQty = itemView.findViewById(R.id.tvQty );
btnPesanDrink = itemView.findViewById(R.id.btnPesanDrink);
}
}
@Override
public void onBindViewHolder(final DrinkAdapter.DrinkViewHolder holder, final int position) {
final Drink list = listDrink.get(position);
holder.tvNameDrink.setText(list.getName_drink());
holder.tvPriceDrink.setText("Rp "+list.getPrice_drink());
if (list.getPhoto_id().length()>0){
Picasso.with(holder.itemView.getContext())
.load(ApiClient.BASE_URL+"assets/cafe/"+list.getPhoto_id())
.placeholder(R.drawable.noimage)
.error(R.drawable.noimage)
.into(holder.ivDrink);
}else{
//jika photo_id kosong
Picasso.with(holder.itemView.getContext())
.load(R.drawable.noimage)
.into(holder.ivDrink);
}
holder.ivMin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(qty==0){
holder.ivMin.setEnabled(false);
}else {
qty = qty-1;
holder.tvQty.setText(""+qty);
}
}
});
holder.ivPlus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(qty==5){
holder.ivPlus.setEnabled(false);
}else {
qty += 1;
holder.tvQty.setText(""+qty);
}
}
});
holder.btnPesanDrink.setOnClickListener(new View.OnClickListener() {
@SuppressLint("ResourceAsColor")
@Override
public void onClick(View v) {
String name = list.getName_drink();
String price = list.getPrice_drink();
String qty = holder.tvQty.getText().toString();
DataHelper dHelper = new DataHelper(v.getContext());
SQLiteDatabase db = dHelper.getWritableDatabase();
db.execSQL("INSERT INTO tb_pesanan(name, price, qty) VALUES('"+name+"','"+price+"','"+qty+"')");
Toast.makeText(v.getContext(), qty+" "+name+" disimpan di keranjang !", Toast.LENGTH_SHORT).show();
holder.btnPesanDrink.setBackgroundColor(R.color.colorSemuWhite);
holder.btnPesanDrink.setEnabled(false);
}
});
}
@Override
public int getItemCount() {
return listDrink.size();
}
}<file_sep>package com.nuzul.caffein.dbSQLite;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import com.nuzul.caffein.MainActivity;
import com.nuzul.caffein.SignInActivity;
import java.util.HashMap;
public class SessionManagement{
private SharedPreferences mSharedPref;
private SharedPreferences.Editor mEditor;
private Context mContext;
int PRIVATE_MODE;
private static final String PREF_NAME = "SharedPreferences";
private static final String IS_LOGIN = "is_login";
public static final String KEY_USER = "username";
public static final String KEY_PASS = "<PASSWORD>";
public SessionManagement(Context mContext) {
this.mContext = mContext;
mSharedPref = this.mContext.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
mEditor = mSharedPref.edit();
}
//untuk menyimpan SharedPreferences
public void createLoginSession(String user, String pass) {
// Storing login value as TRUE
mEditor.putBoolean(IS_LOGIN, true);
mEditor.putString(KEY_USER, user);
mEditor.putString(KEY_PASS, pass);
mEditor.commit();
}
//untuk mendapatkan informasi user
public HashMap<String, String> getUserInformation() {
HashMap<String, String> user = new HashMap<String, String>();
user.put(KEY_USER, mSharedPref.getString(KEY_USER, null));
user.put(KEY_PASS, mSharedPref.getString(KEY_PASS, null));
return user;
}
//jika sudah login
public boolean isLoggedIn() {
return mSharedPref.getBoolean(IS_LOGIN, false);
}
//jika belum login
public void checkIsLogin() {
if (!isLoggedIn()) {
// user is not logged in redirect to MainActivity
Intent i = new Intent(mContext, SignInActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(i);
}
}
public void logoutUser(){
mEditor.clear();
mEditor.commit();
Intent i = new Intent(mContext, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(i);
}
}<file_sep>package com.nuzul.caffein;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class ContactActivity extends AppCompatActivity {
Button btnMaps;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact);
btnMaps = findViewById(R.id.btnMaps);
btnMaps.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), Maps2.class));
}
});
}
}<file_sep>package com.nuzul.caffein;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import com.nuzul.caffein.Adapter.SugestionAdapter;
import com.nuzul.caffein.Model.Sugestion;
import com.nuzul.caffein.dbSQLite.DataHelper;
import java.util.ArrayList;
import java.util.List;
public class SugestionActivity extends AppCompatActivity {
Button btnSaran;
//--------------------------------------------------------------
private DataHelper dHelper;
private List<Sugestion> listSaran = new ArrayList<Sugestion>();
private RecyclerView rv;
private SugestionAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sugestion);
dHelper = new DataHelper(this);
btnSaran = findViewById(R.id.btnSaran);
rv = findViewById(R.id.rvSugestion);
getSaran();
btnSaran.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), SugestionInActivity.class));
}
});
}
public void getSaran(){
listSaran.addAll(dHelper.allSaran());
adapter = new SugestionAdapter(this, listSaran);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
rv.setLayoutManager(mLayoutManager);
rv.setAdapter(adapter);
}
}<file_sep>package com.nuzul.caffein.Model;
public class Sugestion {
String nama, email, saran;
public String getNama() {
return nama;
}
public void setNama(String nama) {
this.nama = nama;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSaran() {
return saran;
}
public void setSaran(String saran) {
this.saran = saran;
}
}<file_sep>package com.nuzul.caffein.Rest;
import com.nuzul.caffein.Model.ResultCoffee;
import com.nuzul.caffein.Model.ResultDessert;
import com.nuzul.caffein.Model.ResultDrink;
import com.nuzul.caffein.Model.ResultFood;
import com.nuzul.caffein.Model.ResultPesanan;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
public interface ApiInterface {
@GET("food/user")
Call<ResultFood> getFood();
@GET("drink/user")
Call<ResultDrink> getDrink();
@GET("coffee/user")
Call<ResultCoffee> getCoffee();
@GET("dessert/user")
Call<ResultDessert> getDessert();
@Multipart
@POST("pesanan/user")
Call<ResultPesanan> postPesanan(@Part MultipartBody.Part file,
@Part("kode_meja") RequestBody kode_meja,
@Part("name") RequestBody name,
@Part("qty") RequestBody qty,
@Part("price") RequestBody price,
@Part("action") RequestBody action);
@Multipart
@POST("pesanan/user")
Call<ResultPesanan> deletePesanan(@Part("name") RequestBody name,
@Part("action") RequestBody action);
}<file_sep>package com.nuzul.caffein.Adapter;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.nuzul.caffein.MainActivity;
import com.nuzul.caffein.Model.Sugestion;
import com.nuzul.caffein.R;
import com.nuzul.caffein.SugestionActivity;
import com.nuzul.caffein.dbSQLite.DataHelper;
import java.util.List;
public class SugestionAdapter extends RecyclerView.Adapter<SugestionAdapter.MyViewHolder> {
private Context context;
private List<Sugestion> listSugestion;
public SugestionAdapter(Context context, List<Sugestion> listSugestion) {
this.context = context;
this.listSugestion = listSugestion;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_sugestion, parent, false);
return new MyViewHolder(itemView);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView tvNama, tvEmail, tvSaran;
public MyViewHolder(View view) {
super(view);
tvNama = view.findViewById(R.id.tvName);
tvEmail = view.findViewById(R.id.tvEmail);
tvSaran = view.findViewById(R.id.tvSaran);
}
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final Sugestion list = listSugestion.get(position);
holder.tvNama.setText(list.getNama());
holder.tvEmail.setText(list.getEmail());
holder.tvSaran.setText(list.getSaran());
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
//Show dialog
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Action");
alertDialog.setMessage("Hapus pesan ini ? ");
alertDialog.setPositiveButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setNegativeButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// DO SOMETHING HERE
DataHelper dHelper = new DataHelper(context);
String nama = list.getNama();
SQLiteDatabase db = dHelper.getWritableDatabase();
db.execSQL("DELETE FROM tb_saran WHERE nama='"+nama+"'");
Toast.makeText(context, "Saran dari "+nama+", berhasil dihapus !", Toast.LENGTH_SHORT).show();
context.startActivity(new Intent(context, SugestionActivity.class));
}
});
AlertDialog dialog = alertDialog.create();
dialog.show();
return true;
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context, "Update !", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public int getItemCount() {
return listSugestion.size();
}
}<file_sep>package com.nuzul.caffein.Adapter;
import android.annotation.SuppressLint;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.nuzul.caffein.Model.Coffee;
import com.nuzul.caffein.R;
import com.nuzul.caffein.Rest.ApiClient;
import com.nuzul.caffein.dbSQLite.DataHelper;
import com.squareup.picasso.Picasso;
import java.util.List;
public class CoffeeAdapter extends RecyclerView.Adapter<CoffeeAdapter.CoffeeViewHolder> {
int qty=0;
List<Coffee> listCoffee;
public CoffeeAdapter(List<Coffee> listCoffee) {
this.listCoffee = listCoffee;
}
@NonNull
@Override
public CoffeeAdapter.CoffeeViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_coffee, parent,false);
CoffeeAdapter.CoffeeViewHolder mHolder = new CoffeeAdapter.CoffeeViewHolder(view);
return mHolder;
}
public class CoffeeViewHolder extends RecyclerView.ViewHolder {
ImageView ivCoffee, ivMin, ivPlus;
TextView tvNameCoffee, tvPriceCoffee, tvQty;
Button btnPesanCoffee;
public CoffeeViewHolder(@NonNull View itemView) {
super(itemView);
ivCoffee = itemView.findViewById(R.id.ivCoffee);
tvNameCoffee = itemView.findViewById(R.id.tvNameCoffee);
tvPriceCoffee = itemView.findViewById(R.id.tvPriceCoffee);
ivMin = itemView.findViewById(R.id.ivMin);
ivPlus = itemView.findViewById(R.id.ivPlus);
tvQty = itemView.findViewById(R.id.tvQty );
btnPesanCoffee = itemView.findViewById(R.id.btnPesanCoffee);
}
}
@Override
public void onBindViewHolder(@NonNull final CoffeeViewHolder holder, int position) {
final Coffee list = listCoffee.get(position);
holder.tvNameCoffee.setText(list.getName_coffee());
holder.tvPriceCoffee.setText("Rp "+list.getPrice_coffee());
if (list.getPhoto_id().length()>0){
Picasso.with(holder.itemView.getContext())
.load(ApiClient.BASE_URL+"assets/cafe/"+list.getPhoto_id())
.placeholder(R.drawable.noimage)
.error(R.drawable.noimage)
.into(holder.ivCoffee);
}else{
//jika photo_id kosong
Picasso.with(holder.itemView.getContext())
.load(R.drawable.noimage)
.into(holder.ivCoffee);
}
holder.ivMin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(qty==0){
holder.ivMin.setEnabled(false);
}else {
qty = qty-1;
holder.tvQty.setText(""+qty);
}
}
});
holder.ivPlus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(qty==5){
holder.ivPlus.setEnabled(false);
}else {
qty += 1;
holder.tvQty.setText(""+qty);
}
}
});
holder.btnPesanCoffee.setOnClickListener(new View.OnClickListener() {
@SuppressLint("ResourceAsColor")
@Override
public void onClick(View v) {
String name = list.getName_coffee();
String price = list.getPrice_coffee();
String qty = holder.tvQty.getText().toString();
DataHelper dHelper = new DataHelper(v.getContext());
SQLiteDatabase db = dHelper.getWritableDatabase();
db.execSQL("INSERT INTO tb_pesanan(name, price, qty) VALUES('"+name+"','"+price+"','"+qty+"')");
Toast.makeText(v.getContext(), qty+" "+name+" disimpan di keranjang !", Toast.LENGTH_SHORT).show();
holder.btnPesanCoffee.setBackgroundColor(R.color.colorSemuWhite);
holder.btnPesanCoffee.setEnabled(false);
}
});
}
@Override
public int getItemCount() {
return listCoffee.size();
}
}
|
a4c060101379ee3b443a5a1fa6e697f4a62c4c28
|
[
"Java"
] | 11
|
Java
|
muhiqbalfn/CaffeIn
|
d9453200ae5193c8d4b7a1271eaa57e807b7cc13
|
96a660592c573ff044bcb6629f24e9e3bcd7b164
|
refs/heads/master
|
<repo_name>metehankelir/mindSoft<file_sep>/index.php
<?php
/**
* Created by PhpStorm.
* User: Ali
* Date: 13.03.2019
* Time: 18:02
*/ ?>
<!doctype html>
<html lang="tr">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>mindSoft</title>
</head>
<body>
<h1>mindSoft</h1>
<hr>
<tr>
<td>mindSoft</td>
</tr>
<tr>
<td>mindSoft</td>
</tr>
<tr>
<td>mindSoft</td>
</tr>
<tr>
<td>mindSoft</td>
</tr>
<tr>
<td>mindSoft</td>
</tr>
</body>
</html>
|
e5b2962bea672bcba7dfe81cebde1a7fd3e77d1f
|
[
"PHP"
] | 1
|
PHP
|
metehankelir/mindSoft
|
cadf741c1735244b1b5874b4b1f9355287db2b30
|
277e0254e1c594382bfc271a824b4194b7afea5c
|
refs/heads/master
|
<repo_name>Mustapha-lourika/karaz-documentation<file_sep>/docs/zh-cn/README.md
# Headline
> An awesome project.zu
<file_sep>/docs/README.md
# Installation de KARAZ STUDIO
> Double-cliquez sur le fichier exécutable karazplatform.exe.
Karaz Studio se lance.
> veuillez cliquer sur suivant pour continuer

>veuillez lire les conditions de licence avant d'installer la plate-forme karaz
cliquez sur J'accepte pour continuer:

> cliquez sur suivant pour continuer:

>choisissez le dossier dans lequel vous voulez installer la plateforme karaz,
Puis cliquez sur installer pour démarrer l'installation

<file_sep>/docs/coverpage.md
<!-- _coverpage.md -->

# KARAZ STUDIO <small>1.1</small>
> Documentation officielle de framework KARAZ STUDIO.
[GitHub](https://github.com/docsifyjs/docsify/)
[Get Started](#hello)<file_sep>/docs/_coverpage.md
<!-- _coverpage.md -->

# KARAZ STUDIO <small>1.1</small>
> Documentation officielle de framework KARAZ STUDIO.
[GitHub](https://github.com/docsifyjs/docsify/)
[Get Started](#installation-de-karaz-studio)
[hello](#hello)
<file_sep>/docs/à-propos-de-karaz-studio/a-propos-de-karaz.js
console.log(232);<file_sep>/docs/zh-cn2/guide.md
<div id='définition-dun-schéma-xsd-sous-karaz'>
## Définition d’un schéma XSD sous KARAZ
Il s’agit du fichier central de tout modèle métier Karaz. Le .xsd décrit les données métier propres au modèle et qui seront:
<ul>
<li>
Exploitées par les processus appliqués au modèle
</li>
<br>
<li>
Affichées par les vues associées au modèle
</li>
</ul>
<img src="images\imag42.png" style="padding:3px;width:550px;height:350px">
</div>
<div id='éléments-dun-schéma-xsd'>
## Eléments d’un schéma XSD
Un schéma XSD sous Karaz peut contenir 3 catégories d’éléments :
<table>
<tr>
<th>
Eléments simples
</th>
<th>
Eléments Complexes
</th>
<th>
Eléments multiples
</th>
</tr>
<tr>
<td>
<ul>
<li>
Int
</li>
<li>
long
</li>
<li>
string
</li>
<li>
double
</li>
<li>
Date
</li>
<li>
dateTime
</li>
</ul>
</td>
<td>
<ul>
<li>
Elément de référence
</li>
<li>
Elément d’attachement
</li>
<li>
Eléments importés
</li>
<li>
Eléments de facette
</li>
</ul>
</td>
<td>
<ul>
<li>
Liste
</li>
<li>
Tableau
</li>
</ul>
</td>
</tr>
</table>
</div>
### Eléments simples
> Les éléments de type <b> int/long </b> permettent de stoker les données métier de type entier ou entier long.
Ces éléments sont servis aux utilisateurs à travers des vues formulaire
Le widget utilisé pour servir un entier est : integer
> Les éléments de type double permet de stoker les information métier de type décimal avec virgule.
Ces éléments sont servis dans les vues formulaire à travers le widget : double
> Les éléments de type Date et DateTime permettent de stoker les informations métier de type date
Ces éléments sont servis dans les vues formulaire à travers les widgets date ,date time.
> Les éléments de type string sont parmi les plus utilisés. Il permettent de stoker les données métier de type chaine de caractère .
Ces éléments sont servis dans les vues formulaire à travers les widgets : text/textArea/select/boolean/stringToggler/htmlEditor
### Eléments Complexes
#### Elément de référence
<img src="images\imag43.png" style="padding:3px">
<ul>
<li>
Les éléments de type référence permettent de faire une jointure xml entre plusieurs modèles.
</li>
<li>
Ils permettent ainsi de relier les modèles entre eux</li>
<li>
Ces éléments sont servis dans les vues formulaire à travers les widgets : reference
</li>
</ul>
<table>
<tr>
<th>
Attribut
</th>
<th>
Type
</th>
<th>
Description
</th>
<th>
Utilisation
</th>
</tr>
<tr>
<th>
dataObjectId
</th>
<td>
long
</td>
<td>
ID karaz de l’objet référencé
</td>
<td>
Utilisé pour accéder à l’objet
</td>
</tr>
<tr>
<th>
description
</th>
<td>
String
</td>
<td>
Sequence de l’objet référencé (IndexString1)
</td>
<td>
Utilisé pour afficher l’intitulé de l’objet
</td>
</tr>
<tr>
<th>
modelQN
</th>
<td>
String
</td>
<td>
Identifier le nom de l’objet référencé
</td>
<td>
Utilisé pour visualiser l’objet
</td>
</tr>
</table>
#### Elément attachement
Les attachements Karaz sont les documents attachés aux objets métiers. Un document peut être attaché soit manuellement par un utilisateur soit automatiquement par le système :
<ul>
<li>
<b> Attachement Manuelle : </b>
se fait directement par l’utilisateur via le formulaire d’une activité manuelle. Il charge alors un document à partir de sa machine en utilisant le service UploadFile pour le chargement du fichier et le service KarazRepository pour le stockage dans la GED interne de Karaz.
</li>
<li>
<b> Attachement automatique : </b> Attachement automatique : se fait par le système à travers l’une des 3 actions :
<ol>
<li>
Directement à travers une activité automatique
</li>
<li>
indirectement dans une activité manuelle à travers une action distante (Remote action). Exemple (i.e bouton Imprimer)
</li>
<li>
Via un menu Rapport dans les vues de consultation
</li>
</ol>
</li>
<li>
Dans le cas de l’attachement automatique, seul le service KarazRepository est utilisé pour le stockage des fichiers générés dans la GED interne de Karaz.
</li>
</ul>
Karaz Modeler propose un type préconstruit «kfx:attachment» qui permet de gérer l’attachement.
<img src="images\imag44.png" style="padding:3px">
<table>
<tr>
<th>
Attribut
</th>
<th>
Type
</th>
<th>
Description
</th>
<th>
Utilisation
</th>
</tr>
<tr>
<td>
fileId
</td>
<td>
long
</td>
<td>
Sequence au niveau GED Karaz
</td>
<td>
Récupéré par le service KarazRepository sous forme de séquence numérique continue
</td>
</tr>
<tr>
<td>
gedId
</td>
<td>
String
</td>
<td>
Identifiant complexe au niveau GED Karaz
</td>
<td>
Récupéré par le service KarazRepository sous forme d’une longue chaine alphanumérique
</td>
</tr>
<tr>
<td>
fileName
</td>
<td>
String
</td>
<td>
Nom du fichier
</td>
<td>
Affiché en FileCombo
</td>
</tr>
<tr>
<td>
fileSize
</td>
<td>
long
</td>
<td>
Taille de fichier on Octet
</td>
<td>
Affichage spéciale
</td>
</tr>
<tr>
<td>
fileSignature
</td>
<td>
String
</td>
<td>
MD5 du contenu de fichier
</td>
<td>
Affichage spéciale pour vérification du transfert
</td>
</tr>
<tr>
<td>
fileTime
</td>
<td>
Time
</td>
<td>
Date/heure de chargement
</td>
<td>
Afficage spéciale
</td>
</tr>
<tr>
<td>
maxSize
</td>
<td>
long
</td>
<td>
Taille maxiamele de chargement
</td>
<td>
Spécifié avant le chargement. Utilisé pour une validation côté client avant de démarrer le chargement.
</td>
</tr>
<tr>
<td>
mime
</td>
<td>
String
</td>
<td>
Type de mimes acceptés, i.e: « application/pdf » ou « image/* ». C’est un élément multiple.
</td>
<td>
Spécifié avant le chargement. Utilisé pour une validation côté client avant de démarrer le chargement.
</td>
</tr>
<tr>
<td>
version
</td>
<td>
int
</td>
<td>
numéro de version GED
</td>
<td>
</td>
</tr>
<tr>
<td>
attachmentName
</td>
<td>
String
</td>
<td>
Catégorie de l'attachement
</td>
<td>
Utilisé par KarazRepository pour une validation côté serveur de l’extension et de la taille. Utilisé aussi pour le classement GED des documents par catégorie.
</td>
</tr>
</table>
Les attachements sont servis dans les vues formulaire à travers les widgets :
<ul>
<li>
<b> FileCombo :</b> qui permet de télécharger le fichier attache.
</li>
<li>
<b> FileDownload :</b> qui permet de télécharger le fichier.</li>
<li>
<b> Html Iframe : </b> qui permet de visualiser directement le contenu du fichier
</li>
</ul>
#### Elément importé
<ul>
<li>
Il est possible sous KARAZ d'importer dan un modèle, un schéma ou une partie d'un schéma d'un autre modèle.
</li>
<li>
Les éléments importés sont identifiables au niveau du schéma XSD à travers la valeur de l’attribut « Prefix »
</li>
</ul>
<table>
<tr>
<td>
<img src="images\imag45.png" style="padding:3px">
</td>
<td>
<img src="images\imag46.png" style="padding:3px">
</td>
</tr>
</table>
#### Elément facette
Les éléments de type facette permettent d’importer un schéma XSD on se basant sur un projet existant.
<img src="images/imag47.png" style="padding:3px;width:200px;height:500">
pour ajouter des facettes au schéma xsd il faut les configurer dans kconfig.xml
### Eléments multiples d’un schéma XSD.
<ul>
<li>
Un élément multiple permet de définir une collection d’éléments (listes ou tables).
</li>
<br>
<li>
Ces éléments peuvent être consultées par les utilisateurs directement dans la vue formulaire. Les widgets utilise pour servir un élément multiple sont : Table/For/Foreach
</li>
</ul>
## explications des éléments d’un schéma XSD
Le schéma xsd porte toujours le nom de modèle
<img src="images\imag48.png" style="padding:3px;width:600px;height:400px">
Si on a des blocs répétitifs (dans cet exemple validation1 et validation2),on utilise un élément abstrait pour factoriser ces éléments:
<table>
<tr>
<td>
<img src="images\imag50.png" style="padding:3px">
</td>
<td>
<img src="images\imag51.png" style="padding:3px;width:300;height:300px">
</td>
</tr>
</table>
dans ce cas on peut ajouter des élément de type 'tns:validation1': <br>
<img src="images\imag52.png" style="padding:3px;width:500px">
### les propriétés des éléments de shéma xsd
<img src="images\imag49.png" style="padding:3px;width:500px">
<ul>
<li>
<b> Name:</b> c'est le nom de l'élément de shéma xsd.le nom ne doit ni commencer ni terminer par une espace.
</li>
<li>
<b>Optionnal: </b> Si pour un élément On coche Optional ,cet élément ne va pas apparaitre dans le fichier d'initialisation de processus (..-ini.xml)
</li>
<li>
<b> Nillable : </b>Elle est appliquée pour les dates Si on coche 'Nillable' Ça signifie que la date peut être nulle
</li>
<li>
<b> Indexed :</b> Si on coche 'indexed' pour un élément, ce dernier sera généré dans le fichier '..-indexation.xml'.
</l>
</ul>
<file_sep>/docs/zh-cn/guide.md
## Pourquoi le BPMN dans Karaz? <button>Modifier </button>
Le concept [BPM](https://bpm.com/what-is-bpm) représente l’un des fondamentaux de la plateforme Karaz. Le choix d’adoption du concept BPM par Ribatis a été motivé par 3 besoins essentiels :
<ol>
<li>
Garantir la répartition fine et la traçabilité complète des actions effectuées par les partie-prenantes au processus.
</li>
<br>
<li>
Piloter et optimiser les processus métier en mesurant les performances de chaque acteur et chaque activité et identifier de façon objective et quantitative les pistes de simplification.
</li>
<br>
<li>
Assurer l’évolutivité et la flexibilité des procédures automatisées en permettant la modification à chaud de leur comportement en fonction des évolutions organisationnelles et réglementaires.
</li>
</ol>
## Comment le BPMN est implémenté sous Karaz ?
La dimension [BPMN](https://www.lucidchart.com/pages/fr/quest-ce-que-le-BPMN) (Business Process Management System) est assurée par la plateforme Karaz à travers les fonctionnalités suivantes :
<ul>
<li>
Un outil de modélisation qui sert à formaliser l’activité de l’organisation en processus. Il permet de définir également les données échangées et les interfaces avec les autres modules;
</li>
<br>
<li>
Des outils de développement pour formaliser la logique qui régit les processus de l’organisation ;
</li>
<br>
<li>
Un moteur d'exécution qui supervise le déroulement des processus ainsi que les échanges de paramètres ;
</li>
<br>
<li>
Un moteur de règles qui évalue l'état de tous les objets impliqués dans le déroulement des processus et déterminera si les conditions sont remplies pour en lancer, poursuivre ou arrêter l'exécution.
</li>
<br>
<li>
Un référentiel qui mémorise tous les objets manipulés, en particulier les définitions des processus, les règles qui doivent déclencher leur exécution, les contraintes d'intégrité, de sécurité ainsi que les mesures de référence relatives au métier de l’organisation ;
</li>
<br>
<li>
Des outils d'administration qui permettent de régler les paramètres de l'ensemble du système et d'obtenir des indicateurs de performance et des statistiques à partir des données collectées lors de l'exécution des processus ;
</li>
<br>
<li>
En adoptant le concept BPM, Ribatis a implémenté l’ensemble des « Capabilities » exigées par le deux standards BPMN 2.0 et BPEL.
</li>
</ul>
## Eléments de modélisation des processus
La norme BPMN prévoit quatre catégories d’éléments de logigrammes représentant les processus métier. Ces 4 catégories sont toutes implémentées par Karaz :
<table >
<tr>
<th>
Éléments de workflow
</th>
<th>
Éléments d'organisation
</th>
<th>
Éléments de lisibilité
</th>
<th>
Comportements spécifiques
</th>
</tr>
<tr>
<td>
<ul>
<li> Activities </li>
<li> Events </li>
<li> Gateways </li>
<li> Sequence flow </li>
</ul>
</td>
<td>
<ul>
<li>Pools </li>
<li> Lanes </li>
</ul>
</td>
<td>
<ul>
<li>Annotation </li>
<li> Links </li>
<li> Groups </li>
</ul>
</td>
<td>
<li>Messages </li>
<li> Signals </li>
<li> Timers </li>
<li> Errors </li>
</td>
</tr>
</table>
### Les éléments de workflow
#### Les activités
<ul>
<li>
Il s'agit d'une activité ou d'une tâche particulière effectuée par une personne ou un système. Il peut s'agir d’une tâche, sous-process, call activity ;
</li>
<br>
<li>
Karaz utilise plusieurs types d’activités (tâches) et d’autres composantes BPM pour décrire les processus métiers. Ces types sont définis par la notation MBPN 2.0. Chacun de ces types détient sa propre chaine d’actions (workflow interne) que Karaz active à des moments précis de l’exécution du processus ;
</li>
<br>
<li>
6types d’activités ou tâches peuvent être définies au niveau de la plateforme Karaz :
</li>
</ul>
##### Tâche utilisateur
<img src="images\imag6.png" style="float:left;padding:3px"> Une « Tâche Utilisateur » est une tâche associée à une personne physique (ou à un pool de personnes). Karaz assistera cette personne dans la réalisation de la tâche via des formulaires web spécifiés par le designer, et des chaines d’actions pré et post réalisation.<br> <br>
##### Tâche automatique
<br>
<img src="images\imag7.png" style="float:left;padding:3px">
L’activité automatique correspond à une tâche exécutée par le moteur de processus Karaz (Karaz Process Engine). Quand l’activité est prête à démarrer, le moteur va exécuter la chaine des actions associées.<br> <br> <br>
##### Tâche Manuelle
<img src="images\imag8.png" style="float:left;padding:3px">
Une tâche manuelle est une tâche qui n'est pas gérée par un moteur de processus Karaz. Le moteur de processus ne suit pas le début et la fin d'une telle tâche. Un exemple de ceci pourrait être l’envoi par poste d’une lettre recommandée à un partenaire.<br> <br> <br>
##### Sous-processus
<img src="images\imag9.png" style="float:left;padding:3px">
Il s’agit d’une activité dont les détails internes ont été modélisés à l'aide d'activités, de passerelles, d'événements et de flux de séquences. Karaz lancera d’autres instances de processus métier et ne clôturera l’activité parente que lorsque tous les sous-processus lancés seront terminés; <br> <br> <br>
##### Sous-processus Ad’Hoc
<img src="images\imag10.png" style="float:left;padding:3px">
Regroupe des activités qui ne sont pas obligatoirement liées par des relations de séquence.<br> <br> <br> <br> <br> <br>
##### Activités d’appel (Call Activity)
<img src="images\imag11.png" style="float:left;padding:3px">
Une activité d'appel identifie un point dans le processus où un processus global ou une tâche globale est utilisée.<br> <br> <br> <br>
#### Les événements
##### Star Event
<img src="images\imag12.png" style="float:left;padding:3px;width:70px;height:70px">
Cette activité marque le début du processus. C’est aussi une activité automatique.
Chaque processus doit avoir une et une seule activité START
<br> <br>
##### End Event
<img src="images\imag13.png" style="float:left;padding:3px;width:70px;height:70px">
Cette activité marque la fin du processus. C’est aussi une activité automatique.
Chaque processus doit avoir au moins une activité END <br> <br>
##### Intermediate Event
<img src="images\imag14.png" style="float:left;padding:3px;width:70px;height:70px">
Ils sont représentés à l'aide de cercles contenant d'autres symboles qui changent en fonction du type d'événement. On les classe en deux catégories, receveur (Catcher) ou lanceur (thrower) selon leur fonction
#### Les passerelles
<ul>
<li>
Il s’agit d’une activité automatique vide (sans aucune chaine d’action). Elle est utilisée pour définir des jointures de transitions (sortantes/entrantes) ou pour marquer un évènement.
</li>
<br>
<li>
Une passerelle constitue dans ce sens un point de décision qui peut ajuster le chemin en fonction des conditions ou des événements. Les entrées sont représentées par des losanges. Elles peuvent être exclusives ou inclusives, parallèles, complexes ou basées sur des données ou événements.
</li>
<br>
<li>
La passerelle exclusive et le type de passerelles le plus utilisé
</li>
</ul>
##### Passerelle exclusive
<img src="images\imag15.png" style="float:left;padding:3px;width:70px;height:70px">
Elle évalue l'état du processus métier et, en fonction de la condition, elle divise le flux en l'un des deux ou plusieurs chemins s'excluant mutuellement.<br> <br>
##### Passerelle inclusive
<img src="images\imag16.png" style="float:left;padding:3px;width:70px;height:70px">
On peut l’utiliser pour créer des chemins alternatifs mais également parallèles dans un flux de processus. Contrairement à la passerelle exclusive, toutes les expressions de condition sont évaluées. La vraie évaluation d'une condition Expression n'exclut pas l'évaluation d'autres expressions de conditions.<br> <br>
##### Passerelle parallèle
<img src="images\imag17.png" style="float:left;padding:3px;width:70px;height:70px">
Une passerelle parallèle est utilisée pour synchroniser (combiner) des flux parallèles et pour créer des flux parallèles. Une passerelle parallèle crée des chemins parallèles sans vérifier les conditions ; chaque flux séquentiel sortant est passé à l'exécution de cette passerelle. Pour les flux entrants, la passerelle parallèle attendra tous les flux entrants avant de déclencher le flux à travers ses flux de séquence sortants.
.<br> <br>
##### Passerelle basée sur un évènement
<img src="images\imag18.png" style="float:left;padding:3px;width:70px;height:70px">
Elle représente un point de branchement dans le processus où les chemins alternatifs qui suivent la passerelle sont basés sur les événements qui se produisent plutôt que sur l'évaluation des expressions utilisant des données de processus (comme avec une passerelle exclusive ou inclusive).
### Flux de séquence
Indique l'ordre des activités à effectuer. Il est représenté par une ligne droite fléchée. Il peut s'agir d'un flux conditionnel ou d'un flux par défaut
<img src="images\imag19.png" style="float:left;padding:3px">
### Eléments d’organisation
Il s’agit de conteneurs visuels permettant d’organiser les éléments BPMN 2.0 selon une logique d’acteur, d’organisation, de fonction,…
#### Piste (Pool)
Une piste représente les principaux participants d'un processus. Une piste différente peut faire référence à une autre organisation ou à un autre service qui participe à un même processus.
#### Couloir (Lane)
Les couloirs au sein d'une piste montrent les activités et les flux d'un rôle ou d'un participant, et définissent qui est responsable de quelle partie du processus.<br> <br>
<img src="images\imag20.png" style="float:left;padding:3px;align:center"> <br> <br> <br> <br> <br> <br>
### Eléments de lisibilité
Il s'agit d'une information supplémentaire utilisée par le Business Analyst ou Designer Karaz pour ajouter un niveau de détail nécessaire au logigramme.
##### Groupe
<img src="images\imag21.png" style="float:left;padding:3px;width:70px;height:70px">
Elle représente un point de branchement dans le processus où les chemins alternatifs qui suivent la passerelle sont basés sur les événements qui se produisent plutôt que sur l'évaluation des expressions utilisant des données de processus (comme avec une passerelle exclusive ou inclusive).
##### Annotation
<img src="images\imag22.png" style="float:left;padding:3px;width:70px;height:70px">
Apporte des explications complémentaires sur une partie du diagramme.<br> <br>
### Comportements spécifiques
Ci-après une liste des éléments personnalisés KARAZ
<img src="images\imag24.png" style="float:right;padding:5px;width:400px;height:270px">
<ul style='padding-top:20px'>
<li>
<b> 'Signal Event' et 'Message Event' </b> :se sont des événements des échange des messages entre les processus
</li>
<li>
<b> 'Send Email', 'Launch Process' et 'Web service Invoker':</b>
se sont des services task ajoutés par karaz.
karaz builder peut interpréter ces éléments pour faciliter le développement des régles de gestion
</li>
<li>
<b> 'boundary Event'</b>:est un événement lié à une activité
</li>
</ul>
## Workflows internes des activités
<ul>
<li>
L’exécution d’une activité par le moteur Karaz se fait en suivant un workflow interne spécifique. Ce workflow interne à l’activité varie selon le type d’activité et il se déclenche à partir d’un ensemble de ports d’entrées. <br>
Le choix du port d’entrée dépend de l’état de l’activité et son exécution interne et jalonnée par des « Moments » précis.
Dans la pratique, les deux types d’activités les plus utilisés dans la modélisation des processus métier sous Karaz sont : L’activité automatique et l’activité manuelle.
</li>
<br>
<li>
Chaque type d’activité dispose de ses propres ports et ses propres moments
Le designer Karaz peut associer des règles de gestion à chacun de ces moments. Il convient de bien comprendre le rôle et l’impact de chacun de ces moments sur l’exécution de l’activité.
</li>
<br>
<li>
Dans la pratique, les deux types d’activités les plus utilisés dans la modélisation des processus métier sous Karaz sont : L’activité automatique et l’activité manuelle.
</li>
</ul>
### Héritage des activités
Les activités dans Karaz correspondent à des classes java. Elles héritent toutes de la classe « Activity »
<img src="images\imag25.png" style="padding:5px;width:400px;height:270px">
### Activités automatiques
Ce workflow interne est valable aussi pour les activités « Start », « End » et « Sub Process » qui sont également des sous type d’activité automatique.
<img src="images\imag26.png" style="padding:5px;width:600px;height:270px">
#### Liste des ports
<table>
<tr>
<th>
Port
</th>
<th>
Type
</th>
<th>
Activation
</th>
</tr>
<tr>
<td>
in
</td>
<td>
Entrée
</td>
<td>
Activé suite à une transition entrante du processus
</td>
</tr>
<tr>
<td>
Error
</td>
<td>
Entrée
</td>
<td>
Activé suite à une réexécution ou une reprise d’un statut « ERROR »
</td>
</tr>
<tr>
<td>
out
</td>
<td>
Sortie
</td>
<td>
Active la suite du processus.
</td>
</tr>
</table>
#### Liste des moments
<table>
<tr>
<th>
Moment
</th>
<th>
Explication
</th>
<th>
Méthode JAVA
</th>
</tr>
<tr>
<td>
Create
</td>
<td>
Exécuté, uniquement la première fois que l’activité est activée. On y associé des règles de gestion qui ne doivent s’appliquer que lors de la création de l’activité (notification externe, création de ressources persisté). Si le moteur Karaz est amené à réactiver l’instance d’activité (suite à une erreur ou à une action effectuée à travers la console ‘Karaz BAM’), ce moment ne sera plus exécuté.
</td>
<td>
create() ;
Toute exception ou erreur sera ignorée (catchée)
</td>
</tr>
<tr>
<td>
Execute
</td>
<td>
C’est le moment principal. Il est exécuté à chaque fois que l’instance d’activité est activée, sauf lors de la Clôture de l’activité par un administrateur à travers la console ‘Karaz BAM’.
</td>
<td>
execute() ;
Toute exception arrêtera le processus et mettra le statut de l’instance en « ERROR »
</td>
</tr>
<tr>
<td>
Close
</td>
<td>
C’est un moment qui est toujours exécuté, même lors de clôture suite à une action sur ‘Karaz BAM’.
</td>
<td>
close() ;
Toute exception sera ignorée.
</td>
</tr>
<tr>
<td>
Initialize
</td>
<td>
Exécuté uniquement lors de la réactivation de l’instance suite à une demande ‘Karaz BAM’ ou à une reprise après une erreur.
</td>
<td>
initialize() ;
Toute exception ou erreur sera ignorée
</td>
</tr>
<tr>
<td>
Propagation
</td>
<td>
Exécuté pour sélectionner la prochaine transition. Soit pour élire une seule transition (de sortie) parmi plusieurs possibilités, soit pour temporiser la propagation (en attendant un évènement externe).
</td>
<td>
checkTransitionToXXX() ;
Toute exception ou erreur sera ignorée
</td>
</tr>
</table>
### Activités utilisateur
<ul>
<li>
L’activité de type utilisateur est plus complexe que le type automatique ;
</li>
<li>
Cette activité gère les interactions avec l’utilisateur en prenant en compte les différents contextes d’exécution des actions ;
</li>
<li>
Les actions sont exécutées tout en garantissant l’intégrité globale du processus ainsi que celle des objets métier sur lesquels il agit.
</li>
</ul> <br> <br>
<img src="images\imag27.png" style="padding:3px;width:670px;height:370px">
#### Liste des ports
<table>
<tr>
<th>
Port
</th>
<th>
Type
</th>
<th>
Activation
</th>
</tr>
<tr>
<td>
in
</td>
<td>
Entrée
</td>
<td>
Activé suite à une transition entrante de processus.
</td>
</tr>
<tr>
<td>
Error
</td>
<td>
Entrée
</td>
<td>
Activé suite à une réexécution ou une reprise d’un statut « ERROR »
</td>
</tr>
<tr>
<td>
out
</td>
<td>
Sortie
</td>
<td>
Active la suite du processus.
</td>
</tr>
<tr>
<td>
taskOut
</td>
<td>
Sortie
</td>
<td>
Ajoute l’instance dans la corbeille des tâches.
</td>
</tr>
<tr>
<td>
taskIn
</td>
<td>
Entrée
</td>
<td>
Activé quand un utilisateur charge l’instance à partir de la corbeille des tâches.
</td>
</tr>
<tr>
<td>
loaded
</td>
<td>
Sortie
</td>
<td>
Retourne le formulaire de collaboration à l’utilisateur et lui associe un lock sur la tâche. L’instance processus est alors réservée pour l’utilisateur
</td>
</tr>
<tr>
<td>
cancel
</td>
<td>
Entrée
</td>
<td>
Activé quand l’utilisateur annule ou abandonne son lock sur la tâche à effectuer.
l’utilisateur
</td>
</tr>
<tr>
<td>
submit
</td>
<td>
Entrée
</td>
<td>
Activé lorsque l’utilisateur soumet le formulaire pour validation.
</td>
</tr>
</table>
#### Liste des moments
<table>
<tr>
<th>
Moment
</th>
<th>
Explication
</th>
<th>
Méthode JAVA
</th>
</tr>
<tr>
<td>
Create
</td>
<td>
Exécuté, uniquement la première fois que l’activité est activée.
</td>
<td>
create() ;
exception ignorée.
</td>
</tr>
<tr>
<td>
Allocate
</td>
<td>
Calcule les ressources (profiles/utilisateurs) associés à l’instance.
</td>
<td>
resource() ;
Toute exception arrêtera le processus et mettra le statut de l’instance en « ERROR »
</td>
</tr>
<tr>
<td>
Close
</td>
<td>
C’est un moment qui est toujours exécuté, même lors de clôture suite à une action sur ‘Karaz BAM’.
</td>
<td>
close() ;
Toute exception sera ignorée.
</td>
</tr>
<tr>
<td>
Initialize
</td>
<td>
Exécuté uniquement lors de la réactivation de l’instance suite à une demande ‘Karaz BAM’(RESTART) ou à une reprise après une erreur.
</td>
<td>
initialize() ;
Toute exception causera un statut "ERROR"
</td>
</tr>
<tr>
<td>
START
</td>
<td>
Exécuté uniquement lorsque l’utilisateur charge un formulaire pour la première fois.
</td>
<td>
start() ;
exception ignorée
</td>
</tr>
<tr>
<td>
Load
</td>
<td>
Exécuté, chaque fois que le formulaire est chargé par l’utilisateur.
</td>
<td>
load() ;
Toute exception causera un statut « ERROR »
</td>
</tr>
<tr>
<td>
Release
</td>
<td>
Exécuté quand l’utilisateur abandonne la tâche et la remet dans le pool.
</td>
<td>
start() ;
exception ignorée
</td>
</tr>
<tr>
<td>
Validate
</td>
<td>
Exécuté lors de la soumission du formulaire pour valider le formulaire. Si aucune erreur n’est déclarée, on passe au moment Close. Sinon, on remet le formulaire à l’utilisateur pour correction.
</td>
<td>
start() ;
exceptions considérés comme erreur de validation
</td>
</tr>
<tr>
<td>
Propagation
</td>
<td>
Exécuté pour sélectionner la prochaine transition. Soit pour élire une seule transition (de sortie) parmi plusieurs possibilités, soit pour temporiser la propagation (en attendant un évènement externe)
</td>
<td>
checkTransitionToXXX() ;
Toute exception/erreur sera ignorée
</td>
</tr>
</table>
#### Status des activités Karaz
<table>
<tr>
<td>
Moment
</td>
<td>
Type activité
</td>
<td>
Méthode Java
</td>
</tr>
<tr>
<td>
Running
</td>
<td>
Automatique
</td>
<td>
L’activité est en cours d’exécution (moment Execute).
</td>
</tr>
<tr>
<td>
Executed
</td>
<td>
Automatique
</td>
<td>
L’activité vient de terminer son exécution (moment Execute). Il s’agit d’un état instable du processus et non accessible à partir de la console BAM.
</td>
</tr>
<tr>
<td>
Closed
</td>
<td>
Toute Activité
</td>
<td>
L’activité est terminée.
</td>
</tr>
<tr>
<td>
Error
</td>
<td>
Toute Activité
</td>
<td>
L’activité est arrêtée suite à une erreur.
</td>
</tr>
<tr>
<td>
Aborted
</td>
<td>
Toute Activité
</td>
<td>
L’activité est arrêtée par le Moteur Karaz suite à une action préméditée et prévue (Exemple : suppression de l’objet métier).
</td>
</tr>
<td>
Initiated
</td>
<td>
Toute Activité
</td>
<td>
L’instance d’activité vient d’être réinitialisée (Suite à une erreur ou perte de connexion par exemple). Il s’agit d’un état instable du processus mais reste accessible à partir de la console BAM.
</td>
</tr>
<tr>
<td>
Allocated
</td>
<td>
Tâche Utilisateur
</td>
<td>
La tâche est allouée à tout le pool. Elle n’est encore assignée à aucun utilisateur.
</td>
</tr>
<tr>
<td>
Loaded
</td>
<td>
Tâche Utilisateur
</td>
<td>
La tâche est affectée à une personne (qui vient d’ouvrir le formulaire). Les autres membres du pool, ne peuvent plus y accédée. Sauf si la tâche est libérée à nouveau.
</td>
</tr>
<td>
Started
</td>
<td>
Tâche Utilisateur
</td>
<td>
Indique que l’activité est au moment Start.
Ce n’est pas un état stable.
</td>
</tr>
<tr>
<td>
TimeOut
</td>
<td>
Toute Activité
</td>
<td>
Le moteur Karaz a fermé l’instance d’activité suite au dépassement de la durée allouée à sa réalisation. Ce statut n’est pas accessible à partir du BAM puisque Karaz passe automatiquement au statut Closed une activité passée par la moment Timeout.
</td>
</tr>
<tr>
<td>
Saving
</td>
<td>
Tâche Utilisateur
</td>
<td>
La tâche est en cours validation. L’activité prend ce statut lorsqu’un problème est survenu au moment de l’enregistrement d’un travail effectué sur une tâche.
</td>
</tr>
<tr>
<td>
Paused
</td>
<td>
Tâche Utilisateur
</td>
<td>
L’utilisateur vient d’enregistrer son formulaire sans valider l’étape. Les données traitées sans enregistrées sur une copie provisoire (XML CC).
</td>
</tr>
<tr>
<td>
Saved
</td>
<td>
Tâche Utilisateur
</td>
<td>
La tâche est validée et les données sont sauvegardées (Xml CC vidé). Il s’agit d’un état provisoire et instable. Il est automatiquement écrasé par le statut « Closed » sauf en cas d’erreur lors de la validation de l’activité.
</td>
</tr>
<tr>
<td>
Propaging
</td>
<td>
Toute Activité
</td>
<td>
L’étape est terminée. Mais le moteur n’a pas encore déterminé la prochaine activité (attente d’autres événements)
</td>
</tr>
<tr>
<td>
Skipped
</td>
<td>
Toute Activité
</td>
<td>
Le moteur Karaz a sauté (court-circuité) cette activité (suite à un paramétrage sur la console d’administration Karaz)
</td>
</tr>
</table>
### Karaz Managed Activities and Actions (KMAA)
Ce schéma présente une comparaison entre BPMN 2.0 et les éléments personnalisés par KARAZ
<img src="images\imag28.png" style="padding:3px">
<ul>
<li>
<b> Documentation </b>: cet artefact est utilisé à des fins de documentation.il peut être associé à une activité particulière, sinon il concernera le processus global
</li>
<li>
<b>Validation Task :</b> Une tâche de validation est une tâche de workflow typique dans laquelle un interprète humain valide les données créées par d'autres collaborateurs.
KMAA prend en charge la persistance et la journalisation des données de validation telles que la connexion du validateur, le temps d'opération et la décision que l'entreprise actuelle doit contenir une occurrence de la facette générique «Support de validation»
</li>
</ul>
## Création de processus
chaque projet contient ou ou plusieurs modèles.
dans cette exemple on a deux modèles "Article" et "Collaborateur"
<img src="images\imag30.png" style="padding:3px;width:200px;height:200px"> <br>
<br>
chaque modèle contient ou ou plusieurs processus .On peut aussi ajouter des autres processus
<img src="images\imag31.png" style="padding:3px;width:300px;height:300px"> <br> <br>
On clique sur 'Open Resource File' pour visualiser le processus : <br>
<img src="images\imag32.png" style="padding:3px;width:200px;height:200px"> <br>
> karaz studio offre une palette qui contient tous les éléments de processus
<img src="images\imag33.png" style="padding:3px;width:250px;height:400px"> <br>
> Un exemple de processus
<img src="images\imag34.png" style="padding:3px;width:350px;height:350px"> <br>
> les propriétés d'une activité utilisateur
<img src="images\imag35.png" style="padding:3px;width:300px;height:300px"> <br>
<ul>
<li>
<b> time to complete </b> :le délai d'une activité
</li>
<li>
<b> View Name </b> : l'activité sera charger la vue nommée par ce nom.
</li>
<li>
[Task List](htttps://www.google.com)
</li>
</ul>
> Les propriétés de l'activité 'Send Email'
<table>
<tr>
<td>
<img src="images\imag36.png" style="float:right;padding:3px;width:300px;height:300px">
</td>
<td>
<img src="images\imag37.png" style="float:left;padding:3px;width:300px;height:300px">
</td>
</tr>
<table>
<br>
<ul>
<li>
<b> Name:</b> le nom de l'activité
</li>
<li>
<b>is Deffered:</b> Si on coche 'is Deffered' le lancement de l'activité sera répétée 'Retry Nbr' fois chaque 'Retry Delay Sec' secondes
</li>
<li>
<b>Email templateQN:</b> c'est le lien de Template pour l'email défini dans 'reporting'
</li>
<li>
<b>Email Container Xpath:</b> la facette d'envoi d'email
</li>
</ul>
> Les propriétés de l'activité 'Launch Process'
<table>
<tr>
<td>
<img src="images\imag38.png" style="float:right;padding:3px;width:300px;height:300px">
</td>
<td>
<img src="images\imag39.png" style="float:left;padding:3px;width:300px;height:300px">
</td>
</tr>
</table>
<br>
<ul>
<li>
<b> Name:</b> le nom de l'activité 'Launch Process'
</li>
<li>
<b>Target ProcessQN</b> le chemin de processus qu'on va lancer.
</li>
<li>
<b>Email templateQN:</b> c'est le lien de Template pour l'email défini dans 'reporting'
</li>
<li>
<b> Container Xpath:</b> c'est la facette utilisé dans shéma XSD de type 'Launch Process'
</li>
<li>
<b> Is Deffered :</b>Si On coche 'Is Deffered' le système va essayer de lancer le processus chaque 10 secondes jusqu'a la réusssite de lancement.
</li>
</ul>
### la génération des EJBs des activiés de processus
pour générer les EJBs de chaque activité on utilise 'Build Stub'.
On trouve les classes générées dans le dossier 'java'
<table>
<tr>
<td>
<img src="images\imag40.png" style="float:right;padding:6px;width:300px;height:300px">
</td>
<td>
<img src="images\imag41.png" style="float:left;padding:6px;width:300px;height:300px">
</td>
</tr>
</table>
<file_sep>/docs/zh-cn/ccs de docsify.md
<link rel="stylesheet" href="//unpkg.com/docsify/themes/vue.css">
<link rel="stylesheet" href="//unpkg.com/docsify/themes/buble.css">
<link rel="stylesheet" href="//unpkg.com/docsify/themes/dark.css">
<link rel="stylesheet" href="//unpkg.com/docsify/themes/pure.css"><file_sep>/docs/à-propos-de-karaz-studio/guide.md
<div id="a-propos-de-karaz">
<button onclick="" >
ho
</button>
A premier abord, Karaz studio peut être assimilé à un environnement de développement intégré (IDE) fournissant des outils de conception, production et déploiement de modules applicatifs métier. Il s’agit en effet d’une bonne partie de ses fonctions, mais pas uniquement…
Karaz Studio constitue un environnement intégré de coproduction de module applicatifs axés sur le management par processus, avec la particularité de réunir dans un point focal les 3 acteurs les plus importants dans tout projet de transformation digitale :
</div>
<file_sep>/docs/_sidebar.md
<!-- docs/_sidebar.md -->
* [A PROPOS DE KARAZ STUDIO](à-propos-de-karaz-studio/guide.md)
* [Installation de KARAZ Studio](/?id=installation-de-karaz-studio)
* [BPMN sous KARAZ](zh-cn/guide.md)
* [Shéma XSD](zh-cn2/guide.md)
* [La conception des vues](vues/guide.md)
|
ee2f38bb38016e65b07fe7a6a5bf7605cc1206c6
|
[
"Markdown",
"JavaScript"
] | 10
|
Markdown
|
Mustapha-lourika/karaz-documentation
|
f6c0481dce11ea0bb32aac006e93f576b49a763c
|
93a7773000f095215f8ae3c5d0dcf717d6a003bf
|
refs/heads/master
|
<file_sep>self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "6c3b0fc48257b0e11b006b3d1d904106",
"url": "/irikeish.io/index.html"
},
{
"revision": "b23cefa06e54db62aa0e",
"url": "/irikeish.io/static/css/main.3b99185b.chunk.css"
},
{
"revision": "a15d41c87a4b0850b9fd",
"url": "/irikeish.io/static/js/2.317c154a.chunk.js"
},
{
"revision": "d705cb622423d72c5defbf368ca70dcc",
"url": "/irikeish.io/static/js/2.317c154a.chunk.js.LICENSE"
},
{
"revision": "b23cefa06e54db62aa0e",
"url": "/irikeish.io/static/js/main.bd6d4ce8.chunk.js"
},
{
"revision": "4069d1af37c8af091c99",
"url": "/irikeish.io/static/js/runtime-main.81ae820c.js"
},
{
"revision": "c7978d435230536aade1113647c04e6f",
"url": "/irikeish.io/static/media/github.c7978d43.svg"
},
{
"revision": "0b000652cc1576118f8822cb19a6bafd",
"url": "/irikeish.io/static/media/linkedin.0b000652.svg"
},
{
"revision": "2d4278a43554e5757af1a037a55db08d",
"url": "/irikeish.io/static/media/resume .2d4278a4.pdf"
},
{
"revision": "d0ad346c5b287269ee72b5f90<PASSWORD>",
"url": "/irikeish.io/static/media/resume.d0ad346c.svg"
},
{
"revision": "7137286db3c9254ace982646907e65a3",
"url": "/irikeish.io/static/media/twitter.7137286d.svg"
}
]);<file_sep># irikeish.io
|
e4d149b9e6046164bf63b08a2aabf1353d2fe52e
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
irikeish/irikeish.io
|
d3106808144d4ffd4e5c64c4c16803b2a234e9d2
|
3dc85a73250af6a4b005f4f473a89b6abe6e2890
|
refs/heads/master
|
<repo_name>tjip1234/octo_py<file_sep>/python_game/game.py
import time
import random
#import simpleaudio as sa
#variables
alive = 1
playerHp = 100
enemyHp = 20
gold = 0
goldBaseDrop = 10
playerBaseDamage = 10
enemyBaseDamage = 5
enemyName = None
def main ():
direction()
print("You walked " + direction_string)
encounter()
def direction():
global direction_string
random_direction = random.randrange(1,5)
if random_direction == 1:
direction_string = "to the left"
elif random_direction == 2:
direction_string = "to the right"
elif random_direction == 3:
direction_string = "straight forward"
elif random_direction == 4:
direction_string = "backwards"
elif random_direction == 5:
direction_string = "in no general direction"
else:
direction_string = "you fucked up the code nigga"
def fight():
global enemyName
global playerHp
global enemyHp
global gold
global alive
print("You've encountered a " + enemyName + "!")
print("Do you want to fight or do you run? (-5 HP)")
forr = input("(fight/run) ")
if forr == "fight":
enemyHp = 20
while playerHp > 0 and enemyHp > 0:
playerTotalDamage = playerBaseDamage*(random.randrange(8,13)/10)
enemyHp -= playerTotalDamage
if enemyHp > 0:
print("You did " + str(playerTotalDamage) + " damage. The " + enemyName + " now has " + str(enemyHp) + " HP")
time.sleep(2)
enemyTotalDamage = enemyBaseDamage*(random.randrange(8,13)/10)
playerHp -= enemyTotalDamage
if playerHp > 0:
print("The " + enemyName + " did " + str(enemyTotalDamage) + " damage. You now have " + str(playerHp) + " HP")
time.sleep(2)
else:
print("The " + enemyName + " did " + str(enemyTotalDamage) + " damage. You now have 0 HP")
print("You've died. Game over...")
alive = 0
else:
goldTotalDrop = int(goldBaseDrop*(random.randrange(10,21)/10))
gold += goldTotalDrop
print("You did " + str(playerTotalDamage) + " damage. The " + enemyName + " died and dropped " + str(goldTotalDrop) + " gold!")
print("You've got " + str(playerHp) + " HP and " + str(gold) + " gold.")
else:
playerHp -=5
if playerHp > 0:
print("You ran away and lost 5 HP. Current HP: " + str(playerHp))
else:
print("You ran away and lost 5 HP.")
print("You've died. Game over...")
alive = 0
def town():
global playerHp
if playerHp<51:
playerHp +=50
print("You come across a town! You get healed for 50 HP. You now have " + str(playerHp) + " HP.")
else:
playerHp=100
print("You come across a town! You get fully healed.")
print("There also is a blacksmith in the town! Would you like to buy something?")
enterBlacksmith = input("(yes/no) ")
if enterBlacksmith=="yes":
print("You enter the blacksmith. You can buy:")
else:
print("You leave the town")
def trader():
global playerHp
global gold
buyAnotherPotion = "yes"
print("You've encountered a trader! They will trade a health potion (+30HP) for 50 gold. Do you want to buy it?")
buyPotion = input("(yes/no) ")
while buyAnotherPotion=="yes":
if buyPotion == "yes":
if gold >= 50:
gold -=50
playerHp += 30
if playerHp >= 70:
print("You have bought a potion. It has fully healed you.")
buyAnotherPotion = "no"
else:
print("You have bought a potion. You now have " + str(playerHp) + " HP.")
print("Do you want to buy another potion?")
buyAnotherPotion = input("(yes/no) ")
else:
print("You don't have enough money to buy the potion. You wander on.")
buyAnotherPotion = "no"
else:
print("You don't buy the potion and wander on.")
buyAnotherPotion = "no"
def encounter():
global enemyName
global playerHp
roll = random.randrange(0,10)
if roll==0:
town()
elif roll==1:
trader()
elif roll==2:
enemyName="1"
fight()
elif roll==3:
enemyName="2"
fight()
elif roll==4:
enemyName="3"
fight()
elif roll==5:
enemyName="4"
fight()
elif roll==6:
enemyName="5"
fight()
elif roll==7:
enemyName="6"
fight()
elif roll==8:
enemyName="7"
fight()
else:
enemyName="8"
fight()
while alive== 1:
main()
pass
<file_sep>/README.md
# octo_py
simple python text game
version 0.0.0.1 ALPHA
|
182485a6dece46ebec0dac254236f6225198196a
|
[
"Markdown",
"Python"
] | 2
|
Python
|
tjip1234/octo_py
|
2ba8f593d875454d37300fe1d920437ee0beec0b
|
1bcd7f53e1e984211d8cb8cb62d682b1e63ae1cc
|
refs/heads/master
|
<file_sep>package servlet;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import dataBase.DataBase;
import models.Group;
import serialization.JsonSerializator;
import serialization.Serialization;
import serialization.TxtSerializator;
import serialization.XmlSerializator;
@WebServlet("/GroupHandler")
@MultipartConfig
public class GroupHandler extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String FILE_PATH = "F://serverFiles/";
private static String MAIN_JSP = "/main.jsp";
private static String EMPTY_GROUP_LIST = "emptyGroupList.html";
private static String INDEX = "index.html";
private static String USER_NAME = "admin";
private static String PASSWORD = "<PASSWORD>";
private RequestDispatcher view = null;
private DataBase db = null;
protected String uploadFile(HttpServletRequest request) throws IOException, ServletException {
Part filePart = request.getPart("file");
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
InputStream fileContent = filePart.getInputStream();
File targetFile = new File(FILE_PATH + fileName); // add if fileName == null
java.nio.file.Files.copy(
fileContent,
targetFile.toPath(),
StandardCopyOption.REPLACE_EXISTING);
IOUtils.closeQuietly(fileContent);
fileContent.close();
return fileName;
}
protected <T> void redirectTo(String path, T parameter, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("groupList", parameter);
view = request.getRequestDispatcher(path);
view.forward(request, response);
}
protected void downloadFile(int groupNumber, HttpServletResponse response) throws IOException {
Serialization<Group> xmlSerialize = new XmlSerializator<Group>(Group.class);
PrintWriter out = response.getWriter();
int i;
try {
Group group = db.getGroup(groupNumber);
xmlSerialize.toFile(group, FILE_PATH + "Group" + groupNumber + ".xml");
}
catch (Exception e) {
e.printStackTrace();
}
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=\"" + "Group" + groupNumber + ".xml" + "\"");
java.io.FileInputStream fileInputStream = new java.io.FileInputStream(FILE_PATH + "Group" + groupNumber + ".xml");
while ((i = fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
out.close();
return;
}
@Override
public void init() throws ServletException {
super.init();
db = new DataBase("jdbc:mysql://localhost:3306/test", "root", "toor");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
List<Group> groups = new ArrayList<Group>();
String action = request.getParameter("action");
int groupNumber = 0;
if(action == null) {
response.sendRedirect(INDEX);
return;
}
if(action.equals("delete")) {
try {
groupNumber = Integer.parseInt(request.getParameter("groupNumber"));
db.deleteGroup(groupNumber);
}
catch (SQLException e) {
e.printStackTrace();
}
}
else if(action.equals("download")) {
groupNumber = Integer.parseInt(request.getParameter("groupNumber"));
downloadFile(groupNumber, response);
return;
}
try {
groups = db.getAllGroups();
if(!groups.isEmpty())
redirectTo(MAIN_JSP, groups, request, response);
else
response.sendRedirect(EMPTY_GROUP_LIST);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
boolean failLogin = false;
String action = request.getParameter("action");
String userName = request.getParameter("userName");
String password = request.getParameter("password");
PrintWriter out = response.getWriter();
List<Group> groups = new ArrayList<Group>();
if(action != null) {
Serialization<Group> serialization = null;
String fileName = uploadFile(request);
if(fileName.toLowerCase().contains(".txt"))
serialization = new TxtSerializator<Group>(Group.class);
else if(fileName.toLowerCase().contains(".xml"))
serialization = new XmlSerializator<Group>(Group.class);
else
serialization = new JsonSerializator<Group>(Group.class);
try {
db.addGroup(serialization.fromFile(FILE_PATH + fileName));
}
catch (Exception e) {
e.printStackTrace();
}
}
else if(!(USER_NAME.equals(userName) && PASSWORD.equals(password)))
failLogin = true;
if(!failLogin) {
try {
groups = db.getAllGroups();
if(!groups.isEmpty()) {
redirectTo(MAIN_JSP, groups, request, response);
return;
}
else
response.sendRedirect(EMPTY_GROUP_LIST);
}
catch (SQLException e) {
e.printStackTrace();
}
}
else {
out.println("Incorrect login or password!!!");
out.print("<a href=\"http://localhost:8080/WebApp/\"><button>Back</button></a>");
}
out.close();
}
}
|
9259a5d4f8373a6749916ca61770643ed39a71fb
|
[
"Java"
] | 1
|
Java
|
vprokh/javaServlet
|
8e47c5ccad1b733b22e049550454119195113bd9
|
3968a86609be32a43986b5149e9fb79dd15be121
|
refs/heads/main
|
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NuGet.Packaging;
using SwiftExcel;
namespace NuPkgReports
{
class Program
{
// Assume that assets in packages that are older than 3 days are harvested.
static readonly DateTimeOffset CompareOffset = DateTimeOffset.UtcNow.AddDays(-3);
static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("Missing arguments...");
Console.WriteLine("NuPkgReports <input:directory-with-nupkgs> <output:reports-output-directory>");
return;
}
string nugetPackageDirectoryPath = args[0];
string outputDirectory = args[1];
// Analyze packages
List<NuGetPackage> packages = new();
foreach (string packageFile in Directory.GetFiles(nugetPackageDirectoryPath, "*.nupkg", SearchOption.TopDirectoryOnly))
{
packages.Add(GetPackage(packageFile));
}
// Create workbook reports and write to disk
foreach (var filter in Enum.GetValues<NuGetFolderFilter>())
{
string alias = filter.ToString().ToLowerInvariant();
Sheet sheet = new()
{
Name = alias,
ColumnsWidth = new List<double> { 50, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20 }
};
WriteWorkbook(Path.Combine(outputDirectory,
$"{alias}.xlsx"),
sheet, packages, filter);
}
}
static NuGetPackage GetPackage(string packageFile)
{
PackageArchiveReader root = new(packageFile);
var x = root.GetItems("runtimes");
IEnumerable<NuGetFolder> folders = GetFolders(root.GetReferenceItems(), "ref", root)
.Concat(GetFolders(root.GetLibItems(), "lib", root))
.Concat(GetFolders(x, "runtimes", root))
.Distinct()
.OrderBy(b => b.TargetFramework);
return new NuGetPackage
{
PackageId = root.NuspecReader.GetId(),
Folders = folders
};
}
static IEnumerable<NuGetFolder> GetFolders(IEnumerable<FrameworkSpecificGroup> frameworkSpecificGroups, string packageDirectory, PackageArchiveReader packageArchiveReader)
{
foreach (var frameworkSpecificGroup in frameworkSpecificGroups)
{
if (packageDirectory == "runtimes")
{
foreach (string item in frameworkSpecificGroup.Items.Where(f => f.EndsWith(".dll")))
{
bool isHarvested = packageArchiveReader.GetEntry(item).LastWriteTime < CompareOffset;
yield return new NuGetFolder(item.Remove(item.LastIndexOf('/')), frameworkSpecificGroup.HasEmptyFolder, isHarvested);
}
}
else
{
bool isHarvested = packageArchiveReader.EnumeratePackageEntries(frameworkSpecificGroup.Items, packageDirectory)
.Where(f => f.FileFullPath.EndsWith(".dll"))
.Any(s => s.PackageEntry.LastWriteTime < CompareOffset);
yield return new NuGetFolder(frameworkSpecificGroup.TargetFramework.GetShortFolderName(), frameworkSpecificGroup.HasEmptyFolder, isHarvested);
}
}
}
static void WriteWorkbook(string outputPath, Sheet sheet, IEnumerable<NuGetPackage> packages, NuGetFolderFilter filter)
{
using ExcelWriter ew = new(outputPath, sheet);
int row = 1;
foreach (NuGetPackage package in packages)
{
IEnumerable<NuGetFolder> folders = package.Folders;
switch (filter)
{
case NuGetFolderFilter.Harvested:
folders = folders.Where(f => f.IsHarvested && !f.IsPlaceholder);
break;
case NuGetFolderFilter.NonPlaceholders:
folders = folders.Where(f => !f.IsPlaceholder);
break;
case NuGetFolderFilter.Placeholders:
folders = folders.Where(f => f.IsPlaceholder);
break;
}
// Skip empty packages
if (!folders.Any())
{
continue;
}
ew.Write(package.PackageId, 1, row);
for (int col = 0; col < folders.Count(); col++)
{
ew.Write(folders.ElementAt(col).TargetFramework, col + 2, row);
}
row++;
}
}
}
}
<file_sep># NuPkgReports
Generate xlsx spreadsheets from nuget packages.
<file_sep>using System;
using System.Collections.Generic;
namespace NuPkgReports
{
class NuGetPackage
{
public string PackageId { get; set; }
public IEnumerable<NuGetFolder> Folders { get; set; }
}
class NuGetFolder : IEquatable<NuGetFolder>
{
public string TargetFramework { get; set; }
public bool IsPlaceholder { get; set; }
public bool IsHarvested { get; set; }
public NuGetFolder(string targetFramework, bool isPlaceholder, bool isHarvested)
{
TargetFramework = targetFramework;
IsPlaceholder = isPlaceholder;
IsHarvested = isHarvested;
}
public override bool Equals(object obj) =>
Equals(obj as NuGetFolder);
public bool Equals(NuGetFolder other) =>
other != null &&
other.TargetFramework == TargetFramework &&
other.IsPlaceholder == IsPlaceholder &&
other.IsHarvested == IsHarvested;
public override int GetHashCode() =>
TargetFramework.GetHashCode();
}
enum NuGetFolderFilter
{
All,
Harvested,
Placeholders,
NonPlaceholders
}
}
|
def43b781f27a34b217c0796c40698a2a255d1c0
|
[
"Markdown",
"C#"
] | 3
|
C#
|
ViktorHofer/nupkgreports
|
00ee94e905881522bb093dce5fbd2a555fa56a8e
|
257cb8bffd306f34eea4a6d89064bb7364ae2dc6
|
refs/heads/master
|
<file_sep>package Lab3_1;
public class Client {
public static void main(String[] args) throws QueueStackException {
TargetStack adapterStack= new Adapter();
adapterStack.push("A");
adapterStack.push("B");
adapterStack.push("C");
adapterStack.push("D");
adapterStack.push("F");
adapterStack.pop();
adapterStack.pop();
adapterStack.pop();
adapterStack.pop();
adapterStack.pop();
System.out.println("Stack: "+adapterStack.toString());
System.out.println(adapterStack.pick());
TargetQueue adapterQueue = new Adapter();
adapterQueue.enqueue("AA");
adapterQueue.enqueue("BB");
adapterQueue.enqueue("CC");
adapterQueue.dequeue();
System.out.println("Queue: "+adapterQueue.toString());
}
}
<file_sep>package Lab7_1;
public class Agent {
private String id;
private Address address;
public Agent(String id, Address address) {
this.id = id;
this.address = address;
}
public String getId() {
return id;
}
public Address getAddress() {
return address;
}
}
<file_sep>package Lab10_1;
public class Mediator implements IMediator{
public Board board;
public Player currentPlayer;
public Mediator(){
board = new Board();
}
public void setCurrentMove(Player player){
currentPlayer = player;
}
@Override
public Board getBoard(){
return board;
}
@Override
public Cell move(Player player, int iRow, int jCol) {
// TODO Auto-generated method stub
if(isValidMove(player, iRow, jCol)){
board.setCell(iRow, jCol, player.getColor());
markCells(player, iRow, jCol);
currentPlayer = player;
if(isGameOver() != Cell.NONE){
return isGameOver();
}
}
return Cell.NONE;
}
@Override
public boolean isValidMove(Player player, int iRow, int jCol){
if(currentPlayer == player) return false; //If white have just move, then back move next
if(board.getCell(iRow, jCol) != Cell.NONE) return false; //move to empty cell
Cell playerColor = player.getColor();
//Neighbor Area
int iUp = iRow > 0 ? iRow - 1 : 0;
int iDown = iRow < Board.row - 1 ? iRow + 1 : iRow;
int jLeft = jCol > 0 ? jCol - 1 : 0;
int jRight = jCol < Board.column - 1 ? jCol + 1 : jCol;
for(int i = iUp; i<=iDown; i++){
for(int j = jLeft; j<=jRight; j++){
if(board.getCell(i, j) != playerColor && board.getCell(i, j) != Cell.NONE){ //Neighbor cell has different color
if(j == jCol){
if(i == iDown){
for(int k = i + 1; k < board.row; k++){
if(board.getCell(k, jCol) == playerColor) //Same color
{
return true;
}
}
} else if(i == iUp){
for(int k = i - 1; k>= 0; k--){
if(board.getCell(k, jCol) == playerColor) //Same color
{
return true;
}
}
}
}else if (i == iRow){
if(j == jRight){
for(int k = j + 1; k < board.column; k++){
if(board.getCell(iRow, k) == playerColor) //Same color
{
return true;
}
}
} else if(j == jLeft){
for(int k = j - 1; k>= 0; k--){
if(board.getCell(iRow, k) == playerColor) //Same color
{
return true;
}
}
}
} else { // i != iRow && j != jColumn
if(i == iDown && j == jRight){
for(int k = 1; k+i<board.row && k+j<board.row ; k ++){
if(board.getCell(i+k, j+k) == playerColor) {
return true;
}
}
}
if(i == iUp && j == jLeft){
for(int k = 1; i-k > 0 && j-k>0 ; k ++){
if(board.getCell(i-k, j-k) == playerColor) {
return true;
}
}
} else if(i == iUp && j == jRight){
for(int k = 1; i-k > 0 && j+k<board.row ; k ++){
if(board.getCell(i-k, j+k) == playerColor) {
return true;
}
}
} else if(i == iDown && j == jLeft){
for(int k = 1; i+k <board.row && j-k>0 ; k ++){
if(board.getCell(i+k, j-k) == playerColor) {
return true;
}
}
}
}
}
}
}
return false;
}
@Override
public void markCells(Player player, int iRow, int jCol) {
// TODO Auto-generated method stub
Cell playerColor = player.getColor();
int iUp = iRow > 0 ? iRow - 1 : 0;
int iDown = iRow < Board.row - 1 ? iRow + 1 : iRow;
int jLeft = jCol > 0 ? jCol - 1 : 0;
int jRight = jCol < Board.column - 1 ? jCol + 1 : jCol;
for(int i = iUp; i<=iDown; i++){
for(int j = jLeft; j<=jRight; j++){
if(board.getCell(i, j) != playerColor && board.getCell(i, j) != Cell.NONE){ //Neighbor cell has different color
System.out.println("i, j: " + i + ", " + j);
if(j == jCol){
if(i == iDown){
int k;
for(k = i + 1; k < board.row; k++){
if(board.getCell(k, jCol) == playerColor){ //Same color
k++;
break;
}
}
if( k > i+1 && k < board.row){
for(int m = i; m<=k-1; m++){
board.setCell(m, jCol, playerColor);
}
}
} else if(i == iUp){
int k;
for(k = i - 1; k>= 0; k--){
if(board.getCell(k, jCol) == playerColor) //Same color
{
k--;
break;
}
}
if( k < i-1 && k >= 0){
for(int m = i; m>=k+1 ; m--){
board.setCell(m, jCol, playerColor);
}
}
}
}else if (i == iRow){
if(j == jRight){
int k;
for(k = j + 1; k < board.column; k++){
if(board.getCell(iRow, k) == playerColor) //Same color
{
k++;
break;
}
}
if( k > j + 1 && k < board.column){
for(int m = j; m <= k-1 ; m++){
board.setCell(iRow, m, playerColor);
}
}
} else if(j == jLeft){
int k;
for(k = j - 1; k>= 0; k--){
if(board.getCell(iRow, k) == playerColor){ //Same color
k--;
break;
}
}
if( k < j - 1 && k >= 0){
for(int m = j; m >= k+1 ; m--){
board.setCell(iRow, m, playerColor);
}
}
}
} else { // i != iRow && j != jColumn
if(i == iDown && j == jRight){
int k;
for(k = 1; k+i<board.row && k+j<board.row ; k ++){
if(board.getCell(i+k, j+k) == playerColor){
k++;
break;
}
}
if( k > 1 && k+i<board.row && k+j<board.row){
for(int m = 0; m <= k-1 ; m++){
board.setCell(i+m, j+m, playerColor);
}
}
}
if(i == iUp && j == jLeft){
int k;
for(k = 1; i-k > 0 && j-k>0 ; k ++){
if(board.getCell(i-k, j-k) == playerColor){
k++;
break;
}
}
if( k > 1 && i-k > 0 && j-k>0){
for(int m = 0; m <= k-1 ; m++){
board.setCell(i-m, j-m, playerColor);
}
}
} else if(i == iUp && j == jRight){
int k;
for(k = 1; i-k > 0 && j+k<board.row ; k ++){
if(board.getCell(i-k, j+k) == playerColor){
k++;
break;
}
}
if( k > 1 && i-k > 0 && j+k<board.row ){
for(int m = 0; m <= k-1 ; m++){
board.setCell(i-m, j+m, playerColor);
}
}
} else if(i == iDown && j == jLeft){
int k;
for(k = 1; i+k<board.row && j-k>0 ; k ++){
if(board.getCell(i+k, j-k) == playerColor){
k++;
break;
}
}
if( k > 1 && i+k <board.row && j-k>0){
for(int m = 0; m <= k-1 ; m++){
board.setCell(i+m, j-m, playerColor);
}
}
}
}
}
}
}
}
@Override
public Cell isGameOver() {
// TODO Auto-generated method stub
//Player winer = new WhitePlayer(this);
int whiteCount = 0;
int blackCount = 0;
for(int i = 0; i<board.row; i++){
for(int j = 0; j<board.column; j++){
if(board.getCell(i, j) == Cell.BLACK) blackCount++;
else if (board.getCell(i, j) == Cell.WHITE) whiteCount++;
else if(board.getCell(i, j) == Cell.NONE){
return Cell.NONE;
}
}
}
return whiteCount > blackCount ? Cell.WHITE : Cell.BLACK;
}
}
<file_sep>package Lab6_1;
public class Validator extends AbstractAgent {
@Override
public void handleRequest(CallRecord callRecord) {
// Check if the the record is valid
if (checkIfValid(callRecord)) {
callRecord.setValid(true);
this.nextAgent.handleRequest(callRecord);
}
}
private boolean checkIfValid(CallRecord callRecord) {
return (callRecord.getCustomer().getAddress() != null && callRecord.getCustomer().getEmail() != null);
}
}<file_sep>package Lab8_1;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.input.KeyEvent;
public class MainController implements Initializable {
private CarController carController;
private RoadCondition currentCondition;
@FXML
private ComboBox<RoadCondition> cmbCondition;
@FXML
private Button btnLeft;
@FXML
private Button btnAccel;
@FXML
private Button btnRight;
@FXML
private Button btnBrake;
@FXML
private TextField txtFeedback;
@Override
public void initialize(URL location, ResourceBundle resources) {
// Init ComboBox
ArrayList<RoadCondition> items = new ArrayList<>();
RoadCondition regular = new RegularCondition();
RoadCondition gravel = new GravelCondition();
RoadCondition wet = new WetCondition();
RoadCondition ice = new IceCondition();
items.add(regular);
items.add(gravel);
items.add(wet);
items.add(ice);
cmbCondition.setItems(FXCollections.observableArrayList(items));
cmbCondition.setValue(regular);
currentCondition = regular;
carController = new CarController(currentCondition);
cmbCondition.valueProperty().addListener(new ChangeListener<RoadCondition>() {
@Override
public void changed(ObservableValue<? extends RoadCondition> observable, RoadCondition oldValue,
RoadCondition newValue) {
currentCondition = newValue;
carController.setCurrentCondition(currentCondition);
;
}
});
}
@FXML
void onLeftClick(ActionEvent event) throws Exception {
int level = carController.getLeftLevel();
txtFeedback.setText("Level: " + level);
}
@FXML
void onAccelClick(ActionEvent event) throws Exception {
int level = carController.getAccelLevel();
txtFeedback.setText("Level: " + level);
}
@FXML
void onRightClick(ActionEvent event) throws Exception {
int level = carController.getRightLevel();
txtFeedback.setText("Level: " + level);
}
@FXML
void onBrakeClick(ActionEvent event) throws Exception {
int level = carController.getBrakeLevel();
txtFeedback.setText("Level: " + level);
}
}
<file_sep>package Lab3_1;
public interface TargetQueue {
void enqueue(String str);
String pick();
boolean isEmpty();
String dequeue() throws QueueStackException;
}
<file_sep>package Lab10_1;
public class BlackPlayer extends Player {
public BlackPlayer(IMediator mediator) {
super(mediator);
color = Cell.BLACK;
// TODO Auto-generated constructor stub
}
@Override
public Cell move(int iRow, int jColumn) {
// TODO Auto-generated method stub
return mediator.move(this, iRow, jColumn);
}
}
<file_sep>package Lab11_1;
public class Root extends Composite {
private String name;
public Root(String name) {
super();
this.name = name;
side = Side.NONE;
}
@Override
public void accept(NodeVisitor visitor) {
visitor.visit(this);
}
@Override
public Side getSide() {
return side;
}
@Override
public String getName() {
return name;
}
}
<file_sep>package Lab7_3;
public class JDBCdemo {
public static void main(String[] args) {
IcommandExecutorFacade executor = new commandExecutorFacade();
executor.process();
}
}
<file_sep>package Lab11_1;
import java.util.HashMap;
public class DisplayNodeVisitor implements NodeVisitor {
private HashMap<String, Integer> rightHashMap;
private HashMap<String, Integer> leftHashMap;
private Composite currentNode;
public DisplayNodeVisitor() {
rightHashMap = new HashMap<>();
leftHashMap = new HashMap<>();
}
public HashMap<String, Integer> getRightHashMap() {
return rightHashMap;
}
public HashMap<String, Integer> getLeftHashMap() {
return leftHashMap;
}
// Visiting a Node
@Override
public void visit(Node node) {
if (node.getSide() == Side.RIGHT) {
rightHashMap.put(currentNode.getName(), rightHashMap.get(currentNode.getName()) + 1);
}
if (node.getSide() == Side.LEFT) {
leftHashMap.put(currentNode.getName(), leftHashMap.get(currentNode.getName()) + 1);
}
for (Composite childNode : node.getChilds()) {
childNode.accept(this);
}
}
// For visiting a Root
@Override
public void visit(Root root) {
for (Composite node : root.getChilds()) {
currentNode = node;
if (node.getSide() == Side.RIGHT) {
rightHashMap.put(node.getName(), 1);
for (Composite childNode : node.getChilds()) {
childNode.accept(this);
}
} else if (node.getSide() == Side.LEFT) {
leftHashMap.put(node.getName(), 1);
for (Composite childNode : node.getChilds()) {
childNode.accept(this);
}
}
}
}
}
<file_sep>package Lab5_1;
public class Main {
public static void main(String[] args) {
TraceFactory factory = SimpleTraceFactory.getFactory();
System.out.println("Tracer: (trace.console)");
Trace consoleTrace = factory.createTracer("trace.console");
consoleTrace.setDebug(true);
consoleTrace.debug("debug my code");
consoleTrace.error("check for errors");
System.out.println(consoleTrace);
System.out.println("\nAnother tracer: (trace.file)");
Trace fileTrace = factory.createTracer("trace.file");
fileTrace.setDebug(false);
fileTrace.debug("debug my code");
fileTrace.error("check for errors");
System.out.println(fileTrace);
}
}
<file_sep>package Lab6_2;
public class Square {
int side;
int origin;
public Square(int side) {
this.side = side;
}
public int getSide() {
return side;
}
public void setSide(int side) {
this.side = side;
}
public int getOrigin() {
return origin;
}
public void setOrigin(int origin) {
this.origin = origin;
}
}
<file_sep>package Lab4_2;
import java.io.Serializable;
import java.util.Arrays;
public class Employee implements Cloneable, Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String lastName;
private String firstName;
private String streetAddress;
private String city;
private String state;
private String zipcode;
private Employee supervisor;
private Employee staff[];
public Employee(int id, String lastName, String firstName, String streetAddress, String city, String state,
String zipcode) {
this.id = id;
this.lastName = lastName;
this.firstName = firstName;
this.streetAddress = streetAddress;
this.city = city;
this.state = state;
this.zipcode = zipcode;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public Employee getSupervisor() {
return supervisor;
}
public void setSupervisor(Employee supervisor) {
this.supervisor = supervisor;
}
public Employee[] getStaff() {
return staff;
}
public void setStaff(Employee[] staff) {
this.staff = staff;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return "Employee [id=" + id + ", lastName=" + lastName + ", firstName=" + firstName + ", streetAddress="
+ streetAddress + ", city=" + city + ", state=" + state + ", zipcode=" + zipcode + ", supervisor="
+ supervisor + ", staff=" + Arrays.toString(staff) + "]";
}
}
<file_sep>package Lab5_1;
public class SimpleTraceFactory implements TraceFactory {
// Create a singleton SimpleTraceFactory (static and constructor is private)
private static TraceFactory factory = new SimpleTraceFactory();
// private constructor to be only accessed from within
private SimpleTraceFactory() {
}
public static TraceFactory getFactory() {
return factory;
}
@Override
public Trace createTracer(String traceType) {
Trace trace = null;
if (traceType.equals("trace.console")) {
trace = new ConsoleTrace();
} else if (traceType.equals("trace.file")) {
trace = new FileTrace();
}
return trace;
}
}
<file_sep>package Lab8_1;
public class RegularCondition implements RoadCondition {
@Override
public String toString() {
return "Regular";
}
@Override
public int getLeftLevel() {
return 5;
}
@Override
public int getAccelLevel() {
return 9;
}
@Override
public int getRightLevel() {
return 5;
}
@Override
public int getBrakeLevel() {
return 8;
}
}
<file_sep>package lab2_1;
public class Singleton {
Runnable runnable = MySingletonLazy::getInstance;
public static void main(String[] args) {
Singleton singleton = new Singleton();
for (int i = 0; i < 5; ++i) {
singleton.start();
}
SingletonEnum.INSTANCE.print();
System.out.println(MySingletonLazy.count);
}
public void start() {
for (int i = 0; i < 10; ++i) {
new Thread(runnable).start();
}
}
}
<file_sep>package Lab8_2;
import java.util.ArrayList;
import java.util.List;
public class StrategyClient {
public static void main(String[] args) {
Flight flight1 = new Flight(175, "United333", "San Francisco", "Fairfield");
Flight flight2 = new Flight(200, "Delta777", "Verginia", "Cedar Rapids");
Flight flight3 = new Flight(235, "American555", "Boston", "Des Moines");
Flight flight4 = new Flight(180, "Sprit888", "Charlot", "Otumwa");
Flight flight5 = new Flight(320, "United999", "Texas", "Des Moines");
List<Flight> flights = new ArrayList<Flight>();
flights.add(flight1);
flights.add(flight2);
flights.add(flight3);
flights.add(flight4);
flights.add(flight5);
// Instance of the Context
FlightContext flightContext = new FlightContext();
// Printing information of the flights
for (Flight flight : flights) {
System.out.println(flight);
}
System.out.println();
// Get revenue using SinglePrice Strategy
Model singlePrice = new SinglePrice();
flightContext.setModel(singlePrice);
System.out.println("Generating revenue using SinglePrice strategy");
System.out.println("Total revenue: " + flightContext.generateRevenue(flights));
// Get revenue using Two classes Strategy
Model twoClasses = new TwoClasses();
flightContext.setModel(twoClasses);
System.out.println("\nGenerating revenue using TwoClasses strategy");
System.out.println("Total revenue: " + flightContext.generateRevenue(flights));
// Get revenue using Multi classes Strategy
Model multiClass = new MultiClass();
flightContext.setModel(multiClass);
System.out.println("\nGenerating revenue using MultiClasses strategy");
System.out.println("Total revenue: " + flightContext.generateRevenue(flights));
}
}
<file_sep>package Lab11_1;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
DisplayNodeVisitor visitor = new DisplayNodeVisitor();
Composite tree = buildTree();
tree.accept(visitor);
// Right Nodes
System.out.println("Right Nodes:");
HashMap<String, Integer> rightHashMap = visitor.getRightHashMap();
for (Map.Entry<String, Integer> map : rightHashMap.entrySet()) {
System.out.println(map.getValue() + " " + map.getKey() + " nodes");
}
// Left Nodes
System.out.println("Left Nodes:");
HashMap<String, Integer> leftHashMap = visitor.getLeftHashMap();
for (Map.Entry<String, Integer> map : leftHashMap.entrySet()) {
System.out.println(map.getValue() + " " + map.getKey() + " nodes");
}
}
public static Composite buildTree() {
Composite topic = new Root("Topic");
Composite A = new Node("A", Side.RIGHT);
Composite A1 = new Node("A1");
Composite AA1 = new Node("AA1");
Composite AA2 = new Node("AA2");
Composite AA3 = new Node("AA3");
Composite A2 = new Node("A2");
Composite B = new Node("B", Side.RIGHT);
Composite B1 = new Node("B1");
Composite B2 = new Node("B2");
Composite C = new Node("C", Side.RIGHT);
Composite C1 = new Node("C1");
Composite C2 = new Node("C2");
Composite D = new Node("D", Side.LEFT);
Composite D1 = new Node("D1");
Composite D2 = new Node("D2");
Composite E = new Node("E", Side.LEFT);
Composite E1 = new Node("E1");
Composite E2 = new Node("E2");
Composite E3 = new Node("E3");
Composite F = new Node("F", Side.LEFT);
Composite F1 = new Node("F1");
Composite F2 = new Node("F2");
topic.addChild(A);
topic.addChild(B);
topic.addChild(C);
topic.addChild(D);
topic.addChild(E);
topic.addChild(F);
A1.addChild(AA1);
A1.addChild(AA2);
A1.addChild(AA3);
A.addChild(A1);
A.addChild(A2);
B.addChild(B1);
B.addChild(B2);
C.addChild(C1);
C.addChild(C2);
D.addChild(D1);
D.addChild(D2);
E.addChild(E1);
E.addChild(E2);
E.addChild(E3);
F.addChild(F1);
F.addChild(F2);
return topic;
}
}
<file_sep>
package Lab5_2.abstractFactory;
public class Address {
private String street1;
private String street2;
private String city;
private String state;
private String zipcode;
}
<file_sep>package Lab4_1;
public class Client {
public static void main (String[] args){
A a=new A();
a.processTemplate(Resource.A);
System.out.println("");
B b=new B();
b.processTemplate(Resource.B);
System.out.println("");
C c=new C();
c.processTemplate(Resource.C);
}
}
<file_sep>package Lab5_1;
public class FileTrace implements Trace {
boolean debug;
String debugMessage;
String errorMessage;
@Override
public void setDebug(boolean debug) {
this.debug = debug;
System.out.println("Inside FileTrace setDebug() method");
}
@Override
public void debug(String debugMessage) {
this.debugMessage = debugMessage;
System.out.println("Inside FileTrace debug() method");
}
@Override
public void error(String errorMessage) {
this.errorMessage = errorMessage;
System.out.println("Inside FileTrace error() method");
}
@Override
public String toString() {
return "FileTrace [debug=" + debug + ", debugMessage=" + debugMessage + ", errorMessage=" + errorMessage + "]";
}
}
<file_sep>package Lab10_1;
public class WhitePlayer extends Player {
public WhitePlayer(IMediator mediator) {
super(mediator);
color = Cell.WHITE;
// TODO Auto-generated constructor stub
}
@Override
public Cell move(int iRow, int jColumn) {
// TODO Auto-generated method stub
return mediator.move(this, iRow, jColumn);
}
}
<file_sep>package Lab6_1;
public class Client {
static ChainBuilder chain = new ChainBuilder();
public Client(ChainBuilder chain) {
Client.chain = chain;
}
public void sendRequest(CallRecord callRecord) {
chain.getHandler().handleRequest(callRecord);
}
public static void main(String[] args) {
chain.buildChain();
Client client = new Client(chain);
// Data for Agent (For now only one Agent)
Address agentsAddress = new Address("777 N court", "Fairfield", "IO", "77777");
Agent agent1 = new Agent("1", agentsAddress);
// Info for one call record
Address address1 = new Address("555 west", "San Francisco", "CA", "55555");
Customer customer1 = new Customer("Mike", "K", address1, "7777777777", "<EMAIL>");
CallRecord callRecord1 = new CallRecord(customer1, agent1, "About sales", false, false);
// Info for one call record
Address address2 = new Address("1000 maharishi", "Fairfield", "IO", "55555");
Customer customer2 = new Customer("Thieory", "Henry", address2, "1414141414", null);
CallRecord callRecord2 = new CallRecord(customer2, agent1, "info needed about sales", false, false);
// Info for one call record
Address address3 = new Address("1010 verill", "Fairfield", "IO", "33333");
Customer customer3 = new Customer("Patrick", "Viera", address3, "4444444444", "<EMAIL>");
CallRecord callRecord3 = new CallRecord(customer3, agent1, "info needed about sales", false, false);
System.out.println("Report of customer records");
System.out.println();
client.sendRequest(callRecord1);
client.sendRequest(callRecord2); // Will not be printed because 'email'
// is null
client.sendRequest(callRecord3);
}
}
<file_sep>package Lab5_1;
public interface TraceFactory {
public Trace createTracer(String traceType);
}
<file_sep>
package Lab5_2.abstractFactory.giftPack;
import Lab5_2.abstractFactory.packaging.EveryDayValueWrap;
import Lab5_2.abstractFactory.packaging.PlainPaperBox;
import Lab5_2.abstractFactory.packaging.ReusableShopperBag;
public class AdultGiftPack extends GiftPack {
@Override
public Packaging packageGift(PackagingType packagingType) {
switch (packagingType) {
case BOX:
return new PlainPaperBox(0.25);
case BAG:
return new ReusableShopperBag(0.00);
case WRAP:
return new EveryDayValueWrap(0.00);
default:
throw new IllegalArgumentException("Unexpected value: " + packagingType);
}
}
}
<file_sep>package Lab3_2;
public interface Iterator {
boolean hasNext();
Object next();
String remove(int indX, int indY);
String add (String str);
}
<file_sep>package Lab11_1;
public class Node extends Composite {
private String name;
public Node(String name) {
super();
this.name = name;
}
public Node(String name, Side side) {
super();
this.name = name;
this.side = side;
}
@Override
public String getName() {
return name;
}
@Override
public Side getSide() {
return side;
}
@Override
public void accept(NodeVisitor visitor) {
visitor.visit(this);
}
}
<file_sep>package Lab5_2.abstractFactory.giftPack;
public enum PackType {
BUSINESS, ADULTS, KIDS;
}
<file_sep>package Lab3_3;
import java.util.ArrayList;
public class Row implements IRow {
ArrayList<String> rows = new ArrayList<>();
@Override
public void addRow(String str) {
rows.add(str);
}
@Override
public String toString() {
return rows.toString();
}
}
<file_sep>package Lab3_1;
import java.util.Arrays;
public class Adaptee {
private String[] data= new String[2];
private int start;
private int end;
public String startString(){
return data[start];
}
public String endString(){
return data[end];
}
public void add(String str) {
if(end==data.length){
resize();
}
data[end]=str;
end++;
}
public int getEnd() {
return end =end-1;
}
public String get(int pos) {
return data[pos];
}
public void remove(int pos) {
boolean stack=false;
//In case of Queue
if (pos==0){
System.arraycopy(data, 1, data, 0, end );
end--;
}
//In case of Stack
if (end - pos >= 0 && pos!=0) System.arraycopy(data, pos+1, data, pos, end-1);
if(pos==1||end==-1)
data[pos]=null;
}
public boolean empty() {
return (end ==-1);
}
private void resize() {
System.out.println("resizing");
int len = data.length;
int newlen = 2 * len;
String[] temp = new String[newlen];
System.arraycopy(data, 0, temp, 0, len);
data = temp;
}
@Override
public String toString() {
return "data=" + Arrays.toString(data);
}
}
<file_sep>package Lab11_2;
public class AddExpression extends Expression {
private Expression leftExpression;
private Expression rightExpression;
public AddExpression(Expression left, Expression right) {
leftExpression = left;
rightExpression = right;
}
@Override
public int interpret() {
return leftExpression.interpret() + rightExpression.interpret();
}
public Expression getLeftExpression() {
return leftExpression;
}
public void setLeftExpression(Expression leftExpression) {
this.leftExpression = leftExpression;
}
public Expression getRightExpression() {
return rightExpression;
}
public void setRightExpression(Expression rightExpression) {
this.rightExpression = rightExpression;
}
}
<file_sep>package Lab11_2;
import java.util.List;
public class Parser {
public Expression parse(List<String> tokenList) {
return next(tokenList);
}
private Expression next(List<String> tokenList) {
int number;
if (isInteger(tokenList.get(0))) {
number = Integer.parseInt(tokenList.get(0));
tokenList.remove(0);
return new NumberExpression(number);
} else {
return parseNonTerminal(tokenList);
}
}
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
private Expression parseNonTerminal(List<String> tokenList) {
String token = tokenList.get(0);
tokenList.remove(0);
Expression left = next(tokenList);
Expression right = next(tokenList);
if (token.equals("+")) {
return new AddExpression(left, right);
} else if (token.equals("-")) {
return new SubtractExpression(left, right);
}
return null;
}
}
<file_sep>
package Lab5_2.abstractFactory.giftPack;
public interface Packaging {
public double getCost();
}
<file_sep>package Lab8_3;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Scanner;
public class Originator {
private StringBuilder content;
public Originator() {
content = new StringBuilder();
}
public void write(String str) {
content = new StringBuilder();
content.append(str);
}
public StringBuilder getString() {
return content;
}
public Memento createMemento() {
return new Memento(this.content);
}
public void setMemento(Memento memento) {
this.content = memento.getContentInMemento();
}
// This is for saving to a file named 'SavedFile.txt'
public void saveToFile() {
try {
PrintStream output = new PrintStream(new File("SavedFile.txt")); // Check Time of creation of the file
output.println(content);
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
}
public String loadFromAFile() {
StringBuilder str = new StringBuilder();
try(BufferedReader file = new BufferedReader(
new FileReader("SavedFile.txt"))) {
System.out.println("Trying to Load what is saved in a file 'SavedFile.txt'");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
str.append(scanner.nextLine());
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
@Override
public String toString() {
return content.toString();
}
public void getStateFromMomento(Memento m) {
content = m.getContentInMemento();
}
}
<file_sep>package Lab4_1;
public class B extends TemplateBuilder {
@Override
public String getSymmetry() {
return "None";
}
@Override
public Integer getColumn() {
return 9;
}
@Override
public Integer getRow() {
return 14;
}
}
<file_sep>package Lab5_2.abstractFactory;
import java.util.ArrayList;
import java.util.List;
import Lab5_2.abstractFactory.giftPack.AdultGiftPack;
import Lab5_2.abstractFactory.giftPack.GiftPack;
import Lab5_2.abstractFactory.giftPack.KidGiftPack;
import Lab5_2.abstractFactory.giftPack.PackType;
import Lab5_2.abstractFactory.giftPack.PackagingType;
public class Client {
public static void main(String[] args) {
GiftPack giftPackKid = new KidGiftPack();
List<GiftItem> kidGiftItemList = new ArrayList<GiftItem>();
GiftItem giftItem1 = new GiftItem("1", "Watch", "Luxery", PackType.KIDS, PackagingType.BOX);
GiftItem giftItem2 = new GiftItem("2", "Shoe", "Running Shoe", PackType.KIDS, PackagingType.BOX);
GiftItem giftItem3 = new GiftItem("3", "T-Shirt", "Running T-Shirt", PackType.KIDS, PackagingType.WRAP);
GiftPack adultGiftPack = new AdultGiftPack();
List<GiftItem> adultGiftItemList = new ArrayList<GiftItem>();
GiftItem giftItem11 = new GiftItem("11", "Watch", "Luxery", PackType.ADULTS, PackagingType.BOX);
GiftItem giftItem22 = new GiftItem("22", "Shoe", "Running Shoe", PackType.ADULTS, PackagingType.BAG);
GiftItem giftItem33 = new GiftItem("33", "T-Shirt", "Running T-Shirt", PackType.ADULTS, PackagingType.WRAP);
kidGiftItemList.add(giftItem1);
kidGiftItemList.add(giftItem2);
kidGiftItemList.add(giftItem3);
adultGiftItemList.add(giftItem11);
adultGiftItemList.add(giftItem22);
adultGiftItemList.add(giftItem33);
giftPackKid.setGiftItems(kidGiftItemList);
adultGiftPack.setGiftItems(adultGiftItemList);
List<GiftPack> kidGiftPacks = new ArrayList<>();
kidGiftPacks.add(giftPackKid);
List<GiftPack> adultGiftPacks = new ArrayList<>();
adultGiftPacks.add(adultGiftPack);
double sumBox = 0D;
double sumBag = 0D;
double sumWrapper = 0D;
for (GiftPack giftPack : kidGiftPacks) {
for (GiftItem giftItem : kidGiftItemList) {
System.out.println("Kid gift Description: " + giftItem.getDescription());
switch (giftItem.getPackagingType()) {
case BOX: {
sumBox += giftPack.packageGift(PackagingType.BOX).getCost();
break;
}
case BAG: {
sumBag += giftPack.packageGift(PackagingType.BAG).getCost();
break;
}
case WRAP: {
sumWrapper += giftPack.packageGift(PackagingType.WRAP).getCost();
break;
}
default:
throw new IllegalArgumentException("Unexpected value: " + giftItem.getPackagingType());
}
}
System.out.println("Sum of Box packaging equals:" + sumBox);
System.out.println("Sum of Bag packaging equals:" + sumBag);
System.out.println("Sum of Wrapper packaging equals:" + sumWrapper);
}
sumBox = 0D;
sumBag = 0D;
sumWrapper = 0D;
for (GiftPack giftPack : adultGiftPacks) {
for (GiftItem giftItem : adultGiftItemList) {
System.out.println("Adult gift Description: " + giftItem.getDescription());
switch (giftItem.getPackagingType()) {
case BOX: {
sumBox += giftPack.packageGift(PackagingType.BOX).getCost();
break;
}
case BAG: {
sumBag += giftPack.packageGift(PackagingType.BAG).getCost();
break;
}
case WRAP: {
sumWrapper += giftPack.packageGift(PackagingType.WRAP).getCost();
break;
}
default:
throw new IllegalArgumentException("Unexpected value: " + giftItem.getPackagingType());
}
}
System.out.println("Sum of Box packaging equals:" + sumBox);
System.out.println("Sum of Bag packaging equals:" + sumBag);
System.out.println("Sum of Wrapper packaging equals:" + sumWrapper);
}
}
}
<file_sep>
package Lab5_2.abstractFactory;
import Lab5_2.abstractFactory.giftPack.PackType;
import Lab5_2.abstractFactory.giftPack.PackagingType;
public class GiftItem {
private String giftId;
private String giftName;
private String description;
private PackType packType;
private PackagingType packagingType;
public GiftItem(String giftId, String giftName, String description, PackType packagingType, PackagingType packaging) {
super();
this.giftId = giftId;
this.giftName = giftName;
this.description = description;
this.packType = packagingType;
this.packagingType = packaging;
}
public String getGiftId() {
return giftId;
}
public String getGiftName() {
return giftName;
}
public String getDescription() {
return description;
}
public PackType getPackType() {
return packType;
}
public PackagingType getPackagingType() {
return packagingType;
}
@Override
public String toString() {
return "GiftItem [giftId=" + giftId + ", giftName=" + giftName + ", description=" + description
+ ", packagingType=" + packType + ", packaging=" + packagingType + "]";
}
}
|
d063fe4e43c86f3f1334f2ee970be60b098aa648
|
[
"Java"
] | 37
|
Java
|
mamekelle/ASD
|
1ac7c5f0b9bb6ed6bd4639f61da0ee14b36b883f
|
fae9fcf9748ff00da1b380105ab9b34d8aa476c5
|
refs/heads/main
|
<file_sep>package com.maximumproblem;
import java.util.*;
/**
* @author saneeths
*this is the class where the maximum values are found out the generic function is formed
*and the comparable class is extended
* @param <T>
*/
public class Maximum<T extends Comparable<T>> {
List<T> list = new ArrayList<T>();//List used to store the parameters
/**
* @param t this method is created to add the parameters to the list and to call
* the max value function here the option method is used for parameters
*
*/
public T maximum(T...t) {
for(T i: t) {
list.add(i);
}
return Maximum.maximumValue(list);
}
/**
* This is the method where the maximum value is found out among the list of parameters
* Here the sorting mathod is used to find the maximum value
*
*/
private static <T extends Comparable<T>> T maximumValue(List<T> parameters) {
int n = parameters.size();
for(int i=0 ; i<n ; i++) {
for(int j=0 ; j<n-i-1 ; j++) {
if(parameters.get(j).compareTo(parameters.get(j+1))>0) {
T temp = parameters.get(j);
parameters.set(j, parameters.get(j+1));
parameters.set(j+1, temp);
}
}
}
T max = parameters.get(n-1);
printMax(parameters,max);
return max;
}
/**
* This method is created to display the maximum value which is internally called
* by maximum method
*/
private static<T> void printMax(List<T> parameters, T max) {
StringBuilder builder = new StringBuilder();
builder.append("Max Value among ");
for(T i: parameters) {
builder.append(i+",");
}
builder.append(" : "+max);
System.out.println(builder);
}
}
|
de3603c5912bdace141b5a893856e4817a42b815
|
[
"Java"
] | 1
|
Java
|
SaneethS/Java_Generics
|
cbb63124335e6c73de6f5098fd4fb52f8506fd52
|
e994378a1dd59df1ea17689cfe6c6327d278f013
|
refs/heads/master
|
<file_sep>(function (window,$) {
window.zUtil={
getDistance:getDistance
};
$.fn.distance=distance;
function getDistance(obj) {
if (!obj instanceof $) {
obj = $(obj);
}
var distance = {};
distance.top = (obj.offset().top - $(document).scrollTop());
distance.bottom = ($(window).height() - distance.top - obj.outerHeight());
distance.left = (obj.offset().left - $(document).scrollLeft());
distance.right = ($(window).width() - distance.left - obj.outerWidth());
return distance;
}
function distance(ele) {
var distance = {};
distance.top = (this.offset().top - $(document).scrollTop());
distance.bottom = ($(window).height() - distance.top - this.outerHeight());
distance.left = (this.offset().left - $(document).scrollLeft());
distance.right = ($(window).width() - distance.left - this.outerWidth());
//$('<div>'+distance.bottom+'</div>').prepend('body').css({position:'fixed',top:0});
//console.log(distance.bottom);
if (ele){
if (!ele instanceof jQuery) {
ele = $(ele);
}
ele.html('<div>距离浏览器左边框:'+parseInt(distance.left)+'</div>' +
'<div>距离浏览器右边框:'+parseInt(distance.right)+'</div>' +
'<div>距离浏览器上边框:'+parseInt(distance.top)+'</div>' +
'<div>距离浏览器下边框:'+parseInt(distance.bottom)+'</div>');
}
return distance;
}
})(window,jQuery);
|
3d3dc48af7cc130311990b6afe3b870c3572fd75
|
[
"JavaScript"
] | 1
|
JavaScript
|
undefined-z/myWorld
|
7b7a19da8cf3bff7a4a2a1e1d8a1c6c0b32724c4
|
f466106f5601aa42d1ea42178426b3a1b0544a22
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace CoffeeBranch.Models
{
public enum FlavourType
{
HotChoclate, FrenchVanilla, CaramelMacchiato, PumpkinSpice, Hazelnut, Mocha
}
public class Menu
{
[Key]
public int Id { get; set; }
//Price of the coffee
public int Price { get; set; }
public FlavourType? FlavourType { get; set; }//FlavourType
public int BranchId { get; set; }//BranchID
public Branch Branch { get; set; } //Linking
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace CoffeeBranch.Models
{
public class Branch
{
[Key]
public int Id { get; set; }
//Name of the Branch
public string Branch_Name { get; set; }
//Address of the Branch
public string Branch_Address { get; set; }
public ICollection<Menu> Menus { get; set; } // 1 to many relation
public ICollection<Order> Orders { get; set; } // 1 person have many orders
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace CoffeeBranch.Models
{
public class Order
{
[Key]//Add primary key
public int ID { get; set; }// ID is primary key
public int BranchId { get; set; } // Branch ID
public int MenuId { get; set; }// Add Menu ID
public string CustomerName { get; set; }//Add Customer name
public Branch Branch { get; set; } //Linking to branch class
public Menu Menu { get; set; }
}
}
<file_sep>using CoffeeBranch.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
namespace CoffeeBranch.Data
{
public class CoffeeDbContext : DbContext
{
// Here we add in all the tables we are using.
public DbSet<Branch> Branch { get; set; }
public DbSet<Menu> Menu { get; set; }
public DbSet<Order> Order { get; set; }
// We need 2 constructors, one is empty, and the other injects in DbContextOptions
public CoffeeDbContext(DbContextOptions<CoffeeDbContext> options)
: base(options)
{
}
public CoffeeDbContext()
{
}
}
}
|
3941e346a581d7d27aa472acb800c95b88620d75
|
[
"C#"
] | 4
|
C#
|
jagdeepgilll/CoffeeBranch
|
6419a4e6c587f1a2f8c800a7f50761d63667eec9
|
0546a1a7972752be02d1568d3082ec1570d79603
|
refs/heads/master
|
<file_sep>from neo4j.v1 import GraphDatabase, basic_auth
driver = GraphDatabase.driver("bolt://localhost:7687", auth=basic_auth("neo4j", "pen.see.hen-919"))
session = driver.session()
session.run("CREATE (a:Target {targetzone: {targetzone}})", {"targetzone": "Docker"})
session.close()
<file_sep>from neo4j.v1 import GraphDatabase, basic_auth
driver = GraphDatabase.driver("bolt://localhost:7687", auth=basic_auth("neo4j", "pen.see.hen-919"))
session = driver.session()
result = session.run("MATCH (n:Apps) RETURN n.appname AS appname")
resultx = session.run("MATCH (p:Pattern) RETURN p.targetcloud AS targetcloud")
resulty = session.run("MATCH (a:AppConfig) RETURN a.appstartscripts AS startscripts")
resultappcfg = session.run("MATCH (a:AppConfig) WHERE a.appstartscripts = '/etc/rc2.d/S90httpd' RETURN a.appstartscripts AS appscripts")
for record in result:
print("%s" % (record["appname"]))
for xrecord in resultx:
print("%s" % (xrecord["targetcloud"]))
for yrecord in resulty:
print("%s" % (yrecord["startscripts"]))
for apprecord in resultappcfg:
print ("Apps Config")
print("%s" % (apprecord["appscripts"]))
session.close()
<file_sep>from neo4j.v1 import GraphDatabase, basic_auth
driver = GraphDatabase.driver("bolt://localhost:7687", auth=basic_auth("neo4j", "pen.see.hen-919"))
session = driver.session()
result = session.run("MATCH (n:Apps) RETURN n.appname AS appname")
for record in result:
print("%s" % (record["appname"]))
session.close()
|
cdb8bebdf303eea6abb732926e35e82fc73eae2a
|
[
"Python"
] | 3
|
Python
|
jmcambell72/neo4j
|
4f304f81881e4a106985313d19c042a431df9896
|
444dec953bc1c071fe5673b6e74c19c4d1df0a6a
|
refs/heads/master
|
<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
//import App from './App';
import registerServiceWorker from './registerServiceWorker';
function Change (props){
if(props.value){
return <h1>this is true </h1>
}
else
return <h1> this is false </h1>
}
class ChangeMeesage extends React.Component {
constructor(props)
{
super(props);
this.state ={ value : true};
}
handleclick=()=>{
this.setState ({
value :!this.state.value
})
}
render(){
return(
<div>
<button onClick={this.handleclick} > change the meesage</button>
<Change value={this.state.value} />
</div>)
}
}
ReactDOM.render(<ChangeMeesage/>, document.getElementById('root'));
registerServiceWorker();
|
976e347116f78c893b460ec0cdaab6b26b0552a9
|
[
"JavaScript"
] | 1
|
JavaScript
|
ThanaL/react-tutorial
|
c1095f447054ab0181cd6bd6b741ef00a3d77402
|
d162db3c7788ba8ccbc4443db86c42c4297eaa91
|
refs/heads/master
|
<file_sep>import { isFunction } from 'lodash';
import { connect as reduxConnect } from 'react-redux';
export function connect(mapStateToProps, mapDispatchToProps, mergeProps, { withRef = true, ... extraOptions } = {}) {
let decorator = reduxConnect(mapStateToProps, mapDispatchToProps, mergeProps, { withRef, ... extraOptions });
return function (Class) {
let Wrapper = decorator(Class);
Class.WrapperComponent = Wrapper;
for (let name of Reflect.ownKeys(Class)) {
if (Reflect.has(Wrapper, name))
continue;
if (isFunction(Class.prototype[name])) {
Wrapper[name] = function (... args) { return Class[name].apply(this === Wrapper ? Class : this, args); };
} else {
Wrapper[name] = Class[name];
}
}
for (let name of Reflect.ownKeys(Class.prototype)) {
if (Reflect.has(Wrapper.prototype, name))
continue;
if (isFunction(Class.prototype[name])) {
Wrapper.prototype[name] = function (... args) { return Class.prototype[name].apply(this instanceof Wrapper ? this.getWrappedInstance() : this, args); };
} else {
Wrapper.prototype[name] = Class.prototype[name];
}
}
return Wrapper;
};
}
export function statics(fields) {
return function (klass) {
return Object.assign(klass, fields);
};
}
<file_sep>import * as actions from '@cideditor/cid/actions';
import { WINDOW_TYPE } from '@cideditor/cid/reducers/windowRegistry';
import { FileSelectorDialog } from '@cideditor/cid/components/dialogs/FileSelectorDialog';
import { put, select } from 'redux-saga/effects';
export let windowShortcuts = {
[`ctrl-x /`]: ({ windowId, dispatch }) => {
dispatch(actions.windowSplit(windowId, { splitType: WINDOW_TYPE.COLUMN }));
},
[`ctrl-x :`]: ({ windowId, dispatch }) => {
dispatch(actions.windowSplit(windowId, { splitType: WINDOW_TYPE.ROW }));
},
[`ctrl-x 0`]: ({ windowId, dispatch }) => {
dispatch(actions.windowKill(windowId));
},
[`ctrl-o`]: ({ dispatch, getState }) => {
dispatch(function * () {
let path = yield select(state => state.activePath);
dispatch(actions.dialogOpen(<FileSelectorDialog initialPath={path} />));
});
},
[`alt-left`]: ({ windowId, dispatch }) => {
dispatch(actions.windowMoveActive(windowId, { direction: actions.WINDOW_MOVE_ACTIVE_LEFT }));
},
[`alt-right`]: ({ windowId, dispatch }) => {
dispatch(actions.windowMoveActive(windowId, { direction: actions.WINDOW_MOVE_ACTIVE_RIGHT }));
},
[`alt-up`]: ({ windowId, dispatch }) => {
dispatch(actions.windowMoveActive(windowId, { direction: actions.WINDOW_MOVE_ACTIVE_UP }));
},
[`alt-down`]: ({ windowId, dispatch }) => {
dispatch(actions.windowMoveActive(windowId, { direction: actions.WINDOW_MOVE_ACTIVE_DOWN }));
}
};
<file_sep>import { containerSet, viewSet, windowSet } from '@cideditor/cid/actions';
import { windowSetActive } from '@cideditor/cid/actions';
import { viewOpenDescriptor } from '@cideditor/cid/actions';
import { ContainerEntry } from '@cideditor/cid/reducers/containerRegistry';
import { ViewEntry } from '@cideditor/cid/reducers/viewRegistry';
import { WINDOW_TYPE } from '@cideditor/cid/reducers/windowRegistry';
import { WindowEntry } from '@cideditor/cid/reducers/windowRegistry';
import { setupAction } from '@cideditor/cid/utils/setupAction';
import { UsageError } from '@manaflair/concierge';
import { concierge, flags } from '@manaflair/concierge';
import { TermElement } from '@manaflair/mylittledom/term';
import { put } from 'redux-saga/effects';
import TextBuffer from 'text-buffer';
concierge
.topLevel(`[--no-output] [--debug-console] [--debug-shortcuts] [--debug-paint-rects]`);
concierge
.command(`open <path>`)
.flag(flags.DEFAULT_COMMAND)
.action(setupAction(env => function * () {
yield put([
viewSet(new ViewEntry({
id: 1,
descriptor: env.path,
})),
containerSet(new ContainerEntry({
id: 1,
element: new TermElement(),
viewId: 1,
})),
windowSet(new WindowEntry({
id: 1,
type: WINDOW_TYPE.VIEW,
containerId: 1,
})),
viewOpenDescriptor.async(
1,
env.path,
),
windowSetActive(
1
),
]);
}, { ui: true }));
concierge
.run(process.argv0, process.argv.slice(2));
<file_sep>import { TextEditor } from '@cideditor/cid/components/TextEditor';
import { statics } from '@cideditor/cid/utils/decorators';
import { autobind } from 'core-decorators';
let defaultEditor = <TextEditor
style={{ width: `100%`, height: `100%` }}
grammar={`language-babel`}
theme={`Atom Dark`}
/>;
@statics({
propTypes: {
style: React.PropTypes.object,
initialComponent: React.PropTypes.node,
},
defaultProps: {
style: {},
initialComponent: defaultEditor
}
})
export class Splittable extends React.PureComponent {
state = {
direction: null,
component: null
};
constructor(props) {
super(props);
this.state.component = props.initialComponent;
}
getSeparatorStyle() {
switch (this.state.direction) {
case `column`: {
return { flex: null, width: `100%`, height: 1, backgroundColor: `white`, backgroundCharacter: `·`, color: `#888888` };
} break;
case `row`: {
return { flex: null, width: 2, height: `100%`, backgroundColor: `white`, backgroundCharacter: `·`, color: `#888888` };
} break;
}
}
@autobind handleHorizontalSplit() {
this.setState({ direction: `column` });
}
@autobind handleVerticalSplit() {
this.setState({ direction: `row` });
}
render() {
return this.state.direction ? <div style={{ ... this.props.style, flex: 1, flexDirection: this.state.direction }}>
<Splittable initialComponent={this.state.component} />
<div style={this.getSeparatorStyle()} />
<Splittable />
</div> : <div style={{ ... this.props.style, flex: 1 }} onShortcuts={{ [`ctrl-x /`]: this.handleHorizontalSplit, [`ctrl-x :`]: this.handleVerticalSplit }}>
{this.state.component}
</div>;
}
}
<file_sep>import { WINDOW_MOVE_ACTIVE_LEFT, WINDOW_MOVE_ACTIVE_RIGHT, WINDOW_MOVE_ACTIVE_UP, WINDOW_MOVE_ACTIVE_DOWN } from '@cideditor/cid/actions';
import { WINDOW_SPLIT, WINDOW_KILL, WINDOW_MOVE_ACTIVE } from '@cideditor/cid/actions';
import { containerSet, containerUnset, viewUnset, windowSet, windowSetActive, windowUnset } from '@cideditor/cid/actions';
import { ContainerEntry } from '@cideditor/cid/reducers/containerRegistry';
import { WINDOW_TYPE } from '@cideditor/cid/reducers/windowRegistry';
import { WindowEntry } from '@cideditor/cid/reducers/windowRegistry';
import { atomicBatch } from '@cideditor/cid/utils/atomicBatch';
import { TermElement } from '@manaflair/mylittledom/term';
import { put, select, takeEvery } from 'redux-saga/effects';
export function * windowManager() {
yield [
takeEvery(WINDOW_SPLIT, splitWindow),
takeEvery(WINDOW_KILL, killWindow),
takeEvery(WINDOW_MOVE_ACTIVE, moveActiveWindow),
];
}
function * splitWindow(action) {
let window = yield select(state => {
return state.windowRegistry.getById(action.windowId);
});
if (!window || window.type !== WINDOW_TYPE.VIEW)
return;
let container = yield select(state => {
return state.containerRegistry.getById(window.containerId);
});
yield * atomicBatch(function * () {
let autoIncrementContainer = yield select(state => {
return state.containerRegistry.autoIncrement;
});
let autoIncrementWindow = yield select(state => {
return state.windowRegistry.autoIncrement;
});
let newContainer = new ContainerEntry({
id: autoIncrementContainer++,
element: new TermElement(),
viewId: container.viewId,
});
let firstNewWindow = new WindowEntry({
id: autoIncrementWindow++,
type: WINDOW_TYPE.VIEW,
containerId: window.containerId,
parentId: window.id,
});
let secondNewWindow = new WindowEntry({
id: autoIncrementWindow++,
type: WINDOW_TYPE.VIEW,
containerId: newContainer.id,
parentId: window.id,
});
let updatedWindow = new WindowEntry({
id: window.id,
type: action.splitType,
containerId: null,
parentId: window.parentId,
childrenIds: new Immutable.List([ firstNewWindow.id, secondNewWindow.id ])
});
yield put(containerSet(newContainer));
yield put(windowSet(updatedWindow));
yield put(windowSet(firstNewWindow));
yield put(windowSet(secondNewWindow));
yield put(windowSetActive(firstNewWindow.id));
});
}
function * killWindow(action) {
let window = yield select(state => {
return state.windowRegistry.getById(action.windowId);
});
if (!window || window.type !== WINDOW_TYPE.VIEW || window.parentId === null)
return;
let parent = yield select(state => {
return state.windowRegistry.getById(window.parentId);
});
let sibling = yield select(state => {
return state.windowRegistry.getById(parent.childrenIds.find(id => id !== window.id));
});
yield * atomicBatch(function * () {
yield put(containerUnset(window.containerId));
yield put(windowUnset(parent.childrenIds.get(0)));
yield put(windowUnset(parent.childrenIds.get(1)));
yield put(windowSet(parent.merge({ type: WINDOW_TYPE.VIEW, containerId: sibling.containerId, childrenIds: null })));
yield put(windowSetActive(parent.id));
});
}
function * moveActiveWindow(action) {
let checkParent;
let getSiblingId;
switch (action.direction) {
case WINDOW_MOVE_ACTIVE_LEFT: {
checkParent = (parent, child) => parent.type === WINDOW_TYPE.ROW && parent.childrenIds.indexOf(child.id) !== 0;
getSiblingId = (parent, child) => parent.childrenIds.get(parent.childrenIds.indexOf(child.id) - 1);
} break;
case WINDOW_MOVE_ACTIVE_RIGHT: {
checkParent = (parent, child) => parent.type === WINDOW_TYPE.ROW && parent.childrenIds.indexOf(child.id) !== parent.childrenIds.size - 1;
getSiblingId = (parent, child) => parent.childrenIds.get(parent.childrenIds.indexOf(child.id) + 1);
} break;
case WINDOW_MOVE_ACTIVE_UP: {
checkParent = (parent, child) => parent.type === WINDOW_TYPE.COLUMN && parent.childrenIds.indexOf(child.id) !== 0;
getSiblingId = (parent, child) => parent.childrenIds.get(parent.childrenIds.indexOf(child.id) - 1);
} break;
case WINDOW_MOVE_ACTIVE_DOWN: {
checkParent = (parent, child) => parent.type === WINDOW_TYPE.COLUMN && parent.childrenIds.indexOf(child.id) !== parent.childrenIds.size - 1;
getSiblingId = (parent, child) => parent.childrenIds.get(parent.childrenIds.indexOf(child.id) + 1);
} break;
}
let child = yield select(state => {
return state.windowRegistry.getById(action.windowId);
});
let parent = child.parentId !== null ? yield select(state => {
return state.windowRegistry.getById(child.parentId);
}) : null;
while (parent && !checkParent(parent, child)) {
child = parent; parent = select.parentId !== null ? yield select(state => {
return state.windowRegistry.getById(child.parentId);
}) : null;
}
if (parent) {
yield put(windowSetActive(getSiblingId(parent, child)));
}
}
<file_sep>import { VIEW_SET, VIEW_UNSET } from '@cideditor/cid/actions';
import { readFileSync } from 'fs';
import Immutable from 'immutable';
import TextBuffer from 'text-buffer';
export let VIEW_STATUS = {
LOADING: `VIEW_STATUS.LOADING`,
ERROR: `VIEW_STATUS.ERROR`,
READY: `VIEW_STATUS.READY`,
};
export let ViewEntry = new Immutable.Record({
id: null,
version: 0,
name: null,
descriptor: null,
status: null,
error: null,
component: null,
}, `ViewEntry`);
export let DirectoryViewEntry = new Immutable.Record({
... new ViewEntry().toJS(),
entries: null,
}, `DirectoryViewEntry`);
export let FileViewEntry = new Immutable.Record({
... new ViewEntry().toJS(),
textBuffer: null,
grammar: null,
theme: null,
readOnly: false,
}, `FileViewEntry`);
export let ViewRegistry = new Immutable.Record({
autoIncrement: 1,
// id -> ViewEntry
entriesById: new Immutable.Map(),
// descriptor -> id
entriesByDescriptor: new Immutable.Map(),
}, `ViewRegistry`);
export class ViewRegistryPublicInterface {
constructor(viewRegistry = new ViewRegistry()) {
this.viewRegistry = viewRegistry;
}
get autoIncrement() {
return this.viewRegistry.autoIncrement;
}
createView(Type, props = {}) {
return new Type({
id: this.viewRegistry.autoIncrement,
... props
});
}
getById(viewId) {
if (viewId === null)
return null;
let instance = this.viewRegistry.entriesById.get(viewId);
if (!instance)
return null;
return instance;
}
getByDescriptor(descriptor) {
if (descriptor === null)
return null;
let id = this.viewRegistry.entriesByDescriptor.get(descriptor);
if (!id)
return null;
return this.getById(id);
}
setView(view) {
let oldView = this.viewRegistry.getIn([ `entriesById`, view.id ], null);
if (oldView && oldView.descriptor !== view.descriptor)
throw new Error(`A view descriptor cannot be changed during its lifetime`);
if (view.descriptor !== null && this.viewRegistry.getIn([ `entriesByDescriptor`, view.descriptor ], view.id) !== view.id)
throw new Error(`A same descriptor cannot be used accross multiple views`);
let viewRegistry = this.viewRegistry.setIn([ `entriesById`, view.id ], view);
if (view.id >= viewRegistry.autoIncrement)
viewRegistry = viewRegistry.merge({ autoIncrement: view.id + 1 });
if (!oldView && view.descriptor !== null)
viewRegistry = viewRegistry.setIn([ `entriesByDescriptor`, view.descriptor ], view.id);
return this.applyRegistry(viewRegistry);
}
unsetView(viewId) {
let oldView = this.viewRegistry.getIn([ `entriesById`, viewId ]);
if (!oldView)
return this;
let viewRegistry = this.viewRegistry.deleteIn([ `entriesById`, viewId ]);
if (!oldView && oldView.descriptor !== null)
viewRegistry = viewRegistry.deleteIn([ `entriesByDescriptor`, oldView.descriptor ]);
return this.applyRegistry(viewRegistry);
}
applyRegistry(viewRegistry) {
if (viewRegistry !== this.viewRegistry) {
return new ViewRegistryPublicInterface(viewRegistry);
} else {
return this;
}
}
}
export function viewRegistry(state = new ViewRegistryPublicInterface(), action) {
switch (action.type) {
default: {
return state;
} break;
case VIEW_SET: {
return state.setView(action.view);
} break;
case VIEW_UNSET: {
return state.unsetView(action.viewId);
} break;
}
}
<file_sep>export class ImmutableRect extends Immutable.Record({
x: null,
y: null,
width: null,
height: null
}) {
static update(current, rect) {
if (!rect)
return null;
let { x, y, width, height } = rect;
if (!current) {
return new ImmutableRect({ x, y, width, height });
} else {
return current.merge({ x, y, width, height });
}
}
}
<file_sep>import { ImmutablePoint } from '@cideditor/cid/utils/ImmutablePoint';
import { SyntaxHighlighter } from '@manaflair/mylittledom/extra';
import { autobind } from 'core-decorators';
import { readFileSync } from 'fs';
import TextBuffer from 'text-buffer';
export class TextEditor extends React.PureComponent {
static propTypes = {
style: React.PropTypes.object,
textBuffer: React.PropTypes.instanceOf(TextBuffer),
grammar: React.PropTypes.string,
theme: React.PropTypes.string,
caret: React.PropTypes.instanceOf(ImmutablePoint),
scroll: React.PropTypes.instanceOf(ImmutablePoint),
value: React.PropTypes.string,
onCaret: React.PropTypes.func,
onScroll: React.PropTypes.func,
onChange: React.PropTypes.func,
autofocus: React.PropTypes.string,
};
static defaultProps = {
style: {},
textBuffer: undefined,
grammar: null,
theme: null,
value: undefined,
onCaret: () => {},
onChange: () => {},
onScroll: () => {}
};
state = {
backgroundColor: null
};
constructor(props) {
super(props);
this.highlighter = new SyntaxHighlighter();
}
componentWillMount() {
this.setGrammar(this.props.grammar);
this.setTheme(this.props.theme);
}
componentWillReceiveProps(nextProps) {
if (nextProps.grammar !== this.props.grammar)
this.setGrammar(nextProps.grammar);
if (nextProps.theme !== this.props.theme) {
this.setTheme(nextProps.theme);
}
}
getShortcuts() {
return {
[`ctrl-t`]: this.handleThemeSelect
};
}
setGrammar(grammar: string) {
if (grammar !== null && !this.highlighter.grammar.registry.has(grammar))
// this.highlighter.grammar.load(grammar, readFileSync(require.resolve(`@cideditor/cid/grammars/${grammar}.tmLanguage`)));
this.highlighter.grammar.load(grammar, readFileSync(`${__dirname}/../grammars/${grammar}.json`));
this.highlighter.grammar.use(grammar);
if (this.input) {
this.highlighter.grammar.apply().apply(this.input.textLines);
this.input.queueDirtyRect();
}
}
setTheme(theme: string) {
if (theme !== null && !this.highlighter.theme.registry.has(theme))
// this.highlighter.theme.load(theme, readFileSync(require.resolve(`@cideditor/cid/themes/${theme}.tmTheme`)));
this.highlighter.theme.load(theme, readFileSync(`${__dirname}/../themes/${theme}.tmTheme`));
this.highlighter.theme.use(theme);
if (this.input) {
this.highlighter.theme.apply().apply(this.input.textLines);
this.input.queueDirtyRect();
}
this.setState({ backgroundColor: this.highlighter.theme.resolve([], `background`, null) });
}
focus() {
if (!this.input)
return;
this.input.focus();
}
blur() {
if (!this.input)
return;
this.input.blur();
}
@autobind setLinenoRef(lineno) {
this.lineno = lineno;
}
@autobind renderLineno(x: number, y: number, l: number) {
if (!this.input)
return this.lineno.renderBackground(l);
return `${y + this.input.scrollTop}`.padEnd(4).substr(x, l);
}
@autobind setInputRef(input) {
this.input = input;
}
@autobind handleCaret(e) {
let { x, y } = e.target.caret;
this.props.onCaret({ x, y });
}
@autobind handleChange(e) {
this.props.onChange(e.target.value);
}
@autobind handleScroll(e) {
let { x, y } = e.target.scrollRect;
this.lineno.queueDirtyRect();
this.props.onScroll({ x, y });
}
render() {
return <div style={{
flexDirection: `row`,
... this.props.style
}}>
<div ref={this.setLinenoRef}
style={{
flex: null,
width: 5,
height: `100%`,
padding: [ 0, 1 ]
}}
contentRenderer={this.renderLineno}
/>
<input ref={this.setInputRef}
style={{
flex: 1,
width: `100%`,
height: `100%`,
paddingLeft: 1,
whiteSpace: `pre`,
backgroundColor: this.state.backgroundColor
}}
textBuffer={this.props.textBuffer}
textLayout={this.highlighter}
caret={this.props.caret}
scroll={this.props.scroll}
value={this.props.value}
onCaret={this.handleCaret}
onScroll={this.handleScroll}
onChange={this.handleChange}
onShortcuts={this.getShortcuts()}
multiline={true}
decored={false}
autofocus={this.props.autofocus}
/>
</div>;
}
}
<file_sep>import { statics } from '@cideditor/cid/utils/decorators';
import { makeRuleset } from '@manaflair/mylittledom';
import { autobind } from 'core-decorators';
let selectClass = makeRuleset({
});
let selectItemClass = makeRuleset({
});
let selectedItemClass = makeRuleset({
background: `blue`,
color: `white`
});
@statics({
propTypes: {
value: React.PropTypes.any,
children: React.PropTypes.oneOfType([
React.PropTypes.immutable.listOf(React.PropTypes.element),
React.PropTypes.element
]),
onChange: React.PropTypes.func
},
defaultProps: {
onChange: () => {}
}
})
export class Select extends React.PureComponent {
@autobind handleUpKey(e) {
e.preventDefault();
this.moveBy(-1);
}
@autobind handleDownKey(e) {
e.preventDefault();
this.moveBy(+1);
}
moveBy(n) {
if (n === 0)
return;
let items = this.props.children.toArray();
let index = items.findIndex(child => child.props.value === this.props.value);
let nextIndex = (index + n) % items.length;
if (index === -1)
nextIndex = index < 0 ? 0 : items.length - 1;
if (nextIndex < 0)
nextIndex += items.length;
let nextValue = items[nextIndex].props.value;
this.props.onChange(nextValue, nextIndex);
}
render() {
return <div>
{React.Children.map(this.props.children, (child, index) => {
let selected = child.props.value === this.props.value;
let onUpKey = e => this.handleUpKey(e, index);
let onDownKey = e => this.handleDownKey(e, index);
return React.cloneElement(child, { onUpKey, onDownKey, selected });
})}
</div>;
}
}
export class SelectItem extends React.PureComponent {
static propTypes = {
value: React.PropTypes.any.isRequired,
children: React.PropTypes.node,
selected: React.PropTypes.bool,
onUpKey: React.PropTypes.func,
onDownKey: React.PropTypes.func
};
@autobind handleUp() {
this.props.onUpKey();
}
render() {
return <div classList={[ selectItemClass, this.props.selected && selectedItemClass ]} onShortcutUp={this.props.handleUp} onShortcutDown={this.props.handleDown}>
{this.props.children || this.props.value}
</div>;
}
}
<file_sep>import { DIALOG_OPEN, DIALOG_CLOSE } from '@cideditor/cid/actions';
import Immutable from 'immutable';
export function dialogStack(state = new Immutable.Stack(), action) {
switch (action.type) {
case DIALOG_OPEN: {
return state.unshift(action.component);
} break;
case DIALOG_CLOSE: {
return state.pop();
} break;
default: {
return state;
} break;
}
}
<file_sep>import { VIEW_OPEN_DESCRIPTOR, containerSet, viewSet } from '@cideditor/cid/actions';
import { EditorView } from '@cideditor/cid/components/views/EditorView';
import { findDriver } from '@cideditor/cid/filesystems';
import { FileViewEntry, DirectoryViewEntry } from '@cideditor/cid/reducers/viewRegistry';
import { VIEW_STATUS } from '@cideditor/cid/reducers/viewRegistry';
import { ViewEntry } from '@cideditor/cid/reducers/viewRegistry';
import { put, select, takeEvery } from 'redux-saga/effects';
import TextBuffer from 'text-buffer';
export function * openManager() {
yield takeEvery(VIEW_OPEN_DESCRIPTOR, function * (action) {
let view = yield select(state => state.viewRegistry.getById(action.viewId));
if (!view) {
yield put(viewSet(view = new ViewEntry({ id: 0 })));
} else {
yield put(viewSet(view = view.merge({ version: view.version + 1 })));
}
let currentVersion = view.version;
try {
let driver = findDriver(action.descriptor);
if (!driver)
throw new Error(`Unsupported protocol`);
yield put(viewSet(view = view.merge({ status: VIEW_STATUS.LOADING })));
// ---
let name = yield driver.getName(action.descriptor);
let stat = yield driver.getStat(action.descriptor, { followLinks: true });
view = yield select(state => state.viewRegistry.getById(action.viewId));
if (!view || view.version !== currentVersion)
return;
let { prepareView, loadExtraData } = getViewTools(driver, action.descriptor, stat);
yield put(viewSet(view = prepareView(view.merge({ name, descriptor: action.descriptor, error: null }))));
// ---
let extraData = yield loadExtraData();
view = yield select(state => state.viewRegistry.getById(action.viewId));
if (!view || view.version !== currentVersion)
return;
yield put(viewSet(view = view.merge({ ... extraData, status: VIEW_STATUS.READY })));
} catch (error) {
view = yield select(state => state.viewRegistry.getById(action.viewId));
if (!view || view.version !== currentVersion)
return;
yield put(viewSet(view = view.merge({ status: VIEW_STATUS.ERROR, error })));
}
});
}
function getViewTools(driver, descriptor, stat) {
switch (true) {
case stat.isDirectory(): {
let prepareView = view => new DirectoryViewEntry({ ... view.toJS(), component: <DiredView /> });
let loadExtraData = async () => ({ entries: await driver.readDirectory(descriptor) });
return { prepareView, loadExtraData };
} break;
case stat.isFile(): {
let prepareView = view => new FileViewEntry({ ... view.toJS(), component: <EditorView />, grammar: `Javascript`, theme: `Tron` });
let loadExtraData = async () => ({ textBuffer: new TextBuffer((await driver.readFile(descriptor)).toString()) });
return { prepareView, loadExtraData };
} break;
default: {
throw new Error(`Referenced entry is neither a file nor a directory`);
} break;
}
}
<file_sep>import { WINDOW_SET_ACTIVE } from '@cideditor/cid/actions';
export function activeWindowId(state = 0, action) {
switch (action.type) {
case WINDOW_SET_ACTIVE: {
return action.windowId;
} break;
default: {
return state;
} break;
}
}
<file_sep>import { statics } from '@cideditor/cid/utils/decorators';
import { autobind } from 'core-decorators';
@statics({
propTypes: {
style: React.PropTypes.object,
onSave: React.PropTypes.func
},
defaultProps: {
onSave: () => {}
}
})
export class ThemeEditor extends React.PureComponent {
state = {
name: `Untitled`
};
@autobind handleNameChange(e) {
this.setState({ name: e.target.value });
}
render() {
return <div style={{ padding: [ 0, 1 ] }}>
<label>
<div style={{ fontWeight: `bold` }}>Theme name:</div>
<input value={this.state.name} onChange={this.handleNameChange} />
</label>
<div style={{ textAlign: `right` }}>
Add new [+]
</div>
</div>;
}
}
<file_sep>import { windowSetActive, windowSplit, windowKill } from '@cideditor/cid/actions';
import { WINDOW_TYPE } from '@cideditor/cid/reducers/windowRegistry';
import { WindowEntry } from '@cideditor/cid/reducers/windowRegistry';
import { windowShortcuts } from '@cideditor/cid/shortcuts';
import { applyShortcuts } from '@cideditor/cid/utils/applyShortcuts';
import { connect } from '@cideditor/cid/utils/decorators';
import * as ReactTerm from '@manaflair/mylittledom/term/react';
import { isChildOf } from '@manaflair/mylittledom';
import { autobind } from 'core-decorators';
@connect((state, props) => {
return { containerRegistry: state.containerRegistry };
})
export class Application extends React.PureComponent {
render() {
return <div style={{ width: `100%`, height: `100%` }}>
<Window windowId={1} />
{this.props.containerRegistry.idSeq().map(containerId =>
<Container key={containerId} containerId={containerId} />
)}
</div>;
}
}
@connect((state, props) => {
let window = state.windowRegistry.getById(props.windowId);
let container = state.containerRegistry.getById(window.containerId);
let isActiveWindow = state.activeWindowId === window.id;
let activeDialog = isActiveWindow && state.dialogStack.size > 0 ? state.dialogStack.first() : null;
return { window, container, isActiveWindow, activeDialog };
})
class Window extends React.PureComponent {
static propTypes = {
onGotoLeft: React.PropTypes.func,
onGotoRight: React.PropTypes.func,
onGotoUp: React.PropTypes.func,
onGotoDown: React.PropTypes.func
};
static defaultProps = {
onGotoLeft: () => {},
onGotoRight: () => {},
onGotoUp: () => {},
onGotoDown: () => {}
};
constructor(props) {
super(props);
this.main = null;
this.container = null;
this.children = new Map();
}
componentDidMount() {
let focused = this.props.container
? this.props.container.element.rootNode.activeElement
: null;
if (this.props.container)
this.container.appendChild(this.props.container.element);
if (this.props.isActiveWindow && focused) {
focused.focus();
}
}
componentDidUpdate(prevProps) {
let focused = this.main
? this.main.rootNode.activeElement
: null;
if (prevProps.container && this.props.container !== prevProps.container && prevProps.container.element.parentNode === this.main)
this.container.removeChild(prevProps.container.element);
if (this.props.container)
this.container.appendChild(this.props.container.element);
if (this.props.isActiveWindow && focused)
focused.focus();
if (this.props.isActiveWindow && this.props.window.type !== WindowEntry.WINDOW_TYPE_VIEW) {
this.requestActivate();
}
}
componentWillUnmount() {
if (this.props.container && this.props.container.element.parentNode === this.main) {
this.container.removeChild(this.props.container);
}
}
getSeparator() {
switch (this.props.window.type) {
case WINDOW_TYPE.COLUMN: {
return null;
} break;
case WINDOW_TYPE.ROW: {
return <div style={{ flex: null, width: 2, height: `100%`, backgroundColor: `#333333` }} />;
} break;
}
}
getDirection() {
switch (this.props.window.type) {
case WINDOW_TYPE.COLUMN: {
return `column`;
} break;
case WINDOW_TYPE.ROW: {
return `row`;
} break;
default: {
return null;
} break;
}
}
getBoundingClientRect() {
if (!this.main)
return null;
return this.main.getBoundingClientRect();
}
requestActivate() {
if (this.props.window.type !== WINDOW_TYPE.VIEW) {
if (this.props.window.childrenIds.size === 0)
return;
let cascadedWindowId = this.props.window.childrenIds.get(0);
let caret = this.main ? this.main.rootNode.getCaretCoordinates() : null;
if (caret) {
let shortestDistance = Infinity;
for (let [ windowId, component ] of this.children.entries()) {
let boundingRect = component.getBoundingClientRect();
if (!boundingRect)
continue;
let distance = boundingRect.getDistanceFromPoint(caret).length;
if (distance <= shortestDistance) {
cascadedWindowId = windowId;
shortestDistance = distance;
}
}
}
let childWindow = this.children.get(cascadedWindowId);
childWindow.requestActivate();
} else {
this.props.dispatch(windowSetActive(this.props.window.id));
}
}
@autobind registerMainRef(main) {
this.main = main;
}
@autobind registerContainerRef(container) {
this.container = container;
}
@autobind registerChildRef(windowId, child) {
if (child) {
this.children.set(windowId, child);
} else {
this.children.delete(windowId);
}
}
@autobind handleFocusCapture(e) {
if (this.props.window.type !== WINDOW_TYPE.VIEW)
return;
this.props.dispatch(windowSetActive(this.props.window.id));
}
render() {
if (this.props.window.type !== WINDOW_TYPE.VIEW) {
let separator = this.getSeparator();
let WrapperComponent = Window.WrapperComponent; // otherwise they won't be connect()'d
let subViewComponents = [];
for (let t = 0; t < this.props.window.childrenIds.size; ++t) {
let windowId = this.props.window.childrenIds.get(t);
if (separator && t > 0) subViewComponents.push(React.cloneElement(separator, {
key: `separator-${t}`
}));
subViewComponents.push(<WrapperComponent
key={windowId}
ref={child => this.registerChildRef(windowId, child)}
windowId={windowId}
onGotoLeft={this.handleGotoLeft}
onGotoRight={this.handleGotoRight}
onGotoUp={this.handleGotoUp}
onGotoDown={this.handleGotoDown}
/>);
}
return <div ref={this.registerMainRef} style={{ ... this.props.style, flex: 1, width: `100%`, height: `100%`, flexDirection: this.getDirection() }}>
{subViewComponents}
</div>;
} else {
return <div ref={this.registerMainRef} style={{ ... this.props.style, flex: 1, width: `100%`, height: `100%` }} onShortcuts={applyShortcuts(windowShortcuts, { windowId: this.props.window.id, dispatch: this.props.dispatch })} onFocusCapture={this.handleFocusCapture}>
{this.props.activeDialog && <div style={{ position: `absolute`, left: 2, right: 2, top: 1 }}>
{this.props.activeDialog}
</div>}
<div ref={this.registerContainerRef} style={{ flex: 1, width: `100%`, height: `100%` }}>
{/* this.props.container.element will be inserted here */}
</div>
</div>;
}
}
}
@connect((state, props) => {
let window = state.windowRegistry.getByContainerId(props.containerId);
let container = state.containerRegistry.getById(props.containerId);
let view = container ? state.viewRegistry.getById(container.viewId) : null;
return { window, container, view };
})
class Container extends React.PureComponent {
render() {
if (!this.props.view || !this.props.view.component)
return null;
return ReactTerm.createPortal(React.cloneElement(this.props.view.component, {
windowId: this.props.window ? this.props.window.id : null,
containerId: this.props.container.id,
viewId: this.props.view.id,
}), this.props.container.element);
}
}
<file_sep>import { WINDOW_TYPE } from '@cideditor/cid/reducers/windowRegistry';
export const WINDOW_MOVE_ACTIVE_LEFT = `WINDOW_MOVE_ACTIVE_LEFT`;
export const WINDOW_MOVE_ACTIVE_RIGHT = `WINDOW_MOVE_ACTIVE_RIGHT`;
export const WINDOW_MOVE_ACTIVE_UP = `WINDOW_MOVE_ACTIVE_UP`;
export const WINDOW_MOVE_ACTIVE_DOWN = `WINDOW_MOVE_ACTIVE_DOWN`;
// ---
export const WINDOW_SET = `WINDOW_SET`;
export const windowSet = (window) => ({ type: WINDOW_SET, window });
export const WINDOW_UNSET = `WINDOW_UNSET`;
export const windowUnset = (windowId) => ({ type: WINDOW_UNSET, windowId });
export const CONTAINER_SET = `CONTAINER_SET`;
export const containerSet = (container) => ({ type: CONTAINER_SET, container });
export const CONTAINER_UNSET = `CONTAINER_UNSET`;
export const containerUnset = (containerId) => ({ type: CONTAINER_UNSET, containerId });
export const VIEW_SET = `VIEW_SET`;
export const viewSet = (view) => ({ type: VIEW_SET, view });
export const VIEW_UNSET = `VIEW_UNSET`;
export const viewUnset = (viewId) => ({ type: VIEW_UNSET, viewId });
// ---
export const DIALOG_OPEN = `DIALOG_OPEN`;
export const dialogOpen = (component) => ({ type: DIALOG_OPEN, component });
export const DIALOG_CLOSE = `DIALOG_CLOSE`;
export const dialogClose = () => ({ type: DIALOG_CLOSE });
// ---
export const WINDOW_KILL = `WINDOW_KILL`;
export const windowKill = (windowId) => ({ type: WINDOW_KILL, windowId });
export const WINDOW_SPLIT = `WINDOW_SPLIT`;
export const windowSplit = (windowId, { splitType = WINDOW_TYPE.ROW } = {}) => ({ type: WINDOW_SPLIT, windowId, splitType });
// ---
export const WINDOW_SET_ACTIVE = `WINDOW_SET_ACTIVE`;
export const windowSetActive = (windowId) => ({ type: WINDOW_SET_ACTIVE, windowId });
export const WINDOW_MOVE_ACTIVE = `WINDOW_MOVE_ACTIVE`;
export const windowMoveActive = (windowId, { direction } = {}) => ({ type: WINDOW_MOVE_ACTIVE, windowId, direction });
// ---
export const VIEW_OPEN_DESCRIPTOR = `VIEW_OPEN_DESCRIPTOR`;
export const viewOpenDescriptor = { async: (viewId, descriptor) => ({ type: VIEW_OPEN_DESCRIPTOR, viewId, descriptor }) };
// ---
export const PATH_SET_ACTIVE = `PATH_SET_ACTIVE`;
export const pathSetActive = (path) => ({ type: PATH_SET_ACTIVE, path });
// ---
export const REFRESH_THEME_LIST = `REFRESH_THEME_LIST`;
export const refreshThemeList = () => ({ type: REFRESH_THEME_LIST });
<file_sep>import { put } from 'redux-saga/effects';
import { asEffect } from 'redux-saga/utils';
export function * atomicBatch(builder) {
let actions = [];
let generator = builder();
let inject, next;
while (!(next = generator.next(inject)).done) {
let yieldValue = next.value, asPut = asEffect.put(yieldValue);
if (!asPut) {
inject = yield yieldValue;
} else {
actions.push(asPut.action);
}
}
if (actions.length > 0)
yield put(actions);
return next.value;
}
<file_sep>import * as fs from 'fs';
import * as path from 'path';
export class LocalDriver {
supports(descriptor) {
return descriptor.match(
/^(?![a-zA-Z+-]+:\/\/)[^\0]+$/
);
}
async getName(descriptor) {
return path.basename(descriptor);
}
async getStat(descriptor, { followLinks = false } = {}) {
return new Promise((resolve, reject) => {
let fsImpl = followLinks
? fs.lstat
: fs.stat;
fsImpl(descriptor, (error, stat) => {
if (error) {
reject(error);
} else {
resolve(stat);
}
});
});
}
async readDirectory(descriptor) {
return new Promise((resolve, reject) => {
fs.readdir(descriptor, (error, listing) => {
if (error) {
reject(error);
} else {
resolve(listing);
}
});
});
}
async readFile(descriptor) {
return new Promise((resolve, reject) => {
fs.readFile(descriptor, (error, body) => {
if (error) {
reject(error);
} else {
resolve(body);
}
});
});
}
async writeFile(descriptor, body) {
return new Promise((resolve, reject) => {
fs.writeFile(descriptor, body, error => {
if (error) {
reject(error);
} else {
resolve();
}
});
});
}
};
<file_sep>export function applyShortcuts(shortcuts, options) {
let mappedShortcuts = {};
for (let sequence of Reflect.ownKeys(shortcuts)) {
mappedShortcuts[sequence] = e => {
e.setDefault(() => {
shortcuts[sequence](options);
});
};
}
return mappedShortcuts;
}
<file_sep>import { Select, SelectItem } from '@cideditor/cid/components/Select';
import { statics } from '@cideditor/cid/utils/decorators';
import { autobind } from 'core-decorators';
import Suggester from 'suggester';
@statics({
propTypes: {
choices: React.PropTypes.immutable.listOf(React.PropTypes.string),
value: React.PropTypes.string,
absolute: React.PropTypes.bool,
autofocus: React.PropTypes.string,
onBlur: React.PropTypes.func,
onChange: React.PropTypes.func
},
defaultProps: {
choices: Immutable.List(),
value: ``,
absolute: true,
onChange: () => {}
}
})
export class TypeAhead extends React.PureComponent {
state = {
value: ``,
suggestions: []
};
constructor(props) {
super(props);
this.state.value = props.value;
}
@autobind handleInputBlur() {
this.props.onBlur();
}
@autobind handleInputChange(e) {
let value = e.target.value;
let suggestions = this.search(value);
this.setState({ value, suggestions });
this.props.onChange(value);
}
@autobind handleSelectChange(value) {
this.props.onChange(value);
}
@autobind handleUp(e) {
e.setDefault(() => {
if (!this.suggestions)
return;
this.suggestions.moveBy(-1);
});
}
@autobind handleDown(e) {
e.setDefault(() => {
if (!this.suggestions)
return;
this.suggestions.moveBy(+1);
});
}
search(value) {
if (value.length === 0)
return Immutable.List();
let normalize = value => value.toLowerCase().replace(/\s+/g, ` `).trim();
let searchValue = normalize(value);
return this.props.choices.filter(choice => {
return normalize(choice).indexOf(searchValue) !== -1;
}).sort();
}
render() {
return <div>
<input
value={this.props.value}
autofocus={this.props.autofocus}
onBlur={this.handleInputBlur}
onChange={this.handleInputChange}
onShortcuts={{
[`down`]: this.handleDown,
[`up`]: this.handleUp
}}
/>
{this.state.suggestions && this.state.suggestions.size > 0 &&
<Select ref={suggestions => { this.suggestions = suggestions }} style={this.props.absolute ? { position: `absolute`, left: 0, right: 0, top: 1, maxHeight: 10 } : { maxHeight: 10 }} value={this.props.value} onChange={this.handleSelectChange}>
{this.state.suggestions.map(choice => {
return <SelectItem key={choice} value={choice} />;
})}
</Select>
}
</div>;
}
}
<file_sep>import { CONTAINER_SET, CONTAINER_UNSET } from '@cideditor/cid/actions';
import { TermElement } from '@manaflair/mylittledom/term';
import Immutable from 'immutable';
export let ContainerEntry = new Immutable.Record({
id: null,
element: null,
viewId: null,
});
export let ContainerRegistry = new Immutable.Record({
autoIncrement: 1,
// id -> ContainerEntry
entriesById: new Immutable.Map(),
});
export class ContainerRegistryPublicInterface {
constructor(containerRegistry = new ContainerRegistry()) {
this.containerRegistry = containerRegistry;
}
get autoIncrement() {
return this.containerRegistry.autoIncrement;
}
idSeq() {
return this.containerRegistry.entriesById.keySeq();
}
containerSeq() {
return this.containerRegistry.entriesById.valueSeq();
}
getById(containerId) {
if (containerId === null)
return null;
let instance = this.containerRegistry.entriesById.get(containerId);
if (!instance)
return null;
return instance;
}
setContainer(container) {
let containerRegistry = this.containerRegistry.setIn([ `entriesById`, container.id ], container);
if (container.id >= containerRegistry.autoIncrement)
containerRegistry = containerRegistry.merge({ autoIncrement: container.id + 1 });
return this.applyRegistry(containerRegistry);
}
unsetContainer(containerId) {
let containerRegistry = this.containerRegistry.deleteIn([ `entriesById`, containerId ]);
return this.applyRegistry(containerRegistry);
}
applyRegistry(containerRegistry) {
if (containerRegistry !== this.containerRegistry) {
return new ContainerRegistryPublicInterface(containerRegistry);
} else {
return this;
}
}
}
export function containerRegistry(state = new ContainerRegistryPublicInterface(), action) {
switch (action.type) {
default: {
return state;
} break;
case CONTAINER_SET: {
return state.setContainer(action.container);
} break;
case CONTAINER_UNSET: {
return state.unsetContainer(action.containerId);
} break;
}
}
<file_sep>Error.stackTraceLimit = Infinity;
global.Immutable = require(`immutable`);
global.React = require(`react`);
global.React.PropTypes.immutable = require(`react-immutable-proptypes`);
<file_sep>import { Application } from '@cideditor/cid/components/Application';
import { buildReducer } from '@cideditor/cid/utils/buildReducer';
import { buildSaga } from '@cideditor/cid/utils/buildSaga';
import { createSagaDispatcher } from '@manaflair/action-sagas';
import { render } from '@manaflair/mylittledom/term/react';
import { TermElement, TermScreen, TermText } from '@manaflair/mylittledom/term';
import { reduxBatch } from '@manaflair/redux-batch';
import { Console } from 'console';
import { Provider } from 'react-redux';
import createSagaMiddleware from 'redux-saga';
import { applyMiddleware, compose, createStore } from 'redux';
import { PassThrough } from 'stream';
import { StringDecoder } from 'string_decoder';
export function setupAction(action, { ui = false } = {}) {
return env => {
if (ui) {
startUi(env)(action);
} else {
return action(env);
}
};
}
function startUi(env) {
let screen = new TermScreen();
let renderTarget = screen;
if (env.debugPaintRects)
screen.debugPaintRects = true;
if (env.debugConsole)
renderTarget = startUiConsole(env, renderTarget);
let stdout = Object.create(process.stdout);
if (!env.output) stdout.write = () => {};
let reducer = buildReducer(`${__dirname}/../reducers`);
let saga = buildSaga(`${__dirname}/../sagas`);
let sagaMiddleware = createSagaMiddleware({ emitter: emit => action => {
if (Array.isArray(action)) store.dispatch(action);
else emit(action);
}});
let sagaDispatcher = createSagaDispatcher(sagaMiddleware);
let store = createStore(reducer, compose(reduxBatch, applyMiddleware(sagaMiddleware), reduxBatch, applyMiddleware(sagaDispatcher), reduxBatch));
let ui = <Provider store={store} children={<Application />} />;
sagaMiddleware.run(saga);
return action => {
store.dispatch(action(env));
render(ui, renderTarget);
screen.attachScreen({ stdout });
};
}
function startUiConsole(env, renderTarget) {
let container = new TermElement();
container.style.flexDirection = `row`;
container.style.width = `100%`;
container.style.height = `100%`;
container.appendTo(renderTarget);
let main = renderTarget = new TermElement();
main.style.flex = 1;
main.style.width = `100%`;
main.style.height = `100%`;
main.appendTo(container);
let console = new TermText();
console.style.flex = null;
console.style.width = 80 + 2 + 2;
console.style.height = `100%`;
console.style.border = `modern`;
console.style.padding = [ 0, 1 ];
console.style.whiteSpace = `preWrap`;
console.appendTo(container);
if (!env.output)
return renderTarget;
let consoleOutput = new PassThrough();
let decoder = new StringDecoder(`utf8`);
consoleOutput.on(`data`, buffer => console.textContent += decoder.write(buffer));
consoleOutput.on(`end`, () => console.textContent += decoder.end());
Reflect.defineProperty(global, `console`, {
value: new Console(consoleOutput)
});
return renderTarget;
}
<file_sep>import { PATH_SET_ACTIVE } from '@cideditor/cid/actions';
export function activePath(state = null, action) {
switch (action.type) {
case PATH_SET_ACTIVE: {
return action.path;
} break;
default: {
return state;
} break;
}
}
<file_sep>import { WINDOW_SET, WINDOW_UNSET } from '@cideditor/cid/actions';
import Immutable from 'immutable';
export let WINDOW_TYPE = {
VIEW: `WINDOW_TYPE_VIEW`,
COLUMN: `WINDOW_TYPE_COLUMN`,
ROW: `WINDOW_TYPE_ROW`,
};
export let WindowEntry = new Immutable.Record({
id: null,
type: null,
containerId: null,
parentId: null,
childrenIds: null,
});
export let WindowRegistry = new Immutable.Record({
autoIncrement: 1,
// id -> WindowEntry
entriesById: new Immutable.Map(),
// containerId -> id
entriesByContainerId: new Immutable.Map(),
});
export class WindowRegistryPublicInterface {
constructor(windowRegistry = new WindowRegistry()) {
this.windowRegistry = windowRegistry;
}
get autoIncrement() {
return this.windowRegistry.autoIncrement;
}
idSeq() {
return this.windowRegistry.entriesById.keySeq();
}
windowSeq() {
return this.windowRegistry.entriesById.valueSeq();
}
getById(windowId) {
if (windowId === null)
return null;
let instance = this.windowRegistry.entriesById.get(windowId);
if (!instance)
return null;
return instance;
}
getByContainerId(containerId) {
if (containerId === null)
return null;
let id = this.windowRegistry.entriesByContainerId.get(containerId);
if (!id)
return null;
return this.getById(id);
}
setWindow(window) {
let oldWindow = this.windowRegistry.getIn([ `entriesById`, window.id ], null);
if (window.containerId !== null && this.windowRegistry.getIn([ `entriesByContainerId`, window.containerId ], window.id) !== window.id)
throw new Error(`A same container cannot be used accross multiple windows`);
let windowRegistry = this.windowRegistry.setIn([ `entriesById`, window.id ], window);
if (oldWindow && oldWindow.containerId !== window.containerId && oldWindow.containerId !== null)
windowRegistry = windowRegistry.deleteIn([ `entriesByContainerId`, oldWindow.containerId ]);
if (window.containerId !== null)
windowRegistry = windowRegistry.setIn([ `entriesByContainerId`, window.containerId ], window.id);
if (window.id >= windowRegistry.autoIncrement)
windowRegistry = windowRegistry.merge({ autoIncrement: window.id + 1 });
return this.applyRegistry(windowRegistry);
}
unsetWindow(windowId) {
let window = this.windowRegistry.getIn([ `entriesById`, windowId ], null);
if (!window)
return this;
let windowRegistry = this.windowRegistry.deleteIn([ `entriesById`, windowId ]);
if (window.containerId)
windowRegistry = windowRegistry.deleteIn([ `entriesByContainerId`, window.containerId ]);
return this.applyRegistry(windowRegistry);
}
applyRegistry(windowRegistry) {
if (windowRegistry !== this.windowRegistry) {
return new WindowRegistryPublicInterface(windowRegistry);
} else {
return this;
}
}
}
export function windowRegistry(state = new WindowRegistryPublicInterface(), action) {
switch (action.type) {
default: {
return state;
} break;
case WINDOW_SET: {
return state.setWindow(action.window);
} break;
case WINDOW_UNSET: {
return state.unsetWindow(action.windowId);
} break;
}
}
|
dbf467b71d2dca761b3c1799274405c8b00abd9d
|
[
"JavaScript"
] | 24
|
JavaScript
|
cideditor/cid
|
0bb0d159d8808fc417c94124530f098f6b0665ac
|
a06a9245ce119ac70ace0082cabe590d07598b4e
|
refs/heads/master
|
<file_sep>#pragma once
#include <vector>
#include "Tokenizador.h"
class Parser
{
public:
string Parse(vector<Token> parseTree);
private:
};
string Parser::Parse(vector<Token>parseTree)
{
Token primero;
Token next;
if (parseTree.size() <= 2) {
if (parseTree.size() == 1 && parseTree.front().tokenS == "heapback") {
parseTree.push_back(Token(28));
return "heapback";
}
else {
return "heapback";
}
}
if (parseTree.size() < 3) {
return "false";
}
primero = parseTree.front();
next = parseTree.at(1);
if (primero.tokenS == "repeat" && parseTree.at(2).num > 0) {
return "repeat";
}
if (primero.tokenS == "While")
{
if (parseTree.at(2).demeTipo() == variable && parseTree.at(2).tokenS[0] >= 97 && parseTree.at(2).tokenS[0] <= 122 && parseTree.at(2).tokenS.length() == 1) {
return "Whileasig";
}
return "";
}
if (primero.tipo == variable) {
if (primero.tokenS[0] >= 97 && primero.tokenS[0] <= 122 && primero.tokenS.length() == 1)
{
if (next.tokenC == '=') {
if (parseTree.at(2).tokenS == "new" && parseTree.at(3).tokenS == "Nodo") {
return "New Nodo";
}
else {
if (parseTree.at(2).tipo == numero) { return "valor"; }
else {
next = parseTree.at(2);
if (next.tokenS[0] >= 97 && next.tokenS[0] <= 122 && next.tokenS.length() == 1) {
return "Nodo a Nodo";
}
}
}
cout << "sif";
}
if (parseTree.at(3).tokenS == "sig" || parseTree.at(3).tokenS == "v") {
return "asignacion";
}
}
}
return "false";
};<file_sep>#include "Graph.h"
#include "Window.h"
#include "Simple_window.h"
using namespace Graph_lib;
class Node {
Graph_lib::Rectangle r{ Point{20,40},30,30 };
Graph_lib::Rectangle r2{ Point{50,40},30,30 };
Circle c{ Point(65, 55), 10 };
Text t{ Point{30,60},"" };
Text var{ Point{10,20},"" };
char nombre;
int valor;
int pos;
public:
Node(int num, int p) {
valor = num;
pos = p;
mov();
t.set_label(to_string(valor));
t.set_font(Font::times_bold);
t.set_color(Color::white);
c.set_color(Color::black);
c.set_fill_color(Color::blue);
r.set_color(Color::black);
r.set_fill_color(Color::blue);
r2.set_color(Color::black);
r2.set_fill_color(Color::yellow);
}
Node(int num, int p, char nom) {
valor = num;
nombre = nom;
sig = NULL;
pos = p;
mov();
var.set_label(to_string(nombre));
t.set_label(to_string(valor));
t.set_font(Font::times_bold);
t.set_color(Color::white);
var.set_font(Font::times_bold);
var.set_color(Color::black);
c.set_color(Color::black);
c.set_fill_color(Color::blue);
r.set_color(Color::black);
r.set_fill_color(Color::blue);
r2.set_color(Color::black);
r2.set_fill_color(Color::yellow);
}
Node(int num, int p, char nom, Node * h) {
valor = num;
nombre = nom;
sig = NULL;
pos = p;
mov();
sig = h;
var.set_label(to_string(nombre));
t.set_label(to_string(valor));
t.set_font(Font::times_bold);
t.set_color(Color::white);
var.set_font(Font::times_bold);
var.set_color(Color::black);
c.set_color(Color::black);
c.set_fill_color(Color::blue);
r.set_color(Color::black);
r.set_fill_color(Color::blue);
r2.set_color(Color::black);
r2.set_fill_color(Color::yellow);
}
void attach(Simple_window &win) {
win.attach(c);
win.attach(r);
win.attach(r2);
win.attach(t);
win.attach(var);
win.put_on_top(r2);
win.put_on_top(c);
win.put_on_top(t);
}
void detach(Simple_window &win) {
win.detach(c);
win.detach(r);
win.detach(r2);
win.detach(t);
win.detach(var);
}
int getPos() {
return pos;
}
void setPos(int p) {
pos = p;
mov();
}
void setValor(int x) {
valor = x;
}
int getValor() {
return valor;
}
char getNombre() {
return nombre;
}
Node* getSiguiente() {
return sig;
}
void setNombre(char c) {
nombre = c;
}
void mov() {
switch (pos) {
case 1:
break;
case 2:
r.move(100, 0);
var.move(100, 0);
r2.move(100, 0);
t.move(100, 0);
c.move(100, 0);
break;
case 3:
r.move(200, 0);
r2.move(200, 0);
t.move(200, 0);
c.move(200, 0);
var.move(200, 0);
break;
case 4:
r.move(300, 0);
r2.move(300, 0);
t.move(300, 0);
c.move(300, 0);
var.move(300, 0);
break;
case 5:
r.move(400, 0);
r2.move(400, 0);
t.move(400, 0);
c.move(400, 0);
var.move(400, 0);
break;
case 6:
r.move(500, 0);
r2.move(500, 0);
t.move(500, 0);
c.move(500, 0);
var.move(500, 0);
break;
case 7:
r.move(600, 0);
r2.move(600, 0);
t.move(600, 0);
c.move(600, 0);
var.move(600, 0);
break;
case 8:
r.move(0, 100);
r2.move(0, 100);
t.move(0, 100);
c.move(0, 100);
var.move(0, 100);
break;
case 9:
r.move(100, 100);
r2.move(100, 100);
t.move(100, 100);
c.move(100, 100);
var.move(100, 100);
break;
case 10:
r.move(200, 100);
r2.move(200, 100);
t.move(200, 100);
c.move(200, 100);
var.move(200, 100);
break;
case 11:
r.move(300, 100);
r2.move(300, 100);
t.move(300, 100);
c.move(300, 100);
var.move(300, 100);
break;
case 12:
r.move(400, 100);
r2.move(400, 100);
t.move(400, 100);
c.move(400, 100);
var.move(400, 100);
break;
case 13:
r.move(500, 100);
r2.move(500, 100);
t.move(500, 100);
c.move(500, 100);
var.move(500, 100);
break;
case 14:
r.move(600, 100);
r2.move(600, 100);
t.move(600, 100);
c.move(600, 100);
var.move(600, 100);
break;
case 15:
r.move(0, 200);
r2.move(0, 200);
t.move(0, 200);
c.move(0, 200);
var.move(0, 200);
break;
case 16:
r.move(100, 200);
r2.move(100, 200);
t.move(100, 200);
c.move(100, 200);
var.move(100, 200);
break;
case 17:
r.move(200, 200);
r2.move(200, 200);
t.move(200, 200);
c.move(200, 200);
var.move(200, 200);
break;
case 18:
r.move(300, 200);
r2.move(300, 200);
t.move(300, 200);
c.move(300, 200);
var.move(300, 200);
break;
case 19:
r.move(400, 200);
r2.move(400, 200);
t.move(400, 200);
c.move(400, 200);
var.move(400, 200);
break;
case 20:
r.move(500, 200);
r2.move(500, 200);
t.move(500, 200);
c.move(500, 200);
var.move(500, 200);
break;
case 21:
r.move(600, 200);
r2.move(600, 200);
t.move(600, 200);
c.move(600, 200);
var.move(600, 200);
break;
case 22:
r.move(0, 300);
r2.move(0, 300);
t.move(0, 300);
c.move(0, 300);
var.move(0, 300);
break;
case 23:
r.move(100, 300);
r2.move(100, 300);
t.move(100, 300);
c.move(100, 300);
var.move(100, 300);
break;
case 24:
r.move(200, 300);
r2.move(200, 300);
t.move(200, 300);
c.move(200, 300);
var.move(200, 300);
break;
case 25:
r.move(300, 300);
r2.move(300, 300);
t.move(300, 300);
c.move(300, 300);
var.move(300, 300);
break;
case 26:
r.move(400, 300);
r2.move(400, 300);
t.move(400, 300);
c.move(400, 300);
var.move(400, 300);
break;
case 27:
r.move(500, 300);
r2.move(500, 300);
t.move(500, 300);
c.move(500, 300);
var.move(500, 300);
break;
case 28:
r.move(600, 300);
r2.move(600, 300);
t.move(600, 300);
c.move(600, 300);
var.move(600, 300);
break;
default:
break;
}
return;
}
bool linea = false;
Node *sig;
};<file_sep>#include "Paraser.h"
#include "Tokenizador.h"
#include "LinePointer.h"
#include <random>
Node* nodos[28];
void crearNodo(int x, char nombre, Text &ops) {
Node* h = new Node(x, 1, nombre);
for (int i = 0; i < 28; i++) {
if (nodos[i] == 0) {
nodos[i] = h;
h->setPos(i + 1);
ops.set_label("Nodo creado");
return;
}
}
ops.set_label("Operacion fallida (Overflow)");
return;
}
void asignarValor(int x, char nombre, Text &ops) {
Node * sig = NULL;
for (int i = 0; i < 28; i++) {
if (nodos[i]) {
if (nodos[i]->getNombre() == nombre) {
sig = nodos[i]->getSiguiente();
}
}
}
Node* h = new Node(x, 1, nombre, sig);
for (int i = 0; i < 28; i++) {
if (nodos[i]) {
if (nodos[i]->getNombre() == nombre) {
delete(nodos[i]);
h->setPos(i);
nodos[i] = h;
ops.set_label("Valor asignado");
return;
}
}
}
ops.set_label("Operacion fallida");
return;
}
void asignarNombre(int i, int x) {
Node * h = new Node(x, i + 1);
delete(nodos[i]);
nodos[i] = h;
return;
}
void buscarValor(char nombre, int ciclos, Text &ops) {
for (int i = 0; i < 28; i++) {
if (nodos[i]) {
if (nodos[i]->getNombre() == nombre) {
Node * h = nodos[i];
while (ciclos != 0 && h) {
h = h->sig;
ciclos--;
}
if (h) { ops.set_label(to_string(h->getValor())); return; }
}
}
}
ops.set_label("Operacion fallida");
}
void borrarNodo(char c, Text &ops) {
for (int i = 0; i < 28; i++) {
if (nodos[i]) {
if (nodos[i]->getNombre() == c) {
delete(nodos[i]);
nodos[i] = 0;
ops.set_label("Nodo borrado");
return;
}
}
}
ops.set_label("Operacion fallida");
return;
}
void limpiarHeap(Text &ops) {
ops.set_label("Heap limpiado");
for (int i = 0; i < 28; i++) {
delete(nodos[i]);
nodos[i] = 0;
}
}
void whileasig(char nom, Text &ops) {
Node* asignado = 0;
for (int i = 0; i < 28; i++) {
if (nodos[i]) {
if (nodos[i]->getNombre() == nom) {
asignado = nodos[i];
}
}
}
int cont = 0;
while (asignado) {
cont++;
asignado = asignado->sig;
}
std::string msj = "Ciclo realizado " + std::to_string(cont) + " veces";
ops.set_label(msj);
}
void setSiguiente(char c1, char c2, int x1, int x2, int n1, bool esnum, bool esnew, Text &ops) {
Node* h1 = 0;
Node* h2 = 0;
for (int i = 0; i < 28; i++) {
if (nodos[i]) {
if (nodos[i]->getNombre() == c1) {
h1 = nodos[i];
}
if (nodos[i]->getNombre() == c2) {
h2 = nodos[i];
}
}
}
if (h1 || h2) {
while (x1 != 0 && h1) {
if (x1 == 1) {
break;
}
h1 = h1->sig;
x1--;
}
while (x2 != 0 && h2) {
h2 = h2->sig;
x2--;
}
if (esnum) {
if (c2 == 0) {
h1->sig = NULL;
ops.set_label("Siguiente asignado");
return;
}
else {
if (h1->sig) {
asignarValor(c2, h1->sig->getNombre(), ops);
ops.set_label("Siguiente asignado");
return;
}
else {
ops.set_label("Nodo nulo");
return;
}
}
}
if (esnew) {
crearNodo(n1, '?', ops);
for (int i = 0; i < 28; i++) {
if (nodos[i]) {
if (nodos[i]->getNombre() == '?') {
asignarNombre(i, n1);
h1->sig = nodos[i];
break;
}
}
}
if (ops.label() == "Operacion fallida") {
return;
}
ops.set_label("Nodo creado y asignado");
return;
}
if (h1 && h2) {
h1->sig = h2;
ops.set_label("Siguiente asignado");
return;
}
}
ops.set_label("Operacion fallida");
return;
}
int generarNumeroAleatorio() {
std::random_device rd;
std::mt19937 eng(rd());
std::uniform_int_distribution<> distr(0, 99);
return distr(eng);
}
void inicializarNodos() {
for (int i = 0; i < 28; i++) {
nodos[i] = 0;
}
return;
}
void abrirVentanaHeap() {
Point tl(100, 100);
Simple_window win(tl, 700, 400, "Heap");
int x_size = win.x_max();
int y_size = win.y_max();
int x_grid = 100;
int y_grid = 100;
Lines grid;
for (int x = x_grid; x < x_size; x += x_grid) {
grid.add(Point(x, 0), Point(x, y_size));
}
for (int y = y_grid; y < y_size; y += y_grid) {
grid.add(Point(0, y), Point(x_size, y));
}
grid.set_color(Color::blue);
grid.set_style(Line_style::dot);
win.attach(grid);
for (int i = 0; i < 28; i++) {
if (nodos[i] != 0) {
nodos[i]->attach(win);
draw_Line(nodos[i], win);
}
}
win.wait_for_button();
for (int i = 0; i < 28; i++) {
if (nodos[i] != 0) {
nodos[i]->detach(win);
}
}
}
vector<string> dividir(string tira) {
string final;
vector<string> vec;
for (int i = 10; i < tira.size(); i++) {
if (tira.at(i) == ';') {
vec.push_back(final);
final = "";
}
else {
final += tira.at(i);
}
}
vec.push_back(final);
return vec;
}
void parseNewNodo(Parser parser, vector<Token> parseTree, int heapback, Text &ops) {
if (heapback == 0) {
if (parseTree.at(5).tokenC == '_') {
int random = generarNumeroAleatorio();
crearNodo(random, parseTree.at(0).tokenS[0], ops);
}
else {
crearNodo(parseTree.at(5).num, parseTree.at(0).tokenS[0], ops);
}
}
else {
if (parseTree.at(5).tokenC == '_') {
int random = generarNumeroAleatorio();
nodos[heapback - 1] = new Node(random, heapback, parseTree.at(0).tokenS[0]);
heapback--;
}
else {
nodos[heapback - 1] = new Node(parseTree.at(5).num, heapback, parseTree.at(0).tokenS[0]);
heapback--;
}
}
return;
}
void parseAsignacion(Parser parser, vector<Token> parseTree, Text &ops) {
bool esnum = false;
bool esnew = false;
int ciclo = 0;
int ciclo2 = 0;
char c1 = parseTree.at(0).tokenS[0];
char c2 = '0';
int n1 = 0;
for (int i = 0; i < parseTree.size(); i++) {
if (parseTree.at(i).tokenS == "sig") {
ciclo++;
}
if (parseTree.at(i).tokenS[0] == 'v') {
if (parseTree.size() == i+2) {
buscarValor(parseTree.at(0).tokenS[0], ciclo, ops);
return;
}
i += 2;
if (parseTree.at(i).tipo == numero) {
asignarValor(parseTree.at(i).num, parseTree.at(0).tokenS[0], ops);
return;
}
else {
int z = i;
while (parseTree.at(z).tokenS[0] != 'v') {
if (parseTree.at(z).tokenS == "sig") {
ciclo2++;
}
z++;
}
for (int i2 = 0; i2 < 28; i2++) {
if (nodos[i2]) {
if (nodos[i2]->getNombre() == parseTree.at(i).tokenS[0]) {
asignarValor(nodos[i2]->getValor(), parseTree.at(0).tokenS[0], ops);
return;
}
}
}
ops.set_label("Operacion fallida");
return;
}
}
if (parseTree.at(i).tokenC == '=' && parseTree.at(i).demeTipo() == operador) {
i++;
if (parseTree.at(i).tipo == numero) {
c2 = parseTree.at(i).num;
esnum = true;
}
else {
if (parseTree.at(i).tokenS == "new" && parseTree.at(i + 1).tokenS == "Nodo") {
if (parseTree.at(i + 3).tokenC == '_') {
n1 = generarNumeroAleatorio();
}
else {
n1 = parseTree.at(i + 3).num;
}
esnew = true;
cout << c2 << endl;
}
else {
c2 = parseTree.at(i).tokenS[0];
}
}
for (i; i < parseTree.size(); i++) {
if (parseTree.at(i).tokenS == "sig") {
ciclo2++;
}
}
setSiguiente(c1, c2, ciclo, ciclo2, n1, esnum, esnew, ops);
break;
}
}
}
void parseValor(Parser parser, vector<Token> parseTree, Text &ops) {
if (parseTree.at(2).num != 0) {
asignarValor(parseTree.at(2).num, parseTree.at(0).tokenS[0], ops);
}
else {
borrarNodo(parseTree.at(0).tokenS[0], ops);
}
}
void parseNodoNodo(Parser parser, vector<Token> parseTree, Text &ops) {
Node * h1 = 0;
Node * h2 = 0;
int pos;
int x;
char nombre;
for (int i = 0; i < 28; i++) {
if (nodos[i]) {
if (nodos[i]->getNombre() == parseTree.at(0).tokenS[0]) {
h1 = nodos[i];
pos = i;
}
if (nodos[i]->getNombre() == parseTree.at(2).tokenS[0]) {
h2 = nodos[i];
nombre = h2->getNombre();
x = h2->getValor();
}
}
}
if (h1 && h2) {
nodos[pos] = 0;
delete(h1);
crearNodo(x, nombre, ops);
nodos[h2->getPos() - 1] = 0;
delete(h2);
}
else {
ops.set_label("Operacion fallida");
}
}
void abrirVentanaComandos() {
using namespace Graph_lib;
Point tl2(100, 100);
Simple_window win2(tl2, 500, 200, "Grid");
Text ops(Point(200, 25), "");
ops.set_color(Color::black);
ops.set_font(Font::times_bold);
int x_size = win2.x_max();
int y_size = win2.y_max();
int x_grid = 100;
int y_grid = 100;
Fl_Input textbox(10, 170, 200, 23, 0);
win2.add(textbox);
win2.attach(ops);
Vector<Token> parseTree;
Parser parser;
int heapback = 0;
while (true) {
win2.wait_for_button();
std::string input = textbox.value();
std::cout << input;
if (input == "heap") { abrirVentanaHeap(); continue; }
if (input == "exit") { break; }
if (input == "limpiar heap") { limpiarHeap(ops); continue; }
Tokenizador tokenizador(input);
Token t = tokenizador.demeToken();
while (t.demeTipo() != nulo) {
std::cout << t;
parseTree.push_back(t);
t = tokenizador.demeToken();
}
parseTree.push_back(t);
cout << parser.Parse(parseTree) << endl;
if (parser.Parse(parseTree) == "heapback") {
heapback = parseTree.at(1).num;
}
if (parser.Parse(parseTree) == "repeat") {
int repeats = parseTree.at(2).num;
Vector<Token> parseTree2;
vector<string> vec = dividir(input);
while (repeats != 0) {
for (int i = 0; i < vec.size(); i++) {
Tokenizador tokenizador2(vec.at(i));
Token t2 = tokenizador2.demeToken();
cout << parser.Parse(parseTree2) << endl;
while (t2.demeTipo() != nulo) {
std::cout << t2;
parseTree2.push_back(t2);
t2 = tokenizador2.demeToken();
}
parseTree2.push_back(t2);
if (parser.Parse(parseTree2) == "New Nodo") {
parseNewNodo(parser, parseTree2, heapback, ops);
}
if (parser.Parse(parseTree2) == "asignacion") {
parseAsignacion(parser, parseTree2, ops);
}
if (parser.Parse(parseTree2) == "valor") {
parseValor(parser, parseTree2, ops);
}
if (parser.Parse(parseTree2) == "Nodo a Nodo") {
parseNodoNodo(parser, parseTree2, ops);
}
}
repeats--;
}
}
if (parser.Parse(parseTree) == "Whileasig") {
char c1;
c1 = parseTree.at(2).tokenS[0];
whileasig(c1, ops);
}
if (parser.Parse(parseTree) == "false") {
ops.set_label("Operacion no reconocida");
}
if (parser.Parse(parseTree) == "New Nodo") {
parseNewNodo(parser, parseTree, heapback, ops);
}
if (parser.Parse(parseTree) == "asignacion") {
parseAsignacion(parser, parseTree, ops);
}
if (parser.Parse(parseTree) == "valor") {
parseValor(parser, parseTree, ops);
}
if (parser.Parse(parseTree) == "Nodo a Nodo") {
parseNodoNodo(parser, parseTree, ops);
}
tokenizador = Tokenizador("reset reset");
t = tokenizador.demeToken();
while (t.demeTipo() != nulo) {
parseTree.push_back(t);
t = tokenizador.demeToken();
}
while (parseTree.size() != 0) {
parseTree.pop_back();
}
abrirVentanaHeap();
}
}
int main()
{
inicializarNodos();
abrirVentanaComandos();
};<file_sep>#include "Node.h"
#include <iostream>
using namespace Graph_lib;
void draw_Line(Node *nodo, Simple_window &win) {
static Open_polyline opl1;
opl1.set_color(Color::black);
static Open_polyline opl2_1;
opl2_1.set_color(Color::black);
static Open_polyline opl2;
opl2.set_color(Color::blue);
static Open_polyline opl2_2;
opl2_2.set_color(Color::blue);
static Open_polyline opl3;
opl3.set_color(Color::green);
static Open_polyline opl2_3;
opl2_3.set_color(Color::green);
static Open_polyline opl4;
opl4.set_color(Color::red);
static Open_polyline opl2_4;
opl2_4.set_color(Color::red);
static Open_polyline opl5;
opl5.set_color(Color::dark_yellow);
static Open_polyline opl2_5;
opl2_5.set_color(Color::dark_yellow);
static Open_polyline opl6;
opl6.set_color(Color::cyan);
static Open_polyline opl2_6;
opl2_6.set_color(Color::cyan);
static Open_polyline opl7;
opl7.set_color(Color::magenta);
static Open_polyline opl2_7;
opl2_7.set_color(Color::magenta);
static Open_polyline opl8;
opl8.set_color(Color::dark_blue);
static Open_polyline opl2_8;
opl2_8.set_color(Color::dark_blue);
static Open_polyline opl9;
opl9.set_color(Color::white);
static Open_polyline opl2_9;
opl2_9.set_color(Color::white);
static Open_polyline opl10;
opl10.set_color(Color::dark_green);
static Open_polyline opl2_10;
opl2_10.set_color(Color::dark_green);
static Open_polyline opl11;
opl11.set_color(Color::black);
static Open_polyline opl2_11;
opl2_11.set_color(Color::black);
static Open_polyline opl12;
opl12.set_color(Color::black);
static Open_polyline opl2_12;
opl2_12.set_color(Color::black);
static Open_polyline opl13;
opl13.set_color(Color::black);
static Open_polyline opl2_13;
opl2_13.set_color(Color::black);
static Open_polyline opl14;
opl14.set_color(Color::black);
static Open_polyline opl2_14;
opl2_14.set_color(Color::black);
static Open_polyline opl15;
opl15.set_color(Color::black);
static Open_polyline opl2_15;
opl2_15.set_color(Color::black);
static Open_polyline opl16;
opl16.set_color(Color::black);
static Open_polyline opl2_16;
opl2_16.set_color(Color::black);
static Open_polyline opl17;
opl17.set_color(Color::black);
static Open_polyline opl2_17;
opl2_17.set_color(Color::black);
static Open_polyline opl18;
opl18.set_color(Color::black);
static Open_polyline opl2_18;
opl2_18.set_color(Color::black);
static Open_polyline opl19;
opl19.set_color(Color::black);
static Open_polyline opl2_19;
opl2_19.set_color(Color::black);
static Open_polyline opl20;
opl20.set_color(Color::black);
static Open_polyline opl2_20;
opl2_20.set_color(Color::black);
static Open_polyline opl21;
opl21.set_color(Color::black);
static Open_polyline opl2_21;
opl2_21.set_color(Color::black);
static Open_polyline opl22;
opl22.set_color(Color::black);
static Open_polyline opl2_22;
opl2_22.set_color(Color::black);
static Open_polyline opl23;
opl23.set_color(Color::black);
static Open_polyline opl2_23;
opl2_23.set_color(Color::black);
static Open_polyline opl24;
opl24.set_color(Color::black);
static Open_polyline opl2_24;
opl2_24.set_color(Color::black);
static Open_polyline opl25;
opl25.set_color(Color::black);
static Open_polyline opl2_25;
opl2_25.set_color(Color::black);
static Open_polyline opl26;
opl26.set_color(Color::black);
static Open_polyline opl2_26;
opl2_26.set_color(Color::black);
static Open_polyline opl27;
opl27.set_color(Color::black);
static Open_polyline opl2_27;
opl2_27.set_color(Color::black);
static Open_polyline opl28;
opl28.set_color(Color::black);
static Open_polyline opl2_28;
opl2_28.set_color(Color::black);
int pos = nodo->getPos();
int sPos = 0;
int posFija = pos;
int sPosFija;
int fila;
int filapos;
if(!nodo->linea){
if (nodo->sig) {
nodo->linea = true;
sPos = nodo->sig->getPos();
sPosFija = sPos;
}
else {
return;
}
if (pos <= 7)
filapos = 55;
else if (pos > 7 && pos <= 14)
{
filapos = 155;
pos = pos - 7;
}
else if (pos > 14 && pos <= 21)
{
filapos = 255;
pos = pos - 14;
}
else
{
filapos = 355;
pos = pos - 21;
}
if (sPosFija <= 7)
fila = 55;
else if (sPosFija > 7 && sPosFija <= 14)
{
sPos = sPos - 7;
fila = 155;
}
else if (sPosFija > 14 && sPosFija <= 21)
{
sPos = sPos - 14;
fila = 255;
}
else
{
fila = 355;
sPos = sPos - 21;
}
if (sPosFija == posFija + 1) {
switch (pos)
{
case 1:
opl1.add(Point(((pos - 1) * 100) + 80, filapos));
opl1.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl1);
break;
case 2:
opl2.add(Point(((pos - 1) * 100) + 80, filapos));
opl2.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl2);
break;
case 3:
opl3.add(Point(((pos - 1) * 100) + 80, filapos));
opl3.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl3);
break;
case 4:
opl4.add(Point(((pos - 1) * 100) + 80, filapos));
opl4.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl4);
break;
case 5:
opl5.add(Point(((pos - 1) * 100) + 80, filapos));
opl5.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl5);
break;
case 6:
opl6.add(Point(((pos - 1) * 100) + 80, filapos));
opl6.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl6);
break;
case 7:
opl7.add(Point(((pos - 1) * 100) + 80, filapos));
opl7.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl7);
break;
case 8:
opl8.add(Point(((pos - 1) * 100) + 80, filapos));
opl8.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl8);
break;
case 9:
opl9.add(Point(((pos - 1) * 100) + 80, filapos));
opl9.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl9);
break;
case 10:
opl10.add(Point(((pos - 1) * 100) + 80, filapos));
opl10.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl10);
break;
case 11:
opl11.add(Point(((pos - 1) * 100) + 80, filapos));
opl11.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl11);
break;
case 12:
opl12.add(Point(((pos - 1) * 100) + 80, filapos));
opl12.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl12);
break;
case 13:
opl13.add(Point(((pos - 1) * 100) + 80, filapos));
opl13.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl13);
break;
case 14:
opl14.add(Point(((pos - 1) * 100) + 80, filapos));
opl14.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl14);
break;
case 15:
opl15.add(Point(((pos - 1) * 100) + 80, filapos));
opl15.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl15);
break;
case 16:
opl16.add(Point(((pos - 1) * 100) + 80, filapos));
opl16.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl16);
break;
case 17:
opl7.add(Point(((pos - 1) * 100) + 80, filapos));
opl7.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl8);
break;
case 18:
opl8.add(Point(((pos - 1) * 100) + 80, filapos));
opl8.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl8);
break;
case 19:
opl19.add(Point(((pos - 1) * 100) + 80, filapos));
opl19.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl19);
break;
case 20:
opl20.add(Point(((pos - 1) * 100) + 80, filapos));
opl20.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl20);
break;
case 21:
opl21.add(Point(((pos - 1) * 100) + 80, filapos));
opl21.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl21);
break;
case 22:
opl22.add(Point(((pos - 1) * 100) + 80, filapos));
opl22.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl22);
break;
case 23:
opl23.add(Point(((pos - 1) * 100) + 80, filapos));
opl23.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl23);
break;
case 24:
opl24.add(Point(((pos - 1) * 100) + 80, filapos));
opl24.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl24);
break;
case 25:
opl25.add(Point(((pos - 1) * 100) + 80, filapos));
opl25.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl25);
break;
case 26:
opl26.add(Point(((pos - 1) * 100) + 80, filapos));
opl26.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl26);
break;
case 27:
opl27.add(Point(((pos - 1) * 100) + 80, filapos));
opl27.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl27);
break;
case 28:
opl28.add(Point(((pos - 1) * 100) + 80, filapos));
opl28.add(Point(((sPos - 1) * 100) + 20, filapos));
win.attach(opl28);
break;
}
}
else {
if (sPosFija <= 7) {
switch (pos)
{
case 1:
opl1.add(Point(((pos - 1) * 100) + 80, filapos));
opl1.add(Point(pos * 100, filapos));
opl1.add(Point(pos * 100, filapos - 25));
opl1.add(Point((sPos - 1) * 100, fila - 25));
opl1.add(Point((sPos - 1) * 100, fila));
opl1.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl1);
break;
case 2:
opl2.add(Point(((pos - 1) * 100) + 80, filapos));
opl2.add(Point(pos * 100, filapos));
opl2.add(Point(pos * 100, filapos - 25));
opl2.add(Point((sPos - 1) * 100, fila - 25));
opl2.add(Point((sPos - 1) * 100, fila));
opl2.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl2);
break;
case 3:
opl3.add(Point(((pos - 1) * 100) + 80, filapos));
opl3.add(Point(pos * 100, filapos));
opl3.add(Point(pos * 100, filapos - 25));
opl3.add(Point((sPos - 1) * 100, fila - 25));
opl3.add(Point((sPos - 1) * 100, fila));
opl3.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl3);
break;
case 4:
opl4.add(Point(((pos - 1) * 100) + 80, filapos));
opl4.add(Point(pos * 100, filapos));
opl4.add(Point(pos * 100, filapos - 25));
opl4.add(Point((sPos - 1) * 100, fila - 25));
opl4.add(Point((sPos - 1) * 100, fila));
opl4.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl4);
break;
case 5:
opl5.add(Point(((pos - 1) * 100) + 80, filapos));
opl5.add(Point(pos * 100, filapos));
opl5.add(Point(pos * 100, filapos - 25));
opl5.add(Point((sPos - 1) * 100, fila - 25));
opl5.add(Point((sPos - 1) * 100, fila));
opl5.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl5);
break;
case 6:
opl6.add(Point(((pos - 1) * 100) + 80, filapos));
opl6.add(Point(pos * 100, filapos));
opl6.add(Point(pos * 100, filapos - 25));
opl6.add(Point((sPos - 1) * 100, fila - 25));
opl6.add(Point((sPos - 1) * 100, fila));
opl6.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl6);
break;
case 7:
opl7.add(Point(((pos - 1) * 100) + 80, filapos));
opl7.add(Point(pos * 100, filapos));
opl7.add(Point(pos * 100, filapos - 25));
opl7.add(Point((sPos - 1) * 100, fila - 25));
opl7.add(Point((sPos - 1) * 100, fila));
opl7.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl7);
break;
case 8:
opl8.add(Point(((pos - 1) * 100) + 80, filapos));
opl8.add(Point(pos * 100, filapos));
opl8.add(Point(pos * 100, filapos - 25));
opl8.add(Point((sPos - 1) * 100, fila - 25));
opl8.add(Point((sPos - 1) * 100, fila));
opl8.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl8);
break;
case 9:
opl9.add(Point(((pos - 1) * 100) + 80, filapos));
opl9.add(Point(pos * 100, filapos));
opl9.add(Point(pos * 100, filapos - 25));
opl9.add(Point((sPos - 1) * 100, fila - 25));
opl9.add(Point((sPos - 1) * 100, fila));
opl9.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl9);
break;
case 10:
opl10.add(Point(((pos - 1) * 100) + 80, filapos));
opl10.add(Point(pos * 100, filapos));
opl10.add(Point(pos * 100, filapos - 25));
opl10.add(Point((sPos - 1) * 100, fila - 25));
opl10.add(Point((sPos - 1) * 100, fila));
opl10.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl10);
break;
case 11:
opl11.add(Point(((pos - 1) * 100) + 80, filapos));
opl11.add(Point(pos * 100, filapos));
opl11.add(Point(pos * 100, filapos - 25));
opl11.add(Point((sPos - 1) * 100, fila - 25));
opl11.add(Point((sPos - 1) * 100, fila));
opl11.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl11);
break;
case 12:
opl12.add(Point(((pos - 1) * 100) + 80, filapos));
opl12.add(Point(pos * 100, filapos));
opl12.add(Point(pos * 100, filapos - 25));
opl12.add(Point((sPos - 1) * 100, fila - 25));
opl12.add(Point((sPos - 1) * 100, fila));
opl12.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl12);
break;
case 13:
opl13.add(Point(((pos - 1) * 100) + 80, filapos));
opl13.add(Point(pos * 100, filapos));
opl13.add(Point(pos * 100, filapos - 25));
opl13.add(Point((sPos - 1) * 100, fila - 25));
opl13.add(Point((sPos - 1) * 100, fila));
opl13.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl13);
break;
case 14:
opl14.add(Point(((pos - 1) * 100) + 80, filapos));
opl14.add(Point(pos * 100, filapos));
opl14.add(Point(pos * 100, filapos - 25));
opl14.add(Point((sPos - 1) * 100, fila - 25));
opl14.add(Point((sPos - 1) * 100, fila));
opl14.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl14);
break;
case 15:
opl15.add(Point(((pos - 1) * 100) + 80, filapos));
opl15.add(Point(pos * 100, filapos));
opl15.add(Point(pos * 100, filapos - 25));
opl15.add(Point((sPos - 1) * 100, fila - 25));
opl15.add(Point((sPos - 1) * 100, fila));
opl15.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl15);
break;
case 16:
opl16.add(Point(((pos - 1) * 100) + 80, filapos));
opl16.add(Point(pos * 100, filapos));
opl16.add(Point(pos * 100, filapos - 25));
opl16.add(Point((sPos - 1) * 100, fila - 25));
opl16.add(Point((sPos - 1) * 100, fila));
opl16.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl16);
break;
case 17:
opl17.add(Point(((pos - 1) * 100) + 80, filapos));
opl17.add(Point(pos * 100, filapos));
opl17.add(Point(pos * 100, filapos - 25));
opl17.add(Point((sPos - 1) * 100, fila - 25));
opl17.add(Point((sPos - 1) * 100, fila));
opl17.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl17);
break;
case 18:
opl18.add(Point(((pos - 1) * 100) + 80, filapos));
opl18.add(Point(pos * 100, filapos));
opl18.add(Point(pos * 100, filapos - 25));
opl18.add(Point((sPos - 1) * 100, fila - 25));
opl18.add(Point((sPos - 1) * 100, fila));
opl18.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl18);
break;
case 19:
opl19.add(Point(((pos - 1) * 100) + 80, filapos));
opl19.add(Point(pos * 100, filapos));
opl19.add(Point(pos * 100, filapos - 25));
opl19.add(Point((sPos - 1) * 100, fila - 25));
opl19.add(Point((sPos - 1) * 100, fila));
opl19.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl19);
break;
case 20:
opl20.add(Point(((pos - 1) * 100) + 80, filapos));
opl20.add(Point(pos * 100, filapos));
opl20.add(Point(pos * 100, filapos - 25));
opl20.add(Point((sPos - 1) * 100, fila - 25));
opl20.add(Point((sPos - 1) * 100, fila));
opl20.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl20);
break;
case 21:
opl21.add(Point(((pos - 1) * 100) + 80, filapos));
opl21.add(Point(((pos - 1) * 100) + 80, filapos));
opl21.add(Point(pos * 100, filapos));
opl21.add(Point(pos * 100, filapos - 25));
opl21.add(Point((sPos - 1) * 100, fila - 25));
opl21.add(Point((sPos - 1) * 100, fila));
opl21.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl21);
break;
case 22:
opl22.add(Point(((pos - 1) * 100) + 80, filapos));
opl22.add(Point(pos * 100, filapos));
opl22.add(Point(pos * 100, filapos - 25));
opl22.add(Point((sPos - 1) * 100, fila - 25));
opl22.add(Point((sPos - 1) * 100, fila));
opl22.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl22);
break;
case 23:
opl23.add(Point(((pos - 1) * 100) + 80, filapos));
opl23.add(Point(pos * 100, filapos));
opl23.add(Point(pos * 100, filapos - 25));
opl23.add(Point((sPos - 1) * 100, fila - 25));
opl23.add(Point((sPos - 1) * 100, fila));
opl23.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl23);
break;
case 24:
opl24.add(Point(((pos - 1) * 100) + 80, filapos));
opl24.add(Point(pos * 100, filapos));
opl24.add(Point(pos * 100, filapos - 25));
opl24.add(Point((sPos - 1) * 100, fila - 25));
opl24.add(Point((sPos - 1) * 100, fila));
opl24.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl24);
break;
case 25:
opl25.add(Point(((pos - 1) * 100) + 80, filapos));
opl25.add(Point(pos * 100, filapos));
opl25.add(Point(pos * 100, filapos - 25));
opl25.add(Point((sPos - 1) * 100, fila - 25));
opl25.add(Point((sPos - 1) * 100, fila));
opl25.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl25);
break;
case 26:
opl26.add(Point(((pos - 1) * 100) + 80, filapos));
opl26.add(Point(pos * 100, filapos));
opl26.add(Point(pos * 100, filapos - 25));
opl26.add(Point((sPos - 1) * 100, fila - 25));
opl26.add(Point((sPos - 1) * 100, fila));
opl26.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl26);
break;
case 27:
opl27.add(Point(((pos - 1) * 100) + 80, filapos));
opl27.add(Point(pos * 100, filapos));
opl27.add(Point(pos * 100, filapos - 25));
opl27.add(Point((sPos - 1) * 100, fila - 25));
opl27.add(Point((sPos - 1) * 100, fila));
opl27.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl27);
break;
case 28:
opl28.add(Point(((pos - 1) * 100) + 80, filapos));
opl28.add(Point(pos * 100, filapos));
opl28.add(Point(pos * 100, filapos - 25));
opl28.add(Point((sPos - 1) * 100, fila - 25));
opl28.add(Point((sPos - 1) * 100, fila));
opl28.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl28);
break;
}
}
else if (sPosFija > 7 && sPosFija <= 14)
{
switch (pos)
{
case 1:
opl1.add(Point(((pos - 1) * 100) + 80, filapos));
opl1.add(Point(pos * 100, filapos));
opl1.add(Point(pos * 100, filapos - 25));
opl1.add(Point(1000, filapos - 25));
opl2_1.add(Point(5, (fila - 25)));
opl2_1.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_1.add(Point((sPos - 1) * 100, fila));
opl2_1.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl1);
win.attach(opl2_1);
break;
case 2:
opl2.add(Point(((pos - 1) * 100) + 80, filapos));
opl2.add(Point(pos * 100, filapos));
opl2.add(Point(pos * 100, filapos - 25));
opl2.add(Point(1000, filapos - 25));
opl2_2.add(Point(5, (fila - 25)));
opl2_2.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_2.add(Point((sPos - 1) * 100, fila));
opl2_2.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl2);
win.attach(opl2_2);
break;
case 3:
opl3.add(Point(((pos - 1) * 100) + 80, filapos));
opl3.add(Point(pos * 100, filapos));
opl3.add(Point(pos * 100, filapos - 25));
opl3.add(Point(1000, filapos - 25));
opl2_3.add(Point(5, (fila - 25)));
opl2_3.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_3.add(Point((sPos - 1) * 100, fila));
opl2_3.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl3);
win.attach(opl2_3);
break;
case 4:
opl4.add(Point(((pos - 1) * 100) + 80, filapos));
opl4.add(Point(pos * 100, filapos));
opl4.add(Point(pos * 100, filapos - 25));
opl4.add(Point(1000, filapos - 25));
opl2_4.add(Point(5, (fila - 25)));
opl2_4.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_4.add(Point((sPos - 1) * 100, fila));
opl2_4.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl4);
win.attach(opl2_4);
break;
case 5:
opl5.add(Point(((pos - 1) * 100) + 80, filapos));
opl5.add(Point(pos * 100, filapos));
opl5.add(Point(pos * 100, filapos - 25));
opl5.add(Point(1000, filapos - 25));
opl2_5.add(Point(5, (fila - 25)));
opl2_5.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_5.add(Point((sPos - 1) * 100, fila));
opl2_5.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl5);
win.attach(opl2_5);
break;
case 6:
opl6.add(Point(((pos - 1) * 100) + 80, filapos));
opl6.add(Point(pos * 100, filapos));
opl6.add(Point(pos * 100, filapos - 25));
opl6.add(Point(1000, filapos - 25));
opl2_6.add(Point(5, (fila - 25)));
opl2_6.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_6.add(Point((sPos - 1) * 100, fila));
opl2_6.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl6);
win.attach(opl2_6);
break;
case 7:
opl7.add(Point(((pos - 1) * 100) + 80, filapos));
opl7.add(Point(pos * 100, filapos));
opl7.add(Point(pos * 100, filapos - 25));
opl7.add(Point(1000, filapos - 25));
opl2_7.add(Point(5, (fila - 25)));
opl2_7.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_7.add(Point((sPos - 1) * 100, fila));
opl2_7.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl7);
win.attach(opl2_7);
break;
case 8:
opl8.add(Point(((pos - 1) * 100) + 80, filapos));
opl8.add(Point(pos * 100, filapos));
opl8.add(Point(pos * 100, filapos - 25));
opl8.add(Point(1000, filapos - 25));
opl2_8.add(Point(5, (fila - 25)));
opl2_8.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_8.add(Point((sPos - 1) * 100, fila));
opl2_8.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl8);
win.attach(opl2_8);
break;
case 9:
opl9.add(Point(((pos - 1) * 100) + 80, filapos));
opl9.add(Point(pos * 100, filapos));
opl9.add(Point(pos * 100, filapos - 25));
opl9.add(Point(1000, filapos - 25));
opl2_9.add(Point(5, (fila - 25)));
opl2_9.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_9.add(Point((sPos - 1) * 100, fila));
opl2_9.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl9);
win.attach(opl2_9);
break;
case 10:
opl10.add(Point(((pos - 1) * 100) + 80, filapos));
opl10.add(Point(pos * 100, filapos));
opl10.add(Point(pos * 100, filapos - 25));
opl10.add(Point(1000, filapos - 25));
opl2_10.add(Point(5, (fila - 25)));
opl2_10.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_10.add(Point((sPos - 1) * 100, fila));
opl2_10.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl10);
win.attach(opl2_10);
break;
case 11:
opl11.add(Point(((pos - 1) * 100) + 80, filapos));
opl11.add(Point(pos * 100, filapos));
opl11.add(Point(pos * 100, filapos - 25));
opl11.add(Point(1000, filapos - 25));
opl2_11.add(Point(5, (fila - 25)));
opl2_11.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_11.add(Point((sPos - 1) * 100, fila));
opl2_11.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl11);
win.attach(opl2_11);
break;
case 12:
opl12.add(Point(((pos - 1) * 100) + 80, filapos));
opl12.add(Point(pos * 100, filapos));
opl12.add(Point(pos * 100, filapos - 25));
opl12.add(Point(1000, filapos - 25));
opl2_12.add(Point(5, (fila - 25)));
opl2_12.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_12.add(Point((sPos - 1) * 100, fila));
opl2_12.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl12);
win.attach(opl2_12);
break;
case 13:
opl13.add(Point(((pos - 1) * 100) + 80, filapos));
opl13.add(Point(pos * 100, filapos));
opl13.add(Point(pos * 100, filapos - 25));
opl13.add(Point(1000, filapos - 25));
opl2_13.add(Point(5, (fila - 25)));
opl2_13.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_13.add(Point((sPos - 1) * 100, fila));
opl2_13.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl13);
win.attach(opl2_13);
break;
case 14:
opl14.add(Point(((pos - 1) * 100) + 80, filapos));
opl14.add(Point(pos * 100, filapos));
opl14.add(Point(pos * 100, filapos - 25));
opl14.add(Point(1000, filapos - 25));
opl2_14.add(Point(5, (fila - 25)));
opl2_14.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_14.add(Point((sPos - 1) * 100, fila));
opl2_14.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl14);
win.attach(opl2_14);
break;
case 15:
opl15.add(Point(((pos - 1) * 100) + 80, filapos));
opl15.add(Point(pos * 100, filapos));
opl15.add(Point(pos * 100, filapos - 25));
opl15.add(Point(1000, filapos - 25));
opl2_15.add(Point(5, (fila - 25)));
opl2_15.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_15.add(Point((sPos - 1) * 100, fila));
opl2_15.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl15);
win.attach(opl2_15);
break;
case 16:
opl16.add(Point(((pos - 1) * 100) + 80, filapos));
opl16.add(Point(pos * 100, filapos));
opl16.add(Point(pos * 100, filapos - 25));
opl16.add(Point(1000, filapos - 25));
opl2_16.add(Point(5, (fila - 25)));
opl2_16.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_16.add(Point((sPos - 1) * 100, fila));
opl2_16.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl16);
win.attach(opl2_16);
break;
case 17:
opl17.add(Point(((pos - 1) * 100) + 80, filapos));
opl17.add(Point(pos * 100, filapos));
opl17.add(Point(pos * 100, filapos - 25));
opl17.add(Point(1000, filapos - 25));
opl2_17.add(Point(5, (fila - 25)));
opl2_17.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_17.add(Point((sPos - 1) * 100, fila));
opl2_17.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl17);
win.attach(opl2_17);
break;
case 18:
opl18.add(Point(((pos - 1) * 100) + 80, filapos));
opl18.add(Point(pos * 100, filapos));
opl18.add(Point(pos * 100, filapos - 25));
opl18.add(Point(1000, filapos - 25));
opl2_18.add(Point(5, (fila - 25)));
opl2_18.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_18.add(Point((sPos - 1) * 100, fila));
opl2_18.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl18);
win.attach(opl2_18);
break;
case 19:
opl19.add(Point(((pos - 1) * 100) + 80, filapos));
opl19.add(Point(pos * 100, filapos));
opl19.add(Point(pos * 100, filapos - 25));
opl19.add(Point(1000, filapos - 25));
opl2_19.add(Point(5, (fila - 25)));
opl2_19.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_19.add(Point((sPos - 1) * 100, fila));
opl2_19.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl19);
win.attach(opl2_19);
break;
case 20:
opl20.add(Point(((pos - 1) * 100) + 80, filapos));
opl20.add(Point(pos * 100, filapos));
opl20.add(Point(pos * 100, filapos - 25));
opl20.add(Point(1000, filapos - 25));
opl2_20.add(Point(5, (fila - 25)));
opl2_20.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_20.add(Point((sPos - 1) * 100, fila));
opl2_20.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl20);
win.attach(opl2_20);
break;
case 21:
opl21.add(Point(((pos - 1) * 100) + 80, filapos));
opl21.add(Point(pos * 100, filapos));
opl21.add(Point(pos * 100, filapos - 25));
opl21.add(Point(1000, filapos - 25));
opl2_21.add(Point(5, (fila - 25)));
opl2_21.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_21.add(Point((sPos - 1) * 100, fila));
opl2_21.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl21);
win.attach(opl2_21);
break;
case 22:
opl22.add(Point(((pos - 1) * 100) + 80, filapos));
opl22.add(Point(pos * 100, filapos));
opl22.add(Point(pos * 100, filapos - 25));
opl22.add(Point(1000, filapos - 25));
opl2_22.add(Point(5, (fila - 25)));
opl2_22.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_22.add(Point((sPos - 1) * 100, fila));
opl2_22.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl22);
win.attach(opl2_22);
break;
case 23:
opl23.add(Point(((pos - 1) * 100) + 80, filapos));
opl23.add(Point(pos * 100, filapos));
opl23.add(Point(pos * 100, filapos - 25));
opl23.add(Point(1000, filapos - 25));
opl2_23.add(Point(5, (fila - 25)));
opl2_23.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_23.add(Point((sPos - 1) * 100, fila));
opl2_23.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl23);
win.attach(opl2_23);
break;
case 24:
opl24.add(Point(((pos - 1) * 100) + 80, filapos));
opl24.add(Point(pos * 100, filapos));
opl24.add(Point(pos * 100, filapos - 25));
opl24.add(Point(1000, filapos - 25));
opl2_24.add(Point(5, (fila - 25)));
opl2_24.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_24.add(Point((sPos - 1) * 100, fila));
opl2_24.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl24);
win.attach(opl2_24);
break;
case 25:
opl25.add(Point(((pos - 1) * 100) + 80, filapos));
opl25.add(Point(pos * 100, filapos));
opl25.add(Point(pos * 100, filapos - 25));
opl25.add(Point(1000, filapos - 25));
opl2_25.add(Point(5, (fila - 25)));
opl2_25.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_25.add(Point((sPos - 1) * 100, fila));
opl2_25.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl25);
win.attach(opl2_25);
break;
case 26:
opl26.add(Point(((pos - 1) * 100) + 80, filapos));
opl26.add(Point(pos * 100, filapos));
opl26.add(Point(pos * 100, filapos - 25));
opl26.add(Point(1000, filapos - 25));
opl2_26.add(Point(5, (fila - 25)));
opl2_26.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_26.add(Point((sPos - 1) * 100, fila));
opl2_26.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl26);
win.attach(opl2_26);
break;
case 27:
opl27.add(Point(((pos - 1) * 100) + 80, filapos));
opl27.add(Point(pos * 100, filapos));
opl27.add(Point(pos * 100, filapos - 25));
opl27.add(Point(1000, filapos - 25));
opl2_27.add(Point(5, (fila - 25)));
opl2_27.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_27.add(Point((sPos - 1) * 100, fila));
opl2_27.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl27);
win.attach(opl2_27);
break;
case 28:
opl28.add(Point(((pos - 1) * 100) + 80, filapos));
opl28.add(Point(pos * 100, filapos));
opl28.add(Point(pos * 100, filapos - 25));
opl28.add(Point(1000, filapos - 25));
opl2_28.add(Point(5, (fila - 25)));
opl2_28.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_28.add(Point((sPos - 1) * 100, fila));
opl2_28.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl28);
win.attach(opl2_28);
break;
}
}
else if (sPosFija > 14 && sPosFija <= 21)
{
switch (pos)
{
case 1:
opl1.add(Point(((pos - 1) * 100) + 80, filapos));
opl1.add(Point(pos * 100, filapos));
opl1.add(Point(pos * 100, filapos - 25));
opl1.add(Point(1000, filapos - 25));
opl2_1.add(Point(5, (fila - 25)));
opl2_1.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_1.add(Point((sPos - 1) * 100, fila));
opl2_1.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl1);
win.attach(opl2_1);
break;
case 2:
opl2.add(Point(((pos - 1) * 100) + 80, filapos));
opl2.add(Point(pos * 100, filapos));
opl2.add(Point(pos * 100, filapos - 25));
opl2.add(Point(1000, filapos - 25));
opl2_2.add(Point(5, (fila - 25)));
opl2_2.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_2.add(Point((sPos - 1) * 100, fila));
opl2_2.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl2);
win.attach(opl2_2);
break;
case 3:
opl3.add(Point(((pos - 1) * 100) + 80, filapos));
opl3.add(Point(pos * 100, filapos));
opl3.add(Point(pos * 100, filapos - 25));
opl3.add(Point(1000, filapos - 25));
opl2_3.add(Point(5, (fila - 25)));
opl2_3.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_3.add(Point((sPos - 1) * 100, fila));
opl2_3.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl3);
win.attach(opl2_3);
break;
case 4:
opl4.add(Point(((pos - 1) * 100) + 80, filapos));
opl4.add(Point(pos * 100, filapos));
opl4.add(Point(pos * 100, filapos - 25));
opl4.add(Point(1000, filapos - 25));
opl2_4.add(Point(5, (fila - 25)));
opl2_4.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_4.add(Point((sPos - 1) * 100, fila));
opl2_4.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl4);
win.attach(opl2_4);
break;
case 5:
opl5.add(Point(((pos - 1) * 100) + 80, filapos));
opl5.add(Point(pos * 100, filapos));
opl5.add(Point(pos * 100, filapos - 25));
opl5.add(Point(1000, filapos - 25));
opl2_5.add(Point(5, (fila - 25)));
opl2_5.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_5.add(Point((sPos - 1) * 100, fila));
opl2_5.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl5);
win.attach(opl2_5);
break;
case 6:
opl6.add(Point(((pos - 1) * 100) + 80, filapos));
opl6.add(Point(pos * 100, filapos));
opl6.add(Point(pos * 100, filapos - 25));
opl6.add(Point(1000, filapos - 25));
opl2_6.add(Point(5, (fila - 25)));
opl2_6.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_6.add(Point((sPos - 1) * 100, fila));
opl2_6.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl6);
win.attach(opl2_6);
break;
case 7:
opl7.add(Point(((pos - 1) * 100) + 80, filapos));
opl7.add(Point(pos * 100, filapos));
opl7.add(Point(pos * 100, filapos - 25));
opl7.add(Point(1000, filapos - 25));
opl2_7.add(Point(5, (fila - 25)));
opl2_7.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_7.add(Point((sPos - 1) * 100, fila));
opl2_7.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl7);
win.attach(opl2_7);
break;
case 8:
opl8.add(Point(((pos - 1) * 100) + 80, filapos));
opl8.add(Point(pos * 100, filapos));
opl8.add(Point(pos * 100, filapos - 25));
opl8.add(Point(1000, filapos - 25));
opl2_8.add(Point(5, (fila - 25)));
opl2_8.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_8.add(Point((sPos - 1) * 100, fila));
opl2_8.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl8);
win.attach(opl2_8);
break;
case 9:
opl9.add(Point(((pos - 1) * 100) + 80, filapos));
opl9.add(Point(pos * 100, filapos));
opl9.add(Point(pos * 100, filapos - 25));
opl9.add(Point(1000, filapos - 25));
opl2_9.add(Point(5, (fila - 25)));
opl2_9.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_9.add(Point((sPos - 1) * 100, fila));
opl2_9.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl9);
win.attach(opl2_9);
break;
case 10:
opl10.add(Point(((pos - 1) * 100) + 80, filapos));
opl10.add(Point(pos * 100, filapos));
opl10.add(Point(pos * 100, filapos - 25));
opl10.add(Point(1000, filapos - 25));
opl2_10.add(Point(5, (fila - 25)));
opl2_10.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_10.add(Point((sPos - 1) * 100, fila));
opl2_10.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl10);
win.attach(opl2_10);
break;
case 11:
opl11.add(Point(((pos - 1) * 100) + 80, filapos));
opl11.add(Point(pos * 100, filapos));
opl11.add(Point(pos * 100, filapos - 25));
opl11.add(Point(1000, filapos - 25));
opl2_11.add(Point(5, (fila - 25)));
opl2_11.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_11.add(Point((sPos - 1) * 100, fila));
opl2_11.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl11);
win.attach(opl2_11);
break;
case 12:
opl12.add(Point(((pos - 1) * 100) + 80, filapos));
opl12.add(Point(pos * 100, filapos));
opl12.add(Point(pos * 100, filapos - 25));
opl12.add(Point(1000, filapos - 25));
opl2_12.add(Point(5, (fila - 25)));
opl2_12.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_12.add(Point((sPos - 1) * 100, fila));
opl2_12.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl12);
win.attach(opl2_12);
break;
case 13:
opl13.add(Point(((pos - 1) * 100) + 80, filapos));
opl13.add(Point(pos * 100, filapos));
opl13.add(Point(pos * 100, filapos - 25));
opl13.add(Point(1000, filapos - 25));
opl2_13.add(Point(5, (fila - 25)));
opl2_13.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_13.add(Point((sPos - 1) * 100, fila));
opl2_13.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl13);
win.attach(opl2_13);
break;
case 14:
opl14.add(Point(((pos - 1) * 100) + 80, filapos));
opl14.add(Point(pos * 100, filapos));
opl14.add(Point(pos * 100, filapos - 25));
opl14.add(Point(1000, filapos - 25));
opl2_14.add(Point(5, (fila - 25)));
opl2_14.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_14.add(Point((sPos - 1) * 100, fila));
opl2_14.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl14);
win.attach(opl2_14);
break;
case 15:
opl15.add(Point(((pos - 1) * 100) + 80, filapos));
opl15.add(Point(pos * 100, filapos));
opl15.add(Point(pos * 100, filapos - 25));
opl15.add(Point(1000, filapos - 25));
opl2_15.add(Point(5, (fila - 25)));
opl2_15.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_15.add(Point((sPos - 1) * 100, fila));
opl2_15.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl15);
win.attach(opl2_15);
break;
case 16:
opl16.add(Point(((pos - 1) * 100) + 80, filapos));
opl16.add(Point(pos * 100, filapos));
opl16.add(Point(pos * 100, filapos - 25));
opl16.add(Point(1000, filapos - 25));
opl2_16.add(Point(5, (fila - 25)));
opl2_16.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_16.add(Point((sPos - 1) * 100, fila));
opl2_16.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl16);
win.attach(opl2_16);
break;
case 17:
opl17.add(Point(((pos - 1) * 100) + 80, filapos));
opl17.add(Point(pos * 100, filapos));
opl17.add(Point(pos * 100, filapos - 25));
opl17.add(Point(1000, filapos - 25));
opl2_17.add(Point(5, (fila - 25)));
opl2_17.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_17.add(Point((sPos - 1) * 100, fila));
opl2_17.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl17);
win.attach(opl2_17);
break;
case 18:
opl18.add(Point(((pos - 1) * 100) + 80, filapos));
opl18.add(Point(pos * 100, filapos));
opl18.add(Point(pos * 100, filapos - 25));
opl18.add(Point(1000, filapos - 25));
opl2_18.add(Point(5, (fila - 25)));
opl2_18.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_18.add(Point((sPos - 1) * 100, fila));
opl2_18.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl18);
win.attach(opl2_18);
break;
case 19:
opl19.add(Point(((pos - 1) * 100) + 80, filapos));
opl19.add(Point(pos * 100, filapos));
opl19.add(Point(pos * 100, filapos - 25));
opl19.add(Point(1000, filapos - 25));
opl2_19.add(Point(5, (fila - 25)));
opl2_19.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_19.add(Point((sPos - 1) * 100, fila));
opl2_19.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl19);
win.attach(opl2_19);
break;
case 20:
opl20.add(Point(((pos - 1) * 100) + 80, filapos));
opl20.add(Point(pos * 100, filapos));
opl20.add(Point(pos * 100, filapos - 25));
opl20.add(Point(1000, filapos - 25));
opl2_20.add(Point(5, (fila - 25)));
opl2_20.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_20.add(Point((sPos - 1) * 100, fila));
opl2_20.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl20);
win.attach(opl2_20);
break;
case 21:
opl21.add(Point(((pos - 1) * 100) + 80, filapos));
opl21.add(Point(pos * 100, filapos));
opl21.add(Point(pos * 100, filapos - 25));
opl21.add(Point(1000, filapos - 25));
opl2_21.add(Point(5, (fila - 25)));
opl2_21.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_21.add(Point((sPos - 1) * 100, fila));
opl2_21.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl21);
win.attach(opl2_21);
break;
case 22:
opl22.add(Point(((pos - 1) * 100) + 80, filapos));
opl22.add(Point(pos * 100, filapos));
opl22.add(Point(pos * 100, filapos - 25));
opl22.add(Point(1000, filapos - 25));
opl2_22.add(Point(5, (fila - 25)));
opl2_22.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_22.add(Point((sPos - 1) * 100, fila));
opl2_22.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl22);
win.attach(opl2_22);
break;
case 23:
opl23.add(Point(((pos - 1) * 100) + 80, filapos));
opl23.add(Point(pos * 100, filapos));
opl23.add(Point(pos * 100, filapos - 25));
opl23.add(Point(1000, filapos - 25));
opl2_23.add(Point(5, (fila - 25)));
opl2_23.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_23.add(Point((sPos - 1) * 100, fila));
opl2_23.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl23);
win.attach(opl2_23);
break;
case 24:
opl24.add(Point(((pos - 1) * 100) + 80, filapos));
opl24.add(Point(pos * 100, filapos));
opl24.add(Point(pos * 100, filapos - 25));
opl24.add(Point(1000, filapos - 25));
opl2_24.add(Point(5, (fila - 25)));
opl2_24.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_24.add(Point((sPos - 1) * 100, fila));
opl2_24.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl24);
win.attach(opl2_24);
break;
case 25:
opl25.add(Point(((pos - 1) * 100) + 80, filapos));
opl25.add(Point(pos * 100, filapos));
opl25.add(Point(pos * 100, filapos - 25));
opl25.add(Point(1000, filapos - 25));
opl2_25.add(Point(5, (fila - 25)));
opl2_25.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_25.add(Point((sPos - 1) * 100, fila));
opl2_25.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl25);
win.attach(opl2_25);
break;
case 26:
opl26.add(Point(((pos - 1) * 100) + 80, filapos));
opl26.add(Point(pos * 100, filapos));
opl26.add(Point(pos * 100, filapos - 25));
opl26.add(Point(1000, filapos - 25));
opl2_26.add(Point(5, (fila - 25)));
opl2_26.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_26.add(Point((sPos - 1) * 100, fila));
opl2_26.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl26);
win.attach(opl2_26);
break;
case 27:
opl27.add(Point(((pos - 1) * 100) + 80, filapos));
opl27.add(Point(pos * 100, filapos));
opl27.add(Point(pos * 100, filapos - 25));
opl27.add(Point(1000, filapos - 25));
opl2_27.add(Point(5, (fila - 25)));
opl2_27.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_27.add(Point((sPos - 1) * 100, fila));
opl2_27.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl27);
win.attach(opl2_27);
break;
case 28:
opl28.add(Point(((pos - 1) * 100) + 80, filapos));
opl28.add(Point(pos * 100, filapos));
opl28.add(Point(pos * 100, filapos - 25));
opl28.add(Point(1000, filapos - 25));
opl2_28.add(Point(5, (fila - 25)));
opl2_28.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_28.add(Point((sPos - 1) * 100, fila));
opl2_28.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl28);
win.attach(opl2_28);
break;
}
}
else
{
switch (pos)
{
case 1:
opl1.add(Point(((pos - 1) * 100) + 80, filapos));
opl1.add(Point(pos * 100, filapos));
opl1.add(Point(pos * 100, filapos - 25));
opl1.add(Point(1000, filapos - 25));
opl2_1.add(Point(5, (fila - 25)));
opl2_1.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_1.add(Point((sPos - 1) * 100, fila));
opl2_1.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl1);
win.attach(opl2_1);
break;
case 2:
opl2.add(Point(((pos - 1) * 100) + 80, filapos));
opl2.add(Point(pos * 100, filapos));
opl2.add(Point(pos * 100, filapos - 25));
opl2.add(Point(1000, filapos - 25));
opl2_2.add(Point(5, (fila - 25)));
opl2_2.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_2.add(Point((sPos - 1) * 100, fila));
opl2_2.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl2);
win.attach(opl2_2);
break;
case 3:
opl3.add(Point(((pos - 1) * 100) + 80, filapos));
opl3.add(Point(pos * 100, filapos));
opl3.add(Point(pos * 100, filapos - 25));
opl3.add(Point(1000, filapos - 25));
opl2_3.add(Point(5, (fila - 25)));
opl2_3.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_3.add(Point((sPos - 1) * 100, fila));
opl2_3.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl3);
win.attach(opl2_3);
break;
case 4:
opl4.add(Point(((pos - 1) * 100) + 80, filapos));
opl4.add(Point(pos * 100, filapos));
opl4.add(Point(pos * 100, filapos - 25));
opl4.add(Point(1000, filapos - 25));
opl2_4.add(Point(5, (fila - 25)));
opl2_4.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_4.add(Point((sPos - 1) * 100, fila));
opl2_4.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl4);
win.attach(opl2_4);
break;
case 5:
opl5.add(Point(((pos - 1) * 100) + 80, filapos));
opl5.add(Point(pos * 100, filapos));
opl5.add(Point(pos * 100, filapos - 25));
opl5.add(Point(1000, filapos - 25));
opl2_5.add(Point(5, (fila - 25)));
opl2_5.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_5.add(Point((sPos - 1) * 100, fila));
opl2_5.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl5);
win.attach(opl2_5);
break;
case 6:
opl6.add(Point(((pos - 1) * 100) + 80, filapos));
opl6.add(Point(pos * 100, filapos));
opl6.add(Point(pos * 100, filapos - 25));
opl6.add(Point(1000, filapos - 25));
opl2_6.add(Point(5, (fila - 25)));
opl2_6.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_6.add(Point((sPos - 1) * 100, fila));
opl2_6.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl6);
win.attach(opl2_6);
break;
case 7:
opl7.add(Point(((pos - 1) * 100) + 80, filapos));
opl7.add(Point(pos * 100, filapos));
opl7.add(Point(pos * 100, filapos - 25));
opl7.add(Point(1000, filapos - 25));
opl2_7.add(Point(5, (fila - 25)));
opl2_7.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_7.add(Point((sPos - 1) * 100, fila));
opl2_7.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl7);
win.attach(opl2_7);
break;
case 8:
opl8.add(Point(((pos - 1) * 100) + 80, filapos));
opl8.add(Point(pos * 100, filapos));
opl8.add(Point(pos * 100, filapos - 25));
opl8.add(Point(1000, filapos - 25));
opl2_8.add(Point(5, (fila - 25)));
opl2_8.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_8.add(Point((sPos - 1) * 100, fila));
opl2_8.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl8);
win.attach(opl2_8);
break;
case 9:
opl9.add(Point(((pos - 1) * 100) + 80, filapos));
opl9.add(Point(pos * 100, filapos));
opl9.add(Point(pos * 100, filapos - 25));
opl9.add(Point(1000, filapos - 25));
opl2_9.add(Point(5, (fila - 25)));
opl2_9.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_9.add(Point((sPos - 1) * 100, fila));
opl2_9.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl9);
win.attach(opl2_9);
break;
case 10:
opl10.add(Point(((pos - 1) * 100) + 80, filapos));
opl10.add(Point(pos * 100, filapos));
opl10.add(Point(pos * 100, filapos - 25));
opl10.add(Point(1000, filapos - 25));
opl2_10.add(Point(5, (fila - 25)));
opl2_10.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_10.add(Point((sPos - 1) * 100, fila));
opl2_10.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl10);
win.attach(opl2_10);
break;
case 11:
opl11.add(Point(((pos - 1) * 100) + 80, filapos));
opl11.add(Point(pos * 100, filapos));
opl11.add(Point(pos * 100, filapos - 25));
opl11.add(Point(1000, filapos - 25));
opl2_11.add(Point(5, (fila - 25)));
opl2_11.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_11.add(Point((sPos - 1) * 100, fila));
opl2_11.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl11);
win.attach(opl2_11);
break;
case 12:
opl12.add(Point(((pos - 1) * 100) + 80, filapos));
opl12.add(Point(pos * 100, filapos));
opl12.add(Point(pos * 100, filapos - 25));
opl12.add(Point(1000, filapos - 25));
opl2_12.add(Point(5, (fila - 25)));
opl2_12.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_12.add(Point((sPos - 1) * 100, fila));
opl2_12.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl12);
win.attach(opl2_12);
break;
case 13:
opl13.add(Point(((pos - 1) * 100) + 80, filapos));
opl13.add(Point(pos * 100, filapos));
opl13.add(Point(pos * 100, filapos - 25));
opl13.add(Point(1000, filapos - 25));
opl2_13.add(Point(5, (fila - 25)));
opl2_13.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_13.add(Point((sPos - 1) * 100, fila));
opl2_13.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl13);
win.attach(opl2_13);
break;
case 14:
opl14.add(Point(((pos - 1) * 100) + 80, filapos));
opl14.add(Point(pos * 100, filapos));
opl14.add(Point(pos * 100, filapos - 25));
opl14.add(Point(1000, filapos - 25));
opl2_14.add(Point(5, (fila - 25)));
opl2_14.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_14.add(Point((sPos - 1) * 100, fila));
opl2_14.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl14);
win.attach(opl2_14);
break;
case 15:
opl15.add(Point(((pos - 1) * 100) + 80, filapos));
opl15.add(Point(pos * 100, filapos));
opl15.add(Point(pos * 100, filapos - 25));
opl15.add(Point(1000, filapos - 25));
opl2_15.add(Point(5, (fila - 25)));
opl2_15.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_15.add(Point((sPos - 1) * 100, fila));
opl2_15.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl15);
win.attach(opl2_15);
break;
case 16:
opl16.add(Point(((pos - 1) * 100) + 80, filapos));
opl16.add(Point(pos * 100, filapos));
opl16.add(Point(pos * 100, filapos - 25));
opl16.add(Point(1000, filapos - 25));
opl2_16.add(Point(5, (fila - 25)));
opl2_16.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_16.add(Point((sPos - 1) * 100, fila));
opl2_16.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl16);
win.attach(opl2_16);
break;
case 17:
opl17.add(Point(((pos - 1) * 100) + 80, filapos));
opl17.add(Point(pos * 100, filapos));
opl17.add(Point(pos * 100, filapos - 25));
opl17.add(Point(1000, filapos - 25));
opl2_17.add(Point(5, (fila - 25)));
opl2_17.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_17.add(Point((sPos - 1) * 100, fila));
opl2_17.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl17);
win.attach(opl2_17);
break;
case 18:
opl18.add(Point(((pos - 1) * 100) + 80, filapos));
opl18.add(Point(pos * 100, filapos));
opl18.add(Point(pos * 100, filapos - 25));
opl18.add(Point(1000, filapos - 25));
opl2_18.add(Point(5, (fila - 25)));
opl2_18.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_18.add(Point((sPos - 1) * 100, fila));
opl2_18.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl18);
win.attach(opl2_18);
break;
case 19:
opl19.add(Point(((pos - 1) * 100) + 80, filapos));
opl19.add(Point(pos * 100, filapos));
opl19.add(Point(pos * 100, filapos - 25));
opl19.add(Point(1000, filapos - 25));
opl2_19.add(Point(5, (fila - 25)));
opl2_19.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_19.add(Point((sPos - 1) * 100, fila));
opl2_19.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl19);
win.attach(opl2_19);
break;
case 20:
opl20.add(Point(((pos - 1) * 100) + 80, filapos));
opl20.add(Point(pos * 100, filapos));
opl20.add(Point(pos * 100, filapos - 25));
opl20.add(Point(1000, filapos - 25));
opl2_20.add(Point(5, (fila - 25)));
opl2_20.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_20.add(Point((sPos - 1) * 100, fila));
opl2_20.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl20);
win.attach(opl2_20);
break;
case 21:
opl21.add(Point(((pos - 1) * 100) + 80, filapos));
opl21.add(Point(pos * 100, filapos));
opl21.add(Point(pos * 100, filapos - 25));
opl21.add(Point(1000, filapos - 25));
opl2_21.add(Point(5, (fila - 25)));
opl2_21.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_21.add(Point((sPos - 1) * 100, fila));
opl2_21.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl21);
win.attach(opl2_21);
break;
case 22:
opl22.add(Point(((pos - 1) * 100) + 80, filapos));
opl22.add(Point(pos * 100, filapos));
opl22.add(Point(pos * 100, filapos - 25));
opl22.add(Point(1000, filapos - 25));
opl2_22.add(Point(5, (fila - 25)));
opl2_22.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_22.add(Point((sPos - 1) * 100, fila));
opl2_22.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl22);
win.attach(opl2_22);
break;
case 23:
opl23.add(Point(((pos - 1) * 100) + 80, filapos));
opl23.add(Point(pos * 100, filapos));
opl23.add(Point(pos * 100, filapos - 25));
opl23.add(Point(1000, filapos - 25));
opl2_23.add(Point(5, (fila - 25)));
opl2_23.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_23.add(Point((sPos - 1) * 100, fila));
opl2_23.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl23);
win.attach(opl2_23);
break;
case 24:
opl24.add(Point(((pos - 1) * 100) + 80, filapos));
opl24.add(Point(pos * 100, filapos));
opl24.add(Point(pos * 100, filapos - 25));
opl24.add(Point(1000, filapos - 25));
opl2_24.add(Point(5, (fila - 25)));
opl2_24.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_24.add(Point((sPos - 1) * 100, fila));
opl2_24.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl24);
win.attach(opl2_24);
break;
case 25:
opl25.add(Point(((pos - 1) * 100) + 80, filapos));
opl25.add(Point(pos * 100, filapos));
opl25.add(Point(pos * 100, filapos - 25));
opl25.add(Point(1000, filapos - 25));
opl2_25.add(Point(5, (fila - 25)));
opl2_25.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_25.add(Point((sPos - 1) * 100, fila));
opl2_25.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl25);
win.attach(opl2_25);
break;
case 26:
opl26.add(Point(((pos - 1) * 100) + 80, filapos));
opl26.add(Point(pos * 100, filapos));
opl26.add(Point(pos * 100, filapos - 25));
opl26.add(Point(1000, filapos - 25));
opl2_26.add(Point(5, (fila - 25)));
opl2_26.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_26.add(Point((sPos - 1) * 100, fila));
opl2_26.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl26);
win.attach(opl2_26);
break;
case 27:
opl27.add(Point(((pos - 1) * 100) + 80, filapos));
opl27.add(Point(pos * 100, filapos));
opl27.add(Point(pos * 100, filapos - 25));
opl27.add(Point(1000, filapos - 25));
opl2_27.add(Point(5, (fila - 25)));
opl2_27.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_27.add(Point((sPos - 1) * 100, fila));
opl2_27.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl27);
win.attach(opl2_27);
break;
case 28:
opl28.add(Point(((pos - 1) * 100) + 80, filapos));
opl28.add(Point(pos * 100, filapos));
opl28.add(Point(pos * 100, filapos - 25));
opl28.add(Point(1000, filapos - 25));
opl2_28.add(Point(5, (fila - 25)));
opl2_28.add(Point((sPos - 1) * 100, (fila - 25)));
opl2_28.add(Point((sPos - 1) * 100, fila));
opl2_28.add(Point(((sPos - 1) * 100) + 20, fila));
win.attach(opl28);
win.attach(opl2_28);
break;
}
}
}
}else
{
switch (pos)
{
case 1:
win.attach(opl2_1);
win.attach(opl1);
break;
case 2:
win.attach(opl2_2);
win.attach(opl2);
break;
case 3:
win.attach(opl2_3);
win.attach(opl3);
break;
case 4:
win.attach(opl2_4);
win.attach(opl4);
break;
case 5:
win.attach(opl2_5);
win.attach(opl5);
break;
case 6:
win.attach(opl2_6);
win.attach(opl6);
break;
case 7:
win.attach(opl2_7);
win.attach(opl7);
break;
case 8:
win.attach(opl2_8);
win.attach(opl8);
break;
case 9:
win.attach(opl2_9);
win.attach(opl9);
break;
case 10:
win.attach(opl2_10);
win.attach(opl10);
break;
case 11:
win.attach(opl2_11);
win.attach(opl11);
break;
case 12:
win.attach(opl2_12);
win.attach(opl12);
break;
case 13:
win.attach(opl2_13);
win.attach(opl13);
break;
case 14:
win.attach(opl2_14);
win.attach(opl14);
break;
case 15:
win.attach(opl2_15);
win.attach(opl15);
break;
case 16:
win.attach(opl2_16);
win.attach(opl16);
break;
case 17:
win.attach(opl2_17);
win.attach(opl8);
break;
case 18:
win.attach(opl2_18);
win.attach(opl8);
break;
case 19:
win.attach(opl2_19);
win.attach(opl19);
break;
case 20:
win.attach(opl2_20);
win.attach(opl20);
break;
case 21:
win.attach(opl2_21);
win.attach(opl21);
break;
case 22:
win.attach(opl2_22);
win.attach(opl22);
break;
case 23:
win.attach(opl2_23);
win.attach(opl23);
break;
case 24:
win.attach(opl2_24);
win.attach(opl24);
break;
case 25:
win.attach(opl2_25);
win.attach(opl25);
break;
case 26:
win.attach(opl2_26);
win.attach(opl26);
break;
case 27:
win.attach(opl2_27);
win.attach(opl27);
break;
case 28:
win.attach(opl2_28);
win.attach(opl28);
break;
}
}
}
<file_sep>#pragma once
#include <vector>
#include <iostream>
#include <string>
using namespace std;
enum Tipo { variable, operador, numero, nulo};
struct Token {
Tipo tipo;
string tokenS;
int num;
char tokenC;
Token(string st) { tipo = variable; tokenS = st; if (st == "While" || st == "new" || st == "Nodo" || st == "Repeat"||st=="sig")tipo = operador; }
Token(char s) { tipo = operador; tokenC = s; }
Token(int n) { tipo = numero; num = n; }
Token() : tipo{ nulo } { }
Tipo demeTipo() { return tipo; }
friend ostream& operator<<(ostream &os, Token & t);
~Token() {};
};
ostream& operator <<(ostream &os, Token & t) {
switch (t.tipo) {
case variable: {
os << "[" << t.tokenS << "]" << "<var>\n";
break;
}
case operador:
if (t.tokenS == "While" || t.tokenS == "new" || t.tokenS == "Nodo" || t.tokenS == "Repeat" || t.tokenS == "sig")
os << "[" << t.tokenS << "]" << "<opr>\n";
else
os << "[" << t.tokenC << "]" << "<opr>\n";
break;
case numero:
os << "[" << t.num << "]" << "<num>\n";
break;
case nulo:
os << "[ ]" << "<nul>\n";
break;
}
return os;
}
class Tokenizador {
private:
int pos;
string tira;
public:
Tokenizador(string entrada);
Token demeToken();
};
Tokenizador::Tokenizador(string entrada) {
tira = entrada;
pos = 0;
}
Token Tokenizador::demeToken() {
if (pos >= tira.length())
return Token();
while (pos < tira.length() && tira[pos] == ' ') pos++; // Omite blancos
if (isalpha(tira[pos])) {
string s = "";
while (isalpha(tira[pos])) s.push_back(tira[pos++]);
return Token(s);
}
if (isdigit(tira[pos])) {
int v = 0;
while (isdigit(tira[pos])) v = v * 10 + tira[pos++] - '0';
return Token(v);
}
if (tira[pos] == '+' || tira[pos] == '-' ||
tira[pos] == '*' || tira[pos] == '/'||
tira[pos]=='>'||tira[pos] == '='||tira[pos]=='('
||tira [pos]==')' ||tira [pos]=='_') {
return Token(tira[pos++]);
}
pos++;
return Token();
}
|
b8cb6f852705ed3348ea8ed93d98e807e0d184b6
|
[
"C++"
] | 5
|
C++
|
MH102/TareaProgramada1
|
922e2c4056dc3828dc2797f953a883ce97f1c03b
|
d3b57b672b50b73e934dddce33af69d5ff5a1744
|
refs/heads/master
|
<file_sep># 360task
Assignment task 360T
How to run:
1- build the project using maven >=3.6.3
2- tested using java >= 13
3- create new artifact using maven package command
4- new artifact can be run using java -jar command as follows:
java -jar assignment-1.0-SNAPSHOT.jar
5- There are 2 possibilities which are shown to the user:
Welcome! Do you want to run Single(S) Process or Multiple(M) Process?
Selecting 'S' will continue the application in a single process mode on which both players exist on the same java process.
Then you are prompted to enter 2 user names and also new message which will be sent to and back between them 10 times.
6- Selecting 'M' will lead to multi process mode in which you have to select between Server(S) and Client(C) modes.
In this mode you have to run the application 2 times from different terminals, first time as Server with no more actions.
7- Then you have to run the application again, while the server is running still. This time you have to select the Client mode.
And then enter a username and the message.
8- In Multi process mode each player starts in a separate Process. The main Process starts a default Player which is named 'host'. And the client which is started by the user.
<file_sep>package com.t360.model;
/**
* @author : <NAME><<EMAIL>>
* @since : 12/20/2019, Fri
**/
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
* This interface is used for base message skeleton
*/
public interface IMessage extends Remote {
String getValue() throws RemoteException;
String getSenderUsername() throws RemoteException;
String getReceiverUsername() throws RemoteException;
}
<file_sep>package com.t360.model;
/**
* Author: <a href="mailto:<EMAIL>"><NAME></a>
* <p>
* Description: <the description of the class for java doc by those that might use it, please use html if possible>
*/
public interface IMessageListener extends java.rmi.Remote {
void messageReceived(IMessage msg) throws java.rmi.RemoteException;
String getUserName() throws java.rmi.RemoteException;
}
<file_sep>welcome.msg=Welcome! Do you want to run Single(S) Process or Multiple(M) Process?
server.pid=server PID:
server.start=Server ready
server.exception=Server exception:
server.exit=Chat Server exiting...
client.pid=client PID:
client.started=---Client started---
input.msg=Msg:
input.usr1=Plz Enter 1st username:
input.usr2=Plz Enter 2nd username:
send.msg.template=Hi %s! Enter your message to sent to %s
msg.log.template=PID:%s,username:%-8s,sender:%-8s,msg:%s
server.client.choice=Server(S) mode or Client(C)?<file_sep>package com.t360.model;
/**
* @author : <NAME><<EMAIL>>
* @since : 12/20/2019, Fri
**/
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
/***
* This class is a private message between 2 players, it holds the message content and the sender and receiver players as well
*/
public class PrivateMessage extends UnicastRemoteObject implements IMessage {
private final String value;
private final String receiverUsername;
private final String senderUsername;
public PrivateMessage(String value, String senderUsername, String receiverUsername)
throws RemoteException {
this.value = value;
this.senderUsername = senderUsername;
this.receiverUsername = receiverUsername;
}
public String getValue() {
return value;
}
@Override
public String getSenderUsername() throws RemoteException {
return senderUsername;
}
public String getReceiverUsername() {
return receiverUsername;
}
}
|
4d8e80e2a39281516b1a75cea1b6be22544ee9aa
|
[
"Markdown",
"Java",
"INI"
] | 5
|
Markdown
|
hajk1/360task
|
dbfde179c0d153c58c09743ad61e9ecb81c09b97
|
244d73b57b5c622fb075834b205119f55607775e
|
refs/heads/master
|
<file_sep>// cброс хэша(якоря) в адресной строке при перезагрузке (из-за плагина)
// history.pushState('', document.title, window.location.pathname);
// закрытие меню
const menuBtn = document.querySelector('.icon-menu'),
menu = document.querySelector('.nav');
const toggleMenu = function () {
menuBtn.classList.toggle('active')
menu.classList.toggle('_active');
}
menuBtn.addEventListener('click', function (e) {
e.stopPropagation()
toggleMenu()
})
// Закрытие по клику вне меню
document.addEventListener('click', function (e) {
const target = e.target;
const its_menu = target == menu || menu.contains(target);
const its_btnMenu = target == menuBtn;
const menu_is_active = menu.classList.contains('_active');
if (!its_menu && !its_btnMenu && menu_is_active) {
toggleMenu();
}
});
const navLeftMenu = document.querySelector('.menu__slider')
const navLeftMenuSlider = new Swiper(navLeftMenu, {
slidesPerView: 6,
direction: 'vertical',
navigation: {
nextEl: '.menu__arrow-next',
prevEl: '.menu__arrow-prev',
},
})
// Социальные иконки
const socialShared = document.querySelector('.social-hints__shared')
const socialLink = document.querySelector('.social-hints__links')
socialShared.addEventListener('click', (evt) => {
evt.preventDefault()
socialLink.classList.toggle('active')
})
// Плагин fullpage.js
new fullpage('#fullpage', {
licenseKey: '59DB8F6F-B819439E-9C9C8AD2-C475CC00',
scrollOverflow: true,
autoScrolling: true,
normalScrollElements: '.form-quiz__expense, .form-quiz__time, .form-quiz__spend, .contact-details__label',
anchors: [
'firstPage',
'secondPage',
'thirdPage',
'fourthPage',
'fivthPage',
'sextantPage',
'seventhPage',
'eighthPage',
'ninthPage',
'tenthPage',
'eleventhPage',
'twelthPage'
],
menu: '#menu',
onLeave: function (origin, destination, direction) {
const loadedSection = this,
header = document.querySelector("header.header"),
hint = document.querySelector(".hints"),
menu = document.querySelector("#menu"),
linkToReji = document.querySelector('.mini-footer');
const isAnimatedAbout = document.querySelectorAll('.about .is-animated')
const isAnimatedOptions = document.querySelectorAll('.options .is-animated')
const isAnimatedHowItWorks = document.querySelectorAll('.how-it-works .is-animated')
const isAnimatedSupport = document.querySelectorAll('.support .is-animated')
const isAnimatedInfo = document.querySelectorAll('.info .is-animated')
const isAnimatedDocumetation = document.querySelectorAll('.documentation .is-animated')
const isAnimatedQuiz = document.querySelectorAll('.quiz .is-animated')
const isAnimatedInstallation = document.querySelectorAll('.installation .is-animated')
const isAnimatedReviews = document.querySelectorAll('.reviews .is-animated')
const isAnimatedRates = document.querySelectorAll('.rates .is-animated')
const isAnimatedContacts = document.querySelectorAll('.contacts .is-animated')
let animationSpeed = 0.3
if (origin.index == 10) {
linkToReji.style.display = 'block'
} else {
linkToReji.style.display = 'none'
}
// Меняем шапку и скрываем навигацинное меню по секциям на первом экране
if (origin.index == 0 && direction == 'down') {
header.classList.add('active')
hint.style.display = ''
menu.style.display = ''
} else if (origin.index == 1 && direction == 'up') {
header.classList.remove('active')
hint.style.display = 'none'
menu.style.display = 'none'
} else if (origin.index >= 2 && direction == 'up') {
navLeftMenuSlider.slidePrev()
}
// Добавляем класс для анимации
function addAnimation(selector, animation) {
selector.forEach(item => {
item.classList.add('animated', animation);
})
}
// Добавляем задержку
function addDelay(selector) {
for (let i = 0; i < selector.length; i++) {
animationSpeed += 0.2
selector[i].style.animationDelay = animationSpeed + 's'
}
}
// Анимация
switch (origin.index) {
case 0:
addAnimation(isAnimatedAbout, 'fadeInUp')
addDelay(isAnimatedAbout)
break
case 1:
addAnimation(isAnimatedOptions, 'fadeInUp')
addDelay(isAnimatedOptions)
break
case 2:
addAnimation(isAnimatedHowItWorks, 'fadeInUp')
addDelay(isAnimatedHowItWorks)
break
case 3:
addAnimation(isAnimatedSupport, 'fadeInUp')
addDelay(isAnimatedSupport)
break
case 4:
addAnimation(isAnimatedInfo, 'fadeInUp')
addDelay(isAnimatedInfo)
navLeftMenuSlider.slideNext()
break
case 5:
addAnimation(isAnimatedDocumetation, 'fadeInUp')
addDelay(isAnimatedDocumetation)
break
case 6:
addAnimation(isAnimatedQuiz, 'fadeInUp')
addDelay(isAnimatedQuiz)
break
case 7:
addAnimation(isAnimatedInstallation, 'fadeInUp')
addDelay(isAnimatedInstallation)
navLeftMenuSlider.slideNext()
break
case 8:
addAnimation(isAnimatedReviews, 'fadeInUp')
addDelay(isAnimatedReviews)
navLeftMenuSlider.slideNext()
break
case 9:
addAnimation(isAnimatedRates, 'fadeInUp')
addDelay(isAnimatedRates)
navLeftMenuSlider.slideNext()
break
case 10:
addAnimation(isAnimatedContacts, 'fadeInUp')
addDelay(isAnimatedContacts)
navLeftMenuSlider.slideNext()
linkToReji.style.display = 'block'
break
}
},
});
// Cкрываем меню и кнопку "поделиться" с телефоном сразу
const menuNav = document.querySelector("#menu");
const hints = document.querySelector(".hints");
const miniFooter = document.querySelector('.mini-footer')
menuNav.style.display = 'none'
hints.style.display = 'none'
miniFooter.style.display = 'none'
// Добавляем активный класс элементу выезжающего меню --------
const navItem = document.querySelectorAll('.nav__item')
function removeClass() {
navItem.forEach(item => {
item.classList.remove('_active')
})
}
navItem.forEach(item => {
item.addEventListener('click', (evt) => {
removeClass()
item.classList.add('_active')
menu.classList.remove('_active')
menuBtn.classList.remove('active')
})
})
// Квиз -------------------------------
const quiz = document.querySelector('.form-quiz')
const arrowsSlider = document.querySelector('.form-quiz__nav')
const nextArrow = document.querySelector('.form-quiz__arrow_next')
const prevArrow = document.querySelector('.form-quiz__arrow_prev')
const paginationSlider = document.querySelector('.form-quiz__arrow_next')
const slides = document.querySelectorAll('.form-quiz .swiper-slide')
let counter = 0
const quizSlider = new Swiper(quiz, {
slidesPerView: 1,
allowTouchMove: false,
autoHeight: true,
navigation: {
nextEl: '.form-quiz__arrow_next',
prevEl: '.form-quiz__arrow_prev',
},
pagination: {
el: '.swiper-pagination',
type: 'bullets',
},
})
nextArrow.addEventListener('click', (evt) => {
counter++
if (slides.length - 1 === counter) {
arrowsSlider.style.display = 'none'
}
})
prevArrow.addEventListener('click', (evt) => {
counter--
})
// Слайдер отзывов
const reviews = document.querySelector('.slider-reviews')
const reviewsSlider = new Swiper(reviews, {
slidesPerView: 1,
slidesPerGroup: 1,
spaceBetween: 20,
navigation: {
nextEl: '.slider-reviews__arrow_next',
prevEl: '.slider-reviews__arrow_prev',
},
breakpoints: {
1366: {
spaceBetween: 50,
slidesPerView: 2,
slidesPerGroup: 2,
}
}
})
// Убираем checked с уже активного чекбокса
function clickRadio(el) {
const siblings = document.querySelectorAll("input[type='radio'][name='" + el.name + "']");
for (let i = 0; i < siblings.length; i++) {
if (siblings[i] != el)
siblings[i].oldChecked = false;
}
if (el.oldChecked)
el.checked = false;
el.oldChecked = el.checked;
}
// range инпуты в квизе
const timeSlider = document.querySelector('.form-quiz__time');
const expenseSlider = document.querySelector('.form-quiz__expense');
const spendSlider = document.querySelector('.form-quiz__spend');
noUiSlider.create(timeSlider, {
start: 0,
connect: 'lower',
range: {
'min': 0,
'max': 10
},
format: wNumb({
decimals: 0
}),
step: 1,
tooltips: true,
});
noUiSlider.create(expenseSlider, {
start: 0,
connect: 'lower',
step: 1,
range: {
'min': 0,
'max': 10000000
},
format: wNumb({
decimals: 0
}),
tooltips: true,
});
noUiSlider.create(spendSlider, {
start: 0,
connect: 'lower',
range: {
'min': 0,
'max': 100
},
format: wNumb({
decimals: 0
}),
tooltips: true,
});
const sendBtn = document.querySelector('.contact-details__btn')
sendBtn.addEventListener('click', () => {
let timeSliderValue = timeSlider.noUiSlider.get()
let expenseSliderValue = expenseSlider.noUiSlider.get();
let spendSliderValue = spendSlider.noUiSlider.get();
})
// маска для номера телефона
function setCursorPosition(pos, elem) {
elem.focus();
if (elem.setSelectionRange) elem.setSelectionRange(pos, pos);
else if (elem.createTextRange) {
let range = elem.createTextRange();
range.collapse(true);
range.moveEnd("character", pos);
range.moveStart("character", pos);
range.select()
}
}
function mask(event) {
let matrix = this.defaultValue,
i = 0,
def = matrix.replace(/\D/g, ""),
val = this.value.replace(/\D/g, "");
def.length >= val.length && (val = def);
matrix = matrix.replace(/[_\d]/g, function (a) {
return val.charAt(i++) || "_"
});
this.value = matrix;
i = matrix.lastIndexOf(val.substr(-1));
i < matrix.length && matrix != this.defaultValue ? i++ : i = matrix.indexOf("_");
setCursorPosition(i, this)
}
const telephonesContacts = document.querySelectorAll(".telephone-contacts");
for (input of telephonesContacts) {
input.addEventListener("input", mask, false)
}
// Валидация инпута Имени
const contactInputName = document.querySelectorAll('.contact-details__input')
contactInputName.forEach(input => {
input.addEventListener('input', function () {
this.value = this.value.replace(/[^а-я/a-z\s]+/ig, "");
})
})
// При клике на логотип убираем меню, класс у шапки и нижний блок
const header = document.querySelector(".header");
const logo = document.querySelector('.header__logo')
logo.addEventListener('click', (evt) => {
header.classList.remove('active')
menuNav.style.display = 'none'
hints.style.display = 'none'
})
|
9c6f93a3ff2cce8913cbd4cd7035232e41d237cb
|
[
"JavaScript"
] | 1
|
JavaScript
|
ohwoow/rob-invest
|
9be0fa89f5b675cc1e4bad8343d65432195a1a69
|
cc498eeebcc4ea9f4f6b3d9f24d7296c91d99707
|
refs/heads/master
|
<file_sep>"""
Custom Authenticator to use Google OAuth with JupyterHub.
Derived from GitHub OAuth authenticator,
https://github.com/jupyter/oauthenticator
"""
import os
import binascii
import json
from tornado import gen
from tornado.auth import GoogleOAuth2Mixin
from tornado.escape import to_unicode
from tornado.web import HTTPError
from IPython.utils.traitlets import Unicode
from jupyterhub.handlers import BaseHandler
from jupyterhub.auth import Authenticator, LocalAuthenticator
from jupyterhub.utils import url_path_join
class GoogleLoginHandler(BaseHandler, GoogleOAuth2Mixin):
def get(self):
guess_uri = '{proto}://{host}{path}'.format(
proto=self.request.protocol,
host=self.request.host,
path=url_path_join(self.hub.server.base_url, 'oauth_callback')
)
redirect_uri = self.authenticator.oauth_callback_url or guess_uri
self.log.info('oauth redirect: %r', redirect_uri)
self.authorize_redirect(
redirect_uri=redirect_uri,
client_id=self.authenticator.oauth_client_id,
scope=['openid', 'email'],
response_type='code')
class GoogleOAuthHandler(BaseHandler, GoogleOAuth2Mixin):
@gen.coroutine
def get(self):
self.settings['google_oauth'] = {
'key': self.authenticator.oauth_client_id,
'secret': self.authenticator.oauth_client_secret,
'scope': ['openid', 'email']
}
# TODO: Check if state argument needs to be checked
#state = to_unicode(self.get_secure_cookie('openid_state'))
#if not state == self.get_argument('state', False):
# raise HTTPError(400, "Invalid state")
username = yield self.authenticator.authenticate(self)
self.log.info('GOOGLEAPPS: username: "%s"', username)
if username:
user = self.user_from_username(username)
self.set_login_cookie(user)
self.redirect(url_path_join(self.hub.server.base_url, 'home'))
else:
# todo: custom error page?
raise HTTPError(403)
class GoogleOAuthenticator(Authenticator):
login_service = "Google"
ACCESS_TOKEN_URL = 'https://www.googleapis.com/oauth2/v1/userinfo'
oauth_callback_url = Unicode('', config=True)
oauth_client_id = Unicode(os.environ.get('OAUTH_CLIENT_ID', ''),
config=True)
oauth_client_secret = Unicode(os.environ.get('OAUTH_CLIENT_SECRET', ''),
config=True)
def login_url(self, base_url):
return url_path_join(base_url, 'oauth_login')
def get_handlers(self, app):
return [
(r'/oauth_login', GoogleLoginHandler),
(r'/oauth2callback', GoogleOAuthHandler),
]
@gen.coroutine
def authenticate(self, handler):
code = handler.get_argument('code', False)
if not code:
raise HTTPError(400, "oauth callback made without a token")
user = yield handler.get_authenticated_user(
redirect_uri=self.oauth_callback_url,
code=code)
access_token = str(user['access_token'])
http_client = handler.get_auth_http_client()
response = yield http_client.fetch(
self.ACCESS_TOKEN_URL + '?access_token=' + access_token
)
if not response:
self.clear_all_cookies()
raise HTTPError(500, 'Google authentication failed')
bodyjs = json.loads(response.body.decode())
username = bodyjs['email']
raise gen.Return(username)
class GoogleAppsOAuthenticator(GoogleOAuthenticator):
hosted_domain = Unicode(os.environ.get('HOSTED_DOMAIN', ''), config=True)
@gen.coroutine
def authenticate(self, handler):
username = yield GoogleOAuthenticator.authenticate(self, handler)
if not username or not username.endswith('@'+self.hosted_domain):
username = None
else:
username = username.split('@')[0]
if self.whitelist and username not in self.whitelist:
username = None
raise gen.Return(username)
class LocalGoogleOAuthenticator(LocalAuthenticator, GoogleOAuthenticator):
"""A version that mixes in local system user creation"""
pass
class LocalGoogleAppsOAuthenticator(LocalAuthenticator, GoogleAppsOAuthenticator):
"""A version that mixes in local system user creation"""
pass
<file_sep>-e git+https://github.com/jupyter/jupyterhub.git#egg=jupyterhub
-e git+https://github.com/ipython/ipython.git#egg=ipython[notebook]
sqlalchemy
simplepam
<file_sep># OAuthenticator
---
Notice: This code has been absorbed by [Jupyter's OAuthenticator](https://github.com/jupyter/oauthenticator). Please use that instead.
---
Google OAuth 2.0 + JuptyerHub Authenticator = OAuthenticator
Google OAuthenticator is based on [GitHub OAuthenticator](https://github.com/jupyter/oauthenticator).
## Installation
First, install dependencies:
pip install -r requirements.txt
Then, install the package:
python setup.py install
## Setup
You will need to create an
[OAuth 2.0 client ID](https://developers.google.com/console/help/new/?hl=en_US#generatingoauth2)
in the Google Developers Console. A client secret will be automatically generated for you. Set the callback URL to:
http[s]://[your-host]/hub/oauth2callback
where `[your-host]` is your server's hostname, e.g. `example.com:8000`.
Then, add the following to your `jupyterhub_config.py` file:
c.JupyterHub.authenticator_class = 'oauthenticator.GoogleOAuthenticator'
You will need to provide the OAuth callback URL and the Google OAuth client ID
and client secret to JupyterHub. For example, if these values are in the
environment variables `$OAUTH_CALLBACK_URL`, `$OAUTH_CLIENT_ID` and
`$OAUTH_CLIENT_SECRET`, you should add the following to your
`jupyterhub_config.py`:
c.GoogleOAuthenticator.oauth_callback_url = os.environ['OAUTH_CALLBACK_URL']
c.GoogleOAuthenticator.oauth_client_id = os.environ['OAUTH_CLIENT_ID']
c.GoogleOAuthenticator.oauth_client_secret = os.environ['OAUTH_CLIENT_SECRET']
If you want to authenticate users in a hosted Google domain, e.g. `your-institution.edu`, use
`oauthenticator.GoogleAppsOAuthenticator` and add the following to your `jupyterhub_config.py`:
c.GoogleOAuthenticator.hosted_domain = os.environ['HOSTED_DOMAIN']
and set the environment variable accordingly. This authenticator was developed to be used in an environment derived from
[compmodels](https://github.com/compmodels/jupyterhub-deploy) where spawned containers are named after users. Container names cannot contain `@' so this latter authenticator class will strip it off in addition to the hosted domain name.
|
b63055537ee729f1bb74083d8b817414e2c6ffbd
|
[
"Markdown",
"Python",
"Text"
] | 3
|
Python
|
ryanlovett/jh-google-oauthenticator
|
5d276d8f65844f6903b8591bd245520e4d688d28
|
16c566d0e5cdfab537dfae7fab9eb3979a01cb00
|
refs/heads/main
|
<file_sep>using System.Linq;
using Tortuga.Anchor.Modeling;
namespace SavageTools.Characters
{
public class FeatureCollection : ChangeTrackingModelCollection<Feature>
{
internal void Add(string name)
{
if (!this.Any(f => f.Name == name))
Add(new Feature() { Name = name });
}
}
}<file_sep>using System;
namespace SavageTools.Characters
{
public struct Trait : IEquatable<Trait>, IComparable, IComparable<Trait>
{
public Trait(int score)
{
Score = score;
}
public Trait(string dieCode)
{
if (string.IsNullOrEmpty(dieCode))
throw new ArgumentException($"{nameof(dieCode)} is null or empty.", nameof(dieCode));
dieCode = dieCode.ToLowerInvariant();
switch (dieCode)
{
case "d2": Score = 2; return;
case "d4": Score = 4; return;
case "d6": Score = 6; return;
case "d8": Score = 8; return;
case "d10": Score = 10; return;
case "d12": Score = 12; return;
}
if (dieCode.StartsWith("d12+"))
{
Score = 12 + int.Parse(dieCode.Substring(4));
return;
}
throw new ArgumentException($"Cannot parse die code \"{dieCode}\" as a trait.");
}
public int HalfScore => (int)Math.Floor(Score / 2M);
public int Score { get; }
public static implicit operator Trait(int score) => new Trait(score);
public static implicit operator Trait(string dieCode) => new Trait(dieCode);
public static Trait operator -(Trait original, int bonus) => original + (bonus * -1);
public static bool operator !=(Trait first, Trait second) => !(first == second);
public static Trait operator +(Trait original, int bonus)
{
//The math is a bit wonky because of the combination of a die code and a bonus
var score = original.Score;
//Adds
while (bonus > 0)
{
if (score < 12)
score += 2;
else
score += 1;
bonus -= 1;
}
//Subtracts
while (bonus < 0)
{
if (score > 12)
score -= 1;
else
score -= 2;
bonus += 1;
}
return new Trait(score);
}
public static bool operator <(Trait first, Trait second) => first.Score < second.Score;
public static bool operator <=(Trait first, Trait second) => first.Score <= second.Score;
public static bool operator ==(Trait first, Trait second) => first.Equals(second);
public static bool operator >(Trait first, Trait second) => first.Score > second.Score;
public static bool operator >=(Trait first, Trait second) => first.Score >= second.Score;
public int CompareTo(object? obj)
{
if (obj == null)
return 1;
var other = obj as Trait?;
if (other == null)
throw new ArgumentException(nameof(obj) + " is not a " + nameof(Trait));
return CompareTo(other.Value);
}
public int CompareTo(Trait other)
{
return Score.CompareTo(other.Score);
}
public override bool Equals(object? obj)
{
if (obj is Trait)
return Equals((Trait)obj);
return base.Equals(obj);
}
public bool Equals(Trait other) => Score == other.Score;
public override int GetHashCode() => Score;
public override string ToString()
{
if (Score == 0)
return "";
if (Score < 4)
return $"d4{Score - 4 }"; //Example: Score 2 would be 4d-2
if (Score <= 12)
return $"d{Score}";
return $"d12+{Score - 12}";
}
}
}
<file_sep>using Tortuga.Anchor.Modeling;
namespace SavageTools.Characters
{
public class CharacterCollection : ModelCollection<Character>
{
}
}
<file_sep>namespace SavageToolsWeb.Pages
{
partial class DeadlandsPage
{
protected override string SettingFileName => "Deadlands Weird West.savage-setting";
}
}
<file_sep># SavageTools
Random NPC generator for Savage Worlds
<file_sep>using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Tortuga.Anchor.Modeling;
namespace SavageTools.Characters
{
public class PowerGroupCollection : ChangeTrackingModelCollection<PowerGroup>
{
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public PowerGroupCollection()
{
ItemPropertyChanged += (s, e) => OnPropertyChanged("UnusedPowers");
CollectionChanged += (s, e) => OnPropertyChanged("UnusedPowers");
}
public int UnusedPowers => this.Sum(p => p.UnusedPowers);
public PowerGroup this[string powerType]
{
get
{
var result = this.FirstOrDefault(s => s.PowerType == powerType);
if (result == null)
{
result = new PowerGroup() { PowerType = powerType };
Add(result);
}
return result;
}
}
public bool ContainsPower(string power, string trapping)
{
return this.Any(g => g.Powers.Any(p => p.Name == power && p.Trapping == trapping));
}
}
}
<file_sep>using System.Linq;
namespace SavageTools.Utilities
{
public record EtuAdventure(NameDescriptionPair Who, NameDescriptionPair What, NameDescriptionPair Why, NameDescriptionPair Where, NameDescriptionPair Complications);
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tortuga.Anchor;
using Tortuga.Anchor.Modeling;
namespace SavageTools.Characters
{
public class Character : ChangeTrackingModelBase
{
public Trait Agility { get => Get<Trait>(); set => Set(value); }
public string Archetype { get { return Get<string>(); } set { Set(value); } }
public int Armor { get { return Get<int>(); } set { Set(value); } }
public EdgeCollection Edges => GetNew<EdgeCollection>();
public int Experience { get => Get<int>(); set => Set(value); }
public int Wounds { get => Get<int>(); set => Set(value); }
/// <summary>
/// Gets or sets the resilient wounds.
/// </summary>
/// <remarks>These are ignored for wild cards. Only extras benefit from resilient wounds</remarks>
public int ResilientWounds { get => Get<int>(); set => Set(value); }
[CalculatedField("Size,Wounds,IsWildCard,ResilientWounds")]
public int? TotalWounds
{
get
{
//Some very large non-wild cards still get wounds
var total = Wounds + ExtraWoundsFromSize;
if (IsWildCard)
total += 3;
else
total += ResilientWounds;
return total > 0 ? (int?)total : null;
}
}
[CalculatedField("Size")]
public int ExtraWoundsFromSize
{
get
{
if (Size <= 3)
return 0;
else if (4 <= Size && Size <= 7)
return 1;
else if (8 <= Size && Size <= 11)
return 2;
else if (12 <= Size && Size <= 20)
return 3;
else
return 4;
}
}
[CalculatedField("Size")]
public int ScaleModifierFromSize
{
get
{
if (Size <= -4)
return -6;
else if (Size == -3)
return -4;
else if (Size == -2)
return -2;
else if (-1 <= Size && Size <= 3)
return 0;
else if (4 <= Size && Size <= 7)
return 2;
else if (8 <= Size && Size <= 11)
return 4;
else if (12 <= Size && Size <= 20)
return 6;
else
return 4;
}
}
public int? Fear { get { return Get<int?>(); } set { Set(value); } }
public FeatureCollection Features => GetNew<FeatureCollection>();
public GearCollection Gear => GetNew<GearCollection>();
public string Gender { get => Get<string>(); set => Set(value); }
[CalculatedField("Size")]
public string HeightFromSize
{
get
{
if (Size < -6)
return "Swarm";
switch (Size)
{
case -4: return "Up to 6\"";
case -3: return "Up to 18\"";
case -2: return "Up to 3'";
case -1: return "Up to 4'";
case 0: return "Up to 6'";
case 1: return "Up to 8'";
case 2: return "Up to 9'";
case 3: return "Up to 12'";
case 4: return "Up to 15'";
case 5: return "Up to 18'";
case 6: return "Up to 24'";
case 7: return "Up to 30'";
case 8: return "Up to 36'";
case 9: return "Up to 50'";
case 10: return "Up to 63'";
case 11: return "Up to 75'";
case 12: return "Up to 100'";
case 13: return "Up to 125'";
case 14: return "Up to 150'";
case 15: return "Up to 200'";
case 16: return "Up to 250'";
case 17: return "Up to 300'";
case 18: return "Up to 400'";
case 19: return "Up to 500'";
case 20: return "Up to 600'";
default: return "";
}
}
}
public bool AnimalIntelligence { get { return Get<bool>(); } set { Set(value); } }
public HindranceCollection Hindrances => GetNew<HindranceCollection>();
public bool IsWildCard { get { return Get<bool>(); } set { Set(value); } }
public Trait MaxAgility { get => GetDefault<Trait>(12); set => Set(value); }
public int MaximumStrain { get { return Get<int>(); } set { Set(value); } }
[CalculatedField("MaximumStrain,Spirit,Vigor")]
public int MaximumStrainTotal => MaximumStrain + Math.Min(Spirit.Score, Vigor.Score);
public Trait MaxSmarts { get => GetDefault<Trait>(12); set => Set(value); }
public Trait MaxSpirit { get => GetDefault<Trait>(12); set => Set(value); }
public Trait MaxStrength { get => GetDefault<Trait>(12); set => Set(value); }
public Trait MaxVigor { get => GetDefault<Trait>(12); set => Set(value); }
public string Name { get => Get<string>(); set => Set(value); }
public int Pace { get { return GetDefault(6); } set { Set(value); } }
public int Parry { get { return Get<int>(); } set { Set(value); } }
public int ParryTotal => 2 + (Skills.SingleOrDefault(s => s.Name == "Fighting")?.Trait.HalfScore ?? 0);
public PersonalityCollection Personality => GetNew<PersonalityCollection>();
public PowerGroupCollection PowerGroups => GetNew<PowerGroupCollection>();
public string Race { get { return Get<string>(); } set { Set(value); } }
public string Rank { get { return Get<string>(); } set { Set(value); } }
public int Reason { get { return Get<int>(); } set { Set(value); } }
[CalculatedField("Reason,Spirit")]
public int ReasonTotal => 2 + Spirit.HalfScore + Reason;
public Trait Running { get { return GetDefault<Trait>(6); } set { Set(value); } }
public int Size { get { return Get<int>(); } set { Set(value); } }
public SkillCollection Skills => GetNew<SkillCollection>();
public Trait Smarts { get => Get<Trait>(); set => Set(value); }
public Trait Spirit { get => Get<Trait>(); set => Set(value); }
public int Status { get { return GetDefault(2); } set { Set(value); } }
public int Strain { get { return Get<int>(); } set { Set(value); } }
public Trait Strength { get => Get<Trait>(); set => Set(value); }
public int Toughness { get { return Get<int>(); } set { Set(value); } }
[CalculatedField("Vigor,Armor,Toughness")]
public int ToughnessTotal => 2 + Vigor.HalfScore + Toughness + Size + Armor;
public int UnusedAdvances { get { return Get<int>(); } set { Set(value); } }
public int UnusedAttributes { get { return Get<int>(); } set { Set(value); } }
public int UnusedEdges { get { return Get<int>(); } set { Set(value); } }
public int UnusedHindrances { get { return Get<int>(); } set { Set(value); } }
public int UnusedIconicEdges { get { return Get<int>(); } set { Set(value); } }
public int UnusedRacialEdges { get { return Get<int>(); } set { Set(value); } }
public int UnusedSkills { get { return Get<int>(); } set { Set(value); } }
public int UnusedSmartSkills { get { return Get<int>(); } set { Set(value); } }
public bool UseReason { get => Get<bool>(); set => Set(value); }
public bool UseStatus { get => Get<bool>(); set => Set(value); }
public bool UseStrain { get => Get<bool>(); set => Set(value); }
public Trait Vigor { get => Get<Trait>(); set => Set(value); }
[CalculatedField("Size")]
public string WeightFromSize
{
get
{
if (Size < -6)
return "Swarm";
switch (Size)
{
case -4: return "Up to 4 lbs";
case -3: return "Up to 16 lbs";
case -2: return "Up to 32 lbs";
case -1: return "Up to 125 lbs";
case 0: return "Up to 250 lbs";
case 1: return "Up to 500 lbs";
case 2: return "Up to 1,000 lbs";
case 3: return "Up to 1 ton ";
case 4: return "Up to 2 tons";
case 5: return "Up to 4 tons";
case 6: return "Up to 8 tons";
case 7: return "Up to 16 tons";
case 8: return "Up to 32 tons";
case 9: return "Up to 64 tons";
case 10: return "Up to 125 tons";
case 11: return "Up to 250 tons";
case 12: return "Up to 500 tons";
case 13: return "Up to 1K tons";
case 14: return "Up to 2K tons";
case 15: return "Up to 4K tons";
case 16: return "Up to 8K tons";
case 17: return "Up to 16K tons";
case 18: return "Up to 32K tons";
case 19: return "Up to 64K tons";
case 20: return "Up to 125K tons";
default: return "";
}
}
}
//public Character Clone()
//{
// var result = new Character()
// {
// Agility = Agility,
// Archetype = Archetype,
// Armor = Armor,
// Experience = Experience,
// Fear = Fear,
// Gender = Gender,
// IsWildCard = IsWildCard,
// MaxAgility = MaxAgility,
// MaximumStrain = MaximumStrain,
// MaxSmarts = MaxSmarts,
// MaxSpirit = MaxSpirit,
// MaxVigor = MaxVigor,
// MaxStrength = MaxStrength,
// Name = Name,
// Pace = Pace,
// Parry = Parry,
// Race = Race,
// Rank = Rank,
// Reason = Reason,
// Size = Size,
// Smarts = Smarts,
// Spirit = Spirit,
// Status = Status,
// Strain = Strain,
// Strength = Strength,
// Toughness = Toughness,
// UnusedAdvances = UnusedAdvances,
// UnusedAttributes = UnusedAttributes,
// UnusedEdges = UnusedEdges,
// UnusedHindrances = UnusedHindrances,
// UnusedIconicEdges = UnusedIconicEdges,
// UnusedRacialEdges = UnusedRacialEdges,
// UnusedSkills = UnusedSkills,
// UnusedSmartSkills = UnusedSmartSkills,
// UseReason = UseReason,
// UseStatus = UseStatus,
// UseStrain = UseStrain,
// Running = Running,
// Vigor = Vigor,
// };
// result.Edges.AddRange(Edges.Select(e => e.Clone()));
// result.Features.AddRange(Features.Select(e => e.Clone()));
// result.Skills.AddRange(Skills.Select(e => e.Clone()));
// result.PowerGroups.AddRange(PowerGroups.Select(e => e.Clone()));
// result.Gear.AddRange(Gear.Select(e => e.Clone()));
// result.Hindrances.AddRange(Hindrances.Select(e => e.Clone()));
// return result;
//}
/// <summary>
/// Determines whether the specified feature has feature.
/// </summary>
/// <param name="feature">The feature.</param>
/// <param name="ignoreRank">if set to <c>true</c> to ignore rank. This is used by the "Born a Hero" option.</param>
/// <returns><c>true</c> if the specified feature has feature; otherwise, <c>false</c>.</returns>
public bool HasFeature(string feature, bool ignoreRank)
{
if (string.IsNullOrEmpty(feature))
throw new ArgumentException($"{nameof(feature)} is null or empty.", nameof(feature));
if (feature.Contains(" or "))
{
var parts = feature.Split(new[] { " or " }, StringSplitOptions.None).Select(f => f.Trim());
foreach (var part in parts)
{
if (HasFeature(part, ignoreRank))
return true;
}
return false;
}
var name = feature;
Trait? trait = null;
if (name.EndsWith(" d4"))
{
trait = 4;
name = name.Substring(0, name.Length - 3);
}
else if (name.EndsWith(" d6"))
{
trait = 6;
name = name.Substring(0, name.Length - 3);
}
else if (name.EndsWith(" d8"))
{
trait = 8;
name = name.Substring(0, name.Length - 3);
}
else if (name.EndsWith(" d10"))
{
trait = 10;
name = name.Substring(0, name.Length - 4);
}
else if (name.EndsWith(" d12"))
{
trait = 12;
name = name.Substring(0, name.Length - 4);
}
//Check for ranks
switch (name)
{
//TODO-31: Load Experience values from settings files
case "Novice": return true;
case "Seasoned": return ignoreRank || Experience >= 20;
case "Veteran": return ignoreRank || Experience >= 40;
case "Heroic": return ignoreRank || Experience >= 60;
case "Legendary": return ignoreRank || Experience >= 80;
}
if (name == "Wild Card")
return IsWildCard;
//Check for attributes
switch (name)
{
case "Vigor": return trait == null || Vigor >= trait;
case "Smarts": return trait == null || Smarts >= trait;
case "Agility": return trait == null || Agility >= trait;
case "Strength": return trait == null || Strength >= trait;
case "Spirit": return trait == null || Spirit >= trait;
case "Status": return trait == null || Status >= trait;
case "Reason": return trait == null || ReasonTotal >= trait;
}
//Check for skills
foreach (var skill in Skills.Where(s => s.Trait > 0))
{
if (skill.Name == name)
return (trait == null) || (skill.Trait > trait);
}
//Check for edges
if (Edges.Any(e => e.Name == name))
return true;
//Check for hindrances
if (Hindrances.Any(e => e.Name == name))
return true;
//Check for actual features
if (Features.Any(e => e.Name == name))
return true;
//Debug.WriteLine("Does not have feature " + feature);
return false;
}
public void Increment(string trait, Dice dice) => Increment(trait, 1, dice);
public void Increment(string trait, int bonus, Dice dice)
{
if (string.IsNullOrEmpty(trait))
throw new ArgumentException($"{nameof(trait)} is null or empty.", nameof(trait));
if (dice == null)
throw new ArgumentNullException(nameof(dice), $"{nameof(dice)} is null.");
switch (trait)
{
case "Vigor": Vigor += bonus; return;
case "Smarts": Smarts += bonus; return;
case "Agility": Agility += bonus; return;
case "Strength": Strength += bonus; return;
case "Spirit": Spirit += bonus; return;
case "MaxVigor": MaxVigor += bonus; return;
case "MaxSmarts": MaxSmarts += bonus; return;
case "MaxAgility": MaxAgility += bonus; return;
case "MaxStrength": MaxStrength += bonus; return;
case "MaxSpirit": MaxSpirit += bonus; return;
case "Pace": Pace += bonus; return;
case "Running": Running += bonus; return;
case "Fear": Fear = (Fear ?? 0) + bonus; return; //A bonus of 0 will set it to 0
case "Parry": Parry += bonus; return;
case "Toughness": Toughness += bonus; return;
case "Strain": Strain += bonus; return;
case "MaximumStrain": MaximumStrain += bonus; return;
case "Reason": Reason += bonus; return;
case "Status": Status += bonus; return;
case "Size": Size += bonus; return;
case "Armor": Armor += bonus; return;
case "Wounds": Wounds += bonus; return;
case "ResilientWounds": ResilientWounds += bonus; return;
case "UnusedAttributes": UnusedAttributes += bonus; return;
case "UnusedSkills": UnusedSkills += bonus; return;
case "UnusedSmartSkills": UnusedSmartSkills += bonus; return;
case "UnusedEdges": UnusedEdges += bonus; return;
case "UnusedRacialEdges": UnusedRacialEdges += bonus; return;
case "UnusedHindrances": UnusedHindrances += bonus; return;
case "UnusedAdvances": UnusedAdvances += bonus; return;
case "PowerPoints": dice.Choose(PowerGroups).PowerPoints += bonus; return;
case "UnusedPowers": dice.Choose(PowerGroups).UnusedPowers += bonus; return;
}
if (trait.StartsWith("PowerPoints:"))
{
PowerGroups[trait.Substring("PowerPoints:".Length)].PowerPoints += bonus;
return;
}
if (trait.StartsWith("UnusedPowers:"))
{
PowerGroups[trait.Substring("UnusedPowers:".Length)].UnusedPowers += bonus;
return;
}
throw new ArgumentException("Unknown trait " + trait);
}
internal Trait GetAttribute(string attribute)
{
switch (attribute)
{
case "Vigor": return Vigor;
case "Smarts": return Smarts;
case "Agility": return Agility;
case "Strength": return Strength;
case "Spirit": return Spirit;
}
throw new ArgumentException("Unknown attribute " + attribute);
}
//[Obsolete]
//public string ToCompactString(bool useHtml)
//{
// var s = new StoryBuilder(useHtml);
// CopyToStory(s);
// return s.ToString();
//}
public string ToMarkdownString(bool isCompact)
{
var output = new StringBuilder();
//helper functions
void Append(string content)
{
output.Append(content);
}
void AppendLine(string? content = null)
{
output.AppendLine(content).AppendLine();
}
void AppendBullet(string content)
{
output.AppendLine("* " + content);
}
void AppendList<T>(string? header, IEnumerable<T> items, Func<T, string>? formatter = null)
{
if (formatter == null)
AppendLine(header + string.Join(", ", items.Select(e => e?.ToString())));
else
AppendLine(header + string.Join(", ", items.Select(formatter)));
}
AppendLine($"### {Name}");
{
var additionTraits = new List<string>();
if (!string.IsNullOrWhiteSpace(Archetype) && Archetype != "(None)")
additionTraits.Add($"**Archetype**: {Archetype}");
if (!string.IsNullOrEmpty(Gender))
additionTraits.Add($"**Race**: {Race} ({Gender})");
else
additionTraits.Add($"**Race**: {Race}");
if (!string.IsNullOrWhiteSpace(Rank) && Rank != "Novice")
additionTraits.Add($"**Rank**: {Rank}");
if (IsWildCard)
additionTraits.Add($"**Wild Card**");
if (additionTraits.Count > 0)
AppendLine(string.Join(" ", additionTraits));
}
AppendLine($"**Attributes:** Agility {Agility + (MaxAgility != 12 ? " (Max " + MaxAgility + ")" : null)}, Smarts {Smarts + (AnimalIntelligence ? " (A)" : "") + (MaxSmarts != 12 ? " (Max " + MaxSmarts + ")" : null)}, Spirt {Spirit + (MaxSpirit != 12 ? " (Max " + MaxSpirit + ")" : null)}, Strength {Strength + (MaxStrength != 12 ? " (Max " + MaxStrength + ")" : null)}, Vigor {Vigor + (MaxVigor != 12 ? " (Max " + MaxVigor + ")" : null)}");
Append($"**Parry** {ParryTotal}, **Toughness** {ToughnessTotal}");
if (Armor > 0)
Append($" ({Armor})");
if (TotalWounds > 0)
Append($", **Wounds** {TotalWounds}");
Append($", **Pace** {Pace}+{Running}");
if (Size != 0)
Append($", **Size** {Size} ({HeightFromSize}, {WeightFromSize})");
AppendLine();
{
var additionTraits = new List<string>();
if (Fear == 0)
additionTraits.Add($"**Fear**");
else if (Fear.HasValue)
additionTraits.Add($"**Fear** {Fear}");
if (UseReason)
additionTraits.Add($"**Reason** {ReasonTotal}");
if (UseStatus)
additionTraits.Add($"**Status** {Status}");
if (UseStrain)
additionTraits.Add($"**Strain** {Strain}/{MaximumStrainTotal}");
if (additionTraits.Count > 0)
AppendList(null, additionTraits);
}
if (Skills.Count > 0)
AppendList("**Skills:** ", Skills, s => s.ShortName);
if (Edges.Count > 0)
{
if (isCompact)
AppendList("**Edges:** ", Edges, e => e.Name);
else
{
AppendLine("#### Edges");
foreach (var edge in Edges)
if (edge.Description.IsNullOrEmpty())
AppendBullet($"**{edge.Name}**");
else
AppendBullet($"**{edge.Name}:** {edge.Description}");
AppendLine();
}
}
if (Hindrances.Count > 0)
{
if (isCompact)
AppendList("**Hindrances:** ", Hindrances, h => h.Name + (h.Level == 2 ? " (major)" : ""));
else
{
AppendLine("#### Hindrances");
foreach (var hindrance in Hindrances)
if (hindrance.Description.IsNullOrEmpty())
AppendBullet($"**{hindrance.Name}**" + (hindrance.Level == 2 ? " (major)" : ""));
else
AppendBullet($"**{hindrance.Name}:**" + (hindrance.Level == 2 ? " (major) " : " ") + hindrance.Description);
AppendLine();
}
}
if (Features.Count > 0)
AppendList("**Features:** ", Features, f => f.Name);
if (Personality.Count > 0)
AppendList("**Personality:** ", Personality, p => p.Name);
foreach (var group in PowerGroups)
AppendList($"**{group.PowerType}**: Power Points {group.PowerPoints}, Powers: ", group.Powers, p => p.LongName);
if (Gear.Count > 0)
AppendList("**Gear:** ", Gear, g => g.Name + (string.IsNullOrEmpty(g.Description) ? "" : ": " + g.Description));
return output.ToString();
}
public void Cleanup()
{
//Remove the skills that were not chosen
foreach (var item in Skills.Where(s => s.Trait == 0).ToList())
Skills.Remove(item);
//Sorting
Skills.Sort(s => s.Name);
Edges.Sort(e => e.Name);
Hindrances.Sort(h => h.Name);
Features.Sort(f => f.Name);
foreach (var group in PowerGroups)
group.Powers.Sort(p => p.LongName);
}
//[Obsolete]
//public void CopyToStory(StoryBuilder story, bool indentAfterName = false)
//{
// if (story == null)
// throw new ArgumentNullException(nameof(story), $"{nameof(story)} is null.");
// if (!string.IsNullOrEmpty(Gender))
// story.Append($"{Name} ({Gender})");
// else
// story.Append($"{Name}");
// if (indentAfterName)
// story.IncreaseIndent();
// if (!string.IsNullOrWhiteSpace(Archetype) && Archetype != "(None)")
// story.Append($", {Archetype}");
// if (Race != "Human")
// story.Append($", {Race}");
// if (Rank != "Novice")
// story.Append($", Rank {Rank}");
// story.AppendLine();
// story.AppendLine($"Agility {Agility}, Smarts {Smarts}{ (AnimalIntelligence ? " (A)" : "")}, Strength {Strength}, Spirt {Spirit}, Vigor {Vigor}");
// story.Append($"Parry {ParryTotal}, Toughness {ToughnessTotal}, Pace {Pace}+{Running}, Size {Size}, ");
// var additionTraits = new List<string>();
// if (Fear == 0)
// additionTraits.Add($"Fear");
// else if (Fear.HasValue)
// additionTraits.Add($"Fear {Fear}");
// if (UseReason)
// additionTraits.Add($"Reason {ReasonTotal}");
// if (UseStatus)
// additionTraits.Add($"Status {Status}");
// if (UseStrain)
// additionTraits.Add($"Strain {Strain}/{MaximumStrainTotal}");
// if (additionTraits.Count > 0)
// story.AppendLine(string.Join(", ", additionTraits));
// if (Skills.Count > 0)
// story.AppendLine(string.Join(", ", Skills.Select(s => s.ShortName)));
// if (Edges.Count > 0)
// story.AppendLine(string.Join(", ", Edges.Select(e => e.ToString())));
// if (Hindrances.Count > 0)
// story.AppendLine(string.Join(", ", Hindrances.Select(h => h.ToString())));
// if (Features.Count > 0)
// story.AppendLine(string.Join(", ", Features.Select(h => h.Name)));
// if (Personality.Count > 0)
// story.AppendLine(string.Join(", ", Personality.Select(h => h.Name)));
// foreach (var group in PowerGroups)
// story.AppendLine($"{group.PowerType}, Power Points {group.PowerPoints}, Powers: {string.Join(", ", group.Powers.Select(p => p.LongName))}");
// if (Gear.Count > 0)
// story.AppendLine(string.Join(", ", Gear.Select(h => h.Name + (string.IsNullOrEmpty(h.Description) ? "" : ": " + h.Description))));
// if (indentAfterName)
// story.DecreaseIndent();
//}
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace Tortuga.Anchor
{
public static class Missing
{
/// <summary>
/// In place sort.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TKey"></typeparam>
/// <param name="entries"></param>
/// <param name="comparer"></param>
public static void Sort<T, TKey>(this IList<T> entries, Func<T, TKey> comparer) where TKey : IComparable<TKey>
{
if (entries == null)
throw new ArgumentNullException("entries", "entries is null.");
if (comparer == null)
throw new ArgumentNullException("comparer", "comparer is null.");
entries.Sort(new CompareByKey<T, TKey>(comparer));
}
class CompareByKey<T, TKey> : IComparer<T> where TKey : IComparable<TKey>
{
private Func<T, TKey> m_GetKey;
public CompareByKey(Func<T, TKey> getKey)
{
m_GetKey = getKey;
}
int IComparer<T>.Compare(T? x, T? y)
{
if (x == null)
throw new ArgumentNullException(nameof(x), $"{nameof(x)} is null.");
if (y == null)
throw new ArgumentNullException(nameof(y), $"{nameof(y)} is null.");
return m_GetKey(x).CompareTo(m_GetKey(y));
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
namespace SavageTools
{
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
public class Table<T> : List<KeyValuePair<T, int>> //Using a KeyValuePair because its cheaper than a Tuple
{
public void Add(T item, int odds) => Add(new KeyValuePair<T, int>(item, odds));
public T RandomChoose(Dice dice)
{
if (dice == null)
throw new ArgumentNullException(nameof(dice), $"{nameof(dice)} is null.");
if (Count == 0)
throw new InvalidOperationException("The list is empty.");
var max = this.Sum(option => option.Value);
var roll = dice.Next(1, max + 1);
foreach (var option in this)
{
roll -= option.Value;
if (roll <= 0)
return option.Key;
}
throw new InvalidOperationException("This cannot happen");
}
public T RandomPick(Dice dice)
{
if (dice == null)
throw new ArgumentNullException(nameof(dice), $"{nameof(dice)} is null.");
if (Count == 0)
throw new InvalidOperationException("The list is empty.");
var max = this.Sum(option => option.Value);
var roll = dice.Next(1, max + 1);
foreach (var option in this)
{
roll -= option.Value;
if (roll <= 0)
{
Remove(option);
return option.Key;
}
}
throw new InvalidOperationException("This cannot happen");
}
}
}
<file_sep>namespace SavageToolsWeb.Pages
{
partial class FutureTechPage
{
protected override string SettingFileName => "Future Tech.savage-setting";
}
}
<file_sep>using System.Linq;
using Tortuga.Anchor.Modeling;
namespace SavageTools.Characters
{
public class PowerGroup : ChangeTrackingModelBase
{
/// <summary>
/// Gets the available powers.
/// </summary>
/// <value>The available powers.</value>
/// <remarks>If empty, uses the default collection</remarks>
public StringCollection AvailablePowers => GetNew<StringCollection>();
/// <summary>
/// Gets the list of available triggers.
/// </summary>
/// <remarks>If empty, no trigger will be generated.</remarks>
public StringCollection AvailableTriggers => GetNew<StringCollection>();
/// <summary>
/// Gets the available trappings.
/// </summary>
/// <value>The available trappings.</value>
/// <remarks>If empty, uses the default collection</remarks>
public StringCollection AvailableTrappings => GetNew<StringCollection>();
public string PowerList => string.Join(", ", Powers.Select(p => p.LongName));
public int PowerPoints { get => Get<int>(); set => Set(value); }
public PowerCollection Powers => GetNew<PowerCollection>();
/// <summary>
/// Gets the prohibited trappings.
/// </summary>
/// <value>The prohibited trappings.</value>
public StringCollection ProhibitedTrappings => GetNew<StringCollection>();
public string PowerType { get => Get<string>(); set => Set(value); }
public int UnusedPowers { get => Get<int>(); set => Set(value); }
//public PowerGroup Clone()
//{
// var result = new PowerGroup() { PowerPoints = PowerPoints, PowerType = PowerType, UnusedPowers = UnusedPowers };
// result.ProhibitedTrappings.AddRange(ProhibitedTrappings);
// result.AvailableTrappings.AddRange(AvailableTrappings);
// result.Powers.AddRange(Powers.Select(x => x.Clone()));
// return result;
//}
}
}
<file_sep>using System;
using Tortuga.Anchor.Modeling;
namespace SavageTools.Characters
{
public class Skill : ChangeTrackingModelBase
{
public Skill(string name, string attribute)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentException($"{nameof(name)} is null or empty.", nameof(name));
if (string.IsNullOrEmpty(attribute))
throw new ArgumentException($"{nameof(attribute)} is null or empty for skill {name}.", nameof(attribute));
Name = name;
Attribute = attribute;
}
public string Attribute { get => Get<string>(); set => Set(value); }
public string LongName => $"{Name} [{Attribute}] {Trait}";
public string Name { get => Get<string>(); set => Set(value); }
public string ShortName => $"{Name} {Trait}";
public Trait Trait { get => GetDefault<Trait>(4); set => Set(value); }
public Trait MaxLevel { get => GetDefault<Trait>(12); set => Set(value); }
public override string ToString() => LongName;
//public Skill Clone()
//{
// return new Skill(Name, Attribute) { Trait = Trait };
//}
}
}
<file_sep>using System;
using System.Diagnostics.CodeAnalysis;
namespace SavageTools
{
[SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")]
public enum Rank
{
Two = 2,
Three = 3,
Four = 4,
Five = 5,
Six = 6,
Seven = 7,
Eight = 8,
Nine = 9,
Ten = 10,
Jack = 11,
Queen = 12,
King = 13,
Ace = 14,
Joker = 15
}
}
<file_sep>using System.Linq;
using Tortuga.Anchor.Modeling;
namespace SavageTools.Characters
{
public class PersonalityCollection : ChangeTrackingModelCollection<Personality>
{
internal void Add(string name)
{
if (!this.Any(f => f.Name == name))
Add(new Personality() { Name = name });
}
}
}<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using SavageTools.Characters;
using SavageTools.Settings;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
namespace SavageTools.Test
{
[TestClass]
public class SettingsFilesTests
{
static readonly XmlSerializer SettingXmlSerializer = new XmlSerializer(typeof(Setting));
static readonly DirectoryInfo Root = new DirectoryInfo(@".\Settings");
[TestMethod]
public void LoadAllSettingFiles()
{
//var settings = new Dictionary<string, FileInfo>(StringComparer.OrdinalIgnoreCase);
var characterGenerators = new Dictionary<string, CharacterGenerator>(StringComparer.OrdinalIgnoreCase);
foreach (var file in Root.GetFiles("*.savage-setting"))
{
Debug.WriteLine($"Loading {file.Name}");
Setting book;
// Open document
using (var stream = file.OpenRead())
book = (Setting)SettingXmlSerializer.Deserialize(stream);
//if (book.ShowSetting)
// settings.Add(book.Name, file);
characterGenerators.Add(book.Name, new CharacterGenerator(file));
}
}
[DataRow("Core.savage-setting")]
[TestMethod]
public void ApplyAllMajorHindrances(string settingName)
{
var dice = new Dice(0);
var file = new FileInfo(Path.Combine(Root.FullName, settingName));
var characterGenerator = new CharacterGenerator(file);
var character = new Character()
{
Strength = 6,
Agility = 6,
Smarts = 6,
Spirit = 6,
Vigor = 6
};
foreach (var hindrance in characterGenerator.MajorHindrances)
CharacterGenerator.ApplyHindrance(character, hindrance, 2, dice);
Debug.WriteLine(character.ToMarkdownString(false));
}
[DataRow("Core.savage-setting")]
[TestMethod]
public void ApplyAllMinorHindrances(string settingName)
{
var dice = new Dice(0);
var file = new FileInfo(Path.Combine(Root.FullName, settingName));
var characterGenerator = new CharacterGenerator(file);
var character = new Character()
{
Strength = 6,
Agility = 6,
Smarts = 6,
Spirit = 6,
Vigor = 6
};
foreach (var hindrance in characterGenerator.MinorHindrances)
CharacterGenerator.ApplyHindrance(character, hindrance, 1, dice);
Debug.WriteLine(character.ToMarkdownString(false));
}
[DataRow("Core.savage-setting")]
[TestMethod]
public void ApplyAllEdges(string settingName)
{
var dice = new Dice(0);
var file = new FileInfo(Path.Combine(Root.FullName, settingName));
var characterGenerator = new CharacterGenerator(file);
var character = new Character()
{
Strength = 6,
Agility = 6,
Smarts = 6,
Spirit = 6,
Vigor = 6
};
foreach (var edge in characterGenerator.Edges)
characterGenerator.ApplyEdge(character, edge, dice);
Debug.WriteLine(character.ToMarkdownString(false));
}
const int Iterations = 100;
[DataRow("Core.savage-setting", "(None)")]
[TestMethod]
public void MakeArchetype(string settingName, string selectedArchetype)
{
var dice = new Dice(0);
var file = new FileInfo(Path.Combine(Root.FullName, settingName));
var characterGenerator = new CharacterGenerator(file);
for (var i = 0; i < Iterations; i++)
{
Character character = MakeCharacter(characterGenerator, dice, selectedArchetype, null, null);
Debug.WriteLine(character.ToMarkdownString(false));
}
}
static Character MakeCharacter(CharacterGenerator characterGenerator, Dice dice,
string selectedArchetype, string selectedRank, string selectedRace)
{
var options = new CharacterOptions(characterGenerator);
//Archetypes
if (selectedArchetype == null)
options.SelectedArchetype = null;
else
options.SelectedArchetype = characterGenerator.Archetypes.SingleOrDefault(a => a.Name == selectedArchetype);
//Ranks
if (selectedRank == null)
options.SelectedRank = null;
else
options.SelectedRank = characterGenerator.Ranks.SingleOrDefault(a => a.Name == selectedRank);
//Race
if (selectedRace == null)
options.SelectedRace = null;
else
options.SelectedRace = characterGenerator.Races.SingleOrDefault(a => a.Name == selectedRace);
return characterGenerator.GenerateCharacter(options, dice);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Tortuga.Anchor;
namespace SavageTools
{
public class Dice : RandomExtended
{
List<Card> m_Deck = new List<Card>();
public Dice(int seed) : base(seed)
{
}
public Dice()
{
}
void ShuffleCards()
{
var deck = new List<Card>();
for (var rank = Rank.Two; rank <= Rank.Ace; rank++)
for (var suit = Suit.Spades; suit <= Suit.Diamonds; suit++)
deck.Add(new Card(suit, rank));
deck.Add(new Card(Suit.RedJ, Rank.Joker));
deck.Add(new Card(Suit.BlackJ, Rank.Joker));
m_Deck = deck;
}
/// <summary>
/// Chooses a card from the deck, then put it back.
/// </summary>
/// <returns>Card.</returns>
/// <remarks>If the card deck is empty, shuffle.</remarks>
public Card ChooseCard()
{
if (m_Deck.Count == 0)
ShuffleCards();
return Choose(m_Deck);
}
/// <summary>
/// Pick a card from the deck. This card may not be pulled again.
/// </summary>
/// <returns>Card.</returns>
/// <remarks>If the card deck is empty, shuffle.</remarks>
public Card PickCard()
{
if (m_Deck.Count == 0)
ShuffleCards(); return Pick(m_Deck);
}
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "D")]
public int D(int count, int die)
{
var result = 0;
for (var i = 0; i < count; i++)
result += Next(1, die + 1);
return result;
}
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "D")]
public int D(int die) => D(1, die);
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "D")]
public int D(string dieCode)
{
if (string.IsNullOrWhiteSpace(dieCode))
return 0;
try
{
var result = 0;
var array = dieCode.ToUpperInvariant().Replace("-", "+-").Split(new[] { '+' });
foreach (var expression in array)
{
if (expression.StartsWith("D"))
{
result += D(1, int.Parse(expression.Substring(1)));
}
else if (expression.Contains("D"))
{
var isNegative = 1;
var fixedExpression = expression;
if (expression.StartsWith("-"))
{
isNegative = -1;
fixedExpression = expression.Substring(1);
}
var parts = fixedExpression.Split(new[] { 'D' }, StringSplitOptions.RemoveEmptyEntries).Select(i => int.Parse(i)).ToArray();
if (parts.Length == 1)
result += D(parts[0], 6) * isNegative;
else if (parts[1] == 66)
result += D66() * isNegative;
else
result += D(parts[0], parts[1]) * isNegative;
}
else if (expression.Length == 0)
{
//skip
}
else
{
result += int.Parse(expression);
}
}
return result;
}
catch (FormatException ex)
{
throw new ArgumentException(string.Format("Cannot parse '{0}'", dieCode), "dieCode", ex);
}
}
public int D66() => (Next(1, 7) * 10) + Next(1, 7);
public bool NextBoolean() => Next(0, 2) == 1;
}
}
<file_sep>using Tortuga.Anchor.Modeling;
namespace SavageTools.Characters
{
public class Hindrance : ChangeTrackingModelBase
{
public string Description { get => Get<string>(); set => Set(value); }
/// <summary>
/// Level 1 = minor, level 2 = major
/// Level 0 means it is a built-in complication that doesn't count towards the hindrance limit
/// </summary>
public int Level { get => Get<int>(); set => Set(value); }
public string LevelName
{
get
{
switch (Level)
{
case 0: return "";
case 1: return "(Minor)";
case 2: return "(Major)";
}
return "";
}
}
public string Name { get => Get<string>(); set => Set(value); }
public Hindrance Clone()
{
return new Hindrance() { Description = Description, Name = Name, Level = Level };
}
public override string ToString()
{
var text = (Name + " " + LevelName).Trim();
if (!string.IsNullOrEmpty(Description))
return text + ": " + Description;
else
return text;
}
}
}
<file_sep>namespace SavageTools.Characters
{
public class MissionOptions
{
//public decimal DistancePerDay => Pace / 2.0M * 8M;
//public int Pace { get; set; } = 6;
public bool UseHtml { get; set; }
//public int EventFrequency { get; set; } = 3;
//public int NumberOfCharacters { get; set; } = 1;
}
}
<file_sep>using Tortuga.Anchor.Modeling;
namespace SavageTools.Characters
{
public class EdgeCollection : ChangeTrackingModelCollection<Edge>
{
public void Add(string name)
{
Add(new Edge() { Name = name });
}
public void Add(string name, string? description)
{
Add(new Edge() { Name = name, Description = description });
}
}
}
<file_sep>using Tortuga.Anchor.Modeling;
namespace SavageTools.Characters
{
public class GearCollection : ChangeTrackingModelCollection<Gear>
{
public void Add(string name, string? description = null)
{
Add(new Gear() { Name = name, Description = description });
}
}
}
<file_sep>using Microsoft.AspNetCore.Components;
using SavageTools.Characters;
namespace SavageToolsWeb.Controls
{
partial class SettingHeader
{
[Parameter]
public CharacterOptions CharacterOptions { get; set; } = null!;
}
}
<file_sep>using SavageTools.Settings;
using System;
using System.Linq;
using Tortuga.Anchor.Modeling;
namespace SavageTools.Characters
{
public class CharacterOptions : ModelBase
{
public CharacterOptions(CharacterGenerator characterGenerator)
{
CharacterGenerator = characterGenerator ?? throw new ArgumentNullException(nameof(characterGenerator));
BornAHero = characterGenerator.BornAHeroSetting;
MoreSkills = characterGenerator.MoreSkillsSetting;
SelectedArchetype = characterGenerator.Archetypes.SingleOrDefault(a => a.Name == "(None)");
//SelectedRank = characterGenerator.Ranks.SingleOrDefault(a => a.Name == "Novice");
}
public CharacterCollection Squad { get => GetNew<CharacterCollection>(); }
public string DisplayMode { get => GetDefault("HTML"); set => Set(value); }
public bool BornAHero { get => GetDefault(false); set => Set(value); }
public bool MoreSkills { get => GetDefault(false); set => Set(value); }
public CharacterGenerator CharacterGenerator { get; }
public int Count
{
get { return GetDefault(1); }
set
{
if (value > 10)
Set(10);
else if (value <= 0)
Set(1);
else
Set(value);
}
}
[CalculatedField("SelectedArchetype")]
public bool RandomArchetype => SelectedArchetypeString == "";
[CalculatedField("SelectedRace")]
public bool RandomRace => SelectedRaceString == "";
[CalculatedField("SelectedRank")]
public bool RandomRank => SelectedRankString == "";
public SettingArchetype? SelectedArchetype
{
get { return Get<SettingArchetype>(); }
set
{
if (Set(value) && value != null && !string.IsNullOrEmpty(value.Race))
{
var newRace = CharacterGenerator.Races.SingleOrDefault(r => r.Name == value.Race);
if (newRace != null)
SelectedRace = newRace;
}
}
}
[CalculatedField("SelectedArchetype")]
public string? SelectedArchetypeString
{
get => SelectedArchetype?.Name ?? "";
set
{
if (string.IsNullOrEmpty(value))
SelectedArchetype = null;
else
SelectedArchetype = CharacterGenerator.Archetypes.Single(a => a.Name == value);
}
}
public SettingRace? SelectedRace { get { return Get<SettingRace>(); } set { Set(value); } }
[CalculatedField("SelectedRace")]
public string? SelectedRaceString
{
get => SelectedRace?.Name ?? "";
set
{
if (string.IsNullOrEmpty(value))
SelectedRace = null;
else
SelectedRace = CharacterGenerator.Races.Single(r => r.Name == value);
}
}
public SettingRank? SelectedRank { get { return Get<SettingRank>(); } set { Set(value); } }
[CalculatedField("SelectedRank")]
public string? SelectedRankString
{
get => SelectedRank?.Name ?? "";
set
{
if (string.IsNullOrEmpty(value))
SelectedRank = null;
else
SelectedRank = CharacterGenerator.Ranks.Single(r => r.Name == value);
}
}
public bool UseCoreSkills { get => GetDefault(true); set => Set(value); }
public bool WildCard { get => GetDefault(false); set => Set(value); }
public Character GenerateCharacter(Dice? dice = null)
{
return CharacterGenerator.GenerateCharacter(this, dice);
}
/*
public void LoadSetting(FileInfo file)
{
var currentArchetype = SelectedArchetype?.Name;
var currentRace = SelectedRace?.Name;
var currentRank = SelectedRank?.Name;
CharacterGenerator.LoadSetting(file, true);
if (currentArchetype != null && SelectedArchetype == null) //selected archetype was replaced so we need to reselect it
SelectedArchetype = CharacterGenerator.Archetypes.Single(a => a.Name == currentArchetype);
if (currentRace != null && SelectedRace == null) //selected race was replaced so we need to reselect it
SelectedRace = CharacterGenerator.Races.Single(a => a.Name == currentRace);
if (currentRank != null && SelectedRank == null) //selected rank was replaced so we need to reselect it
SelectedRank = CharacterGenerator.Ranks.Single(a => a.Name == currentRank);
if (CharacterGenerator.BornAHeroSetting)
BornAHero = true;
}
*/
}
}
<file_sep>using Tortuga.Anchor.Modeling;
namespace SavageTools.Characters
{
public class StringCollection : ChangeTrackingModelCollection<string> { }
}
<file_sep>using System;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
namespace SavageTools.Names
{
public class PersonalityService
{
readonly ImmutableArray<string> m_Personalities;
public PersonalityService(string dataPath)
{
var file = new FileInfo(Path.Combine(dataPath, "personality.txt"));
m_Personalities = File.ReadAllLines(file.FullName).Where(x => !string.IsNullOrEmpty(x)).Distinct().ToImmutableArray();
}
public string CreateRandomPersonality(Dice dice)
{
if (dice == null)
throw new ArgumentNullException(nameof(dice), $"{nameof(dice)} is null.");
return dice.Choose(m_Personalities);
}
}
}
<file_sep>using System.Linq;
using Tortuga.Anchor.Modeling;
namespace SavageTools.Characters
{
public class SkillCollection : ChangeTrackingModelCollection<Skill>
{
public Skill? this[string name] => this.FirstOrDefault(s => s.Name == name);
public bool Contains(string name) => this.Any(s => s.Name == name);
public void Add(string name, string attribute)
{
var skill = this.SingleOrDefault(s => s.Name == name);
if (skill != null)
skill.Trait += 1;
else
Add(new Skill(name, attribute) { Trait = 4 });
}
public void Add(string name, string attribute, Trait minLevel)
{
var skill = this.SingleOrDefault(s => s.Name == name);
if (skill != null)
{
if (skill.Trait < minLevel)
skill.Trait = minLevel;
}
else
Add(new Skill(name, attribute) { Trait = minLevel });
}
}
}
<file_sep>using SavageTools.Characters;
using System;
using System.Collections.Generic;
using System.Linq;
using static SavageTools.CardColor;
using static SavageTools.Rank;
using static SavageTools.Suit;
namespace SavageTools.Utilities
{
public class EtuAdventureGenerator
{
CharacterGenerator m_CharacterGenerator;
EtuDemonGenerator m_DemonGenerator;
public EtuAdventureGenerator(CharacterGenerator characterGenerator)
{
m_CharacterGenerator = characterGenerator;
m_DemonGenerator = new EtuDemonGenerator(characterGenerator);
}
public EtuAdventure GenerateAdventure()
{
var dice = new Dice();
return new EtuAdventure(Who(dice), What(dice), Why(dice), Where(dice), Complications(dice));
}
NameDescriptionPair Where(Dice dice)
{
var c = dice.PickCard();
switch (c)
{
case (_, Two):
case (_, Three):
case (_, Four):
case (_, Five):
switch (c.Suit)
{
case Spades: return new("Campus", "The incident occurs in the facilities.");
case Clubs: return new("Campus", "The incident occurs in the classrooms.");
default: return new("Campus", "The incident occurs in the dorms.");
}
case (_, Six):
case (_, Seven):
case (_, Eight):
if (c.Color == Red)
return new("Pinebox", "The incident occurs at an ongoing business such as the Pizza Barn or Sanctuary Comics.");
else
return new("Pinebox", "The incident occurs when the business was closed or the building was empty or abandoned.");
case (Spades, Nine) or (Spades, Ten):
return new("Home", "The incident occurs one of the older homes or ranches from Pinebox’s early days.");
case (Clubs, Nine) or (Clubs, Ten):
return new("Home", "The incident occurs in an apartment.");
case (Hearts, Nine) or (Hearts, Ten):
return new("Home", "The incident occurs in a small home.");
case (Diamonds, Nine) or (Diamonds, Ten):
return new("Home", "The incident occurs in a larger home or mansion.");
case (_, Jack):
case (_, Queen):
case (_, King):
return Environs(dice);
case (Spades, Ace):
case (Clubs, Ace):
return new("Out of Town", "The incident occurs in a nearby city such as Houston.");
case (Hearts, Ace):
return new("Out of Town", "The incident happens across the border in Mexico.");
case (Diamonds, Ace):
return new("Out of Town", "The incident occurs in another US town or city outside of Texas.");
case (_, Joker):
return new("Hero’s Home", "The event happens—or will happen—at one of the hero’s homes!");
}
return new("", "");
}
NameDescriptionPair Who(Dice dice)
{
switch (dice.PickCard())
{
case (_, Two, Red): return new("Student", "A fraternity or sorority member (and perhaps some companions) are up to no good.", GenerateCharacter(dice, "Student"));
case (_, Two): return new("Student", "A classmate (and perhaps some companions) are up to no good.", GenerateCharacter(dice, "Student"));
case (_, Three, Red): return new("Faculty", "One of ETU’s professors that a character knows.", GenerateCharacter(dice, "Professor"));
case (_, Three): return new("Faculty", "One of ETU’s professors that none of the characters know.", GenerateCharacter(dice, "Professor"));
case (Hearts, Four): return new("Townies", "The townies from Blackburn are up to mischief.", GenerateCharacter(dice, RandomTownieType(dice)));
case (Diamonds, Four): return new("Townies", "The townies from Morganville are up to mischief.", GenerateCharacter(dice, RandomTownieType(dice)));
case (_, Four): return new("Townies", "The locals are up to mischief.", GenerateCharacter(dice, RandomTownieType(dice)));
case (_, Five, Red): return new("Government", "The trouble comes from the local authorities.", GenerateCharacter(dice, "White Collar Worker"));
case (Clubs, Five): return new("Government", "The trouble comes from the military.", GenerateCharacter(dice, "White Collar Worker"));
case (Spades, Five): return new("Government", "The trouble comes from a secret government group.", GenerateCharacter(dice, "White Collar Worker"));
case (_, Six, Red): return new("Cult", "The bad guys are students in a weird cult looking to bring about some major change in the world—or destroy it!", GenerateCharacter(dice, "Cultist"));
case (Clubs, Six): return new("Cult", "The bad guys are townies in a weird cult looking to bring about some major change in the world—or destroy it!", GenerateCharacter(dice, "Cultist"));
case (Spades, Six): return new("Cult", "The bad guys are outsiders in a weird cult looking to bring about some major change in the world—or destroy it!", GenerateCharacter(dice, "Cultist"));
case (_, Seven, Red): return new("Animal", "An animal that may be natural but somehow forced into the mystery by other circumstances");
case (_, Seven): return new("Animal", "An animal that has have been altered somehow—perhaps by drinking from weird chemicals or as the result of a miscast ritual");
case (_, Eight): return new("Scientist", "A technically-minded person is messing with forces beyond her control.", GenerateCharacter(dice, "White Collar Worker"));
case (_, Nine): return new("Corporation", "A company (or at least part of it) is the primary actor.", GenerateCharacter(dice, "White Collar Worker"));
case (_, Ten): return new("Criminal/Organized Crime", "A criminal or group of criminals, or gang, are involved.", GenerateCharacter(dice, "Thug"));
case (_, Jack):
case (_, Queen):
case (_, King):
case (_, Ace):
return new("Supernatural", "A creature, ghost, demon, or human with supernatural abilities is on the prowl.", Supernatural(dice));
case (_, Joker):
var result = Who(dice);
result.AddLinkedItem(Who(dice));
return result;
}
return new("", "");
}
NameDescriptionPair Environs(Dice dice)
{
switch (dice.PickCard().Rank)
{
case Two:
case Three:
return new("<NAME>", "");
case Four: return new("Kestrell Lake", "");
case Five: return new("Lake Greystone", "");
case Six: return new("Old Mill Creek", "");
case Seven: return new("Base X", "");
case Eight: return new("The Burn", "");
case Nine: return new("Indian Mounds State Park", "");
case Ten: return new("<NAME>", "");
case Jack:
case Queen:
case King:
case Ace: return new("The Big Thicket", "");
case Joker: return new("A new area created by the Dean", "");
}
return new("", "");
}
NameDescriptionPair GenerateDemon(Dice dice)
{
var demon = m_DemonGenerator.GenerateDemon(dice);
var text = demon.ToMarkdownString(isCompact: false);
return new("Demon", text) { IsMarkdown = true };
}
NameDescriptionPair GenerateCharacter(Dice dice, string archetype)
{
var options = new CharacterOptions(m_CharacterGenerator);
options.SelectedArchetype = m_CharacterGenerator.Archetypes.Single(a => a.Name == archetype);
options.SelectedRace = m_CharacterGenerator.Races.Single(a => a.Name == "Human (PC)");
var character = m_CharacterGenerator.GenerateCharacter(options, dice);
var text = character.ToMarkdownString(isCompact: false);
return new("", text) { IsMarkdown = true };
}
NameDescriptionPair Supernatural(Dice dice)
{
switch (dice.PickCard())
{
case (_, Two):
case (_, Three):
case (_, Four): return new("Cryptid", "A natural but unproven creature such as a chupacabra, skunk ape, or night panther.");
case (_, Five): return new("Lycanthrope", "A werewolf or other hybrid.");
case (_, Six, Red): return new("Witch/Warlock", "The perpetrator is a master of the black arts.");
case (_, Six): return new("Witch/Warlock", "The perpetrator is apprentice, new recruit, or dabbler in the black arts.");
case (Hearts, Seven): return new("Vampire", "A old or ancient fiend with a network of lessers ");
case (_, Seven): return new("Vampire", "A bloodsucking fiend or similar parasitic humanoid has surfaced.");
case (_, Eight, Red): return new("Ghost", "Some unfortunate soul still lingers in our world. It was violent in life and continues its rage in the afterlife.");
case (_, Eight): return new("Ghost", "Some unfortunate soul still lingers in our world. The ghost was a victim and might only attack if threatened or confused.");
case (_, Nine): return new("Demon", "A vile creature from the pits of Hell roams the earth.", GenerateDemon(dice));
case (_, Ten): return new("Anomaly", "A completely unknown creature—perhaps from some other Savage Worlds setting—has somehow ended up in Pinebox.");
case (_, Jack): return new("Undead", "Some sort of undead (other than a vampire) rises. This could be a pack of zombies, a mummy, a horrible wight, and so on.");
case (_, Queen): return new("Animal", "A normal animal altered by science or sorcery is behind the event.");
case (_, King): return new("Xeno", "The horror is extraterrestrial in nature! It could be grays, a hunter from the stars, or even the servant of some otherworldly deity.");
case (_, Ace): return new("Slough Creature", "Something corrupt has animated the muck and slime of a swampy slough into a human - shaped creature.");
case (_, Joker):
var result = Supernatural(dice);
result.AddLinkedItem(Supernatural(dice));
return result;
}
return new("", "");
}
public List<NameDescriptionPair> CreateRitual(Dice dice, int powerPoints)
{
var common = new List<string>();
var exotic = new List<string>();
var result = new List<NameDescriptionPair>();
common.Add(CommonComponent(dice));
common.Add(CommonComponent(dice));
result.Add(new NameDescriptionPair("Power Points 1-2", string.Join(", ", common)));
for (var i = 3; i <= 20; i += 4)
{
if (common.Count == exotic.Count + 1)
common.Add(CommonComponent(dice));
else
exotic.Add(CommonComponent(dice));
result.Add(new NameDescriptionPair($"Power Points {i}-{i + 1}", string.Join(", ", common) + ", " + string.Join(", ", exotic)));
}
return result;
}
public string CommonComponent(Dice dice)
{
switch (dice.D(2))
{
case 1:
switch (dice.D(20))
{
case 1: return "A cup of alcohol";
case 2: return "A pinecone";
case 3: return "A kitten’s tooth";
case 4: return "A rat’s tail";
case 5: return "A raven’s feather";
case 6: return "A cup of human saliva";
case 7: return "Seven black candles";
case 8: return "Skunk pelt";
case 9: return "A child’s toy";
case 10: return "12 oz. of cemetery dirt";
case 11: return "A pinch of arsenic";
case 12: return "Catfish guts";
case 13: return "A human tooth";
case 14: return "Pebble from a running creek";
case 15: return "Cow urine";
case 16: return "A drop of blood from a disbeliever";
case 17: return "A rattle of a rattlesnake";
case 18: return "Chalk";
case 19: return "Clove of garlic";
case 20: return "A thimble full of earwax";
}
break;
case 2:
switch (dice.D(20))
{
case 1: return "A rusted hinge";
case 2: return "12 oz. of vomit";
case 3: return "6 oz of tortoise (turtle) meat";
case 4: return "1 pound of bat guano";
case 5: return "6 oz. crushed red glass";
case 6: return "A drop of human blood";
case 7: return "A chicken’s foot";
case 8: return "A scorpion tail";
case 9: return "A chip of a tombstone older than 100 years";
case 10: return "A teaspoon of gun powder";
case 11: return "Burned incense";
case 12: return "12 oz. beach sand";
case 13: return "12 oz. river water";
case 14: return "4 oz. whiskey";
case 15: return "6 oz. of holy water";
case 16: return "A lizard’s eye";
case 17: return "Poisonous snake venom (½ teaspoon)";
case 18: return "A broken mirror";
case 19: return "Hair from a woman older than 100 years";
case 20: return "Fresh cow’s milk (unpasteurized)";
}
break;
}
throw new Exception("This should never happen");
}
public string ExoticComponent(Dice dice)
{
switch (dice.D(2))
{
case 1:
switch (dice.D(20))
{
case 1: return "A piece of scrimshaw";
case 2: return "A severed finger";
case 3: return "A blooming Nightflower";
case 4: return "A cup of virgin’s blood (donor at least 18 years old)";
case 5: return "A child’s tear";
case 6: return "A strand of hair from a lion’s mane";
case 7: return "An owl’s eye";
case 8: return "A bear’s claw";
case 9: return "A gallon of human blood";
case 10: return "A human eye";
case 11: return "½ oz. gold";
case 12: return "20 cc of morphine";
case 13: return "Cremated human ash";
case 14: return "A brick from an occupied home";
case 15: return "Radioactive material";
case 16: return "Dirt from a freshly dug grave";
case 17: return "Drop of blood from a priest/nun";
case 18: return "A murderer’s weapon";
case 19: return "Brain of a rabid animal";
case 20: return "Human bones ground to powder";
}
break;
case 2:
switch (dice.D(20))
{
case 1: return "Nitrous oxide (laughing gas)";
case 2: return "Dust from decomposed undead creature";
case 3: return "Unpolished jade";
case 4: return "Ash from a forest fire";
case 5: return "A wedding ring from a murdered bride";
case 6: return "A hawk’s nest";
case 7: return "A drop of demon’s blood";
case 8: return "22 strands each of brunette, blonde, and red hair";
case 9: return "Rhino tusk powder";
case 10: return "An ostrich feather";
case 11: return "Elephant tusk";
case 12: return "A gorilla’s paw";
case 13: return "Skin from a chameleon-like creature";
case 14: return "Fresh shark fin";
case 15: return "10 strands of hair from a bull’s tail";
case 16: return "Crypt air";
case 17: return "Bound evil spirit (exorcism and capture)*";
case 18: return "1 small animal sacrifice (cat/bird)*";
case 19: return "A medium animal sacrifice (large dog)*";
case 20: return "A large animal sacrifice (horse/cow)*";
}
break;
}
throw new Exception("This should never happen");
}
public NameDescriptionPair HighStrangeness(Dice dice)
{
Card c = dice.PickCard();
switch (c)
{
case (Clubs, Two): return new(c, "", "It begins raining rust-colored rain drops.");
case (Clubs, Three): return new(c, "", "Water turns to blood.");
case (Clubs, Four): return new(c, "", "An animal yelps in pain. Its carcass is found with the head turned backwards.");
case (Clubs, Five): return new(c, "", "The sun or moon unexpectedly eclipses. No one else finds it particularly noteworthy.");
case (Clubs, Six): return new(c, "", "A cat or dog approaches the characters and lays a small heart at their feet. Moments later it drops dead. A heart is missing from its body.");
case (Clubs, Seven): return new(c, "", "A thick fog grows unnaturally and covers the entire town for 1d4 days.");
case (Clubs, Eight): return new(c, "", "The wind picks up and the sounds of unintelligible whispered voices are heard in it.");
case (Clubs, Nine): return new(c, "", "A strange mist fills a Large Burst Template area centered on the heroes or triggering source.");
case (Clubs, Ten): return new(c, "", "Everything in a Large Burst Template area becomes as sticky as molasses: people, plants, objects, even the ground itself.");
case (Clubs, Jack): return new(c, "", "Earthworms, grubworms, and maggots begin crawling from a nearby patch of ground.");
case (Clubs, Queen): return new(c, "", $"A pet turns feral and vicious for {dice.D("1d10")} rounds.");
case (Clubs, King): return new(c, "", "There is a sudden, very loud, thunderclap.");
case (Clubs, Ace): return new(c, "", $"Every person in the next public area suddenly develops hiccups lasting {dice.D("1d10")} minutes.");
case (Hearts, Two): return new(c, "", "Somewhere nearby the awful screeching and crunching of a massive car wreck sounds, but no such accident can be found.");
case (Hearts, Three): return new(c, "", "Bark flakes off of a tree, revealing flesh. Exposed to air, the flesh toughens into bark.");
case (Hearts, Four): return new(c, "", "The heroes notice bloody footprints ending right behind them. They can be backtracked only twenty paces before mysteriously appearing as if in mid-stride.");
case (Hearts, Five): return new(c, "", $"Silence reigns as no sound escapes a Large Burst Template area for {dice.D("1d4")} minutes.");
case (Hearts, Six): return new(c, "", "An insect can be heard screaming for help from a spider web.");
case (Hearts, Seven): return new(c, "", "A siren’s song comes from a nearby patch of woods but stops when investigated.");
case (Hearts, Eight): return new(c, "", "The heroes discover tortillas with small holes punched through them all over the ground.");
case (Hearts, Nine): return new(c, "", "All pets and animals flee in terror from the heroes.");
case (Hearts, Ten): return new(c, "", "Shadows cast by the heroes move of their own accord.");
case (Hearts, Jack): return new(c, "", "An unusually large black bird seemingly follows one of the heroes. It continues to do so unless it is shot, killed, or captured.");
case (Hearts, Queen): return new(c, "", $"All cell phones in Golan County suddenly stop working for {dice.D("1d4")} days and no explanation is ever given.");
case (Hearts, King): return new(c, "", "Birds suddenly fill the sky by the thousands, all flying east.");
case (Hearts, Ace): return new(c, "", "One of the heroes vomits uncontrollably, producing a foul, purplish mass that seems to whine and squeal for a few seconds, then “dies.”");
case (Diamonds, Two): return new(c, "", "A series of knocks from interior walls have no visible source.");
case (Diamonds, Three): return new(c, "", "Someone screams for help from a closet, but no one is inside.");
case (Diamonds, Four): return new(c, "", "A nearby mirror splinters and crashes to the ground.");
case (Diamonds, Five): return new(c, "", $"{dice.D("1d6")} mice suddenly appear and scamper in the area looking for a place to hide.");
case (Diamonds, Six): return new(c, "", "All sounds in a Large Burst Template area become “screwed” so they are slow and deep and difficult to understand.");
case (Diamonds, Seven): return new(c, "", "All food or drink sours immediately.");
case (Diamonds, Eight): return new(c, "", "The water draining down a faucet begins to circle in the opposite direction.");
case (Diamonds, Nine): return new(c, "", $"For {dice.D("1d4")} rounds roaches and other creepy crawlies suddenly swarm in a Small Burst emplate.");
case (Diamonds, Ten): return new(c, "", "Something scratches at a door or window, but no cause is ever found.");
case (Diamonds, Jack): return new(c, "", "A bucket of human teeth is found nearby.");
case (Diamonds, Queen): return new(c, "", "A hero seemingly causes any device with a speaker to burst into static at her approach.");
case (Diamonds, King): return new(c, "", "Roll d100. The resulting number becomes a recurring theme for the heroes. It is everywhere they look—doors, phone numbers, ticket numbers, etc.");
case (Diamonds, Ace): return new(c, "", "A homeless person fixates on one of the heroes and begins following her. He is not mean or evil, only very curious and mysteriously drawn to the hero.");
case (Spades, Two): return new(c, "", "A large owl flies to a nearby window, pecks the glass until it cracks, then flies away.");
case (Spades, Three): return new(c, "", "An object suddenly falls from a shelf.");
case (Spades, Four): return new(c, "", "A beverage (beer, wine, water, soda) suddenly boils.");
case (Spades, Five): return new(c, "", "A beverage suddenly turns to solid ice.");
case (Spades, Six): return new(c, "", "All glass (including eyeglasses) in a Large Burst Template area suddenly crack.");
case (Spades, Seven): return new(c, "", "Nearby sinks and toilets turn on or flush.");
case (Spades, Eight): return new(c, "", "A baby’s cry is heard nearby, but cannot be found.");
case (Spades, Nine): return new(c, "", $"All clocks stop and cannot be restarted for {dice.D("1d6")} minutes.");
case (Spades, Ten): return new(c, "", $"The heroes suddenly experience missing time. Roll {dice.D("1d100")} for the number of minutes. They have no memory of what just happened, but all their watches and time pieces are exactly the same and when compared to others they show the indicated time lapse.");
case (Spades, Jack): return new(c, "", "A hero hears someone making a “Shhh!” noise, but no one did.");
case (Spades, Queen): return new(c, "", "Characters controlled by the Dean only speak in questions. When this is pointed out to one of them, he screams in agony and blacks out. The phenomena stops afterward.");
case (Spades, King): return new(c, "", "The heroes experience a moment of déjà vu. End the current scene, then repeat it.");
case (Spades, Ace): return new(c, "", $"A hero begins having migraine headaches that cause him to suffer a –2 to all rolls for {dice.D("1d6")} hours. However, on a successful Spirit roll, he also has a brief glimpse of the future.");
}
//Redraw in the case of a Joker
return HighStrangeness(dice);
}
NameDescriptionPair Complications(Dice dice)
{
var card = dice.PickCard();
if (card.Color == Red)
switch (card)
{
case (_, Two): return new("Mistaken Identity", "One of the students or the target is the victim of mistaken identity.");
case (_, Three): return new("Crime", "The students or the target become victims of a crime or may have to perpetrate one.");
case (_, Four): return new("Misdirection", "The students believe the adventure is about one thing, but the problem changes and the gang must adjust. Generate a second complication.", Complications(dice));
case (_, Five): return new("Timed Travel/Race", "The student’s time is limited and they must hurry to accomplish their goals.");
case (_, Six): return new("Off the Grid", "Someone involved in the case goes missing for a while. Turns out he or she was just busy—but it happens at a very inopportune time.");
case (_, Seven): return new("Heartbreak Hotel", "One of the characters with a romantic relationship hits a glitch. The Significant Other might demand more time or be losing interest. If the card was a Heart, he or she is cheating on the hero with someone else.");
case (_, Eight): return new("Breakdown", $"A character’s car breaks down and must be repaired. Mom and Dad take care of the expensive fix, but it’s in the shop for { dice.D(6) } days.");
case (Hearts, Nine): return new("Teacher’s Pet", "One of the heroes (selected at random) gets noticed by one of his key professors. Adds +1 to his next Exam roll");
case (Diamonds, Nine): return new("Teacher’s Pain", "One of the heroes (selected at random) gets noticed by one of his key professors. The two don’t click and he suffers a –1 penalty for the next Exam roll.");
case (_, Ten): return new("<NAME>", $"The student gets involved in something ugly—like a protracted flame war on social media, a fight with Mom and Dad, or behaving embarrassingly badly in front of friends or teammates. He suffers a –1 penalty to all Smarts and Spirit rolls, and linked skills, for { dice.D(6) } days.");
case (Hearts, Jack): return new("Ambush", "The bad guy(s) know the students are coming and lay in wait to ambush them when the time is right. They’re still carrying a grudge from a previous event.");
case (Diamonds, Jack): return new("Ambush", "The bad guy(s) know the students are coming and lay in wait to ambush them when the time is right. They’re connected to the current mystery.");
case (_, Queen): return new("Can You Hear Me Now?", $"Sometime during the adventure, at the worst possible time, mobile phone coverage inexplicably goes out for { dice.D("2d6")} hours.");
case (_, King): return new("Betrayal", "Someone the students know betrays their loyalty. Maybe someone they got information from tells on them or informs the police that a bunch of “armed lunatics are off chasing make-believe monsters.” Or perhaps someone inadvertently spills the wrong beans.");
case (Hearts, Ace): return new("Weather", "A massive thunderstorm strikes.");
case (Diamonds, Ace): return new("Weather", "A tornado, wildfire, or flood.");
}
else
switch (card)
{
case (_, Two): return new("Pop Quiz", "A big test comes up in one of the student’s classes, determined randomly. Sometime in the next week of classes, he must make a roll as if taking Exams. If he fails, he suffers a –2 penalty to his actual Exams for his shortcomings. If he succeeds, there’s no penalty. If he gets a raise, he gets a +2 bonus on the next Exam.");
case (_, Three): return new("Money Trouble", $"When it rains, it pours. Everyone has an unexpected expense of some sort (the player can describe what it is). The expense is equal to $10 × D6, times the character’s wealth level (Poor=×1, Normal=×2, Rich=×4, Filthy Rich=×6).");
case (Clubs, Four): return new("Media Attention", "A nosy reporter with the Raven’s Report smells a story concerning one of the party’s previous deeds.");
case (Spades, Four): return new("Media Attention", "A nosy reporter from out of town smells a story concerning one of the party’s previous deeds.");
case (Clubs, Five): return new("The Sniffles", "Is this just seasonal allergies or something more serious? Congestion and cold symptoms");
case (Spades, Five): return new("The Sniffles", "Is this just seasonal allergies or something more serious? Digestive tract problems—such as a queasy stomach or loose bowels");
case (_, Six): return new("Crime Doesn’t Pay", "The police pick up on something the gang did and start a quiet investigation. They watch the heroes like hungry hawks.");
case (_, Seven): return new("Rock Out", "A super popular band a couple of the heroes are hot for comes to town. Of course the big concert happens right in the middle of their investigation, so they really need to hurry things up if they want to make the show.");
case (_, Eight): return new("WeirdTV", "A group of students has put together a “ghost hunters” type show. One of them knows about the heroes somehow and wants to accompany them on their next mission–and film it!");
case (_, Nine): return new("Escaped Fugitive", "A prisoner or violent offender is loose in the area where the main action takes place. The police are everywhere—and so is the perp!");
case (_, Ten): return new("Mom and Dad", "One of the heroes’ parents decide to visit, most likely unexpectedly.");
case (_, Jack): return new("Madness Reigns", "Someone who experienced something terrible goes completely insane.");
case (_, Queen): return new("Men in Black", "A group of government operatives in black suits, black ties, white shirts, and black hats show up and ask lots of questions.");
case (_, King): return new("The Cavalry", "The player characters aren’t the first class of heroes to graduate from ETU. A small group of alumni who went through similar challenges notices what the group has been up to and keeps an eye on them.");
case (_, Ace):
var result = HighStrangeness(dice);
result.AddLinkedItem(HighStrangeness(dice));
result.AddLinkedItem(HighStrangeness(dice));
return result;
case (_, Joker): return new("All Hell Breaks Loose", "Magic or Ritualism gone awry causes a dimensional rift. A number of creatures enter our world and run wild. Most go into hiding quickly, but a few may rage if given the opportunity.");
}
return new("", "");
}
// , GenerateCharacter(dice, "Victim", "")
string RandomTownieType(Dice dice)
{
switch (dice.D(7))
{
case 1:
case 2:
case 3:
case 4:
return "Blue Collar Worker";
case 5:
case 6:
return "White Collar Worker";
case 7:
return "Soldier";
}
return "";
}
NameDescriptionPair Victim(Dice dice)
{
switch (dice.PickCard())
{
case (_, Two):
case (_, Three):
case (_, Four): return new("Student", "A fellow ETU student is in peril.", GenerateCharacter(dice, "Student"));
case (_, Five, Red): return new("Faculty", "One of character's professors is the victim.", GenerateCharacter(dice, "Professor"));
case (_, Five): return new("Faculty", "One of ETU’s faculty is the victim.", GenerateCharacter(dice, "Professor"));
case (_, Six, Red): return new("Townies", "The danger is in a nearby town such as Blackburn or outlying ranches", GenerateCharacter(dice, RandomTownieType(dice)));
case (_, Six): return new("Townies", "The locals are in danger.", GenerateCharacter(dice, RandomTownieType(dice)));
case (_, Seven, Red): return new("Government", "A local government official is in danger.", GenerateCharacter(dice, "White Collar Worker"));
case (_, Seven): return new("Government", "A state or federal official is in danger.", GenerateCharacter(dice, "White Collar Worker"));
case (_, Eight): return new("Love Interest", "One of the characters’ love interests (or close friend) is in danger.", GenerateCharacter(dice, "Student"));
case (_, Nine): return new("Animal", "Wildlife or domesticated animals are the victims of this particular tale.");
case (_, Ten): return new("Scientist", "A team of researchers, doctors, or scientists are in danger.", GenerateCharacter(dice, "White Collar Worker"));
case (_, Jack): return new("Corporation", "Someone or some thing has targeted a company and its employees.", GenerateCharacter(dice, "White Collar Worker"));
case (_, Queen): return new("Criminal/Organized Crime", "Bad things are about to happen to bad people. Should the heroes help? Or let it happen?", GenerateCharacter(dice, "Thug"));
case (_, King): return new("The Heroes", "One of the heroes is the target!");
case (_, Ace): return new("Paranormal", "The victim is a supernatural creature.", Supernatural(dice));
case (_, Joker):
var result = Supernatural(dice);
result.AddLinkedItem(Supernatural(dice));
return result;
}
return new("", "");
}
NameDescriptionPair Why(Dice dice)
{
switch (dice.PickCard())
{
case (_, Two):
case (_, Three):
case (_, Four):
return new("Secret", "The antagonists seek forbidden or secret knowledge.");
case (_, Five):
case (_, Six):
case (_, Seven):
return new("Power", "The antagonists are after power of some kind.");
case (_, Eight):
case (_, Nine):
return new("Chaos", "The antagonists seek purely to sew mischief and mayhem.");
case (_, Ten): return new("Sacrifice", "The bad guys are attempting to cause misery or harm to others to appease some dark power they believe will grant them favors.");
case (_, Jack): return new("Love", "The antagonists carry out their ill-placed dark deeds for romantic reasons");
case (_, Queen): return new("Greed", "It’s all about money.");
case (_, King): return new("Ritual", "The bad guys must perform a deed as part of a ritual or ceremony.");
case (_, Ace): return new("Accident", "The antagonists didn’t mean for anything to happen.");
case (_, Joker):
var result = Why(dice);
result.AddLinkedItem(Why(dice));
return result;
}
return new("", "");
}
NameDescriptionPair What(Dice dice)
{
switch (dice.PickCard())
{
case (_, Two):
case (_, Three):
case (_, Four):
case (_, Five):
return new("Missing person", "Someone is missing.", Victim(dice));
case (_, Six, Red):
case (_, Seven, Red):
case (_, Eight, Red):
return new("Death", "Someone has died.", Victim(dice));
case (_, Six):
case (_, Seven):
case (_, Eight):
return new("Death", "Someone is going to die.", Victim(dice));
case (_, Nine):
case (_, Ten):
return new("Accident", "There’s been an accident of some sort, perhaps incidental to the bad guys’ actual plan.", Victim(dice));
case (_, Jack): return new("Sighting", "Someone saw something strange and tells the students.");
case (_, Queen, Red):
return new("Criminal Activity", "A crime has been commited against...", Victim(dice));
case (_, Queen):
return new("Criminal Activity", "A crime is going to be committed against...", Victim(dice));
case (_, King, Red):
case (_, Ace, Red):
return new("Theft", "A theft has been commited against...", Victim(dice));
case (_, King):
case (_, Ace):
return new("Theft", "A theft is going to be commited against...", Victim(dice));
case (_, Joker): return new("Mass Event", "Something BIG is going to happen that could affect the whole town");
}
return new("", "");
}
}
}
<file_sep>namespace SavageTools.Utilities
{
public record NameDescriptionPair(Card? Card, string Name, string Description)
{
public NameDescriptionPair(Card? card, string name, string description, NameDescriptionPair linkedItem)
: this(card, name, description)
=> LinkedItem = linkedItem;
public NameDescriptionPair(string name, string description)
: this(null, name, description) { }
public NameDescriptionPair(string name, string description, NameDescriptionPair linkedItem)
: this(null, name, description)
=> LinkedItem = linkedItem;
public NameDescriptionPair? LinkedItem { get; private set; }
public bool IsMarkdown { get; init; }
public void AddLinkedItem(NameDescriptionPair item)
{
var current = this;
while (current.LinkedItem != null)
current = current.LinkedItem;
//Adds the item to the end of the chain;
current.LinkedItem = item;
}
}
}
<file_sep>using System;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
namespace SavageTools.Names
{
public class LocalNameService
{
readonly ImmutableList<string> m_FemaleNames;
readonly ImmutableList<string> m_LastNames;
readonly ImmutableList<string> m_MaleNames;
public LocalNameService(string dataPath, string prefix)
{
if (!string.IsNullOrWhiteSpace(prefix) && !prefix.EndsWith("-"))
prefix += "-";
var femaleFile = new FileInfo(Path.Combine(dataPath, prefix + "female-first.txt"));
var lastFile = new FileInfo(Path.Combine(dataPath, prefix + "last.txt"));
var maleFile = new FileInfo(Path.Combine(dataPath, prefix + "male-first.txt"));
m_LastNames = File.ReadAllLines(lastFile.FullName).Where(x => !string.IsNullOrEmpty(x)).Select(x => x.Substring(0, 1).ToUpperInvariant() + x.Substring(1)).Distinct().ToImmutableList();
m_FemaleNames = File.ReadAllLines(femaleFile.FullName).Where(x => !string.IsNullOrEmpty(x)).Select(x => x.Substring(0, 1).ToUpperInvariant() + x.Substring(1)).Distinct().ToImmutableList();
m_MaleNames = File.ReadAllLines(maleFile.FullName).Where(x => !string.IsNullOrEmpty(x)).Select(x => x.Substring(0, 1).ToUpperInvariant() + x.Substring(1)).Distinct().ToImmutableList();
}
public RandomPerson CreateRandomPerson(Dice dice)
{
if (dice == null)
throw new ArgumentNullException(nameof(dice), $"{nameof(dice)} is null.");
var isMale = dice.NextBoolean();
return new RandomPerson(
isMale ? dice.Choose(m_MaleNames) : dice.Choose(m_FemaleNames),
dice.Choose(m_LastNames),
isMale ? "M" : "F"
);
}
}
}
<file_sep>using Microsoft.AspNetCore.Components;
using SavageTools;
using SavageTools.Characters;
using System;
namespace SavageToolsWeb.Controls
{
partial class CharacterBuilderForm
{
[Parameter] public CharacterOptions? Options { get; set; }
public string? ErrorDisplay;
public string DisplayMode = "HTML";
protected void SubmitChanges()
{
//These should never happen.
if (Options == null)
return;
ErrorDisplay = null;
try
{
var dice = new Dice();
for (var i = 0; i < Options.Count; i++)
{
Options.Squad.Insert(0, Options.CharacterGenerator.GenerateCharacter(Options, dice));
}
StateHasChanged();
}
catch (Exception ex)
{
ErrorDisplay = "Unable to create character: " + ex.Message;
}
}
}
}
<file_sep>using Tortuga.Anchor.Modeling;
namespace SavageTools.Characters
{
public class HindranceCollection : ChangeTrackingModelCollection<Hindrance>
{
public void Add(string name, string description)
{
Add(new Hindrance() { Name = name, Description = description, Level = 0 });
}
}
}
<file_sep>using SavageTools.Names;
using SavageTools.Settings;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using Tortuga.Anchor;
using Tortuga.Anchor.Collections;
using Tortuga.Anchor.Modeling;
namespace SavageTools.Characters
{
public class CharacterGenerator : ModelBase
{
public LocalNameService NameService { get; }
public PersonalityService PersonalityService { get; }
private static readonly XmlSerializer s_SettingXmlSerializer = new XmlSerializer(typeof(Setting));
public CharacterGenerator(FileInfo setting)
{
LoadSetting(setting, true);
NameService = new LocalNameService(setting.DirectoryName!, NamePrefix);
PersonalityService = new PersonalityService(setting.DirectoryName!);
}
public ObservableCollectionExtended<SettingArchetype> Archetypes => GetNew<ObservableCollectionExtended<SettingArchetype>>();
public bool BornAHeroSetting { get => GetDefault(false); private set => Set(value); }
public bool MoreSkillsSetting { get => GetDefault(false); private set => Set(value); }
public ObservableCollectionExtended<SettingEdge> Edges => GetNew<ObservableCollectionExtended<SettingEdge>>();
//public ObservableCollectionExtended<SettingHindrance> Hindrances => GetNew<ObservableCollectionExtended<SettingHindrance>>();
public ObservableCollectionExtended<SettingHindrance> MinorHindrances => GetNew<ObservableCollectionExtended<SettingHindrance>>();
public ObservableCollectionExtended<SettingHindrance> MajorHindrances => GetNew<ObservableCollectionExtended<SettingHindrance>>();
public string NamePrefix { get => Get<string>(); set => Set(value); }
public string SettingName { get => Get<string>(); set => Set(value); }
public ObservableCollectionExtended<SettingPower> Powers => GetNew<ObservableCollectionExtended<SettingPower>>();
public ObservableCollectionExtended<SettingRace> Races => GetNew<ObservableCollectionExtended<SettingRace>>();
public ObservableCollectionExtended<SettingRank> Ranks => GetNew<ObservableCollectionExtended<SettingRank>>();
public ObservableCollectionExtended<string> Settings => GetNew<ObservableCollectionExtended<string>>();
public ObservableCollectionExtended<SettingSkillOption> Skills => GetNew<ObservableCollectionExtended<SettingSkillOption>>();
public ObservableCollectionExtended<SettingTrapping> Trappings => GetNew<ObservableCollectionExtended<SettingTrapping>>();
public bool UseReason { get => Get<bool>(); set => Set(value); }
public bool UseStatus { get => Get<bool>(); set => Set(value); }
public bool UseStrain { get => Get<bool>(); set => Set(value); }
//public void AddPower(Character result, string arcaneSkill, string power, Dice dice)
//{
// if (result == null)
// throw new ArgumentNullException(nameof(result), $"{nameof(result)} is null.");
// if (string.IsNullOrEmpty(arcaneSkill))
// throw new ArgumentException($"{nameof(arcaneSkill)} is null or empty.", nameof(arcaneSkill));
// if (string.IsNullOrEmpty(power))
// throw new ArgumentException($"{nameof(power)} is null or empty.", nameof(power));
// if (dice == null)
// throw new ArgumentNullException(nameof(dice), $"{nameof(dice)} is null.");
// var trappings = new List<SettingTrapping>();
// var group = result.PowerGroups[arcaneSkill];
// foreach (var item in Trappings)
// {
// if (group.AvailableTrappings.Count > 0 && !group.AvailableTrappings.Contains(item.Name))
// continue;
// if (group.ProhibitedTrappings.Contains(item.Name))
// continue;
// trappings.Add(item);
// }
// if (trappings.Count == 0)
// trappings.Add(new SettingTrapping() { Name = "None" });
// var trapping = dice.Choose(Trappings);
// group.Powers.Add(new Power(power, trapping.Name));
//}
public void ApplyEdge(Character result, Dice dice, string edgeName, string? description = null)
{
if (result == null)
throw new ArgumentNullException(nameof(result), $"{nameof(result)} is null.");
if (string.IsNullOrEmpty(edgeName))
throw new ArgumentException($"{nameof(edgeName)} is null or empty.", nameof(edgeName));
if (dice == null)
throw new ArgumentNullException(nameof(dice), $"{nameof(dice)} is null.");
var edge = Edges.SingleOrDefault(x => string.Equals(x.Name, edgeName, StringComparison.OrdinalIgnoreCase));
if (edge == null)
result.Edges.Add(edgeName, description);
else
ApplyEdge(result, edge, dice, description);
}
public Character CreateBlankCharacter(bool animalIntelligence = false, bool useCoreSkills = true)
{
var result = new Character();
//Add all possible skills (except ones created by edges)
//Filter out the ones not available to animal intelligences
foreach (var item in Skills.Where(s => !animalIntelligence || !s.NoAnimals))
result.Skills.Add(new Skill(item.Name, item.Attribute) { Trait = (item.IsCore && useCoreSkills) ? 4 : 0 });
return result;
}
public Character GenerateCharacter(CharacterOptions options, Dice? dice = null)
{
dice = dice ?? new Dice();
SettingArchetype selectedArchetype;
SettingRace selectedRace;
SettingRank selectedRank;
if (!options.RandomArchetype)
{
selectedArchetype = options.SelectedArchetype!;
}
else
{
var list = Archetypes.Where(a => options.WildCard || !a.WildCard).ToList(); //Don't pick wildcard archetypes unless WildCard is checked.
selectedArchetype = dice.Choose(list);
}
if (!options.RandomRace)
{
selectedRace = options.SelectedRace!;
}
else
{
if (!string.IsNullOrEmpty(selectedArchetype?.Race))
{
//Limited races are only available for their matching Archetype
//For example, a Lion can't be a Wizard.
selectedRace = Races.Single(r => r.Name == selectedArchetype.Race);
}
else
{
selectedRace = dice.Choose(Races.Where(r => !r.IsLimited).ToList());
}
}
if (!options.RandomRank)
{
selectedRank = options.SelectedRank!;
}
else
{
var table = new Table<SettingRank>();
foreach (var item in Ranks)
table.Add(item, 100 - item.Experience); //this should weigh it towards novice
selectedRank = table.RandomChoose(dice);
}
var result = new Character() { Rank = selectedRank.DisplayName ?? selectedRank.Name, IsWildCard = options.WildCard, UseReason = UseReason, UseStatus = UseStatus, UseStrain = UseStrain };
var name = NameService.CreateRandomPerson(dice);
result.Name = name.FullName;
result.Gender = name.Gender;
//Add all possible skills (except ones created by edges)
//Filter out the ones not available to animal intelligences
foreach (var item in Skills.Where(s => !selectedRace.AnimalIntelligence || !s.NoAnimals))
result.Skills.Add(new Skill(item.Name, item.Attribute) { Trait = (item.IsCore && options.UseCoreSkills) ? 4 : 0 });
ApplyArchetype(result, dice, selectedArchetype!);
ApplyRace(result, dice, selectedRace);
if (options.MoreSkills)
result.UnusedSkills += 3;
//Add the rank
result.UnusedAdvances = selectedRank.UnusedAdvances;
result.Experience = selectedRank.Experience;
if (result.UnusedHindrances == 0)//Add some hindrances to make it interesting
{
var extraHindrances = Math.Max(dice.D(6) - 2, 0);
result.UnusedHindrances += extraHindrances;
//Assign the points gained from the extra hindrances
while (extraHindrances > 0)
{
if (extraHindrances >= 2 && dice.NextBoolean())
{
extraHindrances -= 2;
if (dice.NextBoolean())
result.UnusedAttributes += 1;
else
result.UnusedEdges += 1;
}
else
{
extraHindrances -= 1;
result.UnusedSkills += 1;
}
}
}
//Main loop for random picks
while (result.UnusedAttributes > 0 || result.UnusedSkills > 0 || result.UnusedSmartSkills > 0 || result.UnusedAdvances > 0 || result.UnusedEdges > 0 || result.UnusedHindrances > 0 || result.UnusedRacialEdges > 0 || result.UnusedIconicEdges > 0)
{
//tight loop to apply current hindrances
while (result.UnusedHindrances > 0)
PickHindrance(result, dice);
//Pick up racial and iconic edges early because they can grant skills
if (result.UnusedRacialEdges > 0)
PickRacialEdge(result, dice, selectedRace, options.BornAHero);
if (result.UnusedIconicEdges > 0)
PickIconicEdge(result, dice, selectedArchetype!, options.BornAHero);
if (result.UnusedAttributes > 0)
PickAttribute(result, dice);
if (result.UnusedSmartSkills > 0)
PickSmartsSkill(result, dice);
if (result.UnusedSkills > 0)
PickSkill(result, dice);
if (result.UnusedEdges > 0)
PickEdge(result, dice, selectedArchetype, selectedRace, options.BornAHero);
//only apply an advance when everything else has been used
if (result.UnusedAdvances > 0 && result.UnusedAttributes <= 0 && result.UnusedSkills <= 0 && result.UnusedEdges <= 0 && result.UnusedSmartSkills <= 0)
{
PickAdvancement(result, dice);
}
//Out of advancements. Do we need a hindrance?
if (result.UnusedAdvances == 0)
{
if (result.UnusedAttributes < 0)
{
result.UnusedHindrances += -2 * result.UnusedAttributes;
result.UnusedAttributes = 0;
}
if (result.UnusedSmartSkills < 0)
{
result.UnusedSkills += result.UnusedSmartSkills;
result.UnusedSmartSkills = 0;
}
if (result.UnusedSkills < 0)
{
result.UnusedHindrances += -1 * result.UnusedSkills;
result.UnusedSkills = 0;
}
if (result.UnusedEdges < 0)
{
result.UnusedHindrances += -2 * result.UnusedEdges;
result.UnusedEdges = 0;
}
}
}
//pick powers
foreach (var group in result.PowerGroups)
while (group.UnusedPowers > 0)
PickPower(result, group, dice, options.BornAHero);
AddPersonality(result, dice);
result.Cleanup();
return result;
}
public void AddPersonality(Character result, Dice dice)
{
//Add personality
int personalityTraits = dice.D(3);
for (var i = 0; i < personalityTraits; i++)
result.Personality.Add(PersonalityService.CreateRandomPersonality(dice));
}
//public IEnumerable<SettingSkillOption> KnowledgeSkills()
//{
// return Skills.Where(x => x.Name.StartsWith("Knowledge "));
//}
public void LoadSetting(FileInfo file, bool isPrimarySetting)
{
if (file == null)
throw new ArgumentNullException(nameof(file), $"{nameof(file)} is null.");
Setting book;
// Open document
using (var stream = file.OpenRead())
book = (Setting)s_SettingXmlSerializer.Deserialize(stream)!;
if (isPrimarySetting)
SettingName = book.Name;
if (Settings.Any(s => s == book.Name))
return; //already loaded
Settings.Add(book.Name);
if (book.BornAHero)
BornAHeroSetting = true;
if (book.MoreSkills)
MoreSkillsSetting = true;
if (book.UseReason)
UseReason = true;
if (book.UseStatus)
UseStatus = true;
if (book.UseStrain)
UseStrain = true;
if (book.References != null)
foreach (var item in book.References.Where(r => !Settings.Any(s => s == r.Name)))
{
var referencedBook = new FileInfo(Path.Combine(file.DirectoryName!, item.Name + ".savage-setting"));
if (referencedBook.Exists)
LoadSetting(referencedBook, false);
}
//Adding a book overwrites the previous book.
if (book.Skills != null)
foreach (var item in book.Skills)
{
Skills.RemoveAll(s => s.Name == item.Name);
Skills.Add(item);
}
if (book.RemoveSkills != null)
foreach (var item in book.RemoveSkills)
{
Skills.RemoveAll(s => s.Name == item.Name);
}
if (book.Edges != null)
foreach (var item in book.Edges)
{
Edges.RemoveAll(s => s.Name == item.Name);
Edges.Add(item);
}
if (book.Hindrances != null)
{
//If a setting adds a hindrance at either level, it overwrites both.
foreach (var item in book.Hindrances)
{
MinorHindrances.RemoveAll(s => s.Name == item.Name);
MajorHindrances.RemoveAll(s => s.Name == item.Name);
}
foreach (var item in book.Hindrances.Where(h => h.IsMinor()))
{
MinorHindrances.Add(item);
}
foreach (var item in book.Hindrances.Where(h => h.IsMajor()))
{
MajorHindrances.Add(item);
}
}
if (book.Archetypes != null)
{
foreach (var item in book.Archetypes)
{
Archetypes.RemoveAll(s => s.Name == item.Name);
Archetypes.Add(item);
}
Archetypes.Sort(a => a.Name);
}
if (book.Races != null)
{
foreach (var item in book.Races)
{
Races.RemoveAll(s => s.Name == item.Name);
Races.Add(item);
}
Races.Sort(r => r?.Name ?? "");
}
if (book.Ranks != null)
{
Ranks.Clear();
foreach (var item in book.Ranks)
{
Ranks.Add(item);
}
}
if (book.Trappings != null)
foreach (var item in book.Trappings)
{
Trappings.RemoveAll(s => s.Name == item.Name);
Trappings.Add(item);
}
if (book.Powers != null)
foreach (var item in book.Powers)
{
Powers.RemoveAll(s => s.Name == item.Name);
Powers.Add(item);
}
NamePrefix = book.NamePrefix;
}
public void PickEdge(Character result, Dice dice, bool bornAHero)
{
PickEdge(result, dice, null, null, bornAHero);
}
public void ApplyEdge(Character result, SettingEdge edge, Dice dice, string? overrideDescription = null)
{
var description = overrideDescription.IsNullOrEmpty() ? edge.Description : overrideDescription;
result.Edges.Add(new Edge() { Name = edge.Name, Description = description, UniqueGroup = edge.UniqueGroup });
if (edge.Traits != null)
foreach (var item in edge.Traits)
result.Increment(item.Name, item.Bonus, dice);
if (edge.Features != null)
foreach (var item in edge.Features)
result.Features.Add(item.Name);
if (edge.Edges != null)
foreach (var item in edge.Edges)
ApplyEdge(result, item, dice);
if (edge.AvailablePowers != null)
foreach (var item in edge.AvailablePowers)
result.PowerGroups[edge.PowerType].AvailablePowers.Add(item.Name);
if (edge.Triggers != null)
foreach (var item in edge.Triggers)
result.PowerGroups[edge.PowerType].AvailableTriggers.Add(item.Name);
if (edge.Skills != null)
foreach (var item in edge.Skills)
{
var skill = result.Skills.FirstOrDefault(s => s.Name == item.Name);
if (skill == null)
{
skill = new Skill(item.Name, item.Attribute) { Trait = item.Level };
result.Skills.Add(skill);
}
else if (skill.Trait < item.Level)
skill.Trait = item.Level;
if (item.MaxLevelBonus != 0)
skill.MaxLevel += item.MaxLevelBonus;
if (skill.MaxLevel < skill.Trait)
skill.MaxLevel = skill.Trait;
}
if (edge.Powers != null)
foreach (var item in edge.Powers)
ApplyPower(result, result.PowerGroups[edge.PowerType], item, dice);
if (edge.Hindrances != null)
foreach (var item in edge.Hindrances)
{
int level = 0;
if (item.IsMajor())
level = 2;
else if (item.IsMinor())
level = 1;
ApplyHindrance(result, item, level, dice);
}
}
private static void PickAdvancement(Character result, Dice dice)
{
result.UnusedAdvances -= 1;
if (result.UnusedEdges < 0)
result.UnusedEdges += 1;
else if (result.UnusedSkills < 0)
result.UnusedSkills += 2; //pay back the skill point loan
else if (result.UnusedSmartSkills < 0)
result.UnusedSmartSkills += 2; //pay back the skill point loan
else
{
switch (dice.Next(5))
{
case 0:
result.UnusedEdges += 1;
break;
case 1: //increase a high skill
{
var table = new Table<Skill>();
foreach (var skill in result.Skills)
{
var trait = result.GetAttribute(skill.Attribute);
if (skill.Trait >= trait && skill.Trait < skill.MaxLevel)
table.Add(skill, skill.Trait.Score);
}
if (table.Count == 0)
goto case 2;
table.RandomChoose(dice).Trait += 1;
break;
}
case 2: //increase a low skill
{
var table = new Table<Skill>();
foreach (var skill in result.Skills)
{
if (skill.Trait < result.GetAttribute(skill.Attribute) && skill.Trait < skill.MaxLevel)
table.Add(skill, skill.Trait.Score);
}
if (table.Count >= 2)
goto case 3;
table.RandomPick(dice).Trait += 1;
table.RandomPick(dice).Trait += 1; //use Pick so we get 2 different skills
break;
}
case 3: //add a new skill
{
var table = new Table<Skill>();
foreach (var skill in result.Skills)
{
if (skill.Trait == 0)
table.Add(skill, result.GetAttribute(skill.Attribute).Score);
}
if (table.Count == 0)
break; //really?
table.RandomChoose(dice).Trait = 4;
break;
}
case 4:
result.UnusedAttributes += 1;
break;
}
}
}
private static void PickAttribute(Character result, Dice dice)
{
//Attributes are likely to stack rather than spread evenly
var table = new Table<string>();
if (result.Vigor < result.MaxVigor)
table.Add("Vigor", result.Vigor.Score);
if (result.Smarts < result.MaxSmarts)
table.Add("Smarts", result.Smarts.Score);
if (result.Agility < result.MaxAgility)
table.Add("Agility", result.Agility.Score);
if (result.Strength < result.MaxStrength)
table.Add("Strength", result.Strength.Score);
if (result.Spirit < result.MaxSpirit)
table.Add("Spirit", result.Spirit.Score);
if (table.Count == 0) //out of attributes that can be increased
result.UnusedAdvances += 1; //reassign somewhere else
else
result.Increment(table.RandomChoose(dice), dice);
result.UnusedAttributes -= 1;
}
private static void PickSkill(Character result, Dice dice)
{
bool allowHigh = result.UnusedSkills >= 2 && result.UnusedAttributes == 0; //don't buy expensive skills until all of the attributes are picked
var table = new Table<Skill>();
foreach (var item in result.Skills)
{
if (item.Trait == 0)
table.Add(item, result.GetAttribute(item.Attribute).Score - 3); //favor skills that match your attributes
else if ((item.Trait + 1) < result.GetAttribute(item.Attribute)) //favor improving what you know
table.Add(item, result.GetAttribute(item.Attribute).Score - 3 + item.Trait.Score);
else if (allowHigh && item.Trait < 12)
table.Add(item, item.Trait.Score); //Raising skills above the controlling attribute is relatively rare
}
var skill = table.RandomChoose(dice);
if (skill.Trait == 0)
{
result.UnusedSkills -= 1;
skill.Trait = 4;
}
else if (skill.Trait < result.GetAttribute(skill.Attribute))
{
result.UnusedSkills -= 1;
skill.Trait += 1;
}
else
{
result.UnusedSkills -= 2;
skill.Trait += 1;
}
}
private static void PickSmartsSkill(Character result, Dice dice)
{
bool allowHigh = result.UnusedSmartSkills >= 2 && result.UnusedAttributes == 0; //don't buy expensive skills until all of the attributes are picked
var table = new Table<Skill>();
foreach (var item in result.Skills.Where(s => s.Attribute == "Smarts"))
{
if (item.Trait == 0)
table.Add(item, result.GetAttribute(item.Attribute).Score - 3); //favor skills that match your attributes
else if ((item.Trait + 1) < result.GetAttribute(item.Attribute)) //favor improving what you know
table.Add(item, result.GetAttribute(item.Attribute).Score - 3 + item.Trait.Score);
else if (allowHigh && item.Trait < 12)
table.Add(item, item.Trait.Score); //Raising skills above the controlling attribute is relatively rare
}
var skill = table.RandomChoose(dice);
if (skill.Trait == 0)
{
result.UnusedSmartSkills -= 1;
skill.Trait = 4;
}
else if (skill.Trait < result.GetAttribute(skill.Attribute))
{
result.UnusedSmartSkills -= 1;
skill.Trait += 1;
}
else
{
result.UnusedSmartSkills -= 2;
skill.Trait += 1;
}
}
private void AddFixedPower(Character result, SettingPower power)
{
var group = result.PowerGroups[power.PowerType];
group.Powers.Add(new Power(power, power.Trapping, power.Trigger));
}
private void ApplyArchetype(Character result, Dice dice, SettingArchetype archetype)
{
//Add the archetype
result.Archetype = archetype.Name;
result.UnusedAttributes = archetype.UnusedAttributes;
result.UnusedSkills = archetype.UnusedSkills;
result.Agility = archetype.Agility;
result.Smarts = archetype.Smarts;
result.Spirit = archetype.Spirit;
result.Strength = archetype.Strength;
result.Vigor = archetype.Vigor;
result.IsWildCard = result.IsWildCard || archetype.IsWildCard;
//then edges first because they can create new skills
if (archetype.Edges != null)
foreach (var item in archetype.Edges)
ApplyEdge(result, FindEdge(item), dice);
if (archetype.Hindrances != null)
foreach (var item in archetype.Hindrances)
{
//pick up the level from the archetype
var level = 0;
if (item.Type == "Minor" || item.Type == "Minor/Major")
level = 1;
else if (item.Type == "Major")
level = 2;
var hindrance = FindHindrance(item);
if (level == 0) //check for a default
{
if (hindrance.Type == "Minor" || hindrance.Type == "Minor/Major")
level = 1;
else if (hindrance.Type == "Major")
level = 2;
}
ApplyHindrance(result, hindrance, level, dice);
}
if (archetype.Skills != null)
foreach (var item in archetype.Skills)
{
var skill = result.Skills[item.Name];
if (skill != null)
skill.Trait = Math.Max(skill.Trait.Score, item.Level);
else
result.Skills.Add(new Skill(item.Name, item.Attribute) { Trait = item.Level });
if (skill!.MaxLevel < skill.Trait)
skill.MaxLevel = skill.Trait;
}
if (archetype.Traits != null)
foreach (var item in archetype.Traits)
result.Increment(item.Name, item.Bonus, dice);
//Set max traits to at least match the archetype
if (result.MaxAgility < result.Agility)
result.MaxAgility = result.Agility;
if (result.MaxSmarts < result.Smarts)
result.MaxSmarts = result.Smarts;
if (result.MaxSpirit < result.Spirit)
result.MaxSpirit = result.Spirit;
if (result.MaxStrength < result.Strength)
result.MaxStrength = result.Strength;
if (result.MaxVigor < result.Vigor)
result.MaxVigor = result.Vigor;
if (archetype.Features != null)
foreach (var item in archetype.Features)
result.Features.Add(item.Name);
if (archetype.Gear != null)
foreach (var item in archetype.Gear)
{
result.Gear.Add(item.Name, item.Description);
if (item.Traits != null)
foreach (var trait in item.Traits)
result.Increment(trait.Name, trait.Bonus, dice);
}
}
public static void ApplyHindrance(Character result, SettingHindrance hindrance, int level, Dice dice)
{
result.Hindrances.Add(new Hindrance() { Name = hindrance.Name, Description = hindrance.Description, Level = level });
if (hindrance.Trait != null)
foreach (var item in hindrance.Trait)
result.Increment(item.Name, item.Bonus, dice);
if (hindrance.Features != null)
foreach (var item in hindrance.Features)
result.Features.Add(item.Name);
if (hindrance.Skill != null)
foreach (var item in hindrance.Skill)
{
var skill = result.Skills.FirstOrDefault(s => s.Name == item.Name);
if (skill == null)
result.Skills.Add(new Skill(item.Name, item.Attribute) { Trait = item.Level });
else if (skill.Trait < item.Level)
skill.Trait = item.Level;
}
}
private void ApplyRace(Character result, Dice dice, SettingRace race)
{
//Add the race
result.Race = race.Name;
result.AnimalIntelligence = race.AnimalIntelligence;
if (race.Edges != null)
foreach (var item in race.Edges)
ApplyEdge(result, FindEdge(item), dice);
if (race.Hindrances != null)
foreach (var item in race.Hindrances)
{
//pick up the level from the archetype
var level = 0;
if (item.Type == "Minor" || item.Type == "Minor/Major")
level = 1;
else if (item.Type == "Major")
level = 2;
var hindrance = FindHindrance(item);
if (level == 0) //check for a default
{
if (hindrance.Type == "Minor" || hindrance.Type == "Minor/Major")
level = 1;
else if (hindrance.Type == "Major")
level = 2;
}
ApplyHindrance(result, hindrance, level, dice);
}
if (race.Skills != null)
foreach (var item in race.Skills)
{
var skill = result.Skills[item.Name];
if (skill != null)
skill.Trait = Math.Max(skill.Trait.Score, item.Level);
else
result.Skills.Add(new Skill(item.Name, item.Attribute) { Trait = item.Level });
}
if (race.Traits != null)
foreach (var item in race.Traits)
result.Increment(item.Name, item.Bonus, dice);
if (race.Powers != null)
foreach (var item in race.Powers)
AddFixedPower(result, item);
}
private SettingEdge FindEdge(SettingEdge prototype)
{
//If any of these are set, assume its a custom edge
if (!string.IsNullOrEmpty(prototype.Description))
return prototype;
if (prototype.Features?.Length > 0)
return prototype;
if (prototype.Traits?.Length > 0)
return prototype;
if (prototype.Skills?.Length > 0)
return prototype;
//Look for a shared edge
var result = Edges.FirstOrDefault(e => e.Name == prototype.Name);
return result ?? prototype;
}
private SettingHindrance FindHindrance(SettingHindrance prototype)
{
//If any of these are set, assume its a custom hindrance
if (!string.IsNullOrEmpty(prototype.Description))
return prototype;
if (prototype.Features?.Length > 0)
return prototype;
//Look for a shared hindrances
var minor = MinorHindrances.FirstOrDefault(e => e.Name == prototype.Name);
var major = MajorHindrances.FirstOrDefault(e => e.Name == prototype.Name);
if (major != null && prototype.Type == "Major")
return major;
//Perfer the minor version if both are available and major wasn't asked for.
return minor ?? major ?? prototype;
}
private void PickEdge(Character result, Dice dice, SettingArchetype? archetype, SettingRace? race, bool bornAHero)
{
var table = new Table<SettingEdge>();
var edgeList = (IEnumerable<SettingEdge>)Edges;
if (archetype?.IconicEdges != null)
edgeList = edgeList.Concat(archetype.IconicEdges);
if (race?.RacialEdges != null)
edgeList = edgeList.Concat(race.RacialEdges);
foreach (var item in edgeList)
{
//Task-5: Some edges allow duplicates
if (result.Edges.Any(e => e.Name == item.Name))
continue; //no dups
if (!string.IsNullOrEmpty(item.UniqueGroup))
if (result.Edges.Any(e => e.UniqueGroup == item.UniqueGroup))
continue; //can't have multiple from a unique group (i.e. arcane background)
var requirements = item.Requires.Split(',').Select(e => e.Trim());
if (requirements.All(c => result.HasFeature(c, bornAHero)))
table.Add(item, 1);
}
if (table.Count == 0)
{
Debug.WriteLine("No edges were available");
}
else
{
//Debug.WriteLine($"Found {table.Count} edges");
var edge = table.RandomChoose(dice);
ApplyEdge(result, edge, dice);
result.UnusedEdges -= 1;
}
}
private void PickHindrance(Character result, Dice dice)
{
var minors = result.Hindrances.Where(h => h.Level == 1).Count();
var majors = result.Hindrances.Where(h => h.Level == 2).Count();
bool useMajor;
if (result.UnusedHindrances < 2)
useMajor = false; //
else if (result.UnusedHindrances == 2)
{
if (majors == 0 && minors == 0)
useMajor = dice.NextBoolean(); //empty slate, can go either way
else if (majors == 0)
useMajor = true; //we already have 1+ minors so use a major
else
useMajor = false;
}
else
{
if (majors == 0)
useMajor = true; //pick a major if we don't have one already
else if (minors == 0)
useMajor = false; //pick a minor since we don't have any yet
else
useMajor = dice.NextBoolean(); //this shouldn't happen with normal characters
}
var table = new Table<SettingHindrance>();
if (useMajor)
foreach (var item in MajorHindrances)
{
if (result.Hindrances.Any(e => e.Name == item.Name))
continue; //no dups
table.Add(item, 1);
}
else
foreach (var item in MinorHindrances)
{
if (result.Hindrances.Any(e => e.Name == item.Name))
continue; //no dups
table.Add(item, 1);
}
var hindrance = table.RandomChoose(dice);
ApplyHindrance(result, hindrance, useMajor ? 2 : 1, dice);
result.UnusedHindrances -= useMajor ? 2 : 1;
}
private void PickIconicEdge(Character result, Dice dice, SettingArchetype archetype, bool bornAHero)
{
var table = new Table<SettingEdge>();
foreach (var item in archetype.IconicEdges)
{
//Task-5: Some edges allow duplicates
if (result.Edges.Any(e => e.Name == item.Name))
continue; //no dups
if (!string.IsNullOrEmpty(item.UniqueGroup))
if (result.Edges.Any(e => e.UniqueGroup == item.UniqueGroup))
continue; //can't have multiple from a unique group (i.e. arcane background)
var requirements = item.Requires.Split(',').Select(e => e.Trim());
if (requirements.All(c => result.HasFeature(c, bornAHero)))
table.Add(item, 1);
}
if (table.Count == 0)
{
Debug.WriteLine("No edges were available");
}
else
{
//Debug.WriteLine($"Found {table.Count} edges");
var edge = table.RandomChoose(dice);
ApplyEdge(result, edge, dice);
result.UnusedIconicEdges -= 1;
}
}
/// <summary>
/// Adds the indicated power to the character.
/// </summary>
/// <remarks>This does NOT deduct a power slot. Nor does it check requirements.</remarks>
private void ApplyPower(Character result, PowerGroup group, SettingPower power, Dice dice)
{
var trappings = new List<SettingTrapping>();
foreach (var item in Trappings)
{
if (group.AvailableTrappings.Count > 0 && !group.AvailableTrappings.Contains(item.Name))
continue;
if (group.ProhibitedTrappings.Contains(item.Name))
continue;
trappings.Add(item);
}
var trapping = dice.Choose(trappings);
var trigger = dice.Choose(group.AvailableTriggers);
var settingPower = Powers.FirstOrDefault(p => p.Name == power.Name);
if (settingPower != null) //copy missing fields
{
if (power.Description.IsNullOrEmpty())
power.Description = settingPower.Description;
if (power.PowerPointsString.IsNullOrEmpty())
power.PowerPointsString = settingPower.PowerPointsString;
}
group.Powers.Add(new Power(power, trapping.Name, trigger));
}
private void PickPower(Character result, PowerGroup group, Dice dice, bool bornAHero)
{
var powers = new List<SettingPower>();
var trappings = new List<SettingTrapping>();
foreach (var item in Powers)
{
if (group.AvailablePowers.Count > 0 && !group.AvailablePowers.Contains(item.Name))
continue;
var requirements = item.Requires.Split(',').Select(e => e.Trim());
if (requirements.All(c => result.HasFeature(c, bornAHero)))
powers.Add(item);
}
foreach (var item in Trappings)
{
if (group.AvailableTrappings.Count > 0 && !group.AvailableTrappings.Contains(item.Name))
continue;
if (group.ProhibitedTrappings.Contains(item.Name))
continue;
trappings.Add(item);
}
if (powers.Count == 0 || trappings.Count == 0)
{
result.Features.Add($"Has {group.UnusedPowers} unused powers for {group.PowerType}.");
group.UnusedPowers = 0;
return;
}
TryAgain:
var trapping = dice.Choose(trappings);
var trigger = dice.Choose(group.AvailableTriggers);
var power = dice.Choose(powers);
if (result.PowerGroups.ContainsPower(power.Name, trapping.Name))
goto TryAgain;
group.Powers.Add(new Power(power, trapping.Name, trigger));
group.UnusedPowers -= 1;
}
private void PickRacialEdge(Character result, Dice dice, SettingRace race, bool bornAHero)
{
var table = new Table<SettingEdge>();
foreach (var item in race.RacialEdges)
{
//Task-5: Some edges allow duplicates
if (result.Edges.Any(e => e.Name == item.Name))
continue; //no dups
if (!string.IsNullOrEmpty(item.UniqueGroup))
if (result.Edges.Any(e => e.UniqueGroup == item.UniqueGroup))
continue; //can't have multiple from a unique group (i.e. arcane background)
var requirements = item.Requires.Split(',').Select(e => e.Trim());
if (requirements.All(c => result.HasFeature(c, bornAHero)))
table.Add(item, 1);
}
if (table.Count == 0)
{
Debug.WriteLine("No edges were available");
}
else
{
//Debug.WriteLine($"Found {table.Count} edges");
var edge = table.RandomChoose(dice);
ApplyEdge(result, edge, dice);
result.UnusedRacialEdges -= 1;
}
}
}
}
<file_sep>using SavageTools.Characters;
using static SavageTools.CardColor;
using static SavageTools.Rank;
namespace SavageTools.Utilities
{
public class EtuDemonGenerator
{
CharacterGenerator m_CharacterGenerator;
public EtuDemonGenerator(CharacterGenerator characterGenerator)
{
m_CharacterGenerator = characterGenerator;
}
public Character GenerateDemon(Dice dice)
{
var character = m_CharacterGenerator.CreateBlankCharacter();
character.Race = "Demon";
character.Spirit = Trait(dice);
character.Vigor = Trait(dice);
character.Agility = Trait(dice);
character.Smarts = Trait(dice);
character.Strength = Strength(dice);
character.Fear = Fear(dice);
//Demon Abilities
character.Hindrances.Add("Bane", "A character may keep a demon at bay by displaying a holy item.");
character.Hindrances.Add("Weakness (Cold Iron)", "Demons take +1d6 damage from pure iron weapons.");
character.Hindrances.Add("Weakness (Holy Water)", "Demons contacted by holy water make a Spirit roll or become Shaken. Wild Card demons areFatigued as well.");
character.Edges.Add("Immunity", "Demons are immune to poison and disease.");
character.Edges.Add("Infernal Stamina", "Demons gain a +2 bonus to recover from being Shaken.");
character.Edges.Add("Resistant to Normal Weapons", "Demons suffer only half - damage from non-magical attacks except for cold iron.");
character.Edges.Add("Claws", "Damage: Str+d4");
switch (dice.PickCard().Rank)
{
case Rank.Two:
case Rank.Three:
case Rank.Four:
character.Skills["Fighting"]!.Trait = 6;
character.Skills["Notice"]!.Trait = 4;
character.Skills["Stealth"]!.Trait = 6;
break;
case Rank.Five:
case Rank.Six:
case Rank.Seven:
character.Skills["Fighting"]!.Trait = 6;
character.Skills["Notice"]!.Trait = 6;
character.Skills["Stealth"]!.Trait = 6;
character.Skills["Taunt"]!.Trait = 6;
break;
case Rank.Eight:
case Rank.Nine:
case Rank.Ten:
character.Skills["Fighting"]!.Trait = 8;
character.Skills["Notice"]!.Trait = 6;
character.Skills["Intimidation"]!.Trait = 6;
character.Skills["Stealth"]!.Trait = 6;
character.Skills["Taunt"]!.Trait = 6;
break;
case Rank.Jack:
character.Skills["Fighting"]!.Trait = 8;
character.Skills["Notice"]!.Trait = 8;
character.Skills["Intimidation"]!.Trait = 8;
character.Skills["Stealth"]!.Trait = 8;
character.Skills["Taunt"]!.Trait = 8;
break;
case Rank.Queen:
character.Skills["Fighting"]!.Trait = 10;
character.Skills["Notice"]!.Trait = 8;
character.Skills["Intimidation"]!.Trait = 8;
character.Skills["Stealth"]!.Trait = 8;
break;
case Rank.King:
character.Skills["Fighting"]!.Trait = 10;
character.Skills["Notice"]!.Trait = 10;
character.Skills["Intimidation"]!.Trait = 8;
character.Skills["Stealth"]!.Trait = 8;
break;
case Rank.Ace:
character.Skills["Fighting"]!.Trait = 12;
character.Skills["Notice"]!.Trait = 10;
character.Skills["Intimidation"]!.Trait = 10;
character.Skills["Stealth"]!.Trait = 10;
break;
case Rank.Joker:
character.Skills["Fighting"]!.Trait = 14;
character.Skills["Notice"]!.Trait = 10;
character.Skills["Intimidation"]!.Trait = 10;
character.Skills["Stealth"]!.Trait = 10;
break;
}
//SWADE Conversion
character.Skills["Athletics"]!.Trait = character.Skills["Fighting"]!.Trait;
var abilities = dice.D(4);
for (var i = 1; i <= abilities; i++)
AddSpecialAbilities(dice, character, m_CharacterGenerator);
m_CharacterGenerator.AddPersonality(character, dice);
character.Cleanup();
return character;
}
int Fear(Dice dice)
{
switch (dice.PickCard().Rank)
{
case Rank.Two:
case Rank.Three:
case Rank.Four:
case Rank.Five:
case Rank.Six:
case Rank.Seven: return -1;
case Rank.Eight:
case Rank.Nine:
case Rank.Ten:
case Rank.Jack: return -2;
case Rank.Queen:
case Rank.King: return -3;
case Rank.Ace:
case Rank.Joker: return -4;
}
return 0;
}
int Size(Dice dice)
{
switch (dice.PickCard().Rank)
{
case Rank.Two:
case Rank.Three:
case Rank.Four: return -2;
case Rank.Five:
case Rank.Six:
case Rank.Seven: return -1;
case Rank.Eight:
case Rank.Nine:
case Rank.Ten: return 0;
case Rank.Jack: return 1;
case Rank.Queen: return 2;
case Rank.King: return 3;
case Rank.Ace: return 4;
case Rank.Joker: return 5;
}
return 0;
}
Trait Trait(Dice dice)
{
switch (dice.PickCard().Rank)
{
case Rank.Two:
case Rank.Three:
case Rank.Four:
case Rank.Five:
case Rank.Six:
case Rank.Seven: return 4;
case Rank.Eight:
case Rank.Nine:
case Rank.Ten: return 6;
case Rank.Jack: return 8;
case Rank.Queen: return 10;
case Rank.King: return 12;
case Rank.Ace: return 13;
case Rank.Joker: return 14;
}
return 0;
}
Trait Strength(Dice dice)
{
switch (dice.PickCard().Rank)
{
case Rank.Two:
case Rank.Three:
case Rank.Four: return 4;
case Rank.Five:
case Rank.Six:
case Rank.Seven:
case Rank.Eight:
case Rank.Nine:
case Rank.Ten: return 6;
case Rank.Jack: return 8;
case Rank.Queen: return 10;
case Rank.King: return 12;
case Rank.Ace: return 14;
case Rank.Joker: return 16;
}
return 0;
}
void AddSpecialAbilities(Dice dice, Character character, CharacterGenerator generator)
{
void AddEdge(string name, string? description = null) => generator.ApplyEdge(character, dice, name, description);
var card = dice.PickCard();
if (card.Rank == Joker)
character.Edges.Add("Spellcaster", "The demon knows 1d4 offensive spells such as bolt, blast, or burst."); //TODO: Add spells
else if (card.Color == Red)
switch (card)
{
case (_, Two): character.Armor += 4; break;
case (_, Three): character.Armor += 2; break;
case (_, Four): AddEdge("Burrowing"); break;
case (_, Five): AddEdge("Hardy"); break;
case (_, Six): AddEdge("Telekinesis", "Does not require power points."); break;
case (_, Seven): AddEdge("Invulnerability to Normal Weapons"); break;
case (_, Eight): AddEdge("Paralysis", "Vigor roll if Shaken or wounded to avoid being paralyzed for 2d4 rounds"); break;
case (_, Nine): AddEdge("Fast Regeneration"); break;
case (_, Ten): AddEdge("Stun"); break;
case (_, Jack):
character.Edges.RemoveAll(g => g.Name == "Claws");
AddEdge("Claws", "Damage: Str+d6");
AddEdge("Improved Frenzy");
break;
case (_, Queen): AddEdge("Flight", "Pace 12, Climb 1"); break;
case (_, King): AddEdge("Cone Attack", "Damage 2d8. Agility roll –2 to avoid."); break;
case (_, Ace):
switch (dice.D(6))
{
case 1:
case 2:
character.Features.Add($"Extra {dice.D(4)} arms");
break;
case 3:
case 4:
character.Features.Add($"Extra {dice.D(4)} legs"); break;
case 5:
character.Features.Add($"Extra tail"); break;
case 6:
character.Features.Add($"Extra head"); break;
}
break;
}
else
switch (card)
{
case (_, Two): AddEdge("Very Attractive"); break;
case (_, Three): AddEdge("Berserk"); break;
case (_, Four): AddEdge("Quick"); break;
case (_, Five): AddEdge("Dodge"); break;
case (_, Six): AddEdge("Fleet-Footed"); break;
case (_, Seven): AddEdge("Harder to Kill"); break;
case (_, Eight): AddEdge("First Strike"); break;
case (_, Nine): AddEdge("Mighty Blow"); break;
case (_, Ten): AddEdge("No Mercy"); break;
case (_, Jack): AddEdge("Bolts", "Range 2/4/8, Damage 2d6+2, RoF 3."); break;
case (_, Queen): AddEdge("Possession"); break;
case (_, King): character.Gear.Add("Weapon", "The demon is armed with a wicked weapon of some sort befitting its Strength."); break;
case (_, Ace): character.Features.Add("Minions: The demon has 2d4 lesser demons in attendance.Create separately.Each has a single Special Ability."); break;
}
}
}
}
<file_sep>using SavageTools;
using SavageTools.Utilities;
namespace SavageToolsWeb.Pages
{
partial class ETUPage
{
protected override string SettingFileName => "ETU.savage-setting";
}
}
<file_sep>namespace SavageToolsWeb.Pages
{
partial class ModernPage
{
protected override string SettingFileName => "Modern.savage-setting";
}
}
<file_sep>using System;
using System.Diagnostics.CodeAnalysis;
namespace SavageTools
{
[SuppressMessage("Microsoft.Naming", "CA1714:FlagsEnumsShouldHavePluralNames")]
[SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")]
[Flags]
public enum Suit
{
BlackJ = 0,
RedJ = 1,
Spades = 2,
Hearts = 3,
Diamonds = 5,
Clubs = 4
}
public enum CardColor
{
Black = 0,
Red = 1
}
}
<file_sep>using System;
using Tortuga.Anchor.Modeling;
namespace SavageTools.Characters
{
public class Gear : ChangeTrackingModelBase
{
public string? Description { get => Get<string?>(); set => Set(value); }
public string Name { get => Get<string>(); set => Set(value); }
public Gear Clone()
{
return new Gear() { Name = Name, Description = Description };
}
}
}
<file_sep>using System.Linq;
namespace SavageTools.Names
{
public class RandomPerson
{
internal RandomPerson(string first, string last, string gender)
{
FirstName = first;
LastName = last;
Gender = gender;
}
public string FirstName { get; set; }
public string FullName { get { return FirstName + " " + LastName; } }
public string Gender { get; set; }
public string LastName { get; set; }
}
}
<file_sep>using System;
using Tortuga.Anchor.Modeling;
namespace SavageTools.Characters
{
public class Feature : ChangeTrackingModelBase
{
public string Name { get => Get<string>(); set => Set(value); }
public Feature Clone()
{
return new Feature() { Name = Name };
}
}
}<file_sep>using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using Tortuga.Anchor.Modeling;
namespace SavageTools.Characters
{
public class StoryBuilder
{
readonly MissionOptions m_Settings;
readonly StringBuilder m_Story = new StringBuilder();
bool m_NeedsTab = true;
int m_TabDepth;
//TOOD: Add Markdown options
public StoryBuilder(bool useHtml) : this(new MissionOptions() { UseHtml = useHtml })
{
}
public StoryBuilder(MissionOptions? settings = null)
{
m_Settings = settings ?? new MissionOptions();
}
public MissionOptions Settings => m_Settings;
public void Append(string value)
{
if (m_Settings.UseHtml)
{
if (m_NeedsTab)
m_Story.Append($"<p style=\"text-indent: {m_TabDepth * 25}px;\">");
m_Story.Append(WebUtility.HtmlEncode(value));
m_NeedsTab = false;
}
else
{
if (m_NeedsTab)
for (int i = 1; i <= m_TabDepth; i++)
m_Story.Append("\t");
m_NeedsTab = false;
m_Story.Append(value);
}
}
public void AppendLine(string value)
{
if (m_Settings.UseHtml)
{
if (m_NeedsTab)
m_Story.Append($"<p style=\"text-indent: {m_TabDepth * 25}px;\">");
m_Story.Append(WebUtility.HtmlEncode(value));
m_Story.AppendLine("</p>");
}
else
{
if (m_NeedsTab)
for (int i = 1; i <= m_TabDepth; i++)
m_Story.Append("\t");
m_NeedsTab = false;
m_Story.AppendLine(value);
}
m_NeedsTab = true;
}
public override string ToString()
{
return m_Story.ToString();
}
public void IncreaseIndent()
{
m_TabDepth += 1;
}
public void DecreaseIndent()
{
m_TabDepth -= 1;
}
public IDisposable Indent()
{
m_TabDepth += 1;
return new IndentToken(this);
}
public void AppendLine()
{
AppendLine("");
}
class IndentToken : IDisposable
{
readonly StoryBuilder m_StoryBuilder;
public IndentToken(StoryBuilder storyBuilder)
{
m_StoryBuilder = storyBuilder;
}
public void Dispose()
{
m_StoryBuilder.m_TabDepth -= 1;
}
}
}
}
<file_sep>using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Hosting;
namespace SavageToolsWeb.Pages
{
partial class IndexPage
{
[Inject] IWebHostEnvironment Environment { get; set; } = null!;
}
}
<file_sep>namespace SavageTools.Settings
{
public static class SettingsExtension
{
public static bool IsMajor(this SettingHindrance hindrance)
{
return hindrance.Type == "Major" || hindrance.Type == "Minor/Major";
}
public static bool IsMinor(this SettingHindrance hindrance)
{
return hindrance.Type == "Minor" || hindrance.Type == "Minor/Major";
}
}
}
<file_sep>namespace SavageTools
{
public record Card(Suit Suit, Rank Rank)
{
public CardColor Color => (CardColor)(Suit & Suit.RedJ);
public void Deconstruct(out Suit suit, out Rank rank) => (suit, rank) = (Suit, Rank);
public void Deconstruct(out Suit suit, out Rank rank, out CardColor color) => (suit, rank, color) = (Suit, Rank, Color);
//public void Deconstruct(out Rank rank, out CardColor color) => (rank, color) = (Rank, Color);
//public BlackRedCard ToBlackRed => new(Color, Rank);
public static implicit operator Suit(Card c) => c.Suit;
public static implicit operator Rank(Card c) => c.Rank;
public static implicit operator CardColor(Card c) => c.Color;
public override string ToString()
{
if (Rank == Rank.Joker)
return $"{Color} {Rank}";
return $"{Rank} of {Suit}";
}
}
//public record BlackRedCard(CardColor color, Rank Rank);
}
<file_sep>namespace SavageToolsWeb.Pages
{
partial class FantasyPage
{
protected override string SettingFileName => "Fantasy.savage-setting";
}
}
<file_sep>using SavageTools.Settings;
using System;
using Tortuga.Anchor.Modeling;
namespace SavageTools.Characters
{
public class Power : ChangeTrackingModelBase
{
public Power(SettingPower power, string trapping, string trigger)
{
//if (string.IsNullOrEmpty(name))
// throw new ArgumentException($"{nameof(name)} is null or empty.", nameof(name));
if (string.IsNullOrEmpty(trapping))
throw new ArgumentException($"{nameof(trapping)} is null or empty.", nameof(trapping));
Name = power.Name;
Trapping = trapping;
Trigger = trigger;
PowerPoints = power.PowerPoints;
Description = power.Description;
}
public string LongName => $"{Name} [{Trigger} => {Trapping}]";
public string Name { get => Get<string>(); set => Set(value); }
public string Trapping { get => Get<string>(); set => Set(value); }
public string Trigger { get => Get<string>(); set => Set(value); }
public string Description { get => Get<string>(); set => Set(value); }
public int? PowerPoints { get => Get<int?>(); set => Set(value); }
public override string ToString() => LongName;
//public Power Clone()
//{
// return new Power(Name, Trapping, Trigger, PowerPoints);
//}
}
}
<file_sep>using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Logging;
using Microsoft.JSInterop;
using System;
using System.Threading.Tasks;
namespace SavageToolsWeb.Shared
{
public class PageBase : ComponentBase
{
[Inject] protected IJSRuntime JSRuntime { get; set; } = null!;
[Inject] protected ILogger<PageBase> Logger { get; set; } = null!;
[Inject] protected NavigationManager Navigation { get; set; } = null!;
/// <summary>
/// Gets or sets a value indicating whether this instance is connected.
/// </summary>
/// <value><c>true</c> if this instance is connected; <c>false</c> if it is pre-rendering.</value>
protected bool IsConnected { get; set; }
protected bool LoadFailed { get; private set; }
protected Exception? LastError { get; private set; }
protected string? PageTitle { get; set; }
/// <summary>
/// Method invoked after each time the component has been rendered.
/// </summary>
/// <param name="firstRender">The first render.</param>
/// <remarks>Any errors are automatically caught and logged. </remarks>
protected virtual void AfterRender(bool firstRender)
{
}
/// <summary>
/// Method invoked after each time the component has been rendered. Note that the component does
/// not automatically re-render after the completion of any returned <see cref="T:System.Threading.Tasks.Task" />, because
/// that would cause an infinite render loop.
/// </summary>
/// <param name="firstRender">The first render.</param>
/// <remarks>Any errors are automatically caught and logged. </remarks>
protected virtual Task AfterRenderAsync(bool firstRender) => Task.CompletedTask;
protected sealed override void OnAfterRender(bool firstRender)
{
base.OnAfterRender(firstRender);
try
{
AfterRender(firstRender);
}
catch (Exception ex)
{
LoadFailed = true;
LastError = ex;
Logger.LogError(ex, $"Internal error, loading failed during {nameof(AfterRender)}");
}
}
async protected sealed override Task OnAfterRenderAsync(bool firstRender)
{
await JSRuntime.InvokeVoidAsync("setTitle", PageTitle!);
await NavigateToElementAsync();
await base.OnAfterRenderAsync(firstRender);
try
{
await AfterRenderAsync(firstRender);
}
catch (Exception ex)
{
LoadFailed = true;
LastError = ex;
Logger.LogError(ex, $"Internal error, loading failed during {nameof(AfterRenderAsync)}");
}
}
/// <summary>
/// Method invoked when the component is ready to start, having received its
/// initial parameters from its parent in the render tree.
/// Override this method if you will perform an asynchronous operation and
/// want the component to refresh when that operation is completed.
/// </summary>
/// <remarks>Any errors are automatically caught and logged. </remarks>
protected virtual Task InitializedAsync() => Task.CompletedTask;
protected async override sealed Task OnInitializedAsync()
{
await base.OnInitializedAsync();
try
{
await JSRuntime.InvokeVoidAsync("isPreRendering");
IsConnected = true;
}
catch (InvalidOperationException ex) when (ex.Message.Contains("JavaScript interop calls cannot be issued at this time."))
{
}
try
{
await InitializedAsync();
}
catch (Exception ex)
{
LoadFailed = true;
LastError = ex;
Logger.LogError(ex, $"Internal error, loading failed during {nameof(InitializedAsync)}");
}
}
/// <summary>
/// Method invoked when the component is ready to start, having received its
/// initial parameters from its parent in the render tree.
/// </summary>
/// <remarks>Any errors are automatically caught and logged. </remarks>
protected virtual void Initialized()
{
}
protected override sealed void OnInitialized()
{
base.OnInitialized();
try
{
Initialized();
}
catch (Exception ex)
{
LoadFailed = true;
LastError = ex;
Logger.LogError(ex, $"Internal error, loading failed during {nameof(Initialized)}");
}
}
/// <summary>
/// Method invoked when the component has received parameters from its parent in
/// the render tree, and the incoming values have been assigned to properties.
/// </summary>
/// <remarks>Any errors are automatically caught and logged. </remarks>
protected virtual void ParametersSet()
{
}
protected override sealed void OnParametersSet()
{
base.OnParametersSet();
try
{
ParametersSet();
}
catch (Exception ex)
{
LoadFailed = true;
LastError = ex;
Logger.LogError(ex, $"Internal error, loading failed during {nameof(ParametersSet)}");
}
base.OnParametersSet();
}
/// <summary>
/// Method invoked when the component has received parameters from its parent in
/// the render tree, and the incoming values have been assigned to properties.
/// </summary>
/// <remarks>Any errors are automatically caught and logged. </remarks>
protected virtual Task ParametersSetAsync() => Task.CompletedTask;
protected async sealed override Task OnParametersSetAsync()
{
await base.OnParametersSetAsync();
try
{
await ParametersSetAsync();
}
catch (Exception ex)
{
LoadFailed = true;
LastError = ex;
Logger.LogError(ex, $"Internal error, loading failed during {nameof(ParametersSetAsync)}");
}
}
async Task NavigateToElementAsync()
{
if (!IsConnected)
return;
//ref: https://github.com/aspnet/AspNetCore/issues/8393
var fragment = new Uri(Navigation.Uri).Fragment;
if (string.IsNullOrEmpty(fragment))
return;
var elementId = fragment.StartsWith("#") ? fragment.Substring(1) : fragment;
if (string.IsNullOrEmpty(elementId))
return;
await JSRuntime.InvokeAsync<bool>("scrollToElementId", elementId);
}
}
}
<file_sep>using Microsoft.AspNetCore.Components.Web;
using SavageTools;
using SavageTools.Utilities;
using System;
using System.Collections.Generic;
namespace SavageToolsWeb.Pages
{
partial class ETUAdventurePage
{
protected override string SettingFileName => "ETU.savage-setting";
public string? ErrorDisplay;
protected void CreateAdventure()
{
try
{
var gen = new EtuAdventureGenerator(Model!.CharacterGenerator);
Adventure = gen.GenerateAdventure();
StateHasChanged();
}
catch (Exception ex)
{
ErrorDisplay = ex.ToString();
}
}
protected EtuAdventure? Adventure = null;
protected NameDescriptionPair? HighStrangeness = null;
protected List<NameDescriptionPair>? RitualComponents = null;
void ClearAll(MouseEventArgs args)
{
Adventure = null;
HighStrangeness = null;
StateHasChanged();
}
void CreateRitual(MouseEventArgs args)
{
try
{
var gen = new EtuAdventureGenerator(Model!.CharacterGenerator);
RitualComponents = gen.CreateRitual(new Dice(), 0);
StateHasChanged();
}
catch (Exception ex)
{
ErrorDisplay = ex.ToString();
}
}
void CreateHighStrangness(MouseEventArgs args)
{
try
{
var gen = new EtuAdventureGenerator(Model!.CharacterGenerator);
HighStrangeness = gen.HighStrangeness(new Dice());
StateHasChanged();
}
catch (Exception ex)
{
ErrorDisplay = ex.ToString();
}
}
}
}
<file_sep>using Ganss.XSS;
using Markdig;
using Microsoft.AspNetCore.Components;
namespace SavageToolsWeb.Controls
{
partial class MarkdownView
{
private string? _content;
[Inject] public IHtmlSanitizer HtmlSanitizer { get; set; } = null!;
[Parameter]
public string? Content
{
get => _content;
set
{
_content = value;
HtmlContent = ConvertStringToMarkupString(_content);
}
}
public MarkupString HtmlContent { get; private set; }
private MarkupString ConvertStringToMarkupString(string? value)
{
if (!string.IsNullOrWhiteSpace(value))
{
// Convert markdown string to HTML
var html = Markdown.ToHtml(value, new MarkdownPipelineBuilder().UseAdvancedExtensions().Build());
// Sanitize HTML before rendering
var sanitizedHtml = HtmlSanitizer.Sanitize(html);
// Return sanitized HTML as a MarkupString that Blazor can render
return new MarkupString(sanitizedHtml);
}
return new MarkupString();
}
}
}
<file_sep>namespace SavageToolsWeb.Pages
{
partial class UrbanFantasy
{
protected override string SettingFileName => "Urban Fantasy.savage-setting";
}
}
<file_sep>namespace SavageToolsWeb.Pages
{
partial class HorrorPage
{
protected override string SettingFileName => "Horror.savage-setting";
}
}
<file_sep>namespace SavageToolsWeb.Pages
{
partial class ErrorPage
{
}
}
<file_sep>using Tortuga.Anchor.Modeling;
namespace SavageTools.Characters
{
public class Personality : ChangeTrackingModelBase
{
public string Name { get => Get<string>(); set => Set(value); }
}
}<file_sep>using Tortuga.Anchor.Modeling;
namespace SavageTools.Characters
{
public class Edge : ChangeTrackingModelBase
{
public string? Description { get => Get<string?>(); set => Set(value); }
public string Name { get => Get<string>(); set => Set(value); }
public string? UniqueGroup { get => Get<string?>(); set => Set(value); }
public Edge Clone()
{
return new Edge()
{
Description = Description,
Name = Name,
UniqueGroup = UniqueGroup
};
}
public override string ToString()
{
if (!string.IsNullOrEmpty(Description))
return Name + ": " + Description;
else
return Name;
}
}
}
<file_sep>using Tortuga.Anchor.Modeling;
namespace SavageTools.Characters
{
public class PowerCollection : ChangeTrackingModelCollection<Power>
{
//public void Add(string name, string trapping, string trigger)
//{
// Add(new Power(name, trapping, trigger));
//}
}
}
<file_sep>using System.Runtime.CompilerServices;
using Tortuga.Anchor.Modeling.Internals;
namespace SavageToolsWeb.Shared
{
public class PageBase<T> : PageBase where T : class
{
T? m_Model;
readonly PropertyBag m_Properties;
public PageBase()
{
m_Properties = new PropertyBag(this);
}
/// <summary>
/// Gets or sets the model.
/// </summary>
/// <remarks>Normally this will be set in the ParametersSet or ParametersSetAsync method.</remarks>
protected T? Model
{
get => m_Model;
set
{
if (m_Model != value)
{
m_Model = value;
OnModelChanged();
StateHasChanged();
}
}
}
/// <summary>
/// This is called after the model has been replaced or removed.
/// </summary>
protected virtual void OnModelChanged()
{
}
/// <summary>
/// Sets the specified parameter.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="regenerateModel">If true, set the Model property to null so that it will be regenerated.</param>
/// <param name="parameterName">Name of the parameter.</param>
protected void Set(object? value, bool regenerateModel, [CallerMemberName] string parameterName = "")
{
if (m_Properties.Set(value!, parameterName) && regenerateModel)
{
StateHasChanged();
if (regenerateModel)
Model = null;
}
}
/// <summary>
/// Gets the specified parameter.
/// </summary>
/// <typeparam name="TProperty">The type of parameter to return.</typeparam>
/// <param name="parameterName">Name of the parameter.</param>
/// <returns>TProperty.</returns>
protected TProperty Get<TProperty>([CallerMemberName] string parameterName = "") => m_Properties.Get<TProperty>(parameterName);
}
}
<file_sep>using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Hosting;
using SavageTools.Characters;
using SavageToolsWeb.Shared;
using System.IO;
namespace SavageToolsWeb.Pages
{
public abstract class SettingPage : PageBase<CharacterOptions>
{
[Inject] IWebHostEnvironment Environment { get; set; } = null!;
protected abstract string SettingFileName { get; }
protected override void ParametersSet()
{
if (Model == null)
{
var file = new FileInfo(Path.Combine(Environment.WebRootPath, "App_Data", SettingFileName));
var cg = new CharacterGenerator(file);
Model = new CharacterOptions(cg);
Model.PropertyChanged += (s, e) => StateHasChanged();
PageTitle = Model.CharacterGenerator.SettingName;
}
}
}
}
<file_sep>using SavageTools;
using SavageTools.Utilities;
namespace SavageToolsWeb.Pages
{
partial class ETUDemonPage
{
protected override string SettingFileName => "ETU.savage-setting";
protected void CreateDemon()
{
var gen = new EtuDemonGenerator(Model!.CharacterGenerator);
Model.Squad.Insert(0, gen.GenerateDemon(new Dice()));
StateHasChanged();
}
}
}
<file_sep>namespace SavageToolsWeb.Pages
{
partial class AboutPage
{
public AboutPage()
{
PageTitle = "About";
}
}
}
<file_sep>using Microsoft.AspNetCore.Components;
using SavageTools;
using SavageTools.Characters;
using System;
namespace SavageToolsWeb.Controls
{
partial class CharacterBuilderDisplay
{
CharacterOptions? options;
[Parameter]
public CharacterOptions? Options
{
get => options;
set
{
if (options != null)
{
options.PropertyChanged -= Options_PropertyChanged;
options.Squad.CollectionChanged -= Squad_CollectionChanged;
}
options = value;
if (options != null)
{
options.PropertyChanged += Options_PropertyChanged;
options.Squad.CollectionChanged += Squad_CollectionChanged;
}
}
}
private void Squad_CollectionChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
StateHasChanged();
}
private void Options_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
StateHasChanged();
}
public string? ErrorDisplay;
protected void SubmitChanges()
{
//These should never happen.
if (Options == null)
return;
ErrorDisplay = null;
try
{
var dice = new Dice();
for (var i = 0; i < Options.Count; i++)
{
Options.Squad.Insert(0, Options.CharacterGenerator.GenerateCharacter(Options, dice));
}
}
catch (Exception ex)
{
ErrorDisplay = "Unable to create character: " + ex.Message;
}
}
}
}
<file_sep>using System.Xml.Serialization;
using Tortuga.Anchor;
#pragma warning disable RCS1139 // Add summary element to documentation comment.
#nullable disable
namespace SavageTools.Settings
{
/// <remarks/>
[XmlType(AnonymousType = true)]
[XmlRoot(Namespace = "", IsNullable = false)]
public class Setting
{
/// <remarks/>
[XmlAttribute()]
public string Name { get; set; }
/// <remarks/>
[XmlAttribute()]
public string NamePrefix { get; set; }
[XmlAttribute]
public bool BornAHero { get; set; }
[XmlAttribute]
public bool MoreSkills { get; set; }
[XmlAttribute]
public bool UseStrain { get; set; }
[XmlAttribute]
public bool UseReason { get; set; }
[XmlAttribute]
public bool UseStatus { get; set; }
//[XmlAttribute]
//public bool ShowSetting { get; set; }
/// <remarks/>
[XmlArrayItem("Skill", IsNullable = false)]
public SettingSkillOption[] Skills { get; set; }
/// <remarks/>
[XmlArrayItem("Skill", IsNullable = false)]
public SettingRemoveSkill[] RemoveSkills { get; set; }
/// <remarks/>
[XmlArrayItem("Hindrance", IsNullable = false)]
public SettingHindrance[] Hindrances { get; set; }
/// <remarks/>
[XmlArrayItem("Edge", IsNullable = false)]
public SettingEdge[] Edges { get; set; }
/// <remarks/>
[XmlArrayItem("Archetype", IsNullable = false)]
public SettingArchetype[] Archetypes { get; set; }
/// <remarks/>
[XmlArrayItem("Race", IsNullable = false)]
public SettingRace[] Races { get; set; }
/// <remarks/>
[XmlArrayItem("Rank", IsNullable = false)]
public SettingRank[] Ranks { get; set; }
/// <remarks/>
[XmlArrayItem("Reference", IsNullable = false)]
public SettingReference[] References { get; set; }
/// <remarks/>
[XmlArrayItem("Power", IsNullable = false)]
public SettingPower[] Powers { get; set; }
/// <remarks/>
[XmlArrayItem("Trapping", IsNullable = false)]
public SettingTrapping[] Trappings { get; set; }
}
/// <remarks/>
[XmlType(AnonymousType = true)]
public class SettingRemoveSkill
{
/// <remarks/>
[XmlAttribute()]
public string Name { get; set; }
}
/// <remarks/>
[XmlType(AnonymousType = true)]
public class SettingSkillOption
{
/// <remarks/>
[XmlAttribute()]
public string Name { get; set; }
/// <remarks/>
[XmlAttribute()]
public string Attribute { get; set; }
[XmlAttribute()]
public bool IsCore { get; set; }
[XmlAttribute()]
public bool NoAnimals { get; set; }
}
/// <remarks/>
[XmlType(AnonymousType = true)]
public class SettingHindrance
{
/// <remarks/>
[XmlAttribute()]
public string Name { get; set; }
/// <remarks/>
[XmlAttribute()]
public string Type { get; set; }
/// <remarks/>
[XmlAttribute()]
public string Description { get; set; }
/// <remarks/>
[XmlElement("Skill")]
public SettingSkill[] Skill { get; set; }
/// <remarks/>
[XmlElement("Trait")]
public SettingTrait[] Trait { get; set; }
/// <remarks/>
[XmlElement("Feature")]
public SettingFeature[] Features { get; set; }
}
/// <remarks/>
[XmlType(AnonymousType = true)]
public class SettingEdge
{
/// <remarks/>
[XmlElement("Skill")]
public SettingSkill[] Skills { get; set; }
/// <remarks/>
[XmlElement("Trait")]
public SettingTrait[] Traits { get; set; }
/// <remarks/>
[XmlElement("Feature")]
public SettingFeature[] Features { get; set; }
/// <remarks/>
[XmlElement("Edge")]
public SettingEdge[] Edges { get; set; }
/// <remarks/>
[XmlElement("Hindrance")]
public SettingHindrance[] Hindrances { get; set; }
/// <remarks/>
[XmlElement("AvailablePower")]
public SettingAvailablePower[] AvailablePowers { get; set; }
[XmlElement("Power")]
public SettingPower[] Powers { get; set; }
/// <remarks/>
[XmlElement("Trigger")]
public SettingTrigger[] Triggers { get; set; }
/// <remarks/>
[XmlAttribute()]
public string Name { get; set; }
/// <remarks/>
[XmlAttribute()]
public string Requires { get; set; }
/// <remarks/>
[XmlAttribute()]
public string Description { get; set; }
/// <remarks/>
[XmlAttribute()]
public string UniqueGroup { get; set; }
/// <remarks/>
[XmlAttribute()]
public string PowerType { get; set; }
}
/// <remarks/>
[XmlType(AnonymousType = true)]
public class SettingPower
{
/// <remarks/>
[XmlAttribute()]
public string Name { get; set; }
/// <remarks/>
[XmlAttribute()]
public string Requires { get; set; }
/// <remarks/>
[XmlAttribute()]
public string PowerType { get; set; }
/// <remarks/>
[XmlAttribute()]
public string Description { get; set; }
/// <remarks/>
[XmlAttribute()]
public string Trapping { get; set; }
/// <remarks/>
[XmlAttribute()]
public string Trigger { get; set; }
/// <remarks/>
[XmlAttribute("PowerPoints")]
public string PowerPointsString { get; set; }
public int? PowerPoints => !PowerPointsString.IsNullOrEmpty() ? (int?)int.Parse(PowerPointsString) : null;
}
/// <remarks/>
[XmlType(AnonymousType = true)]
public class SettingTrapping
{
/// <remarks/>
[XmlAttribute()]
public string Name { get; set; }
}
/// <remarks/>
[XmlType(AnonymousType = true)]
public class SettingSkill
{
/// <remarks/>
[XmlAttribute()]
public string Name { get; set; }
/// <remarks/>
[XmlAttribute()]
public string Attribute { get; set; }
/// <remarks/>
[XmlAttribute()]
public int Level { get; set; }
/// <remarks/>
[XmlAttribute()]
public int MaxLevelBonus { get; set; }
}
/// <remarks/>
[XmlType(AnonymousType = true)]
public class SettingFeature
{
/// <remarks/>
[XmlAttribute()]
public string Name { get; set; }
}
/// <remarks/>
[XmlType(AnonymousType = true)]
public class SettingGear
{
/// <remarks/>
[XmlAttribute()]
public string Name { get; set; }
/// <remarks/>
[XmlAttribute()]
public string Description { get; set; }
/// <remarks/>
[XmlElement("Trait")]
public SettingTrait[] Traits { get; set; }
}
/// <remarks/>
[XmlType(AnonymousType = true)]
public class SettingAvailablePower
{
/// <remarks/>
[XmlAttribute()]
public string Name { get; set; }
}
/// <remarks/>
[XmlType(AnonymousType = true)]
public class SettingTrigger
{
/// <remarks/>
[XmlAttribute()]
public string Name { get; set; }
}
/// <remarks/>
[XmlType(AnonymousType = true)]
public class SettingArchetype
{
/// <remarks/>
[XmlElement("Skill")]
public SettingSkill[] Skills { get; set; }
/// <remarks/>
[XmlElement("Trait")]
public SettingTrait[] Traits { get; set; }
/// <remarks/>
[XmlElement("Edge")]
public SettingEdge[] Edges { get; set; }
[XmlArrayItem("Edge", IsNullable = false)]
public SettingEdge[] IconicEdges { get; set; }
/// <remarks/>
[XmlElement("Hindrance")]
public SettingHindrance[] Hindrances { get; set; }
/// <remarks/>
[XmlAttribute()]
public string Name { get; set; }
/// <remarks/>
[XmlAttribute()]
public bool WildCard { get; set; }
/// <remarks/>
[XmlAttribute()]
public int UnusedAttributes { get; set; }
/// <remarks/>
[XmlAttribute()]
public int UnusedSkills { get; set; }
/// <remarks/>
[XmlAttribute()]
public int Agility { get; set; }
/// <remarks/>
[XmlAttribute()]
public int Smarts { get; set; }
/// <remarks/>
[XmlAttribute()]
public int Spirit { get; set; }
/// <remarks/>
[XmlAttribute()]
public int Strength { get; set; }
/// <remarks/>
[XmlAttribute()]
public int Vigor { get; set; }
/// <remarks/>
[XmlAttribute()]
public bool IsWildCard { get; set; }
/// <remarks/>
[XmlAttribute()]
public string Race { get; set; }
/// <remarks/>
[XmlElement("Feature")]
public SettingFeature[] Features { get; set; }
/// <remarks/>
[XmlElement("Gear")]
public SettingGear[] Gear { get; set; }
}
/// <remarks/>
[XmlType(AnonymousType = true)]
public class SettingTrait
{
/// <remarks/>
[XmlAttribute()]
public string Name { get; set; }
/// <remarks/>
[XmlAttribute()]
public int Bonus { get; set; }
}
/// <remarks/>
[XmlType(AnonymousType = true)]
public partial class SettingRace
{
/// <remarks/>
[XmlElement("Skill")]
public SettingSkill[] Skills { get; set; }
/// <remarks/>
[XmlElement("Hindrance")]
public SettingHindrance[] Hindrances { get; set; }
/// <remarks/>
[XmlElement("Trait")]
public SettingTrait[] Traits { get; set; }
/// <remarks/>
[XmlElement("Edge")]
public SettingEdge[] Edges { get; set; }
[XmlArrayItem("Edge", IsNullable = false)]
public SettingEdge[] RacialEdges { get; set; }
/// <remarks/>
[XmlElement("Power")]
public SettingPower[] Powers { get; set; }
/// <remarks/>
[XmlAttribute()]
public string Name { get; set; }
/// <remarks/>
[XmlAttribute()]
public bool AnimalIntelligence { get; set; }
/// <remarks/>
[XmlAttribute()]
public bool IsLimited { get; set; }
}
/// <remarks/>
[XmlType(AnonymousType = true)]
public class SettingRank
{
/// <remarks/>
[XmlAttribute()]
public string Name { get; set; }
[XmlAttribute()]
public string DisplayName { get; set; }
/// <remarks/>
[XmlAttribute()]
public int Experience { get; set; }
/// <remarks/>
[XmlAttribute()]
public int UnusedAdvances { get; set; }
}
/// <remarks/>
[XmlType(AnonymousType = true)]
public class SettingReference
{
/// <remarks/>
[XmlAttribute()]
public string Name { get; set; }
}
}
|
707c38190787253043af9d3c7c214c4e8b8b3237
|
[
"Markdown",
"C#"
] | 60
|
C#
|
Grauenwolf/SavageTools
|
ec40c8c709b537d344414fae69c35aa0130e40f1
|
b593454cc2fa1568738da8e7055f514a02aea6f2
|
refs/heads/master
|
<repo_name>ruccoon/cejv679_Assignment<file_sep>/soccer/src/test/java/com/cejv679/spring/StattisticTestCase.java
package com.cejv679.spring;
import com.cejv679.spring.soccer.SoccerHelper;
import com.cejv679.spring.soccer.factory.SoccerFactory;
import com.cejv679.spring.soccer.factory.StatisticFactory;
import com.cejv679.spring.soccer.model.Player;
import com.cejv679.spring.soccer.model.Statistic;
import config.TestConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.math.BigDecimal;
import java.util.Currency;
import static org.junit.Assert.*;
/**
* Unit test for create player.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class)
public class StattisticTestCase {
@Autowired
private SoccerFactory soccerFactory;
@Autowired
private SoccerHelper soccerHelper;
@Autowired
private StatisticFactory statisticFactory;
@Autowired
private Statistic statistic;
@Test
public void assertThatStatistic_IsBuilt() {
assertNotNull(statistic);
}
@Test
public void assertThatStatisticInfo_IsCorrect() {
assertEquals(statistic.getGoals(), 2);
assertEquals(statistic.getBookings(), 1);
}
@Test
public void assertThatStatistic_IsCreated() {
Statistic newStatistic = soccerFactory.createStatistic(5, 1);
assertNotNull(newStatistic);
assertEquals(newStatistic.getGoals(), 5);
assertEquals(newStatistic.getBookings(), 1);
}
@Test
public void assertThatStatistic_IsUpdated(){
Statistic newStatistic = soccerFactory.createStatistic(3,2);
Player newPlayer = soccerFactory.createPlayer("Lionel", "Messi", 30, Currency.getInstance("EUR"), new BigDecimal(80000), "Argentina", "Forward");
statisticFactory.updateStatistic(newPlayer, newStatistic);
assertEquals(newPlayer.getStatistic().getGoals(), 3);
assertEquals(newPlayer.getStatistic().getBookings(), 2);
}
@Test
public void assertThatStatistic_IsValid(){
Statistic newStatistic = soccerFactory.createStatistic(0,0);
assertTrue(soccerHelper.isValidStatistic(newStatistic));
newStatistic = soccerFactory.createStatistic(1,1);
assertTrue(soccerHelper.isValidStatistic(newStatistic));
newStatistic = soccerFactory.createStatistic(-1,0);
assertFalse(soccerHelper.isValidStatistic(newStatistic));
newStatistic = soccerFactory.createStatistic(0,-1);
assertFalse(soccerHelper.isValidStatistic(newStatistic));
}
}
|
0759d8892c8ebe17e422fd932f78d06dd18f7bd1
|
[
"Java"
] | 1
|
Java
|
ruccoon/cejv679_Assignment
|
4bb9ab7ac803a748c6ed888a45b874df990c28b9
|
1488a1c4b071ce02d55f7c0e330aa1183e7f323d
|
refs/heads/master
|
<repo_name>juanoliveira1/Curso-Web<file_sep>/jscontrole/if1.js
function soBoaNoticia(nota) {
if (nota >= 7) {
console.log('Aprovado com ' + nota)
}
else {
console.log('Reprovado com ' + nota)
}
}
soBoaNoticia(6, 9)
soBoaNoticia(7, 1)
function seForVerdadeEuFalo(valor) {
if (valor) {
console.log('É verdade...' + valor)
}
else{
console.log('É mentira ' + valor)
}
}
seForVerdadeEuFalo()
seForVerdadeEuFalo(null)
seForVerdadeEuFalo(undefined)
seForVerdadeEuFalo(NaN)
seForVerdadeEuFalo('')
seForVerdadeEuFalo(0)
seForVerdadeEuFalo(-1)
seForVerdadeEuFalo(' ')
seForVerdadeEuFalo('?')
seForVerdadeEuFalo([])
seForVerdadeEuFalo([1,2])
seForVerdadeEuFalo({})
<file_sep>/jsfundamentos/destructuring.js
// novo recurso do ES2015
const pessoa = {
nome : 'Ana',
idade : 5,
endereco : {
logradouro : 'Rua ABC',
numero : 1000
}
}
const {nome, idade} = pessoa
console.log(nome , idade)
const {nome : n, idade : i} = pessoa
console.log(n,i)
const {sobrenome , bemHumorada = true} = pessoa
console.log(sobrenome , bemHumorada)
const {endereco : { logradouro, numero, cep } } = pessoa
console.log(logradouro, numero , cep)
const {conta : {ag,num} } = pessoa //Não funciona
console.log(ag,num)
|
34fed1617164b56465936c567158b3c1d94e7cca
|
[
"JavaScript"
] | 2
|
JavaScript
|
juanoliveira1/Curso-Web
|
15c0cc8811eb7627dd2b135f06e31bd532a9829b
|
7fd5d62e8e705e0e0829d34721cca3c6b0631683
|
refs/heads/master
|
<repo_name>mirgee/software_verification<file_sep>/du_paths/graph_plot.py
import networkx as nx
import pygraphviz
import matplotlib.pyplot as plt
g=nx.DiGraph()
g.add_edges_from(ebunch = [(1,2),(2,3),(3,4),(3,5),(4,5),(5,6),(5,12),(6,7),(6,8),(7,6),(8,9),(8,10),(9,8),(10,11),(11,5)])
# pos=nx.spring_layout(g)
pos=nx.nx_agraph.graphviz_layout(g, prog='dot')
plt.figure(figsize=(12,12))
labels={}
labels[1]=r'$B_{999}$'
labels[2]=r'$B_0$'
labels[3]=r'$B_1$'
labels[4]=r'$B_9$'
labels[5]=r'$B_2$'
labels[6]=r'$B_4$'
labels[7]=r'$B_8$'
labels[8]=r'$B_5$'
labels[9]=r'$B_6$'
labels[10]=r'$B_7$'
labels[11]=r''
labels[12]=r'$B_3$'
nx.draw_networkx_edges(g,pos,
width=1,alpha=0.5,edge_color='black', arrows=True)
nx.draw_networkx_nodes(g,pos,
node_color='r',
node_size=1000,
alpha=0.8)
nx.draw_networkx_labels(g,pos,labels,font_size=16)
plt.axis('off')
# plt.figure(figsize=(8,6))
plt.savefig("graph.png") # save as png
plt.show() # display<file_sep>/du_paths/du_paths.py
import networkx as nx
edges = [(1,2),(2,3),(3,4),(2,4),(4,5),(5,6),(5,10),(6,7),(6,8),(7,6),(8,9),(9,5)]
defs = [1,8]
uses = [7,10]
g = nx.DiGraph()
# g = nx.random_regular_graph(2, 5)
g.add_edges_from(edges)
res = ""
# Zacatek
for source in g.nodes():
# Konec
for target in g.nodes():
# Pokud je zacatek mezi hledanymi defy a konec mezi use
if (source in defs) and (target in uses):
# Najdi jednoduche cesty
candidates = nx.all_simple_paths(g, source=source, target=target)
# Musi byt def-ciste
candidates = list(filter(lambda path: not any(d in path[1:] for d in defs), candidates))
# Vypis
res += "du({},{},a999) = {}\n".format(source, target, candidates) if len(candidates) > 0 else ""
print(res)<file_sep>/tbl2txt/os_allpairs.py
import metacomm.combinatorics.all_pairs2
all_pairs = metacomm.combinatorics.all_pairs2.all_pairs2
levels = [
["Prum", "Sherlock", "SAPELI"],
["YTONG", "Betong"],
["50 cm", "60 cm", "70 cm"],
["silikonova", "akrylatova"],
["ano", "ne"]
]
pairwise = all_pairs( levels )
for i, v in enumerate(pairwise):
print "%i:\t%s" % (i, str(v))<file_sep>/model/graph_plot.py
import networkx as nx
import pygraphviz
import matplotlib.pyplot as plt
g=nx.DiGraph()
g.add_edges_from([(0,1),(1,2),(1,7),(2,3),(2,6),(3,4),(3,5),(4,3),(5,2),(6,7),(7,8),(7,9),(8,9)])
# pos=nx.spring_layout(g)
pos=nx.nx_agraph.graphviz_layout(g, prog='dot')
plt.figure(figsize=(12,12))
labels={}
labels[0]=r'$B_{999}$'
labels[1]=r'$B_0$'
labels[2]=r'$B_1$'
labels[3]=r'$B_2$'
labels[4]=r'$B_6$'
labels[5]=r'$B_7$'
labels[6]=r'$B_8$'
labels[7]=r'$B_3$'
labels[8]=r'$B_4$'
labels[9]=r'$B_5$'
nx.draw_networkx_edges(g,pos,
width=1,alpha=0.5,edge_color='black', arrows=True)
nx.draw_networkx_nodes(g,pos,
node_color='r',
node_size=1000,
alpha=0.8)
nx.draw_networkx_labels(g,pos,labels,font_size=16)
plt.axis('off')
# plt.figure(figsize=(8,6))
plt.savefig("graph.png") # save as png
plt.show() # display<file_sep>/tbl2txt/ls.py
squares = [[(0, 2, 4, 1, 3), (4, 1, 3, 0, 2), (3, 0, 2, 4, 1), (2, 4, 1, 3, 0), (1, 3, 0, 2, 4)],
[(0, 3, 1, 4, 2), (3, 1, 4, 2, 0), (1, 4, 2, 0, 3), (4, 2, 0, 3, 1), (2, 0, 3, 1, 4)],
[(0, 4, 3, 2, 1), (2, 1, 0, 4, 3), (4, 3, 2, 1, 0), (1, 0, 4, 3, 2), (3, 2, 1, 0, 4)],
[(0, 1, 2, 3, 4), (4, 0, 1, 2, 3), (3, 4, 0, 1, 2), (2, 3, 4, 0, 1), (1, 2, 3, 4, 0)]]
levels = [
["CZ", "UK", "US", "CZ", "UK"],
["muž", "žena", "muž", "žena", "muž"],
["student/ka", "technik", "důchodce/kyně", "student/ka", "technik"],
["svobodbný/á", "rozvedený/á", "svobodný/á", "rozvedený/á", "svobodbný/á"],
["venkov", "město", "venkov", "město", "venkov"],
["garsonka", "chata", "kolej", "garsonka", "chata"]
]
ret = ""
for row in range(len(levels)-1):
for col in range(len(levels)-1):
ret += levels[0][row] + " & "
ret += levels[1][col] + " & "
for i, square in enumerate(squares[:len(levels)-2]):
ret += levels[i+2][square[row][col]]
ret += " & " if i < len(levels) - 3 else " \\\\ \n"
print(ret)
<file_sep>/README.MD
# Software testing scripts
This repository contains few small scripts, which may be useful for generating test cases.
## Def-use paths
Given a control flow digraph (constructed from a piece of code) with some nodes designated as defs or uses, this script constructs all def-clear paths between
each du-pair. For details, see <NAME>, <NAME>, "Introduction to Software Testing" (2017).
To run, enter `du_paths/`, enter desired graph as a list of directed edges, def and use node in `du_paths.py` and run
``python3.6 du_paths.py``.
The output is in the form of
``du(start_node, end_node, variable_name) = list_of_paths``.
## Prime paths
A path between two digraph nodes is considered a **prime path** iff it is a simple path and it does not appear as a proper subpath of any other simple path. The `model.py` script in `model/` prime path coverage (a set containing all prime paths) for a graph given as a list of directed edges. For details, see <NAME>, <NAME>, "Introduction to Software Testing" (2017).
To run:
``
cd model/
python3.6 model
``.
The output is subpaths considered in the individual steps of the algorithm, the resulting paths, and LaTeX formatted paths. `!` signifies a prime path, `*` a cycle.
## Mutually orthogonal latin squares and orthogonal arrays
For every prime power p, there exists p-1 so called **mutually orthogonal latin squares**. Each latin square has the property that for each row or column no element is present more than once. For each two mutually orthogonal latin squares, it is the case that each pair of elements with the same coordinates appear exactly once.
**Orthogonal arrays** are a generalization of latin squares into a tabular form. For orthogonal array of strength s, for each s-tuple of columns, each corresponding row elements appear exactly once (or, in general, the same number of times).
`os.py` in `tbl2txt` converts a given orthogonal array and an array of factors (possible parameter values) the values of factors for tests generated by the orthogonal square.
`ls.py` does the same, but given a list of orthogonal squares.
## Alloy
[Alloy](http://alloytools.org/) is a powerful declarative model-based language and tool for software modelling and verification. It allows efficient construction of software models, subsequent constraint definition and verification of constraint satisfaction.
`alloy/` contains my Alloy solution, `langdon.als`, to a puzzle presented in `6_langdon.pdf`. To run it, please open and execute in [Alloy Analyzer](http://alloytools.org/download.html).
Moreover, `6_clanek.pdf` is my report on the mondex study, and `prezentace.pdf` is a corresponding presentation.
<file_sep>/model/model.py
import copy
def contains_repeated(new_one):
found = {}
for node in new_one:
if found.__contains__(node):
return True
else:
found[node] = 1
return False
def is_circular(arr1, arr2):
if len(arr1) != len(arr2):
return False
str1 = ' '.join(map(str, arr1[:-1]))
str2 = ' '.join(map(str, arr2[:-1]))
if len(str1) != len(str2):
return False
return str1 in str2 + ' ' + str2
edges = [(0,1),(1,2),(1,7),(2,3),(2,6),(3,4),(3,5),(4,3),(5,2),(6,7),(7,8)]
done = []
prev_exclams = [(7,9),(8,9)]
next_exclams = []
num_nodes = 9
print("STEP 1")
for e in edges+prev_exclams:
print(e)
print("\n")
for l in range(1,num_nodes-1):
print("STEP {}".format(l+1))
viable = []
for x in prev_exclams:
edges.append(x)
# Vykricniky, ktere se v danem kroku nepodari rozsirit, jsou hotove
for edge1 in edges:
for edge2 in edges:
if edge1 != edge2 and edge1[-l:] == edge2[:l]:
new_one = edge1+edge2[-1:]
if edge1[0] == edge2[-1]:
print(new_one+('*',))
done.append(new_one+('*',))
elif contains_repeated(new_one):
print(new_one[-1:]+('!',))
done.append(new_one[-1:]+('!',))
elif new_one[-1] == num_nodes:
print(new_one+('!',))
if edge1 in prev_exclams:
prev_exclams.remove(edge1)
elif edge2 in prev_exclams:
prev_exclams.remove(edge2)
next_exclams.append(new_one)
else:
print(new_one)
viable.append(new_one)
for x in prev_exclams:
done.append(x+("!",))
# print("NEXT EXCLAMS")
# for x in next_exclams:
# print(x)
prev_exclams = copy.deepcopy(next_exclams)
next_exclams.clear()
edges = copy.deepcopy(viable)
print("\n")
for d1 in done:
if d1[-1] == "*":
for d2 in done:
if d1 != d2 and is_circular(d1[:-1],d2[:-1]):
done.remove(d2)
print("RESULTS")
for i,d in enumerate(done):
print("{}: {}".format(i, d))
print("\nFOR LATEX")
for i,d in enumerate(done):
print("\item {} $\\rightarrow$ {}".format(i, ','.join(map(str,d[:-1]))))<file_sep>/tbl2txt/ls_allpairs.py
# -*- coding: utf8 -*-
import metacomm.combinatorics.all_pairs2
all_pairs = metacomm.combinatorics.all_pairs2.all_pairs2
levels = [
["CZ", "UK", "RU"],
["muz", "zena"],
["student", "produkcni", "duchodce"],
["garsonka", "<NAME>", "kolej"]
]
pairwise = all_pairs( levels )
for i, v in enumerate(pairwise):
print "%i:\t%s" % (i, str(v))<file_sep>/tbl2txt/os.py
str = \
"""
0000
0112
0221
1011
1120
1202
2022
2101
2210
"""
ret = ""
levels = [
["CZ", "SK", "RU"],
["muz", "zena", "muz"],
["student", "produkcni", "duchodce"],
["garsonka", "<NAME>", "kolej"],
]
# Pro kazdou radku v ort. ctverci
for line in iter(str.splitlines()):
# Pro kazdy charakter radku
for i, char in enumerate(line):
if i < len(levels):
# Vypis prislusnou hodnotu faktoru
ret += levels[i][int(char)]
# Kvuli vypisu do LaTexu
ret += " & " if i < len(levels) - 1 else " \\\\ "
ret += "\n"
print(ret)
|
0afd81f2123c6be94033aba7c0e67620ebd145d5
|
[
"Markdown",
"Python"
] | 9
|
Python
|
mirgee/software_verification
|
53ffebc99af1ebb91533dd480b0ff5f1e265858d
|
aa2fcd426d1631b04fad2eb50946dd7667a61c72
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Classes
{
// Create a new project, and include in it the class Person that you just created.
//Create a class "Student" and another class "Teacher", both descendants of "Person".
//The class "Student" will have a public method "GoToClasses", which will write on screen "I’m going to class."
//The class "Teacher" will have a public method "Explain", which will show on screen "Explanation begins". Also, it will have a private attribute "subject", a string.
//The class Person must have a method "SetAge (int n)" which will indicate the value of their age(eg, 20 years old).
//The student will have a public method "ShowAge" which will write on the screen "My age is: 20 years old" (or the corresponding number).
//You must create another test class called "StudentAndTeacherTest" that will contain "Main" and:
//Create a Person and make it say hello
//Create a student, set his age to 21, tell him to Greet and display his age
//Create a teacher, 30 years old, ask him to say hello and then explain.
class Person
{
int age;
public void Greet()
{
Console.WriteLine("Hi");
}
public void SetAge(int num)
{
age = num;
}
}
class Student : Person
{
public void ShowAge()
{
Console.WriteLine("My age is {age} years old");
}
}
class Teacher : Person
{
private string sub;
public void Explain()
{
Console.WriteLine("Explanation begins");
}
}
class StudentAndTeacherTest
{
static void Main()
{
bool debug = false;
Person myPerson = new Person();
myPerson.Greet();
Student myStudent = new Student();
myStudent.SetAge(21);
myStudent.Greet();
myStudent.ShowAge();
Teacher myTeacher = new Teacher();
myTeacher.SetAge(30);
myTeacher.Greet();
myTeacher.Explain();
if (debug)
Console.ReadLine();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Conditional
{
class Program
{
//Create an application that helps the accounting department create a receipt for each sale that the company makes.Zigs sell for $60 and zags sell for $90. If a customer buys more than 20 total zigs and zags then they receive a discount rate of 20%. Sales tax is 6.25%. Create a console application that asks the user how many zigs and zags they are going to purchase. Calculate the total before and after the discount rate and tax is applied (if the discount rate applies). Store each receipt in a dictionary or list with a unique number that is able to be called on by the accounting department.
static void Main(string[] args)
{
double zag = 90.00;
double markup=1.15;
double zig = 60.00;
double discountrate = .20;
double markup2 = 1.125;
double salestax = .0625;
Console.WriteLine("How many zig are you purchasing");
int numberofzigs = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("How many zags are you purchasing");
int numberofzags = Convert.ToInt32(Console.ReadLine());
double zigprice;
double zagprice;
zigprice = numberofzigs * zig;
zagprice = numberofzags * zag;
double total;
total = zagprice + zigprice;
double endtotal;
int totalnumber = numberofzigs + numberofzags;
string discountamount;
if (totalnumber < 16)
{
endtotal = total * markup;
discountamount = "15%";
}
else if (numberofzags > 10)
{
endtotal = total * markup2;
discountamount = "12.5%";
}
else if (numberofzigs > 10)
{
endtotal = total * markup2;
discountamount = "12.5%";
}
else
{
endtotal = total * markup2;
discountamount = "12.5%";
}
Console.WriteLine($"End total before tax = {endtotal}");
Console.WriteLine($"Markup = {discountamount}");
double tax = endtotal * (1 + salestax);
Console.WriteLine($"End total after tax {tax}");
Console.ReadLine();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Loops
{
class Program
{
//Create for loop that will keep prompting the user to input prices of items, add their input to an accumulator and then ask the user if they have another price to enter, and repeat the process until they say they are done(case insensitive). Once they say no, display the average of all of the prices in currency format.
static void Main(string[] args)
{
double price, average, total = 0;
string question;
int numitems = 0;
do
{
Console.WriteLine("Please enter the price of your item.");
price = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Do you want to enter another item price? Please enter 'yes' if so.");
question = Convert.ToString(Console.ReadLine());
total = total + price;
numitems++;
}
while (question.ToLower() == "yes");
average = (total / (numitems * 100));
Console.WriteLine($"After {numitems} items, your average price is {average:C}.");
Console.ReadLine();
}
}
}
|
b914ef83fdea0e5cf185b852a6c56adf2750dd1d
|
[
"C#"
] | 3
|
C#
|
nickstephens16/ParticipationProblems
|
0916ed16c6fc17c43cb3e405c89b1a5cec748ddf
|
fdff1a9ee920417c7cbf14d843136a7169b06e0c
|
refs/heads/master
|
<repo_name>djeastm/java-csci140<file_sep>/Lab15/src/Lab15.java
/**
* Lab 15
* CSCI 140L
*
* @author <NAME>
* Last Revised: 3/2/2015
*
* A bunch of for loops
*
*/
import java.util.Scanner;
public class Lab15
{
public static void main(String[] args)
{
int n = 0; // A user-entered integer
Scanner input = new Scanner(System.in);
System.out.print("Please enter an integer: ");
n = input.nextInt();
System.out.println("Part 1:");
for (int i = 1; i <= n; i++)
{
System.out.println(i);
}
System.out.println();
System.out.println("Part 2:");
for (int i = 1; i <= n; i++)
{
int intSquared = i*i;
System.out.printf("%d %d\n",i, intSquared);
}
System.out.println();
System.out.println("Part 3:");
for (int i = n; i >= 1; i--)
{
System.out.println(i);
}
System.out.println();
System.out.println("Part 5:");
int sum = 0;
for (int i = 1; i <= n; i++)
{
sum += i;
}
System.out.println(sum);
System.out.println();
System.out.println("Part 6:");
int product = 1;
for (int i = 1; i <= n; i++)
{
product *= i;
}
System.out.println(product);
System.out.println();
System.out.println("Part 7:");
System.out.printf("Please enter %d integers:\n", n);
int sum2 = 0;
for (int i = 1; i <= n; i++)
{
sum2 += input.nextInt();
}
System.out.println(sum2);
System.out.println();
System.out.println("Part 8:");
System.out.println("Please enter two integers:");
int a = input.nextInt();
int b = input.nextInt();
for (int i = a; i <= b; i++)
{
if (i % 2 != 0) {
System.out.println(i);
}
}
input.close();
}
}
<file_sep>/Prog5/src/Prog5.java
/**
* Prog5
* CSCI 140L
*
* @author <NAME>
* Last Revised: 3/6/2015
*
* Allows a manager to calculate charges for several customers.
*
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Prog5
{
public static void main(String[] args) throws FileNotFoundException
{
File inputFile = new File("prog5in.txt");
Scanner input = new Scanner(inputFile);
PrintWriter output = new PrintWriter("prog5out.txt");
double totalRevenue = 0;
while(input.hasNext())
{
final double REMOVALRATE = 150; // Per tree rate for removing
final double TRIMMINGRATE = 50; // Per hour rate for trimming
final double GRINDINGRATE = 30; // Per stump flat rate (does not include surcharge;
final double GRINDINGSURCHARGE = 2; // Surcharge for stumps with diameter greater than 12
String customerName; // Each name taken in from input file
int treeCount = 0; // Number of trees removed
double trimHours = 0; // Number of hours worked trimming
double stumpCount = 0; // Number of stumps ground.
double removalCharge = 0; // Calculated charge for removal
double trimmingCharge = 0; // Calculated charge for trimming
double grindingCharge = 0; // Calculated charge for grinding
double stumpSurcharge = 0; // Calculated surcharge for large stumps
double totalCharge = 0; // Calculated total charge
customerName = input.nextLine();
treeCount = input.nextInt();
trimHours = input.nextDouble();
input.nextLine();
double diameter = input.nextDouble();
while (diameter != -1)
{
if (diameter != -1)
{
if (diameter > 12)
{
stumpSurcharge += (diameter - 12) * GRINDINGSURCHARGE;
}
stumpCount++;
if (input.hasNextDouble())
{
diameter = input.nextDouble();
}
}
}
if (input.hasNext() )
{
input.nextLine();
}
removalCharge = treeCount * REMOVALRATE;
trimmingCharge = trimHours * TRIMMINGRATE;
grindingCharge = (stumpCount * GRINDINGRATE) + stumpSurcharge;
totalCharge = removalCharge + trimmingCharge + grindingCharge;
totalRevenue += totalCharge;
// Print to console
System.out.println("Customer: " + customerName);
System.out.printf ("Tree Removal: $%9.2f\n", removalCharge);
System.out.printf ("Tree Trimming: $%9.2f\n", trimmingCharge);
System.out.printf ("Stump Grinding: $%9.2f\n", grindingCharge);
System.out.printf ("Total: $%9.2f\n", totalCharge);
System.out.println();
// Print to file
// Using System.lineSeparator so the output text file line breaks will work
// both on *nix and Windows machines
String br = System.lineSeparator();
output.println("Customer: " + customerName);
output.printf ("Tree Removal: $%9.2f"+br, removalCharge);
output.printf ("Tree Trimming: $%9.2f"+br, trimmingCharge);
output.printf ("Stump Grinding: $%9.2f"+br, grindingCharge);
output.printf ("Total: $%9.2f"+br, totalCharge);
output.println();
}
System.out.printf ("Total Revenue: $%9.2f\n", totalRevenue);
output.printf ("Total Revenue: $%9.2f\n", totalRevenue);
input.close();
output.close();
}
}
<file_sep>/Test3/src/Test3.java
/**
* Test 3
* CSCI 140L
*
* @author <NAME>
* Last Revised: 4/27/2015
*
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test3
{
public static void main(String[] args)
{
File inputFile = new File("test3.txt");
Scanner input = new Scanner(System.in);
try {
input = new Scanner(inputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
double[] rain = new double[50];
int n = 0;
while (input.hasNext())
{
rain[n] = input.nextDouble();
n++;
}
double avg = computeAve(rain, n);
System.out.printf("Average Rainfall = %.2f\n\n", avg);
System.out.printf("%-20s%-20s\n", "Rainfall Amount", "Deviation From Average");
for (int i = 0; i < n; i++)
{
System.out.printf("%10.2f %10.2f\n", rain[i], rain[i] - avg);
}
System.out.println();
reverse_print(rain, n);
} // End main
public static double computeAve(double[] a, int n)
{
double sum = 0;
double avg = 0;
for (int i = 0; i < n; i++)
{
sum += a[i];
}
avg = sum / n;
return avg;
} // End computeAve
public static void reverse_print(double[] a, int n)
{
System.out.println("Rainfall Amounts in Reverse");
for (int i = n-1; i >= 0; i--)
{
System.out.printf("%3.1f ", a[i]);
}
} // End reverse_print
} // End class
<file_sep>/Prog2/src/Prog2.java
/**
* Program 2
* CSCI 140L
*
* @author <NAME>
* Last Revised: 2/6/2015
*
* Calculates lengths of the sides of a given triangle,
* then calculates the area and the perimeter.
*
*/
import java.util.Scanner;
public class Prog2
{
public static void main(String[] args)
{
double xA; // X value for Vertex A
double yA; // Y value for Vertex A
double xB; // X value for Vertex B
double yB; // Y value for Vertex B
double xC; // X value for Vertex C
double yC; // Y value for Vertex C
double lengthAB; // Calculated length of side AB
double lengthBC; // Calculated length of side BC
double lengthAC; // Calculated length of side AC
double s; // Calculated semiperimeter of the triangle
double area; // Calculated area of the triangle
double perimeter; // Calculated perimeter of the triangle
Scanner input = new Scanner(System.in);
System.out.print("Input the coordinates for vertex A: ");
xA = input.nextDouble();
yA = input.nextDouble();
System.out.print("Input the coordinates for vertex B: ");
xB = input.nextDouble();
yB = input.nextDouble();
System.out.print("Input the coordinates for vertex C: ");
xC = input.nextDouble();
yC = input.nextDouble();
lengthAB = Math.sqrt(Math.pow((xB-xA),2) + Math.pow((yB-yA),2));
lengthBC = Math.sqrt(Math.pow((xC-xB),2) + Math.pow((yC-yB),2));
lengthAC = Math.sqrt(Math.pow((xA-xC),2) + Math.pow((yA-yC),2));
s = 0.5*(lengthAB + lengthBC + lengthAC);
area = Math.sqrt(s*(s-lengthAB)*(s-lengthBC)*(s-lengthAC));
perimeter = lengthAB + lengthBC + lengthAC;
// Results
System.out.println("");
System.out.printf("Vertex A: %10.2f %4.2f\n", xA, yA);
System.out.printf("Vertex B: %10.2f %4.2f\n", xB, yB);
System.out.printf("Vertex C: %10.2f %4.2f\n", xC, yC);
System.out.println("");
System.out.printf("Length AB:%15.2f\n", lengthAB);
System.out.printf("Length BC:%15.2f\n", lengthBC);
System.out.printf("Length AC:%15.2f\n", lengthAC);
System.out.println("");
System.out.printf("Area: %15.2f\n", area);
System.out.printf("Perimeter:%15.2f\n", perimeter);
input.close();
}
}
<file_sep>/Test1/src/Test1.java
/**
* Test 1
* CSCI 140L
*
* @author <NAME>
* Last Revised: 2/18/2015
*
*
*/
import java.util.Scanner;
public class Test1
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
// Part 1
double radius;
double volume;
System.out.println("Input the radius of a sphere: ");
radius = input.nextDouble();
volume = ((double) 4 / 3) * Math.PI * Math.pow(radius, 3);
System.out.printf("The volume of a sphere with radius %7.3f is %7.3f.\n", radius, volume);
// Part 2
double gpa;
String status;
System.out.println("Input a GPA: ");
gpa = input.nextDouble();
if (gpa >= 3.5) {
status = "Dean's List";
} else if (gpa >= 2.0) {
status = "Good Standing";
} else {
status = "Probation";
}
System.out.println(status);
// Part 3
String sourceString;
String subString;
System.out.println("Input a string from which to take a substring: ");
sourceString = input.next();
if (sourceString.length() >= 3) {
subString = sourceString.substring(0,3);
System.out.println(subString);
} else {
System.out.println("ERROR");
}
input.close();
}
}
<file_sep>/Lab14/src/Lab14.java
/**
* Lab 14
* CSCI 140L
*
* @author <NAME> & <NAME>
* Last Revised: 2/25/2015
*
* Reads an integer and displays, using asterisks, a filled and hollow square
*
*/
import java.util.Scanner;
public class Lab14
{
public static void main(String[] args)
{
int lines = 0; // A user-entered integer that represents the number of row
Scanner input = new Scanner(System.in);
System.out.print("Please enter an integer: ");
lines = input.nextInt();
for (int i = 0; i < lines; i++)
{
for (int j = 0; j < lines; j++)
{
System.out.print ("x");
}
System.out.print (" ");
if (i == 0 || i == lines-1)
{
for (int k = 0; k < lines; k++)
{
System.out.print ("x");
}
}
else
{
System.out.print ("x");
for (int k = 0; k < lines-2; k++)
{
System.out.print (" ");
}
System.out.print ("x");
}
System.out.println();
}
input.close();
}
}
<file_sep>/Lab11/src/Lab11.java
/**
* Lab 11
* CSCI 140L
*
* @author <NAME>
* Last Revised: 2/20/2015
*
* Takes in a string from the user, then prints out various substrings
* of that source string.
*
*/
import java.util.Scanner;
public class Lab11
{
public static void main(String[] args)
{
String string; // A user-entered source string
int numLowerCase = 0; // An integer that counts the number of lowercase letters
int numVowels = 0; // An integer that counts the number of vowels
Scanner input = new Scanner(System.in);
System.out.print("Enter a string: ");
string = input.nextLine();
for (int i = 0; i < string.length(); i++)
{
char ch = string.charAt(i);
if (Character.isLowerCase(ch))
{
numLowerCase++;
}
if (ch == 'a' || ch == 'A' ||
ch == 'e' || ch == 'E' ||
ch == 'i' || ch == 'I' ||
ch == 'o' || ch == 'O' ||
ch == 'u' || ch == 'U' ||
ch == 'y' || ch == 'Y')
{
numVowels++;
}
}
System.out.println("Original line: " + string);
System.out.println("Number of lowercase letters: " + numLowerCase);
System.out.println("Number of vowels: " + numVowels);
System.out.print("Line in reverse: ");
for (int i = string.length()-1; i >= 0; i--)
{
System.out.print(string.charAt(i));
}
System.out.println("");
System.out.print("Every other character: ");
for (int i = 0; i < string.length(); i = i + 2)
{
System.out.print(string.charAt(i));
}
System.out.println();
System.out.println("Upper Case: " + string.toUpperCase());
input.close();
}
}
<file_sep>/Lab19/src/Lab19.java
/**
* Lab19
* CSCI 140L
*
* @author <NAME>
* Last Revised: 3/30/2015
*
* Stores values in an array and print them
*
*/
public class Lab19
{
public static void main(String[] args)
{
int[] alpha = new int[50];
for (int i = 0; i < 25; i++)
{
alpha[i] = i * 2;
}
for (int i = 25; i < 50; i++)
{
alpha[i] = -1;
}
for (int i = 0; i < 50; i++)
{
System.out.println(alpha[i]);
}
} // End Main
} // End class
<file_sep>/Lab16/src/Lab16.java
/**
* Lab16
* CSCI 140L
*
* @author <NAME>
* Last Revised: 3/18/2015
*
* Tests a method that returns a count of chars
*
*/
import java.util.Scanner;
public class Lab16
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Part 1 Count = "+charCount("AABBBCCC", 'B'));
System.out.println("Please enter a string:");
String s = input.nextLine();
System.out.println("Please enter a character:");
char ch = input.next().charAt(0);
System.out.println("Part 2 Count = "+charCount(s, ch));
input.close();
} // End main
/**
* Takes in a string and a character and counts the number of occurrences
* of that character in a string
*
* @param s A string to be tested
* @param ch A character to be counted
* @return Returns the number of occurrences of the character in the string
*/
public static int charCount(String s, char ch)
{
int count = 0;
for (int i = 0; i < s.length(); i++)
{
if (s.charAt(i) == ch)
count++;
}
return count;
} // End charCount
}
<file_sep>/Lab6/src/Lab6.java
import java.util.Scanner;
/**
* Lab 6
* CSCI 140L
*
* @author <NAME>
* Last Revised: 2/2/2015
*
* Prompts the user for file path information and prints it as a formatted
* file path. Also prompts the user for a telephone number and prints it as a
* formatted telephone number.
*
*/
public class Lab6 {
public static void main(String[] args) {
String driveLetter; // The letter of the drive
String path; // The file path, including backslashes
String fileName; // The name of the file
String extension; // The file extension
String partA; // Calculated formatted file path;
String inputPhoneNumber; // The phone number, ten-digits unformatted
String areaCode; // Calculated substring of phone number, first three numbers
String prefix; // Calculated substring of phone number, second three numbers
String suffix; // Calculated substring of phone number, last four numbers
String partB; // Calculated formatted phone number;
Scanner input = new Scanner(System.in);
// Part A
System.out.print("Please enter the drive letter: ");
driveLetter = input.next();
System.out.print("Please enter the path: ");
path = input.next();
System.out.print("Please enter the file name: ");
fileName = input.next();
System.out.print("Please enter the extension: ");
extension = input.next();
partA = driveLetter+":"+path+"\\"+fileName+"."+extension;
// Part B
System.out.print("Please enter a ten-digit phone number: ");
inputPhoneNumber = input.next();
areaCode = inputPhoneNumber.substring(0,3);
prefix = inputPhoneNumber.substring(3,6);
suffix = inputPhoneNumber.substring(6,10);
partB = "("+areaCode+") "+prefix+"-"+suffix;
// Results
System.out.println("Results of Part A: " + partA);
System.out.println("Results of Part B: " + partB);
input.close();
}
}
|
23bd0d916ab2db376bddfc745d439008be48ff7c
|
[
"Java"
] | 10
|
Java
|
djeastm/java-csci140
|
ba890272266c0dc8e2047cf5f7167ba1651d7e51
|
36e32c244369036db1abe324aa00a69808ba8cca
|
refs/heads/master
|
<repo_name>ejhigson/texunc<file_sep>/README.md
texunc
======
Converts values and numerical uncertainties into strings with the error on the final digit in brackets. For some examples see ``demo.ipynb``.
<file_sep>/texunc/__init__.py
#!/usr/bin/env python
"""
Convert values and numerical uncertainties into strings of format
1.234(5) \\cdot 10^{-6}
where number in brackets is error on the final digit, and apply this to pandas
dataframes.
"""
from texunc.uncertainty_formatting import latex_form
from texunc.dataframe_funcs import latex_format_df, print_latex_df
<file_sep>/setup.py
#!/usr/bin/env python
"""texunc setup."""
import setuptools
setuptools.setup(name='texunc',
version='0.0.0',
author='<NAME>',
url='https://github.com/ejhigson/texunc',
install_requires=['numpy'],
packages=['texunc'])
<file_sep>/texunc/dataframe_funcs.py
#!/usr/bin/env python
"""
Functions for applying uncertainty formatting to pandas DataFrames.
"""
from texunc.uncertainty_formatting import latex_form
__all__ = ['latex_format_df', 'print_latex_df']
def latex_format_df(df, **kwargs):
"""
Format a pandas multiindex DataFrame with index 'result type' containing
'value' and 'uncertainty' using latex_form.
"""
assert 'result type' in df.index.names
# Save the order to make sure we don't change it
order = df.index.droplevel('result type').unique()
latex_df = (df.stack().unstack(level='result type')
.apply(_pandas_latex_form_apply, axis=1, **kwargs).unstack())
return latex_df.reindex(order)
def print_latex_df(df, str_map=None, caption_above=True, **kwargs):
"""
Formats df and prints it out (can copy paste into tex file).
"""
star_table = kwargs.pop('star_table', False)
caption = kwargs.pop('caption', 'Caption here.')
label = kwargs.pop('label', 'tab:tbc')
# Get latex df as string
df = latex_format_df(df, **kwargs)
# stop to_latex adding row for index names
df.index.names = [None] * len(df.index.names)
df_str = df.to_latex(escape=False)
# format all the strings we need
if str_map is not None:
for key, value in str_map.items():
df_str = df_str.replace(key, value)
table_str = r'table'
if star_table:
table_str += r'*'
caption_str = r'\caption{' + caption + r'}\label{' + label + r'}'
# do the printing
# ---------------
print() # print a new line
print(r'\begin{' + table_str + '}')
print(r'\centering')
if caption_above:
print(caption_str)
print(df_str + r'\end{' + table_str + '}')
else:
print(df_str + caption_str)
print(r'\end{' + table_str + '}')
return df
# Helper functions
# ----------------
def _pandas_latex_form_apply(series, **kwargs):
"""
Helper function for applying latex_form to pandas multiindex. This can be
applied to each row and column except 'result type' to get the value and
uncertainties as a string using latex_form. Works with some missing
uncertainties.
Series must be length 1 with index.values=['value'] or length 2 with
index.values=['value', 'uncertainty'] (in any order). If it does not
contain an uncertainty then None is used.
Parameters
----------
series: pandas Series
kwargs: dict
Keyword args for latex_form.
Returns
-------
str_out: string
See latex_form docstring for more details.
"""
assert series.shape == (1,) or series.shape == (2,)
if series.shape == (1,):
assert series.index.values[0] == 'value'
str_out = latex_form(series.loc['value'], None, **kwargs)
if series.shape == (2,):
inds = sorted(series.index.values)
assert inds[0] == 'uncertainty' and inds[1] == 'value', (
str(series.index.values))
str_out = latex_form(series.loc['value'], series.loc['uncertainty'],
**kwargs)
return str_out
<file_sep>/texunc/uncertainty_formatting.py
#!/usr/bin/env python
"""
Convert values and numerical uncertainties into strings of format
1.234(5) \\cdot 10^{-6}
where number in brackets is error on the final digit.
"""
import numpy as np
__all__ = ['latex_form']
def latex_form(value_in, error_in, **kwargs):
"""
Convert value and error to form
1.234(5) \\cdot 10^{-6}
where number in brackets is error on the final digit.
"""
max_power = kwargs.pop('max_power', 4)
min_power = kwargs.pop('min_power', -max_power)
min_dp = kwargs.pop('min_dp', 1)
min_dp_no_error = kwargs.pop('min_dp_no_error', min_dp)
zero_dp_ints = kwargs.pop('zero_dp_ints', True)
if value_in is None or np.isnan(value_in):
return str(value_in) + '(' + str(error_in) + ')'
# Work out power and adjust error and values
power = _get_power(value_in, max_power, min_power)
value = value_in / (10 ** power)
if error_in is None or np.isnan(error_in):
error = error_in
if power == 0 and value_in == np.rint(value_in) and zero_dp_ints:
min_dp = 0
else:
min_dp = min_dp_no_error
else:
error = error_in / (10 ** power)
# Work out decimal places
dp = int(_get_dp(error, min_dp))
# make output
output = '{:,.{prec}f}'.format(value, prec=dp)
if (error is not None) and ~np.isnan(error):
error *= (10 ** dp)
output += '({:.{prec}f})'.format(error, prec=0)
if power != 0:
output = r'$' + output + r'\cdot 10^{' + str(power) + '}$'
return output
# Helper functions
# ----------------
def _get_power(value_in, max_power, min_power):
"""
Find power to use in standard form (if any).
"""
if value_in == 0 or value_in == np.inf:
return 0
else:
power = int(np.floor(np.log10(abs(value_in))))
if max_power >= power >= min_power:
return 0
else:
return power
def _get_dp(error, dp_min):
"""
Find how many decimal places should be shown given the size of the
numberical uncertainty.
This is the number of decimal places which is needed to have the
error on the final digit (rounded to 1 sigificant figure) in the range 1 to
9. If this number is less than dp_min, dp_min is used.
Parameters
----------
error: float
dp_min: int, None or NaN
Returns
-------
dp_to_use: int
"""
if error is None or np.isnan(error) or error == 0:
return dp_min
if error >= 1:
return dp_min
# have a float error that is less than 1 in magnitude:
# find dp needed for error to be >= to 1
dp_given_error = int(np.ceil(abs(np.log10(error))))
# Reduce dp by 1 when the error in brackets rounds up to 10 so it is
# instead shown as 1
if np.rint(error * (10 ** dp_given_error)) == 10:
dp_given_error -= 1
return max(dp_min, dp_given_error)
|
48d330d2178d1f066faef7edf6d31ae43e1ca1d7
|
[
"Markdown",
"Python"
] | 5
|
Markdown
|
ejhigson/texunc
|
e27172164d11a07f3d7f42d15d80191fd5f6d839
|
3c17be02dc3706e2f08e736e4b972813e1d5b9a1
|
refs/heads/main
|
<file_sep>import Head from "next/head";
import { blogPosts } from "../lib/data";
import Link from "next/link";
import { format, parseISO } from "date-fns";
export default function Home() {
return (
<div>
<Head>
<title>Home</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<div className="space-y-4">
{blogPosts.map((item) => (
<BlogListItem key={item.slug} {...item} />
))}
</div>
</div>
);
}
function BlogListItem({ slug, title, date, content }) {
const sanitizeDate = format(parseISO(date), "MMMM do, uuu");
return (
<div
className="border border-grey-100 shadow hover:shadow-md
hover:border-black-300 rounded-md p-4 transition duration-200 ease-in"
>
<div>
<div>
<Link href={`/blog/${slug}`}>
<a className="font-bold">{title}</a>
</Link>
</div>
<div className="text-gray-600 text-xs">{sanitizeDate}</div>
<div>{content}</div>
</div>
</div>
);
}
<file_sep>## NextJs with TailwindCSS
### Blog
|
e032015201ae6f78f16a23131a24d032fa3d8ac7
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
AzriZzz/nextjs-with-tailwindcss
|
02cd3b54a3d3adbb232a7fb5b12a52fe8e536800
|
a33fb092e9be7e09cef730133441bd4651a1a68c
|
refs/heads/master
|
<file_sep>package com.hui305.aspect;
import com.hui305.annotation.BussAnnotation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* Created by hui_stone on 2020/5/26 0026.
*/
@Aspect
@Component
@Order(1)
public class LoginAspect {
@Pointcut("execution(public * com.hui305..*.addUser(..))")
public void aApplogic() {
}
@Pointcut("execution(public * com.hui305..*.addOne(..))")
public void joinPointForAddOne() {
}
@Around(value = "aApplogic() && @annotation(annotation) &&args(object,..)", argNames = "annotation,object")
public Object interceptorApplogic(ProceedingJoinPoint pj,
BussAnnotation annotation, Object object) throws Throwable {
System.out.println("moduleName:" + annotation.moduleName());
System.out.println("option:" + annotation.option());
pj.proceed();
System.out.println(pj.getSignature().getName());
for(Object obj : pj.getArgs()){
System.out.println(obj.toString());
}
return object;
}
}<file_sep>package com.hui305.mapper;
import com.hui305.domain.Order;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* Created by hui_stone on 2018/5/14 0014.
*/
public interface OrderMapper {
// @Insert("INSERT INTO orders(order_no,order_name,amount,add_time) "
// + "VALUES(#{orderNo}, #{orderName}, #{amount}, #{addTime})")
void addOrder(Order order);
// @Delete("DELETE FROM orders WHERE id=#{id}")
void delOrder(Integer id);
// @Update("UPDATE orders SET order_name=#{orderName} WHERE id=#{id}")
// void updOrder(Order order);
// @Update("UPDATE orders SET order_name = #{orderName} WHERE order_no =#{orderNo}")
void updateOrder(Order order);
// @Select("SELECT * FROM orders")
// @Results({
// @Result(property = "orderNo", column = "order_no"),
// @Result(property = "orderName", column = "order_name"),
// @Result(property = "addTime", column = "add_time"),
// })
List<Order> queryOrders();
// @Select("SELECT * FROM orders WHERE order_no=#{orderNo}")
// @Results({
// @Result(property = "orderNo", column = "order_no"),
// @Result(property = "orderName", column = "order_name"),
// @Result(property = "addTime", column = "add_time"),
// })
Order queryOrderByNo(String orderNo);
}
<file_sep>package com.hui305.Controller;
import com.hui305.domain.Order;
import com.hui305.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.List;
/**
* Created by hui_stone on 2018/5/14 0014.
*/
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private OrderMapper orderMapper;
@RequestMapping("/add")
public String addOrder(Order order){
order.setAddTime(new Date());
orderMapper.addOrder(order);
return "add success!";
}
@RequestMapping("/update")
public String updOrder(Order order){
orderMapper.updateOrder(order);
return "update success!";
}
@RequestMapping("/query")
public Order queryOrder(String orderNo){
return orderMapper.queryOrderByNo(orderNo);
}
@RequestMapping("/queryAll")
public List<Order> queryAll(){
return orderMapper.queryOrders();
}
@RequestMapping("/delete")
public String delOrder(Integer id){
orderMapper.delOrder(id);
return "delete success!";
}
}
<file_sep>package com.hui305.util;
import java.util.Arrays;
import java.util.Random;
/**
* Created by hui_stone on 2019/1/1 0001.
*/
public class RandomUtil {
private static Random random = new Random();
public static int[] getRandomIntArrayInRange(int min,int max){
return random.ints(min,(max+1)).limit(10).toArray();
}
public static int getRandomIntInRange(int min,int max){
return random.ints(min,(max+1)).limit(1).findFirst().getAsInt();
}
public static void main(String[] args) {
int[] array = RandomUtil.getRandomIntArrayInRange(100,200);
Arrays.stream(array).forEach(System.out::println);
int value = getRandomIntInRange(100,200);
System.out.println("=============> "+ value);
}
}
<file_sep>package com.hui305.domain;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;
import java.util.Date;
/**
* Created by hui_stone on 2018/5/14 0014.
*/
@Getter
@Setter
public class Order {
private Integer id;
private String orderNo;
private String orderName;
private BigDecimal amount;
private Date addTime;
public Order(){}
public Order(String orderNo, String orderName, BigDecimal amount){
this.orderNo = orderNo;
this.orderName = orderName;
this.amount = amount;
this.addTime = new Date();
}
}
<file_sep>package com.hui305;
import com.github.pagehelper.PageHelper;
import com.hui305.domain.Order;
import com.hui305.mapper.OrderMapper;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Springboot2MybatisAnnotationApplicationTests {
@Test
public void contextLoads() {
}
@Autowired
private OrderMapper orderMapper;
@Test
public void test1_Add() {
orderMapper.addOrder(new Order("100004", "nokia 3000 ", new BigDecimal("2000")));
}
@Test
public void test_update(){
Order order = new Order();
order.setOrderName("iphone8");
order.setOrderNo("100002");
orderMapper.updateOrder(order);
}
@Test
public void test2_Query() {
Order order = orderMapper.queryOrderByNo("100001");
System.out.println("ordername = : "+order.getOrderName());
Assert.assertNotNull(order);
}
@Test
public void test_QueryList(){
PageHelper.startPage(1,5);
List<Order> orders = orderMapper.queryOrders();
System.out.println("==============> list size:"+orders.size()+"===============");
orders.stream().forEach((o)-> System.out.println(o.getOrderName()));
// List<Order> orderList2 = orders.stream().filter(s->s.getOrderNo().equals("100001")).collect(Collectors.toList());
// System.out.println(orderList2.get(0).getOrderName());
Assert.assertNotNull(orders);
}
}
<file_sep>package com.example.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* TODO
*
* @author bobstone
* @version 1.0
* @date 2022/8/5 18:52
*/
@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class ShardingApplication {
public static void main(String[] args) {
SpringApplication.run(ShardingApplication.class,args);
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.hui305</groupId>
<artifactId>spring-practice</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.hui305</groupId>
<artifactId>springboot2-mybatis-annotation</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot2-mybatis-annotation</name>
<description>Demo project for Spring Boot</description>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--分页插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.3</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
<file_sep>package com.hui305;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
/**
* Created by hui_stone on 2020/5/26 0026.
*/
@SpringBootApplication(exclude= DataSourceAutoConfiguration.class)
public class SpringbootApp {
public static void main(String[] args) {
SpringApplication.run(SpringbootApp.class, args);
}
}
<file_sep>CQRS(Command-Query Responsibility Segregation)
是一种读写分离的模式,从字面意思上理解
Command是命令的意思,其代表写入操作;
Query是查询的意思,代表的查询操作,
这种模式的主要思想是将数据的写入操作和查询操作分开。
为了保证读写操作的数据一致性,需要在两个数据库之间进行数据同步。
Event Sourcing也叫事件溯源,是<NAME>提出的一种架构模式。
其设计思想是系统中的业务都由事件驱动来完成。系统中记录的是一个个事件,由这些事件体现信息的状态。
业务数据可以是事件产生的视图,不一定要保存到数据库中。
|
727732886d58db6a8aaea21c31563e879fccdc1c
|
[
"Markdown",
"Java",
"Maven POM"
] | 10
|
Java
|
hui305/spring_practice
|
dffc9e2bcb59b28a034f317bcd6602fa53b8d337
|
5b2723a8c7367e90c30e898621f57cb612cdd3d8
|
refs/heads/master
|
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>tech.mangosoft</groupId>
<artifactId>flightscanner</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>flightscanner</name>
<description>Scan flights and analyse the data</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<start-class>tech.mangosoft.flightscanner.Application</start-class>
</properties>
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>3.11.0</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-remote-driver</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>com.github.detro</groupId>
<artifactId>ghostdriver</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>io.appium</groupId>
<artifactId>java-client</artifactId>
<version>5.0.0-BETA6</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
<mainClass>${start-class}</mainClass>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>tech.mangosoft.flightscanner.Application</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>assemble-all</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
<file_sep># FlightScanner
Spring Boot Enabled Selenium Based Scrapper
<file_sep>package tech.mangosoft.flightscanner;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
@Component
@Scope("singleton")
public class SeleniumUtils {
private static final Logger log = LoggerFactory.getLogger(Application.class);
@Autowired
private WebDriver driver;
public SeleniumUtils() {
}
public void randomSleep(int sleep) throws InterruptedException {
Thread.sleep(ThreadLocalRandom.current().nextLong(500L*sleep, 1000L*sleep));
}
public List<WebElement> fluentWait(final By locator){
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(10, TimeUnit.SECONDS)
.pollingEvery(3, TimeUnit.SECONDS)
.ignoring(org.openqa.selenium.NoSuchElementException.class);
List<WebElement> foo = wait.until(
new Function<WebDriver, List<WebElement>>() {
public List<WebElement> apply(WebDriver driver) {
return driver.findElements(locator);
}
}
);
return foo;
}
public void mouseMoveToElement(WebElement element){
Actions builder = new Actions(driver);
builder.moveToElement(element).build().perform();
}
public WebElement ensureTextIsTyped(WebElement element, String text) throws InterruptedException {
StringBuffer sb = new StringBuffer();
for(int i=0; i<text.length(); i++){
sb.append(text.charAt(i));
while (! element.getAttribute("value").equals(sb.toString())){
element.clear();
element.sendKeys(sb.toString() );
randomSleep(1);
}
}
return element;
}
public WebElement searchGoogle(String searchString) throws InterruptedException {
driver.get("http://www.google.com");
WebElement element = driver.findElement(By.name("q"));
element.sendKeys(searchString + "\n"); // send also a "\n"
//element.submit();
randomSleep(3);
// wait until the google page shows the result
WebElement dynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("resultStats")));
List<WebElement> findElements = driver.findElements(By.xpath("//*[@id='rso']//h3/a"));
log.debug("Searching " + searchString + ". Results: " + findElements.stream().map((x)->{return x.getAttribute("href");})
.collect(Collectors.joining(", ")));
// this are all the links you like to visit
for (WebElement webElement : findElements)
{
String href = webElement.getAttribute("href");
if (href.indexOf("www." + searchString) >-1) {
//click
log.info("Found corect link at google: " + href + ". Clicking..." );
webElement.click();
randomSleep(5);
return webElement;
}
}
log.error("Can't find searched website " + searchString);
throw new RuntimeException("Can't find searched website " + searchString);
}
}
|
b6b633b4ce5264efc92acf74bc02f25de6e092ba
|
[
"Markdown",
"Java",
"Maven POM"
] | 3
|
Maven POM
|
Mangosoft-team/FlightScanner
|
79c356c2b6e29d6bf1cf92262ebe950a9ccbfd28
|
c8264be6af867623fd1abc954e2065a523ca03f1
|
refs/heads/master
|
<repo_name>michaelsbradleyjr/traits.js.git<file_sep>/test/traits.test.js
;(function (definition) {
// Wrapper adapted from Q:
// https://github.com/kriskowal/q/blob/master/q.js
// Turn off strict mode for this function
/* jshint strict: false */
// This file will function properly as a <script> tag, or a module using
// CommonJS and NodeJS or RequireJS module formats.
// CommonJS
if (typeof exports == "object") {
var chai = require("chai"),
lodash = require("lodash"),
traits = require("../");
definition(chai, lodash, traits);
}
// RequireJS
else if (typeof define == "function" && define.amd) {
require([
"../support/chai.js",
"../support/lodash.min.js",
"../traits.min.js"
], function (chai, lodash, traits) {
definition(chai, lodash, traits);
mocha.run();
});
}
// <script>
else {
// chai library must be already loaded in the global scope and available
// as `chai`
function getGlobal(name) {
return (typeof global != "undefined" && global[name] || window[name]);
}
definition( getGlobal("chai"), getGlobal("_"), getGlobal("traits") );
}
}(function (chai, lodash, traits) {
"use strict";
var undefined = void 0;
var expect = chai.expect,
Trait = traits.Trait;
function accessorP(get, set) {
return {
get: get,
set: set,
enumerable: true
};
}
function conflictP(name) {
var conflict = function () {
throw new Error("Conflicting property: " + name);
};
return {
get: conflict,
set: conflict,
enumerable: false,
conflict: true
};
}
function dataP(value) {
return {
value: value,
enumerable: true
};
}
function identical(name, x, y, title) {
function check(b, title) {
it(title, function () {
expect(b).to.be.ok;
});
return b;
}
title = title + ": " + name + ".value " + x + " equals " + y;
if (x === y) {
// 0 === -0, but they are not identical
return check(x !== 0 || 1/x === 1/y, title);
} else {
return check(lodash.isNaN(x) && lodash.isNaN(y), title);
}
}
function isSameDesc(name, desc1, desc2, title) {
// for conflicting properties, don't compare values because the
// conflicting props are never equal
function cmp(v1, v2, title) {
it(title, function () {
expect(v1).to.equal(v2);
});
return v1 === v2;
}
if (desc1.conflict && desc2.conflict) {
return true;
} else {
return ( cmp(desc1.get, desc2.get, title + ": " + name + ".get")
&& cmp(desc1.set, desc2.set, title + ": " + name + ".set")
&& identical(name, desc1.value, desc2.value, title)
&& cmp(desc1.enumerable, desc2.enumerable, title + ": " + name + ".enumerable")
&& cmp(desc1.required, desc2.required, title + ": " + name + ".required")
&& cmp(desc1.conflict, desc2.conflict, title + ": " + name + ".conflict") );
}
}
function methodP(fun) {
return {
value: fun,
method: true,
enumerable: true
};
}
function requiredP() {
return {
value: undefined,
required: true,
enumerable: false
};
}
function testEqv(obj1, obj2, title) {
describe(title, function () {
var names1 = Object.getOwnPropertyNames(obj1),
names2 = Object.getOwnPropertyNames(obj2),
name;
it(title + ": compared objects declare same amount of properties", function () {
expect(names1.length).to.equal(names2.length);
});
for (var i = 0; i < names1.length; i++) {
name = names1[i];
it("compared object contains " + name, function () {
expect( obj2[name] ).to.not.be.undefined;
});
describe(null, function () {
var isSame = isSameDesc(name, obj1[name], obj2[name], title);
it("same descriptions: " + obj1[name] + " versus: " + obj2[name], function () {
expect(isSame).to.be.ok;
});
});
}
});
}
function testMethod() {}
describe("traits.js", function () {
describe("Trait.eqv", function () {
var T1 = Trait({ a: 0, b:Trait.required, c: testMethod }),
T2 = Trait({ b: Trait.required, a: 0, c: testMethod }),
T3 = Trait({ a: 0, b:Trait.required, c: testMethod, d: "foo" }),
T4 = Trait({ a: 0, b:Trait.required, d: "foo" });
it("eqv is reflexive", function () {
expect( Trait.eqv( T1, T1 ) ).to.be.ok;
});
describe("eqv is symmetric", function () {
it("T1 eqv T2", function () {
expect( Trait.eqv( T1, T2 ) ).to.be.ok;
});
it("T2 eqv T1", function () {
expect( Trait.eqv( T2, T1 ) ).to.be.ok;
});
});
describe("should determine trait inequality", function () {
it("T1 ! eqv T3", function () {
expect( Trait.eqv( T1, T3 ) ).to.not.be.ok;
});
it("T1 ! eqv T4", function () {
expect( Trait.eqv( T2, T4 ) ).to.not.be.ok;
});
});
});
describe("Trait construction, composition", function () {
testEqv(
Trait({}),
{},
"empty trait"
);
testEqv(
Trait({ a: 0,
b: testMethod }),
{ a: dataP(0),
b: methodP(testMethod) },
"simple trait"
);
testEqv(
Trait({ a: Trait.required,
b: 1 }),
{ a: requiredP(),
b: dataP(1) },
"simple trait with required prop"
);
testEqv(
Trait({ a: 0, b: 1, c: Trait.required }),
Trait({ b: 1, c: Trait.required, a: 0}),
"ordering of trait properties is irrelevant"
);
describe(null, function () {
var record = eval("({get a() {}, set a(v) {} })");
var get = Object.getOwnPropertyDescriptor(record,"a").get;
var set = Object.getOwnPropertyDescriptor(record,"a").set;
testEqv(
Trait(record),
{ a: accessorP(get,set) },
"trait with accessor property"
);
});
testEqv(Trait.compose(
Trait({ a: 0,
b: 1 }),
Trait({ c: 2,
d: testMethod })),
{ a: dataP(0),
b: dataP(1),
c: dataP(2),
d: methodP(testMethod) },
"simple composition");
testEqv(Trait.compose(
Trait({ a: 0,
b: 1 }),
Trait({ a: 2,
c: testMethod })),
{ a: conflictP("a"),
b: dataP(1),
c: methodP(testMethod) },
"composition with conflict");
testEqv(Trait.compose(
Trait({ a: 0,
b: 1 }),
Trait({ a: 0,
c: testMethod })),
{ a: dataP(0),
b: dataP(1),
c: methodP(testMethod) },
"composition of identical props does not cause conflict");
testEqv(Trait.compose(
Trait({ a: Trait.required,
b: 1 }),
Trait({ a: Trait.required,
c: testMethod })),
{ a: requiredP(),
b: dataP(1),
c: methodP(testMethod) },
"composition with identical required props");
testEqv(Trait.compose(
Trait({ a: Trait.required,
b: 1 }),
Trait({ a: testMethod })),
{ a: methodP(testMethod),
b: dataP(1) },
"composition satisfying a required prop");
testEqv(Trait.compose(
Trait.compose(Trait({ a: 1 }), Trait({ a: 2 })),
Trait({ b: 0 })),
{ a: conflictP("a"),
b: dataP(0) },
"compose is neutral wrt conflicts");
testEqv(Trait.compose(
Trait.compose(Trait({ a: 1 }), Trait({ a: 2 })),
Trait({ a: Trait.required })),
{ a: conflictP("a") },
"conflicting prop overrides required prop");
testEqv(Trait.compose(
Trait({ a: 0, b: 1 }),
Trait({ c: 2, d: testMethod })),
Trait.compose(
Trait({ c: 2, d: testMethod}),
Trait({ a: 0, b: 1 })),
"compose is commutative");
testEqv(Trait.compose(
Trait({ a: 0, b: 1, c: 3, e: Trait.required }),
Trait({ c: 2, d: testMethod })),
Trait.compose(
Trait({ c: 2, d: testMethod}),
Trait({ a: 0, b: 1, c: 3, e: Trait.required })),
"compose is commutative, also for required/conflicting props");
testEqv(Trait.compose(
Trait({ a: 0, b: 1, c: 3, d: Trait.required }),
Trait.compose(
Trait({ c: 3, d: Trait.required }),
Trait({ c: 2, d: testMethod, e: "foo" }))),
Trait.compose(
Trait.compose(
Trait({ a: 0, b: 1, c: 3, d: Trait.required }),
Trait({ c: 3, d: Trait.required })),
Trait({ c: 2, d: testMethod, e: "foo" })),
"compose is associative");
testEqv(Trait.compose(
Trait.compose(Trait({ b: 2 }), Trait({ a: 1 })),
Trait.compose(Trait({ c: 3 }), Trait({ a: 1 })),
Trait({ d: 4 })),
{ a: dataP(1),
b: dataP(2),
c: dataP(3),
d: dataP(4) },
"diamond import of same prop does not generate conflict");
testEqv(Trait.resolve({},
Trait({ a: 1, b: Trait.required, c: testMethod })),
{ a: dataP(1),
b: requiredP(),
c: methodP(testMethod) },
"resolve with empty resolutions has no effect");
testEqv(Trait.resolve({ a: "A", c: "C" },
Trait({ a: 1, b: Trait.required, c: testMethod })),
{ A: dataP(1),
b: requiredP(),
C: methodP(testMethod),
a: requiredP(),
c: requiredP() },
"resolve: renaming");
testEqv(Trait.resolve({ a: "b" },
Trait({ a: 1, b: 2 })),
{ b: conflictP("b"),
a: requiredP() },
"resolve: renaming to conflicting name causes conflict, ordering 1");
testEqv(Trait.resolve({ a: "b" },
Trait({ b: 2, a: 1 })),
{ b: conflictP("b"),
a: requiredP() },
"resolve: renaming to conflicting name causes conflict, ordering 2");
testEqv(Trait.resolve({ a: undefined },
Trait({ a: 1, b: 2 })),
{ a: requiredP(),
b: dataP(2) },
"resolve: simple exclusion");
testEqv(Trait.resolve({ a: undefined, b: undefined },
Trait({ a: 1, b: 2 })),
{ a: requiredP(),
b: requiredP() },
"resolve: exclusion to \"empty\" trait");
testEqv(Trait.resolve({ a: undefined, b: "c" },
Trait({ a: 1, b: 2 })),
{ a: requiredP(),
c: dataP(2),
b: requiredP() },
"resolve: exclusion and renaming of disjoint props");
testEqv(Trait.resolve({ a: undefined, b: "a" },
Trait({ a: 1, b: 2 })),
{ a: dataP(2),
b: requiredP() },
"resolve: exclusion and renaming of overlapping props");
testEqv(Trait.resolve({ a: "c", b: "c" },
Trait({ a: 1, b: 2 })),
{ c: conflictP("c"),
a: requiredP(),
b: requiredP() },
"resolve: renaming to a common alias causes conflict");
testEqv(Trait.resolve({ b: "a" },
Trait({ a: Trait.required, b: 2 })),
{ a: dataP(2),
b: requiredP() },
"resolve: renaming overrides required target");
testEqv(Trait.resolve({ b: "a" },
Trait({ a: 2, b: Trait.required })),
{ a: dataP(2),
b: requiredP() },
"resolve: renaming required properties has no effect");
testEqv(Trait.resolve({ a: "c", d: "c" },
Trait({ a: 1, b: 2 })),
{ c: dataP(1),
b: dataP(2),
a: requiredP() },
"resolve: renaming of non-existent props has no effect");
testEqv(Trait.resolve({ b: undefined },
Trait({ a: 1 })),
{ a: dataP(1) },
"resolve: exclusion of non-existent props has no effect");
testEqv(Trait.resolve({ a: "c", b: undefined },
Trait({ a: Trait.required, b: Trait.required, c:"foo", d:1 })),
{ a: requiredP(),
b: requiredP(),
c: dataP("foo"),
d: dataP(1) },
"resolve is neutral w.r.t. required properties");
testEqv(Trait.resolve({a: "b", b: "a"},
Trait({ a: 1, b: 2 })),
{ a: dataP(2),
b: dataP(1) },
"resolve supports swapping of property names, ordering 1");
testEqv(Trait.resolve({b: "a", a: "b"},
Trait({ a: 1, b: 2 })),
{ a: dataP(2),
b: dataP(1) },
"resolve supports swapping of property names, ordering 2");
testEqv(Trait.resolve({b: "a", a: "b"},
Trait({ b: 2, a: 1 })),
{ a: dataP(2),
b: dataP(1) },
"resolve supports swapping of property names, ordering 3");
testEqv(Trait.resolve({a: "b", b: "a"},
Trait({ b: 2, a: 1 })),
{ a: dataP(2),
b: dataP(1) },
"resolve supports swapping of property names, ordering 4");
testEqv(Trait.override(
Trait({a: 1, b: 2 }),
Trait({c: 3, d: testMethod })),
{ a: dataP(1),
b: dataP(2),
c: dataP(3),
d: methodP(testMethod) },
"override of mutually exclusive traits");
testEqv(Trait.override(
Trait({a: 1, b: 2 }),
Trait({c: 3, d: testMethod })),
Trait.compose(
Trait({d: testMethod, c: 3 }),
Trait({b: 2, a: 1 })),
"override of mutually exclusive traits is compose");
testEqv(Trait.override(
Trait({a: 1, b: 2 }),
Trait({a: 3, c: testMethod })),
{ a: dataP(1),
b: dataP(2),
c: methodP(testMethod) },
"override of overlapping traits");
testEqv(Trait.override(
Trait({a: 1, b: 2 }),
Trait({b: 4, c: 3 }),
Trait({a: 3, c: testMethod, d: 5 })),
{ a: dataP(1),
b: dataP(2),
c: dataP(3),
d: dataP(5) },
"three-way override of overlapping traits");
testEqv(Trait.override(
Trait({a: Trait.required, b: 2 }),
Trait({a: 1, c: testMethod })),
{ a: dataP(1),
b: dataP(2),
c: methodP(testMethod) },
"override replaces required properties");
describe("override is not commutative", function () {
it("override result depends on argument ordering", function () {
expect(
Trait.eqv(
Trait.override(
Trait({a: 1, b: 2}),
Trait({a: 3, c: 4})),
Trait.override(
Trait({a: 3, c: 4}),
Trait({a: 1, b: 2}))
)
).to.not.be.ok;
});
});
testEqv(Trait.override(
Trait.override(
Trait({a: 1, b: 2}),
Trait({a: 3, c: 4, d: 5})),
Trait({a: 6, c: 7, e: 8})),
Trait.override(
Trait({a: 1, b: 2}),
Trait.override(
Trait({a: 3, c: 4, d: 5}),
Trait({a: 6, c: 7, e: 8}))),
"override is associative");
});
describe("Traite.create", function () {
describe("creation", function () {
var o1 = Trait.create(
Object.prototype,
Trait({ a: 1, b: function () { return this.a; } })
);
it("o1 prototype", function () {
expect(Object.prototype).to.equal(Object.getPrototypeOf(o1));
});
it("o1.a", function () {
expect(1).to.equal(o1.a);
});
it("o1.b()", function () {
expect(1).to.equal( o1.b() );
});
it("Object.keys(o1).length === 2", function () {
expect(2).to.equal( Object.getOwnPropertyNames(o1).length );
});
});
describe("creation with prototype", function () {
var o2 = Trait.create(
Array.prototype, Trait({})
);
it("o2 prototype", function () {
expect(Array.prototype).to.equal( Object.getPrototypeOf(o2) );
});
});
describe("exception for incomplete required properties", function () {
function create() {
Trait.create(
Object.prototype,
Trait({ foo: Trait.required })
);
}
it("required prop error", function () {
expect(create).to.throw("Missing required property: foo");
});
});
describe("exception for unresolved conflicts", function () {
function create() {
Trait.create(
Object.prototype,
Trait.compose(Trait({ a: 0 }), Trait({ a: 1 }))
);
}
it("conflicting prop error", function () {
expect(create).to.throw("Remaining conflicting property: a");
});
});
describe("creates frozen objects", function () {
var o3 = Trait.create(Object.prototype, Trait({ m: function() { return this; } }));
it("closed create freezes object", function () {
expect( Object.isFrozen(o3) ).to.be.ok;
});
it("this refers to composite object", function () {
expect(o3).to.equal( o3.m() );
});
it("this bound to composite object", function () {
expect(o3).to.equal( o3.m.call({}) );
});
});
describe("Object.create", function () {
describe("required props are present but undefined", function () {
var o4 = Object.create(
Object.prototype,
Trait({ foo: Trait.required })
);
it("required property present", function () {
expect("foo" in o4).to.be.ok;
});
it("required property undefined", function () {
expect(o4.foo).to.not.be.ok;
});
});
describe("conflicting props are present", function () {
var o5 = Object.create(
Object.prototype,
Trait.compose(Trait({ a: 0 }), Trait({ a: 1 }))
);
it("conflicting property present", function () {
expect("a" in o5).to.be.ok;
});
function tripConflict() {
(o5.a, o5.a()); // accessor or data prop
}
it("conflicting prop access error", function () {
expect(tripConflict).to.throw("Conflicting property: a");
});
});
describe("Object.create creates unfrozen objects", function () {
var o6 = Object.create(
Object.prototype,
Trait({ m: function() { return this; } })
);
it("open create does not freeze object", function () {
expect( Object.isFrozen(o6) ).to.not.be.ok;
});
it("open create does not freeze methods", function () {
expect( Object.isFrozen(o6.m) ).to.not.be.ok;
});
it("this refers to composite object", function () {
expect(o6).to.equal( o6.m() );
});
it("this not bound to composite object", function () {
var fakethis = {};
expect(fakethis).to.equal( o6.m.call(fakethis) );
});
});
});
describe("Diamond with conflicts", function () {
function makeT1(x) {
return Trait({ m: function() { return x; } });
}
function makeT2(x) {
return Trait.compose(Trait({t2:"foo"}), makeT1(x));
}
function makeT3(x) {
return Trait.compose(Trait({t3:"bar"}), makeT1(x));
}
var T4 = Trait.compose(makeT2(5), makeT3(5));
function create() {
Trait.create(Object.prototype, T4);
}
it("diamond prop conflict", function () {
expect(create).to.throw("Remaining conflicting property: m");
});
});
});
});
}));
<file_sep>/README.md
[](https://travis-ci.org/michaelsbradleyjr/traits.js)
# `Inactive`
*This repository is no longer actively maintained. Please use or create a fork.*
Recommended: **[trait](https://github.com/YR/trait)** by [YR](https://github.com/YR).
N.B. since 2013, when I created this repository, *traits-based composition* seems to have lost none of its value as an alternative (or complement) to inheritance based programming in JavaScript. However, I found my needs better met by [ClojureScript](https://github.com/clojure/clojurescript) as I spent more time with that technology, and left off developing this library not long after I began working on it.
# traits.js
Trait composition library for JavaScript.
## Description
This library is a fork of the original [traits.js](http://soft.vub.ac.be/~tvcutsem/traitsjs/) by [<NAME>](http://soft.vub.ac.be/soft/members/tomvancutsem):
> <a href="https://en.wikipedia.org/wiki/Trait_(computer_programming)">Traits</a> are a flexible language feature to factor out and recombine reusable pieces of code. They are a more robust alternative to multiple inheritance or mixins. They are more robust because name clashes must be resolved explicitly by composers, and because trait composition is order-independent (hence more declarative). To put it simply: if you combine two traits that define a method with the same name, your program will fail. Traits won't automatically give precedence to either one.
## Compatibility
For 1-to-1 features and compatibility with the original *traits.js*, including the built-in ECMAScript 5 shims, please <a href="#installation">install</a> the latest `0.4.x` release.
The `Trait` constructor is available on the object <a href="#usage">exported</a> by the library:
```javascript
var Trait = require("traits.js").Trait; // NodeJS
```
*—or—*
```javascript
Trait = traits.Trait; // browser global scope
```
## Goals
This library will share some similarities with another *traits.js* derivative, [light-traits](https://github.com/Gozala/light-traits/) by [<NAME>](https://github.com/Gozala), e.g. ECMAScript 5 shims will (eventually) *not* be included in the core library. However, it's intended to be a fresh start built atop the same original.
By retooling and experimenting with the original *traits.js*, the primary goal is to come to a deeper understanding of the concepts, implementation, benefits and trade-offs of traits-based composition in JavaScript.
In time, this fork may explore the possibility of leveraging traits as a basis for *gradual typing* in JavaScript libraries, along the lines of Clojure's [core.typed](https://github.com/clojure/core.typed).
A more immediate goal is to leverage traits on top of [Google Polymer](http://www.polymer-project.org/), providing a mechanism for [Custom Element](http://www.w3.org/TR/custom-elements/) *composition* which is complementary to prototypal inheritance, e.g. the `extends` feature of [polymer-element](http://www.polymer-project.org/polymer.html). To that end, this library specifically targets [bower](http://bower.io/), which presently seems to be the favored system for distributing Web Components and expressing dependencies in and between them.
## Installation
You can install the latest release via [bower](http://bower.io/):
```shell
$ bower install traits.js
```
It is also available through [npm](https://npmjs.org/package/traits.js):
```shell
$ npm install traits.js
```
The installed package contains two consumable JavaScript files, `traits.js` and `traits.min.js`.
## Usage
Load *traits.js* in your Node.js programs as you would any other module. The `Trait` constructor is available on the object exported by the library:
```javascript
var Trait = require("traits.js").Trait;
```
In a Web browser, you can load *traits.js* with a `<script>` tag, as you would any other JavaScript library:
```html
<script src="traits.min.js"></script>
<!-- `traits` is now in the global scope -->
<script>
Trait = traits.Trait;
</script>
```
You can also load it as an AMD module, e.g. with [RequireJS](http://requirejs.org/).
## API and Examples
Documentation will be provided in the [wiki](https://github.com/michaelsbradleyjr/traits.js/wiki). For the `0.4.x` releases, the API will exactly match that of the original library, and the latter's documentation can be consulted: [API](http://soft.vub.ac.be/~tvcutsem/traitsjs/api.html), [Tutorial](http://soft.vub.ac.be/~tvcutsem/traitsjs/tutorial.html), [HowToNode article](http://howtonode.org/traitsjs), [PLASTIC Workshop 2011 paper](http://es-lab.googlecode.com/files/traitsJS_PLASTIC2011_final.pdf).
## Development and Testing
The npm and bower distributions are stripped down, so if you wish to hack on the library you should clone it:
```shell
$ git clone https://github.com/michaelsbradleyjr/traits.js
...
$ cd traits.js && npm install .
```
### Testing with Node.js
Launch the mocha test runner with:
```shell
$ npm test
```
You can also have it run continuously, with re-runs triggered by changes to `*.js` files under the project's root.
```shell
$ npm run-script test-watch
```
### Testing with Web browsers
To host the test suite locally, you will need a server — the ever handy [http-server](https://github.com/nodeapps/http-server) is highly recommended:
```shell
$ npm install -g http-server
...
$ http-server -p 12345 -c-1
```
Then point your browser/s to `http://localhost:12345/test/` or `http://localhost:12345/test/amd.html`.
You can also load the test suite as hosted on the `gh-pages` site for this repo: [script tag](http://michaelsbradleyjr.github.io/traits.js/test/), [amd](http://michaelsbradleyjr.github.io/traits.js/test/amd.html).
## Bugs
You can report bugs and discuss features on the [issues page](http://github.com/michaelsbradleyjr/traits.js/issues) or send tweets to [@michaelsbradley](https://twitter.com/michaelsbradley).
## Credit
This software is adapted from an existing work: [traits.js](http://soft.vub.ac.be/~tvcutsem/traitsjs/)
For the original license text please refer to the [licenses](https://github.com/michaelsbradleyjr/traits.js/tree/master/licenses) directory at the [root](https://github.com/michaelsbradleyjr/traits.js/tree/master/) of this distribution.
## Copyright and License
This software is Copyright (c) 2013 by <NAME>, Jr.
The use and distribution terms for this software are covered by the [Apache License, Version 2.0](http://opensource.org/licenses/Apache-2.0) which can be found in the file [LICENSE.txt](http://michaelsbradleyjr.github.io/traits.js/LICENSE.txt) at the [root](https://github.com/michaelsbradleyjr/traits.js/tree/master/) of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software.
---------------------------------------
<div align="left">
<a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference" title="JavaScript Reference"><img src="http://upload.wikimedia.org/wikipedia/en/d/d6/Mozilla_Developer_Network.png" alt="JavaScript Reference" width="64" heigh="73" align="center"/></a> <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference">JavaScript Reference</a>
</div>
<file_sep>/scripts/bump-min.sh
#!/bin/sh
echo "minifying traits.js"
SRC_MIN=`./node_modules/.bin/uglifyjs ./traits.js -c -m`
cat ./scripts/license.txt > ./traits.min.js
echo $SRC_MIN >> ./traits.min.js
echo "gzip'ing traits.min.js"
gzip -c -n ./traits.min.js > ./traits.min.js.gz
echo ""
echo "Finished."
echo ""
<file_sep>/traits.js
/*///////////////////////////////// TRAITS.JS //////////////////////////////////
*
* Version 0.4.1
* Trait composition library for JavaScript
* https://github.com/michaelsbradleyjr/traits.js
*
* This software is Copyright (c) 2013 by <NAME>, Jr.
*
* The use and distribution terms for this software are covered by the Apache
* License, Version 2.0:
*
* http://opensource.org/licenses/Apache-2.0
* http://michaelsbradleyjr.github.io/traits.js/LICENSE.txt
*
* By using this software in any fashion, you are agreeing to be bound by the
* terms of this license. You must not remove this notice, or any other, from
* this software.
*
/////////////////////////////////// CREDIT ////////////////////////////////////
*
* This software is adapted from an existing work:
*
* http://soft.vub.ac.be/~tvcutsem/traitsjs/
*
* For the original license text please refer to:
* https://github.com/michaelsbradleyjr/traits.js/tree/master/licenses
*
/*/////////////////////////////////////////////////////////////////////////////
;(function (definition) {
// Wrapper adapted from Q:
// https://github.com/kriskowal/q/blob/master/q.js
// Turn off strict mode for this function so we can assign to global.traits
/* jshint strict: false */
// This file will function properly as a <script> tag, or a module using
// CommonJS and NodeJS or RequireJS module formats. In Common / Node /
// RequireJS, the module exports the traits.js API and when executed as a
// simple <script>, it creates a `traits` global instead.
// CommonJS
if (typeof exports == "object") {
module.exports = definition();
}
// RequireJS
else if (typeof define == "function" && define.amd) {
define(definition);
}
// <script>
else {
traits = definition();
}
}(function () {
"use strict";
var undefined = void 0;
// == Ancillary functions ==
var SUPPORTS_DEFINEPROP = (function () {
try {
var test = {};
Object.defineProperty(test, "x", {
get: function () { return 0; }
});
return test.x === 0;
} catch(e) {
return false;
}
}());
// IE8 implements Object.defineProperty and Object.getOwnPropertyDescriptor
// only for DOM objects. These methods don't work on plain objects. Hence,
// we need a more elaborate feature-test to see whether the browser truly
// supports these methods:
function supportsGOPD() {
try {
if (Object.getOwnPropertyDescriptor) {
var test = { x: 0 };
return !!Object.getOwnPropertyDescriptor(test, "x");
}
} catch (e) {}
return false;
}
function supportsDP() {
try {
if (Object.defineProperty) {
var test = {};
Object.defineProperty(test, "x", { value: 0 });
return test.x === 0;
}
} catch (e) {}
return false;
}
var call = Function.prototype.call;
/**
* An ad hoc version of bind that only binds the 'this' parameter.
*/
var bindThis = Function.prototype.bind
? function (fun, self) {
return Function.prototype.bind.call(fun, self);
}
: function (fun, self) {
function funcBound(/* var_args */) {
return fun.apply(self, arguments);
}
return funcBound;
},
hasOwnProperty = bindThis(call, Object.prototype.hasOwnProperty),
slice = bindThis(call, Array.prototype.slice),
// feature testing such that traits.js runs on both ES3 and ES5
forEach = Array.prototype.forEach
? bindThis(call, Array.prototype.forEach)
: function (arr, fun) {
for (var i = 0, len = arr.length; i < len; i++) {
fun( arr[i] );
}
},
freeze = Object.freeze || function (obj) { return obj; },
getOwnPropertyNames = Object.getOwnPropertyNames ||
function (obj) {
var props = [];
for (var p in obj) {
if ( hasOwnProperty(obj, p) ) {
props.push(p);
}
}
return props;
},
getOwnPropertyDescriptor = supportsGOPD()
? Object.getOwnPropertyDescriptor
: function (obj, name) {
return {
value: obj[name],
enumerable: true,
writable: true,
configurable: true
};
},
defineProperty = supportsDP()
? Object.defineProperty
: function (obj, name, pd) {
obj[name] = pd.value;
},
defineProperties = Object.defineProperties ||
function (obj, propMap) {
for (var name in propMap) {
if ( hasOwnProperty(propMap, name) ) {
defineProperty( obj, name, propMap[name] );
}
}
},
Object_create = Object.create ||
function (proto, propMap) {
var self;
function dummy() {};
dummy.prototype = proto || Object.prototype;
self = new dummy();
if (propMap) {
defineProperties(self, propMap);
}
return self;
},
getOwnProperties = Object.getOwnProperties ||
function (obj) {
var map = {};
forEach( getOwnPropertyNames(obj), function (name) {
map[name] = getOwnPropertyDescriptor(obj, name);
} );
return map;
};
// end of ES3 - ES5 compatibility functions
function makeConflictAccessor(name) {
function accessor(/* var_args */) {
throw new Error("Conflicting property: " + name);
}
freeze(accessor.prototype);
return freeze(accessor);
}
function makeRequiredPropDesc() {
return freeze({
value: undefined,
enumerable: false,
required: true
});
}
function makeConflictingPropDesc(name) {
var conflict = makeConflictAccessor(name);
if (SUPPORTS_DEFINEPROP) {
return freeze({
get: conflict,
set: conflict,
enumerable: false,
conflict: true
});
} else {
return freeze({
value: conflict,
enumerable: false,
conflict: true
});
}
}
/**
* Are x and y not observably distinguishable?
*/
function identical(x, y) {
if (x === y) {
// 0 === -0, but they are not identical
return x !== 0 || 1/x === 1/y;
} else {
// NaN !== NaN, but they are identical. NaNs are the only
// non-reflexive value, i.e., if x !== x, then x is a NaN.
return x !== x && y !== y;
}
}
// Note: isSameDesc should return true if both desc1 and desc2 represent a
// 'required' property (otherwise two composed required properties would be
// turned into a conflict)
function isSameDesc(desc1, desc2) {
// for conflicting properties, don't compare values because the
// conflicting property values are never equal
if (desc1.conflict && desc2.conflict) {
return true;
} else {
return ( desc1.get === desc2.get
&& desc1.set === desc2.set
&& identical(desc1.value, desc2.value)
&& desc1.enumerable === desc2.enumerable
&& desc1.required === desc2.required
&& desc1.conflict === desc2.conflict );
}
}
function freezeAndBind(meth, self) {
return freeze( bindThis(meth, self) );
}
/**
* makeSet(['foo', ...]) => { foo: true, ...}
*
* makeSet returns an object whose own properties represent a set.
*
* Each string in the names array is added to the set.
*
* To test whether an element is in the set, perform:
* hasOwnProperty(set, element)
*/
function makeSet(names) {
var set = {};
forEach(names, function (name) {
set[name] = true;
});
return freeze(set);
}
// == singleton object used as the placeholder for a required property ==
var required = freeze({
toString: function () { return "<Trait.required>"; }
});
// == The public API methods ==
/**
* var newTrait = trait({ foo:required, ... })
*
* @param object an object record (in principle an object literal)
* @returns a new trait describing all of the own properties of the object
* (both enumerable and non-enumerable)
*
* As a general rule, 'trait' should be invoked with an object literal,
* since the object merely serves as a record descriptor. Both its identity
* and its prototype chain are irrelevant.
*
* Data properties bound to function objects in the argument will be flagged
* as 'method' properties. The prototype of these function objects is
* frozen.
*
* Data properties bound to the 'required' singleton exported by this module
* will be marked as 'required' properties.
*
* The <tt>trait</tt> function is pure if no other code can witness the
* side-effects of freezing the prototypes of the methods. If <tt>trait</tt>
* is invoked with an object literal whose methods are represented as
* in-place anonymous functions, this should normally be the case.
*/
function trait(obj) {
var map = {};
forEach( getOwnPropertyNames(obj), function (name) {
var pd = getOwnPropertyDescriptor(obj, name);
if (pd.value === required) {
pd = makeRequiredPropDesc();
} else if (typeof pd.value == "function") {
pd.method = true;
if ("prototype" in pd.value) {
freeze( pd.value.prototype );
}
} else {
if ( pd.get && pd.get.prototype ) { freeze( pd.get.prototype ); }
if ( pd.set && pd.set.prototype ) { freeze( pd.set.prototype ); }
}
map[name] = pd;
} );
return map;
}
/**
* var newTrait = compose(trait_1, trait_2, ..., trait_N)
*
* @param trait_i a trait object
* @returns a new trait containing the combined own properties of all the
* trait_i.
*
* If two or more traits have own properties with the same name, the new
* trait will contain a 'conflict' property for that name. 'compose' is a
* commutative and associative operation, and the order of its arguments is
* not significant.
*
* If 'compose' is invoked with < 2 arguments, then: compose(trait_1)
* returns a trait equivalent to trait_1 compose() returns an empty trait
*/
function compose(/* var_args */) {
var traits = slice(arguments, 0);
var newTrait = {};
forEach(traits, function (trait) {
forEach( getOwnPropertyNames(trait), function (name) {
var pd = trait[name];
if ( hasOwnProperty(newTrait, name) &&
!newTrait[name].required ) {
// a non-required property with the same name was
// previously defined this is not a conflict if pd
// represents a 'required' property itself:
if (pd.required) {
// skip this property, the required property is now
// present
return;
}
if ( !isSameDesc( newTrait[name], pd ) ) {
// a distinct, non-required property with the same
// name was previously defined by another trait =>
// mark as conflicting property
newTrait[name] = makeConflictingPropDesc(name);
} // else,
// properties are not in conflict if they refer to the
// same value
} else {
newTrait[name] = pd;
}
} );
});
return freeze(newTrait);
}
/**
* var newTrait = exclude(['name', ...], trait)
*
* @param names a list of strings denoting property names.
* @param trait a trait some properties of which should be excluded.
* @returns a new trait with the same own properties as the original trait,
* except that all property names appearing in the first argument
* are replaced by required property descriptors.
*
* Note: exclude(A, exclude(B,t)) is equivalent to exclude(A U B, t)
*/
function exclude(names, trait) {
var exclusions = makeSet(names);
var newTrait = {};
forEach( getOwnPropertyNames(trait), function (name) {
// required properties are not excluded but ignored
if ( !hasOwnProperty(exclusions, name) || trait[name].required ) {
newTrait[name] = trait[name];
} else {
// excluded properties are replaced by required properties
newTrait[name] = makeRequiredPropDesc();
}
} );
return freeze(newTrait);
}
/**
* var newTrait = override(trait_1, trait_2, ..., trait_N)
*
* @returns a new trait with all of the combined properties of the argument
* traits. In contrast to 'compose', 'override' immediately
* resolves all conflicts resulting from this composition by
* overriding the properties of later traits. Trait priority is
* from left to right. I.e. the properties of the leftmost trait
* are never overridden.
*
* override is associative: override(t1,t2,t3) is equivalent to override(t1,
* override(t2, t3)) or to override(override(t1, t2), t3) override is not
* commutative: override(t1,t2) is not equivalent to override(t2,t1)
*
* override() returns an empty trait override(trait_1) returns a trait
* equivalent to trait_1
*/
function override(/* var_args */) {
var traits = slice(arguments, 0);
var newTrait = {};
forEach(traits, function (trait) {
forEach( getOwnPropertyNames(trait), function (name) {
var pd = trait[name];
// add this trait's property to the composite trait only if -
// the trait does not yet have this property - or, the trait
// does have the property, but it's a required property
if ( !hasOwnProperty(newTrait, name) || newTrait[name].required ) {
newTrait[name] = pd;
}
} );
});
return freeze(newTrait);
}
/**
* var newTrait = rename(map, trait)
*
* @param map an object whose own properties serve as a mapping from old
* names to new names.
* @param trait a trait object
* @returns a new trait with the same properties as the original trait,
* except that all properties whose name is an own property of map
* will be renamed to map[name], and a 'required' property for name
* will be added instead.
*
* rename({ a: 'b' }, t) eqv compose( exclude(['a'], t),
* { a: { required: true }, b: t[a] } )
*
* For each renamed property, a required property is generated. If the map
* renames two properties to the same name, a conflict is generated. If the
* map renames a property to an existing unrenamed property, a conflict is
* generated.
*
* Note: rename( A, rename(B, t) ) is eqv to rename(\n -> A( B(n) ), t )
* Note: rename( {...}, exclude( [...], t) ) is not eqv to
* exclude( [...], rename({...}, t) )
*/
function rename(map, trait) {
var renamedTrait = {};
forEach( getOwnPropertyNames(trait), function (name) {
// required props are never renamed
if ( hasOwnProperty(map, name) && !trait[name].required ) {
var alias = map[name]; // alias defined in map
if ( hasOwnProperty(renamedTrait, alias) &&
!renamedTrait[alias].required ) {
// could happen if 2 props are mapped to the same alias
renamedTrait[alias] = makeConflictingPropDesc(alias);
} else {
// add the property under an alias
renamedTrait[alias] = trait[name];
}
// add a required property under the original name but only if a
// property under the original name does not exist such a prop
// could exist if an earlier prop in the trait was previously
// aliased to this name
if ( !hasOwnProperty(renamedTrait, name) ) {
renamedTrait[name] = makeRequiredPropDesc();
}
} else { // no alias defined
if ( hasOwnProperty(renamedTrait, name) ) {
// could happen if another prop was previously aliased to
// name
if ( !trait[name].required ) {
renamedTrait[name] = makeConflictingPropDesc(name);
}
// else required property overridden by a previously aliased
// property and otherwise ignored
} else {
renamedTrait[name] = trait[name];
}
}
} );
return freeze(renamedTrait);
}
/**
* var newTrait = resolve(
* { oldName: 'newName', excludeName: undefined, ... },
* trait
* )
*
* @param resolutions an object whose own properties serve as a mapping from
* old names to new names, or to undefined if the property should be
* excluded
* @param trait a trait object
* @returns a resolved trait with the same own properties as the original
* trait.
*
* This is a convenience function combining renaming and exclusion. It can
* be implemented as <tt>rename(map, exclude(exclusions, trait))</tt> where
* map is the subset of mappings from oldName to newName and exclusions is
* an array of all the keys that map to undefined (or another falsy value).
*
* In a resolved trait, all own properties whose name is an own property of
* resolutions will be renamed to resolutions[name] if it is truthy, or
* their value is changed into a required property descriptor if
* resolutions[name] is falsy.
*
* Note, it's important to _first_ exclude, _then_ rename, since exclude and
* rename are not associative, for example: rename({a: 'b'}, exclude(['b'],
* trait({ a:1,b:2 }))) eqv trait({b:1}) exclude(['b'], rename({a: 'b'},
* trait({ a:1,b:2 }))) eqv trait({b:Trait.required})
*
* writing resolve({a:'b', b: undefined},trait({a:1,b:2})) makes it clear
* that what is meant is to simply drop the old 'b' and rename 'a' to 'b'
*/
function resolve(resolutions, trait) {
var renames = {};
var exclusions = [];
// preprocess renamed and excluded properties
for (var name in resolutions) {
if ( hasOwnProperty(resolutions, name) ) {
if ( resolutions[name] ) { // old name -> new name
renames[name] = resolutions[name];
} else { // name -> undefined
exclusions.push(name);
}
}
}
return rename( renames, exclude(exclusions, trait) );
}
/**
* var obj = create(proto, trait)
*
* @param proto denotes the prototype of the completed object
* @param trait a trait object to be turned into a complete object
* @returns an object with all of the properties described by the trait.
* @throws 'Missing required property' the trait still contains a required
* property.
* @throws 'Remaining conflicting property' if the trait still contains a
* conflicting property.
*
* Trait.create is like Object.create, except that it generates
* high-integrity or final objects. In addition to creating a new object
* from a trait, it also ensures that:
* - an exception is thrown if 'trait' still contains required properties
* - an exception is thrown if 'trait' still contains conflicting
* properties
* - the object is and all of its accessor and method properties are
* frozen
* - the 'this' pseudovariable in all accessors and methods of
* the object is bound to the composed object.
*
* Use Object.create instead of Trait.create if you want to create
* abstract or malleable objects. Keep in mind that for such objects:
* - no exception is thrown if 'trait' still contains required properties
* (the properties are simply dropped from the composite object)
* - no exception is thrown if 'trait' still contains conflicting
* properties (these properties remain as conflicting
* properties in the composite object)
* - neither the object nor its accessor and method properties are frozen
* - the 'this' pseudovariable in all accessors and methods of
* the object is left unbound.
*/
function create(proto, trait) {
var self = Object_create(proto);
var properties = {};
forEach( getOwnPropertyNames(trait), function (name) {
var pd = trait[name];
// check for remaining 'required' properties
// Note: it's OK for the prototype to provide the properties
if (pd.required) {
if ( !(name in proto) ) {
throw new Error("Missing required property: " + name);
}
} else if (pd.conflict) { // check for remaining conflicts
throw new Error("Remaining conflicting property: " + name);
} else if ("value" in pd) { // data property
// freeze all function properties and their prototype
if (pd.method) { // the property is meant to be used as a method
// bind 'this' in trait method to the composite object
properties[name] = {
value: freezeAndBind(pd.value, self),
enumerable: pd.enumerable,
configurable: pd.configurable,
writable: pd.writable
};
} else {
properties[name] = pd;
}
} else { // accessor property
properties[name] = {
get: pd.get ? freezeAndBind(pd.get, self) : undefined,
set: pd.set ? freezeAndBind(pd.set, self) : undefined,
enumerable: pd.enumerable,
configurable: pd.configurable
};
}
} );
defineProperties(self, properties);
return freeze(self);
}
/**
* A shorthand for create(Object.prototype, trait({...}), options)
*/
function object(record, options) {
return create( Object.prototype, trait(record), options );
}
/**
* @return a boolean indicating whether the two argument traits are
* equivalent.
*
* Tests whether two traits are equivalent. T1 is equivalent to T2 iff both
* describe the same set of property names and for all property names n,
* T1[n] is equivalent to T2[n]. Two property descriptors are equivalent if
* they have the same value, accessors and attributes.
*
*/
function eqv(trait1, trait2) {
var names1 = getOwnPropertyNames(trait1);
var names2 = getOwnPropertyNames(trait2);
var name;
if (names1.length !== names2.length) {
return false;
}
for (var i = 0, len = names1.length; i < len; i++) {
name = names1[i];
if ( !trait2[name] || !isSameDesc( trait1[name], trait2[name] ) ) {
return false;
}
}
return true;
}
// if this code is ran in ES3 without an Object.create function, this
// library will define it on Object:
if (!Object.create) {
Object.create = Object_create;
}
// ES5 does not by default provide Object.getOwnProperties if it's not
// defined, the Traits library defines this utility function on Object
if (!Object.getOwnProperties) {
Object.getOwnProperties = getOwnProperties;
}
// expose the public API of this module
function Trait(record) {
// calling Trait as a function creates a new atomic trait
return trait(record);
}
Trait.required = freeze(required);
Trait.compose = freeze(compose);
Trait.resolve = freeze(resolve);
Trait.override = freeze(override);
Trait.create = freeze(create);
Trait.eqv = freeze(eqv);
Trait.object = freeze(object); // not essential, cf. create + trait
freeze(Trait);
var traits = (function () {
function Traits() {}
freeze(Traits.prototype);
freeze(Traits);
return new Traits();
}());
traits.Trait = Trait;
traits.version = "0.4.1";
freeze(traits);
return traits;
}));
|
032cc077bb9474cb9d98106e7f06dc891b8dc6cb
|
[
"JavaScript",
"Markdown",
"Shell"
] | 4
|
JavaScript
|
michaelsbradleyjr/traits.js.git
|
36955607695845bfa1a4f1a8e5ae8bec6a25f2f2
|
a7c88050ff8d983c0ad75cf749a5e08e057efe66
|
refs/heads/master
|
<repo_name>breckinridge22/Tetris<file_sep>/README.md
# Tetris
This is an implementation of Tetris completed for a Game Design class completed at the University of CapeTown using Java and LibGDX.
<file_sep>/core/src/com/mygdx/Tetris/Game.java
package com.mygdx.Tetris;
import java.util.Arrays;
public class Game {
public int [][] grid;
private int linesCleared;
private int score;
public boolean gameOver;
public Game(){
grid = new int[17][10];
for (int row = 0; row < grid.length-1; row ++){
for (int col = 0; col < grid[row].length; col++){
grid[row][col] = 0;
}
}
for (int col = 0; col < grid[16].length; col++){
grid[16][col] = 1;
}
gameOver = false;
score = 0;
linesCleared = 0;
}
public void update(Tetromino tetromino, float dt){
for (int row = 0; row < tetromino.shape.length; row++) {
for (int col = 0; col < tetromino.shape[row].length; col++) {
if (tetromino.shape[row][col] != 0) {
grid[row + (int)tetromino.topPosition[0]][col + (int)tetromino.topPosition[1]] = tetromino.shape[row][col];
}
}
}
clearLines(dt);
this.gameOver = isGameOver();
}
public int getScore(){
return this.score;
}
public int getLinesCleared(){
return this.linesCleared;
}
public int[][] getGrid(){
return this.grid;
}
public boolean isLineCleared(int row){
for (int col = 0; col < this.grid[row].length; col++){
if (this.grid[row][col] == 0){
return false;
}
}
return true;
}
public void clearLines(float dt){
for (int row = 0; row < this.grid.length-1; row++){
if(isLineCleared(row)){
int[][] top = new int[grid.length-(grid.length-row)][];
for (int i = 0; i < top.length; i++){
top[i] = this.grid[i].clone();
}
int k = 0;
for (int col = 0; col < this.grid[k].length; col++){
this.grid[k][col] = 0;
}
for (int i = 0; i < top.length; i++){
this.grid[i+1] = top[i].clone();
}
linesCleared++;
score += 100;
}
}
}
public boolean isGameOver(){
int row = 0;
for (int col = 0; col < this.grid[row].length; col++){
if (this.grid[row][col] != 0){
return true;
}
}
return false;
}
}
<file_sep>/core/src/com/mygdx/Tetris/Tetromino.java
package com.mygdx.Tetris;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
public class Tetromino {
public static int fall_velocity = 1;
public static final Integer I = 1;
public static final Integer O = 2;
public static final Integer T = 3;
public static final Integer L = 4;
public static final Integer J = 5;
public static final Integer S = 6;
public static final Integer Z = 7;
public int [][] Ishape1 = {
{0, 0 ,0, 0},
{1, 1, 1, 1},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
public int [][] Ishape2 = {
{0, 0, 1, 0},
{0, 0, 1, 0},
{0, 0, 1, 0},
{0, 0, 1, 0}
};
public int [][] Ishape3 = {
{0, 0, 0, 0},
{0, 0, 0, 0},
{1, 1, 1, 1},
{0, 0, 0, 0}
};
public int [][] Ishape4 = {
{0, 1, 0, 0},
{0, 1, 0, 0},
{0, 1, 0, 0},
{0, 1, 0, 0}
};
public int [][] Oshape = {
{0, 2, 2, 0},
{0, 2, 2, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
public int[][] Tshape1 = {
{0, 3, 0, 0},
{3, 3, 3, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
public int[][] Tshape2 = {
{0, 3, 0, 0},
{0, 3, 3, 0},
{0, 3, 0, 0},
{0, 0, 0, 0}
};
public int[][] Tshape3 = {
{0, 0, 0, 0},
{3, 3, 3, 0},
{0, 3, 0, 0},
{0, 0, 0, 0}
};
public int[][] Tshape4 = {
{0, 3, 0, 0},
{3, 3, 0, 0},
{0, 3, 0, 0},
{0, 0, 0, 0}
};
public int[][] Lshape1 = {
{0, 0, 4, 0},
{4, 4, 4, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
public int[][] Lshape2 = {
{0, 4, 0, 0},
{0, 4, 0, 0},
{0, 4, 4, 0},
{0, 0, 0, 0}
};
public int[][] Lshape3 = {
{0, 0, 0, 0},
{4, 4, 4, 0},
{4, 0, 0, 0},
{0, 0, 0, 0}
};
public int[][] Lshape4 = {
{4, 4, 0, 0},
{0, 4, 0, 0},
{0, 4, 0, 0},
{0, 0, 0, 0}
};
public int[][] Jshape1 = {
{5, 0, 0, 0},
{5, 5, 5, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
public int[][] Jshape2 = {
{0, 5, 5, 0},
{0, 5, 0, 0},
{0, 5, 0, 0},
{0, 0, 0, 0}
};
public int[][] Jshape3 = {
{0, 0, 0, 0},
{5, 5, 5, 0},
{0, 0, 5, 0},
{0, 0, 0, 0}
};
public int[][] Jshape4 = {
{0, 5, 0, 0},
{0, 5, 0, 0},
{5, 5, 0, 0},
{0, 0, 0, 0}
};
public int[][] Sshape1 = {
{0, 6, 6, 0},
{6, 6, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
public int[][] Sshape2 = {
{0, 6, 0, 0},
{0, 6, 6, 0},
{0, 0, 6, 0},
{0, 0, 0, 0}
};
public int[][] Sshape3 = {
{0, 0, 0, 0},
{0, 6, 6, 0},
{6, 6, 0, 0},
{0, 0, 0, 0}
};
public int[][] Sshape4 = {
{6, 0, 0, 0},
{6, 6, 0, 0},
{0, 6, 0, 0},
{0, 0, 0, 0}
};
public static int[][] Zshape1 = {
{7, 7, 0, 0},
{0, 7, 7, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
public int[][] Zshape2 = {
{0, 0, 7, 0},
{0, 7, 7, 0},
{0, 7, 0, 0},
{0, 0, 0, 0}
};
public int[][] Zshape3 = {
{0, 0, 0, 0},
{7, 7, 0, 0},
{0, 7, 7, 0},
{0, 0, 0, 0}
};
public int[][] Zshape4 = {
{0, 7, 0, 0},
{7, 7, 0, 0},
{7, 0, 0, 0},
{0, 0, 0, 0}
};
private void fillShapes(){
possibleShapes.add(Ishape1);
possibleShapes.add(Oshape);
possibleShapes.add(Tshape1);
possibleShapes.add(Lshape1);
possibleShapes.add(Jshape1);
possibleShapes.add(Sshape1);
possibleShapes.add(Zshape1);
}
public static ArrayList<int[][]> Ishapes = new ArrayList<>();
public static ArrayList<int[][]> Oshapes = new ArrayList<>();
public static ArrayList<int[][]> Tshapes = new ArrayList<>();
public static ArrayList<int[][]> Lshapes = new ArrayList<>();
public static ArrayList<int[][]> Jshapes = new ArrayList<>();
public static ArrayList<int[][]> Sshapes = new ArrayList<>();
public static ArrayList<int[][]> Zshapes = new ArrayList<>();
private void populateShapes(){
Ishapes.add(Ishape1);
Ishapes.add(Ishape2);
Ishapes.add(Ishape3);
Ishapes.add(Ishape4);
Oshapes.add(Oshape);
Oshapes.add(Oshape);
Oshapes.add(Oshape);
Oshapes.add(Oshape);
Tshapes.add(Tshape1);
Tshapes.add(Tshape2);
Tshapes.add(Tshape3);
Tshapes.add(Tshape4);
Lshapes.add(Lshape1);
Lshapes.add(Lshape2);
Lshapes.add(Lshape3);
Lshapes.add(Lshape4);
Jshapes.add(Jshape1);
Jshapes.add(Jshape2);
Jshapes.add(Jshape3);
Jshapes.add(Jshape4);
Sshapes.add(Sshape1);
Sshapes.add(Sshape2);
Sshapes.add(Sshape3);
Sshapes.add(Sshape4);
Zshapes.add(Zshape1);
Zshapes.add(Zshape2);
Zshapes.add(Zshape3);
Zshapes.add(Zshape4);
}
private void fillArray(){
listOfShapes[0] = Ishapes;
listOfShapes[1] = Oshapes;
listOfShapes[2] = Tshapes;
listOfShapes[3] = Lshapes;
listOfShapes[4] = Jshapes;
listOfShapes[5] = Sshapes;
listOfShapes[6] = Zshapes;
}
private ArrayList<int[][]> possibleShapes = new ArrayList<>();
private ArrayList[] listOfShapes = new ArrayList[7];
private Random rand = new Random();
public boolean landed;
public ArrayList<int[][]> shapes;
public int[][] shape;
public int[][] nextRotation;
public float[] topPosition;
public float[] potTopPosition;
int rotation;
public Tetromino(int x, int y){
rotation = 0;
populateShapes();
fillArray();
fillShapes();
this.topPosition = new float[]{x,y};
this.potTopPosition = new float[]{x,y};
pickRandomShape();
this.landed = false;
}
private void pickRandomShape(){
int r = rand.nextInt(7);
this.shapes = new ArrayList(listOfShapes[r]);
this.shape = new int[4][4];
this.nextRotation = new int[4][4];
this.shape = this.shapes.get(rotation);
this.nextRotation = this.shapes.get(rotation+1);
}
public void update(float dt, Game game){
handleInput(game);
fall(game);
}
// deal with the input of the user as long as there are no collisions
public void handleInput(Game game){
if (Gdx.input.isKeyJustPressed(Keys.LEFT) && inBounds()){
this.potTopPosition[1]--;
} else if (Gdx.input.isKeyJustPressed(Keys.RIGHT)){
this.potTopPosition[1]++;
}else if (Gdx.input.isKeyPressed(Keys.DOWN)){
this.potTopPosition[0]++;
}else if (Gdx.input.isKeyJustPressed(Keys.UP)){
if (!checkRotationCollision()){
this.shape = this.shapes.get(++rotation);
if (rotation == 3){
this.nextRotation = this.shapes.get(0);
rotation = -1;
} else {
this.nextRotation = this.shapes.get(rotation+1);
}
}
}
if (!checkCollision(game)){
this.topPosition[0] = this.potTopPosition[0];
this.topPosition[1] = this.potTopPosition[1];
} else {
this.potTopPosition[0] = this.topPosition[0];
this.potTopPosition[1] = this.topPosition[1];
}
}
public boolean checkCollision(Game game){
for (int row = 0; row < this.shape.length; row++) {
for (int col = 0; col < this.shape[row].length; col++) {
if (this.shape[row][col] != 0) {
if (col + this.potTopPosition[1] < 0){
return true;
}
if (col + this.potTopPosition[1] > game.grid[row].length-1){
return true;
}
if (game.grid[row + (int)this.potTopPosition[0]][col + (int)this.potTopPosition[1]] != 0) {
this.landed = true;
return true;
}
}
}
}
return false;
}
public boolean checkRotationCollision(){
for (int row = 0; row < this.nextRotation.length; row++) {
for (int col = 0; col < this.nextRotation[row].length; col++) {
if (this.nextRotation[row][col] != 0) {
if (col + this.potTopPosition[1] < 0){
return true;
}
if (col + this.potTopPosition[1] > 9){
return true;
}
}
}
}
return false;
}
public boolean inBounds(){
if (this.potTopPosition[0] < 0 || this.potTopPosition[0] > 15){
return false;
}
if (this.potTopPosition[1] < 0 || this.potTopPosition[1] > 9){
return false;
}
return true;
}
public void fall(Game game){
this.potTopPosition[0] += .05;
if (!checkCollision(game)){
this.topPosition[0] = this.potTopPosition[0];
this.topPosition[1] = this.potTopPosition[1];
} else {
this.potTopPosition[0] = this.topPosition[0];
this.potTopPosition[1] = this.topPosition[1];
}
}
public boolean isLanded(){
return this.landed;
}
}
<file_sep>/core/src/com/mygdx/Tetris/states/PlayState.java
package com.mygdx.Tetris.states;
import java.util.ArrayList;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.mygdx.Tetris.Game;
import com.mygdx.Tetris.Tetris;
import com.mygdx.Tetris.Tetromino;
public class PlayState extends State {
private Texture title;
private Game game;
private Tetromino tetromino;
private Tetromino nextTet;
private BitmapFont font;
private ArrayList<Texture> blocks;
private ShapeRenderer shapeRenderer;
public PlayState(GameStateManager gsm) {
super(gsm);
game = new Game();
tetromino = new Tetromino(0, 4);
nextTet = new Tetromino(0,4);
blocks = new ArrayList<>();
fillBlocks();
shapeRenderer = new ShapeRenderer();
font = new BitmapFont();
font.setColor(Color.WHITE);
title = new Texture("tetris.png");
// TODO Auto-generated constructor stub
}
public void fillBlocks(){
blocks.add(new Texture("block1.png"));
blocks.add(new Texture("block2.png"));
blocks.add(new Texture("block3.png"));
blocks.add(new Texture("block4.jpeg"));
blocks.add(new Texture("block5.jpeg"));
blocks.add(new Texture("block6.png"));
blocks.add(new Texture("block7.jpg"));
}
@Override
protected void handleInput() {
// TODO Auto-generated method stub
}
@Override
public void update(float dt) {
// TODO Auto-generated method stub
handleInput();
// change potential position
tetromino.update(dt, game);
// then check for collision
if (tetromino.isLanded()){
game.update(tetromino, dt);
tetromino = nextTet;
nextTet = new Tetromino(0,4);
}
if (game.gameOver){
gsm.set(new EndState(gsm, game.getScore()));
dispose();
}
}
public boolean checkCollision(){
for (int row = 0; row < tetromino.shape.length; row++) {
for (int col = 0; col < tetromino.shape[row].length; col++) {
if (tetromino.shape[row][col] != 0) {
if (col + tetromino.potTopPosition[1] < 0){
return true;
}
if (col + tetromino.potTopPosition[1] > game.grid[row].length){
return true;
}
if (game.grid[row + (int)tetromino.potTopPosition[0]][col + (int)tetromino.potTopPosition[1]] != 0) {
tetromino.landed = true;
return true;
}
}
}
}
return false;
}
@Override
public void render(SpriteBatch batch) {
// TODO Auto-generated method stub
batch.begin();
batch.draw(title, (Tetris.WIDTH/2 - title.getWidth()/2), Tetris.HEIGHT - 250);
font.draw(batch, "SCORE:", 400, 350);
font.draw(batch, Integer.toString(game.getScore()), 500, 350);
font.draw(batch, "LINES:", 402, 250);
font.draw(batch, Integer.toString(game.getLinesCleared()), 500, 250);
for (int row = 0; row < tetromino.shape.length; row++) {
for (int col = 0; col < tetromino.shape[row].length; col++) {
if (tetromino.shape[row][col] != 0) {
//draw block at position corresponding to
//row + topLeft.row, and
//col + topLeft.col
batch.draw(blocks.get(tetromino.shape[row][col]-1), 330-(((game.grid[row].length-(col+tetromino.topPosition[1]))*30)), (480 - ((row + (int)tetromino.topPosition[0])*30)));
}
}
}
font.draw(batch, "Next Piece:", 420, 500);
for (int row = 0; row < nextTet.shape.length; row++) {
for (int col = 0; col < nextTet.shape[row].length; col++) {
if (nextTet.shape[row][col] != 0) {
batch.draw(blocks.get(nextTet.shape[row][col]-1), (600-(col+(int)nextTet.topPosition[1])*30), (430 - (row + (int)nextTet.topPosition[0])*30));
}
}
}
for (int row = 1; row < game.grid.length-1; row++) {
for (int col = 0; col < game.grid[row].length; col++) {
if (game.grid[row][col] != 0) {
batch.draw(blocks.get(game.grid[row][col]-1), (330-((game.grid[row].length-col)*30)), 480-((row*30)));
}
}
}
//batch.draw(tetromino.getTexture(), tetromino.getPosition().x, tetromino.getPosition().y);
batch.end();
shapeRenderer.begin(ShapeType.Line);
shapeRenderer.setColor(1, 1, 1, 0);
shapeRenderer.rect(30, 30, 300, 480);
shapeRenderer.end();
}
@Override
public void dispose() {
// TODO Auto-generated method stub
title.dispose();
font.dispose();
}
}
<file_sep>/core/src/com/mygdx/Tetris/states/MenuState.java
package com.mygdx.Tetris.states;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.mygdx.Tetris.Tetris;
public class MenuState extends State {
private Texture title;
private Texture playBtn;
public MenuState(GameStateManager gsm) {
super(gsm);
title = new Texture("Tetris.png");
playBtn = new Texture("playBtn.png");
}
@Override
public void handleInput() {
// TODO Auto-generated method stub
if (Gdx.input.justTouched()){
gsm.set(new PlayState(gsm));
dispose();
}
}
@Override
public void update(float dt) {
// TODO Auto-generated method stub
handleInput();
}
@Override
public void render(SpriteBatch batch) {
// TODO Auto-generated method stub
batch.begin();
batch.draw(title, (Tetris.WIDTH/2 - title.getWidth()/2), Tetris.HEIGHT - 250);
batch.draw(playBtn, Tetris.WIDTH/2 - playBtn.getWidth()/2, Tetris.HEIGHT/2 - 50);
batch.end();
}
@Override
public void dispose() {
// TODO Auto-generated method stub
title.dispose();
playBtn.dispose();
}
}
|
875a2f271ed06532c7318a14d6b9ad51fead559f
|
[
"Markdown",
"Java"
] | 5
|
Markdown
|
breckinridge22/Tetris
|
fc86f47c3232e4433fee24bbc4e598480f29ff31
|
b3294aa9716e441f68adb0d3124ac41a8534a341
|
refs/heads/main
|
<repo_name>Shourya-Dark/C-24<file_sep>/sketch.js
const Engine = Matter.Engine;
const World= Matter.World;
const Bodies = Matter.Bodies;
var engine, world;
var box1, box2, box3, box4, box5;
var pig1, pig2;
var Plank1, Plank2, Plank3, Plank4;
var bird;
function setup(){
var canvas = createCanvas(1366,400);
engine = Engine.create();
world = engine.world;
box1 = new Box(700,300,70,70);
box2 = new Box(920,300,70,70);
box3 = new Box(700,240,70,70);
box4 = new Box(920,240,70,70);
box5 = new Box(810,160,70,70);
ground = new Ground(683,height,1366,20)
pig1 = new Pig(810, 350);
pig2 = new Pig(810, 220);
Plank1 = new Plank(810, 260, 300, PI/2);
Plank2 = new Plank(810, 180, 300, PI/2);
Plank3 = new Plank(760, 120, 150, PI/7);
Plank4 = new Plank(870, 120, 150, -PI/7);
bird = new Bird(100,100);
}
function draw(){
background(0);
Engine.update(engine);
// console.log(box2.body.position.x);
// console.log(box2.body.position.y);
// console.log(box2.body.angle);
box1.display();
box2.display();
box3.display();
box4.display();
box5.display();
pig1.display();
pig2.display();
Plank1.display();
Plank2.display();
Plank3.display();
Plank4.display();
bird.display();
ground.display();
}
|
8e60eb1091db22304db382dcd01fc03c7a96df83
|
[
"JavaScript"
] | 1
|
JavaScript
|
Shourya-Dark/C-24
|
5f567608de3cdace7f85b01d6a348c4ebcdc8b21
|
53eb9cfe7eca15fafb28827f8a385757844a84e8
|
refs/heads/main
|
<repo_name>sr-dev-coder/crwn-clothing<file_sep>/src/pages/sign-in-and-signup-page/sign-in-and-signup-page.component.jsx
import React from 'react';
import './sign-in-and-signup-page.styles.scss';
import SignIn from './../../component/signin/signin.component';
import SignUp from './../../component/sign-up/sign-up.component';
const SignInAndSignUp = () =>(
<div className='sign-in-and-signup'>
<SignIn />
<SignUp />
</div>
)
export default SignInAndSignUp;
|
09c343a26aa8e14c1a29ee188c2e351c3503db7a
|
[
"JavaScript"
] | 1
|
JavaScript
|
sr-dev-coder/crwn-clothing
|
a163fd3bcdd6c4baaa5778734648a6be731eb3ee
|
c7be08e65e48aa60181da7e6fea13be99e25cb16
|
refs/heads/master
|
<repo_name>vihasshah/circular-slider-image-picker<file_sep>/PickerScreen.js
import React from 'react'
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'
import { ImagePicker, Permissions } from 'expo';
import ImageCropper from 'react-native-image-crop-picker'
export default class PickerScreen extends React.Component {
_checkMultiPermissions = async () => {
const { status } = await Permissions.getAsync(Permissions.CAMERA_ROLL,Permissions.CAMERA);
if(status !== 'granted'){
this._askCameraPermission()
}else{
this._renderImagePicker()
}
}
_askCameraPermission = async () => {
const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL,Permissions.CAMERA);
if (status !== 'granted') {
alert("permission not granted")
}else{
alert("permission granted")
}
}
_renderImagePicker = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
allowsEditing: true,
aspect:[1,1],
quality:1,
});
console.log(result)
this.props.navigation.navigate("edit",{URI: result.uri})
}
render = () => {
return (
<View style={styles.container}>
<TouchableOpacity onPress={() => {this._checkMultiPermissions()}}>
<View style={styles.imageBtn}>
<Text>select Image</Text>
</View>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
imageBtn:{
padding:10,
backgroundColor:'#0003'
}
});<file_sep>/EditingScreen.js
import React, { Component } from 'react'
import { View, Image, StyleSheet, Dimensions } from 'react-native'
import PinchZoomView from './PinchZoomView';
export default class EditingScreen extends Component {
render = () => {
let imgUri = this.props.navigation.getParam("URI")
return (
<View style={styles.container}>
<PinchZoomView>
<View style={styles.imageWrapper}>
<Image source={{ uri: imgUri}} style={styles.image} />
</View>
</PinchZoomView>
</View>
)
}
}
const styles = StyleSheet.create({
container:{
flex:1,
justifyContent:'center',
borderWidth:1,borderColor:'#000'
},
imageWrapper:{
flex:1,
justifyContent:'center',
borderWidth:1,borderColor:'#000'
},
image:{
width:Dimensions.get('window').width,
height:Dimensions.get('window').width,
borderRadius:Dimensions.get('window').width / 2,
backgroundColor:'#000',
overflow:'hidden',
resizeMode:'stretch'
}
})
|
2c4e7a74facf98e73c13554bf8ad399e5cf15771
|
[
"JavaScript"
] | 2
|
JavaScript
|
vihasshah/circular-slider-image-picker
|
428ad5eddb93d40a87ee6e4d3b7fd9153f505f11
|
f61ea69915ba64c8bb9b0952c886d3fd2ff2229e
|
refs/heads/master
|
<file_sep>export default {
GetDateTime: GetDateTime,
sortAcutionsByDateAscend: (data) => {
var result = data.sort((prev, next) => {
var prevRemainingTime = GetDateTime(prev.remainingTime);
var nextRemainingTime = GetDateTime(next.remainingTime);
if (prevRemainingTime > nextRemainingTime) {
return 1;
} else if (prevRemainingTime < nextRemainingTime) {
return -1;
}
return 0
});
return result;
}
}
function GetDateTime(miliseconds){
var seconds = parseInt((miliseconds / 1000) % 60)
var minutes = parseInt((miliseconds / (1000 * 60)) % 60);
var hours = parseInt((miliseconds / (1000 * 60 * 60)) % 24);
var date = new Date();
date.setHours(hours, minutes, seconds)
return date;
}<file_sep>
import React, { Component } from 'react';
import utils from './utils.js';
export default class Auction extends Component {
constructor(props){
super(props);
let remainingTimeVal = this.props.prodData.remainingTime;
let bids = this.props.prodData.bids;
//take the last
let amount = (
bids.length > 0 ? bids[bids.length - 1].amount : 0
);
this.time = utils.GetDateTime(remainingTimeVal),
this.state = {
isClose: remainingTimeVal === 0 ? true : false,
prodData: this.props.prodData,
timeFormat : this.GetTimeFormated(this.time),
lastAmount: amount
}
this.handleOferta = this.handleOferta.bind(this);
}
componentDidMount() {
this.intervalID = setInterval(
() => this.tick(),
1000)
}
handleOferta(e){
this.setState((state, props) => {
let amount = this.state.lastAmount + 250;
this.state.prodData.bids.push(
{
"amount": amount,
"dealership": "Instacarro",
"createdAt": new Date().toJSON(),
"channel": "Web"
}
);
return {
prodData: this.state.prodData,
lastAmount : amount
}
})
}
tick(){
this.setState((state,props) => {
if(this.time.getHours() === 0
&& this.time.getMinutes() === 0
&& this.time.getSeconds() === 0){
clearInterval(this.intervalID);
return {
timeFormat: this.state.timeFormat,
isClose: true
}
} else {
this.time.setSeconds(this.time.getSeconds()-1);
return {
timeFormat: this.GetTimeFormated(this.time)
}
}
});
}
componentWillUnmount() {
clearInterval(this.intervalID);
}
GetTimeFormated(date){
return date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
}
render(){
const { prodData, isClose} = this.state;
return (
<div className='card' style={{ opacity : (isClose ? 0.4 : 1) }}>
<div className="img" style={{ backgroundImage: `url(${this.state.prodData.imageUrl})` }}></div>
<span className="label-detail">ver detalhes</span>
<div className="flex-container-column">
<div className="card-content-1">
<div>
TEMP RESTANTE
<div className="time">{this.state.timeFormat}</div>
</div>
<div>
ULTIMA OFERTA
<div className="money">R$ {this.state.lastAmount}</div>
</div>
</div>
<div class="divider"></div>
<div className="card-content-2">
<p> {prodData.make}
{prodData.model}
{prodData.version}
{prodData.year}</p>
</div>
<div className="card-content-3">
<div>
{prodData.year}
</div>
<div>
{prodData.km}
</div>
</div>
<div className="card-footer">
{!isClose ? (
<button onClick={this.handleOferta} className="btn-block secondary">FAZER OFERTA</button>
) : (
<span className="normal">CLOSED</span>
)
}
</div>
</div>
</div>
)
}
}
<file_sep>import React, { Component } from 'react';
import Auction from './auction.js';
import utils from './utils.js';
import axios from 'axios'
export default class AuctionList extends Component {
constructor(props){
super(props);
this.state = { auctions: [], isLoaded: false, error: null};
}
componentDidMount() {
axios.get('https://s3-sa-east-1.amazonaws.com/config.instacarro.com/recruitment/auctions.json')
.then((result) => {
let _data = result.data;
_data[0].remainingTime = 10000;
this.setState({
isLoaded: true,
auctions : utils.sortAcutionsByDateAscend(_data)
})
}, (error) => {
console.error(error);
this.setState({
isLoaded: true,
error: error,
});
})
}
componentWillUnmount() {
}
render(){
const {error, isLoaded, auctions } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="flex-container">
{auctions.map(item => (
<Auction prodData={item} key={item.id}/>
))}
</div>
)
}
}
}
<file_sep>export default [{
"id": "5b79a2d044791c001a61224a",
"make": "CITROËN",
"model": "C3",
"year": 2010,
"version": "1.4 I XTR 8V FLEX 4P MANUAL",
"km": 162607,
"remainingTime": 790968,
"imageUrl": "https://uploads.instacarro.com/JPEG_20180825_1305445b79a2d044791c001a61224a313739693525860090.jpg",
"bids": [{
"amount": 4250,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:36:04.605Z",
"channel": "Web"
}]
}, {
"id": "5b7a0819aefec4001a8c9e4a",
"make": "HYUNDAI",
"model": "VERA CRUZ",
"year": 2010,
"version": "3.8 GLS 4WD 4X4 V6 24V GASOLINA 4P AUTOMATICO",
"km": 122980,
"remainingTime": 415084,
"imageUrl": "https://uploads.instacarro.com/JPEG_20180827_1043255b7a0819aefec4001a8c9e4a1844773866.jpg",
"bids": [{
"amount": 22145,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:37:09.464Z",
"channel": "Web"
}, {
"amount": 22395,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:44:13.165Z",
"channel": "Web"
}, {
"amount": 22645,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:44:34.438Z",
"channel": "Web"
}]
}, {
"id": "5b7aba1744791c001a6122c6",
"make": "FIAT",
"model": "STRADA",
"year": 2015,
"version": "1.8 MPI ADVENTURE CD 16V FLEX 3P AUTOMATIZADO",
"km": 31567,
"remainingTime": 454050,
"imageUrl": "https://uploads.instacarro.com/JPEG_20180825_1355155b7aba1744791c001a6122c64423657144587756499.jpg",
"bids": [{
"amount": 10750,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:28:20.527Z",
"channel": "Web"
}, {
"amount": 40000,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:32:48.322Z",
"channel": "Web"
}, {
"amount": 42000,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:34:24.335Z",
"channel": "Web"
}]
}, {
"id": "5b7bfd60aefec4001a8ca024",
"make": "HONDA",
"model": "CIVIC",
"year": 2008,
"version": "1.8 LXS 16V FLEX 4P AUTOMATICO",
"km": 168902,
"remainingTime": 474333,
"imageUrl": "https://uploads.instacarro.com/JPEG_20180825_1310365b7bfd60aefec4001a8ca0242100825649.jpg",
"bids": [{
"amount": 7500,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:28:41.533Z",
"channel": "Web"
}, {
"amount": 7750,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:43:55.998Z",
"channel": "Web"
}]
}, {
"id": "5b7c4d03aefec4001a8ca0f7",
"make": "VOLKSWAGEN",
"model": "CROSSFOX",
"year": 2011,
"version": "1.6 MI FLEX 8V 4P MANUAL",
"km": 81786,
"remainingTime": 1151391,
"imageUrl": "https://uploads.instacarro.com/JPEG_20180825_1459275b7c4d03aefec4001a8ca0f7642649693.jpg",
"bids": [{
"amount": 6750,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:36:14.589Z",
"channel": "Web"
}, {
"amount": 7000,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:41:10.819Z",
"channel": "Web"
}, {
"amount": 7250,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:41:34.879Z",
"channel": "Web"
}, {
"amount": 7500,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:42:47.245Z",
"channel": "Web"
}]
}, {
"id": "5b7c7943aefec4001a8ca184",
"make": "RENAULT",
"model": "SANDERO",
"year": 2009,
"version": "1.0 EXPRESSION 16V FLEX 4P MANUAL",
"km": 68676,
"remainingTime": 1174585,
"imageUrl": "https://uploads.instacarro.com/JPEG_20180825_1543455b7c7943aefec4001a8ca1841412984798.jpg",
"bids": [{
"amount": 4000,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:36:17.856Z",
"channel": "Web"
}, {
"amount": 4250,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:44:31.102Z",
"channel": "Web"
}]
}, {
"id": "5b7d6651431dd6001aed2022",
"make": "CITROËN",
"model": "C3",
"year": 2015,
"version": "1.5 TENDANCE 8V FLEX 4P MANUAL",
"km": 21713,
"remainingTime": 1185738,
"imageUrl": "https://uploads.instacarro.com/JPEG_20180825_1526445b7d6651431dd6001aed2022-1167198429.jpg",
"bids": [{
"amount": 7750,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:36:21.710Z",
"channel": "Web"
}, {
"amount": 23000,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:41:01.871Z",
"channel": "Web"
}]
}, {
"id": "5b7e9dc2431dd6001aed2130",
"make": "CHEVROLET",
"model": "PRISMA",
"year": 2014,
"version": "1.4 MPFI LT 8V FLEX 4P MANUAL",
"km": 40598,
"remainingTime": 1195942,
"imageUrl": "https://uploads.instacarro.com/JPEG_20180825_1522445b7e9dc2431dd6001aed2130663682537762062826.jpg",
"bids": [{
"amount": 8000,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:36:25.495Z",
"channel": "Web"
}, {
"amount": 8250,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:39:52.176Z",
"channel": "Web"
}]
}, {
"id": "5b7ee35ace8dea001ac40ea7",
"make": "CHEVROLET",
"model": "ASTRA",
"year": 2007,
"version": "2.0 MPFI ADVANTAGE 8V FLEX 4P MANUAL",
"km": 88776,
"remainingTime": 812763,
"imageUrl": "https://uploads.instacarro.com/JPEG_20180825_1415215b7ee35ace8dea001ac40ea7243281839.jpg",
"bids": [{
"amount": 4000,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:30:23.873Z",
"channel": "Web"
}, {
"amount": 4250,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:31:01.375Z",
"channel": "Web"
}, {
"amount": 10750,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:31:42.146Z",
"channel": "Web"
}, {
"amount": 11000,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:34:55.781Z",
"channel": "Web"
}, {
"amount": 11250,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:36:09.018Z",
"channel": "Web"
}, {
"amount": 11500,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:37:54.277Z",
"channel": "Web"
}, {
"amount": 11750,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:40:11.476Z",
"channel": "Web"
}]
}, {
"id": "5b7ffdb1ce8dea0<KEY>",
"make": "TOYOTA",
"model": "FIELDER",
"year": 2008,
"version": "1.8 XEI 16V FLEX 4P AUTOMATICO",
"km": 99255,
"remainingTime": 1205968,
"imageUrl": "https://uploads.instacarro.com/JPEG_20180825_1630275b7ffdb1ce8dea001ac40fbb-1006019815.jpg",
"bids": [{
"amount": 6000,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:35:17.351Z",
"channel": "Web"
}, {
"amount": 6250,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:38:19.773Z",
"channel": "Web"
}, {
"amount": 15000,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:39:16.591Z",
"channel": "Web"
}]
}, {
"id": "5b81ca0ace8dea001ac4125c",
"make": "CHEVROLET",
"model": "MERIVA",
"year": 2010,
"version": "1.8 MPFI PREMIUM 8V FLEX 4P AUTOMATIZADO",
"km": 97254,
"remainingTime": 1691717,
"imageUrl": "https://uploads.instacarro.com/JPEG_20180827_1125215b81ca0ace8dea001ac4125c49046047.jpg",
"bids": []
}, {
"id": "5b83f2b0ce8dea001ac412ed",
"make": "HYUNDAI",
"model": "TUCSON",
"year": 2015,
"version": "2.0 MPFI GLS 16V 143CV 2WD FLEX 4P AUTOMATICO",
"km": 46460,
"remainingTime": 1456713,
"imageUrl": "https://uploads.instacarro.com/JPEG_20180827_1117185b83f2b0ce8dea001ac412ed-1048370064.jpg",
"bids": [{
"amount": 40000,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:40:38.478Z",
"channel": "Mobile"
}, {
"amount": 40250,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:43:11.925Z",
"channel": "Web"
}]
}, {
"id": "5b83f48a431dd6001aed25f1",
"make": "FORD",
"model": "ECOSPORT",
"year": 2006,
"version": "2.0 XLT 16V GASOLINA 4P MANUAL",
"km": 141590,
"remainingTime": 457951,
"imageUrl": "https://uploads.instacarro.com/JPEG_20180827_1108595b83f48a431dd6001aed25f11215791050.jpg",
"bids": [{
"amount": 500,
"dealership": "Instacarro",
"createdAt": "2018-08-27T14:33:13.821Z",
"channel": "Web"
}]
}]<file_sep>import React, { Component } from 'react';
import './App.css';
import AuctionList from './auction-list.js';
import logo from './assets/logo.png';
import phone from './assets/phone.png';
import user from './assets/user.png';
class App extends Component {
render() {
return (
<div className="App">
<ul className="navigation">
<li> <img src={logo} /></li>
<li> <img src={phone} /></li>
<li> (11) 3569-3465</li>
<li> <img src={user} /><br/>User test</li>
</ul>
<AuctionList />
</div>
);
}
}
export default App;
<file_sep># This is an example of displaying a list of auctions. The example is build with react.js and the markup is pure flexbox. Is free of css frameworks.

# Here are some reference that use to guide me trough this simple demo.
# flexbox tutorials
https://internetingishard.com/html-and-css/flexbox/
https://css-tricks.com/snippets/css/a-guide-to-flexbox/
https://www.w3schools.com/css/css3_flexbox.asp#flex-wrap
# how to resolve the problem with background image
https://stackoverflow.com/questions/8195215/css-background-image-on-background-color
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Backgrounds_and_Borders/Scaling_background_images
# example flexbox putting a divider
https://stackoverflow.com/questions/42101096/flexbox-space-between-with-line-between-rows
# flux for dispatch. answer of Matt Styles
https://stackoverflow.com/questions/35537229/how-to-update-parents-state-in-react
|
43c9742e218a7ff02dc9166f61622725d49a2e6b
|
[
"JavaScript",
"Markdown"
] | 6
|
JavaScript
|
mota57/instacarro-example-react
|
867529f4e9d0eb29fa7913eecf0efaf4a5f4535d
|
18903bedb2c6bead872660c2acd5953c9d92eb6b
|
refs/heads/master
|
<repo_name>ghpravash/react-movie-search<file_sep>/src/Searchmovie.js
import React, { useState } from 'react';
import './index.css';
import Moviecard from './Moviecard';
import "./App.css";
// import ReactPaginate from 'react-paginate';
export default function Searchmovie() {
//Two states one for input query and another for displaying movie
//for input query
const [query, setQuery] = useState('startups');
//for movie
const [movies, setMovies] = useState([]);
const url = `https://api.themoviedb.org/3/search/movie?api_key=<KEY>&language=en-US&query=${query}`
const searchMovie = (e) => {
e.preventDefault();
fetch(url)
.then(res => res.json())
.then(data => {
setMovies(data.results);
})
.catch(error => console.error('Error', error));
};
return (
<>
<form className="form">
<label className="label" htmlFor="query">Movie Name:</label>
{/* value={query} connects input to useState */}
<input className="input" type="text" name="query" placeholder="i.e. ice age" onChange={(e) => setQuery(e.target.value)} />
<button className="button" type="submit" onClick={searchMovie}>Search</button>
</form>
<div className="card-list">
{
movies.filter((movie) => movie.poster_path).map((movie) => {
return (
<Moviecard movie={movie} key={movie.id} />
);
})
}
</div>
</>
);
}
|
f79466b6c845bbbcb489fcc8f2d9a848ffe57338
|
[
"JavaScript"
] | 1
|
JavaScript
|
ghpravash/react-movie-search
|
30d9fa1a7e1d5b6fa95eb28a01baeca6c82581b8
|
d8acb142fdffca89bcc93813e1a9415dea8da36a
|
refs/heads/master
|
<repo_name>RocketsFang/k8s_concepts<file_sep>/Dockerfile
### package a nodejs application to learn k8s concept
FROM vish/stress
###RUN apt-get install -y vim
<file_sep>/README.md
# k8s_concepts
used to package a nodejs application to learn k8s basic concepts
<file_sep>/k8s_concepts_db/container/preStop.sh
#!/bin/bash
# need pod to configure with volume
logFile=/opt/datastore/data/preStop.log
echo "The container[$(hostname)] preStop 'ExecAction' is starting ..." 1> $logFile
sigterm_handler() {
echo "Capture termination signal for preStop 'ExecAction', preStart shell will be terminated ..." 1>> $logFile
COUNTER=1
while [ true ]; do
echo "Time used to terminate - preStop shell: " $COUNTER " seconds..." 1>> $logFile
let COUNTER=$COUNTER+1
sleep 1
done
exit $?
}
##trap 'kill ${!}; sigterm_handler' SIGTERM
trap sigterm_handler SIGTERM
duration=20
WORK_COUNTER=1
while [ true ]; do
echo "Simulating works in preStop action duration[$duration] seconds: " $WORK_COUNTER " seconds..." 1>> $logFile
let WORK_COUNTER=$WORK_COUNTER+1
if [ $duration -le $WORK_COUNTER ]; then
echo "The works in preStop action is done ..." 1>> $logFile
break;
fi
sleep 1
done
echo "The container[$(hostname)] preStop 'ExecAction' is ending ..." 1>> $logFile<file_sep>/k8s_concepts_db/container/postStart.sh
#!/bin/bash
# need pod to configure with volume
logFile=/opt/datastore/data/postStart.log
echo "The container[$(hostname)] postStart 'ExecAction' is starting ..." 1> $logFile
sigterm_handler() {
echo "Capture termination signal for preStart 'ExecAction', postStart shell will be terminated ..." 1>> $logFile
COUNTER=1
while [ true ]; do
echo "Time used to terminate - postStart shell: " $COUNTER " seconds..." 1>> $logFile
let COUNTER=$COUNTER+1
sleep 1
done
exit $?
}
##trap 'kill ${!}; sigterm_handler' SIGTERM
trap sigterm_handler SIGTERM
duration=20
WORK_COUNTER=1
while [ true ]; do
echo "Simulating works in postStart action duration[$duration] seconds: " $WORK_COUNTER " seconds..." 1>> $logFile
let WORK_COUNTER=$WORK_COUNTER+1
if [ $duration -le $WORK_COUNTER ]; then
"The works in postStart action is done ..." 1>> $logFile
break;
fi
sleep 1
done
echo "The container[$(hostname)] postStart 'ExecAction' is ending ..." 1>> $logFile<file_sep>/k8s_concepts_db/generatedata.sh
#!/bin/bash
echo "The container[$(hostname)] is starting ..."
echo "Container[$(hostname)] host alias info ..."
cat /etc/hosts
data_file=$1
echo "Data file is: " $data_file
need_run_nodejs=$2
echo "Need nodejs: " $need_run_nodejs
sigterm_handler() {
echo "Capture termination signal, container[$(hostname)] will be terminated ..."
mv $data_file "$data_file"_$(date +"%F_%T")
COUNTER=1
while [ true ]; do
echo "Time used to terminate - $(hostname): " $COUNTER " seconds..."
let COUNTER=$COUNTER+1
sleep 1
done
exit $?
}
generate_data(){
COUNTER=1
echo "### this is the nodejs app file database" 1> $data_file
while [ true ]; do
echo "This is the " $COUNTER "th line." 1>> $data_file
let COUNTER=$COUNTER+1
sleep 5
done
}
if [ "$need_run_nodejs"x == "yes"x ]; then
nodejs /opt/k8s_concepts_nodejs/server/server.js &
fi
##trap 'kill ${!}; sigterm_handler' SIGTERM
trap sigterm_handler SIGTERM
generate_data
|
c74fd9891d1b0f04c03c9b5bc8e4d60b9ce8a716
|
[
"Markdown",
"Dockerfile",
"Shell"
] | 5
|
Dockerfile
|
RocketsFang/k8s_concepts
|
e025721760efed1e11d9ea4974f2d30b0367b39e
|
d1b9962af4f536ec9e91782fc52eb07fa8b34e4a
|
refs/heads/master
|
<file_sep># IMGD4000-SimpleAI
This is a simple unreal project built from scratch for presenting how to craft a simple AI character.
I created this project with vs code as default IDE, so if you are using vs code, you can copy all done, and it should work. If you are using different IDE, please copy the stuffs in "config", "contents", and "source" folder. These are the ones that mainly matters.
- /Source/Presentation/SampleCharacter.cpp (.h) Files for sample character
- Content
- AI: Simple AI controller + implementation
- AI_sample: undeleted folder for demo. no impact.
- Raccoon: character meshs/skeletons/anim/ etc
- RNG: Random Number Generator - A Blueprint Library Function
- Sample Level: Main Level for demo.
How to run:
Copy the files mentioned and copy them into your new project. *However*, due to some reasons I dont know, the sample level does not have a character in it. So you have to drag it in and set it by you own.
- Drag SampleCharacter from C++ directly into your scene
- click on the character, set parent (capsule component) scale to 5 5 2, then go to mesh, set its scale to 20 20 50
- click on character, go to details pane, search for "controller", set it to be SampleController
Then play, it should work.
<file_sep>// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/ObjectMacros.h"
#include "UObject/ScriptMacros.h"
PRAGMA_DISABLE_DEPRECATION_WARNINGS
#ifdef PRESENTATION_PresentationGameModeBase_generated_h
#error "PresentationGameModeBase.generated.h already included, missing '#pragma once' in PresentationGameModeBase.h"
#endif
#define PRESENTATION_PresentationGameModeBase_generated_h
#define Presentation_Source_Presentation_PresentationGameModeBase_h_15_SPARSE_DATA
#define Presentation_Source_Presentation_PresentationGameModeBase_h_15_RPC_WRAPPERS
#define Presentation_Source_Presentation_PresentationGameModeBase_h_15_RPC_WRAPPERS_NO_PURE_DECLS
#define Presentation_Source_Presentation_PresentationGameModeBase_h_15_INCLASS_NO_PURE_DECLS \
private: \
static void StaticRegisterNativesAPresentationGameModeBase(); \
friend struct Z_Construct_UClass_APresentationGameModeBase_Statics; \
public: \
DECLARE_CLASS(APresentationGameModeBase, AGameModeBase, COMPILED_IN_FLAGS(0 | CLASS_Transient | CLASS_Config), CASTCLASS_None, TEXT("/Script/Presentation"), NO_API) \
DECLARE_SERIALIZER(APresentationGameModeBase)
#define Presentation_Source_Presentation_PresentationGameModeBase_h_15_INCLASS \
private: \
static void StaticRegisterNativesAPresentationGameModeBase(); \
friend struct Z_Construct_UClass_APresentationGameModeBase_Statics; \
public: \
DECLARE_CLASS(APresentationGameModeBase, AGameModeBase, COMPILED_IN_FLAGS(0 | CLASS_Transient | CLASS_Config), CASTCLASS_None, TEXT("/Script/Presentation"), NO_API) \
DECLARE_SERIALIZER(APresentationGameModeBase)
#define Presentation_Source_Presentation_PresentationGameModeBase_h_15_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API APresentationGameModeBase(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(APresentationGameModeBase) \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, APresentationGameModeBase); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(APresentationGameModeBase); \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API APresentationGameModeBase(APresentationGameModeBase&&); \
NO_API APresentationGameModeBase(const APresentationGameModeBase&); \
public:
#define Presentation_Source_Presentation_PresentationGameModeBase_h_15_ENHANCED_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API APresentationGameModeBase(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : Super(ObjectInitializer) { }; \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API APresentationGameModeBase(APresentationGameModeBase&&); \
NO_API APresentationGameModeBase(const APresentationGameModeBase&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, APresentationGameModeBase); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(APresentationGameModeBase); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(APresentationGameModeBase)
#define Presentation_Source_Presentation_PresentationGameModeBase_h_15_PRIVATE_PROPERTY_OFFSET
#define Presentation_Source_Presentation_PresentationGameModeBase_h_12_PROLOG
#define Presentation_Source_Presentation_PresentationGameModeBase_h_15_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
Presentation_Source_Presentation_PresentationGameModeBase_h_15_PRIVATE_PROPERTY_OFFSET \
Presentation_Source_Presentation_PresentationGameModeBase_h_15_SPARSE_DATA \
Presentation_Source_Presentation_PresentationGameModeBase_h_15_RPC_WRAPPERS \
Presentation_Source_Presentation_PresentationGameModeBase_h_15_INCLASS \
Presentation_Source_Presentation_PresentationGameModeBase_h_15_STANDARD_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define Presentation_Source_Presentation_PresentationGameModeBase_h_15_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
Presentation_Source_Presentation_PresentationGameModeBase_h_15_PRIVATE_PROPERTY_OFFSET \
Presentation_Source_Presentation_PresentationGameModeBase_h_15_SPARSE_DATA \
Presentation_Source_Presentation_PresentationGameModeBase_h_15_RPC_WRAPPERS_NO_PURE_DECLS \
Presentation_Source_Presentation_PresentationGameModeBase_h_15_INCLASS_NO_PURE_DECLS \
Presentation_Source_Presentation_PresentationGameModeBase_h_15_ENHANCED_CONSTRUCTORS \
private: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
template<> PRESENTATION_API UClass* StaticClass<class APresentationGameModeBase>();
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID Presentation_Source_Presentation_PresentationGameModeBase_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
<file_sep>// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#include "Presentation.h"
#include "Modules/ModuleManager.h"
IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, Presentation, "Presentation" );
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "SampleCharacter.h"
// Sets default values
ASampleCharacter::ASampleCharacter(const FObjectInitializer& ObjectInitializer)
{
// Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
primaryAttackStarted = false;
// Mesh = CreateDefaultSubobject<UStaticMeshComponent>("Mesh");
static ConstructorHelpers::FObjectFinder<USkeletalMesh> MeshContainer(TEXT("SkeletalMesh'/Game/Raccoon/Base.Base'"));
if (MeshContainer.Succeeded()) {
GetMesh()->SetSkeletalMesh(MeshContainer.Object);
GetMesh()->SetRelativeLocation(FVector(0, 0, -87));
}
static ConstructorHelpers::FObjectFinder<UClass> AnimationBlueprint(TEXT("AnimBlueprint'/Game/Raccoon/SampleAnimBP.SampleAnimBP_C'"));
if (AnimationBlueprint.Object != NULL)
GetMesh()->AnimClass = AnimationBlueprint.Object;
}
// Called when the game starts or when spawned
void ASampleCharacter::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void ASampleCharacter::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
// Called to bind functionality to input
void ASampleCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
PlayerInputComponent->BindAction("PrimaryAttack", IE_Pressed, this, &ASampleCharacter::PrimaryAttack);
PlayerInputComponent->BindAxis("MoveForward", this, &ASampleCharacter::MovingForward);
}
void ASampleCharacter::PrimaryAttack() {
if (primaryAttackStarted == true) return;
primaryAttackStarted = true;
UE_LOG(LogTemp, Warning, TEXT("Primary Attacked"));
GetWorld()->GetTimerManager().SetTimer(PrimaryAttackTimeHandle, this, &ASampleCharacter::stopPrimaryAttack, 0.2f);
}
void ASampleCharacter::stopPrimaryAttack() {
primaryAttackStarted = false;
UE_LOG(LogTemp, Warning, TEXT("Stopped Primary Attack"));
}
void ASampleCharacter::MovingForward(float Amount) {
AddMovementInput(GetActorForwardVector(), Amount);
}<file_sep>
[/Script/EngineSettings.GeneralProjectSettings]
ProjectID=26EB76C7442D511162F2998695B1CC0E
<file_sep>// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/GeneratedCppIncludes.h"
#include "Presentation/SampleCharacter.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeSampleCharacter() {}
// Cross Module References
PRESENTATION_API UClass* Z_Construct_UClass_ASampleCharacter_NoRegister();
PRESENTATION_API UClass* Z_Construct_UClass_ASampleCharacter();
ENGINE_API UClass* Z_Construct_UClass_ACharacter();
UPackage* Z_Construct_UPackage__Script_Presentation();
PRESENTATION_API UFunction* Z_Construct_UFunction_ASampleCharacter_MovingForward();
PRESENTATION_API UFunction* Z_Construct_UFunction_ASampleCharacter_PrimaryAttack();
PRESENTATION_API UFunction* Z_Construct_UFunction_ASampleCharacter_stopPrimaryAttack();
// End Cross Module References
void ASampleCharacter::StaticRegisterNativesASampleCharacter()
{
UClass* Class = ASampleCharacter::StaticClass();
static const FNameNativePtrPair Funcs[] = {
{ "MovingForward", &ASampleCharacter::execMovingForward },
{ "PrimaryAttack", &ASampleCharacter::execPrimaryAttack },
{ "stopPrimaryAttack", &ASampleCharacter::execstopPrimaryAttack },
};
FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, UE_ARRAY_COUNT(Funcs));
}
struct Z_Construct_UFunction_ASampleCharacter_MovingForward_Statics
{
struct SampleCharacter_eventMovingForward_Parms
{
float Amount;
};
static const UE4CodeGen_Private::FFloatPropertyParams NewProp_Amount;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_ASampleCharacter_MovingForward_Statics::NewProp_Amount = { "Amount", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(SampleCharacter_eventMovingForward_Parms, Amount), METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_ASampleCharacter_MovingForward_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_ASampleCharacter_MovingForward_Statics::NewProp_Amount,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_ASampleCharacter_MovingForward_Statics::Function_MetaDataParams[] = {
{ "Category", "Raccoon Actions" },
{ "ModuleRelativePath", "SampleCharacter.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_ASampleCharacter_MovingForward_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_ASampleCharacter, nullptr, "MovingForward", nullptr, nullptr, sizeof(SampleCharacter_eventMovingForward_Parms), Z_Construct_UFunction_ASampleCharacter_MovingForward_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_ASampleCharacter_MovingForward_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_ASampleCharacter_MovingForward_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_ASampleCharacter_MovingForward_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_ASampleCharacter_MovingForward()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_ASampleCharacter_MovingForward_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_ASampleCharacter_PrimaryAttack_Statics
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_ASampleCharacter_PrimaryAttack_Statics::Function_MetaDataParams[] = {
{ "Category", "Raccoon Actions" },
{ "ModuleRelativePath", "SampleCharacter.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_ASampleCharacter_PrimaryAttack_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_ASampleCharacter, nullptr, "PrimaryAttack", nullptr, nullptr, 0, nullptr, 0, RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_ASampleCharacter_PrimaryAttack_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_ASampleCharacter_PrimaryAttack_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_ASampleCharacter_PrimaryAttack()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_ASampleCharacter_PrimaryAttack_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_ASampleCharacter_stopPrimaryAttack_Statics
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_ASampleCharacter_stopPrimaryAttack_Statics::Function_MetaDataParams[] = {
{ "Category", "Raccoon Actions" },
{ "ModuleRelativePath", "SampleCharacter.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_ASampleCharacter_stopPrimaryAttack_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_ASampleCharacter, nullptr, "stopPrimaryAttack", nullptr, nullptr, 0, nullptr, 0, RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_ASampleCharacter_stopPrimaryAttack_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_ASampleCharacter_stopPrimaryAttack_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_ASampleCharacter_stopPrimaryAttack()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_ASampleCharacter_stopPrimaryAttack_Statics::FuncParams);
}
return ReturnFunction;
}
UClass* Z_Construct_UClass_ASampleCharacter_NoRegister()
{
return ASampleCharacter::StaticClass();
}
struct Z_Construct_UClass_ASampleCharacter_Statics
{
static UObject* (*const DependentSingletons[])();
static const FClassFunctionLinkInfo FuncInfo[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[];
#endif
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_primaryAttackStarted_MetaData[];
#endif
static void NewProp_primaryAttackStarted_SetBit(void* Obj);
static const UE4CodeGen_Private::FBoolPropertyParams NewProp_primaryAttackStarted;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo;
static const UE4CodeGen_Private::FClassParams ClassParams;
};
UObject* (*const Z_Construct_UClass_ASampleCharacter_Statics::DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_ACharacter,
(UObject* (*)())Z_Construct_UPackage__Script_Presentation,
};
const FClassFunctionLinkInfo Z_Construct_UClass_ASampleCharacter_Statics::FuncInfo[] = {
{ &Z_Construct_UFunction_ASampleCharacter_MovingForward, "MovingForward" }, // 2290105487
{ &Z_Construct_UFunction_ASampleCharacter_PrimaryAttack, "PrimaryAttack" }, // 1529069095
{ &Z_Construct_UFunction_ASampleCharacter_stopPrimaryAttack, "stopPrimaryAttack" }, // 2026181547
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ASampleCharacter_Statics::Class_MetaDataParams[] = {
{ "HideCategories", "Navigation" },
{ "IncludePath", "SampleCharacter.h" },
{ "ModuleRelativePath", "SampleCharacter.h" },
{ "ObjectInitializerConstructorDeclared", "" },
};
#endif
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ASampleCharacter_Statics::NewProp_primaryAttackStarted_MetaData[] = {
{ "Category", "SampleCharacter" },
{ "ModuleRelativePath", "SampleCharacter.h" },
};
#endif
void Z_Construct_UClass_ASampleCharacter_Statics::NewProp_primaryAttackStarted_SetBit(void* Obj)
{
((ASampleCharacter*)Obj)->primaryAttackStarted = 1;
}
const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_ASampleCharacter_Statics::NewProp_primaryAttackStarted = { "primaryAttackStarted", nullptr, (EPropertyFlags)0x0010000000000004, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(ASampleCharacter), &Z_Construct_UClass_ASampleCharacter_Statics::NewProp_primaryAttackStarted_SetBit, METADATA_PARAMS(Z_Construct_UClass_ASampleCharacter_Statics::NewProp_primaryAttackStarted_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_ASampleCharacter_Statics::NewProp_primaryAttackStarted_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_ASampleCharacter_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_ASampleCharacter_Statics::NewProp_primaryAttackStarted,
};
const FCppClassTypeInfoStatic Z_Construct_UClass_ASampleCharacter_Statics::StaticCppClassTypeInfo = {
TCppClassTypeTraits<ASampleCharacter>::IsAbstract,
};
const UE4CodeGen_Private::FClassParams Z_Construct_UClass_ASampleCharacter_Statics::ClassParams = {
&ASampleCharacter::StaticClass,
"Game",
&StaticCppClassTypeInfo,
DependentSingletons,
FuncInfo,
Z_Construct_UClass_ASampleCharacter_Statics::PropPointers,
nullptr,
UE_ARRAY_COUNT(DependentSingletons),
UE_ARRAY_COUNT(FuncInfo),
UE_ARRAY_COUNT(Z_Construct_UClass_ASampleCharacter_Statics::PropPointers),
0,
0x009000A4u,
METADATA_PARAMS(Z_Construct_UClass_ASampleCharacter_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_ASampleCharacter_Statics::Class_MetaDataParams))
};
UClass* Z_Construct_UClass_ASampleCharacter()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_ASampleCharacter_Statics::ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(ASampleCharacter, 2647182466);
template<> PRESENTATION_API UClass* StaticClass<ASampleCharacter>()
{
return ASampleCharacter::StaticClass();
}
static FCompiledInDefer Z_CompiledInDefer_UClass_ASampleCharacter(Z_Construct_UClass_ASampleCharacter, &ASampleCharacter::StaticClass, TEXT("/Script/Presentation"), TEXT("ASampleCharacter"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(ASampleCharacter);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
<file_sep>// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/ObjectMacros.h"
#include "UObject/ScriptMacros.h"
PRAGMA_DISABLE_DEPRECATION_WARNINGS
#ifdef PRESENTATION_SampleCharacter_generated_h
#error "SampleCharacter.generated.h already included, missing '#pragma once' in SampleCharacter.h"
#endif
#define PRESENTATION_SampleCharacter_generated_h
#define Presentation_Source_Presentation_SampleCharacter_h_12_SPARSE_DATA
#define Presentation_Source_Presentation_SampleCharacter_h_12_RPC_WRAPPERS \
\
DECLARE_FUNCTION(execMovingForward) \
{ \
P_GET_PROPERTY(UFloatProperty,Z_Param_Amount); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->MovingForward(Z_Param_Amount); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execPrimaryAttack) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->PrimaryAttack(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execstopPrimaryAttack) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->stopPrimaryAttack(); \
P_NATIVE_END; \
}
#define Presentation_Source_Presentation_SampleCharacter_h_12_RPC_WRAPPERS_NO_PURE_DECLS \
\
DECLARE_FUNCTION(execMovingForward) \
{ \
P_GET_PROPERTY(UFloatProperty,Z_Param_Amount); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->MovingForward(Z_Param_Amount); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execPrimaryAttack) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->PrimaryAttack(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execstopPrimaryAttack) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->stopPrimaryAttack(); \
P_NATIVE_END; \
}
#define Presentation_Source_Presentation_SampleCharacter_h_12_INCLASS_NO_PURE_DECLS \
private: \
static void StaticRegisterNativesASampleCharacter(); \
friend struct Z_Construct_UClass_ASampleCharacter_Statics; \
public: \
DECLARE_CLASS(ASampleCharacter, ACharacter, COMPILED_IN_FLAGS(0 | CLASS_Config), CASTCLASS_None, TEXT("/Script/Presentation"), NO_API) \
DECLARE_SERIALIZER(ASampleCharacter)
#define Presentation_Source_Presentation_SampleCharacter_h_12_INCLASS \
private: \
static void StaticRegisterNativesASampleCharacter(); \
friend struct Z_Construct_UClass_ASampleCharacter_Statics; \
public: \
DECLARE_CLASS(ASampleCharacter, ACharacter, COMPILED_IN_FLAGS(0 | CLASS_Config), CASTCLASS_None, TEXT("/Script/Presentation"), NO_API) \
DECLARE_SERIALIZER(ASampleCharacter)
#define Presentation_Source_Presentation_SampleCharacter_h_12_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API ASampleCharacter(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(ASampleCharacter) \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, ASampleCharacter); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ASampleCharacter); \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API ASampleCharacter(ASampleCharacter&&); \
NO_API ASampleCharacter(const ASampleCharacter&); \
public:
#define Presentation_Source_Presentation_SampleCharacter_h_12_ENHANCED_CONSTRUCTORS \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API ASampleCharacter(ASampleCharacter&&); \
NO_API ASampleCharacter(const ASampleCharacter&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, ASampleCharacter); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ASampleCharacter); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(ASampleCharacter)
#define Presentation_Source_Presentation_SampleCharacter_h_12_PRIVATE_PROPERTY_OFFSET
#define Presentation_Source_Presentation_SampleCharacter_h_9_PROLOG
#define Presentation_Source_Presentation_SampleCharacter_h_12_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
Presentation_Source_Presentation_SampleCharacter_h_12_PRIVATE_PROPERTY_OFFSET \
Presentation_Source_Presentation_SampleCharacter_h_12_SPARSE_DATA \
Presentation_Source_Presentation_SampleCharacter_h_12_RPC_WRAPPERS \
Presentation_Source_Presentation_SampleCharacter_h_12_INCLASS \
Presentation_Source_Presentation_SampleCharacter_h_12_STANDARD_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define Presentation_Source_Presentation_SampleCharacter_h_12_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
Presentation_Source_Presentation_SampleCharacter_h_12_PRIVATE_PROPERTY_OFFSET \
Presentation_Source_Presentation_SampleCharacter_h_12_SPARSE_DATA \
Presentation_Source_Presentation_SampleCharacter_h_12_RPC_WRAPPERS_NO_PURE_DECLS \
Presentation_Source_Presentation_SampleCharacter_h_12_INCLASS_NO_PURE_DECLS \
Presentation_Source_Presentation_SampleCharacter_h_12_ENHANCED_CONSTRUCTORS \
private: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
template<> PRESENTATION_API UClass* StaticClass<class ASampleCharacter>();
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID Presentation_Source_Presentation_SampleCharacter_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
|
02e284db6939b8c0f75a71e9b3be986165a2c44c
|
[
"Markdown",
"C++",
"INI"
] | 7
|
Markdown
|
wDANDANw/IMGD4000-SimpleAI
|
5ae85d9ea7bda8c649e71fd4326ac2bb375bf0b4
|
0b1beeee2e791ddf6264de2a94969cbc8b721932
|
refs/heads/master
|
<file_sep># debugging_practice
Deliberately broken code for learning to debug.
<file_sep>def quick_sort(numbers):
quick_sort_helper(numbers, 0, len(numbers)-1)
def quick_sort_helper(numbers, first, last):
if first<last:
splitpoint = partition(numbers, first, last)
quick_sort_helper(numbers, first, splitpoint-1)
quick_sort_helper(numbers, splitpoint+1, last)
def partition(numbers, first, last):
pivotvalue = numbers[first]
leftmark = first+1
rightmark = last
done = False
while not done:
while leftmark <= rightmark and numbers[leftmark] <= pivotvalue:
leftmark = rightmark + 1
while numbers[rightmark] >= pivotvalue and rightmark >= leftmark:
rightmark = leftmark -1
if rightmark < leftmark -1:
done = True
else:
temp = numbers[leftmark]
numbers[leftmark] = numbers[rightmark]
numbers[rightmark] = temp
temp = numbers[first]
numbers[first] = numbers[rightmark]
numbers[rightmark] = temp
return rightmark
numbers = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print("Before Sort: {}".format(numbers))
quick_sort(numbers)
print("After Sort: {}".format(numbers))
|
fb78e9de6265571c1a1043de6d17862867e4b3ad
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
xpgrind/debugging_practice
|
a218ff9b80e1d73c99a2f8a0d7cfb707424e5c09
|
4faf2b027d0d3496d95377fa31105f2e96e8d13b
|
refs/heads/master
|
<file_sep>class GrepnetStorage {
static save(name, item) {
try {
localStorage.setItem(name, JSON.stringify(item));
} catch (ignore) {
// Do nothing
}
}
static load(name) {
let item = null;
try {
item = JSON.parse(localStorage.getItem(name));
} catch (ignore) {
// Do nothing
}
return item;
}
}
export default () => GrepnetStorage;
<file_sep>#  grepnet-client-www
> Display notification popup when web page is update and grepnet match passed phrase.
## Usage
Add task is simple.
1. Put task name.
2. Put URL to scan.
3. Put phrase to search.
4. Put interval time.
When checker match phrase you will get notification on your desktop.
## Developer Setup
```
npm install
npx bower install
npm start
```
## License
[The MIT License](http://piecioshka.mit-license.org)
<file_sep>const MILLISECONDS_IN_SECOND = 1000;
class Controller {
$http = null;
$scope = null;
$interval = null;
notification = null;
storage = null;
tasks = null;
countdownInterval = null;
grepInterval = null;
/* @ngInject */
constructor(
$http,
$scope,
$state,
$interval,
notification,
storage,
tasks
) {
this.$http = $http;
this.$scope = $scope;
this.$interval = $interval;
this.notification = notification;
this.storage = storage;
this.tasks = tasks;
$scope.pause = () => {
this.stopCountdown();
$scope.task.state = "paused";
this._save();
};
$scope.start = () => {
this.startCountdown();
$scope.task.state = "started";
this._save();
};
$scope.edit = () => {
this.stopCountdown();
$state.go("edit-task", {
index: $scope.$index,
});
};
$scope.remove = () => {
this.stopCountdown();
tasks.remove($scope.$index);
};
$scope.check = () => {
this.startGrepping();
};
$scope.is = (state) => {
return $scope.task.state === state;
};
this._tryStartCountdown();
}
_tryStartCountdown() {
if (this.$scope.is("new")) {
this.startCountdown();
this.$scope.task.state = "started";
this._save();
}
}
_save() {
this.storage.save("grepnet-tasks", this.tasks.getAll());
}
stopCountdown() {
this.$interval.cancel(this.countdownInterval);
this.countdownInterval = null;
this.$interval.cancel(this.grepInterval);
this.grepInterval = null;
}
resetCountdown() {
this.$scope.task.countdown = this.$scope.task.delay;
}
grep(url, phrase) {
const host = window.location.hostname;
const options = { url, phrase };
const fullUrl = `http://${host}:3000`;
console.log("make a request", fullUrl);
return this.$http.post(fullUrl, options).then((response) => {
return {
status: Boolean(response.data.status),
};
});
}
startGrepping() {
this.$scope.task.state = "grepping";
this.grep(this.$scope.task.url, this.$scope.task.phrase).then(
(response) => {
this.resetCountdown();
if (response.status) {
this.stopCountdown();
this.$scope.task.state = "completed";
this.notification.spawn(
this.$scope.task.title,
this.$scope.task.url
);
} else {
this.$scope.task.state = "started";
}
this._save();
},
() => {
this.resetCountdown();
this.$scope.task.state = "error";
}
);
}
startCountdown() {
this.resetCountdown();
this.countdownInterval = this.$interval(() => {
this.$scope.task.countdown--;
}, MILLISECONDS_IN_SECOND);
this.grepInterval = this.$interval(
() => this.startGrepping(),
this.$scope.task.delay * MILLISECONDS_IN_SECOND
);
}
}
export default () => {
return {
restrict: "E",
templateUrl: "scripts/directives/TaskCard.html",
controller: Controller,
};
};
<file_sep>const RequireObjectCoercible = O => {
if (O === null || typeof O === 'undefined') {
throw new TypeError('"this" value must not be null or undefined');
}
return O;
};
const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1;
const ToLength = argument => {
const len = Number(argument);
if (Number.isNaN(len) || len <= 0) { return 0; }
if (len > MAX_SAFE_INTEGER) { return MAX_SAFE_INTEGER; }
return len;
};
if (!String.prototype.padLeft) {
String.prototype.padLeft = function padLeft(maxLength, fillString = ' ') {
const O = RequireObjectCoercible(this);
const S = String(O);
const intMaxLength = ToLength(maxLength);
const stringLength = ToLength(S.length);
if (intMaxLength <= stringLength) { return S; }
let fillStr = typeof fillString === 'undefined' ? '' : String(fillString);
if (fillStr === '') { fillStr = ' '; }
const fillLen = intMaxLength - stringLength;
let stringFiller = '';
while (stringFiller.length < fillLen) {
stringFiller += fillStr;
}
return stringFiller.slice(0, fillLen) + S;
};
}
if (!String.prototype.padRight) {
String.prototype.padRight = function padRight(maxLength, fillString = ' ') {
const O = RequireObjectCoercible(this);
const S = String(O);
const intMaxLength = ToLength(maxLength);
const stringLength = ToLength(S.length);
if (intMaxLength <= stringLength) { return S; }
let fillStr = typeof fillString === 'undefined' ? '' : String(fillString);
if (fillStr === '') { fillStr = ' '; }
const fillLen = intMaxLength - stringLength;
let stringFiller = '';
while (stringFiller.length < fillLen) {
stringFiller += fillStr;
}
return S + stringFiller.slice(0, fillLen);
};
}
|
874d70b6bc1140543a053511145cfbe13959feb1
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
webtest-pl/grepnet-client-www
|
3f1740f3c3312ef5a0487244027b38b9682cb2d7
|
08ad894b29e0e454ebf3ea4108314155bff3c56e
|
refs/heads/master
|
<repo_name>leonidas/lunch-menus<file_sep>/Gemfile
source "http://rubygems.org"
gem 'rest-client'
gem 'nokogiri'
gem 'tidy_ffi'
gem 'activesupport'
gem 'rspec', :require => 'spec'
<file_sep>/spec/flowdock_spec.rb
require './lib/flowdock'
describe 'Flowdock#send_to_inbox' do
before(:each) do
@flowdock = Flowdock.new("deadbeef")
end
it 'delivers a message to flow inbox' do
message = {
foobar: "Foobar",
barbar: "Barbar"
}
RestClient.should_receive(:post).with(
'https://api.flowdock.com/v1/messages/team_inbox/deadbeef',
'{"foobar":"Foobar","barbar":"Barbar"}',
:content_type => :json
)
@flowdock.send_to_inbox(message)
end
end
<file_sep>/lib/menu_formatter.rb
# encoding: UTF-8
module MenuFormatter
def self.create_message(restaurants)
{
source: "Lounasbotti",
from_address: "<EMAIL>",
subject: "Lounaslistat",
tags: ["#lunch"],
content: self.content(restaurants)
}
end
def self.content(restaurants)
restaurants_with_menus, restaurants_without_menus =
restaurants.partition { |r| r.menu }
html = restaurants_with_menus.map { |r|
"<h1><a href=\"#{r.url}\">#{r.name}</a></h1><div>#{r.menu}</div>"
}.join
unless restaurants_without_menus.empty?
html += "<h1>Puuttuvat lounaslistat</h1>"
html += "<p>Näistä ravintoloista ei saatu kaivettua tämän päivän lounaslistoja:</p>"
html += "<ul>"
html += restaurants_without_menus.map { |r|
"<li><a href=\"#{r.url}\">#{r.name}</a></li>"
}.join
html += "</ul>"
end
html
end
end
<file_sep>/spec/spec_helper.rb
require 'tidy_ffi'
def scrape_data(file)
path = File.join(File.dirname(__FILE__), 'scrape_data', file)
File.read(path)
end
def tidy(html)
TidyFFI::Tidy.new(html,
:indent => 0, :wrap => 0, :char_encoding => "utf8", :clean => 0
).clean
end
RSpec::Matchers.define :equal_html do |expected|
match do |actual|
@diffable = true
@actual = tidy(actual)
@expected = tidy(expected)
@actual == @expected
end
end
<file_sep>/lib/flowdock.rb
require 'json'
require 'rest-client'
class Flowdock
API_URL = "https://api.flowdock.com/v1/messages/team_inbox/"
def initialize(flow_token)
@flow_token = flow_token
end
def send_to_inbox(message)
RestClient.post(API_URL + @flow_token, message.to_json, :content_type => :json)
end
end
<file_sep>/lib/restaurants.rb
# encoding: UTF-8
require 'date'
require 'nokogiri'
require 'rest-client'
module RestaurantList
def self.all
[
Restaurant4VA,
RestaurantComo,
RestaurantArtturi,
RestaurantAmericanDiner,
RestaurantTivoli,
RestaurantTillikka
].map(&:new)
end
end
class RestaurantBase
def menu
begin
html = fetch(sources)
parse(html)
rescue Exception
nil
end
end
def sources
[url]
end
private
def fetch(urls)
urls.map { |url| RestClient.get(url) }.join
end
def parse(html)
nil
end
end
class Restaurant4VA < RestaurantBase
def name
'<NAME>'
end
def url
'http://www.4vuodenaikaa.fi/fi/paivanmenu'
end
private
def parse(html)
menu = Nokogiri::HTML(html).css(".art-article")
if menu.css("h2").text.include?(Date.today.day.to_s)
menu.inner_html
else
nil
end
end
end
class RestaurantComo < RestaurantBase
def name
'Como'
end
def url
'http://www.ravintola.fi/como/lounas/1'
end
private
def parse(html)
text_content = Nokogiri::HTML(html).css(".text-content p")
this_day = text_content.drop_while { |n|
!n.text.include?(today)
}.take_while { |n|
!n.text.include?(tomorrow)
}.map(&:to_s).join
if this_day.empty?
nil
else
this_day
end
end
def today
Date.today.strftime("%d.%m.%Y")
end
def tomorrow
(Date.today + 1).strftime("%d.%m.%Y")
end
end
class RestaurantAmericanDiner < RestaurantBase
def name
'American Diner'
end
def url
'http://www.diner.fi/lounas_finlayson.php'
end
private
def parse(html)
content = Nokogiri::HTML(html).css("table.laatikkoiso td")
content.detect { |e| e.text.include? today }.inner_html
end
def today
Date.today.strftime("%d.%m.%Y")
end
end
class RestaurantArtturi < RestaurantBase
def name
"Artturi"
end
def url
'http://www.ravintola-artturi.com/sivut/lounaslistat.html'
end
def sources
[
'http://www.ravintola-artturi.com/sivut/lounas_1.html',
'http://www.ravintola-artturi.com/sivut/lounas_2.html',
'http://www.ravintola-artturi.com/sivut/lounas_3.html',
'http://www.ravintola-artturi.com/sivut/lounas_4.html'
]
end
private
def parse(html)
weeks_content = Nokogiri::HTML(html).css("table").detect { |e|
match = /(\d+, ){10,}\d+/.match(e.text)
match[0].split(', ').include?(this_week)
}
weeks_content.css("tr").detect { |e|
e.text.include?(this_weekday)
}.css("td")[1].inner_html
end
def this_week
Date.today.strftime("%-V")
end
def this_weekday
%w(Sunnuntai Maanantai Tiistai Keskiviikko Torstai Perjantai Lauantai)[
Date.today.strftime("%w").to_i
]
end
end
class RestaurantTillikka < RestaurantBase
def name
"Tillikka"
end
def url
"http://kippis.fi/ravintola/tillikka"
end
private
def parse(html)
content = Nokogiri::HTML(html).css("#info-left")
this_day = content.children.drop_while { |n|
!n.text.include?(today)
}.take_while { |n|
!n.text.include?(tomorrow)
}.map(&:to_s).join
if this_day.empty?
nil
else
this_day
end
end
def today
Date.today.strftime("%d.%m.%Y")
end
def tomorrow
(Date.today + 1).strftime("%d.%m.%Y")
end
end
class RestaurantTivoli < RestaurantBase
def name
"Tivoli"
end
def url
"http://www.tivolibar.fi/lounas.php"
end
private
def parse(html)
utf_html = html.encode("UTF-8", "windows-1252")
content = Nokogiri::HTML(utf_html).css("td.tyyli3")
this_day = content.children.drop_while { |n|
!include_any?(n.text, possible_today_strings)
}.take_while { |n|
!include_any?(n.text, possible_tomorrow_strings)
}.map(&:to_s).join
if this_day.empty?
nil
else
this_day
end
end
def include_any?(includer, includee)
includee.any? { |string| includer.include?(string) }
end
def possible_today_strings
possible_date_formats.map { |format| Date.today.strftime(format)}
end
def possible_tomorrow_strings
possible_date_formats.map { |format| (Date.today + 1).strftime(format)}
end
def possible_date_formats
["%d.%m", "%d.%-m"]
end
end
<file_sep>/spec/lunch_menus_spec.rb
require './lib/lunch_menus'
describe LunchMenus, "#run" do
it 'Formats all restaurant menus, and sends them to Flowdock inbox' do
RestaurantList.stub(:all => :list_of_restaurants)
MenuFormatter.
should_receive(:create_message).
with(:list_of_restaurants).
and_return(:message)
Flowdock.should_receive(:new).
with("deadbeef").
and_return(@flowdock = mock("flowdock"))
@flowdock.
should_receive(:send_to_inbox).
with(:message)
LunchMenus.run("deadbeef")
end
end
describe LunchMenus, "#test-run" do
it 'Formats all restaurant menus, and prints them to console' do
RestaurantList.stub(:all => :list_of_restaurants)
MenuFormatter.
should_receive(:create_message).
with(:list_of_restaurants).
and_return(:message)
ConsoleOutput.should_receive(:print).with(:message)
LunchMenus.test_run
end
end
<file_sep>/lib/console_output.rb
require 'pp'
module ConsoleOutput
def self.print(message)
pp message
File.open("lunch-menus-test-output.html", "w") { |f|
f.write message[:content]
}
system "open lunch-menus-test-output.html"
end
end<file_sep>/README.md
Lunch-menus scrapes lunch menus from the web pages of a few Tampere restaurants and updates them to Flowdock team inbox.
## Installation
Lunch-menus requires Ruby 1.9.
git clone <EMAIL>:leonidas/lunch-menus.git
cd lunch-menus
gem install bundler
bundle install
## Usage
bundle exec bin/lunch-menus FLOW_TOKEN
where FLOW_TOKEN is the API token of the flow you want the lunch menus sent to. You can view your flow API tokens at https://www.flowdock.com/account/tokens.
## Supported restaurants
See lib/restaurants.rb and spec/restaurants_spec.rb for supported restaurants.<file_sep>/spec/restaurants_spec.rb
# encoding: UTF-8
require_relative 'spec_helper'
require './lib/restaurants'
describe 'Restaurant menu' do
class TestRestaurant < RestaurantBase
private
def name; "TestRestaurant"; end
def url; 'http://google.com'; end
def parse(html); raise "foobar" end
end
it 'should be nil if URL cannot be fetched' do
RestClient.stub(:get).and_raise
TestRestaurant.new.menu.should be_nil
end
it 'should be nil if HTML cannot be parsed' do
RestClient.stub(:get).and_return("<html></html>")
TestRestaurant.new.menu.should be_nil
end
end
describe 'Como menu' do
it "is empty if it doesn't contain the menu for today" do
RestClient.stub(:get => scrape_data("como.html"))
Date.stub(:today => Date.parse("2012-02-20"))
RestaurantComo.new.menu.should be_nil
end
it 'is formatted nicely' do
RestClient.stub(:get => scrape_data("como.html"))
Date.stub(:today => Date.parse("2012-02-13"))
RestaurantComo.new.menu.should equal_html('
<p><b>Maanantai 13.02.2012</b><br>
</p>
<p><NAME> COMO- Comon lounas</p>
<p>Lounas tarjoillaan ma-pe klo 11-14. Lounaan hintaan sisältyy tuoretta Bruschetta -leipää, Grisseenejä, oliivi-yrttitahnaa ja antipasteja, sekä kahvi ja vesi.</p>
<p>Comon lounas 9,20€</p>
<p>
1. Gorgonzolajuusto-bruschetta, vihersalaatteja, kirsikkatomaatteja, marinoituja oliiveja ja yrttivinegretteä<br>
2. Kana-kirsikkatomaattikastiketta ja tuoretta oreganoa sekä pastaa<br>
3. Marinoituja katkarapuja ja kasvisrisottoa<br>
4. Salami-kasvispizzaleipä, tomaattibasilikakastiketta</p>
<p>5. Pariloitua porsaanfileepihvi, punaviinikastiketta, tikkuperunoita ja paahdettuja juureksia 14,90</p>
<p>MENU DEL GIORNO <br>
24,90 €</p>
<p>Antipasti<br>
Italialaisia antipasteja: ilmakuivattua kinkkua, salamia, juustoa ja grillattuja kasviksia</p>
<p>Secondi Piatti<br>
Päivän tuoretta kalaa, kasvisrisottoa, oliiviöljyä ja sitruunaa sekä rucola-kirsikkatomaattisalaattia<br>
tai<br>
Paahdettua maissikananrintaa, marsalakastiketta sekä paahdettuja kasviksia ja rosmariiniperunoita</p>
<p>Dolci
<br>
italialaista jäätelöä ja marjoja</p>
<p> </p><p></p>
')
end
end
describe 'Neljä vuodenaikaa menu' do
it "is empty if it doesn't contain the menu for today" do
RestClient.stub(:get => scrape_data("4va.html"))
Date.stub(:today => Date.parse("2012-02-19"))
Restaurant4VA.new.menu.should be_nil
end
it 'is formatted nicely' do
RestClient.stub(:get => scrape_data("4va.html"))
Date.stub(:today => Date.parse("2012-02-18"))
Restaurant4VA.new.menu.should equal_html('
<h2>Lauantai 18 Helmikuuta 2012.</h2>
<p>Kuhaa & Hummeria. 19.50€.</p>
<p>Talon blini kahdella mädillä. 17,90 €.</p>
<p>Mustajuurikeittoa ja kylmäsavulohileipä. 8,90€.</p>
<p>Päivän juusto : Manchego (Espanijalainen lampaanmaitojuusto). 2,80€.</p>
<p><strong>JÄLKIRUOKA: </strong>Tarte Tatin ja Vaniljajäätelöä. 5,80€.</p>
<p><strong>FoodIsArt</strong> <strong>Menu:</strong> Blinit, kuhaa ja hummeria, Café ja 12 cl Cava Ilopart 39,00€ (Ilman viiniä 33,00€)</p>
<p> </p>
')
end
end
describe 'American diner menu' do
it 'is formatted nicely' do
RestClient.stub(:get => scrape_data("american_diner.html"))
Date.stub(:today => Date.parse("2012-02-13"))
RestaurantAmericanDiner.new.menu.should equal_html('
<table border="0" bgcolor="white" width="100%" class="laatikkoiso"><tr><td></td></tr></table><br>
<font color="black"><b><u>MAANANTAI 13.02.2012</u></b></font><br>
<b>Feta- ananassalaatti</b> 7,90 € <small> g ilman leipää</small><br>
- vihersalaattia,kurkkua,tomaattia ja paprikaa<br>
- talon yrttikastiketta<br>
<small>**********</small><br>
<b>Valkosipuliburger</b> 8,00 €<small> vl </small><br>
- emmentaljuustoa ja valkosipulia<br>
- ranskalaiset<br>
<small>**********</small><br>
<b>Savujuusto- pekonibroileria</b> 8,40 €<small> vl g </small><br>
- salsakastike<br>
- lohkoperunat<br>
<small>**********</small><br>
<b>Possunpihvi</b> 9,00 €<small> vl g </small><br>
- dijonsinappikastiketta<br>
- ranskalaiset<br>
<br>
')
end
end
describe 'Artturi menu' do
it 'is formatted nicely' do
RestClient.stub(:get).and_return(
scrape_data("artturi1.html"),
scrape_data("artturi2.html"),
scrape_data("artturi3.html"),
scrape_data("artturi4.html")
)
Date.stub(:today => Date.parse("2012-02-13"))
RestaurantArtturi.new.menu.should equal_html('
<font face="Arial,Helvetica,Geneva,Swiss,SunSans-Regular">SIENI-PEKONIKEITTO<br></font><font face="Arial,Helvetica,Geneva,Swiss,SunSans-Regular" size="1"><i>vähälaktoosinen, gluteeniton</i></font><font face="Arial,Helvetica,Geneva,Swiss,SunSans-Regular"><br>
LASAGNE<br></font><font face="Arial,Helvetica,Geneva,Swiss,SunSans-Regular" size="1"><i>vähälaktoosinen</i></font><font face="Arial,Helvetica,Geneva,Swiss,SunSans-Regular"><br>
PUNAJUURIPIHVIT<br></font><font face="Arial,Helvetica,Geneva,Swiss,SunSans-Regular" size="1"><i>laktoositon</i></font><font face="Arial,Helvetica,Geneva,Swiss,SunSans-Regular"><br>
PAISTETTUA PANGASIUSTA<br></font><font face="Arial,Helvetica,Geneva,Swiss,SunSans-Regular" size="1"><i>vähälaktoosinen</i></font><font face="Arial,Helvetica,Geneva,Swiss,SunSans-Regular"><br>
HÄRÄNPIHVI<br></font><font face="Arial,Helvetica,Geneva,Swiss,SunSans-Regular" size="1"><i>laktoositon, gluteeniton</i></font></td>
')
end
end
describe 'Tillikka menu' do
it 'is formatted nicely' do
RestClient.stub(:get => scrape_data("tillikka.html"))
Date.stub(:today => Date.parse("2012-02-20"))
RestaurantTillikka.new.menu.should equal_html('
<b>20.02.2012</b><br /><p>Punajuurikeitto l,g 7,90€</p>
<p>Tillikan pyttipannua l,g</p>
<p>Pippurinen possupata, riisi l,g 9,20€</p>
<p>Arkisin klo 11-14. Sisältää salaattipöydän, jäävesi/kotikalja, kahvi/tee ja jälkiruuan</p>
')
end
end
describe 'Tivoli menu' do
it 'is formatted nicely' do
RestClient.stub(:get => scrape_data("tivoli.html"))
Date.stub(:today => Date.parse("2012-02-20"))
RestaurantTivoli.new.menu.should equal_html('
Ma 20.02<br>
Katkarapusalaatti 7,30€<br>
-salaatinkastiketta<br>
<br>
Fetaleipä 7,30€<br>
-oliiveja,pestoa<br>
<br>
Lä<NAME>ä 8,40€<br>
-pippurikastketta<br>
<br>
')
end
it 'may display pre-October months with or without the leading zero' do
RestClient.stub(:get => scrape_data("tivoli.html"))
Date.stub(:today => Date.parse("2012-02-21"))
RestaurantTivoli.new.menu.should equal_html('
Ti 21.2<br>
Savulohisalaatti 7,30€<br>
-salaatinkastiketta<br>
<br>
Kanaleipä7,30€<br>
-currymajoneesi<br>
<br>
Lä<NAME>ä 8,40€<br>
-paistettu kananmuna<br>
<br>
')
end
end
<file_sep>/spec/menu_formatter_spec.rb
# encoding: UTF-8
describe 'Lunch menu message' do
before(:each) do
restaurants = [
stub(:name => "Noma", :menu => "<ul><li>fish</li><li>chips</li></ul>", :url => "http://noma.invalid"),
stub(:name => "<NAME>", :menu => "porridge", :url => "http://roca.invalid")
]
@message = MenuFormatter.create_message(restaurants)
end
it "lists restaurant names with links and menus" do
@message[:content].should equal_html('
<h1><a href="http://noma.invalid">Noma</a></h1>
<div><ul><li>fish</li><li>chips</li></ul></div>
<h1><a href="http://roca.invalid">El Celler De Can Roca</a></h1>
<div>porridge</div>
')
end
it "identifies the source of the message" do
@message[:source].should_not be_empty
@message[:from_address].should_not be_empty
end
it 'has a subject' do
@message[:subject].should_not be_empty
end
it 'is tagged #lunch' do
@message[:tags].should include("#lunch")
end
describe 'when menus from some restaurants are missing' do
it "Shows those restaurants at the end of the message" do
restaurants = [
stub(:name => "Mugaritz", :menu => nil, :url => "http://mugaritz.invalid"),
stub(:name => "Noma", :menu => "<ul><li>fish</li><li>chips</li></ul>", :url => "http://noma.invalid"),
stub(:name => "<NAME>", :menu => nil, :url => "http://roca.invalid")
]
@message = MenuFormatter.create_message(restaurants)
@message[:content].should equal_html('
<h1><a href="http://noma.invalid">Noma</a></h1>
<div><ul><li>fish</li><li>chips</li></ul></div>
<h1>Puuttuvat lounaslistat</h1>
<p>Näistä ravintoloista ei saatu kaivettua tämän päivän lounaslistoja:</p>
<ul>
<li><a href="http://mugaritz.invalid">Mugaritz</a></li>
<li><a href="http://roca.invalid">El Celler De Can Roca</a></li>
</ul>
')
end
end
end
<file_sep>/bin/lunch-menus
#! /usr/bin/env ruby
require 'rubygems'
require 'bundler/setup'
require_relative '../lib/lunch_menus.rb'
case ARGV.length
when 0
LunchMenus.test_run
when 1
LunchMenus.run(ARGV[0])
else
$stderr.puts "Usage: bundle exec bin/lunch-menus [FLOW_TOKEN]"
end
<file_sep>/lib/lunch_menus.rb
require_relative 'restaurants'
require_relative 'menu_formatter'
require_relative 'flowdock'
require_relative 'console_output'
module LunchMenus
def self.run(flow_token)
flowdock = Flowdock.new(flow_token)
message = MenuFormatter.create_message(RestaurantList.all)
flowdock.send_to_inbox(message)
end
def self.test_run
def Date.today
Date.parse("2013-04-20")
end
message = MenuFormatter.create_message(RestaurantList.all)
ConsoleOutput.print(message)
end
end
<file_sep>/bin/fetch-test-data
#! /usr/bin/env ruby
require 'rubygems'
require 'bundler/setup'
require 'active_support'
require_relative '../lib/lunch_menus.rb'
if ARGV.length != 1
$stderr.puts "Usage: bundle exec bin/fetch-test-data RESTAURANT_CLASS"
$stderr.puts "Example: bundle exec bin/fetch-test-data RestaurantComo"
exit 1
end
class_name = ARGV[0]
restaurant = ActiveSupport::Inflector.constantize(class_name).new
name = ActiveSupport::Inflector.underscore(class_name.sub(/^Restaurant/, ''))
if restaurant.sources.length == 1
system "curl #{restaurant.sources[0]} -o spec/scrape_data/#{name}.html"
else
restaurant.sources.each_with_index { |url, index|
system "curl #{url} -o spec/scrape_data/#{name}#{index+1}.html"
}
end
|
ab93edadf5a662236ed2ddbc91dc8e1b0ce1a2de
|
[
"Markdown",
"Ruby"
] | 14
|
Ruby
|
leonidas/lunch-menus
|
9b80f574833fb8f9c56f4b8551f33b2c7f867e38
|
74d88976be3b1f077c90da52d2c4f165ac6a596c
|
refs/heads/master
|
<repo_name>theophoric/CAS<file_sep>/events.php
<?php
/*
* Template Name: Events
*
*/
?>
<?php get_header(); ?>
<?php get_sidebar(); ?>
<div id="content">
<?php
$page_data = get_page($page_id);
$content = $page_data->post_content;
$title = $page_data->post_title;
$output .='<div id="page_header">';
$output .= '<h3>'.$title.'</h3>';
$output .= '</div';
$output .= '<div id="page_content">'.$content."</div>";
$output .= '<div id=calendar>';
$output .= '<iframe src="http://www.google.com/calendar/embed?showTitle=0&showNav=0&height=400&wkst=1&bgcolor=%23FFFFFF&src=tedawilson%40gmail.com&color=%23A32929&ctz=America%2FNew_York" style=" border-width:0 " width="600" height="400" frameborder="0" scrolling="no"></iframe>';
$output .= '</div>';
echo $output;
// dynamic_sidebar('EventsPage');
?>
</div>
<?php get_footer(); ?>
<file_sep>/landing.php
<?php
/*
Template Name: Landing
*/
$connect = array(
'menu' => 'Connect',
'container' => 'div',
'container_class' => 'landing_content',
'echo' => false,
'fallback_cb' => 'wp_page_menu'
// 'before' => '<span class="'.is_active_header($term->term_class, $page_class).'">',
// 'after' =>'</span>'
);
$explore = array(
'menu' => 'Explore',
'container' => 'div',
'container_class' => 'landing_content',
'echo' => false,
'fallback_cb' => 'wp_page_menu'
// 'before' => '<span class="'.is_active_header($term->term_class, $page_class).'">',
// 'after' =>'</span>'
);
$engage = array(
'menu' => 'Engage',
'container' => 'div',
'container_class' => 'landing_content',
'echo' => false,
'fallback_cb' => 'wp_page_menu'
// 'before' => '<span class="'.is_active_header($term->term_class, $page_class).'">',
// 'after' =>'</span>'
);
get_template_part('landing_header');
?>
<script type="text/javascript">
Event.observe(window, 'load', content_hide, false);
function content_hide(){ $$('.landing_content').invoke('hide');
// each(function(item){item.setStyle(display: 'hidden');});
}
</script>
<?php
$output = '';
$output .='<div id="landing_background">';
query_posts(array('post_type'=>'Pictures','orderby'=>'rand','showposts'=>1));
while(have_posts()) : the_post();
$data = get_post_custom(get_the_ID());
$output .= get_the_post_thumbnail($result->ID, array(940,600));
$output.='</div>';
$output .= '<div id="landing">
<div id="landing_container" >
<div class="landing_menu" >
<h1 class="landing_toggle">Connect</h1>'.
wp_nav_menu($connect).
' </div>
<div class="landing_menu" >
<h1 class="landing_toggle">Explore</h1>'.
wp_nav_menu($explore).
'</div>
<div class="landing_menu" >
<h1 class="landing_toggle">Engage</h1>'.
wp_nav_menu($engage).
'</div>
</div>
</div>';
$caption = $data['picture_caption'][0];
if(!empty($caption)){
$output .= '<div id="landing_caption"><h5>'.$caption.'</h5></div>';
}
endwhile;
echo $output;
get_footer();<file_sep>/README.md
# Harvard Committee for African Studies
<file_sep>/functions.php
<?php
require_once('libs/FirePHPCore/fb.php');
require_once('libs/FirePHPCore/FirePHP.class.php');
ob_start();
// $firephp = FirePHP::getInstance(true);
add_action('init', 'create_sidebars');
add_action('init', 'create_posts');
add_action('admin_menu', 'create_post_meta');
add_action('save_post', 'meta_save');
add_theme_support('post-thumbnails');
function meta_save(){
organization_meta_save();
people_meta_save();
course_meta_save();
grant_meta_save();
picture_meta_save();
research_meta_save();
news_meta_save();
}
function create_sidebars(){
register_sidebar(array(
'name' => 'menu',
'before_widget' => '<div id="sidebar_video">',
'after_widget' => '</div>',
'before_title' => '<h3>',
'after_title' => '</h3>',
));
register_sidebar(array(
'name' => 'Vimeo',
'before_widget' => '<div id="vimeo_badge">',
'after_widget' => '</div>',
'before_title' => '<h3>',
'after_title' => '</h3>',
));
register_sidebar(array(
'name' => 'header',
'before_widget' => '<div id="header_content">',
'after_widget' => '</div>',
'before_title' => '<h3>',
'after_title' => '</h3>',
));
register_sidebar(array(
'name' => 'footer',
'before_widget' => '<div id="footer_content">',
'after_widget' => '</div>',
'before_title' => '<h3>',
'after_title' => '</h3>',
));
register_sidebar(array(
'name' => 'EventsPage',
'before_widget' => '<div id="events_content">',
'after_widget' => '</div>',
'before_title' => '<h3>',
'after_title' => '</h3>',
));
}
function create_posts(){
$labels = array(
'name' => _x('Pictures', 'post type general name'),
'singular_name' => _x('Picture', 'post type singular name'),
'add_new' => _x('Add New', 'picture'),
'add_new_item' => __('Add New Picture'),
'edit_item' => __('Edit Picture'),
'new_item' => __('New Picture'),
'view_item' => __('View Pictures'),
'search_items' => __('Search Pictures'),
'not_found' => __('No pictures found'),
'parent_item_colon' => ''
);
$args = array(
'labels' => $labels,
'singular_label' => 'pictures',
'public' => true,
'show_ui' => true,
'_builtin' => false,
'capability_type' => 'page',
'hierarchical' => false,
'rewrite' => array("slug" => "pictures"),
'supports' => array( 'title', 'thumbnail'),
'queryvar' => 'pictures');
register_post_type('Pictures', $args);
$labels = array(
'name' => _x('Organizations', 'post type general name'),
'singular_name' => _x('Organization', 'post type singular name'),
'add_new' => _x('Add New', 'organization'),
'add_new_item' => __('Add New Organization'),
'edit_item' => __('Edit organization'),
'new_item' => __('New organization'),
'view_item' => __('View Organizations'),
'search_items' => __('Search Organizations'),
'not_found' => __('No organizations found'),
'parent_item_colon' => ''
);
$args = array(
'labels' => $labels,
'singular_label' => 'organization',
'public' => true,
'show_ui' => true,
'_builtin' => false,
'capability_type' => 'post',
'hierarchical' => false,
'rewrite' => array("slug" => "organizations"),
'supports' => array( 'title'),
'queryvar' => 'organizations');
register_post_type('Organizations', $args);
$labels = array(
'name' => _x('People', 'post type general name'),
'singular_name' => _x('Person', 'post type singular name'),
'add_new' => _x('Add New', 'person'),
'add_new_item' => __('Add New Person'),
'edit_item' => __('Edit Person'),
'new_item' => __('New Person'),
'view_item' => __('View People'),
'search_items' => __('Search People'),
'not_found' => __('No people found'),
'parent_item_colon' => ''
);
$args = array(
'labels' => $labels,
'singular_label' => 'person',
'public' => true,
'show_ui' => true,
'_builtin' => false,
'capability_type' => 'post',
'hierarchical' => false,
'rewrite' => array("slug" => "people"),
'supports' => array('thumbnail', 'profile', 'title'),
'queryvar' => 'people');
register_post_type('People', $args);
$labels = array(
'name' => _x('Courses', 'post type general name'),
'singular_name' => _x('Course', 'post type singular name'),
'add_new' => _x('Add New', 'course'),
'add_new_item' => __('Add New Course'),
'edit_item' => __('Edit Course'),
'new_item' => __('New Course'),
'view_item' => __('View Courses'),
'search_items' => __('Search Courses'),
'not_found' => __('No courses found'),
'parent_item_colon' => ''
);
$args = array(
'labels' => $labels,
'singular_label' => 'course',
'public' => true,
'show_ui' => true,
'_builtin' => false,
'capability_type' => 'post',
'hierarchical' => false,
'rewrite' => array("slug" => "courses"),
'supports' => array('title'),
'queryvar' => 'courses');
register_post_type('Courses', $args);
$labels = array(
'name' => _x('Grants', 'post type general name'),
'singular_name' => _x('Grant', 'post type singular name'),
'add_new' => _x('Add New', 'grant'),
'add_new_item' => __('Add New Grant'),
'edit_item' => __('Edit Grant'),
'new_item' => __('New Grant'),
'view_item' => __('View Grants'),
'search_items' => __('Search Grants'),
'not_found' => __('No grants found'),
'parent_item_colon' => ''
);
$args = array(
'labels' => $labels,
'singular_label' => 'grant',
'public' => true,
'show_ui' => true,
'_builtin' => false,
'capability_type' => 'post',
'hierarchical' => false,
'rewrite' => array("slug" => "grants"),
'supports' => array('title'),
'queryvar' => 'grants');
register_post_type('Grants', $args);
// Research Opportunities //
$labels = array(
'name' => _x('Research Opportunities', 'post type general name'),
'singular_name' => _x('Grant', 'post type singular name'),
'add_new' => _x('Add New', 'Research Opportunities'),
'add_new_item' => __('Add New Research Opportunities'),
'edit_item' => __('Edit Research Opportunity'),
'new_item' => __('New Research Opportunity'),
'view_item' => __('View Research Opportunity'),
'search_items' => __('Search Research Opportunities'),
'not_found' => __('No Research Opportunities found'),
'parent_item_colon' => ''
);
$args = array(
'labels' => $labels,
'singular_label' => 'research',
'public' => true,
'show_ui' => true,
'_builtin' => false,
'capability_type' => 'post',
'hierarchical' => false,
'rewrite' => array("slug" => "research"),
'supports' => array('title'),
'queryvar' => 'research');
register_post_type('Research', $args);
// In the Media //
$labels = array(
'name' => _x('In the Media', 'post type general name'),
'singular_name' => _x('Post', 'post type singular name'),
'add_new' => _x('Add New', 'Post'),
'add_new_item' => __('Add New Post'),
'edit_item' => __('Edit Posts'),
'new_item' => __('New Post'),
'view_item' => __('View Post'),
'search_items' => __('Search Posts'),
'not_found' => __('No Posts found'),
'parent_item_colon' => ''
);
$args = array(
'labels' => $labels,
'singular_label' => 'post',
'public' => true,
'show_ui' => true,
'_builtin' => false,
'capability_type' => 'post',
'hierarchical' => false,
'rewrite' => array("slug" => "news"),
'supports' => array('title', 'editor'),
'queryvar' => 'news');
register_post_type('News', $args);
// HSAFP //
$labels = array(
'name' => _x('Harvard South African Fellowship Program', 'post type general name'),
'singular_name' => _x('Heading', 'post type singular name'),
'add_new' => _x('Add New', 'Heading'),
'add_new_item' => __('Add New Heading'),
'edit_item' => __('Edit Heading'),
'new_item' => __('New Heading'),
'view_item' => __('View Heading'),
'search_items' => __('Search Headings'),
'not_found' => __('No Headings found'),
'parent_item_colon' => ''
);
$args = array(
'labels' => $labels,
'singular_label' => 'heading',
'public' => true,
'show_ui' => true,
'_builtin' => false,
'capability_type' => 'post',
'hierarchical' => false,
'rewrite' => array("slug" => "headings"),
'supports' => array('title', 'editor'),
'queryvar' => 'headings');
register_post_type('Headings', $args);
create_taxonomies();
}
function create_taxonomies(){
// PEOPLE //
register_taxonomy( 'people', array('People'), array(
'hierarchical' => true,
'label' => 'Classifications',
'update_count_callback' => '_update_post_term_count',
'query_var' => true,
'rewrite' => true,
'public' => true,
'show_ui' => true,
) );
// register_taxonomy( 'interests', array('People'), array(
// 'hierarchical' => false,
// 'label' => 'Fields of Interest or Research',
// 'update_count_callback' => '_update_post_term_count',
// 'query_var' => true,
// 'rewrite' => true,
// 'public' => true,
// 'show_ui' => true,
//
// ) );
// Organizations //
register_taxonomy( 'organizations', array('Organizations'), array(
'hierarchical' => true,
'label' => 'Affiliations',
'update_count_callback' => '_update_post_term_count',
'query_var' => true,
'rewrite' => true,
'public' => true,
'show_ui' => true,
) );
// Courses //
register_taxonomy( 'courses', array('Courses'), array(
'hierarchical' => true,
'label' => 'Departments',
'update_count_callback' => '_update_post_term_count',
'query_var' => true,
'rewrite' => true,
'public' => true,
'show_ui' => true,
) );
// Grants //
register_taxonomy( 'grants', array('Grants'), array(
'hierarchical' => true,
'label' => 'Grant Types',
'update_count_callback' => '_update_post_term_count',
'query_var' => true,
'rewrite' => true,
'public' => true,
'show_ui' => true,
) );
// Landing Page //
register_taxonomy( 'pictures', array('attachment'), array(
'hierarchical' => true,
'label' => 'Pictures',
'update_count_callback' => '_update_post_term_count',
'query_var' => true,
'rewrite' => true,
'public' => true,
'show_ui' => true,
) );
// Research //
register_taxonomy( 'research', array('Research'), array(
'hierarchical' => true,
'label' => 'Research Categories',
'update_count_callback' => '_update_post_term_count',
'query_var' => true,
'rewrite' => true,
'public' => true,
'show_ui' => true,
) );
}
function create_post_meta(){
add_meta_box('people-information', 'Information', 'people_meta_content','People','normal', 'low');
add_meta_box('organization-information', 'Information', 'organization_meta_content', 'Organizations','normal', 'low');
add_meta_box('grant-information', 'Information', 'grant_meta_content', 'Grants','normal', 'low');
add_meta_box('course-information', 'Information', 'course_meta_content', 'Courses','normal', 'low');
add_meta_box('picture-information', 'Information', 'picture_meta_content', 'Pictures','normal', 'low');
add_meta_box('research-information', 'Information', 'research_meta_content', 'Research','normal', 'low');
add_meta_box('news-information', 'Information', 'news_meta_content', 'News','normal', 'low');
}
function news_meta_content(){
global $post;
$values = get_post_custom($post->ID);
$output = '';
$output .= '<table class="form-table"><tbody>';
// $output .= '<tr class="form-field ">';
// $output .= '<th scope="row">';
// $output .= '<label for="news_excerpt">Description / Excerpt</label>';
// $output .= '</th><td>';
// $output .= '<textarea name="news_excerpt" cols="70" rows="10" />'.$values['news_excerpt'][0].'</textarea>';
// $output .= '</td>';
$output .= '<tr class="form-field ">';
$output .= '<th scope="row">';
$output .= '<label for="news_link">News Link</label>';
$output .= '</th><td>';
$output .= '<input type="text" name="news_link" value="'.$values['news_link'][0].'"/>';
$output .= '</td>';
$output .= '</tbody></table>';
$output .= '<input type="hidden" name="news_nonce" value="' .
wp_create_nonce( 'news_nonce' ) . '" />';
echo $output;
}
function news_meta_save(){
global $post;
if ( !wp_verify_nonce( $_POST['news_nonce'], 'news_nonce')) {
return $post->ID;
}
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return $post->id;
// $news_excerpt = $_POST['news_excerpt'];
$news_link = $_POST['news_link'];
// update_post_meta($post->ID, 'news_excerpt', $news_excerpt);
update_post_meta($post->ID, 'news_link', $news_link);
}
function research_meta_content(){
global $post;
$values = get_post_custom($post->ID);
$output = '';
$output .= '<table class="form-table"><tbody>';
$output .= '<tr class="form-field ">';
$output .= '<th scope="row">';
$output .= '<label for="research_url">Link URL</label>';
$output .= '</th><td>';
$output .= '<input type="text" name="research_url" value="'.$values['research_url'][0].'"/>';
$output .= '</td>';
$output .= '</tbody></table>';
$output .= '<input type="hidden" name="research_nonce" value="' .
wp_create_nonce( 'research_nonce' ) . '" />';
echo $output;
}
function research_meta_save(){
global $post;
if ( !wp_verify_nonce( $_POST['research_nonce'], 'research_nonce')) {
return $post->ID;
}
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return $post->id;
$research_url = $_POST['research_url'];
update_post_meta($post->ID, 'research_url', $research_url);
}
function picture_meta_content(){
global $post;
$values = get_post_custom($post->ID);
$output = '';
$output .= '<table class="form-table"><tbody>';
$output .= '<tr class="form-field ">';
$output .= '<th scope="row">';
$output .= '<label for="picture_caption">Caption<span class="required">(Optional)</span></label>';
$output .= '</th><td>';
$output .= '<textarea name="picture_caption" cols="70" rows="5" />'.$values['picture_caption'][0].'</textarea>';
$output .= '</td>';
//
// $output .= '<tr class="form-field ">';
// $output .= '<th scope="row">';
// $output .= '<label for="picture_background">Background Color</label>';
// $output .= '</th>';
// $output .= '<td><input type="radio" name="picture_background" value="dark"/>Dark';
// $output .= '<input type="radio" name="picture_background" value="light"/>Light</td>';
$output .= '</tbody></table>';
$output .= '<input type="hidden" name="picture_nonce" value="' .
wp_create_nonce( 'picture_nonce' ) . '" />';
echo $output;
}
function picture_meta_save(){
global $post;
if ( !wp_verify_nonce( $_POST['picture_nonce'], 'picture_nonce')) {
return $post->ID;
}
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return $post->id;
$picture_caption = $_POST['picture_caption'];
$picture_background = $_POST['picture_background'];
update_post_meta($post->ID, 'picture_caption', $picture_caption);
update_post_meta($post->ID, 'picture_background', $picture_background);
}
function organization_meta_content(){
// Use nonce for verification
global $post;
$values = get_post_custom($post->ID);
$output = '';
$output .= '<table class="form-table"><tbody>';
$output .= '<tr class="form-field ">';
$output .= '<th scope="row">';
$output .= '<label for="organization_description">Description</label>';
$output .= '</th><td>';
$output .= '<textarea name="organization_description" cols="70" rows="10" />'.$values['organization_description'][0].'</textarea>';
$output .= '</td>';
$output .= '<tr class="form-field ">';
$output .= '<th scope="row">';
$output .= '<label for="organization_website">Website</label>';
$output .= '</th><td>';
$output .= '<input type="text" name="organization_website" value="'.$values['organization_website'][0].'"/>';
$output .= '</td>';
$output .= '<tr class="form-field ">';
$output .= '<th scope="row">';
$output .= '<label for="organization_email">Email Contact</label>';
$output .= '</th><td>';
$output .= '<input type="text" name="organization_email" value="'.$values['organization_email'][0].'"/>';
$output .= '</td>';
$output .= '</tbody></table>';
$output .= '<input type="hidden" name="organization_nonce" value="' .
wp_create_nonce( 'organization_nonce' ) . '" />';
echo $output;
}
function organization_meta_save(){
global $post;
if ( !wp_verify_nonce( $_POST['organization_nonce'], 'organization_nonce')) {
return $post->ID;
}
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return $post->id;
$organization_description = $_POST['organization_description'];
$website = $_POST['organization_website'];
$email = $_POST['organization_email'];
update_post_meta($post->ID, 'organization_description',$organization_description);
update_post_meta($post->ID, 'organization_website', $website);
update_post_meta($post->ID, 'organization_email', $email);
}
function people_meta_content(){
// NEED TO ADD FORM VALIDATION !!
// Use nonce for verification
global $post;
$values = get_post_custom($post->ID);
//for validation during save
$output .= '<input type="hidden" name="people_noncename" id="people_noncename" value="'.wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
$output = '';
$output .= '<table class="form-table"><tbody>';
//
// $output .= '<tr class="form-field form-required">';
// $output .= '<th scope="row">';
// $output .= '<label for="people_name" style="width:200px;text-align:left;">Name<span class="description"> (Required)</span></label>';
// $output .= '</th><td>';
// $output .= '<input type="text" name="people_name" value="'.$values['people_name'][0].'"/>';
// $output .= '</td>';
$output .= '<tr class="form-field">';
$output .= '<th scope="row">';
$output .= '<label for="people_title">Title</label>';
$output .= '</th><td>';
$output .= '<input type="text" name="people_title" value="'.$values['people_title'][0].'"/>';
$output .= '</td>';
$output .= '<tr class="form-field ">';
$output .= '<th scope="row">';
$output .= '<label for="people_experience">Experience</label>';
$output .= '</th><td>';
$output .= '<input type="text" name="people_experience" value="'.$values['people_experience'][0].'"/>';
$output .= '</td>';
$output .= '<tr class="form-field ">';
$output .= '<th scope="row">';
$output .= '<label for="people_phone">Phone</label>';
$output .= '</th><td>';
$output .= '<input type="text" name="people_phone" value="'.$values['people_phone'][0].'"/>';
$output .= '</td>';
$output .= '<tr class="form-field ">';
$output .= '<th scope="row">';
$output .= '<label for="people_email">Email</label>';
$output .= '</th><td>';
$output .= '<input type="text" name="people_email" value="'.$values['people_email'][0].'"/>';
$output .= '</td>';
$output .= '<tr class="form-field ">';
$output .= '<th scope="row">';
$output .= '<label for="people_biography">Biography</label> ';
$output .= '</th><td>';
$output .= '<textarea name="people_biography" cols="70" rows="10" />'.$values['people_biography'][0].'</textarea>';
$output .= '</td>';
$output .= '</tbody></table>';
$output .= '<input type="hidden" name="people_nonce" value="' .
wp_create_nonce( 'people_nonce' ) . '" />';
echo $output;
}
function people_meta_save(){
if ( !wp_verify_nonce( $_POST['people_nonce'], 'people_nonce')) {
return $post->ID;
}
global $post;
//
// fb($post->id);
// if ( !wp_verify_nonce( $_POST['people_noncename'], plugin_basename(__FILE__) )) {
// return $post;
// }
//
// // // verify if this is an auto save routine. If it is our form has not been submitted, so we dont want
// // // to do anything
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return $post->id;
// OK, we're authenticated: we need to find and save the data
$title = $_POST['people_title'];
$experience = $_POST['people_experience'];
$phone = $_POST['people_phone'];
$email= $_POST['people_email'];
$bio = $_POST['people_biography'];
update_post_meta($post->ID,'people_title', $title);
update_post_meta($post->ID,'people_experience', $experience);
update_post_meta($post->ID,'people_phone', $phone);
update_post_meta($post->ID,'people_email', $email);
update_post_meta($post->ID,'people_biography', $bio);
}
//Organization post functions
function course_meta_content()
{
global $post;
$values = get_post_custom($post->ID);
//for validation during save
$output = '';
$output .= '<table class="form-table"><tbody>';
// $output .= '<tr class="form-field form-required">';
// $output .= '<th scope="row">';
// $output .= '<label for="course_name" style="width:200px;text-align:left;">Course Name<span class="description"> (Required)</span></label>';
// $output .= '</th><td>';
// $output .= '<input type="text" name="course_name" value="'.$values['course_name'][0].'"/>';
// $output .= '</td>';
$output .= '<tr class="form-field form-required">';
$output .= '<th scope="row">';
$output .= '<label for="course_number" style="width:200px;text-align:left;">Course Number<span class="description"> (Required)</span></label>';
$output .= '</th><td>';
$output .= '<input type="text" name="course_number" value="'.$values['course_number'][0].'"/>';
$output .= '</td>';
$output .= '<tr class="form-field form-required">';
$output .= '<th scope="row">';
$output .= '<label for="course_instructor" style="width:200px;text-align:left;">Course Instructor<span class="description"> (Required)</span></label>';
$output .= '</th><td>';
$output .= '<input type="text" name="course_instructor" value="'.$values['course_instructor'][0].'"/>';
$output .= '</td>';
$output .= '<input type="hidden" name="course_nonce" id="course_nonce_id" value="' .
wp_create_nonce( 'course_nonce' ) . '" />';
$output .= '</tbody></table>';
echo $output;
}
function course_meta_save()
{
global $post;
if ( !wp_verify_nonce( $_POST['course_nonce'], 'course_nonce')) {
return $post->ID;
}
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return $post->id;
$number = $_POST['course_number'];
$instructor = $_POST['course_instructor'];
// update_post_meta($post->ID, 'course_name', $name);
update_post_meta($post->ID, 'course_number', $number);
update_post_meta($post->ID, 'course_instructor', $instructor);
}
function grant_meta_content()
{
global $post;
$values = get_post_custom($post->ID);
//for validation during save
$output = '';
$output .= '<table class="form-table"><tbody>';
$output .= '<tr class="form-field form-required">';
$output .= '<th scope="row">';
$output .= '<label for="grant_description" style="width:200px;text-align:left;">Description<span class="description"> (Required)</span></label>';
$output .= '</th><td>';
$output .= '<textarea name="grant_description">'.$values['grant_description'][0].'</textarea>';
$output .= '</td>';
$output .= '<tr class="form-field">';
$output .= '<th scope="row">';
$output .= '<label for="grant_website" style="width:200px;text-align:left;">Website</label>';
$output .= '</th><td>';
$output .= '<input type="text" name="grant_website" value="'.$values['grant_website'][0].'"/>';
$output .= '</td>';
$output .= '<tr class="form-field">';
$output .= '<th scope="row">';
$output .= '<label for="grant_deadline" style="width:200px;text-align:left;">Deadline</label>';
$output .= '</th><td>';
$output .= '<input type="text" name="grant_deadline" value="'.$values['grant_deadline'][0].'"/>';
$output .= '</td>';
$output .= '<input type="hidden" name="grant_nonce" value="' .
wp_create_nonce( 'grant_nonce' ) . '" />';
$output .= '</tbody></table>';
echo $output;
}
function grant_meta_save()
{
if ( !wp_verify_nonce( $_POST['grant_nonce'], 'grant_nonce')) {
return $post->ID;
}
global $post;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return $post->id;
$website = $_POST['grant_website'];
$description = $_POST['grant_description'];
$deadline = $_POST['grant_deadline'];
update_post_meta($post->ID, 'grant_website', $website);
update_post_meta($post->ID, 'grant_description', $description);
update_post_meta($post->ID, 'grant_deadline', $deadline);
}
// function sidebar_main($page_id){
//
// $page = get_page($page_id);
// //
// // $menu_obj = wp_get_nav_menu_object('Connect');
// // $menu_items = wp_get_nav_menu_items($menu_obj->term_id);
// global $wpdb;
//
//
// $query = "
// SELECT *
// FROM wp_term_taxonomy
// WHERE taxonomy = 'nav_menu'
// ";
//
// $menu_list = $wpdb->get_results($query);
// echo '<div id="sidebar">
// <ul class="menu">';
// if($menu_list){
// foreach($menu_list as $menu_item){
// $term = get_term($menu_item->term_id, 'nav_menu');
// $args = array(
// 'menu' => $term->name,
// 'container' => '',
// 'menu_class' => 'sub-menu',
// 'echo' => true,
// 'fallback_cb' => 'wp_page_menu'
// // 'before' => '<span class="'.is_active_header($term->term_id, $page_id).'">',
// // 'after' =>'</span>'
// );
// echo '<li class="top-level '.is_active_header($term->term_id, $page_id).'"><a class="'.is_active_header($term->term_id, $page_id).'">'.$term->name.'</a>';
// wp_nav_menu($args);
// echo '</li>';
// }
//
// }
// echo '</ul></div>';
//
// }
function sidebar_main($page_id){
$page = get_page($page_id);
//
// $menu_obj = wp_get_nav_menu_object('Connect');
// $menu_items = wp_get_nav_menu_items($menu_obj->term_id);
global $wpdb;
$query = "
SELECT *
FROM wp_rjgrk8_term_taxonomy
WHERE taxonomy = 'nav_menu'
";
$menu_list = $wpdb->get_results($query);
// print_r($menu_list);
if(empty($menu_list)){
$query = "
SELECT *
FROM FROM wp_term_taxonomy
WHERE taxonomy = 'nav_menu'
";
$menu_list = $wpdb->get_results($query);}
$output = '';
$output .= '<div id="menu_container">';
$output .= '<ul class="menu">';
if($menu_list){
foreach($menu_list as $menu_item){
$term = get_term($menu_item->term_id, 'nav_menu');
$args = array(
'menu' => $term->name,
'container' => 'div',
'container_class' => 'menu_content',
'echo' => false,
'fallback_cb' => 'wp_page_menu'
// 'before' => '<span class="'.is_active_header($term->term_id, $page_id).'">',
// 'after' =>'</span>'
);
$output .= '<li class="menu_toggle '.is_active_header($term->term_id, $page_id).'"><a class="'.is_active_header($term->term_id, $page_id).'">'.$term->name.'</a></li>';
$output .= wp_nav_menu($args);
}
}
$output .= '</ul></div>';
echo $output;
}
function is_active_header($menu_id, $page_id){
// $menu_obj = wp_get_nav_menu_object();
$menu_obj = wp_get_nav_menu_object($menu_id);
$menu_items = wp_get_nav_menu_items($menu_obj->term_id);
$item_ids = array();
foreach($menu_items as $item){
$item_ids[] = $item->object_id;
}
if(in_array($page_id, $item_ids)){
return "current";
}
// åß_r($results);
}
function category_accordion($taxonomy_name, $constructor) {
$r = array(
'show_option_all' => '',
'show_option_none' => __('No '.$post_data->post_title.'s'),
'orderby' => 'name',
'order' => 'ASC',
'show_last_update' => 0,
'style' => 'list',
'show_count' => 0,
'hide_empty' => 0,
'use_desc_for_title' => 1,
'child_of' => 0,
'hierarchical' => true,
'title_li' => ucwords($taxonomy_name),
'number' => NULL,
'echo' => 1,
'depth' => 0,
'current_category' => 0,
'pad_counts' => 0,
'taxonomy' => $taxonomy_name,
'walker' => 'Walker_Category',
'feed' => '',
'feed_type' => '',
'feed_image' => '',
'exclude' => '',
'exclude_tree' => '' );
if ( !isset( $r['pad_counts'] ) && $r['show_count'] && $r['hierarchical'] )
$r['pad_counts'] = true;
if ( isset( $r['show_date'] ) )
$r['include_last_update_time'] = $r['show_date'];
if ( true == $r['hierarchical'] ) {
$r['exclude_tree'] = $r['exclude'];
$r['exclude'] = '';
}
if ( !isset( $r['class'] ) )
$r['class'] = ( 'category' == $r['taxonomy'] ) ? 'categories' : $r['taxonomy'];
extract( $r );
if ( !taxonomy_exists($taxonomy) ){
return false;}
//build output string
$output= '<div id="accordion_container">';
// $output .= '<ul class="accordion collapsible">';
$categories = get_categories( $r );
foreach($categories as $category){
if($category->category_parent == 0){
$output .= '<li class="accordion_toggle"><a href="#" class="top-level">'.$category->name.'</a></li>';
$output .= '<div class="accordion_content">';
$output .= $category->description;
$output .= call_user_func($constructor, $category);
$output .='</div>';
}
}
// $output .= '</ul>';
$output .= '</div>';
echo $output;
}
function research_accordion_constructor($category){
$r = array('show_option_all' => '',
'show_option_none' => __('No '.$post_data->post_title.'s'),
'orderby' => 'name',
'order' => 'ASC',
'show_last_update' => 0,
'style' => 'list',
'show_count' => 0,
'hide_empty' => 0,
'use_desc_for_title' => 1,
'hierarchical' => true,
'title_li' => ucwords($category->name),
'number' => NULL,
'echo' => 1,
'depth' => 0,
'current_category' => 0,
'pad_counts' => 0,
'walker' => 'Walker_Category',
'feed' => '',
'feed_type' => '',
'feed_image' => '',
'exclude' => '',
'exclude_tree' => '',
'child_of' => $category->term_id,
'taxonomy' => $category->taxonomy);
$children = get_categories( $r );
if(!empty($children)){
$output = '';
$output .= '<div id="accordion_inner_container">';
foreach($children as $child){
$output .= '<li class="accordion_inner_toggle"><a href="#">'.$child->name.'</a></li>';
$output .= '<div class="accordion_inner_content">';
$output .= $child->description;
$output .= '<ul>';
query_posts(array('courses'=>$child->slug));
while(have_posts()) : the_post();
$data = get_post_custom();
$output .= '<li class="accordion_item">'.get_the_title().'</li>';
$output .= '<li class="accordion_item"><a href="'.$data['course_instructor'][0].'"><span class="italic">Link to Website</span></a></li>';
endwhile;
$output .= '</ul></div>';
}
$output .= '</div>';
return $output;
}
else{
$output .= '<ul>';
query_posts(array('courses'=>$category->slug));
while(have_posts()) : the_post();
$data = get_post_custom();
$output .= '<li class="accordion_item"><strong>'.$data['course_number'][0].'</strong> ';
$output .= ' '.get_the_title().' ';
$output .= '<span style="font-style:italic;">'.$data['course_instructor'][0].'</span></li>';
endwhile;
$output .='</ul>';
return $output;
}
}
function organizations_accordion_constructor($category){
query_posts(array('organizations'=>$category->slug));
while(have_posts()) : the_post();
$data = get_post_custom();
$output .= '<ul class="accordion_item">';
$output .= '<li><h4>'.get_the_title().'</h4></li>';
$output .= '<li>'.$data['organization_description'][0].'</li>';
$output .= '<li>'.$data['organization_website'][0].'</li>';
$output .= '<li>'.$data['organization_email'][0].'</li>';
endwhile;
return $output;
}
function courses_accordion_constructor($category){
$r = array('show_option_all' => '',
'show_option_none' => __('No '.$post_data->post_title.'s'),
'orderby' => 'name',
'order' => 'ASC',
'show_last_update' => 0,
'style' => 'list',
'show_count' => 0,
'hide_empty' => 0,
'use_desc_for_title' => 1,
'hierarchical' => true,
'title_li' => ucwords($category->name),
'number' => NULL,
'echo' => 1,
'depth' => 0,
'current_category' => 0,
'pad_counts' => 0,
'walker' => 'Walker_Category',
'feed' => '',
'feed_type' => '',
'feed_image' => '',
'exclude' => '',
'exclude_tree' => '',
'child_of' => $category->term_id,
'taxonomy' => $category->taxonomy);
$children = get_categories( $r );
if(!empty($children)){
$output = '';
$output .= '<div id="accordion_inner_container">';
foreach($children as $child){
$output .= '<li class="accordion_inner_toggle"><a href="#">'.$child->name.'</a></li>';
$output .= '<div class="accordion_inner_content">';
$output .= $child->description;
$output .= '<ul>';
query_posts(array('courses'=>$child->slug));
while(have_posts()) : the_post();
$data = get_post_custom();
$output .= '<li class="accordion_item"><strong>'.$data['course_number'][0].'</strong> ';
$output .= ' '.get_the_title().' ';
$output .= '<span style="font-style:italic;">'.$data['course_instructor'][0].'</span></li>';
endwhile;
$output .= '</ul></div>';
}
$output .= '</div>';
return $output;
}
else{
$output .= '<ul>';
query_posts(array('courses'=>$category->slug));
while(have_posts()) : the_post();
$data = get_post_custom();
$output .= '<li class="accordion_item"><strong>'.$data['course_number'][0].'</strong> ';
$output .= ' '.get_the_title().' ';
$output .= '<span style="font-style:italic;">'.$data['course_instructor'][0].'</span></li>';
endwhile;
$output .='</ul>';
return $output;
}
}
function grants_accordion_constructor($category){
$children = get_accordion_children($category);
if(!empty($children)){
$output = '';
$output .= '<div id="accordion_inner_container">';
foreach($children as $child){
$output .= '<li class="accordion_inner_toggle"><a href="#">'.$child->name.'</a></li>';
$output .= '<div class="accordion_inner_content">';
$output .= $child->description;
$apply_now_items = get_accordion_children($child);
if(!empty($apply_now_items)){
$output .= '<div id="apply_now_container">';
foreach($apply_now_items as $item){
$output .= '<li class="apply_now_toggle"><a href="#">'.$item->name.'</a></li>';
$output .= '<div class="apply_now_content">';
$output .= $item->description;
$output .= '</div>';
}
$output .= '</div>';
}
query_posts(array('grants'=>$child->slug));
while(have_posts()) : the_post();
$data = get_post_custom();
$output .= '<ul class="accordion_item">';
$output .= '<li><h4><strong>'.get_the_title().'</strong></h4></li>';
$output .= '<li><p>'.$data['grant_description'][0].'</p></li>';
$output .= '<li><span class="italic">Deadline: </span>'.$data['grant_deadline'][0].'</li>';
$output .= '<li>'.$data['grant_website'][0].'</li>';
$output .= '</ul>';
endwhile;
$output .= '</div>';
}
$output .= '</div>';
return $output;
}
else{
query_posts(array('grants'=>$category->slug));
while(have_posts()) : the_post();
$data = get_post_custom();
$output .= '<ul class="accordion_item">';
$output .= '<li><h4><strong>'.get_the_title().'</strong></h4></li>';
$output .= '<li><p>'.$data['grant_description'][0].'</p></li>';
$output .= '<li><span class="italic">Deadline: </span>'.$data['grant_deadline'][0].'</li>';
$output .= '<li>'.$data['grant_website'][0].'</li>';
$output .= '</ul>';
endwhile;
return $output;
}
}
function get_accordion_children($category){
$r = array('show_option_all' => '',
'show_option_none' => __('No '.$post_data->post_title.'s'),
'orderby' => 'name',
'order' => 'ASC',
'show_last_update' => 0,
'style' => 'list',
'show_count' => 0,
'hide_empty' => 0,
'use_desc_for_title' => 1,
'hierarchical' => false,
'title_li' => ucwords($category->name),
'number' => NULL,
'echo' => 1,
'depth' => 1,
'current_category' => 0,
'pad_counts' => 0,
'walker' => 'Walker_Category',
'feed' => '',
'feed_type' => '',
'feed_image' => '',
'exclude' => '',
'exclude_tree' => '',
'parent' => $category->term_id,
'taxonomy' => $category->taxonomy);
return get_categories( $r );
}
function people_accordion_constructor($category){
query_posts(array('people'=>$category->slug));
while(have_posts()) : the_post();
$data = get_post_custom();
$output .= get_the_post_thumbnail($post->id,'thumbnail');
$output .= '<ul class="accordion_item">';
$output .= '<li ><h4><strong>'.get_the_title().'</strong></h4></li>';
$output .= '<li class="italic">'.$data['people_title'][0].'</li>';
$output .= '<li>'.$data['people_experience'][0].'</li>';
$output .= '<li>'.$data['people_phone'][0].'</li>';
$output .= '<li>'.$data['people_email'][0].'</li>';
$output .= '<li><p>'.$data['people_biography'][0].'</p></li>';
// fix this!!!
$post_tags = get_the_tags(get_the_ID());
print_r($post_tags);
if($post_tags){
$output .= '<li><strong class="italic">Research Areas: </strong>';
$output .= '</li>';
}
$output .= '</ul>';
endwhile;
return $output;
}
?><file_sep>/hsafp.php
<?php
/*
* Template Name: HSAFP
*
*/
?>
<?php get_header(); ?>
<?php get_sidebar(); ?>
<div id="content">
<?php
$page_data = get_page($page_id);
$content = $page_data->post_content;
$title = $page_data->post_title;
// $picture = $page_data->post_thumbnail;
$output .='<div id="page_header">';
$output .= '<h3>'.$title.'</h3>';
$output .= '</div';
$output .= '<div id="page_content">'.$content."</div>";
$output .= '<div id="accordion_container">';
query_posts(array('post_type'=>'Headings', 'order'=>'asc'));
while(have_posts()) : the_post();
$data = get_post_custom(get_the_ID());
$output .= '<li class="accordion_toggle"><a>'.get_the_title().'</a></li>';
$output .= '<div class="accordion_content">';
$output .= get_the_content();
$output .= '</div>';
endwhile;
$output .= '</div>';
echo $output;
?>
</div>
<?php get_footer(); ?>
<file_sep>/search.php
<?php get_header();
get_sidebar($page);
$output .= '<div id="content">';
$output .= '<h1 class="page-title">Search results for: <span>' . get_search_query() . '</span></h1>';
$people = '';
$research = '';
$organizations = '';
$courses = '';
$grants = '';
$content = '';
$news = '';
while ( have_posts() ) : the_post();
$category = $post->post_type;
$data = get_post_custom();
switch($category){
case "People":
break;
case "Research":
break;
case "Grants":
$grants .= '<ul class="accordion_item">';
$grants .= '<li><h4><strong>'.get_the_title().'</strong></h4></li>';
$grants .= '<li><p>'.$data['grant_description'][0].'</p></li>';
$grants .= '<li><span class="italic">Deadline: </span>'.$data['grant_deadline'][0].'</li>';
$grants .= '<li>'.$data['grant_website'][0].'</li>';
$grants .= '</ul>';
break;
case "Courses" :
$courses .= '<li class="accordion_item"><strong>'.$data['course_number'][0].'</strong> ';
$courses .= ' '.get_the_title().' ';
$courses .= '<span style="font-style:italic;">'.$data['course_instructor'][0].'</span></li>';
break;
case "News" :
$news .= '<ul class="accordion_item">';
$news .= '<li><h4>'.get_the_title().'</h4></li>';
$news .= '<li>'.get_the_content().'</li>';
break;
case "Organizations" :
$organizations .= '<ul class="accordion_item">';
$organizations .= '<li><h4>'.get_the_title().'</h4></li>';
$organizations .= '<li>'.$data['organization_description'][0].'</li>';
$organizations .= '<li>'.$data['organization_website'][0].'</li>';
$organizations .= '<li>'.$data['organization_email'][0].'</li>';
break;
case "page" :
break;
}
endwhile;
$page_data = get_page($page_id);
$content = $page_data->post_content;
$title = $page_data->post_title;
$output .= '<div id="page_header">';
$output .= '<h3>'.$title.'</h3>';
$output .= '</div>';
$output .= '<div id="page_content">'.$content."</div>";
$output .= '</div>';
echo $output;
get_footer(); ?>
<file_sep>/index.php
<?php get_header();
get_sidebar($page);
$output .= '<div id="content">';
$page_data = get_page($page_id);
$content = $page_data->post_content;
$title = $page_data->post_title;
$output .= '<div id="page_header">';
$output .= '<h3>'.$title.'</h3>';
$output .= '</div>';
$output .= '<div id="page_content">'.$content."</div>";
$output .= '</div>';
echo $output;
get_footer(); ?>
<file_sep>/organizations.php
<?php
/*
* Template Name: Organizations
*
*/
?>
<?php get_header(); ?>
<?php get_sidebar(); ?>
<div id="content">
<?php
$page_data = get_page($page_id);
$content = $page_data->post_content;
$title = $page_data->post_title;
// $picture = $page_data->post_thumbnail;
$output .='<div id="page_header">';
$output .= '<h3>'.$title.'</h3>';
$output .= '</div';
$output .= '<div id="page_content">'.$content."</div>";
echo $output;
category_accordion('organizations', 'organizations_accordion_constructor');
?>
</div>
<?php get_footer(); ?>
<file_sep>/libs/cas.js
Event.observe(window, 'load', loadAccordions, false);
function loadAccordions(){
new accordion('menu_container',{
classNames : {
toggle : 'menu_toggle',
toggleActive : 'menu_toggle_active',
content : 'menu_content'
},
direction : 'vertical'
});
new accordion('accordion_container',{
classNames : {
toggle : 'accordion_toggle',
toggleActive : 'accordion_toggle_active',
content : 'accordion_content'
},
direction : 'vertical'
});
new accordion('accordion_inner_container',{
classNames : {
toggle : 'accordion_inner_toggle',
toggleActive : 'accordion_inner_toggle_active',
content : 'accordion_inner_content'
},
direction : 'vertical'
});
new accordion('apply_now_container',{
classNames : {
toggle : 'apply_now_toggle',
toggleActive : 'apply_now_toggle_active',
content : 'apply_now_content'
},
direction : 'vertical'
});
};
<file_sep>/footer.php
<div id="footer">
<div id="social_links">
<ul>
<li><a href="http://twitter.com/AfricaHarvard" ><img src="<?php bloginfo('template_directory'); ?>/images/icons/medium/twitter.png" alt="CAS on Twitter"/></a></li>
<li><a href="http://www.facebook.com/renaldo1#!/pages/Harvard-African-Studies/119796774703178?ref=ts"><img src="<?php bloginfo('template_directory'); ?>/images/icons/medium/facebook.png" alt="CAS on Facebook"/></a></li>
<li><a href="http://vimeo.com/user3839407 "><img src="<?php bloginfo('template_directory'); ?>/images/icons/medium/vimeo.png" alt="CAS on Vimeo"/></a></li>
<li><a href="http://www.youtube.com/user/AfricaHarvard "><img src="<?php bloginfo('template_directory'); ?>/images/icons/medium/youtube.png" alt="CAS on YouTube"/></a></li>
</ul>
</div>
<div id="department_links">
<ul>
<li><a href="http://fas.harvard.edu">FAS</a></li>
<li><a>></a></li>
<li><a href="http://dubois.fas.harvard.edu/">DUBOIS INSTITUTE</a></li>
<li><a>></a></li>
<li><a href="http://aaas.fas.harvard.edu/">AAAS</a></li>
</ul>
</div>
<div id="admin_link">
<li><a href="<?php bloginfo('template_directory'); ?>/wp-admin">Admin Login</a></li>
</div>
</div>
<!--close content wrapper -->
</div>
<!--close body tag -->
</body>
</html><file_sep>/sidebar.php
<div id="navigation">
<?php
sidebar_main($page_id);
// dynamic_sidebar("menu"); ?>
</div><file_sep>/libs/droplicious.js
/*
droplicious v.1.0 Created May 21, 2009
Copyright @2009 http://headfirstproductions.ca Author: <NAME>
Contributors: <NAME> http://canada-jack.com, <NAME> http://www.masonmeyer.com
This software is licensed under the Creative Commons Attribution 2.5 Canada License
<http://creativecommons.org/licenses/by/2.5/ca//>
*/
var dropliciousShowingUpDuration = 0.35;
var dropliciousHidingDuration = 0.35;
var dropliciousHideDelay = .2;
function dropliciousShowingUpEffect(element){
if(!element.visible()){
new Effect.Appear(element, {
duration: dropliciousShowingUpDuration,
from: 0.0,
to: 0.7,
queue: {
position: 'end',
scope: element.identify(),
limit:2
}
});
}
}
function dropliciousHidingEffect(element){
new Effect.Fade(element, {
duration: dropliciousHidingDuration,
from: 0.7,
to: 0.0,
queue: {
position: 'end',
scope: element.identify(),
limit: 2
}
});
}
function setDelayedHide(element){
element.addClassName('waitingtohide')
if(!element.hasClassName('hidding')){
if (!element.hasClassName('hiddingtimerset')){
element.addClassName('hiddingtimerset');
setTimeout(function(){ delayedHide(element); }, dropliciousHideDelay * 1000);
}
}
}
function delayedHide(dropElement){
dropElement.removeClassName('hiddingtimerset');
if (dropElement.hasClassName('waitingtohide')){
dropliciousHidingEffect(dropElement);
dropElement.addClassName('hidding');
setTimeout(
function(){
dropElement.removeClassName('waitingtohide');
dropElement.removeClassName('hidding');
dropElement.removeClassName('active');
}, dropliciousHidingDuration * 1000);
}
}
function linkMouseOut(id){
var dropElement = id.element().next();
if (dropElement && dropElement.hasClassName('active')){
setDelayedHide(dropElement);
}
}
function linkMouseOver(id){
var dropElement = id.element().next();
if(dropElement){
if (!dropElement.hasClassName('hidding')){
dropElement.removeClassName('waitingtohide');
}
if (!dropElement.hasClassName('active')){
dropElement.addClassName('active');
dropliciousShowingUpEffect(dropElement);
}
}
}
function submenuMouseOut(event){
var dropElement = event.findElement("div");
if (dropElement && dropElement.hasClassName('active')){
setDelayedHide(dropElement);
}
}
function submenuMouseOver(event){
var dropElement = event.findElement("div");
if (dropElement && !dropElement.hasClassName('hidding')){
dropElement.removeClassName('waitingtohide');
}
}
document.observe('dom:loaded', function() {
$$('.landing_toggle').each(function(name) {
name.observe('mousemove', linkMouseOver.bindAsEventListener(this));
name.observe('mouseout', linkMouseOut.bindAsEventListener(this));
});
$$('.landing_content').each(function(name){
name.observe('mousemove', submenuMouseOver.bindAsEventListener(this));
name.observe('mouseout', submenuMouseOut.bindAsEventListener(this));
});
})<file_sep>/header.php
<?php
/*
* Template: Header.php
*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!--BEGIN html-->
<html xmlns="http://www.w3.org/1999/xhtml" <?php language_attributes(); ?>>
<head>
<title> </title>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<script type = "text/javascript" src ="<?php bloginfo('template_directory'); ?>/libs/prototype_old.js"></script>
<script type = "text/javascript" src ="<?php bloginfo('template_directory'); ?>/libs/effects_old.js"></script>
<script type = "text/javascript" src ="<?php bloginfo('template_directory'); ?>/libs/accordion.js"></script>
<script type = "text/javascript" src ="<?php bloginfo('template_directory'); ?>/libs/cas.js"></script>
<?php
if(is_page('multimedia')){
require_once('libs/multimedia_header.php');
}
?>
<?php require_once('libs/FirePHPCore/fb.php'); ?>
</head>
<body <?php body_class(); ?>>
<div id="wrapper">
<div id="header"><?php $search_text = "Search"; ?>
<form method="get" id="searchform"
action="<?php bloginfo('home'); ?>/">
<input type="text" value="<?php echo $search_text; ?>"
name="s" id="s"
onblur="if (this.value == '')
{this.value = '<?php echo $search_text; ?>';}"
onfocus="if (this.value == '<?php echo $search_text; ?>')
{this.value = '';}" />
<input type="hidden" id="searchsubmit" />
</form>
</div>
<div id="clear"></div>
<!--BEGIN #main-->
<div id="main">
<file_sep>/landing_header.php
<?php
/*
* Template: LandingHeader.php
*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!--BEGIN html-->
<html xmlns="http://www.w3.org/1999/xhtml" <?php language_attributes(); ?>>
<head>
<title> </title>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<script type = "text/javascript" src ="<?php bloginfo('template_directory'); ?>/libs/prototype.js"></script>
<script type = "text/javascript" src ="<?php bloginfo('template_directory'); ?>/libs/scriptaculous.js"></script>
<script type = "text/javascript" src ="<?php bloginfo('template_directory'); ?>/libs/effects.js"></script>
<script type = "text/javascript" src ="<?php bloginfo('template_directory'); ?>/libs/droplicious.js"></script>
<?php require_once('libs/FirePHPCore/fb.php'); ?>
</head>
<body <?php body_class(); ?>>
<div id="wrapper">
<div id="header">
<?php dynamic_sidebar('header'); ?>
</div>
<div id="clear"></div>
<!--BEGIN #main-->
<div id="main">
<file_sep>/news.php
<?php
/*
* Template Name: News
*
*/
?>
<?php get_header(); ?>
<?php get_sidebar(); ?>
<div id="content">
<?php
$page_data = get_page($page_id);
$content = $page_data->post_content;
$title = $page_data->post_title;
// $picture = $page_data->post_thumbnail;
$output .='<div id="page_header">';
$output .= '<h3>'.$title.'</h3>';
$output .= '</div';
$output .= '<div id="page_content">'.$content."</div>";
$output .= '<div id="news_container">';
query_posts(array('post_type'=>'News','orderby'=>'date'));
while(have_posts()) : the_post();
$data = get_post_custom(get_the_ID());
$output .= '<li><h5>'.get_the_title().'</h5></li>';
$output .= '<li class=" italic date">'.get_the_date().'</li>';
// $output .= '<li><p>'.$data['news_excerpt'][0].'</p></li>';
$output .= '<li class="">'.get_the_content().'</li>';
$output .= '<li style="text-align:right"><a href="'.$data['news_link'][0].'">Link to Original</a></li>';
endwhile;
$output .= '</div>';
echo $output;
?>
</div>
<?php get_footer(); ?>
<file_sep>/multimedia.php
<?php
/*
*
*¢
* Template Name: Multimedia
*
*
*
*/
?>
<?php
get_header();
get_sidebar();
?>
<div id="content">
<?php
$page_data = get_page($page_id);
$content = $page_data->post_content;
$title = $page_data->post_title;
// $picture = $page_data->post_thumbnail;
$output = '';
$output .='<div id="page_header">';
$output .= '<h3>'.$title.'</h3>';
$output .= '</div';
$output .= '<div id="page_content">'.$content."</div>";
echo $output;
$output = '<div id="accordion_container">';
$output .= '<li class="accordion_toggle"><a href="#" class="top-level">Videos</a></li>';
$output .= '<div class="accordion_content">';
$output .= '<div id="accordion_inner_container">';
$output .= '<li class="accordion_inner_toggle"><a href="#">Vimeo</a></li>';
$output .= '<div class="accordion_inner_content vimeo">';
echo $output;
dynamic_sidebar('Vimeo');
$output = '</div>';
$output .= '<li class="accordion_inner_toggle"><a href="#">YouTube</a></li>';
$output .= '<div class="accordion_inner_content">';
// youtube link
$output .= '
<div id="videoBar-bar">
<span style="color:#676767;font-size:11px;margin:10px;padding:4px;">Loading...</span>
</div>';
// close inner_content
$output .='</div>';
// closes inner_container
$output .= '</div>';
// closes content
$output .= '</div>';
$output .= '<li class="accordion_toggle"><a href="#" class="top-level">Twitter Feed</a></li>';
$output .= '<div class="accordion_content">';
$output .= '<div class="twitter_icon"></div><div class="twitter_content">';
echo $output;
twitter_messages('AfricaHarvard');
$output = '</div></div>';
$output .= '</div>';
echo $output;
?>
</div>
<?php get_footer(); ?>
|
c3dca195f504e66720b4c55f45bb5d925c3ced07
|
[
"Markdown",
"JavaScript",
"PHP"
] | 16
|
PHP
|
theophoric/CAS
|
7cb7e7ca38c9a1f11d8fafd5437e77433050a778
|
f634e55dc0b1a15dd5f79a1ff108394db130df9c
|
refs/heads/master
|
<file_sep>import React from 'react';
import crwn from '../images/crwn-clothing-project.PNG';
import monsters from '../images/monsters-rolodex-project.PNG';
import banking from '../images/piggy-banking-project.PNG';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSearchPlus } from '@fortawesome/free-solid-svg-icons';
import { PopupboxManager, PopupboxContainer } from 'react-popupbox';
import 'react-popupbox/dist/react-popupbox.css';
const Projects = () => {
//Monster Rolodex
const openPopupboxMonster = () => {
const content = (
<>
<img className="project-image-popupbox" src={monsters} alt="Monsters Rolodex" />
<p>
My first introduction to React.
<br />
Includes:
<br />
React Events, State vs Props, State Filtering and Searching, Class methods and Arrow Functions, Event Binding,
Asynchronous setState, and Lifecycle methods.
</p>
<b>Demo: </b>
<a className="hyper-link" onClick={() => window.open('https://nkwon320.github.io/monsters-rolodex/', '_blank')}>
https://nkwon320.github.io/monsters-rolodex/
</a>
<br />
<b> Github: </b>
<a className="hyper-link" onClick={() => window.open('https://github.com/nkwon320/monsters-rolodex')}>
https://github.com/nkwon320/monsters-rolodex
</a>
</>
);
PopupboxManager.open({ content });
};
const popupboxConfigMonster = {
titleBar: {
enable: true,
text: 'Monsters Rolodex Project'
},
fadeIn: true,
fadeInSpeed: 500
};
//Piggy Banking
const openPopupboxBanking = () => {
const content = (
<>
<img className="project-image-popupbox" src={banking} alt="Piggy Banking" />
<p>
Front-end Website created with React.
<br />
<br />
Includes:
<br />
Smooth-Scroll, Styled-Components, and React Router. Completely responsive. Works on mobile devices as well!
</p>
<b>Demo: </b>
<a className="hyper-link" onClick={() => window.open('https://piggy-banking.herokuapp.com/', '_blank')}>
https://piggy-banking.herokuapp.com/
</a>
<br />
<b> Github: </b>
<a className="hyper-link" onClick={() => window.open('https://github.com/nkwon320/piggy-banking')}>
https://github.com/nkwon320/piggy-banking
</a>
</>
);
PopupboxManager.open({ content });
};
const popupboxConfigBanking = {
titleBar: {
enable: true,
text: 'Piggy Banking Project - Front End'
},
fadeIn: true,
fadeInSpeed: 500
};
//Crwn-Clothing
const openPopupboxCrwn = () => {
const content = (
<>
<img className="project-image-popupbox" src={crwn} alt="Crwn Clothing" />
<p>
Ongoing project.
<br />
Includes:
<br />
React basics, React Router, Redux, Redux Saga, Asynchronous Redux, React Hooks, Context API, Firebase, Stripe
API, Signin/Signout functionality with Google Signin as well, and Styled-Components.
<br />
<br />
Will Add Soon:
<br /> GraphQL, Apollo, and mobile phone optimization.
</p>
<b>Demo: </b>
<a className="hyper-link" onClick={() => window.open('https://noah-crwn-live.herokuapp.com/', '_blank')}>
https://noah-crwn-live.herokuapp.com/
</a>
<br />
<b> Github: </b>
<a className="hyper-link" onClick={() => window.open('https://github.com/nkwon320/crwn-clothing')}>
https://github.com/nkwon320/crwn-clothing
</a>
</>
);
PopupboxManager.open({ content });
};
const popupboxConfigCrwn = {
titleBar: {
enable: true,
text: 'Crwn Clothing React App'
},
fadeIn: true,
fadeInSpeed: 500
};
return (
<div id="projects" className="project-wrapper">
<div className="container">
<h1 className="text-uppercase text-center py-5">Projects</h1>
<div className="image-box-wrapper row justify-content-center">
<div className="project-image-box" onClick={openPopupboxMonster}>
<img className="projects-img" src={monsters} alt="Monsters Rolodex" />
<div className="overflow"></div>
<FontAwesomeIcon className="project-icon" icon={faSearchPlus} />
</div>
<div className="project-image-box" onClick={openPopupboxBanking}>
<img className="projects-img" src={banking} alt="Piggy Banking Front End" />
<div className="overflow"></div>
<FontAwesomeIcon className="project-icon" icon={faSearchPlus} />
</div>
<div className="project-image-box" onClick={openPopupboxCrwn}>
<img className="projects-img" src={crwn} alt="Crwn-Clothing" />
<div className="overflow"></div>
<FontAwesomeIcon className="project-icon" icon={faSearchPlus} />
</div>
</div>
</div>
<PopupboxContainer {...popupboxConfigMonster} />
<PopupboxContainer {...popupboxConfigBanking} />
<PopupboxContainer {...popupboxConfigCrwn} />
</div>
);
};
export default Projects;
<file_sep>import React from 'react';
const Experience = () => {
return (
<div id="experience" className="experience">
<div className="d-flex justify-content-center my-5">
<h1>experience</h1>
</div>
<div className="container experience-wrapper">
<div className="timeline-block timeline-block-right">
<div className="marker"></div>
<div className="timeline-content">
<h3>2018</h3>
<h3>Human Resources Consultant - Dynamic Signal</h3>
<p>
- Updated training processes by reviewing existing documentation, leveraging feedback from associates, and
working with legal and compliance teams.
<br />
- Liaised between multiple business devisions to improve communications.
<br />
- Facilitated cultural integration planning and developed strategies to foster employee engagement and
commitment.
<br />- Partnered with senior leadership to establish and develop corporate and HR policies and
procedures.
</p>
</div>
</div>
<div className="timeline-block timeline-block-left">
<div className="marker"></div>
<div className="timeline-content">
<h3>2019</h3>
<h3>Workplace Coordinator - Illumio</h3>
<p>
- Coordinated and executed all elements of company events including logistics, budgets, venue selection,
activity planning, transportation and entertainment.
<br />
- Managed office activities by maintaining communication between clients, tracking records and filing all
documents.
<br />
- Maintained accurate, current and compliant financial records by monitoring and addressing variances.
<br />- Oversaw expenditures and worked with accounting department to manage budgets.
</p>
</div>
</div>
<div className="timeline-block timeline-block-right">
<div className="marker"></div>
<div className="timeline-content">
<h3>2020 - Career Change!</h3>
<h3>Coding Dojo Bootcamp</h3>
<p>
- Through this 14 week coding boot-camp, I learned three Full Stacks of web dev languages.
<br />
- Understanding of each language was tested through timed exams to replicate functionality and user
interface.
<br />- Spend 1000+ hours coding, completed ~60 assignments/projects, and 80+ whiteboard algorithm
sessions.
</p>
</div>
</div>
</div>
</div>
);
};
export default Experience;
<file_sep>import React from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPython, faReact, faJava } from '@fortawesome/free-brands-svg-icons';
import { faFileCode } from '@fortawesome/free-solid-svg-icons';
const Services = () => {
return (
<div id="services" className="services">
<h1 className="py-5">languages</h1>
<div className="container">
<div className="row">
<div className="col-lg-3 col-md-6 col-sm-6">
<div className="box">
<div className="circle">
<FontAwesomeIcon className="icon" icon={faFileCode} size="2x" />
</div>
<h3>HTML/CSS/JS</h3>
<p>
HTML 5
<br />
CSS 3
<br />
jQuery
<br />
Bootstrap
</p>
</div>
</div>
<div className="col-lg-3 col-md-6 col-sm-6">
<div className="box">
<div className="circle">
<FontAwesomeIcon className="icon" icon={faPython} size="2x" />
</div>
<h3>Python</h3>
<p>
Flask
<br />
MySQL
<br />
Ajax
<br />
APIs
<br />
Django
</p>
</div>
</div>
<div className="col-lg-3 col-md-6 col-sm-6">
<div className="box">
<div className="circle">
<FontAwesomeIcon className="icon" icon={faJava} size="2x" />
</div>
<h3>Java</h3>
<p>
Spring MVC
<br />
MySQL
</p>
</div>
</div>
<div className="col-lg-3 col-md-6 col-sm-6">
<div className="box">
<div className="circle">
<FontAwesomeIcon className="icon" icon={faReact} size="2x" />
</div>
<h3>React</h3>
<p>
Redux & Redux Saga
<br />
Hooks
<br />
Context API
<br />
Styled-Components
<br />
Firebase
<br />
Stripe API
</p>
</div>
</div>
</div>
</div>
</div>
);
};
export default Services;
|
b86c829bd5a5ccdc401b6e40e050ed4a338f8ade
|
[
"JavaScript"
] | 3
|
JavaScript
|
nkwon320/portfolio-project
|
0516d1f47628b6af8dbec01e51dbd55ff5957535
|
500d92c9e47a5d8fa568a818670320fc2b8a678a
|
refs/heads/master
|
<file_sep>robot_setting = '*** Settings ***\nResource ../setup.txt\n'
robot_variables = '*** Variables ***\n'
robot_testcases = '*** Test Cases ***\n'
robot_keywords = '*** Keywords ***\n'
case = {
u'created_by': 2,
u'created_on': 1447143173,
u'custom_auto_complexity': None,
u'custom_automated_status': 1,
u'custom_case_note': None,
u'custom_case_status': 3,
u'custom_estimate': 1,
u'custom_platform': [1, 2, 3, 4, 5, 6, 7],
u'custom_preconds': u'KKBOX \u672a\u767b\u5165\u3002\r\n',
u'custom_steps_separated': [
{u'content': u'\u7528\u96fb\u5b50\u90f5\u4ef6/FB \u767b\u5165',u'expected': u'\u767b\u5165\u6210\u529f'},
{u'content': u'\u767b\u51fa', u'expected': u'\u767b\u51fa\u6210\u529f'},
{u'content': u'\u7528\u6b65\u9a5f 1 \u76f8\u540c\u7684\u65b9\u5f0f\u518d\u767b\u5165\u4e00\u6b21',u'expected': u'\u767b\u5165\u6210\u529f'}],
u'estimate': None,
u'estimate_forecast': None,
u'id': 1234,
u'milestone_id': None,
u'priority_id': 2,
u'refs': None,
u'section_id': 320,
u'suite_id': 29,
u'title': u'\u540c\u4e00\u500b\u5e33\u865f\u53ef\u4ee5\u91cd\u8907\u767b\u5165/\u767b\u51fa',
u'type_id': 6,
u'updated_by': 2,
u'updated_on': 1449564379}
setting = robot_setting
title = robot_testcases + case['title']
tag = {
'doc': ' [Documentation]',
'setup': ' [Setup]',
'tags': ' [Tags]'}
# TODO If there are precondition displayed, add '[setup] Preconditions'
# and Keywords Preconditions
# TODO Check content and expect inside have '\n' or not
# TODO detect 'for xxx', if is showing not write in case
steps = ""
for num in range(len(case[u'custom_steps_separated'])):
steps += (' ' + case[u'custom_steps_separated'][num][u'content'] + ', ' + case[u'custom_steps_separated'][num][u'expected'] + '\n')
keywords = robot_keywords + ""
for num in range(len(case[u'custom_steps_separated'])):
keywords += (case[u'custom_steps_separated'][num][u'content'] + ', ' + case[u'custom_steps_separated'][num][u'expected'] + '\n')
final = setting +'\n' + title + steps + '\n' + keywords
print final
<file_sep># test-automation-tool
## Test Case generator
Generate a plain text file from Testrail and suit for robotframework
###Usage:
* Generate file to default place
`$ ./case-generator <test case id>`
`$ ./case-gennerator 6799`
* Generate file to some folder
`$ ./case-generator <test case id> <specific folder>`
`$ ./case-generator 6799 album-more`
## Config generator
Detect serial number of android devices and set information that appium need
###Usage:
`$ python config_generator.py`
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from testrail import *
import sys
import os, path
file_dir = os.path.dirname(os.path.abspath(__file__))
try:
case_number = 'get_case/' + sys.argv[1]
except IndexError:
raise IndexError("You Should Input Test Case Number.")
client = APIClient('<Your testrail URL>')
client.user = '<testrail_account>'
client.password = '<<PASSWORD>>'
case = client.send_get(case_number)
robot_setting = '*** Settings ***\nResource ../setup.txt\n'
robot_variables = '*** Variables ***\n'
robot_testcases = '*** Test Cases ***\n'
robot_keywords = '*** Keywords ***\n'
setting = robot_setting
title = robot_testcases + case['title'] + '\n'
label = {
'doc': ' [Documentation] ',
'setup': ' [Setup] ',
'tags': ' [Tags] '}
steps = ""
keywords = robot_keywords
# tag process
# preconditions process
if case[u'custom_preconds']: # empty preconditions will return none
steps += label['setup'] + 'Preconditions\n'
keywords += 'Preconditions\n'
for num in range(len(case[u'custom_steps_separated'])):
if len(case[u'custom_steps_separated'][num][u'expected']) == 0:
steps += (' ' + case[u'custom_steps_separated'][num][u'content'] + '\n')
else:
steps += (' ' + case[u'custom_steps_separated'][num][u'content'] + ', ' + case[u'custom_steps_separated'][num][u'expected'].replace('\n', " ") + '\n')
for num in range(len(case[u'custom_steps_separated'])):
if len(case[u'custom_steps_separated'][num][u'expected']) == 0:
keywords += (case[u'custom_steps_separated'][num][u'content'] + '\n')
else:
keywords += (case[u'custom_steps_separated'][num][u'content'] + ', ' + case[u'custom_steps_separated'][num][u'expected'].replace('\n', " ") + '\n')
final = setting +'\n' + title + steps + '\n' + keywords
if not os.path.exists(file_dir + "/output/"):
os.mkdir(file_dir + "/output/")
output_file = open(file_dir + "/output/c" + sys.argv[1] + ".txt", "w")
output_file.write(final.encode('utf8'))
print "output: " + output_file.name
output_file.close()
try:
if sys.argv[2]:
kkauto_dir = os.path.abspath(os.path.join(file_dir, "../../"))
desination = kkauto_dir + '/test/kkbox/' + sys.argv[2] + '/'
file_name_in_new_desination = kkauto_dir + '/test/kkbox/' + sys.argv[2] + "/c" + sys.argv[1] + ".txt"
if os.path.exists(desination):
result = os.rename(output_file.name, file_name_in_new_desination)
else:
print 'folder not exists'
except IndexError as a:
print "Second Argument: You can input name of suite to move there"
print "move to: " + desination
<file_sep># -*- coding: utf-8 -*-
"""
Desription:
Warning: this script will modify ~/.kkauto.cfg
After execute this script
You need to edit ~/.account.cfg to append more account for deviecs
Athor: <NAME>
"""
import subprocess
import logging
import os.path as path
from ConfigParser import RawConfigParser
logger = logging.getLogger(__name__)
class ConfigWriter():
def __init__(self):
# Location of kkauto.cfg file
# store basic device information to connect appium
self.config_dir = path.expanduser('~/')
self.config_file_name = '.kkauto.cfg'
self.config_location = path.join(self.config_dir,
self.config_file_name)
self.config = RawConfigParser()
self.requests = ['platform', 'platform.version', 'name']
self.appium_connect = ['remote.port', 'remote.host']
self.appium_port = 4723
self.port_idx = 0
self.config_start()
def config_start(self):
self.config_file = open(self.config_location, 'w')
def set_local_apk(self, platform, file_path):
self.config.add_section('kkbox')
if platform == 'android':
self.config.set('kkbox', 'android.app-path', file_path)
elif platform == 'ios':
self.config.set('kkbox', 'ios.app-path', file_path)
def set_default_serialno(self, platform ,device_id):
if platform == 'android':
# [android]
# default-serialno=<ANDROID_SERIALNO>
if not self.config.has_section('android'):
self.config.add_section('android')
print 'android-default add'
self.config.set('android', 'default-serialno', device_id)
else:
#self.config.remove_section('android')
print 'section = [android] already existeds'
elif platform == 'ios':
# [ios]
# default-udid=<IOS_UDID>
if not self.config.has_section('ios'):
self.config.add_section('ios')
print 'ios-default add'
self.config.set('ios', 'default-udid', device_id)
else:
#self.config.remove_section('ios')
print 'section = [ios] already existed'
elif platform == 'device':
# [device]
# default-serialno=<ANDROID_SERIALNO>
if not self.config.has_section('device'):
self.config.add_section('device')
print 'android-default add'
self.config.set('device', 'default-serialno', device_id)
else:
#self.config.remove_section('device')
print 'section = [device] already existed'
def set_default_udid(self, udid):
device_sect = self.id_format(udid)
if not self.config.has_section(udid):
self.config.add_section(device_sect)
def get_devices_id(self):
"Return andoid devices id with list"
command = 'adb devices'
ids = subprocess.check_output(command, shell=True)
ids = ids.strip('\n').replace('\tdevice',"").split('\n')
ids.pop(0)
return ids
def get_property(self, device_id, prop):
""" Get device property by device_id
Properties Example:
[net.bt.name]: [Android]
[ro.product.brand]: [Android]
[dhcp.wlan0.gateway]: [192.168.0.1]
[ro.build.version.release]: [5.0.2]
[ro.build.version.sdk]: [21]
[ro.product.brand]: [InFocus]
[ro.product.model]: [InFocus M810]
[ro.product.manufacturer]: [InFocus]
"""
property_dic = {'platform.version': 'ro.build.version.release',
'platform': 'net.bt.name',
'name': 'ro.product.model'}
command = 'adb -s ' + device_id + ' shell getprop ' + property_dic[prop]
#print 'command: ', command
result = subprocess.check_output(command, shell=True).strip('\n').strip('\r')
#print 'value: ', result
return result
def id_format(self, device_id):
return 'device-%s' % device_id
def _option_process(self, device_id, option_list):
device_sect = self.id_format(device_id)
if not self.config.has_section(device_sect):
self.config.add_section(device_sect)
for option in option_list:
self.config.set(device_sect, option, self.get_property(device_id, option))
else:
print 'section = [%s] already existed' % device_sect
#self.config.remove_section(device_sect)
def set_device_config_ios(self, device_id='<IOS_UDID>'):
self._option_process(device_id, self.requests)
def set_device_config(self, device_id=''):
self._option_process(device_id, self.requests)
def set_appium_config(self, device_id):
device_sect = self.id_format(device_id)
if not self.config.has_section(device_sect):
self.config.add_section(device_sect)
self.config.set(device_sect, self.appium_connect[0], self.appium_port + self.port_idx)
self.port_idx += 2
def _set_status(self, device_id, status):
device_sect = self.id_format(device_id)
self.config.set(device_sect, 'status', status)
def set_device_available(self, device_id):
self._set_status(device_id, 'available')
def set_device_busy(self, device_id):
self._set_status(device_id, 'busy')
def config_close(self):
self.config.write(self.config_file)
self.config_file.close()
# remove swp in vim
command = 'rm ' + '~/.kkauto.cfg.swp'
if path.exists(path.join(self.config_location, '.swp')):
subprocess.check_output(command, shell=True)
def get_sections(self):
return self.config.sections()
def get_options(self, section):
return self.config.options(section)
def get_option(self, section, option):
return self.config.get(section, option)
def get_port(self, section):
return self.get_option(section, 'remote.port')
def remove_all_sections(self):
for section in self.get_sections():
self.config.remove_section(section)
def set_account_config(self, device_id, product, information, value):
device_sect = self.id_format(device_id)
opt = "%s_%s" % (product, information)
self.config.set(device_sect, opt, value)
class AccountWriter():
def __init__(self):
# Location of account.cfg file
# Store account information
self.account_dir = path.expanduser('~/')
self.account_file_name = '.account.cfg'
self.account_config_location = path.join(self.account_dir,
self.account_file_name)
self.account_config = RawConfigParser()
if path.exists(self.account_config_location):
self.account_config.read(self.account_config_location)
def set_example(self):
if not path.exists(self.account_config_location):
self.account_config_file = open(self.account_config_location, 'w+')
self.account_config.add_section('product-account-0')
self.account_config.set('product-account-0', ";= This is a example", "")
self.account_config.set('product-account-0', 'account', 'account')
self.account_config.set('product-account-0', 'password', '<PASSWORD>')
self.account_config.write(self.account_config_file)
self.account_config_file.close()
assert False, "No Accouts information file.\n" + \
"Example of configuration added\n" + \
"Please add account to this file: %s\n" % \
self.account_config_location + \
"You can add more account for KKBOX like this: \n[KKBOX-account-1]\n" + \
"account = <EMAIL>\n" + \
"password = <PASSWORD>"
else:
print "sample existed in Account file"
def get_account_sections(self):
if len(self.account_config.sections()) <= 1:
self.set_example()
return 0 # for no account config
else:
result = self.account_config.sections()
result.pop(0) # remove example
return result
def get_account_option(self, section, option):
return self.account_config.get(section, option)
class AppiumControler():
def __init__(self):
self.port = 4723
self.bootstrap_port = self.port + 1
self.command = 'appium --command-timeout 9999 \
--session-override \
--port %d \
--bootstrap %d' % (self.port, self.bootstrap_port)
if __name__ == '__main__':
c = ConfigWriter()
a = AccountWriter()
appium = AppiumControler()
idx = 0
accounts = a.get_account_sections()
device_ids = c.get_devices_id()
if len(device_ids) == 0:
c.remove_all_sections()
assert False, "No devices existed. Please plugin devices"
elif len(device_ids) > len(accounts):
assert False, "Not enought account for devices"
else:
c.remove_all_sections()
# For robot framework default variable
c.set_default_serialno('ios', '<uuid>')
c.set_default_serialno('android', device_ids[0])
print 'Set android default-serialno with %s' % device_ids[0]
# Add config to device
for device in device_ids:
c.set_device_config(device)
c.set_appium_config(device)
uid = a.get_account_option(accounts[idx], 'account')
pwd = a.get_account_option(accounts[idx], 'password')
c.set_account_config(device, 'kkbox', 'account', uid)
c.set_account_config(device, 'kkbox', 'password', pwd)
idx += 1
# Writing and saving to kkauto.cfg
c.config_close()
# Read kkauto.cfg to get device option
all_devices = c.get_sections()[2:]
print 'You got %d devices' % len(all_devices)
print 'device list:', all_devices
#for device in all_devices:
# print c.get_options(device)
# print c.get_port(device)
# No devices + No account
# One devices with No account
#
|
c105dbfeeb8eb81d151b783dbfc3216a7e5d5363
|
[
"Markdown",
"Python"
] | 4
|
Python
|
canyugs/test-automation-tool
|
a69f2793e125ccf0cf6a6d641b00f314ffca4e77
|
d3b5f830c3d2d983f305ed9792c7a6c33b7e019e
|
refs/heads/master
|
<repo_name>hummans/WhatsApp-Contacts<file_sep>/README.md
# WhatsApp-Contacts
A simple app that fetch your WhatsApp contacts 📱
# Installation
Clone this repository and import into Android Studio
```git clone https://github.com/ayshiff/WhatsApp-Contacts.git```
# Build variants
Use the Android Studio Build Variants button to choose between production and staging flavors combined with debug and release build types
## Generating signed APK
From Android Studio:
- Build menu
- Build APK(s)...
# What's next ?
- [ ] IOS
- [ ] Fetch photos from contacts
- [ ] Design
- [ ] Add favorites contacts
# Contributing
- Fork it
- Create your feature branch (git checkout -b my-new-feature)
- Commit your changes (git commit -m 'Add some feature')
- Push your branch (git push origin my-new-feature)
- Create a new Pull Request
# Reference for help
This is the way contacts are stored in android :

<file_sep>/app/src/main/java/com/ramdoo/ramdo/whatsapp/MainActivity.java
package com.ramdoo.ramdo.whatsapp;
import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static java.lang.Long.parseLong;
/**
* Main class
*/
public class MainActivity extends Activity {
private ArrayList<Map<String, String>> contacts;
private ListView contactsListView;
private ArrayList<String> photoList = new ArrayList<>();
private ArrayAdapter arrayAdapter;
/**
*
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_whatsapp);
getPermissionToReadUserContacts();
contactsListView = (ListView) findViewById(R.id.listWhatsAppContacts);
String[] from = { "ContactName" , "ContactNumber" };
int[] to = { R.id.txtName, R.id.txtNumber };
contacts = fetchWhatsAppContacts();
SimpleAdapter adapter = new SimpleAdapter(this, contacts, R.layout.list_whatsapp, from, to);
/**
* Adding photo support
*/
/*
arrayAdapter = new ArrayAdapter(this, R.layout.list_whatsapp, photoList);
contactsListView.setAdapter(arrayAdapter); */
contactsListView.setAdapter(adapter);
}
/**
*
* @param ContactName
* @param ContactNumber
* @return HashMap<String, String>()
*/
private HashMap<String, String> pushData(String ContactName, String ContactNumber) {
HashMap<String, String> item = new HashMap<String, String>();
item.put("ContactName", ContactName);
item.put("ContactNumber", ContactNumber);
return item;
}
/**
*
* @return ArrayList<Map<String,String>>()
*/
private ArrayList<Map<String, String>> fetchWhatsAppContacts(){
ArrayList<Map<String, String>> list = new ArrayList<Map<String,String>>();
final String[] projection={
ContactsContract.Data.CONTACT_ID,
ContactsContract.Data.MIMETYPE,
"account_type",
ContactsContract.Data.DATA1,
ContactsContract.Data.PHOTO_URI,
};
final String selection= ContactsContract.Data.MIMETYPE+" =? and account_type=?";
final String[] selectionArgs = {
"vnd.android.cursor.item/vnd.com.whatsapp.profile",
"com.whatsapp"
};
ContentResolver cr = getContentResolver();
Cursor c = cr.query(
ContactsContract.Data.CONTENT_URI,
projection,
selection,
selectionArgs,
null);
while(c.moveToNext()){
String id=c.getString(c.getColumnIndex(ContactsContract.Data.CONTACT_ID));
String numberW=c.getString(c.getColumnIndex(ContactsContract.Data.DATA1));
String[] parts = numberW.split("@");
String numberPhone = parts[0];
String number = "Tel : + " + numberPhone.substring(0, 2) + " " + numberPhone.substring(2, numberPhone.length());
String image_uri = c.getString(c.getColumnIndex(ContactsContract.Contacts.PHOTO_URI));
photoList.add(image_uri);
String name="";
Cursor mCursor=getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI,
new String[]{ContactsContract.Contacts.DISPLAY_NAME},
ContactsContract.Contacts._ID+" =?",
new String[]{id},
null);
while(mCursor.moveToNext()){
name=mCursor.getString(mCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
mCursor.close();
list.add(pushData(name, number));
}
return list;
}
// Identifier for the permission request
private static final int READ_CONTACTS_PERMISSIONS_REQUEST = 1;
/**
*
* Called when the user is performing an action which requires the app to read the user's contacts
*/
public void getPermissionToReadUserContacts() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// The permission is NOT already granted.
if (shouldShowRequestPermissionRationale(
Manifest.permission.READ_CONTACTS)) {
}
// This will show the standard permission request dialog UI
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS},
READ_CONTACTS_PERMISSIONS_REQUEST);
}
}
/**
*
* @param requestCode
* @param permissions
* @param grantResults
* Callback with the request from calling requestPermissions(...)
*/
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[],
@NonNull int[] grantResults) {
if (requestCode == READ_CONTACTS_PERMISSIONS_REQUEST) {
if (grantResults.length == 1 &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Read Contacts permission granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Read Contacts permission denied", Toast.LENGTH_SHORT).show();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
|
d3fb14433e3724b208c398bbb01fae6e98216943
|
[
"Markdown",
"Java"
] | 2
|
Markdown
|
hummans/WhatsApp-Contacts
|
917b10c2a8e1fcc3651be4d06c8b9e51d55c4f91
|
3628ee8d294a241fe1f515cb420cd182ab5cbe1e
|
refs/heads/master
|
<file_sep>package types
import (
"testing"
hubtypes "github.com/sentinel-official/hub/types"
)
func TestProvider_Validate(t *testing.T) {
correctAddress := hubtypes.ProvAddress{}
// we dont need to check for contents of the error message, checking whether the error is nil/not-nil is enough.
tests := []struct {
name string
p Provider
}{
{"address zero", Provider{"", "", "", "", ""}},
{"address empty", Provider{correctAddress.String(), "", "", "", ""}},
{"name length zero", Provider{correctAddress.String(), "", "", "", ""}},
{"name length greater than 64", Provider{correctAddress.String(), GT64, "", "", ""}},
{"identity length greater than 64", Provider{correctAddress.String(), "name", GT64, "", ""}},
{"website length greater than 64", Provider{correctAddress.String(), "name", "", GT64, ""}},
{"description length greater than 256", Provider{correctAddress.String(), "name", "", "", GT256}},
{"valid", Provider{correctAddress.String(), "name", "", "", ""}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.p.Validate()
if err == nil && tt.name != "valid" {
t.Errorf("Validate() error = %v", err)
}
})
}
}
<file_sep>package keeper
import (
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/subscription/types"
)
func (k *Keeper) SetQuota(ctx sdk.Context, id uint64, quota types.Quota) {
key := types.QuotaKey(id, quota.GetAddress())
value := k.cdc.MustMarshalBinaryBare("a)
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) GetQuota(ctx sdk.Context, id uint64, address sdk.AccAddress) (quota types.Quota, found bool) {
store := k.Store(ctx)
key := types.QuotaKey(id, address)
value := store.Get(key)
if value == nil {
return quota, false
}
k.cdc.MustUnmarshalBinaryBare(value, "a)
return quota, true
}
func (k *Keeper) HasQuota(ctx sdk.Context, id uint64, address sdk.AccAddress) bool {
key := types.QuotaKey(id, address)
store := k.Store(ctx)
return store.Has(key)
}
func (k *Keeper) DeleteQuota(ctx sdk.Context, id uint64, address sdk.AccAddress) {
key := types.QuotaKey(id, address)
store := k.Store(ctx)
store.Delete(key)
}
func (k *Keeper) GetQuotas(ctx sdk.Context, id uint64, skip, limit int64) (items types.Quotas) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.GetQuotaKeyPrefix(id)),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
var item types.Quota
k.cdc.MustUnmarshalBinaryBare(iter.Value(), &item)
items = append(items, item)
})
return items
}
func (k *Keeper) IterateQuotas(ctx sdk.Context, id uint64, fn func(index int, item types.Quota) (stop bool)) {
store := k.Store(ctx)
iter := sdk.KVStorePrefixIterator(store, types.GetQuotaKeyPrefix(id))
defer iter.Close()
for i := 0; iter.Valid(); iter.Next() {
var quota types.Quota
k.cdc.MustUnmarshalBinaryBare(iter.Value(), "a)
if stop := fn(i, quota); stop {
break
}
i++
}
}
<file_sep>package types
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
)
func (q *Quota) GetAddress() sdk.AccAddress {
if q.Address == "" {
return nil
}
address, err := sdk.AccAddressFromBech32(q.Address)
if err != nil {
panic(err)
}
return address
}
func (q *Quota) Validate() error {
if _, err := sdk.AccAddressFromBech32(q.Address); err != nil {
return fmt.Errorf("address should not be nil or empty")
}
if q.Consumed.IsNegative() {
return fmt.Errorf("consumed should not be negative")
}
if q.Allocated.IsNegative() {
return fmt.Errorf("allocated should not be negative")
}
if q.Consumed.GT(q.Allocated) {
return fmt.Errorf("consumed should not be greater than allocated")
}
return nil
}
type Quotas []Quota
<file_sep>package types
import (
"github.com/cosmos/cosmos-sdk/types/errors"
)
var (
ErrorInvalidField = errors.Register(ModuleName, 101, "invalid field")
ErrorPlanDoesNotExist = errors.Register(ModuleName, 102, "plan does not exist")
ErrorNodeDoesNotExist = errors.Register(ModuleName, 103, "node does not exist")
ErrorUnauthorized = errors.Register(ModuleName, 104, "unauthorized")
ErrorInvalidPlanStatus = errors.Register(ModuleName, 105, "invalid plan status")
ErrorPriceDoesNotExist = errors.Register(ModuleName, 106, "price does not exist")
ErrorInvalidNodeStatus = errors.Register(ModuleName, 107, "invalid node status")
ErrorSubscriptionDoesNotExist = errors.Register(ModuleName, 108, "subscription does not exist")
ErrorInvalidSubscriptionStatus = errors.Register(ModuleName, 109, "invalid subscription status")
ErrorCanNotSubscribe = errors.Register(ModuleName, 110, "can not subscribe")
ErrorInvalidQuota = errors.Register(ModuleName, 111, "invalid quota")
ErrorDuplicateQuota = errors.Register(ModuleName, 112, "duplicate quota")
ErrorQuotaDoesNotExist = errors.Register(ModuleName, 113, "quota does not exist")
ErrorCanNotAddQuota = errors.Register(ModuleName, 114, "can not add quota")
)
<file_sep>package types
import (
"github.com/cosmos/cosmos-sdk/types/errors"
)
var (
ErrorInvalidField = errors.Register(ModuleName, 101, "invalid field")
ErrorProviderDoesNotExist = errors.Register(ModuleName, 102, "provider does not exist")
ErrorPlanDoesNotExist = errors.Register(ModuleName, 103, "plan does not exist")
ErrorNodeDoesNotExist = errors.Register(ModuleName, 104, "node does not exist")
ErrorUnauthorized = errors.Register(ModuleName, 105, "unauthorized")
DuplicateNodeForPlan = errors.Register(ModuleName, 106, "duplicate node for plan")
)
<file_sep>package v05
import (
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
legacyhubtypes "github.com/sentinel-official/hub/types/legacy/v0.5"
)
type (
Session struct {
ID uint64 `json:"id"`
Subscription uint64 `json:"subscription"`
Node hubtypes.NodeAddress `json:"node"`
Address sdk.AccAddress `json:"address"`
Duration time.Duration `json:"duration"`
Bandwidth legacyhubtypes.Bandwidth `json:"bandwidth"`
Status legacyhubtypes.Status `json:"status"`
StatusAt time.Time `json:"status_at"`
}
Sessions []Session
)
<file_sep>package v06
import (
"github.com/sentinel-official/hub/x/swap/types"
legacy "github.com/sentinel-official/hub/x/swap/types/legacy/v0.5"
)
func MigrateSwap(item legacy.Swap) types.Swap {
return types.Swap{
TxHash: item.TxHash.Bytes(),
Receiver: item.Receiver.String(),
Amount: item.Amount,
}
}
func MigrateSwaps(items legacy.Swaps) types.Swaps {
var swaps types.Swaps
for _, item := range items {
swaps = append(swaps, MigrateSwap(item))
}
return swaps
}
<file_sep>package v06
import (
"github.com/sentinel-official/hub/x/subscription/types"
legacy "github.com/sentinel-official/hub/x/subscription/types/legacy/v0.5"
)
func MigrateParams(params legacy.Params) types.Params {
return types.Params{
InactiveDuration: params.InactiveDuration,
}
}
<file_sep>package keeper
import (
"context"
"strings"
"github.com/cosmos/cosmos-sdk/store/prefix"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/query"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/subscription/types"
)
var (
_ types.QueryServiceServer = (*queryServer)(nil)
)
type queryServer struct {
Keeper
}
func NewQueryServiceServer(keeper Keeper) types.QueryServiceServer {
return &queryServer{Keeper: keeper}
}
func (q *queryServer) QuerySubscription(c context.Context, req *types.QuerySubscriptionRequest) (*types.QuerySubscriptionResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
ctx := sdk.UnwrapSDKContext(c)
item, found := q.GetSubscription(ctx, req.Id)
if !found {
return nil, status.Errorf(codes.NotFound, "subscription does not exist for id %d", req.Id)
}
return &types.QuerySubscriptionResponse{Subscription: item}, nil
}
func (q *queryServer) QuerySubscriptions(c context.Context, req *types.QuerySubscriptionsRequest) (*types.QuerySubscriptionsResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
var (
items types.Subscriptions
ctx = sdk.UnwrapSDKContext(c)
store = prefix.NewStore(q.Store(ctx), types.SubscriptionKeyPrefix)
)
pagination, err := query.FilteredPaginate(store, req.Pagination, func(_, value []byte, accumulate bool) (bool, error) {
var item types.Subscription
if err := q.cdc.UnmarshalBinaryBare(value, &item); err != nil {
return false, err
}
if accumulate {
items = append(items, item)
}
return true, nil
})
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &types.QuerySubscriptionsResponse{Subscriptions: items, Pagination: pagination}, nil
}
func (q *queryServer) QuerySubscriptionsForNode(c context.Context, req *types.QuerySubscriptionsForNodeRequest) (*types.QuerySubscriptionsForNodeResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
address, err := hubtypes.NodeAddressFromBech32(req.Address)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid address %s", req.Address)
}
var (
items types.Subscriptions
ctx = sdk.UnwrapSDKContext(c)
store = prefix.NewStore(q.Store(ctx), types.GetSubscriptionForNodeKeyPrefix(address))
)
pagination, err := query.FilteredPaginate(store, req.Pagination, func(key, _ []byte, accumulate bool) (bool, error) {
item, found := q.GetSubscription(ctx, sdk.BigEndianToUint64(key))
if !found {
return false, nil
}
if accumulate {
items = append(items, item)
}
return true, nil
})
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &types.QuerySubscriptionsForNodeResponse{Subscriptions: items, Pagination: pagination}, nil
}
func (q *queryServer) QuerySubscriptionsForPlan(c context.Context, req *types.QuerySubscriptionsForPlanRequest) (*types.QuerySubscriptionsForPlanResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
var (
items types.Subscriptions
ctx = sdk.UnwrapSDKContext(c)
store = prefix.NewStore(q.Store(ctx), types.GetSubscriptionForPlanKeyPrefix(req.Id))
)
pagination, err := query.FilteredPaginate(store, req.Pagination, func(key, _ []byte, accumulate bool) (bool, error) {
item, found := q.GetSubscription(ctx, sdk.BigEndianToUint64(key))
if !found {
return false, nil
}
if accumulate {
items = append(items, item)
}
return true, nil
})
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &types.QuerySubscriptionsForPlanResponse{Subscriptions: items, Pagination: pagination}, nil
}
func (q *queryServer) QuerySubscriptionsForAddress(c context.Context, req *types.QuerySubscriptionsForAddressRequest) (*types.QuerySubscriptionsForAddressResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
address, err := sdk.AccAddressFromBech32(req.Address)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid address %s", req.Address)
}
var (
items types.Subscriptions
pagination *query.PageResponse
ctx = sdk.UnwrapSDKContext(c)
)
if req.Status.Equal(hubtypes.Active) {
store := prefix.NewStore(q.Store(ctx), types.GetActiveSubscriptionForAddressKeyPrefix(address))
pagination, err = query.FilteredPaginate(store, req.Pagination, func(key, _ []byte, accumulate bool) (bool, error) {
item, found := q.GetSubscription(ctx, sdk.BigEndianToUint64(key))
if !found {
return false, nil
}
if accumulate {
items = append(items, item)
}
return true, nil
})
} else if req.Status.Equal(hubtypes.Inactive) {
store := prefix.NewStore(q.Store(ctx), types.GetInactiveSubscriptionForAddressKeyPrefix(address))
pagination, err = query.FilteredPaginate(store, req.Pagination, func(key, _ []byte, accumulate bool) (bool, error) {
item, found := q.GetSubscription(ctx, sdk.BigEndianToUint64(key))
if !found {
return false, nil
}
if accumulate {
items = append(items, item)
}
return true, nil
})
} else {
// NOTE: Do not use this; less efficient; consider using active + inactive
store := prefix.NewStore(q.Store(ctx), types.SubscriptionKeyPrefix)
pagination, err = query.FilteredPaginate(store, req.Pagination, func(_, value []byte, accumulate bool) (bool, error) {
var item types.Subscription
if err := q.cdc.UnmarshalBinaryBare(value, &item); err != nil {
return false, err
}
if !strings.EqualFold(item.Owner, req.Address) {
return false, nil
}
if accumulate {
items = append(items, item)
}
return true, nil
})
}
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &types.QuerySubscriptionsForAddressResponse{Subscriptions: items, Pagination: pagination}, nil
}
func (q *queryServer) QueryQuota(c context.Context, req *types.QueryQuotaRequest) (*types.QueryQuotaResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
address, err := sdk.AccAddressFromBech32(req.Address)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid address %s", req.Address)
}
ctx := sdk.UnwrapSDKContext(c)
item, found := q.GetQuota(ctx, req.Id, address)
if !found {
return nil, status.Errorf(codes.NotFound, "quota does not exist for id %d, and address %s", req.Id, req.Address)
}
return &types.QueryQuotaResponse{Quota: item}, nil
}
func (q *queryServer) QueryQuotas(c context.Context, req *types.QueryQuotasRequest) (*types.QueryQuotasResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
var (
items types.Quotas
ctx = sdk.UnwrapSDKContext(c)
store = prefix.NewStore(q.Store(ctx), types.GetQuotaKeyPrefix(req.Id))
)
pagination, err := query.FilteredPaginate(store, req.Pagination, func(_, value []byte, accumulate bool) (bool, error) {
var item types.Quota
if err := q.cdc.UnmarshalBinaryBare(value, &item); err != nil {
return false, err
}
if accumulate {
items = append(items, item)
}
return true, nil
})
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &types.QueryQuotasResponse{Quotas: items, Pagination: pagination}, nil
}
func (q *queryServer) QueryParams(c context.Context, _ *types.QueryParamsRequest) (*types.QueryParamsResponse, error) {
var (
ctx = sdk.UnwrapSDKContext(c)
params = q.GetParams(ctx)
)
return &types.QueryParamsResponse{Params: params}, nil
}
<file_sep>package v06
import (
hubtypes "github.com/sentinel-official/hub/types/legacy/v0.6"
"github.com/sentinel-official/hub/x/session/types"
legacy "github.com/sentinel-official/hub/x/session/types/legacy/v0.5"
)
func MigrateSession(item legacy.Session) types.Session {
return types.Session{
Id: item.ID,
Subscription: item.Subscription,
Node: item.Node.String(),
Address: item.Address.String(),
Duration: item.Duration,
Bandwidth: hubtypes.MigrateBandwidth(item.Bandwidth),
Status: hubtypes.MigrateStatus(item.Status),
StatusAt: item.StatusAt,
}
}
func MigrateSessions(items legacy.Sessions) types.Sessions {
var sessions types.Sessions
for _, item := range items {
sessions = append(sessions, MigrateSession(item))
}
return sessions
}
<file_sep>package expected
import (
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
hubtypes "github.com/sentinel-official/hub/types"
nodetypes "github.com/sentinel-official/hub/x/node/types"
subscriptiontypes "github.com/sentinel-official/hub/x/subscription/types"
)
type AccountKeeper interface {
GetAccount(ctx sdk.Context, address sdk.AccAddress) authtypes.AccountI
}
type DepositKeeper interface {
SendCoinsFromDepositToAccount(ctx sdk.Context, from, to sdk.AccAddress, coins sdk.Coins) error
}
type PlanKeeper interface {
HasNodeForPlan(ctx sdk.Context, id uint64, address hubtypes.NodeAddress) bool
GetNodesForPlan(ctx sdk.Context, id uint64, skip, limit int64) nodetypes.Nodes
}
type NodeKeeper interface {
GetNode(ctx sdk.Context, address hubtypes.NodeAddress) (nodetypes.Node, bool)
}
type SubscriptionKeeper interface {
GetSubscription(ctx sdk.Context, id uint64) (subscriptiontypes.Subscription, bool)
GetSubscriptionsForNode(ctx sdk.Context, address hubtypes.NodeAddress, skip, limit int64) subscriptiontypes.Subscriptions
HasSubscriptionForNode(ctx sdk.Context, address hubtypes.NodeAddress, id uint64) bool
GetActiveSubscriptionsForAddress(ctx sdk.Context, address sdk.AccAddress, skip, limit int64) subscriptiontypes.Subscriptions
SetQuota(ctx sdk.Context, id uint64, quota subscriptiontypes.Quota)
GetQuota(ctx sdk.Context, id uint64, address sdk.AccAddress) (subscriptiontypes.Quota, bool)
HasQuota(ctx sdk.Context, id uint64, address sdk.AccAddress) bool
}
<file_sep>package types
import (
"github.com/cosmos/cosmos-sdk/types/query"
hubtypes "github.com/sentinel-official/hub/types"
)
func NewQueryNodeRequest(address hubtypes.NodeAddress) *QueryNodeRequest {
return &QueryNodeRequest{
Address: address.String(),
}
}
func NewQueryNodesRequest(status hubtypes.Status, pagination *query.PageRequest) *QueryNodesRequest {
return &QueryNodesRequest{
Status: status,
Pagination: pagination,
}
}
func NewQueryNodesForProviderRequest(address hubtypes.ProvAddress, status hubtypes.Status, pagination *query.PageRequest) *QueryNodesForProviderRequest {
return &QueryNodesForProviderRequest{
Address: address.String(),
Status: status,
Pagination: pagination,
}
}
func NewQueryParamsRequest() *QueryParamsRequest {
return &QueryParamsRequest{}
}
<file_sep>package v06
import (
"github.com/sentinel-official/hub/x/subscription/types"
legacy "github.com/sentinel-official/hub/x/subscription/types/legacy/v0.5"
)
func MigrateQuota(item legacy.Quota) types.Quota {
return types.Quota{
Address: item.Address.String(),
Allocated: item.Allocated,
Consumed: item.Consumed,
}
}
func MigrateQuotas(items legacy.Quotas) types.Quotas {
var quotas types.Quotas
for _, item := range items {
quotas = append(quotas, MigrateQuota(item))
}
return quotas
}
<file_sep>package types
import (
"fmt"
"time"
params "github.com/cosmos/cosmos-sdk/x/params/types"
)
const (
DefaultInactiveDuration = 10 * time.Minute
)
var (
KeyInactiveDuration = []byte("InactiveDuration")
)
var (
_ params.ParamSet = (*Params)(nil)
)
func (p *Params) Validate() error {
if p.InactiveDuration <= 0 {
return fmt.Errorf("inactive_duration should be positive")
}
return nil
}
func (p *Params) ParamSetPairs() params.ParamSetPairs {
return params.ParamSetPairs{
{
Key: KeyInactiveDuration,
Value: &p.InactiveDuration,
ValidatorFn: func(v interface{}) error {
value, ok := v.(time.Duration)
if !ok {
return fmt.Errorf("invalid parameter type %T", v)
}
if value <= 0 {
return fmt.Errorf("inactive duration value should be positive")
}
return nil
},
},
}
}
func NewParams(inactiveDuration time.Duration) Params {
return Params{
InactiveDuration: inactiveDuration,
}
}
func DefaultParams() Params {
return Params{
InactiveDuration: DefaultInactiveDuration,
}
}
func ParamsKeyTable() params.KeyTable {
return params.NewKeyTable().RegisterParamSet(&Params{})
}
<file_sep>package keeper
import (
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
nodetypes "github.com/sentinel-official/hub/x/node/types"
)
func (k *Keeper) HasProvider(ctx sdk.Context, address hubtypes.ProvAddress) bool {
return k.provider.HasProvider(ctx, address)
}
func (k *Keeper) GetNode(ctx sdk.Context, address hubtypes.NodeAddress) (nodetypes.Node, bool) {
return k.node.GetNode(ctx, address)
}
<file_sep>package keeper
import (
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/session/types"
)
func (k *Keeper) ProcessPaymentAndUpdateQuota(ctx sdk.Context, session types.Session) error {
from, err := sdk.AccAddressFromBech32(session.Address)
if err != nil {
return err
}
subscription, found := k.GetSubscription(ctx, session.Subscription)
if !found {
return types.ErrorSubscriptionDoesNotExit
}
if subscription.Status.Equal(hubtypes.StatusInactive) {
return nil
}
quota, found := k.GetQuota(ctx, session.Subscription, from)
if !found {
return types.ErrorQuotaDoesNotExist
}
available := quota.Allocated.Sub(quota.Consumed)
if !available.IsPositive() {
return nil
}
if subscription.Plan == 0 {
bandwidth := hubtypes.NewBandwidth(
session.Bandwidth.Sum(), sdk.ZeroInt(),
).CeilTo(
hubtypes.Gigabyte.Quo(subscription.Price.Amount),
).Sum()
if bandwidth.GT(available) {
bandwidth = available
}
quota.Consumed = quota.Consumed.Add(bandwidth)
k.SetQuota(ctx, session.Subscription, quota)
amount := subscription.Amount(bandwidth)
ctx.Logger().Info("calculated payment for session", "id", session.Id,
"price", subscription.Price, "deposit", subscription.Deposit, "amount", amount,
"consumed", session.Bandwidth.Sum(), "rounded", bandwidth)
sessionNode := session.GetNode()
return k.SendCoinsFromDepositToAccount(ctx, from, sessionNode.Bytes(), amount)
}
bandwidth := session.Bandwidth.Sum()
if bandwidth.GT(available) {
bandwidth = available
}
quota.Consumed = quota.Consumed.Add(bandwidth)
k.SetQuota(ctx, session.Subscription, quota)
ctx.Logger().Info("calculated bandwidth for session", "id", session.Id,
"plan", subscription.Plan, "consumed", session.Bandwidth.Sum(), "rounded", bandwidth)
return nil
}
<file_sep>package keeper
import (
"context"
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/plan/types"
)
var (
_ types.MsgServiceServer = (*msgServer)(nil)
)
type msgServer struct {
Keeper
}
func NewMsgServiceServer(keeper Keeper) types.MsgServiceServer {
return &msgServer{Keeper: keeper}
}
func (k *msgServer) MsgAdd(c context.Context, msg *types.MsgAddRequest) (*types.MsgAddResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
msgFrom, err := hubtypes.ProvAddressFromBech32(msg.From)
if err != nil {
return nil, err
}
if !k.HasProvider(ctx, msgFrom) {
return nil, types.ErrorProviderDoesNotExist
}
var (
count = k.GetCount(ctx)
plan = types.Plan{
Id: count + 1,
Provider: msg.From,
Price: msg.Price,
Validity: msg.Validity,
Bytes: msg.Bytes,
Status: hubtypes.StatusInactive,
StatusAt: ctx.BlockTime(),
}
planProvider = plan.GetProvider()
)
k.SetPlan(ctx, plan)
k.SetInactivePlan(ctx, plan.Id)
k.SetInactivePlanForProvider(ctx, planProvider, plan.Id)
ctx.EventManager().EmitTypedEvent(
&types.EventAddPlan{
From: sdk.AccAddress(msgFrom.Bytes()).String(),
Provider: plan.Provider,
Price: plan.Price,
Validity: plan.Validity,
Bytes: plan.Bytes,
},
)
k.SetCount(ctx, count+1)
ctx.EventManager().EmitTypedEvent(
&types.EventSetPlanCount{
Count: count + 1,
},
)
ctx.EventManager().EmitTypedEvent(&types.EventModuleName)
return &types.MsgAddResponse{}, nil
}
func (k *msgServer) MsgSetStatus(c context.Context, msg *types.MsgSetStatusRequest) (*types.MsgSetStatusResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
msgFrom, err := hubtypes.ProvAddressFromBech32(msg.From)
if err != nil {
return nil, err
}
plan, found := k.GetPlan(ctx, msg.Id)
if !found {
return nil, types.ErrorPlanDoesNotExist
}
if msg.From != plan.Provider {
return nil, types.ErrorUnauthorized
}
var (
planProvider = plan.GetProvider()
)
if plan.Status.Equal(hubtypes.StatusActive) {
if msg.Status.Equal(hubtypes.StatusInactive) {
k.DeleteActivePlan(ctx, plan.Id)
k.DeleteActivePlanForProvider(ctx, planProvider, plan.Id)
k.SetInactivePlan(ctx, plan.Id)
k.SetInactivePlanForProvider(ctx, planProvider, plan.Id)
}
} else {
if msg.Status.Equal(hubtypes.StatusActive) {
k.DeleteInactivePlan(ctx, plan.Id)
k.DeleteInactivePlanForProvider(ctx, planProvider, plan.Id)
k.SetActivePlan(ctx, plan.Id)
k.SetActivePlanForProvider(ctx, planProvider, plan.Id)
}
}
plan.Status = msg.Status
plan.StatusAt = ctx.BlockTime()
k.SetPlan(ctx, plan)
ctx.EventManager().EmitTypedEvent(
&types.EventSetPlanStatus{
From: sdk.AccAddress(msgFrom.Bytes()).String(),
Provider: plan.Provider,
Id: plan.Id,
Status: plan.Status,
},
)
ctx.EventManager().EmitTypedEvent(&types.EventModuleName)
return &types.MsgSetStatusResponse{}, nil
}
func (k *msgServer) MsgAddNode(c context.Context, msg *types.MsgAddNodeRequest) (*types.MsgAddNodeResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
msgFrom, err := hubtypes.ProvAddressFromBech32(msg.From)
if err != nil {
return nil, err
}
plan, found := k.GetPlan(ctx, msg.Id)
if !found {
return nil, types.ErrorPlanDoesNotExist
}
if msg.From != plan.Provider {
return nil, types.ErrorUnauthorized
}
msgAddress, err := hubtypes.NodeAddressFromBech32(msg.Address)
if err != nil {
return nil, err
}
node, found := k.GetNode(ctx, msgAddress)
if !found {
return nil, types.ErrorNodeDoesNotExist
}
if msg.From != node.Provider {
return nil, types.ErrorUnauthorized
}
if k.HasNodeForPlan(ctx, plan.Id, msgAddress) {
return nil, types.DuplicateNodeForPlan
}
var (
planProvider = plan.GetProvider()
nodeAddress = node.GetAddress()
)
k.SetNodeForPlan(ctx, plan.Id, nodeAddress)
k.IncreaseCountForNodeByProvider(ctx, planProvider, nodeAddress)
ctx.EventManager().EmitTypedEvent(
&types.EventAddNodeForPlan{
From: sdk.AccAddress(msgFrom.Bytes()).String(),
Provider: plan.Provider,
Id: plan.Id,
Address: msg.Address,
},
)
ctx.EventManager().EmitTypedEvent(&types.EventModuleName)
return &types.MsgAddNodeResponse{}, nil
}
func (k *msgServer) MsgRemoveNode(c context.Context, msg *types.MsgRemoveNodeRequest) (*types.MsgRemoveNodeResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
msgFrom, err := sdk.AccAddressFromBech32(msg.From)
if err != nil {
return nil, err
}
plan, found := k.GetPlan(ctx, msg.Id)
if !found {
return nil, types.ErrorPlanDoesNotExist
}
planProvider := plan.GetProvider()
if hubtypes.NodeAddress(msgFrom.Bytes()).String() != msg.Address {
if hubtypes.ProvAddress(msgFrom.Bytes()).String() != plan.Provider {
return nil, types.ErrorUnauthorized
}
}
msgAddress, err := hubtypes.NodeAddressFromBech32(msg.Address)
if err != nil {
return nil, err
}
if !k.HasNodeForPlan(ctx, plan.Id, msgAddress) {
return nil, types.ErrorNodeDoesNotExist
}
k.DeleteNodeForPlan(ctx, plan.Id, msgAddress)
k.DecreaseCountForNodeByProvider(ctx, planProvider, msgAddress)
ctx.EventManager().EmitTypedEvent(
&types.EventRemoveNodeForPlan{
From: sdk.AccAddress(msgFrom.Bytes()).String(),
Id: plan.Id,
Address: msg.Address,
},
)
ctx.EventManager().EmitTypedEvent(&types.EventModuleName)
return &types.MsgRemoveNodeResponse{}, nil
}
<file_sep>package v05
type (
GenesisState struct {
Providers Providers `json:"_"`
Params Params `json:"params"`
}
)
<file_sep>package keeper
import (
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
nodetypes "github.com/sentinel-official/hub/x/node/types"
hubtypes "github.com/sentinel-official/hub/types"
subscriptiontypes "github.com/sentinel-official/hub/x/subscription/types"
)
func (k *Keeper) GetAccount(ctx sdk.Context, address sdk.AccAddress) authtypes.AccountI {
return k.account.GetAccount(ctx, address)
}
func (k *Keeper) HasNodeForPlan(ctx sdk.Context, id uint64, address hubtypes.NodeAddress) bool {
return k.plan.HasNodeForPlan(ctx, id, address)
}
func (k *Keeper) GetNode(ctx sdk.Context, address hubtypes.NodeAddress) (nodetypes.Node, bool) {
return k.node.GetNode(ctx, address)
}
func (k *Keeper) GetSubscription(ctx sdk.Context, id uint64) (subscriptiontypes.Subscription, bool) {
return k.subscription.GetSubscription(ctx, id)
}
func (k *Keeper) HasSubscriptionForNode(ctx sdk.Context, address hubtypes.NodeAddress, id uint64) bool {
return k.subscription.HasSubscriptionForNode(ctx, address, id)
}
func (k *Keeper) SetQuota(ctx sdk.Context, id uint64, quota subscriptiontypes.Quota) {
k.subscription.SetQuota(ctx, id, quota)
}
func (k *Keeper) GetQuota(ctx sdk.Context, id uint64, address sdk.AccAddress) (subscriptiontypes.Quota, bool) {
return k.subscription.GetQuota(ctx, id, address)
}
func (k *Keeper) HasQuota(ctx sdk.Context, id uint64, address sdk.AccAddress) bool {
return k.subscription.HasQuota(ctx, id, address)
}
func (k *Keeper) SendCoinsFromDepositToAccount(ctx sdk.Context, from, to sdk.AccAddress, coin sdk.Coin) error {
if coin.IsZero() {
return nil
}
return k.deposit.SendCoinsFromDepositToAccount(ctx, from, to, sdk.NewCoins(coin))
}
<file_sep>package types
import (
"github.com/cosmos/cosmos-sdk/types/errors"
)
var (
ErrorInvalidFieldFrom = errors.Register(ModuleName, 101, "invalid value for field from; expected a valid address")
ErrorProviderDoesNotExist = errors.Register(ModuleName, 102, "provider does not exist")
ErrorDuplicateNode = errors.Register(ModuleName, 103, "duplicate node")
ErrorNodeDoesNotExist = errors.Register(ModuleName, 104, "node does not exist")
ErrorInvalidFieldProviderOrPrice = errors.Register(ModuleName, 105, "invalid value for provider or price; expected either price or provider to be empty")
ErrorInvalidFieldProvider = errors.Register(ModuleName, 106, "invalid value for field provider; expected a valid provider address")
ErrorInvalidFieldPrice = errors.Register(ModuleName, 107, "invalid value for field price; expected a valid price")
ErrorInvalidFieldRemoteURL = errors.Register(ModuleName, 108, "invalid value for field remote_url; expected length between 1 and 64")
ErrorInvalidFieldStatus = errors.Register(ModuleName, 109, "invalid value for field status; expected either Active or Inactive")
ErrorInvalidPlanCount = errors.Register(ModuleName, 110, "invalid plan count")
)
<file_sep>package keeper
import (
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/provider/types"
)
// SetProvider is for inserting a provider into the KVStore.
func (k *Keeper) SetProvider(ctx sdk.Context, provider types.Provider) {
key := types.ProviderKey(provider.GetAddress())
value := k.cdc.MustMarshalBinaryBare(&provider)
store := k.Store(ctx)
store.Set(key, value)
}
// HasProvider is for checking whether a provider with an address exists or not in the KVStore.
func (k *Keeper) HasProvider(ctx sdk.Context, address hubtypes.ProvAddress) bool {
store := k.Store(ctx)
key := types.ProviderKey(address)
return store.Has(key)
}
// GetProvider is for getting a provider with an address from the KVStore.
func (k *Keeper) GetProvider(ctx sdk.Context, address hubtypes.ProvAddress) (provider types.Provider, found bool) {
store := k.Store(ctx)
key := types.ProviderKey(address)
value := store.Get(key)
if value == nil {
return provider, false
}
k.cdc.MustUnmarshalBinaryBare(value, &provider)
return provider, true
}
// GetProviders is for getting the providers from the KVStore.
func (k *Keeper) GetProviders(ctx sdk.Context, skip, limit int64) (items types.Providers) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.ProviderKeyPrefix),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
var item types.Provider
k.cdc.MustUnmarshalBinaryBare(iter.Value(), &item)
items = append(items, item)
})
return items
}
// IterateProviders is for iterating over the providers to perform an action.
func (k *Keeper) IterateProviders(ctx sdk.Context, fn func(index int, item types.Provider) (stop bool)) {
store := k.Store(ctx)
iter := sdk.KVStorePrefixIterator(store, types.ProviderKeyPrefix)
defer iter.Close()
for i := 0; iter.Valid(); iter.Next() {
var provider types.Provider
k.cdc.MustUnmarshalBinaryBare(iter.Value(), &provider)
if stop := fn(i, provider); stop {
break
}
i++
}
}
<file_sep>package cli
import (
"encoding/hex"
"strconv"
"time"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/tx"
"github.com/spf13/cobra"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/session/types"
)
func txStart() *cobra.Command {
cmd := &cobra.Command{
Use: "start [id] [address]",
Short: "Start a session",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
ctx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
id, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return err
}
address, err := hubtypes.NodeAddressFromBech32(args[1])
if err != nil {
return err
}
msg := types.NewMsgStartRequest(ctx.FromAddress, id, address)
if err := msg.ValidateBasic(); err != nil {
return err
}
return tx.GenerateOrBroadcastTxCLI(ctx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}
func txUpdate() *cobra.Command {
cmd := &cobra.Command{
Use: "update [id] [upload] [download] [duration] (signature)",
Short: "Add or update a session",
Args: cobra.ExactArgs(4),
RunE: func(cmd *cobra.Command, args []string) error {
ctx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
id, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return err
}
upload, err := strconv.ParseInt(args[1], 10, 64)
if err != nil {
return err
}
download, err := strconv.ParseInt(args[2], 10, 64)
if err != nil {
return err
}
duration, err := time.ParseDuration(args[3])
if err != nil {
return err
}
var signature []byte = nil
if len(args) > 4 && args[4] != "" {
signature, err = hex.DecodeString(args[4])
if err != nil {
return err
}
}
msg := types.NewMsgUpdateRequest(
ctx.FromAddress.Bytes(),
types.Proof{
Id: id,
Duration: duration,
Bandwidth: hubtypes.NewBandwidthFromInt64(upload, download),
},
signature,
)
if err := msg.ValidateBasic(); err != nil {
return err
}
return tx.GenerateOrBroadcastTxCLI(ctx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}
func txEnd() *cobra.Command {
cmd := &cobra.Command{
Use: "end [id] [rating]",
Short: "End a session",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
ctx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
id, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return err
}
rating, err := strconv.ParseUint(args[1], 10, 64)
if err != nil {
return err
}
msg := types.NewMsgEndRequest(ctx.FromAddress, id, rating)
if err := msg.ValidateBasic(); err != nil {
return err
}
return tx.GenerateOrBroadcastTxCLI(ctx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}
<file_sep>package types
import (
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/types"
crypto "github.com/cosmos/cosmos-sdk/crypto/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/msgservice"
)
var (
amino = codec.NewLegacyAmino()
ModuleCdc = codec.NewAminoCodec(amino)
)
func init() {
RegisterLegacyAminoCodec(amino)
crypto.RegisterCrypto(amino)
amino.Seal()
}
func RegisterLegacyAminoCodec(_ *codec.LegacyAmino) {}
func RegisterInterfaces(registry types.InterfaceRegistry) {
registry.RegisterImplementations((*sdk.Msg)(nil),
&MsgStartRequest{},
&MsgUpdateRequest{},
&MsgEndRequest{},
)
msgservice.RegisterMsgServiceDesc(registry, &_MsgService_serviceDesc)
}
<file_sep>package v05
import (
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
legacyhubtypes "github.com/sentinel-official/hub/types/legacy/v0.5"
)
type (
Plan struct {
ID uint64 `json:"id"`
Provider hubtypes.ProvAddress `json:"provider"`
Price sdk.Coins `json:"price"`
Validity time.Duration `json:"validity"`
Bytes sdk.Int `json:"bytes"`
Status legacyhubtypes.Status `json:"status"`
StatusAt time.Time `json:"status_at"`
}
Plans []Plan
)
<file_sep>package types
import (
"fmt"
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/errors"
hubtypes "github.com/sentinel-official/hub/types"
)
var (
_ sdk.Msg = (*MsgAddRequest)(nil)
_ sdk.Msg = (*MsgSetStatusRequest)(nil)
_ sdk.Msg = (*MsgAddNodeRequest)(nil)
_ sdk.Msg = (*MsgRemoveNodeRequest)(nil)
)
func NewMsgAddRequest(from hubtypes.ProvAddress, price sdk.Coins, validity time.Duration, bytes sdk.Int) *MsgAddRequest {
return &MsgAddRequest{
From: from.String(),
Price: price,
Validity: validity,
Bytes: bytes,
}
}
func (m *MsgAddRequest) Route() string {
return RouterKey
}
func (m *MsgAddRequest) Type() string {
return fmt.Sprintf("%s:add", ModuleName)
}
func (m *MsgAddRequest) ValidateBasic() error {
if _, err := hubtypes.ProvAddressFromBech32(m.From); err != nil {
return errors.Wrapf(ErrorInvalidField, "%s", "from")
}
// Price can be nil. If not, it should be valid
if m.Price != nil && !m.Price.IsValid() {
return errors.Wrapf(ErrorInvalidField, "%s", "price")
}
// Validity should be positive
if m.Validity <= 0 {
return errors.Wrapf(ErrorInvalidField, "%s", "validity")
}
// Bytes should be positive
if !m.Bytes.IsPositive() {
return errors.Wrapf(ErrorInvalidField, "%s", "bytes")
}
return nil
}
func (m *MsgAddRequest) GetSignBytes() []byte {
return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(m))
}
func (m *MsgAddRequest) GetSigners() []sdk.AccAddress {
from, err := hubtypes.ProvAddressFromBech32(m.From)
if err != nil {
panic(err)
}
return []sdk.AccAddress{from.Bytes()}
}
func NewMsgSetStatusRequest(from hubtypes.ProvAddress, id uint64, status hubtypes.Status) *MsgSetStatusRequest {
return &MsgSetStatusRequest{
From: from.String(),
Id: id,
Status: status,
}
}
func (m *MsgSetStatusRequest) Route() string {
return RouterKey
}
func (m *MsgSetStatusRequest) Type() string {
return fmt.Sprintf("%s:set_status", ModuleName)
}
func (m *MsgSetStatusRequest) ValidateBasic() error {
if _, err := hubtypes.ProvAddressFromBech32(m.From); err != nil {
return errors.Wrapf(ErrorInvalidField, "%s", "from")
}
// Id shouldn't be zero
if m.Id == 0 {
return errors.Wrapf(ErrorInvalidField, "%s", "id")
}
// Status should be either Active or Inactive
if !m.Status.Equal(hubtypes.StatusActive) && !m.Status.Equal(hubtypes.StatusInactive) {
return errors.Wrapf(ErrorInvalidField, "%s", "status")
}
return nil
}
func (m *MsgSetStatusRequest) GetSignBytes() []byte {
return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(m))
}
func (m *MsgSetStatusRequest) GetSigners() []sdk.AccAddress {
from, err := hubtypes.ProvAddressFromBech32(m.From)
if err != nil {
panic(err)
}
return []sdk.AccAddress{from.Bytes()}
}
func NewMsgAddNodeRequest(from hubtypes.ProvAddress, id uint64, address hubtypes.NodeAddress) *MsgAddNodeRequest {
return &MsgAddNodeRequest{
From: from.String(),
Id: id,
Address: address.String(),
}
}
func (m *MsgAddNodeRequest) Route() string {
return RouterKey
}
func (m *MsgAddNodeRequest) Type() string {
return fmt.Sprintf("%s:add_node", ModuleName)
}
func (m *MsgAddNodeRequest) ValidateBasic() error {
if _, err := hubtypes.ProvAddressFromBech32(m.From); err != nil {
return errors.Wrapf(ErrorInvalidField, "%s", "from")
}
// Id shouldn't be zero
if m.Id == 0 {
return errors.Wrapf(ErrorInvalidField, "%s", "id")
}
// Address shouldn't be nil or empty
if _, err := hubtypes.NodeAddressFromBech32(m.Address); err != nil {
return errors.Wrapf(ErrorInvalidField, "%s", "address")
}
return nil
}
func (m *MsgAddNodeRequest) GetSignBytes() []byte {
return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(m))
}
func (m *MsgAddNodeRequest) GetSigners() []sdk.AccAddress {
from, err := hubtypes.ProvAddressFromBech32(m.From)
if err != nil {
panic(err)
}
return []sdk.AccAddress{from.Bytes()}
}
func NewMsgRemoveNodeRequest(from sdk.AccAddress, id uint64, address hubtypes.NodeAddress) *MsgRemoveNodeRequest {
return &MsgRemoveNodeRequest{
From: from.String(),
Id: id,
Address: address.String(),
}
}
func (m *MsgRemoveNodeRequest) Route() string {
return RouterKey
}
func (m *MsgRemoveNodeRequest) Type() string {
return fmt.Sprintf("%s:remove_node", ModuleName)
}
func (m *MsgRemoveNodeRequest) ValidateBasic() error {
if _, err := sdk.AccAddressFromBech32(m.From); err != nil {
return errors.Wrapf(ErrorInvalidField, "%s", "from")
}
// Id shouldn't be zero
if m.Id == 0 {
return errors.Wrapf(ErrorInvalidField, "%s", "id")
}
// Address should be valid
if _, err := hubtypes.NodeAddressFromBech32(m.Address); err != nil {
return errors.Wrapf(ErrorInvalidField, "%s", "address")
}
return nil
}
func (m *MsgRemoveNodeRequest) GetSignBytes() []byte {
return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(m))
}
func (m *MsgRemoveNodeRequest) GetSigners() []sdk.AccAddress {
from, err := sdk.AccAddressFromBech32(m.From)
if err != nil {
panic(err)
}
return []sdk.AccAddress{from}
}
<file_sep>package keeper
import (
"context"
"strings"
"github.com/cosmos/cosmos-sdk/store/prefix"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/query"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
hubtypes "github.com/sentinel-official/hub/types"
nodetypes "github.com/sentinel-official/hub/x/node/types"
"github.com/sentinel-official/hub/x/plan/types"
)
var (
_ types.QueryServiceServer = (*queryServer)(nil)
)
type queryServer struct {
Keeper
}
func NewQueryServiceServer(keeper Keeper) types.QueryServiceServer {
return &queryServer{Keeper: keeper}
}
func (q *queryServer) QueryPlan(c context.Context, req *types.QueryPlanRequest) (*types.QueryPlanResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
ctx := sdk.UnwrapSDKContext(c)
item, found := q.GetPlan(ctx, req.Id)
if !found {
return nil, status.Errorf(codes.NotFound, "plan does not exist for id %d", req.Id)
}
return &types.QueryPlanResponse{Plan: item}, nil
}
func (q *queryServer) QueryPlans(c context.Context, req *types.QueryPlansRequest) (res *types.QueryPlansResponse, err error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
var (
items types.Plans
pagination *query.PageResponse
ctx = sdk.UnwrapSDKContext(c)
)
if req.Status.Equal(hubtypes.Active) {
store := prefix.NewStore(q.Store(ctx), types.ActivePlanKeyPrefix)
pagination, err = query.FilteredPaginate(store, req.Pagination, func(key, _ []byte, accumulate bool) (bool, error) {
item, found := q.GetPlan(ctx, sdk.BigEndianToUint64(key))
if !found {
return false, nil
}
if accumulate {
items = append(items, item)
}
return true, nil
})
} else if req.Status.Equal(hubtypes.Inactive) {
store := prefix.NewStore(q.Store(ctx), types.InactivePlanKeyPrefix)
pagination, err = query.FilteredPaginate(store, req.Pagination, func(key, _ []byte, accumulate bool) (bool, error) {
item, found := q.GetPlan(ctx, sdk.BigEndianToUint64(key))
if !found {
return false, nil
}
if accumulate {
items = append(items, item)
}
return true, nil
})
} else {
store := prefix.NewStore(q.Store(ctx), types.PlanKeyPrefix)
pagination, err = query.FilteredPaginate(store, req.Pagination, func(_, value []byte, accumulate bool) (bool, error) {
var item types.Plan
if err := q.cdc.UnmarshalBinaryBare(value, &item); err != nil {
return false, err
}
if accumulate {
items = append(items, item)
}
return true, nil
})
}
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &types.QueryPlansResponse{Plans: items, Pagination: pagination}, nil
}
func (q *queryServer) QueryPlansForProvider(c context.Context, req *types.QueryPlansForProviderRequest) (res *types.QueryPlansForProviderResponse, err error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
address, err := hubtypes.ProvAddressFromBech32(req.Address)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid address %s", req.Address)
}
var (
items types.Plans
pagination *query.PageResponse
ctx = sdk.UnwrapSDKContext(c)
)
if req.Status.Equal(hubtypes.Active) {
store := prefix.NewStore(q.Store(ctx), types.GetActivePlanForProviderKeyPrefix(address))
pagination, err = query.FilteredPaginate(store, req.Pagination, func(key, _ []byte, accumulate bool) (bool, error) {
item, found := q.GetPlan(ctx, sdk.BigEndianToUint64(key))
if !found {
return false, nil
}
if accumulate {
items = append(items, item)
}
return true, nil
})
} else if req.Status.Equal(hubtypes.Inactive) {
store := prefix.NewStore(q.Store(ctx), types.GetInactivePlanForProviderKeyPrefix(address))
pagination, err = query.FilteredPaginate(store, req.Pagination, func(key, _ []byte, accumulate bool) (bool, error) {
item, found := q.GetPlan(ctx, sdk.BigEndianToUint64(key))
if !found {
return false, nil
}
if accumulate {
items = append(items, item)
}
return true, nil
})
} else {
// NOTE: Do not use this; less efficient; consider using active + inactive
store := prefix.NewStore(q.Store(ctx), types.PlanKeyPrefix)
pagination, err = query.FilteredPaginate(store, req.Pagination, func(_, value []byte, accumulate bool) (bool, error) {
var item types.Plan
if err := q.cdc.UnmarshalBinaryBare(value, &item); err != nil {
return false, err
}
if !strings.EqualFold(item.Provider, req.Address) {
return false, nil
}
if accumulate {
items = append(items, item)
}
return true, nil
})
}
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &types.QueryPlansForProviderResponse{Plans: items, Pagination: pagination}, nil
}
func (q *queryServer) QueryNodesForPlan(c context.Context, req *types.QueryNodesForPlanRequest) (*types.QueryNodesForPlanResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
var (
items nodetypes.Nodes
pagination *query.PageResponse
ctx = sdk.UnwrapSDKContext(c)
)
store := prefix.NewStore(q.Store(ctx), types.GetNodeForPlanKeyPrefix(req.Id))
pagination, err := query.FilteredPaginate(store, req.Pagination, func(key, _ []byte, accumulate bool) (bool, error) {
item, found := q.GetNode(ctx, key)
if !found {
return false, nil
}
if accumulate {
items = append(items, item)
}
return true, nil
})
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &types.QueryNodesForPlanResponse{Nodes: items, Pagination: pagination}, nil
}
<file_sep>package v05
import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
type (
Bandwidth struct {
Upload sdk.Int `json:"upload"`
Download sdk.Int `json:"download"`
}
)
<file_sep>package keeper
import (
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
distributionkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper"
paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper"
depositkeeper "github.com/sentinel-official/hub/x/deposit/keeper"
nodekeeper "github.com/sentinel-official/hub/x/node/keeper"
nodetypes "github.com/sentinel-official/hub/x/node/types"
plankeeper "github.com/sentinel-official/hub/x/plan/keeper"
providerkeeper "github.com/sentinel-official/hub/x/provider/keeper"
providertypes "github.com/sentinel-official/hub/x/provider/types"
sessionkeeper "github.com/sentinel-official/hub/x/session/keeper"
sessiontypes "github.com/sentinel-official/hub/x/session/types"
subscriptionkeeper "github.com/sentinel-official/hub/x/subscription/keeper"
subscriptiontypes "github.com/sentinel-official/hub/x/subscription/types"
)
type Keeper struct {
Deposit depositkeeper.Keeper
Provider providerkeeper.Keeper
Node nodekeeper.Keeper
Plan plankeeper.Keeper
Subscription subscriptionkeeper.Keeper
Session sessionkeeper.Keeper
}
func NewKeeper(cdc codec.BinaryMarshaler, key sdk.StoreKey, paramsKeeper paramskeeper.Keeper, accountKeeper authkeeper.AccountKeeper,
bankKeeper bankkeeper.Keeper, distributionKeeper distributionkeeper.Keeper) Keeper {
var (
depositKeeper = depositkeeper.NewKeeper(cdc, key)
providerKeeper = providerkeeper.NewKeeper(cdc, key, paramsKeeper.Subspace(providertypes.ParamsSubspace))
nodeKeeper = nodekeeper.NewKeeper(cdc, key, paramsKeeper.Subspace(nodetypes.ParamsSubspace))
planKeeper = plankeeper.NewKeeper(cdc, key)
subscriptionKeeper = subscriptionkeeper.NewKeeper(cdc, key, paramsKeeper.Subspace(subscriptiontypes.ParamsSubspace))
sessionKeeper = sessionkeeper.NewKeeper(cdc, key, paramsKeeper.Subspace(sessiontypes.ParamsSubspace))
)
depositKeeper.WithBankKeeper(bankKeeper)
providerKeeper.WithDistributionKeeper(distributionKeeper)
nodeKeeper.WithDistributionKeeper(distributionKeeper)
nodeKeeper.WithProviderKeeper(&providerKeeper)
nodeKeeper.WithPlanKeeper(&planKeeper)
planKeeper.WithProviderKeeper(&providerKeeper)
planKeeper.WithNodeKeeper(&nodeKeeper)
subscriptionKeeper.WithDepositKeeper(&depositKeeper)
subscriptionKeeper.WithBankKeeper(bankKeeper)
subscriptionKeeper.WithNodeKeeper(&nodeKeeper)
subscriptionKeeper.WithPlanKeeper(&planKeeper)
sessionKeeper.WithAccountKeeper(accountKeeper)
sessionKeeper.WithDepositKeeper(&depositKeeper)
sessionKeeper.WithNodeKeeper(&nodeKeeper)
sessionKeeper.WithPlanKeeper(&planKeeper)
sessionKeeper.WithSubscriptionKeeper(&subscriptionKeeper)
return Keeper{
Deposit: depositKeeper,
Provider: providerKeeper,
Node: nodeKeeper,
Plan: planKeeper,
Subscription: subscriptionKeeper,
Session: sessionKeeper,
}
}
<file_sep>package rest
import (
"context"
"net/http"
"strconv"
"github.com/cosmos/cosmos-sdk/client"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/rest"
"github.com/gorilla/mux"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/session/types"
)
func querySession(ctx client.Context) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.ParseUint(vars["id"], 10, 64)
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
var (
qc = types.NewQueryServiceClient(ctx)
)
res, err := qc.QuerySession(context.Background(),
types.NewQuerySessionRequest(id))
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, ctx, res)
}
}
func querySessions(ctx client.Context) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var (
query = r.URL.Query()
qc = types.NewQueryServiceClient(ctx)
)
if query.Get("subscription") != "" {
id, err := strconv.ParseUint(query.Get("subscription"), 10, 64)
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
res, err := qc.QuerySessionsForSubscription(context.Background(),
types.NewQuerySessionsForSubscriptionRequest(id, nil))
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, ctx, res)
return
} else if query.Get("node") != "" {
address, err := hubtypes.NodeAddressFromBech32(query.Get("node"))
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
res, err := qc.QuerySessionsForNode(context.Background(),
types.NewQuerySessionsForNodeRequest(address, nil))
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, ctx, res)
return
} else if query.Get("address") != "" {
address, err := sdk.AccAddressFromBech32(query.Get("address"))
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
var status hubtypes.Status
if query.Get("active") != "" {
status = hubtypes.StatusActive
}
res, err := qc.QuerySessionsForAddress(context.Background(),
types.NewQuerySessionsForAddressRequest(address, status, nil))
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, ctx, res)
return
} else {
res, err := qc.QuerySessions(context.Background(), types.NewQuerySessionsRequest(nil))
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, ctx, res)
return
}
}
}
<file_sep>package cli
import (
"context"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/spf13/cobra"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/provider/types"
)
func queryProvider() *cobra.Command {
cmd := &cobra.Command{
Use: "provider",
Short: "Query a provider",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
ctx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
address, err := hubtypes.ProvAddressFromBech32(args[0])
if err != nil {
return err
}
var (
qc = types.NewQueryServiceClient(ctx)
)
res, err := qc.QueryProvider(context.Background(),
types.NewQueryProviderRequest(address))
if err != nil {
return err
}
return ctx.PrintProto(res)
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
func queryProviders() *cobra.Command {
cmd := &cobra.Command{
Use: "providers",
Short: "Query providers",
RunE: func(cmd *cobra.Command, args []string) error {
ctx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
pagination, err := client.ReadPageRequest(cmd.Flags())
if err != nil {
return err
}
var (
qc = types.NewQueryServiceClient(ctx)
)
res, err := qc.QueryProviders(context.Background(),
types.NewQueryProvidersRequest(pagination))
if err != nil {
return err
}
return ctx.PrintProto(res)
},
}
flags.AddQueryFlagsToCmd(cmd)
flags.AddPaginationFlagsToCmd(cmd, "provider")
return cmd
}
func queryParams() *cobra.Command {
cmd := &cobra.Command{
Use: "provider-params",
Short: "Query provider module parameters",
RunE: func(cmd *cobra.Command, _ []string) error {
ctx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
var (
qc = types.NewQueryServiceClient(ctx)
)
res, err := qc.QueryParams(context.Background(),
types.NewQueryParamsRequest())
if err != nil {
return err
}
return ctx.PrintProto(res)
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
<file_sep>package cli
import (
"context"
"strconv"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/spf13/cobra"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/plan/types"
)
func queryPlan() *cobra.Command {
cmd := &cobra.Command{
Use: "plan",
Short: "Query a plan",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
ctx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
id, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return err
}
var (
qc = types.NewQueryServiceClient(ctx)
)
res, err := qc.QueryPlan(context.Background(),
types.NewQueryPlanRequest(id))
if err != nil {
return err
}
return ctx.PrintProto(res)
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
func queryPlans() *cobra.Command {
cmd := &cobra.Command{
Use: "plans",
Short: "Query plans",
RunE: func(cmd *cobra.Command, args []string) (err error) {
ctx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
provider, err := cmd.Flags().GetString(flagProvider)
if err != nil {
return err
}
s, err := cmd.Flags().GetString(flagStatus)
if err != nil {
return err
}
pagination, err := client.ReadPageRequest(cmd.Flags())
if err != nil {
return err
}
var (
status = hubtypes.StatusFromString(s)
qc = types.NewQueryServiceClient(ctx)
)
if len(provider) > 0 {
address, err := hubtypes.ProvAddressFromBech32(provider)
if err != nil {
return err
}
res, err := qc.QueryPlansForProvider(context.Background(),
types.NewQueryPlansForProviderRequest(address, status, pagination))
if err != nil {
return err
}
return ctx.PrintProto(res)
}
res, err := qc.QueryPlans(context.Background(), types.NewQueryPlansRequest(status, pagination))
if err != nil {
return err
}
return ctx.PrintProto(res)
},
}
flags.AddQueryFlagsToCmd(cmd)
flags.AddPaginationFlagsToCmd(cmd, "providers")
cmd.Flags().String(flagProvider, "", "provider address")
cmd.Flags().String(flagStatus, "", "status")
return cmd
}
<file_sep>package keeper
import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
func (k *Keeper) FundCommunityPool(ctx sdk.Context, from sdk.AccAddress, coin sdk.Coin) error {
return k.distribution.FundCommunityPool(ctx, sdk.NewCoins(coin), from)
}
<file_sep>package deposit
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/sentinel-official/hub/x/deposit/keeper"
"github.com/sentinel-official/hub/x/deposit/types"
)
func InitGenesis(ctx sdk.Context, k keeper.Keeper, state types.GenesisState) {
for _, deposit := range state {
k.SetDeposit(ctx, deposit)
}
}
func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState {
var (
deposits = k.GetDeposits(ctx, 0, 0)
)
return types.NewGenesisState(deposits)
}
<file_sep>package swap
import (
"context"
"encoding/json"
"math/rand"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
sdksimulation "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/gorilla/mux"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/spf13/cobra"
abcitypes "github.com/tendermint/tendermint/abci/types"
"github.com/sentinel-official/hub/x/swap/client/cli"
"github.com/sentinel-official/hub/x/swap/keeper"
"github.com/sentinel-official/hub/x/swap/simulation"
"github.com/sentinel-official/hub/x/swap/types"
)
var (
_ module.AppModule = AppModule{}
_ module.AppModuleBasic = AppModuleBasic{}
_ module.AppModuleSimulation = AppModule{}
)
type AppModuleBasic struct{}
func (a AppModuleBasic) Name() string {
return types.ModuleName
}
func (a AppModuleBasic) RegisterLegacyAminoCodec(amino *codec.LegacyAmino) {
types.RegisterLegacyAminoCodec(amino)
}
func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) {
types.RegisterInterfaces(registry)
}
func (a AppModuleBasic) DefaultGenesis(cdc codec.JSONMarshaler) json.RawMessage {
return cdc.MustMarshalJSON(types.DefaultGenesisState())
}
func (a AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, _ client.TxEncodingConfig, message json.RawMessage) error {
var state types.GenesisState
if err := cdc.UnmarshalJSON(message, &state); err != nil {
return err
}
return state.Validate()
}
func (a AppModuleBasic) RegisterRESTRoutes(_ client.Context, _ *mux.Router) {}
func (a AppModuleBasic) RegisterGRPCGatewayRoutes(ctx client.Context, mux *runtime.ServeMux) {
_ = types.RegisterQueryServiceHandlerClient(context.Background(), mux, types.NewQueryServiceClient(ctx))
}
func (a AppModuleBasic) GetTxCmd() *cobra.Command {
return cli.GetTxCmd()
}
func (a AppModuleBasic) GetQueryCmd() *cobra.Command {
return cli.GetQueryCmd()
}
type AppModule struct {
AppModuleBasic
cdc codec.Marshaler
k keeper.Keeper
}
func NewAppModule(cdc codec.Marshaler, k keeper.Keeper) AppModule {
return AppModule{
cdc: cdc,
k: k,
}
}
func (a AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, message json.RawMessage) []abcitypes.ValidatorUpdate {
var state types.GenesisState
cdc.MustUnmarshalJSON(message, &state)
InitGenesis(ctx, a.k, &state)
return nil
}
func (a AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler) json.RawMessage {
return cdc.MustMarshalJSON(ExportGenesis(ctx, a.k))
}
func (a AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {
}
func (a AppModule) Route() sdk.Route {
return sdk.NewRoute(types.RouterKey, NewHandler(a.k))
}
func (a AppModule) QuerierRoute() string {
return types.QuerierRoute
}
func (a AppModule) LegacyQuerierHandler(_ *codec.LegacyAmino) sdk.Querier { return nil }
func (a AppModule) RegisterServices(configurator module.Configurator) {
types.RegisterMsgServiceServer(configurator.MsgServer(), keeper.NewMsgServiceServer(a.k))
types.RegisterQueryServiceServer(configurator.QueryServer(), keeper.NewQueryServiceServer(a.k))
}
func (a AppModule) BeginBlock(_ sdk.Context, _ abcitypes.RequestBeginBlock) {}
func (a AppModule) EndBlock(_ sdk.Context, _ abcitypes.RequestEndBlock) []abcitypes.ValidatorUpdate {
return nil
}
// AppSimulaion Methods
func (AppModule) GenerateGenesisState(simState *module.SimulationState) {
simulation.RandomizedGenesisState(simState)
}
func (a AppModule) ProposalContents(_ module.SimulationState) []sdksimulation.WeightedProposalContent {
return nil
}
func (a AppModule) RandomizedParams(r *rand.Rand) []sdksimulation.ParamChange {
return simulation.ParamChanges(r)
}
func (a AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) {
sdr[types.StoreKey] = simulation.NewDecodeStore(a.cdc)
}
func (a AppModule) WeightedOperations(simState module.SimulationState) []sdksimulation.WeightedOperation {
return simulation.WeightedOperations(simState.AppParams, simState.Cdc, a.k)
}
<file_sep>package cli
import (
"github.com/spf13/cobra"
)
func GetQueryCommands() []*cobra.Command {
return []*cobra.Command{
queryNode(),
queryNodes(),
queryParams(),
}
}
func GetTxCommands() []*cobra.Command {
cmd := &cobra.Command{
Use: "node",
Short: "Node module sub-commands",
}
cmd.AddCommand(
txRegister(),
txUpdate(),
txSetStatus(),
)
return []*cobra.Command{cmd}
}
<file_sep>package keeper
import (
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
protobuf "github.com/gogo/protobuf/types"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/node/types"
)
func (k *Keeper) SetNode(ctx sdk.Context, node types.Node) {
key := types.NodeKey(node.GetAddress())
value := k.cdc.MustMarshalBinaryBare(&node)
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) HasNode(ctx sdk.Context, address hubtypes.NodeAddress) bool {
store := k.Store(ctx)
key := types.NodeKey(address)
return store.Has(key)
}
func (k *Keeper) GetNode(ctx sdk.Context, address hubtypes.NodeAddress) (node types.Node, found bool) {
store := k.Store(ctx)
key := types.NodeKey(address)
value := store.Get(key)
if value == nil {
return node, false
}
k.cdc.MustUnmarshalBinaryBare(value, &node)
return node, true
}
func (k *Keeper) GetNodes(ctx sdk.Context, skip, limit int64) (items types.Nodes) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.NodeKeyPrefix),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
var item types.Node
k.cdc.MustUnmarshalBinaryBare(iter.Value(), &item)
items = append(items, item)
})
return items
}
func (k *Keeper) IterateNodes(ctx sdk.Context, fn func(index int, item types.Node) (stop bool)) {
store := k.Store(ctx)
iter := sdk.KVStorePrefixIterator(store, types.NodeKeyPrefix)
defer iter.Close()
for i := 0; iter.Valid(); iter.Next() {
var node types.Node
k.cdc.MustUnmarshalBinaryBare(iter.Value(), &node)
if stop := fn(i, node); stop {
break
}
i++
}
}
func (k *Keeper) SetActiveNode(ctx sdk.Context, address hubtypes.NodeAddress) {
key := types.ActiveNodeKey(address)
value := k.cdc.MustMarshalBinaryBare(&protobuf.BoolValue{Value: true})
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) DeleteActiveNode(ctx sdk.Context, address hubtypes.NodeAddress) {
key := types.ActiveNodeKey(address)
store := k.Store(ctx)
store.Delete(key)
}
func (k *Keeper) GetActiveNodes(ctx sdk.Context, skip, limit int64) (items types.Nodes) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.ActiveNodeKeyPrefix),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
item, _ := k.GetNode(ctx, types.AddressFromStatusNodeKey(iter.Key()))
items = append(items, item)
})
return items
}
func (k *Keeper) SetInactiveNode(ctx sdk.Context, address hubtypes.NodeAddress) {
key := types.InactiveNodeKey(address)
value := k.cdc.MustMarshalBinaryBare(&protobuf.BoolValue{Value: true})
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) DeleteInactiveNode(ctx sdk.Context, address hubtypes.NodeAddress) {
key := types.InactiveNodeKey(address)
store := k.Store(ctx)
store.Delete(key)
}
func (k *Keeper) GetInactiveNodes(ctx sdk.Context, skip, limit int64) (items types.Nodes) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.InactiveNodeKeyPrefix),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
item, _ := k.GetNode(ctx, types.AddressFromStatusNodeKey(iter.Key()))
items = append(items, item)
})
return items
}
func (k *Keeper) SetActiveNodeForProvider(ctx sdk.Context, provider hubtypes.ProvAddress, address hubtypes.NodeAddress) {
key := types.ActiveNodeForProviderKey(provider, address)
value := k.cdc.MustMarshalBinaryBare(&protobuf.BoolValue{Value: true})
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) DeleteActiveNodeForProvider(ctx sdk.Context, provider hubtypes.ProvAddress, address hubtypes.NodeAddress) {
store := k.Store(ctx)
key := types.ActiveNodeForProviderKey(provider, address)
store.Delete(key)
}
func (k *Keeper) GetActiveNodesForProvider(ctx sdk.Context, address hubtypes.ProvAddress, skip, limit int64) (items types.Nodes) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.GetActiveNodeForProviderKeyPrefix(address)),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
item, _ := k.GetNode(ctx, types.AddressFromStatusNodeForProviderKey(iter.Key()))
items = append(items, item)
})
return items
}
func (k *Keeper) SetInactiveNodeForProvider(ctx sdk.Context, provider hubtypes.ProvAddress, address hubtypes.NodeAddress) {
key := types.InactiveNodeForProviderKey(provider, address)
value := k.cdc.MustMarshalBinaryBare(&protobuf.BoolValue{Value: true})
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) DeleteInactiveNodeForProvider(ctx sdk.Context, provider hubtypes.ProvAddress, address hubtypes.NodeAddress) {
store := k.Store(ctx)
key := types.InactiveNodeForProviderKey(provider, address)
store.Delete(key)
}
func (k *Keeper) GetInactiveNodesForProvider(ctx sdk.Context, address hubtypes.ProvAddress, skip, limit int64) (items types.Nodes) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.GetInactiveNodeForProviderKeyPrefix(address)),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
item, _ := k.GetNode(ctx, types.AddressFromStatusNodeForProviderKey(iter.Key()))
items = append(items, item)
})
return items
}
func (k *Keeper) GetNodesForProvider(ctx sdk.Context, address hubtypes.ProvAddress, skip, limit int64) (items types.Nodes) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.GetActiveNodeForProviderKeyPrefix(address)),
sdk.KVStorePrefixIterator(store, types.GetInactiveNodeForProviderKeyPrefix(address)),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
item, _ := k.GetNode(ctx, types.AddressFromStatusNodeForProviderKey(iter.Key()))
items = append(items, item)
})
return items
}
func (k *Keeper) SetInactiveNodeAt(ctx sdk.Context, at time.Time, address hubtypes.NodeAddress) {
key := types.InactiveNodeAtKey(at, address)
value := k.cdc.MustMarshalBinaryBare(&protobuf.BoolValue{Value: true})
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) DeleteInactiveNodeAt(ctx sdk.Context, at time.Time, address hubtypes.NodeAddress) {
key := types.InactiveNodeAtKey(at, address)
store := k.Store(ctx)
store.Delete(key)
}
func (k *Keeper) IterateInactiveNodesAt(ctx sdk.Context, at time.Time, fn func(index int, key []byte, item types.Node) (stop bool)) {
store := k.Store(ctx)
iter := store.Iterator(types.InactiveNodeAtKeyPrefix, sdk.PrefixEndBytes(types.GetInactiveNodeAtKeyPrefix(at)))
defer iter.Close()
for i := 0; iter.Valid(); iter.Next() {
var (
key = iter.Key()
node, _ = k.GetNode(ctx, types.AddressFromStatusNodeAtKey(key))
)
if stop := fn(i, key, node); stop {
break
}
i++
}
}
<file_sep>package v06
import (
"github.com/sentinel-official/hub/types"
v05 "github.com/sentinel-official/hub/types/legacy/v0.5"
)
func MigrateBandwidth(v v05.Bandwidth) types.Bandwidth {
return types.Bandwidth{
Upload: v.Upload,
Download: v.Download,
}
}
<file_sep>package types
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
)
func (s *Swap) GetTxHash() (hash EthereumHash) {
return BytesToHash(s.TxHash)
}
func (s *Swap) Validate() error {
if len(s.TxHash) != EthereumHashLength {
return fmt.Errorf("tx_hash length should be 32")
}
if _, err := sdk.AccAddressFromBech32(s.Receiver); err != nil {
return err
}
if !s.Amount.IsValid() {
return fmt.Errorf("amount should be valid")
}
return nil
}
type Swaps []Swap
<file_sep>package cli
import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/tx"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/spf13/cobra"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/node/types"
)
func txRegister() *cobra.Command {
cmd := &cobra.Command{
Use: "register",
Short: "Register a node",
RunE: func(cmd *cobra.Command, args []string) error {
ctx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
s, err := cmd.Flags().GetString(flagProvider)
if err != nil {
return err
}
var provider hubtypes.ProvAddress
if len(s) > 0 {
provider, err = hubtypes.ProvAddressFromBech32(s)
if err != nil {
return err
}
}
s, err = cmd.Flags().GetString(flagPrice)
if err != nil {
return err
}
var price sdk.Coins
if len(s) > 0 {
price, err = sdk.ParseCoinsNormalized(s)
if err != nil {
return err
}
}
remoteURL, err := cmd.Flags().GetString(flagRemoteURL)
if err != nil {
return err
}
msg := types.NewMsgRegisterRequest(ctx.FromAddress, provider, price, remoteURL)
if err := msg.ValidateBasic(); err != nil {
return err
}
return tx.GenerateOrBroadcastTxCLI(ctx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
cmd.Flags().String(flagProvider, "", "node provider address")
cmd.Flags().String(flagPrice, "", "node price per Gigabyte")
cmd.Flags().String(flagRemoteURL, "", "node remote URL")
_ = cmd.MarkFlagRequired(flagRemoteURL)
return cmd
}
func txUpdate() *cobra.Command {
cmd := &cobra.Command{
Use: "update",
Short: "Update a node",
RunE: func(cmd *cobra.Command, args []string) error {
ctx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
s, err := cmd.Flags().GetString(flagProvider)
if err != nil {
return err
}
var provider hubtypes.ProvAddress
if len(s) > 0 {
provider, err = hubtypes.ProvAddressFromBech32(s)
if err != nil {
return err
}
}
s, err = cmd.Flags().GetString(flagPrice)
if err != nil {
return err
}
var price sdk.Coins
if len(s) > 0 {
price, err = sdk.ParseCoinsNormalized(s)
if err != nil {
return err
}
}
remoteURL, err := cmd.Flags().GetString(flagRemoteURL)
if err != nil {
return err
}
msg := types.NewMsgUpdateRequest(ctx.FromAddress.Bytes(), provider, price, remoteURL)
if err := msg.ValidateBasic(); err != nil {
return err
}
return tx.GenerateOrBroadcastTxCLI(ctx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
cmd.Flags().String(flagProvider, "", "node provider address")
cmd.Flags().String(flagPrice, "", "node price per Gigabyte")
cmd.Flags().String(flagRemoteURL, "", "node remote URL")
return cmd
}
func txSetStatus() *cobra.Command {
cmd := &cobra.Command{
Use: "status-set [Active | Inactive]",
Short: "Set a node status",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
ctx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
msg := types.NewMsgSetStatusRequest(ctx.FromAddress.Bytes(), hubtypes.StatusFromString(args[0]))
if err := msg.ValidateBasic(); err != nil {
return err
}
return tx.GenerateOrBroadcastTxCLI(ctx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}
<file_sep>package keeper
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/sentinel-official/hub/x/session/types"
)
func (k *Keeper) VerifyProof(ctx sdk.Context, address sdk.AccAddress, proof types.Proof, signature []byte) error {
account := k.GetAccount(ctx, address)
if account == nil {
return types.ErrorAccountDoesNotExist
}
if account.GetPubKey() == nil {
return types.ErrorPublicKeyDoesNotExist
}
bytes, err := proof.Marshal()
if err != nil {
return err
}
if !account.GetPubKey().VerifySignature(bytes, signature) {
return types.ErrorInvalidSignature
}
return nil
}
<file_sep>package types
import (
"fmt"
)
type (
GenesisState Deposits
)
func NewGenesisState(deposits Deposits) GenesisState {
return GenesisState(deposits)
}
func DefaultGenesisState() GenesisState {
return NewGenesisState(nil)
}
func ValidateGenesis(state GenesisState) error {
for _, deposit := range state {
if err := deposit.Validate(); err != nil {
return err
}
}
deposits := make(map[string]bool)
for _, deposit := range state {
if deposits[deposit.Address] {
return fmt.Errorf("found duplicate deposit address %s", deposit.Address)
}
deposits[deposit.Address] = true
}
return nil
}
<file_sep>package types
import (
"github.com/cosmos/cosmos-sdk/types/errors"
)
var (
ErrorMarshal = errors.Register(ModuleName, 101, "error occurred while marshalling")
ErrorUnmarshal = errors.Register(ModuleName, 102, "error occurred while unmarshalling")
ErrorUnknownMsgType = errors.Register(ModuleName, 103, "unknown message type")
ErrorUnknownQueryType = errors.Register(ModuleName, 104, "unknown query type")
ErrorInvalidFieldName = errors.Register(ModuleName, 105, "invalid field name; expected length between 1 and 64")
ErrorDuplicateProvider = errors.Register(ModuleName, 106, "duplicate provider")
ErrorProviderDoesNotExist = errors.Register(ModuleName, 107, "provider does not exist")
ErrorInvalidFieldFrom = errors.Register(ModuleName, 108, "invalid field from; expected a valid address")
ErrorInvalidFieldIdentity = errors.Register(ModuleName, 109, "invalid field identity; expected length between 0 and 64")
ErrorInvalidFieldWebsite = errors.Register(ModuleName, 110, "invalid field website; expected length between 0 and 64")
ErrorInvalidFieldDescription = errors.Register(ModuleName, 111, "invalid field description; expected length between 0 and 256")
)
<file_sep>package types
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
)
func (p *Plan) GetProvider() hubtypes.ProvAddress {
if p.Provider == "" {
return nil
}
address, err := hubtypes.ProvAddressFromBech32(p.Provider)
if err != nil {
panic(err)
}
return address
}
func (p *Plan) PriceForDenom(d string) (sdk.Coin, bool) {
for _, coin := range p.Price {
if coin.Denom == d {
return coin, true
}
}
return sdk.Coin{}, false
}
func (p *Plan) Validate() error {
if p.Id == 0 {
return fmt.Errorf("invalid id; expected positive value")
}
if _, err := hubtypes.ProvAddressFromBech32(p.Provider); err != nil {
return err
}
if p.Price != nil && !p.Price.IsValid() {
return fmt.Errorf("invalid price; expected non-nil and valid value")
}
if p.Validity <= 0 {
return fmt.Errorf("invalid validity; expected positive value")
}
if !p.Bytes.IsPositive() {
return fmt.Errorf("invalid bytes; expected positive value")
}
if !p.Status.Equal(hubtypes.StatusActive) && !p.Status.Equal(hubtypes.StatusInactive) {
return fmt.Errorf("invalid status; exptected active or inactive")
}
if p.StatusAt.IsZero() {
return fmt.Errorf("invalid status at; expected non-zero value")
}
return nil
}
type Plans []Plan
<file_sep>package v06
import (
hubtypes "github.com/sentinel-official/hub/types/legacy/v0.6"
"github.com/sentinel-official/hub/x/node/types"
legacy "github.com/sentinel-official/hub/x/node/types/legacy/v0.5"
)
func MigrateNode(item legacy.Node) types.Node {
return types.Node{
Address: item.Address.String(),
Provider: item.Provider.String(),
Price: item.Price,
RemoteURL: item.RemoteURL,
Status: hubtypes.MigrateStatus(item.Status),
StatusAt: item.StatusAt,
}
}
func MigrateNodes(items legacy.Nodes) types.Nodes {
var nodes types.Nodes
for _, item := range items {
nodes = append(nodes, MigrateNode(item))
}
return nodes
}
<file_sep>package v05
import (
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
legacyhubtypes "github.com/sentinel-official/hub/types/legacy/v0.5"
)
type (
Subscription struct {
ID uint64 `json:"id"`
Owner sdk.AccAddress `json:"owner"`
Node hubtypes.NodeAddress `json:"node"`
Price sdk.Coin `json:"price"`
Deposit sdk.Coin `json:"deposit"`
Plan uint64 `json:"plan"`
Expiry time.Time `json:"expiry"`
Free sdk.Int `json:"free"`
Status legacyhubtypes.Status `json:"status"`
StatusAt time.Time `json:"status_at"`
}
Subscriptions []Subscription
)
<file_sep>package cli
import (
"context"
"strconv"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/spf13/cobra"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/session/types"
)
func querySession() *cobra.Command {
cmd := &cobra.Command{
Use: "session",
Short: "Query a session",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
ctx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
id, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return err
}
var (
qc = types.NewQueryServiceClient(ctx)
)
res, err := qc.QuerySession(context.Background(),
types.NewQuerySessionRequest(id))
if err != nil {
return err
}
return ctx.PrintProto(res)
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
func querySessions() *cobra.Command {
cmd := &cobra.Command{
Use: "sessions",
Short: "Query sessions",
RunE: func(cmd *cobra.Command, args []string) (err error) {
ctx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
subscription, err := cmd.Flags().GetUint64(flagSubscription)
if err != nil {
return err
}
bech32Node, err := cmd.Flags().GetString(flagNodeAddress)
if err != nil {
return err
}
bech32Address, err := cmd.Flags().GetString(flagAddress)
if err != nil {
return err
}
pagination, err := client.ReadPageRequest(cmd.Flags())
if err != nil {
return err
}
var (
qc = types.NewQueryServiceClient(ctx)
)
if subscription > 0 {
res, err := qc.QuerySessionsForSubscription(context.Background(),
types.NewQuerySessionsForSubscriptionRequest(subscription, pagination))
if err != nil {
return err
}
return ctx.PrintProto(res)
} else if len(bech32Node) > 0 {
address, err := hubtypes.NodeAddressFromBech32(bech32Node)
if err != nil {
return err
}
res, err := qc.QuerySessionsForNode(context.Background(), types.NewQuerySessionsForNodeRequest(address, pagination))
if err != nil {
return err
}
return ctx.PrintProto(res)
} else if len(bech32Address) > 0 {
address, err := sdk.AccAddressFromBech32(bech32Address)
if err != nil {
return err
}
var (
active bool
status hubtypes.Status
)
active, err = cmd.Flags().GetBool(flagActive)
if err != nil {
return err
}
if active {
status = hubtypes.StatusActive
}
res, err := qc.QuerySessionsForAddress(context.Background(),
types.NewQuerySessionsForAddressRequest(address, status, pagination))
if err != nil {
return err
}
return ctx.PrintProto(res)
} else {
res, err := qc.QuerySessions(context.Background(),
types.NewQuerySessionsRequest(pagination))
if err != nil {
return err
}
return ctx.PrintProto(res)
}
},
}
flags.AddQueryFlagsToCmd(cmd)
flags.AddPaginationFlagsToCmd(cmd, "sessions")
cmd.Flags().String(flagAddress, "", "account address")
cmd.Flags().Uint64(flagSubscription, 0, "subscription ID")
cmd.Flags().String(flagNodeAddress, "", "node address")
cmd.Flags().Bool(flagActive, false, "active sessions only")
return cmd
}
func queryParams() *cobra.Command {
cmd := &cobra.Command{
Use: "session-params",
Short: "Query session module parameters",
RunE: func(cmd *cobra.Command, _ []string) error {
ctx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
var (
qc = types.NewQueryServiceClient(ctx)
)
res, err := qc.QueryParams(context.Background(),
types.NewQueryParamsRequest())
if err != nil {
return err
}
return ctx.PrintProto(res)
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
<file_sep>package v06
import (
"github.com/sentinel-official/hub/x/provider/types"
legacy "github.com/sentinel-official/hub/x/provider/types/legacy/v0.5"
)
func MigrateProvider(item legacy.Provider) types.Provider {
return types.Provider{
Address: item.Address.String(),
Name: item.Name,
Identity: item.Identity,
Website: item.Website,
Description: item.Description,
}
}
func MigrateProviders(items legacy.Providers) types.Providers {
var providers types.Providers
for _, item := range items {
providers = append(providers, MigrateProvider(item))
}
return providers
}
<file_sep>PACKAGES := $(shell go list ./...)
VERSION := $(shell echo $(shell git describe --tags) | sed 's/^v//')
COMMIT := $(shell git log -1 --format='%H')
TENDERMINT_VERSION := $(shell go list -m github.com/tendermint/tendermint | sed 's:.* ::')
BUILD_TAGS := $(strip netgo,ledger)
LD_FLAGS := -s -w \
-X github.com/cosmos/cosmos-sdk/version.Name=sentinel \
-X github.com/cosmos/cosmos-sdk/version.AppName=sentinelhub \
-X github.com/cosmos/cosmos-sdk/version.Version=${VERSION} \
-X github.com/cosmos/cosmos-sdk/version.Commit=${COMMIT} \
-X github.com/cosmos/cosmos-sdk/version.BuildTags=${BUILD_TAGS} \
-X github.com/tendermint/tendermint/version.TMCoreSemVer=$(TENDERMINT_VERSION)
.PHONY: benchmark
benchmark:
@go test -mod=readonly -v -bench ${PACKAGES}
.PHONY: clean
clean:
rm -rf ./bin ./vendor
.PHONY: install
install: mod-vendor
go install -mod=readonly -tags="${BUILD_TAGS}" -ldflags="${LD_FLAGS}" ./cmd/sentinelhub
.PHONY: go-lint
go-lint:
@golangci-lint run --fix
.PHONY: mod-vendor
mod-vendor: tools
@go mod vendor
@modvendor -copy="**/*.proto" -include=github.com/cosmos/cosmos-sdk/proto,github.com/cosmos/cosmos-sdk/third_party/proto
.PHONY: proto-gen
proto-gen:
@scripts/proto-gen.sh
.PHONY: proto-lint
proto-lint:
@find proto -name *.proto -exec clang-format-12 -i {} \;
.PHONY: test
test:
@go test -mod=readonly -v -cover ${PACKAGES}
.PHONY: tools
tools:
@go install github.com/bufbuild/buf/cmd/buf@v0.37.0
@go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.27.0
@go install github.com/goware/modvendor@v0.3.0
@go install github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway@v1.16.0
<file_sep>package v06
import (
"github.com/sentinel-official/hub/x/swap/types"
legacy "github.com/sentinel-official/hub/x/swap/types/legacy/v0.5"
)
func MigrateParams(params legacy.Params) types.Params {
return types.NewParams(
params.SwapEnabled,
params.SwapDenom,
params.ApproveBy.String(),
)
}
<file_sep>package v06
import (
"github.com/sentinel-official/hub/x/subscription/types"
legacy "github.com/sentinel-official/hub/x/subscription/types/legacy/v0.5"
)
func MigrateGenesisSubscription(item legacy.GenesisSubscription) types.GenesisSubscription {
return types.GenesisSubscription{
Subscription: MigrateSubscription(item.Subscription),
Quotas: MigrateQuotas(item.Quotas),
}
}
func MigrateGenesisSubscriptions(items legacy.GenesisSubscriptions) types.GenesisSubscriptions {
var subscriptions types.GenesisSubscriptions
for _, item := range items {
subscriptions = append(subscriptions, MigrateGenesisSubscription(item))
}
return subscriptions
}
func MigrateGenesisState(state *legacy.GenesisState) *types.GenesisState {
return types.NewGenesisState(
MigrateGenesisSubscriptions(state.Subscriptions),
MigrateParams(state.Params),
)
}
<file_sep>package cli
import (
"context"
"strconv"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/spf13/cobra"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/subscription/types"
)
func querySubscription() *cobra.Command {
cmd := &cobra.Command{
Use: "subscription",
Short: "Query a subscription",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
ctx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
id, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return err
}
var (
qc = types.NewQueryServiceClient(ctx)
)
res, err := qc.QuerySubscription(context.Background(),
types.NewQuerySubscriptionRequest(id))
if err != nil {
return err
}
return ctx.PrintProto(res)
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
func querySubscriptions() *cobra.Command {
cmd := &cobra.Command{
Use: "subscriptions",
Short: "Query subscriptions",
RunE: func(cmd *cobra.Command, args []string) (err error) {
ctx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
bech32Address, err := cmd.Flags().GetString(flagAddress)
if err != nil {
return err
}
plan, err := cmd.Flags().GetUint64(flagPlan)
if err != nil {
return err
}
bech32Node, err := cmd.Flags().GetString(flagNodeAddress)
if err != nil {
return err
}
status, err := cmd.Flags().GetString(flagStatus)
if err != nil {
return err
}
pagination, err := client.ReadPageRequest(cmd.Flags())
if err != nil {
return err
}
var (
qc = types.NewQueryServiceClient(ctx)
)
if len(bech32Address) > 0 {
address, err := sdk.AccAddressFromBech32(bech32Address)
if err != nil {
return err
}
res, err := qc.QuerySubscriptionsForAddress(context.Background(),
types.NewQuerySubscriptionsForAddressRequest(address, hubtypes.StatusFromString(status), pagination))
if err != nil {
return err
}
return ctx.PrintProto(res)
} else if plan > 0 {
res, err := qc.QuerySubscriptionsForPlan(context.Background(),
types.NewQuerySubscriptionsForPlanRequest(plan, pagination))
if err != nil {
return err
}
return ctx.PrintProto(res)
} else if len(bech32Node) > 0 {
address, err := hubtypes.NodeAddressFromBech32(bech32Node)
if err != nil {
return err
}
res, err := qc.QuerySubscriptionsForNode(context.Background(),
types.NewQuerySubscriptionsForNodeRequest(address, pagination))
if err != nil {
return err
}
return ctx.PrintProto(res)
} else {
res, err := qc.QuerySubscriptions(context.Background(),
types.NewQuerySubscriptionsRequest(pagination))
if err != nil {
return err
}
return ctx.PrintProto(res)
}
},
}
flags.AddQueryFlagsToCmd(cmd)
flags.AddPaginationFlagsToCmd(cmd, "subscriptions")
cmd.Flags().String(flagAddress, "", "account address")
cmd.Flags().Uint64(flagPlan, 0, "plan ID")
cmd.Flags().String(flagNodeAddress, "", "node address")
cmd.Flags().String(flagStatus, "", "status")
return cmd
}
func queryQuota() *cobra.Command {
cmd := &cobra.Command{
Use: "quota [id] [address]",
Short: "Query a quota of an address",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
ctx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
id, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return err
}
address, err := sdk.AccAddressFromBech32(args[1])
if err != nil {
return err
}
var (
qc = types.NewQueryServiceClient(ctx)
)
res, err := qc.QueryQuota(context.Background(),
types.NewQueryQuotaRequest(id, address))
if err != nil {
return err
}
return ctx.PrintProto(res)
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
func queryQuotas() *cobra.Command {
cmd := &cobra.Command{
Use: "quotas",
Short: "Query quotas of a subscription",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) (err error) {
ctx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
id, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return err
}
pagination, err := client.ReadPageRequest(cmd.Flags())
if err != nil {
return err
}
var (
qc = types.NewQueryServiceClient(ctx)
)
res, err := qc.QueryQuotas(context.Background(), types.NewQueryQuotasRequest(id, pagination))
if err != nil {
return err
}
return ctx.PrintProto(res)
},
}
flags.AddQueryFlagsToCmd(cmd)
flags.AddPaginationFlagsToCmd(cmd, "quotas")
return cmd
}
func queryParams() *cobra.Command {
cmd := &cobra.Command{
Use: "subscription-params",
Short: "Query subscription module parameters",
RunE: func(cmd *cobra.Command, _ []string) error {
ctx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
var (
qc = types.NewQueryServiceClient(ctx)
)
res, err := qc.QueryParams(context.Background(),
types.NewQueryParamsRequest())
if err != nil {
return err
}
return ctx.PrintProto(res)
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
<file_sep>package expected
import (
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
hubtypes "github.com/sentinel-official/hub/types"
nodetypes "github.com/sentinel-official/hub/x/node/types"
providertypes "github.com/sentinel-official/hub/x/provider/types"
)
type AccountKeeper interface {
GetAccount(ctx sdk.Context, address sdk.AccAddress) authtypes.AccountI
}
type ProviderKeeper interface {
GetProviders(ctx sdk.Context, skip, limit int64) providertypes.Providers
HasProvider(ctx sdk.Context, address hubtypes.ProvAddress) bool
}
type NodeKeeper interface {
GetNode(ctx sdk.Context, address hubtypes.NodeAddress) (nodetypes.Node, bool)
GetNodes(ctx sdk.Context, skip, limit int64) nodetypes.Nodes
GetNodesForProvider(ctx sdk.Context, address hubtypes.ProvAddress, skip, limit int64) nodetypes.Nodes
}
<file_sep>package types
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/errors"
hubtypes "github.com/sentinel-official/hub/types"
)
var (
_ sdk.Msg = (*MsgStartRequest)(nil)
_ sdk.Msg = (*MsgUpdateRequest)(nil)
_ sdk.Msg = (*MsgEndRequest)(nil)
)
func NewMsgStartRequest(from sdk.AccAddress, id uint64, node hubtypes.NodeAddress) *MsgStartRequest {
return &MsgStartRequest{
From: from.String(),
Id: id,
Node: node.String(),
}
}
func (m *MsgStartRequest) Route() string {
return RouterKey
}
func (m *MsgStartRequest) Type() string {
return fmt.Sprintf("%s:start", ModuleName)
}
func (m *MsgStartRequest) ValidateBasic() error {
// From shouldn't be nil or empty
if _, err := sdk.AccAddressFromBech32(m.From); err != nil {
return errors.Wrapf(ErrorInvalidField, "%s", "from")
}
// Id should be positive
if m.Id == 0 {
return errors.Wrapf(ErrorInvalidField, "%s", "id")
}
// Address shouldn't be nil or empty
if _, err := hubtypes.NodeAddressFromBech32(m.Node); err != nil {
return errors.Wrapf(ErrorInvalidField, "%s", "address")
}
return nil
}
func (m *MsgStartRequest) GetSignBytes() []byte {
return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(m))
}
func (m *MsgStartRequest) GetSigners() []sdk.AccAddress {
from, err := sdk.AccAddressFromBech32(m.From)
if err != nil {
panic(err)
}
return []sdk.AccAddress{from}
}
func NewMsgUpdateRequest(from hubtypes.NodeAddress, proof Proof, signature []byte) *MsgUpdateRequest {
return &MsgUpdateRequest{
From: from.String(),
Proof: proof,
Signature: signature,
}
}
func (m *MsgUpdateRequest) Route() string {
return RouterKey
}
func (m *MsgUpdateRequest) Type() string {
return fmt.Sprintf("%s:update", ModuleName)
}
func (m *MsgUpdateRequest) ValidateBasic() error {
// From shouldn't be nil or empty
if _, err := hubtypes.NodeAddressFromBech32(m.From); err != nil {
return errors.Wrapf(ErrorInvalidField, "%s", "from")
}
// Duration shouldn't be negative
if m.Proof.Duration < 0 {
return errors.Wrapf(ErrorInvalidField, "%s", "proof->duration")
}
// Bandwidth shouldn't be negative
if m.Proof.Bandwidth.IsAnyNegative() {
return errors.Wrapf(ErrorInvalidField, "%s", "proof->bandwidth")
}
// Signature can be nil, if not length should be 64
if m.Signature != nil && len(m.Signature) != 64 {
return errors.Wrapf(ErrorInvalidField, "%s", "signature")
}
return nil
}
func (m *MsgUpdateRequest) GetSignBytes() []byte {
return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(m))
}
func (m *MsgUpdateRequest) GetSigners() []sdk.AccAddress {
from, err := hubtypes.NodeAddressFromBech32(m.From)
if err != nil {
panic(err)
}
return []sdk.AccAddress{from.Bytes()}
}
func NewMsgEndRequest(from sdk.AccAddress, id uint64, rating uint64) *MsgEndRequest {
return &MsgEndRequest{
From: from.String(),
Id: id,
Rating: rating,
}
}
func (m *MsgEndRequest) Route() string {
return RouterKey
}
func (m *MsgEndRequest) Type() string {
return fmt.Sprintf("%s:end", ModuleName)
}
func (m *MsgEndRequest) ValidateBasic() error {
// From shouldn't be nil or empty
if _, err := sdk.AccAddressFromBech32(m.From); err != nil {
return errors.Wrapf(ErrorInvalidField, "%s", "from")
}
// Id should be positive
if m.Id == 0 {
return errors.Wrapf(ErrorInvalidField, "%s", "id")
}
// Rating shouldn't be greater than 10
if m.Rating > 10 {
return errors.Wrapf(ErrorInvalidField, "%s", "rating")
}
return nil
}
func (m *MsgEndRequest) GetSignBytes() []byte {
return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(m))
}
func (m *MsgEndRequest) GetSigners() []sdk.AccAddress {
from, err := sdk.AccAddressFromBech32(m.From)
if err != nil {
panic(err)
}
return []sdk.AccAddress{from}
}
<file_sep>package keeper
import (
"fmt"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/store/prefix"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/tendermint/tendermint/libs/log"
"github.com/sentinel-official/hub/x/plan/expected"
"github.com/sentinel-official/hub/x/plan/types"
)
type Keeper struct {
cdc codec.BinaryMarshaler
key sdk.StoreKey
provider expected.ProviderKeeper
node expected.NodeKeeper
}
func NewKeeper(cdc codec.BinaryMarshaler, key sdk.StoreKey) Keeper {
return Keeper{
cdc: cdc,
key: key,
}
}
func (k *Keeper) WithProviderKeeper(keeper expected.ProviderKeeper) {
k.provider = keeper
}
func (k *Keeper) WithNodeKeeper(keeper expected.NodeKeeper) {
k.node = keeper
}
func (k *Keeper) Logger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", "x/"+types.ModuleName)
}
func (k *Keeper) Store(ctx sdk.Context) sdk.KVStore {
child := fmt.Sprintf("%s/", types.ModuleName)
return prefix.NewStore(ctx.KVStore(k.key), []byte(child))
}
<file_sep>package types
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/errors"
hubtypes "github.com/sentinel-official/hub/types"
)
var (
_ sdk.Msg = (*MsgSubscribeToNodeRequest)(nil)
_ sdk.Msg = (*MsgSubscribeToPlanRequest)(nil)
_ sdk.Msg = (*MsgCancelRequest)(nil)
_ sdk.Msg = (*MsgAddQuotaRequest)(nil)
_ sdk.Msg = (*MsgUpdateQuotaRequest)(nil)
)
func NewMsgSubscribeToNodeRequest(from sdk.AccAddress, address hubtypes.NodeAddress, deposit sdk.Coin) *MsgSubscribeToNodeRequest {
return &MsgSubscribeToNodeRequest{
From: from.String(),
Address: address.String(),
Deposit: deposit,
}
}
func (m *MsgSubscribeToNodeRequest) Route() string {
return RouterKey
}
func (m *MsgSubscribeToNodeRequest) Type() string {
return fmt.Sprintf("%s:subscribe_to_node", ModuleName)
}
func (m *MsgSubscribeToNodeRequest) ValidateBasic() error {
if _, err := sdk.AccAddressFromBech32(m.From); err != nil {
return errors.Wrapf(ErrorInvalidField, "%s", "from")
}
// Address should be valid
if _, err := hubtypes.NodeAddressFromBech32(m.Address); err != nil {
return errors.Wrapf(ErrorInvalidField, "%s", "address")
}
// Deposit should be valid and positive
if !m.Deposit.IsValid() || !m.Deposit.IsPositive() {
return errors.Wrapf(ErrorInvalidField, "%s", "deposit")
}
return nil
}
func (m *MsgSubscribeToNodeRequest) GetSignBytes() []byte {
return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(m))
}
func (m *MsgSubscribeToNodeRequest) GetSigners() []sdk.AccAddress {
from, err := sdk.AccAddressFromBech32(m.From)
if err != nil {
panic(err)
}
return []sdk.AccAddress{from}
}
func NewMsgSubscribeToPlanRequest(from sdk.AccAddress, id uint64, denom string) *MsgSubscribeToPlanRequest {
return &MsgSubscribeToPlanRequest{
From: from.String(),
Id: id,
Denom: denom,
}
}
func (m *MsgSubscribeToPlanRequest) Route() string {
return RouterKey
}
func (m *MsgSubscribeToPlanRequest) Type() string {
return fmt.Sprintf("%s:subscribe_to_plan", ModuleName)
}
func (m *MsgSubscribeToPlanRequest) ValidateBasic() error {
if _, err := sdk.AccAddressFromBech32(m.From); err != nil {
return errors.Wrapf(ErrorInvalidField, "%s", "from")
}
// Id shouldn't be zero
if m.Id == 0 {
return errors.Wrapf(ErrorInvalidField, "%s", "id")
}
// Denom should be valid
if err := sdk.ValidateDenom(m.Denom); err != nil {
return errors.Wrapf(ErrorInvalidField, "%s", "denom")
}
return nil
}
func (m *MsgSubscribeToPlanRequest) GetSignBytes() []byte {
return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(m))
}
func (m *MsgSubscribeToPlanRequest) GetSigners() []sdk.AccAddress {
from, err := sdk.AccAddressFromBech32(m.From)
if err != nil {
panic(err)
}
return []sdk.AccAddress{from}
}
func NewMsgCancelRequest(from sdk.AccAddress, id uint64) *MsgCancelRequest {
return &MsgCancelRequest{
From: from.String(),
Id: id,
}
}
func (m *MsgCancelRequest) Route() string {
return RouterKey
}
func (m *MsgCancelRequest) Type() string {
return fmt.Sprintf("%s:cancel", ModuleName)
}
func (m *MsgCancelRequest) ValidateBasic() error {
if _, err := sdk.AccAddressFromBech32(m.From); err != nil {
return errors.Wrapf(ErrorInvalidField, "%s", "from")
}
// Id shouldn't be zero
if m.Id == 0 {
return errors.Wrapf(ErrorInvalidField, "%s", "id")
}
return nil
}
func (m *MsgCancelRequest) GetSignBytes() []byte {
return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(m))
}
func (m *MsgCancelRequest) GetSigners() []sdk.AccAddress {
from, err := sdk.AccAddressFromBech32(m.From)
if err != nil {
panic(err)
}
return []sdk.AccAddress{from}
}
func NewMsgAddQuotaRequest(from sdk.AccAddress, id uint64, address sdk.AccAddress, bytes sdk.Int) *MsgAddQuotaRequest {
return &MsgAddQuotaRequest{
From: from.String(),
Id: id,
Address: address.String(),
Bytes: bytes,
}
}
func (m *MsgAddQuotaRequest) Route() string {
return RouterKey
}
func (m *MsgAddQuotaRequest) Type() string {
return fmt.Sprintf("%s:add_quota", ModuleName)
}
func (m *MsgAddQuotaRequest) ValidateBasic() error {
if _, err := sdk.AccAddressFromBech32(m.From); err != nil {
return errors.Wrapf(ErrorInvalidField, "%s", "from")
}
// Id shouldn't be zero
if m.Id == 0 {
return errors.Wrapf(ErrorInvalidField, "%s", "id")
}
// Address should be valid
if _, err := sdk.AccAddressFromBech32(m.Address); err != nil {
return errors.Wrapf(ErrorInvalidField, "%s", "address")
}
// Bytes should be positive
if !m.Bytes.IsPositive() {
return errors.Wrapf(ErrorInvalidField, "%s", "bytes")
}
return nil
}
func (m *MsgAddQuotaRequest) GetSignBytes() []byte {
return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(m))
}
func (m *MsgAddQuotaRequest) GetSigners() []sdk.AccAddress {
from, err := sdk.AccAddressFromBech32(m.From)
if err != nil {
panic(err)
}
return []sdk.AccAddress{from}
}
func NewMsgUpdateQuotaRequest(from sdk.AccAddress, id uint64, address sdk.AccAddress, bytes sdk.Int) *MsgUpdateQuotaRequest {
return &MsgUpdateQuotaRequest{
From: from.String(),
Id: id,
Address: address.String(),
Bytes: bytes,
}
}
func (m *MsgUpdateQuotaRequest) Route() string {
return RouterKey
}
func (m *MsgUpdateQuotaRequest) Type() string {
return fmt.Sprintf("%s:update_quota", ModuleName)
}
func (m *MsgUpdateQuotaRequest) ValidateBasic() error {
if _, err := sdk.AccAddressFromBech32(m.From); err != nil {
return errors.Wrapf(ErrorInvalidField, "%s", "from")
}
// Id shouldn't be zero
if m.Id == 0 {
return errors.Wrapf(ErrorInvalidField, "%s", "id")
}
// Address shouldn be valid
if _, err := sdk.AccAddressFromBech32(m.Address); err != nil {
return errors.Wrapf(ErrorInvalidField, "%s", "address")
}
// Bytes should be positive
if !m.Bytes.IsPositive() {
return errors.Wrapf(ErrorInvalidField, "%s", "bytes")
}
return nil
}
func (m *MsgUpdateQuotaRequest) GetSignBytes() []byte {
return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(m))
}
func (m *MsgUpdateQuotaRequest) GetSigners() []sdk.AccAddress {
from, err := sdk.AccAddressFromBech32(m.From)
if err != nil {
panic(err)
}
return []sdk.AccAddress{from}
}
<file_sep>package cli
import (
"strconv"
"time"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/tx"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/spf13/cobra"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/plan/types"
)
func txAdd() *cobra.Command {
cmd := &cobra.Command{
Use: "add",
Short: "Add a plan",
RunE: func(cmd *cobra.Command, args []string) error {
ctx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
s, err := cmd.Flags().GetString(flagPrice)
if err != nil {
return err
}
var price sdk.Coins
if len(s) > 0 {
price, err = sdk.ParseCoinsNormalized(s)
if err != nil {
return err
}
}
s, err = cmd.Flags().GetString(flagValidity)
if err != nil {
return err
}
validity, err := time.ParseDuration(s)
if err != nil {
return err
}
bytes, err := cmd.Flags().GetInt64(flagBytes)
if err != nil {
return err
}
msg := types.NewMsgAddRequest(ctx.FromAddress.Bytes(), price, validity, sdk.NewInt(bytes))
if err := msg.ValidateBasic(); err != nil {
return err
}
return tx.GenerateOrBroadcastTxCLI(ctx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
cmd.Flags().String(flagPrice, "", "plan price")
cmd.Flags().String(flagValidity, "", "plan validity")
cmd.Flags().Int64(flagBytes, 0, "plan bytes (upload + download)")
_ = cmd.MarkFlagRequired(flagPrice)
_ = cmd.MarkFlagRequired(flagValidity)
_ = cmd.MarkFlagRequired(flagBytes)
return cmd
}
func txSetStatus() *cobra.Command {
cmd := &cobra.Command{
Use: "status-set [plan] [Active | Inactive]",
Short: "Set a plan status",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
ctx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
id, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return err
}
msg := types.NewMsgSetStatusRequest(ctx.FromAddress.Bytes(), id, hubtypes.StatusFromString(args[1]))
if err := msg.ValidateBasic(); err != nil {
return err
}
return tx.GenerateOrBroadcastTxCLI(ctx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}
func txAddNode() *cobra.Command {
cmd := &cobra.Command{
Use: "node-add [plan] [node]",
Short: "Add a node for a plan",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
ctx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
id, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return err
}
node, err := hubtypes.NodeAddressFromBech32(args[1])
if err != nil {
return err
}
msg := types.NewMsgAddNodeRequest(ctx.FromAddress.Bytes(), id, node)
if err := msg.ValidateBasic(); err != nil {
return err
}
return tx.GenerateOrBroadcastTxCLI(ctx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}
func txRemoveNode() *cobra.Command {
cmd := &cobra.Command{
Use: "node-remove [plan] [node]",
Short: "Remove a node for a plan",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
ctx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
id, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return err
}
node, err := hubtypes.NodeAddressFromBech32(args[1])
if err != nil {
return err
}
msg := types.NewMsgRemoveNodeRequest(ctx.FromAddress, id, node)
if err := msg.ValidateBasic(); err != nil {
return err
}
return tx.GenerateOrBroadcastTxCLI(ctx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}
<file_sep>package types
import (
"fmt"
)
func NewGenesisState(providers Providers, params Params) *GenesisState {
return &GenesisState{
Providers: providers,
Params: params,
}
}
func DefaultGenesisState() *GenesisState {
return NewGenesisState(nil, DefaultParams())
}
func ValidateGenesis(state *GenesisState) error {
if err := state.Params.Validate(); err != nil {
return err
}
for _, provider := range state.Providers {
if err := provider.Validate(); err != nil {
return err
}
}
providers := make(map[string]bool)
for _, provider := range state.Providers {
if providers[provider.Address] {
return fmt.Errorf("found duplicate provider address %s", provider.Address)
}
providers[provider.Address] = true
}
return nil
}
<file_sep>package keeper
import (
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
protobuf "github.com/gogo/protobuf/types"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/session/types"
)
func (k *Keeper) SetCount(ctx sdk.Context, count uint64) {
key := types.CountKey
value := k.cdc.MustMarshalBinaryBare(&protobuf.UInt64Value{Value: count})
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) GetCount(ctx sdk.Context) uint64 {
store := k.Store(ctx)
key := types.CountKey
value := store.Get(key)
if value == nil {
return 0
}
var count protobuf.UInt64Value
k.cdc.MustUnmarshalBinaryBare(value, &count)
return count.Value
}
func (k *Keeper) SetSession(ctx sdk.Context, session types.Session) {
key := types.SessionKey(session.Id)
value := k.cdc.MustMarshalBinaryBare(&session)
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) GetSession(ctx sdk.Context, id uint64) (session types.Session, found bool) {
store := k.Store(ctx)
key := types.SessionKey(id)
value := store.Get(key)
if value == nil {
return session, false
}
k.cdc.MustUnmarshalBinaryBare(value, &session)
return session, true
}
func (k *Keeper) GetSessions(ctx sdk.Context, skip, limit int64) (items types.Sessions) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.SessionKeyPrefix),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
var item types.Session
k.cdc.MustUnmarshalBinaryBare(iter.Value(), &item)
items = append(items, item)
})
return items
}
func (k *Keeper) IterateSessions(ctx sdk.Context, fn func(index int, item types.Session) (stop bool)) {
store := k.Store(ctx)
iter := sdk.KVStorePrefixIterator(store, types.SessionKeyPrefix)
defer iter.Close()
for i := 0; iter.Valid(); iter.Next() {
var session types.Session
k.cdc.MustUnmarshalBinaryBare(iter.Value(), &session)
if stop := fn(i, session); stop {
break
}
i++
}
}
func (k *Keeper) SetSessionForSubscription(ctx sdk.Context, subscription, id uint64) {
key := types.SessionForSubscriptionKey(subscription, id)
value := k.cdc.MustMarshalBinaryBare(&protobuf.BoolValue{Value: true})
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) GetSessionsForSubscription(ctx sdk.Context, id uint64, skip, limit int64) (items types.Sessions) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.GetSessionForSubscriptionKeyPrefix(id)),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
item, _ := k.GetSession(ctx, types.IDFromSessionForSubscriptionKey(iter.Key()))
items = append(items, item)
})
return items
}
func (k *Keeper) SetSessionForNode(ctx sdk.Context, address hubtypes.NodeAddress, id uint64) {
key := types.SessionForNodeKey(address, id)
value := k.cdc.MustMarshalBinaryBare(&protobuf.BoolValue{Value: true})
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) GetSessionsForNode(ctx sdk.Context, address hubtypes.NodeAddress, skip, limit int64) (items types.Sessions) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.GetSessionForNodeKeyPrefix(address)),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
item, _ := k.GetSession(ctx, types.IDFromSessionForNodeKey(iter.Key()))
items = append(items, item)
})
return items
}
func (k *Keeper) SetInactiveSessionForAddress(ctx sdk.Context, address sdk.AccAddress, id uint64) {
key := types.InactiveSessionForAddressKey(address, id)
value := k.cdc.MustMarshalBinaryBare(&protobuf.BoolValue{Value: true})
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) DeleteInactiveSessionForAddress(ctx sdk.Context, address sdk.AccAddress, id uint64) {
key := types.InactiveSessionForAddressKey(address, id)
store := k.Store(ctx)
store.Delete(key)
}
func (k *Keeper) GetInactiveSessionsForAddress(ctx sdk.Context, address sdk.AccAddress, skip, limit int64) (items types.Sessions) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.GetInactiveSessionForAddressKeyPrefix(address)),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
item, _ := k.GetSession(ctx, types.IDFromStatusSessionForAddressKey(iter.Key()))
items = append(items, item)
})
return items
}
func (k *Keeper) SetActiveSessionForAddress(ctx sdk.Context, address sdk.AccAddress, id uint64) {
key := types.ActiveSessionForAddressKey(address, id)
value := k.cdc.MustMarshalBinaryBare(&protobuf.BoolValue{Value: true})
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) DeleteActiveSessionForAddress(ctx sdk.Context, address sdk.AccAddress, id uint64) {
key := types.ActiveSessionForAddressKey(address, id)
store := k.Store(ctx)
store.Delete(key)
}
func (k *Keeper) GetActiveSessionsForAddress(ctx sdk.Context, address sdk.AccAddress, skip, limit int64) (items types.Sessions) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.GetActiveSessionForAddressKeyPrefix(address)),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
item, _ := k.GetSession(ctx, types.IDFromStatusSessionForAddressKey(iter.Key()))
items = append(items, item)
})
return items
}
func (k *Keeper) SetActiveSessionAt(ctx sdk.Context, at time.Time, id uint64) {
key := types.ActiveSessionAtKey(at, id)
value := k.cdc.MustMarshalBinaryBare(&protobuf.BoolValue{Value: true})
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) DeleteActiveSessionAt(ctx sdk.Context, at time.Time, id uint64) {
key := types.ActiveSessionAtKey(at, id)
store := k.Store(ctx)
store.Delete(key)
}
func (k *Keeper) IterateActiveSessionsAt(ctx sdk.Context, end time.Time, fn func(index int, key []byte, item types.Session) (stop bool)) {
store := k.Store(ctx)
iter := store.Iterator(types.ActiveSessionAtKeyPrefix, sdk.PrefixEndBytes(types.GetActiveSessionAtKeyPrefix(end)))
defer iter.Close()
for i := 0; iter.Valid(); iter.Next() {
var (
key = iter.Key()
session, _ = k.GetSession(ctx, types.IDFromActiveSessionAtKey(key))
)
if stop := fn(i, key, session); stop {
break
}
i++
}
}
<file_sep>package v05
import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
type (
Quota struct {
Address sdk.AccAddress `json:"address"`
Consumed sdk.Int `json:"consumed"`
Allocated sdk.Int `json:"allocated"`
}
Quotas []Quota
)
<file_sep>package simulation
import (
"fmt"
"testing"
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/kv"
"github.com/sentinel-official/hub/x/swap/types"
)
func TestDecoderStore(t *testing.T) {
cdc, _ := simapp.MakeCodecs()
dec := NewDecodeStore(cdc)
swapperPK := ed25519.GenPrivKey().PubKey()
swapperAddr := sdk.AccAddress(swapperPK.Address())
receiver := sdk.AccAddress(swapperPK.Address())
txHash := types.EthereumHash{}
txHash.SetBytes([]byte("6ca7abe5be0ee9bacf582a42f70a2c384b2121ffa6cc33f3ae0b7e41d3480dbe"))
amount := sdk.NewInt(1000)
swap := types.NewMsgSwapRequest(swapperAddr, txHash, receiver, amount)
KVPair := kv.Pair{
Key: types.SwapKeyPrefix, Value: cdc.MustMarshalBinaryBare(swap),
}
tests := []struct {
name string
want string
}{
{"SwapMessage", fmt.Sprintf("%s\n%s", *swap, *swap)},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
require.Equal(t, tt.want, dec(KVPair, KVPair), tt.name)
})
}
}
<file_sep>package expected
import (
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
hubtypes "github.com/sentinel-official/hub/types"
providertypes "github.com/sentinel-official/hub/x/provider/types"
)
type AccountKeeper interface {
GetAccount(ctx sdk.Context, address sdk.AccAddress) authtypes.AccountI
}
type DistributionKeeper interface {
FundCommunityPool(ctx sdk.Context, amount sdk.Coins, sender sdk.AccAddress) error
}
type ProviderKeeper interface {
HasProvider(ctx sdk.Context, address hubtypes.ProvAddress) bool
GetProviders(ctx sdk.Context, skip, limit int64) providertypes.Providers
}
type PlanKeeper interface {
GetCountForNodeByProvider(ctx sdk.Context, p hubtypes.ProvAddress, n hubtypes.NodeAddress) uint64
}
<file_sep>package simulation
import (
"bytes"
"fmt"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/types/kv"
"github.com/sentinel-official/hub/x/swap/types"
)
func NewDecodeStore(cdc codec.Marshaler) func(kvA, kvB kv.Pair) string {
decoderFn := func(kvA, kvB kv.Pair) string {
if bytes.Equal(kvA.Key[:1], types.SwapKeyPrefix) {
var swapA, swapB types.MsgSwapRequest
cdc.MustUnmarshalBinaryBare(kvA.Value, &swapA)
cdc.MustUnmarshalBinaryBare(kvB.Value, &swapB)
return fmt.Sprintf("%s\n%s", swapA, swapB)
}
panic(fmt.Sprintf("invalid swap key prefix: %X", kvA.Key[:1]))
}
return decoderFn
}
<file_sep>package v05
import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
type (
Deposit struct {
Address sdk.AccAddress `json:"address"`
Coins sdk.Coins `json:"coins"`
}
Deposits []Deposit
)
<file_sep>package types
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/query"
hubtypes "github.com/sentinel-official/hub/types"
)
func NewQuerySubscriptionRequest(id uint64) *QuerySubscriptionRequest {
return &QuerySubscriptionRequest{
Id: id,
}
}
func NewQuerySubscriptionsRequest(pagination *query.PageRequest) *QuerySubscriptionsRequest {
return &QuerySubscriptionsRequest{
Pagination: pagination,
}
}
func NewQuerySubscriptionsForNodeRequest(address hubtypes.NodeAddress, pagination *query.PageRequest) *QuerySubscriptionsForNodeRequest {
return &QuerySubscriptionsForNodeRequest{
Address: address.String(),
Pagination: pagination,
}
}
func NewQuerySubscriptionsForPlanRequest(id uint64, pagination *query.PageRequest) *QuerySubscriptionsForPlanRequest {
return &QuerySubscriptionsForPlanRequest{
Id: id,
Pagination: pagination,
}
}
func NewQuerySubscriptionsForAddressRequest(address sdk.AccAddress, status hubtypes.Status, pagination *query.PageRequest) *QuerySubscriptionsForAddressRequest {
return &QuerySubscriptionsForAddressRequest{
Address: address.String(),
Status: status,
Pagination: pagination,
}
}
func NewQueryQuotaRequest(id uint64, address sdk.AccAddress) *QueryQuotaRequest {
return &QueryQuotaRequest{
Id: id,
Address: address.String(),
}
}
func NewQueryQuotasRequest(id uint64, pagination *query.PageRequest) *QueryQuotasRequest {
return &QueryQuotasRequest{
Id: id,
Pagination: pagination,
}
}
func NewQueryParamsRequest() *QueryParamsRequest {
return &QueryParamsRequest{}
}
<file_sep>package types
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
)
func (d *Deposit) GetAddress() sdk.AccAddress {
if d.Address == "" {
return nil
}
address, err := sdk.AccAddressFromBech32(d.Address)
if err != nil {
panic(err)
}
return address
}
func (d *Deposit) Validate() error {
if _, err := sdk.AccAddressFromBech32(d.Address); err != nil {
return err
}
if d.Coins == nil || !d.Coins.IsValid() {
return fmt.Errorf("invalid coins; expected non-nil and valid value")
}
return nil
}
type (
Deposits []Deposit
)
<file_sep>package expected
import (
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
hubtypes "github.com/sentinel-official/hub/types"
nodetypes "github.com/sentinel-official/hub/x/node/types"
plantypes "github.com/sentinel-official/hub/x/plan/types"
)
type AccountKeeper interface {
GetAccount(ctx sdk.Context, address sdk.AccAddress) authtypes.AccountI
}
type BankKeeper interface {
SendCoins(ctx sdk.Context, from sdk.AccAddress, to sdk.AccAddress, coins sdk.Coins) error
}
type DepositKeeper interface {
Add(ctx sdk.Context, address sdk.AccAddress, coins sdk.Coins) error
Subtract(ctx sdk.Context, address sdk.AccAddress, coins sdk.Coins) error
}
type NodeKeeper interface {
GetNode(ctx sdk.Context, address hubtypes.NodeAddress) (nodetypes.Node, bool)
GetNodes(ctx sdk.Context, skip, limit int64) nodetypes.Nodes
GetActiveNodes(ctx sdk.Context, skip, limit int64) nodetypes.Nodes
}
type PlanKeeper interface {
GetPlan(ctx sdk.Context, id uint64) (plantypes.Plan, bool)
GetPlans(ctx sdk.Context, skip, limit int64) plantypes.Plans
GetActivePlans(ctx sdk.Context, skip, limit int64) plantypes.Plans
}
<file_sep>package plan
import (
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/plan/keeper"
"github.com/sentinel-official/hub/x/plan/types"
)
func InitGenesis(ctx sdk.Context, k keeper.Keeper, state types.GenesisState) {
for _, item := range state {
k.SetPlan(ctx, item.Plan)
if item.Plan.Status.Equal(hubtypes.StatusActive) {
k.SetActivePlan(ctx, item.Plan.Id)
k.SetActivePlanForProvider(ctx, item.Plan.GetProvider(), item.Plan.Id)
} else {
k.SetInactivePlan(ctx, item.Plan.Id)
k.SetInactivePlanForProvider(ctx, item.Plan.GetProvider(), item.Plan.Id)
}
for _, node := range item.Nodes {
address, err := hubtypes.NodeAddressFromBech32(node)
if err != nil {
panic(err)
}
k.SetNodeForPlan(ctx, item.Plan.Id, address)
}
}
k.SetCount(ctx, uint64(len(state)))
}
func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState {
plans := k.GetPlans(ctx, 0, 0)
items := make(types.GenesisPlans, 0, len(plans))
for _, plan := range plans {
item := types.GenesisPlan{
Plan: plan,
Nodes: nil,
}
nodes := k.GetNodesForPlan(ctx, plan.Id, 0, 0)
for _, node := range nodes {
item.Nodes = append(item.Nodes, node.Address)
}
items = append(items, item)
}
return types.NewGenesisState(items)
}
<file_sep>package keeper
import (
sdk "github.com/cosmos/cosmos-sdk/types"
protobuf "github.com/gogo/protobuf/types"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/plan/types"
)
func (k *Keeper) SetCount(ctx sdk.Context, count uint64) {
key := types.CountKey
value := k.cdc.MustMarshalBinaryBare(&protobuf.UInt64Value{Value: count})
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) GetCount(ctx sdk.Context) uint64 {
store := k.Store(ctx)
key := types.CountKey
value := store.Get(key)
if value == nil {
return 0
}
var count protobuf.UInt64Value
k.cdc.MustUnmarshalBinaryBare(value, &count)
return count.GetValue()
}
func (k *Keeper) SetPlan(ctx sdk.Context, plan types.Plan) {
key := types.PlanKey(plan.Id)
value := k.cdc.MustMarshalBinaryBare(&plan)
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) GetPlan(ctx sdk.Context, id uint64) (plan types.Plan, found bool) {
store := k.Store(ctx)
key := types.PlanKey(id)
value := store.Get(key)
if value == nil {
return plan, false
}
k.cdc.MustUnmarshalBinaryBare(value, &plan)
return plan, true
}
func (k *Keeper) GetPlans(ctx sdk.Context, skip, limit int64) (items types.Plans) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.PlanKeyPrefix),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
var item types.Plan
k.cdc.MustUnmarshalBinaryBare(iter.Value(), &item)
items = append(items, item)
})
return items
}
func (k *Keeper) SetActivePlan(ctx sdk.Context, id uint64) {
key := types.ActivePlanKey(id)
value := k.cdc.MustMarshalBinaryBare(&protobuf.BoolValue{Value: true})
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) DeleteActivePlan(ctx sdk.Context, id uint64) {
key := types.ActivePlanKey(id)
store := k.Store(ctx)
store.Delete(key)
}
func (k *Keeper) GetActivePlans(ctx sdk.Context, skip, limit int64) (items types.Plans) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.ActivePlanKeyPrefix),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
item, _ := k.GetPlan(ctx, types.IDFromStatusPlanKey(iter.Key()))
items = append(items, item)
})
return items
}
func (k *Keeper) SetInactivePlan(ctx sdk.Context, id uint64) {
key := types.InactivePlanKey(id)
value := k.cdc.MustMarshalBinaryBare(&protobuf.BoolValue{Value: true})
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) DeleteInactivePlan(ctx sdk.Context, id uint64) {
key := types.InactivePlanKey(id)
store := k.Store(ctx)
store.Delete(key)
}
func (k *Keeper) GetInactivePlans(ctx sdk.Context, skip, limit int64) (items types.Plans) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.InactivePlanKeyPrefix),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
item, _ := k.GetPlan(ctx, types.IDFromStatusPlanKey(iter.Key()))
items = append(items, item)
})
return items
}
func (k *Keeper) SetActivePlanForProvider(ctx sdk.Context, address hubtypes.ProvAddress, id uint64) {
key := types.ActivePlanForProviderKey(address, id)
value := k.cdc.MustMarshalBinaryBare(&protobuf.BoolValue{Value: true})
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) DeleteActivePlanForProvider(ctx sdk.Context, address hubtypes.ProvAddress, id uint64) {
store := k.Store(ctx)
key := types.ActivePlanForProviderKey(address, id)
store.Delete(key)
}
func (k *Keeper) GetActivePlansForProvider(ctx sdk.Context, address hubtypes.ProvAddress, skip, limit int64) (items types.Plans) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.GetActivePlanForProviderKeyPrefix(address)),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
item, _ := k.GetPlan(ctx, types.IDFromStatusPlanForProviderKey(iter.Key()))
items = append(items, item)
})
return items
}
func (k *Keeper) SetInactivePlanForProvider(ctx sdk.Context, address hubtypes.ProvAddress, id uint64) {
key := types.InactivePlanForProviderKey(address, id)
value := k.cdc.MustMarshalBinaryBare(&protobuf.BoolValue{Value: true})
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) DeleteInactivePlanForProvider(ctx sdk.Context, address hubtypes.ProvAddress, id uint64) {
store := k.Store(ctx)
key := types.InactivePlanForProviderKey(address, id)
store.Delete(key)
}
func (k *Keeper) GetInactivePlansForProvider(ctx sdk.Context, address hubtypes.ProvAddress, skip, limit int64) (items types.Plans) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.GetInactivePlanForProviderKeyPrefix(address)),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
item, _ := k.GetPlan(ctx, types.IDFromStatusPlanForProviderKey(iter.Key()))
items = append(items, item)
})
return items
}
func (k *Keeper) GetPlansForProvider(ctx sdk.Context, address hubtypes.ProvAddress, skip, limit int64) (items types.Plans) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.GetActivePlanForProviderKeyPrefix(address)),
sdk.KVStorePrefixIterator(store, types.GetInactivePlanForProviderKeyPrefix(address)),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
item, _ := k.GetPlan(ctx, types.IDFromStatusPlanForProviderKey(iter.Key()))
items = append(items, item)
})
return items
}
<file_sep>package rest
import (
"context"
"net/http"
"strconv"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/types/rest"
"github.com/gorilla/mux"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/plan/types"
)
func queryPlan(ctx client.Context) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.ParseUint(vars["id"], 10, 64)
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
var (
qc = types.NewQueryServiceClient(ctx)
)
res, err := qc.QueryPlan(context.Background(),
types.NewQueryPlanRequest(id))
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, ctx, res)
}
}
func queryPlans(ctx client.Context) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var (
query = r.URL.Query()
status = hubtypes.StatusFromString(query.Get("status"))
qc = types.NewQueryServiceClient(ctx)
)
if query.Get("provider") != "" {
address, err := hubtypes.ProvAddressFromBech32(query.Get("provider"))
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
res, err := qc.QueryPlansForProvider(context.Background(), types.NewQueryPlansForProviderRequest(address, status, nil))
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, ctx, res)
return
}
res, err := qc.QueryPlans(context.Background(), types.NewQueryPlansRequest(status, nil))
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, ctx, res)
}
}
<file_sep>package types
import (
"errors"
"strings"
"testing"
sdk "github.com/cosmos/cosmos-sdk/types"
)
var (
GT64 = strings.Repeat("sentinel", 9)
GT256 = strings.Repeat("sentinel", 33)
)
func TestMsgRegister_ValidateBasic(t *testing.T) {
correctAddress, err := sdk.AccAddressFromBech32("sent1grdunxx5jxd0ja75wt508sn6v39p70hhw53zs8")
if err != nil {
t.Errorf("failed: %s\n", err)
}
tests := []struct {
name string
m *MsgRegisterRequest
want error
}{
{"from nil", NewMsgRegisterRequest(nil, "", "", "", ""), ErrorInvalidFieldFrom},
{"from zero", NewMsgRegisterRequest(sdk.AccAddress{}, "", "", "", ""), ErrorInvalidFieldFrom},
{"from empty", NewMsgRegisterRequest(sdk.AccAddress(""), "", "", "", ""), ErrorInvalidFieldFrom},
{"name zero", NewMsgRegisterRequest(correctAddress, "", "", "", ""), ErrorInvalidFieldName},
{"name GT64", NewMsgRegisterRequest(correctAddress, GT64, "", "", ""), ErrorInvalidFieldName},
{"identity GT64", NewMsgRegisterRequest(correctAddress, "test-name", GT64, "", ""), ErrorInvalidFieldIdentity},
{"website GT64", NewMsgRegisterRequest(correctAddress, "test-name", "test-identity", GT64, ""), ErrorInvalidFieldWebsite},
{"description GT256", NewMsgRegisterRequest(correctAddress, "test-name", "test-identity", "test-website", GT256), ErrorInvalidFieldDescription},
{"from correct", NewMsgRegisterRequest(correctAddress, "test-name", "", "", ""), nil},
{"name correct", NewMsgRegisterRequest(correctAddress, "test-name", "", "", ""), nil},
{"identity empty", NewMsgRegisterRequest(correctAddress, "test-name", "", "", ""), nil},
{"identity correct", NewMsgRegisterRequest(correctAddress, "test-name", "test-identity", "", ""), nil},
{"website empty", NewMsgRegisterRequest(correctAddress, "test-name", "test-identity", "", ""), nil},
{"website correct", NewMsgRegisterRequest(correctAddress, "test-name", "test-identity", "test-website", ""), nil},
{"description empty", NewMsgRegisterRequest(correctAddress, "test-name", "test-identity", "", ""), nil},
{"description correct", NewMsgRegisterRequest(correctAddress, "test-name", "test-identity", "", "test-description"), nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := tt.m.ValidateBasic(); !errors.Is(tt.want, err) {
t.Errorf("ValidateBasic() = %v, want %v", err, tt.want)
}
})
}
}
func TestMsgUpdate_ValidateBasic(t *testing.T) {
correctAddress, err := sdk.AccAddressFromBech32("sent1grdunxx5jxd0ja75wt508sn6v39p70hhw53zs8")
if err != nil {
t.Errorf("failed: %s\n", err)
}
tests := []struct {
name string
m *MsgRegisterRequest
want error
}{
{"from nil", NewMsgRegisterRequest(nil, "", "", "", ""), ErrorInvalidFieldFrom},
{"from zero", NewMsgRegisterRequest(sdk.AccAddress{}, "", "", "", ""), ErrorInvalidFieldFrom},
{"from empty", NewMsgRegisterRequest(sdk.AccAddress(""), "", "", "", ""), ErrorInvalidFieldFrom},
{"name zero", NewMsgRegisterRequest(correctAddress, "", "", "", ""), ErrorInvalidFieldName},
{"name GT64", NewMsgRegisterRequest(correctAddress, GT64, "", "", ""), ErrorInvalidFieldName},
{"identity GT64", NewMsgRegisterRequest(correctAddress, "test-name", GT64, "", ""), ErrorInvalidFieldIdentity},
{"website GT64", NewMsgRegisterRequest(correctAddress, "test-name", "test-identity", GT64, ""), ErrorInvalidFieldWebsite},
{"description GT256", NewMsgRegisterRequest(correctAddress, "test-name", "test-identity", "test-website", GT256), ErrorInvalidFieldDescription},
{"from correct", NewMsgRegisterRequest(correctAddress, "test-name", "", "", ""), nil},
{"name correct", NewMsgRegisterRequest(correctAddress, "test-name", "", "", ""), nil},
{"identity empty", NewMsgRegisterRequest(correctAddress, "test-name", "", "", ""), nil},
{"identity correct", NewMsgRegisterRequest(correctAddress, "test-name", "test-identity", "", ""), nil},
{"website empty", NewMsgRegisterRequest(correctAddress, "test-name", "test-identity", "", ""), nil},
{"website correct", NewMsgRegisterRequest(correctAddress, "test-name", "test-identity", "test-website", ""), nil},
{"description empty", NewMsgRegisterRequest(correctAddress, "test-name", "test-identity", "", ""), nil},
{"description correct", NewMsgRegisterRequest(correctAddress, "test-name", "test-identity", "", "test-description"), nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := tt.m.ValidateBasic(); !errors.Is(tt.want, err) {
t.Errorf("ValidateBasic() = %v, want %v", err, tt.want)
}
})
}
}
<file_sep>package provider
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/sentinel-official/hub/x/provider/keeper"
"github.com/sentinel-official/hub/x/provider/types"
)
func InitGenesis(ctx sdk.Context, k keeper.Keeper, state *types.GenesisState) {
k.SetParams(ctx, state.Params)
for _, provider := range state.Providers {
k.SetProvider(ctx, provider)
}
}
func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState {
return types.NewGenesisState(k.GetProviders(ctx, 0, 0), k.GetParams(ctx))
}
<file_sep>package v06
import (
"github.com/sentinel-official/hub/x/session/types"
legacy "github.com/sentinel-official/hub/x/session/types/legacy/v0.5"
)
func MigrateParams(params legacy.Params) types.Params {
return types.NewParams(
params.InactiveDuration,
params.ProofVerificationEnabled,
)
}
<file_sep>package v05
import (
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
legacyhubtypes "github.com/sentinel-official/hub/types/legacy/v0.5"
)
type (
Node struct {
Address hubtypes.NodeAddress `json:"address"`
Provider hubtypes.ProvAddress `json:"provider"`
Price sdk.Coins `json:"price"`
RemoteURL string `json:"remote_url"`
Status legacyhubtypes.Status `json:"status"`
StatusAt time.Time `json:"status_at"`
}
Nodes []Node
)
<file_sep>package keeper
import (
"context"
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/subscription/types"
)
var (
_ types.MsgServiceServer = (*msgServer)(nil)
)
type msgServer struct {
Keeper
}
func NewMsgServiceServer(keeper Keeper) types.MsgServiceServer {
return &msgServer{Keeper: keeper}
}
func (k *msgServer) MsgSubscribeToNode(c context.Context, msg *types.MsgSubscribeToNodeRequest) (*types.MsgSubscribeToNodeResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
msgAddress, err := hubtypes.NodeAddressFromBech32(msg.Address)
if err != nil {
return nil, err
}
node, found := k.GetNode(ctx, msgAddress)
if !found {
return nil, types.ErrorNodeDoesNotExist
}
if node.Provider != "" {
return nil, types.ErrorCanNotSubscribe
}
if !node.Status.Equal(hubtypes.StatusActive) {
return nil, types.ErrorInvalidNodeStatus
}
price, found := node.PriceForDenom(msg.Deposit.Denom)
if !found {
return nil, types.ErrorPriceDoesNotExist
}
msgFrom, err := sdk.AccAddressFromBech32(msg.From)
if err != nil {
return nil, err
}
if err := k.AddDeposit(ctx, msgFrom, msg.Deposit); err != nil {
return nil, err
}
var (
count = k.GetCount(ctx)
subscription = types.Subscription{
Id: count + 1,
Owner: msg.From,
Node: node.Address,
Price: price,
Deposit: msg.Deposit,
Free: sdk.ZeroInt(),
Status: hubtypes.StatusActive,
StatusAt: ctx.BlockTime(),
}
subscriptionNode = subscription.GetNode()
)
k.SetSubscription(ctx, subscription)
k.SetSubscriptionForNode(ctx, subscriptionNode, subscription.Id)
ctx.EventManager().EmitTypedEvent(
&types.EventSubscribeToNode{
Id: subscription.Id,
From: sdk.AccAddress(msgFrom.Bytes()).String(),
Owner: subscription.Owner,
Node: subscription.Node,
Price: subscription.Price,
Deposit: subscription.Deposit,
Free: subscription.Free,
},
)
var (
bandwidth, _ = node.BytesForCoin(msg.Deposit)
quota = types.Quota{
Address: msg.From,
Consumed: sdk.ZeroInt(),
Allocated: bandwidth,
}
quotaAddress = quota.GetAddress()
)
k.SetQuota(ctx, subscription.Id, quota)
k.SetActiveSubscriptionForAddress(ctx, quotaAddress, subscription.Id)
ctx.EventManager().EmitTypedEvent(
&types.EventAddQuota{
From: subscription.Owner,
Id: subscription.Id,
Address: quota.Address,
Consumed: quota.Consumed,
Allocated: quota.Allocated,
},
)
k.SetCount(ctx, count+1)
ctx.EventManager().EmitTypedEvent(
&types.EventSetSubscriptionCount{
Count: count + 1,
},
)
ctx.EventManager().EmitTypedEvent(&types.EventModuleName)
return &types.MsgSubscribeToNodeResponse{}, nil
}
func (k *msgServer) MsgSubscribeToPlan(c context.Context, msg *types.MsgSubscribeToPlanRequest) (*types.MsgSubscribeToPlanResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
plan, found := k.GetPlan(ctx, msg.Id)
if !found {
return nil, types.ErrorPlanDoesNotExist
}
if !plan.Status.Equal(hubtypes.StatusActive) {
return nil, types.ErrorInvalidPlanStatus
}
msgFrom, err := sdk.AccAddressFromBech32(msg.From)
if err != nil {
return nil, err
}
if plan.Price != nil {
price, found := plan.PriceForDenom(msg.Denom)
if !found {
return nil, types.ErrorPriceDoesNotExist
}
planProvider := plan.GetProvider()
if err := k.SendCoin(ctx, msgFrom, planProvider.Bytes(), price); err != nil {
return nil, err
}
}
var (
count = k.GetCount(ctx)
subscription = types.Subscription{
Id: count + 1,
Owner: msg.From,
Plan: plan.Id,
Denom: msg.Denom,
Expiry: ctx.BlockTime().Add(plan.Validity),
Free: sdk.ZeroInt(),
Status: hubtypes.StatusActive,
StatusAt: ctx.BlockTime(),
}
)
k.SetSubscription(ctx, subscription)
k.SetSubscriptionForPlan(ctx, subscription.Plan, subscription.Id)
k.SetInactiveSubscriptionAt(ctx, subscription.Expiry, subscription.Id)
ctx.EventManager().EmitTypedEvent(
&types.EventSubscribeToPlan{
Id: subscription.Id,
From: sdk.AccAddress(msgFrom.Bytes()).String(),
Owner: subscription.Owner,
Plan: subscription.Plan,
Denom: subscription.Denom,
Expiry: subscription.Expiry,
Free: subscription.Free,
},
)
var (
quota = types.Quota{
Address: msg.From,
Consumed: sdk.ZeroInt(),
Allocated: plan.Bytes,
}
quotaAddress = quota.GetAddress()
)
k.SetQuota(ctx, subscription.Id, quota)
k.SetActiveSubscriptionForAddress(ctx, quotaAddress, subscription.Id)
ctx.EventManager().EmitTypedEvent(
&types.EventAddQuota{
From: subscription.Owner,
Id: subscription.Id,
Address: quota.Address,
Consumed: quota.Consumed,
Allocated: quota.Allocated,
},
)
k.SetCount(ctx, count+1)
ctx.EventManager().EmitTypedEvent(
&types.EventSetSubscriptionCount{
Count: count + 1,
},
)
ctx.EventManager().EmitTypedEvent(&types.EventModuleName)
return &types.MsgSubscribeToPlanResponse{}, nil
}
func (k *msgServer) MsgCancel(c context.Context, msg *types.MsgCancelRequest) (*types.MsgCancelResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
msgFrom, err := sdk.AccAddressFromBech32(msg.From)
if err != nil {
return nil, err
}
subscription, found := k.GetSubscription(ctx, msg.Id)
if !found {
return nil, types.ErrorSubscriptionDoesNotExist
}
if msg.From != subscription.Owner {
return nil, types.ErrorUnauthorized
}
if !subscription.Status.Equal(hubtypes.StatusActive) {
return nil, types.ErrorInvalidSubscriptionStatus
}
inactiveDuration := k.InactiveDuration(ctx)
if subscription.Plan > 0 {
k.DeleteInactiveSubscriptionAt(ctx, subscription.Expiry, subscription.Id)
}
subscription.Status = hubtypes.StatusInactivePending
subscription.StatusAt = ctx.BlockTime()
k.SetInactiveSubscriptionAt(ctx, ctx.BlockTime().Add(inactiveDuration), subscription.Id)
k.SetSubscription(ctx, subscription)
ctx.EventManager().EmitTypedEvent(
&types.EventCancelSubscription{
From: sdk.AccAddress(msgFrom.Bytes()).String(),
Id: subscription.Id,
},
)
ctx.EventManager().EmitTypedEvent(&types.EventModuleName)
return &types.MsgCancelResponse{}, nil
}
func (k *msgServer) MsgAddQuota(c context.Context, msg *types.MsgAddQuotaRequest) (*types.MsgAddQuotaResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
msgAddress, err := sdk.AccAddressFromBech32(msg.Address)
if err != nil {
return nil, err
}
subscription, found := k.GetSubscription(ctx, msg.Id)
if !found {
return nil, types.ErrorSubscriptionDoesNotExist
}
if subscription.Plan == 0 {
return nil, types.ErrorCanNotAddQuota
}
if msg.From != subscription.Owner {
return nil, types.ErrorUnauthorized
}
if !subscription.Status.Equal(hubtypes.StatusActive) {
return nil, types.ErrorInvalidSubscriptionStatus
}
if k.HasQuota(ctx, subscription.Id, msgAddress) {
return nil, types.ErrorDuplicateQuota
}
if msg.Bytes.GT(subscription.Free) {
return nil, types.ErrorInvalidQuota
}
subscription.Free = subscription.Free.Sub(msg.Bytes)
k.SetSubscription(ctx, subscription)
var (
quota = types.Quota{
Address: msg.Address,
Consumed: sdk.ZeroInt(),
Allocated: msg.Bytes,
}
quotaAddress = quota.GetAddress()
)
k.SetQuota(ctx, subscription.Id, quota)
k.SetActiveSubscriptionForAddress(ctx, quotaAddress, subscription.Id)
ctx.EventManager().EmitTypedEvent(
&types.EventAddQuota{
From: subscription.Owner,
Id: subscription.Id,
Address: quota.Address,
Consumed: quota.Consumed,
Allocated: quota.Allocated,
},
)
ctx.EventManager().EmitTypedEvent(&types.EventModuleName)
return &types.MsgAddQuotaResponse{}, nil
}
func (k *msgServer) MsgUpdateQuota(c context.Context, msg *types.MsgUpdateQuotaRequest) (*types.MsgUpdateQuotaResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
subscription, found := k.GetSubscription(ctx, msg.Id)
if !found {
return nil, types.ErrorSubscriptionDoesNotExist
}
if msg.From != subscription.Owner {
return nil, types.ErrorUnauthorized
}
if !subscription.Status.Equal(hubtypes.StatusActive) {
return nil, types.ErrorInvalidSubscriptionStatus
}
msgAddress, err := sdk.AccAddressFromBech32(msg.Address)
if err != nil {
return nil, err
}
quota, found := k.GetQuota(ctx, subscription.Id, msgAddress)
if !found {
return nil, types.ErrorQuotaDoesNotExist
}
subscription.Free = subscription.Free.Add(quota.Allocated)
if msg.Bytes.LT(quota.Consumed) || msg.Bytes.GT(subscription.Free) {
return nil, types.ErrorInvalidQuota
}
subscription.Free = subscription.Free.Sub(msg.Bytes)
k.SetSubscription(ctx, subscription)
quota.Allocated = msg.Bytes
k.SetQuota(ctx, subscription.Id, quota)
ctx.EventManager().EmitTypedEvent(
&types.EventUpdateQuota{
From: subscription.Owner,
Id: subscription.Id,
Address: quota.Address,
Consumed: quota.Consumed,
Allocated: quota.Allocated,
},
)
ctx.EventManager().EmitTypedEvent(&types.EventModuleName)
return &types.MsgUpdateQuotaResponse{}, nil
}
<file_sep>package types
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
)
func (s *Session) GetAddress() sdk.AccAddress {
if s.Address == "" {
return nil
}
address, err := sdk.AccAddressFromBech32(s.Address)
if err != nil {
panic(err)
}
return address
}
func (s *Session) GetNode() hubtypes.NodeAddress {
if s.Node == "" {
return nil
}
address, err := hubtypes.NodeAddressFromBech32(s.Node)
if err != nil {
panic(err)
}
return address
}
func (s *Session) Validate() error {
if s.Id == 0 {
return fmt.Errorf("id should not be zero")
}
if s.Subscription == 0 {
return fmt.Errorf("subscription should not be zero")
}
if _, err := hubtypes.NodeAddressFromBech32(s.Node); err != nil {
return fmt.Errorf("node should not be nil or empty")
}
if _, err := sdk.AccAddressFromBech32(s.Address); err != nil {
return fmt.Errorf("address should not be nil or empty")
}
if s.Duration <= 0 {
return fmt.Errorf("duration should be positive")
}
if s.Bandwidth.IsAllPositive() {
return fmt.Errorf("bandwidth should be valid")
}
if !s.Status.Equal(hubtypes.StatusActive) && !s.Status.Equal(hubtypes.StatusInactive) {
return fmt.Errorf("status should be either active or inactive")
}
if s.StatusAt.IsZero() {
return fmt.Errorf("status_at should not be zero")
}
return nil
}
type (
Sessions []Session
)
<file_sep>package rest
import (
"context"
"net/http"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/types/rest"
"github.com/gorilla/mux"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/provider/types"
)
func queryProvider(ctx client.Context) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
address, err := hubtypes.ProvAddressFromBech32(vars["address"])
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
var (
qc = types.NewQueryServiceClient(ctx)
)
res, err := qc.QueryProvider(context.Background(),
types.NewQueryProviderRequest(address))
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, ctx, res)
}
}
func queryProviders(ctx client.Context) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var (
qc = types.NewQueryServiceClient(ctx)
)
providers, err := qc.QueryProviders(context.Background(),
types.NewQueryProvidersRequest(nil))
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, ctx, providers)
}
}
<file_sep>package keeper
import (
"context"
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/node/types"
)
var (
_ types.MsgServiceServer = (*msgServer)(nil)
)
type msgServer struct {
Keeper
}
func NewMsgServiceServer(keeper Keeper) types.MsgServiceServer {
return &msgServer{Keeper: keeper}
}
func (k *msgServer) MsgRegister(c context.Context, msg *types.MsgRegisterRequest) (*types.MsgRegisterResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
msgFrom, err := sdk.AccAddressFromBech32(msg.From)
if err != nil {
return nil, err
}
if k.HasNode(ctx, msgFrom.Bytes()) {
return nil, types.ErrorDuplicateNode
}
if msg.Provider != "" {
msgProvider, err := hubtypes.ProvAddressFromBech32(msg.Provider)
if err != nil {
return nil, err
}
if !k.HasProvider(ctx, msgProvider) {
return nil, types.ErrorProviderDoesNotExist
}
}
deposit := k.Deposit(ctx)
if deposit.IsPositive() {
if err := k.FundCommunityPool(ctx, msgFrom, deposit); err != nil {
return nil, err
}
}
var (
nodeAddress = hubtypes.NodeAddress(msgFrom.Bytes())
node = types.Node{
Address: nodeAddress.String(),
Provider: msg.Provider,
Price: msg.Price,
RemoteURL: msg.RemoteURL,
Status: hubtypes.StatusInactive,
StatusAt: ctx.BlockTime(),
}
nodeProvider = node.GetProvider()
)
k.SetNode(ctx, node)
k.SetInactiveNode(ctx, nodeAddress)
if nodeProvider != nil {
k.SetInactiveNodeForProvider(ctx, nodeProvider, nodeAddress)
}
ctx.EventManager().EmitTypedEvent(
&types.EventRegisterNode{
From: sdk.AccAddress(msgFrom.Bytes()).String(),
Address: node.Address,
Provider: node.Provider,
Price: node.Price,
RemoteURL: node.RemoteURL,
},
)
ctx.EventManager().EmitTypedEvent(&types.EventModuleName)
return &types.MsgRegisterResponse{}, nil
}
func (k *msgServer) MsgUpdate(c context.Context, msg *types.MsgUpdateRequest) (*types.MsgUpdateResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
msgFrom, err := hubtypes.NodeAddressFromBech32(msg.From)
if err != nil {
return nil, err
}
node, found := k.GetNode(ctx, msgFrom)
if !found {
return nil, types.ErrorNodeDoesNotExist
}
if node.Provider == msg.Provider {
msg.Provider = ""
}
if node.Provider != "" && (msg.Provider != "" || msg.Price != nil) {
var (
nodeAddress = node.GetAddress()
nodeProvider = node.GetProvider()
)
if k.GetCountForNodeByProvider(ctx, nodeProvider, nodeAddress) > 0 {
return nil, types.ErrorInvalidPlanCount
}
if node.Status.Equal(hubtypes.StatusActive) {
k.DeleteActiveNodeForProvider(ctx, nodeProvider, nodeAddress)
} else {
k.DeleteInactiveNodeForProvider(ctx, nodeProvider, nodeAddress)
}
}
if msg.Provider != "" {
msgProvider, err := hubtypes.ProvAddressFromBech32(msg.Provider)
if err != nil {
return nil, err
}
if !k.HasProvider(ctx, msgProvider) {
return nil, types.ErrorProviderDoesNotExist
}
node.Price = nil
node.Provider = msg.Provider
var (
nodeAddress = node.GetAddress()
nodeProvider = node.GetProvider()
)
if node.Status.Equal(hubtypes.StatusActive) {
k.SetActiveNodeForProvider(ctx, nodeProvider, nodeAddress)
} else {
k.SetInactiveNodeForProvider(ctx, nodeProvider, nodeAddress)
}
}
if msg.Price != nil {
node.Provider = ""
node.Price = msg.Price
}
if msg.RemoteURL != "" {
node.RemoteURL = msg.RemoteURL
}
k.SetNode(ctx, node)
ctx.EventManager().EmitTypedEvent(
&types.EventUpdateNode{
From: sdk.AccAddress(msgFrom.Bytes()).String(),
Address: node.Address,
Provider: msg.Provider,
Price: msg.Price,
RemoteURL: msg.RemoteURL,
},
)
ctx.EventManager().EmitTypedEvent(&types.EventModuleName)
return &types.MsgUpdateResponse{}, nil
}
func (k *msgServer) MsgSetStatus(c context.Context, msg *types.MsgSetStatusRequest) (*types.MsgSetStatusResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
msgFrom, err := hubtypes.NodeAddressFromBech32(msg.From)
if err != nil {
return nil, err
}
node, found := k.GetNode(ctx, msgFrom)
if !found {
return nil, types.ErrorNodeDoesNotExist
}
var (
nodeAddress = node.GetAddress()
nodeProvider = node.GetProvider()
inactiveDuration = k.InactiveDuration(ctx)
)
if node.Status.Equal(hubtypes.StatusActive) {
if msg.Status.Equal(hubtypes.StatusInactive) {
k.DeleteActiveNode(ctx, nodeAddress)
k.SetInactiveNode(ctx, nodeAddress)
if node.Provider != "" {
k.DeleteActiveNodeForProvider(ctx, nodeProvider, nodeAddress)
k.SetInactiveNodeForProvider(ctx, nodeProvider, nodeAddress)
}
}
k.DeleteInactiveNodeAt(ctx, node.StatusAt.Add(inactiveDuration), nodeAddress)
} else {
if msg.Status.Equal(hubtypes.StatusActive) {
k.DeleteInactiveNode(ctx, nodeAddress)
k.SetActiveNode(ctx, nodeAddress)
if node.Provider != "" {
k.DeleteInactiveNodeForProvider(ctx, nodeProvider, nodeAddress)
k.SetActiveNodeForProvider(ctx, nodeProvider, nodeAddress)
}
}
}
node.Status = msg.Status
node.StatusAt = ctx.BlockTime()
if node.Status.Equal(hubtypes.StatusActive) {
k.SetInactiveNodeAt(ctx, node.StatusAt.Add(inactiveDuration), nodeAddress)
}
k.SetNode(ctx, node)
ctx.EventManager().EmitTypedEvent(
&types.EventSetNodeStatus{
From: sdk.AccAddress(msgFrom.Bytes()).String(),
Address: node.Address,
Status: node.Status,
},
)
ctx.EventManager().EmitTypedEvent(&types.EventModuleName)
return &types.MsgSetStatusResponse{}, nil
}
<file_sep>package subscription
import (
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/subscription/keeper"
"github.com/sentinel-official/hub/x/subscription/types"
)
func InitGenesis(ctx sdk.Context, k keeper.Keeper, state *types.GenesisState) {
k.SetParams(ctx, state.Params)
for _, item := range state.Subscriptions {
k.SetSubscription(ctx, item.Subscription)
if item.Subscription.Id == 0 {
k.SetSubscriptionForNode(ctx, item.Subscription.GetNode(), item.Subscription.Id)
} else {
k.SetSubscriptionForPlan(ctx, item.Subscription.Plan, item.Subscription.Id)
}
for _, quota := range item.Quotas {
k.SetQuota(ctx, item.Subscription.Id, quota)
if item.Subscription.Status.Equal(hubtypes.StatusInactive) {
k.SetInactiveSubscriptionForAddress(ctx, quota.GetAddress(), item.Subscription.Id)
} else {
k.SetActiveSubscriptionForAddress(ctx, quota.GetAddress(), item.Subscription.Id)
}
}
if item.Subscription.Status.Equal(hubtypes.StatusInactivePending) {
k.SetInactiveSubscriptionAt(ctx, item.Subscription.StatusAt.Add(k.InactiveDuration(ctx)), item.Subscription.Id)
}
}
k.SetCount(ctx, uint64(len(state.Subscriptions)))
}
func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState {
subscriptions := k.GetSubscriptions(ctx, 0, 0)
items := make(types.GenesisSubscriptions, 0, len(subscriptions))
for _, item := range subscriptions {
items = append(items, types.GenesisSubscription{
Subscription: item,
Quotas: k.GetQuotas(ctx, item.Id, 0, 0),
})
}
return types.NewGenesisState(items, k.GetParams(ctx))
}
<file_sep>package types
import (
"fmt"
)
type (
GenesisPlans []GenesisPlan
GenesisState GenesisPlans
)
func NewGenesisState(plans GenesisPlans) GenesisState {
return GenesisState(plans)
}
func DefaultGenesisState() GenesisState {
return NewGenesisState(nil)
}
func ValidateGenesis(state GenesisState) error {
for _, item := range state {
if err := item.Plan.Validate(); err != nil {
return err
}
}
plans := make(map[uint64]bool)
for _, item := range state {
id := item.Plan.Id
if plans[id] {
return fmt.Errorf("duplicate plan id %d", id)
}
plans[id] = true
}
for _, item := range state {
nodes := make(map[string]bool)
for _, address := range item.Nodes {
if nodes[address] {
return fmt.Errorf("duplicate node for plan %d", item.Plan.Id)
}
nodes[address] = true
}
}
return nil
}
<file_sep>package v06
import (
deposit "github.com/sentinel-official/hub/x/deposit/types/legacy/v0.6"
node "github.com/sentinel-official/hub/x/node/types/legacy/v0.6"
plan "github.com/sentinel-official/hub/x/plan/types/legacy/v0.6"
provider "github.com/sentinel-official/hub/x/provider/types/legacy/v0.6"
session "github.com/sentinel-official/hub/x/session/types/legacy/v0.6"
subscription "github.com/sentinel-official/hub/x/subscription/types/legacy/v0.6"
"github.com/sentinel-official/hub/x/vpn/types"
legacy "github.com/sentinel-official/hub/x/vpn/types/legacy/v0.5"
)
func MigrateGenesisState(state *legacy.GenesisState) *types.GenesisState {
return types.NewGenesisState(
deposit.MigrateGenesisState(state.Deposits),
provider.MigrateGenesisState(state.Providers),
node.MigrateGenesisState(state.Nodes),
plan.MigrateGenesisState(state.Plans),
subscription.MigrateGenesisState(state.Subscriptions),
session.MigrateGenesisState(state.Sessions),
)
}
<file_sep>package v05
const (
ModuleName = "vpn"
)
<file_sep>package keeper
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/sentinel-official/hub/x/provider/types"
)
func (k *Keeper) Deposit(ctx sdk.Context) (deposit sdk.Coin) {
k.params.Get(ctx, types.KeyDeposit, &deposit)
return
}
func (k *Keeper) SetParams(ctx sdk.Context, params types.Params) {
k.params.SetParamSet(ctx, ¶ms)
}
func (k *Keeper) GetParams(ctx sdk.Context) types.Params {
return types.NewParams(
k.Deposit(ctx),
)
}
<file_sep>package vpn
import (
sdk "github.com/cosmos/cosmos-sdk/types"
abcitypes "github.com/tendermint/tendermint/abci/types"
"github.com/sentinel-official/hub/x/node"
"github.com/sentinel-official/hub/x/session"
"github.com/sentinel-official/hub/x/subscription"
"github.com/sentinel-official/hub/x/vpn/keeper"
)
func EndBlock(ctx sdk.Context, k keeper.Keeper) abcitypes.ValidatorUpdates {
ctx, write := ctx.CacheContext()
defer write()
node.EndBlock(ctx, k.Node)
session.EndBlock(ctx, k.Session)
subscription.EndBlock(ctx, k.Subscription)
return nil
}
<file_sep>package v05
type (
GenesisState Deposits
)
<file_sep>package hub
import (
"encoding/json"
"io"
"os"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/grpc/tmservice"
"github.com/cosmos/cosmos-sdk/client/rpc"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/server/api"
serverconfig "github.com/cosmos/cosmos-sdk/server/config"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/version"
"github.com/cosmos/cosmos-sdk/x/auth"
"github.com/cosmos/cosmos-sdk/x/auth/ante"
authrest "github.com/cosmos/cosmos-sdk/x/auth/client/rest"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
authsimulation "github.com/cosmos/cosmos-sdk/x/auth/simulation"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
authvesting "github.com/cosmos/cosmos-sdk/x/auth/vesting"
"github.com/cosmos/cosmos-sdk/x/bank"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/cosmos/cosmos-sdk/x/capability"
capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper"
capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types"
"github.com/cosmos/cosmos-sdk/x/crisis"
crisiskeeper "github.com/cosmos/cosmos-sdk/x/crisis/keeper"
crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types"
"github.com/cosmos/cosmos-sdk/x/distribution"
distributionclient "github.com/cosmos/cosmos-sdk/x/distribution/client"
distributionkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper"
distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
"github.com/cosmos/cosmos-sdk/x/evidence"
evidencekeeper "github.com/cosmos/cosmos-sdk/x/evidence/keeper"
evidencetypes "github.com/cosmos/cosmos-sdk/x/evidence/types"
"github.com/cosmos/cosmos-sdk/x/genutil"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
"github.com/cosmos/cosmos-sdk/x/gov"
govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
ibctransfer "github.com/cosmos/cosmos-sdk/x/ibc/applications/transfer"
ibctransferkeeper "github.com/cosmos/cosmos-sdk/x/ibc/applications/transfer/keeper"
ibctransfertypes "github.com/cosmos/cosmos-sdk/x/ibc/applications/transfer/types"
ibc "github.com/cosmos/cosmos-sdk/x/ibc/core"
ibcclient "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client"
ibcporttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/05-port/types"
ibchost "github.com/cosmos/cosmos-sdk/x/ibc/core/24-host"
ibckeeper "github.com/cosmos/cosmos-sdk/x/ibc/core/keeper"
"github.com/cosmos/cosmos-sdk/x/mint"
mintkeeper "github.com/cosmos/cosmos-sdk/x/mint/keeper"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
"github.com/cosmos/cosmos-sdk/x/params"
paramsclient "github.com/cosmos/cosmos-sdk/x/params/client"
paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper"
paramstypes "github.com/cosmos/cosmos-sdk/x/params/types"
paramsproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal"
"github.com/cosmos/cosmos-sdk/x/slashing"
slashingkeeper "github.com/cosmos/cosmos-sdk/x/slashing/keeper"
slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
"github.com/cosmos/cosmos-sdk/x/staking"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/cosmos/cosmos-sdk/x/upgrade"
upgradeclient "github.com/cosmos/cosmos-sdk/x/upgrade/client"
upgradekeeper "github.com/cosmos/cosmos-sdk/x/upgrade/keeper"
upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types"
abci "github.com/tendermint/tendermint/abci/types"
tmjson "github.com/tendermint/tendermint/libs/json"
"github.com/tendermint/tendermint/libs/log"
tmos "github.com/tendermint/tendermint/libs/os"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
tmdb "github.com/tendermint/tm-db"
hubparams "github.com/sentinel-official/hub/params"
deposittypes "github.com/sentinel-official/hub/x/deposit/types"
"github.com/sentinel-official/hub/x/swap"
swapkeeper "github.com/sentinel-official/hub/x/swap/keeper"
swaptypes "github.com/sentinel-official/hub/x/swap/types"
"github.com/sentinel-official/hub/x/vpn"
vpnkeeper "github.com/sentinel-official/hub/x/vpn/keeper"
vpntypes "github.com/sentinel-official/hub/x/vpn/types"
)
const (
appName = "Sentinel Hub"
)
var (
DefaultNodeHome = os.ExpandEnv("${HOME}/.sentinelhub")
ModuleBasics = module.NewBasicManager(
auth.AppModuleBasic{},
authvesting.AppModuleBasic{},
bank.AppModuleBasic{},
capability.AppModule{},
crisis.AppModuleBasic{},
distribution.AppModuleBasic{},
evidence.AppModuleBasic{},
genutil.AppModuleBasic{},
gov.NewAppModuleBasic(
distributionclient.ProposalHandler,
paramsclient.ProposalHandler,
upgradeclient.ProposalHandler,
upgradeclient.CancelProposalHandler,
),
ibc.AppModuleBasic{},
mint.AppModuleBasic{},
params.AppModuleBasic{},
slashing.AppModuleBasic{},
staking.AppModuleBasic{},
ibctransfer.AppModuleBasic{},
upgrade.AppModuleBasic{},
swap.AppModuleBasic{},
vpn.AppModuleBasic{},
)
)
var (
_ simapp.App = (*App)(nil)
_ servertypes.Application = (*App)(nil)
)
type App struct {
*baseapp.BaseApp
invarCheckPeriod uint
amino *codec.LegacyAmino
cdc codec.Marshaler
interfaceRegistry codectypes.InterfaceRegistry
manager *module.Manager
simulationManager *module.SimulationManager
keys map[string]*sdk.KVStoreKey
tkeys map[string]*sdk.TransientStoreKey
mkeys map[string]*sdk.MemoryStoreKey
accountKeeper authkeeper.AccountKeeper
bankKeeper bankkeeper.Keeper
capabilityKeeper *capabilitykeeper.Keeper
crisisKeeper crisiskeeper.Keeper
distributionKeeper distributionkeeper.Keeper
evidenceKeeper evidencekeeper.Keeper
govKeeper govkeeper.Keeper
ibcKeeper *ibckeeper.Keeper
ibcTransferKeeper ibctransferkeeper.Keeper
mintKeeper mintkeeper.Keeper
paramsKeeper paramskeeper.Keeper
slashingKeeper slashingkeeper.Keeper
stakingKeeper stakingkeeper.Keeper
upgradeKeeper upgradekeeper.Keeper
swapKeeper swapkeeper.Keeper
vpnKeeper vpnkeeper.Keeper
scopedIBCKeeper capabilitykeeper.ScopedKeeper
scopedIBCTransferKeeper capabilitykeeper.ScopedKeeper
}
func NewApp(
logger log.Logger,
db tmdb.DB,
tracer io.Writer,
loadLatest bool,
skipUpgradeHeights map[int64]bool,
homePath string,
invarCheckPeriod uint,
encodingConfig hubparams.EncodingConfig,
appOptions servertypes.AppOptions,
baseAppOptions ...func(*baseapp.BaseApp),
) *App {
var (
cdc = encodingConfig.Marshaler
amino = encodingConfig.Amino
interfaceRegistry = encodingConfig.InterfaceRegistry
tkeys = sdk.NewTransientStoreKeys(paramstypes.TStoreKey)
mkeys = sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey)
keys = sdk.NewKVStoreKeys(
authtypes.StoreKey, banktypes.StoreKey, capabilitytypes.StoreKey,
distributiontypes.StoreKey, evidencetypes.StoreKey, govtypes.StoreKey,
ibchost.StoreKey, ibctransfertypes.StoreKey, minttypes.StoreKey,
paramstypes.StoreKey, slashingtypes.StoreKey, stakingtypes.StoreKey,
upgradetypes.StoreKey, swaptypes.StoreKey, vpntypes.StoreKey,
)
)
baseApp := baseapp.NewBaseApp(appName, logger, db, encodingConfig.TxConfig.TxDecoder(), baseAppOptions...)
baseApp.SetCommitMultiStoreTracer(tracer)
baseApp.SetAppVersion(version.Version)
baseApp.SetInterfaceRegistry(interfaceRegistry)
app := &App{
BaseApp: baseApp,
amino: amino,
cdc: cdc,
keys: keys,
tkeys: tkeys,
mkeys: mkeys,
interfaceRegistry: interfaceRegistry,
invarCheckPeriod: invarCheckPeriod,
}
app.paramsKeeper = paramskeeper.NewKeeper(
app.cdc,
app.amino,
keys[paramstypes.StoreKey],
tkeys[paramstypes.TStoreKey],
)
app.paramsKeeper.Subspace(authtypes.ModuleName)
app.paramsKeeper.Subspace(banktypes.ModuleName)
app.paramsKeeper.Subspace(crisistypes.ModuleName)
app.paramsKeeper.Subspace(distributiontypes.ModuleName)
app.paramsKeeper.Subspace(evidencetypes.ModuleName)
app.paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(govtypes.ParamKeyTable())
app.paramsKeeper.Subspace(ibctransfertypes.ModuleName)
app.paramsKeeper.Subspace(ibchost.ModuleName)
app.paramsKeeper.Subspace(minttypes.ModuleName)
app.paramsKeeper.Subspace(slashingtypes.ModuleName)
app.paramsKeeper.Subspace(stakingtypes.ModuleName)
app.paramsKeeper.Subspace(swaptypes.ModuleName)
baseApp.SetParamStore(
app.paramsKeeper.
Subspace(baseapp.Paramspace).
WithKeyTable(paramskeeper.ConsensusParamsKeyTable()),
)
app.capabilityKeeper = capabilitykeeper.NewKeeper(
app.cdc,
app.keys[capabilitytypes.StoreKey],
app.mkeys[capabilitytypes.MemStoreKey],
)
var (
scopedIBCKeeper = app.capabilityKeeper.ScopeToModule(ibchost.ModuleName)
scopedTransferKeeper = app.capabilityKeeper.ScopeToModule(ibctransfertypes.ModuleName)
)
app.accountKeeper = authkeeper.NewAccountKeeper(
app.cdc,
app.keys[authtypes.StoreKey],
app.GetSubspace(authtypes.ModuleName),
authtypes.ProtoBaseAccount,
app.ModuleAccountsPermissions(),
)
app.bankKeeper = bankkeeper.NewBaseKeeper(
app.cdc,
app.keys[banktypes.StoreKey],
app.accountKeeper,
app.GetSubspace(banktypes.ModuleName),
app.ModuleAccountAddrs(),
)
stakingKeeper := stakingkeeper.NewKeeper(
app.cdc,
app.keys[stakingtypes.StoreKey],
app.accountKeeper,
app.bankKeeper,
app.GetSubspace(stakingtypes.ModuleName),
)
app.mintKeeper = mintkeeper.NewKeeper(
app.cdc,
app.keys[minttypes.StoreKey],
app.GetSubspace(minttypes.ModuleName),
&stakingKeeper,
app.accountKeeper,
app.bankKeeper,
authtypes.FeeCollectorName,
)
app.distributionKeeper = distributionkeeper.NewKeeper(
app.cdc,
app.keys[distributiontypes.StoreKey],
app.GetSubspace(distributiontypes.ModuleName),
app.accountKeeper,
app.bankKeeper,
&stakingKeeper,
authtypes.FeeCollectorName,
app.ModuleAccountAddrs(),
)
app.slashingKeeper = slashingkeeper.NewKeeper(
app.cdc,
app.keys[slashingtypes.StoreKey],
&stakingKeeper,
app.GetSubspace(slashingtypes.ModuleName),
)
app.crisisKeeper = crisiskeeper.NewKeeper(
app.GetSubspace(crisistypes.ModuleName),
app.invarCheckPeriod,
app.bankKeeper,
authtypes.FeeCollectorName,
)
app.upgradeKeeper = upgradekeeper.NewKeeper(
skipUpgradeHeights,
app.keys[upgradetypes.StoreKey],
app.cdc,
homePath,
)
app.stakingKeeper = *stakingKeeper.SetHooks(
stakingtypes.NewMultiStakingHooks(
app.distributionKeeper.Hooks(),
app.slashingKeeper.Hooks(),
),
)
app.ibcKeeper = ibckeeper.NewKeeper(
app.cdc,
app.keys[ibchost.StoreKey],
app.GetSubspace(ibchost.ModuleName),
app.stakingKeeper,
scopedIBCKeeper,
)
govRouter := govtypes.NewRouter()
govRouter.AddRoute(govtypes.RouterKey, govtypes.ProposalHandler).
AddRoute(paramsproposal.RouterKey, params.NewParamChangeProposalHandler(app.paramsKeeper)).
AddRoute(distributiontypes.RouterKey, distribution.NewCommunityPoolSpendProposalHandler(app.distributionKeeper)).
AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(app.upgradeKeeper)).
AddRoute(ibchost.RouterKey, ibcclient.NewClientUpdateProposalHandler(app.ibcKeeper.ClientKeeper))
app.govKeeper = govkeeper.NewKeeper(
app.cdc,
app.keys[govtypes.StoreKey],
app.GetSubspace(govtypes.ModuleName),
app.accountKeeper,
app.bankKeeper,
&stakingKeeper,
govRouter,
)
app.ibcTransferKeeper = ibctransferkeeper.NewKeeper(
app.cdc,
app.keys[ibctransfertypes.StoreKey],
app.GetSubspace(ibctransfertypes.ModuleName),
app.ibcKeeper.ChannelKeeper,
&app.ibcKeeper.PortKeeper,
app.accountKeeper,
app.bankKeeper,
scopedTransferKeeper,
)
var (
evidenceRouter = evidencetypes.NewRouter()
ibcRouter = ibcporttypes.NewRouter()
transferModule = ibctransfer.NewAppModule(app.ibcTransferKeeper)
)
ibcRouter.AddRoute(ibctransfertypes.ModuleName, transferModule)
app.ibcKeeper.SetRouter(ibcRouter)
app.evidenceKeeper = *evidencekeeper.NewKeeper(
app.cdc,
app.keys[evidencetypes.StoreKey],
&app.stakingKeeper,
app.slashingKeeper,
)
app.evidenceKeeper.SetRouter(evidenceRouter)
app.swapKeeper = swapkeeper.NewKeeper(
app.cdc,
app.keys[swaptypes.StoreKey],
app.GetSubspace(swaptypes.ModuleName),
app.accountKeeper,
app.bankKeeper,
)
app.vpnKeeper = vpnkeeper.NewKeeper(
app.cdc,
app.keys[vpntypes.StoreKey],
app.paramsKeeper,
app.accountKeeper,
app.bankKeeper,
app.distributionKeeper,
)
var (
skipGenesisInvariants = false
opt = appOptions.Get(crisis.FlagSkipGenesisInvariants)
)
if opt, ok := opt.(bool); ok {
skipGenesisInvariants = opt
}
app.manager = module.NewManager(
auth.NewAppModule(app.cdc, app.accountKeeper, nil),
authvesting.NewAppModule(app.accountKeeper, app.bankKeeper),
bank.NewAppModule(app.cdc, app.bankKeeper, app.accountKeeper),
capability.NewAppModule(app.cdc, *app.capabilityKeeper),
crisis.NewAppModule(&app.crisisKeeper, skipGenesisInvariants),
distribution.NewAppModule(app.cdc, app.distributionKeeper, app.accountKeeper, app.bankKeeper, app.stakingKeeper),
evidence.NewAppModule(app.evidenceKeeper),
genutil.NewAppModule(app.accountKeeper, app.stakingKeeper, app.BaseApp.DeliverTx, encodingConfig.TxConfig),
gov.NewAppModule(app.cdc, app.govKeeper, app.accountKeeper, app.bankKeeper),
ibc.NewAppModule(app.ibcKeeper),
params.NewAppModule(app.paramsKeeper),
mint.NewAppModule(app.cdc, app.mintKeeper, app.accountKeeper),
slashing.NewAppModule(app.cdc, app.slashingKeeper, app.accountKeeper, app.bankKeeper, app.stakingKeeper),
staking.NewAppModule(app.cdc, app.stakingKeeper, app.accountKeeper, app.bankKeeper),
upgrade.NewAppModule(app.upgradeKeeper),
transferModule,
swap.NewAppModule(app.cdc, app.swapKeeper),
vpn.NewAppModule(app.accountKeeper, app.vpnKeeper),
)
// NOTE: order is very important here
app.manager.SetOrderBeginBlockers(
upgradetypes.ModuleName, minttypes.ModuleName, distributiontypes.ModuleName,
slashingtypes.ModuleName, evidencetypes.ModuleName, stakingtypes.ModuleName,
ibchost.ModuleName,
)
app.manager.SetOrderEndBlockers(
crisistypes.ModuleName, govtypes.ModuleName, stakingtypes.ModuleName,
vpntypes.ModuleName,
)
app.manager.SetOrderInitGenesis(
capabilitytypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName,
distributiontypes.ModuleName, stakingtypes.ModuleName, slashingtypes.ModuleName,
govtypes.ModuleName, minttypes.ModuleName, crisistypes.ModuleName,
ibchost.ModuleName, genutiltypes.ModuleName, evidencetypes.ModuleName,
ibctransfertypes.ModuleName, swaptypes.ModuleName, vpntypes.ModuleName,
)
app.manager.RegisterInvariants(&app.crisisKeeper)
app.manager.RegisterRoutes(app.Router(), app.QueryRouter(), encodingConfig.Amino)
app.manager.RegisterServices(module.NewConfigurator(app.MsgServiceRouter(), app.GRPCQueryRouter()))
app.simulationManager = module.NewSimulationManager(
auth.NewAppModule(app.cdc, app.accountKeeper, authsimulation.RandomGenesisAccounts),
bank.NewAppModule(app.cdc, app.bankKeeper, app.accountKeeper),
capability.NewAppModule(app.cdc, *app.capabilityKeeper),
distribution.NewAppModule(app.cdc, app.distributionKeeper, app.accountKeeper, app.bankKeeper, app.stakingKeeper),
evidence.NewAppModule(app.evidenceKeeper),
gov.NewAppModule(app.cdc, app.govKeeper, app.accountKeeper, app.bankKeeper),
ibc.NewAppModule(app.ibcKeeper),
mint.NewAppModule(app.cdc, app.mintKeeper, app.accountKeeper),
params.NewAppModule(app.paramsKeeper),
slashing.NewAppModule(app.cdc, app.slashingKeeper, app.accountKeeper, app.bankKeeper, app.stakingKeeper),
staking.NewAppModule(app.cdc, app.stakingKeeper, app.accountKeeper, app.bankKeeper),
transferModule,
swap.NewAppModule(app.cdc, app.swapKeeper),
vpn.NewAppModule(app.accountKeeper, app.vpnKeeper),
)
app.simulationManager.RegisterStoreDecoders()
app.MountKVStores(app.keys)
app.MountTransientStores(app.tkeys)
app.MountMemoryStores(app.mkeys)
app.SetInitChainer(app.InitChainer)
app.SetBeginBlocker(app.BeginBlocker)
app.SetAnteHandler(
ante.NewAnteHandler(
app.accountKeeper,
app.bankKeeper,
ante.DefaultSigVerificationGasConsumer,
encodingConfig.TxConfig.SignModeHandler(),
),
)
app.SetEndBlocker(app.EndBlocker)
if loadLatest {
if err := app.LoadLatestVersion(); err != nil {
tmos.Exit(err.Error())
}
ctx := app.BaseApp.NewUncachedContext(true, tmproto.Header{})
app.capabilityKeeper.InitializeAndSeal(ctx)
}
app.scopedIBCKeeper = scopedIBCKeeper
app.scopedIBCTransferKeeper = scopedTransferKeeper
return app
}
func (a *App) Name() string { return a.BaseApp.Name() }
func (a *App) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock {
return a.manager.BeginBlock(ctx, req)
}
func (a *App) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock {
return a.manager.EndBlock(ctx, req)
}
func (a *App) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain {
var state map[string]json.RawMessage
if err := tmjson.Unmarshal(req.AppStateBytes, &state); err != nil {
panic(err)
}
return a.manager.InitGenesis(ctx, a.cdc, state)
}
func (a *App) LegacyAmino() *codec.LegacyAmino {
return a.amino
}
func (a *App) AppCodec() codec.Marshaler {
return a.cdc
}
func (a *App) InterfaceRegistry() codectypes.InterfaceRegistry {
return a.interfaceRegistry
}
func (a *App) RegisterTxService(ctx client.Context) {
authtx.RegisterTxService(a.BaseApp.GRPCQueryRouter(), ctx, a.BaseApp.Simulate, a.interfaceRegistry)
}
func (a *App) RegisterTendermintService(ctx client.Context) {
tmservice.RegisterTendermintService(a.BaseApp.GRPCQueryRouter(), ctx, a.interfaceRegistry)
}
func (a *App) RegisterAPIRoutes(server *api.Server, _ serverconfig.APIConfig) {
ctx := server.ClientCtx
rpc.RegisterRoutes(ctx, server.Router)
authrest.RegisterTxRoutes(ctx, server.Router)
authtx.RegisterGRPCGatewayRoutes(ctx, server.GRPCGatewayRouter)
tmservice.RegisterGRPCGatewayRoutes(ctx, server.GRPCGatewayRouter)
ModuleBasics.RegisterRESTRoutes(ctx, server.Router)
ModuleBasics.RegisterGRPCGatewayRoutes(ctx, server.GRPCGatewayRouter)
}
func (a *App) LoadHeight(height int64) error {
return a.LoadVersion(height)
}
func (a *App) ModuleAccountsPermissions() map[string][]string {
return map[string][]string{
authtypes.FeeCollectorName: nil,
distributiontypes.ModuleName: nil,
govtypes.ModuleName: {authtypes.Burner},
ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner},
minttypes.ModuleName: {authtypes.Minter},
stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking},
stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking},
swaptypes.ModuleName: {authtypes.Minter},
deposittypes.ModuleName: nil,
}
}
func (a *App) ModuleAccountAddrs() map[string]bool {
accounts := make(map[string]bool)
for name := range a.ModuleAccountsPermissions() {
accounts[authtypes.NewModuleAddress(name).String()] = true
}
return accounts
}
func (a *App) SimulationManager() *module.SimulationManager {
return a.simulationManager
}
func (a *App) GetSubspace(moduleName string) paramstypes.Subspace {
subspace, _ := a.paramsKeeper.GetSubspace(moduleName)
return subspace
}
<file_sep>package types
import (
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
)
const (
ModuleName = "session"
QuerierRoute = ModuleName
)
var (
ParamsSubspace = ModuleName
RouterKey = ModuleName
StoreKey = ModuleName
)
var (
EventModuleName = EventModule{Name: ModuleName}
)
var (
CountKey = []byte{0x00}
SessionKeyPrefix = []byte{0x11}
SessionForSubscriptionKeyPrefix = []byte{0x20}
SessionForNodeKeyPrefix = []byte{0x21}
InactiveSessionForAddressKeyPrefix = []byte{0x30}
ActiveSessionForAddressKeyPrefix = []byte{0x31}
ActiveSessionAtKeyPrefix = []byte{0x40}
)
func SessionKey(id uint64) []byte {
return append(SessionKeyPrefix, sdk.Uint64ToBigEndian(id)...)
}
func GetSessionForSubscriptionKeyPrefix(id uint64) []byte {
return append(SessionForSubscriptionKeyPrefix, sdk.Uint64ToBigEndian(id)...)
}
func SessionForSubscriptionKey(subscription, id uint64) []byte {
return append(GetSessionForSubscriptionKeyPrefix(subscription), sdk.Uint64ToBigEndian(id)...)
}
func GetSessionForNodeKeyPrefix(address hubtypes.NodeAddress) []byte {
return append(SessionForNodeKeyPrefix, address.Bytes()...)
}
func SessionForNodeKey(address hubtypes.NodeAddress, id uint64) []byte {
return append(GetSessionForNodeKeyPrefix(address), sdk.Uint64ToBigEndian(id)...)
}
func GetInactiveSessionForAddressKeyPrefix(address sdk.AccAddress) []byte {
return append(InactiveSessionForAddressKeyPrefix, address.Bytes()...)
}
func InactiveSessionForAddressKey(address sdk.AccAddress, id uint64) []byte {
return append(GetInactiveSessionForAddressKeyPrefix(address), sdk.Uint64ToBigEndian(id)...)
}
func GetActiveSessionForAddressKeyPrefix(address sdk.AccAddress) []byte {
return append(ActiveSessionForAddressKeyPrefix, address.Bytes()...)
}
func ActiveSessionForAddressKey(address sdk.AccAddress, id uint64) []byte {
return append(GetActiveSessionForAddressKeyPrefix(address), sdk.Uint64ToBigEndian(id)...)
}
func GetActiveSessionAtKeyPrefix(at time.Time) []byte {
return append(ActiveSessionAtKeyPrefix, sdk.FormatTimeBytes(at)...)
}
func ActiveSessionAtKey(at time.Time, id uint64) []byte {
return append(GetActiveSessionAtKeyPrefix(at), sdk.Uint64ToBigEndian(id)...)
}
func IDFromSessionForSubscriptionKey(key []byte) uint64 {
return sdk.BigEndianToUint64(key[1+8:])
}
func IDFromSessionForNodeKey(key []byte) uint64 {
return sdk.BigEndianToUint64(key[1+sdk.AddrLen:])
}
func IDFromStatusSessionForAddressKey(key []byte) uint64 {
return sdk.BigEndianToUint64(key[1+sdk.AddrLen:])
}
func IDFromActiveSessionAtKey(key []byte) uint64 {
return sdk.BigEndianToUint64(key[1+29:])
}
<file_sep>package keeper
import (
"fmt"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/store/prefix"
sdk "github.com/cosmos/cosmos-sdk/types"
paramstypes "github.com/cosmos/cosmos-sdk/x/params/types"
"github.com/tendermint/tendermint/libs/log"
"github.com/sentinel-official/hub/x/provider/expected"
"github.com/sentinel-official/hub/x/provider/types"
)
type Keeper struct {
cdc codec.BinaryMarshaler
key sdk.StoreKey
params paramstypes.Subspace
distribution expected.DistributionKeeper
}
func NewKeeper(cdc codec.BinaryMarshaler, key sdk.StoreKey, params paramstypes.Subspace) Keeper {
return Keeper{
cdc: cdc,
key: key,
params: params.WithKeyTable(types.ParamsKeyTable()),
}
}
func (k *Keeper) WithDistributionKeeper(keeper expected.DistributionKeeper) {
k.distribution = keeper
}
func (k *Keeper) Logger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", "x/"+types.ModuleName)
}
func (k *Keeper) Store(ctx sdk.Context) sdk.KVStore {
child := fmt.Sprintf("%s/", types.ModuleName)
return prefix.NewStore(ctx.KVStore(k.key), []byte(child))
}
<file_sep>package session
import (
sdk "github.com/cosmos/cosmos-sdk/types"
abcitypes "github.com/tendermint/tendermint/abci/types"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/session/keeper"
"github.com/sentinel-official/hub/x/session/types"
)
func EndBlock(ctx sdk.Context, k keeper.Keeper) []abcitypes.ValidatorUpdate {
var (
log = k.Logger(ctx)
end = ctx.BlockTime().Add(-1 * k.InactiveDuration(ctx))
)
k.IterateActiveSessionsAt(ctx, end, func(_ int, key []byte, item types.Session) bool {
log.Info("inactive session", "key", key, "value", item)
itemAddress := item.GetAddress()
if err := k.ProcessPaymentAndUpdateQuota(ctx, item); err != nil {
log.Error("failed to process the payment", "cause", err)
}
k.DeleteActiveSessionForAddress(ctx, itemAddress, item.Id)
k.DeleteActiveSessionAt(ctx, item.StatusAt, item.Id)
item.Status = hubtypes.StatusInactive
item.StatusAt = ctx.BlockTime()
k.SetSession(ctx, item)
k.SetInactiveSessionForAddress(ctx, itemAddress, item.Id)
return false
})
return nil
}
<file_sep>package types
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
)
func (n *Node) GetAddress() hubtypes.NodeAddress {
if n.Address == "" {
return nil
}
address, err := hubtypes.NodeAddressFromBech32(n.Address)
if err != nil {
panic(err)
}
return address
}
func (n *Node) GetProvider() hubtypes.ProvAddress {
if n.Provider == "" {
return nil
}
address, err := hubtypes.ProvAddressFromBech32(n.Provider)
if err != nil {
panic(err)
}
return address
}
func (n *Node) Validate() error {
if _, err := hubtypes.NodeAddressFromBech32(n.Address); err != nil {
return err
}
if (n.Provider != "" && n.Price != nil) ||
(n.Provider == "" && n.Price == nil) {
return fmt.Errorf("invalid provider and price combination; expected one of them empty")
}
if _, err := hubtypes.ProvAddressFromBech32(n.Provider); err != nil {
return err
}
if n.Price != nil && !n.Price.IsValid() {
return fmt.Errorf("invalid price; expected non-nil and valid value")
}
if len(n.RemoteURL) == 0 || len(n.RemoteURL) > 64 {
return fmt.Errorf("invalid remote url length; expected length is between 1 and 64")
}
if !n.Status.Equal(hubtypes.StatusActive) && !n.Status.Equal(hubtypes.StatusInactive) {
return fmt.Errorf("invalid status; exptected active or inactive")
}
if n.StatusAt.IsZero() {
return fmt.Errorf("invalid status at; expected non-zero value")
}
return nil
}
func (n *Node) PriceForDenom(s string) (sdk.Coin, bool) {
for _, coin := range n.Price {
if coin.Denom == s {
return coin, true
}
}
return sdk.Coin{}, false
}
func (n *Node) BytesForCoin(coin sdk.Coin) (sdk.Int, error) {
price, found := n.PriceForDenom(coin.Denom)
if !found {
return sdk.ZeroInt(), fmt.Errorf("price for denom %s does not exist", coin.Denom)
}
x := hubtypes.Gigabyte.Quo(price.Amount)
if x.IsPositive() {
return coin.Amount.Mul(x), nil
}
y := sdk.NewDecFromInt(price.Amount).
QuoInt(hubtypes.Gigabyte).
Ceil().TruncateInt()
return coin.Amount.Quo(y), nil
}
type Nodes []Node
<file_sep>package rest
import (
"context"
"net/http"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/types/rest"
"github.com/gorilla/mux"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/node/types"
)
func queryNode(ctx client.Context) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
address, err := hubtypes.NodeAddressFromBech32(vars["address"])
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
var (
qc = types.NewQueryServiceClient(ctx)
)
res, err := qc.QueryNode(context.Background(),
types.NewQueryNodeRequest(address))
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, ctx, res)
}
}
func queryNodes(ctx client.Context) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var (
query = r.URL.Query()
status = hubtypes.StatusFromString(query.Get("status"))
qc = types.NewQueryServiceClient(ctx)
)
if query.Get("provider") != "" {
address, err := hubtypes.ProvAddressFromBech32(query.Get("provider"))
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
res, err := qc.QueryNodesForProvider(context.Background(),
types.NewQueryNodesForProviderRequest(address, status, nil))
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, ctx, res)
return
} else if query.Get("plan") != "" {
rest.PostProcessResponse(w, ctx, nil)
return
} else {
res, err := qc.QueryNodes(context.Background(),
types.NewQueryNodesRequest(status, nil))
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, ctx, res)
return
}
}
}
<file_sep>package keeper
import (
"context"
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/provider/types"
)
var (
_ types.MsgServiceServer = (*msgServer)(nil)
)
type msgServer struct {
Keeper
}
func NewMsgServiceServer(keeper Keeper) types.MsgServiceServer {
return &msgServer{Keeper: keeper}
}
func (k *msgServer) MsgRegister(c context.Context, msg *types.MsgRegisterRequest) (*types.MsgRegisterResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
msgFrom, err := sdk.AccAddressFromBech32(msg.From)
if err != nil {
return nil, err
}
_, found := k.GetProvider(ctx, msgFrom.Bytes())
if found {
return nil, types.ErrorDuplicateProvider
}
deposit := k.Deposit(ctx)
if deposit.IsPositive() {
if err := k.FundCommunityPool(ctx, msgFrom, deposit); err != nil {
return nil, err
}
}
var (
provAddress = hubtypes.ProvAddress(msgFrom.Bytes())
provider = types.Provider{
Address: provAddress.String(),
Name: msg.Name,
Identity: msg.Identity,
Website: msg.Website,
Description: msg.Description,
}
)
k.SetProvider(ctx, provider)
ctx.EventManager().EmitTypedEvent(
&types.EventRegisterProvider{
From: sdk.AccAddress(msgFrom.Bytes()).String(),
Address: provider.Address,
Name: provider.Name,
Identity: provider.Identity,
Website: provider.Website,
Description: provider.Description,
},
)
ctx.EventManager().EmitTypedEvent(&types.EventModuleName)
return &types.MsgRegisterResponse{}, nil
}
func (k *msgServer) MsgUpdate(c context.Context, msg *types.MsgUpdateRequest) (*types.MsgUpdateResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
msgFrom, err := hubtypes.ProvAddressFromBech32(msg.From)
if err != nil {
return nil, err
}
provider, found := k.GetProvider(ctx, msgFrom)
if !found {
return nil, types.ErrorProviderDoesNotExist
}
if len(msg.Name) > 0 {
provider.Name = msg.Name
}
if len(msg.Identity) > 0 {
provider.Identity = msg.Identity
}
if len(msg.Website) > 0 {
provider.Website = msg.Website
}
if len(msg.Description) > 0 {
provider.Description = msg.Description
}
k.SetProvider(ctx, provider)
ctx.EventManager().EmitTypedEvent(
&types.EventUpdateProvider{
From: sdk.AccAddress(msgFrom.Bytes()).String(),
Address: provider.Address,
Name: msg.Name,
Identity: msg.Identity,
Website: msg.Website,
Description: msg.Description,
},
)
ctx.EventManager().EmitTypedEvent(&types.EventModuleName)
return &types.MsgUpdateResponse{}, nil
}
<file_sep>package v06
import (
"github.com/sentinel-official/hub/x/plan/types"
legacy "github.com/sentinel-official/hub/x/plan/types/legacy/v0.5"
)
func MigrateGenesisPlan(item legacy.GenesisPlan) types.GenesisPlan {
var nodes = make([]string, 0, len(item.Nodes))
for _, item := range item.Nodes {
nodes = append(nodes, item.String())
}
return types.GenesisPlan{
Plan: MigratePlan(item.Plan),
Nodes: nodes,
}
}
func MigrateGenesisPlans(items legacy.GenesisPlans) types.GenesisPlans {
var plans types.GenesisPlans
for _, item := range items {
plans = append(plans, MigrateGenesisPlan(item))
}
return plans
}
func MigrateGenesisState(state legacy.GenesisState) types.GenesisState {
return types.NewGenesisState(
MigrateGenesisPlans(legacy.GenesisPlans(state)),
)
}
<file_sep>package types
import (
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
)
const (
ModuleName = "node"
QuerierRoute = ModuleName
)
var (
ParamsSubspace = ModuleName
RouterKey = ModuleName
StoreKey = ModuleName
)
var (
EventModuleName = EventModule{Name: ModuleName}
)
var (
NodeKeyPrefix = []byte{0x10}
ActiveNodeKeyPrefix = []byte{0x20}
InactiveNodeKeyPrefix = []byte{0x21}
ActiveNodeForProviderKeyPrefix = []byte{0x30}
InactiveNodeForProviderKeyPrefix = []byte{0x31}
InactiveNodeAtKeyPrefix = []byte{0x41}
)
func NodeKey(address hubtypes.NodeAddress) []byte {
return append(NodeKeyPrefix, address.Bytes()...)
}
func ActiveNodeKey(address hubtypes.NodeAddress) []byte {
return append(ActiveNodeKeyPrefix, address.Bytes()...)
}
func InactiveNodeKey(address hubtypes.NodeAddress) []byte {
return append(InactiveNodeKeyPrefix, address.Bytes()...)
}
func GetActiveNodeForProviderKeyPrefix(address hubtypes.ProvAddress) []byte {
return append(ActiveNodeForProviderKeyPrefix, address.Bytes()...)
}
func ActiveNodeForProviderKey(provider hubtypes.ProvAddress, address hubtypes.NodeAddress) []byte {
return append(GetActiveNodeForProviderKeyPrefix(provider), address.Bytes()...)
}
func GetInactiveNodeForProviderKeyPrefix(address hubtypes.ProvAddress) []byte {
return append(InactiveNodeForProviderKeyPrefix, address.Bytes()...)
}
func InactiveNodeForProviderKey(provider hubtypes.ProvAddress, address hubtypes.NodeAddress) []byte {
return append(GetInactiveNodeForProviderKeyPrefix(provider), address.Bytes()...)
}
func GetInactiveNodeAtKeyPrefix(at time.Time) []byte {
return append(InactiveNodeAtKeyPrefix, sdk.FormatTimeBytes(at)...)
}
func InactiveNodeAtKey(at time.Time, address hubtypes.NodeAddress) []byte {
return append(GetInactiveNodeAtKeyPrefix(at), address.Bytes()...)
}
func AddressFromStatusNodeKey(key []byte) hubtypes.NodeAddress {
return key[1:]
}
func AddressFromStatusNodeForProviderKey(key []byte) hubtypes.NodeAddress {
return key[1+sdk.AddrLen:]
}
func AddressFromStatusNodeAtKey(key []byte) hubtypes.NodeAddress {
return key[1+29:]
}
<file_sep>package keeper
import (
"context"
"strings"
"github.com/cosmos/cosmos-sdk/store/prefix"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/query"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/node/types"
)
var (
_ types.QueryServiceServer = (*queryServer)(nil)
)
type queryServer struct {
Keeper
}
func NewQueryServiceServer(keeper Keeper) types.QueryServiceServer {
return &queryServer{Keeper: keeper}
}
func (q *queryServer) QueryNode(c context.Context, req *types.QueryNodeRequest) (*types.QueryNodeResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
address, err := hubtypes.NodeAddressFromBech32(req.Address)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid address %s", req.Address)
}
ctx := sdk.UnwrapSDKContext(c)
item, found := q.GetNode(ctx, address)
if !found {
return nil, status.Errorf(codes.NotFound, "node does not exist for address %s", req.Address)
}
return &types.QueryNodeResponse{Node: item}, nil
}
func (q *queryServer) QueryNodes(c context.Context, req *types.QueryNodesRequest) (res *types.QueryNodesResponse, err error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
var (
items types.Nodes
pagination *query.PageResponse
ctx = sdk.UnwrapSDKContext(c)
)
if req.Status.Equal(hubtypes.Active) {
store := prefix.NewStore(q.Store(ctx), types.ActiveNodeKeyPrefix)
pagination, err = query.FilteredPaginate(store, req.Pagination, func(key, _ []byte, accumulate bool) (bool, error) {
item, found := q.GetNode(ctx, key)
if !found {
return false, nil
}
if accumulate {
items = append(items, item)
}
return true, nil
})
} else if req.Status.Equal(hubtypes.Inactive) {
store := prefix.NewStore(q.Store(ctx), types.InactiveNodeKeyPrefix)
pagination, err = query.FilteredPaginate(store, req.Pagination, func(key, _ []byte, accumulate bool) (bool, error) {
item, found := q.GetNode(ctx, key)
if !found {
return false, nil
}
if accumulate {
items = append(items, item)
}
return true, nil
})
} else {
store := prefix.NewStore(q.Store(ctx), types.NodeKeyPrefix)
pagination, err = query.FilteredPaginate(store, req.Pagination, func(_, value []byte, accumulate bool) (bool, error) {
var node types.Node
if err := q.cdc.UnmarshalBinaryBare(value, &node); err != nil {
return false, err
}
if accumulate {
items = append(items, node)
}
return true, nil
})
}
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &types.QueryNodesResponse{Nodes: items, Pagination: pagination}, nil
}
func (q *queryServer) QueryNodesForProvider(c context.Context, req *types.QueryNodesForProviderRequest) (res *types.QueryNodesForProviderResponse, err error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
provider, err := hubtypes.ProvAddressFromBech32(req.Address)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid address %s", req.Address)
}
var (
items types.Nodes
pagination *query.PageResponse
ctx = sdk.UnwrapSDKContext(c)
)
if req.Status.Equal(hubtypes.Active) {
store := prefix.NewStore(q.Store(ctx), types.GetActiveNodeForProviderKeyPrefix(provider))
pagination, err = query.FilteredPaginate(store, req.Pagination, func(key, _ []byte, accumulate bool) (bool, error) {
item, found := q.GetNode(ctx, key)
if !found {
return false, nil
}
if accumulate {
items = append(items, item)
}
return true, nil
})
} else if req.Status.Equal(hubtypes.Inactive) {
store := prefix.NewStore(q.Store(ctx), types.GetInactiveNodeForProviderKeyPrefix(provider))
pagination, err = query.FilteredPaginate(store, req.Pagination, func(key, _ []byte, accumulate bool) (bool, error) {
item, found := q.GetNode(ctx, key)
if !found {
return false, nil
}
if accumulate {
items = append(items, item)
}
return true, nil
})
} else {
// NOTE: Do not use this; less efficient; consider using active + inactive
store := prefix.NewStore(q.Store(ctx), types.NodeKeyPrefix)
pagination, err = query.FilteredPaginate(store, req.Pagination, func(_, value []byte, accumulate bool) (bool, error) {
var item types.Node
if err := q.cdc.UnmarshalBinaryBare(value, &item); err != nil {
return false, err
}
if !strings.EqualFold(item.Provider, req.Address) {
return false, nil
}
if accumulate {
items = append(items, item)
}
return true, nil
})
}
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &types.QueryNodesForProviderResponse{Nodes: items, Pagination: pagination}, nil
}
func (q *queryServer) QueryParams(c context.Context, _ *types.QueryParamsRequest) (*types.QueryParamsResponse, error) {
var (
ctx = sdk.UnwrapSDKContext(c)
params = q.GetParams(ctx)
)
return &types.QueryParamsResponse{Params: params}, nil
}
<file_sep>package types
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
)
func NewMsgSwapRequest(from sdk.AccAddress, txHash EthereumHash, receiver sdk.AccAddress, amount sdk.Int) *MsgSwapRequest {
return &MsgSwapRequest{
From: from.String(),
TxHash: txHash.Bytes(),
Receiver: receiver.String(),
Amount: amount,
}
}
func (m *MsgSwapRequest) Route() string {
return RouterKey
}
func (m *MsgSwapRequest) Type() string {
return fmt.Sprintf("%s:swap", ModuleName)
}
func (m *MsgSwapRequest) ValidateBasic() error {
if _, err := sdk.AccAddressFromBech32(m.From); err != nil {
return ErrorInvalidFieldFrom
}
if _, err := sdk.AccAddressFromBech32(m.Receiver); err != nil {
return ErrorInvalidFieldReceiver
}
if m.Amount.LT(PrecisionLoss) {
return ErrorInvalidFieldAmount
}
return nil
}
func (m *MsgSwapRequest) GetSignBytes() []byte {
return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(m))
}
func (m *MsgSwapRequest) GetSigners() []sdk.AccAddress {
from, err := sdk.AccAddressFromBech32(m.From)
if err != nil {
panic(err)
}
return []sdk.AccAddress{from}
}
<file_sep>package v05
import (
hubtypes "github.com/sentinel-official/hub/types"
)
type (
GenesisPlan struct {
Plan Plan `json:"_"`
Nodes []hubtypes.NodeAddress `json:"nodes"`
}
GenesisPlans []GenesisPlan
GenesisState GenesisPlans
)
<file_sep>package types
import (
"github.com/cosmos/cosmos-sdk/types/errors"
)
var (
ErrorInvalidField = errors.Register(ModuleName, 101, "invalid field")
ErrorSubscriptionDoesNotExit = errors.Register(ModuleName, 102, "subscription does not exist")
ErrorInvalidSubscriptionStatus = errors.Register(ModuleName, 103, "invalid subscription status")
ErrorUnauthorized = errors.Register(ModuleName, 104, "unauthorized")
ErrorQuotaDoesNotExist = errors.Register(ModuleName, 105, "quota does not exist")
ErrorFailedToVerifyProof = errors.Register(ModuleName, 106, "failed to verify proof")
ErrorNotEnoughQuota = errors.Register(ModuleName, 107, "not enough quota")
ErrorNodeDoesNotExist = errors.Register(ModuleName, 108, "node does not exist")
ErrorInvalidNodeStatus = errors.Register(ModuleName, 109, "invalid node status")
ErrorSessionDoesNotExist = errors.Register(ModuleName, 110, "session does not exist")
ErrorInvalidSessionStatus = errors.Register(ModuleName, 111, "invalid session status")
ErrorAccountDoesNotExist = errors.Register(ModuleName, 112, "account does not exist")
ErrorPublicKeyDoesNotExist = errors.Register(ModuleName, 113, "public key does not exist")
ErrorInvalidSignature = errors.Register(ModuleName, 114, "invalid signature")
ErrorNodeAddressMismatch = errors.Register(ModuleName, 115, "node address mismatch")
ErrorNodeDoesNotExistForPlan = errors.Register(ModuleName, 116, "node does not exist for plan")
ErrorDuplicateSession = errors.Register(ModuleName, 117, "duplicate session")
)
<file_sep>package cli
import (
"context"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/spf13/cobra"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/node/types"
)
func queryNode() *cobra.Command {
cmd := &cobra.Command{
Use: "node",
Short: "Query a node",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
ctx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
address, err := hubtypes.NodeAddressFromBech32(args[0])
if err != nil {
return err
}
var (
qc = types.NewQueryServiceClient(ctx)
)
res, err := qc.QueryNode(context.Background(),
types.NewQueryNodeRequest(address))
if err != nil {
return err
}
return ctx.PrintProto(res)
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
func queryNodes() *cobra.Command {
cmd := &cobra.Command{
Use: "nodes",
Short: "Query nodes",
RunE: func(cmd *cobra.Command, args []string) (err error) {
ctx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
provider, err := cmd.Flags().GetString(flagProvider)
if err != nil {
return err
}
plan, err := cmd.Flags().GetUint64(flagPlan)
if err != nil {
return err
}
s, err := cmd.Flags().GetString(flagStatus)
if err != nil {
return err
}
pagination, err := client.ReadPageRequest(cmd.Flags())
if err != nil {
return err
}
var (
status = hubtypes.StatusFromString(s)
qc = types.NewQueryServiceClient(ctx)
)
if len(provider) > 0 {
address, err := hubtypes.ProvAddressFromBech32(provider)
if err != nil {
return err
}
res, err := qc.QueryNodesForProvider(context.Background(),
types.NewQueryNodesForProviderRequest(address, status, pagination))
if err != nil {
return err
}
return ctx.PrintProto(res)
} else if plan > 0 {
return nil
} else {
res, err := qc.QueryNodes(context.Background(),
types.NewQueryNodesRequest(status, pagination))
if err != nil {
return err
}
return ctx.PrintProto(res)
}
},
}
flags.AddQueryFlagsToCmd(cmd)
flags.AddPaginationFlagsToCmd(cmd, "nodes")
cmd.Flags().String(flagProvider, "", "provider address")
cmd.Flags().Uint64(flagPlan, 0, "subscription plan ID")
cmd.Flags().String(flagStatus, "", "status")
return cmd
}
func queryParams() *cobra.Command {
cmd := &cobra.Command{
Use: "node-params",
Short: "Query node module parameters",
RunE: func(cmd *cobra.Command, _ []string) error {
ctx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
var (
qc = types.NewQueryServiceClient(ctx)
)
res, err := qc.QueryParams(context.Background(),
types.NewQueryParamsRequest())
if err != nil {
return err
}
return ctx.PrintProto(res)
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
<file_sep>package types
import (
"errors"
"testing"
sdk "github.com/cosmos/cosmos-sdk/types"
)
func TestMsgSwapRequest_ValidateBasic(t *testing.T) {
correctAddress, err := sdk.AccAddressFromBech32("cosmos1hlzx7raug6wea9fs955nkzwe2xaa65gnpmddal")
if err != nil {
t.Errorf("invalid address provided: %s", err)
}
tests := []struct {
name string
m *MsgSwapRequest
want error
}{
{"nil from address", NewMsgSwapRequest(nil, EthereumHash{}, nil, sdk.NewInt(0)), ErrorInvalidFieldFrom},
{"empty from address", NewMsgSwapRequest(sdk.AccAddress{}, EthereumHash{}, nil, sdk.NewInt(0)), ErrorInvalidFieldFrom},
{"nil receiver address", NewMsgSwapRequest(correctAddress, EthereumHash{}, nil, sdk.NewInt(0)), ErrorInvalidFieldReceiver},
{"empty receiver address", NewMsgSwapRequest(correctAddress, EthereumHash{}, sdk.AccAddress{}, sdk.NewInt(0)), ErrorInvalidFieldReceiver},
{"invalid amount", NewMsgSwapRequest(correctAddress, EthereumHash{}, correctAddress, sdk.NewInt(10)), ErrorInvalidFieldAmount},
{"valid", NewMsgSwapRequest(correctAddress, EthereumHash{}, correctAddress, sdk.NewInt(1000)), nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := tt.m.ValidateBasic(); !errors.Is(err, tt.want) {
t.Errorf("ValidateBasic() = %v, want %v", err, tt.want)
}
})
}
}
<file_sep>package rest
import (
"context"
"net/http"
"strconv"
"github.com/cosmos/cosmos-sdk/client"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/rest"
"github.com/gorilla/mux"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/subscription/types"
)
func querySubscription(ctx client.Context) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.ParseUint(vars["id"], 10, 64)
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
var (
qc = types.NewQueryServiceClient(ctx)
)
res, err := qc.QuerySubscription(context.Background(),
types.NewQuerySubscriptionRequest(id))
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, ctx, res)
}
}
func querySubscriptions(ctx client.Context) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var (
query = r.URL.Query()
status = hubtypes.StatusFromString(query.Get("status"))
qc = types.NewQueryServiceClient(ctx)
)
if query.Get("address") != "" {
address, err := sdk.AccAddressFromBech32(query.Get("address"))
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
res, err := qc.QuerySubscriptionsForAddress(context.Background(),
types.NewQuerySubscriptionsForAddressRequest(address, status, nil))
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, ctx, res)
return
} else if query.Get("plan") != "" {
id, err := strconv.ParseUint(query.Get("plan"), 10, 64)
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
res, err := qc.QuerySubscriptionsForPlan(context.Background(),
types.NewQuerySubscriptionsForPlanRequest(id, nil))
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, ctx, res)
return
} else if query.Get("node") != "" {
address, err := hubtypes.NodeAddressFromBech32(query.Get("node"))
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
res, err := qc.QuerySubscriptionsForNode(context.Background(),
types.NewQuerySubscriptionsForNodeRequest(address, nil))
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, ctx, res)
return
} else {
res, err := qc.QuerySubscriptions(context.Background(),
types.NewQuerySubscriptionsRequest(nil))
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, ctx, res)
return
}
}
}
func queryQuota(ctx client.Context) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.ParseUint(vars["id"], 10, 64)
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
address, err := sdk.AccAddressFromBech32(vars["address"])
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
var (
qc = types.NewQueryServiceClient(ctx)
)
res, err := qc.QueryQuota(context.Background(),
types.NewQueryQuotaRequest(id, address))
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, ctx, res)
}
}
func queryQuotas(ctx client.Context) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var (
vars = mux.Vars(r)
qc = types.NewQueryServiceClient(ctx)
)
id, err := strconv.ParseUint(vars["id"], 10, 64)
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
res, err := qc.QueryQuotas(context.Background(),
types.NewQueryQuotasRequest(id, nil))
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, ctx, res)
}
}
<file_sep>package types
import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
const (
ModuleName = "swap"
QuerierRoute = ModuleName
DefaultParamspace = ModuleName
)
var (
ParamsSubspace = ModuleName
RouterKey = ModuleName
StoreKey = ModuleName
)
var (
PrecisionLoss = sdk.NewInt(100)
)
var (
EventModuleName = EventModule{Name: ModuleName}
)
var (
SwapKeyPrefix = []byte{0x10}
)
func SwapKey(hash EthereumHash) []byte {
return append(SwapKeyPrefix, hash.Bytes()...)
}
<file_sep>package v06
import (
"github.com/sentinel-official/hub/x/provider/types"
legacy "github.com/sentinel-official/hub/x/provider/types/legacy/v0.5"
)
func MigrateGenesisState(state *legacy.GenesisState) *types.GenesisState {
return types.NewGenesisState(
MigrateProviders(state.Providers),
MigrateParams(state.Params),
)
}
<file_sep>package node
import (
sdk "github.com/cosmos/cosmos-sdk/types"
abcitypes "github.com/tendermint/tendermint/abci/types"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/node/keeper"
"github.com/sentinel-official/hub/x/node/types"
)
func EndBlock(ctx sdk.Context, k keeper.Keeper) []abcitypes.ValidatorUpdate {
var (
log = k.Logger(ctx)
inactiveDuration = k.InactiveDuration(ctx)
)
k.IterateInactiveNodesAt(ctx, ctx.BlockTime(), func(_ int, key []byte, item types.Node) bool {
log.Info("inactive node", "key", key, "value", item)
itemAddress := item.GetAddress()
k.DeleteActiveNode(ctx, itemAddress)
k.SetInactiveNode(ctx, itemAddress)
if item.Provider != "" {
itemProvider := item.GetProvider()
k.DeleteActiveNodeForProvider(ctx, itemProvider, itemAddress)
k.SetInactiveNodeForProvider(ctx, itemProvider, itemAddress)
}
k.DeleteInactiveNodeAt(ctx, item.StatusAt.Add(inactiveDuration), itemAddress)
item.Status = hubtypes.StatusInactive
item.StatusAt = ctx.BlockTime()
k.SetNode(ctx, item)
return false
})
return nil
}
<file_sep>package v05
type (
GenesisState struct {
Swaps Swaps `json:"_"`
Params Params `json:"params"`
}
)
<file_sep>package keeper
import (
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/deposit/types"
)
// SetDeposit is for inserting a deposit into KVStore.
func (k *Keeper) SetDeposit(ctx sdk.Context, deposit types.Deposit) {
key := types.DepositKey(deposit.GetAddress())
value := k.cdc.MustMarshalBinaryBare(&deposit)
store := k.Store(ctx)
store.Set(key, value)
}
// GetDeposit is for getting the deposit of an address from KVStore.
func (k *Keeper) GetDeposit(ctx sdk.Context, address sdk.AccAddress) (deposit types.Deposit, found bool) {
store := k.Store(ctx)
key := types.DepositKey(address)
value := store.Get(key)
if value == nil {
return deposit, false
}
k.cdc.MustUnmarshalBinaryBare(value, &deposit)
return deposit, true
}
// GetDeposits is for getting the deposits from KVStore.
func (k *Keeper) GetDeposits(ctx sdk.Context, skip, limit int64) (items types.Deposits) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.DepositKeyPrefix),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
var item types.Deposit
k.cdc.MustUnmarshalBinaryBare(iter.Value(), &item)
items = append(items, item)
})
return items
}
// Add is for adding the amount to the deposit account from the bank account of an address.
func (k *Keeper) Add(ctx sdk.Context, address sdk.AccAddress, coins sdk.Coins) error {
if err := k.bank.SendCoinsFromAccountToModule(ctx, address, types.ModuleName, coins); err != nil {
return err
}
deposit, found := k.GetDeposit(ctx, address)
if !found {
deposit = types.Deposit{
Address: address.String(),
Coins: sdk.NewCoins(),
}
}
deposit.Coins = deposit.Coins.Add(coins...)
if deposit.Coins.IsAnyNegative() {
return types.ErrorInsufficientDepositFunds
}
k.SetDeposit(ctx, deposit)
return nil
}
// Subtract is for adding the amount to the bank account from the deposit account of an address.
func (k *Keeper) Subtract(ctx sdk.Context, address sdk.AccAddress, coins sdk.Coins) error {
deposit, found := k.GetDeposit(ctx, address)
if !found {
return types.ErrorDepositDoesNotExist
}
deposit.Coins, _ = deposit.Coins.SafeSub(coins)
if deposit.Coins.IsAnyNegative() {
return types.ErrorInsufficientDepositFunds
}
if err := k.bank.SendCoinsFromModuleToAccount(ctx, types.ModuleName, address, coins); err != nil {
return err
}
k.SetDeposit(ctx, deposit)
return nil
}
// SendCoinsFromDepositToAccount is for sending the amount
// from the deposit account of from address to the bank account of to address.
func (k *Keeper) SendCoinsFromDepositToAccount(ctx sdk.Context, from, to sdk.AccAddress, coins sdk.Coins) error {
deposit, found := k.GetDeposit(ctx, from)
if !found {
return types.ErrorDepositDoesNotExist
}
deposit.Coins, _ = deposit.Coins.SafeSub(coins)
if deposit.Coins.IsAnyNegative() {
return types.ErrorInsufficientDepositFunds
}
if err := k.bank.SendCoinsFromModuleToAccount(ctx, types.ModuleName, to, coins); err != nil {
return err
}
k.SetDeposit(ctx, deposit)
return nil
}
// SendCoinsFromAccountToDeposit is for sending the amount
// from the bank account of from address to the deposit account of to address.
func (k *Keeper) SendCoinsFromAccountToDeposit(ctx sdk.Context, from, to sdk.AccAddress, coins sdk.Coins) error {
if err := k.bank.SendCoinsFromAccountToModule(ctx, from, types.ModuleName, coins); err != nil {
return err
}
deposit, found := k.GetDeposit(ctx, to)
if !found {
deposit = types.Deposit{
Address: to.String(),
Coins: sdk.Coins{},
}
}
deposit.Coins = deposit.Coins.Add(coins...)
if deposit.Coins.IsAnyNegative() {
return types.ErrorInsufficientDepositFunds
}
k.SetDeposit(ctx, deposit)
return nil
}
// IterateDeposits is for iterating over all the deposits to perform an action.
func (k *Keeper) IterateDeposits(ctx sdk.Context, fn func(index int64, item types.Deposit) (stop bool)) {
store := k.Store(ctx)
iterator := sdk.KVStorePrefixIterator(store, types.DepositKeyPrefix)
defer iterator.Close()
for i := int64(0); iterator.Valid(); iterator.Next() {
var deposit types.Deposit
k.cdc.MustUnmarshalBinaryBare(iterator.Value(), &deposit)
if stop := fn(i, deposit); stop {
break
}
i++
}
}
<file_sep>package v05
import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
type (
Params struct {
Deposit sdk.Coin `json:"deposit"`
}
)
<file_sep>package v05
const (
ModuleName = "swap"
)
<file_sep>package cli
import (
"github.com/spf13/cobra"
)
func GetQueryCommands() []*cobra.Command {
return []*cobra.Command{
querySubscription(),
querySubscriptions(),
queryParams(),
queryQuota(),
queryQuotas(),
}
}
func GetTxCommands() []*cobra.Command {
cmd := &cobra.Command{
Use: "subscription",
Short: "Subscription module sub-commands",
}
cmd.AddCommand(
txSubscribeToNode(),
txSubscribeToPlan(),
txCancel(),
txAddQuota(),
txUpdateQuota(),
)
return []*cobra.Command{cmd}
}
<file_sep>package v05
type (
Status byte
)
<file_sep>package v06
import (
"github.com/sentinel-official/hub/types"
v05 "github.com/sentinel-official/hub/types/legacy/v0.5"
)
func MigrateStatus(v v05.Status) types.Status {
return types.Status(v)
}
<file_sep>package v05
import (
hubtypes "github.com/sentinel-official/hub/types"
)
type (
Provider struct {
Address hubtypes.ProvAddress `json:"address"`
Name string `json:"name"`
Identity string `json:"identity"`
Website string `json:"website"`
Description string `json:"description"`
}
Providers []Provider
)
<file_sep>package v05
import (
"time"
)
type (
Params struct {
InactiveDuration time.Duration `json:"inactive_duration"`
}
)
<file_sep>package types
import (
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
)
const (
ModuleName = "plan"
QuerierRoute = ModuleName
)
var (
RouterKey = ModuleName
StoreKey = ModuleName
)
var (
EventModuleName = EventModule{Name: ModuleName}
)
var (
CountKey = []byte{0x00}
PlanKeyPrefix = []byte{0x10}
ActivePlanKeyPrefix = []byte{0x20}
InactivePlanKeyPrefix = []byte{0x21}
ActivePlanForProviderKeyPrefix = []byte{0x30}
InactivePlanForProviderKeyPrefix = []byte{0x31}
NodeForPlanKeyPrefix = []byte{0x40}
CountForNodeByProviderKeyPrefix = []byte{0x50}
)
func PlanKey(id uint64) []byte {
return append(PlanKeyPrefix, sdk.Uint64ToBigEndian(id)...)
}
func ActivePlanKey(id uint64) []byte {
return append(ActivePlanKeyPrefix, sdk.Uint64ToBigEndian(id)...)
}
func InactivePlanKey(id uint64) []byte {
return append(InactivePlanKeyPrefix, sdk.Uint64ToBigEndian(id)...)
}
func GetActivePlanForProviderKeyPrefix(address hubtypes.ProvAddress) []byte {
return append(ActivePlanForProviderKeyPrefix, address.Bytes()...)
}
func ActivePlanForProviderKey(address hubtypes.ProvAddress, id uint64) []byte {
return append(GetActivePlanForProviderKeyPrefix(address), sdk.Uint64ToBigEndian(id)...)
}
func GetInactivePlanForProviderKeyPrefix(address hubtypes.ProvAddress) []byte {
return append(InactivePlanForProviderKeyPrefix, address.Bytes()...)
}
func InactivePlanForProviderKey(address hubtypes.ProvAddress, id uint64) []byte {
return append(GetInactivePlanForProviderKeyPrefix(address), sdk.Uint64ToBigEndian(id)...)
}
func GetNodeForPlanKeyPrefix(id uint64) []byte {
return append(NodeForPlanKeyPrefix, sdk.Uint64ToBigEndian(id)...)
}
func NodeForPlanKey(id uint64, address hubtypes.NodeAddress) []byte {
return append(GetNodeForPlanKeyPrefix(id), address.Bytes()...)
}
func CountForNodeByProviderKey(p hubtypes.ProvAddress, n hubtypes.NodeAddress) []byte {
return append(CountForNodeByProviderKeyPrefix, append(p.Bytes(), n.Bytes()...)...)
}
func IDFromStatusPlanKey(key []byte) uint64 {
return sdk.BigEndianToUint64(key[1:])
}
func IDFromStatusPlanForProviderKey(key []byte) uint64 {
return sdk.BigEndianToUint64(key[1+sdk.AddrLen:])
}
func AddressFromNodeForPlanKey(key []byte) hubtypes.NodeAddress {
return key[1+8:]
}
<file_sep>package types
import (
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/types"
cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec"
deposittypes "github.com/sentinel-official/hub/x/deposit/types"
nodetypes "github.com/sentinel-official/hub/x/node/types"
plantypes "github.com/sentinel-official/hub/x/plan/types"
providertypes "github.com/sentinel-official/hub/x/provider/types"
sessiontypes "github.com/sentinel-official/hub/x/session/types"
subscriptiontypes "github.com/sentinel-official/hub/x/subscription/types"
)
var (
amino = codec.NewLegacyAmino()
ModuleCdc = codec.NewAminoCodec(amino)
)
func init() {
RegisterLegacyAminoCodec(amino)
cryptocodec.RegisterCrypto(amino)
amino.Seal()
}
func RegisterLegacyAminoCodec(_ *codec.LegacyAmino) {}
func RegisterInterfaces(registry types.InterfaceRegistry) {
deposittypes.RegisterInterfaces(registry)
providertypes.RegisterInterfaces(registry)
nodetypes.RegisterInterfaces(registry)
plantypes.RegisterInterfaces(registry)
subscriptiontypes.RegisterInterfaces(registry)
sessiontypes.RegisterInterfaces(registry)
}
<file_sep>package v06
import (
"github.com/sentinel-official/hub/x/deposit/types"
legacy "github.com/sentinel-official/hub/x/deposit/types/legacy/v0.5"
)
func MigrateGenesisState(state legacy.GenesisState) types.GenesisState {
return types.NewGenesisState(
MigrateDeposits(legacy.Deposits(state)),
)
}
<file_sep>package types
import (
"fmt"
hubtypes "github.com/sentinel-official/hub/types"
)
func (p *Provider) GetAddress() hubtypes.ProvAddress {
if p.Address == "" {
return nil
}
address, err := hubtypes.ProvAddressFromBech32(p.Address)
if err != nil {
panic(err)
}
return address
}
func (p *Provider) Validate() error {
if _, err := hubtypes.ProvAddressFromBech32(p.Address); err != nil {
return fmt.Errorf("address should not be nil or empty")
}
if len(p.Name) == 0 || len(p.Name) > 64 {
return fmt.Errorf("name length should be between 1 and 64")
}
if len(p.Identity) > 64 {
return fmt.Errorf("identity length should be between 0 and 64")
}
if len(p.Website) > 64 {
return fmt.Errorf("website length should be between 0 and 64")
}
if len(p.Description) > 256 {
return fmt.Errorf("description length should be between 0 and 256")
}
return nil
}
type Providers []Provider
<file_sep>package v06
import (
"github.com/sentinel-official/hub/x/swap/types"
legacy "github.com/sentinel-official/hub/x/swap/types/legacy/v0.5"
)
func MigrateGenesisState(state *legacy.GenesisState) *types.GenesisState {
return types.NewGenesisState(
MigrateSwaps(state.Swaps),
MigrateParams(state.Params),
)
}
<file_sep>package types
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
params "github.com/cosmos/cosmos-sdk/x/params/types"
)
const (
DefaultSwapEnabled = false
DefaultSwapDenom = "tsent"
DefaultApproveBy = ""
)
var (
KeySwapEnabled = []byte("SwapEnabled")
KeySwapDenom = []byte("SwapDenom")
KeyApproveBy = []byte("ApproveBy")
)
var (
_ params.ParamSet = (*Params)(nil)
)
func (p *Params) Validate() error {
if err := sdk.ValidateDenom(p.SwapDenom); err != nil {
return err
}
approveBy, err := sdk.AccAddressFromBech32(p.ApproveBy)
if err != nil {
return err
}
if approveBy == nil || approveBy.Empty() {
return fmt.Errorf("approve_by should not nil or empty")
}
return nil
}
func (p *Params) ParamSetPairs() params.ParamSetPairs {
return params.ParamSetPairs{
{
Key: KeySwapEnabled,
Value: &p.SwapEnabled,
ValidatorFn: func(v interface{}) error {
_, ok := v.(bool)
if !ok {
return fmt.Errorf("invalid parameter type %T", v)
}
return nil
},
},
{
Key: KeySwapDenom,
Value: &p.SwapDenom,
ValidatorFn: func(v interface{}) error {
value, ok := v.(string)
if !ok {
return fmt.Errorf("invalid parameter type %T", v)
}
return sdk.ValidateDenom(value)
},
},
{
Key: KeyApproveBy,
Value: &p.ApproveBy,
ValidatorFn: func(v interface{}) error {
value, ok := v.(string)
if !ok {
return fmt.Errorf("invalid parameter type %T", v)
}
_, err := sdk.AccAddressFromBech32(value)
if err != nil {
return err
}
return nil
},
},
}
}
func NewParams(swapEnabled bool, swapDenom, approveBy string) Params {
return Params{
SwapEnabled: swapEnabled,
SwapDenom: swapDenom,
ApproveBy: approveBy,
}
}
func DefaultParams() Params {
return Params{
SwapEnabled: DefaultSwapEnabled,
SwapDenom: DefaultSwapDenom,
ApproveBy: DefaultApproveBy,
}
}
func ParamsKeyTable() params.KeyTable {
return params.NewKeyTable().RegisterParamSet(&Params{})
}
<file_sep>package simulation
import (
"fmt"
"math/rand"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
sdksimulation "github.com/cosmos/cosmos-sdk/x/simulation"
"github.com/sentinel-official/hub/x/swap/types"
)
func ParamChanges(r *rand.Rand) []simtypes.ParamChange {
return []simtypes.ParamChange{
sdksimulation.NewSimParamChange(types.ModuleName, string(types.KeySwapDenom), func(r *rand.Rand) string {
return fmt.Sprintf("%s", GetRandomSwapDenom(r))
}),
sdksimulation.NewSimParamChange(types.ModuleName, string(types.KeySwapEnabled), func(r *rand.Rand) string {
return fmt.Sprintf("%v", GetRandomSwapEnabled(r))
}),
sdksimulation.NewSimParamChange(types.ModuleName, string(types.KeyApproveBy), func(r *rand.Rand) string {
return fmt.Sprintf("%s", GetRandomApproveBy(r))
}),
}
}
<file_sep>package v05
type (
GenesisSubscription struct {
Subscription Subscription `json:"_"`
Quotas Quotas `json:"quotas"`
}
GenesisSubscriptions []GenesisSubscription
GenesisState struct {
Subscriptions GenesisSubscriptions `json:"_"`
Params Params `json:"params"`
}
)
<file_sep>package v05
import (
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
)
type (
Params struct {
Deposit sdk.Coin `json:"deposit"`
InactiveDuration time.Duration `json:"inactive_duration"`
}
)
<file_sep>package v06
import (
hubtypes "github.com/sentinel-official/hub/types/legacy/v0.6"
"github.com/sentinel-official/hub/x/plan/types"
legacy "github.com/sentinel-official/hub/x/plan/types/legacy/v0.5"
)
func MigratePlan(item legacy.Plan) types.Plan {
return types.Plan{
Id: item.ID,
Provider: item.Provider.String(),
Price: item.Price,
Validity: item.Validity,
Bytes: item.Bytes,
Status: hubtypes.MigrateStatus(item.Status),
StatusAt: item.StatusAt,
}
}
<file_sep>module github.com/sentinel-official/hub
go 1.16
require (
github.com/cosmos/cosmos-sdk v0.42.5
github.com/gogo/protobuf v1.3.3
github.com/golang/protobuf v1.5.2
github.com/gorilla/mux v1.8.0
github.com/grpc-ecosystem/grpc-gateway v1.16.0
github.com/spf13/cast v1.3.1
github.com/spf13/cobra v1.1.3
github.com/stretchr/testify v1.7.0
github.com/tendermint/tendermint v0.34.10
github.com/tendermint/tm-db v0.6.4
google.golang.org/genproto v0.0.0-20210524171403-669157292da3
google.golang.org/grpc v1.38.0
gopkg.in/yaml.v2 v2.4.0
)
replace (
github.com/cosmos/cosmos-sdk => github.com/sentinel-official/cosmos-sdk v0.42.6-sentinel
github.com/gogo/protobuf => github.com/regen-network/protobuf v1.3.3-alpha.regen.1
google.golang.org/grpc => google.golang.org/grpc v1.33.2
)
<file_sep>package types
import (
hubtypes "github.com/sentinel-official/hub/types"
)
const (
ModuleName = "provider"
QuerierRoute = ModuleName
)
var (
ParamsSubspace = ModuleName
RouterKey = ModuleName
StoreKey = ModuleName
)
var (
EventModuleName = EventModule{Name: ModuleName}
)
var (
ProviderKeyPrefix = []byte{0x10}
)
func ProviderKey(address hubtypes.ProvAddress) []byte {
return append(ProviderKeyPrefix, address.Bytes()...)
}
<file_sep>package v05
import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
type (
Params struct {
SwapEnabled bool `json:"swap_enabled"`
SwapDenom string `json:"swap_denom"`
ApproveBy sdk.AccAddress `json:"approve_by"`
}
)
<file_sep>package vpn
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/errors"
nodekeeper "github.com/sentinel-official/hub/x/node/keeper"
nodetypes "github.com/sentinel-official/hub/x/node/types"
plankeeper "github.com/sentinel-official/hub/x/plan/keeper"
plantypes "github.com/sentinel-official/hub/x/plan/types"
providerkeeper "github.com/sentinel-official/hub/x/provider/keeper"
providertypes "github.com/sentinel-official/hub/x/provider/types"
sessionkeeper "github.com/sentinel-official/hub/x/session/keeper"
sessiontypes "github.com/sentinel-official/hub/x/session/types"
subscriptionkeeper "github.com/sentinel-official/hub/x/subscription/keeper"
subscriptiontypes "github.com/sentinel-official/hub/x/subscription/types"
"github.com/sentinel-official/hub/x/vpn/keeper"
"github.com/sentinel-official/hub/x/vpn/types"
)
func NewHandler(k keeper.Keeper) sdk.Handler {
var (
providerServer = providerkeeper.NewMsgServiceServer(k.Provider)
nodeServer = nodekeeper.NewMsgServiceServer(k.Node)
planServer = plankeeper.NewMsgServiceServer(k.Plan)
subscriptionServer = subscriptionkeeper.NewMsgServiceServer(k.Subscription)
sessionServer = sessionkeeper.NewMsgServiceServer(k.Session)
)
return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) {
ctx = ctx.WithEventManager(sdk.NewEventManager())
switch msg := msg.(type) {
case *providertypes.MsgRegisterRequest:
res, err := providerServer.MsgRegister(sdk.WrapSDKContext(ctx), msg)
return sdk.WrapServiceResult(ctx, res, err)
case *providertypes.MsgUpdateRequest:
res, err := providerServer.MsgUpdate(sdk.WrapSDKContext(ctx), msg)
return sdk.WrapServiceResult(ctx, res, err)
case *nodetypes.MsgRegisterRequest:
res, err := nodeServer.MsgRegister(sdk.WrapSDKContext(ctx), msg)
return sdk.WrapServiceResult(ctx, res, err)
case *nodetypes.MsgUpdateRequest:
res, err := nodeServer.MsgUpdate(sdk.WrapSDKContext(ctx), msg)
return sdk.WrapServiceResult(ctx, res, err)
case *nodetypes.MsgSetStatusRequest:
res, err := nodeServer.MsgSetStatus(sdk.WrapSDKContext(ctx), msg)
return sdk.WrapServiceResult(ctx, res, err)
case *plantypes.MsgAddRequest:
res, err := planServer.MsgAdd(sdk.WrapSDKContext(ctx), msg)
return sdk.WrapServiceResult(ctx, res, err)
case *plantypes.MsgSetStatusRequest:
res, err := planServer.MsgSetStatus(sdk.WrapSDKContext(ctx), msg)
return sdk.WrapServiceResult(ctx, res, err)
case *plantypes.MsgAddNodeRequest:
res, err := planServer.MsgAddNode(sdk.WrapSDKContext(ctx), msg)
return sdk.WrapServiceResult(ctx, res, err)
case *plantypes.MsgRemoveNodeRequest:
res, err := planServer.MsgRemoveNode(sdk.WrapSDKContext(ctx), msg)
return sdk.WrapServiceResult(ctx, res, err)
case *subscriptiontypes.MsgSubscribeToPlanRequest:
res, err := subscriptionServer.MsgSubscribeToPlan(sdk.WrapSDKContext(ctx), msg)
return sdk.WrapServiceResult(ctx, res, err)
case *subscriptiontypes.MsgSubscribeToNodeRequest:
res, err := subscriptionServer.MsgSubscribeToNode(sdk.WrapSDKContext(ctx), msg)
return sdk.WrapServiceResult(ctx, res, err)
case *subscriptiontypes.MsgCancelRequest:
res, err := subscriptionServer.MsgCancel(sdk.WrapSDKContext(ctx), msg)
return sdk.WrapServiceResult(ctx, res, err)
case *subscriptiontypes.MsgAddQuotaRequest:
res, err := subscriptionServer.MsgAddQuota(sdk.WrapSDKContext(ctx), msg)
return sdk.WrapServiceResult(ctx, res, err)
case *subscriptiontypes.MsgUpdateQuotaRequest:
res, err := subscriptionServer.MsgUpdateQuota(sdk.WrapSDKContext(ctx), msg)
return sdk.WrapServiceResult(ctx, res, err)
case *sessiontypes.MsgStartRequest:
res, err := sessionServer.MsgStart(sdk.WrapSDKContext(ctx), msg)
return sdk.WrapServiceResult(ctx, res, err)
case *sessiontypes.MsgUpdateRequest:
res, err := sessionServer.MsgUpdate(sdk.WrapSDKContext(ctx), msg)
return sdk.WrapServiceResult(ctx, res, err)
case *sessiontypes.MsgEndRequest:
res, err := sessionServer.MsgEnd(sdk.WrapSDKContext(ctx), msg)
return sdk.WrapServiceResult(ctx, res, err)
default:
return nil, errors.Wrapf(types.ErrorUnknownMsgType, "%s", msg.Type())
}
}
}
<file_sep>package cmd
import (
"encoding/json"
"fmt"
"io/ioutil"
"time"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types"
evidencetypes "github.com/cosmos/cosmos-sdk/x/evidence/types"
"github.com/cosmos/cosmos-sdk/x/genutil/client/cli"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
ibctransfertypes "github.com/cosmos/cosmos-sdk/x/ibc/applications/transfer/types"
ibchost "github.com/cosmos/cosmos-sdk/x/ibc/core/24-host"
"github.com/cosmos/cosmos-sdk/x/ibc/core/exported"
ibctypes "github.com/cosmos/cosmos-sdk/x/ibc/core/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/spf13/cobra"
tmjson "github.com/tendermint/tendermint/libs/json"
tmtypes "github.com/tendermint/tendermint/types"
swaptypes "github.com/sentinel-official/hub/x/swap/types"
v05swaptypes "github.com/sentinel-official/hub/x/swap/types/legacy/v0.5"
v06swaptypes "github.com/sentinel-official/hub/x/swap/types/legacy/v0.6"
vpntypes "github.com/sentinel-official/hub/x/vpn/types"
v05vpntypes "github.com/sentinel-official/hub/x/vpn/types/legacy/v0.5"
v06vpntypes "github.com/sentinel-official/hub/x/vpn/types/legacy/v0.6"
)
const (
flagGenesisTime = "genesis-time"
flagInitialHeight = "initial-height"
)
func migrateCmd() *cobra.Command {
cmd := cobra.Command{
Use: "migrate [genesis-file]",
Short: "Migrate Genesis file from v0.5 to v0.6",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
var ctx = client.GetClientContextFromCmd(cmd)
blob, err := ioutil.ReadFile(args[0])
if err != nil {
return err
}
chainID, err := cmd.Flags().GetString(flags.FlagChainID)
if err != nil {
return err
}
genesisTime, err := cmd.Flags().GetString(flagGenesisTime)
if err != nil {
return err
}
initialHeight, err := cmd.Flags().GetInt64(flagInitialHeight)
if err != nil {
return err
}
genesis, err := tmtypes.GenesisDocFromJSON(blob)
if err != nil {
return err
}
var state genutiltypes.AppMap
if err := json.Unmarshal(genesis.AppState, &state); err != nil {
return err
}
state, err = migrateFunc(state, ctx)
if err != nil {
return err
}
var (
bankGenesis banktypes.GenesisState
stakingGenesis stakingtypes.GenesisState
vpnGenesis vpntypes.GenesisState
)
ctx.JSONMarshaler.MustUnmarshalJSON(state[banktypes.ModuleName], &bankGenesis)
ctx.JSONMarshaler.MustUnmarshalJSON(state[stakingtypes.ModuleName], &stakingGenesis)
ctx.JSONMarshaler.MustUnmarshalJSON(state[vpntypes.ModuleName], &vpnGenesis)
bankGenesis.DenomMetadata = []banktypes.Metadata{
{
Description: "The native staking token of the Sentinel Hub.",
DenomUnits: []*banktypes.DenomUnit{
{Denom: "dvpn", Exponent: uint32(6), Aliases: []string{}},
{Denom: "mdvpn", Exponent: uint32(3), Aliases: []string{"millidvpn"}},
{Denom: "udvpn", Exponent: uint32(0), Aliases: []string{"microdvpn"}},
},
Base: "udvpn",
Display: "dvpn",
},
}
stakingGenesis.Params.HistoricalEntries = 10000
vpnGenesis.Nodes.Params.InactiveDuration = 1 * time.Hour
vpnGenesis.Sessions.Params.InactiveDuration = 2 * time.Hour
vpnGenesis.Subscriptions.Params.InactiveDuration = 4 * time.Hour
var (
ibcTransferGenesis = ibctransfertypes.DefaultGenesisState()
ibcGenesis = ibctypes.DefaultGenesisState()
capabilityGenesis = capabilitytypes.DefaultGenesis()
evidenceGenesis = evidencetypes.DefaultGenesisState()
)
ibcTransferGenesis.Params.ReceiveEnabled = true
ibcTransferGenesis.Params.SendEnabled = true
ibcGenesis.ClientGenesis.Params.AllowedClients = []string{exported.Tendermint}
state[banktypes.ModuleName] = ctx.JSONMarshaler.MustMarshalJSON(&bankGenesis)
state[ibctransfertypes.ModuleName] = ctx.JSONMarshaler.MustMarshalJSON(ibcTransferGenesis)
state[ibchost.ModuleName] = ctx.JSONMarshaler.MustMarshalJSON(ibcGenesis)
state[capabilitytypes.ModuleName] = ctx.JSONMarshaler.MustMarshalJSON(capabilityGenesis)
state[evidencetypes.ModuleName] = ctx.JSONMarshaler.MustMarshalJSON(evidenceGenesis)
state[stakingtypes.ModuleName] = ctx.JSONMarshaler.MustMarshalJSON(&stakingGenesis)
state[vpntypes.ModuleName] = ctx.JSONMarshaler.MustMarshalJSON(&vpnGenesis)
genesis.AppState, err = json.Marshal(state)
if err != nil {
return err
}
if genesisTime != "" {
var t time.Time
if err := t.UnmarshalText([]byte(genesisTime)); err != nil {
return err
}
genesis.GenesisTime = t
}
if chainID != "" {
genesis.ChainID = chainID
}
genesis.InitialHeight = initialHeight
blob, err = tmjson.Marshal(genesis)
if err != nil {
return err
}
sortedBlob, err := sdk.SortJSON(blob)
if err != nil {
return err
}
fmt.Println(string(sortedBlob))
return nil
},
}
cmd.Flags().String(flags.FlagChainID, "", "set chain id")
cmd.Flags().String(flagGenesisTime, "", "set genesis time")
cmd.Flags().Int64(flagInitialHeight, 0, "set the initial height")
return &cmd
}
func migrateFunc(state genutiltypes.AppMap, ctx client.Context) (genutiltypes.AppMap, error) {
migrateFunc := cli.GetMigrationCallback("v0.40")
if migrateFunc == nil {
return nil, fmt.Errorf("sdk migration function is not available")
}
state = migrateFunc(state, ctx)
var (
swapGenesis v05swaptypes.GenesisState
vpnGenesis v05vpntypes.GenesisState
amino = codec.NewLegacyAmino()
)
amino.MustUnmarshalJSON(state[v05swaptypes.ModuleName], &swapGenesis)
amino.MustUnmarshalJSON(state[v05vpntypes.ModuleName], &vpnGenesis)
state[swaptypes.ModuleName] = ctx.JSONMarshaler.MustMarshalJSON(v06swaptypes.MigrateGenesisState(&swapGenesis))
state[vpntypes.ModuleName] = ctx.JSONMarshaler.MustMarshalJSON(v06vpntypes.MigrateGenesisState(&vpnGenesis))
return state, nil
}
<file_sep>package types
import (
"fmt"
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
params "github.com/cosmos/cosmos-sdk/x/params/types"
)
const (
DefaultInactiveDuration = 5 * time.Minute
)
var (
DefaultDeposit = sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1000))
)
var (
KeyDeposit = []byte("Deposit")
KeyInactiveDuration = []byte("InactiveDuration")
)
var (
_ params.ParamSet = (*Params)(nil)
)
func (p *Params) Validate() error {
if !p.Deposit.IsValid() {
return fmt.Errorf("deposit should be valid")
}
if p.InactiveDuration <= 0 {
return fmt.Errorf("inactive_duration should be positive")
}
return nil
}
func (p *Params) ParamSetPairs() params.ParamSetPairs {
return params.ParamSetPairs{
{
Key: KeyDeposit,
Value: &p.Deposit,
ValidatorFn: func(v interface{}) error {
value, ok := v.(sdk.Coin)
if !ok {
return fmt.Errorf("invalid parameter type %T", v)
}
if !value.IsValid() {
return fmt.Errorf("deposit value should be valid")
}
return nil
},
},
{
Key: KeyInactiveDuration,
Value: &p.InactiveDuration,
ValidatorFn: func(v interface{}) error {
value, ok := v.(time.Duration)
if !ok {
return fmt.Errorf("invalid parameter type %T", v)
}
if value <= 0 {
return fmt.Errorf("inactive duration value should be positive")
}
return nil
},
},
}
}
func NewParams(deposit sdk.Coin, inactiveDuration time.Duration) Params {
return Params{
Deposit: deposit,
InactiveDuration: inactiveDuration,
}
}
func DefaultParams() Params {
return Params{
Deposit: DefaultDeposit,
InactiveDuration: DefaultInactiveDuration,
}
}
func ParamsKeyTable() params.KeyTable {
return params.NewKeyTable().RegisterParamSet(&Params{})
}
<file_sep>package v05
type (
GenesisState struct {
Sessions Sessions `json:"_"`
Params Params `json:"params"`
}
)
<file_sep>package cli
import (
"strconv"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/tx"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/spf13/cobra"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/subscription/types"
)
func txSubscribeToPlan() *cobra.Command {
cmd := &cobra.Command{
Use: "subscribe-plan [plan] [denom]",
Short: "Subscribe to a plan",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
ctx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
id, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return err
}
msg := types.NewMsgSubscribeToPlanRequest(ctx.FromAddress, id, args[1])
if err := msg.ValidateBasic(); err != nil {
return err
}
return tx.GenerateOrBroadcastTxCLI(ctx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}
func txSubscribeToNode() *cobra.Command {
cmd := &cobra.Command{
Use: "subscribe-node [node] [deposit]",
Short: "Subscribe to a node",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
ctx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
address, err := hubtypes.NodeAddressFromBech32(args[0])
if err != nil {
return err
}
deposit, err := sdk.ParseCoinNormalized(args[1])
if err != nil {
return err
}
msg := types.NewMsgSubscribeToNodeRequest(ctx.FromAddress, address, deposit)
if err := msg.ValidateBasic(); err != nil {
return err
}
return tx.GenerateOrBroadcastTxCLI(ctx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}
func txAddQuota() *cobra.Command {
cmd := &cobra.Command{
Use: "quota-add [subscription] [address] [bytes]",
Short: "Add a quota of a subscription",
Args: cobra.ExactArgs(3),
RunE: func(cmd *cobra.Command, args []string) error {
ctx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
id, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return err
}
address, err := sdk.AccAddressFromBech32(args[1])
if err != nil {
return err
}
bytes, err := strconv.ParseInt(args[2], 10, 64)
if err != nil {
return err
}
msg := types.NewMsgAddQuotaRequest(ctx.FromAddress, id, address, sdk.NewInt(bytes))
if err := msg.ValidateBasic(); err != nil {
return err
}
return tx.GenerateOrBroadcastTxCLI(ctx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}
func txUpdateQuota() *cobra.Command {
cmd := &cobra.Command{
Use: "quota-update [subscription] [address] [bytes]",
Short: "Update a quota of a subscription",
Args: cobra.ExactArgs(3),
RunE: func(cmd *cobra.Command, args []string) error {
ctx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
id, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return err
}
address, err := sdk.AccAddressFromBech32(args[1])
if err != nil {
return err
}
bytes, err := strconv.ParseInt(args[2], 10, 64)
if err != nil {
return err
}
msg := types.NewMsgUpdateQuotaRequest(ctx.FromAddress, id, address, sdk.NewInt(bytes))
if err := msg.ValidateBasic(); err != nil {
return err
}
return tx.GenerateOrBroadcastTxCLI(ctx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}
func txCancel() *cobra.Command {
cmd := &cobra.Command{
Use: "cancel [subscription]",
Short: "Cancel a subscription",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
ctx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
id, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return err
}
msg := types.NewMsgCancelRequest(ctx.FromAddress, id)
if err := msg.ValidateBasic(); err != nil {
return err
}
return tx.GenerateOrBroadcastTxCLI(ctx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}
<file_sep>package simulation
import (
"encoding/json"
"math/rand"
"testing"
"time"
"github.com/cosmos/cosmos-sdk/codec"
cdctypes "github.com/cosmos/cosmos-sdk/codec/types"
cryptocdc "github.com/cosmos/cosmos-sdk/crypto/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
sdksimulation "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/sentinel-official/hub/x/swap/types"
"github.com/stretchr/testify/require"
)
func TestRandomizedGenesisState(t *testing.T) {
interfaceRegistry := cdctypes.NewInterfaceRegistry()
cryptocdc.RegisterInterfaces(interfaceRegistry)
cdc := codec.NewProtoCodec(interfaceRegistry)
s := rand.NewSource(1)
r := rand.New(s)
simState := &module.SimulationState{
AppParams: make(sdksimulation.AppParams),
Cdc: cdc,
Rand: r,
GenState: make(map[string]json.RawMessage),
Accounts: sdksimulation.RandomAccounts(r, 3),
InitialStake: 1000,
NumBonded: 0,
GenTimestamp: time.Time{},
UnbondTime: 0,
ParamChanges: []sdksimulation.ParamChange{},
Contents: []sdksimulation.WeightedProposalContent{},
}
RandomizedGenesisState(simState)
var swapGenesis types.GenesisState
simState.Cdc.MustUnmarshalJSON(simState.GenState[types.ModuleName], &swapGenesis)
require.Equal(t, "sent1grdunxx5jxd0ja75wt508sn6v39p70hhw53zs8", swapGenesis.Swaps[0].Receiver)
require.Equal(t, []byte{
0x62, 0x33, 0x37, 0x63, 0x34, 0x62, 0x33, 0x36, 0x32, 0x39, 0x38, 0x66, 0x32, 0x30, 0x61, 0x63, 0x37, 0x66,
0x63, 0x35, 0x64, 0x65, 0x32, 0x62, 0x34, 0x61, 0x63, 0x31, 0x31, 0x36, 0x37, 0x64, 0x37, 0x61, 0x30, 0x34,
0x34, 0x34, 0x30, 0x32, 0x61, 0x34, 0x30, 0x66, 0x32, 0x62, 0x35, 0x66, 0x31, 0x65, 0x31, 0x62, 0x62, 0x37,
0x66, 0x30, 0x65, 0x65, 0x35, 0x66, 0x36, 0x33, 0x34, 0x36,
}, swapGenesis.Swaps[0].TxHash)
require.Equal(t, sdk.Coin{Denom: "sent", Amount: sdk.NewInt(1000)}, swapGenesis.Swaps[0].Amount)
require.Equal(t, false, swapGenesis.Params.SwapEnabled)
require.Equal(t, "cxgdXhhuTSkuxK", swapGenesis.Params.SwapDenom)
}
<file_sep>package types
import (
"github.com/cosmos/cosmos-sdk/types/errors"
)
var (
ErrorMarshal = errors.Register(ModuleName, 101, "error occurred while marshalling")
ErrorUnmarshal = errors.Register(ModuleName, 102, "error occurred while unmarshalling")
ErrorUnknownMsgType = errors.Register(ModuleName, 103, "unknown message type")
ErrorUnknownQueryType = errors.Register(ModuleName, 104, "unknown query type")
ErrorInvalidFieldFrom = errors.Register(ModuleName, 105, "invalid value for field from; expected a valid address")
ErrorSwapIsDisabled = errors.Register(ModuleName, 106, "swap is disabled")
ErrorUnauthorized = errors.Register(ModuleName, 107, "unauthorized")
ErrorDuplicateSwap = errors.Register(ModuleName, 108, "duplicate swap")
ErrorInvalidFieldReceiver = errors.Register(ModuleName, 109, "invalid value for field receiver; expected a valid address")
ErrorInvalidFieldAmount = errors.Register(ModuleName, 110, "invalid value for field amount; expected a value greater than or equal to 100")
)
<file_sep>package types
import (
"fmt"
)
type (
GenesisSubscriptions []GenesisSubscription
)
func NewGenesisState(subscriptions GenesisSubscriptions, params Params) *GenesisState {
return &GenesisState{
Subscriptions: subscriptions,
Params: params,
}
}
func DefaultGenesisState() *GenesisState {
return NewGenesisState(nil, DefaultParams())
}
func ValidateGenesis(state *GenesisState) error {
if err := state.Params.Validate(); err != nil {
return err
}
for _, item := range state.Subscriptions {
if err := item.Subscription.Validate(); err != nil {
return err
}
}
subscriptions := make(map[uint64]bool)
for _, item := range state.Subscriptions {
if subscriptions[item.Subscription.Id] {
return fmt.Errorf("duplicate subscription id %d", item.Subscription.Id)
}
subscriptions[item.Subscription.Id] = true
}
for _, item := range state.Subscriptions {
for _, quota := range item.Quotas {
if err := quota.Validate(); err != nil {
return err
}
}
}
for _, item := range state.Subscriptions {
quotas := make(map[string]bool)
for _, quota := range item.Quotas {
if quotas[quota.Address] {
return fmt.Errorf("duplicate quota for subscription %d", item.Subscription.Id)
}
quotas[quota.Address] = true
}
}
return nil
}
<file_sep>package simulation
import (
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/simapp/helpers"
"github.com/cosmos/cosmos-sdk/simapp/params"
sdksimulation "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/cosmos/cosmos-sdk/x/simulation"
"github.com/sentinel-official/hub/x/swap/keeper"
types "github.com/sentinel-official/hub/x/swap/types"
"math/rand"
"github.com/cosmos/cosmos-sdk/baseapp"
sdk "github.com/cosmos/cosmos-sdk/types"
)
const OpWeightMsgSwapRequest = "op_weight_msg_swap_request"
func WeightedOperations(ap sdksimulation.AppParams, cdc codec.JSONMarshaler, k keeper.Keeper) simulation.WeightedOperations {
var weightMsgSwapRequest int
randSwapFn := func(r *rand.Rand) {
weightMsgSwapRequest = 100
}
ap.GetOrGenerate(cdc, OpWeightMsgSwapRequest, &weightMsgSwapRequest, nil, randSwapFn)
operation := simulation.NewWeightedOperation(weightMsgSwapRequest, SimulateMsgSwapRequest(k, cdc))
return simulation.WeightedOperations{operation}
}
func SimulateMsgSwapRequest(k keeper.Keeper, cdc codec.JSONMarshaler) sdksimulation.Operation {
return func(
r *rand.Rand,
app *baseapp.BaseApp,
ctx sdk.Context,
accounts []sdksimulation.Account,
chainID string,
) (sdksimulation.OperationMsg, []sdksimulation.FutureOperation, error) {
acc1, _ := sdksimulation.RandomAcc(r, accounts)
acc2, _ := sdksimulation.RandomAcc(r, accounts)
sender := k.GetAccount(ctx, acc1.Address)
receiver := k.GetAccount(ctx, acc2.Address)
hash := types.EthereumHash{}
denom := k.GetParams(ctx).SwapDenom
amount := sdksimulation.RandomAmount(r, sdk.NewInt(60<<13))
coins := sdk.Coins{
{Denom: denom, Amount: amount},
}
fees, err := sdksimulation.RandomFees(r, ctx, coins)
if err != nil {
return sdksimulation.NoOpMsg(types.ModuleName, "swap_request", err.Error()), nil, err
}
_, found := k.GetSwap(ctx, hash)
if found {
return sdksimulation.NoOpMsg(types.ModuleName, "swap_request", "swap already exists for this txn hash"), nil, nil
}
msg := types.NewMsgSwapRequest(sender.GetAddress(), hash, receiver.GetAddress(), amount)
txGen := params.MakeTestEncodingConfig().TxConfig
txn, err := helpers.GenTx(
txGen,
[]sdk.Msg{msg},
fees,
helpers.DefaultGenTxGas,
chainID,
[]uint64{sender.GetAccountNumber()},
[]uint64{sender.GetSequence()},
)
if err != nil {
return sdksimulation.NoOpMsg(types.ModuleName, "swap_request", err.Error()), nil, err
}
_, _, err = app.Deliver(txGen.TxEncoder(), txn)
if err != nil {
return sdksimulation.NoOpMsg(types.ModuleName, "swap_request", err.Error()), nil, err
}
return sdksimulation.NewOperationMsg(msg, true, ""), nil, nil
}
}
<file_sep>package node
import (
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/node/keeper"
"github.com/sentinel-official/hub/x/node/types"
)
func InitGenesis(ctx sdk.Context, k keeper.Keeper, state *types.GenesisState) {
k.SetParams(ctx, state.Params)
for _, node := range state.Nodes {
k.SetNode(ctx, node)
if node.Status.Equal(hubtypes.StatusActive) {
k.SetActiveNode(ctx, node.GetAddress())
if node.Provider != "" {
k.SetActiveNodeForProvider(ctx, node.GetProvider(), node.GetAddress())
}
k.SetInactiveNodeAt(ctx, node.StatusAt, node.GetAddress())
} else {
k.SetInactiveNode(ctx, node.GetAddress())
if node.Provider != "" {
k.SetInactiveNodeForProvider(ctx, node.GetProvider(), node.GetAddress())
}
}
}
}
func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState {
return types.NewGenesisState(k.GetNodes(ctx, 0, 0), k.GetParams(ctx))
}
<file_sep>package v05
type (
GenesisState struct {
Nodes Nodes `json:"_"`
Params Params `json:"params"`
}
)
<file_sep>package subscription
import (
sdk "github.com/cosmos/cosmos-sdk/types"
abcitypes "github.com/tendermint/tendermint/abci/types"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/subscription/keeper"
"github.com/sentinel-official/hub/x/subscription/types"
)
func EndBlock(ctx sdk.Context, k keeper.Keeper) []abcitypes.ValidatorUpdate {
var (
log = k.Logger(ctx)
inactiveDuration = k.InactiveDuration(ctx)
)
k.IterateInactiveSubscriptions(ctx, ctx.BlockTime(), func(_ int, key []byte, item types.Subscription) bool {
log.Info("inactive subscription", "key", key, "value", item)
if item.Plan == 0 {
consumed := sdk.ZeroInt()
k.IterateQuotas(ctx, item.Id, func(_ int, quota types.Quota) bool {
consumed = consumed.Add(quota.Consumed)
return false
})
amount := item.Deposit.Sub(item.Amount(consumed))
log.Info("calculated refund of subscription", "id", item.Id,
"consumed", consumed, "amount", amount)
itemOwner := item.GetOwner()
if err := k.SubtractDeposit(ctx, itemOwner, amount); err != nil {
log.Error("failed to subtract the deposit", "cause", err)
}
} else {
if item.Status.Equal(hubtypes.StatusActive) {
item.Status = hubtypes.StatusInactivePending
item.StatusAt = item.Expiry
k.SetSubscription(ctx, item)
k.DeleteInactiveSubscriptionAt(ctx, item.Expiry, item.Id)
k.SetInactiveSubscriptionAt(ctx, item.Expiry.Add(inactiveDuration), item.Id)
return false
}
}
k.DeleteInactiveSubscriptionAt(ctx, item.StatusAt.Add(inactiveDuration), item.Id)
k.IterateQuotas(ctx, item.Id, func(_ int, quota types.Quota) bool {
quotaAddress := quota.GetAddress()
k.DeleteActiveSubscriptionForAddress(ctx, quotaAddress, item.Id)
k.SetInactiveSubscriptionForAddress(ctx, quotaAddress, item.Id)
return false
})
item.Status = hubtypes.StatusInactive
item.StatusAt = ctx.BlockTime()
k.SetSubscription(ctx, item)
return false
})
return nil
}
<file_sep>package keeper
import (
"context"
"strings"
"github.com/cosmos/cosmos-sdk/store/prefix"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/query"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/session/types"
)
var (
_ types.QueryServiceServer = (*queryServer)(nil)
)
type queryServer struct {
Keeper
}
func NewQueryServiceServer(keeper Keeper) types.QueryServiceServer {
return &queryServer{Keeper: keeper}
}
func (q *queryServer) QuerySession(c context.Context, req *types.QuerySessionRequest) (*types.QuerySessionResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
ctx := sdk.UnwrapSDKContext(c)
item, found := q.GetSession(ctx, req.Id)
if !found {
return nil, status.Errorf(codes.NotFound, "session does not exist for id %d", req.Id)
}
return &types.QuerySessionResponse{Session: item}, nil
}
func (q *queryServer) QuerySessions(c context.Context, req *types.QuerySessionsRequest) (*types.QuerySessionsResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
var (
items types.Sessions
ctx = sdk.UnwrapSDKContext(c)
store = prefix.NewStore(q.Store(ctx), types.SessionKeyPrefix)
)
pagination, err := query.FilteredPaginate(store, req.Pagination, func(_, value []byte, accumulate bool) (bool, error) {
var item types.Session
if err := q.cdc.UnmarshalBinaryBare(value, &item); err != nil {
return false, err
}
if accumulate {
items = append(items, item)
}
return true, nil
})
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &types.QuerySessionsResponse{Sessions: items, Pagination: pagination}, nil
}
func (q *queryServer) QuerySessionsForSubscription(c context.Context, req *types.QuerySessionsForSubscriptionRequest) (*types.QuerySessionsForSubscriptionResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
var (
items types.Sessions
ctx = sdk.UnwrapSDKContext(c)
store = prefix.NewStore(q.Store(ctx), types.GetSessionForSubscriptionKeyPrefix(req.Id))
)
pagination, err := query.FilteredPaginate(store, req.Pagination, func(key, _ []byte, accumulate bool) (bool, error) {
item, found := q.GetSession(ctx, sdk.BigEndianToUint64(key))
if !found {
return false, nil
}
if accumulate {
items = append(items, item)
}
return true, nil
})
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &types.QuerySessionsForSubscriptionResponse{Sessions: items, Pagination: pagination}, nil
}
func (q *queryServer) QuerySessionsForNode(c context.Context, req *types.QuerySessionsForNodeRequest) (*types.QuerySessionsForNodeResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
address, err := hubtypes.NodeAddressFromBech32(req.Address)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid address %s", req.Address)
}
var (
items types.Sessions
ctx = sdk.UnwrapSDKContext(c)
store = prefix.NewStore(q.Store(ctx), types.GetSessionForNodeKeyPrefix(address))
)
pagination, err := query.FilteredPaginate(store, req.Pagination, func(key, _ []byte, accumulate bool) (bool, error) {
item, found := q.GetSession(ctx, sdk.BigEndianToUint64(key))
if !found {
return false, nil
}
if accumulate {
items = append(items, item)
}
return true, nil
})
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &types.QuerySessionsForNodeResponse{Sessions: items, Pagination: pagination}, nil
}
func (q *queryServer) QuerySessionsForAddress(c context.Context, req *types.QuerySessionsForAddressRequest) (*types.QuerySessionsForAddressResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
address, err := sdk.AccAddressFromBech32(req.Address)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid address %s", req.Address)
}
var (
items types.Sessions
pagination *query.PageResponse
ctx = sdk.UnwrapSDKContext(c)
)
if req.Status.Equal(hubtypes.StatusActive) {
store := prefix.NewStore(q.Store(ctx), types.GetActiveSessionForAddressKeyPrefix(address))
pagination, err = query.FilteredPaginate(store, req.Pagination, func(key []byte, _ []byte, accumulate bool) (bool, error) {
item, found := q.GetSession(ctx, sdk.BigEndianToUint64(key))
if !found {
return false, nil
}
if accumulate {
items = append(items, item)
}
return true, nil
})
} else if req.Status.Equal(hubtypes.StatusInactive) {
store := prefix.NewStore(q.Store(ctx), types.GetInactiveSessionForAddressKeyPrefix(address))
pagination, err = query.FilteredPaginate(store, req.Pagination, func(key []byte, _ []byte, accumulate bool) (bool, error) {
item, found := q.GetSession(ctx, sdk.BigEndianToUint64(key))
if !found {
return false, nil
}
if accumulate {
items = append(items, item)
}
return true, nil
})
} else {
// NOTE: Do not use this; less efficient; consider using active + inactive
store := prefix.NewStore(q.Store(ctx), types.SessionKeyPrefix)
pagination, err = query.FilteredPaginate(store, req.Pagination, func(_, value []byte, accumulate bool) (bool, error) {
var item types.Session
if err := q.cdc.UnmarshalBinaryBare(value, &item); err != nil {
return false, err
}
if !strings.EqualFold(item.Address, req.Address) {
return false, nil
}
if accumulate {
items = append(items, item)
}
return true, nil
})
}
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &types.QuerySessionsForAddressResponse{Sessions: items, Pagination: pagination}, nil
}
func (q *queryServer) QueryParams(c context.Context, _ *types.QueryParamsRequest) (*types.QueryParamsResponse, error) {
var (
ctx = sdk.UnwrapSDKContext(c)
params = q.GetParams(ctx)
)
return &types.QueryParamsResponse{Params: params}, nil
}
<file_sep>package types
import (
"bytes"
"encoding/json"
"fmt"
"strings"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/bech32"
"gopkg.in/yaml.v2"
)
const (
// Bech32MainPrefix defines the Bech32 prefix of an account address.
Bech32MainPrefix = "sent"
// PrefixValidator is the prefix for validator keys.
PrefixValidator = "val"
// PrefixConsensus is the prefix for consensus keys.
PrefixConsensus = "cons"
// PrefixPublic is the prefix for public keys.
PrefixPublic = "pub"
// PrefixOperator is the prefix for operator keys.
PrefixOperator = "oper"
// PrefixProvider is the prefix for provider keys.
PrefixProvider = "prov"
// PrefixNode is the prefix for node keys.
PrefixNode = "node"
// Bech32PrefixAccAddr defines the Bech32 prefix of an account address.
Bech32PrefixAccAddr = Bech32MainPrefix
// Bech32PrefixAccPub defines the Bech32 prefix of an account public key.
Bech32PrefixAccPub = Bech32MainPrefix + PrefixPublic
// Bech32PrefixValAddr defines the Bech32 prefix of a validator operator address.
Bech32PrefixValAddr = Bech32MainPrefix + PrefixValidator + PrefixOperator
// Bech32PrefixValPub defines the Bech32 prefix of a validator operator public key.
Bech32PrefixValPub = Bech32MainPrefix + PrefixValidator + PrefixOperator + PrefixPublic
// Bech32PrefixConsAddr defines the Bech32 prefix of a validator consensus address.
Bech32PrefixConsAddr = Bech32MainPrefix + PrefixValidator + PrefixConsensus
// Bech32PrefixConsPub defines the Bech32 prefix of a validator consensus public key.
Bech32PrefixConsPub = Bech32MainPrefix + PrefixValidator + PrefixConsensus + PrefixPublic
// Bech32PrefixProvAddr defines the Bech32 prefix of a provider address.
Bech32PrefixProvAddr = Bech32MainPrefix + PrefixProvider
// Bech32PrefixProvPub defines the Bech32 prefix of a provider public key.
Bech32PrefixProvPub = Bech32MainPrefix + PrefixProvider + PrefixPublic
// Bech32PrefixNodeAddr defines the Bech32 prefix of a node address.
Bech32PrefixNodeAddr = Bech32MainPrefix + PrefixNode
// Bech32PrefixNodePub defines the Bech32 prefix of a node public key.
Bech32PrefixNodePub = Bech32MainPrefix + PrefixNode + PrefixPublic
)
var (
_ sdk.Address = ProvAddress{}
_ yaml.Marshaler = ProvAddress{}
_ sdk.Address = NodeAddress{}
_ yaml.Marshaler = NodeAddress{}
)
type ProvAddress []byte
func (p ProvAddress) Equals(address sdk.Address) bool {
if p.Empty() && address == nil {
return true
}
return bytes.Equal(p.Bytes(), address.Bytes())
}
func (p ProvAddress) Empty() bool {
return bytes.Equal(p.Bytes(), ProvAddress{}.Bytes())
}
func (p ProvAddress) Bytes() []byte {
return p
}
func (p ProvAddress) String() string {
if p.Empty() {
return ""
}
s, err := bech32.ConvertAndEncode(GetConfig().GetBech32ProviderAddrPrefix(), p.Bytes())
if err != nil {
panic(err)
}
return s
}
func (p ProvAddress) Format(f fmt.State, c rune) {
switch c {
case 's':
_, _ = f.Write([]byte(p.String()))
case 'p':
_, _ = f.Write([]byte(fmt.Sprintf("%p", p)))
default:
_, _ = f.Write([]byte(fmt.Sprintf("%X", p.Bytes())))
}
}
func (p ProvAddress) Marshal() ([]byte, error) {
return p, nil
}
func (p ProvAddress) MarshalJSON() ([]byte, error) {
return json.Marshal(p.String())
}
func (p ProvAddress) MarshalYAML() (interface{}, error) {
return p.String(), nil
}
func (p *ProvAddress) Unmarshal(data []byte) error {
*p = data
return nil
}
func (p *ProvAddress) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
address, err := ProvAddressFromBech32(s)
if err != nil {
return err
}
*p = address
return nil
}
func (p *ProvAddress) UnmarshalYAML(data []byte) error {
var s string
if err := yaml.Unmarshal(data, &s); err != nil {
return err
}
address, err := ProvAddressFromBech32(s)
if err != nil {
return err
}
*p = address
return nil
}
func ProvAddressFromBech32(s string) (ProvAddress, error) {
if len(strings.TrimSpace(s)) == 0 {
return ProvAddress{}, fmt.Errorf("empty address string is not allowed")
}
bz, err := sdk.GetFromBech32(s, GetConfig().GetBech32ProviderAddrPrefix())
if err != nil {
return nil, err
}
if err = sdk.VerifyAddressFormat(bz); err != nil {
return nil, err
}
return bz, nil
}
type NodeAddress []byte
func (n NodeAddress) Equals(address sdk.Address) bool {
if n.Empty() && address == nil {
return true
}
return bytes.Equal(n.Bytes(), address.Bytes())
}
func (n NodeAddress) Empty() bool {
return bytes.Equal(n.Bytes(), NodeAddress{}.Bytes())
}
func (n NodeAddress) Bytes() []byte {
return n
}
func (n NodeAddress) String() string {
if n.Empty() {
return ""
}
s, err := bech32.ConvertAndEncode(GetConfig().GetBech32NodeAddrPrefix(), n.Bytes())
if err != nil {
panic(err)
}
return s
}
func (n NodeAddress) Format(f fmt.State, c rune) {
switch c {
case 's':
_, _ = f.Write([]byte(n.String()))
case 'p':
_, _ = f.Write([]byte(fmt.Sprintf("%p", n)))
default:
_, _ = f.Write([]byte(fmt.Sprintf("%X", n.Bytes())))
}
}
func (n NodeAddress) Marshal() ([]byte, error) {
return n, nil
}
func (n NodeAddress) MarshalJSON() ([]byte, error) {
return json.Marshal(n.String())
}
func (n NodeAddress) MarshalYAML() (interface{}, error) {
return n.String(), nil
}
func (n *NodeAddress) Unmarshal(data []byte) error {
*n = data
return nil
}
func (n *NodeAddress) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
address, err := NodeAddressFromBech32(s)
if err != nil {
return err
}
*n = address
return nil
}
func (n *NodeAddress) UnmarshalYAML(data []byte) error {
var s string
if err := yaml.Unmarshal(data, &s); err != nil {
return err
}
address, err := NodeAddressFromBech32(s)
if err != nil {
return err
}
*n = address
return nil
}
func NodeAddressFromBech32(s string) (NodeAddress, error) {
if len(strings.TrimSpace(s)) == 0 {
return NodeAddress{}, fmt.Errorf("empty address string is not allowed")
}
bz, err := sdk.GetFromBech32(s, GetConfig().GetBech32NodeAddrPrefix())
if err != nil {
return nil, err
}
if err = sdk.VerifyAddressFormat(bz); err != nil {
return nil, err
}
return bz, nil
}
<file_sep>package keeper
import (
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
)
func (k *Keeper) FundCommunityPool(ctx sdk.Context, from sdk.AccAddress, coin sdk.Coin) error {
return k.distribution.FundCommunityPool(ctx, sdk.NewCoins(coin), from)
}
func (k *Keeper) HasProvider(ctx sdk.Context, address hubtypes.ProvAddress) bool {
return k.provider.HasProvider(ctx, address)
}
func (k *Keeper) GetCountForNodeByProvider(ctx sdk.Context, p hubtypes.ProvAddress, n hubtypes.NodeAddress) uint64 {
return k.plan.GetCountForNodeByProvider(ctx, p, n)
}
<file_sep>package types
import (
"math"
sdk "github.com/cosmos/cosmos-sdk/types"
)
type PaginatedIterator struct {
index int
items []sdk.Iterator
}
func NewPaginatedIterator(items ...sdk.Iterator) *PaginatedIterator {
return &PaginatedIterator{
items: items,
}
}
func (p *PaginatedIterator) Skip(skip int64) {
if skip <= 0 {
return
}
for index, iter := range p.items {
for ; skip > 0 && iter.Valid(); iter.Next() {
skip = skip - 1
}
if skip == 0 {
p.index = index
return
}
}
}
func (p *PaginatedIterator) Limit(limit int64, iterFunc func(iter sdk.Iterator)) {
if limit <= 0 {
limit = int64(math.MaxInt64)
}
for index, iter := range p.items {
if index < p.index {
continue
}
for ; limit > 0 && iter.Valid(); iter.Next() {
iterFunc(iter)
limit = limit - 1
}
}
}
func (p *PaginatedIterator) Close() {
for _, iter := range p.items {
iter.Close()
}
}
<file_sep>package expected
import (
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
)
type AccountKeeper interface {
GetAccount(ctx sdk.Context, address sdk.AccAddress) authtypes.AccountI
}
<file_sep>package keeper
import (
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
protobuf "github.com/gogo/protobuf/types"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/subscription/types"
)
func (k *Keeper) SetCount(ctx sdk.Context, count uint64) {
key := types.CountKey
value := k.cdc.MustMarshalBinaryBare(&protobuf.UInt64Value{Value: count})
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) GetCount(ctx sdk.Context) uint64 {
store := k.Store(ctx)
key := types.CountKey
value := store.Get(key)
if value == nil {
return 0
}
var count protobuf.UInt64Value
k.cdc.MustUnmarshalBinaryBare(value, &count)
return count.GetValue()
}
func (k *Keeper) SetSubscription(ctx sdk.Context, subscription types.Subscription) {
key := types.SubscriptionKey(subscription.Id)
value := k.cdc.MustMarshalBinaryBare(&subscription)
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) GetSubscription(ctx sdk.Context, id uint64) (subscription types.Subscription, found bool) {
store := k.Store(ctx)
key := types.SubscriptionKey(id)
value := store.Get(key)
if value == nil {
return subscription, false
}
k.cdc.MustUnmarshalBinaryBare(value, &subscription)
return subscription, true
}
func (k *Keeper) GetSubscriptions(ctx sdk.Context, skip, limit int64) (items types.Subscriptions) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.SubscriptionKeyPrefix),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
var item types.Subscription
k.cdc.MustUnmarshalBinaryBare(iter.Value(), &item)
items = append(items, item)
})
return items
}
func (k *Keeper) SetSubscriptionForNode(ctx sdk.Context, address hubtypes.NodeAddress, id uint64) {
key := types.SubscriptionForNodeKey(address, id)
value := k.cdc.MustMarshalBinaryBare(&protobuf.BoolValue{Value: true})
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) HasSubscriptionForNode(ctx sdk.Context, address hubtypes.NodeAddress, id uint64) bool {
key := types.SubscriptionForNodeKey(address, id)
store := k.Store(ctx)
return store.Has(key)
}
func (k *Keeper) GetSubscriptionsForNode(ctx sdk.Context, address hubtypes.NodeAddress, skip, limit int64) (items types.Subscriptions) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.GetSubscriptionForNodeKeyPrefix(address)),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
item, _ := k.GetSubscription(ctx, types.IDFromSubscriptionForNodeKey(iter.Key()))
items = append(items, item)
})
return items
}
func (k *Keeper) SetSubscriptionForPlan(ctx sdk.Context, plan, id uint64) {
key := types.SubscriptionForPlanKey(plan, id)
value := k.cdc.MustMarshalBinaryBare(&protobuf.BoolValue{Value: true})
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) HasSubscriptionForPlan(ctx sdk.Context, plan, id uint64) bool {
key := types.SubscriptionForPlanKey(plan, id)
store := k.Store(ctx)
return store.Has(key)
}
func (k *Keeper) GetSubscriptionsForPlan(ctx sdk.Context, plan uint64, skip, limit int64) (items types.Subscriptions) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, sdk.Uint64ToBigEndian(plan)),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
item, _ := k.GetSubscription(ctx, types.IDFromSubscriptionForPlanKey(iter.Key()))
items = append(items, item)
})
return items
}
func (k *Keeper) SetActiveSubscriptionForAddress(ctx sdk.Context, address sdk.AccAddress, id uint64) {
key := types.ActiveSubscriptionForAddressKey(address, id)
value := k.cdc.MustMarshalBinaryBare(&protobuf.BoolValue{Value: true})
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) DeleteActiveSubscriptionForAddress(ctx sdk.Context, address sdk.AccAddress, id uint64) {
store := k.Store(ctx)
key := types.ActiveSubscriptionForAddressKey(address, id)
store.Delete(key)
}
func (k *Keeper) GetActiveSubscriptionsForAddress(ctx sdk.Context, address sdk.AccAddress, skip, limit int64) (items types.Subscriptions) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.GetActiveSubscriptionForAddressKeyPrefix(address)),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
item, _ := k.GetSubscription(ctx, types.IDFromStatusSubscriptionForAddressKey(iter.Key()))
items = append(items, item)
})
return items
}
func (k *Keeper) SetInactiveSubscriptionForAddress(ctx sdk.Context, address sdk.AccAddress, id uint64) {
key := types.InactiveSubscriptionForAddressKey(address, id)
value := k.cdc.MustMarshalBinaryBare(&protobuf.BoolValue{Value: true})
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) DeleteInactiveSubscriptionForAddress(ctx sdk.Context, address sdk.AccAddress, id uint64) {
store := k.Store(ctx)
key := types.InactiveSubscriptionForAddressKey(address, id)
store.Delete(key)
}
func (k *Keeper) GetInactiveSubscriptionsForAddress(ctx sdk.Context, address sdk.AccAddress, skip, limit int64) (items types.Subscriptions) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.GetInactiveSubscriptionForAddressKeyPrefix(address)),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
item, _ := k.GetSubscription(ctx, types.IDFromStatusSubscriptionForAddressKey(iter.Key()))
items = append(items, item)
})
return items
}
func (k *Keeper) GetSubscriptionsForAddress(ctx sdk.Context, address sdk.AccAddress, skip, limit int64) (items types.Subscriptions) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.GetActiveSubscriptionForAddressKeyPrefix(address)),
sdk.KVStorePrefixIterator(store, types.GetInactiveSubscriptionForAddressKeyPrefix(address)),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
item, _ := k.GetSubscription(ctx, types.IDFromStatusSubscriptionForAddressKey(iter.Key()))
items = append(items, item)
})
return items
}
func (k *Keeper) SetInactiveSubscriptionAt(ctx sdk.Context, at time.Time, id uint64) {
key := types.InactiveSubscriptionAtKey(at, id)
value := k.cdc.MustMarshalBinaryBare(&protobuf.BoolValue{Value: true})
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) DeleteInactiveSubscriptionAt(ctx sdk.Context, at time.Time, id uint64) {
key := types.InactiveSubscriptionAtKey(at, id)
store := k.Store(ctx)
store.Delete(key)
}
func (k *Keeper) IterateInactiveSubscriptions(ctx sdk.Context, end time.Time, fn func(index int, key []byte, item types.Subscription) (stop bool)) {
store := k.Store(ctx)
iter := store.Iterator(types.InactiveSubscriptionAtKeyPrefix, sdk.PrefixEndBytes(types.GetInactiveSubscriptionAtKeyPrefix(end)))
defer iter.Close()
for i := 0; iter.Valid(); iter.Next() {
var (
key = iter.Key()
subscription, _ = k.GetSubscription(ctx, types.IDFromInactiveSubscriptionAtKey(key))
)
if stop := fn(i, key, subscription); stop {
break
}
i++
}
}
<file_sep>package types
import (
"fmt"
deposittypes "github.com/sentinel-official/hub/x/deposit/types"
nodetypes "github.com/sentinel-official/hub/x/node/types"
plantypes "github.com/sentinel-official/hub/x/plan/types"
providertypes "github.com/sentinel-official/hub/x/provider/types"
sessiontypes "github.com/sentinel-official/hub/x/session/types"
subscriptiontypes "github.com/sentinel-official/hub/x/subscription/types"
)
func init() {
nodetypes.ParamsSubspace = fmt.Sprintf("%s/%s", ModuleName, nodetypes.ModuleName)
subscriptiontypes.ParamsSubspace = fmt.Sprintf("%s/%s", ModuleName, subscriptiontypes.ModuleName)
sessiontypes.ParamsSubspace = fmt.Sprintf("%s/%s", ModuleName, sessiontypes.ModuleName)
deposittypes.RouterKey = ModuleName
providertypes.RouterKey = ModuleName
nodetypes.RouterKey = ModuleName
plantypes.RouterKey = ModuleName
subscriptiontypes.RouterKey = ModuleName
sessiontypes.RouterKey = ModuleName
deposittypes.StoreKey = ModuleName
providertypes.StoreKey = ModuleName
nodetypes.StoreKey = ModuleName
plantypes.StoreKey = ModuleName
subscriptiontypes.StoreKey = ModuleName
sessiontypes.StoreKey = ModuleName
}
<file_sep>package types
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
params "github.com/cosmos/cosmos-sdk/x/params/types"
)
var (
DefaultDeposit = sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1000))
)
var (
KeyDeposit = []byte("Deposit")
)
var (
_ params.ParamSet = (*Params)(nil)
)
func (p *Params) Validate() error {
if !p.Deposit.IsValid() {
return fmt.Errorf("deposit should be valid")
}
return nil
}
func (p *Params) ParamSetPairs() params.ParamSetPairs {
return params.ParamSetPairs{
{
Key: KeyDeposit,
Value: &p.Deposit,
ValidatorFn: func(_ interface{}) error {
return nil
},
},
}
}
func NewParams(deposit sdk.Coin) Params {
return Params{
Deposit: deposit,
}
}
func DefaultParams() Params {
return Params{
Deposit: DefaultDeposit,
}
}
func ParamsKeyTable() params.KeyTable {
return params.NewKeyTable().RegisterParamSet(&Params{})
}
<file_sep>package keeper
import (
"context"
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/session/types"
)
var (
_ types.MsgServiceServer = (*msgServer)(nil)
)
type msgServer struct {
Keeper
}
func NewMsgServiceServer(keeper Keeper) types.MsgServiceServer {
return &msgServer{Keeper: keeper}
}
func (k *msgServer) MsgStart(c context.Context, msg *types.MsgStartRequest) (*types.MsgStartResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
msgFrom, err := sdk.AccAddressFromBech32(msg.From)
if err != nil {
return nil, err
}
subscription, found := k.GetSubscription(ctx, msg.Id)
if !found {
return nil, types.ErrorSubscriptionDoesNotExit
}
if !subscription.Status.Equal(hubtypes.StatusActive) {
return nil, types.ErrorInvalidSubscriptionStatus
}
msgNode, err := hubtypes.NodeAddressFromBech32(msg.Node)
if err != nil {
return nil, err
}
node, found := k.GetNode(ctx, msgNode)
if !found {
return nil, types.ErrorNodeDoesNotExist
}
if !node.Status.Equal(hubtypes.StatusActive) {
return nil, types.ErrorInvalidNodeStatus
}
if subscription.Plan == 0 {
if node.Address != subscription.Node {
return nil, types.ErrorNodeAddressMismatch
}
} else {
if k.HasNodeForPlan(ctx, subscription.Plan, msgNode) {
return nil, types.ErrorNodeDoesNotExistForPlan
}
}
quota, found := k.GetQuota(ctx, subscription.Id, msgFrom)
if !found {
return nil, types.ErrorQuotaDoesNotExist
}
if quota.Consumed.GTE(quota.Allocated) {
return nil, types.ErrorNotEnoughQuota
}
items := k.GetActiveSessionsForAddress(ctx, msgFrom, 0, 1)
if len(items) > 0 {
return nil, types.ErrorDuplicateSession
}
var (
count = k.GetCount(ctx)
session = types.Session{
Id: count + 1,
Subscription: subscription.Id,
Node: node.Address,
Address: msg.From,
Duration: 0,
Bandwidth: hubtypes.NewBandwidthFromInt64(0, 0),
Status: hubtypes.StatusActive,
StatusAt: ctx.BlockTime(),
}
sessionNode = session.GetNode()
sessionAddress = session.GetAddress()
)
k.SetCount(ctx, count+1)
ctx.EventManager().EmitTypedEvent(
&types.EventSetSessionCount{
Count: count + 1,
},
)
k.SetSession(ctx, session)
k.SetSessionForSubscription(ctx, session.Subscription, session.Id)
k.SetSessionForNode(ctx, sessionNode, session.Id)
k.SetActiveSessionForAddress(ctx, sessionAddress, session.Id)
k.SetActiveSessionAt(ctx, session.StatusAt, session.Id)
ctx.EventManager().EmitTypedEvent(
&types.EventStartSession{
From: sdk.AccAddress(msgFrom.Bytes()).String(),
Id: session.Id,
Subscription: session.Subscription,
Node: session.Node,
},
)
ctx.EventManager().EmitTypedEvent(&types.EventModuleName)
return &types.MsgStartResponse{}, nil
}
func (k *msgServer) MsgUpdate(c context.Context, msg *types.MsgUpdateRequest) (*types.MsgUpdateResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
msgFrom, err := hubtypes.NodeAddressFromBech32(msg.From)
if err != nil {
return nil, err
}
session, found := k.GetSession(ctx, msg.Proof.Id)
if !found {
return nil, types.ErrorSessionDoesNotExist
}
if !session.Status.Equal(hubtypes.StatusActive) {
return nil, types.ErrorInvalidSessionStatus
}
if msg.From != session.Node {
return nil, types.ErrorUnauthorized
}
if k.ProofVerificationEnabled(ctx) {
sessionAddress := session.GetAddress()
if err := k.VerifyProof(ctx, sessionAddress, msg.Proof, msg.Signature); err != nil {
return nil, types.ErrorFailedToVerifyProof
}
}
k.DeleteActiveSessionAt(ctx, session.StatusAt, session.Id)
session.Duration = msg.Proof.Duration
session.Bandwidth = msg.Proof.Bandwidth
session.StatusAt = ctx.BlockTime()
k.SetSession(ctx, session)
k.SetActiveSessionAt(ctx, session.StatusAt, session.Id)
ctx.EventManager().EmitTypedEvent(
&types.EventUpdateSession{
From: sdk.AccAddress(msgFrom.Bytes()).String(),
Id: session.Id,
Subscription: session.Subscription,
Node: session.Node,
Address: session.Address,
Duration: session.Duration,
Bandwidth: session.Bandwidth,
},
)
ctx.EventManager().EmitTypedEvent(&types.EventModuleName)
return &types.MsgUpdateResponse{}, nil
}
func (k *msgServer) MsgEnd(c context.Context, msg *types.MsgEndRequest) (*types.MsgEndResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
msgFrom, err := sdk.AccAddressFromBech32(msg.From)
if err != nil {
return nil, err
}
session, found := k.GetSession(ctx, msg.Id)
if !found {
return nil, types.ErrorSessionDoesNotExist
}
if !session.Status.Equal(hubtypes.StatusActive) {
return nil, types.ErrorInvalidSessionStatus
}
if msg.From != session.Address {
return nil, types.ErrorUnauthorized
}
if err := k.ProcessPaymentAndUpdateQuota(ctx, session); err != nil {
return nil, err
}
k.DeleteActiveSessionForAddress(ctx, msgFrom, session.Id)
k.DeleteActiveSessionAt(ctx, session.StatusAt, session.Id)
session.Status = hubtypes.StatusInactive
session.StatusAt = ctx.BlockTime()
k.SetSession(ctx, session)
k.SetInactiveSessionForAddress(ctx, msgFrom, session.Id)
ctx.EventManager().EmitTypedEvent(
&types.EventEndSession{
From: sdk.AccAddress(msgFrom.Bytes()).String(),
Id: session.Id,
Subscription: session.Subscription,
Node: session.Node,
},
)
ctx.EventManager().EmitTypedEvent(&types.EventModuleName)
return &types.MsgEndResponse{}, nil
}
<file_sep>package v06
import (
hubtypes "github.com/sentinel-official/hub/types/legacy/v0.6"
"github.com/sentinel-official/hub/x/subscription/types"
legacy "github.com/sentinel-official/hub/x/subscription/types/legacy/v0.5"
)
func MigrateSubscription(item legacy.Subscription) types.Subscription {
return types.Subscription{
Id: item.ID,
Owner: item.Owner.String(),
Node: item.Node.String(),
Price: item.Price,
Deposit: item.Deposit,
Plan: item.Plan,
Denom: "",
Expiry: item.Expiry,
Free: item.Free,
Status: hubtypes.MigrateStatus(item.Status),
StatusAt: item.StatusAt,
}
}
func MigrateSubscriptions(items legacy.Subscriptions) types.Subscriptions {
var subscriptions types.Subscriptions
for _, item := range items {
subscriptions = append(subscriptions, MigrateSubscription(item))
}
return subscriptions
}
<file_sep>package simulation
import (
"math/rand"
"testing"
"github.com/stretchr/testify/require"
)
func TestParamChanges(t *testing.T) {
s := rand.NewSource(1)
r := rand.New(s)
tests := []struct {
composedKey string
key string
simValue string
subspace string
}{
{"swap/SwapDenom", "SwapDenom", "<KEY>", "swap"},
{"swap/SwapEnabled", "SwapEnabled", "true", "swap"},
{"swap/ApproveBy", "ApproveBy", "<KEY>", "swap"},
}
paramChanges := ParamChanges(r)
for i, tt := range paramChanges {
require.Equal(t, tests[i].composedKey, tt.ComposedKey())
require.Equal(t, tests[i].key, tt.Key())
require.Equal(t, tests[i].simValue, tt.SimValue()(r))
require.Equal(t, tests[i].subspace, tt.Subspace())
}
}
<file_sep>package expected
import (
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
)
type AccountKeeper interface {
GetAccount(ctx sdk.Context, address sdk.AccAddress) authtypes.AccountI
}
type DistributionKeeper interface {
FundCommunityPool(ctx sdk.Context, amount sdk.Coins, sender sdk.AccAddress) error
}
<file_sep>package session
import (
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
"github.com/sentinel-official/hub/x/session/keeper"
"github.com/sentinel-official/hub/x/session/types"
)
func InitGenesis(ctx sdk.Context, k keeper.Keeper, state *types.GenesisState) {
k.SetParams(ctx, state.Params)
for _, session := range state.Sessions {
var (
sessionNode = session.GetNode()
sessionAddress = session.GetAddress()
)
k.SetSession(ctx, session)
k.SetSessionForSubscription(ctx, session.Subscription, session.Id)
k.SetSessionForNode(ctx, sessionNode, session.Id)
if session.Status.Equal(hubtypes.StatusActive) {
k.SetActiveSessionForAddress(ctx, sessionAddress, session.Id)
k.SetActiveSessionAt(ctx, session.StatusAt, session.Id)
} else {
k.SetInactiveSessionForAddress(ctx, sessionAddress, session.Id)
}
}
k.SetCount(ctx, uint64(len(state.Sessions)))
}
func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState {
return types.NewGenesisState(
k.GetSessions(ctx, 0, 0),
k.GetParams(ctx),
)
}
<file_sep>package v05
import (
deposit "github.com/sentinel-official/hub/x/deposit/types/legacy/v0.5"
node "github.com/sentinel-official/hub/x/node/types/legacy/v0.5"
plan "github.com/sentinel-official/hub/x/plan/types/legacy/v0.5"
provider "github.com/sentinel-official/hub/x/provider/types/legacy/v0.5"
session "github.com/sentinel-official/hub/x/session/types/legacy/v0.5"
subscription "github.com/sentinel-official/hub/x/subscription/types/legacy/v0.5"
)
type (
GenesisState struct {
Deposits deposit.GenesisState `json:"deposits"`
Providers *provider.GenesisState `json:"providers"`
Nodes *node.GenesisState `json:"nodes"`
Plans plan.GenesisState `json:"plans"`
Subscriptions *subscription.GenesisState `json:"subscriptions"`
Sessions *session.GenesisState `json:"sessions"`
}
)
<file_sep>package types
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
)
func (s *Subscription) GetNode() hubtypes.NodeAddress {
if s.Node == "" {
return nil
}
address, err := hubtypes.NodeAddressFromBech32(s.Node)
if err != nil {
panic(err)
}
return address
}
func (s *Subscription) GetOwner() sdk.AccAddress {
if s.Owner == "" {
return nil
}
address, err := sdk.AccAddressFromBech32(s.Owner)
if err != nil {
panic(err)
}
return address
}
func (s *Subscription) Amount(consumed sdk.Int) sdk.Coin {
var (
amount sdk.Int
x = hubtypes.Gigabyte.Quo(s.Price.Amount)
)
if x.IsPositive() {
amount = hubtypes.NewBandwidth(consumed, sdk.ZeroInt()).
CeilTo(x).
Sum().Quo(x)
} else {
y := sdk.NewDecFromInt(s.Price.Amount).
QuoInt(hubtypes.Gigabyte).
Ceil().TruncateInt()
amount = consumed.Mul(y)
}
return sdk.NewCoin(s.Price.Denom, amount)
}
func (s *Subscription) Validate() error {
if s.Id == 0 {
return fmt.Errorf("id should not be zero")
}
if _, err := sdk.AccAddressFromBech32(s.Owner); err != nil {
return fmt.Errorf("owner should not nil or empty")
}
if s.Plan == 0 {
if _, err := hubtypes.NodeAddressFromBech32(s.Node); err != nil {
return fmt.Errorf("node should not be nil or empty")
}
if !s.Price.IsValid() {
return fmt.Errorf("price should be valid")
}
if !s.Deposit.IsValid() {
return fmt.Errorf("deposit should be valid")
}
} else {
if s.Expiry.IsZero() {
return fmt.Errorf("expiry should not be zero")
}
}
if s.Free.IsNegative() {
return fmt.Errorf("free should not be negative")
}
if !s.Status.IsValid() {
return fmt.Errorf("status should be valid")
}
if s.StatusAt.IsZero() {
return fmt.Errorf("status_at should not be zero")
}
return nil
}
type Subscriptions []Subscription
<file_sep>package types
import (
"errors"
"strings"
"testing"
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
)
var (
GT64 = strings.Repeat("sentinel", 9)
)
func TestMsgRegisterRequest_ValidateBasic(t *testing.T) {
correctAddress, err := sdk.AccAddressFromBech32("sent1grdunxx5jxd0ja75wt508sn6v39p70hhw53zs8")
if err != nil {
t.Errorf("invalid address: %s", err)
}
wrongProvider := hubtypes.ProvAddress(correctAddress.String())
correctCoins := sdk.NewCoins(sdk.Coin{
Denom: "sent",
Amount: sdk.NewInt(10),
})
wrongCoins := sdk.Coins{sdk.Coin{Denom: "--!sent--!", Amount: sdk.NewInt(-1)}}
tests := []struct {
name string
m *MsgRegisterRequest
want error
}{
{"nil from address", NewMsgRegisterRequest(nil, nil, sdk.Coins{}, ""), ErrorInvalidFieldFrom},
{"empty from address", NewMsgRegisterRequest(sdk.AccAddress{}, nil, sdk.Coins{}, ""), ErrorInvalidFieldFrom},
{"nil provider and price", NewMsgRegisterRequest(correctAddress, nil, nil, ""), ErrorInvalidFieldProviderOrPrice},
{"empty provider and nil price", NewMsgRegisterRequest(correctAddress, hubtypes.ProvAddress{}, nil, ""), ErrorInvalidFieldProviderOrPrice},
{"invalid provider", NewMsgRegisterRequest(correctAddress, wrongProvider, nil, ""), ErrorInvalidFieldProvider},
{"wrong price", NewMsgRegisterRequest(correctAddress, hubtypes.ProvAddress{}, wrongCoins, ""), ErrorInvalidFieldPrice},
{"empty remote_url", NewMsgRegisterRequest(correctAddress, nil, correctCoins, ""), ErrorInvalidFieldRemoteURL},
{"remote_url GT64", NewMsgRegisterRequest(correctAddress, nil, correctCoins, GT64), ErrorInvalidFieldRemoteURL},
{"valid", NewMsgRegisterRequest(correctAddress, nil, correctCoins, "https://sentinel.co"), nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := tt.m.ValidateBasic(); !errors.Is(err, tt.want) {
t.Errorf("ValidateBasic() = %s, want %s", err, tt.want)
}
})
}
}
func TestMsgUpdateRequest_ValidateBasic(t *testing.T) {
nodeAddress, err := hubtypes.NodeAddressFromBech32("sentnode1grdunxx5jxd0ja75wt508sn6v39p70hhczsm43")
if err != nil {
t.Errorf("invalid provider address: %s", err)
}
provAddress, err := hubtypes.ProvAddressFromBech32("sentprov1grdunxx5jxd0ja75wt508sn6v39p70hhxrdetl")
if err != nil {
t.Errorf("invalid provider address: %s", err)
}
wrongProvAddress := hubtypes.ProvAddress("sentwrongprov1grdunxx5jxd0ja75wt508sn6v39p70hhxrdetl")
correctCoins := sdk.NewCoins(sdk.Coin{
Denom: "sent",
Amount: sdk.NewInt(10),
})
wrongCoins := sdk.Coins{sdk.Coin{Denom: "--!sent--!", Amount: sdk.NewInt(-1)}}
tests := []struct {
name string
m *MsgUpdateRequest
want error
}{
{"nil from address", NewMsgUpdateRequest(nil, nil, sdk.Coins{}, ""), ErrorInvalidFieldFrom},
{"empty from address", NewMsgUpdateRequest(hubtypes.NodeAddress{}, nil, sdk.Coins{}, ""), ErrorInvalidFieldFrom},
{"non-empty provider and price", NewMsgUpdateRequest(nodeAddress, provAddress, correctCoins, ""), ErrorInvalidFieldProviderOrPrice},
{"wrong provider", NewMsgUpdateRequest(nodeAddress, wrongProvAddress, nil, ""), ErrorInvalidFieldProvider},
{"wrong price", NewMsgUpdateRequest(nodeAddress, hubtypes.ProvAddress{}, wrongCoins, ""), ErrorInvalidFieldPrice},
{"remote_url GT64", NewMsgUpdateRequest(nodeAddress, hubtypes.ProvAddress{}, correctCoins, GT64), ErrorInvalidFieldRemoteURL},
{"valid", NewMsgUpdateRequest(nodeAddress, hubtypes.ProvAddress{}, correctCoins, "https://sentinel.co"), nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := tt.m.ValidateBasic(); !errors.Is(err, tt.want) {
t.Errorf("ValidateBasic() = %s, want %s", err, tt.want)
}
})
}
}
func TestMsgSetStatusRequest_ValidateBasic(t *testing.T) {
nodeAddress, err := hubtypes.NodeAddressFromBech32("sentnode1grdunxx5jxd0ja75wt508sn6v39p70hhczsm43")
if err != nil {
t.Errorf("invalid provider address: %s", err)
}
status := hubtypes.StatusInactivePending
tests := []struct {
name string
m *MsgSetStatusRequest
want error
}{
{"nil from address", NewMsgSetStatusRequest(nil, status), ErrorInvalidFieldFrom},
{"empty from address", NewMsgSetStatusRequest(hubtypes.NodeAddress{}, status), ErrorInvalidFieldFrom},
{"wrong status", NewMsgSetStatusRequest(nodeAddress, status), ErrorInvalidFieldStatus},
{"valid", NewMsgSetStatusRequest(nodeAddress, hubtypes.Active), nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := tt.m.ValidateBasic(); !errors.Is(err, tt.want) {
t.Errorf("ValidateBasic() = %s, want %s", err, tt.want)
}
})
}
}
<file_sep>package types
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
)
var (
_ sdk.Msg = (*MsgRegisterRequest)(nil)
_ sdk.Msg = (*MsgUpdateRequest)(nil)
_ sdk.Msg = (*MsgSetStatusRequest)(nil)
)
func NewMsgRegisterRequest(from sdk.AccAddress, provider hubtypes.ProvAddress, price sdk.Coins, remoteURL string) *MsgRegisterRequest {
return &MsgRegisterRequest{
From: from.String(),
Provider: provider.String(),
Price: price,
RemoteURL: remoteURL,
}
}
func (m *MsgRegisterRequest) Route() string {
return RouterKey
}
func (m *MsgRegisterRequest) Type() string {
return fmt.Sprintf("%s:register", ModuleName)
}
func (m *MsgRegisterRequest) ValidateBasic() error {
if _, err := sdk.AccAddressFromBech32(m.From); err != nil {
return ErrorInvalidFieldFrom
}
// Either provider or price should be empty
if (m.Provider != "" && m.Price != nil) ||
(m.Provider == "" && m.Price == nil) {
return ErrorInvalidFieldProviderOrPrice
}
// Provider can be empty. If not, it should be valid
if m.Provider != "" {
if _, err := hubtypes.ProvAddressFromBech32(m.Provider); err != nil {
return ErrorInvalidFieldProvider
}
}
// Price can be nil. If not, it should be valid
if m.Price != nil && !m.Price.IsValid() {
return ErrorInvalidFieldPrice
}
// RemoteURL length should be between 1 and 64
if len(m.RemoteURL) == 0 || len(m.RemoteURL) > 64 {
return ErrorInvalidFieldRemoteURL
}
return nil
}
func (m *MsgRegisterRequest) GetSignBytes() []byte {
return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(m))
}
func (m *MsgRegisterRequest) GetSigners() []sdk.AccAddress {
from, err := sdk.AccAddressFromBech32(m.From)
if err != nil {
panic(err)
}
return []sdk.AccAddress{from}
}
func NewMsgUpdateRequest(from hubtypes.NodeAddress, provider hubtypes.ProvAddress, price sdk.Coins, remoteURL string) *MsgUpdateRequest {
return &MsgUpdateRequest{
From: from.String(),
Provider: provider.String(),
Price: price,
RemoteURL: remoteURL,
}
}
func (m *MsgUpdateRequest) Route() string {
return RouterKey
}
func (m *MsgUpdateRequest) Type() string {
return fmt.Sprintf("%s:update", ModuleName)
}
func (m *MsgUpdateRequest) ValidateBasic() error {
if _, err := hubtypes.NodeAddressFromBech32(m.From); err != nil {
return ErrorInvalidFieldFrom
}
if m.Provider != "" && m.Price != nil {
return ErrorInvalidFieldProviderOrPrice
}
// Provider can be empty. If not, it should be valid
if m.Provider != "" {
if _, err := hubtypes.ProvAddressFromBech32(m.Provider); err != nil {
return ErrorInvalidFieldProvider
}
}
// Price can be nil. If not, it should be valid
if m.Price != nil && !m.Price.IsValid() {
return ErrorInvalidFieldPrice
}
// RemoteURL length should be between 0 and 64
if len(m.RemoteURL) > 64 {
return ErrorInvalidFieldRemoteURL
}
return nil
}
func (m *MsgUpdateRequest) GetSignBytes() []byte {
return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(m))
}
func (m *MsgUpdateRequest) GetSigners() []sdk.AccAddress {
from, err := hubtypes.NodeAddressFromBech32(m.From)
if err != nil {
panic(err)
}
return []sdk.AccAddress{from.Bytes()}
}
func NewMsgSetStatusRequest(from hubtypes.NodeAddress, status hubtypes.Status) *MsgSetStatusRequest {
return &MsgSetStatusRequest{
From: from.String(),
Status: status,
}
}
func (m *MsgSetStatusRequest) Route() string {
return RouterKey
}
func (m *MsgSetStatusRequest) Type() string {
return fmt.Sprintf("%s:set_status", ModuleName)
}
func (m *MsgSetStatusRequest) ValidateBasic() error {
if _, err := hubtypes.NodeAddressFromBech32(m.From); err != nil {
return ErrorInvalidFieldFrom
}
// Status should be either Active or Inactive
if !m.Status.Equal(hubtypes.StatusActive) && !m.Status.Equal(hubtypes.StatusInactive) {
return ErrorInvalidFieldStatus
}
return nil
}
func (m *MsgSetStatusRequest) GetSignBytes() []byte {
return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(m))
}
func (m *MsgSetStatusRequest) GetSigners() []sdk.AccAddress {
from, err := hubtypes.NodeAddressFromBech32(m.From)
if err != nil {
panic(err)
}
return []sdk.AccAddress{from.Bytes()}
}
<file_sep>package types
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/query"
hubtypes "github.com/sentinel-official/hub/types"
)
func NewQuerySessionRequest(id uint64) *QuerySessionRequest {
return &QuerySessionRequest{
Id: id,
}
}
func NewQuerySessionsRequest(pagination *query.PageRequest) *QuerySessionsRequest {
return &QuerySessionsRequest{
Pagination: pagination,
}
}
func NewQuerySessionsForSubscriptionRequest(id uint64, pagination *query.PageRequest) *QuerySessionsForSubscriptionRequest {
return &QuerySessionsForSubscriptionRequest{
Id: id,
Pagination: pagination,
}
}
func NewQuerySessionsForNodeRequest(address hubtypes.NodeAddress, pagination *query.PageRequest) *QuerySessionsForNodeRequest {
return &QuerySessionsForNodeRequest{
Address: address.String(),
Pagination: pagination,
}
}
func NewQuerySessionsForAddressRequest(address sdk.AccAddress, status hubtypes.Status, pagination *query.PageRequest) *QuerySessionsForAddressRequest {
return &QuerySessionsForAddressRequest{
Address: address.String(),
Status: status,
Pagination: pagination,
}
}
func NewQueryParamsRequest() *QueryParamsRequest {
return &QueryParamsRequest{}
}
<file_sep>package v06
import (
"github.com/sentinel-official/hub/x/provider/types"
legacy "github.com/sentinel-official/hub/x/provider/types/legacy/v0.5"
)
func MigrateParams(params legacy.Params) types.Params {
return types.NewParams(
params.Deposit,
)
}
<file_sep>package keeper
import (
sdk "github.com/cosmos/cosmos-sdk/types"
protobuf "github.com/gogo/protobuf/types"
hubtypes "github.com/sentinel-official/hub/types"
nodetypes "github.com/sentinel-official/hub/x/node/types"
"github.com/sentinel-official/hub/x/plan/types"
)
func (k *Keeper) SetNodeForPlan(ctx sdk.Context, id uint64, address hubtypes.NodeAddress) {
key := types.NodeForPlanKey(id, address)
value := k.cdc.MustMarshalBinaryBare(&protobuf.BoolValue{Value: true})
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) HasNodeForPlan(ctx sdk.Context, id uint64, address hubtypes.NodeAddress) bool {
store := k.Store(ctx)
key := types.NodeForPlanKey(id, address)
return store.Has(key)
}
func (k *Keeper) DeleteNodeForPlan(ctx sdk.Context, id uint64, address hubtypes.NodeAddress) {
store := k.Store(ctx)
key := types.NodeForPlanKey(id, address)
store.Delete(key)
}
func (k *Keeper) GetNodesForPlan(ctx sdk.Context, id uint64, skip, limit int64) (items nodetypes.Nodes) {
var (
store = k.Store(ctx)
iter = hubtypes.NewPaginatedIterator(
sdk.KVStorePrefixIterator(store, types.GetNodeForPlanKeyPrefix(id)),
)
)
defer iter.Close()
iter.Skip(skip)
iter.Limit(limit, func(iter sdk.Iterator) {
item, _ := k.GetNode(ctx, types.AddressFromNodeForPlanKey(iter.Key()))
items = append(items, item)
})
return items
}
func (k *Keeper) SetCountForNodeByProvider(ctx sdk.Context, p hubtypes.ProvAddress, n hubtypes.NodeAddress, count uint64) {
key := types.CountForNodeByProviderKey(p, n)
value := k.cdc.MustMarshalBinaryBare(&protobuf.UInt64Value{Value: count})
store := k.Store(ctx)
store.Set(key, value)
}
func (k *Keeper) GetCountForNodeByProvider(ctx sdk.Context, p hubtypes.ProvAddress, n hubtypes.NodeAddress) uint64 {
store := k.Store(ctx)
key := types.CountForNodeByProviderKey(p, n)
value := store.Get(key)
if value == nil {
return 0
}
var count protobuf.UInt64Value
k.cdc.MustUnmarshalBinaryBare(value, &count)
return count.GetValue()
}
func (k *Keeper) IncreaseCountForNodeByProvider(ctx sdk.Context, p hubtypes.ProvAddress, n hubtypes.NodeAddress) {
k.SetCountForNodeByProvider(ctx, p, n, k.GetCountForNodeByProvider(ctx, p, n)+1)
}
func (k *Keeper) DecreaseCountForNodeByProvider(ctx sdk.Context, p hubtypes.ProvAddress, n hubtypes.NodeAddress) {
k.SetCountForNodeByProvider(ctx, p, n, k.GetCountForNodeByProvider(ctx, p, n)-1)
}
<file_sep>package types
const (
StatusUnknown Status = iota
StatusActive
StatusInactivePending
StatusInactive
)
func StatusFromString(s string) Status {
switch s {
case "Active":
return StatusActive
case "InactivePending":
return StatusInactivePending
case "Inactive":
return StatusInactive
default:
return StatusUnknown
}
}
func (s Status) IsValid() bool {
return s == StatusActive ||
s == StatusInactivePending ||
s == StatusInactive
}
func (s Status) Equal(v Status) bool {
return s == v
}
<file_sep>package keeper
import (
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
nodetypes "github.com/sentinel-official/hub/x/node/types"
plantypes "github.com/sentinel-official/hub/x/plan/types"
)
func (k *Keeper) SendCoin(ctx sdk.Context, from sdk.AccAddress, to sdk.AccAddress, coin sdk.Coin) error {
return k.bank.SendCoins(ctx, from, to, sdk.NewCoins(coin))
}
func (k *Keeper) AddDeposit(ctx sdk.Context, address sdk.AccAddress, coin sdk.Coin) error {
return k.deposit.Add(ctx, address, sdk.NewCoins(coin))
}
func (k *Keeper) SubtractDeposit(ctx sdk.Context, address sdk.AccAddress, coin sdk.Coin) error {
if coin.IsZero() {
return nil
}
return k.deposit.Subtract(ctx, address, sdk.NewCoins(coin))
}
func (k *Keeper) GetNode(ctx sdk.Context, address hubtypes.NodeAddress) (nodetypes.Node, bool) {
return k.node.GetNode(ctx, address)
}
func (k *Keeper) GetPlan(ctx sdk.Context, id uint64) (plantypes.Plan, bool) {
return k.plan.GetPlan(ctx, id)
}
<file_sep>package simulation
import (
"encoding/json"
"fmt"
"math/rand"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/sentinel-official/hub/x/swap/types"
)
func GetRandomSwapDenom(r *rand.Rand) string {
// denom length should be between 3-128
return simulation.RandStringOfLength(r, r.Intn(125)+3)
}
func GetRandomApproveBy(r *rand.Rand) string {
bz := make([]byte, 20)
_, err := r.Read(bz)
if err != nil {
panic(err)
}
return sdk.AccAddress(bz).String()
}
func GetRandomSwapEnabled(r *rand.Rand) bool {
return r.Intn(2) == 1
}
func RandomizedGenesisState(simState *module.SimulationState) {
var (
swapEnabled bool
approveBy string
swapDenom string
)
swapEnabledSim := func(r *rand.Rand) {
swapEnabled = GetRandomSwapEnabled(r)
}
approveBySim := func(r *rand.Rand) {
approveBy = GetRandomApproveBy(r)
}
swapDenomSim := func(r *rand.Rand) {
swapDenom = GetRandomSwapDenom(r)
}
simState.AppParams.GetOrGenerate(simState.Cdc, string(types.KeySwapEnabled), &swapEnabled, simState.Rand, swapEnabledSim)
simState.AppParams.GetOrGenerate(simState.Cdc, string(types.KeyApproveBy), &approveBy, simState.Rand, approveBySim)
simState.AppParams.GetOrGenerate(simState.Cdc, string(types.KeySwapDenom), &swapDenom, simState.Rand, swapDenomSim)
params := types.NewParams(swapEnabled, swapDenom, approveBy)
var swaps types.Swaps
swaps = append(swaps, types.Swap{
TxHash: []byte("b37c4b36298f20ac7fc5de2b4ac1167d7a044402a40f2b5f1e1bb7f0ee5f6346"),
Receiver: "sent1grdunxx5jxd0ja75wt508sn6v39p70hhw53zs8",
Amount: sdk.Coin{Denom: "sent", Amount: sdk.NewInt(1000)},
})
swapGenesis := types.NewGenesisState(swaps, params)
bz, err := json.MarshalIndent(&swapGenesis.Params, "", "")
if err != nil {
panic(err)
}
fmt.Printf("selected randomly generated swap parameters: %s\n", bz)
simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(swapGenesis)
}
<file_sep>package types
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
)
var (
_ sdk.Msg = (*MsgRegisterRequest)(nil)
_ sdk.Msg = (*MsgUpdateRequest)(nil)
)
func NewMsgRegisterRequest(from sdk.AccAddress, name, identity, website, description string) *MsgRegisterRequest {
return &MsgRegisterRequest{
From: from.String(),
Name: name,
Identity: identity,
Website: website,
Description: description,
}
}
func (m *MsgRegisterRequest) Route() string {
return RouterKey
}
func (m *MsgRegisterRequest) Type() string {
return fmt.Sprintf("%s:register", ModuleName)
}
func (m *MsgRegisterRequest) ValidateBasic() error {
if _, err := sdk.AccAddressFromBech32(m.From); err != nil {
return ErrorInvalidFieldFrom
}
// Name length should be between 1 and 64
if len(m.Name) == 0 || len(m.Name) > 64 {
return ErrorInvalidFieldName
}
// Identity length should be between 0 and 64
if len(m.Identity) > 64 {
return ErrorInvalidFieldIdentity
}
// Website length should be between 0 and 64
if len(m.Website) > 64 {
return ErrorInvalidFieldWebsite
}
// Description length should be between 0 and 256
if len(m.Description) > 256 {
return ErrorInvalidFieldDescription
}
return nil
}
func (m *MsgRegisterRequest) GetSignBytes() []byte {
return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(m))
}
func (m *MsgRegisterRequest) GetSigners() []sdk.AccAddress {
from, err := sdk.AccAddressFromBech32(m.From)
if err != nil {
panic(err)
}
return []sdk.AccAddress{from}
}
func NewMsgUpdateRequest(from hubtypes.ProvAddress, name, identity, website, description string) *MsgUpdateRequest {
return &MsgUpdateRequest{
From: from.String(),
Name: name,
Identity: identity,
Website: website,
Description: description,
}
}
func (m *MsgUpdateRequest) Route() string {
return RouterKey
}
func (m *MsgUpdateRequest) Type() string {
return fmt.Sprintf("%s:update", ModuleName)
}
func (m MsgUpdateRequest) ValidateBasic() error {
if _, err := hubtypes.ProvAddressFromBech32(m.From); err != nil {
return ErrorInvalidFieldFrom
}
// Name length should be between 0 and 64
if len(m.Name) > 64 {
return ErrorInvalidFieldName
}
// Identity length should be between 0 and 64
if len(m.Identity) > 64 {
return ErrorInvalidFieldIdentity
}
// Website length should be between 0 and 64
if len(m.Website) > 64 {
return ErrorInvalidFieldWebsite
}
// Description length should be between 0 and 256
if len(m.Description) > 256 {
return ErrorInvalidFieldDescription
}
return nil
}
func (m *MsgUpdateRequest) GetSignBytes() []byte {
return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(m))
}
func (m *MsgUpdateRequest) GetSigners() []sdk.AccAddress {
from, err := hubtypes.ProvAddressFromBech32(m.From)
if err != nil {
panic(err)
}
return []sdk.AccAddress{from.Bytes()}
}
<file_sep>package v05
import (
"time"
)
type (
Params struct {
InactiveDuration time.Duration `json:"inactive_duration"`
ProofVerificationEnabled bool `json:"proof_verification_enabled"`
}
)
<file_sep>package types
import (
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
hubtypes "github.com/sentinel-official/hub/types"
)
const (
ModuleName = "subscription"
QuerierRoute = ModuleName
)
var (
ParamsSubspace = ModuleName
RouterKey = ModuleName
StoreKey = ModuleName
)
var (
EventModuleName = EventModule{Name: ModuleName}
)
var (
CountKey = []byte{0x00}
SubscriptionKeyPrefix = []byte{0x10}
SubscriptionForNodeKeyPrefix = []byte{0x11}
SubscriptionForPlanKeyPrefix = []byte{0x12}
ActiveSubscriptionForAddressKeyPrefix = []byte{0x20}
InactiveSubscriptionForAddressKeyPrefix = []byte{0x21}
InactiveSubscriptionAtKeyPrefix = []byte{0x30}
QuotaKeyPrefix = []byte{0x40}
)
func SubscriptionKey(id uint64) []byte {
return append(SubscriptionKeyPrefix, sdk.Uint64ToBigEndian(id)...)
}
func GetSubscriptionForNodeKeyPrefix(address hubtypes.NodeAddress) []byte {
return append(SubscriptionForNodeKeyPrefix, address.Bytes()...)
}
func SubscriptionForNodeKey(address hubtypes.NodeAddress, id uint64) []byte {
return append(GetSubscriptionForNodeKeyPrefix(address), sdk.Uint64ToBigEndian(id)...)
}
func GetSubscriptionForPlanKeyPrefix(id uint64) []byte {
return append(SubscriptionForPlanKeyPrefix, sdk.Uint64ToBigEndian(id)...)
}
func SubscriptionForPlanKey(p, s uint64) []byte {
return append(GetSubscriptionForPlanKeyPrefix(p), sdk.Uint64ToBigEndian(s)...)
}
func GetActiveSubscriptionForAddressKeyPrefix(address sdk.AccAddress) []byte {
return append(ActiveSubscriptionForAddressKeyPrefix, address.Bytes()...)
}
func ActiveSubscriptionForAddressKey(address sdk.AccAddress, i uint64) []byte {
return append(GetActiveSubscriptionForAddressKeyPrefix(address), sdk.Uint64ToBigEndian(i)...)
}
func GetInactiveSubscriptionForAddressKeyPrefix(address sdk.AccAddress) []byte {
return append(InactiveSubscriptionForAddressKeyPrefix, address.Bytes()...)
}
func InactiveSubscriptionForAddressKey(address sdk.AccAddress, i uint64) []byte {
return append(GetInactiveSubscriptionForAddressKeyPrefix(address), sdk.Uint64ToBigEndian(i)...)
}
func GetInactiveSubscriptionAtKeyPrefix(at time.Time) []byte {
return append(InactiveSubscriptionAtKeyPrefix, sdk.FormatTimeBytes(at)...)
}
func InactiveSubscriptionAtKey(at time.Time, id uint64) []byte {
return append(GetInactiveSubscriptionAtKeyPrefix(at), sdk.Uint64ToBigEndian(id)...)
}
func GetQuotaKeyPrefix(id uint64) []byte {
return append(QuotaKeyPrefix, sdk.Uint64ToBigEndian(id)...)
}
func QuotaKey(id uint64, address sdk.AccAddress) []byte {
return append(GetQuotaKeyPrefix(id), address.Bytes()...)
}
func IDFromSubscriptionForNodeKey(key []byte) uint64 {
return sdk.BigEndianToUint64(key[1+sdk.AddrLen:])
}
func IDFromSubscriptionForPlanKey(key []byte) uint64 {
return sdk.BigEndianToUint64(key[1+8:])
}
func IDFromStatusSubscriptionForAddressKey(key []byte) uint64 {
return sdk.BigEndianToUint64(key[1+sdk.AddrLen:])
}
func IDFromInactiveSubscriptionAtKey(key []byte) uint64 {
return sdk.BigEndianToUint64(key[1+29:])
}
<file_sep>package v06
import (
"github.com/sentinel-official/hub/x/node/types"
legacy "github.com/sentinel-official/hub/x/node/types/legacy/v0.5"
)
func MigrateGenesisState(state *legacy.GenesisState) *types.GenesisState {
return types.NewGenesisState(
MigrateNodes(state.Nodes),
MigrateParams(state.Params),
)
}
<file_sep>package v05
import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
type (
Swap struct {
TxHash EthereumHash `json:"tx_hash"`
Receiver sdk.AccAddress `json:"receiver"`
Amount sdk.Coin `json:"amount"`
}
Swaps []Swap
)
<file_sep>package v06
import (
"github.com/sentinel-official/hub/x/deposit/types"
legacy "github.com/sentinel-official/hub/x/deposit/types/legacy/v0.5"
)
func MigrateDeposit(item legacy.Deposit) types.Deposit {
return types.Deposit{
Address: item.Address.String(),
Coins: item.Coins,
}
}
func MigrateDeposits(items legacy.Deposits) types.Deposits {
var deposits types.Deposits
for _, item := range items {
deposits = append(deposits, MigrateDeposit(item))
}
return deposits
}
<file_sep>package types
import (
"math/big"
sdk "github.com/cosmos/cosmos-sdk/types"
)
var (
Kilobyte = sdk.NewInt(1000)
Megabyte = sdk.NewInt(1000).Mul(Kilobyte)
Gigabyte = sdk.NewInt(1000).Mul(Megabyte)
)
func NewBandwidth(upload, download sdk.Int) Bandwidth {
return Bandwidth{
Upload: upload,
Download: download,
}
}
func (b Bandwidth) IsAnyZero() bool {
return b.Upload.IsZero() || b.Download.IsZero()
}
func (b Bandwidth) IsAllZero() bool {
return b.Upload.IsZero() && b.Download.IsZero()
}
func (b Bandwidth) IsAnyNegative() bool {
return b.Upload.IsNegative() || b.Download.IsNegative()
}
func (b Bandwidth) IsAllPositive() bool {
return b.Upload.IsPositive() && b.Download.IsPositive()
}
func (b Bandwidth) Sum() sdk.Int {
return b.Upload.Add(b.Download)
}
func (b Bandwidth) Add(v Bandwidth) Bandwidth {
b.Upload = b.Upload.Add(v.Upload)
b.Download = b.Download.Add(v.Download)
return b
}
func (b Bandwidth) Sub(v Bandwidth) Bandwidth {
b.Upload = b.Upload.Sub(v.Upload)
b.Download = b.Download.Sub(v.Download)
return b
}
func (b Bandwidth) IsAllLTE(v Bandwidth) bool {
return b.Upload.LTE(v.Upload) && b.Download.LTE(v.Download)
}
func (b Bandwidth) IsAnyGT(v Bandwidth) bool {
return b.Upload.GT(v.Upload) || b.Download.GT(v.Download)
}
func (b Bandwidth) CeilTo(precision sdk.Int) Bandwidth {
if !precision.IsPositive() {
return b
}
v := NewBandwidth(
precision.Sub(sdk.NewIntFromBigInt(
big.NewInt(0).Rem(b.Upload.BigInt(), precision.BigInt()))),
precision.Sub(sdk.NewIntFromBigInt(
big.NewInt(0).Rem(b.Download.BigInt(), precision.BigInt()))),
)
if v.Upload.Equal(precision) {
v.Upload = sdk.NewInt(0)
}
if v.Download.Equal(precision) {
v.Download = sdk.NewInt(0)
}
return b.Add(v)
}
func NewBandwidthFromInt64(upload, download int64) Bandwidth {
return Bandwidth{
Upload: sdk.NewInt(upload),
Download: sdk.NewInt(download),
}
}
|
84884d074c970832ef8e070645f54295ed52ada2
|
[
"Makefile",
"Go Module",
"Go"
] | 167
|
Go
|
1Crazymoney/hub
|
4cd6b2bb3609b6ca86414d50216568e90b847c28
|
1135b57402617e2d79bf0464508058d7679c7f44
|
refs/heads/master
|
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule} from '@angular/forms';
import { HttpModule} from '@angular/http';
import { RouterModule, Routes } from '@angular/router';
import 'hammerjs';
import 'hammer-timejs';
import { HammerGestureConfig, HAMMER_GESTURE_CONFIG } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ListViewComponent } from './list-view/list-view.component';
import { MyServiceService } from './my-service.service';
import { LoginComponent } from './login/login.component';
export class MyHammerConfig extends HammerGestureConfig {
overrides = <any>{
'swipe': {velocity: 0.4, threshold: 20} // override default settings
}
}
const routes: Routes = [
{
path: 'list',
component: ListViewComponent
},
{
path: '',
component: LoginComponent
}
];
@NgModule({
declarations: [
AppComponent,
ListViewComponent,
LoginComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot(routes)
],
providers: [MyServiceService, { provide: HAMMER_GESTURE_CONFIG,
useClass: MyHammerConfig}],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
import { MyServiceService } from '../my-service.service';
import { ActivatedRoute, Params } from '@angular/router';
@Component({
selector: 'app-list-view',
templateUrl: './list-view.component.html',
styleUrls: ['./list-view.component.css']
})
export class ListViewComponent implements OnInit {
constructor() { }
items = ['Example 1', 'Example 2', 'Example 3', 'Example 4', 'Example 5', 'Example 6', 'Example 7'];
a: any;
newItem = '';
msg: any;
ngOnInit() {
// this.initArray(this.items);
}
pushItem = function () {
if (this.newItem !== '') {
this.items.push(this.newItem);
this.newItem = '';
}
};
removeItem = function (index) {
this.items.splice(index, 1);
this.initArray(this.items);
};
// initArray(len) {
// for( let i = 0; i < len.length; i++) {
// a[i] = true;
// }
// }
swipe(i) {
console.log('swipe left is working');
this.msg = 'X';
}
swipe1() {
this.msg = '';
}
}
<file_sep>I have used JavaScript for implementing Assignment 1 and 2.
Assignment 1 and Assignment 2 are on .txt file. Please copy and paste JS code on a console or any IDE of your choice.
For assignment 3,
I have used Angular 4 framework.
You can download my project and on terminal go to my project and run "npm install" to install all the dependencies.
Then run "npm start" and go to localhost:4200.
I have implemented every feature of assignment 3 including responsiveness, password validation, routing and delete an item.
I have additionally implemented an add item field to add extra items to list.
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private router: Router) {
}
ngOnInit() {
}
valid() {
const pas = document.getElementById('password') as HTMLInputElement;
const password = pas.value;
console.log(password);
const re = /(?=.*[a-z])(?=.*[A-Z]).{8,}/;
console.log(re.test(password));
if ( re.test(password) == false) {
alert("Password is not correct. Conditions are: minimum length of 8, 1 uppercase letter and 1 lowercase letter.");
}
else {this.router.navigate(['/list']); }
}
}
<file_sep>import { Injectable } from '@angular/core';
import { Http} from '@angular/http';
import { RouterModule} from '@angular/router';
@Injectable()
export class MyServiceService {
constructor(private http: Http, private _router: RouterModule) {}
fetchData() {
this.http.get('src/assests/list-view.json').subscribe((data) => console.log(data));
}
}
|
2ae96e6fcb1de1d8e6df7f2ba58f78311dea8b31
|
[
"Markdown",
"TypeScript"
] | 5
|
TypeScript
|
gittmaan/Walmart-Assignment
|
bc27e01384856586c803b6da79916b40d97d1f23
|
686e55e0dafe4724e5f4e2a9133f02bb7a31506a
|
refs/heads/master
|
<repo_name>shalevy1/rect-annotator<file_sep>/README.md
# Rect Annotator
An image annotation tool for drawing bounding boxes in different angles around objects in images.
<img src="screenshots/1.png" alt="A screenshot from the tool" width="500"/>
## Why it was born?
First, I never like the idea of re-inventing the wheel. What I need is an image annotation tool for a very simple task: drawing bounding boxes in different angles around interested objects. I went through many available tools (free and paid) in the internet but none of them sastified me in doing such simple task. So here we go: A very simple and fast tool for quickly annotating image datasets.
We can use the polygon drawing function in some tools to draw a rectangle with angles. However, it can't draw an ideal rectangle and also it is never a ideal way to draw rectangles. In addition, some graphic tools draw the rectangle and rotate it following the object. This also wastes our time and effort to addjust the rectangle size and angle. Why don't we rotate the object to a right angle and simply draw a rectangle in a right angle. It can give us a TRUE rectangle and save a lot of our effort. That's the main idea of the tool.
## Required packages
* Python 3
* PyQt5
```bash
pip install pyqt5
```
## Usage (5-second tutorial)
<img src="screenshots/usage.gif" alt="How to use" width="500"/>
To make full use of our fingers, the UI has no button, menu or anything that wastes your clicks. We only need to press the key to adjust the angle of the image and drag the mouse to draw rectangles.
Everything we have to remember is:
<kbd>Q</kbd> : Rotate the image in anti-clockwise direction (5 degrees / stroke)
<kbd>W</kbd> : Rotate the image in clockwise direction (5 degrees / stroke)
<kbd>A</kbd> : Rotate the image in anti-clockwise direction (1 degree / stroke)
<kbd>S</kbd> : Rotate the image in clockwise direction (1 degree / stroke)
<kbd>T</kbd> : Delete the previous rectangle
How do you feel? Yes, it's very simple and fast. You even don't waste any single key stroke when using it.
The annotation data will be stored in the same folder with your images with the name ```anns.txt```. To keep the UI simple, I don't create any input for image folder path, you need to modify the code to set the value for ```IMAGE_FOLDER_PATH```. Also, check out my iPython notebook in examples to see how to use the annotation data for crop patches from images.
You might notice that the display image gets blur everytime we draw a new rectangle. This is caused by the effect of rotating a pixmap many times. However, the quality of the image won't change so much when we use the annotation data to crop the image because a single rotation is performed for each cropping process.
## Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.
## License
[MIT](https://choosealicense.com/licenses/mit/)
<file_sep>/src/main_app.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import glob
try:
from PyQt5 import QtWidgets, QtGui, QtCore
except:
print('No PyQt-Module installed.')
quit()
__author__ = "<NAME>"
__copyright__ = "Copyright 2019, Bien Nguyen"
__credits__ = ["<NAME>"]
__license__ = "MIT"
__version__ = "1.0.0"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Production"
IMAGE_FOLDER_PATH = '../image_dataset/'
# ###########################
class App(QtWidgets.QWidget):
def __init__(self):
super().__init__()
# Main window
self.title = 'Rect Annotator'
self.width = 640
self.height = 480
self.img_label = QtWidgets.QLabel(self)
self.img_label.setAlignment(QtCore.Qt.AlignCenter)
# Browse image folder
self.image_browser = ImageBrowser(IMAGE_FOLDER_PATH)
# Annotating file
self.ann_file_manager = AnnotationFileManager(IMAGE_FOLDER_PATH + 'anns.txt')
# Frezze image when drawing
self.on_drawing_img = None
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
# self.setGeometry(self.left, self.top, self.width, self.height)
self.load_new_im(show_rect=False)
self.show()
self.load_new_im()
# self.img_label.move(-161,-160)
def load_new_im(self, show_rect=True):
im_name = self.image_browser.get_current_im_name()
real_rects = self.ann_file_manager.get_im_rects(im_name)
self.display_im = DisplayImage(IMAGE_FOLDER_PATH + im_name, real_rects, self.width, show_rect)
self.width = self.display_im.pixmap_im.width()
self.height = self.display_im.pixmap_im.height()
self.resize(self.display_im.pixmap_im.width(), self.display_im.pixmap_im.height())
self.center()
self.img_label.setPixmap(self.display_im.get_display_im())
def center(self):
frameGm = self.frameGeometry()
centerPoint = QtWidgets.QDesktopWidget().availableGeometry().center()
frameGm.moveCenter(centerPoint)
self.move(frameGm.topLeft())
def keyPressEvent(self, e):
rotating_angle = 0
if e.key() == QtCore.Qt.Key_Q:
# Rotation transform
rotating_angle = -5
elif e.key() == QtCore.Qt.Key_W:
rotating_angle = 5
elif e.key() == QtCore.Qt.Key_A:
rotating_angle = -1
elif e.key() == QtCore.Qt.Key_S:
rotating_angle = 1
elif e.key() == QtCore.Qt.Key_T:
# delete the last rectangles from the rectangle list
self.display_im.del_last_rect()
self.img_label.setPixmap(self.display_im.get_display_im())
elif e.key() == QtCore.Qt.Key_Right:
# Always save and check first
self.ann_file_manager.update_im_rects(self.image_browser.get_current_im_name(),
self.display_im.get_real_rect())
self.ann_file_manager.save()
if (self.image_browser.next_im() == -1):
QtWidgets.QMessageBox.information(self, "", "End of the image list", QtWidgets.QMessageBox.Ok)
return
self.load_new_im()
elif e.key() == QtCore.Qt.Key_Left:
# Always save and check first
self.ann_file_manager.update_im_rects(self.image_browser.get_current_im_name(),
self.display_im.get_real_rect())
self.ann_file_manager.save()
if (self.image_browser.prev_im() == -1):
QtWidgets.QMessageBox.information(self, "", "At the beginning of the image list", QtWidgets.QMessageBox.Ok)
return
self.load_new_im()
if rotating_angle != 0:
self.display_im.angle += rotating_angle
tmp_img = self.display_im.get_display_im()
self.img_label.setPixmap(tmp_img)
def mousePressEvent(self, e):
self.rect_start_pos = e.pos()
self.on_drawing_img = self.display_im.get_display_im()
def mouseMoveEvent(self, e):
display_img = self.on_drawing_img
pos_in_img_x, pos_in_img_y, w, h = self.get_curr_rect_params(e, display_img)
tmp_pixmap = draw_rect(display_img, pos_in_img_x, pos_in_img_y, w, h)
self.img_label.setPixmap(tmp_pixmap)
def mouseReleaseEvent(self, e):
display_img = self.display_im.get_display_im()
pos_in_img_x, pos_in_img_y, w, h = self.get_curr_rect_params(e, display_img)
# minimum size of the rectangle is 5x5
if w >= 5 and h >= 5:
self.display_im.add_rect(pos_in_img_x, pos_in_img_y, w, h)
def closeEvent(self, e):
# Save data before closing the app
self.ann_file_manager.update_im_rects(self.image_browser.get_current_im_name(),
self.display_im.get_real_rect())
self.ann_file_manager.save()
def get_curr_rect_params(self, e, display_img):
# print('Mouse move')
w = e.pos().x() - self.rect_start_pos.x()
h = e.pos().y() - self.rect_start_pos.y()
# Calculate the real-time rectangle draw by the mouse
pos_in_img_x = self.rect_start_pos.x() + (display_img.width() - self.width) / 2
pos_in_img_y = self.rect_start_pos.y() + (display_img.height() - self.height) / 2
return pos_in_img_x, pos_in_img_y, w, h
# ##################################
def draw_rect(pixmap_img, x, y, w, h):
tmp_pixmap = QtGui.QPixmap(pixmap_img)
# create painter instance with pixmap
painterInstance = QtGui.QPainter(tmp_pixmap)
# set rectangle color and thickness
penRectangle = QtGui.QPen(QtCore.Qt.green)
penRectangle.setWidth(2)
# draw rectangle on painter
painterInstance.setPen(penRectangle)
painterInstance.drawRect(x, y, w, h)
return tmp_pixmap
# ##########################
class DisplayImage():
def __init__(self, im_path, real_rects, wnd_width, show_rect = True):
self.pixmap_im = QtGui.QPixmap(im_path)
self.im_scale_ratio = self.pixmap_im.width() / wnd_width
self.pixmap_im = self.pixmap_im.scaledToWidth(wnd_width)
self.angle = 0 # current angle of the displaying image
tmp_rects = []
for rect in real_rects:
tmp_rect = rect[:]
tmp_rect[:-1] = [x/self.im_scale_ratio for x in rect[:-1]]
tmp_rects.append(tmp_rect)
self.rects = tmp_rects # current rectangle overlay the image
self.refresh_im(show_rect)
def refresh_im(self, show_rect=True):
display_pixmap = QtGui.QPixmap(self.pixmap_im)
if show_rect:
for rect_params in self.rects:
original_width = display_pixmap.width()
original_height = display_pixmap.height()
# Rotate the image following current angle
display_pixmap = display_pixmap.transformed(QtGui.QTransform().rotate(rect_params[4]),
QtCore.Qt.SmoothTransformation)
display_pixmap = draw_rect(display_pixmap, rect_params[0], rect_params[1], rect_params[2], rect_params[3])
# Rotate back to the original image
display_pixmap = display_pixmap.transformed(QtGui.QTransform().rotate(-rect_params[4]),
QtCore.Qt.SmoothTransformation)
# Crop to get only the image
offset_x = (display_pixmap.width() - original_width)/2
offset_y = (display_pixmap.height() - original_height)/2
display_pixmap = display_pixmap.copy(offset_x, offset_y, original_width, original_height)
self.rect_pixmap_im = display_pixmap
def get_display_im(self):
rotate_transform = QtGui.QTransform().rotate(self.angle)
display_pixmap = self.rect_pixmap_im.transformed(rotate_transform, QtCore.Qt.SmoothTransformation)
return display_pixmap
def add_rect(self, pos_in_img_x, pos_in_img_y, w, h):
self.rects.append([pos_in_img_x, pos_in_img_y, w, h, self.angle])
self.refresh_im()
# Get rectangles in the real image size
def get_real_rect(self):
real_rects = []
for rect in self.rects:
tmp_rect = rect[:]
# multiply with image scale ratio to get the real position except the angle
tmp_rect[:-1] = [x * self.im_scale_ratio for x in tmp_rect[:-1]]
real_rects.append(tmp_rect)
return real_rects
def del_last_rect(self):
self.rects = self.rects[:-1]
self.refresh_im()
# ########################### Browse images in a folder
class ImageBrowser():
def __init__(self, im_folder_path):
self.im_folder_path = im_folder_path
self.im_names = []
self._current_im_id = 0
self.init_im_info()
def init_im_info(self):
# Get PNG, JPG files
for ext in ['png', 'jpg']:
self.im_names += [os.path.basename(im_path) for im_path in glob.glob(self.im_folder_path + '*' + ext)]
if len(self.im_names) == 0:
print('Image folder is empty.')
def get_current_im_name(self):
return self.im_names[self._current_im_id]
# return QtGui.QPixmap(self.im_folder_path + self.im_names[self._current_im_id])
def next_im(self):
if self._current_im_id < len(self.im_names) - 1:
self._current_im_id += 1
else:
return -1 # End of image list
return 0
def prev_im(self):
if self._current_im_id > 0:
self._current_im_id -= 1
else:
return -1 # at the beginning of the image list
return 0
# ############################
class AnnotationFileManager():
def __init__(self, file_path):
self.file_path = file_path
self.anns = []
self.load_data()
def load_data(self):
try:
with open(self.file_path, 'r') as f:
self.anns = [self.parse_line(line.rstrip()) for line in f]
# self.anns = f.read().splitlines()
except:
return
def parse_line(self, line_str):
data = []
str_list = line_str.split() # image name - x - y - w - h - angle
if len(str_list) < 6:
return []
data.append(str_list[0])
data.extend(float(x) for x in str_list[1:])
return data
def get_im_rects(self, im_name):
rects = []
for im_info in self.anns:
if im_info[0] == im_name:
rects.append(im_info[1:])
return rects
def update_im_rects(self, im_name, rects):
tmp_anns = [ line for line in self.anns if line[0] != im_name]
for rect in rects:
ann = [im_name]
ann.extend(rect)
tmp_anns.append(ann)
self.anns = tmp_anns
def save(self):
with open(self.file_path, 'w') as f:
for ann in self.anns:
f.write(' '.join(str(x) for x in ann) + '\n')
# ############################
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
|
e1666c6344fe645e2540cc1e2aec186f40d6f5f7
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
shalevy1/rect-annotator
|
35a54e729b0e1c4406d52f7bec49cbe70c365dac
|
21dcc6f1b7403d7eb6065300788bacca0cce0504
|
refs/heads/master
|
<repo_name>Hieucodegym/7.-Abstract-Class-Interface<file_sep>/[Thuc hanh] Lop Animal và interface Edible/src/Animal/Tiger.java
package Animal;
import Edible.Edible;
public class Tiger extends Animal{
@Override
public String makingSound(){
return "Tiger: roarrrrr!";
}
}<file_sep>/[Bai tap] Trien khai interface 'Resizeable' cho cac lop hinh hoc/src/Main.java
public class Main {
public static void main(String[] args) {
Circle[] circles = new Circle[3];
circles[0] = new Circle(1.3);
circles[1] = new Circle(1.1);
circles[2] = new Circle(5.3);
for (Circle circle: circles){
System.out.println(String.valueOf(circle));
}
System.out.println("---------------------------------");
Rectangle[] rectangles = new Rectangle[4];
rectangles[0] = new Rectangle(1.8, 2);
rectangles[1] = new Rectangle(0.2, 3);
rectangles[2] = new Rectangle(1.11, 1);
rectangles[3] = new Rectangle(1.5, 5);
for (Rectangle rectangle : rectangles){
System.out.println(String.valueOf(rectangle));
}
System.out.println("---------------------------------");
Square[] squares = new Square[3];
squares[0] = new Square(4);
squares[1] = new Square(1);
squares[2] = new Square(2);
for (Square square : squares){
System.out.println(String.valueOf(square));
}
System.out.println("---------------------------------");
Shape[] shape = new Shape[5];
shape[0] = new Circle(1.3);
shape[1] = new Square(4);
shape[2] = new Rectangle(1.3, 12);
shape[3] = new Circle(1.3);
shape[4] = new Square(6);
for (Shape shapes : shape){
if (shapes instanceof Colorable){
System.out.println(String.valueOf(shapes));
((Colorable) shapes).howToColor();
}
}
}
}
<file_sep>/[Thuc hanh] trien khai interface 'Comparable' cho cac lop hinh hoc/src/Main.java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
ComparableCircle[] comparableCircle = new ComparableCircle[3];
comparableCircle[0] = new ComparableCircle(3.6);
comparableCircle[1] = new ComparableCircle();
comparableCircle[2] = new ComparableCircle("indigo",false, 3.5);
System.out.println("Trước khi sort:");
for (ComparableCircle comparableCircles : comparableCircle){
System.out.println(comparableCircles);
}
Arrays.sort(comparableCircle);
System.out.println("Sau khi sort:");
for (ComparableCircle comparableCircles : comparableCircle){
System.out.println(comparableCircles);
}
}
}
<file_sep>/[Bai tap] Trien khai interface 'Resizeable' cho cac lop hinh hoc/src/Rectangle.java
public class Rectangle extends Shape implements Resizeable{
private double width = 1.0;
private double height = 1.0;
public Rectangle(){};
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public Rectangle(String color, boolean filled, double width, double height) {
super(color, filled);
this.width = width;
this.height = height;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getArea(){
return width * height;
}
public double getPerimeter(){
return (width + height) * 2;
}
@Override
public void resize(double percent) {
setWidth(getWidth() + ((Math.random() * 100) + percent + 1));
setHeight(getHeight() + ((Math.random() * 100) + percent + 1));
}
@Override
public String toString() {
resize(3);
return "Rectangle with height =" + getHeight() + " Width = " + getWidth() +
" Area = " + getArea() + " Perimeter = " + getPerimeter();
}
}
|
faad715f10c47b9ff1c6bce81f8f542bb8f04154
|
[
"Java"
] | 4
|
Java
|
Hieucodegym/7.-Abstract-Class-Interface
|
df00cecf7224f17a88152476647fad8df779981a
|
4c7483ac4141f9259bee2c72fb4bd891ad9b5e5c
|
refs/heads/master
|
<repo_name>khanhbvh/HashFruit.Web<file_sep>/HashFruit.Web/Scripts/myweb/home.js
app.service("HomeService", function ($http) {
var root = 'http://jsonplaceholder.typicode.com';
this.GetTest = function () {
var request = $http({
method: "GET",
url: root + '/users',
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
return request;
};
});
app.controller('HomeController', function ($scope, HomeService) {
$scope.ShowHello = function () {
Pace.restart();
var result = HomeService.GetTest2();
result.then(function (pl) {
if (!pl.data.IsError) {
}
alert("hello angular");
},
result.catch(function (pl) {
}),
function (errorPl) {
});
};
$scope.ShowMessage = function () {
AlertMessage('fa fa-info', 'Test Title', 'Info message');
};
});<file_sep>/HashFruit.Web/Helper/Utilities.cs
using System.Web.Mvc;
namespace HashFruit.Web.Helper
{
public static class Utilities
{
public static string IsRootActive(this HtmlHelper html, string control)
{
var routeData = html.ViewContext.RouteData;
var routeControl = (string)routeData.Values["controller"];
var returnActive = control == routeControl;
return returnActive ? "active" : "";
}
public static string IsActive(this HtmlHelper html, string control, string action)
{
var routeData = html.ViewContext.RouteData;
var routeAction = (string)routeData.Values["action"];
var routeControl = (string)routeData.Values["controller"];
// both must match
var returnActive = control == routeControl &&
(action == routeAction);
return returnActive ? "active" : "";
}
}
}<file_sep>/README.md
# HashFruit.Web
commit
<file_sep>/HashFruit.Web/App_Start/BundleConfig.cs
using System.Web.Optimization;
namespace HashFruit.Web
{
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery.js"));
bundles.Add(new ScriptBundle("~/bundles/angular").Include(
"~/Scripts/angular.min.js",
"~/Scripts/myweb/app.js"));
bundles.Add(new ScriptBundle("~/bundles/templateJS").Include(
"~/Scripts/bootstrap.min.js",
"~/Scripts/jquery.scrollUp.min.js",
"~/Scripts/price-range.js",
"~/Scripts/main.js",
"~/Scripts/jquery.prettyPhoto.js",
"~/Scripts/pace.js",
"~/Scripts/bootstrap-notify.min.js",
"~/Scripts/myweb/main.js"
));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.min.css",
"~/Content/font-awesome.min.css",
"~/Content/prettyPhoto.css",
"~/Content/price-range.css",
"~/Content/animate.css",
"~/Content/main.css",
"~/Content/responsive.css",
"~/Content/pace.css"));
}
}
}<file_sep>/HashFruit.Web/Scripts/myweb/product.js
app.service("ProductService", function ($http) {
this.GetTest = function () {
var request = $http({
method: "GET",
url: "/Home/GetTest",
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
return request;
};
});
app.controller('ProductController', function ($scope, ProductService) {
$scope.ShowHello = function () {
alert("hello product");
};
});<file_sep>/HashFruit.Web/Scripts/myweb/app.js
var app = angular.module('appHashFruit', []);<file_sep>/HashFruit.Web/Controllers/FeatureController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace HashFruit.Web.Controllers
{
public class FeatureController : Controller
{
// GET: Feature
public ActionResult Index()
{
ViewBag.Title = "Feature";
return View();
}
public ActionResult Detail()
{
ViewBag.Title = "Feature Detail";
return View();
}
}
}
|
a8e033bccc2aecb08b8ac2e7a40eb364eee239bf
|
[
"JavaScript",
"C#",
"Markdown"
] | 7
|
JavaScript
|
khanhbvh/HashFruit.Web
|
c8d2bf904b9932d16c275fe1b965b76382742e21
|
c4d8fdd4501e0cb8c585b2905fa3df40dceccd1b
|
refs/heads/master
|
<repo_name>Nilecode/Nilecode-Todo-App<file_sep>/chrome/chrome_extension/js/magic.js
/*
Author : <NAME>
Email : <EMAIL>
License : MIT
*/
// If the user is already logged in, then do the magic, or else, just show the form
check_session();
// Welcome the user:
$('#get_username').keyup(function () {
var name = $(this).val();
name !== '' ? $('.welcome_message span').text(name) : $('.welcome_message span').text('there');
});
// The login/Signup form:
$('#main_form').submit(function () {
// Store username and password values in variables
get_username = $('#get_username').val();
get_password = $('#get_password').val();
// Create new localStorage entry with the username
localStorage["current user"] = get_username;
// Check if this user have a localStorage entry:
if(localStorage["'" + get_username + "'"])
{
// Okay, he have one :)
nilecode_todo('registered member');
console.log('(Passed through login/signup form, if condition succeeded)' + get_username + ' is a registered member.');
}
else
{
// No localStorage entry for this user! He's a new member :P
nilecode_todo('new member');
console.log('(Passed through login/signup form, if condition failed, we\'re in else now)' + get_username + ' is a new member.');
};
//window.location.reload();
return false;
});
// Session check function (Always run on page refresh):
function check_session()
{
// Focus on the username input field in the signup/login form
$('#get_username').focus();
// Create a new variable with the previousely created localStorage while logging in/signing up
current_user = localStorage["current user"];
// Check if the localStorage entry of loginout equals "logged in", if so, login the user
if(localStorage["loginout"] == 'logged in') {
login();
nilecode_todo('registered member');
}
else {
// If it equals to anything else, log him out
logout();
}
};
// The login function:
function login()
{
// Flag the user as logged in
localStorage["loginout"] = "logged in";
// Append username to the top left of the page
$('#the_username span.put').text(current_user);
// Show the todos list, the top panel,..etc (this things that the logged in user should see)
$('.top_panel, .main_controls, #todo_list').removeClass('hide');
// Hide the login/signup form
$('#signup_login, #chrome').addClass('hide');
console.log('(Passed through the login function) Logged in successfuly.');
};
function logout()
{
// Flag the user as logged out
localStorage["loginout"] = "logged out";
// Empty the value of the localStorage key "current user"
localStorage["current user"] = "";
// Hide the stuff that the logged out user shouldn't see
$('.top_panel, .main_controls, #todo_list').addClass('hide');
// Remove tasks from the DOM
// $('#tasks_pool ul li').remove();
// Show the signup/login form
$('#signup_login, #chrome').removeClass('hide');
console.log('(Passed through the logout function) User is currently logged out.');
};
// The bad boy ;)
function nilecode_todo(action)
{
// Adding new todo item function
function new_todo() {
// Focus on the new todo input field
$('.new_task').focus();
// New todo item form submittion
$('#new_task').submit(function () {
// Decleare vars (date and tags will be handeled dynamically soon isA)
task = $('.new_task').val();
task_month = 'July';
task_year = '2012';
task_day = '30';
function make_identifier()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 10; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
identifier = make_identifier();
// The todo item HTML template (check for tags while storing into the variable)
todo_template = tags("\n\
<li class='cf' data-id='" + identifier + "' data-completed='no' data-day='" + task_day + "' data-month='" + task_month + "' data-year='" + task_year + "'>\n\
<datetime>" + task_day + "<br>" + task_month + "<br>" + task_year + "</datetime>\n\
<p>" + task + "</p>\n\
<i class='icon-remove mark_as_deleted'></i>\n\
<i class='icon-ok mark_as_completed'></i>\n\
</li>");
// Push new tags into the tags array in the user object
user.tags.push($(todo_template).find('.inline_tags').text());
// Push the new todo item into the todos array in the user object
user.todos.push(todo_template);
console.log('Pushed: ' + todo_template + ' to todos array.');
// Insert the new task to the list
$('#tasks_pool ul').prepend(todo_template);
console.log('(Passed through new todo item form submittion function) Successfuly inserted new task.');
// Hide the 'we didn't find anything' paragraph
$('p.not_found').hide();
// Empty the text input
$('.new_task').val('');
// Prepare the object to be stored in the localStorage via JSON.stringify, then
// overwrite the old one
localStorage["" + current_user + ""] = JSON.stringify(user);
console.log('(Passed through new todo item form submittion function) Everything is now synced with localStorage.');
return false;
});
};
// Now, we're out of the form submittion, we'll check the values sent by the
// check_session function:
// If the check_session said he's a new member:
if(action == 'new member')
{
login();
user = {};
// Insert the username and password from the form
user.username = get_username;
user.password = get_password;
// Create an empty array for the todo items and tags
user.todos = [];
user.tags = [];
// Then store the new object into the localStorage after JSON.strigify it
localStorage["" + localStorage["current user"] + ""] = JSON.stringify(user);
// Run the new todo form submittion function
new_todo();
}
// If the check_session said that he is already a registered member
else if(action == 'registered member')
{
login();
// Get his saved object from the localStorage stored by his name, the parse it via JSON.parse
user = JSON.parse(localStorage["" + current_user + ""]);
// Run the new todo form submittion function
new_todo();
// List all saved todos from the todos array stored in the user object
var todo_loop = user.todos, _todo = '';
for ( _todo in todo_loop ){
$('#tasks_pool ul').prepend(todo_loop[_todo]);
};
// List all saved tags from the tags array stored in the user object
var tags_loop = user.tags, x = '';
for ( x in tags_loop ){
$('#tags_list').prepend('<li><a href="#!/tags/' + tags_loop[x] + '">' + tags_loop[x] + '</a></li>');
};
}
// If none of the above:
else {
// LOL the user :D
alert('What are you doing :(')
return false;
}
};
function tags(text) {
if (hashtag_regexp = /#([a-zA-Z0-9]+)/g)
{
html_tag = text.replace(hashtag_regexp, '<a class="inline_tags" href="#!/tags/$1">$1</a>');
return html_tag;
}
else { return text; }
};
// Delete a todo item
$('.mark_as_deleted').click(function() {
// Get the user object from the localStorage
user = JSON.parse(localStorage["" + current_user + ""]);
// Get identifier (actually the array key)
var id = $(this).parents('li').attr('data-id');
// Delete the todo item from the array
user.todos.splice(user.todos.indexOf(id), 1);
// Show the user we have deleted it
$(this).parents('li').fadeOut(1000).remove();
// Rewrite the user object in the localStorage
localStorage["" + localStorage["current user"] + ""] = JSON.stringify(user);
});
// Mark as completed
$('.mark_as_completed').click(function() {
// Get the user object from the localStorage
user = JSON.parse(localStorage["" + current_user + ""]);
// Get identifier (actually the array key)
var id = $(this).parents('li').attr('data-id');
var todo_content = $(this).parents('li').find('p').text();
// Wrap the p content in a <del>
$(this).parents('li').find('p').html('<del>' + todo_content + '</del>');
// Delete the old todo
user.todos.splice(user.todos.indexOf(id), 1);
// Rewrite the modified todo item in the todos array
user.todos[user.todos.indexOf(id), 1] = '<li class="cf" data-id="' + id + '" data-completed="yes">' + $('li[data-id="' + id +'"]').html() + '<li>';
// Rewrite the user object in the localStorage
localStorage["" + localStorage["current user"] + ""] = JSON.stringify(user);
});
$('.logout a').click(function() {
logout();
});
function main_nav(trigger, page)
{
if (localStorage["loginout"] == "logged in") {
$(trigger).click(function() {
$('.page').addClass('hide');
$(page).removeClass('hide');
$('.main_controls ul li a').removeClass('selected');
$(this).addClass('selected');
})
};
};
// The tags page (functionality of this page is coming soon)
main_nav('#open_tags', '#tags');
// The help page
main_nav('#open_help', '#help');
// The about page
main_nav('#open_about', '#about');
// The home page
main_nav('.branding_controls h1', '#todo_list');<file_sep>/README.md
Nilecode-Todo-App
=================
A simple todo app based on HTML5 localStorage, this app doesn't store anything online,
all your information will be stored on your own computer, and thus, super super fast, thanks to HTML5's localStorage API.
The app is currently in alpha phase.
How to test the app:
====================
Download or clone the files, then copy the files to your local web server, ex: `http://localhost/app`,
no configurations needed, you're good to go.
Documentation:
==============
## `check_session()` function:
This function checks the current user status, by first checking an already stored value to the localStorage
key `"loginout"`, and if the value equals to `"logged in"`, then another two functions will run `login()` and `nilecode_todo` while
passing the param `'registered member'` to the `nilecode_todo` function as `nilecode_todo('registered member')`.
If the check found that the localStorage value doesn't eaqual to `"logged in"`, then we'll go through the `else` section
wich will run the function `logout()` and logout the user.
## `login()` function:
This function runs inside the `check_session()` function if the if condition succeeded, so if there is already
a key called `"loginout"` in the localStorage, then that means that the user has already used the app before
and thus there must be another localStorage entry with the key of the user name ex: `localStorage("<NAME>")`.
The `login()` function will search for this localStorage entry which is already save before, and then parse it
via `JSON.parse` ex: `user = JSON.parse(localStorage["<NAME>"]);` while `localStorage["<NAME>"]` has
a strigified object stored in it.
Then the function will mark the current user as logged in by setting another localStorage entry with the key
`loginout` and will add the value `"logged in"` in it, ex: `localStorage["loginout"] = "logged in";`.
After parsing the object from the localStorage we can now access all the information stored in it, like the
username, password, and todos. In this function we'll use the username `user.username` to insert it in the top left of the app
ex: `$('selector').text(user.username);`.
In the CSS I have a class called `.hide`, this class `display: none;` the element it applies to, and the function
now will remove this class from the elements that the logged in user should see.
ex: `$(selector).removeClass('hide');`, and then hide the elements that the logged in user shouldn't see
ex: `$(selector).addClass('hide');`.
## `logout()` function:
First, this function will flag the user as logged out ex: `localStorage["loginout"] = "logged out";`, then
it will empty the `loginout` localStorage key which we talked about previousely, and then hide and show stuff that
the logged out user should and shouldn't see.
## `nilecode_todo()` function:
This function is the main thing here; It has one param `action` passed to it, which we'll be using inside the
function to if condition some stuff based on the value sent to the `action` param.
This function have a child function called `new_todo()`, which handels the input of a new todos, we'll talk
about this function later.
The `nilecode_todo()` function will check if the param `action` equals to `new member`, and then will create
a new user object, and insert `username` and `password` fetched from the login/signup form inputs and also create
an empty todos array `user.todos = [];` in that same object; Then stringify and store the user object in the
localStorage of this user, the key of the new user storage is fetched from the `current user` localStorage entry
ex: `localStorage["<NAME>"] = JSON.stringify(user);`. Finally it'll run the `new_todo()` function.
In the other case if the `action` param equals to `registered member`, this means we have an object already stored
in the localStorage for that user, we can fetch and parse it now ex: `user = JSON.parse(localStorage["<NAME>"]);`, then we'll
run the `new_todo()` function, and finally insert the stored todos to the view from the todos array in the
user object ex: `var data = user.todos, x = ''; for ( x in data ){ $('#tasks_pool ul').prepend(data[x]); }`.
The last thing would happen, the final `else` check if none of the above conditions were met, then it'll
through this alert `alert('What are you doing :(')`.
### `new_todo()` function:
This function handels the process of adding new todo items to the `user.todos` array, so it'll first declear
some vars:
* `task` which is the content of the todo item.
* `task_month`, `task_year`, `task_day` which are the choosed date for the todo (planned feature).
* `identifier` which used in the previous release before this commit (8c462358eb64e908a756b21382e2e445b1e8c14a) to find
specific todo item and mark as completed or delete it, after the commit, I've disabled this feature because it won't
work now until I find a way to target a specific todo item in the `user.todos` array to mark as deleted or completed.
* `todo_template` which holds the new todo HTML template to insert into the todos loop.
After declearing these vars on form submit, we take the `todo_template` and push it to the `user.todos` array
ex: `user.todos.push(todo_template);`. Then insert the new todo item on top of the view list the view ex: `$(selector).prepend(todo_template);`
and then hide the paragraph which says `No tasks found yet! add some` ex: `$(selector).hide();` then
empty the form's text input ex: `$(selector).val('');`.
Finally we stringify the user object, and overwrite the old one ex: `localStorage["Islam Magdy"] = JSON.stringify(user);`.
## `completed()` and `deleted()` functions:
These functions are supposed to mark user's todo items as completed and/or deleted, it used to work before, but
after rewriting the code to be based on the user object, these functions won't work anymore based on the previous
logic/mechanism, however, this will be fixed in the future updates.
## `main_nav()` function:
This function handels the pages' navigation, it allows for two params `trigger`, and `page`, the `trigger` param is
the link that when clicked shows the selector passed to the `page` param, it will show this page, and
hide all other pages, that simple.
Road Map:
=========
I'm planning to do the following in the future releases:
* Add support for tags by filtering the user's input, search for words starting with a hash, and store these
tags in the user object, then list them in the tags page, and when clicking on a tag from the tags page,
the user should see a list of the todo items that include this tag.
* Add support for marking todo items as completed and/or deleted.
* Add support for logging in or signing up via Facebook, Google Plus, and Twitter.
* Add new page called `Settings` page, which will allow the user to delete all store information about him/her or
delete only the todos or completed todos, also will allow the user to enter a URI of a php file on the server
that he added the app to, and then the app should be able to automatically connect to this file via `AJAX` to
store the user info in a data base in case if the user want to switch from client side storage to server side storage.
* Create and publish a chrome extension for the app.
* Create a Firefox plugin for the app.<file_sep>/js/magic.js
/*
Author : <NAME>
Email : <EMAIL>
License : MIT
*/
/* Translations:
*==============
* Replace 'en' with your language if it exist in the translation file: js/translation.js
*/ lang = en;
// Render the templates:
render = {
header: new EJS({url: 'js/header.ejs'}).render(lang),
welcome: new EJS({url: 'js/welcome.ejs'}).render(lang),
pages: new EJS({url: 'js/pages.ejs'}).render(lang),
todos_list: new EJS({url: 'js/todos_list.ejs'}).render(lang)
}
$('header').html(render.header);
$('#pages').append(render.todos_list).append(render.pages).prepend(render.welcome);
// If the user is already logged in, then do the magic, or else, just show the form
check_session();
// Init popovers ( This needs to be run only when logged in, I'll do it in a coming update )
launch_popovers();
// Welcome the user:
$('#get_username').keyup(function () {
var name = $(this).val();
name !== '' ? $('.welcome_message span').text(name) : $('.welcome_message span').text(lang.there);
});
// The login/Signup form:
$('#main_form').submit(function () {
// Store username and password values in variables
get_username = $('#get_username').val();
get_password = $('#get_password').val();
password_salt = '<KEY>
password = Aes.Ctr.encrypt(get_password, password_salt, 256);
// Create new localStorage entry with the username
localStorage["current user"] = get_username;
// Create a new variable with the previousely created localStorage while logging in/signing up
current_user = localStorage["current user"];
// Check if this user have a localStorage entry:
if(localStorage["" + get_username + ""])
{
// Check for the password
user = JSON.parse(localStorage["" + get_username + ""]);
if (get_password == <PASSWORD>(user.password, password_salt, 256)) {
nilecode_todo('registered member');
console.log('(Passed through login/signup form, if condition succeeded)' + get_username + ' is a registered member.');
} else {
$('#get_password').css('border-bottom', '1px dashed #<PASSWORD>').attr('placeholder', 'Sorry, invalid passowrd!').val('');
console.log('(Passowrd didn\'t match!)');
return false;
};
}
else
{
// No localStorage entry for this user! He's a new member :P
nilecode_todo('new member');
console.log('(Passed through login/signup form, if condition failed, we\'re in else now)' + get_username + ' is a new member.');
};
window.location.reload();
return false;
});
// Session check function (Always run on page refresh):
function check_session()
{
// Focus on the username input field in the signup/login form
$('#get_username').focus();
current_user = localStorage["current user"];
// Check if the localStorage entry of loginout equals "logged in", if so, login the user
if(localStorage["loginout"] == 'logged in') {
login();
nilecode_todo('registered member');
}
else {
// If it equals to anything else, log him out
logout();
}
};
// The login function:
function login()
{
// Flag the user as logged in
localStorage["loginout"] = "logged in";
// Append username to the top left of the page
$('#the_username span.put').text(current_user);
console.log('(Passed through the login function) Logged in successfuly.');
};
function logout()
{
// Flag the user as logged out
localStorage["loginout"] = "logged out";
// Empty the value of the localStorage key "current user"
localStorage["current user"] = "";
console.log('(Passed through the logout function) User is currently logged out.');
};
// The bad boy ;)
function nilecode_todo(action)
{
// Adding new todo item function
function new_todo() {
// Focus on the new todo input field
$('.new_task').focus();
// New todo item form submittion
$('body').on('submit', '#new_task', function () {
// Decleare vars (date and tags will be handeled dynamically soon isA)
task = $('.new_task').val();
task_month = date_time('month');
task_year = date_time('year');
task_day = date_time('day');
task_time = date_time('time');
function make_identifier()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 20; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
identifier = make_identifier();
// The todo item HTML template
todo_template = "\n\
<li class='cf' data-id='" + identifier + "' data-completed='no' data-day='" + task_day + "' data-month='" + task_month + "' data-year='" + task_year + "'>\n\
<datetime title='" + task_time + "'>" + task_day + "<br>" + task_month + "<br>" + task_year + "</datetime>\n\
<p>" + task + "</p>\n\
<i class='icon-remove mark_as_deleted'></i>\n\
<i class='icon-ok mark_as_completed'></i>\n\
</li>";
// Check for tags
todo_template = tags_check(todo_template);
// Then check for dates
todo_template = date_time(todo_template);
var tag_text = $(todo_template).find('.inline_tags').text();
/*
TODO: Check if the tag already exist, then don't repeat it
but intead, mark it as happened twice, and then link
all todos that has this tag with this tag, and mark
this tag as happened x times in x todos.
*/
if ($('' + todo_template +'').find('a').length < 2) {
user.tags['' + identifier + ''] = [];
user.tags['' + identifier + ''] = $(todo_template).find('.inline_tags').text();
console.info('Added single tag');
};
if ($('' + todo_template +'').find('a').length > 1) {
user.tags['' + identifier + ''] = [];
$(todo_template).find('.inline_tags').each(function() {
user.tags['' + identifier + ''].push( $(this).text() );
});
console.info('Added multiple tags');
};
// Push the new todo item into the todos object
user.todos['' + identifier + ''] = todo_template;
user.due['' + identifier + ''] = task_day + ' ' + task_month + ', ' + task_year;
console.log('Pushed: ' + todo_template + ' to todos array.');
// Insert the new task to the list
$('#tasks_pool ul').prepend(todo_template);
console.log('(Passed through new todo item form submittion function) Successfuly inserted new task.');
// Hide the 'we didn't find anything' paragraph
$('p.not_found').hide();
// Empty the text input
$('.new_task').val('');
// Prepare the object to be stored in the localStorage via JSON.stringify, then
// overwrite the old one
localStorage["" + current_user + ""] = JSON.stringify(user);
console.log('(Passed through new todo item form submittion function) Everything is now synced with localStorage.');
launch_popovers();
return false;
});
};
// Now, we're out of the form submittion, we'll check the values sent by the
// check_session function:
// If the check_session said he's a new member:
if(action == 'new member')
{
login();
user = {};
// Insert the username and password from the form
user.username = get_username;
user.password = <PASSWORD>;
// Create empty objects for the todo items and tags
user.todos = {};
user.tags = {};
user.due = {};
// Then store the new object into the localStorage after JSON.strigify it
localStorage["" + localStorage["current user"] + ""] = JSON.stringify(user);
// Run the new todo form submittion function
new_todo();
// Reload the page
window.location.reload();
}
// If the check_session said that he is already a registered member
else if(action == 'registered member')
{
login();
// Get his saved object from the localStorage stored by his name, the parse it via JSON.parse
user = JSON.parse(localStorage["" + current_user + ""]);
// Run the new todo form submittion function
new_todo();
// List all saved todos from the todos array stored in the user object
var todo_loop = user.todos, _todo = '';
for ( _todo in todo_loop ){
$('#tasks_pool ul').prepend(todo_loop[_todo]);
};
// List all saved tags from the tags array stored in the user object
var tags_loop = user.tags, x = '';
for ( x in tags_loop ){
$('#tags_list').prepend('<li><a href="#!/tags/' + tags_loop[x] + '">' + tags_loop[x] + '</a></li>');
};
}
// If none of the above:
else {
console.error('I couldn\'t get it man, come debug this.. :(')
return false;
}
};
// Tags Check
function tags_check(check) {
tags_regex = /#([a-zA-Z0-9]+)/g;
if(tags_regex.test(check)) {
var tags = check.replace(tags_regex, '<a rel="popover" data-content="Click to view all todo items tagged with: $1" data-original-title="$1" class="inline_tags" href="#!/tags/$1">$1</a>');
return tags;
}
else { return check; }
};
// Date/Time Check
function date_time(check) {
// Terms to check
date = {
tomorrow : /:(tomorrow)/g,
twoDays : /:(2 days)/g,
nextWeek : /:(next week)/g,
today : /:(today)/g
};
// Date
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth();
var yyyy = today.getFullYear();
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"];
if(dd<10) dd ='0'+dd
// if(mm<10) mm ='0'+mm
var current_date = dd+'/'+mm+'/'+yyyy;
var current_day = dd;
var current_month = monthNames[mm];
var current_year = yyyy;
// Time
var am_pm = "";
var curr_hour = today.getHours();
var curr_min = today.getMinutes();
if (curr_hour < 12) {
am_pm = "AM";
} else {
am_pm = "PM";
}
if (curr_hour == 0) {
curr_hour = 12;
}
if (curr_hour > 12) {
curr_hour = curr_hour - 12;
}
var current_time = curr_hour + ":" + curr_min + " " + am_pm;
if (check == "date") return current_date
if (check == "day") return current_day
if (check == "month") return current_month
if (check == "year") return current_year
if (check == "time") return current_time
if (date["tomorrow"].test(check))
{
tomorrow = check.replace(date["tomorrow"], '"$1"');
var current_day = current_day +1;
return tomorrow;
}
if (date["twoDays"].test(check))
{
var twodays = check.replace(date["twoDays"], '"$1"');
return twodays;
}
if (date["nextWeek"].test(check))
{
var week = check.replace(date["nextWeek"], '"$1"');
return week;
}
if (date["today"].test(check))
{
var today = check.replace(date["today"], '"$1"');
return today;
}
else { return check; }
};
function launch_popovers() {
// Popovers by Bootstrap (mainly for tags, and would probably be used in some other areas)
$('.inline_tags').popover({
animation: true,
title: 'Hint!',
content: 'This is a hint, but actually I couldn\'t get the hint information! sorry for that, try again laters please',
trigger: 'hover'
});
};
// Delete a todo item
$('body').on("click", ".mark_as_deleted", function() {
// Get the user object from the localStorage
user = JSON.parse(localStorage["" + current_user + ""]);
// Get identifier
var id = $(this).parents('li').attr('data-id');
// Delete the todo item and any related tags
delete user.todos['' + id + ''];
delete user.tags['' + id + ''];
// if (user.tags['' + id + '']) {
// if (!$.isArray(user.tags['' + id + ''])) {
// }
// else if ($.isArray(user.tags['' + id + ''])) {
// delete user.tags['' + id + ''];
// // TODO: find only spe
// }
// else { console.error('I couldn\'t delete this entry! this entry is not an object nor array! so weird.'); }
// };
// Show the user we have deleted it
$(this).parents('li').fadeOut(1000).remove();
// Rewrite the user object in the localStorage
localStorage["" + localStorage["current user"] + ""] = JSON.stringify(user);
// Empty the tags container
$('#tags_list li').remove();
// Insert new tags loop after mods
var tags_loop = user.tags, x = '';
for ( x in tags_loop ){
$('#tags_list').prepend('<li><a href="#!/tags/' + tags_loop[x] + '">' + tags_loop[x] + '</a></li>');
};
})
// Mark as completed
$('body').on("click", ".mark_as_completed", function() {
// Get the user object from the localStorage
user = JSON.parse(localStorage["" + current_user + ""]);
// Get identifier
var id = $(this).parents('li').attr('data-id');
var todo_content = $(this).parents('li').find('p').text();
// Wrap the p content in a <del>
$(this).parents('li').find('p').html('<del>' + todo_content + '</del>');
// Delete the old todo
delete user.todos['' + id + ''];
// Rewrite the modified todo item in the todos object
user.todos['' + id + ''] = '<li class="cf" data-id="' + id + '" data-completed="yes">' + $('li[data-id="' + id +'"]').html() + '</li>';
// Rewrite the user object in the localStorage
localStorage["" + localStorage["current user"] + ""] = JSON.stringify(user);
})
$('.logout a').click(function() {
logout();
$('body').fadeOut(500);
setTimeout(function() {
window.location.reload();
}, 700);
});
// Always render the footer
var footer = new EJS({url: 'js/footer.ejs'}).render(lang);
$('footer').html(footer);
function main_nav(trigger, page)
{
if (localStorage["loginout"] == "logged in") {
$(trigger).click(function() {
if ($('#tags_list li').length == 0 && trigger == '#open_tags') {
$(trigger).text('You don\'t have any tags yet');
setTimeout(function() {
$(trigger).text('Tags');
}, 2000);
return false
}
else {
$('.page').addClass('hide');
$(page).removeClass('hide');
$('.main_controls ul li a').removeClass('selected');
$(this).addClass('selected');
}
})
};
};
// The tags page (functionality of this page is coming soon)
main_nav('#open_tags', '#tags')
// The help page
main_nav('#open_help', '#help')
// The about page
main_nav('#open_about', '#about')
// The home page
main_nav('.branding_controls h1', '#todo_list')<file_sep>/js/store.js
documents = function store(req, id, data) {
if (req == 'set') {
localStorage["" + id + ""] = data;
};
if (req == 'get') {
if (localStorage["" + id + ""])
{
res = localStorage["" + id + ""];
return res;
}
else {
console.log('Sorry I couldn\'t find the and entry with ID ' + id +' !');
}
};
if (req == 'update') {
if (localStorage["" + id + ""])
{
localStorage["" + id + ""] = data;
} else {
console.log('Sorry I couldn\'t find the and entry with ID ' + id +' !');
}
};
if (req == 'destroy') {
if (localStorage["" + id + ""])
{
localStorage.clear("" + id + "");
} else {
console.log('Sorry I couldn\'t find the and entry with ID ' + id +' !');
}
};
}<file_sep>/js/translation.js
/*
* Translations:
* =============
* Author: <NAME> (<EMAIL>)
*
* How to use this file:
* ---------------------
* 1- If your language doesn't exist, then please create another new function for your language exactly like the
* English 'en' example below. Start from the letters 'en' and end with the curly bracket '}'
* You can copy and paste.
* 2- Translate the words after the 'return' between quotes '', please don't remove the quotes.
*
* 3- You're good to go, just finally go to the file magic.js, find the word 'lang', and change the letters 'en'
* to your language letters.
*
* 4- All done :)
*
*/
// English International:
en = {
'siteTitle' : 'Nilecode Todos',
'Hello' : 'Hi',
'there' : 'there',
'logout' : 'Logout',
'inputTask' : 'Type a new task and hit enter...',
'tags' : 'tags',
'help' : 'help',
'about' : 'about',
'home' : 'home',
'footerCopyrights' : '© 2012 Nilecode',
'loginSignupNote' : 'Please note: If you have an account already, we\'ll use it to sign you in to your current todo list. If you\'re a new member, we will log you in and save your login information for next time, simple eh? :)',
'loginSignupButton' : 'Login/Signup',
'usernamePlaceholder' : 'Username (can have speaces. Ex: Islam Magdy)',
'passwordPlaceholder' : '<PASSWORD>',
'installChrome' : 'Install Chrome Extension'
}
// Chinese:
zh = {
'siteTitle' : '待办事项列表应用',
'Hello' : '嗨',
'there' : '伙计',
'logout' : '退出系统',
'inputTask' : '输入一项新任务,然后点击Enter键。。。',
'tags' : '帮助',
'help' : '标签',
'about' : '关于',
'home' : '主页',
'footerCopyrights' : '© 2012 待办事项列表应用',
'loginSignupNote' : '请注意:如果你已经有一个账号,你可以直接用该账号注册你当前的待办事项列表应用。如果你是新加入的成员,你可以直接登录,你的登录信息将会保留,以供下次使用,是不是很容易呢?:)',
'loginSignupButton' : '登录 / 注册',
'usernamePlaceholder' : '用户名(能添加空格。 例如: Li Ming)',
'passwordPlaceholder' : '密码',
'installChrome' : '安装Chrome浏览器扩充套件'
}
|
0d2be539683851ab366afbc54fc505ed716e6573
|
[
"JavaScript",
"Markdown"
] | 5
|
JavaScript
|
Nilecode/Nilecode-Todo-App
|
242f9d48ce8279d83a845ca4b9e603132a8fd9da
|
d19255ba7ead03cd5d8c05a17b00a9fcbf611a1c
|
refs/heads/master
|
<repo_name>BrandonBruceLee/Userscript--Twitch-Chat-Emotes<file_sep>/src/userscript-header.js
<% if (_.isObject(pkg.userscript)) {
var output = [];
output.push('// ==UserScript==');
_.forOwn(pkg.userscript, function (val, key) {
if (_.isArray(val)) {
_.forEach(val, function (nestedVal) {
output.push('// @' + key + ' ' + nestedVal);
});
}
else {
output.push('// @' + key + ' ' + val);
}
});
output.push('// ==/UserScript==');
output = output.join('\n'); %><%= output %><%
} %>
<file_sep>/README.md
# [Homepage](http://cletusc.github.io/Userscript--Twitch-Chat-Emotes/)
This is the build guide and source for the [Emote Menu for Twitch](http://cletusc.github.io/Userscript--Twitch-Chat-Emotes/). Normal users should check out the homepage as it is a lot more friendly. For developers that want to contribute, check out the build guide below, make some neat changes, then open a pull request.
# Building
In order to speed up building and testing, this project uses [npm](https://www.npmjs.org/) and [grunt](http://gruntjs.com/) to build the script.
### Basics
1. Make sure npm is installed as per their docs.
2. Run `npm install` to get the latest dependencies.
3. Make sure `grunt-cli` is globally installed: `npm install -g grunt-cli`.
4. Make changes to the script in the `src` folder (or other files as shown in the locations section below).
5. Run `grunt` to build the compiled script.
### Source files
- Userscript metadata: All userscript metadata is found in `package.json` within the `userscript` property and must be valid JSON.
- Templates: All templates are found in `src/templates` and are compiled using [hogan](https://www.npmjs.org/package/grunt-hogan). Templates are accessible within `src/script.js` by referencing `templates.filename();`. For a filename of `foo.html`, you can reference it by `templates.foo();`. You may pass in data to the template like so: `templates.foo({bar: 'baz'});`
- Styles: All CSS styles are found in `src/styles`. When adding a new file, you must also [add the filename to the Gruntfile](https://github.com/search?q=%22build%2Fstyles.css%22+path%3A%2FGruntfile.js+repo%3Acletusc%2FUserscript--Twitch-Chat-Emotes&type=Code&ref=searchresults) in the correct order.
- News updates: All news updates should be put in `news.json` and must be valid JSON. The key must be a timestamp in the form of `YYYY-MM-DDTHH:MM`, e.g. `2014-02-05T15:07` and the value will be your message. All links must have `target="_blank"`.
### Compiled files
- `script.user.js`: This is the userscript file which has all of the required metadata to work with the various userscript engines.
- `script.min.js`: This is the browser-ready minified version of the script. This is ideal for referencing by third-party scripts. Third-party scripts should only check for updates directly from Github once every 24 hours; do not directly reference the Github file. For direct linking, you should mirror this script to a CDN and use that instead.
### Grunt commands
- `grunt`: Compiles the script.
- `grunt watch`: Watches for changes to `package.json` and files in `src/` and automatically runs `grunt`.
- `grunt init`: Creates a simple `build/script-paths.json`. Every time you compile, the compiled userscript will be copied to all paths in this file. This allows you to easily test the userscript using your normal engine (Greasemonkey or others). With `grunt watch`, all you need to do is make the changes in the source, and refresh your browser! An example file might look like this:
```json
[
"D:/AppData/Mozilla Firefox/Profiles/default/gm_scripts/Twitch_Chat_Emotes/script.user.js"
]
```
|
9f561c10be09721844ea1005bfb2df24763564e9
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
BrandonBruceLee/Userscript--Twitch-Chat-Emotes
|
3b862e913078cb05dab37a2af08326d79284114e
|
77a6be41cf54a3700dea44c81d8d1fdd13a45dc1
|
refs/heads/master
|
<repo_name>kaspeedza8/workshopKTB<file_sep>/src/day28ProjectTest/postDetail.js
import React, { Component } from 'react';
import {Link} from 'react-router-dom'
import backBut from './backBut.png'
export default class postDetail extends Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<div className="container">
<Link to='/checkPost'> <img className="backBut" src={backBut} width="5%" /> </Link>
<table border="1">
<tr>
<td>รหัสตู้ : 1492421 วันที่ : 16/07/61 ละติจูด,ลองติจูด : 16.487467 , 102.807074 ที่อยู่ : ถ.ศรีจันทร์(Sri Chan Rd) ต.ในเมือง(T.Nai Muang), อ.เมือง(A.Muang),Khon Kaen 40000 </td>
</tr>
<tr>
<td>รหัสตู้ : 1492423 วันที่ : 17/07/61 ละติจูด,ลองติจูด : 16.487467 , 102.807074 ที่อยู่ : ถ.ศรีจันทร์(Sri Chan Rd) ต.ในเมือง(T.Nai Muang), อ.เมือง(A.Muang),Khon Kaen 40000 </td>
</tr>
</table>
</div>
);
}
}
<file_sep>/src/day3/Dog.js
import React from 'react';
import '../App.css'
class Dog extends React.Component{
constructor(props){
super(props);
this.state ={
}
}
render(){
const {dname , dcolor,dage} = this.props;
return(
<div className='Dog'>
<h2>Dump Dog</h2> <center>
<table border='1' style={{backgroundColor:'darkgreen' }}>
<tbody>
<tr>
<th>NAME</th>
<th>COLOR</th>
<th>AGE</th>
</tr>
<tr>
<td>{dname}</td>
<td>{dcolor}</td>
<td>{dage}</td>
</tr>
</tbody>
</table>
</center>
</div>
)
}
}
export default Dog ;<file_sep>/src/day3/Cat.js
import React from 'react';
class Cat extends React.Component {
constructor(props) {
super(props);
this.state = {
cname: 'Meow',
ccolor: 'Brown',
cage: 10
}
}
render() {
const { cname, ccolor, cage } = this.state;
return (
<div className='Cat'>
<h2>Dump Cat</h2> <center>
<table border='1' style={{backgroundColor:'darkgreen'}}>
<tbody>
<tr>
<th>NAME</th>
<th>COLOR</th>
<th>AGE</th>
</tr>
<tr>
<td>{cname}</td>
<td>{ccolor}</td>
<td>{cage}</td>
</tr>
</tbody>
</table>
</center>
</div>
)
}
}
export default Cat;<file_sep>/src/day10/dayten.js
import React, { Component } from 'react';
export default class dayten extends Component {
render() {
return (
<div> <Eye lefteye="BlueEyes" righteye="RedEyes" />
</div>
);
}
}
const Eye = ({lefteye , righteye}) => {
return(
<div>
<h1>DATA 1 : {lefteye}</h1>
<h2>DATA 2 : {righteye}</h2>
</div>
)
}
const Func = ({count , x}) =>{
return(
<div>
<button onClick={count} type="button" className="btn btn-outline-primary">Stateless : {x}</button>
</div>
)
}<file_sep>/src/day13_14/Begin.js
import React, { Component } from 'react';
import TheWord from './TheWord';
export default class Begin extends Component {
constructor(props) {
super(props)
this.state = {
x: 0,
height: '',
weight: '',
};
this.checkOut = this.checkOut.bind(this);
};
checkOut() {
this.setState({ x: this.state.x - 1 })
if (this.state.x < 1) {
alert('ไม่สามารถทำให้ค่าน้อยกว่า 0 ได้อีกแล้ว')
this.setState({ x: 0 })
}
}
checkBMI = (e) => {
const { name, value } = e.target
this.setState({ [name]: String(value) })
}
callBMI = () => {
const {height , weight} = this.state
var toCm = height/100
var bmiFinal = weight/(toCm*toCm);
this.setState({result : bmiFinal.toFixed(2)});
console.log(bmiFinal.toFixed(2))
}
render() {
const { x, height, weight,result } = this.state
return (
<div>
<div>
<center>
<h1>Part I</h1>
<h2>{x}</h2>
<button onClick={() => {
this.setState({ x: x + 1 })
if (this.state.x >= 100) {
alert('=========== Congratulations ===========')
this.setState({ x: 0 })
}
}}>Add</button>
<button onClick={this.checkOut}>Remove</button>
<button onClick={() => { this.setState({ x: 0 }) }}>Reset</button>
</center> <hr />
</div>
<div>
<center>
<h1>Part II</h1>
<form>
<input name="weight" type="text" value={weight}
onChange={this.checkBMI}
maxLength="3" placeholder="(kg)"></input> <br />
<input name="height" type="text" value={height}
onChange={this.checkBMI}
maxLength="3" placeholder="(cm)"></input> <br />
<button onClick={this.callBMI} type="button" className="btn btn-outline-primary">Calculate</button>
<br />
<h2>Your value is : {result}</h2>
<hr/>
</form>
<form>
<div>
<h1>Part III</h1>
<TheWord/>
</div>
</form>
</center></div>
</div>
);
}
}
<file_sep>/src/day6/Appmain.js
import React, { Component } from 'react'
//import { send } from 'q';
class Appmain extends Component {
constructor(props){
super(props)
this.state = {
abc : '' ,
def : 'Armor' ,
isRemoveB : false
}
}
cala = (y , z) => {
this.setState({abc : y , abd : z , sum : y+z})
}
settrue = () => {
this.setState({isRemoveB : true})
}
render() {
return(
<div>
<center>
<A cala={this.cala} ></A>
{/* <B abc={this.state.abc}
abd={this.state.abd}
sum={this.state.abc+this.state.abd}></B> */}
<button onClick={this.settrue}>RemoveB</button>
{!this.state.isRemoveB ?
<B abc={this.state.abc}
abd={this.state.abd}
sum={this.state.abc+this.state.abd}>
</B> : null}
</center>
</div>
)
}
}
export default Appmain ;
class A extends React.Component {
constructor(props){
super(props)
this.state ={
y : '',
z : ''
}
this.sendvalue = this.sendvalue.bind(this);
}
sendvalue = (e) => {
const {name , value} = e.target
this.setState({[name] : Number(value)}) //
}
componentDidMount(){
this.setState({y:10 , z:5})
console.log('Component DidMount A')
}
render() {
const {cala} = this.props
const{y , z} = this.state
return(
<div>
<input type="text" name='y' value={y} onChange={this.sendvalue} ></input> <br/>
<input type="text" name='z' value={z} onChange={this.sendvalue} ></input> <br/>
<button onClick= {()=>{cala(y,z)}}
type="button"
className="btn btn-outline-primary">
SEND</button>
</div>
)
}
}
class B extends React.Component {
constructor(props){
super(props)
this.state ={
newsum : 0
}
}
componentWillReceiveProps(nextProps){ //ให้รู้ว่ามีการเปลี่ยนแปลงค่า
console.log('Received Next Props')
console.log(nextProps.sum)
this.setState({newsum : nextProps.sum + 2})
}
componentWillUnmount() {
console.log('bye bye')
}
render() {
const {abc, abd , sum} = this.props
return(
<div>
<hr/>
<a href="#"
class="list-group-item list-group-item-action list-group-item-primary disabled"
>The Value is : {this.state.newsum}</a>
<hr/>
</div>
)
}
}<file_sep>/src/day25/main.js
import React, { Component } from 'react';
import { Button } from 'react-bootstrap';
export default class main extends Component {
constructor(props) {
super(props);
this.state = {
usr: '',
pwd: ''
};
}
componentWillMount() {
localStorage.setItem("checklogin", "0")
}
inputValue = (e) => {
const { name, value } = e.target
this.setState({ [name]: String(value) })
}
checkLogin = (e) => {
e.preventDefault();
const { usr, pwd } = this.state
if (usr === 'asd' && pwd === 'asd') {
alert('login complete !')
localStorage.setItem("checklogin", "1")
window.location.href = '/listPresent'
} else {
alert('Username or Password Incorrect !!!')
}
}
render() {
const { usr, pwd } = this.state
return (
<div>
<div className="theBox" style={{ marginTop: '40%' }}>
<form>
<input name='usr' value={usr} onChange={this.inputValue} type="text" className="form-control" required placeholder="Username" /><br />
<input name='pwd' value={pwd} onChange={this.inputValue} type="password" className="form-control" required placeholder="<PASSWORD>" /><br />
<small className="form-text text-muted">Admin</small>
<center><Button onClick={this.checkLogin} variant="success" type="submit">Login</Button></center>
</form>
</div>
</div>
);
}
}
{/* <meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> */}
<file_sep>/src/day11/Chicken.js
import React, { Component } from 'react';
export default class Chicken extends Component {
constructor(props) {
super(props)
};
render() {
let {AppAlert} = this.props
return (
<div>
<button onClick={AppAlert} type="button" className="btn btn-outline-primary">DETAIL</button>
</div>
);
}
}
<file_sep>/src/day27/responseWeb.js
import React, { Component } from 'react';
import fond from './fond.jpg'
export default class responseWeb extends Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<div >
<h1 className="glow">ResponsiveWebApplication</h1>
<div className="col-3 col-s-3 menu">
<ul>
<li>A lonely road, crossed another cold state line
Miles away from those I love purpose undefined
While I recall all the words you spoke to me
Can't help but wish that I was there
And where I'd love to be, oh yeah
Dear God the only thing I ask of you is
To hold her when I'm not around
When I'm much too far away
We all need that person who can be true to you
But I left her when I found her
And now I wish I'd stayed
'Cause I'm lonely and I'm tired
I'm missing you again oh no
Once again
There's nothing here for me on this barren road
There's no one here while the city sleeps
And all the shops are closed
Can't help but think of the times I've had with you
Pictures and some memories will have to help me through, oh yeah
Dear God…</li>
</ul>
</div>
<div class="col-6 col-s-9">
<ul>
<li>I remember black skies
The lightning all around me
I remember each flash
As time began to blur
Like a startling sign
That fate had finally found me
And your voice was all I heard
That I get what I deserve
So give me reason
To prove me wrong
To wash this memory clean
Let the floods cross
The distance in your eyes
Give me reason
To fill this hole
Connect this space between
Let it be enough to reach the truth that lies
Across this new divide
There was nothing inside
The memories left abandoned
There was nowhere to hide
The ashes fell like snow
And the ground caved in
Between where we were standing
And your voice was all I heard
That I get what I deserve
So give me reason
To prove me wrong
To wash this memory clean
Let the floods cross
The distance in your eyes
Across this…
</li>
</ul>
</div>
<div class="col-3 col-s-12">
<div class="aside">
<h2>What?</h2>
<p>Chania is a city on the island of Crete.</p>
<h2>Where?</h2>
<p>Crete is a Greek island in the Mediterranean Sea.</p>
<h2>How?</h2>
<p>You can reach Chania airport from all over Europe.</p>
</div>
</div>
<div class="footer">
<p>Resize the browser window to see how the content respond to the resizing.</p>
</div>
</div>
);
}
}
<file_sep>/src/day23/Details.js
import React, { Component } from 'react';
export default class Details extends Component {
constructor(props) {
super(props);
this.state = {
userDetail: ''
};
}
componentDidMount() {
this.fetchData();
}
fetchData = async () => {
const item = localStorage.getItem("item");
const response = await fetch('https://reqres.in/api/users/' + item);
const jsonData = await response.json();
this.setState({ userDetail: jsonData.data })
}
render() {
const { userDetail } = this.state;
return (
<div style={{justifyContent: 'center' }}>
<h1>Hello WOrlds</h1>
<br/>
<div>
<table id='myTable' className="table table-dark table-hover">
<thead>
<tr>
<th></th>
<th>FirstName</th>
<th>LastName</th>
</tr>
</thead>
<tbody>
<tr>
<td><img src={userDetail.avatar} alt={userDetail.id}/></td>
<td>{userDetail.first_name}</td>
<td>{userDetail.last_name}</td>
</tr>
</tbody>
</table>
</div>
</div>
);
}
}
<file_sep>/src/day19_test/Login.js
import React, { Component } from 'react';
// import { Link } from 'react-router-dom'
export default class Login extends Component {
constructor(props) {
super(props);
this.state = {
us : '' ,
pass : ''
};
}
componentWillMount(){
localStorage.removeItem("key");
}
inputForm = (e) => {
const { name, value } = e.target
this.setState({ [name]: String(value) })
}
loginForm = (e) => {
e.preventDefault();
const {us,pass} = this.state
if (us === "asd" && pass === "asd") {
localStorage.setItem("key" , "login")
alert('login complete')
window.location.href = "/Landing";
}else{
alert('Error')
}
}
render() {
const{us , pass} = this.state
return (
<div>
<h1>XxX</h1>
<form onSubmit={this.loginForm} >
<input onChange={this.inputForm} value={us} name="us" type="text" placeholder="Username" required></input><br/>
<input onChange={this.inputForm} value={pass} name="pass" type="password" placeholder="<PASSWORD>" required></input><br/>
<br/>
<button onClick={this.loginForm} type="submit" >Login</button>
{/* <Link to="/Landing" className="navbar-item">xxx</Link> */}
</form>
</div>
);
}
}
<file_sep>/src/day25/listPresent.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom'
import { Button } from 'react-bootstrap'
export default class listPresent extends Component {
constructor(props) {
super(props);
this.state = {
userList1: [],
userList2: [],
userList3: [],
userList4: [],
cf: ''
};
}
componentDidMount() {
this.fetchData();
}
componentWillMount() {
if (localStorage.getItem('checklogin') !== '1') {
window.alert('Please login first !')
window.location.href = "/"
}
}
fetchData = async () => {
const response1 = await fetch('https://reqres.in/api/users?page=1')
const response2 = await fetch('https://reqres.in/api/users?page=2')
const response3 = await fetch('https://reqres.in/api/users?page=3')
const response4 = await fetch('https://reqres.in/api/users?page=4')
const jsonData1 = await response1.json();
const jsonData2 = await response2.json();
const jsonData3 = await response3.json();
const jsonData4 = await response4.json();
this.setState({ userList1: jsonData1.data })
this.setState({ userList2: jsonData2.data })
this.setState({ userList3: jsonData3.data })
this.setState({ userList4: jsonData4.data })
}
logoutConfirm = () => {
if (window.confirm("Are you sure to logout ?")) {
window.location.href = "/"
}
}
searchList = () => {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
sendId = (item) => {
localStorage.setItem('item', item)
console.log(item)
}
componentWillUnmount() {
localStorage.removeItem('checklogin')
}
render() {
const { userList1, userList2, userList3, userList4 } = this.state
return (
<div >
<div>
<h1>ListTurner</h1>
<input style={{ marginTop: '5%' }} onKeyUp={this.searchList} type="text" id="myInput" placeholder="Search for names.." />
<table id='myTable' className="table table-dark table-hover">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th></th>
</tr>
</thead>
<tbody>
{
userList1.map((item, index) => {
return (
<tr key={index}>
<td>{item.first_name}</td>
<td>{item.last_name}</td>
<td>{item.email}</td>
<td><Link to='/autoDetail'
onClick={() => { this.sendId(item.id) }}>{item.id}</Link></td>
</tr>
)
})
}
{
userList2.map((item, index) => {
return (
<tr key={index}>
<td>{item.first_name}</td>
<td>{item.last_name}</td>
<td>{item.email}</td>
<td><Link to='/autoDetail'
onClick={() => { this.sendId(item.id) }}>{item.id}</Link></td>
</tr>
)
})
}
{
userList3.map((item, index) => {
return (
<tr key={index}>
<td>{item.first_name}</td>
<td>{item.last_name}</td>
<td>{item.email}</td>
<td><Link to='/autoDetail'
onClick={() => { this.sendId(item.id) }}>{item.id}</Link></td>
</tr>
)
})
}
{
userList4.map((item, index) => {
return (
<tr key={index}>
<td>{item.first_name}</td>
<td>{item.last_name}</td>
<td>{item.email}</td>
<td><Link to='/autoDetail'
onClick={() => { this.sendId(item.id) }}>{item.id}</Link></td>
</tr>
)
})
}
</tbody>
</table>
</div>
<div style={{ position: 'fixed', top: '0px', right: '0px' }}>
<Button onClick={this.logoutConfirm} type="button" className='btn btn-danger'>logout</Button> <br />
</div>
</div>
);
}
}
<file_sep>/src/day11/InputPaladin.js
import React, { Component } from 'react';
export default class InputPaladin extends Component {
constructor(props) {
super(props)
this.state = {
result : '' ,
boolean : true
};
};
keepValue = (e) => {
const {name , value} = e.target
this.setState({[name] : Number(value)})
}
checkPaladin = (paladin) => {
paladin = "ZZZxZZZ"
var result = paladin.split(" ");
}
render() {
let {paladin , result , boolean} = this.state
return (
<div>
<input name="a" value={paladin} type='text' onChange={this.keepValue}></input>
<button onClick={this.checkPaladin} >X</button> <br/>
<center> : <b>{result} {boolean}</b></center> <hr/>
</div>
);
}
}
<file_sep>/src/day13_14/TheWord.js
import React, { Component } from 'react';
export default class TheWord extends Component {
constructor(props) {
super(props);
this.state = {
inputArray : '' ,
outWord : '' ,
printSum : ''
};
}
amendTheSentence = (e) => {
const { name, value } = e.target
this.setState({ [name]: String(value) })
this.setState({outWord : value.toUpperCase()})
console.log({value})
}
transformFunc = () => {
const {outWord , printSum} = this.state;
for(let i=0 ;i<outWord.length;i++){
var digit = outWord ;
var isUpperCase = digit === digit.toUpperCase();
if(isUpperCase){
var isFirst = i==0 ;
if(!isFirst){
printSum = printSum+" " ;
}
printSum = printSum+digit.toLowerCase() ;
} else {
printSum = printSum+digit ;
}
}
return printSum ;
}
render() {
const {outWord , printSum} = this.state;
return (
<div>
<div>
</div>
<div className="form-group">
<input onChange={this.amendTheSentence} type="text" className="form-control" name="a" aria-describedby="helpId"/>
<small id="helpId" className="form-text text-muted">Insert_text_to_transform</small>
<h2>{outWord}</h2>
<a onClick={this.transformFunc} href="button1" className="btn btn-primary active" role="button">Transform</a>
<h3>{printSum}</h3>
</div>
</div>
);
}
}
<file_sep>/src/day7/Compo.js
import React, { Component } from 'react'
class Compo extends Component {
constructor(props){
super(props)
this.state = {
cat : '' ,
dog : ''
}
}
clickbait = (a,b)=>{
console.log(a+b)
}
render() {
return(
<div>
<Compoa cat='SWOTCAT' clickbait={this.clickbait}></Compoa>
</div>
)
}
}
export default Compo ;
class Compoa extends Component {
constructor(props){
super(props)
this.state = {
a : 2 ,
b : 3
}
}
render() {
const {cat,clickbait ,a,b} = this.props
return(
<div>
<span>{cat}</span> <br/>
<button onClick={()=>{clickbait(a,b)}}
type="button" className="btn btn-primary btn-lg"
>Click</button>
</div>
)
}
}
class Compob extends Component {
constructor(props){
super(props)
this.state = {
}
}
render() {
return(
<div>
</div>
)
}
}<file_sep>/src/day11/Egg.js
import React from 'react'
class Egg extends React.Component{
constructor(props) {
super(props)
this.state = {
time : 0 ,
timeout : '' ,
};
setInterval(() => {
this.setState({
time : this.state.time + 1
})
}, 1000)
if(this.state.timeout===0){
console.log("Time OUt")
} else{
console.log("HI")
}
};
render(){
let {time} = this.state
return(
<div>
TIMEBOMB : {time}
</div>
)
}
}
export default Egg
/*
time : 17999
setInterval(() => {
this.setState({
time : this.state.time - 1
})
}, 1000) */<file_sep>/src/KeyProps_ArrayComponents/Day18ArrayComp.js
import React, { Component } from 'react';
export default class Day18ArrayComp extends Component {
constructor(props) {
super(props);
this.state = {
ruby: 'Boo Boo Test',
arrayList: [
{ ability: 'Str', id: 1 },
{ ability: 'Int', id: 2 },
{ ability: 'Dex', id: 3 },
{ ability: 'Asssasin', id: 0 },
]
}
}
render() {
return (
<div style={{ color: "red" }}>
<b>{this.state.ruby}</b>
{
this.state.arrayList.map((item, i) => (
<Showtime key={i} arrayList={item} />
)
)
}
</div>
)
}
}
class Showtime extends React.Component {
render() {
return (
<div>
<span>{this.props.arrayList.ability}</span>
<span>{this.props.arrayList.id}</span>
</div>
);
}
}
<file_sep>/src/day19_test/Landing.js
import React, { Component } from 'react';
// import { async } from 'q';
import { Link } from 'react-router-dom'
export default class Landing extends Component {
constructor(props) {
super(props);
this.state = {
userList: [],
storeId: "",
x: ""
};
}
componentWillMount() {
if (localStorage.getItem("key") == null) {
alert('please login first !')
window.location.href = "/";
}
}
componentDidMount() {
this.fetchData();
}
searchFunc = () => {
var input, filter, ul, li, a, i, txtValue;
input = document.getElementById('myInput');
filter = input.value.toUpperCase();
ul = document.getElementById("myUL");
li = ul.getElementsByTagName('li');
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
logOut = () => {
localStorage.removeItem("key")
alert('Logout Complete !')
window.location.href = "/";
}
fetchData = async () => {
// debugger;
const response = await fetch('https://reqres.in/api/users');
const jsonData = await response.json();
this.setState({ userList: jsonData.data })
// fetch('https://reqres.in/api/users')
// .then(function (response) {
// return response.json();
// })
// .then(function (myJson) {
// _this.setState({ userList: myJson.data })
// });
}
sendFunctionId = (item) => {
console.log(item)
localStorage.setItem("item", item)
}
render() {
const { userList } = this.state;
return (
<div>
<span><center><h1>Landing</h1></center></span>
{/* <button onClick={this.fetchData} type="button" className="btn btn-outline-primary">Search</button> */}
<br /><br />
<div> <center>
<table border="1" >
<thead>
<tr>
<th>Name</th>
<th>Lastname</th>
<th>Email</th>
<th></th>
</tr>
</thead>
<tbody>
{
userList.map((item, index) => {
return (
<tr key={index}>
<td>
{item.first_name}
</td>
<td>
{item.last_name}
</td>
<td>
{item.email}
</td>
<td>
<Link to="/Detail" className="navbar-item"
onClick={() => {
this.sendFunctionId(item.id)
}}>View</Link>
</td>
</tr>
)
})
}
</tbody>
</table>
<br /><br />
<div>
<div>
<form >
<input id="myInput" onKeyUp={this.searchFunc} type="text"></input> <br />
</form>
<br />
<ul id="myUL">
<li><Link to="/Detail" className="navbar-item">Str</Link></li>
<li><Link to="/DetailInt" className="navbar-item">Int</Link></li>
<li><Link to="/DetailDex" className="navbar-item">Dex</Link></li>
<li><a href="www.google.co.th">Jelly</a></li>
<li><a href="www.google.co.th">Soap</a></li>
<li><a href="www.google.co.th">Price</a></li>
<li><a href="www.google.co.th">Ghost</a></li>
</ul>
<button onClick={this.logOut} type="button" className="btn btn-outline-primary">Logout</button>
</div>
</div>
</center>
</div>
</div>
);
}
}
<file_sep>/src/day19_test/Detail.js
import React, { Component } from 'react';
export default class Detail extends Component {
constructor(props) {
super(props);
this.state = {
userDetail: "",
};
}
// componentWillMount() {
// localStorage.getItem("item");
// }
componentDidMount() {
this.fetchData();
}
fetchData = async () => {
const item = localStorage.getItem("item");
const response = await fetch('https://reqres.in/api/users/'+item);
const jsonData = await response.json();
this.setState({ userDetail: jsonData.data })
}
render() {
const { userDetail } = this.state;
// const {fromId} = this.props;
return (
<div>
<h1>Detail Is Here</h1>
<table border="5.5">
<thead>
<tr>
<th>
AVATAR
</th>
<th>
ID
</th>
<th>
E-MAIL
</th>
<th>
FIRSTNAME
</th>
<th>
LASTNAME
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<img src={userDetail.avatar} alt={userDetail.id} />
</td>
<td>
{userDetail.id}
</td>
<td>
{userDetail.email}
</td>
<td>
{userDetail.first_name}
</td>
<td>
{userDetail.last_name}
</td>
</tr>
</tbody>
</table>
</div>
);
}
}
<file_sep>/src/day11/FirstProject.js
import React from 'react'
import Egg from './Egg';
import Chicken from './Chicken';
class FirstProject extends React.Component {
constructor(props) {
super(props)
};
myAlert(){
alert("--------------------! Simon Says !--------------------")
}
render(){
return(
<div>
<Egg />
<Chicken AppAlert={this.myAlert}> </Chicken>
</div>
)
}
}
export default FirstProject<file_sep>/src/day4/AppCycle.js
import React from 'react';
//import App from './App';
import './day6/AppCycle.css';
class AppCycle extends React.Component {
constructor(Props){
super(Props);
this.state = {
cycletester : 'UX'
}
}
componentWillMount() {
console.log('Will Mount Will Making First');
}
//--------------------------------------------
componentDidMount() {
this.setState ({cycletester : 'Did Mount Change Value'}) // Function MethodsetState : AsyncoNize
console.log(this.state.cycletester);
}
//--------------------------------------------
// componentWillReceiveProps(nextProps) {
// if (this.props.count !== nextProps.count) {
// this.setState({count: nextProps.count});
// }}
//--------------------------------------------
// shouldComponentUpdate(nextProps, nextState) {
// if (this.props.count === nextState.count) {
// return false;
// } }
//--------------------------------------------
componentWillUpdate(nextProps, nextState) {
console.log(' Printf("Hello Will Update!")')
}
//--------------------------------------------
componentDidUpdate(prevProps, prevState) {
if (this.props.count === prevProps.count) {
console.log(' Printf("Hello Did Update!")')
}
}
//--------------------------------------------
// componentWillUnmount() {
// document.removeEventListener("click", SomeFunction);
// }
//--------------------------------------------
// componentDidCatch(error, info) {
// this.setState({hasError: true });
// }
//--------------------------------------------
render(){
const{cycletester}= this.state ;
return (
<div className="AppCycle">
<h1>{cycletester}</h1> <hr/>
<AppSup header="Life Cycle"> </AppSup>
</div>
)
}
}
export default AppCycle ;
class AppSup extends React.Component {
constructor(Props){
super(Props);
this.state = {
count : 0 ,
reset : 'Force Reset'
}
}
render(){
const { reset , count} = this.state ;
const { header } = this.props ;
return (
<div className="AppSup">
<h2>{header}</h2><br/>
<button onClick={()=>{this.setState({count : count + 1})}} type="button" className="btn btn-primary" > +{count} </button> <br/>
<button onClick={()=>{this.setState({count:0,})}} type="button" className="btn btn-outline-primary"> {reset} </button>
</div>
)
}
}<file_sep>/src/day23/ListTurner.js
import React, { Component } from 'react';
import '../App.css';
import { Link } from 'react-router-dom'
export default class ListTurner extends Component {
constructor(props) {
super(props);
this.state = {
userList: [],
cf: ''
};
}
componentDidMount() {
this.fetchData();
}
componentWillMount() {
if (localStorage.getItem('checklogin') !== '1') {
window.alert('Please login first !')
window.location.href = "/"
}
}
fetchData = async () => {
const response = await fetch('https://reqres.in/api/users')
const jsonData = await response.json();
this.setState({ userList: jsonData.data })
}
logoutConfirm = () => {
if (window.confirm("Are you sure to logout ?")) {
window.location.href = "/"
}
}
searchList = () => {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
sendId = (item) => {
localStorage.setItem('item',item)
console.log(item)
}
componentWillUnmount(){
localStorage.removeItem('checklogin')
}
render() {
const { userList } = this.state
return (
<div style={{ display: 'flex', justifyContent: 'center' }}>
<div>
<h1>ListTurner</h1>
<input style={{ marginTop: '10%' }} onKeyUp={this.searchList} type="text" id="myInput" placeholder="Search for names.." />
<table id='myTable' className="table table-dark table-hover">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th></th>
</tr>
</thead>
<tbody>
{
userList.map((item, index) => {
return (
<tr key={index}>
<td>{item.first_name}</td>
<td>{item.last_name}</td>
<td>{item.email}</td>
<td><Link to='/Details'
onClick={()=>{this.sendId(item.id)}}>{item.id}</Link></td>
</tr>
)
})
}
</tbody>
</table>
</div>
<div style={{ position: 'fixed', top: '0px', right: '0px' }}>
<button onClick={this.logoutConfirm} type="button" className="btn btn-danger">logout</button> <br />
</div>
</div>
);
}
}
|
c7075ad2e3792730f28357043c918247a493468c
|
[
"JavaScript"
] | 22
|
JavaScript
|
kaspeedza8/workshopKTB
|
9c7df37f2b6c698f98e60123fa2ce272723d1c9e
|
8eb379a5a5f7633e0523cb5157f3cc525da2d023
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DeterminerProchainJoueur
{
public class Poker
{
public int DetermineProchainJoueur(int DernierAAvoirParle, string[] TabDernieresDecisions)
{
return -2
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercice3
{
public class FichierExercice3
{
[TextFixture]
[Test]
}
}
|
f6231768c720d8c6ba3c7637845fd7b2553907e4
|
[
"C#"
] | 2
|
C#
|
mlarameecstj/Exercice3Alain
|
a07a4084af92e001b5ecdb8a5f43752f14f8d1e7
|
1e95104bdbee675565d780f409a269f8cda93255
|
refs/heads/master
|
<repo_name>jonasjohansson8908/jj-tools<file_sep>/requirements.txt
pytest>=5.3.5
coverage>=5.0.4
<file_sep>/README.md
[](https://travis-ci.com/jonasjohansson8908/jj-tools)
[](https://codecov.io/gh/jonasjohansson8908/jj-tools)
# jj-tools
A collection of tools, developed for my own use in python projects.
## Prerequisites
- Python 3.x
- Pytest 5.3.5
## Setup
## Testing
Run from root repo folder:
```
python3 -m pytest
```
<file_sep>/src/utils/progress.py
"""
progress.py is a scalable loading bar that uses carriage return to print and
update the progress on stdout. The percentage of the progress is also shown.
Author: <NAME>, <EMAIL>
"""
def update_progress(progress, msg_pre='', msg_post='', scaling=1):
"""Formats and prints the progress as a progress bar to stdout.
Args:
progress (int): The progress that is to be printed. Given as an integer value
between 0-100 which corresponds to the progress percentage.
msg_pre (str), optional: Message that if provided, will be shown before the
progress bar.
"""
# limit the progress to 0-100% and round to integer number
if progress > 100:
progress = 100
elif progress < 0:
progress = 0
else:
progress = round(progress)
# force scaling to integer value
if scaling < 1:
scaling = 1
else:
scaling = round(scaling)
# calculate filled and empty elements
n_filled = (scaling * progress // 10)
n_empty = scaling * 10 - n_filled
# print the progress bar
print('\r{0} [{1}] {2}% {3}'.format(msg_pre, '#' * n_filled + '-' * n_empty,
progress, msg_post), end='')
<file_sep>/tests/test_progress.py
"""
Tests for the functions of utils/progress.py
"""
from src.utils.progress import update_progress
def test_progress_bar(capsys):
"""
Tests of the function progress_bar()
"""
# test empty progress bar
update_progress(0)
captured = capsys.readouterr()
assert captured.out == ('\r [----------] 0% ')
# test negative input
update_progress(-2)
captured = capsys.readouterr()
assert captured.out == ('\r [----------] 0% ')
# test no progress with pre message
update_progress(0, msg_pre='installing')
captured = capsys.readouterr()
assert captured.out == ('\rinstalling [----------] 0% ')
# test no progress with post message
update_progress(0, msg_post='done')
captured = capsys.readouterr()
assert captured.out == ('\r [----------] 0% done')
# test no progress with pre and post message
update_progress(0, msg_pre='installing', msg_post='done')
captured = capsys.readouterr()
assert captured.out == ('\rinstalling [----------] 0% done')
# test float input
update_progress(79.9)
captured = capsys.readouterr()
assert captured.out == ('\r [########--] 80% ')
# test too large input
update_progress(150)
captured = capsys.readouterr()
assert captured.out == ('\r [##########] 100% ')
# test scaling < 1
update_progress(50, scaling=0.2)
captured = capsys.readouterr()
assert captured.out == ('\r [#####-----] 50% ')
# test scaled progress bar
update_progress(70, scaling=2)
captured = capsys.readouterr()
assert captured.out == ('\r [##############------] 70% ')
# test progress bar scaled with float
update_progress(70, scaling=2.6)
captured = capsys.readouterr()
assert captured.out == ('\r [#####################---------] 70% ')
|
1d137cdf43890adcc6d42d440d289ea36d6aac5c
|
[
"Markdown",
"Python",
"Text"
] | 4
|
Text
|
jonasjohansson8908/jj-tools
|
3c3bde3353b0259acfe47cfd8ab2d6e1b3d3796b
|
b57d491e2ac2b8cd7dbb255c3955c3878ff14870
|
refs/heads/master
|
<repo_name>schaapkabap/iprwc<file_sep>/src/app/shared/models/auth.model.ts
import {User} from './user.model';
export class Auth {
public user: User;
public token: string;
}
<file_sep>/src/app/shared/components/header/header.component.ts
import {Component, Input, OnInit, Output} from '@angular/core';
import {CartService} from '../../services/cart.service';
import {Observable} from 'rxjs';
import {UserService} from '../../services/user.service';
import {AuthenicationService} from '../../services/authenication.service';
import {Auth} from '../../models/auth.model';
import {User} from '../../models/user.model';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
total: number;
@Input() user: User;
constructor(private cart: CartService,
private authService: AuthenicationService) {
}
ngOnInit() {
this.cart.getWinkelwagen().subscribe(data => {
this.total = data.length;
});
this.authService.currentObserverUser().subscribe(data => {
if (data == null) {
this.user = new User();
} else {
this.user = data;
}
});
}
}
<file_sep>/src/app/app-routing.module.ts
import {NgModule} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';
import {ProfileComponent} from './pages/profile/profile.component';
import {LoginComponent} from './pages/login/login.component';
import {AuthGuard} from './shared/guards/auth.guard';
import {ProductComponent} from './pages/product/product.component';
import {LogoutComponent} from './pages/logout/logout.component';
import {ProductDetailComponent} from './pages/product/product-detail/product-detail.component';
import {CartComponent} from './pages/cart/cart.component';
import {ProductListComponent} from './pages/product/product-list/product-list.component';
import {ProductEditComponent} from './pages/product/product-edit/product-edit.component';
import {ProductNewComponent} from './pages/product/product-new/product-new.component';
import {CheckoutComponent} from './pages/checkout/checkout.component';
import {AdminPanelComponent} from './pages/admin-panel/admin-panel.component';
import {UserGuard} from './shared/guards/user.guard';
const routes: Routes = [
{
path: 'app/login',
component: LoginComponent
},
{
path: 'app/admin-panel',
component: AdminPanelComponent,
canActivate: [UserGuard]
},
{
path: 'app/logout',
component: LogoutComponent
},
{
path: 'app/product',
component: ProductComponent
},
{
path: 'app/product/new',
component: ProductNewComponent,
canActivate: [UserGuard]
},
{
path: 'app/product/edit/:id',
component: ProductEditComponent,
canActivate: [UserGuard]
},
{
path: 'app/product/:id',
component: ProductDetailComponent
},
{
path: 'app/profile',
component: ProfileComponent,
canActivate: [AuthGuard]
},
{
path: 'app/profile/edit',
component: ProfileComponent,
canActivate: [AuthGuard]
},
{
path: 'app/cart',
component: CheckoutComponent
},
{
path: '',
component: ProductComponent,
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
<file_sep>/src/app/shared/components/side-bar/side-bar.component.ts
import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {Router} from '@angular/router';
@Component({
selector: 'app-side-bar',
templateUrl: './side-bar.component.html',
styleUrls: ['./side-bar.component.scss']
})
export class SideBarComponent implements OnInit {
menu = false;
constructor() {
}
ngOnInit() {
}
toggleMenu() {
this.menu = !this.menu;
}
}
<file_sep>/src/app/shared/components/settings-button/settings-button.component.ts
import {Component, HostListener, Input, OnInit, Output} from '@angular/core';
import {Route, Router} from '@angular/router';
import {UserService} from '../../services/user.service';
import {AuthenicationService} from '../../services/authenication.service';
@Component({
selector: 'app-settings-button',
template: '<li class="nav-item"><a class="cursor nav-link">Profiel</a></li>',
styleUrls: ['./settings-button.component.scss']
})
export class SettingsButtonComponent implements OnInit {
@Input() path: String = '';
constructor(private router: Router,
private userService: UserService,
private authService: AuthenicationService) {
}
ngOnInit() {
}
@HostListener('click') onClick() {
const user = this.authService.currentUser;
if (user.username === 'admin') {
this.router.navigate(['/app/admin-panel']);
}
if (user != null) {
this.router.navigate(['/app/profile']);
}
}
}
<file_sep>/src/app/shared/models/user.model.ts
export class User {
public id: number;
public username: string;
public email: string;
static generateToken(username: string, password: string) {
return btoa(username + ':' + password);
}
}
<file_sep>/src/app/shared/services/cart.service.ts
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, Observable, of, Subject} from 'rxjs';
import {environment} from '../../../environments/environment';
import {Product} from '../models/product.model';
@Injectable({
providedIn: 'root'
})
export class CartService {
products: Product[] = [];
private total = new BehaviorSubject<Product[]>(this.products);
private singleProducts = new BehaviorSubject<Product[]>(this.products);
totaalprijs: number;
constructor() {
if (localStorage.getItem('winkelwagen') == null) {
localStorage.setItem('winkelwagen', JSON.stringify(this.products));
}
this.products = JSON.parse(localStorage.getItem('winkelwagen'));
this.updateCart();
}
addProduct(p: Product) {
this.products.push(p);
localStorage.setItem('winkelwagen', JSON.stringify(this.products));
this.updateCart();
}
deleteProduct(p: Product) {
for (let i = 0; i < this.products.length; i++) {
if (this.products[i].id === p.id) {
this.products.splice(i, 1);
localStorage.setItem('winkelwagen', JSON.stringify(this.products));
break;
}
}
this.updateCart();
}
getSingleProducts(): Observable<Product[]> {
return this.singleProducts;
}
// gettotaal(): Observable<number> {
// this.totaalprijs = 0;
// this.products.forEach((item, index) => {
// this.totaalprijs += item.price;
// });
// console.log(this.totaalprijs);
// return of(this.totaalprijs);
// }
private searchSingleProducts(products: Product[]) {
const singleProducts: Product[] = [];
for (let i = 0; i < products.length; i++) {
let k = true;
for (let j = 0; j < singleProducts.length; j++) {
if (products[i].id === singleProducts[j].id) {
k = false;
}
}
if (k) {
singleProducts.push(products[i]);
}
}
return singleProducts;
}
getWinkelwagen(): Observable<Product[]> {
return this.total;
}
private updateCart() {
this.total.next(this.products);
this.singleProducts.next(this.searchSingleProducts(this.products));
}
}
<file_sep>/src/app/pages/register/register.component.ts
import {Component, OnInit} from '@angular/core';
import {FormGroup, NgForm} from '@angular/forms';
import {AuthenicationService} from '../../shared/services/authenication.service';
import {UserService} from '../../shared/services/user.service';
import {User} from '../../shared/models/user.model';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
user: any;
public form: FormGroup;
constructor(private authService: AuthenicationService,
private userService: UserService,
) {
}
ngOnInit() {
this.user = new User();
}
onSubmit(f: NgForm) {
console.log(this.user);
this.userService.save(this.user).subscribe();
}
}
<file_sep>/src/app/pages/product/product-edit/product-edit.component.ts
import {Component, OnInit} from '@angular/core';
import {Product} from '../../../shared/models/product.model';
import {ProductService} from '../../../shared/services/product.service';
import {ActivatedRoute, Router} from '@angular/router';
import {HttpClient} from '@angular/common/http';
import {FormGroup, NgForm} from '@angular/forms';
@Component({
selector: 'app-product-edit',
templateUrl: './product-edit.component.html',
styleUrls: ['./product-edit.component.sass']
})
export class ProductEditComponent implements OnInit {
id: number;
private sub: any;
product: Product;
form: FormGroup;
constructor(private productService: ProductService,
private route: ActivatedRoute,
private http: HttpClient,
private router: Router) {
}
ngOnInit() {
this.product = new Product();
const id = +this.route.snapshot.params.id;
this.productService.get(id).subscribe(data => this.product = data);
}
onSubmit(f: NgForm) {
const valid = true;
if (f.form.valid && valid) {
this.productService.update(this.product).subscribe(() => {
this.router.navigate(['/app/product/', this.product.id]);
});
}
}
}
<file_sep>/src/app/shared/services/authenication.service.ts
import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Auth} from '../models/auth.model';
import {map} from 'rxjs/operators';
import {environment} from '../../../environments/environment';
import {User} from '../models/user.model';
import {BehaviorSubject, Observable} from 'rxjs';
@Injectable({providedIn: 'root'})
export class AuthenicationService {
user: BehaviorSubject<User> = new BehaviorSubject(null);
constructor(private http: HttpClient) {
this.load();
}
load() {
if (!localStorage.getItem('authenticated_user')) {
return;
}
const auth: Auth = JSON.parse(localStorage.getItem('authenticated_user'));
this.user.next(auth.user);
}
login(username: string, password: string): any {
const body = new FormData();
body.append('username', username);
body.append('password', <PASSWORD>);
return this.http.post<User>(environment.apiHostname + 'auth/login', body).pipe(map(data => {
const auth = new Auth();
const user = <User>data;
if (user) {
auth.user = user;
auth.token = User.generateToken(username, password);
this.user.next(auth.user);
localStorage.setItem('authenticated_user', JSON.stringify(auth));
}
return user;
}));
}
get currentUser(): User {
return this.user.getValue();
}
currentObserverUser(): Observable<User> {
return this.user;
}
logout() {
localStorage.removeItem('authenticated_user');
this.user.next(null);
}
}
<file_sep>/src/app/shared/interceptor/error.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AuthenicationService } from '../services/authenication.service';
import { ErrorInterceptorSkipHeader } from './skip.error.interceptor';
@Injectable({ providedIn: 'root' })
export class ErrorInterceptor implements HttpInterceptor {
constructor(private auth: AuthenicationService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (request.headers.has(ErrorInterceptorSkipHeader)) {
const headers = request.headers.delete(ErrorInterceptorSkipHeader);
return next.handle(request.clone({ headers }));
}
return next.handle(request).pipe(catchError(err => {
if (err.status === 401) {
// Logout
this.auth.logout();
location.reload();
}
return throwError(err.error.message || err.statusText);
}));
}
}
<file_sep>/src/app/pages/pages.module.ts
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {LoginModule} from './login/login.module';
import {ProfileComponent} from './profile/profile.component';
import {SideBarModule} from '../shared/components/side-bar/side-bar.module';
import {HeaderModule} from '../shared/components/header/header.module';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {RouterModule} from '@angular/router';
import {ProductComponent} from './product/product.component';
import {LogoutComponent} from './logout/logout.component';
import {ProductDetailComponent} from './product/product-detail/product-detail.component';
import {CartComponent} from './cart/cart.component';
import { ProductListComponent } from './product/product-list/product-list.component';
import { ProductEditComponent } from './product/product-edit/product-edit.component';
import {RegisterComponent} from './register/register.component';
import { ProductNewComponent } from './product/product-new/product-new.component';
import {SharedModule} from '../shared/shared.module';
import { AdminPanelComponent } from './admin-panel/admin-panel.component';
import { CheckoutComponent } from './checkout/checkout.component';
@NgModule({
declarations: [
ProfileComponent,
ProductComponent,
ProductDetailComponent,
CartComponent,
LogoutComponent,
ProductListComponent,
ProductEditComponent,
RegisterComponent,
ProductNewComponent,
AdminPanelComponent,
CheckoutComponent
],
imports: [
RouterModule,
CommonModule,
SharedModule,
LoginModule,
SideBarModule,
HeaderModule,
FormsModule,
ReactiveFormsModule
]
})
export class PagesModule {
}
<file_sep>/src/app/shared/services/user.service.ts
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {environment} from '../../../environments/environment';
import {User} from '../models/user.model';
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private http: HttpClient) { }
update(user: any): Observable<Object> {
return this.http.put(environment.apiHostname + 'users/me', user);
}
save(user: any): Observable<Object> {
return this.http.post(environment.apiHostname + 'users', user);
}
}
<file_sep>/src/app/app.module.ts
import {BrowserModule} from '@angular/platform-browser';
import {CUSTOM_ELEMENTS_SCHEMA, NgModule, NO_ERRORS_SCHEMA} from '@angular/core';
import {AppComponent} from './app.component';
import {ProjectModule} from './pages/project/project.module';
import {RegisterComponent} from './pages/register/register.component';
import {ProductComponent} from './pages/product/product.component';
import {ProductDetailComponent} from './pages/product/product-detail/product-detail.component';
import {ProfileComponent} from './pages/profile/profile.component';
import {AppRoutingModule} from './app-routing.module';
import {PagesModule} from './pages/pages.module';
import {AuthenicationService} from './shared/services/authenication.service';
import {HTTP_INTERCEPTORS, HttpClientModule} from '@angular/common/http';
import {BasicAuthInterceptor} from './shared/interceptor/basic.interceptor';
import {ErrorInterceptor} from './shared/interceptor/error.interceptor';
import {SharedModule} from './shared/shared.module';
import {SideBarModule} from './shared/components/side-bar/side-bar.module';
import {HeaderModule} from './shared/components/header/header.module';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
SideBarModule,
HeaderModule,
ProjectModule,
SharedModule,
PagesModule
],
providers: [
AuthenicationService,
{provide: HTTP_INTERCEPTORS, useClass: BasicAuthInterceptor, multi: true},
{provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true},
],
bootstrap: [AppComponent],
schemas: [ CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA ]
})
export class AppModule {
}
<file_sep>/src/app/pages/product/product.component.ts
import {Component, OnInit} from '@angular/core';
import {Product} from '../../shared/models/product.model';
import {ProductService} from '../../shared/services/product.service';
import {ActivatedRoute} from '@angular/router';
import {HttpClient} from '@angular/common/http';
import {CartService} from '../../shared/services/cart.service';
@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
id: number;
private sub: any;
products: Product[];
constructor(private productService: ProductService,
private http: HttpClient,
private cart: CartService) {
}
ngOnInit() {
this.products = Array<Product>();
console.log(this.cart.getWinkelwagen().subscribe(data => {
console.log(data);
}));
this.productService.getAll().subscribe(data => this.products = data);
}
addToCart(product: Product) {
this.cart.addProduct(product);
}
}
<file_sep>/src/app/pages/logout/logout.component.ts
import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {AuthenicationService} from '../../shared/services/authenication.service';
@Component({
selector: 'app-logout',
template: ' ',
styles: [' ']
})
export class LogoutComponent implements OnInit {
constructor(private auth: AuthenicationService, private route: Router) {
}
ngOnInit() {
this.auth.logout();
this.route.navigate(['app/login']);
}
}
<file_sep>/src/app/pages/product/product-detail/product-detail.component.ts
import {Component, OnInit} from '@angular/core';
import {ProductService} from '../../../shared/services/product.service';
import {ActivatedRoute} from '@angular/router';
import {HttpClient} from '@angular/common/http';
import {Product} from '../../../shared/models/product.model';
@Component({
selector: 'app-product-detail',
templateUrl: './product-detail.component.html',
styleUrls: ['./product-detail.component.css']
})
export class ProductDetailComponent implements OnInit {
id: number;
private sub: any;
product: Product;
constructor(private productService: ProductService,
private route: ActivatedRoute,
private http: HttpClient) {
}
ngOnInit() {
this.product = new Product();
const id = +this.route.snapshot.params.id;
this.productService.get(id).subscribe(data => this.product = data);
}
}
<file_sep>/src/app/shared/interceptor/skip.error.interceptor.ts
export const ErrorInterceptorSkipHeader = 'X-Skip-Error-Interceptor';
<file_sep>/src/app/app.component.ts
import {Component} from '@angular/core';
import {NavigationEnd, Router} from '@angular/router';
// declare ga as a function to set and sent the events
declare let ga: Function;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.sass']
})
export class AppComponent {
title = 'iprwc';
constructor(public router: Router) {
// subscribe to router events and send page views to Google Analytics
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
ga('set', 'page', event.urlAfterRedirects);
ga('send', 'pageview');
}
});
}
}
<file_sep>/src/app/shared/guards/user.guard.ts
import {Injectable} from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '@angular/router';
import {User} from '../models/user.model';
import {Auth} from '../models/auth.model';
@Injectable({
providedIn: 'root'
})
export class UserGuard implements CanActivate {
private user: Auth;
constructor(private router: Router) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (localStorage.getItem('authenticated_user')) {
this.user = JSON.parse(localStorage.getItem('authenticated_user'));
if (this.user.user.username === 'admin') {
return true;
}
}
this.router.navigate(['/app/login'], {queryParams: {url: state.url}});
return false;
}
}
<file_sep>/src/app/pages/product/product-list/product-list.component.ts
import {Component, OnInit} from '@angular/core';
import {ProductService} from '../../../shared/services/product.service';
import {HttpClient} from '@angular/common/http';
import {Product} from '../../../shared/models/product.model';
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.sass']
})
export class ProductListComponent implements OnInit {
id: number;
private sub: any;
products: Product[];
constructor(private productService: ProductService,
private http: HttpClient) {
}
ngOnInit() {
this.products = Array<Product>();
this.productService.getAll().subscribe(data => this.products = data);
}
deleteItem(product: Product) {
console.log(product.name);
this.products.slice(product.id);
this.productService.delete(product).subscribe(success => {
const index = this.products.indexOf(product, 0);
if (index > -1) {
this.products.splice(index, 1);
}
});
}
}
<file_sep>/src/app/shared/components/cart/add-to-cart-button/add-to-cart-button.component.ts
import {Component, HostListener, Input, OnInit} from '@angular/core';
import {Product} from '../../../models/product.model';
import {CartService} from '../../../services/cart.service';
import {Router} from '@angular/router';
@Component({
selector: 'app-add-to-cart-button',
template: '<button class="card-link btn btn-info">Add to Cart</button>',
styleUrls: ['./add-to-cart-button.component.sass']
})
export class AddToCartButtonComponent implements OnInit {
@Input() product: Product;
constructor(private cart: CartService,
private router: Router) {
}
ngOnInit() {
}
@HostListener('click') onClick() {
this.cart.addProduct(this.product);
this.router.navigate(['/app/product']);
}
}
<file_sep>/src/environments/environment.prod.ts
export const environment = {
production: true,
apiHostname: 'https://iprwc.schaapkabap.nl/api/',
};
<file_sep>/src/app/pages/profile/profile.component.ts
import { Component, OnInit } from '@angular/core';
import {FormGroup, NgForm} from '@angular/forms';
import {AuthenicationService} from '../../shared/services/authenication.service';
import {UserService} from '../../shared/services/user.service';
import {User} from '../../shared/models/user.model';
import {Router} from '@angular/router';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.scss']
})
export class ProfileComponent implements OnInit {
user: any;
form: FormGroup;
constructor(
private authService: AuthenicationService,
private userService: UserService,
private router: Router
) { }
ngOnInit() {
this.user = <any> this.authService.currentUser;
}
onSubmit(f: NgForm) {
let valid = true;
if (this.user.password.length !== 0 && this.user.password.length <= 5) {
valid = false;
alert('Uw wachtwoord voldoet niet aan de minimale lengte.');
}
if (f.form.valid && valid) {
this.userService.update(this.user).subscribe(() => {
// Login again
this.authService.login(this.user.username, this.user.password).subscribe(() => {
this.router.navigate(['/']);
});
});
}
}
}
<file_sep>/readme.txt
=+=URLS=+=
app/login,
app/admin-panel,
app/logout,
app/product,
app/product/new,
app/product/edit/2,
app/product/2,
app/profile,
app/profile/edit,
app/cart,
=+=Useraccounts=+=
Admin-account
Inloggevens:
gebruikersnaam: admin
wachtwoord: admin
Normale-gebruikers-account:
Inloggevens:
gebruikersnaam: test
wachtwoord: test<PASSWORD>
<file_sep>/src/app/shared/models/cart.model.ts
import {Product} from './product.model';
export class Cart {
public product: any;
}
<file_sep>/src/app/pages/cart/cart.component.ts
import {Component, OnInit, Output} from '@angular/core';
import {CartService} from '../../shared/services/cart.service';
import {Product} from '../../shared/models/product.model';
import {forEach} from '@angular/router/src/utils/collection';
import {isCombinedNodeFlagSet} from 'tslint';
@Component({
selector: 'app-card',
templateUrl: './cart.component.html',
styleUrls: ['./card.component.sass']
})
export class CartComponent implements OnInit {
public products: Product [] = [];
public singleProducts: Product[] = [];
@Output() total;
constructor(private cart: CartService) {
}
ngOnInit() {
this.cart.getWinkelwagen().subscribe(data => {
this.products = data;
console.log(this.products.length);
});
this.cart.getSingleProducts().subscribe(data => {
this.singleProducts = data;
this.total = this.counTotal();
console.log(data);
});
}
getTotal(product: Product) {
let singleProducts: Product[];
singleProducts = this.products.filter(singleProduct => (
product.id === singleProduct.id
));
return singleProducts.length;
}
counTotal(): number {
let total: number;
total = 0;
for (const product of this.products) {
total = total + product.price;
}
return total;
}
removeProductOfCart(product: Product) {
this.cart.deleteProduct(product);
}
addProductToCart(product: Product) {
this.cart.addProduct(product);
}
}
<file_sep>/src/app/pages/login/login.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LoginComponent } from './login.component';
import { ReactiveFormsModule } from '@angular/forms';
import {SideBarModule} from '../../shared/components/side-bar/side-bar.module';
import {HeaderModule} from '../../shared/components/header/header.module';
@NgModule({
declarations: [
LoginComponent
],
imports: [
CommonModule,
ReactiveFormsModule,
SideBarModule,
HeaderModule
]
})
export class LoginModule { }
<file_sep>/src/app/pages/product/product-new/product-new.component.ts
import { Component, OnInit } from '@angular/core';
import {FormGroup, NgForm} from '@angular/forms';
import {Product} from '../../../shared/models/product.model';
import {ProductService} from '../../../shared/services/product.service';
import {ActivatedRoute, Router} from '@angular/router';
import {HttpClient} from '@angular/common/http';
@Component({
selector: 'app-product-new',
templateUrl: './product-new.component.html',
styleUrls: ['./product-new.component.sass']
})
export class ProductNewComponent implements OnInit {
product: Product;
form: FormGroup;
constructor(private productService: ProductService,
private route: ActivatedRoute,
private http: HttpClient,
private router: Router) { }
ngOnInit() {
this.product = new Product();
}
onSubmit(f: NgForm) {
const valid = true;
if (f.form.valid && valid) {
this.productService.save(this.product).subscribe(() => {
this.router.navigate(['/app/product/']);
});
}
}
}
<file_sep>/src/app/shared/shared.module.ts
import {CUSTOM_ELEMENTS_SCHEMA, NgModule, NO_ERRORS_SCHEMA} from '@angular/core';
import {CommonModule} from '@angular/common';
import {AddToCartButtonComponent} from './components/cart/add-to-cart-button/add-to-cart-button.component';
import { CartComponent } from './components/cart/cart.component';
import { SettingsButtonComponent } from './components/settings-button/settings-button.component';
@NgModule({
declarations: [AddToCartButtonComponent, CartComponent, SettingsButtonComponent],
imports: [
CommonModule
],
exports: [AddToCartButtonComponent, SettingsButtonComponent]
})
export class SharedModule {
}
|
664f3d15482de9f324e220d0580226ae92fa36e5
|
[
"TypeScript",
"Text"
] | 30
|
TypeScript
|
schaapkabap/iprwc
|
1b54e01bfb6c6984c6f5fe1c7a757a71d5ebbc69
|
c2d5c7412894c09177ff95fdc01c5c5060f3511b
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
from __future__ import print_function
from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim, vmodl
from subprocess import call
import sys
import csv
import atexit
import ssl
import time
import getpass
import argparse
def conecta(vcenter, login, senha):
try:
context = None
if hasattr(ssl, '_create_unverified_context'):
context = ssl._create_unverified_context()
conn = SmartConnect(host=vcenter, user=login, pwd=<PASSWORD>, port=443, sslContext=context)
atexit.register(Disconnect, conn)
return conn.RetrieveContent()
except vmodl.MethodFault as e:
print("Falha vmodl: %s" % e.msg)
return 1
except Exception as e:
print("Falha excecao: %s" % str(e))
return 1
def get_args():
parser = argparse.ArgumentParser(prog='resizing',
description='Argumentos para alterar o flavor no Vcenter')
parser.add_argument('--arquivo','-a',
required=True,
action='store',
default=None,
help='Informe o arquivo a ser utilizado')
parser.add_argument('--workes','-w',
required=False,
action='store',
default=None,
help='Informe a quantidade de workes')
args = parser.parse_args()
return args
def get_obj(content, vimtype, name ):
obj = None
container = content.viewManager.CreateContainerView(
content.rootFolder, vimtype, True)
for c in container.view:
if name:
if c.name == name:
obj = c
break
else:
obj = c
break
return obj
def ler_arquivo( arquivo):
lista = []
with open(arquivo,"r",newline='') as file_csv:
linha_csv = csv.reader(file_csv, delimiter=';', quoting=csv.QUOTE_ALL)
for linha in linha_csv:
lista.append(linha)
file_csv.close()
return lista
def main():
args = get_args()
lista_arquivo = ler_arquivo(args.arquivo)
num_workers = args.workes
if __name__ == "__main__":
main()
<file_sep>### python teste
Vamos contruir projetos de Python e CI/CD ( ou tentar ).
<file_sep>VAGRANT_VM_PROVIDER = "virtualbox"
Vagrant.configure("2") do |config|
config.vm.define "node" do |node1|
node1.vm.box = "centos/7"
node1.vm.hostname = "node1"
node1.vm.network :private_network, ip: "192.168.10.2"
#node1.vm.provision "file", source: "/Users/mac/.ssh/id_rsa.pub", destination: "/home/vagrant/.ssh/me.pub"
#node1.vm.provision "shell", inline: "cat /home/vagrant/.ssh/me.pub >> /home/vagrant/.ssh/authorized_keys"
node1.vm.provision "shell", inline: "yum install -y https://dl.fedoraproject.org/pub/epel/7/x86_64/Packages/e/epel-release-7-11.noarch.rpm"
node1.vm.provision "shell", inline: "yum install -y python36.x86_64 python34-pip.noarch"
node1.vm.provision "shell", inline: "pip3 install --upgrade pip", privileged: "True"
node1.vm.provider :virtualbox do |v|
v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
v.customize ["modifyvm", :id, "--memory", 512]
v.customize ["modifyvm", :id, "--cpus", 1]
end
end
end
<file_sep>#!/usr/bin/env python
from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim, vmodl
import atexit
import ssl
import humanize
import argparse
def get_args():
parser = argparse.ArgumentParser(
description='Argumentos para migracao no Vcenter')
parser.add_argument('--name','-n',
required=True,
action='store',
default=None,
help='Nome do datastore ou datastore-cluster de origem ')
parser.add_argument('--destino','-d',
required=True,
action='store',
default=None,
help='Nome do datastore ou datastore-cluster de destino')
args = parser.parse_args()
return args
def wait_task(task, action='job', hideResult=False):
task_done = False
while not task_done:
if task.info.state == 'success':
return task.info.result
if task.info.state == 'error':
print("Tem erro na task")
task_done = True
def get_obj(content, vimtype, name ):
obj = None
container = content.viewManager.CreateContainerView(
content.rootFolder, vimtype, True)
for c in container.view:
if name:
if c.name == name:
obj = c
break
else:
obj = c
break
return obj
def Mostra_vm(vm):
vmconfig = vm.summary
print("Virtual Machine: ",vmconfig.config.name, "\nEstado: ", vmconfig.runtime.powerState,"\n")
def Mostra_datastore(datastore):
try:
summary = datastore.summary
capacity = summary.capacity
freeSpace = summary.freeSpace
uncommittedSpace = summary.uncommitted
freeSpacePercentage = (float(freeSpace) / capacity) * 100
print("=================================================")
print("Datastore name: ", summary.name)
print("Capacidade: ", humanize.naturalsize(capacity, binary=True))
utilizado = (capacity - freeSpace)
print("Utilizado: ", humanize.naturalsize(utilizado, binary=True))
if uncommittedSpace is not None:
provisionedSpace = (capacity - freeSpace) + uncommittedSpace
print("Provisionado: ", humanize.naturalsize(provisionedSpace,
binary=True))
print("Espaco livre: ", humanize.naturalsize(freeSpace, binary=True))
print("Percentual de espaco livre: " + str(freeSpacePercentage) + "%")
print("Virtual Machines: ",format(len(datastore.vm)))
vmList = datastore.vm
for vm in vmList:
Mostra_vm(vm)
print("=================================================")
except Exception as error:
print("Unable to access summary for datastore: ", datastore.name)
print(error)
pass
def get_vm(vm):
if vm is None:
print("Virtual machine nao encontrada")
exit(1)
else:
vm_details = vm.summary
return vm_details.config.name
def main():
args = get_args()
context = None
try:
conn = None
try:
if hasattr(ssl, '_create_unverified_context'):
context = ssl._create_unverified_context()
conn = SmartConnect(host="lxl1vmwvc001", user="<EMAIL>", pwd="<PASSWORD>", port=443, sslContext=context)
except IOError as e:
pass
atexit,register(Disconnect, conn)
atexit.register(Disconnect, conn)
content = conn.RetrieveContent()
print("============DataStore de Origem==================")
ori_datastore = get_obj(content,[vim.Datastore], args.name)
Mostra_datastore(ori_datastore)
print("============DataStore de Destino=================")
dest_datastore = get_obj(content,[vim.Datastore], args.destino)
Mostra_datastore(dest_datastore)
for vmList in dest_datastore.vm:
vm_name = get_vm(vmList)
vm_migrate = get_obj(content,[vim.VirtualMachine], vm_name)
migrate_priority = vim.VirtualMachine.MovePriority.defaultPriority
vm_relocate_spec = vim.vm.RelocateSpec()
vm_relocate_spec.datastore = dest_datastore
task = vm_migrate.Relocate(spec=vm_relocate_spec)
wait_task(task)
except vmodl.MethodFault as e:
print("Falha vmodl: %s" % e.msg)
return 1
except Exception as e:
print("Falha excecao: %s" % str(e))
return 1
# Start program
if __name__ == "__main__":
main()
<file_sep>#!/usr/bin/env python
import atexit
import argparse
import sys
import time
import ssl
from pyVmomi import vim, vmodl
from pyVim import connect
from pyVim.connect import Disconnect
def get_objeto(content, vimtype, name):
"""
Assossiando nome ao objeto
"""
obj = None
container = content.viewManager.CreateContainerView(content.rootFolder, vimtype, True)
for c in container.view:
if c.name == name:
obj = c
break
return obj
def wait_task(task, actionName='job', hideResult=False):
task_done = False
while not task_done:
if task.info.state == 'success':
return task.info.result
if task.info.state == 'error':
print("tem error na Task")
task_done = True
def main():
if hasattr(ssl, '_create_unverified_context'):
context = ssl._create_unverified_context()
try:
si = None
try:
si = connect.Connect(host="****", user="*****", pwd="****", port=443, sslContext=context)
except IOError as e:
pass
atexit,register(Disconnect, si)
content = si.RetrieveContent()
datacenter = get_objeto(content, [vim.Datacenter],'CCTI')
vmFolder = datacenter.vmFolder
vm = get_objeto(content, [vim.VirtualMachine], 'tf-leandro001')
destination_host = get_objeto(content, [vim.HostSystem], 'xvd042.df.intrabb.bb.com.br')
destination_storage = get_objeto(content, [vim.Datastore],'VMW_LAB_VSPHERE_dvol1')
resource_pool = get_objeto(content, [vim.ResourcePool], 'LAB')
if vm.runtime.powerState == 'powerOff':
print('Alerta! Migracao apenas para vm power OFF')
sys.exit()
migrate_priority = vim.VirtualMachine.MovePriority.defaultPriority
msg = " Migrando tf-leandro001 para DataStore %s " % (destination_storage)
print(msg)
"""
A magia começa aqui
"""
vm_relocate_spec = vim.vm.RelocateSpec()
vm_relocate_spec.host = destination_host
vm_relocate_spec.pool = resource_pool
#vm_relocate_spec.folder = vmFolder
vm_relocate_spec.datastore = destination_storage
task = vm.Relocate(spec=vm_relocate_spec)
"""
esperando terminar a migracao
"""
wait_task(task)
except vmodl.MethodFault as e:
print("Falha vmodl: %s" % e.msg)
return 1
except Exception as e:
print("Falha excecao: %s" % str(e))
return 1
#star program
if __name__ == "__main__":
main()
<file_sep>#!/usr/bin/env python
from __future__ import print_function
from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim
import atexit
import ssl
import humanize
def get_obj (vim_type, name=None):
obj = None
container = content.viewManager.CreateContainerView(
content.rootFolder, vim_type, True)
if name:
for c in container.view:
if c.name == name:
obj = c
return [obj]
else:
return container.view
def PrintDataInfo(datastore):
try:
summary = datastore.summary
capacity = summary.capacity
freeSpace = summary.freeSpace
uncommittedSpace = summary.uncommitted
freeSpacePercentage = (float(freeSpace) / capacity) * 100
print("=================================================")
print("Datastore name: ", summary.name)
print("Capacidade: ", humanize.naturalsize(capacity, binary=True))
if uncommittedSpace is not None:
provisionedSpace = (capacity - freeSpace) + uncommittedSpace
print("Provisionado: ", humanize.naturalsize(provisionedSpace,
binary=True))
print("Espaco livre: ", humanize.naturalsize(freeSpace, binary=True))
print("Percentual de espaco livre: " + str(freeSpacePercentage) + "%")
print("Virtual Machines: ",format(len(datastore.vm)))
print("=================================================")
except Exception as error:
print("Unable to access summary for datastore: ", datastore.name)
print(error)
pass
def main():
context = None
if hasattr(ssl, '_create_unverified_context'):
context = ssl._create_unverified_context()
conn = SmartConnect(host="***", user="***********", pwd="*********", port=443, sslContext=context)
atexit.register(Disconnect, conn)
content = conn.RetrieveContent()
for datacenter in content.rootFolder.childEntity:
datastores = datacenter.datastore
for ds in datastores:
PrintDataInfo(ds)
return 0
# Start program
if __name__ == "__main__":
main()
|
b3f318a88812306fc8b8b4f8c5731827ff291809
|
[
"Markdown",
"Python",
"Ruby"
] | 6
|
Python
|
leandrosb/python
|
3559794c7f647a5f127efdf7b1f4dc7a92e92868
|
31fa14489df97ec6dfd96a465179d793c1dfa0eb
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.