blob_id
large_stringlengths 40
40
| language
large_stringclasses 1
value | repo_name
large_stringlengths 5
119
| path
large_stringlengths 4
271
| score
float64 2.52
4.84
| int_score
int64 3
5
| text
stringlengths 26
4.09M
|
|---|---|---|---|---|---|---|
cf2433a3525846e7bc03dd4315bf630977376a20
|
TypeScript
|
aaronm-2112/JS_Data-Algs
|
/arrays/easy.ts
| 3.890625
| 4
|
// Question #1
// // Given an array of integers, return the indices of the two numbers that add up to a given target.
var twoSum = function (nums: Array<number>, target: number) {
if (nums.length < 2) {
return null;
}
let difference = 0;
let differencesIdx: { [difference: number]: number } = {};
for (let i = 0; i < nums.length; i++) {
difference = target - nums[i];
if (difference > 0) differencesIdx[difference] = i;
}
for (let i = 0; i < nums.length; i++) {
difference = target - nums[i];
let targetDifference = target - difference;
if (targetDifference > 0 && differencesIdx[targetDifference]) {
return [i, differencesIdx[targetDifference]];
}
}
return null;
};
// // Question #2
// // Given an array of numbers that represent the height of vertical lines on the x-axis return the greatest possible area
// // Assume all numbers are positive
// // Brute Force Solution:
// // O(n^2)
// // Space: O(1)
const areaOfShape = (nums: Array<number>): number => {
let area = 0;
for (let i = 0; i < nums.length; i++) {
let tempArea = 0;
for (let j = i + 1; j < nums.length; j++) {
let minSide = Math.min(nums[i], nums[j]);
let base = j - i;
base === minSide
? (tempArea = Math.pow(base, 2))
: (tempArea = base * minSide);
if (tempArea > area) area = tempArea;
}
}
return area;
};
// // test cases
// console.log(areaOfShape([3, 2, 4])) // E: 6, G: 6
// console.log(areaOfShape([6, 8, 9, 3, 9])) // E: 32, G: 32
// // Optimal solution using shifting pointers
// // O(n)
// // Space: O(1)
const areaOfShapeOptimal = (nums: Array<number>): number => {
let maxArea = 0;
let leftPointer = 0;
let rightPointer = nums.length - 1;
while (leftPointer < rightPointer) {
const minimumSide = Math.min(nums[leftPointer], nums[rightPointer]);
const base = rightPointer - leftPointer;
const area = minimumSide * base;
if (area > maxArea) maxArea = area;
// the pointer with the minimum side needs to close inward
if (minimumSide == nums[leftPointer]) {
leftPointer += 1;
} else {
rightPointer -= 1;
}
}
return maxArea;
};
// // test cases
// console.log(areaOfShapeOptimal([3, 2, 4])) // E: 6, G: 6
// console.log(areaOfShapeOptimal([6, 8, 9, 3, 9])) // E: 32, G: 32
function trapRainWater(nums: Array<number>): number {
let minContainerWall = 0;
let minContainerWallIdx = 0;
let trappedUnitsOfWater = 0;
let i = 0;
while (i < nums.length - 1) {
minContainerWall = 0;
minContainerWallIdx = 0;
for (let j = i + 1; j < nums.length; j++) {
// console.log(`Inner loop i value: ${i} and j value: ${j}`)
if (nums[j] < nums[i]) {
// a candidate for the greatest height that is less than the height at i
if (nums[j] >= minContainerWall) {
minContainerWall = nums[j];
minContainerWallIdx = j;
}
} else {
// nums[j] >= nums[i] so fill in all units of water for spaces i - j
let waterHeight = Math.min(nums[i], nums[j]);
for (let p = i; p < j; p++) {
trappedUnitsOfWater += waterHeight - nums[p];
}
// now set i to j as we have filled in a distinct container from i to j with water
i = j;
// stop the inner for loop
continue;
}
}
// assume we never found a height >= the height at i
// fill i to maxheightidx with water using maxHeight - nums[curr]
if (i < minContainerWallIdx) {
for (let curr = i + 1; curr < minContainerWallIdx; curr++) {
trappedUnitsOfWater += minContainerWall - nums[curr];
}
i = minContainerWallIdx;
}
}
return trappedUnitsOfWater;
}
// 1D Array question
// given an array of integers sorted in ascending order,
// return the starting and ending index of a given target value in an array
// solution needs to be O(log N)
// O(log n) in best case but all dupes would make this runtime O(n)
function getTargetIndices(array: number[], target: number): number[] {
let left = 0;
let right = array.length - 1;
const indices: number[] = [];
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (array[mid] === target) {
let startIndex = mid - 1;
while (startIndex >= left) {
if (array[startIndex] !== target) {
break;
}
startIndex -= 1;
}
// add the start index to the indices
indices.push(startIndex + 1);
let endIndex = mid + 1;
while (endIndex <= right) {
if (array[endIndex] !== target) {
break;
}
endIndex += 1;
}
// add the end index to the indices
indices.push(endIndex - 1);
// return the indices to the user
return indices;
} else if (array[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return [-1, -1];
}
// O(log n ) in all cases
// space: O(1)
function getTargetIndicesBS(array: number[], target: number): number[] {
if (array.length === 0) return [-1, -1];
// binary search for an index that holds our target value -- may return -1 if the target isn't in the array
const firstPos = binarySearch(array, 0, array.length - 1, target);
if (firstPos === -1) return [-1, -1];
let leftPointer = firstPos - 1;
let tempLeftPointer = leftPointer;
while (leftPointer >= 0 && array[leftPointer] === target) {
tempLeftPointer = leftPointer;
leftPointer = binarySearch(array, 0, leftPointer - 1, target);
}
if (leftPointer === -1) {
leftPointer = tempLeftPointer;
} else {
leftPointer += 1;
}
let rightPointer = firstPos + 1;
let tempRightPointer = rightPointer;
while (
rightPointer < array.length - 1 &&
array[rightPointer] === target &&
rightPointer >= 0
) {
tempRightPointer = rightPointer;
rightPointer = binarySearch(
array,
rightPointer + 1,
array.length - 1,
target
);
}
if (rightPointer === -1) {
rightPointer = tempRightPointer;
} else {
rightPointer -= 1;
}
return [leftPointer, rightPointer];
}
function binarySearch(
array: number[],
left: number,
right: number,
target: number
): number {
if (left > right) {
return -1;
}
let mid: number = Math.floor((left + right) / 2);
if (array[mid] === target) {
return mid;
} else if (array[mid] < target) {
return binarySearch(array, mid + 1, right, target);
} else {
return binarySearch(array, left, mid - 1, target);
}
}
console.log(getTargetIndices([1, 1, 1, 2, 2, 3, 3, 4, 5, 6, 6], 4)); // E: [7,7] G: [7,7]
console.log(getTargetIndices([1, 1, 1, 2, 2, 3, 3, 4, 5, 6, 6], 3)); // E: [5,6] G: [5,6]
console.log(getTargetIndices([1, 1, 1, 2, 2, 3, 3, 4, 5, 6, 6], 1)); // E: [0,2] G: [0,2]
console.log(getTargetIndices([1, 1, 1, 2, 2, 3, 3, 4, 5, 6, 6], 6)); // E: [9,10] G: [9,10]
// the solution for left is off by one
console.log(getTargetIndicesBS([1, 1, 1, 2, 2, 3, 3, 4, 5, 6, 6], 1)); // E: [0,2] G: [0,2]
console.log(getTargetIndicesBS([1, 1, 1, 2, 2, 3, 3, 4, 5, 6, 6], 3)); // E: [5,6] G: [5,6]
console.log(getTargetIndicesBS([1, 1, 1, 2, 2, 3, 3, 4, 5, 6, 6], 4)); // E: [7,7] G: [7,7]
// console.log(trapRainWater([1, 0, 2, 0, 1, 0, 2])) // E: 6 G: 6
// console.log(trapRainWater([4, 2, 0, 3, 2, 5])) // E: 9 G: 6
// console.log(trapRainWater([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1])) // E: 6 G: 6
// console.log(trapRainWater([0, 2, 0]))
// // 2D Array Traversals and Questions-----------------------------------------------------------
const directions = [
[-1, 0],
[0, 1],
[1, 0],
[0, -1],
];
const createCopy = (array: number[][]): boolean[][] => {
return new Array<Array<boolean>>(array.length).fill([]).map(() => {
return new Array(array[0].length).fill(false);
});
};
// basic traversals-------------
// DFS
const dfs = (
array: number[][],
currentPosition: number[],
visited: boolean[][]
): void => {
let row = currentPosition[0];
let col = currentPosition[1];
visited[row][col] = true;
console.log(array[row][col]);
for (let dir of directions) {
let nextRow = row + dir[0];
let nextCol = col + dir[1];
if (
nextRow >= 0 &&
nextRow < array.length &&
nextCol >= 0 &&
nextCol < array[nextRow].length
) {
if (visited[nextRow][nextCol] !== true) {
dfs(array, [nextRow, nextCol], visited);
}
}
}
};
let test2darray = [
[0, 1, 2, 3],
[4, 5, 6, 7],
];
dfs(test2darray, [0, 0], createCopy(test2darray)); // E: 0,1,2,3,7,6,5,4 G: 0,1,2,3,7,6,5,4
// BFS
// // calculate time for a set of oranges to rot a set of fresh oranges if a rotten orange will rot any adjacent
// // fresho oranges every minute. If all of the fresh oranges cannot be rotted return -1.
// 2D Array Questions -----------
// // Time: O(MxN)
// // Space: O(MxN) --b/c worst case we can have all rotten oranges
function calculateTimeToRotOranges(matrix: number[][]): number {
// track all oranges
let freshOrangesTotal: number = 0;
let rottenOranges: number[][] = [];
// check if there are elements in the array
for (let row = 0; row < matrix.length; row++) {
for (let col = 0; col < matrix[0].length; col++) {
// check if position is where a fresh orange is located
if (matrix[row][col] === 1) {
freshOrangesTotal += 1;
} else if (matrix[row][col] === 2) {
rottenOranges.push([row, col]);
}
}
}
// declare total time
let totalTime = 0;
// traverse the current collection of rotten orange locations
while (rottenOranges.length) {
console.log(rottenOranges);
let rotted = false;
const newRottenOranges: number[][] = [];
for (let i = 0; i < rottenOranges.length; i++) {
// for each rotten orange check its 4 adjacent positions
for (let j = 0; j < directions.length; j++) {
const nextRow = rottenOranges[i][0] + directions[j][0];
const nextCol = rottenOranges[i][1] + directions[j][1];
// check if the the adjacent position is in bounds
if (
nextRow < matrix.length &&
nextRow >= 0 &&
nextCol < matrix[0].length &&
nextCol >= 0
) {
// check if there is a fresh orange located at this position
if (matrix[nextRow][nextCol] === 1) {
// mark the orange as rotted
matrix[nextRow][nextCol] = 2;
// set rotted to true
rotted = true;
// decrease the amount of fresh oranges
freshOrangesTotal -= 1;
// add the new rotted orange's position to the collection of new rotten orange positions
newRottenOranges.push([nextRow, nextCol]);
}
}
}
}
// get rid of all the old rotten oranges because we no longer need to consider them
rottenOranges = [];
// check if any oranges were rotted
if (rotted) {
// increment the total time
totalTime += 1;
// add the new rotten orange locations to the collection of rotten orange locations
rottenOranges = newRottenOranges;
}
}
// check if there are fresh oranges that didn't rot
if (freshOrangesTotal > 0) {
// return -1 to mark not all oranges were rotted
return -1;
}
// all oranges rotted. return the total amount of time this took
return totalTime;
}
// // test case
// let testOrangesOne = [
// [2,1,1,0,0],
// [1,1,1,0,0],
// [0,1,1,1,1],
// [0,1,0,0,1]
// ]
// let testOrangesTwo = [
// [1,1,0,0,0],
// [2,1,0,0,0],
// [0,0,0,1,2],
// [0,1,0,0,1]
// ]
// console.log(calculateTimeToRotOranges(testOrangesOne))
// console.log(calculateTimeToRotOranges(testOrangesTwo))
// // alternative solution -- aka, not my own
const ROTTEN = 2;
const FRESH = 1;
const EMPTY = 0;
const orangesRotting = function (grid: number[][]) {
if (grid.length === 0) return 0;
const queue: number[][] = [];
let freshOranges = 0;
for (let row = 0; row < grid.length; row++) {
for (let col = 0; col < grid[0].length; col++) {
if (grid[row][col] === ROTTEN) {
queue.push([row, col]);
}
if (grid[row][col] === FRESH) {
freshOranges += 1;
}
}
}
let currentQueueSize = queue.length;
let minutes = 0;
while (queue.length > 0) {
if (currentQueueSize === 0) {
minutes += 1;
currentQueueSize = queue.length;
}
const currentOrange = queue.shift();
currentQueueSize--;
const row = currentOrange![0];
const col = currentOrange![1];
for (let i = 0; i < directions.length; i++) {
const currentDir = directions[i];
const nextRow = currentDir[0] + row;
const nextCol = currentDir[1] + col;
if (
nextRow < 0 ||
nextRow >= grid.length ||
nextCol < 0 ||
nextCol >= grid[0].length
) {
continue;
}
if (grid[nextRow][nextCol] === FRESH) {
grid[nextRow][nextCol] = 2;
freshOranges--;
queue.push([nextRow, nextCol]);
}
}
}
if (freshOranges <= 0) {
return -1;
}
return minutes;
};
// walls and gates question
// given a 2D array containing -1s(walls), 0s(gates), and INFs(emoty room), fill each empty room with the number of steps to the nearest gate.
// if it is impossible to reach a gate, leave INF as the value. INF is equal to 2147483647.
// Output: A gate with updated distance values (when applicable)
// Time: O(MxN)
// Space: O(MxN + q) where q is the size of the queue and can be as large as the diagonal of the grid
const shortestPathToExit = (grid: number[][]): number[][] => {
// declare the collection of all gates
const gates: number[][] = [];
// declare the constants that represent walls, gates, and empty rooms
const WALL = -1;
const GATE = 0;
const EMPTY_ROOM = 2147483647;
// scan the grid and add all of the gates to the gates collection
for (let row = 0; row < grid.length; row++) {
for (let col = 0; col < grid[0].length; col++) {
if (grid[row][col] === GATE) {
gates.push([row, col]);
}
}
}
// traverse all of the gates
for (let gateIndx = 0; gateIndx < gates.length; gateIndx++) {
// declare a queue to hold empty rooms
const queue: number[][] = [];
// add the current gate location to the queue
queue.push(gates[gateIndx]);
// declare a queue length
let queueLength = queue.length;
// declare a distance
let distance = 0;
// declare a set of positions that keep track of what's been visited in the grid
let visited: { [key: string]: boolean } = {};
// add current gate to visited
visited[`[${gates[gateIndx][0]},${gates[gateIndx][1]}]`] = true;
// loop while there are elements in the queue
while (queue.length) {
// get the current position
let currentPosition = queue.shift();
let row = currentPosition![0];
let col = currentPosition![1];
// decrease the queue length
queueLength--;
if (grid[row][col] > GATE) {
// check if the position's current distance from a gate is greater than the current distance from our starting gate
if (distance < grid[row][col]) {
// update the value with the new minimum distance to a gate
grid[row][col] = distance;
}
}
// add the adjacent empty spaces to the queue
for (
let directionsIdx = 0;
directionsIdx < directions.length;
directionsIdx++
) {
let nextRow = directions[directionsIdx][0] + row;
let nextCol = directions[directionsIdx][1] + col;
// check if next row and next col represent a position that is within the bounds of the grid
if (
nextRow < grid.length &&
nextRow >= 0 &&
nextCol >= 0 &&
nextCol < grid[0].length
) {
// check if value at the next row and col is greater than 0 -- meaning it is not a gate or a wall
if (grid[nextRow][nextCol] > 0) {
// check if the value has not already been visited
if (!visited[`[${nextRow},${nextCol}]`]) {
queue.push([nextRow, nextCol]);
visited[`[${nextRow},${nextCol}]`] = true;
}
}
}
}
// check if queueLength is 0
if (queueLength === 0) {
// increase the distance
distance++;
// reset the queue length
queueLength = queue.length;
}
}
}
// print out the grid
return grid;
};
console.log(
shortestPathToExit([
[0, 2147483647, -1, 2147483647],
[-1, 2147483647, -1, 2147483647],
[0, 2147483647, 2147483647, 0],
[-1, -1, -1, 2147483647],
])
);
// alternative solution using DFS
// O(n)
// space: O(n)
const wallsAndGates = function (grid: number[][]) {
const WALL = -1;
const GATE = 0;
const EMPTY_ROOM = 2147483647;
for (let row = 0; row < grid.length; row++) {
for (let col = 0; col < grid[0].length; col++) {
if (grid[row][col] === GATE) {
// perform our depth first search
wallsAndGatesDFS(grid, row, col, 0);
}
}
}
return grid;
};
function wallsAndGatesDFS(
grid: number[][],
row: number,
col: number,
step: number
) {
if (
row < 0 ||
row >= grid.length ||
col < 0 ||
col >= grid[0].length ||
step > grid[row][col]
) {
return;
}
grid[row][col] = step;
for (let i = 0; i < directions.length; i++) {
const currentDir = directions[i];
wallsAndGatesDFS(grid, row + currentDir[0], col + currentDir[1], step++);
}
}
// count the length of all rivers
// array can be of different lengths
function riverSizes(matrix: number[][]) {
// Write your code here.
const visitedLand = new Array();
for (let i = 0; i < matrix.length; i++) {
visitedLand.push(matrix[i].slice().fill(0));
}
const riverLengths = [];
for (let row = 0; row < matrix.length; row++) {
for (let col = 0; col < matrix[row].length; col++) {
if (matrix[row][col] === 1 && visitedLand[row][col] !== 1) {
let riverLength = getRiverLength(matrix, row, col, visitedLand);
riverLengths.push(riverLength);
}
}
}
return riverLengths;
}
function getRiverLength(
land: number[][],
row: number,
col: number,
visitedLand: number[][]
) {
let length = 0;
let directions = [
[-1, 0],
[0, 1],
[1, 0],
[0, -1],
];
let queue = [];
queue.push([row, col]);
length++;
visitedLand[row][col] = 1;
while (queue.length) {
let position = queue.pop();
let currentRow = position![0];
let currentCol = position![1];
directions.forEach((direction) => {
let nextRow = currentRow + direction[0];
let nextCol = currentCol + direction[1];
if (nextRow >= 0 && nextRow < land.length) {
if (nextCol >= 0 && nextCol < land[nextRow].length) {
if (
land[nextRow][nextCol] === 1 &&
visitedLand[nextRow][nextCol] == 0
) {
queue.push([nextRow, nextCol]);
length++;
visitedLand[nextRow][nextCol] = 1;
}
}
}
});
}
return length;
}
// expect a length of 4
console.log(
riverSizes([
[0, 1, 1, 1, 0],
[0, 1, 0, 0],
])
);
|
79f8ed179f57b53c40f06ce2ec80633b09a97d95
|
TypeScript
|
nazar-maslianka/HealthCheck
|
/HealthCheck/ClientApp/src/app/models/healthCheckResult.ts
| 2.625
| 3
|
interface Result {
checks: Check[];
totalStatus: string;
totalResponseTime: number;
}
interface Check {
name: string;
status: string;
responseTime: number;
}
|
b8bb5fa8c04f38cede6907cf27dc4d31298bfb6a
|
TypeScript
|
dainnovation722/test
|
/main.ts
| 3.3125
| 3
|
let b: number[];
function collision_judgement(X: number, Y: number): boolean {
if (Y < 0) {
// collision in upper side
return false
} else if (Y > 4) {
// collision in lower side
return false
} else if (X - 1 < 0) {
// collision in left side
return false
} else if (X + 1 > 4) {
// collision in right side
return false
} else {
return true
}
}
function return_coordinate(X: number, Y: number): number[] {
let direction: number;
while (true) {
direction = randint(1, 4)
if (direction == 1) {
// right
X += 1
if (collision_judgement(X, Y)) {
break
}
} else if (direction == 2) {
// left
X += -1
if (collision_judgement(X, Y)) {
break
}
} else if (direction == 3) {
// upper
Y += -1
if (collision_judgement(X, Y)) {
break
}
} else if (direction == 4) {
// lower
Y += 1
if (collision_judgement(X, Y)) {
break
}
}
}
return [X, Y]
}
let X = 0
let Y = 0
while (true) {
b = return_coordinate(X, Y)
X = b[0]
Y = b[1]
console.log(b)
led.plot(X, Y)
led.plot(X + 1, Y)
led.plot(X - 1, Y)
basic.pause(1000)
basic.clearScreen()
}
|
3c65bd9791d00ac49add12f7bb707ff17d6d8091
|
TypeScript
|
PiNengShaoNian/learn-algo-systematically
|
/src/stage2/unique-morse-code-words.ts
| 3.484375
| 3
|
/*
国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串, 比如: "a" 对应 ".-", "b" 对应 "-...", "c" 对应 "-.-.", 等等。
为了方便,所有26个英文字母对应摩尔斯密码表如下:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
给定一个单词列表,每个单词可以写成每个字母对应摩尔斯密码的组合。例如,"cab" 可以写成 "-.-..--...",(即 "-.-." + ".-" + "-..." 字符串的结合)。我们将这样一个连接过程称作单词翻译。
返回我们可以获得所有词不同单词翻译的数量。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/unique-morse-code-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
function uniqueMorseRepresentations(words: string[]): number {
const codes: string[] = [
'.-',
'-...',
'-.-.',
'-..',
'.',
'..-.',
'--.',
'....',
'..',
'.---',
'-.-',
'.-..',
'--',
'-.',
'---',
'.--.',
'--.-',
'.-.',
'...',
'-',
'..-',
'...-',
'.--',
'-..-',
'-.--',
'--..',
]
const word2MorseCode = (word: string): string => {
let res = ''
for (let i = 0; i < word.length; i++) {
res += codes[word[i].charCodeAt(0) - 97]
}
return res
}
const set = new Set<string>()
for (let i = 0; i < words.length; i++) {
set.add(word2MorseCode(words[i]))
}
return set.size
}
|
07b8df36c8ce4cb8e169d96edb68fe98ac923dc1
|
TypeScript
|
esgf-compute/webapp
|
/webapp/src/app/core/notification.service.ts
| 2.796875
| 3
|
import { Injectable } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Subject } from 'rxjs/Subject';
import { switchMap } from 'rxjs/operators';
import { NEVER } from 'rxjs';
export enum NotificationType {
Message,
Warn,
Error
}
@Injectable()
export class NotificationService {
notification$ = new Subject<any>();
toggles: {stream: any, toggle: Subject<boolean>}[] = [];
subscribe(fn: any): any {
/**
* The goal is to have the latest subscriber recieving notifications.
* For the moment it's assumed that the latest subscriber will call
* unsubscribe. It's possible for another component to unsunscribe
* for another component.
*/
let toggle = new Subject<boolean>();
let stream = toggle
.pipe(switchMap((value: boolean) => value ? this.notification$ : NEVER));
let streamSub = stream.subscribe(fn);
if (this.toggles.length > 0) {
this.toggles[this.toggles.length-1].toggle.next(false);
}
this.toggles.push({stream: stream, toggle: toggle});
toggle.next(true);
return streamSub;
}
unsubscribe() {
let last = this.toggles.pop();
last.toggle.next(false);
if (this.toggles.length > 0) {
this.toggles[this.toggles.length-1].toggle.next(true);
}
}
message(text: string, link: string = null) {
this.notification$.next({type: NotificationType.Message, text: text, link: link});
}
warn(text: string) {
this.notification$.next({type: NotificationType.Warn, text: text});
}
error(text: string) {
this.notification$.next({type: NotificationType.Error, text: text});
}
}
|
a36b46cc1adf0e1591d009f6489f150059b770f0
|
TypeScript
|
messageformat/messageformat
|
/packages/number-skeleton/src/pattern-parser/number-tokens.ts
| 3.71875
| 4
|
export type NumberToken =
| { char: '.'; width: number }
| { char: '#'; width: number }
| { char: ','; width: number }
| { char: '0'; width: number; digits: string }
| { char: '@'; width: number; min: number }
| { char: 'E'; width: number; expDigits: number; plus: boolean };
const isDigit = (char: string) => char >= '0' && char <= '9';
export function parseNumberToken(src: string, pos: number): NumberToken | null {
const char = src[pos];
if (isDigit(char)) {
let digits = char;
while (true) {
const next = src[++pos];
if (isDigit(next)) digits += next;
else return { char: '0', digits, width: digits.length };
}
}
switch (char) {
case '#': {
let width = 1;
while (src[++pos] === '#') ++width;
return { char, width };
}
case '@': {
let min = 1;
while (src[++pos] === '@') ++min;
let width = min;
pos -= 1;
while (src[++pos] === '#') ++width;
return { char, min, width };
}
case 'E': {
const plus = src[pos + 1] === '+';
if (plus) ++pos;
let expDigits = 0;
while (src[++pos] === '0') ++expDigits;
const width = (plus ? 2 : 1) + expDigits;
if (expDigits) return { char, expDigits, plus, width };
else break;
}
case '.':
case ',':
return { char, width: 1 };
}
return null;
}
|
fc3812f581b9872de065318d8c77d928a22ae8ee
|
TypeScript
|
MuraliNunna/count-loc
|
/lib/index.ts
| 2.578125
| 3
|
import { FileTotals } from "./interfaces";
import JSLanguageUtils from "./languages/js";
const processCountsForFile = (
extension: string,
data: string,
fileName: string
): FileTotals | undefined => {
switch (extension) {
case ".js":
return JSLanguageUtils.processJSFile(data, fileName);
default:
console.log(`Stats for ${fileName}: This language is not yet supported.`);
break;
}
};
const CheckCounts = {
processCountsForFile,
};
export default CheckCounts;
|
273811f616550f30564b05ed905ae49efcce09f9
|
TypeScript
|
zunderscore/azure-boards-estimate
|
/src/services/cardSets.ts
| 2.546875
| 3
|
import { defaultCardSets, ICardSet } from "../model/cards";
import { IService } from "./services";
export interface ICardSetService extends IService {
getSets(): Promise<ICardSet[]>;
getSet(cardSetId: string): Promise<ICardSet>;
}
export const CardSetServiceId = "CardSetService";
export class MockCardSetService implements ICardSetService {
async getSet(cardSetId: string): Promise<ICardSet> {
return defaultCardSets.filter(cs => cs.id === cardSetId)[0];
}
async getSets(): Promise<ICardSet[]> {
return defaultCardSets;
}
}
export class CardSetService implements ICardSetService {
getSet(cardSetId: string): Promise<ICardSet> {
throw new Error("Method not implemented.");
}
getSets(): Promise<ICardSet[]> {
throw new Error("Method not implemented.");
}
}
|
daed3bebdd1671ac1ce2c59c353570ba6920cc08
|
TypeScript
|
tarcCar/teste-viasoft
|
/client/src/store/actions/feedback/feedbackActions.ts
| 2.765625
| 3
|
import { FeedbackActionsTypes } from "./feedbackActionsTypes";
import {
getAllFeedback,
getFeedbackById,
saveFeedback,
updateFeedback,
} from "../../../services/feedbackService";
import { Feedback } from "../../../types/feedback";
const setGetFeedbacks = (
feedbacksDoUsuario: Feedback[],
feedbacksParaUsuario: Feedback[]
): FeedbackActionsTypes => ({
type: "GET_FEEDBACKS",
feedbacksDoUsuario,
feedbacksParaUsuario,
});
const setGetFeedbacksErro = (error: string): FeedbackActionsTypes => ({
type: "GET_FEEDBACKS_ERRO",
error,
});
const setGetFeedbacksLoading = (loading: boolean): FeedbackActionsTypes => ({
type: "LOADING_GET_FEEDBACKS",
loading,
});
const setSaveFeedback = (feedback?: Feedback): FeedbackActionsTypes => ({
type: "SAVE_FEEDBACK",
feedback,
});
const setSaveFeedbackErro = (error: string): FeedbackActionsTypes => ({
type: "SAVE_FEEDBACK_ERRO",
error,
});
const setSaveFeedbackLoading = (loading: boolean): FeedbackActionsTypes => ({
type: "LOADING_SAVE_FEEDBACK",
loading,
});
const setUpdateFeedback = (feedback: Feedback): FeedbackActionsTypes => ({
type: "UPDATE_FEEDBACK",
feedback,
});
const setGetFeedbackById = (feedback: Feedback): FeedbackActionsTypes => ({
type: "GET_FEEDBACK_BY_ID",
feedback,
});
const setGetFeedbackByIdErro = (error: string): FeedbackActionsTypes => ({
type: "GET_FEEDBACK_BY_ID_ERRO",
error,
});
const setGetFeedbackByIdLoading = (loading: boolean): FeedbackActionsTypes => ({
type: "LOADING_GET_FEEDBACK_BY_ID",
loading,
});
const setClearFeedback = (): FeedbackActionsTypes => ({
type: "CLEAR_FEEDBACK",
});
export const getFeedbacksAction = (): any => async (dispatch: any) => {
try {
dispatch(setGetFeedbacksLoading(true));
const feedbacks = await getAllFeedback();
dispatch(
setGetFeedbacks(
feedbacks.feedbacksDoUsuario,
feedbacks.feedbacksParaUsuario
)
);
} catch (error) {
console.log(error);
dispatch(setGetFeedbacksErro(error.message));
}
};
export const saveFeedbacksAction = (feedback: Feedback): any => async (
dispatch: any
) => {
try {
dispatch(setSaveFeedbackLoading(true));
if (!feedback.id) {
const novoFeedback = await saveFeedback(feedback);
dispatch(setSaveFeedback(novoFeedback));
} else {
await updateFeedback(feedback);
dispatch(setUpdateFeedback(feedback));
}
} catch (error) {
console.log(error);
dispatch(setSaveFeedbackErro(error.message));
}
};
export const getFeedbacByIdkAction = (id: string): any => async (
dispatch: any
) => {
try {
dispatch(setGetFeedbackByIdLoading(true));
const novoFeedback = await getFeedbackById(id);
dispatch(setGetFeedbackById(novoFeedback));
} catch (error) {
console.log(error);
dispatch(setGetFeedbackByIdErro(error.message));
}
};
export const clearFeedbackAction = (): any => async (dispatch: any) => {
dispatch(setClearFeedback());
};
|
6adb56b9d9f016397fd1319894f8969f6f016b11
|
TypeScript
|
nirbhay41/Amazon-Clone
|
/src/pages/api/db/addToCart.ts
| 2.625
| 3
|
import { NextApiRequest, NextApiResponse } from "next";
import { connectToDatabase } from "../../../utils/db";
export default async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'POST') {
const { db } = await connectToDatabase();
const { product: productDetails, userEmail }: { product: Product, userEmail: string } = req.body;
// get the collection
const coll = db.collection(userEmail);
// get cart list from the document
const cartList: Product[] = (await coll.findOne({})).cart;
let isPresent = false;
cartList.forEach(item => {
if (item.id === productDetails.id)
isPresent = true;
});
if (isPresent) {
// update the quantity
await coll.updateOne({
"cart.id": productDetails.id
},{
$inc: {
"cart.$.quantity": productDetails.quantity
}
});
res.status(200).send({
data: "Updated Successfully into db",
});
} else {
// add to cart
await coll.findOneAndUpdate({}, {
$push: {
"cart": productDetails
}
});
res.status(200).send({
data: "Inserted Successfully into db",
});
}
res.end();
}else{
res.setHeader('Allow', 'POST');
res.status(405).end('Method Not Allowed');
}
}
|
104eb2771a76ce364830d45cf7e719030ac4a92c
|
TypeScript
|
starspot/starspot
|
/packages/starspot-json-api/test/update-resource-test.ts
| 2.828125
| 3
|
import { expect } from "chai";
import ResourceController, { after } from "../src/resource-controller";
import Resource, { attribute, updatable, readOnly, writableAttributes, updatableAttributes, creatableAttributes } from "../src/resource";
import JSONAPI from "../src/json-api";
import { createApplication, createResponse, createJSONRequest } from "starspot-test-core";
import Model from "./helpers/model";
// http://jsonapi.org/format/1.1/#fetching
describe("Fetching Data", function () {
@writableAttributes("isWritable")
@creatableAttributes("isCreatable")
@updatableAttributes("isUpdatable")
class PhotoResource extends Resource<Photo> {
@attribute
@updatable
title: string;
@attribute
@updatable
src: string;
@attribute
@readOnly({ ignoreWrites: true })
fingerprint: string;
@attribute
@readOnly
superEmoInfo: string;
async updateAttributes(attributes: Resource.Attributes) {
Object.assign(this.model, attributes);
}
static async findByID(id: JSONAPI.ID) {
return new Photo({ id });
}
}
class Photo extends Model { };
// http://jsonapi.org/format/upcoming/#crud-updating
describe("Updating Resources", function () {
it("allows a resource to be updated", async function () {
class PhotoController extends ResourceController {
@after("update")
didUpdate(model: Photo) {
didUpdateWasCalled = true;
expect(model).to.be.an.instanceof(Photo);
}
}
let didUpdateWasCalled = false;
let app = await createApplication()
.routes(({ resources }) => {
resources("photos");
})
.controller("photo", PhotoController)
.register("resource", "photo", PhotoResource)
.boot();
let response = createResponse();
let request = createJSONAPIRequest("PATCH", "/photos/123", {
"data": {
"id": "1234",
"type": "photos",
"attributes": {
"title": "Ember Hamster",
"src": "http://example.com/images/productivity.png",
"is-writable": true,
"is-updatable": true
}
}
});
await app.dispatch(request, response);
expect(didUpdateWasCalled).to.be.true;
expect(response.statusCode).to.equal(200);
expect(response.getHeader("content-type")).to.equal("application/vnd.api+json");
expect(response.toJSON()).to.deep.equal({
data: {
"type": "photos",
"id": "1234",
"attributes": {
"title": "Ember Hamster",
"src": "http://example.com/images/productivity.png",
"is-writable": true,
"is-updatable": true,
"is-creatable": null,
"fingerprint": null,
"super-emo-info": null
}
}
});
});
it("ignores a field that is presented for update but that has `@readOnly({ignoreWrites: true})`", async function() {
class PhotoController extends ResourceController {
@after("update")
didUpdate(model: Photo) {
didUpdateWasCalled = true;
expect(model).to.be.an.instanceof(Photo);
}
}
let didUpdateWasCalled = false;
let app = await createApplication()
.routes(({ resources }) => {
resources("photos");
})
.controller("photo", PhotoController)
.register("resource", "photo", PhotoResource)
.boot();
let response = createResponse();
let request = createJSONAPIRequest("PATCH", "/photos/123", {
"data": {
"id": "1234",
"type": "photos",
"attributes": {
"title": "Ember Hamster",
"src": "http://example.com/images/productivity.png",
"is-writable": true,
"is-updatable": true,
"fingerprint": "jsfkjh342kjl234kl"
}
}
});
await app.dispatch(request, response);
expect(didUpdateWasCalled).to.be.true;
expect(response.statusCode).to.equal(200);
expect(response.getHeader("content-type")).to.equal("application/vnd.api+json");
expect(response.toJSON()).to.deep.equal({
data: {
"type": "photos",
"id": "1234",
"attributes": {
"title": "Ember Hamster",
"src": "http://example.com/images/productivity.png",
"is-writable": true,
"is-updatable": true,
"is-creatable": null,
"fingerprint": null,
"super-emo-info": null
}
}
});
});
it("returns an exception when a field that is presented for update that is set to `@readOnly()`", async function() {
class PhotoController extends ResourceController {
@after("update")
didUpdate(model: Photo) {
didUpdateWasCalled = true;
expect(model).to.be.an.instanceof(Photo);
}
}
let didUpdateWasCalled = false;
let app = await createApplication()
.routes(({ resources }) => {
resources("photos");
})
.controller("photo", PhotoController)
.register("resource", "photo", PhotoResource)
.boot();
let response = createResponse();
let request = createJSONAPIRequest("PATCH", "/photos/123", {
"data": {
"id": "1234",
"type": "photos",
"attributes": {
"title": "Ember Hamster",
"src": "http://example.com/images/productivity.png",
"is-writable": true,
"is-updatable": true,
"super-emo-info": "OMG don't touch me!!!!"
}
}
});
await app.dispatch(request, response);
expect(didUpdateWasCalled).to.be.false;
expect(response.statusCode).to.equal(422);
expect(response.getHeader("content-type")).to.equal("application/vnd.api+json");
expect(response.toJSON()).to.deep.equal({
errors: ["The super-emo-info attribute of type photos cannot be set during updates."]
});
});
});
});
function createJSONAPIRequest(method: string, url: string, json?: any) {
let request = createJSONRequest(url, method, json);
request.headers["Content-Type"] = "application/vnd.api+json";
return request;
}
|
9db1a5a537df55c4f78bdd85bcb90de7feb818ee
|
TypeScript
|
ovac/graphql-code-generator
|
/dev-test/star-wars/types.ts
| 3.25
| 3
|
/* tslint:disable */
// ====================================================
// START: Typescript template
// ====================================================
// ====================================================
// Interfaces
// ====================================================
/** A character from the Star Wars universe */
export interface Character {
/** The ID of the character */
id: string;
/** The name of the character */
name: string;
/** The friends of the character, or an empty list if they have none */
friends?: (Character | null)[] | null;
/** The friends of the character exposed as a connection with edges */
friendsConnection: FriendsConnection;
/** The movies this character appears in */
appearsIn: (Episode | null)[];
}
// ====================================================
// Types
// ====================================================
/** The query type, represents all of the entry points into our object graph */
export interface Query {
hero?: Character | null;
reviews?: (Review | null)[] | null;
search?: (SearchResult | null)[] | null;
character?: Character | null;
droid?: Droid | null;
human?: Human | null;
starship?: Starship | null;
}
/** A connection object for a character's friends */
export interface FriendsConnection {
/** The total number of friends */
totalCount?: number | null;
/** The edges for each of the character's friends. */
edges?: (FriendsEdge | null)[] | null;
/** A list of the friends, as a convenience when edges are not needed. */
friends?: (Character | null)[] | null;
/** Information for paginating this connection */
pageInfo: PageInfo;
}
/** An edge object for a character's friends */
export interface FriendsEdge {
/** A cursor used for pagination */
cursor: string;
/** The character represented by this friendship edge */
node?: Character | null;
}
/** Information for paginating this connection */
export interface PageInfo {
startCursor?: string | null;
endCursor?: string | null;
hasNextPage: boolean;
}
/** Represents a review for a movie */
export interface Review {
/** The number of stars this review gave, 1-5 */
stars: number;
/** Comment about the movie */
commentary?: string | null;
}
/** A humanoid creature from the Star Wars universe */
export interface Human extends Character {
/** The ID of the human */
id: string;
/** What this human calls themselves */
name: string;
/** The home planet of the human, or null if unknown */
homePlanet?: string | null;
/** Height in the preferred unit, default is meters */
height?: number | null;
/** Mass in kilograms, or null if unknown */
mass?: number | null;
/** This human's friends, or an empty list if they have none */
friends?: (Character | null)[] | null;
/** The friends of the human exposed as a connection with edges */
friendsConnection: FriendsConnection;
/** The movies this human appears in */
appearsIn: (Episode | null)[];
/** A list of starships this person has piloted, or an empty list if none */
starships?: (Starship | null)[] | null;
}
export interface Starship {
/** The ID of the starship */
id: string;
/** The name of the starship */
name: string;
/** Length of the starship, along the longest axis */
length?: number | null;
}
/** An autonomous mechanical character in the Star Wars universe */
export interface Droid extends Character {
/** The ID of the droid */
id: string;
/** What others call this droid */
name: string;
/** This droid's friends, or an empty list if they have none */
friends?: (Character | null)[] | null;
/** The friends of the droid exposed as a connection with edges */
friendsConnection: FriendsConnection;
/** The movies this droid appears in */
appearsIn: (Episode | null)[];
/** This droid's primary function */
primaryFunction?: string | null;
}
/** The mutation type, represents all updates we can make to our data */
export interface Mutation {
createReview?: Review | null;
}
// ====================================================
// InputTypes
// ====================================================
/** The input object sent when someone is creating a new review */
export interface ReviewInput {
/** 0-5 stars */
stars: number;
/** Comment about the movie, optional */
commentary?: string | null;
/** Favorite color, optional */
favoriteColor?: ColorInput | null;
}
/** The input object sent when passing a color */
export interface ColorInput {
red: number;
green: number;
blue: number;
}
// ====================================================
// Arguments
// ====================================================
export interface HeroQueryArgs {
episode?: Episode | null;
}
export interface ReviewsQueryArgs {
episode: Episode;
}
export interface SearchQueryArgs {
text?: string | null;
}
export interface CharacterQueryArgs {
id: string;
}
export interface DroidQueryArgs {
id: string;
}
export interface HumanQueryArgs {
id: string;
}
export interface StarshipQueryArgs {
id: string;
}
export interface HeightHumanArgs {
unit?: LengthUnit | null;
}
export interface FriendsConnectionHumanArgs {
first?: number | null;
after?: string | null;
}
export interface LengthStarshipArgs {
unit?: LengthUnit | null;
}
export interface FriendsConnectionDroidArgs {
first?: number | null;
after?: string | null;
}
export interface CreateReviewMutationArgs {
episode?: Episode | null;
review: ReviewInput;
}
// ====================================================
// Enums
// ====================================================
/** The episodes in the Star Wars trilogy */
export enum Episode {
NEWHOPE = 'NEWHOPE',
EMPIRE = 'EMPIRE',
JEDI = 'JEDI'
}
/** Units of height */
export enum LengthUnit {
METER = 'METER',
FOOT = 'FOOT'
}
// ====================================================
// Unions
// ====================================================
export type SearchResult = Human | Droid | Starship;
// ====================================================
// END: Typescript template
// ====================================================
// ====================================================
// Documents
// ====================================================
export namespace CreateReviewForEpisode {
export type Variables = {
episode: Episode;
review: ReviewInput;
};
export type Mutation = {
__typename?: 'Mutation';
createReview?: CreateReview | null;
};
export type CreateReview = {
__typename?: 'Review';
stars: number;
commentary?: string | null;
};
}
export namespace HeroAndFriendsNames {
export type Variables = {
episode?: Episode | null;
};
export type Query = {
__typename?: 'Query';
hero?: Hero | null;
};
export type Hero = {
__typename?: 'Character';
name: string;
friends?: (Friends | null)[] | null;
};
export type Friends = {
__typename?: 'Character';
name: string;
};
}
export namespace HeroAppearsIn {
export type Variables = {};
export type Query = {
__typename?: 'Query';
hero?: Hero | null;
};
export type Hero = {
__typename?: 'Character';
name: string;
appearsIn: (Episode | null)[];
};
}
export namespace HeroDetails {
export type Variables = {
episode?: Episode | null;
};
export type Query = {
__typename?: 'Query';
hero?: Hero | null;
};
export type Hero = {
__typename?: HumanInlineFragment['__typename'] | DroidInlineFragment['__typename'];
name: string;
} & (HumanInlineFragment | DroidInlineFragment);
export type HumanInlineFragment = {
__typename?: 'Human';
height?: number | null;
};
export type DroidInlineFragment = {
__typename?: 'Droid';
primaryFunction?: string | null;
};
}
export namespace HeroDetailsWithFragment {
export type Variables = {
episode?: Episode | null;
};
export type Query = {
__typename?: 'Query';
hero?: Hero | null;
};
export type Hero = HeroDetails.Fragment;
}
export namespace HeroName {
export type Variables = {
episode?: Episode | null;
};
export type Query = {
__typename?: 'Query';
hero?: Hero | null;
};
export type Hero = {
__typename?: 'Character';
name: string;
};
}
export namespace HeroNameConditionalInclusion {
export type Variables = {
episode?: Episode | null;
includeName: boolean;
};
export type Query = {
__typename?: 'Query';
hero?: Hero | null;
};
export type Hero = {
__typename?: 'Character';
name: string;
};
}
export namespace HeroNameConditionalExclusion {
export type Variables = {
episode?: Episode | null;
skipName: boolean;
};
export type Query = {
__typename?: 'Query';
hero?: Hero | null;
};
export type Hero = {
__typename?: 'Character';
name: string;
};
}
export namespace HeroParentTypeDependentField {
export type Variables = {
episode?: Episode | null;
};
export type Query = {
__typename?: 'Query';
hero?: Hero | null;
};
export type Hero = {
__typename?: HumanInlineFragment['__typename'] | DroidInlineFragment['__typename'];
name: string;
} & (HumanInlineFragment | DroidInlineFragment);
export type HumanInlineFragment = {
__typename?: 'Human';
friends?: (Friends | null)[] | null;
};
export type Friends = {
__typename?: _HumanInlineFragment['__typename'];
name: string;
} & (_HumanInlineFragment);
export type _HumanInlineFragment = {
__typename?: 'Human';
height?: number | null;
};
export type DroidInlineFragment = {
__typename?: 'Droid';
friends?: (_Friends | null)[] | null;
};
export type _Friends = {
__typename?: __HumanInlineFragment['__typename'];
name: string;
} & (__HumanInlineFragment);
export type __HumanInlineFragment = {
__typename?: 'Human';
height?: number | null;
};
}
export namespace HeroTypeDependentAliasedField {
export type Variables = {
episode?: Episode | null;
};
export type Query = {
__typename?: 'Query';
hero?: Hero | null;
};
export type Hero = HumanInlineFragment | DroidInlineFragment;
export type HumanInlineFragment = {
__typename?: 'Human';
property?: string | null;
};
export type DroidInlineFragment = {
__typename?: 'Droid';
property?: string | null;
};
}
export namespace HumanWithNullHeight {
export type Variables = {};
export type Query = {
__typename?: 'Query';
human?: Human | null;
};
export type Human = {
__typename?: 'Human';
name: string;
mass?: number | null;
};
}
export namespace TwoHeroes {
export type Variables = {};
export type Query = {
__typename?: 'Query';
r2?: R2 | null;
luke?: Luke | null;
};
export type R2 = {
__typename?: 'Character';
name: string;
};
export type Luke = {
__typename?: 'Character';
name: string;
};
}
export namespace HeroDetails {
export type Fragment = {
__typename?: 'Character';
name: string;
} & (HumanInlineFragment | DroidInlineFragment);
export type HumanInlineFragment = {
__typename?: 'Human';
height?: number | null;
};
export type DroidInlineFragment = {
__typename?: 'Droid';
primaryFunction?: string | null;
};
}
|
9c39d877b7b1b4717849177bcc4df188671db3da
|
TypeScript
|
Myna65/tdd-template
|
/src/use-cases/book-flight.test.ts
| 3.015625
| 3
|
import {Customer} from "../domain/customer";
import {Flight} from "../domain/flight";
import {InMemoryPaymentGateway} from "../gateways/in-memory-payment-gateway";
import {BookFlightUseCase} from "./book-flight";
let paymentGateway : InMemoryPaymentGateway;
function expectCustomerToBeCharged(customer: Customer, amount: number) {
const payment = paymentGateway.findByCustomer(customer);
expect(payment.amount).toBe(amount);
}
beforeEach(() => {
paymentGateway = new InMemoryPaymentGateway();
});
function bookFlight(customer: Customer, from: string, to: string) {
const flight = new Flight(from, to);
const bookFlightUseCase = new BookFlightUseCase(paymentGateway);
bookFlightUseCase.execute(customer, flight);
}
function expectCustomerMiles(customer: Customer, miles: number) {
expect(customer.miles).toEqual(miles);
}
test('From EU to EU', () => {
const customer = new Customer();
bookFlight(customer, "Luxembourg", "Barcelona");
expectCustomerToBeCharged(customer, 50);
});
test('From EU to Outside', () => {
const customer = new Customer();
bookFlight(customer, "Luxembourg", "Tokyo");
expectCustomerToBeCharged(customer, 100);
});
test('From EU to Outside with miles', () => {
const availableMiles = 1000;
const flightPrice = 100;
const customer = new Customer(availableMiles);
bookFlight(customer, "Luxembourg", "Tokyo");
expectCustomerToBeCharged(customer, flightPrice - availableMiles * 0.01);
expectCustomerMiles(customer, 0);
});
test('From EU to Outside with too many miles', () => {
const availableMiles = 100000;
const flightPrice = 100;
const customer = new Customer(availableMiles);
bookFlight(customer, "Luxembourg", "Tokyo");
expectCustomerToBeCharged(customer, 0);
expectCustomerMiles(customer, availableMiles - flightPrice * 100);
});
|
c8024b5301b9808cca5eb4e6e3af78c22efb0cfd
|
TypeScript
|
roma-lukashik/neural-network
|
/src/NeuralNetwork.ts
| 2.890625
| 3
|
import NeuronLayer from './NeuronLayer';
import { gradientDescent, Optimizer } from './optimizers';
import { ILossFunction, LossFunction, LossFunctions } from './loss-functions';
import * as array from './engine/ArrayOperators';
import * as vector from './engine/VectorsOperators';
import * as Distributions from './engine/Distributions';
import Vector = vector.Vector;
import Neuron from './Neuron';
interface INeuralNetworkOptions {
learningRate: number;
weightInitializationStrategy: () => number;
}
interface ITrainOptions {
optimizer: Optimizer;
lossFunction: ILossFunction;
epochs: number;
}
const defaultNeuralNetworkOptions: INeuralNetworkOptions = {
learningRate: 0.1,
weightInitializationStrategy: Distributions.uniform,
};
const defaultTrainOptions: ITrainOptions = {
optimizer: gradientDescent,
lossFunction: LossFunctions.quadratic,
epochs: 5,
};
export default class NeuralNetwork {
private readonly hiddenLayers: NeuronLayer[];
private readonly outputLayer: NeuronLayer;
constructor(
private readonly inputsNumber: number,
private readonly layers: NeuronLayer[],
private readonly neuralNetworkOptions: Partial<INeuralNetworkOptions> = {},
) {
this.neuralNetworkOptions = { ...defaultNeuralNetworkOptions, ...this.neuralNetworkOptions };
this.hiddenLayers = this.layers.slice(0, this.layers.length - 1);
this.outputLayer = this.layers[this.layers.length - 1];
this.initializeWeights();
}
private initializeWeights() {
const [firstLayer, ...otherLayers] = this.layers;
firstLayer.getNeurons().forEach((neuron) => {
array.times(this.inputsNumber, () => this.initializeWeight(neuron));
});
otherLayers.forEach((layer, i) => {
const previousLayer = this.layers[i];
layer.getNeurons().forEach((neuron) => {
previousLayer.getNeurons().forEach(() => this.initializeWeight(neuron));
});
});
}
private initializeWeight(neuron: Neuron) {
neuron.addWeight(this.neuralNetworkOptions.weightInitializationStrategy());
}
public train(features: Vector[], labels: Vector[], trainOptions: Partial<ITrainOptions> = {}): Vector {
const { optimizer, lossFunction, epochs } = { ...defaultTrainOptions, ...trainOptions };
const trainingSet = array.pair(features, labels);
const errors = [] as Vector;
array.times(epochs, () => {
let loss = 0;
trainingSet.forEach(([feature, label]) => {
// TODO fix that
array.times(5, () => {
this.feetForward(feature);
const deltas = optimizer(this.hiddenLayers, this.outputLayer, label, lossFunction.dx);
this.layers.forEach((layer, i) => this.updateNeuronsWeights(layer, deltas[i]));
});
loss += this.calculateError(label, lossFunction.fx);
});
trainingSet.sort(() => Math.random() - 0.5);
errors.push(loss / trainingSet.length);
});
return errors;
}
public feetForward(feature: Vector): Vector {
let output = feature;
this.layers.forEach((layer) => {
output = layer.feedForward(output);
});
return output;
}
private updateNeuronsWeights(neuronLayer: NeuronLayer, deltas: Vector) {
const deltasWithLearningRate = vector.scalar(deltas, this.neuralNetworkOptions.learningRate);
neuronLayer.getNeurons().forEach((neuron, i) => {
neuron.getWeights().forEach((neuronWeight, j) => {
const weightDelta = deltasWithLearningRate[i] * neuron.calculatePdTotalNetInputWrtWeight(j);
neuronWeight.setValue(neuronWeight.getValue() - weightDelta);
});
neuron.setBias(neuron.getBias() - deltasWithLearningRate[i]);
});
}
private calculateError(label: Vector, lossFunction: LossFunction): number {
const errors = array.pair(this.outputLayer.getOutput(), label).map(([prediction, target]) => {
return lossFunction(prediction, target);
});
return vector.argSum(errors);
}
}
|
2f2778581f4a8382fe3e323a9c67f082e91f1a01
|
TypeScript
|
pfgalego/sdk-codegen
|
/packages/api-explorer/src/reducers/spec/utils.spec.ts
| 2.53125
| 3
|
import { ApiModel } from '@looker/sdk-codegen'
import { omit } from 'lodash'
import { specs } from '../../test-data'
import { SpecItems } from '../../App'
import {
getDefaultSpecKey,
parseSpec,
fetchSpec,
initDefaultSpecState,
} from './utils'
describe('Spec reducer utils', () => {
const spec = specs['3.1']
describe('parseSpec', () => {
test('given a spec it returns an ApiModel with both readonly and writeable types', () => {
const api = parseSpec(spec.specContent!)
expect(api).toBeDefined()
const types = Object.keys(api.types)
expect(types).toEqual(
expect.arrayContaining(['Dashboard', 'WriteDashboard'])
)
})
})
describe('getDefaultSpecKey', () => {
const specList: SpecItems = {
defaultKey: { status: 'experimental', isDefault: true },
deprecatedKey: { status: 'deprecated' },
currentKey: { status: 'current' },
stableKey: { status: 'stable' },
}
test('it throws if no specs are provided', () => {
expect(() => {
getDefaultSpecKey({} as SpecItems)
}).toThrow('No specs found.')
})
test('it returns specKey for default spec if found', () => {
expect(getDefaultSpecKey(specList)).toEqual('defaultKey')
})
test('it returns specKey for spec marked as current if none are marked as default', () => {
const specItems = omit(specList, 'defaultKey')
expect(getDefaultSpecKey(specItems)).toEqual('currentKey')
})
test('it returns first spec if no spec is marked as default or current', () => {
const specItems = omit(specList, ['defaultKey', 'currentKey'])
expect(getDefaultSpecKey(specItems)).toEqual('deprecatedKey')
})
})
describe('fetchSpec', () => {
const specList: SpecItems = {
fromModel: {
status: 'experimental',
api: ApiModel.fromJson(specs['3.1'].specContent),
},
fromSpecContent: {
status: 'current',
specContent: specs['3.1'].specContent,
},
emptySpecItem: { status: 'deprecated' },
}
test('it uses api model if found ', () => {
const fetchedSpec = fetchSpec('fromModel', specList)
expect(fetchedSpec.api).toBeInstanceOf(ApiModel)
})
test('it uses spec content to create model if model is not available', () => {
const fetchedSpec = fetchSpec('fromSpecContent', specList)
expect(fetchedSpec.api).toBeInstanceOf(ApiModel)
})
test('it throws for invalid key', () => {
expect(() => fetchSpec('Bad Key', specList)).toThrow(
'Spec not found: "Bad Key"'
)
})
test('it throws if no model, content or url are found', () => {
expect(() => fetchSpec('emptySpecItem', specList)).toThrow(
'Could not fetch spec.'
)
})
})
describe('initDefaultSpecState', () => {
const saveLocation = window.location
afterAll(() => {
window.location = saveLocation
})
test('it fetches spec using key defined in url', () => {
window.history.pushState({}, '', '/4.0/')
const fetchedSpec = initDefaultSpecState(specs)
expect(fetchedSpec).toBeDefined()
expect(fetchedSpec.key).toEqual('4.0')
})
test('it gets default spec if url does not specify a key', () => {
window.history.pushState({}, '', '/')
const fetchedSpec = initDefaultSpecState(specs)
expect(fetchedSpec).toBeDefined()
expect(fetchedSpec.key).toEqual('3.1')
})
})
})
|
288469f29450f77152e9d33ef0245af4de7c2467
|
TypeScript
|
bestlyg/bestlyg-data-structure-and-algorithm-typescript-2019
|
/src/utils/model/Person.ts
| 3.421875
| 3
|
import { Comparable, Hash } from "../../types";
import { hashCode as hash, getClassName } from "../index";
export default class Person implements Comparable<Person>, Hash {
private _age: number;
private _name: string;
constructor(name: string, age: number) {
this._age = age;
this._name = name;
}
get age(): number {
return this._age;
}
get name(): string {
return this._name;
}
hashCode(): number {
let hashCode = hash(this._age);
hashCode = hashCode * 31 + hash(this._name);
return hashCode;
}
equals(obj: any): boolean {
if (obj === this) return true;
if (obj === null || getClassName(this) !== getClassName(obj)) return false;
return (
(obj as Person).age === this.age && (obj as Person).name === this.name
);
}
compareTo(obj: Person): number {
return this.age - obj.age;
}
public toString(): string {
return `Person name:${this.name} age:${this.age}`;
}
}
|
134c0b58a0c558b62584beec6ac2f505858979a4
|
TypeScript
|
joseywoermann/spotify-monthly-playlist
|
/src/util/helpers.ts
| 2.96875
| 3
|
import chalk from "chalk";
export const debugLog = <T>(message: T): void => {
console.log(chalk.hex("#9DD1BA")(`${getUTCTime()} [DEBUG] ${message}`));
};
export const infoLog = <T>(message: T): void => {
console.log(chalk.hex("#BAD755")(`${getUTCTime()} [INFO] ${message}`));
};
export const warnLog = <T>(message: T): void => {
console.log(chalk.hex("#FED762")(`${getUTCTime()} [WARN] ${message}`));
};
export const errorLog = <T>(message: T): void => {
console.log(chalk.hex("#FD647A")(`${getUTCTime()} [ERROR] ${message}`));
};
export const getMonth = (): string => {
return new Date().toLocaleString("default", {
month: "long",
});
};
export const getYear = (): number => {
return new Date().getFullYear();
};
// What an ugly piece of code
export const getUTCTime = (): string => {
return `[${new Date().getUTCFullYear()}-${format(
(new Date().getUTCMonth() + 1).toString()
)}-${format(
new Date().getUTCDate().toString()
)}] [${new Date().getUTCHours()}-${new Date().getUTCMinutes()}-${new Date().getUTCSeconds()}]`;
};
const format = (date: string): string => {
let formattedDate: string;
if (date.length === 1) {
formattedDate = `0${date}`;
} else {
formattedDate = date;
}
return formattedDate;
};
|
44148b19cf4a3020b3d18bfb13b34c3bbb88d7f0
|
TypeScript
|
Softcaze/GroupProject
|
/Group.Client/src/components/apps/home-feed/Feed.service.ts
| 2.515625
| 3
|
import { IGroup } from "../../../model/IGroup";
import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
import { Constants } from "../../../common/Constants";
import { IFeedEvent } from "../../../model/IFeedEvent";
const GET_MY_GROUPS_API: string = "/getGroups";
const GET_SUGGESTED_GROUPS: string = "/getGroupSuggestion";
const GET_FEED_EVENTS: string = "/getNews";
export class FeedService {
public static getMyGroups(webToken: string, userId: string): Promise<IGroup[]> {
return new Promise<IGroup[]>((resolve, reject) => {
axios.get(`${Constants.GROUP_API_URL}${Constants.API_PREFIX}${Constants.API_ROUTES.GROUP}${GET_MY_GROUPS_API}?userId=${userId}&webToken=${webToken}`, {
headers: {
"Content-Type": "application/json",
},
} as AxiosRequestConfig).then((result: any) => {
if (result)
resolve(result.data.map(lt => lt.idGroup));
else
resolve(null);
}).catch((err) => {
console.log(err);
});
});
}
public static getSuggestedGroups(webToken: string, userId: string): Promise<IGroup[]> {
return new Promise<IGroup[]>((resolve, reject) => {
axios.get(`${Constants.GROUP_API_URL}${Constants.API_PREFIX}${Constants.API_ROUTES.GROUP}${GET_SUGGESTED_GROUPS}?userId=${userId}&webToken=${webToken}`, {
headers: {
"Content-Type": "application/json",
},
} as AxiosRequestConfig).then((result: AxiosResponse<IGroup[]>) => {
if (result)
resolve(result.data);
else
resolve(null);
}).catch((err) => {
console.log(err);
});
});
}
public static getFeedEvents(webToken: string, userId: string): Promise<IFeedEvent[]> {
return new Promise<IFeedEvent[]>((resolve, reject) => {
axios.get(`${Constants.GROUP_API_URL}${Constants.API_PREFIX}${Constants.API_ROUTES.USER}${GET_FEED_EVENTS}?userId=${userId}&webToken=${webToken}`, {
headers: {
"Content-Type": "application/json",
},
} as AxiosRequestConfig).then((result: AxiosResponse<IFeedEvent[]>) => {
if (result)
resolve(result.data);
else
resolve(null);
}).catch((err) => {
console.log(err);
});
});
}
}
|
6d41a4e378e2215ecc4cbd7343223293a92f8811
|
TypeScript
|
Azure/Hyperledger-Fabric-on-Azure-Kubernetes-Service
|
/azhlfTool/commandDefs/msp/import/fromAzureStorage.ts
| 2.75
| 3
|
import { Argv } from "yargs";
import { MspCommandHandler } from "../../../commandHandlers/msp";
interface Arguments {
organization: string;
fileshare: string;
}
export const command = "fromAzureStorage";
export const desc = "Import MSP from Azure storage.";
export const builder = (yargs: Argv): Arguments =>
yargs
.option("organization", {
demandOption: true,
requiresArg: true,
type: "string",
description: "The organization name.",
alias: "o"
})
.option("fileshare", {
demandOption: true,
requiresArg: true,
type: "string",
alias: "f",
description:
"The azure file share url to download MSP. Should be in format: https://$STORAGE_ACCOUNT.file.core.windows.net/$STORAGE_FILE_SHARE?$SAS_TOKEN. On Windows please wrap argument in triple quotes!"
}).argv;
export const handler = async (argv: Arguments): Promise<void> => {
try {
await new MspCommandHandler().importFromAzureStorage(argv.organization, argv.fileshare);
} catch (error) {
console.error(error);
}
};
|
f4d8aaf68f036bd16e2ee28856cf9c4b1290b061
|
TypeScript
|
niebieska/TicketsBooking
|
/src/client/src/app/model/MovieHour.ts
| 2.75
| 3
|
import {MovieType} from "./MovieType";
export class MovieHour {
id: number;
hour: string;
movieType: MovieType;
constructor(id?:number, hour?:string, movieType?: MovieType){
this.id = id;
this.hour = hour;
this.movieType = movieType;
}
}
|
72ec0aa7813bfe9a3fb30aede9113928537a2746
|
TypeScript
|
muzzatech/Andreani-Api
|
/src/api/AndrianiURL.ts
| 2.734375
| 3
|
type AndreaniEntity =
| 'dispatch'
| 'orders'
| 'authorize'
| 'provinces'
| 'offices'
| 'tariff';
type AndreaniMethod = 'findBy' | 'find' | 'create' | 'login';
interface AndreaniEntityURL {
findByPK(): string;
find(): string;
create(): string;
login(): string;
}
const EntityParser = new Map<AndreaniEntity, string>();
EntityParser.set('dispatch', 'envios');
EntityParser.set('orders', 'ordenes-de-envio');
EntityParser.set('provinces', 'regiones');
EntityParser.set('offices', 'sucursales');
EntityParser.set('tariff', 'tarifas');
class AndreaniURL {
private host!: string;
private protocol!: string;
private basePath!: string;
protected getMethod(method: AndreaniMethod): string {
let select!: string;
switch (method) {
case 'find':
select = '?';
break;
case 'findBy':
select = '/';
break;
case 'create':
case 'login':
select = '';
break;
default:
throw new Error('selected method not available');
break;
}
return select;
}
protected createURL(entity: AndreaniEntity, method: AndreaniMethod): string {
let baseUrl = `${this.protocol}://${this.host}`;
if (entity === 'authorize') {
baseUrl = baseUrl.concat('/login');
} else {
const basePathHelper = entity === 'orders' ? `/v2` : `/${this.basePath}`;
const entityParse: any = `/${EntityParser.get(entity)}`;
baseUrl = baseUrl.concat(
basePathHelper,
entityParse,
this.getMethod(method),
);
}
return baseUrl;
}
on(entity: AndreaniEntity): AndreaniEntityURL {
const findByPK = () => this.createURL(entity, 'findBy');
const find = () => this.createURL(entity, 'find');
const create = () => this.createURL(entity, 'create');
const login = () => this.createURL(entity, 'login');
return {
findByPK,
find,
create,
login,
};
}
configure(host: string, protocol = 'https', basePath = 'v1'): void {
this.host = host;
this.protocol = protocol;
this.basePath = basePath;
}
}
const i: AndreaniURL = new AndreaniURL();
export { i as AndreaniURL };
|
cef30d8452d63f435ca566af63570995f0489b58
|
TypeScript
|
TeamBerry/muscadine
|
/src/models/message.model.ts
| 3.15625
| 3
|
export class Message {
public author: {
_id: string
name?: string
color?: string
role?: string
badge?: string
}
public contents: string
public source: string
public scope: string
public time: Date
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
constructor(message?: any) {
this.author = message && message.author || null
this.contents = message && message.contents
this.source = message && message.source || 'human'
this.scope = message && message.scope || null
this.time = message && message.time || new Date()
}
}
export class SystemMessage extends Message {
public context: 'success' | 'info' | 'berries' | null
constructor(message?: Partial<SystemMessage>) {
super(message)
this.source = 'system'
this.context = message?.context ?? null
}
}
export class FeedbackMessage extends Message {
/**
* Qualifies the feedback of the message
*
* @type {('error' | 'success' | 'info' | 'warning')}
* @memberof Message
*/
public context: 'error' | 'success' | 'info' | 'warning' | null
constructor(message?: Partial<FeedbackMessage>) {
super(message)
this.source = 'feedback'
this.context = message?.context ?? null
}
}
|
e6f8ddc02d64682b624dfe7d3f7f1628a1ebfb07
|
TypeScript
|
MKleinSB/pxt-envirobit-meowbit
|
/envirobit.ts
| 2.515625
| 3
|
//% weight=100 color=#000000 icon="\uf043" block="Enviro:Bit"
namespace envirobit {
class bme280 {
is_setup: boolean
addr: number
dig_t1: uint16
dig_t2: int16
dig_t3: int16
dig_p1: uint16
dig_p2: int16
dig_p3: int16
dig_p4: int16
dig_p5: int16
dig_p6: int16
dig_p7: int16
dig_p8: int16
dig_p9: int16
dig_h1: uint8
dig_h2: int16
dig_h3: uint8
dig_h4: int16
dig_h5: int16
dig_h6: int8
temperature: number
pressure: number
humidity: number
altitude: number
//qnh: number
constructor(addr: number) {
this.is_setup = false
this.addr = addr
}
setup(): void {
if (this.is_setup) return
this.is_setup = true
//this.qnh = 101325 // hPa standard ISO atmosphere at sea level
smbus.writeByte(this.addr, 0xe0, 0xb6) // Soft reset
control.waitMicros(200000)
smbus.writeByte(this.addr, 0xf2, 0b00000111) // x16 humidity oversampling
control.waitMicros(200000)
smbus.writeByte(this.addr, 0xf4, 0b10110111) // x16 oversampling, normal mode
control.waitMicros(200000)
smbus.writeByte(this.addr, 0xf5, 0b10010000) // 500ms standby time, 16 filter coef
control.waitMicros(200000)
// Registers 0x88 to 0x9F, then 0xA0 padding byte (b) and finally 0xA1
let compensation: number[] = smbus.unpack("<HhhHhhhhhhhhbB", smbus.readBuffer(this.addr, 0x88, 26))
// Registers 0xE1 to 0xE7
let temp: number[] = smbus.unpack("<hBbBbb", smbus.readBuffer(this.addr, 0xe1, 7))
compensation.push(temp.shift()) // first two-byte number is dig_h2 (0xe1 / 0xe2)
compensation.push(temp.shift()) // second single-byte number is dig_h3 (0xe3)
let reg_e4: number = temp.shift()
let reg_e5: number = temp.shift()
let reg_e6: number = temp.shift()
compensation.push((reg_e5 & 0x0f) | (reg_e4 << 4)) // dig_h4
compensation.push((reg_e5 >> 4) | (reg_e6 << 4)) // dig_h5
compensation.push(temp.shift()) // dig_h6 (0xe7)
this.dig_t1 = compensation.shift()
this.dig_t2 = compensation.shift()
this.dig_t3 = compensation.shift()
this.dig_p1 = compensation.shift()
this.dig_p2 = compensation.shift()
this.dig_p3 = compensation.shift()
this.dig_p4 = compensation.shift()
this.dig_p5 = compensation.shift()
this.dig_p6 = compensation.shift()
this.dig_p7 = compensation.shift()
this.dig_p8 = compensation.shift()
this.dig_p9 = compensation.shift()
compensation.shift() // Dispose of unused byte (0xa0)
this.dig_h1 = compensation.shift()
this.dig_h2 = compensation.shift()
this.dig_h3 = compensation.shift()
this.dig_h4 = compensation.shift()
this.dig_h5 = compensation.shift()
this.dig_h6 = compensation.shift()
}
getChipID(): number {
this.setup()
return smbus.readBuffer(this.addr, 0xd0, 1)[0]
}
update(): void {
this.setup()
let raw: Buffer = smbus.readBuffer(this.addr, 0xf7, 8)
let raw_temp: number = (raw[3] << 12) + (raw[4] << 4) + (raw[5] >> 4)
let raw_press: number = (raw[0] << 12) + (raw[1] << 4) + (raw[2] >> 4)
let raw_hum: number = (raw[6] << 8) + raw[7]
let var1: number = ((((raw_temp>>3) - (this.dig_t1<<1))) * (this.dig_t2)) >> 11;
let var2: number = (((((raw_temp>>4) - (this.dig_t1)) * ((raw_temp>>4) - (this.dig_t1))) >> 12) * (this.dig_t3)) >> 14;
let t_fine: number = var1 + var2;
this.temperature = ((t_fine * 5 + 128) >> 8)
var1 = (t_fine >> 1) - 64000
var2 = (((var1 >> 2) * (var1 >> 2)) >> 11) * this.dig_p6
var2 = var2 + ((var1 * this.dig_p5) << 1)
var2 = (var2 >> 2) + (this.dig_p4 << 16)
var1 = (((this.dig_p3 * ((var1 >> 2) * (var1 >> 2)) >> 13) >> 3) + (((this.dig_p2) * var1) >> 1)) >> 18
var1 = ((32768 + var1) * this.dig_p1) >> 15
if (var1 == 0) {
return // avoid exception caused by division by zero
}
let _p = ((1048576 - raw_press) - (var2 >> 12)) * 3125
_p = (_p / var1) * 2;
var1 = (this.dig_p9 * (((_p >> 3) * (_p >> 3)) >> 13)) >> 12
var2 = (((_p >> 2)) * this.dig_p8) >> 13
this.pressure = _p + ((var1 + var2 + this.dig_p7) >> 4)
var1 = t_fine - 76800
var2 = (((raw_hum << 14) - (this.dig_h4 << 20) - (this.dig_h5 * var1)) + 16384) >> 15
var1 = var2 * (((((((var1 * this.dig_h6) >> 10) * (((var1 * this.dig_h3) >> 11) + 32768)) >> 10) + 2097152) * this.dig_h2 + 8192) >> 14)
var2 = var1 - (((((var1 >> 15) * (var1 >> 15)) >> 7) * this.dig_h1) >> 4)
if (var2 < 0) var2 = 0
if (var2 > 419430400) var2 = 419430400
this.humidity = (var2 >> 12)
}
/*setQNH(qnh: number): void {
this.qnh = qnh
}*/
getTemperature(): number {
this.update()
return this.temperature
}
getPressure(): number {
this.update()
return this.pressure
}
getHumidity(): number {
this.update()
return this.humidity
}
/*getAltitude(): number {
this.update()
return this.altitude
}*/
}
class tcs3472 {
is_setup: boolean
addr: number
leds: DigitalPin
constructor(addr: number, leds: DigitalPin = DigitalPin.P8) {
this.is_setup = false
this.addr = addr
this.leds = leds
}
setup(): void {
if (this.is_setup) return
this.is_setup = true
smbus.writeByte(this.addr, 0x80, 0x03)
smbus.writeByte(this.addr, 0x81, 0x2b)
}
setIntegrationTime(time: number): void {
this.setup()
time = Math.clamp(0, 255, time * 10 / 24)
smbus.writeByte(this.addr, 0x81, 255 - time)
}
setLEDs(state: number): void {
pins.digitalWritePin(this.leds, state)
}
light(): number {
return this.raw()[0]
}
rgb(): number[] {
let result: number[] = this.raw()
let clear: number = result.shift()
for (let x: number = 0; x < result.length; x++) {
result[x] = result[x] * 255 / clear
}
return result
}
raw(): number[] {
this.setup()
let result: Buffer = smbus.readBuffer(this.addr, 0xb4, pins.sizeOf(NumberFormat.UInt16LE) * 4)
return smbus.unpack("HHHH", result)
}
}
class sound {
pin: AnalogPin
offset: number
threshold: number
timeout: number
clap_handler: Action
polling: boolean
watching: boolean
clap_time: number
sample: number
samples: number[]
constructor(pin: AnalogPin = AnalogPin.P2) {
this.pin = pin
this.offset = 580
this.threshold = 25
this.timeout = 100
this.polling = false
this.watching = false
this.clap_time = 0
this.sample = 0
this.samples = [0, 0, 0, 0, 0]
}
watchLevel(): void {
if(this.watching) return
control.runInParallel(() => {
while (true) {
this.samples[this.sample] = Math.abs(this.read())
this.sample += 1
this.sample %= 5
basic.pause(100)
}
})
this.watching = true
}
getLevel(): number {
let level: number = 0;
for (let x: number = 0; x < 5; x++){
let sample: number = _sound.samples[x]
if (sample > level) {
level = sample
}
}
return level
}
startPoll(): void {
if(this.polling) return
control.runInParallel(() => {
while (true) {
this.poll()
basic.pause(100)
}
})
this.polling = true
}
timeSinceLastClap(): number {
return game.runtime() - this.clap_time
}
setOffset(offset: number) {
this.offset = offset
}
read(): number {
return pins.analogReadPin(this.pin) - this.offset
}
onClap(clap_handler: Action): void {
this.clap_handler = clap_handler
this.startPoll()
}
setThreshold(threshold: number) {
this.threshold = threshold
}
setTimeout(timeout: number) {
this.timeout = timeout
}
poll(): void {
if (this.waitForClap(this.threshold, this.timeout)) {
this.clap_handler()
this.clap_time = game.runtime()
}
}
waitForClap(threshold: number = 25, timeout: number = 500): boolean {
let start: number = game.runtime()
while (game.runtime() < start + timeout) {
if (this.read() > threshold) {
while (this.read() > threshold) {
control.waitMicros(10)
}
return true
}
control.waitMicros(100)
}
return false
}
waitForDoubleClap(threshold: number = 25, distance: number = 500, timeout: number = 1000): boolean {
let start: number = game.runtime()
while (game.runtime() < start + timeout) {
if (this.waitForClap(threshold, 50)) {
control.waitMicros(100000)
if (this.waitForClap(threshold, distance)) {
return true
}
}
}
return false
}
}
let _bme280: bme280 = new bme280(0x76)
let _tcs3472: tcs3472 = new tcs3472(0x29, DigitalPin.P8)
let _sound: sound = new sound(AnalogPin.P2)
let sensitivity: number = 25
export function getBME280ChipID(): number {
return _bme280.getChipID()
}
//%
export enum OnOff {
Off = 0,
On = 1
}
/**
* Get the time since the last clap enviro:bit detected in milliseconds
*/
//% blockId=envirobit_time_since_last_clap
//% block="Time since last clap (ms)"
//% subcategory="Sound"
export function timeSinceLastClap(): number {
return _sound.timeSinceLastClap()
}
/**
* Set how sensitive the microphone is when detecting claps
* @param value - sensitivity (0-100)
*/
//% blockId=envirobit_set_clap_sensitivity
//% block="Set clap sensitivity to %value"
//% value.min=0 value.max=100 value.defl=80
//% subcategory="Sound"
export function setClapSensitivity(value: number): void {
value = Math.clamp(0, 100, value)
sensitivity = 105 - value
_sound.setThreshold(sensitivity);
}
/**
* Perform an action when a clap is heard
* @param clap_handler - function to run when a clap is detected
*/
//% blockId=envirobit_on_clap
//% block="When I hear a clap"
//% subcategory="Sound"
export function onClap(clap_handler: Action): void {
_sound.onClap(clap_handler);
}
/**
* Listen for two claps or loud sounds
* Returns true if two claps are heard, false if not.
* DEPRECATED: Use onClap instead
* @param timeout - time (in ms) to wait (500-2500)
*/
//% blockId=envirobit_wait_for_double_clap
//% block="Listen %timeout|ms for a double clap"
//% timeout.min=500 timeout.max=2500 timeout.defl=1000
//% subcategory="Sound"
//% color=#444444
export function waitForDoubleClap(timeout: number = 1000): boolean {
return _sound.waitForDoubleClap(sensitivity, 500, timeout)
}
/**
* Listen for a clap or loud sound
* Returns true if a single clap is heard, false if not.
* DEPRECATED: Use onClap instead
* @param timeout - time (in ms) to wait (500-2500)
*/
//% blockId=envirobit_wait_for_clap
//% block="Listen %timeout|ms for a clap"
//% timeout.min=500 timeout.max=2500 timeout.defl=1000
//% subcategory="Sound"
//% color=#444444
export function waitForClap(timeout: number = 1000): boolean {
return _sound.waitForClap(sensitivity, timeout)
}
/**
* Read the current sound level from the microphone
*/
//% blockId=envirobit_get_sound_level
//% block="Get sound"
//% subcategory="Sound"
export function getSoundLevel(): number {
return _sound.read()
}
/**
* Read the current noise level from the microphone
*/
//% blockId=envirobit_get_noise_level
//% block="Get noise level"
//% subcategory="Sound"
export function getNoiseLevel(): number {
_sound.watchLevel()
return _sound.getLevel()
}
/**
* Set the colour sensor LEDs
*/
//% blockId=envirobit_set_leds
//% block="Set LEDs to %state"
//% subcategory="Colour & Light"
export function setLEDs(state: OnOff): void {
_tcs3472.setLEDs(state)
}
/**
* Get the light level
*/
//% blockId=envirobit_get_light_clear
//% block="Get light"
//% subcategory="Colour & Light"
export function getLight(): number {
return Math.round(_tcs3472.light())
}
/**
* Get the amount of red the colour sensor sees
*/
//% blockId=envirobit_get_light_red
//% block="Get red"
//% subcategory="Colour & Light"
export function getRed(): number {
return Math.round(_tcs3472.rgb()[0])
}
/**
* Get the amount of green the colour sensor sees
*/
//% blockId=envirobit_get_light_green
//% block="Get green"
//% subcategory="Colour & Light"
export function getGreen(): number {
return Math.round(_tcs3472.rgb()[1])
}
/**
* Set the integration time of the colour sensor in ms
*/
//% blockId=envirobit_set_integration_time
//% block="Set colour integration time %time ms"
//% time.min=0 time.max=612 value.defl=500
//% subcategory="Expert"
export function setColourIntegrationTime(time: number): void {
return _tcs3472.setIntegrationTime(time)
}
/**
* Get the amount of blue the colour sensor sees
*/
//% blockId=envirobit_get_light_blue
//% block="Get blue"
//% subcategory="Colour & Light"
export function getBlue(): number {
return Math.round(_tcs3472.rgb()[2])
}
/**
* Return the temperature in degrees celcius
*/
//% blockId=envirobit_get_temperature
//% block="Get temperature"
//% subcategory="Air & Weather"
export function getTemperature(): number {
return Math.round(_bme280.getTemperature() / 100.0)
}
/**
* Return the temperature in degrees celcius with two decimal places
*/
//% blockId=envirobit_get_temperature_decimal
//% block="Get temperature (decimal)"
//% subcategory="Expert"
export function getTemperatureDecimal(): number {
return Math.roundWithPrecision(_bme280.getTemperature() / 100.0, 2)
}
/**
* Return the temperature in degrees celcius * 100
*/
//% blockId=envirobit_get_temperature_fine
//% block="Get temperature (x100)"
//% subcategory="Expert"
export function getTemperatureFine(): number {
return Math.round(_bme280.getTemperature())
}
/**
* Get the air pressure in hPa
*/
//% blockId=envirobit_get_pressure
//% block="Get pressure"
//% subcategory="Air & Weather"
export function getPressure(): number {
return Math.round(_bme280.getPressure() / 100.0)
}
/**
* Get the air pressure in hPa with two decimal places
*/
//% blockId=envirobit_get_pressure_decimal
//% block="Get pressure (decimal)"
//% subcategory="Expert"
export function getPressureDecimal(): number {
return Math.roundWithPrecision(_bme280.getPressure() / 100.0, 2)
}
/**
* Get the air pressure in pascals (hPa * 100)
*/
//% blockId=envirobit_get_pressure_fine
//% block="Get pressure (x100)"
//% subcategory="Expert"
export function getPressureFine(): number {
return _bme280.getPressure()
}
/**
* Get the relative humidity in %
*/
//% blockId=envirobit_get_humidity
//% block="Get humidity"
//% subcategory="Air & Weather"
export function getHumidity(): number {
return Math.round(_bme280.getHumidity() / 1024.0)
}
/**
* Get the relative humidity in % with two decimal places
*/
//% blockId=envirobit_get_humidity_decimal
//% block="Get humidity (decimal)"
//% subcategory="Expert"
export function getHumidityDecimal(): number {
return Math.roundWithPrecision(_bme280.getHumidity() / 1024.0, 2)
}
/**
* Get the relative humidity in % * 100
*/
//% blockId=envirobit_get_humidity_fine
//% block="Get humidity (x100)"
//% subcategory="Expert"
export function getHumidityFine(): number {
return Math.round((_bme280.getHumidity() * 100.0) / 1024.0)
}
/*
//% blockId=envirobit_get_altitude
//% block="Get altitude"
//% subcategory="Air & Weather"
export function getAltitude(): number {
return _bme280.getAltitude()
}
*/
}
namespace smbus {
export function writeByte(addr: number, register: number, value: number): void {
let temp = pins.createBuffer(2);
temp[0] = register;
temp[1] = value;
pins.i2cWriteBuffer(addr, temp, false);
}
export function writeBuffer(addr: number, register: number, value: Buffer): void {
let temp = pins.createBuffer(value.length + 1);
temp[0] = register;
for (let x = 0; x < value.length; x++) {
temp[x + 1] = value[x];
}
pins.i2cWriteBuffer(addr, temp, false);
}
export function readBuffer(addr: number, register: number, len: number): Buffer {
let temp = pins.createBuffer(1);
temp[0] = register;
pins.i2cWriteBuffer(addr, temp, false);
return pins.i2cReadBuffer(addr, len, false);
}
function readNumber(addr: number, register: number, fmt: NumberFormat = NumberFormat.UInt8LE): number {
let temp = pins.createBuffer(1);
temp[0] = register;
pins.i2cWriteBuffer(addr, temp, false);
return pins.i2cReadNumber(addr, fmt, false);
}
export function unpack(fmt: string, buf: Buffer): number[] {
let le: boolean = true;
let offset: number = 0;
let result: number[] = [];
let num_format: NumberFormat = 0;
for (let c = 0; c < fmt.length; c++) {
switch (fmt.charAt(c)) {
case '<':
le = true;
continue;
case '>':
le = false;
continue;
case 'c':
case 'B':
num_format = le ? NumberFormat.UInt8LE : NumberFormat.UInt8BE; break;
case 'b':
num_format = le ? NumberFormat.Int8LE : NumberFormat.Int8BE; break;
case 'H':
num_format = le ? NumberFormat.UInt16LE : NumberFormat.UInt16BE; break;
case 'h':
num_format = le ? NumberFormat.Int16LE : NumberFormat.Int16BE; break;
}
result.push(buf.getNumber(num_format, offset));
offset += pins.sizeOf(num_format);
}
return result;
}
}
|
3de03121a55a80318a4117a2513a3ef3518b9f5e
|
TypeScript
|
RequestNetwork/requestNetwork
|
/packages/toolbox/src/commands/request/calculateReference.ts
| 2.703125
| 3
|
import { PaymentReferenceCalculator } from '@requestnetwork/payment-detection';
import * as yargs from 'yargs';
import { utils } from 'ethers';
interface IReqOptions {
requestId: string;
salt: string;
address: string;
}
const calculateReferenceForRequest = (options: IReqOptions): void => {
try {
const paymentRef = PaymentReferenceCalculator.calculate(
options.requestId,
options.salt,
options.address,
);
console.log('#####################################################################');
console.log(`Payment reference: ${paymentRef}`);
console.log('#####################################################################');
const indexedRef = utils.keccak256(`0x${paymentRef}`);
console.log(`Payment reference indexed: ${indexedRef}`);
} catch (e) {
if (e instanceof Error) {
console.error(`Error ! ${e.message}`);
}
}
};
export const command = 'calculateReference <requestId> <salt> <address>';
export const describe = 'Calculates the payment reference from requestId, salt and address';
export const builder = (): yargs.Argv<IReqOptions> =>
yargs.env().options({
requestId: {
demand: true,
type: 'string',
desc: 'Request ID',
},
salt: {
demand: true,
type: 'string',
desc: 'Salt used for request creation',
},
address: {
demand: true,
type: 'string',
desc: 'Address used for request creation',
},
});
export const handler = calculateReferenceForRequest;
|
c0dc737138ec74ebca33df700f7f384a3ea73af3
|
TypeScript
|
heifade/happywork-test-web
|
/src/pageBase/pageBaseService.ts
| 2.6875
| 3
|
import { ListItemModule } from "./list/listModule";
import { wait } from "../util/util";
let dataList: ListItemModule[];
function initDataList() {
let list = new Array<ListItemModule>();
for (let i = 0; i < 20; i++) {
list.push({ id: `${i}`, name: `name${i}` });
}
dataList = list;
}
initDataList();
export async function fetchDataList() {
await wait(500);
return dataList;
}
export async function deleteData(id: string) {
await wait(500);
dataList = dataList.filter(u => u.id !== id);
}
export async function saveData(item: ListItemModule) {
await wait(500);
let d = dataList.find(m => m.id == item.id);
d.name = item.name;
}
|
55e4896efd29daff972a73938446aa74988abb43
|
TypeScript
|
GregTCLTK/WebGen
|
/src/components/cards/searchCard.ts
| 2.53125
| 3
|
import { createElement, draw, img, span } from "../Components";
import { CommonCard } from "../../types/card";
import '../../css/search.webgen.static.css';
import { CommonIcon, CommonIconType, Icon } from "../generic/Icon";
export type SearchEntry = {
name: string;
icon?: string;
tags?: string[];
category?: string;
suffix?: string;
id: string;
}
export const enum SearchMode {
ShowBegin,
HideBegin,
HideWhenEmpty
}
export const searchCard = (settings: {
type: "smart" | "default",
maxWidth?: string | "default",
mode?: SearchMode
placeholder?: string,
notfound?: string,
icons?: {
edit: string
close: string
remove: string
download: string
},
actions?: {
close?: () => void,
click?: (arg: SearchEntry) => void,
download?: (arg: SearchEntry) => void,
edit?: (arg: SearchEntry) => void,
remove?: (arg: SearchEntry) => void
},
index: SearchEntry[],
width?: number
}): CommonCard => ({
getSize: () => ({ height: undefined, width: settings.width }),
draw: (card) => {
let search = createElement("div");
search.classList.add("search");
let input = createElement("input") as HTMLInputElement;
let ul = createElement("ul") as HTMLUListElement
input.placeholder = settings.placeholder || "Search...";
if (settings.actions?.close) {
let icon = draw(Icon(settings.icons?.close ?? CommonIcon(CommonIconType.Close)));
icon.onclick = settings.actions?.close;
search.append(icon);
}
let list: SearchEntry[] = [];
let lastsearch = "";
const reRenderElements = (x: SearchEntry) => {
let tags: HTMLElement[] = [];
x.tags?.filter((tag) => tags.push(span(tag, "tag")))
let li = createElement("li");
li.onclick = () => settings.actions?.click?.(x);
const left = createElement("left");
const right = createElement("right");
if (x.icon) {
const image = img(x.icon);
image.loading = "lazy";
left.append(image);
}
left.append(x.name);
if (x.category) right.append(span(x.category, "tag", "category"));
if (x.suffix) right.append(x.suffix);
right.append(...tags);
if (settings.actions?.download) {
const download = draw(Icon(settings.icons?.download ?? CommonIcon(CommonIconType.Download)));
download.onclick = () => settings.actions?.download?.(x);
right.append(download);
}
if (settings.actions?.edit) {
const edit = draw(Icon(settings.icons?.edit ?? CommonIcon(CommonIconType.Edit)));
edit.onclick = () => settings.actions?.edit?.(x);
right.append(edit);
}
if (settings.actions?.remove) {
const remove = draw(Icon(settings.icons?.remove ?? CommonIcon(CommonIconType.Delete)));
remove.onclick = () => settings.actions?.remove?.(x);
right.append(remove);
}
li.append(left);
li.append(right);
ul.append(li);
}
input.onkeyup = (d: KeyboardEvent) => {
if (d.key == "Enter") {
if (ul.children.item.length == 1) {
let element = <HTMLButtonElement | undefined>ul.children[ 0 ];
element?.click();
}
}
if (lastsearch == input.value) return;
lastsearch = input.value;
if (settings.mode === SearchMode.HideWhenEmpty && lastsearch === "") {
ul.innerHTML = "";
return;
}
if (settings.type == "smart" && settings.index) {
let smart = input.value.split(` `);
let tags: string[] = [];
let name = "";
smart.forEach(e => {
if (e.startsWith("#") || e.startsWith("!"))
tags.push(e);
else
name += " " + e;
});
name = name.slice(1);
list = settings.index;
tags.forEach(e => {
if (e.startsWith("#"))
list = list.filter(x => x.tags ? x.tags.indexOf(e.slice(1)) != -1 : false);
else if (e.startsWith("!"))
list = list.filter(x => x.tags ? x.tags.indexOf(e.slice(1)) == -1 : false);
if (list.length == 0)
return;
});
list = list.filter(x => x.name.toLowerCase().includes(name.toLowerCase()));
} else
list = settings.index.filter(x => x.name.toLowerCase().includes(input.value.toLowerCase()));
ul.innerHTML = "";
list.forEach(x => reRenderElements(x));
if (ul.childNodes.length == 0 && settings.notfound !== undefined) {
let li = createElement("li");
li.onclick = () => settings?.actions?.click?.({ id: "notfound", name: "notfound" });
li.classList.add("gray");
li.innerText = settings.notfound;
ul.append(li);
}
};
search.append(input);
search.append(ul);
if (settings.mode === SearchMode.ShowBegin) {
settings.index.forEach(x => reRenderElements(x));
}
card.append(search)
return card
}
});
|
556f80ec0a1c891f5c9e95a658d8ff58e6d10601
|
TypeScript
|
IamRaduB/sync-i18n
|
/src/commands/validate.command.ts
| 2.5625
| 3
|
import { Command } from 'commander';
import { join } from 'path';
import { readdir } from 'fs';
import { promisify } from 'util';
import { Logger } from '../services/logger.service';
import { FileService } from '../services/file.service';
import { UtilService } from '../services/util.service';
import { Invalid } from '../util/error';
const readdirPromise = promisify(readdir);
export class ValidateCommand {
private command: Command;
constructor(
private program: Command,
private log: Logger,
private fileService: FileService,
private utilService: UtilService,
) {
this.command = program.command('validate <rootFile> [specificFiles...]') as Command;
this.setup();
}
setup() {
this.command.action((rootFile: string, specificFiles: string[]) => {
this.log.info('Validating...');
if (specificFiles && specificFiles.length) {
return this.validateSpecificFiles(this.program.dir, rootFile, specificFiles);
}
return this.validateAllFiles(this.program.dir, rootFile);
});
}
async validateFile(rootLangData: any, langFile: string): Promise<boolean> {
this.log.debug(`Validating file ${langFile}`);
let lang;
try {
lang = await this.fileService.readFile(langFile);
} catch (e) {
this.log.error(`Unable to read language file ${langFile}`, e);
throw e;
}
const errors = this.utilService.compareLangObjects('', rootLangData, lang);
if (!errors.length) {
this.log.valid(langFile);
return true;
}
this.printErrors(errors, langFile);
return false;
}
async validateSpecificFiles(inputDir: string, rootFile: string, specificFiles: string[]) {
this.log.debug(`Validating a subset of files in ${inputDir}. Root ${rootFile}`);
this.log.debug(`Root file ${rootFile}. Specific files: ${specificFiles.join(',')}`);
let root: any;
const rootPath = join(process.cwd(), inputDir, rootFile);
try {
root = await this.fileService.readFile(rootPath);
} catch (e) {
this.log.error(`Unable to read root file ${join(process.cwd(), inputDir, rootFile)}`, e);
throw e;
}
const promises = specificFiles.map((fileName) => {
const filePath = join(process.cwd(), inputDir, fileName);
return this.validateFile(root, filePath);
});
await Promise.all(promises);
}
async validateAllFiles(inputDir: string, rootFile: string) {
this.log.debug(`Validating all files in ${inputDir} against root ${rootFile}`);
let root: any;
const rootPath = join(process.cwd(), inputDir, rootFile);
try {
root = await this.fileService.readFile(rootPath);
} catch (e) {
this.log.error(`Unable to read root file ${rootPath}`, e);
throw e;
}
// read the contents of the translations directory
// and filter out the root file
const fileNames = (await readdirPromise(join(process.cwd(), inputDir))).filter((fname) => fname !== rootFile);
const promises = fileNames.map((fname) => {
return this.validateFile(root, join(inputDir, fname));
});
await Promise.all(promises);
}
printErrors(errors: Invalid[], langFile: string) {
errors.forEach((error) => {
this.log.invalid(langFile);
this.log.invalidDetails(error.message);
this.log.invalidDetails('Root:', error.rootValue);
this.log.invalidDetails(`${langFile}:`, error.lang);
});
}
getCommand(): Command {
return this.command;
}
}
|
a0eae5e2672a3577b20ede5074c272c09c7bdb0b
|
TypeScript
|
mmajkafmp/typescript-sandbox
|
/src/design-patterns/behavioral-observer/mall.ts
| 2.59375
| 3
|
import Observer from './observer';
import Sale from './sale';
export default class Mall implements Observer {
sales: Sale[];
constructor() {
this.sales = [];
}
notify(storeName: string, discount: number) {
this.sales.push({ storeName, discount });
}
}
|
d11088fc8fda3e06843495aa05495117017d7be3
|
TypeScript
|
vambil/COMP-426-Final
|
/scripts/Parent.ts
| 2.65625
| 3
|
class Parent {
private children: Child[];
private requests: Requests[];
constructor() {
this.children = [];
this.requests = [];
}
getChildren() {
return this.children;
}
getRequests() {
return this.requests;
}
addChild(child: Child) {
this.children[this.children.length] = child;
this.updateTables();
}
removeChild(child: Child) {
for (let i = 0; i < this.children.length; i++) {
if (this.children[i] === child) {
this.children.splice(i,1);
}
}
this.updateTables();
}
sendFund(child: Child, fund: Fund) {
child.receiveFund(fund);
}
receiveRequest(request: Requests) {
this.requests[this.requests.length] = request;
this.updateTables();
}
approveRequest(index: number) {
let request: Requests = this.requests[index];
request.getChild().receiveFund(request.getFund());
this.requests.splice(index, 1);
this.updateTables();
}
denyRequest(index: number) {
this.requests.splice(index,1);
this.updateTables();
}
notify(child: Child, store: string) {
child.addApproved(store);
}
updateTables() {
}
}
|
a6843a8f64cdee421587a0fb450c6b74bd8295f0
|
TypeScript
|
akurilov/platform
|
/ui/src/dashboards/actions/v2/hoverTime.ts
| 2.859375
| 3
|
export type Action = SetHoverTimeAction
interface SetHoverTimeAction {
type: 'SET_HOVER_TIME'
payload: {
hoverTime: string
}
}
export const setHoverTime = (hoverTime: string): SetHoverTimeAction => ({
type: 'SET_HOVER_TIME',
payload: {hoverTime},
})
|
e609b112f0ae102b7e6a872f21104ff05c077d4b
|
TypeScript
|
omochi/angular2-quickstart
|
/app/main.ts
| 3.09375
| 3
|
import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from './app.component';
class Cat {
name: string;
age: number;
constructor(name: string) {
this.name = name;
}
greet(): void {
console.log("I am " + this.name);
}
}
var cat1 = new Cat("tama");
cat1.greet();
var cat2 = {
name: "mike",
age: 3
};
cat2.greet();
var cat3 = {
namae: "hoge",
hage: 4
};
cat3.greet();
bootstrap(AppComponent);
|
dbfeff1ca45720298a1a2b2d7d205c4e25f1b9f0
|
TypeScript
|
gxh1996/jumpAdventure
|
/jumpAdventure/assets/scripts/indexScene/selectPanel/horizelScrollView.ts
| 2.625
| 3
|
const { ccclass, property, disallowMultiple, menu, requireComponent } = cc._decorator;
/* ---------------------水平滚动页面----------------------- */
@ccclass
@disallowMultiple()
@menu('自定义组件/HorizelScrollView')
@requireComponent(cc.ScrollView)
export default class HorizelScrollPage extends cc.Component {
@property(cc.Node)
private content: cc.Node = null;
@property({
type: [cc.Component.EventHandler],
displayName: "翻页事件"
})
private scrollEvents: cc.Component.EventHandler[] = [];
private page: cc.Prefab = null;
private scrollView: cc.ScrollView = null;
/**content的初始位置,也是页面指针为1时的位置*/
private initPosOfContent: cc.Vec2;
private pageWidth: number;
/**页面数值,也是内容节点的孩子节点*/
private pages: cc.Node[] = null;
private virtualMode: boolean = false;
/**移动超过页面宽度百分比的长度就发生翻页*/
private scrollThreshold: number = 0.4;
/**翻页的时间*/
private turnPageTime: number = 1;
private curIdx: number = 0;
private maxIdx: number = 0;
/**实际页面指针*/
private _curIdx: number = 0;
/**实际最大页面数,为奇数*/
private _maxPageNum: number = 3;
/**中间页位置的坐标 */
private PosOfMedianPage: cc.Vec2;
/**中间页的实际页指针 */
private idxOfMedianPage: number;
/**超出界面后停止拖动 */
private stopDragInOverFace: boolean = true;
onLoad() {
this.scrollView = this.node.getComponent(cc.ScrollView);
this.pages = this.content.children;
this.onEvent();
}
private onEvent() {
this.node.on("touch-up", this.touchUp, this);
this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.touchCancel, this);
}
/**
* 初始化列表,创建需要个数的页面
*/
init(page: cc.Prefab, n: number) {
this.page = page;
this.curIdx = 0;
this.maxIdx = -1;
this._curIdx = 0;
this.idxOfMedianPage = Math.floor(this._maxPageNum / 2);
this.initPosOfContent = this.content.getPosition();
this.pageWidth = this.page.data.width;
this.PosOfMedianPage = this.getContentPos(this.idxOfMedianPage);
this.setPageNum(n);
}
/**
* 设置逻辑页面数量
*/
setPageNum(n: number) {
if (this.curIdx > n - 1) {
console.error("无法设置页面数量,因为要删除的页面中有正在显示的");
return;
}
if (n === this.getPageNum())
return;
/**实际需要页面数 */
let _n: number = n > this._maxPageNum ? this._maxPageNum : n;
if (this.pages.length !== _n) {
if (this.pages.length > _n)
this.deletePages(this.pages.length - _n);
else if (this.pages.length < _n)
this.addPages(_n - this.pages.length);
}
this.maxIdx = n - 1;
if (this.getPageNum() > this._maxPageNum && !this.virtualMode)
this.openVirtualMode();
if (this.getPageNum() <= this._maxPageNum && this.virtualMode)
this.closeVirtualMode();
}
/**
* 逻辑页面数量
*/
getPageNum(): number {
return this.maxIdx + 1;
}
getPages(): cc.Node[] {
return this.pages;
}
private horizelLayout() {
let i: number;
for (i = 0; i < this.pages.length; i++)
this.pages[i].setPosition(this.getPagePos(i));
}
/**
* 得到该页面坐标
*/
private getPagePos(no: number): cc.Vec2 {
return cc.v2(this.pageWidth / 2 + this.pageWidth * no);
}
private addPages(n: number) {
let i: number;
for (i = 0; i < n; i++)
this.content.addChild(cc.instantiate(this.page));
}
/**
* 从后面删除多个页面
*/
private deletePages(n: number) {
let i: number;
let p: number = this.pages.length - 1;
for (i = 0; i < n; i++)
this.content.removeChild(this.pages[p]);
}
private openVirtualMode() {
this.virtualMode = true;
}
private closeVirtualMode() {
this.virtualMode = false;
}
/**
* 当显示页面i时Content的坐标
* @param i 实际页面指针
*/
private getContentPos(i: number): cc.Vec2 {
return cc.v2(this.initPosOfContent.x - this.pageWidth * i, this.initPosOfContent.y);
}
/**
* 得到显示页面i时相对于ScrollView水平方向的百分比位置上
* @param i 实际指针
* @returns percent
*/
private getPercent(i: number): number {
//0显示第一个页面,1显示最后一个页面
if (i === 0)
return 0;
else
return i / (this.pages.length - 1);
}
/**
* 滚动到当前实际指针指向的页面
*/
private scrollToCurPage(): number {
let curP: cc.Vec2 = this.content.getPosition();
let t: number = Math.abs(this.getContentPos(this._curIdx).x - curP.x) / this.pageWidth * this.turnPageTime;
this.scrollView.scrollToPercentHorizontal(this.getPercent(this._curIdx), t);
return t;
}
/**
* 需要给页面重新排序
* @param dir 翻页方向 -1左
*/
private needMovePage(dir: number): boolean {
/**需要几个页面 */
let needP: number;
/**已有几个s */
let haveP: number;
if (dir === -1) {
//左
needP = this.curIdx;
haveP = this._curIdx;
}
else if (dir === 1) {
needP = this.maxIdx - this.curIdx;
haveP = this.pages.length - 1 - this._curIdx;
}
//只能多不能少
if (needP > haveP)
return true;
return false;
}
private dealScroll() {
let self = this;
let newP: cc.Vec2 = this.content.getPosition();
let oldP: cc.Vec2 = this.getContentPos(this._curIdx);
let dir: number = newP.x - oldP.x;
let l: number = Math.abs(dir);
let turnPage: boolean = l > this.pageWidth * this.scrollThreshold;
if (turnPage) {
//需要翻页
if (dir > 0) {
//向左
if (this.curIdx === 0)
return;
//可以向左翻页
this.curIdx--;
this._curIdx--;
let t: number = this.scrollToCurPage();
//修正真实页面
if (this.virtualMode && this.needMovePage(-1) && this._curIdx !== this.idxOfMedianPage) {
this.scheduleOnce(() => {
//将最后一个页面放在最前面
let n: cc.Node = self.pages.pop();
self.pages.unshift(n);
self.scrollView.setContentPosition(self.PosOfMedianPage);
self.horizelLayout();
//这时我们要初始化这个页面
self.updatePageContent(n, self.curIdx - self.idxOfMedianPage);
self._curIdx = self.idxOfMedianPage;
}, t);
}
}
else {
//向右
if (this.curIdx === this.maxIdx)
return;
this.curIdx++;
this._curIdx++;
let t: number = this.scrollToCurPage();
if (this.virtualMode && this.needMovePage(1) && this._curIdx !== this.idxOfMedianPage) {
this.scheduleOnce(() => {
//将第一个页面放在最后面
let n: cc.Node = self.pages.shift();
self.pages.push(n);
self.scrollView.setContentPosition(self.getContentPos(1));
self.horizelLayout();
//这时我们要初始化这个页面
self.updatePageContent(n, self.curIdx + self.idxOfMedianPage);
self._curIdx = self.idxOfMedianPage;
}, t);
}
}
}
else {
//处于边界,scrollView会帮你还原
if (this.curIdx === 0 && dir > 0 || this.curIdx === this.maxIdx && dir < 0)
return;
//还原
let t: number = l / this.pageWidth * this.turnPageTime;
this.scrollView.scrollToPercentHorizontal(this.getPercent(this._curIdx), t);
}
// console.log("当前显示的是页面", this.curIdx);
}
/**
* 将该页面更新为页面no
*/
private updatePageContent(node: cc.Node, no: number) {
// console.error("待实现");
let e: cc.Event.EventCustom = new cc.Event.EventCustom("updatePageContent", true);
e.detail = [node, no];
this.node.dispatchEvent(e);
}
/* ----------------------事件回调------------------------- */
private touchUp() {
// console.log("触摸结束");
this.dealScroll();
}
private touchCancel() {
console.log("touchCancel");
this.dealScroll();
}
private scrollBegan() {
console.log("scrollBegan");
}
private scrollEnded() {
console.log("scrollEnded");
}
// private scrolling() {
// console.log("scrolling");
// }
update(dt) {
}
}
|
6db15f952af75d043c31bc364d74bd3f70e3f5e8
|
TypeScript
|
Jameskmonger/adventofcode
|
/src/2019/Day 1/part1.ts
| 3.140625
| 3
|
import {modules} from "./modules"
class FuelCalculator {
/**
* Calculates the fuel needed for a given mass
* @param modules list of modules' masses
*/
public fuelForMass(modules: number[]) {
return modules
.map(m => Math.floor(m / 3) - 2)
.reduce((acc, val) => acc + val);
}
}
const fuelCalculator = new FuelCalculator();
console.log("Needed fuel:", fuelCalculator.fuelForMass(modules));
|
219b4c7d29e902290d4b65eeefa3347c898257ab
|
TypeScript
|
redarrowlabs/modeljx
|
/src/modeljx.ts
| 3.015625
| 3
|
import * as Immutable from 'immutable';
import * as _ from 'lodash';
export interface ProjectionStage<TFromType, TResultType> {
override(props: {
fromProperty: (from: TFromType) => any,
toProperty: (to: TResultType) => any,
use: (from: any) => any,
when?: (from: any) => boolean
} | {
forProperty: (from: TFromType) => any,
use: (from: any) => any,
when?: (from: any) => boolean
}): ProjectionStage<TFromType, TResultType>,
withMapping(mapping: (sourcePropertyName: string) => string): ProjectionStage<TFromType, TResultType>,
build(): (from: TFromType | TFromType[] | Immutable.List<TFromType>) => TResultType | Immutable.List<TResultType>
}
interface ConditionalFunction {
when?: (x: any) => boolean,
use: (from: any) => any
}
class ProjectionStageImpl<TFromType, TResultType> implements ProjectionStage<TFromType, TResultType> {
private from: (o: any) => TFromType;
private to: (o: any) => TResultType;
private _projections: Immutable.Map<string, Immutable.Map<string, Immutable.List<ConditionalFunction>>> =
Immutable.Map<string, Immutable.Map<string, Immutable.List<ConditionalFunction>>>();
private _mappings: Immutable.List<((x: string) => string)> =
Immutable.List<((x: string) => string)>();
constructor(
from: (o: any) => TFromType,
to: (o: any) => TResultType) {
this.from = from;
this.to = to;
}
withMapping(mapping: (sourcePropertyName: string) => string): ProjectionStage<TFromType, TResultType> {
this._mappings = this._mappings.push(mapping);
return this;
}
override(props: {
fromProperty: (from: TFromType) => any,
toProperty: (to: TResultType) => any,
use: (from: any) => any,
when?: (from: any) => boolean
[index: string]: any;
} | {
forProperty: (from: TFromType) => any,
use: (from: any) => any,
when?: (from: any) => boolean,
[index: string]: any;
}): ProjectionStage<TFromType, TResultType> {
props;
let {fromProperty, toProperty, forProperty, use, when} = props;
let from = '';
let to = '';
if (fromProperty) {
from = ProjectionStageImpl.extractPropertyName(fromProperty);
to = ProjectionStageImpl.extractPropertyName(toProperty);
} else if (forProperty) {
from = to = ProjectionStageImpl.extractPropertyName(forProperty);
} else {
throw "unsupported projection type";
}
this.overrideProperty(from, to, use, when);
return this;
}
private overrideProperty(
fromProperty: string,
toProperty: string,
use: (from: any) => any,
when?: (from: any) => boolean) {
let toMap = this._projections.get(fromProperty);
if (!toMap) {
toMap = Immutable.Map<string, Immutable.List<ConditionalFunction>>();
}
let projections = toMap.get(toProperty);
if (!projections) {
projections = Immutable.List<ConditionalFunction>();
}
projections = projections.push({when, use});
toMap = toMap.set(toProperty, projections);
this._projections = this._projections.set(fromProperty, toMap);
}
private static extractPropertyName(fromProperty: Function | string): string {
if (!fromProperty) {
return '';
}
if (typeof(fromProperty) === 'string') {
const parts = fromProperty.split('.');
return parts[parts.length - 1];
}
let serialized: string = fromProperty.toString();
let isLambda = serialized.indexOf('=>') > -1;
const rValue = isLambda
? serialized.split('=>')[1].trim()
: serialized.split('return')[1].split(';')[0];
return ProjectionStageImpl.extractPropertyName(rValue);
}
build(): (from: TFromType | TFromType[] | Immutable.List<TFromType>) => TResultType | Immutable.List<TResultType> {
const HasBeenProjected = Symbol('short circuit Immutable forEach loops');
var isMappable = function (toCheck: any) {
return toCheck && (toCheck.constructor === Array || toCheck.toJS && toCheck.toJS().constructor === Array);
};
var projectSingle = function (from: TFromType) {
let result: { [key: string]: any } = (this.to({}) as any).toJS();
let source: { [key: string]: any } = _.clone((this.from(from) as any).toJS());
for (const fromProperty in source) {
const registeredProjections = this._projections.get(fromProperty);
var sourceProperty = source[fromProperty];
// ### Attempt to find a specific projection definition:
try {
if (registeredProjections) {
registeredProjections.forEach((projections: Immutable.List<ConditionalFunction>, toProperty: string) => {
projections.forEach((projection: ConditionalFunction) => {
if (result.hasOwnProperty(toProperty)) {
if (!projection.when || (projection.when && projection.when(source))) {
result[toProperty] = sourceProperty == null? null: _.clone(projection.use(sourceProperty));
throw HasBeenProjected;
}
}
});
});
}
// ### Attempt pattern-based automapping:
this._mappings.forEach((mapping: (x: string) => string) => {
const mappedProperty = mapping(fromProperty);
if (result.hasOwnProperty(mappedProperty)) {
result[mappedProperty] = sourceProperty;
throw HasBeenProjected;
}
});
// ### Attempt direct mapping:
if (result.hasOwnProperty(fromProperty)) {
result[fromProperty] = sourceProperty;
}
} catch (e) {
if (e !== HasBeenProjected) {
throw e;
}
}
}
return this.to(result);
};
return (from: TFromType | TFromType[] | Immutable.List<TFromType>): TResultType | Immutable.List<TResultType> => {
return isMappable(from)
? Immutable.List<TResultType>((from as any).map((x: any) => projectSingle.call(this, x)))
: projectSingle.call(this, from);
};
}
}
export class ProjectionBuilder {
static defineProjection<TFromType, TResultType>(
from: (o: any) => TFromType,
to: (o: any) => TResultType): ProjectionStage<TFromType, TResultType> {
return new ProjectionStageImpl<TFromType, TResultType>(from, to);
}
}
|
a1093abc9db6eb1e7fcb74f6b932756e1f720d48
|
TypeScript
|
vuepress-theme-hope/vuepress-theme-hope
|
/packages/theme/src/shared/options/feature/options.ts
| 2.578125
| 3
|
import type {
BlogLocaleConfig,
BlogLocaleData,
BlogLocaleOptions,
PaginationLocaleData,
} from "./blog.js";
import type {
EncryptConfig,
EncryptLocaleData,
EncryptOptions,
} from "./encrypt.js";
export interface FeatureLocaleData {
/**
* Blog related i18n config
*
* 博客相关多语言配置
*/
blogLocales: BlogLocaleData;
/**
* Pagination related i18n config
*
* 分页相关多语言配置
*/
paginationLocales: PaginationLocaleData;
/**
* Encrypt related i18n config
*
* 加密相关多语言配置
*/
encryptLocales: EncryptLocaleData;
}
export interface FeatureLocaleOptions {
/**
* Blog feature options
*
* 博客功能配置
*/
blog?: BlogLocaleOptions;
}
export interface FeatureLocaleConfig {
blog?: BlogLocaleConfig;
}
/**
* @kind root
*/
export interface FeatureOptions {
/**
* Encrypt config
*
* 加密配置
*/
encrypt?: EncryptOptions;
/**
* Whether enable hotReload for features that requires app to restart
*
* @description These features includes blog support and structure sidebar feature
*
* 是否为需要重启整个 app 的功能启用热更新
*
* @description 这些功能包括博客支持和结构侧边栏功能
*
* @default app.env.isDebug
*/
hotReload?: boolean;
}
// for config size consideration, blog options can be held in root and merged in client side
export interface FeatureConfig extends FeatureLocaleConfig {
/**
* Encrypt config
*
* 加密配置
*/
encrypt: EncryptConfig;
}
|
27decb40020949662612ef132a17f5160d08240a
|
TypeScript
|
zengyujiao/react
|
/day-4/weui-app/src/stores/index.ts
| 3.421875
| 3
|
import { createStore } from 'redux'
interface stateType{
// 如果在这里定义了类型,那么必须传入什么类型进来,在这里规定了类型,是比较严谨的一种写法
name: string
age: Number | boolean
searchText: string
}
interface actionType{
type: string
searchText: string
}
const store:object = createStore((state: stateType = {
name: 'react',
age: 18,
searchText:''
}, action: actionType) => {
switch (action.type) {
case 'INCRMENT':
// 在stateType里面定义了什么类型,那么这里只能是定义好的类型,如果用其它类型,那么会报错
return {
...state,
name:'redux'
}
case 'SEARCHTEXT':
return {
...state,
searchText:action.searchText
}
default:
return state
}
})
export default store
|
518b2bf836a31e3f1d3ef60483697bd4ba9f36ab
|
TypeScript
|
DmitriyMenshayev/TestProject1
|
/src/index.ts
| 2.859375
| 3
|
//for questions and suggestions you can contact me:
// dmitry.menshaev@gmail.com
import * as PIXI from 'pixi.js';
//Importing PIXI in global scope with PIXI is OK.
//For this simpile project pollutting global scope is OK too,
//but for large or giant AAA projects it's usually a bad idea to
//pollute the global scope, so different methods can be used:
//IIFE (classic style), namespaces (just JS objects), typescript namespaces, or ES6 block scopes.
//For bigger project namespace should be used with object "app" (PIXI.Application)
//and other variables that should be in the same scope
(function dontPolluteTheGlobalScope(): void{
//particles libarary for test 3
const particles = require('pixi-particles');
//load 274918 english words for test 2,
//more fun than random string from functions
//like Math.random().toString(36).substring(2, 8),
//can reduce performance though :(
//Also excuce me if unacceptable words are shown.
const englishWords: string[] = require('an-array-of-english-words');
//Interface to create dynamic objects.
//Interfaces for every object to save
//from typos and Development Environment support
//on property types are possible, but I will
//keep everything simple for now.
interface LooseObject {
[key: string]: any
}
// trying not to pollute global scope,
// and also get acess to local scopes and etc.
const controlObject: LooseObject = {};
const settings = {
width: 1080, //"Instagram" aspect ratio, just square. Works best for
height: 1080, //Desktop + mobile (portrait + landscape) kind of responsive elements
backgroundColor: 0xffffff,
//"roundPixels: true" gives so much performance (probably x2) and cons are almost not noticable,
// but I won't use it for now
};
const app = new PIXI.Application(settings);
document.body.appendChild(app.view);
app.loader
//could be imported as atlas also, but it is simpiler to edit/remove/add everything
//one by one while developing
.add('card', 'assets/card.png')
//some random pictures from opengameart.org and others websites,
//public domain ot other free licenses
.add('coin', 'assets/coin.png')
.add('ball', 'assets/ball.png')
.add('van', 'assets/van.png')
.add('house', 'assets/house.png')
//Fire particles
.add('particle', 'assets/particle.png')
.add('fire', 'assets/fire.png')
.load((loader, resources) => {
//Seperation of concerens: creating objects to control respective scenes.
//everything is accessible, but no pollution of scope
//All methods and variables will be inside.
//main container, needed for game to be responsive
const main: LooseObject = {
scene: new PIXI.Container(),
//track the current scene in main game container
currentScene: "menu"
};
app.stage.addChild(main.scene);
//Container for buttons that tied to screen
const UI: LooseObject = {
scene: new PIXI.Container()
};
app.stage.addChild(UI.scene);
const menu: LooseObject = {
scene: new PIXI.Container(),
//help us identify scene
name: "menu"
};
main.scene.addChild(menu.scene);
const testOne: LooseObject = {
scene: new PIXI.Container(),
name: "testOne"
};
testOne.scene.visible = false;
main.scene.addChild(testOne.scene);
const testTwo: LooseObject = {
scene: new PIXI.Container(),
name: "testTwo"
};
testTwo.scene.visible = false;
main.scene.addChild(testTwo.scene);
const testThree: LooseObject = {
scene: new PIXI.Container(),
name: "testThree"
};
testThree.scene.visible = false;
main.scene.addChild(testThree.scene);
//BACK TO MENU BUTTON
//Local variable could be create to hold "PIXI.Text" object and then
//added to "UI" object to make names simplier, but for small files it
//is probably more understandable this way, also most of the paramaters
//are well known PIXI objects/methods/parameters.
UI.backButton = new PIXI.Text("Back to Menu");
UI.backButton.anchor.set(0, 1);
UI.backButton.position.set(20, settings.height - 20);
UI.backButton.interactive = true;
UI.backButton.buttonMode = true;
UI.backButton.on("pointerdown", () => {
switchScenes(menu);
});
UI.backButton.visible = false;
UI.scene.addChild(UI.backButton);
//FPS METER
UI.FPSMeter = new PIXI.Text("");
UI.FPSMeter.anchor.set(1, 0);
UI.FPSMeter.position.set(settings.width - 20, 20);
UI.scene.addChild(UI.FPSMeter);
app.ticker.add((delta) => {
UI.FPSMeter.text = (60/delta).toFixed(0);
});
//MENU SCENE
menu.testOneButton = new PIXI.Text("Test One");
menu.testOneButton.style.fontSize = 72;
menu.testOneButton.anchor.set(0.5, 0.5);
menu.testOneButton.position.set(540, 270);
menu.testOneButton.interactive = true;
menu.testOneButton.buttonMode = true;
menu.testOneButton.on("pointerdown", () => {
switchScenes(testOne);
});
menu.scene.addChild(menu.testOneButton);
menu.testTwoButton = new PIXI.Text("Test Two");
menu.testTwoButton.style.fontSize = 72;
menu.testTwoButton.anchor.set(0.5, 0.5);
menu.testTwoButton.position.set(540, 540);
menu.testTwoButton.interactive = true;
menu.testTwoButton.buttonMode = true;
menu.testTwoButton.on("pointerdown", () => {
switchScenes(testTwo);
});
menu.scene.addChild(menu.testTwoButton);
menu.testThreeButton = new PIXI.Text("Test Three");
menu.testThreeButton.style.fontSize = 72;
menu.testThreeButton.anchor.set(0.5, 0.5);
menu.testThreeButton.position.set(540, 810);
menu.testThreeButton.interactive = true;
menu.testThreeButton.buttonMode = true;
menu.testThreeButton.on("pointerdown", () => {
switchScenes(testThree);
});
menu.scene.addChild(menu.testThreeButton);
//SCENE SWITCHER
function switchScenes(targetScene: LooseObject): void {
if (targetScene.name === "menu"){
//clean test one after completion. Could be done with callbacks,
//but because we know exactly which scene we are dealing with it is OK
if (main.currentScene === "testOne"){
testOne.scene.visible = false;
if (testOne.numberOfCardsMoving === 0){
testOne.clear();
}
} else {
testTwo.scene.visible = false;
testThree.scene.visible = false;
}
UI.backButton.visible = false;
menu.scene.visible = true;
} else {
menu.scene.visible = false;
UI.backButton.visible = true;
targetScene.scene.visible = true;
}
main.currentScene = targetScene.name;
}
//TEST 1
//create start button
testOne.startButton = new PIXI.Text("START"); //use default style
testOne.startButton.style.fontSize = 72;
testOne.startButton.anchor.set(0.5, 0.5);
testOne.startButton.position.set(540, 108);
testOne.startButton.interactive = true;
testOne.startButton.buttonMode = true;
testOne.scene.addChild(testOne.startButton);
//Create deck
testOne.deck = new PIXI.Container();
testOne.scene.addChild(testOne.deck);
testOne.cards = [];
testOne.startX = 100;
for (let i = 0; i < 144; i++){
let card: PIXI.Sprite = new PIXI.Sprite(resources.card.texture);
card.position.set(testOne.startX, 300);
testOne.deck.addChild(card);
testOne.cards[i] = card;
testOne.startX += 5;
}
testOne.numberOfCardsMoving = 0;
//Setup movement
testOne.targetX = 100;
//pass starting timer in case of lag
testOne.moveCard = function(card: PIXI.Sprite, startingTimer: number): void {
//Use control object to pass context, use timer and remove function from the ticker later
let controlObject = {
timer: startingTimer,
func: animation,
card: card,
targetX: testOne.targetX,
startingX: card.x
}
app.ticker.add(controlObject.func, controlObject);
function animation(delta: number): void{
this.timer += delta;
//calculate card's new position
this.card.x = this.startingX + (this.targetX - this.startingX)*(this.timer/120);
this.card.y = 300 + 300*(this.timer/120);
//1 sec == 60 frames in PIXI
//Fix Z-order once, use undefined field because of performance
if (this.timer > 60 && !this.zOrderChanged){
testOne.deck.removeChild(this.card);
testOne.deck.addChild(this.card);
this.zOrderChanged = true;
}
if (this.timer > 120){
this.card.position.set(this.targetX, 600);
testOne.numberOfCardsMoving--;
app.ticker.remove(this.func, this);
}
//clean itself if scene is closed
if (!testOne.scene.visible) {
app.ticker.remove(this.func, this);
testOne.numberOfCardsMoving--;
if (testOne.numberOfCardsMoving === 0){
testOne.clear();
}
}
}
}
testOne.moveCards = function(): void{
testOne.startButton.visible = false;
let controlObject = {
timer: 0,
func: animation,
currentIndex: 143
}
app.ticker.add(controlObject.func, controlObject);
function animation(delta: number): void{
this.timer += delta;
//calculate card's new position
if (this.currentIndex >= 0){
if (this.timer > 60){
this.timer -= 60;
testOne.moveCard(testOne.cards[this.currentIndex], this.timer);
testOne.targetX += 5;
this.currentIndex--;
testOne.numberOfCardsMoving++;
}
} else {
app.ticker.remove(this.func, this);
}
if (!testOne.scene.visible) {
app.ticker.remove(this.func, this);
if (testOne.numberOfCardsMoving === 0){
testOne.clear();
}
}
}
}
testOne.startButton.on("pointerdown", testOne.moveCards);
testOne.clear = function():void {
testOne.startButton.visible = true;
testOne.startX = 100;
testOne.targetX = 100;
for (let i = 0; i < 144; i++){
let card = testOne.cards[i];
//reset zIndex of the card
testOne.scene.removeChild(card);
testOne.scene.addChild(card);
card.position.set(testOne.startX, 300);
testOne.startX += 5;
}
}
//TEST 2
//Array of images for test 2
testTwo.images = [
resources.card.texture,
resources.coin.texture,
resources.ball.texture,
resources.van.texture,
resources.house.texture
];
testTwo.startButton = new PIXI.Text("START");
testTwo.startButton.style.fontSize = 72;
testTwo.startButton.anchor.set(0.5, 0.5);
testTwo.startButton.position.set(540, 108);
testTwo.startButton.interactive = true;
testTwo.startButton.buttonMode = true;
testTwo.scene.addChild(testTwo.startButton);
testTwo.spritesContainer = new PIXI.Container();
testTwo.spritesContainer.position.set(540, 540);
testTwo.scene.addChild(testTwo.spritesContainer);
testTwo.start = function(): void {
testTwo.startButton.visible = false;
let controlObject = {
timer: 0,
func: animation
}
app.ticker.add(controlObject.func, controlObject);
function animation(delta: number): void{
this.timer += delta;
//calculate card's new position
if (this.timer > 120){
this.timer = 0;
//remove elements from previous iteration starting from last
let lastIndex: number = testTwo.spritesContainer.children.length - 1;
for (let i = lastIndex; i >= 0; i--){
testTwo.spritesContainer.removeChildAt(i);
}
//generate new elements
let elementsWidth: number = 0; //cummulative width of all elements
for (let i = 0; i < 3; i++){
//union type
let element: PIXI.Text | PIXI.Sprite;
//choose between text and image,
//Math.random() returns a value between 0 and 0.999999... ,
//so exact 50/50 are ranges [0, 0.5) and [0.5, 1)
if (Math.random() < 0.5){ //element is Text
//index of random word
let currentIndex: number = Math.floor(Math.random()*englishWords.length);
//Random word
let elementString: string = englishWords[currentIndex];
element = new PIXI.Text(elementString);
//random font size, from 10 to 100
let fontSize: number = (Math.random()*90) + 10;
//Check type, just for TypeScript compiler
//could be omited and type of element set to any
//for the sake of simplicity for
//experienced developer and performance.
//Otherwise "Sprite" has no "style".
if (element instanceof PIXI.Text){
//change fontSize
element.style.fontSize = fontSize;
}
} else { //element is Sprite
//index of random image
let currentIndex: number = Math.floor(Math.random()*testTwo.images.length);
element = new PIXI.Sprite(testTwo.images[currentIndex]);
}
element.anchor.set(0, 0.5);
element.x = elementsWidth;
//add 10 pixels space between elements
elementsWidth += (element.width + 10);
testTwo.spritesContainer.addChild(element);
}
//center the container (PIXI.Container doesn't have "anchor" property :P)
testTwo.spritesContainer.pivot.set(testTwo.spritesContainer.width/2, testTwo.spritesContainer.height/2);
}
//clean itself if scene is closed
if (!testTwo.scene.visible) {
let lastIndex: number = testTwo.spritesContainer.children.length - 1;
for (let i = lastIndex; i >= 0; i--){
testTwo.spritesContainer.removeChildAt(i);
}
testTwo.startButton.visible = true;
app.ticker.remove(this.func, this);
}
}
}
testTwo.startButton.on("pointerdown", testTwo.start);
//TEST 3
//Actually more than 10 particles :(
//I found free fire art and made fire than consisted
//of 10 or less sprites, but it didn't look really well.
//According to my understanding if particles are used
//there are a lot of simple sprites. If you use better images
//it's better to just animate it with Spine or make animation from frames
testThree.startButton = new PIXI.Text("START");
testThree.startButton.style.fontSize = 72;
testThree.startButton.anchor.set(0.5, 0.5);
testThree.startButton.position.set(540, 108);
testThree.startButton.interactive = true;
testThree.startButton.buttonMode = true;
testThree.scene.addChild(testThree.startButton);
testThree.particlesContainer = new PIXI.Container();
testThree.particlesContainer.position.set(540, 540);
testThree.particlesContainer.scale.set(3, 3);
testThree.scene.addChild(testThree.particlesContainer);
testThree.emitterConfig = {
alpha: {
start: 0.62,
end: 0
},
scale: {
start: 0.25,
end: 0.75,
minimumScaleMultiplier: 1
},
color: {
start: '#fff191',
end: '#ff622c'
},
speed: {
start: 50,
end: 150,
minimumSpeedMultiplier: 1
},
acceleration: {
x: 0,
y: 0
},
maxSpeed: 0,
startRotation: {
min: 255,
max: 280
},
noRotation: false,
rotationSpeed: {
min: 50,
max: 50
},
lifetime: {
min: 0.1,
max: 0.75
},
blendMode: 'normal',
frequency: 0.001,
emitterLifetime: -1,
maxParticles: 1000,
pos: {
x: 0,
y: 0
},
addAtBack: false,
spawnType: 'circle',
spawnCircle: {
x: 0,
y: 0,
r: 10
}
};
testThree.fireTextures = [resources.particle.texture, resources.fire.texture];
testThree.start = function(): void {
testThree.startButton.visible = false;
testThree.emitter = new particles.Emitter(
testThree.particlesContainer,
testThree.fireTextures,
testThree.emitterConfig
);
let controlObject = {
timer: 0,
func: animation
};
// Start emitting
testThree.emitter.emit = true;
app.ticker.add(controlObject.func, controlObject);
function animation(delta: number): void{
this.timer += delta;
//calculate card's new position
testThree.emitter.update(delta/60);
//clean itself if scene is closed
if (!testThree.scene.visible) {
app.ticker.remove(this.func, this);
testThree.emitter.destroy();
testThree.startButton.visible = true;
// stop emitting
}
}
}
testThree.startButton.on("pointerdown", testThree.start);
//UTILITY FUNCTIONS
//resize the window responsively
controlObject.onResize = function():void {
//resize the canvas
let windowWidth: number = window.innerWidth;
let windowHeight: number = window.innerHeight;
let newScale: number;
if (windowHeight > windowWidth){
main.scene.position.set(0, (windowHeight-windowWidth)/2);
newScale = windowWidth/1080;
} else {
main.scene.position.set((windowWidth-windowHeight)/2, 0);
newScale = windowHeight/1080;
}
app.renderer.resize(windowWidth, windowHeight);
main.scene.scale.set(newScale, newScale);
//resize and update position of the some elements
UI.FPSMeter.position.set(windowWidth - 20, 20);
UI.backButton.position.set(20, windowHeight - 20);
}
//add resize event
window.addEventListener('resize', controlObject.onResize);
//call once to init the game
controlObject.onResize();
});
//add key "Enter" toggle fullscreen event
document.addEventListener('keydown', onKeyDown);
function onKeyDown(key: any){
//press "Enter" to go fullscreen:
if (key.keyCode === 13){
// toggle fullscreen when the game is started
document.documentElement.requestFullscreen();
controlObject.onResize();
}
}
})();
//The end, thank you! :)
|
bb60aeafad67f3feb9a73ccca13b34c5960fe2e4
|
TypeScript
|
ushpar71/ticketing
|
/auth/src/astro/nakshatra.ts
| 2.671875
| 3
|
const nakshatra = require('./json/nakshatra.json');
const division = 27;
const duration = 360 / division;
//-----
export const getNakshatras = () => {
return nakshatra;
};
//-----
export const getNNakshatra = (id: number) => {
id === 0 ? (id = 1) : id;
return getNNNakshatra(id);
};
//-----
export const getNNNakshatra = (startId: number = 0, endId: number = 0) => {
var num = startId + endId;
while (num > division) {
num -= division;
}
while (num < 1) {
num += division;
}
return nakshatra[num];
};
//-----
export const getDNakshatra = (startDeg: number = 0, nakshatras: number = 0) => {
var num = Math.round(startDeg / duration) + nakshatras;
while (num > division) {
num -= division;
}
while (num < 1) {
num += division;
}
return nakshatra[num];
};
|
a4fb256662a68b2d86eddf82eaa356bc8d4874ac
|
TypeScript
|
alexandresantosm/typescript
|
/src/aula_07/aula07.ts
| 3.640625
| 4
|
/*Type assertions
- É um recurso de casting, ou seja, de conversão de tipo
*/
const teste1: any = "Isso é uma string";
alert((<string>teste1).length); //sintaxe utilizando o operador diamante
/*
Sintaxe utilizando o operador 'as'.
Obs.: quando utilizar TypeScript com JSX, muito comum no React, a única sintaxe aceita é utilizando o operador "as".
*/
alert((teste1 as string).length);
|
ee24bfcf1968c322fb8230e3d376cdfefef1f5f7
|
TypeScript
|
nadipalli-swetha/news-application
|
/newsApplicationF/src/app/home/home.component.ts
| 2.640625
| 3
|
import { Component, OnInit } from '@angular/core';
import { NewsService} from "../services/news.service";
import { News} from "../models/News";
import { NewsProvider} from "../interfaces/news-provider";
import { HttpResponse} from "@angular/common/http";
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit, NewsProvider {
// HttpResponse from the backend of type <News[]>
newsResponse: HttpResponse<News[]> = new HttpResponse<News[]>();
countries = ["us", "uk"];
selectedCountry: string = this.countries[1];
isInfoModalHidden: boolean = true;
private pageSize = 6; // Determines the amount of news the API should retrieve.
basic: boolean;
newsArticleInModal: any = {
webTitle: String,
bodyText: String
};
isUSAFlagHidden: boolean = true;
isNPaperIconHidden: boolean = true;
constructor(private service: NewsService) {}
ngOnInit() {
this.displaySmallIcons(this.selectedCountry);
this.isInfoModalHidden = false;
this.getNews(this.selectedCountry, this.pageSize);
}
/*
Changes the location of the News url.
*/
changeCountryNews(location) {
this.selectedCountry = location;
this.displaySmallIcons(this.selectedCountry);
this.getNews(this.selectedCountry, this.pageSize);
this.isInfoModalHidden = false;
}
/*
Gets any kind of News (UK news) to the "Home" view.
*/
getNews(location, pageSize) {
this.service.getGeneralNews(location, pageSize).subscribe((articleNews: HttpResponse<News[]>) => {
this.newsResponse = articleNews;
// Modify the received date.
this.newsResponse.body.forEach(function (article) {
let dateObject: Date = new Date(article.webPublicationDate);
article.webPublicationDate = dateObject.toDateString();
});
});
}
/*
To redirect to the real website of the News.
*/
goToNewsSite(url) {
window.location.href = url;
}
/*
Increments the amount of News cards that are on the page by 3.
*/
incrementNewsOnPage() {
this.getNews( this.selectedCountry,this.pageSize += 3);
}
/*
Shows the modal that has information about a News.
*/
public showModal(card: News) {
this.newsArticleInModal.bodyText = card.fields.bodyText;
this.newsArticleInModal.webTitle = card.webTitle;
this.basic = true;
}
private displaySmallIcons(location) {
this.selectedCountry = location;
if (this.selectedCountry == 'us') {
this.isUSAFlagHidden = false;
this.isNPaperIconHidden = true;
} else if (this.selectedCountry == 'uk') {
this.isUSAFlagHidden = true;
this.isNPaperIconHidden = false;
}
}
}
|
e791f6897f213a7d46057df7ba9dd836a52b94cc
|
TypeScript
|
cesar07hoyos03/digistore
|
/src/app/store/reducers/ui.reducer.ts
| 3.109375
| 3
|
import { START_PLAYING, STOP_PLAYING, UiActions } from '../actions/ui.actions';
import { TIME_OUT_GAME } from '../actions';
export interface UiState {
isPlaying: boolean;
timeOutGame: boolean;
}
export const initialState: UiState = {
isPlaying: false,
timeOutGame: false,
};
/**
* Reducer to handle the UI states in the application
* @param {UiState} state
* @param {UiActions} action
* @returns {any}
*/
export function reducer(state = initialState, action: UiActions): UiState {
switch (action.type) {
case START_PLAYING:
return {
isPlaying: true,
timeOutGame: false
};
case STOP_PLAYING:
return {
isPlaying: false,
timeOutGame: false
};
case TIME_OUT_GAME:
return {
...state,
timeOutGame: true
};
default:
return state;
}
}
// Selectors
const getIsPlaying = (state: UiState) => state.isPlaying;
|
75be8a683974a2b8c36c4e6bcf8c51f292f0af34
|
TypeScript
|
DkReactNative/TheBox
|
/utils/functions.ts
| 2.5625
| 3
|
import AsyncStorage from '@react-native-community/async-storage';
import CameraRoll, {PhotoIdentifier} from '@react-native-community/cameraroll';
import {NativeTouchEvent} from 'react-native';
import {useDispatch} from 'react-redux';
import {
changeSortConditionAndNumColumns,
photoChunk,
sortCondition,
sortedPhotos,
} from '../types/interfaces';
import {Constant} from './constants';
export const sortPhotos = (
photos: Array<PhotoIdentifier>,
sortCondition: 'day' | 'month',
) => {
let result: any = {};
let timestamps = photos
.map((photo) => photo.node.timestamp * 1000)
.sort((a, b) => b - a);
let timestamps_str = timestamps.map((timestamp) => timestamp.toString());
if (sortCondition == 'day') {
for (let TS of timestamps_str) {
result[timestampToDate(+TS, 'day')] = [];
}
for (let photo of photos) {
result[timestampToDate(photo.node.timestamp * 1000, 'day')].push(photo);
}
return result;
} else if (sortCondition == 'month') {
for (let TS of timestamps_str) {
result[timestampToDate(+TS, 'month')] = [];
}
for (let photo of photos) {
result[timestampToDate(photo.node.timestamp * 1000, 'month')].push(photo);
}
return result;
}
return result;
};
// export const splitDate = (date: string) => {
// let
// }
export const timestampToDate = (
timestamp: number,
condition: 'day' | 'month',
) => {
let date = new Date(timestamp);
let month = date.getUTCMonth() + 1; //months from 1-12
let day = date.getUTCDate();
let year = date.getUTCFullYear();
let result;
if (condition == 'day') {
result = new Date(year, month, day).toString().split(year.toString())[0];
} else if (condition == 'month') {
const monthNames = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];
result = monthNames[new Date(year, month).getMonth()];
}
if (result) {
return result;
} else {
return 'unknown';
}
};
export const getStoragePhotos = (per: boolean, numberOfPhotos: number) => {
if (per) {
let photos = CameraRoll.getPhotos({
first: numberOfPhotos,
assetType: 'All',
});
return photos;
}
};
export const pow2abs = (a: number, b: number) => {
return Math.pow(Math.abs(a - b), 2);
};
export const getDistance = (x1: number, y1: number, x2: number, y2: number) => {
let distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
return distance;
};
export const findDiameter = (width: number, height: number) => {
let pow2 = Math.pow(width, 2) + Math.pow(height, 2);
return Math.sqrt(pow2);
};
export const changeSortCondition: changeSortConditionAndNumColumns = (
sortCondition,
pinchOrZoom,
numCols,
) => {
let result = {
sortCondition: 'day',
numColumns: 2,
};
if (pinchOrZoom === 'zoom') {
if (sortCondition === 'day') {
if (numCols === 2) {
console.log('A');
result = {...result, sortCondition: 'day', numColumns: 2};
} else if (numCols === 3) {
console.log('B');
result = {...result, sortCondition: 'day', numColumns: 2};
}
} else if (sortCondition === 'month') {
console.log('C');
result = {...result, sortCondition: 'day', numColumns: 3};
}
}
if (pinchOrZoom === 'pinch') {
if (sortCondition === 'day') {
if (numCols === 2) {
console.log('D');
result = {...result, sortCondition: 'day', numColumns: 3};
} else if (numCols === 3) {
console.log('E');
result = {...result, sortCondition: 'month', numColumns: 4};
}
} else if (sortCondition === 'month') {
console.log('F');
result = {...result, sortCondition: 'month', numColumns: 4};
}
}
return result;
};
export const opacityTransition = (
sortCondition: sortCondition,
numColumns: 2 | 3 | 4,
pinchOrZoom: 'pinch' | 'zoom' | undefined,
) => {
let result: any = {
day: {
col: {
2: [0, 0],
3: [0, 0],
},
},
month: {
col: {
4: [0, 0],
},
},
};
if (sortCondition === 'day') {
if (numColumns === 2) {
result = {
...result,
day: {...result.day, col: {...result.day.col, 2: [1, 0]}},
};
} else if (numColumns === 3) {
result = {
...result,
day: {...result.day, col: {...result.day.col, 3: [1, 0]}},
};
}
} else if (sortCondition === 'month') {
if (numColumns === 4) {
result = {
...result,
month: {...result.month, col: {...result.month.col, 4: [1, 0]}},
};
}
}
if (pinchOrZoom === undefined) {
return result;
}
let newSortCondition = changeSortCondition(
sortCondition,
pinchOrZoom,
numColumns,
).sortCondition;
let newNumColumns = changeSortCondition(
sortCondition,
pinchOrZoom,
numColumns,
).numColumns;
console.log('newNumColumns', newNumColumns);
console.log('newSortCondition', newSortCondition);
if (newSortCondition === 'day') {
if (newNumColumns === 2) {
result = {
...result,
day: {...result.day, col: {...result.day.col, 2: [0, 1]}},
};
} else if (newNumColumns === 3) {
result = {
...result,
day: {...result.day, col: {...result.day.col, 3: [0, 1]}},
};
}
} else if (newSortCondition === 'month') {
if (newNumColumns === 4) {
result = {
...result,
month: {...result.month, col: {...result.month.col, 4: [0, 1]}},
};
}
}
return result;
};
export const test = (photos: any) => {
let result: Array<photoChunk> = [];
for (let sortedPhotosDate of Object.keys(photos)) {
let _result = {
date: sortedPhotosDate,
data: photos[sortedPhotosDate],
};
result.push(_result);
}
return result;
};
export const storeData = async (key: string, value: any) => {
const dispatch = useDispatch();
try {
await AsyncStorage.setItem(key, value);
} catch {
dispatch({
type: Constant.actionTypes.error.setError,
payload: 'setting data from local storage failed',
});
}
};
export const getData = async (key: string) => {
const dispatch = useDispatch();
try {
let value = await AsyncStorage.getItem(key);
return value;
} catch {
dispatch({
type: Constant.actionTypes.error.setError,
payload: 'getting data from local storage failed',
});
}
};
|
2e5f3e45f0f9f8585a385ed9a0a92574d845de97
|
TypeScript
|
TobiObeck/xstate
|
/packages/xstate-react/src/utils.ts
| 3
| 3
|
import {
AnyInterpreter,
AnyState,
Interpreter,
InterpreterStatus
} from 'xstate';
export function partition<T, A extends T, B extends T>(
items: T[],
predicate: (item: T) => item is A
): [A[], B[]] {
const [truthy, falsy] = [[], []] as [A[], B[]];
for (const item of items) {
if (predicate(item)) {
truthy.push(item);
} else {
falsy.push(item as B);
}
}
return [truthy, falsy];
}
export function getServiceSnapshot<
TService extends Interpreter<any, any, any, any>
>(service: TService): TService['state'] {
return service.status !== 0
? service.getSnapshot()
: service.machine.initialState;
}
// From https://github.com/reduxjs/react-redux/blob/master/src/utils/shallowEqual.ts
function is(x: unknown, y: unknown) {
if (x === y) {
return x !== 0 || y !== 0 || 1 / x === 1 / y;
} else {
return x !== x && y !== y;
}
}
export function shallowEqual(objA: any, objB: any) {
if (is(objA, objB)) return true;
if (
typeof objA !== 'object' ||
objA === null ||
typeof objB !== 'object' ||
objB === null
) {
return false;
}
const keysA = Object.keys(objA);
const keysB = Object.keys(objB);
if (keysA.length !== keysB.length) return false;
for (let i = 0; i < keysA.length; i++) {
if (
!Object.prototype.hasOwnProperty.call(objB, keysA[i]) ||
!is(objA[keysA[i]], objB[keysA[i]])
) {
return false;
}
}
return true;
}
export function isService(
actor: any
): actor is Interpreter<any, any, any, any> {
return 'state' in actor && 'machine' in actor;
}
export function isInterpreterStateEqual(
service: AnyInterpreter,
prevState: AnyState,
nextState: AnyState
) {
if (service.status === InterpreterStatus.NotStarted) {
return true;
}
// Only change the current state if:
// - the incoming state is the "live" initial state (since it might have new actors)
// - OR the incoming state actually changed.
//
// The "live" initial state will have .changed === undefined.
const initialStateChanged =
nextState.changed === undefined &&
(Object.keys(nextState.children).length > 0 ||
typeof prevState.changed === 'boolean');
return !(nextState.changed || initialStateChanged);
}
|
9e9e776b49ea6fd108b6e9c7c9c2c29c8aa06d09
|
TypeScript
|
rxdi/deploy
|
/src/app/services/time/time.service.ts
| 2.703125
| 3
|
import { Service } from '@rxdi/core';
@Service()
export class TimeService {
calculateTime(time: string) {
const date = new Date(time);
return {
day: this.getDay(date),
month: this.getDay(date),
year: this.getDay(date),
};
}
getDay(date: Date): number {
return date.getUTCDate();
}
getMonth(date: Date): number {
return date.getUTCDate();
}
getYear(date: Date): number {
return date.getUTCFullYear();
}
}
|
0945e4d53e454cdf74a18e26c1016e6784d9e1c8
|
TypeScript
|
nhat-phan/najs-eloquent
|
/dist/lib/definitions/model/IModel.d.ts
| 2.578125
| 3
|
/// <reference path="../../contracts/Driver.d.ts" />
/// <reference path="../utils/IClassSetting.d.ts" />
/// <reference path="IModelRecord.d.ts" />
/// <reference path="IModelFillable.d.ts" />
/// <reference path="IModelSerialization.d.ts" />
/// <reference path="IModelTimestamps.d.ts" />
/// <reference path="IModelSoftDeletes.d.ts" />
/// <reference path="IModelRelation.d.ts" />
/// <reference path="../relations/IRelationDataBucket.d.ts" />
/// <reference path="../query-builders/IQueryBuilder.d.ts" />
declare namespace NajsEloquent.Model {
type ModelDefinition<T extends IModel = IModel> = string | {
new (): T;
};
interface IModelSharedMetadata {
features: {
[name in string]: boolean;
};
/**
* The model's relation definitions.
*/
relationDefinitions: NajsEloquent.Relation.RelationDefinitions;
}
interface IModelInternalData {
/**
* The model's class setting instance.
*/
classSettings?: NajsEloquent.Util.IClassSetting;
/**
* The model's internal event emitter.
*/
eventEmitter?: Najs.Contracts.Event.AsyncEventEmitter;
/**
* The model's relation data bucket.
*/
relationDataBucket: NajsEloquent.Relation.IRelationDataBucket;
/**
* The model's relations data.
*/
relations: {
[name in string]: NajsEloquent.Relation.IRelationData<any>;
};
/**
* The model's overridden data.
*/
overridden?: {
fillable?: boolean;
guarded?: boolean;
visible?: boolean;
hidden?: boolean;
};
}
class IModel {
/**
* Contains metadata data which shared for all model instances
*/
protected readonly sharedMetadata: IModelSharedMetadata;
/**
* The driver associated with the model.
*/
protected driver: Najs.Contracts.Eloquent.Driver;
/**
* The model's attributes.
*/
protected attributes: object;
/**
* The model's internal data
*/
protected internalData: IModelInternalData;
}
interface IModel extends IModelRecord, IModelEvent, IModelFillable, IModelSerialization, IModelTimestamps, IModelSoftDeletes, IModelRelation {
/**
* Primary key of the model
*/
id?: any;
/**
* Get driver which is used by the model.
*/
getDriver<T>(): Najs.Contracts.Eloquent.Driver<T>;
/**
* Get model name.
*/
getModelName(): string;
/**
* Start new query of model.
*/
newQuery(): QueryBuilder.IQueryBuilder<this>;
/**
* Start new query of model with name.
*/
newQuery(name: string): QueryBuilder.IQueryBuilder<this>;
}
type ModelInternal<T = any> = IModel & {
sharedMetadata: IModelSharedMetadata;
internalData: IModelInternalData;
driver: Najs.Contracts.Eloquent.Driver<T>;
attributes: T;
};
}
|
1da2a5006e9933d82941da6cf209c32c7f96a337
|
TypeScript
|
alu0101235516/ull-esit-inf-dsi-20-21-prct03-static-types-functions-Espinette
|
/src/ejercicio-7.ts
| 3.609375
| 4
|
// Ejercicio 7 - El siguiente número
function nextNumber(numero: number) {
let numString: string = numero.toFixed();
let aux: string = "";
const tam: number = numString.length;
for (let i: number = tam-1; i > -1; i--) {
for (let j: number = 0; j < tam; j++) {
if (i-j > 0) {
if (parseInt(numString.charAt(i-j)) >
parseInt(numString.charAt(i-j-1))) {
aux = numString.charAt(i-j);
numString = numString.substr(0, i-j-1) + aux +
numString.charAt(i-j-1) + numString.substr(i-j+1, tam);
return parseInt(numString);
} else {
aux = numString.charAt(i-j);
numString = numString.substr(0, i-j-1) + aux +
numString.charAt(i-j-1) + numString.substr(i-j+1, tam);
}
}
}
numString = numero.toFixed();
}
return -1;
}
console.log(`Siguiente numero a 10500: ${nextNumber(10500)}`);
console.log(`Siguiente numero a 513: ${nextNumber(513)}`);
console.log(`Siguiente numero a 2017: ${nextNumber(2017)}`);
console.log(`Siguiente numero a 9: ${nextNumber(9)}`);
console.log(`Siguiente numero a 111: ${nextNumber(111)}`);
console.log(`Siguiente numero a 531: ${nextNumber(531)}`);
|
1b823ec3d9298fef474b10060edced75dbf9f28e
|
TypeScript
|
byglimps/boomerang
|
/src/main.ts
| 3.03125
| 3
|
import * as fs from "fs";
import * as path from "path";
import * as crypto from "crypto";
import * as gm from "gm";
type ImagePath = {
location: string;
name: string;
};
export class Boomerang {
constructor(images: Array<string>) {
this.mkdir();
this.create(images);
}
public async create(images: Array<string>): Promise<Array<ImagePath>> {
if (!images || images.length == 0) throw "No images passed";
try {
const imagePaths = await this.save(images);
const dest = path.resolve(`tmp/${this.generateId()}.gif`);
let gmi = gm("");
// Make a shallow copy of array then map it in reverse order
// slice(0) is cheap way of making a clone of original array
imagePaths
.slice(0)
.reverse()
.map(img => img && gmi.in(img.location));
imagePaths.map(img => img && gmi.in(img.location));
gmi
.delay(15)
.resize(1280, 720)
.gravity("Center")
.write(dest, async err => {
if (err) throw err;
await this.unlink(imagePaths);
return;
});
return imagePaths;
} catch (e) {
return e;
}
}
// Generate unique id for file
private generateId(): string {
return crypto.randomBytes(16).toString("hex");
}
// Create temp storage folder
private mkdir(): void {
const folder: string = path.resolve("tmp/");
if (!fs.existsSync(folder)) {
fs.mkdirSync(folder);
}
}
// Save files
private async save(images: Array<string>): Promise<Array<ImagePath>> {
let response: Array<ImagePath> = new Array();
await Promise.all(
images.map(pic => {
const filename: string = this.generateId();
const filepath: string = path.resolve(`tmp/${filename}.jpg`);
const base64 = pic.replace(/^data:image\/png;base64,/, "");
fs.writeFileSync(filepath, base64, "base64");
response.push({ location: filepath, name: filename });
})
);
return response;
}
// Remove files
private async unlink(paths: Array<ImagePath>) {
await Promise.all(paths.map(path => fs.unlinkSync(path.location)));
}
}
|
a6e880def86fb98373a2801a5fbe6fa6d67ba806
|
TypeScript
|
YoshiyukiKato/nightharbor
|
/src/reporter/simple-reporter.ts
| 2.9375
| 3
|
import {IReporter} from "../interface";
export default class SimpleReporter implements IReporter {
private results: any[];
public constructor() {
this.results = [];
}
public write(result: any): void {
this.results.push(result);
}
public close(): Promise<any> {
this.results.forEach((result) => {
const {url, ...resultExceptUrl} = result;
const headIndent = " ";
const bodyIndent = " ";
const head = "\n\n" + headIndent + url + "\n";
const bottom = "\n";
const body = Object.keys(resultExceptUrl).reduce((acc: string, key: string) => {
return acc + `${bodyIndent}${key}: ${resultExceptUrl[key]}\n`;
}, "");
console.log(head + body + bottom);
});
return Promise.resolve();
}
}
|
4b63cd39f871811f872f66c47012126d226934a1
|
TypeScript
|
benjaminParisel/Formation_JavaScript_Bonitasoft_2017_11
|
/BuildWebpack/src/js/random.ts
| 3.203125
| 3
|
export const getRandomInt = (min: number, max: number) : number => {
console.log('getRandomInt');
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
};
export const getRandomIntInclusive = (min: number, max: number) : number => {
console.log('getRandomIntInclusive');
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive
};
|
be79cd8d2ab1eb91472db7e07bcba6dd164e13ef
|
TypeScript
|
minhdpt/tetris_game
|
/src/menu/GameOver.ts
| 2.5625
| 3
|
import {Text} from 'pixi.js';
import SoundManager from '../manager/SoundManager';
import BaseMenu from './BaseMenu';
/**
* Display Game Over screen
*/
export default class GameOver extends BaseMenu {
scoreInfo: Text;
constructor(game) {
super(game, 'GAME\nOVER', 'Touch to restart');
this.scoreInfo = new Text('Last score', this.info.style);
this.scoreInfo.anchor.set(0.5);
this.scoreInfo.x = this.game.app.view.width * 0.5;
this.scoreInfo.y = this.game.app.renderer.height * 0.50;
this.addChild(this.scoreInfo);
}
enter(opts) {
this.registerTouchEvents()
let score = this.game.scores.getNewest();
this.scoreInfo.text = `Score: ${score.points}\nLines: ${score.lines}`;
(this.game.SoundManager as SoundManager).playSound('sfx_gameover')
}
registerTouchEvents()
{
this.game.app.stage.interactive = true
this.game.app.stage
.once('pointerdown', this.handlePlayTouchStart.bind(this))
}
update(dt) {
super.update(dt);
if (this.game.key.space.trigger()) {
this.game.setState('play', {restart: true});
(this.game.SoundManager as SoundManager).stopdAllSound()
}
}
handlePlayTouchStart(event)
{
(this.game as any).key.space.onPress()
}
}
|
70651c274f06b61fea892bf4115cb5c2d3ac4805
|
TypeScript
|
RenatoBrito81/EncurtadorDeURL
|
/src/Controller/URLController.ts
| 2.953125
| 3
|
import { URLmodel } from "../database/model/URLmodel";
import { Request, Response } from "express";
import shortId from 'shortid'
import "dotenv/config";
export class URLController {
public async EncurtarURL(req: Request, res: Response): Promise<void>{
const { urlOrigem } = req.body;
//Ver se a URL já existe
const url = await URLmodel.findOne({ urlOrigem });
if(url){
res.json(url);
return;
}
//Criar o hash para encurtar a URL
const hash = shortId.generate();
//const urlEncurtada = `${config.API_URL}/${hash}`;
const urlEncurtada = `${process.env.API_URL}/${hash}`;
//Salvar a URL no banco de dados
const salvarURL = URLmodel.create({ urlOrigem, hash, urlEncurtada });
//Retornar a URL encurtada
res.json(salvarURL);
}
public async RedirecionarURL(req: Request, res: Response): Promise<void>{
//Pegar o hash da URL
const { hash } = req.params;
const url = await URLmodel.findOne({ hash: hash });
if(url){
//Redirecionar para a URL original
res.redirect(url.urlOrigem);
return;
}
res.status(400).json({ error: 'URL não encontrada.' });
}
public async RetornarURLS(req: Request, res: Response): Promise<void>{
const urls = await URLmodel.find();
if(urls){
res.json(urls);
return;
}
res.status(400).json({ error: "Não há urls cadastradas." });
}
}
|
a63fa9ad96f09d5f6c36ba585574137645c1c9a4
|
TypeScript
|
IngridGdesigns/typescript-playground
|
/course-notes/ex4_functions.ts
| 4.78125
| 5
|
// ex 1: Functions and void versus undefined
function subtract(n1: number, n2: number): number {
return n1 - n2;
}
function printResult(num: number) {
console.log(`Result: ${num}`);
}
printResult(subtract(10, 4)); // function printResult(num: number): void
/* return type of void - The function doesn't return antyhing, it successfully completes,
doesn't return anything. Use Void not undefined because it's deliberate that you are not
returning anything. */
console.log(printResult(subtract(12, 5))); // you would get undefined as a value
// undefined is a type in typescript, you wont get an error
let someThing: undefined; // not very useful
// ex 2 : Function types
function multiply(num1: number, num2: number) {
return num1 * num2;
}
// void = ignoring the return type, clearly defined there, a callback function as a parameter
function multiplyAndHandle(n1: number, n2: number, cb: (num: number) => void) {
const result = n1 + n2;
cb(result); // callback
}
//// avoid this
let combineV;
combineV = multiply; // combineValues has an "any" type
console.log(combineV(3, 3)); // Output: 9
/// instead do this:
/// takes a function and takes in two numbers / (parameters), you need to match the types
let combinationValues: (a: number, b: number) => number; // two arguments and returns a number
// specify funciton type at the end of error
combinationValues = multiply;
console.log(combinationValues(4, 5));
// function types allows us to describe which type of function specifically we want to use
// somewhere, with variables or a callback
// passing in an anonymous function
multiplyAndHandle(2, 4, (result) => {
// Typescrip is able to infer that result is a number
console.log(result);
});
|
bb18fb527488e239f6b2f8939938e8780f3abbc8
|
TypeScript
|
cypeng001/h5game
|
/client/project/src/particle/affector/PSAffectorLinearForce.ts
| 2.84375
| 3
|
class PSAffectorLinearForce extends PSAffector {
protected static DEF_ATTR = {
FORCE: 100,
};
protected static ForceApp = {
AVERAGE: 0,
ADD: 1
};
protected _forceVector: PSVec3 = [0, -1, 0];
protected _forceApp: number = PSAffectorLinearForce.ForceApp.ADD;
protected _dynForce: PSDynAttr;
constructor(technique: PSTechnique) {
super(technique);
}
public setForceVector(forceVector: PSVec3): void {
PSVec3Util.copy(forceVector, this._forceVector);
PSVec3Util.normalize(this._forceVector);
}
public setForceApp(forceApp: number): void {
this._forceApp = forceApp;
}
public setDynForce(dynForce: PSDynAttr): void {
this._dynForce = dynForce;
}
public effectParticle(particle: PSParticle, timeElapsed: number): void {
var percent = particle.timeFactor;
var vecTmp = PSVec3Ftry.getInstance().create(1, 1, 1);
PSVec3Util.multiply(this._forceVector,
PSUtil.calcDynAttr(this._dynForce, percent, PSAffectorLinearForce.DEF_ATTR.FORCE),
vecTmp);
if (this._forceApp == PSAffectorLinearForce.ForceApp.ADD) {
PSVec3Util.multiply(vecTmp, timeElapsed, vecTmp);
PSVec3Util.add(particle.direction, vecTmp, particle.direction);
}
else {
PSVec3Util.add(particle.direction, vecTmp, vecTmp);
PSVec3Util.multiply(vecTmp, 0.5, particle.direction);
}
PSVec3Ftry.getInstance().release(vecTmp);
}
}
|
b9cb87e70ab2757e9fb5720dfb4fa87a60a59e0d
|
TypeScript
|
martendV/mei-long
|
/router/route-validator.ts
| 2.953125
| 3
|
import { Route, UrlParameterObject } from "../interfaces/router-interface.ts";
import { ServerRequest } from "../deps.ts";
export class RouteValidator {
public request: ServerRequest;
constructor(request: ServerRequest) {
this.request = request;
}
public naturallyMatches(route: Route): boolean {
return this.request.url === route.url &&
this.request.method === route.method;
}
public matchParams(
route: Route,
): { matches: boolean; params: Map<string, string> } {
const requestRouteArray = this.request.url.split("/");
const routeArray = route.url.split("/");
if (requestRouteArray.length !== routeArray.length) {
return { matches: false, params: new Map<string, string>() };
}
const { url: parameterizedUrl, params } = this.getUrlParameterObject(
requestRouteArray,
routeArray,
);
if (
parameterizedUrl === this.request.url &&
this.request.method === route.method
) {
return { matches: true, params };
}
return { matches: false, params: new Map<string, string>() };
}
private getUrlParameterObject(
requestRouteArray: string[],
routeArray: string[],
): UrlParameterObject {
const params = new Map<string, string>();
const url = routeArray.map((val, index) => {
if (val.includes(":")) {
const parameter = requestRouteArray[index];
if (index !== 1) {
params.set(
`${requestRouteArray[index - 1]}_${val.replace(":", "")}`,
requestRouteArray[index],
);
} else {
params.set(
`${val.replace(":", "")}`,
requestRouteArray[index],
);
}
return parameter;
} else {
return val;
}
}).join("/");
return { url, params };
}
}
|
31b44c7ab2072579c42677656cd48012a2e6af79
|
TypeScript
|
r00t-101-LoL/replikit
|
/packages/messages/src/messageBuilder.ts
| 2.703125
| 3
|
import { OutMessage, Attachment, TextToken, MessageHeader, Button } from "@replikit/core/typings";
import { AttachmentType, TextTokenKind, TextTokenProp, Builder, assert } from "@replikit/core";
import { hashString, MetadataLike, extractMetadata } from "@replikit/messages";
export class MessageBuilder extends Builder {
protected readonly message: OutMessage = {
forwarded: [],
attachments: [],
tokens: [],
buttons: []
};
addReply(metadata: MetadataLike): this {
this.message.reply = extractMetadata(metadata);
return this;
}
addHeader(header: MessageHeader): this {
this.message.header = header;
return this;
}
useMetadata(metadata: MetadataLike): this {
this.message.metadata = extractMetadata(metadata);
return this;
}
addToken(token: TextToken): this {
this.message.tokens.push(token);
return this;
}
addTokens(tokens: TextToken[]): this {
this.message.tokens.push(...tokens);
return this;
}
addCode(code: string): this {
return this.addText(code, [TextTokenProp.Code]);
}
addText(text: string, props?: TextTokenProp[]): this {
return this.addToken({
kind: TextTokenKind.Text,
text,
props: props ?? []
});
}
addCodeLine(line?: string): this {
return this.addCode(line ? line + "\n" : "\n");
}
addCodeLines(lines: string[]): this {
return this.addCode(lines.join("\n") + "\n");
}
addLine(line?: string): this {
return this.addText(line ? line + "\n" : "\n");
}
addLines(lines: string[]): this {
return this.addText(lines.join("\n") + "\n");
}
addAttachmentByUrl(type: AttachmentType, url: string): this {
this.message.attachments.push({ type, id: hashString(url), url });
return this;
}
addAttachment(attachment: Attachment): this {
this.message.attachments.push(attachment);
return this;
}
addAttachments(attachments: Attachment[]): this {
this.message.attachments.push(...attachments);
return this;
}
addButton(row: number, button: Button): this;
addButton(button: Button): this;
addButton(rowOrButton: number | Button, button?: Button): this {
const rowIndex = typeof rowOrButton === "number" ? rowOrButton : 0;
assert(rowIndex >= 0, "Row index must not be positive");
let buttons = this.message.buttons[rowIndex];
while (!buttons) {
this.message.buttons.push([]);
buttons = this.message.buttons[rowIndex];
}
buttons.push(button ?? (rowOrButton as Button));
return this;
}
build(): OutMessage {
return this.message;
}
}
|
1e4bfa80e15201626e688095762cf7f5faa5f5a4
|
TypeScript
|
Nax/screepy
|
/src/tasks/index.ts
| 2.84375
| 3
|
import buildRoads from './build/roads';
import buildExtensions from './build/extensions';
import creepReap from './creep/reap';
interface ITask {
task:() => void,
period:number;
};
interface IComputedTask extends ITask {
skew:number;
};
const combineTasks = (tasks:ITask[]) => {
const taskTable:IComputedTask[] = [];
for (let t of tasks) {
const computed:IComputedTask = {
task: t.task,
period: t.period,
skew: taskTable.length % t.period
};
taskTable.push(computed);
}
return () => {
const tick = Game.time;
for (let task of taskTable) {
if (tick % task.period === task.skew) {
task.task();
}
}
};
}
export default combineTasks([
{ task: buildRoads, period: 10 },
{ task: buildExtensions, period: 20 },
{ task: creepReap, period: 100 }
]);
|
63975537bd43f52dd4f8f5097fa29c2708da06b5
|
TypeScript
|
lutterotti/angular-budget-calendar
|
/src/app/directives/numerical-pipe.directive.ts
| 2.53125
| 3
|
import { Directive, ElementRef, forwardRef, HostListener, Input, Renderer2 } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { formatNumber } from '@angular/common';
import { isNull } from 'lodash';
export const AV_NUMERIC_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => NumericalPipeDirective),
multi: true
};
@Directive({
selector: '[numerical-pipe]',
providers: [AV_NUMERIC_VALUE_ACCESSOR]
})
export class NumericalPipeDirective implements ControlValueAccessor {
@Input() prefix: string = '';
private _onChangedCallback(value: string | number) {}
private _onTouchedCallback() {}
constructor(private ElementRef: ElementRef, private Renderer2: Renderer2) {}
@HostListener('change', ['$event.target.value'])
onChange(input: string | number) {
this.writeValue(input);
}
registerOnTouched(fn: any): void {
this._onTouchedCallback = fn;
}
registerOnChange(fn: any): void {
this._onChangedCallback = fn;
}
writeValue(input: string | number) {
this._onChangedCallback(input);
const amount = !isNull(input) ? input.toString().replace(/[^0-9]/, '' ) : '';
this.Renderer2.setProperty(this.ElementRef.nativeElement, 'value', `${this.prefix}${amount}`);
}
}
|
e8c4958d1695e198eaaa992c2796084650a4ff16
|
TypeScript
|
zstefanovska/algo-comparer
|
/src/comparer/comparer.ts
| 2.953125
| 3
|
import { ProblemOptions, Algorithm, InputFunction, AlgorithmResults, MetricValuesMap, IAnalyzer } from "./models";
import * as Performance from "performance-node";
export class AlgorithmComparer {
private algorithms: Algorithm[] = [];
private problemName: string;
private metrics: string[];
private inputs: any[] | InputFunction<any>;
public results: AlgorithmResults = {};
constructor(private options: ProblemOptions, private analyzer: IAnalyzer) {
this.problemName = options.name;
this.metrics = options.metricNames.slice();
this.inputs = options.inputs;
}
registerAlgorithm(algorithm: Algorithm) {
if (!algorithm) {
throw Error("The algorithm is not defined");
}
// check problem name
if (algorithm.problemName !== this.problemName) {
throw Error(`The algorithm ${algorithm.name} solves the problem ${algorithm.problemName}, instead of ${this.problemName}`);
}
if (!algorithm.metrics) {
throw Error("The algorithm metrics are not defined");
}
// check available metrics
let availableMetrics = Object.keys(algorithm.metrics);
this.metrics.forEach(metric => {
if (!availableMetrics.includes(metric)) {
throw Error(`Metric ${metric} is not available on algorithm ${algorithm.name}`);
}
});
// check name uniqueness
if (this.results[algorithm.name]) {
throw Error(`The algorithm ${algorithm.name} is already registered on problem ${this.problemName}`);
}
this.algorithms.push(algorithm);
this.results[algorithm.name] = {
runDetails: [],
totals: {
timeSpent: 0
}
};
}
getInput(index: number) {
if (typeof this.inputs === "function") {
return this.inputs(index);
} else {
return this.inputs[index];
}
}
getInputLength() {
const maxInputs = 100;
if (this.options.inputLength)
return this.options.inputLength;
return (typeof this.inputs === "function") ? maxInputs : this.inputs.length;
}
runAlgorithms() {
const performance = new Performance();
const inputLength = this.getInputLength();
for (let index = 0; index < inputLength; index++) {
const input = this.getInput(index);
this.algorithms.forEach(algorithm => {
const startTime = performance.now();
algorithm.run(input);
const endTime = performance.now();
const metrics: MetricValuesMap = {
runTime: (endTime - startTime) | 0
};
this.metrics.forEach(metric => metrics[metric] = algorithm.metrics[metric]());
this.results[algorithm.name].runDetails.push({ index, metrics });
this.results[algorithm.name].totals.timeSpent += metrics.runTime;
algorithm.reset();
});
}
}
displayResults() {
Object.keys(this.results).forEach(algorithm => {
console.log(algorithm);
console.log(this.results[algorithm].totals);
console.log(this.results[algorithm].runDetails);
});
}
displayAnalysis(): any {
Object.keys(this.results).forEach(algorithm => {
console.log(`Algoritm Name: ${algorithm}`);
const result = this.results[algorithm];
console.log(` Total run time: ${(result.totals.timeSpent / 1000).toPrecision(3)}s`);
const metricValues = this.metrics.map(metricName => ({
name: metricName,
values: result.runDetails.map(run => run.metrics[metricName])
}));
metricValues.forEach(metric => {
const complexity = this.analyzer.analyzeMetrics(metric.values);
console.log(` Metric: ${metric.name}, Estimated complexity: ${complexity}`);
});
});
}
}
|
7457c3d44b15a3c5ce77cdecbf8fa10d55afacad
|
TypeScript
|
munishase/ExistingAPIs
|
/src/Services/Authentication.ts
| 2.703125
| 3
|
import { BaseLayer } from "./BaseLayer";
import jwt from 'jsonwebtoken';
import AuthenticationToken from "../types/AuthenticationToken";
export class Authentication extends BaseLayer {
public Authorize(username: string, password: string): string {
if (username == "munish" && password == "singla") {
const payload = { username, password };
const signOptions = {
issuer: this.environmentConfig.PrivateKey.Issuer,
subject: this.environmentConfig.PrivateKey.Subject,
audience: this.environmentConfig.PrivateKey.Audience,
expiresIn: this.environmentConfig.PrivateKey.ExpiresIn
//algorithm: "RS256" // RSASSA [ "RS256", "RS384", "RS512" ]
};
return jwt.sign(payload, this.environmentConfig.PrivateKey.Value, signOptions);
} else {
throw new Error("invalid");
}
}
public verifyAuthentication(token: unknown): boolean {
if (token && typeof token === 'string') {
const decoded = jwt.verify(token, this.environmentConfig.PrivateKey) as AuthenticationToken;
return decoded.username === "munish" && decoded.password === "singla";
}
return false;
}
}
|
2c75905d77d145126200c55e575132bb985431b1
|
TypeScript
|
enriko-riba/PixiTest
|
/Web/app/_engine/KeyboardMapper.ts
| 3.109375
| 3
|
import { State } from "./SceneManager";
/**
* Simple keyboard mapper.
*/
export class KeyboardMapper {
/**
* Stores keyboard pressed state.
*/
private keyboard: boolean[];
/**
* Stores an array of KeyboardAction instances per Global.State. The 'state' indexer is a numeric value from the Global.State enum.
*/
private stateActions: { [state: number]: KeyboardAction[]; };
private ALT_KEY: number = 18;
private SHIFT_KEY: number = 16;
private CTRL_KEY: number = 17;
/**
* Creates a new KeyboardMapper instance.
*/
constructor() {
this.stateActions = {};
this.keyboard = [];
for (var i: number = 0; i < 256; i++) { this.keyboard[i] = false; }
document.addEventListener('keydown', this.keydown.bind(this), false);
document.addEventListener('keyup', this.keyup.bind(this), false);
}
/*
* Invokes needed action handlers based on the pressed keys.
*/
public update(currentState: State) {
// state specific handler
var actions: KeyboardAction[] = this.stateActions[currentState];
this.findHandlerAndInvoke(actions);
// global handlers
actions = this.stateActions[State.GLOBAL];
this.findHandlerAndInvoke(actions);
}
/**
* Searches for all keyboard handlers with matching current pressed key combinations and invokes them.
*/
private findHandlerAndInvoke(actions: KeyboardAction[]) {
if (actions) {
var len = actions.length;
for (var i: number = 0; i < len; i++) {
var ka = actions[i];
if (ka && ka.isAssigned()
&& this.keyboard[ka.key]
&& this.keyboard[this.ALT_KEY] == ka.altKey
&& this.keyboard[this.SHIFT_KEY] == ka.shiftKey
&& this.keyboard[this.CTRL_KEY] == ka.ctrlKey) {
ka.handler();
if (ka.releaseKeyAfterInvoke) this.keyboard[ka.key] = false;
}
}
}
}
private keydown(e/*: JQueryEventObject*/) {
this.keyboard[e.which] = true;
}
private keyup(e/*: JQueryEventObject*/) {
this.keyboard[e.which] = false;
}
public addKeyboardActionHandler = (action: KeyboardAction, state: State) => {
if (!this.stateActions[state]) this.stateActions[state] = [];
this.stateActions[state].push(action);
}
public isKeyDown(keyCode: number) {
return this.keyboard[keyCode];
}
}
export class KeyboardAction {
/**
* Returns true if the handler is assigned.
*/
public isAssigned(): boolean {
return this.handler !== undefined;
}
/**
* Creates a new KeyboardAction instance.
*/
constructor(
public key: number,
public name: string,
public handler: KeyboardActionCallback = undefined,
public releaseKeyAfterInvoke: boolean = true,
public shiftKey: boolean = false,
public ctrlKey: boolean = false,
public altKey: boolean = false) {
}
}
export interface KeyboardActionCallback {
(): void;
}
|
b19e1968031527a880cb58a0551b3abf722a5619
|
TypeScript
|
LancerComet/simple-phy-canvas
|
/src/splash-ball/index.ts
| 3.015625
| 3
|
const canvas = document.querySelector('#app-canvas') as HTMLCanvasElement
const context = canvas.getContext('2d') as CanvasRenderingContext2D
window.addEventListener('resize', setCanvasSize)
setCanvasSize()
function setCanvasSize () {
const width = document.body.clientWidth
const height = document.body.clientHeight
canvas.width = width
canvas.height = height
}
class Ball {
createAt: number = Date.now()
readonly G: number // px / s
readonly resistance: number
readonly initSpeedX: number // px / s
readonly initSpeedY: number // px / s
readonly initX: number
readonly initY: number
private bounceYCount: number = 1
color: string
size: number
x: number
y: number
moveX () {
const time = (Date.now() - this.createAt) / 1000
const currentSpeed = this.initSpeedX
this.x += currentSpeed
}
moveY () {
const time = (Date.now() - this.createAt) / 1000
const currentSpeed = this.initSpeedY - this.G * time
this.y += currentSpeed * -1
}
reset () {
this.x = this.initX
this.y = this.initY
this.createAt = Date.now()
}
bounceY () {
this.createAt = Date.now() - this.resistance * this.bounceYCount
this.bounceYCount++
}
canvas: HTMLCanvasElement = document.createElement('canvas')
private createCanvas () {
const canvas = this.canvas
canvas.width = this.size
canvas.height = this.size
const context = canvas.getContext('2d') as CanvasRenderingContext2D
context.beginPath()
context.arc(this.size / 2, this.size / 2, this.size / 2, 0, Math.PI * 2)
context.fillStyle = this.color
context.fill()
context.closePath()
}
constructor (param: IBallOption) {
this.initSpeedX = param.speedX || 0
this.initSpeedY = param.speedY || 0
this.G = param.G || 40
this.initX = param.x || 0
this.initY = param.y || 0
this.reset()
this.color = param.color || '#ffffff'
this.size = param.size || 10
this.resistance = param.resistance || 100
this.createCanvas()
}
}
interface IBallOption {
speedX?: number
speedY?: number
x?: number
y?: number
G?: number
color?: string
size?: number
resistance?: number
}
const balls: Ball[] = []
createBall(1000)
function createBall (count: number) {
let i = 0
while (i < count) {
balls.push(
new Ball({
// speedX: Math.random() * 32 * (Math.random() > .5 ? 1 : -1),
// speedY: Math.random() * 50,
// x: Math.random() * canvas.width,
speedX: Math.random() * 40 * (Math.random() > .5 ? 1 : -1),
speedY: Math.random() * 60,
x: canvas.width / 2,
y: canvas.height,
size: Math.round(Math.random() * 20) || 10,
color: getRandomColor()
})
)
i++
}
}
function tick () {
context.clearRect(0, 0, canvas.width, canvas.height)
for (let i = 0, length = balls.length; i < length; i++) {
const ball = balls[i]
if (!ball) {
continue
}
ball.moveX()
ball.moveY()
if (
ball.x < 0 ||
ball.x > canvas.width ||
ball.y > canvas.height
) {
ball.reset()
}
context.drawImage(ball.canvas, ball.x, ball.y)
}
requestAnimationFrame(tick)
}
function getRandomColor () {
const colors = [
'#42A5F5', '#29B6F6', '#26C6DA', '#26A69A', '#66BB6A', '#FFC107', '#FF5722'
]
return colors[Math.floor(Math.random() * colors.length)]
}
|
281b2ac6cbdeebcb124b34c0f3205f4096c9242f
|
TypeScript
|
marcobiedermann/codewars
|
/kata/6 kyu/replace-with-alphabet-position/index.test.ts
| 2.734375
| 3
|
import alphabetPosition from '.';
describe('alphabetPosition', () => {
it('should replace every letter with its position in the alphabet', () => {
expect.assertions(2);
expect(alphabetPosition("The sunset sets at twelve o' clock.")).toBe(
'20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11',
);
expect(alphabetPosition('The narwhal bacons at midnight.')).toBe(
'20 8 5 14 1 18 23 8 1 12 2 1 3 15 14 19 1 20 13 9 4 14 9 7 8 20',
);
});
});
|
c6a842cc927f4d38444ce48653c2cea7365fe7ab
|
TypeScript
|
nhcarter123/ocs
|
/src/state/types/tournament.ts
| 3.078125
| 3
|
export type Tournament = {
id: string;
name: string;
description?: string;
pools: Pool[];
date: Date;
playerCount?: number;
maxRating?: number;
avgRating?: number;
};
export type Pool = {
players: string[];
};
export type CreateTournamentPayload = {
name: string;
date: Date;
description?: string;
};
export type DeleteTournamentPayload = {
id: string;
};
export type CreateTournamentAction = {
type: TournamentActionTypes.createTournament;
payload?: CreateTournamentPayload;
};
export type DeleteTournamentAction = {
type: TournamentActionTypes.deleteTournament;
payload?: DeleteTournamentPayload;
};
export type CreateParams = {
tournaments: Tournament[];
payload: CreateTournamentPayload;
};
export type DeleteParams = {
tournaments: Tournament[];
payload: DeleteTournamentPayload;
};
export enum TournamentActionTypes {
createTournament = 'createTournament',
deleteTournament = 'deleteTournament'
}
export type TournamentAction = CreateTournamentAction | DeleteTournamentAction;
|
8f28ed2d11ac562b22ba9364e6fbc5bf80095ab8
|
TypeScript
|
synergy2411/ng-tcs
|
/demo/users-app/src/app/components/observable-demo/observable-demo.component.ts
| 2.671875
| 3
|
import {
Component,
ElementRef,
OnDestroy,
OnInit,
ViewChild,
} from '@angular/core';
import {
concat,
forkJoin,
from,
fromEvent,
interval,
Observable,
ReplaySubject,
Subject,
Subscription,
} from 'rxjs';
import {
debounceTime,
map,
mergeAll,
mergeMap,
switchAll,
switchMap,
take,
takeUntil,
takeWhile,
} from 'rxjs/operators';
import { ajax } from 'rxjs/ajax';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-observable-demo',
templateUrl: './observable-demo.component.html',
styleUrls: ['./observable-demo.component.css'],
})
export class ObservableDemoComponent implements OnInit, OnDestroy {
@ViewChild('btnClick', { static: true })
btnClick: ElementRef<HTMLButtonElement>;
@ViewChild('search', { static: true })
search: ElementRef<HTMLInputElement>;
repos: Array<any> = [];
constructor(private httpClient: HttpClient) {}
unSubHttp$: Subscription;
onUnsubHttp() {
this.unSubHttp$.unsubscribe();
}
ngOnInit() {
this.unSubHttp$ = this.httpClient
.get(`https://api.github.com/users/synergy2411/repos`)
.subscribe(console.log);
// SUBJECT
// const subject = new Subject()
// const subject = new ReplaySubject(2)
// subject.subscribe((pkg) => console.log("Subs 1 :", pkg ))
// subject.next("First Pakage")
// subject.next("Second Pakage")
// subject.next("Third Pakage")
// subject.subscribe((pkg) => console.log("Subs 2 :", pkg ))
// subject.next("Fourth Pakage")
// OUTPUT :
// Sub 1 : first, second, third, fourth
// Sub 2 : Fourth, second, third
// const source1$ = interval(1000).pipe(take(5)) // 01234 - 5 seconds
// const source2$ = interval(2000).pipe(take(3)) // 012 - 6 seconds
// const source3$ = interval(3000).pipe(take(3)) // 012 - 9 Seconds
// forkJoin([source1$, source1$]).subscribe(console.log)
// forkJoin({
// s1 : source1$,
// s2 : source2$,
// s3 : source3$
// }).subscribe(console.log)
// OUTPUT : {s1 : 4 , s2: 2}
// CONCAT - combine observables which runs in order
// concat(source1$, source2$).subscribe(console.log)
// TypeAhead Suggestion
const search$ = fromEvent(this.search.nativeElement, 'input');
search$
.pipe(
debounceTime(1000),
switchMap((event: any) => {
return this.httpClient.get(
`https://api.github.com/users/${event.target.value}/repos`
);
// .pipe()
// return ajax.getJSON(`https://api.github.com/users/${event.target.value}/repos`)
})
)
.subscribe((repoData: any) => {
console.log(repoData);
this.repos = repoData;
});
// Merge -> Merge All the request/observable
// Switch -> stop the previous observable and give the result of new observable
// INTERVAL, TAKE, TAKEUNTIL, TAKEWHILE, FROM, FROMEVENT
// const fromEvent$ = fromEvent(document,"click")
// const notifier = fromEvent(this.btnClick.nativeElement,"click")
// const source$ = interval(1000)
// source$.pipe(
// take(5)
// takeUntil(notifier)
// takeWhile((value) => {return value < 5})
// ).subscribe(console.log)
// fromEvent$.subscribe(eventData => console.log(eventData))
// const array = ["foo","bar","bam"]
// const source$ = from(array)
// source$.pipe(take(2)).subscribe(console.log)
}
unSub$: Subscription;
obs$ = new Observable((observer) => {
observer.next(interval(1000));
// setTimeout(() => {
// observer.next("First Packages")
// } , 1000)
// setTimeout(() => {
// observer.next("Second Packages")
// } , 2000)
// setTimeout(() => {
// observer.next("ThirdPackages")
// } , 3000)
// setTimeout(() => {
// observer.next("Fourth Packages")
// // observer.error(new Error("Error occured..."));
// } , 5000)
// setTimeout(() => {
// observer.complete();
// } , 7000)
});
onSubscribe() {
console.log('Started');
this.unSub$ = this.obs$.pipe(mergeAll()).subscribe(
(num: number) => {
console.log(num);
},
console.error,
() => {
console.log('COMPLETED');
}
);
console.log('Stopped');
}
onUnsubscribe() {
this.unSub$.unsubscribe();
}
ngOnDestroy() {
if (this.unSub$) {
this.unSub$.unsubscribe();
}
}
}
|
c9f7246d8aa768e8ae262695bf69eeb86c59b83c
|
TypeScript
|
jenskuhrjorgensen/HelloBank
|
/App/Api/Api.ts
| 2.90625
| 3
|
import {AccountById} from "../Model/Account"
import {AccountBuilder} from "../Model/AccountBuilder"
import {OwnerById} from "../Model/Owner"
import {OwnerBuilder} from "../Model/OwnerBuilder"
const DELAY = 2000
interface AccountsNormalized {
result: Array<string>,
entities: {
accounts: AccountById,
owners: OwnerById,
}
}
// The API has been mocked to return normalized data - this should probably be done in a mapper layer, because the backend would return Array<Account>
export function fetchAccounts(): Promise<AccountsNormalized> {
return new Promise((resolve, reject) => {
setTimeout(() => {
const accounts = {
"0": new AccountBuilder()
.id("0")
.name("Savings")
.description("This account is for my savings")
.owner("0")
.build(),
"1": new AccountBuilder()
.id("1")
.name("Check")
.description("This is my check account")
.owner("0")
.build(),
"2": new AccountBuilder()
.id("2")
.name("Real estate")
.description("This is for my real estate expenses")
.owner("1")
.build(),
"3": new AccountBuilder()
.id("3")
.name("Private")
.description("This is for fun!!")
.owner("1")
.build(),
"4": new AccountBuilder()
.id("4")
.name("Shared")
.description("This is for my wife...")
.owner("1")
.build(),
"5": new AccountBuilder()
.id("5")
.name("Kids")
.description("This is our kids' savings account")
.owner("1")
.build(),
"6": new AccountBuilder()
.id("6")
.name("Spending")
.description("This is for general expenses")
.owner("1")
.build(),
"7": new AccountBuilder()
.id("7")
.name("Some other account 1")
.description("Description")
.owner("1")
.build(),
"8": new AccountBuilder()
.id("8")
.name("Some other account 2")
.description("Description")
.owner("1")
.build(),
"9": new AccountBuilder()
.id("9")
.name("Some other account 3")
.description("Description")
.owner("1")
.build(),
"10": new AccountBuilder()
.id("10")
.name("Some other account 4")
.description("Description")
.owner("1")
.build(),
"11": new AccountBuilder()
.id("11")
.name("Some other account 5")
.description("Description")
.owner("1")
.build(),
"12": new AccountBuilder()
.id("12")
.name("Some other account 6")
.description("Description")
.owner("1")
.build(),
"13": new AccountBuilder()
.id("13")
.name("Some other account 7")
.description("Description")
.owner("1")
.build(),
}
resolve({
result: Object.keys(accounts),
entities: {
accounts: accounts,
owners: {
"0": new OwnerBuilder().firstName("John").lastName("Doe").build(),
"1": new OwnerBuilder().firstName("Paul").lastName("Rudd").build(),
}
}
})
}, DELAY)
})
}
|
b0723ab6ce683fdcde54313b58f8f0ea14ab04b8
|
TypeScript
|
codexetreme/DinoGame
|
/DinoGame/Engine/GameLoopComponents.ts
| 2.625
| 3
|
class GameLoopComponents {
fps: number = 60;
protected now: number;
protected then: number = Date.now();
protected interval: number = 1000 / this.fps;
delta: number = 0.0;
startGame() {
this.Start();
this.drawGame();
this.fixedUpdate();
//this.garbageCollection();
}
protected drawGame = () => {
requestAnimationFrame(this.drawGame);
this.now = Date.now();
this.delta = this.now - this.then;
if (this.delta > this.interval) {
this.then = this.now - (this.delta % this.interval);
Canvas.clearCanvas();
this.Update();
for (var i = 0; i < gameResources.getInstance().GameObjects.length; i++) {
gameResources.getInstance().GameObjects[i].updateGameObject();
}
}
}
protected fixedUpdate() {
setInterval(() => {
for (var i = 0; i < gameResources.getInstance().Rigidbodies.length; i++) {
gameResources.getInstance().Rigidbodies[i].updateRigidbody();
}
}, 20);
}
protected garbageCollection() {
setInterval(() => {
for (var i = 0; i < gameResources.getInstance().GameObjects.length; i++) {
let go: GameObject = gameResources.getInstance().GameObjects[i];
if (go.transform.position.x < Canvas.getWidth() || go.transform.position.y > Canvas.getHeight()) {
delete gameResources.getInstance().GameObjects[i];
}
}
}, 2000);
}
// override this function and implement your own logic
protected Update() {
}
protected Start() {
Canvas.loadCanvas(1200, 500);
for (var i = 0; i < gameResources.getInstance().GameObjects.length; i++) {
gameResources.getInstance().GameObjects[i].updateGameObject();
}
}
}
|
4c506e93cf395b12dc8a3ce57cdc15a0c097c51a
|
TypeScript
|
zalman778/ct-constructor
|
/src/app/model/response.model.ts
| 2.53125
| 3
|
/*
Модель json ответа сервера.
*/
export interface IResponse {
status: string;
message: string;
code: string;
payload: object;
}
|
3ff9a3f7aab0c7743a459b8ecf5b4184a5b3b805
|
TypeScript
|
green-fox-academy/zsomborvermes
|
/week-04/typescript/day-2/sharpie-set/SharpieSet.ts
| 3.375
| 3
|
import { Sharpie } from "./Sharpie";
export class SharpieSet {
private sharpieList: Sharpie[] = [];
add(sharpie: Sharpie) {
this.sharpieList.push(sharpie);
}
getSharpieList() {
return this.sharpieList;
}
countUsable() {
let usable: number = 0;
this.sharpieList.forEach(e => {
if (e.getInkAmount() > 0) {
usable++;
}
});
return usable;
}
removeTrash() {
this.sharpieList = this.sharpieList.filter(e => e.getInkAmount() > 0);
}
}
let sharpieSet = new SharpieSet();
console.log(sharpieSet.getSharpieList());
for (let i = 0; i < 100; i++) {
sharpieSet.add(new Sharpie('black', i));
}
console.log(sharpieSet.getSharpieList());
console.log(sharpieSet.countUsable());
for (let i = 0; i < 10000; i++) {
sharpieSet.getSharpieList()[Math.floor(Math.random() * 100)].use();
}
console.log(sharpieSet.countUsable());
sharpieSet.removeTrash();
console.log(sharpieSet.getSharpieList());
|
6d2712767042cf633c7d4cbbe46e1aed522673e6
|
TypeScript
|
josecullen/calendar
|
/src/app/lib/calendar-view/config/calendar-view-config.class.ts
| 2.65625
| 3
|
import { CalendarHeaderConfig, ICalendarHeaderConfig } from './header-config.class';
import { CalendarConfig } from '../../calendar/config/calendar-config.class';
import { MonthViewConfig } from './month-view-config.class';
import { IMonthViewConfig } from './month-view-config.interface';
export class CalendarViewConfig extends CalendarConfig {
constructor(
public header:CalendarHeaderConfig = new CalendarHeaderConfig(),
public month:MonthViewConfig = new MonthViewConfig(),
public selection:'simple' | 'picked' | 'range' = 'simple',
public stylePrefix:string = 'trb'
){
super(header, month)
}
static from(config:ICalendarViewConfig): CalendarViewConfig {
console.log('dateessssss', config.month ? config.month.monthLabels : '')
const conf = this.copyObject(config, new CalendarViewConfig())
console.log('dateessssss', conf.month.dayLabels)
return conf
}
private static copyObject(from:any, to:any):CalendarViewConfig {
to = Object.assign({}, to)
Object.keys(from).forEach(key => {
this.assign(from[key], to, key)
})
return to
}
private static assign(value, target, key){
if(value instanceof Array){
target[key] = value
} else if(value instanceof Object){
target[key] = this.copyObject(value, target[key])
} else {
target[key] = value
}
}
}
export class ICalendarViewConfig {
header?:ICalendarHeaderConfig
month?:IMonthViewConfig
selection?:'simple' | 'picked' | 'range'
stylePrefix?:string
}
|
4d58a52b977a5998336b7ecc5cf954edb52032f0
|
TypeScript
|
SanderRonde/CustomRightClickMenu
|
/tools/definitions/types/node-stream-zip.d.ts
| 2.578125
| 3
|
import { Stream } from "stream";
export = NodeStreamZip;
interface FileEntry {
}
declare class NodeStreamZip {
constructor(config: {
file?: string;
storeEntries?: boolean;
skipEntryNameValidation?: boolean;
});
entries(): {[key: string]: FileEntry};
entry(name: string): FileEntry;
stream(entry: FileEntry, fn: (err: Error|null, stm: Stream) => void): void;
extract(filename: string|null, files: string, callback: (err?: Error) => void): void;
close(): void;
on(event: string, callback: () => void): void;
}
|
5e467db24c5cd000772db4d7fe67e4c09409fd9a
|
TypeScript
|
Angular-RU/angular-ru-sdk
|
/libs/cdk/object/src/is-object.ts
| 2.765625
| 3
|
export function isObject<T>(object: T): boolean {
return object === Object(object);
}
|
1c17fc3c17813716dcb96be3ff95097e92a77367
|
TypeScript
|
KRISACHAN/ying-datastructures-algorithms
|
/src/core/utils.ts
| 3.6875
| 4
|
export type DefalutListType = number[]
export type ICompareFunction<T> = (a: T, b: T) => number
export type IEqualsFunction<T> = (a: T, b: T) => boolean
export type IDiffFunction<T> = (a: T, b: T) => number
// 红黑色色值枚举
export enum Colors {
RED = 0,
BLACK = 1,
}
// 红黑树色值文本枚举
export enum ColorTexts {
RED = 'RED',
BLACK = 'BLACK',
}
// 对比的枚举
export enum Compare {
LESS_THAN = -1,
BIGGER_THAN = 1,
EQUALS = 0,
}
// 是否存在当前数据
export const DOES_NOT_EXIST = -1
// a 小于 b
export const lesserEquals = <T>(
a: T,
b: T,
compareFn: ICompareFunction<T>,
): boolean => {
const comp = compareFn(a, b)
return comp === Compare.LESS_THAN || comp === Compare.EQUALS
}
// a 大于 b
export const biggerEquals = <T>(
a: T,
b: T,
compareFn: ICompareFunction<T>,
): boolean => {
const comp = compareFn(a, b)
return comp === Compare.BIGGER_THAN || comp === Compare.EQUALS
}
// a 等于 a
export const defaultEquals = <T>(a: T, b: T): boolean => a === b
// a 与 b的大小判断
export const defaultCompare = <T>(a: T, b: T): number => {
if (a === b) {
return Compare.EQUALS
}
return a < b ? Compare.LESS_THAN : Compare.BIGGER_THAN
}
// 将数据转换成字符串
export const defaultToString = (item: unknown): string => {
if (item === null) {
return 'NULL'
} else if (item === undefined) {
return 'UNDEFINED'
} else if (typeof item === 'string') {
return item
}
return item.toString()
}
// 数据交换
export const Swap = (array: unknown[], a: number, b: number): void => {
const tmpl: unknown = array[a]
array[a] = array[b]
array[b] = tmpl
}
// 反向对比
export const reverseCompare = <T>(
compareFn: ICompareFunction<T>,
): ICompareFunction<T> => (a, b) => compareFn(b, a)
// 获取a 与 b的差值
export const defaultDiff = <T>(a: T, b: T): number => Number(a) - Number(b)
// 随机数组
export const RandomList: number[] = [1, 2, 3, 4, 7, 5]
// 排列数组
export const SortedList: number[] = [1, 2, 3, 4, 5, 7]
// 随机数组集合
export const RandomLists: number[][] = [
[1, 2, 3, 4, 7, 5],
[3, 9, 8, 7, 5, 1, 2, 3],
[30, 4, 8, 1, 9, 5, 10, 5, 9, 3, 7],
[5, 8, 9, 7, 2, 3, 6, 4, 5, 1, 22, 88, 66, 102, 1024],
[5, 9, 8, 7, 3, 2, 0, 1, 88, 5, 125, 98, 127, 888, 555],
]
// 排列数组集合
export const SortedLists: number[][] = [
[1, 2, 3, 4, 5, 7],
[1, 2, 3, 3, 5, 7, 8, 9],
[1, 3, 4, 5, 5, 7, 8, 9, 9, 10, 30],
[1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 22, 66, 88, 102, 1024],
[0, 1, 2, 3, 5, 5, 7, 8, 9, 88, 98, 125, 127, 555, 888],
]
// 获取数据类型
export const dataType = (data: unknown): string => {
const type: string = Object.prototype.toString.call(data)
return type.replace(/^\[object\s(.+)\]$/, '$1').toLowerCase()
}
// 是否存在该数据
export const isExist = (data: unknown): boolean => {
return !['undefined', 'null'].includes(dataType(data))
}
// 是否存在当前所有数据
export const isExistAll = (...dataList: unknown[]): boolean => {
return dataList.every(isExist)
}
|
2223c0d1ab41314df451c048344371578e8031eb
|
TypeScript
|
NIV54/url-shortener-client
|
/src/common/types/ShortURL.type.ts
| 2.53125
| 3
|
export interface ShortURLInput {
url: string;
alias: string;
}
export interface ShortURL extends ShortURLInput {
id: number;
lastUpdated: string;
}
|
63bbfa4500c70d5601ab88cec3e4e9e623be8783
|
TypeScript
|
rokkerdoktor/prok
|
/src/common/core/utils/get-query-params.ts
| 2.625
| 3
|
export function getQueryParams(url: string) {
const parts = url.split('?');
if (!parts[1] || parts.length > 2) return null;
const hashes = parts[1].split('&');
const params = {};
hashes.map(hash => {
const [key, val] = hash.split('=');
params[key] = decodeURIComponent(val);
});
return params;
}
|
5326a0753eeae4f2e826cd8bf9f31ef4be9aac1a
|
TypeScript
|
MichaelDuo/react-mindmap
|
/src/store/editor/reducers.ts
| 2.53125
| 3
|
import { EditorState, ActionTypes, INCREASE } from './types';
import fakeData from '../_fakeStates/editor';
const initialState: EditorState = fakeData;
export function editorReducer(
state = initialState,
action: ActionTypes
): EditorState {
switch (action.type) {
case INCREASE:
return { ...state, ...{ count: state.count + 1 } };
default:
return state;
}
}
|
f274276f5fb75013840b2c16402abab344a9fa19
|
TypeScript
|
driquelme/edge-currency-plugins
|
/src/common/utxobased/keymanager/bitcoincashUtils/base32.ts
| 2.875
| 3
|
// @flow
/***
* https://github.com/bitcoincashjs/cashaddr
* Copyright (c) 2018 Matias Alejo Garcia
* Copyright (c) 2017 Emilio Almansi
* Distributed under the MIT software license, see the accompanying
* file LICENSE or http://www.opensource.org/licenses/mit-license.php.
*/
/***
* Charset containing the 32 symbols used in the base32 encoding.
*/
const CHARSET: string = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'
/***
* Inverted index mapping each symbol into its index within the charset.
*/
interface CHARSET_INVERSE_INDEX {
[value: string]: number
}
// eslint-disable-next-line @typescript-eslint/no-redeclare
const CHARSET_INVERSE_INDEX: CHARSET_INVERSE_INDEX = {
q: 0,
p: 1,
z: 2,
r: 3,
y: 4,
9: 5,
x: 6,
8: 7,
g: 8,
f: 9,
2: 10,
t: 11,
v: 12,
d: 13,
w: 14,
0: 15,
s: 16,
3: 17,
j: 18,
n: 19,
5: 20,
4: 21,
k: 22,
h: 23,
c: 24,
e: 25,
6: 26,
m: 27,
u: 28,
a: 29,
7: 30,
l: 31
}
/***
* Encodes the given array of 5-bit integers as a base32-encoded string.
*
* @param {Array} data Array of integers between 0 and 31 inclusive.
*/
export function encode(data: number[]): string {
let base32 = ''
for (let i = 0; i < data.length; i++) {
const value = data[i]
if (value < 0 || value > 32) throw new Error(`InvalidArgument: ${value}`)
base32 += CHARSET[value]
}
return base32
}
/***
* Decodes the given base32-encoded string into an array of 5-bit integers.
*
* @param {string} base32
*/
export function decode(base32: string): number[] {
const data = []
for (let i = 0; i < base32.length; i++) {
const value = base32[i]
if (!(value in CHARSET_INVERSE_INDEX)) {
throw new Error(`InvalidArgument: ${value} not in CHARSET_INVERSE_INDEX`)
}
data.push(CHARSET_INVERSE_INDEX[value])
}
return data
}
|
f566cfc8366874d74779bfc87a38958d93a135cc
|
TypeScript
|
eventfarm/javascript-sdk
|
/src/Api/UseCase/UserIdentifier.ts
| 2.515625
| 3
|
/**
* This file was auto generated, please do not edit it directly.
**/
import { RestClientInterface } from '../../Interfaces';
export class UserIdentifier {
constructor(private restClient: RestClientInterface) {}
// Queries
// Commands
/**
* @param string - userIdentifierId
* @param string - identifier
* @param string? - poolId
* @return Promise|Observable|any
*/
SetUserIdentifier(
userIdentifierId: string,
identifier: string,
poolId: string = null,
): any {
return this.restClient.post('UserIdentifier/UseCase/SetUserIdentifier', {
userIdentifierId,
identifier,
poolId,
});
}
}
|
22d7dc4bafef99fa1cec06f8dd52625d4a113777
|
TypeScript
|
SystangoTechnologies/uk-loan-apr-calculator
|
/src/APRCalculator.ts
| 3.171875
| 3
|
import Instalment from './Instalment'
import InstalmentFrequency from './InstalmentFrequency'
import InstalmentType from './InstalmentType'
export default class APRCalculator {
private _advances
private _payments
public constructor(firstAdvance: number) {
this.constructorMthod(firstAdvance, [], [])
}
private constructorMthod(firstAdvance: number, advances, payments) {
this._advances = advances
this._payments = payments
const inst = new Instalment()
inst.Amount = firstAdvance
inst.DaysAfterFirstAdvance = 0
this._advances.push(inst)
}
public SinglePaymentCalculation(payment: number, daysAfterAdvance: number): number {
return Math.round(((Math.pow((this._advances[0].Amount / payment), ((365.25 / daysAfterAdvance) * -1)) - 1) * 100))
}
public Calculate(guess = 0): number {
let rateToTry: number = (guess / 100)
let difference = 1
let amountToAdd = 0.0001
while ((difference !== 0)) {
let advances = 0
let payments = 0
this._advances.forEach(function(value, key) {
advances += value.Calculate(rateToTry)
})
this._payments.forEach(function(value, key) {
payments += value.Calculate(rateToTry)
})
difference = (payments - advances)
if ((difference <= 0.0000001) && (difference >= -0.0000001)) {
break
}
if (difference > 0) {
amountToAdd = (amountToAdd * 2)
rateToTry = (rateToTry + amountToAdd)
} else {
amountToAdd = (amountToAdd / 2)
rateToTry = (rateToTry - amountToAdd)
}
}
return parseFloat((rateToTry * 100).toFixed(2))
}
public AddInstalment(amount: number, daysAfterFirstAdvance: number, instalmentType: InstalmentType = InstalmentType.Payment): void {
const instalment = new Instalment()
instalment.Amount = amount
instalment.DaysAfterFirstAdvance = daysAfterFirstAdvance
switch (instalmentType) {
case InstalmentType.Payment:
this._payments.push(instalment)
break
case InstalmentType.Advance:
this._advances.push(instalment)
break
}
}
private static GetDaysBewteenInstalments(instalmentFrequency: InstalmentFrequency): number {
switch (instalmentFrequency) {
case InstalmentFrequency.Daily:
return 1
break
case InstalmentFrequency.Weekly:
return 7
break
case InstalmentFrequency.Fortnightly:
return 14
break
case InstalmentFrequency.FourWeekly:
return 28
break
case InstalmentFrequency.Monthly:
return (365.25 / 12)
break
case InstalmentFrequency.Quarterly:
return (365.25 / 4)
break
case InstalmentFrequency.Annually:
return 365.25
break
}
return 1
}
public AddRegularInstalments(amount: number, numberOfInstalments: number, instalmentFrequency: InstalmentFrequency, daysAfterFirstAdvancefirstInstalment = 0): void {
const daysBetweenInstalments = APRCalculator.GetDaysBewteenInstalments(instalmentFrequency)
if ((daysAfterFirstAdvancefirstInstalment === 0)) {
daysAfterFirstAdvancefirstInstalment = daysBetweenInstalments
}
for (let i: number = 0; (i < numberOfInstalments); i++) {
const inst = new Instalment()
inst.Amount = amount
inst.DaysAfterFirstAdvance = daysAfterFirstAdvancefirstInstalment + (daysBetweenInstalments * i)
this._payments.push(inst)
}
}
private calculateAPRMonthly(goal: number, term: number, loanCost): number {
try {
let startApr = 0
let endApr = 100
for (let l = 0; l < 100; l++) {
const discounted = this.calculateTotalDiscounted(term, loanCost, startApr)
console.log('here', goal, discounted)
if ((discounted + 1.5) > goal && (discounted - 1.5) < goal) {
return startApr
}
if (discounted > goal) {
startApr++
}
if (discounted < goal) {
endApr = startApr--
}
if (endApr !== 100) {
startApr = startApr + 0.1
}
}
return startApr
} catch (error) {
console.log(error)
}
}
private calculateTotalDiscounted(term, loanCost, apr) {
let totalRepay = 0
const ratio = (1 / (1 + (apr / 100)))
for (let l = 1; l <= term; l++) {
if (l !== term) {
const t = 3 * (Math.pow(ratio, l / 12))
totalRepay += t
} else {
const t = (loanCost + 3) * (Math.pow(ratio, l / 12))
totalRepay += t
}
}
return totalRepay
}
}
|
2514f264b20a972fc5c48fefe35cd6119f933a9c
|
TypeScript
|
Avi-Meshulam/events.ts
|
/src/publisher.ts
| 3.0625
| 3
|
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { INotifyPropertyChanged } from './INotifyPropertyChanged';
import { PropertyChangedEventArgs } from './propertyChangedEventArgs';
export class Publisher implements INotifyPropertyChanged {
// Singleton
private static readonly _instance = new Publisher();
// Using a Subject in order to allow for multiple subscribers
// See: http://reactivex.io/rxjs/manual/overview.html#subject
private readonly _propertyChanged = new Subject<PropertyChangedEventArgs>();
private constructor() { }
static get instance(): Publisher {
return Publisher._instance;
}
// INotifyPropertyChanged implementation
get propertyChanged(): Observable<PropertyChangedEventArgs> {
return this._propertyChanged.asObservable();
}
//#region Properties
private _someProperty = null;
get someProperty(): any {
return this._someProperty;
}
set someProperty(value: any) {
if (this._someProperty !== value) {
const oldValue = this._someProperty;
this._someProperty = value;
// Could be useful to have a name() function, like in C#, e.g. name(this.someProperty)
this.onPropertyChanged('someProperty', oldValue);
}
}
//#endregion Properties
private onPropertyChanged(propertyName: string, oldValue?: any): void {
// Trigger a call to next() on all subscribers
this._propertyChanged.next(new PropertyChangedEventArgs(propertyName, oldValue));
}
}
|
4a94b08c27aef6ff0a6713d762fb803c3116a36c
|
TypeScript
|
chenyuantao/estr
|
/src/ustring.ts
| 3.125
| 3
|
/**
* File: src/ustring.ts
* Project: estr
* Created Date: Thursday, December 13 2018, 2:09:32 PM
* Author: billbai <billbai42@gmail.com>
* -----
* Copyright (c) 2018 billbai
*/
import {
toCodePoints,
fromCodePoints,
isHighSurrogate,
isLowSurrogate
} from './util';
import { nextBreak as nextGraphemeBreakIndex } from './grapheme_breaker';
/**
* The Interface to Represent an Index Range.
* The type of index (char code, code point or grapheme)
* should be determined by context.
*/
export interface IndexRange {
/** the start index, inclusive */
start: number;
/** the end index, inclusive */
end: number;
}
export class Grapheme {
codePoints: number[];
constructor(codePoints: number[]) {
this.codePoints = codePoints;
}
/**
* create a grapheme obj from string slice
* @param str the string to slice
* @param startIndex start char code index of the str, inclusive.
* @param endIndex end char code index of the str, inclusive.
*/
static fromStringSlice(str: string, startIndex: number, endIndex: number) {
let codePoints = toCodePoints(str.slice(startIndex, endIndex + 1));
return new Grapheme(codePoints);
}
/** return a string representation of the Gtrapheme */
toString() {
return fromCodePoints(...this.codePoints);
}
}
export class UString {
private _str: string;
private _codePoints?: number[];
// codePoint index => code unit (char code) index range
// TODO: (billbai) use a more compact representation to reduce memory
private _codePoint2CharCodeIndexMap: IndexRange[] = [];
private _charCode2CodePointIndexMap: number[] = [];
// the char code index range of each grapheme.
// TODO: (billbai) use a more compact representation to reduce memory
private _graphemeIndecies: IndexRange[] = [];
constructor(str: string) {
this._str = str;
this._generateCodePoints();
this._generateGraphemes();
}
private _generateCodePoints() {
let codePoint2CharCodeIndexMap: IndexRange[] = [];
let charCode2CodePointIndexMap: number[] = [];
let codePoints: number[] = [];
const charCodeLen = this._str.length;
for (let i = 0; i < charCodeLen; i++) {
let charCode = this._str.charCodeAt(i);
if (isHighSurrogate(charCode) && i <= charCodeLen - 1) {
let nextCharCode = this._str.charCodeAt(i + 1);
if (isLowSurrogate(nextCharCode)) {
i++;
codePoints.push(
((charCode & 0x3ff) << 10) + (nextCharCode & 0x3ff) + 0x10000
);
codePoint2CharCodeIndexMap.push({ start: i - 1, end: i });
let codePointIndex = codePoints.length - 1;
charCode2CodePointIndexMap[i - 1] = codePointIndex;
charCode2CodePointIndexMap[i] = codePointIndex;
continue;
}
}
codePoints.push(charCode);
codePoint2CharCodeIndexMap.push({ start: i, end: i });
let codePointIndex = codePoints.length - 1;
charCode2CodePointIndexMap[i] = codePointIndex;
}
this._codePoints = codePoints;
this._codePoint2CharCodeIndexMap = codePoint2CharCodeIndexMap;
this._charCode2CodePointIndexMap = charCode2CodePointIndexMap;
}
private _generateGraphemes() {
const charCodeLen = this._str.length;
let graphemeIndecies: IndexRange[] = [];
let lastIndex = 0;
while (lastIndex < charCodeLen) {
let nextIndex = nextGraphemeBreakIndex(this._str, lastIndex);
graphemeIndecies.push({ start: lastIndex, end: nextIndex - 1 });
lastIndex = nextIndex;
}
this._graphemeIndecies = graphemeIndecies;
}
/** return all code points */
codePoints(): number[] {
return this._codePoints || [];
}
/** return the javascript string ( UCS-2 Encoding) */
toString() {
return this._str;
}
/** return all graphemes */
graphemes() {
return this._graphemeIndecies.map(indexRange => {
return Grapheme.fromStringSlice(
this._str,
indexRange.start,
indexRange.end
);
});
}
/** return the count of char codes (code units of UTF-16) */
charCodeCount() {
return this._str.length;
}
/** return the count of Unicode code points */
codePointCount() {
return this.codePoints().length;
}
/** return the count of grapheme,
* the grapheme boundaries are calculated
* from UAX #29 grapheme break algorithm.
*/
graphemeCount() {
return this._graphemeIndecies.length;
}
/**
* Get the code point at index
* @param index the code point index. Range [0...codePointCount]
* @note: the behavior is NOT the same as JS String.codePointAt(index)
* which accecpts an index of the char code index.
*/
codePointAt(index: number): number {
return this.codePoints()[index];
}
/**
* Get the code point at char code index
* @param charCodeIndex the char code index. [0...charCodeIndex]
* @note: the behavior is NOT the same as JS String.codePointAt(index)
* Although they all accept a char code index,
* but the UString can return the correct 'surrogate paired' code point
* when the char code at the index is a low surrogate,
* which the JS String one will return the low surrogate's value.
*/
codePointAtCharCodePoint(charCodeIndex: number) {
let codePointIndex = this.charCodeIndex2CodePointIndex(charCodeIndex);
return this.codePointAt(codePointIndex);
}
/**
* get the char code (code uint) at the char code index.
* Does exactly the same thing as the JS String.charCodeAt(index)
* @param index the char code index. [0...charCodeCount]
*/
charCodeAt(index: number): number {
return this._str.charCodeAt(index);
}
/**
* get the grapheme at grapheme index
* @param index the grapheme index. [0...graphemeCount]
*/
graphemeAt(index: number): Grapheme {
const graphemeIndexRange = this._graphemeIndecies[index];
return Grapheme.fromStringSlice(
this._str,
graphemeIndexRange.start,
graphemeIndexRange.end
);
}
/**
* convert code point index to char code index range
* @param index the code point index
*/
codePointIndex2CharCodeIndexRange(index: number): IndexRange {
return this._codePoint2CharCodeIndexMap[index];
}
/**
* convert grapheme index to char code index range
* @param index the grapheme index
*/
graphemeIndex2CharCodeIndexRange(index: number): IndexRange {
return this._graphemeIndecies[index];
}
/**
* convert char code index to code point index
* @param index the char code index
*/
charCodeIndex2CodePointIndex(index: number): number {
return this._charCode2CodePointIndexMap[index];
}
/**
* convert char code index to grapheme index
* @param index the char code index
*/
charCodeIndex2GraphemeIndex(index: number): number {
// search to
let low = 0;
let hi = this._graphemeIndecies.length - 1;
while (low <= hi) {
let mid = low + Math.floor((hi - low) / 2);
let graphemeIndexRange = this._graphemeIndecies[mid];
if (
graphemeIndexRange.start <= index &&
graphemeIndexRange.end >= index
) {
return mid;
} else if (index < graphemeIndexRange.start) {
hi = mid - 1;
} else if (index > graphemeIndexRange.end) {
low = mid + 1;
} else {
throw new Error(
'Error binary search grapheme index from char code index. Must be a bug.'
);
}
}
return -1;
}
// slice
/**
* slice the string by char code index
* @param start start index, inclusive
* @param to to index, exclusive
*/
sliceByCharCode(start: number, to?: number) {
if (to === undefined) {
to = this.charCodeCount();
}
return new UString(this._str.slice(start, to));
}
/**
* slice by grapheme index
* @param start start grapheme index, inclusive
* @param to end grapheme index, exclusive
*/
sliceByGrapheme(start: number, to?: number) {
if (to === undefined) {
to = this.graphemeCount();
}
const charCodeStart = this.graphemeIndex2CharCodeIndexRange(start).start;
const charCodeEnd = this.graphemeIndex2CharCodeIndexRange(to - 1).end;
return new UString(this._str.slice(charCodeStart, charCodeEnd + 1));
}
/**
* slice by code point index
* @param start start code point index, inclusive
* @param to to code point, exclusive
*/
sliceByCodePoint(start: number, to?: number) {
if (to === undefined) {
to = this.codePointCount();
}
const charCodeStart = this.codePointIndex2CharCodeIndexRange(start).start;
const charCodeEnd = this.codePointIndex2CharCodeIndexRange(to - 1).end;
return new UString(this._str.slice(charCodeStart, charCodeEnd + 1));
}
}
|
2c6d14a48be2875a018e84e40fef0bfb4b4147d3
|
TypeScript
|
loumisha96/tytusx
|
/20211SVAC/G16/app/Clases/Hijos/If.ts
| 2.671875
| 3
|
import Entorno from '../AST/Entorno';
import { Instruccion } from './../Interfaces/Instruccion';
export class If implements Instruccion{
condicicion:any;
sentencias:any;
sino:any;
fila:number;
columna:number;
t:string;
constructor(condicion:any,sentencias:any,sino:any,fila:number,columna:number){
this.condicicion=condicion;
this.sentencias=sentencias;
this.sino=sino;
this.fila=fila;
this.columna=columna;
}
insertSimbolsTable(node: any, anterior:string, eAnterior:any):Entorno {
console.log("pasó por el if")
return eAnterior;
}
ejecutar(entorno: any) {
throw new Error('Method not implemented.');
}
}
|
409d6bb638f610a12d1775c94bff82097c2e9e1d
|
TypeScript
|
AndreGeng/practice-algorithm
|
/add-two-large-num/index.ts
| 3.46875
| 3
|
function paddingWithZero(str: string, targetLen: number, left: boolean) {
const strArr = str.split("")
while (strArr.length < targetLen) {
if (left) {
strArr.unshift("0")
} else {
strArr.push("0")
}
}
return strArr.join("")
}
function integerAdd(str1: string, str2: string) {
let highV = 0
const maxLen = Math.max(str1.length, str2.length)
const result = []
for (let i = 0; i < maxLen; i++) {
let v1 = typeof str1[str1.length - 1 - i] === "undefined" ? 0 : Number(str1[str1.length - 1 - i])
let v2 = typeof str2[str2.length - 1 - i] === "undefined" ? 0 : Number(str2[str2.length - 1 - i])
const tmp = v1 + v2 + highV
const r = tmp%10
highV = Math.floor(tmp/10)
result.unshift(r)
}
if (highV > 0) {
result.unshift(highV)
}
return result.join("")
}
function bigNumAdd(str1: string, str2: string) {
let [i1, d1] = str1.split(".")
let [i2, d2] = str2.split(".")
if (typeof d1 === "undefined") {
d1 = "0"
}
if (typeof d2 === "undefined") {
d2 = "0"
}
const iTargetLen = Math.max(i1.length, i2.length)
const dTargetLen = Math.max(d1.length, d2.length)
i1 = paddingWithZero(i1, iTargetLen, true)
i2 = paddingWithZero(i2, iTargetLen, true)
d1 = paddingWithZero(d1, dTargetLen, false)
d2 = paddingWithZero(d2, dTargetLen, false)
let result = (integerAdd(i1 + d1, i2 + d2)).split("")
// 添加小数点
result.splice(-d1.length, 0, ".")
return result.join("")
}
console.log(bigNumAdd("9007199254740991.34", "12345.876"))
|
3e479a946b88b7b1ffd27a330813dc5f13181045
|
TypeScript
|
naspinall/studs
|
/src/builder/limitQueryBuilder.ts
| 2.8125
| 3
|
import { ParameterManager } from "../common/ParameterManager";
import { OperatorConfiguration } from "../operators/Operator";
import { Primitive } from "../utility/types";
export class LimitQueryBuilder {
private limit: number = 0;
private parameterManager = new ParameterManager();
getParameterManager(): ParameterManager {
return this.parameterManager;
}
configure({ count }: OperatorConfiguration): LimitQueryBuilder {
this.parameterManager.configure({ count });
return this;
}
setLimit(limit: number) {
if (!Number.isInteger(limit)) throw new Error("Invalid limit");
this.limit = limit;
}
toSQL(): [string, Array<Primitive>] {
if (this.limit > 0) {
const parameter = this.parameterManager.addValue(this.limit);
return [` limit ${parameter}`, [this.limit]];
} else return ["", []];
}
}
|
815aa2e95531d67d9d7ac38f01b4754cbea7d84c
|
TypeScript
|
bhavya0598/PracticeProject
|
/src/app/store/user.reducer.ts
| 2.765625
| 3
|
import { IUserForm } from '../../assets/model/IUserForm'
import { UserActionTypes, UserFormActions } from './user.actions';
export interface IAppState {
user: IUserForm[],
isLoading: boolean;
}
const INITIAL_STATE: IAppState = {
user: [],
isLoading: false
}
export function rootReducer(state = INITIAL_STATE, action: UserFormActions): IAppState{
switch (action.type)
{
case UserActionTypes.GetUserFormLoad: {
return {
...state,
isLoading: true
}
}
case UserActionTypes.GetUserFormSuccess:{
return {
...state,
user: action.payload,
isLoading: false
}
}
case UserActionTypes.GetUserFormFail:{
return{
user: [],
isLoading: false
}
}
default:
return state;
}
}
|
20a81f9c3b675bf9ca23d64603f81f37120e0fc0
|
TypeScript
|
koole/tailwind-component-code-action
|
/src/util/generateStyledComponent.ts
| 2.703125
| 3
|
import { IClassAttribute } from "./parseDocument";
import generate from "@babel/generator";
import {
variableDeclaration,
variableDeclarator,
identifier,
taggedTemplateExpression,
memberExpression,
callExpression,
templateLiteral,
templateElement,
StringLiteral,
} from "@babel/types";
const generateStyleBlock = (classNames: StringLiteral) => {
return `${classNames}`;
};
export const generateStyledComponent = (
elementName: string,
tailwindcomponentName: string,
classAttr: IClassAttribute | null
) => {
const styleString =
classAttr !== null ? generateStyleBlock(classAttr.properties) : "";
return generate(
variableDeclaration("const", [
variableDeclarator(
identifier(tailwindcomponentName),
taggedTemplateExpression(
// Is default tag? just concat with a '.', otherwise wrap with '()'
elementName[0] === elementName[0].toLowerCase()
? memberExpression(identifier("tw"), identifier(elementName))
: callExpression(identifier("tw"), [identifier(elementName)]),
templateLiteral([templateElement({ raw: styleString })], [])
)
),
])
).code;
};
|
cb88258a2903ec6d2b88f9e3fe776c6b61504163
|
TypeScript
|
EdduSoft/resuelve-test
|
/src/validation/player.team.ts
| 2.6875
| 3
|
import { Allow, IsInt, IsNotEmpty, IsNumber, IsPositive } from 'class-validator'
/**
* Class ValidatePlayerTeam
*
* Model and request validation
*
* @author Eduardo Díaz <eddusoft@gmail.com>
*/
export class ValidatePlayerTeam {
/**
* nombre property
*/
@IsNotEmpty()
nombre: string
/**
* nivel property
*/
@IsNotEmpty()
nivel: string
/**
* goles property
*/
@IsInt()
@IsPositive()
goles: number
/**
* sueldo property
*/
@IsNumber()
@IsPositive()
sueldo: number
/**
* bono property
*/
@IsNumber()
@IsPositive()
bono: number
/**
* sueldo_completo property
*/
@Allow()
sueldo_completo: number|null
/**
* equipo property
*/
@IsNotEmpty()
equipo: string
}
|
b03139d7af86a3e6f396ba1554922da3e595dfea
|
TypeScript
|
markjdvs/angular
|
/s03l34-35_services-depencyInject/src/app/courses.service.ts
| 3.21875
| 3
|
// 02 we wanto to export a plain typescipt Class.
// Normally we add a decorator (@Component) to a Class. But we don't have one for Service!
export class CoursesService {
getCourses() {
// for now we don't do the http service.
return ['course1', 'course2', 'course3'];
}
}
// Ok now we have a service but we need to use it in our "courses.component.ts". How?
// 03 first we need to add a constructor --> courses.component.ts
|
4a338c6c006bb918fc3062619f1c3e12c19b87d7
|
TypeScript
|
murdisto/ng5
|
/src/app/home/home.component.ts
| 2.515625
| 3
|
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
itemCount: number; //interpolation
btnText: string = 'Add an item'; //one-way data binding / property binding. see html template for <p> element
itemText: string = 'My first item'; //two-way data binding. see template <input> element. requires formsModule in app.module
items = []; //array to hold items added by user
constructor(private _data: DataService) { }
ngOnInit() {
this._data.item.subscribe(res => this.items = res); // no idea what this is doing
this.itemCount = this.items.length; //set item count when page loads
this._data.changeItem(this.items); //call the changeItem method that's in data.service
}
addItem() {
//when add item button is pushed do this:
this.items.push(this.itemText); //add the new item to the items array
this.itemText = ''; //clear out the input field
this.itemCount = this.items.length; //update the item count
this._data.changeItem(this.items); //call the changeItem method that's in data.service
}
removeItem(i) {
this.items.splice(i, 1);
this.itemCount = this.items.length;
this._data.changeItem(this.items); //call the changeItem method that's in data.service
}
}
|
d67faa7bd4683f8a4b331249355f40a5c29aad7a
|
TypeScript
|
kazuhito-m/line-bot-sandbox
|
/typescript/src/app.ts
| 2.546875
| 3
|
import Provider from './quiz/Provider';
import Quiz from './quiz/Quiz';
import Kani from './quiz/Kani';
import { Command } from './cmd/Command';
import Express, { Request, Response } from 'express';
import CheckListInterlocutor from './checklist/CheckListInterlocutor';
import {
Client, middleware, ClientConfig, MiddlewareConfig,
MessageEvent,
TextEventMessage, TextMessage, PostbackEvent,
FlexMessage, FlexBubble, FlexBox, FlexImage, FlexText,
} from '@line/bot-sdk';
/**
* アプリ全体のTODO
* ProcfileをREADMEに書く。
* 最後のクイズであることを知らせる。
* クイズが最後までいったら、クイズを初期化する。
* ボットが動いている様子を録画する。
* lint対応
* 複数ユーザーでテスト
* 点数(正解だったクイズ)を表示する。
まずは全問回答する、という前提で。
スキップ(次のクイズ)が押される考慮
*/
const clientConfig: ClientConfig = {
channelAccessToken: process.env.LINE_CHANNEL_ACCESS_TOKEN || '',
};
const middlewareConfig: MiddlewareConfig = {
channelSecret: process.env.LINE_CHANNEL_SECRET || '',
};
const botClient = new Client(clientConfig);
const botMiddleware = middleware(middlewareConfig);
const app = Express();
const QUIZ_PROVIDER: Provider = new Kani();
// ユーザーとcurrentQuizのマッピング
const userProviderMap = new Map<string, Provider>();
const checklist: CheckListInterlocutor = new CheckListInterlocutor(botClient);
// 不要なコントローラー(サーバー起動の動作確認のため、だった気がする)
app.get('/', (request: Request, response: Response) => {
return response.send('Hello mahaker!!');
});
app.post('/webhook', botMiddleware, (request: Request, response: Response) => {
Promise
.all(request.body.events.map(handleEvent))
.then((result) => response.json(result))
.catch((err) => {
console.error(err);
response.status(500).end();
});
});
async function handleEvent(event: MessageEvent | PostbackEvent) {
const userId: string | undefined = event.source.userId;
if (!userId) return;
// 初めてボットを利用するユーザーはMapに追加
if (userProviderMap.get(userId) === undefined) {
userProviderMap.set(userId, QUIZ_PROVIDER);
}
if (event.type === 'postback') {
if (replayChecklist(event)) return;
handleRichMenuAction(event);
} else if (event.type === 'message') {
const _event: MessageEvent = event as MessageEvent;
const _textEventMessage: TextEventMessage = _event.message as TextEventMessage;
if (_textEventMessage.text === 'クイズ') {
pushQuiz(userId);
} else if (_textEventMessage.text === 'チェックリスト') {
await pushChecklist(_event);
} else {
await botClient.pushMessage(userId, buildText('不正な入力です。クイズをする場合は「クイズ」、チェックリストをする場合は「チェックリスト」と入力してください。'));
}
}
}
// リッチメニュー上からのアクション
async function handleRichMenuAction(event: PostbackEvent) {
const userId: string | undefined = event.source.userId;
const data = JSON.parse(event.postback.data);
if (!userId) {
return;
}
const quizProvider: Provider | undefined = userProviderMap.get(userId);
if (!quizProvider) {
return;
}
const currentQuiz: Quiz = quizProvider.current();
if (data.cmd === 'answer') {
if (currentQuiz.isCorrect(data.answer)) {
// 正解なら次の問題を送信
await botClient.pushMessage(userId, buildText('せいかい!'));
if (quizProvider.hasNext()) {
quizProvider.next();
}
pushQuiz(userId);
} else {
// 不正解なら今の問題を送信
await botClient.pushMessage(userId, buildText('はずれ!'));
pushQuiz(userId);
}
} else if (data.cmd === 'ctrl') {
switch (data.action) {
case (Command.RESTART):
quizProvider.init();
pushQuiz(userId);
break;
case (Command.DETAIL):
await botClient.pushMessage(userId, buildText(currentQuiz.getDetail()));
break;
case (Command.NEXT):
if (quizProvider.hasNext()) {
quizProvider.next();
}
pushQuiz(userId);
break;
}
}
}
// 睡眠クイズを返す。
async function pushQuiz(userId: string) {
const provider: Provider | undefined = userProviderMap.get(userId);
if (provider === undefined) {
return;
}
const quiz: Quiz = provider.current();
await botClient.pushMessage(userId, buildQuizForm(quiz));
}
// チェックリストを返す。
async function pushChecklist(event: MessageEvent) {
const userId = event.source.userId;
if (!userId) return;
await checklist.start(userId);
}
// チェックリストの返答なら処理する。
function replayChecklist(event: PostbackEvent): boolean {
const userId = event.source.userId;
if (!userId) return false;
checklist.reply(userId, event);
return true;
}
// テキストメッセージを返す。最大2000文字
function buildText(t: string): TextMessage {
return {
type: 'text',
text: t,
};
}
function buildQuizForm(q: Quiz): FlexMessage {
const flexHeaderContents: FlexText = {
type: 'text',
text: `問題${q.getNo()}`,
size: 'lg',
align: 'center',
weight: 'bold',
};
const flexHeader: FlexBox = {
type: 'box',
layout: 'horizontal',
contents: [flexHeaderContents],
};
const flexHero: FlexImage = {
type: 'image',
url: q.getImageUrl(),
};
const flexBodyContents: FlexText = {
type: 'text',
text: q.getText(),
size: 'md',
align: 'start',
wrap: true,
};
const flexBody: FlexBox = {
type: 'box',
layout: 'horizontal',
spacing: 'md',
contents: [flexBodyContents],
};
const flexContents: FlexBubble = {
type: 'bubble',
direction: 'ltr',
header: flexHeader,
hero: flexHero,
body: flexBody,
};
const message: FlexMessage = {
type: 'flex',
altText: 'Flex message',
contents: flexContents,
};
return message;
}
export default app;
|
d4a50a98119760e534537f36dbce184e5c5db0d3
|
TypeScript
|
gfpeltier/ts-tanks
|
/src/models/tank.ts
| 2.859375
| 3
|
import * as PIXI from 'pixi.js'
import * as sprites from '../sprites'
import { Terrain } from './terrain';
import { Projectile, ProjectileType } from './projectile';
export enum TankColor {
Black,
Blue,
Yellow,
Green,
Red
}
export class Tank {
tank: PIXI.Container;
tbody: PIXI.Sprite;
tbarrel: PIXI.Sprite;
health: number;
vx: number;
vy: number;
vrot: number;
vfwd: number;
vpow: number;
power: number;
constructor(color: TankColor) {
this.health = 100;
this.power = 100;
this.vx = 0;
this.vy = 0;
this.vrot = 0;
this.vfwd = 0;
this.vpow = 0;
this.tank = new PIXI.Container();
this.tbody = sprites.tankBody(color);
this.tbarrel = sprites.tankBarrel();
this.tbarrel.x = 8;
this.tbarrel.y = 14;
this.tbarrel.width = 12;
this.tbarrel.height = 4;
this.tbarrel.pivot.y = 2;
this.tbarrel.pivot.x = 30;
this.tbarrel.rotation = (Math.PI / 2);
this.tbody.width = 16;
this.tbody.height = 8;
this.tbody.y = 12;
this.tank.addChild(this.tbody);
this.tank.addChild(this.tbarrel);
this.tank.pivot.x = 8;
this.tank.pivot.y = 4;
this.tank.x = 50;
this.tank.y = 50;
}
_collidingBelow(terrain:Terrain): boolean {
let ispts = terrain.intersectRect(this.tank.x-8, this.tank.y+1, this.width(), this.height());
return ispts.length != 0;
}
handleMovement(terrain: Terrain) {
if(!this._collidingBelow(terrain)){
this.tank.y += 1;
return;
}
let nx = this.tank.x + this.vx;
let ipts = terrain.intersectRect(nx-8, this.tank.y, this.width(), this.height());
if(ipts.length != 0){
ipts = terrain.intersectRect(nx-8, this.tank.y-4, this.width(), this.height());
if(ipts.length == 0){
this.tank.x = nx;
this.tank.y -= 4;
}
}else{
this.tank.x = nx;
}
this.tank.x = Math.min(this.tank.x, terrain.width);
this.tank.x = Math.max(this.tank.x, 0);
this.tank.y += this.vy;
let nrot = this.tbarrel.rotation + this.vrot;
if(nrot <= Math.PI && nrot >= 0)
this.tbarrel.rotation += this.vrot;
this.power += this.vpow;
this.power = Math.min(this.power, 100);
this.power = Math.max(this.power, 0);
}
getHealth() {
return this.health;
}
getBarrelAngle():number {
return this.tbarrel.rotation * 180 / Math.PI;
}
getPower():number {
return this.power;
}
_scaledPower():number {
return this.power * 0.15;
}
fireProjectile():Projectile {
let vx = -1 * this._scaledPower() * Math.cos(this.tbarrel.rotation);
let vy = -1 * this._scaledPower() * Math.sin(this.tbarrel.rotation);
return new Projectile(ProjectileType.Basic, this.tank.x, this.tank.y, vx, vy);
}
setPosition(x:number, y:number) {
this.tank.x = x;
this.tank.y = y;
}
bodyWidth(): number{
return this.tbody.width;
}
bodyHeight(): number{
return this.tbody.height;
}
x(): number {
return this.tank.x;
}
y(): number {
return this.tank.y;
}
width(): number {
return this.tank.width;
}
height(): number {
return 17.2;
}
showBounds(){
let rect = new PIXI.Graphics();
rect.beginFill(0xFF0000);
rect.drawRect(this.tank.x, this.tank.y, this.width(), this.height());
this.tank.addChild(rect);
}
}
|
39139bc27d48d78a1f5584743c980f74d79e456a
|
TypeScript
|
Majdi-Zlitni/Madara
|
/src/types/index.ts
| 2.71875
| 3
|
export type ColumnType = 'Todo' | 'In progress' | 'Done'
export type TrimmedColumnType = 'Todo' | 'Inprogress' | 'Done'
export type Task = {
text: string
createdAt: string
id: string
columnType: ColumnType
}
export type TaskFirestoreResult = {
tasks: Task[]
}
export type Status = 'idle' | 'loading' | 'success' | 'error'
|
990c626bf71b7b00d36af9be0d6d60124d9cdfcd
|
TypeScript
|
dzebleckis/aoc
|
/2021/4/index.ts
| 2.9375
| 3
|
export {};
const text = await Deno.readTextFile("./4/input");
const input = text.split("\n").filter((n) => n != "");
const numbersLine = input[0];
input.shift();
const boardSize = 5;
type Digit = {
number: number;
matched: boolean;
};
type B2 = Digit[][];
type Board = Digit[][];
const boards: Board[] = [];
let rows = [];
for (const line of input) {
const digits = line
.split(" ")
.filter((d) => d != "")
.map((d) => ({
number: parseInt(d.trim()),
matched: false,
}));
rows.push(digits);
if (rows.length === boardSize) {
boards.push([...rows]);
rows = [];
}
}
console.log("numbers", numbersLine);
function boardFinished(board: Board): boolean {
let rows = true;
let cols = true;
for (let i = 0; i < boardSize; i++) {
for (let j = 0; j < boardSize; j++) {
rows = rows && board[i][j].matched;
cols = cols && board[j][i].matched;
}
if (rows || cols) {
return true;
} else {
rows = true;
cols = true;
}
}
return false;
}
function sortWinners(
boards: Board[],
numbers: number[],
acc: { number: number; board: Board }[] = [],
): { number: number; board: Board }[] {
for (let i = 0; i < numbers.length; i++) {
for (let j = 0; j < boards.length; j++) {
for (let row = 0; row < boardSize; row++) {
for (let col = 0; col < boardSize; col++) {
const board = boards[j];
if (board[row][col].number === numbers[i]) {
board[row][col].matched = true;
if (boardFinished(board)) {
acc.push({ number: numbers[i], board });
const n2 = numbers.slice(i);
const copy = [...boards];
copy.splice(j, 1);
return sortWinners(copy, n2, acc);
}
}
}
}
}
}
return acc;
}
function sumBoard(board: Board): number {
let result = 0;
for (const row of board) {
for (const digit of row) {
if (!digit.matched) {
result += digit.number;
}
}
}
return result;
}
const numbers = numbersLine.split(",").map((n) => parseInt(n));
const results = sortWinners(boards, numbers)!;
const winner = results[0];
const sum1 = sumBoard(winner.board);
console.log(winner.number, sum1, winner.number * sum1);
const loser = results[results.length - 1];
const sum2 = sumBoard(loser.board);
console.log(loser.number, sum2, loser.number * sum2);
|
8a280a28d7856f1a3784e2037ab6792a9add5ef9
|
TypeScript
|
Kryndex/AssemblyScript
|
/tests/kitchensink.ts
| 3.3125
| 3
|
/// <reference path="../assembly.d.ts" />
// TODO: binaryen's optimizer seems to keep / eliminate random things here
class MyClass {
instanceFunctionVoid(): void {
}
static staticFunctionVoid(): void {
}
instanceFunctionInt(v: int): int {
return v;
}
static staticFunctionInt(v: int): int {
return v;
}
}
export function dropPrefix(a: int): void {
++a;
--a;
+a;
-a;
}
export function dontDropPrefix(a: int): int {
return ++a;
}
export function dropPostfix(a: int): void {
a++;
a--;
}
export function dontDropPostfix(a: int): int {
return a++;
}
export function dropBinary(a: int, b: int): void {
a + b;
a - b;
a * b;
a / b;
a == b;
a != b;
a > b;
a >= b;
a < b;
a <= b;
// int only
a % b;
a & b;
a | b;
a ^ b;
a << b;
a >> b;
}
export function dontDropBinary(a: int, b: int): int {
return a + b;
}
export function ifFloat(a: float, b: double): void {
if (a) {}
while (a) {}
do {} while (a);
if (b) {}
while (b) {}
do {} while (b);
}
export function ternary(a: int, b: int): int {
return a > b ? a == b ? 0 : 1 : -1 as ushort;
}
export function overflow(): byte {
return (0xFF as byte) + (0xFF as byte);
}
export function castIntToFloat(a: int): float {
return reinterpretf(a);
}
export function castLongToDouble(a: long): double {
return reinterpretd(a);
}
export function castFloatToInt(a: float): int {
return reinterpreti(a);
}
export function castDoubleToLong(a: double): long {
return reinterpretl(a);
}
type f64 = double;
export function typeAlias(a: f64): float {
type f32 = float;
let b: f32 = a as float;
return b;
}
|
92479f01de39d6de3bc71271929cda217eca28a7
|
TypeScript
|
frontarm/demoboard
|
/packages/demoboard-core/src/types/DemoboardLayout.ts
| 2.703125
| 3
|
/*
* Copyright 2019 Seven Stripes Kabushiki Kaisha
*
* This source code is licensed under the Apache License, Version 2.0, found
* in the LICENSE file in the root directory of this source tree.
*/
import { DemoboardPanelType } from './DemoboardPanelType'
export type DemoboardLayoutMode = 'mobile' | 'single' | 'double'
export type DemoboardLayoutSide = 'left' | 'right'
export interface DemoboardLayout<
PanelType extends DemoboardPanelType = DemoboardPanelType
> {
actions: DemoboardLayoutActions
// Initially based on the number of lines. Can also be passed in via props,
// and resized by the user.
height?: number
// Initially set to 0.5. Can also be passed in vai props and resized by the
// user.
editorProportion: number
leftPanelProportion: number
rightPanelProportion: number
sidebarWidth: number
// Based on layout state and props
fullScreen: boolean
// In mobile and single modes, only one of the sides can be displayed at a
// time. This will be `null` when the mode is double or triple.
side: DemoboardLayoutSide | null
// Based on the available width.
mode: DemoboardLayoutMode
// Based on panel the project's panelPriorityOrder, along with the width
// and height of the screen.
sidebarPanel: PanelType | null
leftPanel: PanelType | null
rightPanel: PanelType | null
// Based on layout state, the height of the screen, and whether the panel
// that would normally appear above the panels has any priority.
leftPanelMaximized: boolean
rightPanelMaximized: boolean
}
export type DemoboardLayoutActions = {
changeDimensions: (options: { width: number; height: number }) => void
setSidebarWidth: (proportion: number) => void
setEditorProportion: (proportion: number) => void
setLeftPanelProportion: (proportion: number) => void
setRightPanelProportion: (proportion: number) => void
toggleFullScreen: () => void
toggleLeftPanelMaximized: () => void
toggleRightPanelMaximized: () => void
showLeftSide: () => void
showRightSide: () => void
}
|
ef25819a562bbba738757e5ce720f7ee0f59abd0
|
TypeScript
|
samchon/tgrid.examples
|
/src/projects/simple-calculator/client.ts
| 3.0625
| 3
|
import { WebConnector } from "tgrid/protocols/web";
import { Driver } from "tgrid/components";
import { ISimpleCalculator } from "../../controllers/ICalculator";
async function main(): Promise<void>
{
//----
// CONNECTION
//----
let connector: WebConnector<{}, null> = new WebConnector(null);
await connector.connect("ws://127.0.0.1:10101", {});
//----
// CALL FUNCTIONS
//----
// GET DRIVER
let calc: Driver<ISimpleCalculator> = connector.getDriver<ISimpleCalculator>();
// CALL FUNCTIONS WITH AWAIT SYMBOL
console.log("1 + 3 =", await calc.plus(1, 3));
console.log("7 - 4 =", await calc.minus(7, 4));
console.log("8 x 9 =", await calc.multiplies(8, 9));
// TO CATCH EXCEPTION IS ALSO POSSIBLE
try
{
await calc.divides(4, 0);
}
catch (err)
{
console.log("4 / 0 -> Error:", err.message);
}
//----
// TERMINATE
//----
await connector.close();
}
main();
|
31df4fec8a5749a1206d6432b56eb244892002be
|
TypeScript
|
andonary/cart-tdd
|
/src/domain/services/vaultService.ts
| 2.703125
| 3
|
import {Product} from "../models/business/product";
import {Vault} from "../models/business/vault";
export class VaultService {
private vault: Vault = new Vault();
private listProduct: Product[] = [];
createProduct(product: {name: string, price: number}): Product {
const _newProduct = new Product(product);
this.listProduct.push(_newProduct);
return _newProduct;
}
fillVault(): void {
this.vault = new Vault(this.listProduct);
}
retrieveVault(): Vault {
return this.vault;
}
}
|
b9e63e348c971e54acc3862733a240d3916b4ac3
|
TypeScript
|
mrrs878/blog
|
/src/hooks/useRequest.ts
| 2.625
| 3
|
/*
* @Author: your name
* @Date: 2020-10-09 09:57:25
* @LastEditTime: 2020-10-20 17:19:18
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \blog\src\hooks\useRequest.ts
*/
import { useEffect, useState, useCallback } from 'react';
function useRequest<P, T>(api: (params: P) => Promise<T>, params?: P, visiable = true)
:[boolean, T|undefined, (params?: P) => void, () => void] {
const [res, setRes] = useState<T>();
const [loading, setLoading] = useState(() => false);
const [newParams, setNewParams] = useState(() => params);
const [autoFetch, setAutoFetch] = useState(() => visiable);
const fetch = useCallback(async () => {
if (!newParams && autoFetch === false) return;
if (autoFetch) {
const _params = (newParams || {}) as P;
setLoading(true);
const tmp = await api(_params);
setRes(tmp);
setLoading(false);
}
}, [api, autoFetch, newParams]);
useEffect(() => {
fetch();
}, [fetch]);
const doFetch = useCallback((rest = null) => {
setNewParams(rest);
setAutoFetch(true);
}, []);
return [loading, res, doFetch, fetch];
}
export default useRequest;
|
482f47737218351b4db922e18d72b573f28c979e
|
TypeScript
|
fernandozanutto/apresentacao-teste-unitario
|
/src/libs/core/src/cookie.ts
| 2.84375
| 3
|
/**********************************************************
* Criador: Thiago Feijó *
* Data: 21/12/2017 *
* Descrição: Classe responsavel por gerenciar cookies. *
* *******************************************************/
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AplsCookie {
/**
* Faz leitura dos cookies e retorna o valor a partir da chava
* @param name chave para encontrar o valor no registro do cookie
*/
static get(name: string) {
const app = window['app'] ? window['app'] + '_' : '';
const nameEQ = `${app}${name}` + '=';
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) === 0) {
return c.substring(nameEQ.length, c.length);
}
}
return null;
}
/**
* Seta valor em cookie
* @param name Chave para identificar cookie
*/
static set(name, value, options = null) {
const app = window['app'] ? window['app'] + '_' : '';
options = options || {};
var str = encodeURIComponent(`${app}${name}`) + '=' + encodeURIComponent(value) + '; Path=/';
const isSecure = this.isDesenvolvimento() ? '' : 'secure';
str += !!options.expires ? ';expires=' + options.expires.toUTCString() : '; ' + isSecure;
var cookieLength = str.length + 1;
if (cookieLength > 4096) {
console.warn("Cookie '" + `${app}${name}` + "' possibly not set or overflowed because it was too large (" + cookieLength + ' > 4096 bytes)!');
}
document.cookie = str;
}
/**
* Atualiza time do cooke
* @param name Chave para identificar cookie
*/
static atualiza(name, expires) {
const app = window['app'] ? window['app'] + '_' : '';
const isSecure = this.isDesenvolvimento() ? '' : 'secure';
document.cookie = `${`${app}${name}`}=${this.get(name)}; Path=/; expires=${expires.toUTCString()}; ${isSecure}`;
}
/**
* Seta por cima do atual um cookie com data de expiração mais antiga que a data atual
* assim ele se algo elimina
* @param name Chave para identificar cookie
*/
static delete(name) {
const app = window['app'] ? window['app'] + '_' : '';
document.cookie = `${app}${name}` + '=; Path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
static isDesenvolvimento() {
const url = document.URL;
let isDev = true;
if (url != null && url.indexOf('localhost') === -1 && url.indexOf('127.0.0.1') === -1) {
isDev = false;
}
return isDev;
}
}
|
602d89937661ce212886f7f9860689b17b8ed022
|
TypeScript
|
Kruimeldief/trilogy
|
/tests/find-or-create.ts
| 2.875
| 3
|
import test from 'ava'
import { connect } from '../src'
import { Game } from './helpers/types'
const db = connect(':memory:')
test.after.always(() => db.close())
test('creates missing objects or returns an existing one', async t => {
const games = await db.model<Game>('games', {
name: { type: String, primary: true },
last_played: Date,
genre: String
})
t.is(await games.count({ genre: 'FPS' }), 0)
const first = {
name: 'Overwatch',
last_played: new Date('Jan 31, 2017'),
genre: 'FPS'
}
const fresh = await games.findOrCreate(first)
t.is(await games.count({ genre: 'FPS' }), 1)
const existing1 = await games.findOrCreate({ name: 'Overwatch' })
const existing2 = await games.findOrCreate(first)
t.deepEqual(fresh, existing1)
t.deepEqual(fresh, existing2)
t.is(await games.count({ genre: 'FPS' }), 1)
t.is(fresh!.last_played.toISOString(), existing1!.last_played.toISOString())
t.is(fresh!.last_played.toISOString(), existing2!.last_played.toISOString())
})
|
c42416fdb82d87402d0a6afc79bf89bc7f46f22a
|
TypeScript
|
tunyanghevond/typescript-with-redux
|
/src/state/reducers/repositoriesReducer.ts
| 2.984375
| 3
|
import {ActionType} from '../action-type';
import {Action} from '../actions';
const initialState = {
loading:false,
error: null,
data: []
};
interface RepositoriesState {
loading:boolean;
error: string | null;
data: string[];
};
const reducer = (state:RepositoriesState = initialState, actoin:Action):RepositoriesState => {
switch(actoin.type){
case ActionType.SEARCH_REPOSIORIES:
return {loading:true, error:null, data:[]};
case ActionType.SEARCH_REPOSIORIES_SUCCESS:
return {loading:false,error:null, data: actoin.payload};
case ActionType.SEARCH_REPOSIORIES_ERROR :
return {loading:false,error:actoin.payload, data:[]};
default:
return state ;
}
};
export default reducer;
|