add json func

This commit is contained in:
2022-04-03 09:04:24 +03:00
parent 909cd73762
commit a42013753a
39 changed files with 83 additions and 0 deletions

6
~/CSS/README.md Normal file
View File

@@ -0,0 +1,6 @@
# CSS
- [`@font-face`](font-face.css) - пример добавления шрифта из файла
- [Pixel Art](pixel-art.css) - настройки для рендера Pixel Art на `canvas`
- [Список без точек](ul-remove-bullets.css) - убираем точки (bullet) в списках
- [BG Image cover](back-image-cover.css) - Фоновое изображение по центру

View File

@@ -0,0 +1,8 @@
body{
margin: 0px;
height: 100vh;
background-image: url('../img/landing.jpg');
background-size: cover;
background-position: center center;
background-repeat: no-repeat;
}

8
~/CSS/font-face.css Normal file
View File

@@ -0,0 +1,8 @@
@font-face {
font-family: 'MyWebFont';
src: url('webfont.eot'); /* IE9 Compat Modes */
src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('webfont.woff') format('woff'), /* Modern Browsers */
url('webfont.ttf') format('truetype'), /* Safari, Android, iOS */
url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}

7
~/CSS/pixel-art.css Normal file
View File

@@ -0,0 +1,7 @@
canvas {
image-rendering: crisp-edges;
image-rendering: pixelated;
}
/* JavaScript */
/* context.imageSmoothingEnabled = false; */

View File

@@ -0,0 +1,3 @@
ul {
list-style-type: none;
}

5
~/HTML/README.md Normal file
View File

@@ -0,0 +1,5 @@
# HTML
- [favicons.html](favicons.html)
- [anchors.html](anchors.html) - Пример использования якоря на странице
- [humans.txt](humans.txt)

3
~/HTML/anchors.html Normal file
View File

@@ -0,0 +1,3 @@
<p><a name="top"></a></p>
<p>...</p>
<p><a href="#top">Наверх</a></p>

9
~/HTML/favicons.html Normal file
View File

@@ -0,0 +1,9 @@
<head>
<!-- Icons -->
<link rel="apple-touch-icon" sizes="180×180" href="apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="120×120" href="favicon-120x120.png">
<link rel="icon" type="image/png" sizes="32×32" href="favicon-32×32.png">
<link rel="icon" type="image/png" sizes="16×16" href="favicon-16×16.png">
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="manifest" href="site.webmanifest">
</head>

10
~/HTML/humans.txt Normal file
View File

@@ -0,0 +1,10 @@
/* SITE */
Last Updated: Thu JNov 18 01:24 AM MSK 2021
Components: Null
/* TEAM */
Chef: Alexander Popov
Contacts: iiiypuk [at] iiiypuk.me
Twitter: @_iiiypuk
Ko-Fi: iiiypuk
From: Russia

17
~/HTTP/README.md Normal file
View File

@@ -0,0 +1,17 @@
# HTTP status code
## Информационные
## Успех
- `200` `OK` — успешный запрос
- `201` `Created` — в результате успешного выполнения запроса был создан новый ресурс
## Перенаправление
## Ошибка клиента
- `400` `Bad Request` — сервер обнаружил в запросе клиента синтаксическую ошибку
- `401` `Unauthorized` — для доступа к запрашиваемому ресурсу требуется аутентификация
- `403` `Forbidden` — сервер понял запрос, но он отказывается его выполнять из-за ограничений в доступе для клиента к указанному ресурсу
- `404` `Not Found` — ошибка в написании адреса Web-страницы. Сервер понял запрос, но не нашёл соответствующего ресурса по указанному URL
## Ошибка сервера

21
~/JavaScript/README.md Normal file
View File

@@ -0,0 +1,21 @@
# JavaScript
## Basic
- [Arrays](arrays.js) - работа с массивами
- [Spread syntax](spread.js) - распаковка массива в аргументы
- [fetch](fetch.js) - ...
- [location.href](location.href.js) - Переход на другую страницу
- [Text Content](textContent.js) - Получить текстовое содержимое элемента
- [Add DOM Elements](addElements.js) - Добавление элементов в DOM
- [Add Class](addClass.js) - Добавление/Удаление классов
## Other
- [Webpack](webpack.md) example config
## Canvas
- [Drawing text](drawing-text.js) - примеры рисования текста на CANVAS
- [`measureText()`](measureText.js) - возвращает информацию об измеренном тексте, например ширину
- [`drawImage()`](canvas.drawImage.js) - метод Canvas 2D API рисования изображения на холсте
## GameDev
- Canvas [GameLoop](gameloop.js) example

5
~/JavaScript/addClass.js Normal file
View File

