[ javascript ]OPTIONS request instead of GET request

XMLHttpRequest cannot load https://whatever.xss.com/whatever?whatever=whatever. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mydomain.com:XXXX' is therefore not allowed access.
Advertisements

[ javascript ] the good parts

1)Default value

var difficulty = game.difficulty || 'easy!';

Trying to get a value from an undefined value will produce a TypeError

game.options.packs
// TypeError

2)Four way to invoke method

i)Method Invocation

 

ii)Function Invocation

 

iii)Constructor Invocation

In the classical OOP style, you create instances of objects that are based on classes! JavaScript does not work like this at all. In JavaScript objects are derived from other objects.

var House = function (windows, color) {
 this.windows = windows;
 this.color = color;
};

House.prototype.getwindows = function () {
 return this.windows;
};

House.prototype.getcolor = function () {
 return this.color;
};

house1 = new House(10, 'red');
house2 = new House(12, 'grey');

$('#clickconstructorinvocation').click(function () {
 $('#constructorinvocation').html('House two has ' + house2.getwindows() + ' Windows and is ' + house2.getcolor() + ' in color.');
});

Result

House two has 12 Windows and is grey in color.

Make sure to always use a capital letter on the variable that stores the function constructor. This is how you can quickly determine when a variable is meant to hold a JavaScript constructor.

iv)Apply Invocation

The first parameter to the apply method is what this should be bound to.

var car = {
 make: 'Subaru',
 model: 'WRX'
};
var truck = {
 make: 'Nissan',
 model: 'Titan'
};

function describe(info) {
 return info + ' ' + this.make + ' ' + this.model;
}

$('#clickapplyinvocation').click(function () {
 $('#applyinvocation').html(describe.apply(truck, [2015]) + ' ( <code>this</code> bound to <code>truck</code> )<br> ' + describe.apply(car, [2016]) + ' ( <code>this</code> bound to <code>car</code>) ');
});

Result

2015 Nissan Titan ( this bound to truck )
2016 Subaru WRX ( this bound to car)

 

3) arguments

var sum = function () {
 var i, sum = 0;
 for (i = 0; i < arguments.length; i += 1) {
 sum += arguments[i];
 }
 return sum;
};

$('#clickarguments').click(function () {
 $('#arguments').html(sum(1,2,3,4,5,6,7,8,9));
});

 

4) try/catch/throw

var adder = function (one, two) {
 if (typeof one !== 'number' || typeof two !== 'number') {
 throw {
 name: 'TypeError',
 message: '<code>adder()</code> needs numbers'
 }
 }
 return one + two;
};

var tryadding = function () {
 try {
 adder("four");
 } catch (e) {
 var message = (e.name + ': ' + e.message);
 $('#exceptions').html(message);
 }
};

$('#clickexceptions').click(function () {
 tryadding();
});

 

5) Towers of Hanoi puzzle solved with recursion

var recurred = '';
var hanoi = function (disc, source, temporary, destination) {
 if (disc > 0) {
 hanoi(disc - 1, source, destination, temporary);
 recurred += 'Move disc ' + disc + ' from ' + source + ' to ' + destination + '<br>';
 hanoi(disc - 1, temporary, source, destination);
 }
};

$('#clickrecursion').click(function () {
 hanoi(4, 'Soure', 'Temporary', 'Destination');
 $('#recursion').html(recurred);
});

Result

Move disc 1 from Soure to Temporary
Move disc 2 from Soure to Destination
Move disc 1 from Temporary to Destination
Move disc 3 from Soure to Temporary
Move disc 1 from Destination to Soure
Move disc 2 from Destination to Temporary
Move disc 1 from Soure to Temporary
Move disc 4 from Soure to Destination
Move disc 1 from Temporary to Destination
Move disc 2 from Temporary to Soure
Move disc 1 from Destination to Soure
Move disc 3 from Temporary to Destination
Move disc 1 from Soure to Temporary
Move disc 2 from Soure to Destination
Move disc 1 from Temporary to Destination

 

6) scope

var : declare local variable which can be used inside the closure

 

7) closure

Closure depends on Lexical Scope.

 

function crockford() {
 var fact = "Douglas Crockford variable scopes are his fists";

 function nunchucks() {
 console.log(fact);
 }

 swing(nunchucks);
}

function swing(nunchucks) {
 nunchucks(); // "Douglas Crockford variable scopes are his fists"
}

crockford();

 

If you have an inner function for which the compiler can not find a reference to a variable in it’s scope, it will move outside of it’s bubble so to speak to the next outer level, and request that outer scope for a reference to that variable. This continues until finally the global scope is reached, and if there is no variable reference there, then one gets created (in non strict mode).

 

8) callback

 

9) module

var module = (function factory() {

 var privateobject = {fact: "Douglas Crockford can have full conversations using only javascript's reserved words."};

 return {
 preach: function () {
 console.log(privateobject.fact);
 }
 };
})();

