serveless aws gcp speed
html5 jquery bootstrap modal load No Jquery
Usually use jquery load url
https://stackoverflow.com/questions/34503683/jquery-to-open-bootstrap-v3-modal-of-remote-url
Only use html5
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
https://stackoverflow.com/questions/17636528/how-do-i-load-an-html-page-in-a-div-using-javascript
<a href="url ooxxooxx" data-toggle="modal" data-target="#myModal" onclick="myModal(this)">
click me
</a>
<div id="part3dviewModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<p>Loading...</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
function myModal(o){
p = document.querySelector("#myModal .modal-body");
p.innerHTML = '<object type="text/html" data="' + o.href + '" ></object>';
}
</script>
Search two time then change paginate table record have problem
laravel controller use class but no pass class ?
class PostController extends Controller
{
public function update(Post $post,
before
class PostController extends Controller
{
public function update($post_id,
$post = Post::findOrFail($post_id);
And many more things.
file_put_contents failed to open stream: Permission denied /tmp/cache/views/
php artisan view:clear
https://laracasts.com/discuss/channels/laravel/permission-denied-on-storageframeworkviews
https://laravel.io/forum/07-06-2016-session-permissions-issue
https://laracasts.com/discuss/channels/general-discussion/laravel-framework-file-permission-security
laravel livewire file update Real-Time File Validation mutile files
https://laravel-news.com/livewire-file-upload
use Livewire\Component;
use Livewire\WithFileUploads;
class Show extends Component
{
use WithFileUploads;
public $files = [];
public function updatedFiles() // 即時檢查檔案格式
{
$this->validate([
'files.*' => 'image|max:1024', // 1MB Max
]);
}
public function store()
{
$filenames = collect($this->photos)->map->store('photos');
'files' => $filenames->implode(','),
updatedFiles() is Hook into the “updated”
updatedPhoto public $Photo
updatedPhotos public $photos = []
updatedFile public $file
updatedFiles public $files = []
laravel livewire Name problem
Use - and lowwercase
App/Http/Livewire/Order/DropdownMaterial.php
class DropdownMaterial extends Component
{
resources/views/livewire/order/create.blade.php
@livewire('order.dropdown-material', ['post' => $order_material_id])
Laravel livewire have Big Problem!
Must have Div At first.
<div style="text-align: center">
<button wire:click="increment">+</button>
<h1>{{ $count }}</h1>
</div>
<div>
<button wire:click="increment">+</button>
<h1>{{ $count }}</h1>
<button class="btn btn-success btn-block" wire:click="create">
{{ trans('global.add') }} {{ trans('cruds.order.title_singular') }}
</button>
</div>
laravel livewire namespace
namespace App\Http\Livewire;
use Gate;
use Livewire\Component;
use Symfony\Component\HttpFoundation\Response;
class Orders extends Component
{
public function render()
{
abort_if(Gate::denies('order_access'), Response::HTTP_FORBIDDEN, '403 Forbidden');
return view('livewire.order');
}
}
resources/views/livewire/order.blade.php
@extends('layouts.app')
@section('content')
@livewire('order.show')
@endsection
App/Http/Livewire/Order/Show.php
namespace App\Http\Livewire\Order;
public function render()
{
abort_if(Gate::denies('order_access'), Response::HTTP_FORBIDDEN, '403 Forbidden');
$this->orders = Order::all();
// Order::where('owner_id', auth()->id())->get(); // 只能看自己
return view('livewire.order.show');
}
resources/views/livewire/order/show.blade.php
{{ virables }}
laravel eloquent orm
[one to one]
Table: User, Phone
Model: User
Relation: return $this->hasOne('App\Phone');
Talbe Phone need have user_id. Auto use User id -> Phone user_id
Table: User, Phone
Model: Phone
Relaion: return $this->belongsTo('App\User');
Table Phone need have user_id. Auto use User id -> User user_id
[one to many]
Table: Post, Comment
Model: Post
Relation: return $this->hasMany('App\Comment');
Table Comment need have post_id. Auto use Post id -> Comment post_id
Table: Post, Comment
Model: Comment
Relaion: return $this->belongsTo('App\Post');
Table Comment need have post_id. Auto Post id -> Comment post_id
[Many To Many]
Table: User, Role, Role_User
Table Role_User must have user_id, role_id
Model: User
way1:
Relaion: return $this->belongsToMany('App\Role', 'role_user');
way2:
Relaion: return $this->belongsToMany('App\Role');
Must database/migrations defined talbe class like "CreateRoleUserPivotTable"
livewire laravel route problem!
protected $namespace = 'App\Http\Controllers';
...
$this->routes(function () {
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
});
Add backup namespace then get problem for livewire. Every route just use App\Http|controllers ooxxooxxooxx.
OLD Way
web.php
Route::resource('users', 'UsersController');
Route::delete('users/destroy', 'UsersController@massDestroy');
Get Error
Route::resource('orders', 'livewire.order');
Route::resource('orders', 'livewire@order');
Route::view('orders', [\App\Http\Livewire\Order::class, 'render']);
Maybe Way
web.php
Route::view('orders', 'livewire.order');
Files:
\app\Http\Livewire\Order.php inside use return view('livewire.order');
\resources\views\livewire\order.blade.php
Get Error
Undefined variable: orders or other ooxxooxx
Alwasy get this Error.
web.php
Route::get('/admin/orders', [\App\Http\Livewire\Order::class, 'render']);
Files:
\app\Http\Livewire\Order.php
And use
return <<<'blade'
blade;
Get plain text @foreach($orders as o$key -> $permission
Same Error.
Beacuse view run first. Only create view then @livewire('')
example:order and orderlist order view for fist(main) load page. orderlist be loaded by order view. order view have @livewire('orderlist'). https://stackoverflow.com/questions/64038485/laravel-livewire-components-or-controllers
or just remove namespace
Route::get('/admin/orders', \App\Http\Livewire\Order::class);
Don't add namespace in app/Http/livewire/ any file. Always get errors.
php auth role is_admin isAdmin or .... check role admin
public function getIsAdminAttribute()
{
return (bool) $this->admin;
}
Auth::user()->isAdmin or auth()->user()->isAdmin
https://laracasts.com/discuss/channels/code-review/how-to-check-user-role-after-login
namespace App;
use App\Role;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function getIsAdminAttribute()
{
return $this->roles->pluck( 'name' )->contains( 'admin' );
}
public function roles()
{
// you will need a role model
// Role::class is equivalent to string 'App\Role'
return $this->belongsToMany( Role::class, 'users_role' );
}
}
LoginController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use Input;
use Validator;
use Redirect;
class LoginController extends Controller
{
//
public function login_post( Request $request )
{
$data = Input::except( array( '_token' ) );
// var_dump($data);
$rule = array(
'email' => 'required|email',
'password' => 'required',
);
$validator = Validator::make( $data, $rule );
if ($validator->fails()) {
// should do something
} else {
// no need to populate $data again with the same values
// $data = Input::except( array( '_token' ) );
if (Auth::attempt( $data )) {
// here i want to check logged in user role
$user = Auth::user();
if ($user->roles->pluck( 'name' )->contains( 'admin' )) {
return Redirect::to( '/admin-dashboard' );
}
return Redirect::to( '/dashboard' );
}
}
}
}
https://laravel.tw/docs/5.2/eloquent-serialization#appending-values-to-json
https://codertw.com/%E7%A8%8B%E5%BC%8F%E8%AA%9E%E8%A8%80/111359/
方法簽名為getXXXAttribute get XXX Attribute So XXX => IsAdmin
public function getIsAdminAttribute()
{
return $this->roles()->where('id', 1)->exists();
}
https://stackoverflow.com/questions/44017571/pass-current-eloquent-into-getxattribute-in-model
public function getIsAdminAttribute()
{
return Admin::where('user_id', $this->id)->count() > 0;
}
Error Running: npm install vue-template-compiler --save-dev --production=false
Error
Additional dependencies must be installed. This will only take a moment.
Running: npm install vue-template-compiler --save-dev --production=false
https://qiita.com/ucan-lab/items/f5bcdfceecffb9def4c5
Use yarn, Not npm
yarn add vue-template-compiler --dev --production=false
yarn run dev
php laravel UI Boostrap jetstream docker-compose
docker-compose up -d
docker-compose exec app composer create-project --prefer-dist laravel/laravel .
== jetstream Livewire !Now No Use
docker-compose exec app composer require laravel/jetstream
docker-compose exec app php artisan jetstream:install livewire --teams
docker-compose exec app php artisan migrate
docker-compose exec web yarn install
docker-compose exec web yarn dev
== jetstream end
== Laravel UI Bootstrap Auth *more easy
docker-compose exec app composer require laravel/ui
docker-compose exec app php artisan ui bootstrap --auth
[ docker-compose exec app php artisan migrate ]
docker-compose exec web yarn install
docker-compose exec web yarn run dev
[ docker-compose exec web yarn add vue-template-compiler --dev --production=false ]
== Laravel UI Bootstrap end
docker-compose exec app composer require doctrine/dbal
docker-compose exec app composer require --dev barryvdh/laravel-ide-helper
docker-compose exec app composer require --dev beyondcode/laravel-dump-server
docker-compose exec app composer require --dev barryvdh/laravel-debugbar
docker-compose exec app composer require --dev roave/security-advisories:dev-master
docker-compose exec app php artisan vendor:publish --provider="BeyondCode\DumpServer\DumpServerServiceProvider"
docker-compose exec app php artisan vendor:publish --provider="Barryvdh\Debugbar\ServiceProvider"
=== remove all
docker-compose down --rmi all --volumes
docker-compose down --volumes
.參考:
blade @can @cannot
https://laravel.com/docs/8.x/authorization#via-blade-templates
https://laravel.com/docs/8.x/authorization
flutter release apk
1. pubspec.yqml
2. local.properties
噴墨
博奕代工
這份報導,還是沒有寫出真正的情況,也是把事情混在一起談,因為並不是每一個進去博奕工作的工程師能了解大部份的情況
她碰到的根本是洗錢中心,不是博奕代工 內容中又把博奕代工和洗錢中心混在一起來談 區分三個角度 1. 線上博奕 2. 博奕代工 3. 洗錢 1. 線上博奕 對我們工程師來的角度來談,在國外“維運“,在合法的地方“維運“就是合法,大公司分工非常細和明確的,工程師只會負責開發遊戲,不負責“維運“ 大公司對於“風控“非常嚴格,一來怕內賊,二來怕一鍋踹,怎麼會混在一起 中小公司才有可能混在一起,也才有可能在一個地方“維運“ 2. 博奕代工 對我們工程師來的角度來談,代工就是幫忙寫遊戲系統、程式,這肯定100%不犯法,大公司會非常嚴格執行這個做法,建立一間公司,主力就是遊戲開發,開發遊戲,賣給台灣公司、外國公司都是合法的 就算是做實體機台(台灣有名就那家),賣給國外一樣合法 中小公司的代工理論上都就是上面所述,實際上會做到1. 的情況,那就會出現同樣問題“維運“,那“維運“到底合不合法,後面討論 3. 洗錢 癈話,一定違法,一定會出問題 “維運“這塊工作內,會有一定違法的兩個點:金流、客服,工程師的“維運“就妙在這裡,不是工程師的人做“維運“,那就要看你是做什麼了,這很清楚了吧! 內文中的點: 1. 拿現金 大公司是不會拿現金給你的,一定會匯給你,而且還會給你保足額的勞健保,該給你的一定給你 中小公司正常也不會拿現金給你的,那什麼時候拿現金,要避稅,可能是公司避,可能是你自己要避稅,都不是這些,那就是現金太多,應該就懂了吧! 2. 看到荷官…… 訓練的話應該是沒問題,實際被運用在台灣內的某角落才算違法吧! 3. 看到桌子…… 這是開發系統一定會需要的,實際被運用在台灣內的某角落才算違法吧! 4. 工作要上繳存簿,這不用想就知道這間公司是不正常的吧!不管是不是博奕,這年代還有人相信要上繳存簿?! 5. 跟政府談? 文內跟政府單位談線上博奕,這思序不清吧!國內連實體博奕都沒有,這些工作都是對國外,就算是出國轉回給內銷用,本質還是國外,國內那管得著,要談的是國外 日本、新加坡之類 6. 中國要求菲律賓停止“新“牌照發放,舊的能用,更好用,更貴,菲律賓不是笨蛋 7. 大量台灣人材... ... 大陸人材更多吧 8. 避免大量年輕人成為洗錢人頭戶,這跟博奕有個鬼關係,意思是沒博奕就沒有洗錢人頭戶?! 都混在一起談,詐騙就不用洗錢人頭戶?!犯毒就不用洗錢人頭戶?!GCP logging winston LoggingWinston severity
const winston = require('winston');
const useFormat = winston.format.combine(
winston.format((info, opts) => {
let level = info.level.toUpperCase();
if(level === 'VERBOSE') {
level = 'DEBUG';
}
info['severity'] = level;
delete info.level;
return info;
})(),
winston.format.json());
const { LoggingWinston } = require('@google-cloud/logging-winston');
const loggingWinston = new LoggingWinston();
const logger = winston.createLogger({
level: 'debug',
format: useFormat,
transports: [
new winston.transports.Console(),
loggingWinston
]
});
gcloud tools docker
docker run -it -e CLOUDSDK_CONFIG=/config/mygcloud -v `pwd`/gcloud:/config/mygcloud -v `pwd`/gcloud/certs:/certs gcr.io/google.com/cloudsdktool/cloud-sdk
2. Put Projects
docker run -it -e CLOUDSDK_CONFIG=/config/mygcloud \
-v `pwd`/gcloud:/config/mygcloud \
-v `pwd`/gcloud/certs:/certs \
-v `pwd`/Documents/Projects:/home \
gcr.io/google.com/cloudsdktool/cloud-sdk
Firebase deploy default vpcConnector vpc-Connector gcloud vpc
Failed
javascript How does the double exclamation (!!) work in javascript?
value | !value | !!value |
false | true | false |
true | false | true |
null | true | false |
undefined | true | false |
0 | true | false |
-0 | true | false |
1 | false | true |
-5 | false | true |
NaN | true | false |
'' | true | false |
'hello' | true | false |
aws FortiGate VM public / private vm Can't OutGoing. SG need setting correct.
node.js express.js sequelize redis cache
const to = require('await-to-js').default;
const Redis = require('ioredis');
const redis = new Redis(ooxxooxx);
function Cache() {}
Cache.get = async function(key) {
const [err, res] = await to(redis.get(key));
if (err) {console.error('REDIS::Cache::get]', err); return null;}
return JSON.parse(res);
};
Cache.set = async function(key, value) {
value = JSON.stringify(value);
const [err] = await to(redis.set(key, value));
if (err) {console.error('REDIS::Cache::set]', err); }
};
//
// sequelize.query
//
async function CacheSequelizeQuery(sequelize, sql, params, redisKey) {
const cacheData = await Cache.get(redisKey);
if (cacheData) return cacheData; // not empty return cache data
const [err, lists] = await to(sequelize.query(sql, params));
if (err) throw err;
if (lists) await Cache.set(redisKey, lists); // not empty set cache data
return lists;
}
//
// findOneCache
//
Sequelize.Model.findOneCache = async function() {
let redisKey;
for (const parms of Object.values(arguments)) {
if (parms.where) redisKey = [this.name, JSON.stringify(parms.where)].join(':');
}
const cacheValue = await Cache.get(redisKey);
if (cacheValue) return JSON.parse(cacheValue);
const result = await Sequelize.Model.findOne.apply(this, arguments);
Cache.set(redisKey, JSON.stringify(result));
return result;
};
node.js redis special delete del
const Redis = require('ioredis');
const redis = new Redis();
const delScript = `
local all_keys = {};
local keys = {};
local done = false;
local cursor = "0"
repeat
local result = redis.call("SCAN", cursor, "match", KEYS[1], "count", KEYS[2])
cursor = result[1];
keys = result[2];
for i, key in ipairs(keys) do
all_keys[#all_keys+1] = key;
end
if cursor == "0" then
done = true;
end
until done
for i, key in ipairs(all_keys) do
redis.call("DEL", key);
end
return true;
`;
redis.defineCommand('del', {
numberOfKeys: 2,
lua: delScript
});
redis.del('login:202007*', 10000, function(error, result) {
console.log('error: ', error);
console.log('result: ', result);
});
javascript functions parm default value
// default num: 0, unit: 'pics'
function items(op) {
const { num, unit } = Object.assign({}, { num: 0, unit: 'pics'}, op);
}
mysql virtual colume alert
ALTER TABLE `user`
ADD `last name` VARCHAR(50)
AS (
case `name`
when admin then 0
else CONCAT(`name`, 'user')
end
)
;
vs code vscode remote ssh Error: EACCES: permission denied
1. make sure that sudo -u newuser -i works in a regular ssh session without requesting a password
sed -i s/"-o RemoteCommand=none"/""/ ~/.vscode/extensions/ms-vscode-remote.remote-ssh-*/out/extension.js
sed -i s/"bash"/""/ ~/.vscode/extensions/ms-vscode-remote.remote-ssh-*/out/extension.js
3. create an ssh config entry with a RemoteCommand like this one:
Host pi-for-newuser
Hostname pi
User pi
RemoteCommand sudo -u newuser -i
RequestTTY Yes
RemoteCommand sudo -i
firebase functinos cookie only __session
firebase functions cold start use Express.js node.js get problem
https://medium.com/@siriwatknp/cold-start-workaround-in-firebase-cloud-functions-8e9db1426bd3
So
google office
https://firebase.google.com/docs/functions/networking
const http = require('http');
const functions = require('firebase-functions');
// Setting the `keepAlive` option to `true` keeps
// connections open between function invocations
const agent = new http.Agent({keepAlive: true});
exports.function = functions.https.onRequest((request, response) => {
req = http.request({
host: '',
port: 80,
path: '',
method: 'GET',
agent: agent, // Holds the connection open after the first invocation
}, res => {
let rawData = '';
res.setEncoding('utf8');
res.on('data', chunk => { rawData += chunk; });
...
Two line let me confused. Not only me.
const agent = new http.Agent({keepAlive: true});
agent: agent, // Holds the connection open after the first invocation
Some guy same me.
Get same problem.
https://stackoverflow.com/questions/56912118/how-can-i-maintain-persist-a-cloud-functions-connection-using-expressjs
Success??
https://stackoverflow.com/questions/55425015/how-to-keep-alive-dialogflow-firebase-function-to-avoid-new-connection-time-wastThanks Max. However I found the answer to this problem from the same link I posted above (i.e. firebase.google.com/docs/functions/networking). Just adding two lines of code solved the problem. Now response is quite prompt. I added following lines: 1. const agent = new http.Agent({keepAlive: true}); 2. agent: agent, – Vipul Sisodia Apr 2 '19 at 19:04
See Express.js
https://nodejs.org/dist/latest-v10.x/docs/api/http.html#http_new_agent_options
Not thing can Try.
Other way
https://medium.com/@onufrienkos/keep-alive-connection-on-inter-service-http-requests-3f2de73ffa1https://stackoverflow.com/questions/60667847/unable-to-verify-leaf-signature-from-request-with-firebase-functions-node-js-wit index.js
require('https').globalAgent.keepAlive = true;
const functions = require('firebase-functions');
const express = require('express');
const app = express();
...
exports.api = functions.runWith(runtimeOpts).https.onRequest(app);
require('https').globalAgent.keepAlive = true;
Try by yourself.
mysql json mariadb
nodejs node.js console.log util.format ...args for logging log
const util = require('util');
function d(...args) {
if (typeof (console) !== 'undefined') {
console.log('[Logging]', util.format(...args));
}
}
[轉]網站使用體驗三大核心指標 – LCP, FID, CLS
nodejs express cache redis
const express = require('express')
const app = express()
const redis = require('redis')
const redisClient = redis.createClient(6379)
async function getSomethingFromDatabase (req, res, next) {
try {
const { id } = req.params;
const data = await database.query()
// Set data to Redis
redisClient.setex(id, 3600, JSON.stringify(data))
res.status(200).send(data)
} catch (err) {
console.error(err)
res.status(500)
}
}
function cache (req, res, next) {
const { id } = req.params
redisClient.get(id, (err, data) => {
if (err) {
return res.status(500).send(err)
}
// If data exists return the cached value
if (data != null) {
return res.status(200).send(data)
}
// If data does not exist, proceed to the getSomethingFromDatabase function
next()
})
}
app.get('/data/:id', cache, getSomethingFromDatabase)
app.listen(3000, () => console.log(`Server running on Port ${port}`))
vs code 無法使用eslint
"eslint.workingDirectories": [
{ "mode": "auto" }
],
Promise.all map
const arr = {};
await Promise.all(
UsersQuery.map(async function (data) {
const city = await db.sequelize.query(`
select * from city
`,
type: db.sequelize.QueryTypes.SELECT
});
arr[data.user_id] = city[0].name;
})
}
UsersQuery.forEach(async function (data, index) {
this[index].name = arr[data.user_id];
}, UsersQuery);
sqlmap
docker https://hub.docker.com/r/googlesky/sqlmap
執行指令:
docker run --rm -it -v /tmp/sqlmap:/root/.sqlmap/ googlesky/sqlmap -h
GET
docker run --rm -it -v /tmp/sqlmap:/root/.sqlmap/ googlesky/sqlmap --url='https://test.com/date=2020-04-01' --level=5 --risk=3
POST & header token
docker run --rm -it -v /tmp/sqlmap:/root/.sqlmap/ googlesky/sqlmap --url='http://oo.xx.oo.xx:5000/user/info' --headers='Authorization: bearer eyJhbGcoooooxxxxxoooooxx......' --data='{id: "u123"}' --level=5 --risk=3
nodejs moment moment-timezone
const moment = require('moment-timezone');
app.get('/moment', (req, res) => {
const datestr = '2020-07-01';
res.status(200).json({
local_offset: moment(datestr).utc(),
local_unix: moment(datestr).unix(),
zone0_unix: moment(datestr).zone(0).unix(),
zone8_unix: moment(datestr).zone(8).unix(),
timezone0_unix: moment.tz(datestr, 'GMT').unix(),
timezone8_unix: moment.tz(datestr, 'Asia/Taipei').unix(),
});
});
// No use, just for keep
function dateForTimezone(offset, d) {
// Copy date if supplied or use current
d = d? new Date(+d) : new Date();
// Use supplied offset or system
offset = offset || -d.getTimezoneOffset();
// Prepare offset values
var offSign = offset < 0? '-' : '+';
offset = Math.abs(offset);
var offHours = ('0' + (offset/60 | 0)).slice(-2);
var offMins = ('0' + (offset % 60)).slice(-2);
// Apply offset to d
d.setUTCMinutes(d.getUTCMinutes() - offset);
return offSign + offHours + ':' + offMins;
// Return formatted string
return d.getUTCFullYear() +
'-' + ('0' + (d.getUTCMonth()+1)).slice(-2) +
'-' + ('0' + d.getUTCDate()).slice(-2) +
'T' + ('0' + d.getUTCHours()).slice(-2) +
':' + ('0' + d.getUTCMinutes()).slice(-2) +
':' + ('0' + d.getUTCSeconds()).slice(-2) +
'.' + ('000' + d.getUTCMilliseconds()).slice(-3) +
offSign + offHours + ':' + offMins;
}
IMPORT
Server timezone 0
Client time zone +8
Server run result:
{
"local_offset": "2020-06-30T16:00:00.000Z",
"local_unix": 1593532800,
"zone0_unix": 1593532800,
"zone8_unix": 1593532800,
"timezone0_unix": 1593561600,
"timezone8_unix": 1593532800
}
Client run result:
{
"local_offset": "2020-07-01T00:00:00.000Z",
"local_unix": 1593561600,
"zone0_unix": 1593561600,
"zone8_unix": 1593561600,
"timezone0_unix": 1593561600,
"timezone8_unix": 1593532800
}
Conclusion
moment().zone().unix() Auto fix zone / utc
moment("").tz("GMT").unix() Auto fix zone / utc
moment().tz("", "GMT").unix() No auto fix zone / utc
typeorm connection
const typeorm = require("typeorm");
const connectionManager = require("typeorm").getConnectionManager();
//const connectionManager = typeorm.getConnectionManager();
const connected = connectionManager.has("default");
if(!connected){
// ? load connection options from ormconfig or environment
//const connectionOptions = await getConnectionOptions();
connectionManager.create({
//name: "default",
type: "mysql",
// "extra": {
// "socketPath": "/cloudsql/ooxxooxx"
// },
host: "oo.xx.oo.xx",
port: 3306,
username: "root",
password: "ooxxooxx",
database: "ooxxdb",
synchronize: false,
logging: true, // this.env === 'dev' ? true : false
ssl: SSL,
keepConnectionAlive: false,
});
}
try {
db = connectionManager.get();
if(!connected){
await db.connect();
console.log('connect .... OK!');
}
}catch(error) {
console.log("TypeORM Error: ", error);
};
var ranks = await db.query("select * from users");
Sequelize 基本認識
## 1. Timestamps
https://sequelize.org/v5/manual/models-definition.html#timestamps
## 2. Database synchronization
https://sequelize.org/v5/manual/models-definition.html#database-synchronization
建議不要直接使用於正式環境,應該在測試建立後,取得對應 sql 碼後,在正式上線時,手動更新正式 DB 資料結構
**2.1** 使用 sync 建立的 table name 會加上 s
**2.2** 正常情況下,對 table 操作盡可能還是已手動為主,雖然 Sequelize 有提供一些操作,但減少使用比較安全,當手動操作完畢後,應該把 raw sql 匯出備份,正式上線時,再手動更新
## 3. Modeling a table 建立
https://sequelize.org/v5/manual/getting-started.html
```
const Model = Sequelize.Model;
class User extends Model {}
User.init({
```
建議使用
```
sequelize.define:'user', {
// attributes
firstName: {
```
原因,看起來簡單多了
3.1 Model 操作
https://sequelize.org/v5/manual/models-usage.html
## 4. Raw queries
https://sequelize.org/v5/manual/raw-queries.html
基本當join比較複雜建議使用,因為清楚、效率可控,或更複雜的 sub sql 都可以進行,避免 ORM 處理不當,造成效能大幅下降
**4.1** 回傳是 [results, metadata]
**4.2** 有使用參數情況下,務必使用 Replacements 千萬不要直接raw sql + 參數
西方式傲慢
中國為西方贏得時間,西方卻浪費了它 張彥
https://cn.nytimes.com/opinion/20200314/china-response-china/zh-hant/
普立茲獎 張彥
https://zh.wikipedia.org/zh-tw/%E5%BC%A0%E5%BD%A6_(%E7%BE%8E%E5%9B%BD%E8%AE%B0%E8%80%85)
連 柳葉刀的主編 中國傳遞了非常清淅的訊息,可是我們浪費了整整2個月
https://news.sina.com.tw/article/20200401/34733366.html
https://www.facebook.com/watch/?v=538201007134058
[轉]Go 交叉編譯
在Windows上編譯
To MacOs
SET CGO_ENABLED=0
SET GOOS=darwin
SET GOARCH=amd64
go build main.go
To Linux
SET CGO_ENABLED=0
SET GOOS=linux
SET GOARCH=amd64
go build main.go
To Windows ???
go build main.go
在Linux上編譯
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build main.go
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build main.go
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build main.go
javascript firestore object sort
const bookListsQuery = await modules.firestore.collection('books')
.get();
const sortedObj = Object.values(bookListsQuery.docs).sort(function(a, b){
console.log('a %s b %s', a.data().order, b.data().order)
return Number(a.data().order) > Number(b.data().order);
});
sortedObj.forEach(function(doc){
console.log(doc.data())
});
other way
object use map to array, then it sorted.
const bookListsQuery = await modules.firestore.collection('books')
.get();
const sortedArr = bookListsQuery.docs.map(function (doc) { // 轉換成array
return doc.data()
});
sortedArr.sort(function compare(a, b) {
return a.order > b.order; // 升 小->大
});
sortedArr.forEach(function(data){
console.log(data.data())
})
==========
Sorting multiple object properties with JavaScript
https://bithacker.dev/javascript-object-multi-property-sort
let students = [{
firstName: 'John',
lastName: 'Appletree',
grade: 12
},{
firstName: 'Mighty',
lastName: 'Peachtree',
grade: 10
},{
firstName: 'Kim',
lastName: 'Appletree',
grade: 11
},{
firstName: 'Shooter',
lastName: 'Appletree',
grade: 12
}];
let sortBy = [{
prop:'grade',
direction: -1
},{
prop:'lastName',
direction: 1
}];
array.sort(function(a,b){
let i = 0, result = 0;
while(i < sortBy.length && result === 0) {
result = sortBy[i].direction*(a[ sortBy[i].prop ].toString() < b[ sortBy[i].prop ].toString() ? -1 : (a[ sortBy[i].prop ].toString() > b[ sortBy[i].prop ].toString() ? 1 : 0));
i++;
}
return result;
})
fb 中研院研究出快篩試劑
13 小時前
中研院研究出快篩試劑,
綠媒大肆吹捧,
817們高潮連連,
綠媒說根本是大陸搶了台灣的研究功勞,
結果人家那是2月的事,
如何搶台灣3月研發出來的成果功勞?
(原來中國有坐時光機穿越未來,
抄襲台灣研究成果的能力啊)
。。。
接著衛福部被抓包,
2月就核准進口大陸快篩試劑,
但衛福部辯解說進口的是抗體試劑,
中研院研發的是抗原試劑,
(既然兩者快篩試劑不同,
那白痴綠媒說大陸搶了台灣研究功勞,
這是什麼毛病?
反正只要政治正確,
造謠就沒問題是嘛!?)
。。。
那中研院的快篩試劑何時可量產?
中研院長回覆說:
『此一問題「難以回答」。
做試劑不能為了趕進度忽略靈敏性與準確度。
而快篩何時人體試驗、量產,
都必須與衛福部、廠商密切合作,
時間難以預估。
「即使今年用不上,
也必須為未來的疫情做準備。」』
。。。
所以817在高潮一個,
根本還無法真正問世的東西。
台灣現在就是腦殘當道啊!
[轉]Keep your promises when using Cloud Functions for Firebase!
const ref_p1_state = root.child(`player_states/${game_state.p1uid}`)
const ref_p2_state = root.child(`player_states/${game_state.p2uid}`)
const pr_update_p1 = ref_p1_state.update(update_p1)
const pr_update_p2 = ref_p2_state.update(update_p2)
return Promise.all([pr_update_p1, pr_update_p2])
==========
https://stackoverflow.com/questions/55430079/promise-all-does-not-wait-for-firestore-query-to-loop
nodexjs expressjs ajv apidoc converter generator restclient curl postman
https://github.com/willfarrell/apidoc-plugin-schema
required can't product doc.
converter
https://github.com/apidoc/apidoc#converter
to swagger
https://github.com/fsbahman/apidoc-swagger
postman collection to apidoc
https://github.com/bonzzy/docmaster
RestClient -> curl -> postman
promise.all error catch
Promise.all(state.routes.map(function(route) {
return route.handler.promiseHandler().catch(function(err) {
return err;
});
}))
.then(function(arrayOfValuesOrErrors) {
// handling of my array containing values and/or errors.
})
.catch(function(err) {
console.log(err.message); // some coding error in handling happened
});
Alternately, if you have a case where you don't particularly care about the values of the resolved promises when there is one failure but you still want them to have run, you could do something like this which will resolve with the promises as normal when they all succeed and reject with the failed promises when any of them fail:
function promiseNoReallyAll (promises) {
return new Promise(
async (resolve, reject) => {
const failedPromises = []
const successfulPromises = await Promise.all(
promises.map(
promise => promise.catch(error => {
failedPromises.push(error)
})
)
)
if (failedPromises.length) {
reject(failedPromises)
} else {
resolve(successfulPromises)
}
}
)
}
firestore import
base on https://github.com/dalenguyen/firestore-import-export
能處理timestamp
filestore2json json2filestore
ok can use. good job.
timestamp have error.
pve Transparent Failover
Ray Tracy HA 只是高可用度,他沒有不停頓 (Non-stop) 等級的容錯(FT)能力,所以只能把死掉的 VM 重開機來復原,他做不到:接手死掉 VM 當時狀態,不停頓的執行下去....
市面上可穩定商轉的 FT 軟體最便宜也要上百萬起跳....且對硬體條件有諸多限制...
還有,測試 HA 盡量採用拔電源線的方式,而不是只拔網路線,否則在複雜網路環境中,復原後可能整個 Cluster 會發生 #叢集腦裂(雖然機率很小,你還是可以賭看看)....
而且原本初階 HA 就是設計成:用來對抗 Host 全機故障,而不是對抗只有網路故障;所以即便將網路隔離,若 Host 沒掛掉的話,復原的時候都會有風險.....
完整的 HA 流程,在啟動備用 VM 之前,Cluster 會先自動下 ipmi 或 BMC 指令給隔離的 Host 強制它完全關機之後,才啟動備用 VM, 就是為了避免發生上述風險....(這個動作稱為 fence)
這裡大部分玩 cluster 的人都不知道要去設定 ipmi/bmc 做 fence; 如果有設定 fence 的話, 就可以用拔網路線來做測試了, 因為拔掉之後, fence 會自動去把那台隔離的 host 關機, 就不會發生復原之後的腦裂問題.....(當然, 你不能去拔 fence 用的那條 ipmi 網路線...🤣🤣🤣)
Jason Cheng 如果經費不多想做 FT,可以參考台灣團隊開發的 Cuju 專案,基於 kvm 實作,去年底 Proxmox 社團使用者年會該團隊講者有來分享
https://github.com/Cuju-ft/Cuju
拿H1N1來對比武漢肺炎
中間一些部份內容,讓人理解到為什麼日韓和美國都不是很在意
https://www.youtube.com/watch?v=rJiKxV4rTCQ
https://www.youtube.com/watch?v=K2TYIV6osR8
https://www.youtube.com/watch?v=K2TYIV6osR8
https://youtu.be/UBYPkjs9ve4?t=315
https://youtu.be/UBYPkjs9ve4?t=511
https://youtu.be/0RI5JsfuZKE?t=22
https://www.youtube.com/watch?v=bPvuqvc5C1M 纽约首例新冠患者未在医院治疗,纽约州长:80%都能自愈 没必要去医院
https://www.youtube.com/watch?v=AiCghCxro8o
https://www.guancha.cn/internation/2020_03_03_539596.shtml
螢幕色彩偏離值
螢幕色彩偏離值只有0.98(校色後),未校色為1.17,1F最高為6.37(其餘都在1附近)
高達75%ARGB,116%SRGB。
表現已經達到頂級水平。
目前要顯示優秀的筆電(偏離值在1以下)非常的少,普遍都在2附近
MACBOOK PRO 13的螢幕表現
https://kknews.cc/zh-tw/digital/x2k6al8.html
吹哨 的鬼邏輯 時間線
https://www.youtube.com/watch?v=kO5EXjFKE7U
https://youtu.be/H0trgOgKFoE?t=716
https://youtu.be/DiFpRW_kw8g?t=1608
=============
我的美國公務員生活點滴 (番外篇2)
https://www.mobile01.com/topicdetail.php?f=651&t=5981610
沒有效果的運動方式 浪費時間的肌力訓練動作
6個浪費時間的肌力訓練動作
https://www.don1don.com/archives/23096/6%E5%80%8B%E6%B5%AA%E8%B2%BB%E6%99%82%E9%96%93%E7%9A%84%E8%82%8C%E5%8A%9B%E8%A8%93%E7%B7%B4%E5%8B%95%E4%BD%9C1. 小腿上提 (Calf Raises)
替代方案:運動員應該讓他們的小腿肌自然發展,進行深蹲、跳蠅、還有日常的運動訓練就已經足夠了。
2.下斜式臥推 (Decline Bench Press)
替代方案:建議進行站姿滑輪胸推 (Standing Cable Presses),這個動作更接近於平日的運動形態
3.大腿推蹬機 (Leg Press)
替代方案:建議進行後腳抬高蹲 (Single-Leg Rear-Foot-Elevated Split Squats),因為大多數運動動作都是依靠單腳去進行,這個訓練動作正好乎合運動員的需求。
4.槓鈴彎舉 (Bicep Curls)
替代方案:對於想要讓手臂變強壯的運動員,引體向上 ( Pull-Ups)將會是一個比較好的選擇,另外也可以配合啞鈴或槓片來增加強度。
5.腿部伸展訓練機 (Machine Leg Extensions)
替代方案:建議採用前蹲舉(Front Squats)或跨步(Lunges),兩者都需要運動員去維持身體平衡,這在運動當中是一個非常重要的能力。
6.史密斯機器 (Smith Machine)
替代方案:採用自由重量 (Free Weight)進行深蹲、抓舉等動作將會為你身體的平衡帶來挑戰,如果做相同的重量覺得太重,那就換輕一點的吧!
反駁
https://james927.pixnet.net/blog/post/576068409種沒有效果的運動方式
http://www.unclesam.cc/blog/9-least-effective-exercises-from-webmd/1. 頭後方的滑輪下拉(Lat Pull-down)
只有少數人有靈活的肩關節,讓他們在進行滑輪下拉時,能保持脊椎的直挺。所以在進行這個動作,若動作不正確時,將可能導致肩膀、旋轉肌群的受傷,若滑輪的槓子撞擊到頸部的後側,可能導致頸椎(cervical vertebrae)的受傷。
2. 槓鈴肩推舉(Military Press)
比較安全的方式是置於身體前側
3. 直立上提(Upright Row)
將槓鈴往上提至下巴處,真得不可行的方式(big no-no),這會壓迫到肩膀處的神經,衝擊到肩膀。
4. 大腿推蹬機,不適的膝蓋位置(Leg Press with Poor Knee Position)
在進行推蹬的動作,不要讓膝蓋過於前彎,超過90度,這你傷害到你的背部及膝蓋。
5. 利用史密斯機器輔助進行深蹲(Squats on the Smith Machine)
在使用史密斯機器來輔助時,人們往往會將腳步跨的更加前面。(換個方式說,藉由器材來進行訓練時,有的人會依著機器,但實際上姿勢跑掉或是受傷的機會就大大的提升)。
6. 在燃燒卡路里機器上的不良動作(Bad Form on Cardio Machines)
在使用燃燒卡路里的機器(跑步機),不要將坡度或阻力設定的太強,導致你要緊握著把手。設定在一個自然的狀況下,手握輕握著把手,讓你的身體能很自然、平衡下進行運動。
7. 局部的運動(Exercises for Spot Reduction)
人們透過局部的訓練來削減特定部位的脂肪,像是大腿、髖關節、胃及手臂,這是錯誤的想法,你不能把脂肪看成是一區一區的。有興趣的話,可以查查部落格上「迷思」的文章,對於脂肪有很多的說明囉。
避免使用健身房10種常見的訓練設備(二)
https://www.unclesam.cc/blog/10-exercise-machines-to-avoid-2/6. 坐姿旋轉機(Seated Rotation Machine)
■ 實際的效用:「因為骨盆沒有跟著胸部移動,這個動作會施加過多的扭力在脊椎上。 」
■ 較好的動作:「砍木頭(Cable Wood Chop)」,讓你的腳踝跟著軀著活動,每邊進行10~12次。
7. 坐姿大腿推蹬機(Seated Leg Press Machine)
■ 實際的效用:「在沒有緊縮髖關節、臀肌、肩膀及下背部的必要的穩定肌肉之下, 這動作通常會強迫脊迫脊椎彎曲。」
■ 較好的動作:「徒手深蹲(Body-weight Squats Bischoff, Beth)」,在下背沒有拱起的狀況下,專注在下蹲的控制,1組進行12~15次,可以增加組數來訓練肌力
8. 史密斯機器(Smith Machine)
■ 實際的效用:「 槓子是固定在機器上,呈直接升降的移動方式,並非自然而有弧度的移動。這讓膝蓋、肩膀及下背帶來壓力。」
■ 較好的動作:「徒手深蹲(Body-weight squats)」,在下背沒有拱起的狀況下,專注在下蹲的控制,1組進行12~15次,可以增加組數來訓練肌力。
9. 羅馬背伸椅(Roman Chair Back Extension Machine)
■ 實際的效用:「 重複的彎曲你的背,而壓力加壓在脊椎上,增加椎間盤受損的風險。」
■ 較好的動作:「Bird-Dog」,四足跪姿,往前伸展右手臂及往後延伸左腳,重複進行7~10次,換邊進行。
10. 羅馬起坐椅(Roman Chair Sit-up)
■ 實際的效用:「捲腹的動作會將不必要的壓力落在下背部。」
■ 較好的動作:「棒式(Plank)」,維持20~60秒。
AI bot 聊天
[轉]虛擬機跑起來!RouterOS CHR 軟路由效能輕鬆突破 1000M!
https://youtu.be/4PzJulQTSrY?t=1016
占美 i5 4278u
口罩
政府絕對可以跟四大超商提出要求,口罩請用成本價售出,為了人民,至於四大超商評估是否要接這個案子
同時間其他的單位 一般藥局、連鎖藥局、全聯、屈沉世、大賣場、連鎖嬰幼、連鎖寵物等等通路,
政府絕對可以提出要求,口罩請用成本價售出,為了人民,他們可以評估是否要接這個案子
有人願意賠錢 做名聲、做善事就讓他做,互蒙其利,那來合理利潤,用合理利潤來談的話,每間通路成本不同,那我都用飛機來運口罩,一個賣200,運輸成本佔120,派人去各國搶購成本佔60,合理賺20,合理吧?! 為了合理,一堆漏洞就在裡面了!
特殊時期,你要賣,就給我照成本賣
說不定就一堆企業用成本賣,大打廣告,賺名聲
轉藥局為的是什麼? 用健保卡可以管理購買人! 而不是上面說的問題,用四大超商結果是一堆人買不到,現在的推論是有人一直買一直屯,真假比例誰知,真用 真屯?!
一開始說口罩不缺,實際缺的要死,完全能理解 政府本來在特定時期就需要說一些幹話,跟大陸一樣,在特殊時期也是要說說幹話:「中央已經掌握住情況,民眾無需恐荒」
要控制價格,讓民眾檢舉,噁心一點,做個網頁,讓民眾回報購買通路價格,做成歷史價格,用市場來打市場
要控制購買,要有手段能控制,健保卡,各通路會員制
想想這事還真的很難辨,照上做了,肯定又會發現上面的做法會有問題產生... 哈
==========
看大陸官方的說明比較準,之前說封城,實際上它的意思不是封城,是管制,我看繁華十年,實際上只要真的有親人,有人擔保,還有進入後隔離,就能進入了
致死率 妳如果有看我轉的論文,妳會發現
有的省份死亡率高到30%,大部份都是10%
我不知道我有沒有看錯
看29頁的圖,就會知道中獎和死亡 除非我搞錯意思
https://www.medrxiv.org/content/10.1101/2020.02.06.20020974v1.full.pdf
隨時都在變異,論文中提到的 超級感染者,這才是最可怕的
我到不覺得 一開始跟時間賽跑這個東西,我看AKA說的很清楚,我也非常能認同, 當疾症發生時,絕對不是看到黑影就開槍,實際上經過sars後,大陸已經有一套做法了,早已改了很多法令,為了這種情況,早在李文景發聲前,中國官方機構早就發現異常,但絕對不是我們想的,因為這個狀況從現在看來,從論文看來,很早就感染,而且不發燒,沒症狀,也能傳染,這怎麼防護?就算那時候用SARS的規格來防,沒用啊!因為沒發燒啊!連檢查ct都可能沒有異狀,看的越多越會覺得這個病很皮!
我都不看台灣報導,只看中國官方,然後結合yb上的相關內容,去掉 “情緒“ 來看,自然看的清,像妳剛說的,屍體燒不完,我大概都有看到新聞,我都直接略過,內容都懶得看了! 這種 屍體燒不完 ,大概就像我們sars時,我們彰化也在傳,那醫院半夜都有人進進出出一樣...呵呵
屍體燒不完 如果是真的話,香港、台灣早就也跟著燒不完了,因為 論文已經說的很明白了,沒有症狀!沒有症狀也能感染啊!連檢查都可能查不出來,怎麼防止!
年輕人不就醫也沒事的
最近看一個大陸yb,她老婆中獎,他自己照顧她老婆,應該撐過去了
https://youtu.be/9LOn5iBWRdc
還是不行,要住院
==========
https://www.youtube.com/watch?v=b-Fy80yHYQo
https://www.youtube.com/watch?v=_ZijOuFySgg
https://www.facebook.com/931837986851749/posts/2734799916555538/
https://www.facebook.com/931837986851749/posts/2736794659689397/
https://youtu.be/A75ivAVd-M0?t=1642
呵~~ 像候漢廷 fb的內容
>> 提高口罩的價格,才能阻卻不必要的搶購。才能促使商家願意增產。政府統一收購為0.94元,最終售價為8、6、5元,何來誘因使商家拚命生產?
>> 台灣所有口罩由政府統一收購,價格不高,阻卻商人販售回台。縱使事先即有執照者,同樣一批口罩,大陸售價高,台灣售價低,自然多數販售給大陸。
>> 無法轉賣毫無利潤,僅憑企業慈悲,難解問題。而國際代購業者售價必然高於台灣法定價格,台企業要嘛放棄購買,要嘛轉手倒賣。
https://youtu.be/KvcOb3bY9zk?t=337
大陸VS台灣領取口罩大PK|寒國人 底下討論也非常值得一看
韓國管制使用app 自主回報 還用app的gps來追
https://youtu.be/I2fn5lIM3ec?t=190 韓國用app回報
大陸買口罩的方式
https://www.youtube.com/watch?v=KvcOb3bY9zk&feature=youtu.be&t=337
===== 次氯酸水 =====
次氯酸VS漂白水 兩者一樣嗎?
「次氯酸HOCl」與「漂白水NaOCl」常被認為是相同的物質,但實際上他們是具有非常不同性質的兩種成分,現在就讓白博士來為大家解惑。
首先讓我們先來看一下化學式,雖然同樣具有「氧」和「氯」,但只要換了其中一個元素,如從「氫」變成「鈉」,就完全是另一個成分了。
以「酸鹼度」來看,次氯酸HOCl是弱酸性(pH<7);而漂白水NaOCl是鹼性(pH>7)。
殺菌能力就更不用說了,在相同濃度下,次氯酸HOCl的殺菌能力是漂白水NaOCl的100倍以上。
所以次氯酸與漂白水是看似相同卻是非常不同的成份。
http://www.honova.com/sabre.htm
https://www.youtube.com/watch?v=rRfmAMG5JBo
https://professorlin.com/2020/02/17/%E5%86%A0%E7%8B%80%E7%97%85%E6%AF%92%E6%9C%89%E5%A5%97%E8%86%9C%EF%BC%8C%E6%89%80%E4%BB%A5%E6%AC%A1%E6%B0%AF%E9%85%B8%E6%B0%B4%E7%84%A1%E6%95%88%EF%BC%9F/
====== =====
#武汉肺炎Q&A
#冠狀病毒 #CoronaVirus
感恩 抽空为我们解答
Q: #我需要戴口罩吗?
🅰普通口罩无法过滤病毒。如果你没有生病不需要戴口罩。但如果生病了就应该戴口罩,这样打喷嚏或者咳嗽的时候口水才不会到处飞。其实戴口罩不是为自己而是为别人戴。请把口罩让给真正需要的人。
Q:#遇到咳嗽的人立刻暂时停止呼吸、#马上远离有用吗?
🅰我们来不及提前知道他们几时要咳嗽打喷嚏,所以一旦他们突然打喷嚏咳嗽的时候,细菌病毒就马上到处飞,进入我们的鼻子/眼睛/嘴巴,感染我们的呼吸道。就算不呼吸/逃跑也是没用的。
Q:#此病毒存活可以多久?
🅰科学家还不知道它可以在表面上活多久。但是我们看普通的感冒病毒它能够在表面上活几个小时,如果我们打喷嚏在手上,过一个小时我们手上的病毒有可能感染别人。但也要看湿度,如果表面比较干,病毒会活得比较短。如果表面比较潮湿比如有口水/鼻涕,病毒就会活得比较久。
Q:#干洗手消毒凝胶VS肥皂水哪一个比较好?
🅰肥皂水更快更方便因为只需要20秒就可以把全部病毒给毁灭掉。但是在外不方便的话,用干洗手消毒凝胶的时候确保手是干的才有效,如果手湿湿的话,那些流感病毒有可能不会被毁灭掉。如果要把所有病毒给毁灭掉就要等4分钟,才会把病毒给完全毁灭掉。
Q:#家中的宠物会感染2019新冠状病毒吗?
🅰狗/猫不会被感染,也不会传播给人。最近没有报告显示狗/猫传染给人。
Q:#我会因为来自中国的物品而被感染吗?
🅰不会。因为病毒不会在包裹上活得那么久,而且也没有报告显示有人因为包裹而受感染。
Q:#低温利于病毒存活?#所以天气越温暖越有利疫情控制?
🅰病毒不喜欢热,遇到60多度就会死亡,遇到潮湿空气就会变重掉下来不会漂浮在空气。所以马来西亚的天气比较不利于病毒的传播。
Q:#2019新冠状病毒与其他大规模爆发性传染病的比较
🅰死亡率只有2%。比其他的爆发性传染病低很多,所以不必担心,很多人都开始慢慢痊愈。此疾病死亡的人都是因为年纪比较大/有其他疾病比如心脏病或肺部疾病,他们的免疫力比较弱,所以比较难康复。
Q: #有疫苗可以帮助这个病毒吗 ?
🅰很难有疫苗因为它突变太快了
(科学家已发现病毒在变异了)
Q: #空气清净机可以过滤病毒吗❓
🅰不能,因为病毒是很小很小的
**以上资料来自 讲座笔记
flutter build release
https://blog.csdn.net/joye123/article/details/94588949
signingConfig signingConfigs.release
Important is signingConfig signingConfigs.debug -> signingConfig signingConfigs.release
signingConfigs {
release {
keyAlias keystoreProperties['keyAlias']
keyPassword keystoreProperties['keyPassword']
storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
storePassword keystoreProperties['storePassword']
}
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.release
minifyEnabled true
useProguard true
}
}
}
flutter create project name com.xxx.xxx
https://medium.com/@skyblazar.cc/how-to-change-the-package-name-of-your-flutter-app-4529e6e6e6fc
EDITED : 27-Dec-18
for package name just change in build build.gradle only
defaultConfig {
applicationId "your.package.name"
minSdkVersion 16
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
flutter create --org com.yourdomain appname
golang loggin gin
https://marcoma.xyz/2019/03/17/gin-tutorial-7/
https://github.com/natefinch/lumberjack
https://juejin.im/post/5d3932bde51d454f73356e2d
function widget or widget StatelessWidget
拆分widget
永遠不要使用方法返回的形式創建可重用的widget,始終將它們封裝到StatelessWidget中。 注意這個結論中的可重用。
[轉]职场困惑:我该怎么办?
看了楼主的回复,我觉得你存在一个非常典型的思维方式: 我自己称为借斧子(参考这个里面的第一个故事: http://news.sina.com.cn/o/2018-01-07/doc-ifyqiwuw7820642.shtml )
很多人喜欢猜,猜别人的想法,别人的动机,给自己预设很多条件,然后在这个限制中拼命挣扎。无论你怎么去预设你老大的思维,都不及你去和他当面深入交流一下。无论结局如何,聊完,你基本上可以获得你想要的答案:
1. 如果老大告诉你绩效 B 的原因: 这个最好
2. 老板告诉你一个你不能接受的原因: 你们经过争论是否能统一思想,如果不能,说明你和老大思路不和,要不改变自己,要不就换个老大
3. 老大不告诉你: 说明你不可能拿到 A 了,你该换工作了
最后,注意和老大及时高频率的沟通,注意不是去拍马屁,不是去出风头,而是去实实在在的沟通工作内容,任何工作相关的东西都可以,保持几天一次一对一沟通的频率,能够让你和老大的关系提升许多。不要觉得不想厚黑就不去主动找老大聊工作,没有那么多非黑即白的东西
ethereum docker geth shell for geth attach and tail log
#!/bin/sh
IFS=$'\n'
echo $1
echo $2
case $2 in
attach) docker exec -it $(docker ps -a --no-trunc | grep $1 | awk '{print $1}') geth attach --datadir=/root/.ethereum/devchain
;;
log) docker exec -it $(docker ps -a --no-trunc | grep $1 | awk '{print $1}') tail -n 30 -f /root/geth.log
;;
sh) docker exec -it $(docker ps -a --no-trunc | grep $1 | awk '{print $1}') sh
;;
bash) docker exec -it $(docker ps -a --no-trunc | grep $1 | awk '{print $1}') bash
;;
*) echo "command parms1: docker container name"
echo "command parms2: attach (geth attach) or log (tail -n 30 -f) or sh or bash"
esac
[轉]如何為LINUX, WINDOWS容器加入憑證?
ubuntu
/usr/local/share/ca-certificates
update-ca-certificates
windows
Import-Certificate -FilePath ooxx -CertStoreLocation ooxx
How to test your self ethereum geth private poa truffle part2
https://medium.com/finnovate-io/how-do-i-sign-transactions-with-web3-f90a853904a2
https://ethereum.stackexchange.com/questions/60611/defining-the-transaction-object-for-offline-transaction-signing-using-web3-js-f
https://github.com/ethereum/web3.js/issues/1430
https://programtheblockchain.com/posts/
signTransaction(tx, "0x"+privateKey) "0x" privatekey need becarful.
--ws --wsaddr 0.0.0.0 --wsorigins "*" --wsapi "db,admin,debug,miner,eth,net,web3,network,txpool"
var fs = require('fs');
var Web3 = require("web3");
var provider = new Web3.providers.HttpProvider("http://192.168.99.100:18545");
var wsprovider = new Web3.providers.WebsocketProvider("ws://192.168.99.100:18546");
//var web3 = new Web3(provider);
var web3 = new Web3(wsprovider);
console.log("before web set account: %o", web3.eth.defaultAccount);
const privateKey = '138cbbfb21686ddc3b5ffeb2cfc83491175af68319977acb81d0ae93392c626c';
const account = web3.eth.accounts.privateKeyToAccount('0x' + privateKey);
//web3.eth.accounts.wallet.add(account);
//console.log("private key import to account: %o", account.address)
web3.eth.defaultAccount = account.address;
// try {
// web3.eth.personal.unlockAccount(account.address, "").then(console.log('Account unlocked!'));
// } catch (err) {
// console.error('web3 unlockAccount Error: %o', err);
// }
var certjson;
var certjsonpath = './Cert.json';
try {
certjson = JSON.parse(fs.readFileSync(certjsonpath));
} catch (err) {
console.error('readFileSync Error: %o', err);
}
var contractjson;
var contractjsonpath = './MetaCoin.json';
try {
contractjson = JSON.parse(fs.readFileSync(contractjsonpath));
} catch (err) {
console.error('readFileSync Error: %o', err);
}
const getNonce = () => {
return new Promise((resolve, reject) => {
web3.eth.getTransactionCount(web3.eth.defaultAccount, 'pending', (error, result) => {
if(error) reject(error);
resolve(web3.utils.toHex(result));
})
})
}
const getGasPrice = () => {
return new Promise((resolve, reject) => {
web3.eth.getGasPrice((error, result) => {
if(error) reject(error);
resolve(web3.utils.toHex(result));
})
})
}
const createContract = (contractfrom_caller, nonce="") => {
return new Promise((resolve, reject) => {
const tx = {
from: contractfrom_caller,
gasPrice: web3.utils.toHex(web3.utils.toWei('2', 'gwei')), //20,000,000,000
gas: web3.utils.toHex('6819490'),
//gasLimit: 9000000,
value: '0x00', // web3.utils.toHex('0'),
data: certjson.bytecode
};
if(nonce!="") { tx.nonce = nonce; console.log("tx: %o", tx); }
// const keystore = "Contents of keystore file";
// const decryptedAccount = web3.eth.accounts.decrypt(keystore, 'PASSWORD');
// web3.eth.accounts.signTransaction(rawTransaction, decryptedAccount.privateKey)
// .then(console.log);
// OR
// decryptedAccount.signTransaction(tx)
//const signPromise = web3.eth.accounts.signTransaction(tx, "0x"+privateKey);
web3.eth.accounts.signTransaction(tx, "0x"+privateKey)
.then(resolve)
.catch(reject);
})
}
const getBalance = (contractAddr, coinOwnerAddr) => {
return new Promise((resolve, reject) => {
web3.eth.call({
to: contractAddr,
data: metaCoinContract.methods.getBalance(coinOwnerAddr).encodeABI()
})
.then(resolve)
.catch(reject);
// .then(o => {
// resolve(o);
// })
// .catch((error) => {
// reject(error)
// });
})
}
const sendCoin = (contractAddr, sendCointoAddr, coinNumber, nonce="") => {
return new Promise((resolve, reject) => {
const tx = {
from: contractfrom_caller,
to: contractAddr,
gasPrice: web3.utils.toHex(web3.utils.toWei('2', 'gwei')), //20,000,000,000
gas: web3.utils.toHex('181949'),
//gasLimit: 9000000,
value: '0x00', // web3.utils.toHex('0'),
data: metaCoinContract.methods.sendCoin(sendCointoAddr, coinNumber).encodeABI()
};
if(nonce!="") { tx.nonce = nonce; console.log("tx: %o", tx); }
// const keystore = "Contents of keystore file";
// const decryptedAccount = web3.eth.accounts.decrypt(keystore, 'PASSWORD');
// web3.eth.accounts.signTransaction(rawTransaction, decryptedAccount.privateKey)
// .then(console.log);
// OR
// decryptedAccount.signTransaction(tx)
//const signPromise = web3.eth.accounts.signTransaction(tx, "0x"+privateKey);
web3.eth.accounts.signTransaction(tx, "0x"+privateKey)
.then(resolve)
.catch(reject);
})
}
contractAddr = "0x3Da963B807bF892F7A10B61E9ffD830068f8C23d";
contractfrom_caller = "0xe79d33e93bd888b35e055f1a12d876354729037b";
coinOwnerAddr = "0xe79d33e93bd888b35e055f1a12d876354729037b"
sendCointoAddr = "0x5921a4C1B13afbD4b61d63e9c7BD47741C47B176";
const metaCoinContract = new web3.eth.Contract(contractjson.abi, contractAddr);
// getBalance
// web3.eth.call({
// to: contractAddr,
// data: metaCoinContract.methods.getBalance(coinOwnerAddr).encodeABI()
// })
// .then(o => {
// console.log("%s getBalance at %s contract: %o", coinOwnerAddr, contractAddr, web3.utils.hexToNumberString(o))
// });
getBalance(contractAddr, coinOwnerAddr)
.then(o => { console.log("%s getBalance at %s contract: %o", coinOwnerAddr, contractAddr, web3.utils.hexToNumberString(o)) })
.catch((error) => { console.log("getBalance catch error: %o", error.message); });
// transfor coin
// const signPromise = sendCoin(contractAddr, sendCointoAddr, 10);
// signPromise.then((signedTx) => {
// const sentTx = web3.eth.sendSignedTransaction(signedTx.raw || signedTx.rawTransaction);
// sentTx.on("receipt", receipt => {
// console.log("receipt: %o", receipt);
// console.log("receipt.contractAddress: %o", receipt.contractAddress);
// });
// sentTx.on("error", error => {
// console.log("sendSignedTransaction error: %o", error.message);
// })
// sentTx.then(o => {
// TxHash = o.transactionHash;
// console.log("##### TxHash: %o", TxHash)
// });
// }).catch((error) => {
// console.log("sendSignedTransaction catch error: %o", error.message);
// });
// getBalance coin sender & reciver
getBalance(contractAddr, coinOwnerAddr)
.then(o => { console.log("coinOwnerAddr %s getBalance at %s contract: %o", coinOwnerAddr, contractAddr, web3.utils.hexToNumberString(o)) })
.catch((error) => { console.log("getBalance catch error: %o", error.message); });
getBalance(contractAddr, sendCointoAddr)
.then(o => { console.log("sendCointoAddr %s getBalance at %s contract: %o", coinOwnerAddr, contractAddr, web3.utils.hexToNumberString(o)) })
.catch((error) => { console.log("getBalance catch error: %o", error.message); });
Promise.all([getNonce(), getGasPrice()]).then(values => {
var nonce = web3.utils.hexToNumberString(values[0]);
console.log("Nonce: %o", nonce);
createContract(contractAddr, web3.utils.toHex(nonce)).then((signedTx) => {
console.log('createContract signedTx: %o', signedTx);
const sentTx = web3.eth.sendSignedTransaction(signedTx.raw || signedTx.rawTransaction);
sentTx.then(o => {
TxHash = o.transactionHash;
console.log("##### createContract TxHash: %o", TxHash);
web3.eth.getTransactionReceipt(TxHash).then(o=>{
console.log("check contractAddress object: %s", o.contractAddress);
});
})
.catch((error) => { console.log("createContract sendSignedTransaction catch error: %o", error.message); });
}).catch((error) => { console.log("screateContract catch error: %o", error.message); });
nonce++;
setInterval( () => {
sendCoin(contractAddr, sendCointoAddr, 10, web3.utils.toHex(nonce)).then((signedTx) => {
console.log('sendCoin 3 signedTx: %o', signedTx);
const sentTx3 = web3.eth.sendSignedTransaction(signedTx.raw || signedTx.rawTransaction);
sentTx3.then(o => {
TxHash = o.transactionHash;
console.log("##### sendCoin 3 TxHash: %o", TxHash);
})
.catch((error) => { console.log("sendCoin 3 catch error: %o", error.message); });
}).catch((error) => { console.log("sendSignedTransaction3 catch error: %o", error.message); });
nonce++;
console.log("Nonce: %o", nonce);
getBalance(contractAddr, coinOwnerAddr)
.then(o => { console.log("coinOwnerAddr %s getBalance at %s contract: %o", coinOwnerAddr, contractAddr, web3.utils.hexToNumberString(o)) })
.catch((error) => { console.log("getBalance catch error: %o", error.message); });
getBalance(contractAddr, sendCointoAddr)
.then(o => { console.log("sendCointoAddr %s getBalance at %s contract: %o", coinOwnerAddr, contractAddr, web3.utils.hexToNumberString(o)) })
.catch((error) => { console.log("getBalance catch error: %o", error.message); });
}, Math.random() * 1000);
})
.then(console.log("Promise all transaction ok!"))
.catch(e => console.log("promise all error: %o", e.message))
// sendCoin(contractAddr, sendCointoAddr, 10).then((signedTx) => {
// console.log('sendCoin 2 signedTx: %o', signedTx);
// const sentTx2 = web3.eth.sendSignedTransaction(signedTx.raw || signedTx.rawTransaction);
// sentTx2.then(o => {
// TxHash = o.transactionHash;
// console.log("##### sendCoin 2 TxHash: %o", TxHash)
// })
// .catch((error) => { console.log("sendCoin 2 catch error: %o", error.message); });
// }).catch((error) => { console.log("sendSignedTransaction2 catch error: %o", error.message); });
// sendCoin(contractAddr, sendCointoAddr, 10).then((signedTx) => {
// console.log('sendCoin 3 signedTx: %o', signedTx);
// const sentTx3 = web3.eth.sendSignedTransaction(signedTx.raw || signedTx.rawTransaction);
// sentTx3.then(o => {
// TxHash = o.transactionHash;
// console.log("##### sendCoin 3 TxHash: %o", TxHash)
// })
// .catch((error) => { console.log("sendCoin 3 catch error: %o", error.message); });
// }).catch((error) => { console.log("sendSignedTransaction3 catch error: %o", error.message); });
//metaCoinContract.events.allEvents()
metaCoinContract.events.Transfer()
.on('data', function(event){
console.log("##### events data: %o", event); // same results as the optional callback above
})
.on('changed', function(event){
console.log("##### events changed: %o", event);
})
.on('error', console.error);
metaCoinContract.getPastEvents('Transfer', function(error, events){ console.log("##### getPastEvents changed: %o", events); })
.then(function(events){
console.log("##### getPastEvents changed: %o", events) // same results as the optional callback above
});