@@ -0,0 +1,5 @@
// Use element.classList.add to add a class:
element.classList.add('my-class');
// And element.classList.remove to remove a class:
element.classList.remove('my-class');

View File

@@ -0,0 +1,3 @@
let newDiv = document.createElement('div');
newDiv.appendChild(document.createTextNode('some text'));
document.body.appendChild(newDiv);

17
~/JavaScript/arrays.js Normal file
View File

@@ -0,0 +1,17 @@
let cats = ['Bob', 'Willy', 'Mini'];
// pop(): Remove an item from the end of an array
// pop() returns the removed item
cats.pop(); // ['Bob', 'Willy']
// push(): Add items to the end of an array
// push() returns the new array length
cats.push('Mini'); // ['Bob', 'Willy', 'Mini']
// shift(): Remove an item from the beginning of an array
// shift() returns the removed item
cats.shift(); // ['Willy', 'Mini']
// unshift(): Add items to the beginning of an array
// unshift() returns the new array length.
cats.unshift('Puff', 'George'); // ['Puff', 'George', 'Willy', 'Mini']

View File

@@ -0,0 +1,44 @@
// void ctx.drawImage(image, dx, dy);
// void ctx.drawImage(image, dx, dy, dWidth, dHeight);
// void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
// image
// Элемент для отображения в контексте.
// Функция принимает любой источник изображения, пригодный для отображения
// на холсте
// dx
// Координата по оси Х, обозначающая стартовую точку холста-приёмника,
// в которую будет помещён верхний левый угол исходного image.
// dy
// Координата по оси Y, обозначающая стартовую точку холста-приёмника,
// в которую будет помещён верхний левый угол исходного image.
// dWidth
// Ширина изображения, полученного из исходного image.
// Эта опция позволяет масштабировать изображение по ширине.
// Если опция не задана, изображение не будет масштабировано.
// dHeight
// Высота изображения, полученного из исходного image.
// Эта опция позволяет масштабировать изображение по высоте.
// Если опция не задана, изображение не будет масштабировано.
// sx
// Координата по оси X верхнего левого угла фрагмента,
// который будет вырезан из изображения-источника и помещён в контекст-приёмник.
// sy
// Координата по оси Y верхнего левого угла фрагмента,
// который будет вырезан из изображения-источника и помещён в контекст-приёмник.
// sWidth
// Ширина фрагмента, который будет вырезан из изображения источника
// и помещён в контекст-приёмник. Если не задана, фрагмент от точки,
// заданной sx и sy до правого нижнего угла источника
// будет целиком скопирован в контекст-приёмник.
// sHeight
// Высота фрагмента, который будет вырезан из изображения источника
// и помещён в контекст-приёмник.
function Draw() {
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let image = document.getElementById('source');
ctx.drawImage(image, 33, 71, 104, 124, 21, 20, 87, 104);
}

View File

@@ -0,0 +1,14 @@
function Draw() {
let context = document.getElementById('canvas').getContext('2d');
// Styling text
// font = value
// textAlign = value | *start, end, left, right, center
// textBaseline = value | top, hanging, middle, *alphabetic, ideographic, bottom
// direction = value | ltr, rtl, *inherit
// fillText(text, x, y [, maxWidth])
// strokeText(text, x, y [, maxWidth])
context.font = '48px serif';
context.fillText('Hello world', 10, 50);
}

3
~/JavaScript/fetch.js Normal file
View File

@@ -0,0 +1,3 @@
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));

113
~/JavaScript/gameloop.js Normal file
View File

@@ -0,0 +1,113 @@
// Main variables
let DEBUG = true;
let canvas;
let context;
let cW;
let cH;
// FPS
let secondsPassed;
let oldTimeStamp;
let fps;
let dragging = false;
function mMove(e) {
'use strict';
if (dragging) {
point.pX = e.offsetX * cW / canvas.clientWidth | 0;
point.pY = e.offsetY * cH / canvas.clientHeight | 0;
};
}
function mDown(e) {
'use strict';
dragging = true;
}
function mUp(e) {
'use strict';
dragging = false;
}
function clearContext() {
'use strict';
context.fillStyle = '#b27e56';
context.fillRect(0, 0, cW, cH);
}
// Init
window.onload = function() {
'use strict';
canvas = document.getElementById('game');
context = canvas.getContext('2d');
cW = canvas.width;
cH = canvas.height;
canvas.style.height = window.innerHeight + "px";
if (DEBUG) {
console.log('Canvas set size to ' + window.innerHeight + 'px');
console.log(canvas.getBoundingClientRect());
};
canvas.addEventListener('mousedown', mDown, false);
canvas.addEventListener('mouseup', mUp, false);
canvas.addEventListener('mousemove', mMove, false);
canvas.addEventListener('touchstart', mDown, false);
canvas.addEventListener('touchend', mUp, false);
canvas.addEventListener('touchmove', mMove, false);
window.requestAnimationFrame(gameLoop);
};
window.addEventListener('resize', function() {
'use strict';
let canvas = document.getElementById('game');
canvas.style.height = window.innerHeight + "px";
if (DEBUG) {
console.log('Canvas resized to ' + window.innerHeight + 'px');
console.log(canvas.getBoundingClientRect());
};
}, true);
// GameLoop
function gameLoop(timeStamp) {
'use strict';
// fps counter
secondsPassed = (timeStamp - oldTimeStamp) / 1000;
oldTimeStamp = timeStamp;
fps = Math.round(1 / secondsPassed);
// end fps counter
update();
draw();
if (DEBUG) {
context.font = '15px Arial';
context.fillStyle = '#101024';
context.fillText('FPS: ' + fps, 10, 20);
};
window.requestAnimationFrame(gameLoop);
}
function update() {
'use strict';
//
}
function draw() {
'use strict';
clearContext();
}

