lang
stringclasses
10 values
seed
stringlengths
5
2.12k
typescript
GetListOptions >({ key: 'newsIndex', default: undefined, }); export const refreshNewsItemState = atomFamily<number, string>({ key: 'refreshNewsItem',
typescript
export default ({ filePath }: Options) => CameraRoll.save( `${filePath.includes('file://') ? '' : 'file://'}${filePath}`, { type: 'photo', }, );
typescript
<gh_stars>0 export const getModal = ({ modals }) => { return modals.slice(modals.length - 1)[0] || {}; };
typescript
import { COLLECTIONS } from '../../config/constants'; const resolversShopProductType: IResolvers = { ShopProduct: { productId: (parent) => parent.product_id, platformId: (parent) => parent.platform_id, product: async(parent, __, { db}) => { const result = await new ProductService({}, { id: parent.product_id}, {db}).details(); return result.product; }, platform: async(parent, __, { db}) => { const result = await new PlatformService({ }, { id: parent.platform_id}, {db}).details();
typescript
if (!page) { throw new Error(`Cannot cancel dialog because no browser has been launched`); } if (!dialog) {
typescript
}, 100); } }; document.addEventListener("mousedown", handleClickOutside);
typescript
import {Entity, PrimaryColumn} from "typeorm"; @Entity() export class Guild { /** used discord guild id */ @PrimaryColumn() public id: string; }
typescript
{ this.authRoomUsers.set(roomId, { roomId, userIds: [] }); users = this.authRoomUsers.get(roomId)!; } users.userIds.push(userId); await this.writeDataToFile(); console.log(`[${this.className}] New authorization record for User [${userId}] in Room [${roomId}] was created.`); } public async remove(roomId: string, userId: string): Promise<void> { const users = this.authRoomUsers.get(roomId);
typescript
import { DemoVersionComponent } from './demo-version/demo-version.component'; export const DEMOVERSION_COMPONENTS = [DemoVersionComponent]; export * from './demo-version/demo-version.component';
typescript
str = str.concat(`<DropDown>`, '\n'); str = str.concat(`<ReleaseNotes :sha='${js.js_beautify(JSON.stringify(obj))}' />`, '\n'); str = str.concat(`</DropDown>`, '\n'); str = str.concat('!!!', '\n\n'); str = str.concat('<!-- ---------------------------------------------- -->', '\n'); str = str.concat(postText); const baseVersionsObj = JSON.parse(fs.readFileSync(versionsJson).toString()); baseVersionsObj[packageJson.version] = str; let filteredObject: any = {}; Object.keys(baseVersionsObj).sort(compareVersions).reverse().map((key) => { filteredObject[key] = baseVersionsObj[key] }); fs.writeFileSync(versionsJson, JSON.stringify(filteredObject, undefined, 4)); printConsoleStatus(`Release notes added successfully!`, 'success'); return str;
typescript
import { defaultLocalOptions, defaultRemoteOptions } from "./lib/common"; if (!module.parent) { if (process.env.APPINSIGHTS_INSTRUMENTATIONKEY) { applicationinsights.setup(); applicationinsights.start(); }
typescript
} } passwordEmpty(){ if(this.myFormGroup.controls['password'].value.length!=0){ this.nullValueErrorMessage = false;
typescript
import createWithBsPrefix from 'react-bootstrap/createWithBsPrefix'; export default createWithBsPrefix<'span'>('sidebar-menu-nav-icon', { displayName: 'SidebarMenuNavIcon', Component: 'span' });
typescript
* @param {boolean} onlyRunning * @param callback() */ public proxies(onlyRunning: boolean, callback: (error: any, response: Response, body: any) => void): void { this.setEndpoint('/proxies'); if (onlyRunning) { this.setEndpoint('/proxies_running'); } Request.get({ url: this.host.href,
typescript
return this.commandArgs.buildId.val().then((buildId) => { return this._deleteBuild(buildapi, buildId, project); }); }); } public friendlyOutput(build: buildContracts.Build): void { trace.println(); } private _deleteBuild(buildapi: buildClient.IBuildApi, buildId: number, project: string) { trace.info("Deleting build...") buildapi.deleteBuild(buildId,project)
typescript
describe('NamedLinesComponent', () => { let component: NamedLinesComponent; let fixture: ComponentFixture<NamedLinesComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ NamedLinesComponent ] }) .compileComponents();
typescript
export * from './byte-number/byte-number-pipe'; export * from './full-name/full-name-pipe'; export * from './router/route-data-pipe'; export * from './router/route-param-pipe'; export * from './slice/slice-pipe'; export * from './clip/clip-pipe';
typescript
describe('check correct cdn', () => { const script = createScript(cdnExample) test('should load script correctly', async () => { try { expect(await script).toBeTruthy()
typescript
} updateProfile(currentUser: User | null): void { if (currentUser) { this.email = currentUser.email; this.name = currentUser.displayName; this.photoUrl = currentUser.photoURL; } } deleteAccount(): void {
typescript
this.children.splice( this.children.findIndex( c => c === child ), 1 ); // eslint-disable-next-line no-param-reassign child.parent = null; this.invalidateSceneGraph(); } } public hide(): void { this.visible = false;
typescript
import { suite } from "@vangware/test"; import { getOwnPropertyDescriptors } from "../src/getOwnPropertyDescriptors"; export default suite([ { given: "an object with a foo property", must: "return property descriptors of that object", received: getOwnPropertyDescriptors({ foo: "bar" }), wanted: { foo: { value: "bar", writable: true, // TODO: Remove next comment when @vangware/test is updated // eslint-disable-next-line sort-keys enumerable: true,
typescript
} ` export default function Template({ data }) { const { allMarkdownRemark } = data const { edges } = allMarkdownRemark const title = 'Portfolio' const description = `A sampling of public projects I have worked on over my ${new Date().getFullYear() - 2005}+ year career` return ( <Layout> <Main> <SEO description={description} path="/portfolio" title={title} /> <Banner description={description} title={title} />
typescript
export class ComponentOverviewUpdateWithWhereUniqueWithoutComponentInput { @Field(() => ComponentOverviewWhereUniqueInput, {nullable:false}) where!: ComponentOverviewWhereUniqueInput; @Field(() => ComponentOverviewUpdateWithoutComponentInput, {nullable:false})
typescript
const validate = yobta( catchYobta( 'catched yobta!', stringYobta(), requiredYobta(), minCharactersYobta(5) ) ) it('does not catch when no errors', () => { let result = validate('yobta') expect(result).toEqual('yobta')
typescript
export interface User { id: number; username: string; password: string; active: boolean; roles: string; permissions: string[]; roleList: string[]; permissionList: string[]; }
typescript
description: string; tags: string[]; iconUrl: string; owner: Schema.Types.ObjectId; members: Schema.Types.ObjectId[]; reviews: Schema.Types.ObjectId[]; createdAt: Date; }
typescript
<a target="_blank" href="https://cprimozic.net/"> <NAME> / ameo </a> </div> <div> {' '} Full Source Code on{' '} <a href="https://github.com/ameobea/spotifytrack" target="_blank"> Github </a> </div> </footer> );
typescript
const navigateToOtherPageNone = "navigate to other page (no transition)"; const navigateToOtherPageSlide = "navigate to other page (slide transition)"; const navigateToOtherPageFlip = "navigate to other page (flip transition)"; const players = "Players"; const teams = "Teams"; const playerBack = "playerBack"; const stillOtherPageBack = "stillOtherPageBack"; const somePageBack = "somePageBack"; const otherPageBack = "otherPageBack"; const teamBack = "teamBack"; const frameHomeBack = "frameHomeBack"; const tabTopBack = "tabTopBack"; const tabBottomBack = "tabBottomBack";
typescript
if (typeof credentials !== 'undefined' && credentials !== null) { if (next.data.permission && !this.isAllowed(next.data.permission)) { return false; } return true;
typescript
// Append the slice of the `styleName` from the end of the previous hyphen to the start of this hyphen. stylePropName += styleName.slice(matchEndIndex, matchIndex); // Omit the hyphen. matchEndIndex = matchIndex + 1; if (matchEndIndex < styleName.length) { stylePropName += styleName[matchEndIndex].toUpperCase();
typescript
export { FileCheckController } from './FileCheckController' export { UrlCheckController } from './UrlCheckController'
typescript
rel="noopener noreferrer" > Learn more. </a> </p> <div className="top-container"> <div className="form-module instance-details-container"> <EditInstanceDetails />
typescript
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MdSnackBar } from '@angular/material'; import { HttpModule, JsonpModule } from '@angular/http'; import { GitHubService } from 'app/services/git-hub.service'; import { StatsService } from 'app/services/stats.service';
typescript
import { TodosComponent } from './todos/todos.component'; const routes:Routes = [ { path:'todos', component:TodosComponent } ] @NgModule({ imports:[RouterModule.forChild(routes)],
typescript
prevState => ({...prevState, searchQuery: newValue}) ); } } /> </div> </div> <UserSettings username={this.state.settings.userInfo.username}/> </div> </div> </header> <div className="action-bar"> {this.actionBarContent()}
typescript
<gh_stars>100-1000 import React, { memo } from "react"; import { SelectionProps } from "./Grid"; import { createHTMLBox } from "./utils"; const Selection: React.FC<SelectionProps> = memo((props) => { return createHTMLBox({ strokeWidth: 1, ...props }); }); export default Selection;
typescript
export { default } from './useQuerystring';
typescript
* @date 2022-03-16 */ export async function getMyIp(timeout?: number): Promise<Array<GetMyIpItem>> { const services: Array<string> = [ "https://icanhazip.com", "https://ifconfig.me/all.json", "https://api.ipify.org", "https://ipinfo.io/ip", "https://ipecho.net/plain", "https://alanwei.azurewebsites.net/api/tool/ip" ]; const list: Array<GetMyIpItem> = [];
typescript
); }; const Output = ({ responseData }: OutputProps) => { const { words } = responseData; return ( <div> <HighlightContainer> {words.map((word) => ( <TokenSpan token={word} /> ))}
typescript
import { ShellModel } from '../../../../../shell/data-store'; export class UserImageModel extends ShellModel { link: string; constructor() { super(); } }
typescript
ico: 'fal fa-registered', template: '(r)', title: 'Trademark' }, { example: '', ico: 'fal fa-trademark', template: '(tm)', title: 'Trademark' }, {
typescript
*/ Role?: Array<string>; /** * * @type {Array<string>} * @memberof VariableResourceScope */ TargetRole?: Array<string>; /** * * @type {Array<string>} * @memberof VariableResourceScope */ Action?: Array<string>;
typescript
import Header from "./Header"; import { Link } from 'react-scroll'; // import NavBar from '..components/NavBar'; import Intro from '../components/Intro'; import Features from '../components/Features'; import About from '../components/About'; import Setup from '../components/Setup'; import "./MyApp.css"; import startingGif from '../../src/assets/gifs/2.gif'; const MyApp: React.FC = () => { const darkMode = useDarkMode(); const { t } = useTranslation();
typescript
} const Title: React.FC<Props> = ({ children, className }) => ( <h2 className={`text-2xl text-center text-warning font-semibold ${className}`}> {children} </h2> ); export default Title;
typescript
<Switch> <Route exact path='/signin' component={AuthView} /> <Route exact path='/dashboard' component={Dashboard} /> <Route exact path='/' component={HomePage} /> <Route path='/course/:courseID' render={({match}: RouteComponentProps) => { return ( <CourseView id={(match.params as {courseID: string}).courseID}/> ); }}/> <Route path='/enroll/:courseID' render={({match}: RouteComponentProps) => { return ( <JoinCourseView id={(match.params as { courseID: string }).courseID}/> );
typescript
export function configure(fxconfig: any): void { fxconfig.foo = 'bar'; }
typescript
styleUrls: ['./general-reports.component.scss'] }) export class GeneralReportsComponent implements OnInit { constructor() { } ngOnInit() { } }
typescript
const { addEventListener, AsyncStorage, Bridge, Device, HippyRegister, } = HippyGlobal; export {
typescript
import {LoginSuccess} from '@/models/LoginSuccess'; export interface OAuthLoginSuccess extends LoginSuccess{ accessToken: string; }
typescript
* The title to render in the UI. * If not set the `name` is used. */ title?: string; /** * Theme's name from the package.json file. */ name: string; /** * Theme version. */ version: string; /** * Theme directory in the themes location directory.
typescript
/* jsdocs */ static { // something } }
typescript
export class EditEnemyInteractorResponse { constructor(readonly imageUrl?: string) {} }
typescript
machine: string; blueprints: Blueprints; matchers: Object | Function; options?: { [k: string]: any }; } export default PolyType;
typescript
const props = { onClick: handleMoreInfoClick, spanInnerText: 'giggle forest에 대해', aInnerText: '자세히 알아보세요', }; return <MoreInfoView {...props} />; } export default MoreInfo;
typescript
@Entity() export class User { @PrimaryGeneratedColumn('uuid') id?: string; @Column() name: string;
typescript
this.to.close() ]); } get initialized(): Promise<any> {
typescript
export function printLogs( result: LogApiResource[], config: LogsConfig, outputFormat?: string ) { result.forEach(log => printLog(log, outputFormat)); } export function printLog(log: LogApiResource, outputFormat?: string) { if (outputFormat === 'json') { writeOutput(JSON.stringify(log)); } else { writeOutput(`[${log.level}][${log.date_created}]: ${log.message}`);
typescript
import { createSlice, PayloadAction } from '@reduxjs/toolkit'; export interface Top3Disease { name: string, personAmount: string, percent: number } export interface AgingDisease { fromAge: number, toAge: number, aging: number, top3Diseases: Top3Disease[], imageBase64: string }
typescript
); this.updateArticles(this.config.params); } async onChangeParams(nextParams: IParams) { await this.updateArticles(nextParams); } async updateArticles(params: IParams) { const currentPage = params && params.page ? parseInt(params.page, 10) : 1; const count = 5; const articles = await this.config.api.articles({ offset: (currentPage - 1) * count, limit: count });
typescript
el.style.borderTopWidth = `${fraq * parseFloat(style.borderTopWidth)}px`; el.style.borderBottomWidth = `${fraq * parseFloat(style.borderBottomWidth)}px`; }, () => { el.style.overflow = style.overflow; ['opacity', 'height', 'paddingTop', 'paddingBottom', 'marginTop', 'marginBottom', 'borderTopWidth', 'borderBottomWidth'].forEach((name) => { (el.style as any)[name] = (style as any)[name]; }); }); } else done();
typescript
); const fieldValue = `${name}.value`; return resourceParam.type === 'array' ? ( <TextColumnField name={fieldValue} label={resourceParam.name} required={emptyIsInvalid} onChange={(values: string[]) => { if (!hasParam) {
typescript
template: ` <div style="text-align:center"> <h1>{{ title }}!</h1> <img width="150" alt="Angular Logo" src="/assets/angular.png" /> </div> `
typescript
import { TabMover } from "./tabMover"; const tabMover = new TabMover(); browser.menus.create({ contexts: ["tab"], onclick: (_, tab) => tabMover.moveTabOrHighlightedTabs(tab), title: "Move to the next window", }); browser.browserAction.onClicked.addListener((tab) => tabMover.moveTabOrHighlightedTabs(tab)); browser.commands.onCommand.addListener(() => tabMover.moveActiveTab());
typescript
export function validate_submission<QT extends ResponseKind>(response: ResponseSpecification<QT>, submission: SubmissionType<QT>) : SubmissionType<QT> { let handler = <ResponseHandler<QT>>RESPONSE_HANDLERS[response.kind]; return handler.validate ? handler.validate(response, submission) : submission; } export function render_response<QT extends ResponseKind>(response: ResponseSpecification<QT>, question_id: string, question_uuid: string, skin?: ExamComponentSkin) : string { return (<ResponseHandler<QT>><unknown>RESPONSE_HANDLERS[<QT>response.kind]).render(response, question_id, question_uuid, skin); } export function render_solution<QT extends ResponseKind>(response: ResponseSpecification<QT>, solution: ViableSubmissionType<QT>, question_id: string, question_uuid: string, skin?: ExamComponentSkin) : string { return (<ResponseHandler<QT>><unknown>RESPONSE_HANDLERS[<QT>response.kind]).render_sample_solution(response, solution, question_id, question_uuid, skin); } export function activate_response<QT extends ResponseKind>(kind: QT, is_sample_solution: boolean, responseElem: JQuery) : void {
typescript
let timer: null | NodeJS.Timeout = null export function debounce(callback: any, delay: number) { return function() { let context = this let arg = arguments if (timer !== null) {
typescript
this.setState({value: validatedTime, cursorPosition: newPosition}, () => { inputEl.selectionStart = validatedCursorPosition; inputEl.selectionEnd = validatedCursorPosition; const changeEvent = event as SyntheticEvent<HTMLInputElement>; callback(changeEvent, validatedTime);
typescript
@Injectable() export class ValidateStudentMiddleware implements NestMiddleware { private students = students use(req: Request, res: Response, next: NextFunction) { const studentId = req.params.studentId; const isStudentExist = this.students.some(student => student.id === studentId) if (!isStudentExist) { throw new HttpException("Student not found",400) } next() } }
typescript
class ProjectPermissionManager { private readonly searchBox: MultiSetTypeaheadSearchBox<IRole>; private readonly client: PermissionApiClient; private readonly errorHandler: ErrorHandler; private readonly savePermissionButtonSelector: string; private readonly isUserTypeaheadEnabled: boolean; private projectId: number; private currentRoleSelectedItem: IRole;
typescript
basicColumns: [ {field: {name: 'trip.bussSchedule.path', template: InputTemplate.path}}, { field: {name: 'fullName'}, subColumns: [ {field: {name: 'phoneNumber', template: InputTemplate.phone}}, {field: {name: 'email'}} ] }, { field: {name: 'totalPrice', template: InputTemplate.money},
typescript
import { Transport } from '@nestjs/microservices'; const PATTERN_METADATA = 'microservices:pattern'; const TRANSPORT_METADATA = 'microservices:transport'; const PATTERN_HANDLER_METADATA = 'microservices:handler_type'; export const KafkaTopic = (topicName?: string): MethodDecorator => { // eslint-disable-next-line return (target: object, key: string | symbol, descriptor: PropertyDescriptor) => { Reflect.defineMetadata(PATTERN_METADATA, topicName, descriptor.value); Reflect.defineMetadata(PATTERN_HANDLER_METADATA, 2, descriptor.value); Reflect.defineMetadata(TRANSPORT_METADATA, Transport.KAFKA, descriptor.value); return descriptor; };
typescript
return { ...state, fetchState: "attempt", axiosErrorResponse: null }; case apiActions.success: return { ...state, fetchState: "success",
typescript
import { Review, ReviewLog } from 'src/@types'; export interface ReviewLogScreenProps { navigation: any; route: any; review: Review; log: ReviewLog; } export const mapStateToProps = () => ({}); export const mapDispatchToProps = () => ({});
typescript
const serviceSchema: ServiceSchema = { name: 'documents-store', version: '1.0.0', settings: { $noVersionPrefix: false, }, mixins: [mongodbMixin('documents')], };
typescript
}).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(TakeTransportComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
typescript
case 'JUMP_TO_ACTION': case 'JUMP_TO_STATE': return setState(extractState(message)) case 'IMPORT_STATE': { const { computedStates } = payload.nextLiftedState const { state } = computedStates[computedStates.length - 1] ?? {} return state !== undefined && setState(state) } } } }) return { ...program, setState,
typescript
return request({ url: 'zys/costMaster/valve/control', method: 'post', data: params }) } /** * 获取指定历史指令 * @param params * @returns */ export const GetZhiLinHistory = (params: IQueryMeterRead) => { return request({
typescript
export { PresetsDirective, PresetDirective, PresetsPlugin, PresetPlugin } from './presets.directive'; export { DateRangePickerComponent, DateRangePickerPlugin } from './daterangepicker.component';
typescript
reel_type: string; user: UserResponse; ranked_position: number; seen_ranked_position: number; muted: boolean; prefetch_count: number; has_besties_media: boolean; media_count: number; unique_integer_reel_id: string | number;
typescript
msb: number; lsb: number; pc: number; elxxx: boolean; }; export type DrumJSON = { sfx: boolean; } & VoiceJSON; export type DrumToneJson = { name: string;
typescript
@Injectable() export class TodoService { constructor(@InjectModel('TodoItem')private readonly todoItemModel:Model<TodoItem>) { } async create(todoItemDto:TodoItemDto): Promise<TodoItem>{ const createdTodo = new this.todoItemModel(todoItemDto); return await createdTodo.save(); } async findAll(): Promise<TodoItem[]>{ return await this.todoItemModel.findAll().exec();
typescript
return of(void 0); } public restore(): Observable<Feeder> {
typescript
export class AddressModel { AddressLine1 = ''; AddressLine2 = ''; AddressLine3 = ''; PostTown = ''; County = ''; PostCode = ''; Country = '';
typescript
export const ONBOARDING = '/onboarding'; export const SIGN_IN = '/onboarding/signin'; export const SIGN_UP = '/onboarding/signup'; export const DASHBOARD = '/dashboard';
typescript
return functionEndpoint; } async removeEndpoint(safeFunctionName: string): Promise<void> { await this.read(); _unset(this, `functions.${safeFunctionName}`); await this.save();
typescript
export function foo(): number { return 5; }
typescript
const Section: FunctionComponent<SectionProps> = ({ children, className = '', dark = false, }) => { const css = className || '' const darkerBackground = dark ? 'bg-gray-100 md:border' : ''
typescript
const element: HTMLElement | null = document.getElementById(id) if (element === null) throw Error('Cannot find HTMLElement.') const stage = new Konva.Stage({ container: id, width: element.clientWidth,
typescript
var send = JSON.stringify({parentId:this.comment.id,id:this.comment.articlesId,data:text.value,subName:this.comment.subName,profile:this.comment.profile}) this._http.post('/comments',send,{headers:headers}) .map(res=>res.json()) .subscribe( (data)=>{}, (err)=>console.log(err),
typescript
export * from './account'; export * from './account.service'; export * from './management/account-management.component'; export * from './edit/account-edit.component'; export * from './list/account-list.component';
typescript
apiVersion: traefik.containo.us/v1alpha1 kind: IngressRoute metadata: name: whoami spec: entryPoints: - web routes: - kind: Rule match: Host(\`demo.kubevious.io\`) middlewares: - name: samples-security@kubernetescrd # Middleware not found in the namespace "samples" namespace: samples - name: redirect # Middleware not found in same namespace services:
typescript
export async function getUser(userId?: number | null | undefined) { if (!userId) { return null; } const user = await User.findByPk(userId);
typescript
export const candidateInitMock: RTCIceCandidateInit = { candidate: 'mid: audio, candidate: a=candidate:941443129 2 udp 1845501695 192.168.127.12 49669 typ srflx' + ' raddr 192.168.1.2 rport 49669 generation 0' };
typescript
import express from 'express' import admin from './entities/Admin/routes' import committee from './entities/Committee/routes' import { activateProposals, finishProposal } from './entities/Proposal/jobs' import proposal from './entities/Proposal/routes' import sitemap from './entities/Sitemap/routes' import social from './entities/Social/routes' import subscription from './entities/Subscription/routes' import updates from './entities/Updates/routes' import score from './entities/Votes/routes' require('newrelic')
typescript
" App is running at http://localhost:%d in %s mode", app.config.port, app.config.env ); console.log(" Press CTRL-C to stop\n"); }); export default server;
typescript
field.jsonInputMapping.pop(); console.log("AFTER element:" + element.value) }
typescript
} }); } else { next(createError('Not Authorized', 401)); } }
typescript
export class Route { public static URLV1:string = "metax/v1/" }
typescript
import { factoryConf } from '../../model' import { PresenterUiState } from '..' import { ImplPresenterUiState } from './presenter-ui-state' export function factoryPresenterUiState(): PresenterUiState { return new ImplPresenterUiState(factoryConf())
typescript
export default class PasswordDoesntMatch extends DomainException { constructor() { super('PasswordDoesntMatch', "Password confirmation doesn't matches"); } }
typescript
innerHeight: window.innerHeight, innerWidth: window.innerWidth, outerHeight: window.outerHeight, outerWidth: window.outerWidth }; } else { console.error('ReferenceError: typeof "window" is undefined'); return { innerHeight: 0, innerWidth: 0, outerHeight: 0, outerWidth: 0 }; }