type
stringclasses 7
values | content
stringlengths 4
9.55k
| repo
stringlengths 7
96
| path
stringlengths 4
178
| language
stringclasses 1
value |
---|---|---|---|---|
ArrowFunction |
async () => {
// arrange
const user = new User({
access_token: "access_token",
token_type: "token_type",
profile: {} as UserProfile,
});
// act
await subject.storeUser(user);
// assert
const storageString = await subject.settings.userStore.get(subject["_userStoreKey"]);
expect(storageString).not.toBeNull();
} | pbklink/oidc-client-ts | src/UserManager.test.ts | TypeScript |
ArrowFunction |
async () => {
// arrange
const user = new User({
access_token: "access_token",
token_type: "token_type",
profile: {} as UserProfile,
});
await subject.storeUser(user);
// act
await subject.storeUser(null);
// assert
const storageString = await subject.settings.userStore.get(subject["_userStoreKey"]);
expect(storageString).toBeNull();
} | pbklink/oidc-client-ts | src/UserManager.test.ts | TypeScript |
ArrowFunction |
(event, args) => {
const command = `${args}`;
console.log(command);
const { exec } = require('child_process');
exec(command, (error: Error, stdout: string, stderr: Error) => {
if (error) {
console.log(`error: ${error.message}`);
event.reply('shellResponse', `Error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
event.reply('shellResponse', `Error: ${stderr}`);
return;
}
if (stdout) {
console.log(`${stdout}`);
event.reply('shellResponse', `${stdout}`);
}
});
} | AnthonyGress/FireTV-Toolkit | src/main/main.ts | TypeScript |
ArrowFunction |
(error: Error, stdout: string, stderr: Error) => {
if (error) {
console.log(`error: ${error.message}`);
event.reply('shellResponse', `Error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
event.reply('shellResponse', `Error: ${stderr}`);
return;
}
if (stdout) {
console.log(`${stdout}`);
event.reply('shellResponse', `${stdout}`);
}
} | AnthonyGress/FireTV-Toolkit | src/main/main.ts | TypeScript |
ArrowFunction |
async (event, args) => {
const command = `${adbPath}${args}`;
console.log(command);
const { exec } = require('child_process');
exec(command, (error: Error, stdout: string, stderr: Error) => {
if (error) {
console.log(`error: ${error.message}`);
event.reply('adbResponse', `Error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
event.reply('adbResponse', `Error: ${stderr}`);
return;
}
if (stdout) {
console.log(`${stdout}`);
event.reply('adbResponse', `${stdout}`);
}
});
} | AnthonyGress/FireTV-Toolkit | src/main/main.ts | TypeScript |
ArrowFunction |
(error: Error, stdout: string, stderr: Error) => {
if (error) {
console.log(`error: ${error.message}`);
event.reply('adbResponse', `Error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
event.reply('adbResponse', `Error: ${stderr}`);
return;
}
if (stdout) {
console.log(`${stdout}`);
event.reply('adbResponse', `${stdout}`);
}
} | AnthonyGress/FireTV-Toolkit | src/main/main.ts | TypeScript |
ArrowFunction |
async () => {
const installer = require('electron-devtools-installer');
const forceDownload = !!process.env.UPGRADE_EXTENSIONS;
const extensions = ['REACT_DEVELOPER_TOOLS'];
return installer
.default(
extensions.map((name) => installer[name]),
forceDownload
)
.catch(console.log);
} | AnthonyGress/FireTV-Toolkit | src/main/main.ts | TypeScript |
ArrowFunction |
(name) => installer[name] | AnthonyGress/FireTV-Toolkit | src/main/main.ts | TypeScript |
ArrowFunction |
async () => {
if (isDevelopment) {
await installExtensions();
}
const RESOURCES_PATH = app.isPackaged
? path.join(process.resourcesPath, 'assets')
: path.join(__dirname, '../../assets');
const getAssetPath = (...paths: string[]): string => {
return path.join(RESOURCES_PATH, ...paths);
};
mainWindow = new BrowserWindow({
show: false,
width: 1024,
height: 728,
icon: getAssetPath('icon.png'),
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
},
});
mainWindow.loadURL(resolveHtmlPath('index.html'));
mainWindow.on('ready-to-show', () => {
if (!mainWindow) {
throw new Error('"mainWindow" is not defined');
}
if (process.env.START_MINIMIZED) {
mainWindow.minimize();
} else {
mainWindow.show();
}
});
mainWindow.on('closed', () => {
mainWindow = null;
});
const menuBuilder = new MenuBuilder(mainWindow);
menuBuilder.buildMenu();
// Open urls in the user's browser
mainWindow.webContents.on('new-window', (event, url) => {
event.preventDefault();
shell.openExternal(url);
});
// Remove this if your app does not use auto updates
// eslint-disable-next-line
new AppUpdater();
} | AnthonyGress/FireTV-Toolkit | src/main/main.ts | TypeScript |
ArrowFunction |
(...paths: string[]): string => {
return path.join(RESOURCES_PATH, ...paths);
} | AnthonyGress/FireTV-Toolkit | src/main/main.ts | TypeScript |
ArrowFunction |
() => {
if (!mainWindow) {
throw new Error('"mainWindow" is not defined');
}
if (process.env.START_MINIMIZED) {
mainWindow.minimize();
} else {
mainWindow.show();
}
} | AnthonyGress/FireTV-Toolkit | src/main/main.ts | TypeScript |
ArrowFunction |
() => {
mainWindow = null;
} | AnthonyGress/FireTV-Toolkit | src/main/main.ts | TypeScript |
ArrowFunction |
(event, url) => {
event.preventDefault();
shell.openExternal(url);
} | AnthonyGress/FireTV-Toolkit | src/main/main.ts | TypeScript |
ArrowFunction |
() => {
// Respect the OSX convention of having the application in memory even
// after all windows have been closed
if (process.platform !== 'darwin') {
app.quit();
}
} | AnthonyGress/FireTV-Toolkit | src/main/main.ts | TypeScript |
ArrowFunction |
() => {
createWindow();
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) createWindow();
});
} | AnthonyGress/FireTV-Toolkit | src/main/main.ts | TypeScript |
ArrowFunction |
() => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) createWindow();
} | AnthonyGress/FireTV-Toolkit | src/main/main.ts | TypeScript |
ClassDeclaration |
export default class AppUpdater {
constructor() {
log.transports.file.level = 'info'
autoUpdater.logger = log;
autoUpdater.checkForUpdatesAndNotify();
}
} | AnthonyGress/FireTV-Toolkit | src/main/main.ts | TypeScript |
ArrowFunction |
({ className, children, onClick, ...props }: Props) => {
const handleMouseUp: React.MouseEventHandler<HTMLButtonElement> = (event) => {
event.currentTarget.blur()
}
return (
<button
{...props}
className={cx(styles.button, className)}
type="button"
onClick={onClick}
onMouseUp={handleMouseUp}
>
{children}
</button> | TonCherAmi/mpdweb-frontend | app/common/components/Button/index.tsx | TypeScript |
ArrowFunction |
(event) => {
event.currentTarget.blur()
} | TonCherAmi/mpdweb-frontend | app/common/components/Button/index.tsx | TypeScript |
InterfaceDeclaration |
interface Props extends React.ComponentProps<'button'> {
className?: string
onClick: React.MouseEventHandler
children: React.ReactNode
} | TonCherAmi/mpdweb-frontend | app/common/components/Button/index.tsx | TypeScript |
MethodDeclaration |
cx(styles | TonCherAmi/mpdweb-frontend | app/common/components/Button/index.tsx | TypeScript |
FunctionDeclaration |
export default function logCacheEntry() {
return (
_target: any,
_propertyName: string,
descriptor: TypedPropertyDescriptor<(...args: any[]) => Promise<any>>,
): void => {
const method = descriptor.value;
if (!method) return;
descriptor.value = async function descriptorValue(...args: any[]): Promise<any> {
return new Promise(async resolve => {
const { debugManager, ...otherContext } = args[5] as RequestContext;
if (!debugManager) {
await method.apply(this, args);
resolve();
return;
}
const startTime = debugManager.now();
await method.apply(this, args);
const endTime = debugManager.now();
const duration = endTime - startTime;
resolve();
debugManager.emit(CACHE_ENTRY_ADDED, {
cachemapOptions: args[3],
cacheType: args[0],
context: otherContext,
hash: args[1],
options: args[4],
stats: { duration, endTime, startTime },
value: args[2],
});
});
};
};
} | badbatch/graphql-box | packages/cache-manager/src/debug/log-cache-entry/index.ts | TypeScript |
ArrowFunction |
(
_target: any,
_propertyName: string,
descriptor: TypedPropertyDescriptor<(...args: any[]) => Promise<any>>,
): void => {
const method = descriptor.value;
if (!method) return;
descriptor.value = async function descriptorValue(...args: any[]): Promise<any> {
return new Promise(async resolve => {
const { debugManager, ...otherContext } = args[5] as RequestContext;
if (!debugManager) {
await method.apply(this, args);
resolve();
return;
}
const startTime = debugManager.now();
await method.apply(this, args);
const endTime = debugManager.now();
const duration = endTime - startTime;
resolve();
debugManager.emit(CACHE_ENTRY_ADDED, {
cachemapOptions: args[3],
cacheType: args[0],
context: otherContext,
hash: args[1],
options: args[4],
stats: { duration, endTime, startTime },
value: args[2],
});
});
};
} | badbatch/graphql-box | packages/cache-manager/src/debug/log-cache-entry/index.ts | TypeScript |
ArrowFunction |
async resolve => {
const { debugManager, ...otherContext } = args[5] as RequestContext;
if (!debugManager) {
await method.apply(this, args);
resolve();
return;
}
const startTime = debugManager.now();
await method.apply(this, args);
const endTime = debugManager.now();
const duration = endTime - startTime;
resolve();
debugManager.emit(CACHE_ENTRY_ADDED, {
cachemapOptions: args[3],
cacheType: args[0],
context: otherContext,
hash: args[1],
options: args[4],
stats: { duration, endTime, startTime },
value: args[2],
});
} | badbatch/graphql-box | packages/cache-manager/src/debug/log-cache-entry/index.ts | TypeScript |
ArrowFunction |
(point) => {
const newPoint = new IndexedVector2(point, this.elements.length);
result.push(newPoint);
this.elements.push(newPoint);
} | AIEdX/Babylon.js | packages/dev/core/src/Meshes/polygonMesh.ts | TypeScript |
ArrowFunction |
(point) => {
// x
if (point.x < lmin.x) {
lmin.x = point.x;
} else if (point.x > lmax.x) {
lmax.x = point.x;
}
// y
if (point.y < lmin.y) {
lmin.y = point.y;
} else if (point.y > lmax.y) {
lmax.y = point.y;
}
} | AIEdX/Babylon.js | packages/dev/core/src/Meshes/polygonMesh.ts | TypeScript |
ArrowFunction |
(val) => !isNaN(val) | AIEdX/Babylon.js | packages/dev/core/src/Meshes/polygonMesh.ts | TypeScript |
ArrowFunction |
(p) => {
normals.push(0, 1.0, 0);
positions.push(p.x, 0, p.y);
uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
} | AIEdX/Babylon.js | packages/dev/core/src/Meshes/polygonMesh.ts | TypeScript |
ArrowFunction |
(p) => {
//add the elements at the depth
normals.push(0, -1.0, 0);
positions.push(p.x, -depth, p.y);
uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
} | AIEdX/Babylon.js | packages/dev/core/src/Meshes/polygonMesh.ts | TypeScript |
ArrowFunction |
(hole) => {
this._addSide(positions, normals, uvs, indices, bounds, hole, depth, true, smoothingThreshold);
} | AIEdX/Babylon.js | packages/dev/core/src/Meshes/polygonMesh.ts | TypeScript |
ClassDeclaration | /**
* Vector2 wth index property
*/
class IndexedVector2 extends Vector2 {
constructor(
original: Vector2,
/** Index of the vector2 */
public index: number
) {
super(original.x, original.y);
}
} | AIEdX/Babylon.js | packages/dev/core/src/Meshes/polygonMesh.ts | TypeScript |
ClassDeclaration | /**
* Defines points to create a polygon
*/
class PolygonPoints {
elements = new Array<IndexedVector2>();
add(originalPoints: Array<Vector2>): Array<IndexedVector2> {
const result = new Array<IndexedVector2>();
originalPoints.forEach((point) => {
const newPoint = new IndexedVector2(point, this.elements.length);
result.push(newPoint);
this.elements.push(newPoint);
});
return result;
}
computeBounds(): { min: Vector2; max: Vector2; width: number; height: number } {
const lmin = new Vector2(this.elements[0].x, this.elements[0].y);
const lmax = new Vector2(this.elements[0].x, this.elements[0].y);
this.elements.forEach((point) => {
// x
if (point.x < lmin.x) {
lmin.x = point.x;
} else if (point.x > lmax.x) {
lmax.x = point.x;
}
// y
if (point.y < lmin.y) {
lmin.y = point.y;
} else if (point.y > lmax.y) {
lmax.y = point.y;
}
});
return {
min: lmin,
max: lmax,
width: lmax.x - lmin.x,
height: lmax.y - lmin.y,
};
}
} | AIEdX/Babylon.js | packages/dev/core/src/Meshes/polygonMesh.ts | TypeScript |
ClassDeclaration | /**
* Polygon
* @see https://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
*/
export class Polygon {
/**
* Creates a rectangle
* @param xmin bottom X coord
* @param ymin bottom Y coord
* @param xmax top X coord
* @param ymax top Y coord
* @returns points that make the resulting rectangle
*/
static Rectangle(xmin: number, ymin: number, xmax: number, ymax: number): Vector2[] {
return [new Vector2(xmin, ymin), new Vector2(xmax, ymin), new Vector2(xmax, ymax), new Vector2(xmin, ymax)];
}
/**
* Creates a circle
* @param radius radius of circle
* @param cx scale in x
* @param cy scale in y
* @param numberOfSides number of sides that make up the circle
* @returns points that make the resulting circle
*/
static Circle(radius: number, cx: number = 0, cy: number = 0, numberOfSides: number = 32): Vector2[] {
const result = new Array<Vector2>();
let angle = 0;
const increment = (Math.PI * 2) / numberOfSides;
for (let i = 0; i < numberOfSides; i++) {
result.push(new Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
angle -= increment;
}
return result;
}
/**
* Creates a polygon from input string
* @param input Input polygon data
* @returns the parsed points
*/
static Parse(input: string): Vector2[] {
const floats = input
.split(/[^-+eE.\d]+/)
.map(parseFloat)
.filter((val) => !isNaN(val));
let i: number;
const result = [];
for (i = 0; i < (floats.length & 0x7ffffffe); i += 2) {
result.push(new Vector2(floats[i], floats[i + 1]));
}
return result;
}
/**
* Starts building a polygon from x and y coordinates
* @param x x coordinate
* @param y y coordinate
* @returns the started path2
*/
static StartingAt(x: number, y: number): Path2 {
return Path2.StartingAt(x, y);
}
} | AIEdX/Babylon.js | packages/dev/core/src/Meshes/polygonMesh.ts | TypeScript |
MethodDeclaration |
add(originalPoints: Array<Vector2>): Array<IndexedVector2> {
const result = new Array<IndexedVector2>();
originalPoints.forEach((point) => {
const newPoint = new IndexedVector2(point, this.elements.length);
result.push(newPoint);
this.elements.push(newPoint);
});
return result;
} | AIEdX/Babylon.js | packages/dev/core/src/Meshes/polygonMesh.ts | TypeScript |
MethodDeclaration |
computeBounds(): { min: Vector2; max: Vector2; width: number; height: number } {
const lmin = new Vector2(this.elements[0].x, this.elements[0].y);
const lmax = new Vector2(this.elements[0].x, this.elements[0].y);
this.elements.forEach((point) => {
// x
if (point.x < lmin.x) {
lmin.x = point.x;
} else if (point.x > lmax.x) {
lmax.x = point.x;
}
// y
if (point.y < lmin.y) {
lmin.y = point.y;
} else if (point.y > lmax.y) {
lmax.y = point.y;
}
});
return {
min: lmin,
max: lmax,
width: lmax.x - lmin.x,
height: lmax.y - lmin.y,
};
} | AIEdX/Babylon.js | packages/dev/core/src/Meshes/polygonMesh.ts | TypeScript |
MethodDeclaration | /**
* Creates a rectangle
* @param xmin bottom X coord
* @param ymin bottom Y coord
* @param xmax top X coord
* @param ymax top Y coord
* @returns points that make the resulting rectangle
*/
static Rectangle(xmin: number, ymin: number, xmax: number, ymax: number): Vector2[] {
return [new Vector2(xmin, ymin), new Vector2(xmax, ymin), new Vector2(xmax, ymax), new Vector2(xmin, ymax)];
} | AIEdX/Babylon.js | packages/dev/core/src/Meshes/polygonMesh.ts | TypeScript |
MethodDeclaration | /**
* Creates a circle
* @param radius radius of circle
* @param cx scale in x
* @param cy scale in y
* @param numberOfSides number of sides that make up the circle
* @returns points that make the resulting circle
*/
static Circle(radius: number, cx: number = 0, cy: number = 0, numberOfSides: number = 32): Vector2[] {
const result = new Array<Vector2>();
let angle = 0;
const increment = (Math.PI * 2) / numberOfSides;
for (let i = 0; i < numberOfSides; i++) {
result.push(new Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
angle -= increment;
}
return result;
} | AIEdX/Babylon.js | packages/dev/core/src/Meshes/polygonMesh.ts | TypeScript |
MethodDeclaration | /**
* Creates a polygon from input string
* @param input Input polygon data
* @returns the parsed points
*/
static Parse(input: string): Vector2[] {
const floats = input
.split(/[^-+eE.\d]+/)
.map(parseFloat)
.filter((val) => !isNaN(val));
let i: number;
const result = [];
for (i = 0; i < (floats.length & 0x7ffffffe); i += 2) {
result.push(new Vector2(floats[i], floats[i + 1]));
}
return result;
} | AIEdX/Babylon.js | packages/dev/core/src/Meshes/polygonMesh.ts | TypeScript |
MethodDeclaration | /**
* Starts building a polygon from x and y coordinates
* @param x x coordinate
* @param y y coordinate
* @returns the started path2
*/
static StartingAt(x: number, y: number): Path2 {
return Path2.StartingAt(x, y);
} | AIEdX/Babylon.js | packages/dev/core/src/Meshes/polygonMesh.ts | TypeScript |
MethodDeclaration |
private _addToepoint(points: Vector2[]) {
for (const p of points) {
this._epoints.push(p.x, p.y);
}
} | AIEdX/Babylon.js | packages/dev/core/src/Meshes/polygonMesh.ts | TypeScript |
MethodDeclaration | /**
* Adds a hole within the polygon
* @param hole Array of points defining the hole
* @returns this
*/
addHole(hole: Vector2[]): PolygonMeshBuilder {
this._points.add(hole);
const holepoints = new PolygonPoints();
holepoints.add(hole);
this._holes.push(holepoints);
this._eholes.push(this._epoints.length / 2);
this._addToepoint(hole);
return this;
} | AIEdX/Babylon.js | packages/dev/core/src/Meshes/polygonMesh.ts | TypeScript |
MethodDeclaration | /**
* Creates the polygon
* @param updatable If the mesh should be updatable
* @param depth The depth of the mesh created
* @param smoothingThreshold Dot product threshold for smoothed normals
* @returns the created mesh
*/
build(updatable: boolean = false, depth: number = 0, smoothingThreshold: number = 2): Mesh {
const result = new Mesh(this._name, this._scene);
const vertexData = this.buildVertexData(depth, smoothingThreshold);
result.setVerticesData(VertexBuffer.PositionKind, <number[]>vertexData.positions, updatable);
result.setVerticesData(VertexBuffer.NormalKind, <number[]>vertexData.normals, updatable);
result.setVerticesData(VertexBuffer.UVKind, <number[]>vertexData.uvs, updatable);
result.setIndices(<number[]>vertexData.indices);
return result;
} | AIEdX/Babylon.js | packages/dev/core/src/Meshes/polygonMesh.ts | TypeScript |
MethodDeclaration | /**
* Creates the polygon
* @param depth The depth of the mesh created
* @param smoothingThreshold Dot product threshold for smoothed normals
* @returns the created VertexData
*/
buildVertexData(depth: number = 0, smoothingThreshold: number = 2): VertexData {
const result = new VertexData();
const normals = new Array<number>();
const positions = new Array<number>();
const uvs = new Array<number>();
const bounds = this._points.computeBounds();
this._points.elements.forEach((p) => {
normals.push(0, 1.0, 0);
positions.push(p.x, 0, p.y);
uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
});
const indices = new Array<number>();
const res = this.bjsEarcut(this._epoints, this._eholes, 2);
for (let i = 0; i < res.length; i++) {
indices.push(res[i]);
}
if (depth > 0) {
const positionscount = positions.length / 3; //get the current pointcount
this._points.elements.forEach((p) => {
//add the elements at the depth
normals.push(0, -1.0, 0);
positions.push(p.x, -depth, p.y);
uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
});
const totalCount = indices.length;
for (let i = 0; i < totalCount; i += 3) {
const i0 = indices[i + 0];
const i1 = indices[i + 1];
const i2 = indices[i + 2];
indices.push(i2 + positionscount);
indices.push(i1 + positionscount);
indices.push(i0 + positionscount);
}
//Add the sides
this._addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false, smoothingThreshold);
this._holes.forEach((hole) => {
this._addSide(positions, normals, uvs, indices, bounds, hole, depth, true, smoothingThreshold);
});
}
result.indices = indices;
result.positions = positions;
result.normals = normals;
result.uvs = uvs;
return result;
} | AIEdX/Babylon.js | packages/dev/core/src/Meshes/polygonMesh.ts | TypeScript |
MethodDeclaration | /**
* Adds a side to the polygon
* @param positions points that make the polygon
* @param normals normals of the polygon
* @param uvs uvs of the polygon
* @param indices indices of the polygon
* @param bounds bounds of the polygon
* @param points points of the polygon
* @param depth depth of the polygon
* @param flip flip of the polygon
* @param smoothingThreshold
*/
private _addSide(positions: any[], normals: any[], uvs: any[], indices: any[], bounds: any, points: PolygonPoints, depth: number, flip: boolean, smoothingThreshold: number) {
let startIndex: number = positions.length / 3;
let ulength: number = 0;
for (let i: number = 0; i < points.elements.length; i++) {
const p: IndexedVector2 = points.elements[i];
const p1: IndexedVector2 = points.elements[(i + 1) % points.elements.length];
positions.push(p.x, 0, p.y);
positions.push(p.x, -depth, p.y);
positions.push(p1.x, 0, p1.y);
positions.push(p1.x, -depth, p1.y);
const p0: IndexedVector2 = points.elements[(i + points.elements.length - 1) % points.elements.length];
const p2: IndexedVector2 = points.elements[(i + 2) % points.elements.length];
let vc = new Vector3(-(p1.y - p.y), 0, p1.x - p.x);
let vp = new Vector3(-(p.y - p0.y), 0, p.x - p0.x);
let vn = new Vector3(-(p2.y - p1.y), 0, p2.x - p1.x);
if (!flip) {
vc = vc.scale(-1);
vp = vp.scale(-1);
vn = vn.scale(-1);
}
const vc_norm = vc.normalizeToNew();
let vp_norm = vp.normalizeToNew();
let vn_norm = vn.normalizeToNew();
const dotp = Vector3.Dot(vp_norm, vc_norm);
if (dotp > smoothingThreshold) {
if (dotp < Epsilon - 1) {
vp_norm = new Vector3(p.x, 0, p.y).subtract(new Vector3(p1.x, 0, p1.y)).normalize();
} else {
// cheap average weighed by side length
vp_norm = vp.add(vc).normalize();
}
} else {
vp_norm = vc_norm;
}
const dotn = Vector3.Dot(vn, vc);
if (dotn > smoothingThreshold) {
if (dotn < Epsilon - 1) {
// back to back
vn_norm = new Vector3(p1.x, 0, p1.y).subtract(new Vector3(p.x, 0, p.y)).normalize();
} else {
// cheap average weighed by side length
vn_norm = vn.add(vc).normalize();
}
} else {
vn_norm = vc_norm;
}
uvs.push(ulength / bounds.width, 0);
uvs.push(ulength / bounds.width, 1);
ulength += vc.length();
uvs.push(ulength / bounds.width, 0);
uvs.push(ulength / bounds.width, 1);
normals.push(vp_norm.x, vp_norm.y, vp_norm.z);
normals.push(vp_norm.x, vp_norm.y, vp_norm.z);
normals.push(vn_norm.x, vn_norm.y, vn_norm.z);
normals.push(vn_norm.x, vn_norm.y, vn_norm.z);
if (!flip) {
indices.push(startIndex);
indices.push(startIndex + 1);
indices.push(startIndex + 2);
indices.push(startIndex + 1);
indices.push(startIndex + 3);
indices.push(startIndex + 2);
} else {
indices.push(startIndex);
indices.push(startIndex + 2);
indices.push(startIndex + 1);
indices.push(startIndex + 1);
indices.push(startIndex + 2);
indices.push(startIndex + 3);
}
startIndex += 4;
}
} | AIEdX/Babylon.js | packages/dev/core/src/Meshes/polygonMesh.ts | TypeScript |
ClassDeclaration | /** Handles [[IOSMDOptions]], e.g. returning default options with OSMDOptionsStandard() */
export class OSMDOptions {
/** Returns the default options for OSMD.
* These are e.g. used if no options are given in the [[OpenSheetMusicDisplay]] constructor.
*/
public static OSMDOptionsStandard(): IOSMDOptions {
return {
autoResize: true,
backend: "svg",
drawingParameters: DrawingParametersEnum.default,
};
}
public static BackendTypeFromString(value: string): BackendType {
if (value && value.toLowerCase() === "canvas") {
return BackendType.Canvas;
} else {
return BackendType.SVG;
}
}
} | Richienb/opensheetmusicdisplay | src/OpenSheetMusicDisplay/OSMDOptions.ts | TypeScript |
InterfaceDeclaration |
export interface AutoBeamOptions {
/** Whether to extend beams over rests. Default false. */
beam_rests?: boolean;
/** Whether to extend beams only over rests that are in the middle of a potential beam. Default false. */
beam_middle_rests_only?: boolean;
/** Whether to maintain stem direction of autoBeamed notes. Discouraged, reduces beams. Default false. */
maintain_stem_directions?: boolean;
/** Groups of notes (fractions) to beam within a measure.
* List of fractions, each fraction being [nominator, denominator].
* E.g. [[3,4],[1,4]] will beam the first 3 quarters of a measure, then the last quarter.
*/
groups?: [number[]];
} | Richienb/opensheetmusicdisplay | src/OpenSheetMusicDisplay/OSMDOptions.ts | TypeScript |
EnumDeclaration |
export enum AlignRestOption {
Never = 0, // false should also work
Always = 1, // true should also work
Auto = 2
} | Richienb/opensheetmusicdisplay | src/OpenSheetMusicDisplay/OSMDOptions.ts | TypeScript |
EnumDeclaration |
export enum FillEmptyMeasuresWithWholeRests {
No = 0,
YesVisible = 1,
YesInvisible = 2
} | Richienb/opensheetmusicdisplay | src/OpenSheetMusicDisplay/OSMDOptions.ts | TypeScript |
EnumDeclaration |
export enum BackendType {
SVG = 0,
Canvas = 1
} | Richienb/opensheetmusicdisplay | src/OpenSheetMusicDisplay/OSMDOptions.ts | TypeScript |
MethodDeclaration | /** Returns the default options for OSMD.
* These are e.g. used if no options are given in the [[OpenSheetMusicDisplay]] constructor.
*/
public static OSMDOptionsStandard(): IOSMDOptions {
return {
autoResize: true,
backend: "svg",
drawingParameters: DrawingParametersEnum.default,
};
} | Richienb/opensheetmusicdisplay | src/OpenSheetMusicDisplay/OSMDOptions.ts | TypeScript |
MethodDeclaration |
public static BackendTypeFromString(value: string): BackendType {
if (value && value.toLowerCase() === "canvas") {
return BackendType.Canvas;
} else {
return BackendType.SVG;
}
} | Richienb/opensheetmusicdisplay | src/OpenSheetMusicDisplay/OSMDOptions.ts | TypeScript |
ArrowFunction |
() => {
// State
const { user, loading, error } = useSelector(userState)
// Router
const history = useHistory()
const location = useLocation()
// Refs
const mounted = useMounted()
const searchRef = useRef() as React.MutableRefObject<HTMLInputElement>
// Handlers
const dispatch = useDispatch()
const focusSearchHandler = useCallback(() => {
searchRef.current.focus()
}, [])
const submitHandler = (input: string) => {
dispatch(getUser(input))
}
// Hooks
useEffect(() => {
focusSearchHandler()
}, [focusSearchHandler])
useError(error, focusSearchHandler)
useEffect(() => {
if (mounted) return
if (user) {
const [userName] = location.pathname.split('/').filter((p) => p)
if (userName !== user.login) history.push(`/${user.login}`)
} else if (!loading) {
history.push('/')
}
}, [history, loading, location.pathname, mounted, user])
return (
<header
className="flex sticky top-0 z-10 justify-center items-center p-5 bg-gray-500 bg-opacity-75 transition-all"
style={{
minHeight: location.pathname === '/' ? '100vh' : '0'
}} | soffanadam/github-profile | src/containers/SearchBar.tsx | TypeScript |
ArrowFunction |
() => {
searchRef.current.focus()
} | soffanadam/github-profile | src/containers/SearchBar.tsx | TypeScript |
ArrowFunction |
(input: string) => {
dispatch(getUser(input))
} | soffanadam/github-profile | src/containers/SearchBar.tsx | TypeScript |
ArrowFunction |
() => {
focusSearchHandler()
} | soffanadam/github-profile | src/containers/SearchBar.tsx | TypeScript |
ArrowFunction |
() => {
if (mounted) return
if (user) {
const [userName] = location.pathname.split('/').filter((p) => p)
if (userName !== user.login) history.push(`/${user.login}`)
} else if (!loading) {
history.push('/')
}
} | soffanadam/github-profile | src/containers/SearchBar.tsx | TypeScript |
FunctionDeclaration |
function App() {
const [tabIndex, setTabIndex] = useState(0);
return (
<div className="App">
{/* <header className="App-header"> */}
<Header></Header>
<Tabs selectedIndex={tabIndex} onSelect={(tabIndex) => setTabIndex(tabIndex)} | oshigoto46/oshigoto-site | frontend/src/App.tsx | TypeScript |
ArrowFunction |
(goToSection) => (
<>
<p>
该回调函数使您可以运行任何模式或自定义校验 | FrimJo/documentation | src/data/zh/api.tsx | TypeScript |
ArrowFunction |
(goToSection) => (
<>
<ul>
<li>
<p>
您可以使用<code>defaultValue/defaultChecked</code> | FrimJo/documentation | src/data/zh/api.tsx | TypeScript |
ArrowFunction |
(goToSection) => (
<p>
将表单校验规则应用于架构级别的<code>Yup</code>,请参阅校验架构
<button | FrimJo/documentation | src/data/zh/api.tsx | TypeScript |
ArrowFunction |
(goToSection) => (
<p>
将此选项设置为<code>true</code>将启用浏览器的本机校验。{" "}
<a | FrimJo/documentation | src/data/zh/api.tsx | TypeScript |
ArrowFunction |
(goToSection) => (
<>
<h2 className={typographyStyles.title}>自定义注册</h2>
<p> | FrimJo/documentation | src/data/zh/api.tsx | TypeScript |
ArrowFunction |
() => (
<>
<p>包含每个输入组件表单错误和错误消息的对象 | FrimJo/documentation | src/data/zh/api.tsx | TypeScript |
ArrowFunction |
(goToSection) => (
<>
<p>
<b className={typographyStyles.note}>注意 | FrimJo/documentation | src/data/zh/api.tsx | TypeScript |
ArrowFunction |
(goToSection) => ({
title: "reset",
description: (
<>
<p>
此函数将重置表单中的字段值和错误。通过提供<code>omitResetState</code> | FrimJo/documentation | src/data/zh/api.tsx | TypeScript |
MethodDeclaration |
该函数的完整形式为
<code> | FrimJo/documentation | src/data/zh/api.tsx | TypeScript |
MethodDeclaration |
values< | FrimJo/documentation | src/data/zh/api.tsx | TypeScript |
MethodDeclaration |
通过提供<code> | FrimJo/documentation | src/data/zh/api.tsx | TypeScript |
MethodDeclaration |
omitResetState< | FrimJo/documentation | src/data/zh/api.tsx | TypeScript |
InterfaceDeclaration |
export interface IIndicatorsProps {
project: {
closedVulnerabilities: number;
currentMonthAuthors: number;
currentMonthCommits: number;
lastClosingVuln: number;
maxOpenSeverity: number;
maxSeverity: number;
meanRemediate: number;
openVulnerabilities: number;
pendingClosingCheck: number;
remediatedOverTime: string;
totalFindings: number;
totalTreatment: string;
};
resources: {
repositories: string;
};
} | jvasque6/integrates | front/src/scenes/Dashboard/containers/IndicatorsView/types.ts | TypeScript |
InterfaceDeclaration |
export interface IGraphData {
backgroundColor: string[];
data: number[];
hoverBackgroundColor: string[];
} | jvasque6/integrates | front/src/scenes/Dashboard/containers/IndicatorsView/types.ts | TypeScript |
TypeAliasDeclaration |
export type IIndicatorsViewBaseProps = Pick<RouteComponentProps<{ projectName: string }>, "match">; | jvasque6/integrates | front/src/scenes/Dashboard/containers/IndicatorsView/types.ts | TypeScript |
FunctionDeclaration |
export function RefreshOrderView({ initialOrderId }: RefreshOrderViewProps) {
const classes = useStyles();
const [refreshView] = useOrderCommand('Refresh views');
const { register, handleSubmit, setValue, formState, setError, control } = useForm<FormData>({
defaultValues: {
orderId: initialOrderId,
},
});
const { errors } = formState;
const onSubmit = async (data: FormData) => {
try {
await refreshView(`/orders-admin/${data.orderId}/rebuild`, {});
setValue('orderId', '');
} catch (err) {
setError('orderId', { message: 'Invalid format' });
}
};
return (
<Container className={classes.root}>
<Typography variant="overline">Refresh Views</Typography>
<form className={classes.form} onSubmit={handleSubmit(onSubmit)}>
<Controller
control={control}
name="orderId"
render={({ field }) => (
<TextField
{...field}
label="Order Id"
variant="outlined"
className={classes.input}
disabled={formState.isSubmitting}
error={!!errors.orderId} | andlju/swetugg-tix | back-office/components/admin/refresh-order-view.tsx | TypeScript |
ArrowFunction |
(theme) => ({
root: {
padding: theme.spacing(0),
},
form: {
display: 'flex',
flexDirection: 'row',
},
input: {
flex: '1',
},
button: {},
progressWrapper: {
margin: theme.spacing(1),
position: 'relative',
},
buttonProgress: {
color: theme.palette.action.active,
position: 'absolute',
top: '50%',
left: '50%',
marginTop: -12,
marginLeft: -12,
},
}) | andlju/swetugg-tix | back-office/components/admin/refresh-order-view.tsx | TypeScript |
ArrowFunction |
async (data: FormData) => {
try {
await refreshView(`/orders-admin/${data.orderId}/rebuild`, {});
setValue('orderId', '');
} catch (err) {
setError('orderId', { message: 'Invalid format' });
}
} | andlju/swetugg-tix | back-office/components/admin/refresh-order-view.tsx | TypeScript |
InterfaceDeclaration |
interface RefreshOrderViewProps {
initialOrderId?: string;
} | andlju/swetugg-tix | back-office/components/admin/refresh-order-view.tsx | TypeScript |
TypeAliasDeclaration |
type FormData = {
orderId: string;
}; | andlju/swetugg-tix | back-office/components/admin/refresh-order-view.tsx | TypeScript |
MethodDeclaration |
handleSubmit(onSubmit) | andlju/swetugg-tix | back-office/components/admin/refresh-order-view.tsx | TypeScript |
InterfaceDeclaration |
export interface IDropDownItem extends React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>{
value: TDropDownValue;
} | hedgalex/plvideo | project/frontend/src/ui/dropdown/components/_ifaces/IDropDownItem.ts | TypeScript |
InterfaceDeclaration |
export interface LoggingClientContext {
/**
* The port where the logging server listens for logging events on the localhost
*/
readonly port: number;
/**
* The minimal log level to use for configuration
*/
readonly level: LogLevel;
} | Edgpaez/stryker-js | packages/core/src/logging/logging-client-context.ts | TypeScript |
ArrowFunction |
(iconProps: IFluentIconsProps, props: React.HTMLAttributes<HTMLElement>): JSX.Element => {
const {
primaryFill,
className
} = iconProps;
return <svg {...props} width={24} height={24} viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" className={className}><path d="M9 20.25V13.5H6.84a5.77 5.77 0 01-4.19 2.74 1 1 0 11-.3-1.98 4 4 0 001.85-.76H1.75a1 1 0 110-2h20.5a1 1 0 110 2H22v7a1 1 0 11-2 0v-7h-4.74l-.14 1.35 2.76-.34a1 1 0 01.24 1.98l-4 .5a1 1 0 01-1.11-1.09l.23-2.4H11v6.75a1 1 0 11-2 0zm13-9.75V5a1 1 0 10-2 0v5.5h2zm-6.45 0L16 6.1a1 1 0 10-1.98-.2l-.46 4.6h2zm-4.55 0V4.75a1 1 0 10-2 0v5.75h2zm-3.11 0C7.97 9.97 8 9.46 8 9a1 1 0 00-1-1H2.5a1 1 0 100 2h3.44l-.08.5h2.03z" fill={primaryFill} /></svg>;
} | LiquidatorCoder/fluentui-system-icons | packages/react-icons/src/components/StrikethroughGaNa24Filled.tsx | TypeScript |
ArrowFunction |
() => {
page = new NestJSBFFPage();
} | FernandoVezzali/nestjs-bff | frontend/e2e/app.e2e-spec.ts | TypeScript |
ArrowFunction |
() => {
page.navigateTo();
expect(page.getParagraphText()).toContain('NestJS-BFF');
} | FernandoVezzali/nestjs-bff | frontend/e2e/app.e2e-spec.ts | TypeScript |
FunctionDeclaration |
function warnFailedFetch(err: Error, path: string | string[]) {
if (!err.message.match('fetch')) {
console.error(err)
}
console.error(
`[hmr] Failed to reload ${path}. ` +
`This could be due to syntax errors or importing non-existent ` +
`modules. (see errors above)`
)
} | MarvinRudolph/vite | src/client/client.ts | TypeScript |
FunctionDeclaration |
async function handleMessage(payload: HMRPayload) {
const { path, changeSrcPath, timestamp } = payload as UpdatePayload
if (changeSrcPath) {
bustSwCache(changeSrcPath)
}
if (path && path !== changeSrcPath) {
bustSwCache(path)
}
switch (payload.type) {
case 'connected':
console.log(`[vite] connected.`)
break
case 'vue-reload':
queueUpdate(
import(`${path}?t=${timestamp}`)
.catch((err) => warnFailedFetch(err, path))
.then((m) => () => {
__VUE_HMR_RUNTIME__.reload(path, m.default)
console.log(`[vite] ${path} reloaded.`)
})
)
break
case 'vue-rerender':
const templatePath = `${path}?type=template`
bustSwCache(templatePath)
import(`${templatePath}&t=${timestamp}`).then((m) => {
__VUE_HMR_RUNTIME__.rerender(path, m.render)
console.log(`[vite] ${path} template updated.`)
})
break
case 'style-update':
// check if this is referenced in html via <link>
const el = document.querySelector(`link[href*='${path}']`)
if (el) {
bustSwCache(path)
el.setAttribute(
'href',
`${path}${path.includes('?') ? '&' : '?'}t=${timestamp}`
)
break
}
// imported CSS
const importQuery = path.includes('?') ? '&import' : '?import'
bustSwCache(`${path}${importQuery}`)
await import(`${path}${importQuery}&t=${timestamp}`)
console.log(`[vite] ${path} updated.`)
break
case 'style-remove':
removeStyle(payload.id)
break
case 'js-update':
queueUpdate(updateModule(path, changeSrcPath, timestamp))
break
case 'custom':
const cbs = customUpdateMap.get(payload.id)
if (cbs) {
cbs.forEach((cb) => cb(payload.customData))
}
break
case 'full-reload':
if (path.endsWith('.html')) {
// if html file is edited, only reload the page if the browser is
// currently on that page.
const pagePath = location.pathname
if (
pagePath === path ||
(pagePath.endsWith('/') && pagePath + 'index.html' === path)
) {
location.reload()
}
return
} else {
location.reload()
}
}
} | MarvinRudolph/vite | src/client/client.ts | TypeScript |
FunctionDeclaration | /**
* buffer multiple hot updates triggered by the same src change
* so that they are invoked in the same order they were sent.
* (otherwise the order may be inconsistent because of the http request round trip)
*/
async function queueUpdate(p: Promise<(() => void) | undefined>) {
queued.push(p)
if (!pending) {
pending = true
await Promise.resolve()
pending = false
const loading = [...queued]
queued = []
;(await Promise.all(loading)).forEach((fn) => fn && fn())
}
} | MarvinRudolph/vite | src/client/client.ts | TypeScript |
FunctionDeclaration |
export function updateStyle(id: string, content: string) {
let style = sheetsMap.get(id)
if (supportsConstructedSheet && !content.includes('@import')) {
if (style && !(style instanceof CSSStyleSheet)) {
removeStyle(id)
style = undefined
}
if (!style) {
style = new CSSStyleSheet()
style.replaceSync(content)
// @ts-ignore
document.adoptedStyleSheets = [...document.adoptedStyleSheets, style]
} else {
style.replaceSync(content)
}
} else {
if (style && !(style instanceof HTMLStyleElement)) {
removeStyle(id)
style = undefined
}
if (!style) {
style = document.createElement('style')
style.setAttribute('type', 'text/css')
style.innerHTML = content
document.head.appendChild(style)
} else {
style.innerHTML = content
}
}
sheetsMap.set(id, style)
} | MarvinRudolph/vite | src/client/client.ts | TypeScript |
FunctionDeclaration |
function removeStyle(id: string) {
let style = sheetsMap.get(id)
if (style) {
if (style instanceof CSSStyleSheet) {
// @ts-ignore
const index = document.adoptedStyleSheets.indexOf(style)
// @ts-ignore
document.adoptedStyleSheets = document.adoptedStyleSheets.filter(
(s: CSSStyleSheet) => s !== style
)
} else {
document.head.removeChild(style)
}
sheetsMap.delete(id)
}
} | MarvinRudolph/vite | src/client/client.ts | TypeScript |
FunctionDeclaration |
async function updateModule(
id: string,
changedPath: string,
timestamp: number
) {
const mod = hotModulesMap.get(id)
if (!mod) {
console.error(
`[vite] got js update notification for "${id}" but no client callback ` +
`was registered. Something is wrong.`
)
console.error(hotModulesMap)
return
}
const moduleMap = new Map()
const isSelfUpdate = id === changedPath
// make sure we only import each dep once
const modulesToUpdate = new Set<string>()
if (isSelfUpdate) {
// self update - only update self
modulesToUpdate.add(id)
} else {
// dep update
for (const { deps } of mod.callbacks) {
if (Array.isArray(deps)) {
deps.forEach((dep) => modulesToUpdate.add(dep))
} else {
modulesToUpdate.add(deps)
}
}
}
// determine the qualified callbacks before we re-import the modules
const callbacks = mod.callbacks.filter(({ deps }) => {
return Array.isArray(deps)
? deps.some((dep) => modulesToUpdate.has(dep))
: modulesToUpdate.has(deps)
})
await Promise.all(
Array.from(modulesToUpdate).map(async (dep) => {
const disposer = disposeMap.get(dep)
if (disposer) await disposer(dataMap.get(dep))
try {
const newMod = await import(
dep + (dep.includes('?') ? '&' : '?') + `t=${timestamp}`
)
moduleMap.set(dep, newMod)
} catch (e) {
warnFailedFetch(e, dep)
}
})
)
return () => {
for (const { deps, fn } of callbacks) {
if (Array.isArray(deps)) {
fn(deps.map((dep) => moduleMap.get(dep)))
} else {
fn(moduleMap.get(deps))
}
}
console.log(`[vite]: js module hot updated: `, id)
}
} | MarvinRudolph/vite | src/client/client.ts | TypeScript |
FunctionDeclaration |
function bustSwCache(path: string) {
const sw = navigator.serviceWorker && navigator.serviceWorker.controller
if (sw) {
return new Promise((r) => {
const channel = new MessageChannel()
channel.port1.onmessage = (e) => {
if (e.data.busted) r()
}
sw.postMessage(
{
type: 'bust-cache',
path: `${location.protocol}//${location.host}${path}`
},
[channel.port2]
)
})
}
} | MarvinRudolph/vite | src/client/client.ts | TypeScript |
ArrowFunction |
async () => {
const hasExistingSw = !!navigator.serviceWorker.controller
const prompt = (msg: string) => {
if (confirm(msg)) {
location.reload()
} else {
console.warn(msg)
}
}
if (__SW_ENABLED__) {
// if not enabled but has existing sw, registering the sw will force the
// cache to be busted.
try {
navigator.serviceWorker.register('/sw.js')
} catch (e) {
console.log('[vite] failed to register service worker:', e)
}
// Notify the user to reload the page if a new service worker has taken
// control.
if (hasExistingSw) {
navigator.serviceWorker.addEventListener('controllerchange', () =>
prompt(`[vite] Service worker cache invalidated. Reload is required.`)
)
} else {
console.log(`[vite] service worker registered.`)
}
} else if (hasExistingSw) {
for (const reg of await navigator.serviceWorker.getRegistrations()) {
await reg.unregister()
}
prompt(
`[vite] Unregistered stale service worker. ` +
`Reload is required to invalidate cache.`
)
}
} | MarvinRudolph/vite | src/client/client.ts | TypeScript |
ArrowFunction |
(msg: string) => {
if (confirm(msg)) {
location.reload()
} else {
console.warn(msg)
}
} | MarvinRudolph/vite | src/client/client.ts | TypeScript |
ArrowFunction |
() =>
prompt(`[vite] Service worker cache invalidated. Reload is required.`) | MarvinRudolph/vite | src/client/client.ts | TypeScript |
ArrowFunction |
async ({ data }) => {
const payload = JSON.parse(data) as HMRPayload | MultiUpdatePayload
if (payload.type === 'multi') {
payload.updates.forEach(handleMessage)
} else {
handleMessage(payload)
}
} | MarvinRudolph/vite | src/client/client.ts | TypeScript |
ArrowFunction |
(err) => warnFailedFetch(err, path) | MarvinRudolph/vite | src/client/client.ts | TypeScript |
ArrowFunction |
(m) => () => {
__VUE_HMR_RUNTIME__.reload(path, m.default)
console.log(`[vite] ${path} reloaded.`)
} | MarvinRudolph/vite | src/client/client.ts | TypeScript |
ArrowFunction |
() => {
__VUE_HMR_RUNTIME__.reload(path, m.default)
console.log(`[vite] ${path} reloaded.`)
} | MarvinRudolph/vite | src/client/client.ts | TypeScript |
ArrowFunction |
(m) => {
__VUE_HMR_RUNTIME__.rerender(path, m.render)
console.log(`[vite] ${path} template updated.`)
} | MarvinRudolph/vite | src/client/client.ts | TypeScript |
ArrowFunction |
(cb) => cb(payload.customData) | MarvinRudolph/vite | src/client/client.ts | TypeScript |
ArrowFunction |
(fn) => fn && fn() | MarvinRudolph/vite | src/client/client.ts | TypeScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.