module.preach();

 

10) delegation ( inheritance )

All objects in JavaScript are created by a constructor function. This new object is not based on the prototype, it is linked to the prototype.

 

function Person(name) {
 this.name = name;
}

Person.prototype.myname = function () {
 return 'I am ' + this.name;
};

var Person1 = new Person('Douglas Crockford');
var Person2 = new Person('Brendan Eich');

Person1.greet = function () {
 $('#delegationex').html('Hello, my name is ' + this.myname() + '!<br>');
};

Person2.greet = function () {
 $('#delegationex').append('Hi, my name is ' + this.myname() + '!');
};

Person1.greet();

Person2.greet();

Neither the Person1 or Person2 object has a myname() function defined on them. So what happens in this example when they execute, is they need to move up the prototype chain to find that myname() function. Since each Person object has a link to Person.prototype we can see that the prototype does indeed have a function named myname(). So we can say that these new objects are delegating the responsibility of calling the myname() function to their prototype.

 

11) Array

JavaScript converts the array subscripts into strings, and those strings become properties on the object.

We can define `false`, `[]`, `null`, `undefined`, `NaN` to Array.

> typeof false
"boolean"
> typeof []
"object"
> typeof null
"object"
> typeof undefined
"undefined"
> typeof NaN
"number

 

ref : http://vegibit.com/douglas-crockford-the-good-parts-examples/#modules

More about this : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

More about module pattern : http://vegibit.com/javascript-module-pattern/

More about Object function : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object

อัตราดอกเบี้ยแบบไม่หักภาษี

เวลาดูดอกเบี้ยเผื่อเรียกพิเศษของธนาคาร ก็ดูที่เขาคำนวณให้ทุกที

เช่น

แบบไม่หักภาษีร้อยละ 1.25 ต่อปี (เทียบเท่าเงินฝากประจำร้อยละ 1.47 ต่อปี)

มันคิดยังไงกัน

 

สมมติมีเงินฝาก 100

ได้ดอกจริงๆ 1.47*0.85=1.2495 ( 0.85 คือ เงินเหลือหลังหักภาษี 15% แล้ว )

 

[ stringex ] acts_as_url

Installation

gem 'stringex', git: 'https://github.com/rsl/stringex.git'
bundle

Usage

class YourModel < ActiveRecord::Base
  acts_as_url :title, sync_url: true
end
  • All the update will be applied to the `url` column.

We can use normal ActiveRecord query. Example

YourModel.where(url: "whatever")

Migration

class AddUrlToYourModel < ActiveRecord::Migration
def change
add_column :your_models, :url, :string
add_index :your_models, :url
end
end

Filling the NULL value in the URL column.

YourModel.initialize_urls

 

Conversion

'rock &amp; roll'.to_url =&gt; "rock-and-roll"

 

ref : https://github.com/rsl/stringex

[ progress_job ] progress bar in rails

Dependencies

delayed_job_active_record ( https://dsin.wordpress.com/2017/03/22/rails-delayed_job/ )

 

Installation

Gemfile

gem 'progress_job'

then

$ bundle install

 

First run

adding 3 columns to the delayed_jobs table

progress_stage : string ( customizable description for the current progress stage of the task )

progress_current : integer ( number representing the current progress value of the task )
progress_max : integer ( number representing the maximum progress value of the task )

$ rails generate progress_job:install
 $ rake db:migrate

 

Override method using `ProgressJob::Base`

class MyJob &lt;&nbsp; ProgressJob::Base
...
  update_progress(step: 10) # increase the progress_current for step
  update_stage('name of stage') # change the progress_stage
  update_stage_progress('name of stage', step: 11) # change progress_stage and increase&nbsp; &nbsp;progress_current for step
  update_progress_max(progress_max) # change progress_max
...
end

 

Progress_job also gives you a route from which you can get all the info on a progress_job, and it is located at:

GET /progress-jobs/:job_id

Ajax call which will check the route every few seconds and update the progress bar visible on the screen.

app/jobs/export.rb

class ExportJob < ProgressJob::Base
def initialize(users, progress_max)
super progress_max: progress_max
@users = users
end

def perform
update_stage('Exporting users')
csv_string = CSV.generate do |csv|
@users.each do |user|
csv << user.to_csv
update_progress
end
end
File.open('path/to/export.csv', 'w') { |f| f.write(csv_string) }
end
end

ref : https://infinum.co/the-capsized-eight/progress-bar-in-rails,

DEMO : https://github.com/d4be4st/progress_job_demo

[ Google Analytics : analytics.js ] set sample rate

ga.js ( legacy )

_gaq.push(['_setSampleRate', '80']);

analytics.js

ga('create', 'UA-XXXXX-Y', {
sampleRate: 80
});

This defaults to 100  (no users are sampled out) but large sites may need to use a lower sample rate to stay within Google Analytics processing limits.

ref : https://misterphilip.com/universal-analytics/migration/config

, https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#sampleRate