View File

@@ -0,0 +1,4 @@
// Перейти на нужную страницу можно с помощью JavaScript
// document.location.href = "https://www.site";
document.location.href = url.value;

View File

@@ -0,0 +1,5 @@
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let text = ctx.measureText('Hello world');
console.log(text.width); // 56;

11
~/JavaScript/spread.js Normal file
View File

@@ -0,0 +1,11 @@
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers));
// expected output: 6
console.log(sum.apply(null, numbers));
// expected output: 6

View File

@@ -0,0 +1,3 @@
document.getElementById('element').textContent;
// If you need to target < IE9 then you need to use
document.getElementById('element').innerText;

33
~/JavaScript/webpack.md Normal file
View File

@@ -0,0 +1,33 @@
## WebPack
`packages.json`
```json
"scripts": {
"serve": "webpack serve",
"html": "html-minifier --collapse-whitespace --remove-comments src/index.html --output dist/index.html",
"css": "csso src/styles.css --output dist/styles.css",
"build": "npm run html && npm run css && webpack --mode=production"
},
"devDependencies": {
"webpack": "^5.42.0",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2"
}
```
`webpack.config.js`
```javascript
const path = require('path');
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'engine.js',
},
devServer: {
contentBase: path.join(__dirname, 'src'),
compress: false,
port: 55555,
},
};
```

1
~/PHP/Fenom.md Normal file
View File

@@ -0,0 +1 @@
# Fenom

11
~/PHP/README.md Normal file
View File

@@ -0,0 +1,11 @@
# PHP
## std
- [`gettype`](gettype.php) - Возвращает тип переменной
- [`in_array`](in_array.php) - Проверяет, присутствует ли значение в массиве
- [`json_decode`](json_decode.php) - Декодирует строку JSON
- [`json_encode`](json_encode.php) - Возвращает JSON-представление данных
- [`SQLite3`](sqlite3.php) - Простой использования класса SQLite3
## Libs
- [`Fenom`](Fenom.md) - fenom

18
~/PHP/gettype.php Normal file
View File

@@ -0,0 +1,18 @@
<?php
// gettype(mixed $value): string
$value = 1;
// Return Values
// Possible values for the returned string are:
//
// "boolean"
// "integer"
// "double" (for historical reasons "double" is returned in case of a float, and not simply "float")
// "string"
// "array"
// "object"
// "resource"
// "resource (closed)" as of PHP 7.2.0
// "NULL"
// "unknown type"
?>

10
~/PHP/in_array.php Normal file
View File

@@ -0,0 +1,10 @@
<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo("Got Irix");
}
if (in_array("mac", $os)) {
echo("Got mac");
}
?>

43
~/PHP/json_decode.php Normal file
View File

@@ -0,0 +1,43 @@
<?php
/*
json_decode(
string $json,
?bool $associative = null,
int $depth = 512,
int $flags = 0
): mixed
*/
/*
json
Строка (string) json для декодирования.
Эта функция работает только со строками в кодировке UTF-8.
associative
Если true, объекты JSON будут возвращены как ассоциативные массивы (array);
если false, объекты JSON будут возвращены как объекты (object).
Если null, объекты JSON будут возвращены как ассоциативные массивы (array)
или объекты (object) в зависимости от того,
установлена ли JSON_OBJECT_AS_ARRAY в flags.
depth
Максимальная глубина вложенности структуры,
для которой будет производиться декодирование.
flags
Битовая маска из констант JSON_BIGINT_AS_STRING, JSON_INVALID_UTF8_IGNORE,
JSON_INVALID_UTF8_SUBSTITUTE, JSON_OBJECT_AS_ARRAY, JSON_THROW_ON_ERROR.
Поведение этих констант описаны на странице JSON-констант.
*/
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
?>

