Datasets:

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
6e0cf66fc9100ebc830cc642e6bc23b4ed375c13
TypeScript
WangHL0927/grafana
/packages/grafana-data/src/utils/labels.ts
3.1875
3
import { Labels } from '../types/data'; /** * Regexp to extract Prometheus-style labels */ const labelRegexp = /\b(\w+)(!?=~?)"([^"\n]*?)"/g; /** * Returns a map of label keys to value from an input selector string. * * Example: `parseLabels('{job="foo", instance="bar"}) // {job: "foo", instance: "bar"}` */ export function parseLabels(labels: string): Labels { const labelsByKey: Labels = {}; labels.replace(labelRegexp, (_, key, operator, value) => { labelsByKey[key] = value; return ''; }); return labelsByKey; } /** * Returns a map labels that are common to the given label sets. */ export function findCommonLabels(labelsSets: Labels[]): Labels { return labelsSets.reduce((acc, labels) => { if (!labels) { throw new Error('Need parsed labels to find common labels.'); } if (!acc) { // Initial set acc = { ...labels }; } else { // Remove incoming labels that are missing or not matching in value Object.keys(labels).forEach(key => { if (acc[key] === undefined || acc[key] !== labels[key]) { delete acc[key]; } }); // Remove common labels that are missing from incoming label set Object.keys(acc).forEach(key => { if (labels[key] === undefined) { delete acc[key]; } }); } return acc; }, (undefined as unknown) as Labels); } /** * Returns a map of labels that are in `labels`, but not in `commonLabels`. */ export function findUniqueLabels(labels: Labels, commonLabels: Labels): Labels { const uncommonLabels: Labels = { ...labels }; Object.keys(commonLabels).forEach(key => { delete uncommonLabels[key]; }); return uncommonLabels; } /** * Serializes the given labels to a string. */ export function formatLabels(labels: Labels, defaultValue = ''): string { if (!labels || Object.keys(labels).length === 0) { return defaultValue; } const labelKeys = Object.keys(labels).sort(); const cleanSelector = labelKeys.map(key => `${key}="${labels[key]}"`).join(', '); return ['{', cleanSelector, '}'].join(''); }
e595855b74733dd484e0bae5f19014c328d64013
TypeScript
taosut/SourceBin
/backend/src/models/User.ts
2.71875
3
import mongoose from 'mongoose'; import * as uuid from 'uuid'; export interface User extends mongoose.Document { _id: string; email: string; username: string; about: { avatarURL?: string; bio?: string; website?: string; location?: string; }; oauth: { discord?: string; github?: string; }; plan: 'Free' | 'Pro'; payments: { stripeId?: string; }; createdAt: Date; } const userSchema = new mongoose.Schema({ _id: { type: String, required: true, default: uuid.v4, }, email: { type: String, unique: true, required: true, }, username: { type: String, required: true, }, about: { avatarURL: String, bio: String, website: String, location: String, }, oauth: { discord: String, github: String, }, plan: { type: String, enum: ['Free', 'Pro'], required: true, default: 'Free', }, payments: { stripeId: String, }, createdAt: { type: Date, required: true, default: Date.now, }, }); export const UserModel = mongoose.model<User>('User', userSchema);
3cc64f45ce10ca171a073b11f8064f781be01c8d
TypeScript
MarkMatute/MarkMatute.github.io
/src/models/projects.ts
2.65625
3
export class Project { title?: string; subTitle?: string; image?: string; company?: string; description?: string; technologies?: string[]; tags?: string[]; liveLink?: string; slug?: string; } export const PROJECTS: Project[] = [ { title: 'Open Source Projects', subTitle: 'REST API templates, personal projects, Open source tools', image: '/images/9.png', company: 'SimpleIdeaLabs', description: ` <div> <a href="https://github.com/SimpleIdeaLabs/nestjs-starter-template" target="_blank"> <h6>nestjs-starter-template</h6> </a> <p> This is a robust API boilerplate built with NestJS, designed to provide essential out-of-the-box features for your project. With this boilerplate, you'll have access to key features like a Dockerized app, TDD E2E testing, comprehensive logging, and user login functionality. Whether you're a seasoned developer or just starting out, this boilerplate will save you time and effort by providing a solid foundation for your project. </p> <hr /> <a href="https://github.com/SimpleIdeaLabs/simple-ts" target="_blank"> <h6>simple-ts</h6> </a> <p> This is a TypeScript boilerplate that comes with all the essential tools you need for software development. It includes automatic code formatting with eslint and prettier, mandatory code standard implementation with husky, testing with Jest, and a Docker development setup. </p> <hr/> <a href="https://github.com/MarkMatute/node-modules-browser" target="_blank"> <h6>node-modules-browser</h6> </a> <p> Our tool generates a simple HTML file that shows your Node dependencies. It reads your project's package.json file, making it easy to manage your dependencies. With our tool, you can view your dependencies in a clear and straightforward format, eliminating the need to navigate through a long list of dependencies in your terminal. </p> </div> `, technologies: ['nodejs', 'react', 'redux', 'typescript', 'javascript', 'nestjs', 'docker', 'aws'], tags: ['microservice', 'nodejs', 'typescript', 'opensource'], liveLink: '', slug: 'open-source' }, { title: 'File Service', subTitle: 'REST API to handle file upload and download.', image: '/images/1.png', company: 'Healthbeats', description: ` The implementation of a robust microservice that can handle all file uploads and downloads in a centralized location is an important and strategic decision. This type of microservice not only helps to streamline file management across different systems and applications, but also provides an extra layer of security by ensuring that all access to files is authenticated, preventing unauthorized access or file leakage. <br /> <br /> In order to further enhance the security of this microservice, strict measures must be put in place during the file upload process. By implementing a file validation system, the microservice can ensure that only expected file types and file sizes are uploaded. This will help to mitigate the risk of uploading malicious files or files that may cause system failures due to their size. <br /> <br /> To further protect against malware or viruses, an antivirus scanning system can also be implemented to scan all files during the upload process. This allows the microservice to identify and remove any potentially harmful files before they are uploaded to Amazon S3, mitigating the risk of malware or virus infections. <br /> <br /> Overall, the implementation of a centralized file management microservice, combined with strict file validation and antivirus scanning, provides a robust and secure solution for managing file uploads and downloads across multiple systems and applications. `, technologies: ['nodejs', 'typescript', 'javascript', 'nestjs', 'clamav', 'docker', 'aws'], tags: ['microservice', 'nodejs', 'typescript', 'rest-api'], liveLink: '', slug: 'healthbeats-file-service' }, { title: 'Reporting Service', subTitle: 'REST API to handle complex data generation.', image: '/images/2.png', company: 'Healthbeats', description: ` Our microservice REST API is the perfect solution for any project that requires computing patient data for generating PDF and CSV reports. Our service is equipped with robust features that make it efficient, reliable, and easy to use. One of its most significant benefits is that it is connected to Snowflake, providing you with a secure and reliable way to store and manage your data. Additionally, our API includes extensive logging that enables you to track and troubleshoot any issues that may arise. <br/><br/> Another great feature of our microservice is that it comes with TDD e2e testing, ensuring that your code is always up to par. With this feature, you can easily test your application and ensure that it meets your requirements before deployment. And, thanks to our Dockerization, you can easily deploy and scale our service to meet the demands of your application. <br/><br/> In summary, our microservice REST API offers a robust set of features that make it an excellent choice for any project that requires patient data computation for generating PDF and CSV reports. Its integration with Snowflake, extensive logging, TDD e2e testing, and Dockerization are just a few of the many benefits that make it the ideal choice for any developer. `, technologies: ['nodejs', 'typescript', 'javascript', 'nestjs', 'docker', 'aws'], tags: ['microservice', 'nodejs', 'typescript', 'rest-api'], liveLink: '', slug: 'healthbeats-reporting-service' }, { title: 'Healthbeats Service', subTitle: 'REST API to power Healthbeats platform.', image: '/images/3.png', company: 'Healthbeats', description: ` Our REST API service is the backbone of our company, providing the core functionality that powers our web and mobile applications. With a range of features such as alert generation and notifications, this service serves both our internal needs and the needs of our customers. We have designed our service to be versatile and scalable, allowing us to meet the ever-changing demands of our business. <br/><br/> One of the most significant benefits of our API is the extensive access control list (ACL) management. This feature is crucial, given that we handle patient data, and even the slightest mistake can have severe consequences. Our ACL management system is designed to ensure that only authorized personnel can access the data, and every action taken is carefully logged and monitored. Additionally, we have implemented a complete API registration and configuration process to streamline the management of our service. <br/><br/> Managing a complex API with over 300 endpoints can be challenging, but we have put in place a system to make it as streamlined as possible. Our team has worked tirelessly to ensure that every aspect of our service is thoroughly tested and optimized, ensuring maximum performance and reliability. With this level of attention to detail, we can confidently say that our REST API is one of the most robust and reliable services available in the market today. <br/><br/> In summary, our REST API service is the lifeblood of our business, powering our web and mobile applications with its extensive range of features. We have implemented a range of systems and processes to ensure that our API is secure, reliable, and efficient. With extensive ACL management, complete API registration and configuration, and thorough testing and optimization, we have created a service that we are proud to offer to our customers. `, technologies: ['nodejs', 'typescript', 'javascript', 'express', 'docker', 'aws'], tags: ['microservice', 'nodejs', 'typescript', 'rest-api'], liveLink: '', slug: 'healthbeats-platform-service' }, { title: 'Healthbeats Web App', subTitle: 'Web App to empower Health Providers.', image: '/images/4.png', company: 'Healthbeats', description: ` Our web dashboard, built using React technologies, provides multi-tenant users with comprehensive data tables, profiles, and report displays. It's user-friendly, highly customizable, and designed to meet the needs of businesses of all sizes. Whether you need to monitor key metrics, track KPIs, or generate custom reports, our dashboard is designed to help you make informed decisions. <hr/> <div id="carouselExampleIndicators" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="1" aria-label="Slide 2"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="2" aria-label="Slide 3"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="3" aria-label="Slide 4"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="4" aria-label="Slide 5"></button> </div> <div class="carousel-inner"> <div class="carousel-item active"> <img src="/images/projects/healthbeats/1.png" class="d-block w-100" alt="First slide"> </div> <div class="carousel-item"> <img src="/images/projects/healthbeats/2.png" class="d-block w-100" alt="Second slide"> </div> <div class="carousel-item"> <img src="/images/projects/healthbeats/3.png" class="d-block w-100" alt="Third slide"> </div> <div class="carousel-item"> <img src="/images/projects/healthbeats/4.png" class="d-block w-100" alt="Fourth slide"> </div> <div class="carousel-item"> <img src="/images/projects/healthbeats/5.png" class="d-block w-100" alt="Fifth slide"> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> `, technologies: ['react', 'redux', 'materialui', 'docker'], tags: ['web-app', 'react', 'material-ui'], liveLink: '', slug: 'healthbeats-web-app' }, { title: 'Healthbeats Mobile App', subTitle: 'Mobile App to extend Healthbeats to patients.', image: '/images/5.png', company: 'Healthbeats', description: ` The Healthbeat mobile app, built with hybrid technologies such as React Native, empowers customers with advanced health tech capabilities that connect with IoT devices to take vital signs. This exciting app brings the power of Healthbeat's platform into the hands of users, providing them with a seamless and intuitive experience. <hr/> <div id="carouselExampleIndicators" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="1" aria-label="Slide 2"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="2" aria-label="Slide 3"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="3" aria-label="Slide 4"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="4" aria-label="Slide 5"></button> </div> <div class="carousel-inner"> <div class="carousel-item active"> <img src="/images/projects/healthbeats/6.png" class="d-block w-100" alt="First slide"> </div> <div class="carousel-item"> <img src="/images/projects/healthbeats/7.png" class="d-block w-100" alt="Second slide"> </div> <div class="carousel-item"> <img src="/images/projects/healthbeats/8.png" class="d-block w-100" alt="Third slide"> </div> <div class="carousel-item"> <img src="/images/projects/healthbeats/9.png" class="d-block w-100" alt="Fourth slide"> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> `, technologies: ['react', 'redux', 'swift', 'android'], tags: ['react', 'react-native', 'ios','android', 'mobile-app'], liveLink: '', slug: 'healthbeats-mobile-app' }, { title: 'Dishqou Mobile App', subTitle: 'Meal planning platform.', image: '/images/6.png', company: 'Dishqou', description: ` Elevate your nutrition planning game with the ultimate solution designed specifically for health professionals. <br/> Streamline your workflow and provide your clients with personalized nutrition plans that cater to their unique needs and goals. <br/> With our cutting-edge platform, you can empower your clients to take control of their health and wellness like never before. `, technologies: ['react', 'redux', 'swift', 'android'], tags: ['react', 'react-native', 'ios','android', 'mobile-app'], liveLink: '', slug: 'dishqou-mobile-app' }, { title: 'Driftr Service', subTitle: 'REST API to power Driftr Mobile App.', image: '/images/8.png', company: 'Driftr', description: ` The REST API service powering the Driftr Mobile App utilizes AWS RDS to store data and AWS S3 for file storage, designed with simplicity and robustness in mind. <br/><br/> What sets this service apart is its utilization of AWS EKS for deployment, along with social media integrations, messaging, and a host of other features. `, technologies: ['nodejs', 'typescript', 'javascript', 'nestjs', 'docker', 'aws'], tags: ['microservice', 'nodejs', 'typescript', 'rest-api'], liveLink: '', slug: 'driftr-service' }, { title: 'Driftr Mobile App', subTitle: 'Tindr inspired car matching app.', image: '/images/7.png', company: 'Driftr', description: ` Built with hybrid technologies like React Native and inspired by Tinder, this mobile app is designed to help users find cars around the world with a seamless swiping experience. With its intuitive user interface, this app is the perfect tool for browsing cars and finding the perfect match. <hr/> <div id="carouselExampleIndicators" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="1" aria-label="Slide 2"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="2" aria-label="Slide 3"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="3" aria-label="Slide 4"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="4" aria-label="Slide 5"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="5" aria-label="Slide 6"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="6" aria-label="Slide 7"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="7" aria-label="Slide 8"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="8" aria-label="Slide 9"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="9" aria-label="Slide 10"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="10" aria-label="Slide 11"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="11" aria-label="Slide 12"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="12" aria-label="Slide 13"></button> </div> <div class="carousel-inner"> <div class="carousel-item active"> <img src="/images/projects/driftr/1.png" class="d-block w-100" alt="First slide"> </div> <div class="carousel-item"> <img src="/images/projects/driftr/2.png" class="d-block w-100" alt="First slide"> </div> <div class="carousel-item"> <img src="/images/projects/driftr/3.png" class="d-block w-100" alt="First slide"> </div> <div class="carousel-item"> <img src="/images/projects/driftr/4.png" class="d-block w-100" alt="First slide"> </div> <div class="carousel-item"> <img src="/images/projects/driftr/5.png" class="d-block w-100" alt="First slide"> </div> <div class="carousel-item"> <img src="/images/projects/driftr/6.png" class="d-block w-100" alt="First slide"> </div> <div class="carousel-item"> <img src="/images/projects/driftr/7.png" class="d-block w-100" alt="First slide"> </div> <div class="carousel-item"> <img src="/images/projects/driftr/8.png" class="d-block w-100" alt="First slide"> </div> <div class="carousel-item"> <img src="/images/projects/driftr/9.png" class="d-block w-100" alt="First slide"> </div> <div class="carousel-item"> <img src="/images/projects/driftr/10.png" class="d-block w-100" alt="First slide"> </div> <div class="carousel-item"> <img src="/images/projects/driftr/11.png" class="d-block w-100" alt="First slide"> </div> <div class="carousel-item"> <img src="/images/projects/driftr/12.png" class="d-block w-100" alt="First slide"> </div> <div class="carousel-item"> <img src="/images/projects/driftr/13.png" class="d-block w-100" alt="First slide"> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> `, technologies: ['react', 'redux', 'swift', 'android'], tags: ['react', 'react-native', 'ios','android', 'mobile-app'], liveLink: '', slug: 'driftr-mobile-app' }, ];
ec981d094e76b0758b4a28a063b0589807afef94
TypeScript
sean-hammon/phogra-ui2
/src/admin/store/admin.reducer.ts
2.625
3
import { AdminState, initialState } from './admin.state'; import { AdminActions, ReducerAction } from './admin.actions'; export function adminReducer( state: AdminState = initialState, action: ReducerAction ): AdminState { switch (action.type) { case AdminActions.LOGIN_SUCCESS: console.log('reducer', action.payload); return {...state, user: action.payload }; case AdminActions.LOGIN_ERROR: console.log('reducer', action.payload); console.log(state); return {...state, apiError: action.payload }; default: return state; } }
ceaf03adfe4196771388d711b192ac2f79bd3411
TypeScript
OhioUniversityRevUC2020/APIServer
/src/routes/UserRoute.ts
2.53125
3
import { Body, Get, JsonController, Param, Post, QueryParam } from 'routing-controllers'; import { Inject } from 'typedi'; import { UserService } from '../services/UserService'; @JsonController('/user') export class UserRoute { @Inject() private userService!: UserService; @Post('/link') async link( @Body() body: { userId: string; minecraftName: string; }, ): Promise<any> { const { userId, minecraftName } = body; try { await this.userService.linkAccount(userId, minecraftName); return { success: true, }; } catch (e) { return { success: false, error: e.message, }; } } @Get('/credits') async credits(@QueryParam('id') id: string): Promise<any> { try { const credits: number[] = await this.userService.getCredits(id); return { success: true, credits: credits[0], }; } catch (e) { return { success: false, error: e.message, }; } } }
9aa032b753a58d0b06f8ea049e0b867a7ad69054
TypeScript
soitun/tabris-js
/test/typescript/Widgets/Picker.test.ts
2.71875
3
import {ColorValue, Picker, PickerSelectEvent, Properties, PropertyChangedEvent, FontValue} from 'tabris'; let widget: Picker = new Picker(); // Properties let borderColor: ColorValue; let itemCount: number; let itemText: (index: number) => string; let selectionIndex: number; let textColor: ColorValue; let font: FontValue; let message: string; let floatMessage: boolean; let style: 'default' | 'outline' | 'fill' | 'underline' | 'none'; borderColor = widget.borderColor; itemCount = widget.itemCount; itemText = widget.itemText; selectionIndex = widget.selectionIndex; textColor = widget.textColor; font = widget.font; message = widget.message; floatMessage = widget.floatMessage; style = widget.style; widget.borderColor = borderColor; widget.itemCount = itemCount; widget.itemText = itemText; widget.selectionIndex = selectionIndex; widget.textColor = textColor; widget.font = font; widget.message = message; widget.floatMessage = floatMessage; widget.style = style; let properties = {borderColor, itemCount, itemText, selectionIndex, textColor, font, style, message, floatMessage}; widget = new Picker(properties); widget.set(properties); // Events let target: Picker = widget; let timeStamp: number = 0; let type: string = 'foo'; let index: number = 0; let value: number = 0; let selectionIndexChangedEvent: PropertyChangedEvent<Picker, number> = {target, timeStamp, type, value}; let pickerSelectEvent: PickerSelectEvent = {target, timeStamp, type, index}; widget .onSelectionIndexChanged((event: PropertyChangedEvent<Picker, number>) => {}) .onSelect((event: PickerSelectEvent) => {}); class CustomComponent extends Picker { public foo: string; constructor(props: Properties<Picker> & Partial<Pick<CustomComponent, 'foo'>>) { super(props); } } new CustomComponent({foo: 'bar'}).set({foo: 'bar'});
2a7b31333e37c7ac19f699d19f7449ffc61ceb17
TypeScript
green-fox-academy/gulyaasjaanos
/inheritance/garden-app/Tree.ts
2.609375
3
"use strict"; import {Plant} from "./Plant"; class Tree extends Plant { public static absorb:number = 0.40; private static type:string = "Tree"; constructor (color:string, wateramount:number) { super(color, wateramount, Tree.absorb, Tree.type); } } export {Tree};
04d99e4125cd13f487e41ac67febd03f465a65dd
TypeScript
composablesys/collabs
/crdts/src/base_collabs/abstract_maps.d.ts
2.9375
3
import { IMap, MapEventsRecord } from "@collabs/core"; import { PrimitiveCRDT } from "./primitive_crdt"; /** * Skeletal implementation of the [[IMap]] interface, as a subclass of * [[PrimitiveCRDT]]. * * This class is a convenience for Collab implementers. It provides * some default method implementations and leaves the others abstract. */ export declare abstract class AbstractMap_PrimitiveCRDT< K, V, SetArgs extends unknown[] = [V], Events extends MapEventsRecord<K, V> = MapEventsRecord<K, V> > extends PrimitiveCRDT<Events> implements IMap<K, V, SetArgs, Events> { clear(): void; forEach( callbackfn: (value: V, key: K, map: this) => void, thisArg?: any // eslint-disable-line @typescript-eslint/no-explicit-any ): void; [Symbol.iterator](): IterableIterator<[K, V]>; keys(): IterableIterator<K>; values(): IterableIterator<V>; toString(): string; keyOf(searchElement: V): K | undefined; abstract set(key: K, ...args: SetArgs): V | undefined; abstract delete(key: K): void; abstract get(key: K): V | undefined; abstract has(key: K): boolean; abstract entries(): IterableIterator<[K, V]>; abstract readonly size: number; }
a4d4cbdd6018cf54c983933eb6c89d67014e4da9
TypeScript
LinuCC/guren-tree
/src/use-count-to.ts
2.84375
3
import { useInterval } from "./use-interval"; import { useState, useEffect } from "react"; export const useCountTo = ({ max, delay }: { max: number; delay: number | null; }): number => { const [count, setCount] = useState(0); const [delayStatus, setDelayStatus] = useState<number | null>(delay); useEffect(() => { setDelayStatus(delay); }, [delay]); useInterval(() => { if (count < max) { setCount(count + 1); } if (count >= max) { // Stop the timer setDelayStatus(null); } }, delayStatus); return count; };
cc3d9e3fe026ba7ac4807decd6094c30c3ad38a4
TypeScript
nargok/ts_playground
/src/constructor-parameters.ts
3.8125
4
export {}; class Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } } let taro = new Person("taro", 43); console.log({ taro }); type PersonType = typeof Person; type Profile = ConstructorParameters<PersonType>; const profile: Profile = ["boy", 23]; const boy = new Person(...profile); console.log({ boy }); type MyConstructorParameters< T extends new (...args: any) => any > = T extends new (...args: infer P) => any ? P : never;
e290b63f0148d423ab0e8d6687b44d0cdc27e497
TypeScript
frothywater/quick-sort-visualize
/api/generateRandomNumbers.ts
2.921875
3
export default function generateRandomNumbers(count: number): number[] { const array = new Array<number>(count); for (let i = 0; i < count; i++) array[i] = Math.random(); return array; }
b65dd8c9de01d1753073782334f663df078b9b70
TypeScript
Mahluza/Code-Checker
/server/tests/FileMatch.spec.ts
2.6875
3
import { expect } from 'chai' import CodeMatch from '../src/models/comparision/CodeMatch' import FileMatch from '../src/models/comparision/FileMatch' import FileModel from '../src/models/content/FileModel' import SyntaxTreeNode from '../src/models/content/SyntaxTreeNode' describe('tests for FileMatch', () => { let file1: string = 'let a = 3' let file2: string = 'let b = 3' let fModel1 = new FileModel('file1.ts', file1, '') let fModel2 = new FileModel('file2.ts', file2, '') let file_match = new FileMatch(fModel1, fModel2) let child1 = [new SyntaxTreeNode(229, 1, 1, '229.247.246.78.8', null)] let s1: SyntaxTreeNode = new SyntaxTreeNode(294, 1, 1, '229.247.246.78.8', child1, []) let s2: SyntaxTreeNode = new SyntaxTreeNode(294, 1, 1, '229.247.246.78.8', child1, []) let code_match = new CodeMatch(s1, s2, 100) file_match.addCodeMatch(code_match) it('FileMatch for files with simple statements', () => { expect(file_match.getSimilarities()).to.deep.equal([ { id: 0, codeMatch: { node1: { nodeType: 294, startLineNumber: 1, endLineNumber: 1, hashCode: '229.247.246.78.8', children: [ { nodeType: 229, startLineNumber: 1, endLineNumber: 1, hashCode: '229.247.246.78.8', children: null, commentLines: [], }, ], commentLines: [], }, node2: { nodeType: 294, startLineNumber: 1, endLineNumber: 1, hashCode: '229.247.246.78.8', children: [ { nodeType: 229, startLineNumber: 1, endLineNumber: 1, hashCode: '229.247.246.78.8', children: null, commentLines: [], }, ], commentLines: [], }, type: 'COMPLETE_MATCH', rangeOfNode1: [1, 1], rangeOfNode2: [1, 1], }, similarity: 100, }, ]) }) })
a8638da8d5762d9ba8155bd15b2d7afa941d5c91
TypeScript
dbgeek/codewars
/typescriptKatas/JosephusSurvivor/index.ts
3.671875
4
export function josephusSurvivor(n: number, k: number) { const d: number[] = [...Array(n +1).keys()]; d.shift(); let p = 0; while (d.length > 1) { p = (p + k-1) % d.length d.splice(p ,1) } return d[0] } console.log(josephusSurvivor(7,3), 4) console.log(josephusSurvivor(7,300), 7) console.log(josephusSurvivor(100,1), 100) console.log(josephusSurvivor(300,300), 265)
4355dfc1d25c45b77b1f11183b3b59c4cce38fe8
TypeScript
thiagozf/warthog
/src/torm/operators.ts
2.984375
3
import { SelectQueryBuilder } from 'typeorm'; export function addQueryBuilderWhereItem<E>( qb: SelectQueryBuilder<E>, dbColumn: string, columnWithAlias: string, operator: string, value: any ): SelectQueryBuilder<E> { switch (operator) { case 'eq': if (value === null) { return qb.andWhere(`${columnWithAlias} IS NULL`); } return qb.andWhere(`${columnWithAlias} = :${dbColumn}`, { [dbColumn]: value }); case 'not': return qb.andWhere(`${columnWithAlias} != :${dbColumn}`, { [dbColumn]: value }); case 'lt': return qb.andWhere(`${columnWithAlias} < :${dbColumn}`, { [dbColumn]: value }); case 'lte': return qb.andWhere(`${columnWithAlias} <= :${dbColumn}`, { [dbColumn]: value }); case 'gt': return qb.andWhere(`${columnWithAlias} > :${dbColumn}`, { [dbColumn]: value }); case 'gte': return qb.andWhere(`${columnWithAlias} >= :${dbColumn}`, { [dbColumn]: value }); case 'in': // IN (:... is the syntax for exploding array params into (?, ?, ?) in QueryBuilder return qb.andWhere(`${columnWithAlias} IN (:...${dbColumn})`, { [dbColumn]: value }); case 'contains': return qb.andWhere(`LOWER(${columnWithAlias}) LIKE :${dbColumn}`, { [dbColumn]: `%${value}%` }); case 'startsWith': return qb.andWhere(`LOWER(${columnWithAlias}) LIKE :${dbColumn}`, { [dbColumn]: `${value}%` }); case 'endsWith': return qb.andWhere(`LOWER(${columnWithAlias}) LIKE :${dbColumn}`, { [dbColumn]: `%${value}` }); default: throw new Error(`Can't find operator ${operator}`); } }
187ca01e6e4cd81d57aec42fcea0d85dbd8337b4
TypeScript
werk85/matechs-effect
/packages/core/src/next/Schedule/addDelayM.ts
2.921875
3
import { chain_ } from "../Effect/chain_" import { delay } from "../Effect/delay" import { Effect } from "../Effect/effect" import { succeedNow } from "../Effect/succeedNow" import { Schedule } from "./schedule" import { updated_ } from "./updated_" /** * Returns a new schedule with the effectfully calculated delay added to every update. */ export const addDelayM = <B, S1, R1>(f: (b: B) => Effect<S1, R1, never, number>) => < S, R, ST, A >( self: Schedule<S, R, ST, A, B> ) => updated_(self, (update) => (a, s) => chain_(f(self.extract(a, s)), (d) => chain_(update(a, s), (r) => delay(d)(succeedNow(r))) ) )
cf18c18bc7ba6bc22cabfb6cc0b5bc0df841e316
TypeScript
codeapps/angularRestarunt
/src/app/shared/calculator/calculator.component.ts
2.578125
3
import { Component, OnInit, HostListener, Inject } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; @Component({ selector: 'app-calculator', templateUrl: './calculator.component.html', styleUrls: ['./calculator.component.scss'] }) export class CalculatorComponent implements OnInit { private stack: (number | string)[]; display: string; tempHistory: string = ''; calcHistory: string; historyData = [{keys: '', result: ''}]; history_Pop: boolean = false; equalClick = false; constructor(public dialogRef: MatDialogRef<CalculatorComponent>, @Inject(MAT_DIALOG_DATA) public data: any ) { } ngOnInit() { this.display = '0'; this.stack = ['=']; } numberPressed(val: string) { if (typeof this.stack[this.stack.length - 1] !== 'number') { this.display = val; this.stack.push(parseFloat(this.display)); } else { this.display += val; this.stack[this.stack.length - 1] = parseFloat(this.display); } this.tempHistory += val; } round(value, decimals) { return Number(Math.round(value + decimals) + value + decimals); } operatorPressed(val: string) { const precedenceMap = { '+': 0, '-': 0, '*': 1, '/': 1 }; this.ensureNumber(); const precedence = precedenceMap[val]; let reduce = true; while (reduce) { let i = this.stack.length - 1; let lastPrecedence = 100; while (i >= 0) { if (typeof this.stack[i] === 'string') { lastPrecedence = precedenceMap[this.stack[i]]; break; } i--; } if (precedence <= lastPrecedence) { reduce = this.reduceLast(); } else { reduce = false; } } if (parseFloat(this.display)) { this.tempHistory += val; this.calcHistory = this.tempHistory; this.stack.push(val); } if (this.equalClick) { this.tempHistory = this.display += val; this.equalClick = false; } } equalPressed() { this.ensureNumber(); while (this.reduceLast()) { } this.stack.pop(); let dataCalc = {keys: this.tempHistory, result: this.display} this.tempHistory = '='; this.tempHistory = this.display; this.calcHistory = ''; this.historyData.push(dataCalc) if (this.display) { this.equalClick = true; } } percentPressed() { this.ensureNumber(); const num1:any = this.stack[1]; const num2:any = this.stack[3]; const operator = this.stack[2]; let result = this.stack.pop(); if(operator == '-' || operator == '+') { result = (num1*num2) as number / 100; } else { while (this.reduceLast()) { }; result = this.stack.pop() as number / 100; } this.display = result.toString(10); this.calcHistory += this.display; this.tempHistory = this.calcHistory; // this.stack.push(this.display); } acPressed() { this.stack = ['=']; this.display = '0'; this.tempHistory = ''; this.calcHistory = ''; } cePressed() { if (typeof this.stack[this.stack.length - 1] === 'number') { this.stack.pop(); } this.display = '0'; } backPrssed() { if (this.display.length) { this.display = this.display.substring(0, this.display.length - 1); this.tempHistory = this.display; } if (this.display.length == 0) { this.display = '0'; this.tempHistory = ''; } } private ensureNumber() { if (typeof this.stack[this.stack.length - 1] === 'string') { this.stack.push(parseFloat(this.display)); } } private reduceLast() { if (this.stack.length < 4) { return false; } const num2 = this.stack.pop() as number; const op = this.stack.pop() as string; const num1 = this.stack.pop() as number; let result = num1; switch (op) { case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '/': result = num1 / num2; break; } this.stack.push(result); this.display = result.toString(10); return true; } @HostListener('keydown', ['$event']) onkeyup(event) { event.preventDefault(); switch (event.keyCode) { case 96: this.numberPressed('0'); break; case 97: this.numberPressed('1'); break; case 98: this.numberPressed('2'); break; case 99: this.numberPressed('3'); break; case 100: this.numberPressed('4'); break; case 101: this.numberPressed('5'); break; case 102: this.numberPressed('6'); break; case 103: this.numberPressed('7'); break; case 104: this.numberPressed('8'); break; case 105: this.numberPressed('9'); break; case 110: this.numberPressed('.'); break; case 8: this.backPrssed();; break; case 106: this.operatorPressed('*'); break; case 111: this.operatorPressed('/'); break; case 109: this.operatorPressed('-'); break; case 107: this.operatorPressed('+'); break; case 187: this.equalPressed(); break; case 13: this.equalPressed(); break; case 53: if (event.shiftKey) { this.percentPressed(); } break; default: break; } } }
66a85c7adca6464dbf7cb72e2b8c050c0a4525d8
TypeScript
green-fox-academy/Hpeter1988
/week-01/day-3/define-basic-info.ts
3.078125
3
'use strict'; // Define several things as a variable, then print their values let myName: string = "Harasztia Péter" let myAge: number = 30 let myHight: number = 1.7 let married: boolean = false console.log(myName) console.log(myAge) console.log(myHight) console.log(married) export {};
c3ff2290a7a0a7dd11182daae19990c615a2b87b
TypeScript
postcasio/isogame
/src/game/editor/Cursor.ts
3.046875
3
import { EditorObjectMesh } from "."; export class Cursor { mesh?: EditorObjectMesh; x = 0; y = 0; z = 0; grabbedMesh?: EditorObjectMesh; grabbedWidth = 0; grabbedHeight = 0; grabbedDepth = 0; constructor(x: number, y: number, z: number) { this.x = x; this.y = y; this.z = z; } grabMesh( mesh: EditorObjectMesh, width: number, height: number, depth: number ): void { this.grabbedMesh = mesh; this.grabbedWidth = width; this.grabbedHeight = height; this.grabbedDepth = depth; this.updateMesh(); } hasMesh() { return this.grabbedMesh ? true : false; } getMesh() { return this.grabbedMesh; } releaseMesh(): EditorObjectMesh { const mesh = this.grabbedMesh!; this.grabbedMesh = undefined; return mesh; } setX(value: number) { this.x = value; this.updateMesh(); } setY(value: number) { this.y = value; this.updateMesh(); } setZ(value: number) { this.z = value; this.updateMesh(); } moveTo(x: number, y: number, z: number) { this.x = x; this.y = y; this.z = z; /** TODO THIS NORMAL */ this.updateMesh(); } setVisible(visible: boolean) { const mesh = this.getMesh(); if (mesh) { mesh.visible = visible; } } updateMesh() { this.getMesh()?.position.set( this.x * 1, (this.y + this.grabbedHeight / 2) * 1, this.z * 1 ); } }
011edd2a69139fe4f0405fcf73626d439ef7e458
TypeScript
xBATx/text-annotation-tool
/src/actions/index.ts
2.5625
3
import { Action } from 'redux'; import { SUBMIT_ARTICLE_MODAL, ADD_ANNOTATION, SELECT_TEXT, REMOVE_SELECTED_ELEMENT, RESET_SELECTION, SELECT_ANNOTATION, SET_ARTICLE_MODAL_OPENED, SET_ARTICLE_MODAL_TEXT, ADD_RELATION, SELECT_RELATION, SET_SHOW_RELATIONS, PREPARE_RELATION, } from 'src/constants'; import { Annotation, Relation, SelectedText } from 'src/types'; // Action types interface SelectTextType extends Action { type: typeof SELECT_TEXT; selectedText: SelectedText | null; } interface RemoveSelectedElementType extends Action { type: typeof REMOVE_SELECTED_ELEMENT; } interface ResetSelectionType extends Action { type: typeof RESET_SELECTION; } interface AddAnnotationType extends Action { type: typeof ADD_ANNOTATION; annotation: Annotation; } interface SelectAnnotationType extends Action { type: typeof SELECT_ANNOTATION; id: string | null; } interface PrepareRelationType extends Action { type: typeof PREPARE_RELATION; toA8nId: string | null; } interface AddRelationType extends Action { type: typeof ADD_RELATION; relation: Relation; } interface SelectRelationType extends Action { type: typeof SELECT_RELATION; id: string | null; } interface SetShowRelationsType extends Action { type: typeof SET_SHOW_RELATIONS; show: boolean; } // Article modal action types interface SetArticleModalOpenedType extends Action { type: typeof SET_ARTICLE_MODAL_OPENED; opened: boolean; } interface SetArticleModalTextType extends Action { type: typeof SET_ARTICLE_MODAL_TEXT; text: string; } interface SubmitArticleModalType extends Action { type: typeof SUBMIT_ARTICLE_MODAL; text: string; annotations: Annotation[]; relations: Relation[]; } // Action factories export const SelectText = ( selectedText: SelectedText | null, ): SelectTextType => ({ type: SELECT_TEXT, selectedText, }); export const RemoveSelectedElement: RemoveSelectedElementType = { type: REMOVE_SELECTED_ELEMENT, }; export const ResetSelection: ResetSelectionType = { type: RESET_SELECTION, }; export const AddAnnotation = (annotation: Annotation): AddAnnotationType => ({ type: ADD_ANNOTATION, annotation, }); export const SelectAnnotation = (id: string | null): SelectAnnotationType => ({ type: SELECT_ANNOTATION, id, }); export const PrepareRelation = ( toA8nId: string | null, ): PrepareRelationType => ({ type: PREPARE_RELATION, toA8nId, }); export const AddRelation = (relation: Relation): AddRelationType => ({ type: ADD_RELATION, relation, }); export const SelectRelation = (id: string | null): SelectRelationType => ({ type: SELECT_RELATION, id, }); export const SetShowRelations = (show: boolean): SetShowRelationsType => ({ type: SET_SHOW_RELATIONS, show, }); // Add article modal actions export const SetArticleModalOpened = ( opened: boolean, ): SetArticleModalOpenedType => ({ type: SET_ARTICLE_MODAL_OPENED, opened, }); export const SetArticleInput = (text: string): SetArticleModalTextType => ({ type: SET_ARTICLE_MODAL_TEXT, text, }); export const SubmitArticleModal = ( text: string, annotations: Annotation[], relations: Relation[], ): SubmitArticleModalType => ({ type: SUBMIT_ARTICLE_MODAL, text, annotations, relations, }); export type AppActions = | SelectTextType | RemoveSelectedElementType | ResetSelectionType | AddAnnotationType | SelectAnnotationType | PrepareRelationType | AddRelationType | SelectRelationType | SetShowRelationsType | SetArticleModalOpenedType | SetArticleModalTextType | SubmitArticleModalType;
729f4737c78dc17a7ff26ceab6a73132cbfe817e
TypeScript
dghalbr/wheeler
/src/expression.ts
3
3
import {Add, And, Divide, Equals, GreaterThan, GreaterThanOrEqualTo, LessThan, LessThanOrEqualTo, Modulo, Multiply, NotEquals, Or, Subtract } from './filters'; import {Cast, Length, Contains, Trim, Now} from './methods'; import {IExpression} from './expressions/iexpression'; import {UnaryExpression, BinaryExpression, ValueExpression, PropertyExpression, MethodExpression} from './expressions'; import {All, Any} from './lambdas'; export class Expression { public static add(left: number, right: number): IExpression public static add(left: IExpression, right: number): IExpression public static add(left: any, right: number) { left = Expression.expressionOrValue(left); return new Add(left, new ValueExpression(right)); } public static and(left: IExpression, right: IExpression): IExpression { return new And(left, right); } public static divide(left: number, right: number): IExpression public static divide(left: IExpression, right: number): IExpression public static divide(left: any, right: number) { left = Expression.expressionOrValue(left); return new Divide(left, new ValueExpression(right)); }; public static equals<Type, T>(param: (type: Type) => T, value: IExpression): IExpression public static equals<Type, T>(param: (type: Type) => T, value: T): IExpression public static equals<Type, T>(param: (type: Type) => T, value: any): IExpression public static equals<Type, T>(param: IExpression, value: any) public static equals<Type, T>(param: any, value: any) { let left: any; if (param.accept) { left = param; } else { left = new PropertyExpression(Expression.nameof(param)); } let right: any; if (value.accept) { right = value; } else { right = new ValueExpression(value); } return new Equals(left, right); } public static gt<Type, T>(left: (type: Type) => T, value: any): IExpression public static gt(left: IExpression, value: any): IExpression public static gt(left: any, value: any): IExpression { left = Expression.expressionOrValue(left); return new GreaterThan(left, new ValueExpression(value)); } public static gte<Type, T>(left: (type: Type) => T, value: any): IExpression public static gte(left: IExpression, value: any): IExpression public static gte(left: any, value: any): IExpression { left = Expression.expressionOrValue(left); return new GreaterThanOrEqualTo(left, new ValueExpression(value)); } public static lt<Type, T>(left: (type: Type) => T, value: any): IExpression public static lt(left: IExpression, value: any): IExpression public static lt(left: any, value: any): IExpression { left = Expression.expressionOrValue(left); return new LessThan(left, new ValueExpression(value)); } public static lte<Type, T>(left: (type: Type) => T, value: any): IExpression public static lte(left: IExpression, value: any): IExpression public static lte(left: any, value: any): IExpression { left = Expression.expressionOrValue(left); return new LessThanOrEqualTo(left, new ValueExpression(value)); } public static len<Type, T>(param: (type: Type) => T): IExpression { let propName = Expression.nameof(param); return new Length(new PropertyExpression(propName)); } public static mod(left: number, right: number): IExpression { return new Modulo(new ValueExpression(left), new ValueExpression(right)); } public static multiply(left: number, right: number): IExpression public static multiply(left: IExpression, right: number): IExpression public static multiply(left: any, right: number): IExpression { left = Expression.expressionOrValue(left); return new Multiply(left, new ValueExpression(right)); } public static nameof<Type, T>(param: (type: Type) => T): string { // Replace with nameof when typescript adds it. let varExtractor = new RegExp('return (.*);'); // HACK: cast to a string. let m = varExtractor.exec(param + ''); if (m == null) { throw new Error(`Cannot find return type for param (value: ${param})`); } let returnValue = m[1]; // drop the first lambda (that's the root object) let splits = returnValue.split('.'); splits.shift(); return splits.join().replace(',', '/'); } public static not_equals<Type, T>(param: (type: Type) => T, value: IExpression): IExpression public static not_equals<Type, T>(param: (type: Type) => T, value: T): IExpression public static not_equals<Type, T>(param: (type: Type) => T, value: any): IExpression { let propName = Expression.nameof(param); let right: any; if (value instanceof MethodExpression) { right = value; } else { right = new ValueExpression(value); } return new NotEquals(new PropertyExpression(propName), right); } public static or(left: IExpression, right: IExpression): IExpression { return new Or(left, right); } public static subtract(left: number, right: any): IExpression public static subtract(left: IExpression, right: any): IExpression public static subtract(left: any, right: any): IExpression { left = Expression.expressionOrValue(left); return new Subtract(left, new ValueExpression(right)); } public static cast<T, Type>(type: string, param?: (type: Type) => T): IExpression { let exps: IExpression[] = []; if (param) { let propName = Expression.nameof(param); exps.push(new PropertyExpression(propName)); } exps.push(new PropertyExpression(type)); return exps.length === 2 ? new Cast(exps[0], exps[1]) : new Cast(exps[0]); } public static top(param: number): IExpression { if (!param || param < 0) { throw new RangeError(`Parameter must be greater than zero (value: ${param})`); } return new UnaryExpression(new ValueExpression(param)); } public static skip(param: number): IExpression { if (!param || param < 0) { throw new RangeError(`Parameter must be greater than zero (value: ${param})`); } return new UnaryExpression(new ValueExpression(param)); } public static trim(v: string): IExpression { return new Trim(new ValueExpression(v)); } public static now(): IExpression { return new Now(); } public static contains<Type, T>(param: (type: Type) => T, value: T): IExpression public static contains<Type, T>(param: (type: Type) => T, value: IExpression): IExpression public static contains<Type, T>(param: (type: Type) => T, value: any): IExpression { let propName = Expression.nameof(param); let right: any; if (value instanceof MethodExpression) { right = value; } else { right = new ValueExpression(value); } return new Contains(new PropertyExpression(propName), right); } public static any<Type, T>(param: (type: Type) => T, ex: IExpression): IExpression { let propName = Expression.nameof(param); return new Any(new PropertyExpression(propName), ex); } private static expressionOrValue(value: any): IExpression { if (typeof value === 'function') { value = new PropertyExpression(Expression.nameof(value)); } else if (!value.accept) { value = new ValueExpression(value) } return value; } }
336a4bd13f6fcdc4f68b7a4eb0019d44690b074d
TypeScript
greenn-lab/egovframe-msa-edu
/frontend/admin/src/hooks/useLocalStorage.ts
3.109375
3
import { useState } from 'react' export const useLocalStorage = (key: string, initialValue: unknown = '') => { const [storeValue, setStoreValue] = useState(() => { try { const item = window.localStorage.getItem(key) return item ? JSON.parse(item) : initialValue } catch (error) { return initialValue } }) const setValue = (value: unknown) => { try { const valueToStore = value instanceof Function ? value(storeValue) : value setStoreValue(valueToStore) window.localStorage.setItem(key, JSON.stringify(valueToStore)) } catch (error) { console.error(`useLocalStorage setValue error : ${error.message}`) } } return [storeValue, setValue] }
6f2b3042c72a019df14b9b9ad28c00e92be467b2
TypeScript
angelospillos/nodejs-typeorm-typescript-tslint-expessjs-nodemon-boilerplate-example-template
/src/action/user.action.ts
2.75
3
import { Request, Response } from "express"; import { getManager } from "typeorm"; import { UserEntity } from "../entity/user.entity"; export namespace UserAction { /** * Loads all users from the database. */ export async function getAll(request: Request, response: Response) { // get a user repository to perform operations with user const userRepository = getManager().getRepository(UserEntity); // load a user by a given user id const users = await userRepository.find(); // return loaded users response.send(users); } /** * Loads user by a given id. */ export async function getById(request: Request, response: Response) { // get a post repository to perform operations with user const userRepository = getManager().getRepository(UserEntity); // load a post by a given post id const user = await userRepository.findOne(request.params.id); // if user was not found return 404 to the client if (!user) { response.status(404); response.end(); return; } // return loaded post response.send(user); } /** * Saves given user. */ export async function save(request: Request, response: Response) { // get a user repository to perform operations with user const userRepository = getManager().getRepository(UserEntity); // create a real user object from user json object sent over http const newUser = userRepository.create(request.body); // save received user await userRepository.save(newUser); // return saved user back response.send(newUser); } }
bfd432d2d133bc28a593e68fe9abaa47a676ba48
TypeScript
DNaunin/ComicVine
/src/utils/api.ts
2.625
3
export type APICharacter = { gender: 1 | 2 | 3; image: { icon_url: string; medium_url: string; screen_url: string; screen_large_url: string; small_url: string; super_url: string; thumb_url: string; tiny_url: string; original_url: string; image_tags: string; }; name: string; publisher: { napi_detail_url: string; id: string; name: string; }; real_name: string; }; export type APICharacters = { error: string; limit: number; offset: number; number_of_page_results: number; number_of_total_results: number; status_code: number; results: APICharacter[]; }; export async function getHero(id: number) { const response = await fetch( `https://cors-anywhere.herokuapp.com/https://comicvine.gamespot.com/api/characters/?api_key=3ddd177d9376a5571e28309e6dc67408e1ed0854&format=json&filter=id:${id}&field_list=real_name,gender,name,image,publisher`, { headers: { origin: "localhost" }, } ); if (!response.ok) { throw new Error("api not working"); } const result = (await response.json()) as APICharacters; console.log(result.results); if (result.results.length == 0) { console.log("empty"); return { image: { small_url: "https://images.unsplash.com/photo-1531257243018-c547a2e35767?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=782&q=80", }, name: "Character not found", real_name: "not existent", publisher: { name: "not published" }, }; } return result.results[0]; } export async function getCharacters(name?: string) { const response = await fetch( `https://cors-anywhere.herokuapp.com/https://comicvine.gamespot.com/api/characters/?api_key=3ddd177d9376a5571e28309e6dc67408e1ed0854&format=json&filter=publisher:marvel${ name ? `,name:${name}` : "" }&field_list=real_name,gender,name,image,publisher` ); if (!response.ok) { return []; } const result = (await response.json()) as APICharacters; return result.results; }
808894c33ddab19b0af1aedd64f6d41ae26ffd01
TypeScript
Small-Basic-French/SmallBasic-Online
/src/compiler/syntax/command-parser.ts
2.671875
3
import { ErrorCode, Diagnostic } from "../diagnostics"; import { BaseCommandSyntax, IfCommandSyntax, ElseIfCommandSyntax, ElseCommandSyntax, EndIfCommandSyntax, ForCommandSyntax, ForStepClause, EndForCommandSyntax, WhileCommandSyntax, EndWhileCommandSyntax, LabelCommandSyntax, GoToCommandSyntax, SubCommandSyntax, EndSubCommandSyntax, ExpressionCommandSyntax } from "./nodes/commands"; import { Token, TokenKind } from "./nodes/tokens"; import { BaseExpressionSyntax, BinaryOperatorExpressionSyntax, UnaryOperatorExpressionSyntax, ObjectAccessExpressionSyntax, ArrayAccessExpressionSyntax, CallExpressionSyntax, IdentifierExpressionSyntax, NumberLiteralExpressionSyntax, StringLiteralExpressionSyntax, ParenthesisExpressionSyntax } from "./nodes/expressions"; import { TextRange } from "./nodes/syntax-nodes"; export class CommandsParser { private index: number = 0; private line: number = 0; private currentLineHasErrors: boolean = false; private _commands: BaseCommandSyntax[] = []; public get commands(): ReadonlyArray<BaseCommandSyntax> { return this._commands; } public constructor(private tokens: ReadonlyArray<Token>, private diagnostics: Diagnostic[]) { this.tokens = this.tokens.filter(token => { switch (token.kind) { // Ignore tokens that shouldn't be parsed. case TokenKind.Comment: case TokenKind.UnrecognizedToken: return false; default: return true; } }); while (this.index < this.tokens.length) { this.currentLineHasErrors = false; this.parseNextCommand(); while (this.index < this.tokens.length && this.line === this.tokens[this.index].range.line) { this.index++; } this.line++; } } private parseNextCommand(): void { let current = this.peek(); if (current) { switch (current.kind) { case TokenKind.IfKeyword: this._commands.push(this.parseIfCommand()); break; case TokenKind.ElseKeyword: this._commands.push(this.parseElseCommand()); break; case TokenKind.ElseIfKeyword: this._commands.push(this.parseElseIfCommand()); break; case TokenKind.EndIfKeyword: this._commands.push(this.parseEndIfCommand()); break; case TokenKind.ForKeyword: this._commands.push(this.parseForCommand()); break; case TokenKind.EndForKeyword: this._commands.push(this.parseEndForCommand()); break; case TokenKind.WhileKeyword: this._commands.push(this.parseWhileCommand()); break; case TokenKind.EndWhileKeyword: this._commands.push(this.parseEndWhileCommand()); break; case TokenKind.GoToKeyword: this._commands.push(this.parseGoToCommand()); break; case TokenKind.Identifier: if (this.isNext(TokenKind.Colon, 1)) { this._commands.push(this.parseLabelCommand()); } else { this._commands.push(this.parseExpressionCommand()); } break; case TokenKind.SubKeyword: this._commands.push(this.parseSubCommand()); break; case TokenKind.EndSubKeyword: this._commands.push(this.parseEndSubCommand()); break; case TokenKind.Minus: case TokenKind.NumberLiteral: case TokenKind.StringLiteral: case TokenKind.LeftParen: this._commands.push(this.parseExpressionCommand()); break; default: this.eat(current.kind); this.reportError(new Diagnostic(ErrorCode.UnrecognizedCommand, current.range, current.text)); break; } } current = this.peek(); if (current) { this.reportError(new Diagnostic(ErrorCode.UnexpectedToken_ExpectingEOL, current.range, current.text)); } } private parseIfCommand(): IfCommandSyntax { const ifKeyword = this.eat(TokenKind.IfKeyword); const expression = this.parseBaseExpression(); const thenKeyword = this.eat(TokenKind.ThenKeyword); return new IfCommandSyntax(ifKeyword, expression, thenKeyword); } private parseElseIfCommand(): ElseIfCommandSyntax { const elseIfKeyword = this.eat(TokenKind.ElseIfKeyword); const expression = this.parseBaseExpression(); const thenKeyword = this.eat(TokenKind.ThenKeyword); return new ElseIfCommandSyntax(elseIfKeyword, expression, thenKeyword); } private parseElseCommand(): ElseCommandSyntax { const elseKeyword = this.eat(TokenKind.ElseKeyword); return new ElseCommandSyntax(elseKeyword); } private parseEndIfCommand(): EndIfCommandSyntax { const endIfKeyword = this.eat(TokenKind.EndIfKeyword); return new EndIfCommandSyntax(endIfKeyword); } private parseForCommand(): ForCommandSyntax { const forKeyword = this.eat(TokenKind.ForKeyword); const identifierToken = this.eat(TokenKind.Identifier); const equalToken = this.eat(TokenKind.Equal); const fromExpression = this.parseBaseExpression(); const toToken = this.eat(TokenKind.ToKeyword); const toExpression = this.parseBaseExpression(); let stepClauseSyntax: ForStepClause | undefined; if (this.isNext(TokenKind.StepKeyword)) { const stepToken = this.eat(TokenKind.StepKeyword); const stepExpression = this.parseBaseExpression(); stepClauseSyntax = { stepToken: stepToken, expression: stepExpression }; } return new ForCommandSyntax(forKeyword, identifierToken, equalToken, fromExpression, toToken, toExpression, stepClauseSyntax); } private parseEndForCommand(): EndForCommandSyntax { const endForKeyword = this.eat(TokenKind.EndForKeyword); return new EndForCommandSyntax(endForKeyword); } private parseWhileCommand(): WhileCommandSyntax { const whileToken = this.eat(TokenKind.WhileKeyword); const expression = this.parseBaseExpression(); return new WhileCommandSyntax(whileToken, expression); } private parseEndWhileCommand(): EndWhileCommandSyntax { const endWhileKeyword = this.eat(TokenKind.EndWhileKeyword); return new EndWhileCommandSyntax(endWhileKeyword); } private parseLabelCommand(): LabelCommandSyntax { const labelToken = this.eat(TokenKind.Identifier); const colonToken = this.eat(TokenKind.Colon); return new LabelCommandSyntax(labelToken, colonToken); } private parseGoToCommand(): GoToCommandSyntax { const gotoToken = this.eat(TokenKind.GoToKeyword); const labelToken = this.eat(TokenKind.Identifier); return new GoToCommandSyntax(gotoToken, labelToken); } private parseSubCommand(): SubCommandSyntax { const subToken = this.eat(TokenKind.SubKeyword); const nameToken = this.eat(TokenKind.Identifier); return new SubCommandSyntax(subToken, nameToken); } private parseEndSubCommand(): EndSubCommandSyntax { const endSubToken = this.eat(TokenKind.EndSubKeyword); return new EndSubCommandSyntax(endSubToken); } private parseExpressionCommand(): ExpressionCommandSyntax { const expression = this.parseBaseExpression(); return new ExpressionCommandSyntax(expression); } private parseBaseExpression(): BaseExpressionSyntax { return this.parseBinaryOperator(0); } private parseBinaryOperator(precedence: number): BaseExpressionSyntax { if (precedence >= CommandsParser.BinaryOperatorPrecedence.length) { return this.parseUnaryOperator(); } let expression = this.parseBinaryOperator(precedence + 1); const expectedOperatorKind = CommandsParser.BinaryOperatorPrecedence[precedence]; while (this.isNext(expectedOperatorKind)) { const operatorToken = this.eat(expectedOperatorKind); const rightHandSide = this.parseBinaryOperator(precedence + 1); expression = new BinaryOperatorExpressionSyntax(expression, operatorToken, rightHandSide); } return expression; } private parseUnaryOperator(): BaseExpressionSyntax { if (this.isNext(TokenKind.Minus)) { const minusToken = this.eat(TokenKind.Minus); const expression = this.parseBaseExpression(); return new UnaryOperatorExpressionSyntax(minusToken, expression); } return this.parseCoreExpression(); } private parseCoreExpression(): BaseExpressionSyntax { let current: Token | undefined; let expression = this.parseTerminalExpression(); postfixExpression: while (current = this.peek()) { switch (current.kind) { case TokenKind.Dot: { const dotToken = this.eat(TokenKind.Dot); const identifierToken = this.eat(TokenKind.Identifier); expression = new ObjectAccessExpressionSyntax(expression, dotToken, identifierToken); break; } case TokenKind.LeftSquareBracket: { const leftSquareBracket = this.eat(TokenKind.LeftSquareBracket); const indexExpression = this.parseBaseExpression(); const rightSquareBracket = this.eat(TokenKind.RightSquareBracket); expression = new ArrayAccessExpressionSyntax(expression, leftSquareBracket, indexExpression, rightSquareBracket); break; } case TokenKind.LeftParen: { const leftParen = this.eat(TokenKind.LeftParen); const argumentsList: BaseExpressionSyntax[] = []; const commasList: Token[] = []; current = this.peek(); let expectingComma = false; if (current && (current.kind !== TokenKind.RightParen)) { loop: while (current) { if (expectingComma) { switch (current.kind) { case TokenKind.Comma: { commasList.push(this.eat(TokenKind.Comma)); break; } case TokenKind.RightParen: { break loop; } default: { this.reportError(new Diagnostic( ErrorCode.UnexpectedToken_ExpectingToken, current.range, current.text, Token.toDisplayString(TokenKind.Comma))); commasList.push(this.createMissingToken(current.range)); break; } } } else { argumentsList.push(this.parseBaseExpression()); } expectingComma = !expectingComma; current = this.peek(); } } const rightParen = this.eat(TokenKind.RightParen); expression = new CallExpressionSyntax(expression, leftParen, argumentsList, commasList, rightParen); break; } default: break postfixExpression; } } return expression; } private parseTerminalExpression(): BaseExpressionSyntax { const current = this.peek(); if (!current) { const range = this.tokens[this.index - 1].range; this.reportError(new Diagnostic(ErrorCode.UnexpectedEOL_ExpectingExpression, range)); return new IdentifierExpressionSyntax(this.createMissingToken(range)); } switch (current.kind) { case TokenKind.Identifier: { const identifierToken = this.eat(TokenKind.Identifier); return new IdentifierExpressionSyntax(identifierToken); } case TokenKind.NumberLiteral: { const numberToken = this.eat(TokenKind.NumberLiteral); return new NumberLiteralExpressionSyntax(numberToken); } case TokenKind.StringLiteral: { const stringToken = this.eat(TokenKind.StringLiteral); return new StringLiteralExpressionSyntax(stringToken); } case TokenKind.LeftParen: { const leftParen = this.eat(TokenKind.LeftParen); const expression = this.parseBaseExpression(); const rightParen = this.eat(TokenKind.RightParen); return new ParenthesisExpressionSyntax(leftParen, expression, rightParen); } default: { this.eat(current.kind); this.reportError(new Diagnostic(ErrorCode.UnexpectedToken_ExpectingExpression, current.range, current.text)); return new IdentifierExpressionSyntax(this.createMissingToken(current.range)); } } } private isNext(kind: TokenKind, offset?: number): boolean { const current = this.peek(offset); return !!current && current.kind === kind; } private peek(offset?: number): Token | undefined { offset || (offset = 0); if (this.index + offset < this.tokens.length) { const current = this.tokens[this.index + offset]; if (current.range.line === this.line) { return current; } } return; } private eat(kind: TokenKind): Token { if (this.index < this.tokens.length) { const current = this.tokens[this.index]; if (current.range.line === this.line) { if (current.kind === kind) { this.index++; return current; } else { this.reportError(new Diagnostic(ErrorCode.UnexpectedToken_ExpectingToken, current.range, current.text, Token.toDisplayString(kind))); return this.createMissingToken(current.range); } } } const range = this.tokens[this.index - 1].range; this.reportError(new Diagnostic(ErrorCode.UnexpectedEOL_ExpectingToken, range, Token.toDisplayString(kind))); return this.createMissingToken(range); } private createMissingToken(range: TextRange): Token { return new Token("<Missing>", TokenKind.MissingToken, range); } private reportError(error: Diagnostic): void { if (!this.currentLineHasErrors) { this.diagnostics.push(error); this.currentLineHasErrors = true; } } private static BinaryOperatorPrecedence: TokenKind[] = [ TokenKind.Or, TokenKind.And, TokenKind.Equal, TokenKind.NotEqual, TokenKind.LessThan, TokenKind.GreaterThan, TokenKind.LessThanOrEqual, TokenKind.GreaterThanOrEqual, TokenKind.Plus, TokenKind.Minus, TokenKind.Multiply, TokenKind.Divide ]; }
ec6784b118d2d97549249c63411fb5f960e7fe35
TypeScript
pacifist24/tlFormatter
/lib/tlFormatter.ts
2.90625
3
export type TLData = { mode: string phase: number bossName: string damage: number battleDate: string characters: { lv: number name: string star: number rank: number specialLv: number remark: string }[] startTime: number endTime: number timeline: { time: number; name: string; remark: string }[] } export type FormatStyle = { headerFormat: string selfUbFormat: string bossUbFormat: string footerFormat: string nameConvs: { [key: string]: string } startTime: number paddingName: string arrange: string } // 01:20⇒80のように分秒表記を秒に変更 const timeStr2Num = (timeStr: string) => { return parseInt(timeStr.substr(0, 2)) * 60 + parseInt(timeStr.substr(3, 2)) } // 80⇒01:20のように秒を分秒表記に変更 const timeNum2Str = (timeNum: number) => { const min = Math.floor(timeNum / 60) const sec = timeNum % 60 return ('00' + min).slice(-2) + ':' + ('00' + sec).slice(-2) } // プリコネのTL書き出し機能により出力された文字列から情報を抜き出す export const parseTlData = (text: string): TLData => { function* readLine(text: string) { const lines: string[] = text.split(/\r\n|\n/).filter((line: string) => { return line !== '' }) for (const line of lines) { yield line.split(' ') } } const it = readLine(text) const tlData: TLData = <TLData>{} // 1行目 // クランモード 5段階目 シードレイク let line = it.next().value if (line) { tlData.mode = line[0] tlData.phase = parseInt(line[1].replace('段階目', '')) tlData.bossName = line[2] } // 2行目 // 32702296ダメージ line = it.next().value if (line) { tlData.damage = parseInt(line[0].replace('ダメージ', '')) } // 3行目 // バトル時間 01:30 line = it.next().value // if (line) { // tlData.duration = timeStr2Num(line[1]) // } // 4行目 // バトル日時 2021/06/29 22:40 line = it.next().value if (line) { tlData.battleDate = line[1] + ' ' + line[2] } // 5行目 // ---- line = it.next().value // 6行目 // ◆パーティ編成 line = it.next().value // 7~11行目 // アカリ ★6 Lv202 RANK14 // サレン(サマー) ★3 Lv202 RANK14 // ネネカ ★5 Lv202 RANK21 // キャル(ニューイヤー) ★4 Lv202 RANK21 // ルナ ★5 Lv202 RANK21 tlData.characters = [] for (let i = 0; i < 5; i++) { line = it.next().value if (line) { // RANK以降を切り取って、文頭のRANKの文字を削る const behindRank = line.slice(3).join('').substr(4) const rankStr = behindRank.match(/[0-9]+/)[0] tlData.characters[i] = { lv: parseInt(line[2].replace('Lv', '')), name: line[0], star: parseInt(line[1].replace('★', '')), rank: parseInt(rankStr), specialLv: 0, remark: behindRank.substr(rankStr.length), } } } // 存在する名前一覧(キャルとキャル(ニューイヤー)のような並びがあったらキャル(ニューイヤー)を先にする) const existCharacterNames = tlData.characters.map( (character) => character.name ) existCharacterNames.push(tlData.bossName) existCharacterNames.sort().reverse() // 12行目 // ---- line = it.next().value // 13行目 // ◆ユニオンバースト発動時間 line = it.next().value // 14行目 // 01:30 バトル開始 line = it.next().value if (line) { tlData.startTime = timeStr2Num(line[0]) } // 15行目以降 // 01:19 アカリ // ~ // 00:00 バトル終了 tlData.timeline = [] while ((line = it.next().value)) { if (line[1] === 'バトル終了') { tlData.endTime = timeStr2Num(line[0]) } else { // TL行の時間を除いた部分 キャル(ニューイヤー) シャドバ後等 const lineWithoutTime = line.slice(1).join(' ') let remarkStr = '' let characterNameStr = '' for (let i = 0; i < existCharacterNames.length; i++) { // 存在するキャラとの前方一致を確認して以後の部分をコメントとする if (lineWithoutTime.indexOf(existCharacterNames[i]) === 0) { characterNameStr = existCharacterNames[i] remarkStr = lineWithoutTime .substr(existCharacterNames[i].length) .trim() break } } // コメント無し行 tlData.timeline.push({ name: characterNameStr, time: timeStr2Num(line[0]), remark: remarkStr, }) } } return tlData } export const formatTL = (tlData: TLData, formatStyle: FormatStyle): string => { const headerTemplateText = formatStyle.headerFormat + '\n' const characterUbTemplateText = formatStyle.selfUbFormat + '\n' const bossUbTemplateText = formatStyle.bossUbFormat + '\n' const footerTemplateText = formatStyle.footerFormat + '\n' // 名前の変換を行う const convertName = (name: string) => { if (name in formatStyle.nameConvs) { return formatStyle.nameConvs[name] } return name } // 半角は1文字 全角は2文字として文字数をカウント const getLen = (str: string) => { let result = 0 for (let i = 0; i < str.length; i++) { const chr = str.charCodeAt(i) if ( (chr >= 0x00 && chr < 0x81) || chr === 0xf8f0 || (chr >= 0xff61 && chr < 0xffa0) || (chr >= 0xf8f1 && chr < 0xf8f4) ) { //半角文字の場合は1を加算 result += 1 } else { //それ以外の文字の場合は2を加算 result += 2 } } //結果を返す return result } // 一番長い名前のキャラの名前の長さ const maxLength = Math.max( ...tlData.characters.map((character) => getLen(convertName(character.name))) ) const doPadding = (name: string) => { const nameLen = getLen(name) const paddingStr = Array(Math.floor((maxLength - nameLen) / 2) + 1).join(' ') + ((maxLength - nameLen) % 2 === 1 ? ' ' : '') switch (formatStyle.paddingName) { case 'none': return name case 'head': return paddingStr + name default: return name + paddingStr } } const lessTime = tlData.startTime - formatStyle.startTime let timelineOutput = '' if (formatStyle.arrange === 'none') { for (const ub of tlData.timeline) { if (ub.time - lessTime < 1) { // 時間不足によりUBが打てなければ以降をカット break } if (ub.name === tlData.bossName) { timelineOutput += bossUbTemplateText .replace('<UB使用時秒数>', timeNum2Str(ub.time - lessTime).substr(1)) .replace('<UB使用キャラ名>', ub.name) .replace('<UB備考>', ub.remark) } else { timelineOutput += characterUbTemplateText .replace('<UB使用時秒数>', timeNum2Str(ub.time - lessTime).substr(1)) .replace('<UB使用キャラ名>', doPadding(convertName(ub.name))) .replace('<UB備考>', ub.remark) } } } else { let index = 0 while (index < tlData.timeline.length) { const ub = tlData.timeline[index] if (ub.time - lessTime < 1) { // 時間不足によりUBが打てなければ以降をカット break } if (ub.name === tlData.bossName) { timelineOutput += bossUbTemplateText .replace('<UB使用時秒数>', timeNum2Str(ub.time - lessTime).substr(1)) .replace('<UB使用キャラ名>', ub.name) .replace('<UB備考>', ub.remark) } else { let subNames = '' for (let i = index + 1; i < tlData.timeline.length; i++) { const subUb = tlData.timeline[i] if ( subUb.name !== tlData.bossName && subUb.remark === '' && ub.time === subUb.time ) { subNames += ' ' + doPadding(convertName(subUb.name)) index = i } else { break } } if (formatStyle.arrange === 'same') { timelineOutput += characterUbTemplateText .replace( '<UB使用時秒数>', timeNum2Str(ub.time - lessTime).substr(1) ) .replace( '<UB使用キャラ名>', doPadding(convertName(ub.name)) + subNames ) .replace('<UB備考>', ub.remark) } else if (formatStyle.arrange === 'next') { timelineOutput += characterUbTemplateText .replace( '<UB使用時秒数>', timeNum2Str(ub.time - lessTime).substr(1) ) .replace('<UB使用キャラ名>', doPadding(convertName(ub.name))) .replace('<UB備考>', ub.remark) + (subNames ? '⇒' + subNames + '\n' : '') } } index++ } } timelineOutput = headerTemplateText + timelineOutput + footerTemplateText return timelineOutput .replace('<モード>', tlData.mode) .replace('<段階>', tlData.phase.toString()) .replace('<ボス名>', tlData.bossName.toString()) .replace('<詳細与ダメージ>', tlData.damage.toString()) .replace('<ダメージ>', Math.floor(tlData.damage / 10000) + '万') .replace('<所要秒数>', (tlData.startTime - tlData.endTime).toString()) .replace('<バトル日時>', tlData.battleDate.toString()) .replace('<キャラ1名>', doPadding(convertName(tlData.characters[0].name))) .replace('<キャラ1星>', tlData.characters[0].star.toString()) .replace('<キャラ1R>', tlData.characters[0].rank.toString()) .replace('<キャラ1LV>', tlData.characters[0].lv.toString()) .replace('<キャラ1専用LV>', tlData.characters[0].specialLv.toString()) .replace('<キャラ1備考>', tlData.characters[0].remark.toString()) .replace('<キャラ2名>', doPadding(convertName(tlData.characters[1].name))) .replace('<キャラ2星>', tlData.characters[1].star.toString()) .replace('<キャラ2R>', tlData.characters[1].rank.toString()) .replace('<キャラ2LV>', tlData.characters[1].lv.toString()) .replace('<キャラ2専用LV>', tlData.characters[1].specialLv.toString()) .replace('<キャラ2備考>', tlData.characters[1].remark.toString()) .replace('<キャラ3名>', doPadding(convertName(tlData.characters[2].name))) .replace('<キャラ3星>', tlData.characters[2].star.toString()) .replace('<キャラ3R>', tlData.characters[2].rank.toString()) .replace('<キャラ3LV>', tlData.characters[2].lv.toString()) .replace('<キャラ3専用LV>', tlData.characters[2].specialLv.toString()) .replace('<キャラ3備考>', tlData.characters[2].remark.toString()) .replace('<キャラ4名>', doPadding(convertName(tlData.characters[3].name))) .replace('<キャラ4星>', tlData.characters[3].star.toString()) .replace('<キャラ4R>', tlData.characters[3].rank.toString()) .replace('<キャラ4LV>', tlData.characters[3].lv.toString()) .replace('<キャラ4専用LV>', tlData.characters[3].specialLv.toString()) .replace('<キャラ4備考>', tlData.characters[3].remark.toString()) .replace('<キャラ5名>', doPadding(convertName(tlData.characters[4].name))) .replace('<キャラ5星>', tlData.characters[4].star.toString()) .replace('<キャラ5R>', tlData.characters[4].rank.toString()) .replace('<キャラ5LV>', tlData.characters[4].lv.toString()) .replace('<キャラ5専用LV>', tlData.characters[4].specialLv.toString()) .replace('<キャラ5備考>', tlData.characters[4].remark.toString()) .replace('<開始秒数>', timeNum2Str(tlData.startTime - lessTime).substr(1)) .replace( '<終了秒数>', timeNum2Str( tlData.endTime - lessTime > 0 ? tlData.endTime - lessTime : 0 ).substr(1) ) }
8cc922b4343308a628bafa9952976b864a919d41
TypeScript
420Integrated/fourtwentyjs-client
/test/net/peer/peer.ts
2.734375
3
/* eslint-disable */ // TODO: re-enable linting. Disabled because much of test is commented out // resulting in unused variable false positives import tape from 'tape-catch' const td = require('testdouble') import { Peer } from '../../../lib/net/peer' import * as events from 'events' tape('[Peer]', (t) => { const peer = new Peer({ id: '0123456789abcdef', address: 'address0', transport: 'transport0', inbound: true, }) t.test('should get/set idle state', (t) => { t.ok(peer.idle, 'is initially idle') peer.idle = false t.notOk(peer.idle, 'idle set to false') t.end() }) // Deactivated along TypeScript transition, peer.bindProtocol // can not be called with sender with string type /*t.test('should bind protocol', async (t) => { const bound = (new events.EventEmitter() as any) const sender = 'sender' const protocol = td.object('Protocol') bound.name = 'bound0' protocol.name = 'proto0' t.plan(3) td.when(protocol.bind(peer, sender)).thenResolve(bound) await peer.bindProtocol(protocol, sender) t.equals(peer.bound.get('bound0'), bound, 'protocol bound') peer.on('message', (msg: any, name: any) => { t.ok(msg === 'msg0' && name === 'proto0', 'on message') }) peer.on('error', (err: any, name: any) => { t.ok(err === 'err0' && name === 'proto0', 'on error') }) bound.emit('message', 'msg0') bound.emit('error', 'err0') }) t.test('should understand protocols', t => { t.ok(peer.understands('bound0'), 'understands bound protocol') t.notOk(peer.understands('unknown'), 'does not understand unknown protocol') t.end() }) t.test('should convert to string', t => { t.equals( peer.toString(true), 'id=0123456789abcdef address=address0 transport=transport0 protocols=bound0 inbound=true', 'correct full id string' ) peer.inbound = false t.equals( peer.toString(), 'id=01234567 address=address0 transport=transport0 protocols=bound0', 'correct short id string' ) t.end() })*/ })
f06e404f839c0454b8ba6cdb0e92e7f86de7fb8d
TypeScript
andre-potsdam/Proto_2019
/proto-app/src/app/common/model/form-control-config.ts
3.046875
3
import { Subject } from 'rxjs'; export class FormControlConfig { // Name for technical purposes. No whitespaces. name: string; // Label of form row. rowLabel?: string; // Explaining information for row. // NOTE: This is rendered as inner HTML, so HTML tags can be used! infoText?: string; // Info text is only displayed, if showInfo==true and infoText is defined. private _showInfo: boolean; get showInfo() { return this._showInfo; } // Special setter in order to ensure, that only one info text is visible per form. set showInfo(showInfo) { if (this._showInfo === showInfo) { return; } this._showInfo = showInfo; this.showInfoSubject.next(this); } readonly showInfoSubject = new Subject<FormControlConfig>(); // Keys for language dependent properties. readonly keyForRowLabel: string; readonly keyForInfoText: string; constructor(name: string, showInfo: boolean) { this.name = name; this.showInfo = showInfo; this.keyForRowLabel = this.name + '_rowLabel'; this.keyForInfoText = this.name + '_infoText'; } isInfoAvailable() { return this.infoText; } // Update all language dependent strings from given properties. // Following properties MUST be defined in given map: // <name>_rowLabel // <name>_infoText // updateLanguageStrings(properties: any) { this.rowLabel = this.getLanguageString(properties, this.keyForRowLabel); this.infoText = this.getLanguageString(properties, this.keyForInfoText); } getLanguageString(properties: any, key: string) { if (properties.hasOwnProperty(key)) { return properties[key]; } else { throw new Error('missing property ' + key); } } }
83e1cdb2d386878cb5c0ff1d57c8fd6a6af721c2
TypeScript
transclusion/vdom
/src/diff.ts
2.5625
3
import {callWillDiffHook} from './callWillDiffHook' import { DID_INSERT, DID_REMOVE, DID_UPDATE, INSERT, POP_NODE, PUSH_NODE, REMOVE, REMOVE_ATTR, REPLACE, SET_ATTR, SET_TEXT, } from './constants' import {extractVNode} from './extractVNode' import {hasHook} from './hasHook' import {isThunk} from './isThunk' import {isVElement} from './isVElement' import {isVText} from './isVText' import {toHTML} from './toHTML' import {IAttrs, IVElement, IVThunk, Patch, VNode} from './types' function diffListeners(a: IAttrs, b: IAttrs, patches: Patch[]) { const aEventValues = a.on const bEventValues = b.on if (aEventValues === bEventValues) { return false } const aListenerKeys = aEventValues ? Object.keys(aEventValues) : [] const bListenerKeys = bEventValues ? Object.keys(bEventValues) : [] if (aListenerKeys.length !== bListenerKeys.length) { patches.push([SET_ATTR, 'on', bEventValues]) return true } else { const keys = aListenerKeys.filter((k) => bListenerKeys.indexOf(k) > -1) let isDifferent = false keys.forEach((k) => { if ((aEventValues || {})[k] !== (bEventValues || {})[k]) { isDifferent = true } }) if (isDifferent) { patches.push([SET_ATTR, 'on', bEventValues]) return true } } return false } function diffData(a: IAttrs | undefined, b: IAttrs | undefined, patches: Patch[]) { let didUpdate = false if (b) { // Diff added/updated attributes Object.keys(b).forEach((attr) => { if (!a) { patches.push([SET_ATTR, attr, b[attr]]) } else if (attr === 'on') { if (diffListeners(a, b, patches)) { didUpdate = true } } else if (attr !== 'hook' && a[attr] !== b[attr]) { patches.push([SET_ATTR, attr, b[attr]]) didUpdate = true } }) } if (a) { // Diff removed attributes Object.keys(a).forEach((attr) => { if (!b || b[attr] === undefined) { patches.push([REMOVE_ATTR, attr]) didUpdate = true } }) } return didUpdate } function diffChildren(a: IVElement, b: IVElement, patches: Patch[]) { const len: number = Math.max(a.children.length, b.children.length) let i: number let removed = 0 let didUpdate = false for (i = 0; i < len; i++) { const index: number = i - removed if (a.children[i] === undefined) { if (isVElement(b.children[i])) { callWillDiffHook(b.children[i] as IVElement, a.children[i], b.children[i]) } patches.push([INSERT, extractVNode(b.children[i])]) if (isVElement(b.children[i]) && hasHook(b.children[i] as IVElement, 'didInsert')) { patches.push([PUSH_NODE, index]) patches.push([DID_INSERT, (b.children[i] as IVElement).data?.hook?.didInsert]) patches.push([POP_NODE, 1]) } didUpdate = true } else if (b.children[i] === undefined) { patches.push([REMOVE, index]) if (isVElement(a.children[i]) && hasHook(a.children[i] as IVElement, 'didRemove')) { patches.push([DID_REMOVE, (a.children[i] as IVElement).data?.hook?.didRemove]) } didUpdate = true removed += 1 } else { const childPatches: Patch[] = [] diffVNode(a.children[i], b.children[i], childPatches) if (childPatches.length) { let pHead = childPatches[0] if (pHead[0] === PUSH_NODE) { // If the first child patch is a PUSH_NODE patch, then insert the index const h = pHead as any h.splice(1, 0, index) } else { // Otherwise add a new PUSH_NODE patch patches.push([PUSH_NODE, index]) } // Append child patches patches.push(...childPatches) // If the last patch is a POP_NODE patch, then increase the pop count by 1 pHead = patches[patches.length - 1] if (pHead && pHead[0] === POP_NODE) { pHead[1] += 1 } else { patches.push([POP_NODE, 1]) } didUpdate = true } } } return didUpdate } function diffVNode(a: VNode, b: VNode, patches: Patch[]) { if (a === b) { return } let didInsert = false let didUpdate = false if (isVElement(a) && isVElement(b)) { const bVElement = b as IVElement callWillDiffHook(bVElement, a, b) const aVElement = a as IVElement let aData = aVElement.data const bData = bVElement.data if ((!aData || aData.innerHTML === undefined) && bVElement.data && bData?.innerHTML !== undefined) { const innerHTML: string = aVElement.children.map(toHTML).join('') aVElement.data = aData = aData ? {...aData, innerHTML} : {innerHTML} aVElement.children = [] } if (aVElement.name === bVElement.name) { if (!hasHook(a as IVElement, 'didInsert') && hasHook(bVElement, 'didInsert')) { patches.push([DID_INSERT, bData?.hook?.didInsert]) didInsert = true } if (diffData(aData, bData, patches)) { didUpdate = true } if (diffChildren(aVElement, bVElement, patches)) { didUpdate = true } } else { patches.push([REPLACE, extractVNode(b)]) didInsert = true if (hasHook(bVElement, 'didInsert')) { patches.push([DID_INSERT, bData?.hook?.didInsert]) } } if (!didInsert && didUpdate && bData && bData.hook && bData.hook.didUpdate) { patches.push([DID_UPDATE, bData.hook.didUpdate]) } } else if (isVText(a) && isVText(b)) { patches.push([SET_TEXT, b as string]) } else if (a !== b) { if (isThunk(b)) { // Resolve thunk const t = b as IVThunk const vElement = t.fn.apply(undefined, t.args) Object.assign(b, vElement) } patches.push([REPLACE, extractVNode(b)]) } } export function diff(a: VNode, b: VNode): Patch[] { const patches: Patch[] = [] diffVNode(a, b, patches) let len = patches.length if (len) { while (patches[len - 1][0] === POP_NODE) { patches.pop() len -= 1 } } return patches }
928f02b0580ab2c94267be900c073c4fa42094f7
TypeScript
denoland/deno_std
/log/handlers.ts
2.953125
3
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. import { getLevelByName, LevelName, LogLevels } from "./levels.ts"; import type { LogRecord } from "./logger.ts"; import { blue, bold, red, yellow } from "../fmt/colors.ts"; import { exists, existsSync } from "../fs/exists.ts"; import { BufWriterSync } from "../io/buf_writer.ts"; import type { Writer } from "../types.d.ts"; const DEFAULT_FORMATTER = "{levelName} {msg}"; export type FormatterFunction = (logRecord: LogRecord) => string; export type LogMode = "a" | "w" | "x"; export interface HandlerOptions { formatter?: string | FormatterFunction; } export class BaseHandler { level: number; levelName: LevelName; formatter: string | FormatterFunction; constructor(levelName: LevelName, options: HandlerOptions = {}) { this.level = getLevelByName(levelName); this.levelName = levelName; this.formatter = options.formatter || DEFAULT_FORMATTER; } handle(logRecord: LogRecord) { if (this.level > logRecord.level) return; const msg = this.format(logRecord); return this.log(msg); } format(logRecord: LogRecord): string { if (this.formatter instanceof Function) { return this.formatter(logRecord); } return this.formatter.replace(/{([^\s}]+)}/g, (match, p1): string => { const value = logRecord[p1 as keyof LogRecord]; // do not interpolate missing values if (value == null) { return match; } return String(value); }); } log(_msg: string) {} setup() {} destroy() {} } /** * This is the default logger. It will output color coded log messages to the * console via `console.log()`. */ export class ConsoleHandler extends BaseHandler { override format(logRecord: LogRecord): string { let msg = super.format(logRecord); switch (logRecord.level) { case LogLevels.INFO: msg = blue(msg); break; case LogLevels.WARNING: msg = yellow(msg); break; case LogLevels.ERROR: msg = red(msg); break; case LogLevels.CRITICAL: msg = bold(red(msg)); break; default: break; } return msg; } override log(msg: string) { console.log(msg); } } export abstract class WriterHandler extends BaseHandler { protected _writer!: Writer; #encoder = new TextEncoder(); abstract override log(msg: string): void; } interface FileHandlerOptions extends HandlerOptions { filename: string; mode?: LogMode; } /** * This handler will output to a file using an optional mode (default is `a`, * e.g. append). The file will grow indefinitely. It uses a buffer for writing * to file. Logs can be manually flushed with `fileHandler.flush()`. Log * messages with a log level greater than error are immediately flushed. Logs * are also flushed on process completion. * * Behavior of the log modes is as follows: * * - `'a'` - Default mode. Appends new log messages to the end of an existing log * file, or create a new log file if none exists. * - `'w'` - Upon creation of the handler, any existing log file will be removed * and a new one created. * - `'x'` - This will create a new log file and throw an error if one already * exists. * * This handler requires `--allow-write` permission on the log file. */ export class FileHandler extends WriterHandler { protected _file: Deno.FsFile | undefined; protected _buf!: BufWriterSync; protected _filename: string; protected _mode: LogMode; protected _openOptions: Deno.OpenOptions; protected _encoder = new TextEncoder(); #unloadCallback = (() => { this.destroy(); }).bind(this); constructor(levelName: LevelName, options: FileHandlerOptions) { super(levelName, options); this._filename = options.filename; // default to append mode, write only this._mode = options.mode ? options.mode : "a"; this._openOptions = { createNew: this._mode === "x", create: this._mode !== "x", append: this._mode === "a", truncate: this._mode !== "a", write: true, }; } override setup() { this._file = Deno.openSync(this._filename, this._openOptions); this._writer = this._file; this._buf = new BufWriterSync(this._file); addEventListener("unload", this.#unloadCallback); } override handle(logRecord: LogRecord) { super.handle(logRecord); // Immediately flush if log level is higher than ERROR if (logRecord.level > LogLevels.ERROR) { this.flush(); } } log(msg: string) { if (this._encoder.encode(msg).byteLength + 1 > this._buf.available()) { this.flush(); } this._buf.writeSync(this._encoder.encode(msg + "\n")); } flush() { if (this._buf?.buffered() > 0) { this._buf.flush(); } } override destroy() { this.flush(); this._file?.close(); this._file = undefined; removeEventListener("unload", this.#unloadCallback); } } interface RotatingFileHandlerOptions extends FileHandlerOptions { maxBytes: number; maxBackupCount: number; } /** * This handler extends the functionality of the {@linkcode FileHandler} by * "rotating" the log file when it reaches a certain size. `maxBytes` specifies * the maximum size in bytes that the log file can grow to before rolling over * to a new one. If the size of the new log message plus the current log file * size exceeds `maxBytes` then a roll-over is triggered. When a roll-over * occurs, before the log message is written, the log file is renamed and * appended with `.1`. If a `.1` version already existed, it would have been * renamed `.2` first and so on. The maximum number of log files to keep is * specified by `maxBackupCount`. After the renames are complete the log message * is written to the original, now blank, file. * * Example: Given `log.txt`, `log.txt.1`, `log.txt.2` and `log.txt.3`, a * `maxBackupCount` of 3 and a new log message which would cause `log.txt` to * exceed `maxBytes`, then `log.txt.2` would be renamed to `log.txt.3` (thereby * discarding the original contents of `log.txt.3` since 3 is the maximum number * of backups to keep), `log.txt.1` would be renamed to `log.txt.2`, `log.txt` * would be renamed to `log.txt.1` and finally `log.txt` would be created from * scratch where the new log message would be written. * * This handler uses a buffer for writing log messages to file. Logs can be * manually flushed with `fileHandler.flush()`. Log messages with a log level * greater than ERROR are immediately flushed. Logs are also flushed on process * completion. * * Additional notes on `mode` as described above: * * - `'a'` Default mode. As above, this will pick up where the logs left off in * rotation, or create a new log file if it doesn't exist. * - `'w'` in addition to starting with a clean `filename`, this mode will also * cause any existing backups (up to `maxBackupCount`) to be deleted on setup * giving a fully clean slate. * - `'x'` requires that neither `filename`, nor any backups (up to * `maxBackupCount`), exist before setup. * * This handler requires both `--allow-read` and `--allow-write` permissions on * the log files. */ export class RotatingFileHandler extends FileHandler { #maxBytes: number; #maxBackupCount: number; #currentFileSize = 0; constructor(levelName: LevelName, options: RotatingFileHandlerOptions) { super(levelName, options); this.#maxBytes = options.maxBytes; this.#maxBackupCount = options.maxBackupCount; } override async setup() { if (this.#maxBytes < 1) { this.destroy(); throw new Error("maxBytes cannot be less than 1"); } if (this.#maxBackupCount < 1) { this.destroy(); throw new Error("maxBackupCount cannot be less than 1"); } await super.setup(); if (this._mode === "w") { // Remove old backups too as it doesn't make sense to start with a clean // log file, but old backups for (let i = 1; i <= this.#maxBackupCount; i++) { try { await Deno.remove(this._filename + "." + i); } catch (error) { if (!(error instanceof Deno.errors.NotFound)) { throw error; } } } } else if (this._mode === "x") { // Throw if any backups also exist for (let i = 1; i <= this.#maxBackupCount; i++) { if (await exists(this._filename + "." + i)) { this.destroy(); throw new Deno.errors.AlreadyExists( "Backup log file " + this._filename + "." + i + " already exists", ); } } } else { this.#currentFileSize = (await Deno.stat(this._filename)).size; } } override log(msg: string) { const msgByteLength = this._encoder.encode(msg).byteLength + 1; if (this.#currentFileSize + msgByteLength > this.#maxBytes) { this.rotateLogFiles(); this.#currentFileSize = 0; } super.log(msg); this.#currentFileSize += msgByteLength; } rotateLogFiles() { this._buf.flush(); this._file!.close(); for (let i = this.#maxBackupCount - 1; i >= 0; i--) { const source = this._filename + (i === 0 ? "" : "." + i); const dest = this._filename + "." + (i + 1); if (existsSync(source)) { Deno.renameSync(source, dest); } } this._file = Deno.openSync(this._filename, this._openOptions); this._writer = this._file; this._buf = new BufWriterSync(this._file); } }
38b640e7d2c5e845149ab4719b4cc90e41160850
TypeScript
Sergiobi9/TFGdashboard
/src/app/pages/concerts/pipe/date-concert.pipe.ts
3.234375
3
import { Pipe, PipeTransform } from "@angular/core"; /* * Raise the value exponentially * Takes an exponent argument that defaults to 1. * Usage: * value | exponentialStrength:exponent * Example: * {{ 2 | exponentialStrength:10 }} * formats to: 1024 */ @Pipe({ name: "dateConcertPipe" }) export class DayConcertPipe implements PipeTransform { months = ["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"]; transform(concertDate: string) { var date = new Date(concertDate); var month = date.getMonth(); var monthString = this.months[month]; var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); return day + " " + monthString; } getMonth(){ } }
bcc5478c75a7ba2f95025d2676f90d0aaf128fa9
TypeScript
wjdgpwl1004/next-toyProject
/reducers/user.ts
2.734375
3
import { UserState } from "../types/reduxState"; import produce from 'immer'; //* 초기 상태 const initialState: UserState = { id: 0, email: "", lastname: "", firstname: "", birthday: "", isLogged: false, profileImage: "", signUpError: null, logInError: null, }; export const SIGN_UP_REQUEST = 'SIGN_UP_REQUEST'; export const SIGN_UP_SUCCESS = 'SIGN_UP_SUCCESS'; export const SIGN_UP_FAILURE = 'SIGN_UP_FAILURE'; export const LOG_IN_REQUEST = 'LOG_IN_REQUEST'; export const LOG_IN_SUCCESS = 'LOG_IN_SUCCESS'; export const LOG_IN_FAILURE = 'LOG_IN_FAILURE'; export const GET_USER_INFO_REQUEST = 'GET_USER_INFO_REQUEST'; export const GET_USER_INFO_SUCCESS = 'GET_USER_INFO_SUCCESS'; export const GET_USER_INFO_FAILURE = 'GET_USER_INFO_FAILURE'; export const LOG_OUT_REQUEST = 'LOG_OUT_REQUEST'; export const LOG_OUT_SUCCESS = 'LOG_OUT_SUCCESS'; export const LOG_OUT_FAILURE = 'LOG_OUT_FAILURE'; const reducer = (state = initialState, action: any) => produce(state, (draft) => { switch (action.type) { case SIGN_UP_REQUEST: draft.signUpError = null; break; case SIGN_UP_SUCCESS: draft.id = action.data.id; draft.email = action.data.email; draft.lastname = action.data.lastname; draft.firstname = action.data.firstname; draft.birthday = action.data.birthday; draft.profileImage = action.data.profileImage; draft.isLogged = true; break; case SIGN_UP_FAILURE: draft.signUpError = action.error; break; case LOG_IN_REQUEST: draft.logInError = null; break; case LOG_IN_SUCCESS: draft.id = action.data.id; draft.email = action.data.email; draft.lastname = action.data.lastname; draft.firstname = action.data.firstname; draft.birthday = action.data.birthday; draft.profileImage = action.data.profileImage; draft.isLogged = true; break; case LOG_IN_FAILURE: draft.logInError = action.error; break; case GET_USER_INFO_SUCCESS: draft.id = action.data.id; draft.email = action.data.email; draft.lastname = action.data.lastname; draft.firstname = action.data.firstname; draft.birthday = action.data.birthday; draft.profileImage = action.data.profileImage; draft.isLogged = true; break; case LOG_OUT_SUCCESS: draft.id = 0; draft.email = ""; draft.lastname = ""; draft.firstname = ""; draft.birthday = ""; draft.profileImage = ""; draft.isLogged = false; break; default: break; } }); export default reducer;
3ed570af92d91ea43a95bcc51e6bc8b5ea6afcb3
TypeScript
mlaanderson/firebase-budget
/webapp/src/controllers/events.ts
3.421875
3
type Constructor<T> = new(...args: any[]) => T; function EventMaker<T extends Constructor<{}>>(Base: T) { return class Events extends Base { private listeners: {[event: string]: Array<(...args : any[]) => void>}; constructor(...args: any[]) { super(...args); this.listeners = {}; } on(event: string, handler: (...args : any[]) => void, context?: any) : Events { if (!this.listeners) this.listeners = {}; if (event in this.listeners === false) { this.listeners[event] = []; } if (context) { handler.bind(context); } this.listeners[event].push(handler); return this; } off(event: string, handler?: (...args : any[]) => void) : Events { if (!this.listeners) return this; if (event in this.listeners === false) return this; if (handler) { let idx = this.listeners[event].indexOf(handler); if (idx >= 0) { this.listeners[event].splice(idx, 1); } } else { this.listeners[event] = []; } return this; } once(event: string, handler: (...args : any[]) => void, context?: any) : Events { if (context) { handler.bind(context); } let tHandler = (...args : any[]) => { handler(...args); this.off(event, tHandler); } this.on(event, tHandler); return this; } emit(event: string, ...args : any[]) : Events { if (!this.listeners) return this; if (event in this.listeners === false) return this; let errors: Array<any> = new Array<any>(); for (let handler of this.listeners[event]) { try { handler(...args); } catch (error) { errors.push(error); } } for (let error of errors) { throw(error); } return this; } emitAsync(event: string, ...args : any[]) : Promise<void> { if (!this.listeners) return Promise.resolve(); let promises = new Array<Promise<void>>(); if (event in this.listeners === false) return Promise.resolve(); for (let handler of this.listeners[event]) { promises.push(new Promise((resolve, reject) => { try { handler(...args); } catch (error) { return reject(error); } resolve(); })); } return new Promise((resolve, reject) => { Promise.all(promises).then(() => { resolve(); }).catch((reason) => { reject(reason); }); }); } static Extend<T extends Constructor<{}>>(Base: T) { return EventMaker(Base); } } } const Events = EventMaker(Object); export default Events;
cbfe6cb2712d68763f55fea50f724ad37a886844
TypeScript
ApPlamen/Restaurants
/FrontEnd/src/app/shared/components/simple-table/simple-table.component.ts
2.75
3
import { ChangeDetectionStrategy, Component, Injector, Input } from '@angular/core'; import { SimpleTableColumn } from '../../models/simple-table.model'; import { NOT_AVAILABLE } from './simple-table.constants'; @Component({ selector: 'tmc-simple-table', templateUrl: './simple-table.component.html', styleUrls: ['./simple-table.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush }) export class SimpleTableComponent { /** Column configuration **/ @Input() columns: SimpleTableColumn[]; /** * Data items to display */ @Input() data: any[]; /** * A heading describing the information displayed in the table */ @Input() title: string; constructor(private injector: Injector) {} /** * Format a data item value based on the column configuration. * By default, the value is formatted using the standard `toString` implementation. * If the column is configured with a pipe then we use it to get the formatted value. * When a value is missing we display N/A. * * @param dataItem Data item which contains the information to display. * @param column Configuration of the specific column to display. * @returns Formatted value. */ public getFormattedValue(dataItem: any, column: SimpleTableColumn): string { const notAvailable = NOT_AVAILABLE; const value = dataItem[column.field]; let formattedValue = value?.toString(); if (column.pipe) { const pipe = this.injector.get(column.pipe); formattedValue = pipe.transform(value, ...(column.pipeArgs || [])); } const isEmptyValue = formattedValue ?? formattedValue === ''; formattedValue = !isEmptyValue ? notAvailable : formattedValue; return formattedValue; } }
d1cd6a05e31341cec8dcf89225ae5f7004e31d05
TypeScript
SimonAlling/telia-wifi-auto-login
/.userscripter/build/config.ts
2.78125
3
import { not } from "./utils"; import { FILE_CONFIG, FILE_CONFIG_PROPERTIES_OPTIONAL, FILE_CONFIG_PROPERTIES_REQUIRED, format, } from "./io"; // These keys must be present in the config file: import CONFIG_KEYS_REQUIRED from "../../config/validation/userscript-required"; // These keys are recognized but not required: import CONFIG_KEYS_OPTIONAL from "../../config/validation/userscript-optional"; export class UserscriptConfigError extends Error {} export class MissingPropertiesException extends UserscriptConfigError { constructor(public keys: string[]) { super(); } } export type Config = { [key: string]: string }; // All recognized replacement keys: export const CONFIG_KEYS = CONFIG_KEYS_REQUIRED.concat(CONFIG_KEYS_OPTIONAL); export function isRecognizedProperty(key: string): boolean { return CONFIG_KEYS.includes(key); } export function unrecognizedProperties(config: Config): string[] { return Object.keys(config).filter(not(isRecognizedProperty)); } export function validate(config: Config): Config { const missingKeys = CONFIG_KEYS_REQUIRED.filter(key => !config.hasOwnProperty(key)); if (missingKeys.length > 0) { throw new MissingPropertiesException(missingKeys); } return config; }
0524e03e481ebeee3ddb011b979885f0b57c4c9f
TypeScript
roybcr/Algorithms
/source/Unions/makeUnique.ts
4.0625
4
/** * makeUnique Takes a Set or an Array of elements, and if it’s given an Array, * it’ll sort that Array remove duplicates according to some comparison function. * After all that, it will return the original collection. {@link makeUnique}. */ export function makeUnique<T, C extends Set<T> | T[]>( collection: C, comparer: (x: T, y: T) => number, ): Set<T> | T[] { // Early bail-out if we have a Set. // We assume the elements are already unique. if (collection instanceof Set) { return collection; } // Sort the array, then remove consecutive duplicates. collection.sort(comparer); for (let i = 0; i < collection.length; i++) { let j = i; while (j < collection.length && comparer(collection[i], collection[j + 1]) === 0) { j++; } collection.splice(i + 1, j - i); } return collection; } console.log(makeUnique([132, 43, 5, 454, 2, 323, 45, 6, 6, 76], (a: number, b: number) => a - b));
eae0ccacc0bde36fe4d45af1e4a732d824737670
TypeScript
cancerberoSgx/suitecommerce-types
/tests/ts-any-issue/src/valueOfTypeTest.ts
4.15625
4
/** returns the type of the value with key K in the Mapped type T. * * Example1: `type _string = ValueOf<A, 'a'>` * * Example 2 : * ``` // the following is model-like class which attributes object are described with a type param and which // getAttributes() and setAttributes methods are automatically type checked, not only for references // describing the attributes names but also for references describing its attribute values type Obj = {[k:string]: any} class Model<Attributes extends Obj = {}>{ attributes: Attributes = {} as Attributes getAttribute<T extends string = typeof name>(name: T) : ValueOf<Attributes, T> { return this.attributes[name] } setAttribute<T extends string = typeof name>(name: T, value: ValueOf<Attributes, T>): void { this.attributes[name]=value } } interface A1 { name: string, age: number } const m = new Model<A1>() var string1 = m.getAttribute('name') var number1 = m.getAttribute('age') m.setAttribute('name', 'seba') // ok m.setAttribute('name', 123) // error m.setAttribute('age', 123) // ok m.setAttribute('age', 'seba') // error ``` */ type ValueOf<T extends { [k: string]: any }, K extends string> = T[K]; // the following is model-like class which attributes object are described with a type param and which getAttributes() and setAttributes methods are automatically type checked, not only for references describing the attributes names but also for references describing its attribute values type Obj = {[k:string]: any} class Model<Attributes extends Obj = {}>{ attributes: Attributes = {} as Attributes getAttribute<T extends string = typeof name>(name: T) : ValueOf<Attributes, T> { return this.attributes[name] } setAttribute<T extends string = typeof name>(name: T, value: ValueOf<Attributes, T>): void { this.attributes[name]=value } } interface A1 { name: string, age: number } const m = new Model<A1>() var string1 = m.getAttribute('name') var number1 = m.getAttribute('age') m.setAttribute('name', 'seba') // ok m.setAttribute('name', 123) // error m.setAttribute('age', 123) // ok m.setAttribute('age', 'seba') // error
727c7601f597cabf641cf867f67f69639f606c05
TypeScript
remuspoienar/apigen-admin
/src/app/helpers/api-request.helper.ts
2.71875
3
export function formatBody(body: Object) { for (let key in body) { let value = body[key]; if (!(value instanceof Array)) continue; let newKey = formatKey(key); delete body[key]; body[newKey] = value.map(obj => formatBody(obj)); } } function formatKey(key: string) { let upperLetter = regex.exec(key)[0]; let keyName = key.split(regex).join(`_${upperLetter.toLowerCase()}`).concat('_attributes'); return keyName; } let regex = new RegExp(/[A-Z]/);
46bcaa5b51ab36a590ca6949776280b8ef255bda
TypeScript
garaev-salavat/angular-hw6-tsk6
/src/app/mock-lessons.ts
2.6875
3
import { Lesson } from './lesson'; import { Student } from './student'; import { StudentGrade } from './student-grade'; export const LESSONS: Lesson[] = [ { id: 1, date: new Date(2021, 1, 16), theme: 'Привязка данных', homework: 'Домашнее задание на тему привязки данных', note: 'Примечания к уроку по привязке данных', }, { id: 2, date: new Date(2021, 1, 23), theme: 'Компоненты', homework: 'Домашнее задание на тему Компоненты', note: 'Примечания к уроку по Компоненты', }, { id: 3, date: new Date(2021, 1, 30), theme: 'Директивы', homework: 'Домашнее задание на тему Директивы', note: 'Примечания к уроку по Директивы', }, { id: 4, date: new Date(2021, 2, 6), theme: 'Жизненный цикл', homework: 'Домашнее задание на тему Жизненный цикл', note: 'Примечания к уроку по Жизненный цикл', }, ]; export const STUDENT: Student[] = [ { id: 1, firstName: 'Иван', lastName: 'Иванов', }, { id: 2, firstName: 'Георгий', lastName: 'Паравозов', }, { id: 3, firstName: 'Ксения', lastName: 'Павлова', }, { id: 4, firstName: 'Роман', lastName: 'Горбунов', }, { id: 5, firstName: 'Андрей', lastName: 'Орлов', }, ]; export const STUDENT_GRADE: StudentGrade[] = [ { lessonId: 1, studentId: 1, grade: 3, }, { lessonId: 2, studentId: 1, grade: 5, }, { lessonId: 3, studentId: 1, grade: 4, }, { lessonId: 4, studentId: 1, grade: 6, }, { lessonId: 1, studentId: 2, grade: 4, }, { lessonId: 2, studentId: 2, grade: 4, }, { lessonId: 3, studentId: 2, grade: 5, }, { lessonId: 4, studentId: 2, grade: 3, }, { lessonId: 1, studentId: 3, grade: 3, }, { lessonId: 2, studentId: 3, grade: 6, }, { lessonId: 3, studentId: 3, grade: 5, }, { lessonId: 4, studentId: 3, grade: 3, }, { lessonId: 1, studentId: 4, grade: 3, }, { lessonId: 2, studentId: 4, grade: 6, }, { lessonId: 3, studentId: 4, grade: 5, }, { lessonId: 4, studentId: 4, grade: 4, }, { lessonId: 1, studentId: 5, grade: 3, }, { lessonId: 2, studentId: 5, grade: 3, }, { lessonId: 5, studentId: 5, grade: 3, }, { lessonId: 4, studentId: 5, grade: 3, }, ];
a55746f8d8e7aae7568e5b1399f824d6ae748747
TypeScript
ststeiger/AnySqlWebAdmin
/AnySqlWebAdmin/TypeScript/Tools/urlModifier.ts
2.921875
3
 namespace Tools { interface Dictionary<T> { [key: string]: T; } export class UrlModifier { public url: string; public hash: string; public keys: string[]; public values: Dictionary<string>; protected m_caseSensitive:boolean; get queryString(): string { let qs = ""; for (let i = 0; i < this.keys.length; ++i) { qs += (i === 0 ? "?" : "&") + encodeURIComponent(this.keys[i]) + "=" + encodeURIComponent(this.values[this.keys[i]]); } // Next i return qs; } // End Property queryString constructor(url:string, caseSensitive?: boolean) { this.autoBind(this); if (caseSensitive == null) caseSensitive = false; this.hash = null; this.keys = []; this.values = {}; this.m_caseSensitive = caseSensitive; let hashStart = url.indexOf('#'); let paramStart = url.indexOf('?'); // Remove and save hash, if exists if (hashStart !== -1) { this.hash = url.substr(hashStart + 1); url = url.substr(0, hashStart); } // End if (hashStart !== -1) if (paramStart < 0) return; this.url = url.substr(0, paramStart); let queryString = url.substr(paramStart + 1); let kvps = queryString.split('&'); for (let i = 0; i < kvps.length; i++) { let kvp = kvps[i].split('='); kvp[0] = decodeURIComponent(kvp[0]); kvp[1] = decodeURIComponent(kvp[1]); let key = this.m_caseSensitive ? kvp[0] : kvp[0].toLowerCase(); this.keys.push(key); this.values[key] = kvp[1]; } // Next i } // End Constructor private autoBind(self: any) : any { for (const key of Object.getOwnPropertyNames(self.constructor.prototype)) { if (key !== 'constructor') { // console.log(key); let isFunction = true; let desc = Object.getOwnPropertyDescriptor(self.constructor.prototype, key); if (desc.get != null) { desc.get = desc.get.bind(self); isFunction = false; } if (desc.set != null) { desc.set = desc.set.bind(self); isFunction = false; } // const val = self[key]; // NO ! key could be a property ! if (isFunction && typeof(self[key]) === 'function') { let val = self[key]; self[key] = val.bind(self); } } // End if (key !== 'constructor' && typeof val === 'function') } // Next key return self; } // End Function autoBind public containsKey(key: string):boolean { let caseKey = this.m_caseSensitive ? key : key.toLowerCase(); let index = this.keys.indexOf(caseKey); return (index > -1); } // End Function containsKey public get(key: string): string { let caseKey = this.m_caseSensitive ? key : key.toLowerCase(); return this.values[caseKey]; } // End Function get public set(key: string, value: string): UrlModifier { let caseKey = this.m_caseSensitive ? key : key.toLowerCase(); let index = this.keys.indexOf(caseKey); if (index == -1) { this.keys.push(caseKey); } this.values[caseKey] = value; return this; } // End Function set public add(key: string, value: string): UrlModifier { return this.set(key, value); } // End Function add public remove(key: string): UrlModifier { let caseKey = this.m_caseSensitive ? key : key.toLowerCase(); let index = this.keys.indexOf(caseKey); if (index > -1) { this.keys.splice(index, 1); } delete this.values[caseKey]; return this; } // End Function remove public encode(pd:object & {[key: string]: string}):UrlModifier { let k:string; for (k in pd) this.add(k, pd[k]); return this; } public toUrl() { let newUrl = this.url + this.queryString; if(this.hash != null) newUrl += "#" + this.hash; return newUrl; } // End Function toUrl } // End Class UrlModifier } // End Namespace Tools // let a = new Tools.UrlModifier("https://www.youtube.com/watch?v=RkVJNOQ7B74&list=LLqYvX1BFZVm3txSbXfLfQcA&index=67#foobar");
b16cdbcb1afecc4ae3ab4258ba7890392b0e474d
TypeScript
kpwags/digital-family-cookbook
/frontend/src/utils/UserFunctions.ts
2.578125
3
import { UserAccount } from '@models/UserAccount'; export const hasRole = (user: UserAccount | null, roleName: string): boolean => { if (user) { return user.roles.filter((u) => u.normalizedName === roleName).length > 0; } return false; };
f42f82eb2502f7c8e03724dd3cf84a16771974b8
TypeScript
lexytail/games-letter
/index.ts
3.28125
3
const random = (max: number) => (Math.random() * (max + 1)) | 0 class Square { public $element: HTMLDivElement = document.createElement('div') constructor( public $root: HTMLElement, public letter: string, public size: number = 100 ) { this.init() } protected init() { Object.assign(this.$element.style, { width: `${this.size}px`, height: `${this.size}px`, position: 'absolute', backgroundColor: '#f0ff0f', color: '#000', cursor: 'pointer', textTransform: 'uppercase', display: 'flex', alignItems: 'center', justifyContent: 'center' } as CSSStyleDeclaration) this.$element.innerHTML = this.letter this.$root.appendChild(this.$element) } setPos(x: number, y: number) { this.$element.style.top = `${y}px` this.$element.style.left = `${x}px` } } class Game { public squares: Square[] = [] public square_size: number = 50 public timerId?: number public width: number = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth public height: number = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight public $container = document.body public alphabet: string = 'qwertyuiopasdfghjklzxcvbnm' public get randomLetter(): string { const number = random(this.alphabet.length - 1) const letter = this.alphabet[number] return letter } public start() { this.timerId = setInterval(this.update.bind(this), 500) this.init() } public init() { document.addEventListener('keypress', (event) => { if (event.defaultPrevented) return; const key = event.key || event.keyCode; const index = this.squares.findIndex((square) => square.letter === key) if (index === -1) { return } const square = this.squares[index] this.$container.removeChild(square.$element) this.squares.splice(index, 1) }) } public stop() { clearTimeout(this.timerId) } protected update() { this.addSquare() if (this.squares.length > 10) return this.game_over() } public game_over() { this.stop() alert('Game over') } addSquare(): void { const x = random(this.width - this.square_size * 2) const y = random(this.height - this.square_size * 2) const square = new Square(this.$container, this.randomLetter) square.setPos(x, y) this.squares.push(square) } }
081b2b05ccc92f75ca9cdbd820f73be7e0f5608c
TypeScript
th4t-gi/apcsa-lotr-game
/ts-version/src/warrior.ts
2.984375
3
class Warrior { static readonly ANSI_RESET = "\u001B[0m"; static readonly ANSI_BLACK = "\u001B[30m"; static readonly ANSI_RED = "\u001B[31m"; static readonly ANSI_GREEN = "\u001B[32m"; static readonly ANSI_YELLOW = "\u001B[33m"; static readonly ANSI_BLUE = "\u001B[34m"; static readonly ANSI_PURPLE = "\u001B[35m"; static readonly ANSI_CYAN = "\u001B[36m"; static readonly ANSI_WHITE = "\u001B[37m"; protected static readonly STARTING_HEALTH: number = 55; protected readonly ATTACK_POW: number = 6; protected readonly ATTACK_PROB: number = 67; protected readonly CRITICAL_PROB: number = 0; protected readonly SHEILD_PROB: number = 0; private name: string; private health: number; private index: number; private color: string; protected readonly type: string = "Warrior"; constructor(name: string = "Generic Warrior", index: number = 0, health: number = Warrior.STARTING_HEALTH, color: string = "White") { this.name = name this.health = health this.index = index; this.color = Warrior.getColorCode(color); } getName(): string { return this.name; } getHealth(): number { return this.health; } getIndex(): number { return this.index; } getColor(): string { return this.color; } printName(): string { return this.color + this.name + Warrior.ANSI_RESET } getAttackPow(): number { return this.ATTACK_POW; } getAttackProb(): number { return this.ATTACK_PROB; } getCriticalProb(): number { return this.CRITICAL_PROB; } getSheildProb(): number { return this.SHEILD_PROB; } getType(): string { return this.type } getHealthBar(): string { return "|".repeat(this.health) } set setIndex(i: number) { this.index = i; } battleCry(): string { return "From Middle Earth!!!"; } async attack(opponent: Warrior, delay = 1000, verbose = true) { let roll: number = Math.floor(Math.random() * 100) + 1; if (verbose) console.log(`${this.printName()} is attacking ${opponent.printName()}!`) await Warrior.sleep(delay) let msg: string; let damage: number = 0; if (roll <= this.getCriticalProb()) { msg = `${this.printName()} ${this instanceof Elf ? "shoots an arrow" : "throws an axe"} and scores a CRITICAL HIT on ${opponent.printName()}!` damage = this.getAttackPow() * 2 } else if (roll <= this.getAttackProb()) { let defense: number = Math.floor(Math.random() * 100) + 1; if (defense <= opponent.getSheildProb()) { msg = `${this.printName()} blocks ${opponent.printName()}'s attack!` } else { msg = `${this.printName()} successfully attacks ${opponent.printName()}!` damage = this.getAttackPow(); } } else { msg = `${this.printName()}'s attack has failed.`; } if (verbose) console.log(msg); opponent.health -= damage; Warrior.sleep(delay) } static async sleep(milli: number) { return new Promise((resolve) => setTimeout(resolve, milli)); } static getColorCode(name: string) { const map = { "Black": Warrior.ANSI_BLACK, "White": Warrior.ANSI_WHITE, "Red": Warrior.ANSI_RED, "Yellow": Warrior.ANSI_YELLOW, "Green": Warrior.ANSI_GREEN, "Blue": Warrior.ANSI_BLUE, "Purple": Warrior.ANSI_PURPLE, "Cyan": Warrior.ANSI_CYAN, } if (!map[name]) return map["White"] return map[name]; } initWarrior(type: string = "Warrior", name: string = "", index: number = 0) { const map = { "Warrior": new Warrior(name, index), "Elf": new Elf(name, index), "Dwarf": new Dwarf(name, index), "Man": new Man(name, index), "GondorMan": new GondorMan(name, index), "RohanMan": new RohanMan(name, index), } if (!map[type]) return map["Warrior"] return map[type] } } class Elf extends Warrior { protected static readonly STARTING_HEALTH: number = 70; protected readonly ATTACK_POW: number = 4; protected readonly ATTACK_PROB: number = 83; protected readonly CRITICAL_PROB: number = 17; protected readonly SHEILD_PROB: number = 0; protected readonly type: string = "Elf"; constructor(name: string = "Generic Elf", index: number = 0, health: number = Elf.STARTING_HEALTH, color: string = "White") { super(name, index, health, color) } getAttackPow(): number { return this.ATTACK_POW; } getAttackProb(): number { return this.ATTACK_PROB; } getCriticalProb(): number { return this.CRITICAL_PROB; } getSheildProb(): number { return this.SHEILD_PROB; } getType(): string { return this.type } battleCry(): string { return "Tomorrow, a red moon rises!"; } } class Dwarf extends Warrior { protected static readonly STARTING_HEALTH: number = 60; protected readonly ATTACK_POW: number = 7; protected readonly ATTACK_PROB: number = 50; protected readonly CRITICAL_PROB: number = 33; protected readonly SHEILD_PROB: number = 0; protected readonly type: string = "Dwarf"; constructor(name: string = "Generic Dwarf", index: number = 0, health: number = Dwarf.STARTING_HEALTH, color: string = "White") { super(name, index, health, color) } getAttackPow(): number { return this.ATTACK_POW; } getAttackProb(): number { return this.ATTACK_PROB; } getCriticalProb(): number { return this.CRITICAL_PROB; } getSheildProb(): number { return this.SHEILD_PROB; } getType(): string { return this.type } battleCry(): string { return "For Moria!!"; } }
afc7936d3a14025152b2f4db927d6193acd28436
TypeScript
downplay/create-rogue-app
/packages/herotext/test/parse.programs.speak.test.ts
3.34375
3
import { text, commonFunctions } from "../index"; import { mockRng } from "./testUtils"; import { render } from "../src/execute"; // TODO: Early version was simpler, like this: // {<20}$speak($slice($number,1))teen // {<100}$speak($slice($number,0,1)0)-$speak($slice($number,1)) // {<1000}$speak($slice($number,0,1)0) hundred$and($slice($number,1)) // // Would be nice to support "first match" (maybe label:. ) so the additional // preconditions aren't required, additionally need both AND and OR somehow // // And finally it'd be good to automatically convert these to numbers // ($number,0,0) // Either by defining it on the $slice signature, or by using <0> // TODO: Also, really think about how these are treated as numbers, strings, weights. // Would be nice to express {00} to only match the 00 string. Maybe some way of things // being "string and number" until they're used. Or should we do like: // {<12>} for a number, {10} for a weight, {[12]} for a string ... hrm ... // should % still do anything? it("Counts up to 9999", () => { const rng = mockRng(); const fixture = text` [$speak(1) $speak(12) $speak(17) $speak(34) $speak(112) $speak(285) $speak(300) $speak(516) $speak(999) $speak(1000)] ${commonFunctions} speak: ($number) {0}nought {1}one {2}two {3}three {4}four {5}five {6}six {7}seven {8}eight {9}nine {10}ten {11}eleven {12}twelve {13}thirteen {14}$umpteen($slice($number,1)) {15}fifteen {>15,<20}$umpteen($slice($number,1)) {20}twenty {30}thirty {40}fourty {50}fifty {60}sixty {70}seventy {80}eighty {90}ninety {>20,<100,$slice($number,1)!=0}$speak($slice($number,0,1)0)-$speak($slice($number,1)) {>=100,<1000}$speak($slice($number,0,1)) hundred$and($slice($number,1)) {1000}one thousand umpteen: ($number) $speak($number)teen and: ($number) {0} {0%} and $speak($number) `; expect(render(fixture, rng)).toEqual(`one twelve seventeen thirty-four one hundred and twelve two hundred and eighty-five three hundred five hundred and sixteen nine hundred and ninety-nine one thousand`); });
bcde311cf6dbb40a8d1eed26b0773388f6b10f2a
TypeScript
wessberg/fovea-wordpress-landing-test
/src/Service/WaitOperations/WaitOperations.ts
2.734375
3
import {IWaitOperations} from "./Interface/IWaitOperations"; export class WaitOperations implements IWaitOperations { public async wait (time: number = 0): Promise<void> { return new Promise<void>(resolve => setTimeout(resolve, time)); } }
f98c9b5bf6110d0ab5b0872d793774655d3e9b02
TypeScript
josephluck/pion
/examples/simple.ts
2.765625
3
import { View, h } from '../src' export type MyState = { title: string } const defaultState: MyState = { title: 'Hello' } const view: View<MyState> = (state = defaultState, update) => { const updateTitle = () => { update({ title: Date.now().toString() }) } return h('div', { id: 'my-div', onclick: updateTitle, }, state.title) } export default view
90fbfc1c9ae3464a562a867a5d8cc618e44b081f
TypeScript
SrMatheus2000/Senac_TI
/Tipos/Exercício 1/tipos.ts
3.03125
3
// let OlaMundo = (teste: string) => { // console.log(teste); // }; // OlaMundo("Olá Mundo"); let mensagem: string = "ola mundo" let numero: number = 2 let boleano: boolean = false let listadepalavras: Array<string> = ['1', '2'] let listadenumeros: Array<number> = [1, 2]
4dcf8b0728f168734e5993330701a38ec4fbb91d
TypeScript
jpbberry/typed-emitter
/src/utils/Decorators.ts
3.09375
3
import { EventEmitter } from '../emitters/EventEmitter' import { ExtendedEmitter } from '../emitters/ExtendedEmitter' export const eventMapper = Symbol('__event_map') // export enum EventMapperType { // } export interface EventMapperOptions { event: string method: string | Function type: 'on' | 'once' } type EMITTER = EventEmitter<any> | ExtendedEmitter function addEvent (target: EMITTER, method: string, event: string, type: 'on' | 'once') { if (target[eventMapper] === undefined) { target[eventMapper] = [] } else if (!target.hasOwnProperty(eventMapper)) { target[eventMapper] = [ ...target[eventMapper] ] } target[eventMapper]!.push({ event, method, type }) } export function Event (event: string) { return function (target: EMITTER, method: string) { addEvent(target, method, event, 'on') } } export function Once (event: string) { return function (target: EMITTER, method: string) { addEvent(target, method, event, 'once') } }
65113416d550224e68adfa3190b83174ffcf9a23
TypeScript
bketelsen/react-strapi-img
/src/imageLoader.ts
2.890625
3
export default class ImageLoader { private img: HTMLImageElement | null = null; load(src: string, srcSet: string, onDecode: () => void): void { this.img = new Image(); if (srcSet) this.img.srcset = srcSet; this.img.src = src; this.img .decode() .then(() => { onDecode(); }) .catch(() => { throw new Error(`react-strapi-img: Could not decode image "${src}".`); }); } unload(): void { if (this.img) { this.clearImgSrc(); this.img = null; } } private clearImgSrc() { (this.img as HTMLImageElement).srcset = ""; (this.img as HTMLImageElement).src = ""; try { delete (this.img as HTMLImageElement).srcset; delete (this.img as HTMLImageElement).src; } catch (error) {} } }
47f3a89dc5e4e16cc91f8b5379cf246b02d9afec
TypeScript
dj-death/SimProX
/kernel/Engine/ComputeEngine/Finance/Finance.ts
2.5625
3
 import * as Fin from './'; import ENUMS = require('../ENUMS'); import console = require('../../../utils/logger'); import Utils = require('../../../utils/Utils'); import Q = require('q'); export default class Finance { departmentName = "Finance"; get Proto(): Finance { return Finance.prototype; } private insurances: Fin.Insurance[]; private bankAccounts: Fin.BankAccount[]; capital: Fin.Capital; init() { this.insurances = []; this.bankAccounts = []; this.capital = null; } register(objects: any[]) { let i = 0, len = objects.length, object; for (; i < len; i++) { object = objects[i]; if (object instanceof Fin.Insurance) { this.insurances.push(object); } else if (object instanceof Fin.BankAccount) { this.bankAccounts.push(object); } else if (object instanceof Fin.Capital) { this.capital = object; } } } calcOverdraftLimit(company_BankFile): number { let sums = 0; this.bankAccounts.forEach(function (account) { sums += account.calcOverdraftLimit(company_BankFile); }); return sums; } get insurancesPremiumsCost(): number { return Utils.sums(this.insurances, "premiumsCost"); } get insurancesClaimsForLosses(): number { return Utils.sums(this.insurances, "claimsForLosses"); } get insurancesReceipts(): number { return Utils.sums(this.insurances, "receipts"); } get insurancesPrimaryNonInsuredRisk(): number { return Utils.sums(this.insurances, "primaryNonInsuredRisk"); } get interestPaid(): number { return Utils.sums(this.bankAccounts, "interestPaid"); } get interestReceived(): number { return Utils.sums(this.bankAccounts, "interestReceived"); } get banksOverdraft(): number { return Utils.sums(this.bankAccounts, "overdraft"); } get termDeposit(): number { return Utils.sums(this.bankAccounts, "termDeposit"); } get termLoansValue(): number { return Utils.sums(this.bankAccounts, "termLoans"); } get additionalLoans(): number { return Utils.sums(this.bankAccounts, "additionalLoans"); } get balance(): number { return Utils.sums(this.bankAccounts, "balance"); } get cashValue(): number { return Utils.sums(this.bankAccounts, "cash"); } get interestBearingDebts(): number { return this.termLoansValue + this.banksOverdraft; } get dividendRate(): number { return this.capital.dividendRate; } getEndState(prefix?: string): Q.Promise<any> { let deferred = Q.defer(); let endState = {}; let that: Object = this; let deptName = this.departmentName; setImmediate(function () { for (let key in that) { console.silly("fin GES @ %s of %s", key); if (!Finance.prototype.hasOwnProperty(key)) { continue; } try { let value = that[key]; if (!Utils.isBasicType(value)) { continue; } if (isNaN(value)) { console.warn("GES @ %s: %s is NaN", deptName, key); } key = prefix ? (prefix + key) : key; endState[key] = value; } catch (e) { console.error(e, "exception @ %s", deptName); deferred.reject(e); } } deferred.resolve(endState); }); return deferred.promise; } }
3b18bda8339f598992010296c617af5c9cbc9533
TypeScript
kjlevitz/neon-js
/packages/neon-core/__tests__/wallet/nep2.ts
2.765625
3
import * as NEP2 from "../../src/wallet/nep2"; import { isNEP2, isWIF } from "../../src/wallet/verify"; const simpleScrypt = { n: 256, r: 1, p: 1, }; const simpleKeys = { a: { wif: "L1QqQJnpBwbsPGAuutuzPTac8piqvbR1HRjrY5qHup48TBCBFe4g", passphrase: "city of zion", encryptedWif: "6PYLHmDf7R4im6NUF34MwcbViPpjwfdkrPMdFjuCXnEFmmK2A7AAzVAvTa", }, b: { wif: "L2QTooFoDFyRFTxmtiVHt5CfsXfVnexdbENGDkkrrgTTryiLsPMG", passphrase: "我的密码", encryptedWif: "6PYWVp3xerNdVMtSELSNZDBMP1qXrM1o6NrCQHqpeWLMd3rgeUE1rQuwrm", }, c: { wif: "KyKvWLZsNwBJx5j9nurHYRwhYfdQUu9tTEDsLCUHDbYBL8cHxMiG", passphrase: "MyL33tP@33w0rd", encryptedWif: "6PYNoc1EFvW5rJD2Tg6k24xEVGZ56sY1YN5NG2sSF1qUKHy47uEwTkdcYs", }, }; const testKey = { wif: "L1QqQJnpBwbsPGAuutuzPTac8piqvbR1HRjrY5qHup48TBCBFe4g", passphrase: "city of zion", encryptedWif: "6PYLHmDf6AjF4AsVtosmxHuPYeuyJL3SLuw7J1U8i7HxKAnYNsp61HYRfF", }; describe("NEP2", () => { describe("Default", () => { test("encrypt", async () => { const result = await NEP2.encrypt(testKey.wif, testKey.passphrase); expect(isNEP2(result)).toBeTruthy(); expect(result).toBe(testKey.encryptedWif); }, 10000); test("decrypt", async () => { const result = await NEP2.decrypt( testKey.encryptedWif, testKey.passphrase ); expect(isWIF(result)).toBeTruthy(); expect(result).toBe(testKey.wif); }, 10000); }); describe.each([ ["Basic", simpleKeys.a], ["Chinese", simpleKeys.b], ["Symbols", simpleKeys.c], ])("%s", (msg: string, data: any) => { test("encrypt", async () => { const result = await NEP2.encrypt( data.wif, data.passphrase, simpleScrypt ); expect(isNEP2(result)).toBeTruthy(); expect(result).toBe(data.encryptedWif); }); test("decrypt", async () => { const result = await NEP2.decrypt( data.encryptedWif, data.passphrase, simpleScrypt ); expect(isWIF(result)).toBeTruthy(); expect(result).toBe(data.wif); }); }); describe("Error", () => { test("Errors on wrong password", () => { const thrower = NEP2.decrypt( simpleKeys.a.encryptedWif, "wrongpassword", simpleScrypt ); expect(thrower).rejects.toThrow("Wrong password"); }); test("Errors on wrong scrypt params", () => { const thrower = NEP2.decrypt( simpleKeys.a.encryptedWif, simpleKeys.a.passphrase ); expect(thrower).rejects.toThrow("scrypt parameters"); }); }); });
21962d4d842b6315082b9462b529c49e94914a01
TypeScript
Mathieu94110/Meteo-App
/src/types.ts
2.625
3
export const GET_METEO_DATA = "GET_METEO_DATA"; export const SET_LOADING = "SET_LOADING"; export const SET_ERROR = "SET_ERROR"; export const SET_ALERT = "SET_ALERT"; export interface Meteo { description: string; icon: string; id: number; main: string; } export interface MeteoData { base: string; clouds: { all: number; }; cod: number; coord: { lon: number; lat: number; }; dt: number; id: number; main: { feels_like: number; humidity: number; pressure: number; temp: number; temp_max: number; temp_min: number; }; name: string; sys: { country: string; id: number; sunrise: number; sunset: number; type: number; }; timezone: number; visibility: number; weather: Meteo[]; wind: { // speed: number; // deg: number; // }; // } export interface MeteoError { cod: string; message: string; } export interface MeteoState { data: MeteoData | null; loading: boolean; error: string; } interface GetMeteoAction { type: typeof GET_METEO_DATA; payload: MeteoData; } interface SetLoadingAction { type: typeof SET_LOADING; } interface SetErrorAction { type: typeof SET_ERROR; payload: string; } export type MeteoAction = GetMeteoAction | SetLoadingAction | SetErrorAction; export interface AlertAction { type: typeof SET_ALERT; payload: string; } export interface AlertState { message: string; }
13d247cbe80217547fd44b4ca12bcacdeba2cfe0
TypeScript
NominaUN/frontendAngular2
/src/app/Services/fonds/fonds.service.ts
2.5625
3
import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Fond } from '../../Models/fond' import { Observable } from 'rxjs/Observable'; @Injectable() export class FondsService { private urlget : string = "http://localhost:3000/api/v1/fonds.json"; private urlpost : string = "http://localhost:3000/api/v1/fonds"; headers: Headers; options: RequestOptions; constructor(private http: Http) { this.headers = new Headers({ 'Content-Type': 'application/json' }); this.options = new RequestOptions({ headers: this.headers }); } getFonds(): Observable<Fond[]> { return this.http.get(this.urlget).map((response: Response) => <Fond[]>response.json().data); } setFonds(fond: Fond): Observable<Fond> { return this.http.post(this.urlpost, JSON.stringify(fond), this.options).map(response => response.json()) } updateFond(fond): Observable<Fond> { const url = `${this.urlpost}/${fond.id}`; console.log(url) return this.http.put(url, JSON.stringify(fond), this.options).map((res: Response) => res.json()) // .map(function(res : Response){ // console.log(res.json()); // res.json() // }) .catch(this.handleError); } private handleError(error: any): Promise<any> { console.error('An error occurred', error); // for demo purposes only return Promise.reject(error.message || error); } private extractData(res: Response) { let body = res.json(); return body || {}; } deleteFond(id: number): Observable<Fond> { const url = `${this.urlpost}/${id}`; return this.http.delete(url, this.options) .map(this.extractData) .catch(this.handleError); } }
da1f1ea293e6bcadce4c9780aaf4dd108a4049d2
TypeScript
OyvindSabo/truss-simulation
/front-end/src/models/strut/Strut.ts
3
3
import Name from '../name/Name'; import Node from '../node/Node'; export interface StrutProps { id?: string; name?: string; source: Node; target: Node; radius?: number; } class Strut { id: string; name: Name; source: Node; target: Node; radius: number; _changeListeners: (() => void)[]; constructor({ id, name, source, target, radius }: StrutProps) { this.id = id || `${new Date().getTime()}`; this.name = new Name(name || ''); this.name.addChangeListener(this._callChangeListeners); this.source = source; this.target = target; this.radius = radius || 0.1; this._changeListeners = []; } addChangeListener(changeListener: () => void) { this._changeListeners.push(changeListener); } // This will be passed as a callback so it has to be an arrow function _callChangeListeners = () => { this._changeListeners.forEach(changeListener => { changeListener(); }); }; objectify() { return { id: this.id, name: this.name.objectify(), sourceId: this.source.id, targetId: this.target.id, radius: this.radius, }; } } export default Strut;
67848f6ed8009c61a432e64a969636451bbac747
TypeScript
gtgalone/studya
/frontend/src/redux/services/api.ts
2.5625
3
import { schema, normalize, Schema } from 'normalizr' import getConfig from 'next/config' import 'isomorphic-fetch' import { AxiosInstance } from 'axios' import { processLogout } from '../../shared/helper/auth-helper' // Extracts the next page URL from Github API response. function getNextPageUrl(response: any) { const link: string = response.headers.get('link') if (!link) { return null } const nextLink = link.split(',').find(s => s.indexOf('rel="next"') > -1) if (!nextLink) { return null } return nextLink.split(';')[0].slice(1, -1) } // Fetches an API response and normalizes the result JSON according to schema. // This makes every API response have the same shape, regardless of how nested it was. function callApi(endpoint: string, schema: Schema, token: string) { const fullUrl = (endpoint.indexOf(getConfig().publicRuntimeConfig.API_URL) === -1) ? getConfig().publicRuntimeConfig.API_URL + endpoint : endpoint const options: any = { method: 'GET', headers: Object.assign( {'Site': getConfig().publicRuntimeConfig.CURRENT_SITE}, token && { 'Authorization': 'Bearer ' + token } ), credentials: 'include' } return fetch(fullUrl, options) .then(response => response.json().then(json => ({ json, response })) ) .then<{}>(({ json, response }) => { if (!response.ok) { return Promise.reject(json) } const nextPageUrl = getNextPageUrl(response) return Object.assign({}, normalize(json, schema), { nextPageUrl } ) }) .then( response => ({response}), error => { processLogout() return { error: error.message || 'Something bad happened' } } ) } // We use this Normalizr schemas to transform API responses from a nested form // to a flat form where repos and users are placed in `entities`, and nested // JSON objects are replaced with their IDs. This is very convenient for // consumption by reducers, because we can easily build a normalized tree // and keep it updated as we fetch more data. // Read more about Normalizr: https://github.com/gaearon/normalizr const parcelsSchema = new schema.Entity('parcels') // api services export const fetchParcel = (endpoint: string, token: string) => callApi(endpoint, parcelsSchema, token) export const fetchLogin = async (http: AxiosInstance, payload: any) => { // try { // return await http.post('/api/login', { // user: payload, // }) // } catch (error) { // // error.message // } return fetch('/api/login', { method: 'POST', headers : { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ user: payload }), }).then((response) => response, (error) => { error.message //=> String }) } export const fetchSignup = (payload: any) => { return fetch('/api/signup', { method: 'POST', headers : { "Content-Type": "application/json" }, credentials: 'include', body: JSON.stringify({ user: payload }) }).then((response) => response, (error) => { error.message //=> String }) } export const fetchUnconfirmation = (payload: any) => { return fetch('/api/unconfirmation', { method: 'POST', headers : { "Content-Type": "application/json" }, credentials: 'include', body: JSON.stringify(payload) }).then((response) => response, (error) => { error.message //=> String }) } export const fetchPassword = (payload: any) => { return fetch('/api/password', { method: 'POST', headers : { "Content-Type": "application/json" }, credentials: 'include', body: JSON.stringify(payload) }).then((response) => response, (error) => { error.message //=> String }) } export const fetchResetPassword = (payload: any) => { return fetch('/api/reset-password', { method: 'POST', headers : { "Content-Type": "application/json" }, credentials: 'include', body: JSON.stringify(payload) }).then((response) => response, (error) => { error.message //=> String }) } export const fetchFeedback = (payload: any) => { return fetch(`${getConfig().publicRuntimeConfig.API_URL}feedbacks`, { method: 'POST', headers : { 'Content-Type': 'application/json', 'Authorization': `Bearer ${payload.token}`, 'Site': getConfig().publicRuntimeConfig.CURRENT_SITE }, credentials: 'include', body: JSON.stringify({ contents: payload.contents }) }).then((response) => response, (error) => { error.message //=> String }) } export const fetchSelectedParcel = (id: string) => { if (id) { return fetch(`${getConfig().publicRuntimeConfig.API_URL}pnu_polygons?pnu=${id}`, { headers: { 'Site': getConfig().publicRuntimeConfig.CURRENT_SITE }, credentials: 'include' }) .then((response) => response.json()) .then( response => ({response}), error => ({error: error.message || 'Something bad happened'}) ) } else { return { response: null } } }
94000bae767185d1c8c387458ce27c0b70d8001b
TypeScript
ilanddev/javascript-sdk
/src/sdk/model/advanced-backups/backup-group/protection-source.ts
2.546875
3
import { VCloudProtectionSourceType } from './__json__/vcloud-protection-source-type'; import { ProtectionSourceJson } from './__json__/protection-source-json'; /** * Backup Group Disk Unit. */ /* istanbul ignore next: autogenerated */ export class ProtectionSource { constructor(private _json: ProtectionSourceJson) { } /** * Gets the iland entity UUID. May be null if the source has been deleted. * @returns {string | null} iland entity uuid */ get entityUuid(): string | null { return this._json.entity_uuid || null; } /** * Gets the type of the associated iland IaaS entity. * @returns {VCloudProtectionSourceType} entity type */ get entityType(): VCloudProtectionSourceType { return this._json.entity_type; } /** * Gets the name of the associated entity. * @returns {string} entity name */ get entityName(): string { return this._json.entity_name; } /** * The UID of the associated entity in the backend backup system. * @returns {string} native uid */ get nativeUid(): string { return this._json.native_uid; } /** * Gets the json representation of this class. * @returns {ProtectionSourceJson} */ get json(): ProtectionSourceJson { return Object.assign({}, this._json); } /** * Gets the string representation of this class. * @returns {string} */ toString(): string { return JSON.stringify(this._json, undefined, 2); } }
5087dfe73f60c43fd3a4afc27aa28c7417adebc5
TypeScript
asterlibraryjs/aster-js-validation
/tests/asserts.test.ts
3.09375
3
import { assert } from "chai"; import { Validator, SucceedValidationResult, ValidationResult } from "../src"; describe("Validator", () => { type MyModel = { readonly id: number, readonly name: string, readonly value: any; }; const myModelValidator = Validator.create<MyModel>(expect => { expect("id").toBeNumber({ min: 0 }).orFail("id must be a number greater than 0"); expect("name").toBeString({ minLength: 6, maxLength: 20 }).orFail("name must have more than 6 chars and less than 20"); expect("value").toBeDefined().orFail("value must be defined"); }); it("Should successfully validate a model", async () => { const result = await myModelValidator.validate({ id: 2, name: "Bernard", value: null }); assert.equal(result, SucceedValidationResult); }); it("Should successfully validate a model using a callback", async () => { const callback = Validator.createCallback<MyModel>(expect => { expect("id").toBeOk().orFail("id must be Ok!"); expect("id").toBeNumber({ min: 0 }).orFail("id must be a number greater than 0"); }); const result = await callback({ id: 2, name: "Bernard", value: null }); assert.equal(result, SucceedValidationResult); }); it("Should successfully validate a model using a self validation on conditional state", async () => { const callback = Validator.createCallback<MyModel>(expect => { expect().must(myModelValidator).when(t => t.value !== null); }); const result = await callback({ id: 0, name: "", value: null }); assert.equal(result, SucceedValidationResult); }); it("Should fail to validate id", async () => { const result = await myModelValidator.validate({ id: 0, name: "Bernard", value: null }); assert.deepEqual(result, { type: "failed", errors: { id: "id must be a number greater than 0" } }); }); it("Should fail to validate name length", async () => { const result = await myModelValidator.validate({ id: 22, name: "Berni", value: null }); assert.deepEqual(result, { type: "failed", errors: { name: "name must have more than 6 chars and less than 20" } }); }); it("Should fail to validate id and name length", async () => { const result = await myModelValidator.validate({ id: 0, name: "Berni", value: null }); assert.deepEqual(result, { type: "failed", errors: { id: "id must be a number greater than 0", name: "name must have more than 6 chars and less than 20" } }); }); it("Should fail validate a model using a self validation on conditional state", async () => { const callback = Validator.createCallback<MyModel>(expect => { expect().use(myModelValidator).when(t => t.value !== null); }); const result = await callback({ id: 0, name: "", value: 1 }); assert.deepEqual(result, { type: "failed", errors: { id: "id must be a number greater than 0", name: "name must have more than 6 chars and less than 20" } }); }); it("Should succeed to validate a model with conditional extension", async () => { const callback = Validator.createCallback<MyModel>(expect => { expect("id").toBeNumber().whenDefined().orFail("id must be a valid string"); }); const result = await callback({ id: <any>void 0, name: "", value: 1 }); assert.deepEqual(result, SucceedValidationResult); }); it("Should match with a custom regex", async () => { const callback = Validator.createCallback<MyModel>(expect => { expect("name").toMatch(/^[\w]+$/).orFail("Invalid!"); }); const result = await callback({ id: 0, name: "bob", value: 1 }); assert.deepEqual(result, SucceedValidationResult); }); it("Should throw the default error with a custom regex when no fail is set", async () => { const callback = Validator.createCallback<MyModel>(expect => { expect("name").toMatch(/^[\w]+$/); }); const result = await callback({ id: 0, name: "bob*", value: 1 }); assert.deepEqual(result, { type: "failed", errors: { name: `Invalid value for "name": "bob*"` } }); }); it("Should throw the default error with a custom regex when no fail is set", async () => { const callback = Validator.createCallback<MyModel>(expect => { expect("name").toMatch(/^[\w]+$/).orFail((_, p) => { throw new Error(`Bad ${p}!`) }); }); let result: ValidationResult | undefined; let error: any; try { result = await callback({ id: 0, name: "bob*", value: 1 }); } catch (err) { error = err } assert.isUndefined(result); assert.isDefined(error); assert.equal(error.message, "Bad name!"); }); it("Should validate inclusive min values", async () => { const callback = Validator.createCallback<MyModel>(expect => { expect("id").toBeNumber({ min: 0, includeMin: true }); }); const result = await callback({ id: 0, name: "bob", value: 1 }); assert.deepEqual(result, SucceedValidationResult); }); it("Should validate inclusive max values", async () => { const callback = Validator.createCallback<MyModel>(expect => { expect("id").toBeNumber({ max: 10, includeMax: true }); }); const result = await callback({ id: 10, name: "bob", value: 1 }); assert.deepEqual(result, SucceedValidationResult); }); });
e395d8997716f316e84bf87467fbb6b027bfe4df
TypeScript
hwahee/probability_one_nth
/src/ts/RandomGenerator.ts
3.453125
3
export class RandomGenerator { constructor(private min: number=0, private max: number=0) { if (max < min) { this.min ^= this.max ^= this.min ^= this.max } } set(min: number, max: number): void { this.min = min, this.max = max if (max < min) { this.min ^= this.max ^= this.min ^= this.max console.log(`Range reversed`) } console.log(`Generator set: [${this.min},${this.max})`) } get(): number { const diff = this.max - this.min let ret: number = Math.floor(Math.random() * diff) + this.min return ret } }
8e7af7b248354755a64c30c0d2e2f5a21969bd8d
TypeScript
dominickudiabor/react-native-ecommerce
/src/common/redux/reducers/feature.ts
2.703125
3
import { FetchActions, FetchSuccessLoadOne } from 'common/redux/actions/feature' import { FeatureState, LOAD_ONE_SUCCESS } from 'common/redux/types' export function feature(state: FeatureState = {}, action: FetchActions): FeatureState { switch (action.type) { case LOAD_ONE_SUCCESS: { if (!(action as FetchSuccessLoadOne).payload) return { ...state } const { id, data } = (action as FetchSuccessLoadOne).payload return { ...state, [id]: data as any, } } default: return state } }
b91b9e777e9e1bb601784824ce439ad3d48c6e84
TypeScript
JBoss925/MafiaBackend
/app/playerHandler.ts
2.671875
3
// This file contains the firebase implementations of the endpoints. import { Request, Response } from "express-serve-static-core"; import { firestore } from "firebase"; import * as commonOps from "./util/commonOps"; import { v4 as uuid } from 'uuid'; import { CreatePlayerRequest, GetPlayerRequest, DeletePlayerRequest } from "./requestTypes"; import { Player } from "./types"; import { isUndefined } from "util"; export async function createPlayer(db: firestore.Firestore, req: Request, res: Response) { let request = req.body as CreatePlayerRequest; let userObj: Player; if (isUndefined(request.uuid)) { userObj = { uuid: uuid(), name: request.name, role: "unset", isProtected: false, isTargeted: false, isSuspected: false, isAccused: false, numVotesAgainst: 0 }; } else { userObj = { uuid: request.uuid, name: request.name, role: "unset", isProtected: false, isTargeted: false, isSuspected: false, isAccused: false, numVotesAgainst: 0 }; } return db.collection('players').doc(userObj.uuid).set(userObj).then(() => { res.json(userObj); }); } export async function getPlayer(db: firestore.Firestore, req: Request, res: Response) { let request = req.body as GetPlayerRequest; return db.collection('players').doc(request.uuid).get().then((doc) => { if (!doc.exists) { res.json({ error: "no user by that name!" }); } else { res.json(doc.data()); } }); } export async function deletePlayer(db: firestore.Firestore, req: Request, res: Response) { let request = req.body as DeletePlayerRequest; return db.collection('players').doc(request.uuid).delete().then(() => { res.json({ deleted: true }); }) }
0cf4a32984dc7b05f7c10471d7f2914b4894b2b5
TypeScript
honkit/honkit
/packages/honkit/src/plugins/listFilters.ts
2.578125
3
import Immutable from "immutable"; /** List filters from a list of plugins @param {OrderedMap<String:Plugin>} @return {Map<String:Function>} */ function listFilters(plugins) { return plugins.reverse().reduce((result, plugin) => { return result.merge(plugin.getFilters()); }, Immutable.Map()); } export default listFilters;
00f3cd728ecb52086734cbbcd3aaf65244d223ac
TypeScript
abhiramps/BANKAPP-ANGULAR
/src/app/transaction-history/transaction-history.component.ts
2.515625
3
import { Component, OnInit } from '@angular/core'; import { BankServiceService } from "../services/bank-service.service"; @Component({ selector: 'app-transaction-history', templateUrl: './transaction-history.component.html', styleUrls: ['./transaction-history.component.css'] }) export class TransactionHistoryComponent implements OnInit { public transactions:{username:string,amount:number,type_of_transaction:string}[] = [ ]; constructor(private BankService: BankServiceService) { this.BankService.onHistory().subscribe((data:any)=>{ this.transactions=data.history // alert(data.message) }) } ngOnInit(): void { } // public transactions = [] // objectKeys=Object.keys(this.transactions); } // { username: "abhi", amount: 1000, type_of_transaction: "credit" }, // { username: "ram", amount: 500, type_of_transaction: "debit" }, // { username: "sasi", amount: 3000, type_of_transaction: "credit" }, // { username: "sugu", amount: 2000, type_of_transaction: "debit" },
1d392e3f38c88955abf87acbfff02f3433b12726
TypeScript
polly-zou/test
/src/store/common/reducers.ts
2.734375
3
import { ChatState, SEND_MESSAGE, DELETE_MESSAGE, ChatActionTypes } from './models' const initialState: ChatState = { messages: [ { user: "Alan", message: "test1", timestamp: 1 }, { user: "Alan2", message: "test2", timestamp: 2 }, { user: "Alan3", message: "test3", timestamp: 3 }, ] } export function chatReducer(state = initialState,action:ChatActionTypes): ChatState{ switch (action.type) { case SEND_MESSAGE: return { messages:[...state.messages,action.playload] } case DELETE_MESSAGE: return { messages: state.messages.filter( message => message.timestamp !== action.meta.timestamp ) } default: return state } }
d892aef96cf90530c17bc2a616f9a06f17a823e5
TypeScript
Arthur3DLHC/Mini3DEngine
/src/math/plane.ts
3.078125
3
import vec3 from "../../lib/tsm/vec3.js"; import { BoundingSphere } from "./boundingSphere.js"; import mat4 from "../../lib/tsm/mat4.js"; export class Plane { public constructor(a: number = 0, b: number = 0, c: number = 0, d: number = 0) { this.normal = new vec3([a, b, c]); this.constant = d; } public normal: vec3; public constant: number; private static _tmpMatrix: mat4 = new mat4(); public copy(): Plane { return new Plane(this.normal.x, this.normal.y, this.normal.z, this.constant); } public setComponents(x: number, y: number, z: number, w: number): Plane { this.normal.x = x; this.normal.y = y; this.normal.z = z; this.constant = w; return this; } public setFromPoints(point1: vec3, point2: vec3, point3: vec3): Plane { // from babylon.js, and do not sure whether is same with three.js yet var x1 = point2.x - point1.x; var y1 = point2.y - point1.y; var z1 = point2.z - point1.z; var x2 = point3.x - point1.x; var y2 = point3.y - point1.y; var z2 = point3.z - point1.z; var yz = (y1 * z2) - (z1 * y2); var xz = (z1 * x2) - (x1 * z2); var xy = (x1 * y2) - (y1 * x2); var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy))); var invPyth; if (pyth !== 0) { invPyth = 1.0 / pyth; } else { invPyth = 0.0; } this.normal.x = yz * invPyth; this.normal.y = xz * invPyth; this.normal.z = xy * invPyth; this.constant = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z)); return this; } public setFromNormalAndPoint(normal: vec3, point: vec3): Plane { this.normal = normal.copyTo(); this.normal.normalize(); this.constant = - vec3.dot( this.normal, point ); return this; } public normalize(): Plane { // from babylon.js var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z))); var magnitude = 0.0; if (norm !== 0) { magnitude = 1.0 / norm; } this.normal.x *= magnitude; this.normal.y *= magnitude; this.normal.z *= magnitude; this.constant *= magnitude; return this; } public negate(): Plane { this.normal.negate(); this.constant *= -1; return this; } public distanceToPoint(point: vec3): number { return vec3.dot(this.normal, point) + this.constant; } public distanceToSphere(sphere: BoundingSphere): number { return this.distanceToPoint(sphere.center) - sphere.radius; } public transform(transformation: mat4): Plane { // multiply inverse transform matrix // https://stackoverflow.com/questions/7685495/transforming-a-3d-plane-using-a-4x4-matrix // https://github.com/BabylonJS/Babylon.js/blob/master/src/Maths/math.plane.ts // inverse const inversedMatrix = Plane._tmpMatrix; transformation.copyTo(inversedMatrix); inversedMatrix.inverse(); const m = inversedMatrix.values; const x = this.normal.x; const y = this.normal.y; const z = this.normal.z; const d = this.constant; // transpose this.normal.x = x * m[0] + y * m[1] + z * m[2] + d * m[3]; this.normal.y = x * m[4] + y * m[5] + z * m[6] + d * m[7]; this.normal.z = x * m[8] + y * m[9] + z * m[10] + d * m[11]; this.constant = x * m[12] + y * m[13] + z * m[14] + d * m[15]; return this; } public static fromPoints(p1: vec3, p2: vec3, p3: vec3): Plane { const result = new Plane(0, 0, 0, 0); result.setFromPoints(p1, p2, p3); return result; } public static fromNormalAndPoint(normal: vec3, point: vec3): Plane { // normal.normalize(); // const d = - vec3.dot( normal, point ); // return new Plane(normal.x, normal.y, normal.z, d); return new Plane().setFromNormalAndPoint(normal, point); } }
c0077f6b9b5bc2226b0ec6f803b8440180862341
TypeScript
somesocks/vet
/src/isAllOf.ts
3.15625
3
import Assertion from './types/Assertion'; import Validator from './types/Validator'; import ExtendedValidator from './types/ExtendedValidator'; import ValidatorType from './types/ValidatorType'; import assert from './utils/assert'; import schema from './utils/schema'; function isFunction(val) { return typeof val === 'function'; } type BoxedValidatorTypes<T extends any[]> = { [P in keyof T] : { _box : ValidatorType<T[P]> } } [Exclude<keyof T, keyof any[]>]; type UnionToIntersection<U> = (U extends any ? (k : U) => void : never) extends ((k : infer I) => void) ? I : never; type UnboxIntersection<T> = T extends { _box : infer U } ? U : never; type IsAllOfType<T extends any[]> = UnboxIntersection<UnionToIntersection<BoxedValidatorTypes<T>>> type IsAllOfValidator<T extends any[]> = ExtendedValidator<IsAllOfType<T>>; /** * Constructs a function that checks equality against any number of arguments * @param {...*} eq - values to check equality against * @returns a function that takes in a parameter val, and returns true if val is equal to any of the options in ...eq * @memberof vet * @example * ```javascript * let isAllOf from 'vet/isAllOf'); * let isNumber from 'vet/numbers/isNumber'); * let isPositive from 'vet/numbers/isPositive'); * * let check = isAllOf(isNumber, isPositive); * * check(-1); // returns false * * check(1); // returns true * ``` */ function isAllOf<T extends any[]>(...args : T) : IsAllOfValidator<T> { const validators = arguments; const res : ExtendedValidator = function (val) { for (let i = 0; i < validators.length; i++) { const validator = validators[i]; const check = typeof validator === 'function' ? validator(val) : (val === validator); if (!check) { return false; } } return true; } as ExtendedValidator; res.assert = function _assert(val) { for (let i = 0; i < validators.length; i++) { const validator = validators[i]; if (typeof validator === 'function') { if (typeof validator.assert === 'function') { validator.assert(val); } else { assert(validator)(val); } } else { assert(val === validator); } } return; }; let s = 'isAllOf('; for (let i = 0; i < validators.length; i++) { s += schema(validators[i]) + ', '; } s += ')'; res.schema = s; return res; } export = isAllOf;
af888e94b723136744afbe4797e6ac863443ae99
TypeScript
Musasthl/Seb4Vision.SportView
/Seb4Vision.CSportView.Web/ClientApp/app/pipe/PipeLoopNumber.ts
2.53125
3
import { PipeTransform, Pipe } from "../../../node_modules/@angular/core"; @Pipe({name: "pipeLoopNumber"}) export class PipeLoopNumber implements PipeTransform{ transform(value: any, args: string[]) :any { let res = [] for(let i = 0; i < value; i++) { res.push(i); } return res; } }
3f9f41dff4d834f0a0b701af48102b390011a219
TypeScript
markosinho/matf-kurs
/web-shop-mare/src/services/UserService.ts
2.65625
3
import { IUserEntity, UserEntity } from '../entities/UserEntity'; import { UserRepo } from '../repositories/UserRepo'; export class UserService { private userRepo: UserRepo; constructor(userRepo: UserRepo) { this.userRepo = userRepo; } public async save(user: UserEntity) { return this.userRepo.save(user); } public async findByUserName(userName: string) { return this.userRepo.findByUserName(userName); } public async findByUserId(userId: string) { return this.userRepo.findById(userId); } // TODO: Fix argument types public async confirmRegistration(userName: any, registrationToken: any) { // Find by username const user = await this.userRepo.findByUserName(userName); if (user === undefined) { return undefined; } user.registrationConfirmed = user.registrationToken === registrationToken; return this.save(user); } public async findAll() { return this.userRepo.findAll(); } public async deleteByUserName(userName: string) { return this.userRepo.deleteByUserName(userName); } }
8303a044c26fb271f8aed88b47292e1a3ac94bfc
TypeScript
green-fox-academy/somakanyasi
/Week01/Day-04/define-basic-info.ts
2.9375
3
'use strict'; // Define several things as a variable, then print their values let myName: string = "Soma"; let myAge: number = 27; let myHeight: number = 1.88; let amMarried: boolean = false;
6a58d65467f3b5360292069bee8c2c9a3079b5ee
TypeScript
ngochuy2902/AnyPicsClient
/src/shared/utils/index.ts
2.625
3
import { isNil, omitBy } from 'lodash'; import queryString from 'query-string'; function handlePayload(payload: any) { const newPayload: any = {}; payload && Object.keys(payload).forEach((key) => { newPayload[key] = payload[key] === '' ? null : payload[key]; }); return omitBy(newPayload, isNil); } function camelToSnake(value: string) { return value.replace(/[\w]([A-Z])/g, (m) => `${m[0]}_${m[1]}`).toLowerCase(); } const stringifyParams = (data: any) => { const { params, option } = data; return queryString.stringify(handlePayload({ ...params }), { arrayFormat: 'brackets', encode: false, skipNull: true, skipEmptyString: true, ...option, }); }; function getCurrentDomain() { const parts = window.location.hostname.split('.'); parts.shift(); return parts.join('.'); } export { stringifyParams, camelToSnake, getCurrentDomain };
5ae4316f1d43e0e85d43370186d07f59003cf0d0
TypeScript
umeshrapolu29/hrms-admin
/src/app/employees/employee-filter.pipe.ts
2.75
3
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'filter' }) export class FilterPipe implements PipeTransform { transform(items: any[], searchText: string): any[] { if(!items) return []; if(!searchText) return items; return this.searchItems(items, searchText.toLowerCase()); } private searchItems(items :any[], searchText): any[] { let results = []; items.forEach(it => { if (it.title.toLowerCase().includes(searchText)) { results.push(it); } else { let searchResults = this.searchItems(it.items_containers, searchText); if (searchResults.length > 0) { results.push({ title: it.title, items_containers: searchResults }); } } }); return results; } }
c892b750d8ed85678f4a59956e9e532553d01d8e
TypeScript
acferM/api-covid
/src/modules/vacines/infra/typeorm/repositories/VacinesRepository.ts
2.890625
3
import { getRepository, Repository } from "typeorm" import Vacine from "../entities/Vacine" interface CreateVacineDTO { name: string manufacturer: string time_between_applications: string applications_amount: number } class VacinesRepository { private ormRepository: Repository<Vacine> constructor() { this.ormRepository = getRepository(Vacine) } async create(data: CreateVacineDTO): Promise<Vacine> { const vacine = this.ormRepository.create(data) await this.ormRepository.save(vacine) return vacine } async findById(id: string): Promise<Vacine | undefined> { return this.ormRepository.findOne(id) } async findByName(name: string): Promise<Vacine | undefined> { const vacines = await this.ormRepository.find() const vacine = vacines.find(vacine => vacine.name.toLowerCase() === name) return vacine } async listAll(): Promise<Vacine[]> { return this.ormRepository.find() } async save(vacine: Vacine) { return this.ormRepository.save(vacine) } async delete(vacine: Vacine): Promise<void> { await this.ormRepository.remove(vacine) } } export default VacinesRepository
78e4a9b2c8c429b5a81919056dadc8cc4e1c3d5b
TypeScript
andrenanninga/ludum-dare-45
/src/entities/Player.ts
2.734375
3
import * as THREE from "three"; import Matter from "matter-js"; import { Game } from "../Game"; import { createTile, updateTile } from "../utils/createTile"; class Player extends THREE.Group { game: Game; mesh: THREE.Mesh; frame: 0; state: "walking" | "idle"; direction: "left" | "right"; static FRAMERATE = 10; static animations = { idle: [52, 53, 53, 52, 52, 52, 52, 52, 54, 54, 52, 52], walk: [44, 45, 46, 47] }; constructor(game: Game) { super(); this.game = game; this.mesh = createTile(game.loader.assets.tileset, 44); this.mesh.position.y = Game.TILE / 2; this.mesh.rotation.y = Math.PI / 4; this.add(this.mesh); this.scale.set(0.6666, 0.6666, 0.6666); this.frame = 0; this.state = "idle"; this.direction = "right"; this.position.x = 0.5; this.position.z = 0.5; this.game.physics.addBody( this, Matter.Bodies.circle(0, 0, 0.3 * Game.TILE, { frictionAir: 0.4 }) ); } update() { const body: Matter.Body = this.userData.body; const force = new THREE.Vector2(); this.frame += 1; this.state = "idle"; if (this.game.input.up.down) { this.direction = "left"; this.state = "walking"; force.x -= 1; force.y -= 1; } if (this.game.input.down.down) { this.direction = "right"; this.state = "walking"; force.x += 1; force.y += 1; } if (this.game.input.left.down) { this.direction = "left"; this.state = "walking"; force.x -= 1; force.y += 1; } if (this.game.input.right.down) { this.direction = "right"; this.state = "walking"; force.x += 1; force.y -= 1; } force.clampLength(-1, 1); force.multiplyScalar((body.mass / 14000) * Game.TILE); if (this.state === "walking") { updateTile( this.mesh, Player.animations.walk[ Math.floor(this.frame / Player.FRAMERATE) % Player.animations.walk.length ] ); } else if (this.state === "idle") { updateTile( this.mesh, Player.animations.idle[ Math.floor(this.frame / Player.FRAMERATE) % Player.animations.idle.length ] ); } this.mesh.lookAt(this.game.camera.position); this.mesh.scale.setX(this.direction === "left" ? -1 : 1); Matter.Body.applyForce(body, body.position, force); } } export { Player };
65ee9f154779edeb333328b0cffb36bff0482846
TypeScript
end5/CoC-UEE-Web
/classes/coc/view/charview/KeyColor.ts
2.84375
3
/** * Coded by aimozg on 28.07.2017. */ export class KeyColor { private _src:uint; private _base: string; private tfs:/*String*/Array; public KeyColor(src:uint, base: string, tf: string) { this._src = src; this._base = base; if (tf) this.tfs = tf.split(";"); else this.tfs = []; } public transform(baseValue:uint):uint { var hsl: any = Color.toHsl(baseValue); for each (var tf: string in tfs) { var fn: any[] = tf.match(/^(\w+)\(([\d.,-]+)\)/); var fname: string = fn ? fn[1] : undefined; var values:/*Number*/Array = fn ? fn[2].split(",") : []; switch (fname) { case "shift": case "h": hsl.h = hsl.h + values[0]; break; case "shiftTo": case "hto": if (hsl.h > values[0]) { hsl.h -= values[1]; } else { hsl.h += values[2]; } break; case "saturate": case "s": hsl.s += values[0]; break; case "desaturate": hsl.s -= values[0]; break; case "darken": hsl.l -= values[0]; break; case "lighten": case "l": hsl.l += values[0]; break; default: trace("Error: invalid color transform '" + tf + "'"); break; } hsl.h = hsl.h % 360; while (hsl.h < 0) hsl.h += 360; hsl.s = Utils.boundFloat(0, hsl.s, 100); hsl.l = Utils.boundFloat(0, hsl.l, 100); } return Color.fromHsl(hsl); } public get src():uint { return _src; } public get base(): string { return _base; } }
49c3e8fa6d0e4714884c4a323f50e2c960a85784
TypeScript
rabee198/ctoken-swap
/helpers/flatten.ts
2.515625
3
// import { Contract } from 'ethers/lib/ethers'; import { writeFileSync } from "fs"; // import { HardhatRuntimeEnvironment } from 'hardhat/types'; const hre = require('hardhat') // require('hardhat-log-remover'); const TASK_FLATTEN_GET_FLATTENED_SOURCE = 'flatten:get-flattened-sources'; const TASK_COMPILE_SOLIDITY_GET_SOURCE_PATHS = 'compile:solidity:get-source-paths'; const SOLIDITY_PRAGMA = 'pragma solidity'; const LICENSE_IDENTIFIER = 'License-Identifier'; const EXPERIMENTAL_ABIENCODER = 'pragma experimental ABIEncoderV2;'; // const CONSOLE_LOG = 'console.log' // const CONSOLE_IMPORT = 'import "hardhat/console.sol";' // const encodeDeployParams = (instance: Contract, args: (string | string[])[]) => { // return instance.interface.encodeDeploy(args).replace('0x', ''); // }; // Remove lines at "text" that includes "matcher" string, but keeping first "keep" lines const removeLines = (text: string, matcher: string, keep = 0): string => { let counter = keep; return text .split('\n') .filter((line) => { const match = !line.includes(matcher); if (match === false && counter > 0) { counter--; return true; } return match; }) .join('\n'); }; const flattenExcludePath = 'flatten' // Try to find the path of a Contract by name of the file without ".sol" const findPath = async (id: string): Promise<string> => { const paths = await hre.run(TASK_COMPILE_SOLIDITY_GET_SOURCE_PATHS); // console.log('paths:', paths) const path = paths.find((x: string) => { if (x.indexOf(flattenExcludePath) !== -1) { return false } let t = x.split('/'); t = t[t.length - 1].split('\\') // console.log('t:', t) return t[t.length - 1].split('.')[0] == id; }); if (!path) { throw Error('Missing path for contract name: ${id}'); } // console.log('found id: %s %s', id, path) return path; }; // Hardhat Flattener, similar to truffle flattener const hardhatFlattener = async (filePath: string): Promise<string> => { // await hre.run('remove-logs') return await hre.run(TASK_FLATTEN_GET_FLATTENED_SOURCE, { files: [filePath] }); } const removeComments = (source: any) => { return source.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, '') } const removeBlankLines = (source: any) => { return source.replace(/^\s*[\r\n]/gm, '') } // Verify a smart contract at Polygon Matic network via a GET request to the block explorer export const flattenContract = async ( id: string, to: string // instance: Contract, // args: (string | string[])[] ) => { const filePath = await findPath(id); // const encodedConstructorParams = encodeDeployParams(instance, args); let flattenSourceCode = await hardhatFlattener(filePath); // console.log(flattenSourceCode) flattenSourceCode = removeComments(flattenSourceCode) // flattenSourceCode = removeBlankLines(flattenSourceCode) // Remove pragmas and license identifier after first match, required by block explorers like explorer-mainnet.maticgivil.com or Etherscan const cleanedSourceCode = '// SPDX-License-Identifier: GPL-3.0-or-later\n\n' + removeLines( removeLines(removeLines(flattenSourceCode, LICENSE_IDENTIFIER, 1), SOLIDITY_PRAGMA, 1), EXPERIMENTAL_ABIENCODER, 1 ); writeFileSync(to, cleanedSourceCode) console.info('flatten %s to %s success', id, to) return cleanedSourceCode // console.log(cleanedSourceCode) };
dd6cc363981b8d81f36cbbe2aab9606297b6146f
TypeScript
linuxcarl/tsc-solid
/src/srp/class/useCase.ts
2.609375
3
export class UseCase { #repository: any; #notifier: any; public constructor(repo: any, notifier: any) { this.#repository = repo; this.#notifier = notifier; } public doSomethingWithTaxes(): string { return 'Do somethings realted with taxes'; } public saveChanges(): string { try { const updated = this.#repository.update(); return updated; } catch (error) { throw new Error(error); } } public notify(): boolean { try { const send = this.#notifier.notify('Hi friend! it send mai...'); return send; } catch (error) { throw new Error(error); } } }
496de44e0a687bb3eb529bb00eef020e304d0b8b
TypeScript
desssad/tr_u_ng_courses
/src/app/lesson43/courses.service.ts
2.671875
3
import {Injectable} from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {Observable} from 'rxjs'; import {map} from 'rxjs/operators'; export interface Course { id: string; title: string; price: number; description: string; lecturer: string; } const url = 'http://localhost:3000/courses'; @Injectable({ providedIn: 'root' }) export class CoursesService { constructor(private http: HttpClient) {} addCourse(course: Course) { this.http.post<Course>(url, course).subscribe(); } updateCourse(course: Course) { return this.http.put<Course>(`${url}/${course.id}` , course); } existCourse(id: string): Observable<boolean> { return this.getCourse(id).pipe(map(c => c ? true : false)); } getCourse(id: string): Observable<Course> { return this.http.get<Course>(`${url}/${id}`); } getCourses(): Observable<Course[]> { return this.http.get<Course[]>(url); } removeCourse(id: string) { return this.http.delete(`${url}/${id}`); } }
e2df70da09c398be27c02c9bb26d83e781c82b51
TypeScript
Harley-Davidson-Inc/HDI-Chatbot-Cognigy-Extension
/extensions/google-sheets/src/nodes/getSpreadsheet.ts
2.515625
3
import { createNodeDescriptor, INodeFunctionBaseParams } from "@cognigy/extension-tools"; import axios from 'axios'; export interface IGetSpreadsheetParams extends INodeFunctionBaseParams { config: { connection: { key: string; }; spreadsheetId: string; sheetName: string; filter: string; storeLocation: string; contextKey: string; inputKey: string; }; } export const getSpreadsheetNode = createNodeDescriptor({ type: "getSpreadsheet", defaultLabel: "Get Spreadsheet", fields: [ { key: "connection", label: "API Key", type: "connection", params: { connectionType: "google-cloud-connection", required: true } }, { key: "spreadsheetId", label: "ID", description: "The Spreadsheet ID. One can find the ID in the URL behind spreadsheets", type: "cognigyText", params: { required: true, }, }, { key: "sheetName", label: "Sheet Name", description: "The name of he sheet that includes the table data", type: "cognigyText", params: { required: true, }, }, { key: "filter", label: "Filter", description: "A data filter such as A1 or F30", type: "cognigyText", defaultValue: "A2:G30" }, { key: "storeLocation", type: "select", label: "Where to store the result", defaultValue: "input", params: { options: [ { label: "Input", value: "input" }, { label: "Context", value: "context" } ], required: true }, }, { key: "inputKey", type: "cognigyText", label: "Input Key to store Result", defaultValue: "spreadsheet", condition: { key: "storeLocation", value: "input", } }, { key: "contextKey", type: "cognigyText", label: "Context Key to store Result", defaultValue: "spreadsheet", condition: { key: "storeLocation", value: "context", } }, ], sections: [ { key: "storage", label: "Storage Option", defaultCollapsed: true, fields: [ "storeLocation", "inputKey", "contextKey", ] } ], form: [ { type: "field", key: "connection" }, { type: "field", key: "spreadsheetId" }, { type: "field", key: "sheetName" }, { type: "field", key: "filter" }, { type: "section", key: "storage" }, ], appearance: { color: "#0F9D57" }, function: async ({ cognigy, config }: IGetSpreadsheetParams) => { const { api } = cognigy; const { spreadsheetId, sheetName, filter, connection, storeLocation, contextKey, inputKey } = config; const { key } = connection; try { const response = await axios({ method: 'get', url: `https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}/values/${sheetName}!${filter}?key=${key}`, headers: { 'Content-Type': 'application/json' } }); if (storeLocation === "context") { api.addToContext(contextKey, response.data, "simple"); } else { // @ts-ignore api.addToInput(inputKey, response.data); } } catch (error) { if (storeLocation === "context") { api.addToContext(contextKey, error.message, "simple"); } else { // @ts-ignore api.addToInput(inputKey, error.message); } } } });
9f787994e2133b513f03836da84ca0a5efe1dfcb
TypeScript
AidaHerreravilar/ejercicionumerodemes
/src/index.ts
2.671875
3
let mes:number=document.getElementById("numerodemes"); let btn=document.getElementById("btn"); btn?.addEventListener("click", ()=>{ let mes2=Number(mes.value); let diasve:= 2; let diast:= 4,6,9,11; let diastr:= 1,3,5,7,8,10,12; switch (true) { case (mes2===diasve): console.log("tiene 28 dias"); break; case (mes2===diast): console.log("tiene 30 dias"); break; case (mes2===diastr): console.log("tiene 31 dias"); break; default: break; } } //ejercicio dos
192b0a9b144b0233b98750aae8d2e956ba669166
TypeScript
gavar/mvcs
/packages/logger/src/core/logger-factory.ts
3.5625
4
import { Logger } from "./logger"; /** * Manufactures logger instances. */ export interface LoggerFactory { /** * Get an appropriate {@link Logger} instance as specified by the {@param name} parameter. * @param name - the name of the Logger to return. * @returns a logger instance. */ getLogger(name: string): Logger; } export namespace LoggerFactory { /** * Logger factory providing loggers. * @default ConsoleLoggerFactory */ export let factory: LoggerFactory; /** * Return a logger named corresponding to the type passed as parameter, * using the statically bound {@link LoggerFactory} instance. * @param type - the returned logger will be named after class or function. * @returns a logger instance. */ export function getLogger(type: Function): Logger; /** * Return a logger named corresponding to the type of given instance * using the statically bound {@link LoggerFactory} instance. * @param object - the returned logger will be named after instance class. * @returns a logger instance. */ export function getLogger(object: { constructor: Function }): Logger; /** * Get a logger named according to the name parameter, * using the statically bound {@link LoggerFactory} instance. * @param name - the name of the logger. * @returns a logger instance. */ export function getLogger(name: string): Logger; /** @internal */ export function getLogger(type: any): Logger { const {factory} = LoggerFactory; if (arguments.length < 1) return factory.getLogger(""); if (typeof type === "string") return factory.getLogger(type); if (typeof type === "function") return factory.getLogger(type.name); if (type && typeof type.constructor === "function") return factory.getLogger(type.constructor.name); return factory.getLogger(String(type)); } }
c81a4b16d01f7cbb3bc5655ec9ffc00ede61f0af
TypeScript
kristingorge/backgroundfetch_playground
/src/background_fetch.ts
2.515625
3
export interface BackgroundFetchManager { fetch(id: string, toFetch: RequestInfo | RequestInfo[], options: BackgroundFetchOptions): Promise<BackgroundFetchRegistration>; get(id: string): Promise<BackgroundFetchRegistration|null>; getIds(): Promise<string[]>; } export interface ImageResource { src: string; sizes?: string; type?: string; } export interface BackgroundFetchUIOptions { icons?: ImageResource[]; title?: string; } export interface BackgroundFetchOptions extends BackgroundFetchUIOptions { downloadTotal?: number; } export enum BackgroundFetchFailureReason { // The background fetch has not completed yet, or was successful. "", // The operation was aborted by the user, or abort() was called. "aborted", // A response had a not-ok-status. "bad-status", // A fetch failed for other reasons, e.g. CORS, MIX, an invalid partial response, // or a general network failure for a fetch that cannot be retried. "fetch-error", // Storage quota was reached during the operation. "quota-exceeded", // The provided downloadTotal was exceeded. "download-total-exceeded" }; export enum BackgroundFetchResult { InProgress = "", Success = "success", Failure = "failure" }; export interface BackgroundFetchRecord { request: Request; responseReady: Promise<Response>; }; // from https://wicg.github.io/background-fetch/#background-fetch-registration export interface BackgroundFetchRegistration extends EventTarget { id: string; uploadTotal: number; uploaded: number; downloadTotal: number; downloaded: number; result: BackgroundFetchResult; failureReason: BackgroundFetchFailureReason; recordsAvailable: boolean; abort(): Promise<boolean>; match(request: RequestInfo, options?: CacheQueryOptions): Promise<BackgroundFetchRecord>; matchAll(request?: RequestInfo, options?: CacheQueryOptions): Promise<Array<BackgroundFetchRecord>>; }
24c24e04f4c81f6596af60e332e01bf8079405cf
TypeScript
nkgrnkgr/styled-toolkit-todo
/simple-todo-app/src/Todo/modules/inputBox/slice.ts
2.671875
3
import { createSlice, PayloadAction } from "@reduxjs/toolkit"; export interface InputBoxState { text: string; } const initialState: InputBoxState = { text: "", }; export const { actions, reducer, name } = createSlice({ name: "inputBox", initialState, reducers: { changeText: (state, action: PayloadAction<string>) => { state.text = action.payload; }, clearText: (state) => { state.text = ""; }, }, });
36328f083825b9f4a02bda8aa363afb29799e3df
TypeScript
0zcl/utils-library
/types/browser.ts
2.609375
3
export interface BrowserInfo { /** 浏览器类型 */ type: 'ios' | 'android' | 'windowsPhone' | 'MacOSX' | 'windows' | 'linux' | undefined isWeiXin: boolean }
a7a72d6638a27a30fe0647a75261fe17f8c69f13
TypeScript
Kaciaryna/google-map-area-editor
/src/models/UnboundState.ts
2.546875
3
import {PolygonInstanceMap, PolygonMap} from "@/models/Polygon"; import {Region} from "@/models/Region"; export interface UnboundState { map: google.maps.Map | null; polygonData: PolygonMap; polygonInstances: PolygonInstanceMap; regions: Region[]; } const unboundState: UnboundState = { map: null, polygonData: {}, polygonInstances: {}, regions: [], } export default unboundState; export function getMapInstance(): google.maps.Map { if (unboundState.map) { return unboundState.map; } throw new Error("Map instance is not defined"); }
be6b7fc304894915f7f496c81364c9112916bce1
TypeScript
Braden1996/solana-nft-sentiment-finder
/src/twitter/TwitterApi.ts
2.53125
3
import axios, { AxiosInstance } from 'axios'; import { chunk } from 'lodash'; import { TwitterResponse } from './twitterTypes'; export class TwitterApi { private readonly api: AxiosInstance; constructor(bearerToken: string) { this.api = axios.create({ baseURL: 'https://api.twitter.com/2', timeout: 1000, headers: { 'User-Agent': 'v2UserLookupJS', authorization: `Bearer ${bearerToken}`, }, }); } async getFollowers(twitterIds: string[]) { let output: TwitterResponse[] = []; for (const twitterIdChunk of chunk(twitterIds, 100)) { try { const res = await this.api.get('/users/by', { params: { usernames: twitterIdChunk.join(','), 'user.fields': 'public_metrics', }, }); output = output.concat(res.data.data); } catch { throw new Error('Unsuccessful request'); } } return output; } }
5414d307e7bcbe52696df87951977b5962fd58c4
TypeScript
smitray/test-fastlane
/src/database/models/user.ts
2.578125
3
import Realm from 'realm' export type IUser = { _id: string, email: string, type: string, avatar: string, name: string, isTermAccepted: boolean, isVerified: boolean, stripeCustomerId: string, profile: { bio: string, callDuration: number, callPrice: number, charityDonationPercentage: number, charityName: string, league: string, payoutAccountNumber: string, payoutRoutingNumber: string, socialHandle: string, zipCode: string }, } export class Profile extends Realm.Object { static schema: Realm.ObjectSchema = { name: 'User_profile', embedded: true, properties: { bio: 'string?', callDuration: 'int?', callPrice: 'int?', charityDonationPercentage: 'int?', charityName: 'string?', league: 'string?', payoutAccountNumber: 'string?', payoutRoutingNumber: 'string?', socialHandle: 'string?', zipCode: 'string?', leagueId: 'objectId?', sportId: 'objectId?', } } } class User extends Realm.Object { _id: string status: string name: string static schema: Realm.ObjectSchema = { name: 'User', primaryKey: '_id', properties: { _id: 'string?', email: 'string?', type: 'string?', avatar: 'string?', name: 'string?', isTermAccepted: 'bool?', isVerified: 'bool?', stripeCustomerId: 'string?', profile: 'User_profile', // Embed an of objects }, } get fullname() { return this.name } } export default User
1ce2f1e5b05a43e4cc2f3ec605c6308da8a06303
TypeScript
semencov/typograf
/src/rules/ru/nbsp/abbr.ts
2.921875
3
import type { TypografRule } from '../../../main'; import { privateLabel } from '../../../consts'; function abbr($0: string, $1: string, $2: string, $3: string) { // дд.мм.гггг if ($2 === 'дд' && $3 === 'мм') { return $0; } // Являются ли сокращения ссылкой if (['рф', 'ру', 'рус', 'орг', 'укр', 'бг', 'срб'].indexOf($3) > -1) { return $0; } return $1 + $2 + '.' + '\u00A0' + $3 + '.'; } export const abbrRule: TypografRule = { name: 'ru/nbsp/abbr', handler(text) { const re = new RegExp(`(^|\\s|${privateLabel})([а-яё]{1,3})\\. ?([а-яё]{1,3})\\.`, 'g'); return text .replace(re, abbr) // Для тройных сокращений - а.е.м. .replace(re, abbr); }, };
3fba71114d6275d7f5cd123f582caa38867edca2
TypeScript
faiscacriativa/ngx-sparkler
/src/lib/core/concerns/data-provider.ts
2.578125
3
import { Observable } from "rxjs"; import { map, tap } from "rxjs/operators"; // import { DialogService, LoadingService } from "@sparkler/ngx-ui"; import { ApiResponse } from "../interfaces/api-response"; import { HttpService } from "../services/http.service"; export abstract class DataProvider<T> { protected endpoint: string; protected idField = "id"; constructor( // private dialog: DialogService, private http: HttpService, // private loading: LoadingService ) { } // public delete(data: T): Promise<Boolean> { // return new Promise((resolve, reject) => { // const confirmText = this.getDeleteConfirmText(data); // this.dialog.confirm(confirmText) // .then((reason) => { // if (reason.dismiss) { // return reject(true); // } // const id = data[this.idField]; // this.loading.show(); // this.http.delete(`${this.endpoint}/${id}`) // .pipe(tap( // () => this.loading.hide(), // () => this.loading.hide() // )) // .subscribe( // () => resolve(false), // () => reject(false) // ); // }); // }); // } public delete(data: T): Observable<boolean> { const id = data[this.idField]; return this.http.delete(`${this.endpoint}/${id}`) .pipe(map((response: ApiResponse) => response.data)); } public get(id: any): Observable<T> { return this.http.get(`${this.endpoint}/${id}`) .pipe(map((response: ApiResponse) => response.data)); } public list(): Observable<T[]> { return this.http.get(this.endpoint) .pipe(map((response: ApiResponse) => response.data)); } public store(data: T): Observable<T> { return this.http.post(this.endpoint, data) .pipe(map((response: ApiResponse) => response.data)); } public update(id: any, data: T): Observable<T> { return this.http.put(`${this.endpoint}/${id}`, data) .pipe(map((response: ApiResponse) => response.data)); } public patch(id: any, data: T): Observable<T> { return this.http.patch(`${this.endpoint}/${id}`, data) .pipe(map((response: ApiResponse) => response.data)); } // protected abstract getDeleteConfirmText(data: T): string; }
5861152d8cbce4413ecda4335a39b990880ef3e7
TypeScript
ringteki/ringteki
/server/game/GameActions/TriggerAbilityAction.ts
2.703125
3
import TriggeredAbilityContext = require('../TriggeredAbilityContext'); import TriggeredAbility = require('../triggeredability'); import AbilityResolver = require('../gamesteps/abilityresolver'); import CardAbility = require('../CardAbility'); import Event = require('../Events/Event'); import DrawCard = require('../drawcard'); import Player = require('../player'); import { CardGameAction, CardActionProperties } from './CardGameAction'; export interface TriggerAbilityProperties extends CardActionProperties { ability: CardAbility; subResolution?: boolean; ignoredRequirements?: string[]; player?: Player; event?: Event; } export class TriggerAbilityAction extends CardGameAction { name = 'triggerAbility'; defaultProperties: TriggerAbilityProperties = { ability: null, ignoredRequirements: [], subResolution: false }; constructor(properties: ((context: TriggeredAbilityContext) => TriggerAbilityProperties) | TriggerAbilityProperties) { super(properties); } getEffectMessage(context: TriggeredAbilityContext): [string, any[]] { let properties = this.getProperties(context) as TriggerAbilityProperties; return ['resolve {0}\'s {1} ability', [properties.target, properties.ability.title]]; } canAffect(card: DrawCard, context: TriggeredAbilityContext, additionalProperties = {}): boolean { let properties = this.getProperties(context, additionalProperties) as TriggerAbilityProperties; let ability = properties.ability as TriggeredAbility; let player = properties.player || context.player; let newContextEvent = properties.event; if(!super.canAffect(card, context) || !ability || !properties.subResolution && player.isAbilityAtMax(ability.maxIdentifier)) { return false; } let newContext = ability.createContext(player, newContextEvent); let ignoredRequirements = properties.ignoredRequirements.concat('player', 'location', 'limit'); return !ability.meetsRequirements(newContext, ignoredRequirements); } eventHandler(event, additionalProperties): void { let properties = this.getProperties(event.context, additionalProperties) as TriggerAbilityProperties; let player = properties.player || event.context.player; let newContextEvent = properties.event; let newContext = (properties.ability as TriggeredAbility).createContext(player, newContextEvent); newContext.subResolution = !!properties.subResolution; event.context.game.queueStep(new AbilityResolver(event.context.game, newContext)); } hasTargetsChosenByInitiatingPlayer(context) { let properties = this.getProperties(context) as TriggerAbilityProperties; return properties.ability && properties.ability.hasTargetsChosenByInitiatingPlayer && properties.ability.hasTargetsChosenByInitiatingPlayer(context); } }
86b892151354794a69bca684383d91857cb22baa
TypeScript
degiorgioo/PowerCoders-TypeScript-WorkShop
/TypeScript/printSum.ts
4.25
4
/** * TypeScript checks at compiletime the types of the given value. This means that when the compiler * checks the code, an error occurs when the type of the value is not correct. * * @param summand1 - Number one. * @param summand2 - Number two. */ function printSumTypeScript(summand1: number, summand2: number) : void { let res: number = summand1 + summand2; console.log(res); } /** * * 1) Valid call. * 2) Invalid call. Error: [ts] Argument of type '"1"' is not assignable to parameter of type 'number'. * 3) Invalid call. Error: [ts] Argument of type '"2"' is not assignable to parameter of type 'number'. * 4) Invalid call. Error: [ts] Argument of type '"1"' is not assignable to parameter of type 'number'. * Error: [ts] Argument of type '"2"' is not assignable to parameter of type 'number'. */ printSumTypeScript(1 ,2); printSumTypeScript("1" ,2); printSumTypeScript(1 ,"2"); printSumTypeScript("1" ,"2");
688c399a018738e79077a6245d4948f88b8cc666
TypeScript
maciejtutak/tslox
/src/Scanner.ts
3.21875
3
import { Literal, Token } from "./Token"; import { Result } from "./Result"; import TokenType from "./TokenType"; // export class ScannerError extends Error { // line: number; // message: string; // constructor(line: number, message: string) { // super('ScannerError'); // this.line = line; // this.message = message; // } // } export class ScannerError extends Error { line: number; constructor(line: number, ...params: any[]) { super(...params); if (Error.captureStackTrace) { Error.captureStackTrace(this, ScannerError) } this.name = 'ScannerError' this.line = line; } } export class Scanner { private readonly source: string; private tokens: Token[] = []; private errors: ScannerError[] = []; private start: number = 0; private current: number = 0; private line: number = 1; private readonly keywords: Record<string, TokenType> = { and: TokenType.AND, class: TokenType.CLASS, else: TokenType.ELSE, false: TokenType.FALSE, for: TokenType.FOR, fun: TokenType.FUN, if: TokenType.IF, nil: TokenType.NIL, or: TokenType.OR, print: TokenType.PRINT, return: TokenType.RETURN, super: TokenType.SUPER, this: TokenType.THIS, true: TokenType.TRUE, var: TokenType.VAR, while: TokenType.WHILE }; constructor(source: string) { this.source = source; } static scan(source: string): Result<Token[], ScannerError[]> { const scanner: Scanner = new Scanner(source); return scanner.scanTokens(); } private scanTokens(): Result<Token[], ScannerError[]> { while (!this.isAtEnd()) { this.start = this.current; this.scanToken(); } this.tokens.push(new Token(TokenType.EOF, "", this.line, null)) this.errors.forEach(e => console.log(e instanceof ScannerError)) if (this.errors.length === 0) { return Result.Ok(this.tokens); } return Result.Fail(this.errors); } private isAtEnd(): boolean { return this.current >= this.source.length; } private scanToken(): void { const c: string = this.advance(); switch (c) { case '(': this.addToken(TokenType.LEFT_PAREN); break; case ')': this.addToken(TokenType.RIGHT_PAREN); break; case '{': this.addToken(TokenType.LEFT_BRACE); break; case '}': this.addToken(TokenType.RIGHT_BRACE); break; case ',': this.addToken(TokenType.COMMA); break; case '.': this.addToken(TokenType.DOT); break; case '-': this.addToken(TokenType.MINUS); break; case '+': this.addToken(TokenType.PLUS); break; case ';': this.addToken(TokenType.SEMICOLON); break; case '*': this.addToken(TokenType.STAR); break; case '!': this.addToken(this.match('=') ? TokenType.BANG_EQUAL : TokenType.BANG); break; case '=': this.addToken(this.match('=') ? TokenType.EQUAL_EQUAL : TokenType.EQUAL); break; case '<': this.addToken(this.match('=') ? TokenType.LESS_EQUAL : TokenType.LESS); break; case '>': this.addToken(this.match('=') ? TokenType.GREATER_EQUAL : TokenType.GREATER); break; case '/': if (this.match('/')) { // A comment that goes until the end of the line while (this.peek() != '\n' && !this.isAtEnd()) { this.advance() } } else if (this.match('*')) { // a multi line comment // console.log('currently watching', this.peek(), this.peekNext()); while ((this.peek() != '*' && this.peekNext() != '/') || (this.peek() != '*' && this.peekNext() === '/') || (this.peek() === '*' && this.peekNext() != '/')) { // console.log('in loop', this.peek(), this.peekNext()); if (this.isAtEnd()) { this.errors.push(new ScannerError(this.line, 'Multi-line comment termination "*/" expected.')); break; } this.advance(); } // consume */ if (!this.isAtEnd()) { this.advance(); this.advance(); } } else { this.addToken(TokenType.SLASH) } break; // Ignore whitespace case ' ': case '\r': case '\t': break; case '\n': this.line++; break; case '"': this.scanString(); break; default: if (this.isDigit(c)) { this.scanNumber(); } else if (this.isAlpha(c)) { this.identifier(); } // else { this.errors.push(new ScannerError(this.line, 'Unexpected character.')); } else { this.errors.push(new ScannerError(this.line, 'Unexpected character.')); } break; } } private advance(): string { this.current++; return this.source.charAt(this.current - 1); } private addToken(type: TokenType, literal: Literal = null) { const text: string = this.source.substring(this.start, this.current); this.tokens.push(new Token(type, text, this.line, literal)); } private match(expected: string): boolean { if (this.isAtEnd()) { return false; } if (this.source.charAt(this.current) != expected) { return false; } this.current++; return true; } private peek(): string | undefined { if (this.isAtEnd()) { return undefined; } return this.source.charAt(this.current); } private scanString(): void { while (this.peek() != '"' && !this.isAtEnd()) { if (this.peek() === '\n') { this.line++; } this.advance(); } // Unterminated string if (this.isAtEnd()) { // this.errors.push(new ScannerError(this.line, 'Unexpected string.')); this.errors.push(new ScannerError(this.line, 'Unexpected string.')); return; } // Closing " this.advance(); const value: string = this.source.substring(this.start + 1, this.current - 1); this.addToken(TokenType.STRING, value); } private isDigit(c?: string): boolean { if (c === undefined) { return false; } return (c >= '0' && c <= '9'); } private scanNumber(): void { while (this.isDigit(this.peek())) { this.advance() } if (this.peek() === "." && this.isDigit(this.peekNext())) { this.advance(); while (this.isDigit(this.peek())) { this.advance() } } this.addToken(TokenType.NUMBER, Number.parseFloat(this.source.substring(this.start, this.current))) } private peekNext(): string | undefined { if (this.current + 1 >= this.source.length) { return undefined; } return this.source.charAt(this.current + 1) } private identifier(): void { while (this.isAlphaNumeric(this.peek())) { this.advance() } const identifier: string = this.source.substring(this.start, this.current); let type: TokenType = this.keywords[identifier]; if (type === undefined) { type = TokenType.IDENTIFIER } this.addToken(type); } private isAlpha(c: string): boolean { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c === '_'; } private isAlphaNumeric(c?: string): boolean { if (c === undefined) { return false; } return this.isAlpha(c) || this.isDigit(c); } }
f3dc91d471a2ed023649fbf6c2ca12453ef257e1
TypeScript
technologiestiftung/culturematch-client
/src/app/user/shared/user.model.ts
3.015625
3
export interface UserSource { id: string, displayName: string, email: string, } export class UserModel { public id: string; public displayName: string; public email: string; constructor(source: UserSource) { this.id = source.id; this.displayName = source.displayName; this.email = source.email; } }
12253b75629d0ce96c76514107c4309b6c051e57
TypeScript
t-codill/automl-excel
/src/automl/common/utils/loggerGetKey.ts
2.671875
3
import { Region } from "./getRegion"; enum Geographies { Asia = "asia", Australia = "australia", Euap = "euap", Europe = "europe", UnitedStates = "unitedstates", Development = "development" } const instrumentationKeys: { [key: string]: string | undefined; } = { [Geographies.Asia]: "6d8dfd01-1ce0-486c-905f-7ffe96403fba", [Geographies.Australia]: "6d8dfd01-1ce0-486c-905f-7ffe96403fba", [Geographies.Euap]: "780d5f6b-af1b-47b2-9130-dcbfbce9c90f", [Geographies.Europe]: "d8a12332-ff3d-48c8-a332-eba3203f9d21", [Geographies.UnitedStates]: "37bee233-bf42-415c-aaf3-2e3385a31175", [Geographies.Development]: "09ab9f4a-c812-418a-8ef7-36c860aa003e", }; const regionToGeographyMapping: { [key in Region]: string | undefined; } = { australiaeast: Geographies.Australia, australiasoutheast: Geographies.Australia, centralus: Geographies.UnitedStates, centraluseuap: Geographies.Euap, eastasia: Geographies.Asia, eastus: Geographies.UnitedStates, eastus2: Geographies.UnitedStates, eastus2euap: Geographies.Euap, northcentralus: Geographies.UnitedStates, northeurope: Geographies.Europe, southcentralus: Geographies.UnitedStates, southeastasia: Geographies.Asia, westcentralus: Geographies.UnitedStates, westeurope: Geographies.Europe, westus: Geographies.UnitedStates, westus2: Geographies.UnitedStates, development: Geographies.Development, test: Geographies.Development }; export function loggerGetKey(region: Region): string | undefined { const geography = regionToGeographyMapping[region]; const key = geography ? instrumentationKeys[geography] : undefined; return key; }
69e7928774f4d83002fed9957b6a3f615994c84b
TypeScript
seanwallawalla-forks/brs
/src/parser/AstNode.ts
2.984375
3
import { Location } from "../lexer"; /** * ABC (that's minimally compliant with ESLint/ESTree) for all nodes within * the AST generated by our parser. */ export abstract class AstNode { readonly type!: string; /** @param type should match the name of the derived class */ constructor(type: string) { this.type = type; } /** Currently only used by ESLint for walking the tree */ public parent: AstNode | undefined; /** Alias for location used by ESLint */ public get loc() { return this.location; } public abstract location: Location; }
935930c50ebac734f64c5fa2aee10a2363e71da4
TypeScript
VictorBalbo/functional-analyser
/src/models/Repository.ts
2.6875
3
import { Metrics } from './Metrics' export interface Repository extends Metrics { default_branch?: string full_name?: string language?: string name?: string pushed_at?: Date clone_url: string // Computed properties lamdasPerFiles: number[] totalFiles: number } export const getFolderPath = (repo: Repository) => `./Repositories/${repo.language}/${repo.name}` export const calculateMetrics = (repo: Repository) => { repo.lambdasTotal = repo.lamdasPerFiles.reduce((accumulator, value) => accumulator + value, 0) repo.avgLambdasPerFile = repo.lambdasTotal / repo.totalFiles repo.filesWithLambda = repo.lamdasPerFiles.length repo.avgLambdasPerValidFile = repo.lambdasTotal / repo.filesWithLambda // console.log(`${repo.language} - ${repo.name}: ${repo.totalFiles} files, ${repo.filesWithLambda} valid files, ${repo.lambdasTotal} total lambdas, ${repo.avgLambdasPerFile.toFixed(2)} lambdas per file, ${repo.avgLambdasPerValidFile.toFixed(2)} lambdas per valid file.`) return repo }
fdeeca7d32415ef8fa1f5fc0ed9760ed634758b3
TypeScript
l11180730/umi-plugin-apimerge
/src/utils/index.ts
2.5625
3
import path from 'path'; import { EOL } from 'os'; import { readFileSync } from 'fs'; import { utils } from 'umi'; const { t, parser, traverse, winPath } = utils; export const getPath = (absPath: string) => { const info = path.parse(absPath); return winPath(path.join(info.dir, info.name).replace(/'/, "'")); }; export const genCodes = (imports: string[]) => { const importItems: string[] = imports .map( (ele, index) => `import { IRequest as Q${index}, IResponse as P${index} } from "@/${winPath(getPath(ele))}";`, ); const exportItems: string[][] = imports.reduce((pre, _, key) => { pre[0].push(`Q${key}`); pre[1].push(`P${key}`); return pre; }, [[], []] as any); const codes: any = [ ...importItems, ` interface RequestApis extends ${exportItems[0].join(', ')}{}; interface ResponseApis extends ${exportItems[1].join(', ')}{}; type Request<T extends keyof RequestApis> = RequestApis[T]; type Response<T extends keyof ResponseApis> = ResponseApis[T]; export declare namespace MAPI { type ApiKeys = keyof ResponseApis & keyof RequestApis; type Request<T extends ApiKeys> = RequestApis[T]; type Response<T extends ApiKeys> = ResponseApis[T]; }; `, ].join(EOL); return codes; } export const isValidHook = (filePath: string) => { const isTS = path.extname(filePath) === '.ts'; const isTSX = path.extname(filePath) === '.tsx'; const content = readFileSync(filePath, { encoding: 'utf-8' }).toString(); const ast = parser.parse(content, { sourceType: 'module', plugins: [ // .ts 不能加 jsx,因为里面可能有 `<Type>{}` 这种写法 // .tsx, .js, .jsx 可以加 isTS ? false : 'jsx', // 非 ts 不解析 typescript isTS || isTSX ? 'typescript' : false, // 支持更多语法 'classProperties', 'dynamicImport', 'exportDefaultFrom', 'exportNamespaceFrom', 'functionBind', 'nullishCoalescingOperator', 'objectRestSpread', 'optionalChaining', 'decorators-legacy', ].filter(Boolean) as utils.parser.ParserPlugin[], }); let valid = false; let identifierName = ''; traverse.default(ast, { enter(p) { if (p.isExportDefaultDeclaration()) { const { type } = p.node.declaration; try { if ( type === 'ArrowFunctionExpression' || type === 'FunctionDeclaration' ) { valid = true; } else if (type === 'Identifier') { identifierName = (p.node.declaration as utils.t.Identifier).name; } } catch (e) { console.error(e); } } }, }); try { if (identifierName) { ast.program.body.forEach(ele => { if (ele.type === 'FunctionDeclaration') { if (ele.id?.name === identifierName) { valid = true; } } if (ele.type === 'VariableDeclaration') { if ( (ele.declarations[0].id as utils.t.Identifier).name === identifierName && (ele.declarations[0].init as utils.t.ArrowFunctionExpression) .type === 'ArrowFunctionExpression' ) { valid = true; } } }); } } catch (e) { valid = false; } return valid; }; export const getValidFiles = (files: string[], modelsDir: string) => files .map(file => { const filePath = path.join(modelsDir, file); const valid = isValidHook(filePath); if (valid) { return filePath; } return ''; }) .filter(ele => !!ele) as string[];
690b154c373c76336858a32c7692e5f8b5746f04
TypeScript
qjliang/algorithm-design
/src/Linked-List/06-Linked-list-queue/LoopQueue.ts
3.484375
3
import { InitArray } from './array' interface ILoopQueue<E> { getSize: () => number isEmpty: () => boolean enqueue: (e: E) => void dequeue: () => E | null getFront: () => E | null } export class LoopQueue<E> implements ILoopQueue<E> { private array: Array<E | null> private front: number = 0 tail: number= 0 private size: number = 0 constructor(capacity: number = 10) { this.array = new Array(capacity + 1 ) } public getCapacity(){ return this.array.length -1; } public getSize(){ return this.size; } public isEmpty(){ return this.front === this.tail; } public enqueue(e: E){ if((this.tail + 1) % this.array.length === this.front) this.resize(this.getCapacity() * 2); this.array[this.tail] = e; this.tail = (this.tail + 1) % this.array.length; this.size ++; } public dequeue(){ if(this.isEmpty()) throw new Error("Cannot dequeue from an empty queue."); const ret = this.array[this.front]; this.array[this.front] = null; this.front = (this.front + 1) % this.array.length; this.size --; if(this.size === this.getCapacity() / 4 && this.getCapacity() / 2 !== 0) this.resize(this.getCapacity() / 2); return ret; } public getFront(){ return this.array[this.front]; } private resize(newCapacity: number) { const newData = new Array(newCapacity + 1) for(let i = 0 ; i < this.size ; i ++) newData[i] = this.array[(i + this.front) % this.array.length]; this.array = newData; this.front = 0; this.tail = this.size; } }
c111d0f98068137d675599c9b1a30742b65dd3a4
TypeScript
techery/janet-ts
/src/__tests__/ClassHelpers.ts
2.765625
3
import {BaseAction} from "janet-ts/Action"; import "jest"; import {getActionName, getClassName, getFullClassNameComponentsFromClass} from "../ClassHelpers"; describe("ClassHelpers", () => { describe("#getClassName", () => { it("should return class name", () => { class TestClass { } expect(getClassName(TestClass)).toBe("TestClass"); }); }); describe("#getFullClassNameComponentsFromClass", () => { it("should return full class name", () => { class TestClass extends BaseAction<any> { } expect(getFullClassNameComponentsFromClass(TestClass)).toEqual(["@@janet", "BaseAction", "TestClass"]); }); }); describe("#getActionName", () => { it("should return action type name", () => { class TestClass extends BaseAction<any> { } expect(getActionName(TestClass)).toEqual("@@janet/BaseAction/TestClass"); expect(getActionName(BaseAction)).toEqual("@@janet/BaseAction"); }); it("should return action type name from plain object action", () => { expect(getActionName({ type: "test", })).toEqual("test"); }); it("should throw an exception for invalid action types", () => { expect(() => { getActionName(1); }).toThrowError(/Invalid action type:.*/); expect(() => { getActionName("asdad"); }).toThrowError(/Invalid action type:.*/); }); }); });
51d3fcbda85b69ec8651b055e6bcd2306536847d
TypeScript
zazzel/get-caller-file
/index.ts
3.015625
3
// Call this function in a another function to find out the file from // which that function was called from. (Inspects the v8 stack trace) // // Inspired by http://stackoverflow.com/questions/13227489 export = function getCallerFile(position = 2) { if (position >= Error.stackTraceLimit) { throw new TypeError('getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `' + position + '` and Error.stackTraceLimit was: `' + Error.stackTraceLimit + '`'); } const oldPrepareStackTrace = Error.prepareStackTrace; Error.prepareStackTrace = (_, stack) => stack; const stack = new Error().stack; Error.prepareStackTrace = oldPrepareStackTrace; if (stack !== null && typeof stack === 'object') { // stack[0] holds this file // stack[1] holds where this function was called // stack[2] holds the file we're interested in return stack[position] ? (stack[position] as any).getFileName() : undefined; } };
f8e99ef7650a18de50743e4719332f2e20b28b7c
TypeScript
kanzaki923/jsdialog
/src/input-box.ts
2.921875
3
import WindowBase from "./window-base.js"; export default class InputBox extends WindowBase<string>{ protected textBox:HTMLInputElement; protected _isHintShow:boolean; public set maxLength(val:number){ if (!this.textBox) return; this.textBox.maxLength = Math.max(val, this.textBox.minLength !== -1 ? this.textBox.minLength : val); } public set minLength(val:number){ if (!this.textBox) return; this.textBox.minLength = Math.min(val, this.textBox.maxLength !== -1 ? this.textBox.maxLength : val); } public set placeholder(val:string){ if (!this.textBox) return; this.textBox.placeholder = val; } public set text(val:string){ if (!this.textBox) return; this.textBox.value = val; } public set isHintShow(val:boolean){ this._isHintShow = val; } public init():void{ const tbox = document.createElement("input"); tbox.setAttribute("type", "text"); tbox.style.cssText = ` width:100%; margin:.35rem 0; margin-bottom:0; padding: .5rem .5rem; border-radius: 5px; border: solid 1px #555; box-sizing: border-box; background-color: #fff; `; tbox.title = "テキスト入力欄"; this.textBox = tbox; tbox.addEventListener("input", () => {this.check()}); this._isHintShow = false; } private check():void{ if (this._isHintShow){ const val = this.textBox.value; let isOk = true; if (this.textBox.minLength !==-1 && val.length < this.textBox.minLength) isOk = false; else if(this.textBox.maxLength !==-1 && val.length > this.maxLength) isOk = false if (!isOk){ this.textBox.style.backgroundColor = "pink"; }else{ this.textBox.style.backgroundColor = "#fff"; } } } makeContentElem(): HTMLElement { const c = document.createElement("div"); const head = document.createElement("div"); head.textContent = this.content; let notes:HTMLElement; if (this._isHintShow && this.textBox){ notes = document.createElement("div"); notes.style.cssText = `font-size: .7rem; color:#666`; notes.textContent = ` 最小文字数: ${this.textBox.minLength === -1 ? "制限なし" : this.textBox.minLength}, 最大文字数: ${this.textBox.maxLength === -1 ? "制限なし" : this.textBox.maxLength} `; } this.check(); c.appendChild(head); c.appendChild(this.textBox); if (notes) c.appendChild(notes); return c; } protected getResult(): string { return this.textBox?.value; } }
3e38a5a02f6ab2102a305d44c8bf35be71153132
TypeScript
JohannesLauinger/angular_frontend
/src/app/kunde/update-kunde/interessen/update-interessen.component.ts
2.734375
3
// eslint-disable-next-line eslint-comments/disable-enable-pair /* eslint-disable @typescript-eslint/consistent-type-imports */ // eslint-disable-next-line eslint-comments/disable-enable-pair /* eslint-disable @typescript-eslint/no-unnecessary-condition */ import { ActivatedRoute, Router } from '@angular/router'; import { Component, Input } from '@angular/core'; import { FormControl, FormGroup } from '@angular/forms'; import { Kunde, KundeService } from '../../shared'; import type { OnDestroy, OnInit } from '@angular/core'; import { HOME_PATH } from '../../../shared'; import { Subscription } from 'rxjs'; /** * Komponente f&uuml;r das Tag <code>hs-update-interessen</code> */ @Component({ selector: 'hs-update-interessen', templateUrl: './update-interessen.component.html', styleUrls: ['./update-interessen.component.css'], }) export class UpdateInteressenComponent implements OnInit, OnDestroy { // <hs-update-interessen [kunde]="..."> @Input() kunde!: Kunde; hasInteressen: boolean | undefined; form!: FormGroup; reisen!: FormControl; lesen!: FormControl; sport!: FormControl; private updateSubscription: Subscription | undefined; constructor( private readonly kundeservice: KundeService, private readonly router: Router, private readonly route: ActivatedRoute, ) { console.log('UpdateInteressenComponent.constructor()'); } /** * Das Formular als Gruppe von Controls initialisieren und mit den * Interessen des zu &auml;ndernden Kunden vorbelegen. */ ngOnInit() { console.log('kunde=', this.kunde); // eslint-disable-next-line no-null/no-null if (this.kunde.interessen === null) { this.hasInteressen = false; this.reisen = new FormControl(false); this.lesen = new FormControl(false); this.sport = new FormControl(false); } else { this.hasInteressen = true; // Definition und Vorbelegung der Eingabedaten (hier: Checkbox) const hasReisen = this.kunde.hasInteresse('R'); this.reisen = new FormControl(hasReisen); const hasLesen = this.kunde.hasInteresse('L'); this.lesen = new FormControl(hasLesen); const hasSport = this.kunde.hasInteresse('S'); this.sport = new FormControl(hasSport); } this.form = new FormGroup({ // siehe ngFormControl innerhalb von @Component({template: `...`}) reisen: this.reisen, lesen: this.lesen, sport: this.sport, }); } ngOnDestroy() { if (this.updateSubscription !== undefined) { this.updateSubscription.unsubscribe(); } } /** * Die aktuellen Interessen f&uuml;r das angezeigte Kunde-Objekt * zur&uuml;ckschreiben. * @return false, um das durch den Button-Klick ausgel&ouml;ste Ereignis * zu konsumieren. */ // eslint-disable-next-line max-lines-per-function onUpdate() { if (this.form.pristine) { console.log( 'UpdateInteressenComponent.onUpdate(): keine Aenderungen', ); // eslint-disable-next-line unicorn/no-useless-undefined return undefined; } if (this.kunde === undefined) { console.error( 'UpdateInteressenComponent.onUpdate(): kunde === undefined', ); // eslint-disable-next-line unicorn/no-useless-undefined return undefined; } this.kunde.updateInterssen( // eslint-disable-next-line @typescript-eslint/no-unsafe-argument this.reisen.value, // eslint-disable-next-line @typescript-eslint/no-unsafe-argument this.lesen.value, // eslint-disable-next-line @typescript-eslint/no-unsafe-argument this.sport.value, ); console.log('kunde=', this.kunde); const successFn = () => { console.log( `UpdateInteressenComponent.onUpdate(): successFn: path: ${HOME_PATH}`, ); this.router .navigate(['..'], { relativeTo: this.route }) .then( navResult => { if (navResult) { console.log( 'UpdateInteressenComponent.onUpdate(): Navigation', ); return true; } console.error( 'UpdateInteressenComponent.onUpdate(): Navigation fehlgeschlagen', ); return false; }, () => { console.error( 'UpdateInteressenComponent.onUpdate(): Navigation fehlgeschlagen', ); return false; }, ) .catch(err => console.error( 'UpdateInteressenComponent.onUpdate(): Navigation fehlgeschlagen:', err, ), ); }; const errorFn: ( status: number, // eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style errors: { [s: string]: unknown } | undefined, // eslint-disable-next-line unicorn/no-useless-undefined ) => void = (status, errors = undefined) => { console.error( `UpdateInteressenComponent.onUpdate(): errorFn(): status: ${status}, errors=`, errors, ); }; this.updateSubscription = this.kundeservice.update( this.kunde, successFn, errorFn, ); // damit das (Submit-) Ereignis konsumiert wird und nicht an // uebergeordnete Eltern-Komponenten propagiert wird bis zum // Refresh der gesamten Seite return false; } }
25c49009203867f4ed94d3b6957ee7e7c4a5d6e1
TypeScript
stencila/dockta
/src/Parser.ts
2.890625
3
import Doer from './Doer' import { SoftwarePackage } from '@stencila/schema' /** * A base class for language parsers * * A language `Parser` generates a JSON-LD `SoftwarePackage` instance based on the * contents of a directory. It is responsible for determining which packages the application * needs, resolving the dependencies of those packages (both system and language packages) and * turning those into a JSON-LD `SoftwarePackage` instance. * * If the `Parser` finds a corresponding requirements file for the language (e.g. `requirements.txt` for Python), * then it uses that to determine the language packages to install. If no requirements file is found, * it scans for source code files for package import statements (e.g. `library(package)` in `.R` files), * generates a package list from those statements and creates a requirements file. */ export default abstract class Parser extends Doer { /** * Parse the project folder */ abstract parse(): Promise<SoftwarePackage | null> }