language stringclasses 6
values | original_string stringlengths 25 887k | text stringlengths 25 887k |
|---|---|---|
JavaScript | function gitHasChanges() {
return git(`status --porcelain --untracked-files=all`)
.then(result => {
let {index, workingTree} = gitUtil.extractStatus(result);
if (index) {
if (isNonEmpty(index.modified) || isNonEmpty(index.added) || isNonEmpty(index.deleted) ||
... | function gitHasChanges() {
return git(`status --porcelain --untracked-files=all`)
.then(result => {
let {index, workingTree} = gitUtil.extractStatus(result);
if (index) {
if (isNonEmpty(index.modified) || isNonEmpty(index.added) || isNonEmpty(index.deleted) ||
... |
JavaScript | async function post(post) {
if (!isValid(post)) return response_400("Invalid post data");
post.id = generateRandomId();
post.createdTime = new Date();
await POSTS.put(post.id, JSON.stringify(post));
return new Response("Success", {
status: 200,
statusText: "OK",
headers: {
...cors_headers... | async function post(post) {
if (!isValid(post)) return response_400("Invalid post data");
post.id = generateRandomId();
post.createdTime = new Date();
await POSTS.put(post.id, JSON.stringify(post));
return new Response("Success", {
status: 200,
statusText: "OK",
headers: {
...cors_headers... |
JavaScript | function isValid(post) {
return typeof(post.title) === "string"
&& typeof(post.username) === "string"
&& typeof(post.content) === "string";
} | function isValid(post) {
return typeof(post.title) === "string"
&& typeof(post.username) === "string"
&& typeof(post.content) === "string";
} |
JavaScript | function generateRandomId(length = 10, characters = "abcdefghijklmnopqrstuvwxzyABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") {
let id = "";
for (let i = 0; i < length; i++) {
id += characters[Math.floor(Math.random() * characters.length)];
}
return id;
} | function generateRandomId(length = 10, characters = "abcdefghijklmnopqrstuvwxzyABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") {
let id = "";
for (let i = 0; i < length; i++) {
id += characters[Math.floor(Math.random() * characters.length)];
}
return id;
} |
JavaScript | preInit({ agent, protocol, timeout, concurrency, connection }) {
this.concurrency = concurrency > 0 ? concurrency : 1;
this.connection = Connection.create(connection);
if (agent) this.globalize(protocol, agent);
} | preInit({ agent, protocol, timeout, concurrency, connection }) {
this.concurrency = concurrency > 0 ? concurrency : 1;
this.connection = Connection.create(connection);
if (agent) this.globalize(protocol, agent);
} |
JavaScript | preDelete() {
if (
global.FMS_API_CLIENT.AGENTS &&
global.FMS_API_CLIENT.AGENTS[this.global]
) {
this.localize()[`${this.protocol}Agent`].destroy();
delete global.FMS_API_CLIENT.AGENTS[this.global];
}
} | preDelete() {
if (
global.FMS_API_CLIENT.AGENTS &&
global.FMS_API_CLIENT.AGENTS[this.global]
) {
this.localize()[`${this.protocol}Agent`].destroy();
delete global.FMS_API_CLIENT.AGENTS[this.global];
}
} |
JavaScript | globalize(protocol, agent) {
if (!this.global) this.global = uuidv4();
/**
* @global
*/
global.FMS_API_CLIENT.AGENTS[this.global] =
protocol === 'https'
? {
httpsAgent: new https.Agent(this.agent)
}
: {
httpAgent: new http.Agent(this.agent)
... | globalize(protocol, agent) {
if (!this.global) this.global = uuidv4();
/**
* @global
*/
global.FMS_API_CLIENT.AGENTS[this.global] =
protocol === 'https'
? {
httpsAgent: new https.Agent(this.agent)
}
: {
httpAgent: new http.Agent(this.agent)
... |
JavaScript | localize() {
if (typeof global.FMS_API_CLIENT.AGENTS === 'undefined')
global.FMS_API_CLIENT.AGENTS = [];
if (global.FMS_API_CLIENT.AGENTS[this.global]) {
return global.FMS_API_CLIENT.AGENTS[this.global];
} else {
return this.globalize(this.protocol, this.agent);
}
} | localize() {
if (typeof global.FMS_API_CLIENT.AGENTS === 'undefined')
global.FMS_API_CLIENT.AGENTS = [];
if (global.FMS_API_CLIENT.AGENTS[this.global]) {
return global.FMS_API_CLIENT.AGENTS[this.global];
} else {
return this.globalize(this.protocol, this.agent);
}
} |
JavaScript | request(data, parameters = {}) {
const id = uuidv4();
const interceptor = instance.interceptors.request.use(
({ httpAgent, httpsAgent, ...request }) => {
instance.interceptors.request.eject(interceptor);
return new Promise((resolve, reject) =>
this.push({
request: thi... | request(data, parameters = {}) {
const id = uuidv4();
const interceptor = instance.interceptors.request.use(
({ httpAgent, httpsAgent, ...request }) => {
instance.interceptors.request.eject(interceptor);
return new Promise((resolve, reject) =>
this.push({
request: thi... |
JavaScript | handleResponse(response, id) {
const token = _.get(response, 'config.headers.Authorization');
if (token) {
this.connection.deactivate(token, id);
}
if (typeof response.data !== 'object') {
return Promise.reject({
message: 'The Data API is currently unavailable',
code: '1630'
... | handleResponse(response, id) {
const token = _.get(response, 'config.headers.Authorization');
if (token) {
this.connection.deactivate(token, id);
}
if (typeof response.data !== 'object') {
return Promise.reject({
message: 'The Data API is currently unavailable',
code: '1630'
... |
JavaScript | handleRequest(config, id) {
config.id = id;
return config.url.startsWith('http')
? omit(config, ['params.request', 'data.request'])
: Promise.reject({
code: '1630',
message: 'The Data API Requires https or http'
});
} | handleRequest(config, id) {
config.id = id;
return config.url.startsWith('http')
? omit(config, ['params.request', 'data.request'])
: Promise.reject({
code: '1630',
message: 'The Data API Requires https or http'
});
} |
JavaScript | push({ request, resolve, reject }) {
this.queue.push({
request: this.mutate(request, (value, key) =>
key.replace(/\./g, '{{dot}}')
),
resolve
});
this.shift();
this.watch(reject);
} | push({ request, resolve, reject }) {
this.queue.push({
request: this.mutate(request, (value, key) =>
key.replace(/\./g, '{{dot}}')
),
resolve
});
this.shift();
this.watch(reject);
} |
JavaScript | shift() {
if (this.pending.length < this.concurrency) {
this.pending.push(this.queue.shift());
}
} | shift() {
if (this.pending.length < this.concurrency) {
this.pending.push(this.queue.shift());
}
} |
JavaScript | mutate(request, mutation) {
const {
transformRequest,
transformResponse,
adapter,
validateStatus,
...value
} = request;
const modified = request.url.includes('/containers/')
? request
: deepMapKeys(value, mutation);
return {
...modified,
transformR... | mutate(request, mutation) {
const {
transformRequest,
transformResponse,
adapter,
validateStatus,
...value
} = request;
const modified = request.url.includes('/containers/')
? request
: deepMapKeys(value, mutation);
return {
...modified,
transformR... |
JavaScript | handleError(error, id) {
const token = _.get(error, 'config.headers.Authorization');
if (token) {
this.connection.deactivate(token, id);
}
this.connection.confirm();
if (error.code) {
return Promise.reject({ code: error.code, message: error.message });
} else if (
error.r... | handleError(error, id) {
const token = _.get(error, 'config.headers.Authorization');
if (token) {
this.connection.deactivate(token, id);
}
this.connection.confirm();
if (error.code) {
return Promise.reject({ code: error.code, message: error.message });
} else if (
error.r... |
JavaScript | watch(reject) {
if (!this.global) this.global = uuidv4();
if (!global.FMS_API_CLIENT.WATCHERS) global.FMS_API_CLIENT.WATCHERS = {};
if (!global.FMS_API_CLIENT.WATCHERS[this.global]) {
const WATCHER = setTimeout(
function watch() {
this.connection.clear();
if (
t... | watch(reject) {
if (!this.global) this.global = uuidv4();
if (!global.FMS_API_CLIENT.WATCHERS) global.FMS_API_CLIENT.WATCHERS = {};
if (!global.FMS_API_CLIENT.WATCHERS[this.global]) {
const WATCHER = setTimeout(
function watch() {
this.connection.clear();
if (
t... |
JavaScript | resolve() {
const pending = this.pending.shift();
this.connection
.authentication(
Object.assign(
this.mutate(pending.request, (value, key) =>
key.replace(/{{dot}}/g, '.')
),
{ id: pending.id }
),
_.isEmpty(this.agent) ? {} : this.localize(... | resolve() {
const pending = this.pending.shift();
this.connection
.authentication(
Object.assign(
this.mutate(pending.request, (value, key) =>
key.replace(/{{dot}}/g, '.')
),
{ id: pending.id }
),
_.isEmpty(this.agent) ? {} : this.localize(... |
JavaScript | status() {
const status = {
data: {
since: this.since,
in: pretty(this.in),
out: pretty(this.out)
}
};
return status;
} | status() {
const status = {
data: {
since: this.since,
in: pretty(this.in),
out: pretty(this.out)
}
};
return status;
} |
JavaScript | basic() {
const auth = `Basic ${Buffer.from(`${this.user}:${this.password}`).toString(
'base64'
)}`;
return auth;
} | basic() {
const auth = `Basic ${Buffer.from(`${this.user}:${this.password}`).toString(
'base64'
)}`;
return auth;
} |
JavaScript | authentication({ headers, id, ...request }) {
return new Promise((resolve, reject) => {
const sessions = _.sortBy(
this.sessions.filter(session => !session.expired()),
['active', 'used'],
['desc']
);
const session = sessions[0];
session.active = true;
session.ur... | authentication({ headers, id, ...request }) {
return new Promise((resolve, reject) => {
const sessions = _.sortBy(
this.sessions.filter(session => !session.expired()),
['active', 'used'],
['desc']
);
const session = sessions[0];
session.active = true;
session.ur... |
JavaScript | clear(header) {
this.sessions = this.sessions.filter(session =>
typeof header === 'string'
? header.replace('Bearer ', '') !== session.token
: !session.expired()
);
} | clear(header) {
this.sessions = this.sessions.filter(session =>
typeof header === 'string'
? header.replace('Bearer ', '') !== session.token
: !session.expired()
);
} |
JavaScript | extend(header) {
const token = header.replace('Bearer ', '');
const session = _.find(this.sessions, session => session.token === token);
if (session) session.extend();
} | extend(header) {
const token = header.replace('Bearer ', '');
const session = _.find(this.sessions, session => session.token === token);
if (session) session.extend();
} |
JavaScript | confirm() {
this.sessions.forEach(session => {
if (_.isEmpty(session.request)) {
session.active = false;
}
});
} | confirm() {
this.sessions.forEach(session => {
if (_.isEmpty(session.request)) {
session.active = false;
}
});
} |
JavaScript | deactivate(header, id) {
const token = header.replace('Bearer ', '');
const session = _.find(
this.sessions,
session => session.token === token || session.request === id
);
if (session) session.deactivate();
} | deactivate(header, id) {
const token = header.replace('Bearer ', '');
const session = _.find(
this.sessions,
session => session.token === token || session.request === id
);
if (session) session.deactivate();
} |
JavaScript | preInit(data) {
const {
agent,
timeout,
concurrency,
threshold,
usage,
proxy,
...connection
} = data;
const protocol = data.server.startsWith('https') ? 'https' : 'http';
this.data = Data.create({ track: usage === undefined });
this.agent = Agent.create({
... | preInit(data) {
const {
agent,
timeout,
concurrency,
threshold,
usage,
proxy,
...connection
} = data;
const protocol = data.server.startsWith('https') ? 'https' : 'http';
this.data = Data.create({ track: usage === undefined });
this.agent = Agent.create({
... |
JavaScript | preDelete() {
return new Promise((resolve, reject) =>
this.agent.connection
.end()
.then(response => resolve())
.catch(error => resolve(error))
);
} | preDelete() {
return new Promise((resolve, reject) =>
this.agent.connection
.end()
.then(response => resolve())
.catch(error => resolve(error))
);
} |
JavaScript | login() {
return new Promise((resolve, reject) =>
this.agent.connection
.start(!_.isEmpty(this.agent.agent) ? this.agent.localize() : false)
.then(body => this.data.outgoing(body))
.then(body => this._save(resolve(body)))
.catch(error => this._save(reject(error)))
);
} | login() {
return new Promise((resolve, reject) =>
this.agent.connection
.start(!_.isEmpty(this.agent.agent) ? this.agent.localize() : false)
.then(body => this.data.outgoing(body))
.then(body => this._save(resolve(body)))
.catch(error => this._save(reject(error)))
);
} |
JavaScript | logout(id) {
return new Promise((resolve, reject) =>
this.agent.connection
.end(!_.isEmpty(this.agent.agent) ? this.agent.localize() : false, id)
.then(body => this.data.outgoing(body))
.then(body => this._save(resolve(body)))
.catch(error => this._save(reject(error)))
);
... | logout(id) {
return new Promise((resolve, reject) =>
this.agent.connection
.end(!_.isEmpty(this.agent.agent) ? this.agent.localize() : false, id)
.then(body => this.data.outgoing(body))
.then(body => this._save(resolve(body)))
.catch(error => this._save(reject(error)))
);
... |
JavaScript | productInfo() {
return new Promise((resolve, reject) =>
productInfo(this.agent.connection.server, this.agent.connection.version)
.then(response => resolve(response))
.catch(error => this._save(reject(error)))
);
} | productInfo() {
return new Promise((resolve, reject) =>
productInfo(this.agent.connection.server, this.agent.connection.version)
.then(response => resolve(response))
.catch(error => this._save(reject(error)))
);
} |
JavaScript | status() {
return new Promise((resolve, reject) =>
resolve({
...this.data.status(),
queue: this.agent.queue.map(({ url }) => ({ url })),
pending: this.agent.pending.map(({ url }) => ({ url })),
sessions: this.agent.connection.sessions.map(
({ issued, expires, id }) =>... | status() {
return new Promise((resolve, reject) =>
resolve({
...this.data.status(),
queue: this.agent.queue.map(({ url }) => ({ url })),
pending: this.agent.pending.map(({ url }) => ({ url })),
sessions: this.agent.connection.sessions.map(
({ issued, expires, id }) =>... |
JavaScript | reset() {
return new Promise((resolve, reject) => {
const logouts = [];
this.agent.queue = [];
this.agent.pending = [];
this.agent.connection.sessions.forEach(({ id }) =>
logouts.push(this.logout(id))
);
Promise.all(logouts)
.then(results => {
return thi... | reset() {
return new Promise((resolve, reject) => {
const logouts = [];
this.agent.queue = [];
this.agent.pending = [];
this.agent.connection.sessions.forEach(({ id }) =>
logouts.push(this.logout(id))
);
Promise.all(logouts)
.then(results => {
return thi... |
JavaScript | databases(credentials, version) {
return new Promise((resolve, reject) =>
databases(
this.agent.connection.server,
credentials || this.agent.connection.credentials,
this.agent.connection.version
)
.then(response => resolve(response))
.catch(error => this._save(rej... | databases(credentials, version) {
return new Promise((resolve, reject) =>
databases(
this.agent.connection.server,
credentials || this.agent.connection.credentials,
this.agent.connection.version
)
.then(response => resolve(response))
.catch(error => this._save(rej... |
JavaScript | layouts(parameters = {}) {
return new Promise((resolve, reject) =>
this.agent
.request(
{
url: urls.layouts(
this.agent.connection.server,
this.agent.connection.database,
this.agent.connection.version
),
method: 'g... | layouts(parameters = {}) {
return new Promise((resolve, reject) =>
this.agent
.request(
{
url: urls.layouts(
this.agent.connection.server,
this.agent.connection.database,
this.agent.connection.version
),
method: 'g... |
JavaScript | scripts(parameters = {}) {
return new Promise((resolve, reject) =>
this.agent
.request(
{
url: urls.scripts(
this.agent.connection.server,
this.agent.connection.database,
this.agent.connection.version
),
method: 'g... | scripts(parameters = {}) {
return new Promise((resolve, reject) =>
this.agent
.request(
{
url: urls.scripts(
this.agent.connection.server,
this.agent.connection.database,
this.agent.connection.version
),
method: 'g... |
JavaScript | layout(layout, parameters = {}) {
return new Promise((resolve, reject) =>
this.agent
.request(
{
url: urls.layout(
this.agent.connection.server,
this.agent.connection.database,
layout,
this.agent.connection.version
... | layout(layout, parameters = {}) {
return new Promise((resolve, reject) =>
this.agent
.request(
{
url: urls.layout(
this.agent.connection.server,
this.agent.connection.database,
layout,
this.agent.connection.version
... |
JavaScript | duplicate(layout, recordId, parameters = {}) {
return new Promise((resolve, reject) =>
this.agent
.request(
{
url: urls.duplicate(
this.agent.connection.server,
this.agent.connection.database,
layout,
recordId,
... | duplicate(layout, recordId, parameters = {}) {
return new Promise((resolve, reject) =>
this.agent
.request(
{
url: urls.duplicate(
this.agent.connection.server,
this.agent.connection.database,
layout,
recordId,
... |
JavaScript | create(layout, data = {}, parameters = {}) {
return new Promise((resolve, reject) =>
this.agent
.request(
{
url: urls.create(
this.agent.connection.server,
this.agent.connection.database,
layout,
this.agent.connection.versio... | create(layout, data = {}, parameters = {}) {
return new Promise((resolve, reject) =>
this.agent
.request(
{
url: urls.create(
this.agent.connection.server,
this.agent.connection.database,
layout,
this.agent.connection.versio... |
JavaScript | edit(layout, recordId, data, parameters = {}) {
return new Promise((resolve, reject) =>
this.agent
.request(
{
url: urls.update(
this.agent.connection.server,
this.agent.connection.database,
layout,
recordId,
t... | edit(layout, recordId, data, parameters = {}) {
return new Promise((resolve, reject) =>
this.agent
.request(
{
url: urls.update(
this.agent.connection.server,
this.agent.connection.database,
layout,
recordId,
t... |
JavaScript | delete(layout, recordId, parameters = {}) {
return new Promise((resolve, reject) =>
this.agent
.request(
{
url: urls.delete(
this.agent.connection.server,
this.agent.connection.database,
layout,
recordId,
this.... | delete(layout, recordId, parameters = {}) {
return new Promise((resolve, reject) =>
this.agent
.request(
{
url: urls.delete(
this.agent.connection.server,
this.agent.connection.database,
layout,
recordId,
this.... |
JavaScript | list(layout, parameters = {}) {
return new Promise((resolve, reject) =>
this.agent
.request(
{
url: urls.list(
this.agent.connection.server,
this.agent.connection.database,
layout,
this.agent.connection.version
)... | list(layout, parameters = {}) {
return new Promise((resolve, reject) =>
this.agent
.request(
{
url: urls.list(
this.agent.connection.server,
this.agent.connection.database,
layout,
this.agent.connection.version
)... |
JavaScript | find(layout, query, parameters = {}) {
return new Promise((resolve, reject) =>
this.agent
.request(
{
url: urls.find(
this.agent.connection.server,
this.agent.connection.database,
layout,
this.agent.connection.version
... | find(layout, query, parameters = {}) {
return new Promise((resolve, reject) =>
this.agent
.request(
{
url: urls.find(
this.agent.connection.server,
this.agent.connection.database,
layout,
this.agent.connection.version
... |
JavaScript | globals(data, parameters) {
return new Promise((resolve, reject) =>
this.agent
.request(
{
url: urls.globals(
this.agent.connection.server,
this.agent.connection.database,
this.agent.connection.version
),
method: '... | globals(data, parameters) {
return new Promise((resolve, reject) =>
this.agent
.request(
{
url: urls.globals(
this.agent.connection.server,
this.agent.connection.database,
this.agent.connection.version
),
method: '... |
JavaScript | upload(file, layout, containerFieldName, recordId = 0, parameters = {}) {
return new Promise((resolve, reject) => {
let stream;
const form = new FormData();
const resolveRecordId = () =>
recordId === 0
? this.create(layout, {}).then(response => response.recordId)
: Prom... | upload(file, layout, containerFieldName, recordId = 0, parameters = {}) {
return new Promise((resolve, reject) => {
let stream;
const form = new FormData();
const resolveRecordId = () =>
recordId === 0
? this.create(layout, {}).then(response => response.recordId)
: Prom... |
JavaScript | run(layout, scripts, parameters, request) {
return new Promise((resolve, reject) =>
this.agent
.request(
{
url: urls.list(
this.agent.connection.server,
this.agent.connection.database,
layout,
this.agent.connection.version
... | run(layout, scripts, parameters, request) {
return new Promise((resolve, reject) =>
this.agent
.request(
{
url: urls.list(
this.agent.connection.server,
this.agent.connection.database,
layout,
this.agent.connection.version
... |
JavaScript | script(layout, script, param = {}, parameters) {
return new Promise((resolve, reject) =>
this.agent
.request(
{
url: urls.script(
this.agent.connection.server,
this.agent.connection.database,
layout,
script,
th... | script(layout, script, param = {}, parameters) {
return new Promise((resolve, reject) =>
this.agent
.request(
{
url: urls.script(
this.agent.connection.server,
this.agent.connection.database,
layout,
script,
th... |
JavaScript | function checkAnswer(answer){
correct = myQuestions[currentQuestionIndex].correctAnswer;
if (answer === correct && currentQuestionIndex !== finalQuestionIndex){
score++;
alert("Correct!");
currentQuestionIndex++;
generateQuestion();
//display in the results div that the ... | function checkAnswer(answer){
correct = myQuestions[currentQuestionIndex].correctAnswer;
if (answer === correct && currentQuestionIndex !== finalQuestionIndex){
score++;
alert("Correct!");
currentQuestionIndex++;
generateQuestion();
//display in the results div that the ... |
JavaScript | function generateScores(){
initialsContainer.innerHTML = "";
scoreContainer.innerHTML = "";
var highscores = JSON.parse(localStorage.getItem("savedHighscores")) || [];
for (i=0; i<highscores.length; i++){
var newNameSpan = document.createElement("li");
var newScoreSpan = document.createE... | function generateScores(){
initialsContainer.innerHTML = "";
scoreContainer.innerHTML = "";
var highscores = JSON.parse(localStorage.getItem("savedHighscores")) || [];
for (i=0; i<highscores.length; i++){
var newNameSpan = document.createElement("li");
var newScoreSpan = document.createE... |
JavaScript | trim(ago, now = Date.now()) {
const times = this.times;
const path = this.line.path;
const oldest = now-ago;
while(times[0] < oldest) {
times.shift();
path.shift();
}
return this.length;
} | trim(ago, now = Date.now()) {
const times = this.times;
const path = this.line.path;
const oldest = now-ago;
while(times[0] < oldest) {
times.shift();
path.shift();
}
return this.length;
} |
JavaScript | draw() {
this.viewport();
// Flow FBO and view renders
Object.assign(this.uniforms.render, this.state, {
time: this.timer.time,
previous: this.particles.buffers[1].color[0].bind(1),
viewSize: this.viewSize,
viewRes: this.viewRes,... | draw() {
this.viewport();
// Flow FBO and view renders
Object.assign(this.uniforms.render, this.state, {
time: this.timer.time,
previous: this.particles.buffers[1].color[0].bind(1),
viewSize: this.viewSize,
viewRes: this.viewRes,... |
JavaScript | drawBuffer(index) {
this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, null);
if(this.state.autoClearView) {
this.gl.clear(this.gl.COLOR_BUFFER_BIT);
}
return this.copyBuffer(index).stepBuffers();
} | drawBuffer(index) {
this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, null);
if(this.state.autoClearView) {
this.gl.clear(this.gl.COLOR_BUFFER_BIT);
}
return this.copyBuffer(index).stepBuffers();
} |
JavaScript | copyBuffer(index = 0) {
if(index < this.buffers.length) {
this.copyShader.bind();
Object.assign(this.copyShader.uniforms, {
view: this.buffers[index].color[0].bind(0),
viewRes: this.viewRes
});
this.screen.render();
... | copyBuffer(index = 0) {
if(index < this.buffers.length) {
this.copyShader.bind();
Object.assign(this.copyShader.uniforms, {
view: this.buffers[index].color[0].bind(0),
viewRes: this.viewRes
});
this.screen.render();
... |
JavaScript | spawn(spawner = initSpawner) {
this.particles.spawn(spawner);
return this;
} | spawn(spawner = initSpawner) {
this.particles.spawn(spawner);
return this;
} |
JavaScript | spawnShader(shader, update, ...rest) {
this.timer.tick();
this.particles.logic = shader;
// @todo Allow switching between the particles data and the targets.
// Disabling blending here is important
this.gl.disable(this.gl.BLEND);
this.particles.step(Particles.applyUpd... | spawnShader(shader, update, ...rest) {
this.timer.tick();
this.particles.logic = shader;
// @todo Allow switching between the particles data and the targets.
// Disabling blending here is important
this.gl.disable(this.gl.BLEND);
this.particles.step(Particles.applyUpd... |
JavaScript | step(update, buffer) {
if(buffer) {
buffer.bind();
}
else {
step(this.buffers);
this.buffers[0].bind();
}
this.gl.viewport(0, 0, this.shape[0], this.shape[1]);
this.logic.bind();
Particles.applyUpdate(Object.assign(this.logic... | step(update, buffer) {
if(buffer) {
buffer.bind();
}
else {
step(this.buffers);
this.buffers[0].bind();
}
this.gl.viewport(0, 0, this.shape[0], this.shape[1]);
this.logic.bind();
Particles.applyUpdate(Object.assign(this.logic... |
JavaScript | apply(f, out = this.outputs) {
this.each((track, key, ...rest) => {
const trackOut = (out[key] || (out[key] = {}));
return apply(f(track, key, ...rest, trackOut), trackOut);
});
return this;
} | apply(f, out = this.outputs) {
this.each((track, key, ...rest) => {
const trackOut = (out[key] || (out[key] = {}));
return apply(f(track, key, ...rest, trackOut), trackOut);
});
return this;
} |
JavaScript | add(...frame) {
const adding = makeFrame(...frame);
const f = this.indexOf(adding);
this.insertFrame(f, adding);
return f;
} | add(...frame) {
const adding = makeFrame(...frame);
const f = this.indexOf(adding);
this.insertFrame(f, adding);
return f;
} |
JavaScript | spliceSpan(duration, start = 0, ...adding) {
const a = this.gapAt(start);
const b = this.gapAt(start+duration);
const i = Math.min(a, b);
return this.splice(Math.ceil(i), Math.floor(Math.max(a, b)-i),
...adding);
} | spliceSpan(duration, start = 0, ...adding) {
const a = this.gapAt(start);
const b = this.gapAt(start+duration);
const i = Math.min(a, b);
return this.splice(Math.ceil(i), Math.floor(Math.max(a, b)-i),
...adding);
} |
JavaScript | to(...frame) {
this.add(...frame);
return this;
} | to(...frame) {
this.add(...frame);
return this;
} |
JavaScript | easeJoin(f, align) {
let ease = null;
if(f > 0) {
const frame = this.frames[f];
ease = ((frame.ease && frame.ease.length)?
frame.ease : [0, 1]);
ease.splice(1, 0, joinCurve(this.frames[f-1].ease, align));
frame.ease = ease;
}... | easeJoin(f, align) {
let ease = null;
if(f > 0) {
const frame = this.frames[f];
ease = ((frame.ease && frame.ease.length)?
frame.ease : [0, 1]);
ease.splice(1, 0, joinCurve(this.frames[f-1].ease, align));
frame.ease = ease;
}... |
JavaScript | sample(dt = 1, method = 'frequencies') {
this.analyser[method](step(this.orderLog[0]));
orderLogRates(this.orderLog, dt);
return this;
} | sample(dt = 1, method = 'frequencies') {
this.analyser[method](step(this.orderLog[0]));
orderLogRates(this.orderLog, dt);
return this;
} |
JavaScript | function processBundle(resolve, reject) {
var bundle = this;
// Apply particular options if global settings dictate source files should be referenced inside sourcemaps.
var sourcemapOptions = {};
if (globalSettings.sourcemapOptions.type === 'External_ReferencedFiles') {
sourcemapOptions.include... | function processBundle(resolve, reject) {
var bundle = this;
// Apply particular options if global settings dictate source files should be referenced inside sourcemaps.
var sourcemapOptions = {};
if (globalSettings.sourcemapOptions.type === 'External_ReferencedFiles') {
sourcemapOptions.include... |
JavaScript | function makeAnalyser(...rest) {
const a = analyser(...rest);
const gain = a.gain = a.ctx.createGain();
const out = (a.splitter || a.analyser);
a.source.disconnect();
a.source.connect(gain).connect(out);
return a;
} | function makeAnalyser(...rest) {
const a = analyser(...rest);
const gain = a.gain = a.ctx.createGain();
const out = (a.splitter || a.analyser);
a.source.disconnect();
a.source.connect(gain).connect(out);
return a;
} |
JavaScript | function runWebpack(taskOptions) {
// Ensure there is an options object (incase none were supplied to this function).
taskOptions = (taskOptions || {});
// Bind a shorter reference to the script settings from the global file.
var scriptSettings = globalSettings.taskConfiguration.scripts;
// If pro... | function runWebpack(taskOptions) {
// Ensure there is an options object (incase none were supplied to this function).
taskOptions = (taskOptions || {});
// Bind a shorter reference to the script settings from the global file.
var scriptSettings = globalSettings.taskConfiguration.scripts;
// If pro... |
JavaScript | function firebaseConfig() {
const config = {
apiKey: "AIzaSyBpHwvxDeJ3W7c0YArgP1XSIiMmsCANo68",
authDomain: "firstfbproyect.firebaseapp.com",
projectId: "firstfbproyect",
storageBucket: "firstfbproyect.appspot.com",
messagingSenderId: "888798996437",
appId: "1:888798996437:web:18e424580075bd45... | function firebaseConfig() {
const config = {
apiKey: "AIzaSyBpHwvxDeJ3W7c0YArgP1XSIiMmsCANo68",
authDomain: "firstfbproyect.firebaseapp.com",
projectId: "firstfbproyect",
storageBucket: "firstfbproyect.appspot.com",
messagingSenderId: "888798996437",
appId: "1:888798996437:web:18e424580075bd45... |
JavaScript | function merge(source, dependencies) {
return function output() {
const mergedFiles = mergeStream(source(), dependencies())
.pipe(project.analyzer);
const bundleType = global.config.build.bundleType;
let outputs = [];
if (bundleType === 'both' || bundleType === 'bundled') {
outputs.push(w... | function merge(source, dependencies) {
return function output() {
const mergedFiles = mergeStream(source(), dependencies())
.pipe(project.analyzer);
const bundleType = global.config.build.bundleType;
let outputs = [];
if (bundleType === 'both' || bundleType === 'bundled') {
outputs.push(w... |
JavaScript | function writeBundledOutput(stream) {
return new Promise(resolve => {
stream.pipe(project.bundler)
.pipe(gulp.dest(bundledPath))
.on('end', resolve);
});
} | function writeBundledOutput(stream) {
return new Promise(resolve => {
stream.pipe(project.bundler)
.pipe(gulp.dest(bundledPath))
.on('end', resolve);
});
} |
JavaScript | function writeBundledServiceWorker() {
// On windows if we pass the path with back slashes the sw-precache node module is not going
// to strip the build/bundled or build/unbundled because the path was passed in with back slash.
return polymer.addServiceWorker({
project: project,
buildRoot: bundledPath.re... | function writeBundledServiceWorker() {
// On windows if we pass the path with back slashes the sw-precache node module is not going
// to strip the build/bundled or build/unbundled because the path was passed in with back slash.
return polymer.addServiceWorker({
project: project,
buildRoot: bundledPath.re... |
JavaScript | function writeUnbundledServiceWorker() {
return polymer.addServiceWorker({
project: project,
buildRoot: unbundledPath.replace('\\', '/'),
swConfig: global.config.swPrecacheConfig,
serviceWorkerPath: global.config.serviceWorkerPath
});
} | function writeUnbundledServiceWorker() {
return polymer.addServiceWorker({
project: project,
buildRoot: unbundledPath.replace('\\', '/'),
swConfig: global.config.swPrecacheConfig,
serviceWorkerPath: global.config.serviceWorkerPath
});
} |
JavaScript | function writable(value, start = _internal__WEBPACK_IMPORTED_MODULE_0__["noop"]) {
let stop;
const subscribers = [];
function set(new_value) {
if (Object(_internal__WEBPACK_IMPORTED_MODULE_0__["safe_not_equal"])(value, new_value)) {
value = new_value;
if (stop) { // store is ... | function writable(value, start = _internal__WEBPACK_IMPORTED_MODULE_0__["noop"]) {
let stop;
const subscribers = [];
function set(new_value) {
if (Object(_internal__WEBPACK_IMPORTED_MODULE_0__["safe_not_equal"])(value, new_value)) {
value = new_value;
if (stop) { // store is ... |
JavaScript | _sendIntentSuccess(intentObj, req, res) {
let data = {
result: intentObj.result()
};
try {
data.result = data.result.toJSON();
} catch (e) {
}
handleIntentSuccess(req, res, null, data, intentObj);
} | _sendIntentSuccess(intentObj, req, res) {
let data = {
result: intentObj.result()
};
try {
data.result = data.result.toJSON();
} catch (e) {
}
handleIntentSuccess(req, res, null, data, intentObj);
} |
JavaScript | _requestUniqueId() {
if (uniqueRequestId >= MAX_REQUEST_ID) {
uniqueRequestId = 0;
}
return uniqueRequestId++;
} | _requestUniqueId() {
if (uniqueRequestId >= MAX_REQUEST_ID) {
uniqueRequestId = 0;
}
return uniqueRequestId++;
} |
JavaScript | addHandler(actionObj, verb, url) {
if (typeof this[actions][actionObj.name] === 'undefined') {
this[actions][actionObj.name] = actionObj;
}
// check if it is a match.
let match = actionObj.__getMatch();
if (match.length > 0) {
for (let i = 0; i < match.length; i++) {
... | addHandler(actionObj, verb, url) {
if (typeof this[actions][actionObj.name] === 'undefined') {
this[actions][actionObj.name] = actionObj;
}
// check if it is a match.
let match = actionObj.__getMatch();
if (match.length > 0) {
for (let i = 0; i < match.length; i++) {
... |
JavaScript | listen(done) {
const app = express();
configureApp(app, this[config]);
// Configure Helmet
configureHelmet(app, this[config].helmet);
// handle CORS
registerCors(app, this[config].cors, this[config].corsIgnore);
// Handle static assets
registerStaticPaths(app, this[config... | listen(done) {
const app = express();
configureApp(app, this[config]);
// Configure Helmet
configureHelmet(app, this[config].helmet);
// handle CORS
registerCors(app, this[config].cors, this[config].corsIgnore);
// Handle static assets
registerStaticPaths(app, this[config... |
JavaScript | function configureApp(app, config) {
app.set('query parser', 'simple');
app.set('x-powered-by', false);
if (thorin.env === 'production') {
app.set('env', 'production');
}
app.set('views', undefined);
app.set('view cache', false);
if (config.trustProxy) {
app.set('trust proxy', tr... | function configureApp(app, config) {
app.set('query parser', 'simple');
app.set('x-powered-by', false);
if (thorin.env === 'production') {
app.set('env', 'production');
}
app.set('views', undefined);
app.set('view cache', false);
if (config.trustProxy) {
app.set('trust proxy', tr... |
JavaScript | function registerMiddleware(app, config) {
/* Check for basic auth */
if (config.authorization && typeof config.authorization.basic === 'object' && config.authorization.basic) {
registerBasicAuth(app, config.authorization.basic);
}
// Check if we have favicon
registerFavicon(app, config);
... | function registerMiddleware(app, config) {
/* Check for basic auth */
if (config.authorization && typeof config.authorization.basic === 'object' && config.authorization.basic) {
registerBasicAuth(app, config.authorization.basic);
}
// Check if we have favicon
registerFavicon(app, config);
... |
JavaScript | function handleRequestError(err, req, res, next) {
// In order to make errors visible, we have to set CORS for em.
let intentObj;
if (req.intent) {
intentObj = req.intent;
delete req.intent;
}
setCors.call(this, req, res, req.method);
let reqErr,
reqData,
statusCode = 400... | function handleRequestError(err, req, res, next) {
// In order to make errors visible, we have to set CORS for em.
let intentObj;
if (req.intent) {
intentObj = req.intent;
delete req.intent;
}
setCors.call(this, req, res, req.method);
let reqErr,
reqData,
statusCode = 400... |
JavaScript | function registerCors(app, corsConfig, corsIgnore) {
if (corsConfig === false) return;
let domains = [];
if (typeof corsConfig === 'string') {
domains = corsConfig.split(' ');
} else if (corsConfig instanceof Array) {
domains = corsConfig;
}
app.use((req, res, next) => {
let or... | function registerCors(app, corsConfig, corsIgnore) {
if (corsConfig === false) return;
let domains = [];
if (typeof corsConfig === 'string') {
domains = corsConfig.split(' ');
} else if (corsConfig instanceof Array) {
domains = corsConfig;
}
app.use((req, res, next) => {
let or... |
JavaScript | function parseRequestInput(source, target) {
let keys = Object.keys(source);
if (keys.length === 1) {
// Check if we have our main key as the full JSON
let tmp = keys[0], shouldParse = false;
tmp = tmp.trim();
if (tmp.charAt(0) === '{') {
for (let i = 0; i < Math.min(tmp.length, ... | function parseRequestInput(source, target) {
let keys = Object.keys(source);
if (keys.length === 1) {
// Check if we have our main key as the full JSON
let tmp = keys[0], shouldParse = false;
tmp = tmp.trim();
if (tmp.charAt(0) === '{') {
for (let i = 0; i < Math.min(tmp.length, ... |
JavaScript | function handleIntentSuccess(req, res, next, data, intentObj) {
let took = Date.now() - req.startAt,
status = 200,
isDone = false;
/* IF we already have a status code, we just end the rqeuest right here. */
try {
if (typeof res.statusCode !== 'number') {
res.status(status);
}... | function handleIntentSuccess(req, res, next, data, intentObj) {
let took = Date.now() - req.startAt,
status = 200,
isDone = false;
/* IF we already have a status code, we just end the rqeuest right here. */
try {
if (typeof res.statusCode !== 'number') {
res.status(status);
}... |
JavaScript | function handleIntentError(req, res, next, data, intentObj) {
if (intentObj.hasRawResult()) {
data.rawData = intentObj.result();
}
req.intent = intentObj;
return handleRequestError.call(this, data, req, res, next);
} | function handleIntentError(req, res, next, data, intentObj) {
if (intentObj.hasRawResult()) {
data.rawData = intentObj.result();
}
req.intent = intentObj;
return handleRequestError.call(this, data, req, res, next);
} |
JavaScript | function registerActionPath(verb, url, actionName) {
var app = this[server];
var reqHandler = handleIncomingRequest.bind(this, actionName, url);
app[verb](url, reqHandler);
// We have to insert the action handler right before the notfound handler.
let requestLayer = app._router.stack.pop(); // last ... | function registerActionPath(verb, url, actionName) {
var app = this[server];
var reqHandler = handleIncomingRequest.bind(this, actionName, url);
app[verb](url, reqHandler);
// We have to insert the action handler right before the notfound handler.
let requestLayer = app._router.stack.pop(); // last ... |
JavaScript | init(httpConfig) {
this[config] = thorin.util.extend({
debug: true,
port: 3000,
basePath: '/',
actionPath: '/dispatch', // this is the default frux listener for incoming frux actions.
authorization: {
"header": "Authorization", // By default, we will look into th... | init(httpConfig) {
this[config] = thorin.util.extend({
debug: true,
port: 3000,
basePath: '/',
actionPath: '/dispatch', // this is the default frux listener for incoming frux actions.
authorization: {
"header": "Authorization", // By default, we will look into th... |
JavaScript | run(done) {
this.app.listen((e) => {
if (e) return done(e);
thorin.dispatcher.registerTransport(this);
done();
});
} | run(done) {
this.app.listen((e) => {
if (e) return done(e);
thorin.dispatcher.registerTransport(this);
done();
});
} |
JavaScript | addMiddleware(fn) {
if (!this[app]) {
this[middleware].push(fn);
return this;
}
if (this.app.running) {
console.error('Thorin.transport.http: addMiddleware() must be called before the app is running.');
return this;
}
if (typeof fn !== 'function') {
... | addMiddleware(fn) {
if (!this[app]) {
this[middleware].push(fn);
return this;
}
if (this.app.running) {
console.error('Thorin.transport.http: addMiddleware() must be called before the app is running.');
return this;
}
if (typeof fn !== 'function') {
... |
JavaScript | routeAction(actionObj) {
this.app.addHandler(actionObj);
for (let i = 0; i < actionObj.aliases.length; i++) {
let alias = actionObj.aliases[i];
if (typeof alias.verb !== 'string') {
continue;
}
this.app.addHandler(actionObj, alias.verb, alias.name);
}
} | routeAction(actionObj) {
this.app.addHandler(actionObj);
for (let i = 0; i < actionObj.aliases.length; i++) {
let alias = actionObj.aliases[i];
if (typeof alias.verb !== 'string') {
continue;
}
this.app.addHandler(actionObj, alias.verb, alias.name);
}
} |
JavaScript | _log() {
if (this[config].debug === false) return;
let logObj = thorin.logger(this.name);
logObj.log.apply(logObj, arguments);
} | _log() {
if (this[config].debug === false) return;
let logObj = thorin.logger(this.name);
logObj.log.apply(logObj, arguments);
} |
JavaScript | match(reg) {
if (!(reg instanceof RegExp)) {
console.warn(`Action ${this.name} requires a regex for match()`);
return this;
}
this[match].push(reg);
return this;
} | match(reg) {
if (!(reg instanceof RegExp)) {
console.warn(`Action ${this.name} requires a regex for match()`);
return this;
}
this[match].push(reg);
return this;
} |
JavaScript | enableCors(originDomain, opt) {
this.cors = {
credentials: true
};
if (typeof originDomain === 'string') { // remove any trailing /
let corsDomain;
if (originDomain.indexOf('://') !== -1) {
let tmp = originDomain.split('//');
corsDomain = tmp[0] + '//';
... | enableCors(originDomain, opt) {
this.cors = {
credentials: true
};
if (typeof originDomain === 'string') { // remove any trailing /
let corsDomain;
if (originDomain.indexOf('://') !== -1) {
let tmp = originDomain.split('//');
corsDomain = tmp[0] + '//';
... |
JavaScript | hasCors() {
if (typeof this[cors] === 'undefined' || this[cors] === false) return false;
if (typeof this[cors] !== 'object' || !this[cors]) return false;
return true;
} | hasCors() {
if (typeof this[cors] === 'undefined' || this[cors] === false) return false;
if (typeof this[cors] !== 'object' || !this[cors]) return false;
return true;
} |
JavaScript | function researchedElecMiner() {
Object.values(mineableList).forEach((mineable) => {
mineable.elecMinersResearchDom.style.display = 'inline-block';
});
} | function researchedElecMiner() {
Object.values(mineableList).forEach((mineable) => {
mineable.elecMinersResearchDom.style.display = 'inline-block';
});
} |
JavaScript | function createDictionaryofTopWords(threshold) {
let topWords = {}
for (let [key, value] of Object.entries(frequencyData)) {
if (value.frequency > threshold) {
// threshold for top words
topWords[key] = value.frequency
}
}
return topWords
} | function createDictionaryofTopWords(threshold) {
let topWords = {}
for (let [key, value] of Object.entries(frequencyData)) {
if (value.frequency > threshold) {
// threshold for top words
topWords[key] = value.frequency
}
}
return topWords
} |
JavaScript | calculateInstanceSourceTargetPositions64xyLow(attribute, {startRow, endRow}) {
const isFP64 = this.use64bitPositions();
attribute.constant = !isFP64;
if (!isFP64) {
attribute.value = new Float32Array(4);
return;
}
const {data, getSourcePosition, getTargetPosition} = this.props;
con... | calculateInstanceSourceTargetPositions64xyLow(attribute, {startRow, endRow}) {
const isFP64 = this.use64bitPositions();
attribute.constant = !isFP64;
if (!isFP64) {
attribute.value = new Float32Array(4);
return;
}
const {data, getSourcePosition, getTargetPosition} = this.props;
con... |
JavaScript | function extractCameraVectors({viewMatrix, viewMatrixInverse}) {
// Read the translation from the inverse view matrix
return {
eye: [viewMatrixInverse[12], viewMatrixInverse[13], viewMatrixInverse[14]],
direction: [-viewMatrix[2], -viewMatrix[6], -viewMatrix[10]],
up: [viewMatrix[1], viewMatrix[5], view... | function extractCameraVectors({viewMatrix, viewMatrixInverse}) {
// Read the translation from the inverse view matrix
return {
eye: [viewMatrixInverse[12], viewMatrixInverse[13], viewMatrixInverse[14]],
direction: [-viewMatrix[2], -viewMatrix[6], -viewMatrix[10]],
up: [viewMatrix[1], viewMatrix[5], view... |
JavaScript | addIcon (aName, svgString) {
const node = SvgIconNode.clone().setTitle(aName).setSvgString(svgString)
this.addSubnode(node)
return this
} | addIcon (aName, svgString) {
const node = SvgIconNode.clone().setTitle(aName).setSvgString(svgString)
this.addSubnode(node)
return this
} |
JavaScript | function dateChange(date, interval, units) {
switch (interval) {
case 'year':
date.setFullYear(date.getFullYear() + units)
break
case 'quarter':
date.setMonth(date.getMonth() + 3 * units)
break
case 'month':
date.setMonth(date.getMonth() + units)
break
ca... | function dateChange(date, interval, units) {
switch (interval) {
case 'year':
date.setFullYear(date.getFullYear() + units)
break
case 'quarter':
date.setMonth(date.getMonth() + 3 * units)
break
case 'month':
date.setMonth(date.getMonth() + units)
break
ca... |
JavaScript | async function runSeed() {
console.log('seeding...')
try {
await preSeed()
await seed()
} catch (err) {
console.error(err)
process.exitCode = 1
} finally {
console.log('closing db connection')
await db.close()
console.log('db connection closed')
}
} | async function runSeed() {
console.log('seeding...')
try {
await preSeed()
await seed()
} catch (err) {
console.error(err)
process.exitCode = 1
} finally {
console.log('closing db connection')
await db.close()
console.log('db connection closed')
}
} |
JavaScript | async init () {
return new Promise(function(fulfill, reject) {
// Enter session into DB
var result = async function() {
// TODO: Write your own function to insert the session into your
// Database. The function should return an object which contains
// the id of the created Data... | async init () {
return new Promise(function(fulfill, reject) {
// Enter session into DB
var result = async function() {
// TODO: Write your own function to insert the session into your
// Database. The function should return an object which contains
// the id of the created Data... |
JavaScript | function cart_container(){
$.ajax({
url : "action.php",
method : "POST",
data : {get_cart_product:1},
success : function(data){
$("#cart_product").html(data);
}
})
cart_count();
} | function cart_container(){
$.ajax({
url : "action.php",
method : "POST",
data : {get_cart_product:1},
success : function(data){
$("#cart_product").html(data);
}
})
cart_count();
} |
JavaScript | function render() {
/* This array holds the relative URL to the image used
* for that particular row of the game level.
*/
var rowImages = [
'images/water-block.png', // Top row is water
'images/stone-block.png', // Row 1 of 3 of stone
... | function render() {
/* This array holds the relative URL to the image used
* for that particular row of the game level.
*/
var rowImages = [
'images/water-block.png', // Top row is water
'images/stone-block.png', // Row 1 of 3 of stone
... |
JavaScript | function renderEntities() {
/* Loop through all of the objects within the allEnemies array and call
* the render function you have defined.
* Then check if a collision with the player has occurred
*/
player.render();
allEnemies.forEach(function(enemy) {
en... | function renderEntities() {
/* Loop through all of the objects within the allEnemies array and call
* the render function you have defined.
* Then check if a collision with the player has occurred
*/
player.render();
allEnemies.forEach(function(enemy) {
en... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.