31
~/PHP/json_encode.php Normal file
View File

@@ -0,0 +1,31 @@
<?php
/*
json_decode(
string $json,
?bool $associative = null,
int $depth = 512,
int $flags = 0
): mixed
*/
/*
value
value - значение, которое будет закодировано.
Может быть любого типа, кроме resource.
flags
Битовая маска, составляемая из значений JSON_FORCE_OBJECT, JSON_HEX_QUOT,
JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_INVALID_UTF8_IGNORE,
JSON_INVALID_UTF8_SUBSTITUTE, JSON_NUMERIC_CHECK, JSON_PARTIAL_OUTPUT_ON_ERROR,
JSON_PRESERVE_ZERO_FRACTION, JSON_PRETTY_PRINT, JSON_UNESCAPED_LINE_TERMINATORS,
JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE, JSON_THROW_ON_ERROR.
Смысл этих констант объясняется на странице JSON-констант.
depth
Устанавливает максимальную глубину. Должен быть больше нуля.
*/
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>

21
~/PHP/sqlite3.php Normal file
View File

@@ -0,0 +1,21 @@
<?php
/**
* Простой пример расширения класса SQLite3 и изменения параметров конструктора.
* После чего использование метода open для инициализации БД.
*/
class MyDB extends SQLite3
{
function __construct()
{
$this->open('mysqlitedb.db');
}
}
$db = new MyDB();
$db->exec('CREATE TABLE foo (bar STRING)');
$db->exec("INSERT INTO foo (bar) VALUES ('This is a test')");
$result = $db->query('SELECT bar FROM foo');
var_dump($result->fetchArray());
?>

View File

@@ -0,0 +1,10 @@
## Legend
- 🐛 - Bug
- ✔️ - Fixed
- ❌ - Removed
- - Added
- - Information
- ♻️ - Edited
## 0.1.0 - [17/04/2021] - (not work)
-

View File

@@ -0,0 +1 @@
-

View File

@@ -0,0 +1,37 @@
settings =
{
orientation =
{
default = "portrait",
supported = { "portrait", },
},
android =
{
usesPermissions =
{
"android.permission.INTERNET",
},
},
iphone =
{
xcassets = "Images.xcassets",
plist =
{
UIStatusBarHidden = false,
UILaunchStoryboardName = "LaunchScreen",
},
},
plugins =
{
},
excludeFiles =
{
all = { "Icon.png", "Icon-*dpi.png", "Images.xcassets", },
android = { "LaunchScreen.storyboardc", },
},
}

View File

@@ -0,0 +1,18 @@
application =
{
content =
{
width = 1080,
height = 1920,
scale = "letterbox",
fps = 60,
--[[
imageSuffix =
{
["@2x"] = 2,
["@4x"] = 4,
},
--]]
},
}

View File

View File

@@ -0,0 +1,70 @@
local composer = require('composer')
local scene = composer.newScene()
local groupBack
local groupMain
local groupUI
function gameLoop()
--
end
local function onFrame(event)
--
end
function scene:create(event)
local sceneGroup = self.view
groupBack = display.newGroup()
groupMain = display.newGroup()
groupUI = display.newGroup()
local debugRect = display.newRect(display.contentCenterX, display.contentCenterY, display.contentWidth, display.contentHeight )
debugRect:setFillColor(0.807, 0.925, 0.956)
end
function scene:show(event)
local sceneGroup = self.view
local phase = event.phase
if (phase == "will") then
-- Code here runs when the scene is still off screen (but is about to come on screen)
elseif (phase == "did") then
gameLoopTimer = timer.performWithDelay(500, gameLoop, 0)
end
end
function scene:hide(event)
local sceneGroup = self.view
local phase = event.phase
if (phase == "will") then
-- Code here runs when the scene is on screen (but is about to go off screen)
elseif (phase == "did") then
-- Code here runs immediately after the scene goes entirely off screen
end
end
function scene:destroy(event)
local sceneGroup = self.view
-- Code here runs prior to the removal of scene's view
end
scene:addEventListener('create', scene)
scene:addEventListener('show', scene)
scene:addEventListener('hide', scene)
scene:addEventListener('destroy', scene)
Runtime:addEventListener('enterFrame', onFrame)
return scene

3
~/nginx/README.md Normal file
View File

@@ -0,0 +1,3 @@
# nginx
- [`redirect`](redirect)

24
~/nginx/redirect.conf Normal file
View File

@@ -0,0 +1,24 @@
server {
listen 80;
server_name SITE_URL;
location /robots.txt {
root FOLDER;
}
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
server_name SITE_URL;
ssl_certificate PATH_TO_PEM;
ssl_certificate_key PATH_TO_PEM;
root FOLDER;
}