type
stringclasses
7 values
content
stringlengths
4
9.55k
repo
stringlengths
7
96
path
stringlengths
4
178
language
stringclasses
1 value
MethodDeclaration
/** * From a RawStyle, generate a StyleRule of a specific style */ public static getRule( rawRule: IStyleRule<INodeStyle | IEdgeStyle>, styleType: StyleType ): StyleRule { const rule = Tools.clone(rawRule); rule.style = {[styleType]: rule.style[styleType]}; return new StyleRule(rule); }
Linkurious/ogma-linkurious-parser
src/styles/styleRules.ts
TypeScript
MethodDeclaration
/** * Check for non unique index in styles rules and update them if exists */ public static sanitizeStylesIndex(styles: IStyles): IStyles { const seenIndex: Array<number> = []; const sanitizedStyles: IStyles = Tools.clone(styles); let maxIndex = Math.max(...[...styles.node.map((s) => s.index), ...styles.edge.map((s) => s.index)]) + 1; sanitizedStyles.node = sanitizedStyles.node.map((style) => { if (seenIndex.includes(style.index)) { style.index = maxIndex; maxIndex++; } else { seenIndex.push(style.index); } return style; }); sanitizedStyles.edge = sanitizedStyles.edge.map((style) => { if (seenIndex.includes(style.index)) { style.index = maxIndex; maxIndex++; } else { seenIndex.push(style.index); } return style; }); return sanitizedStyles; }
Linkurious/ogma-linkurious-parser
src/styles/styleRules.ts
TypeScript
ClassDeclaration
@NgModule({ declarations: [HomeComponent], imports: [CommonModule, HomeRoutingModule, SharedCommonModule, CountdownModule], providers: [CategoryService] }) export class HomeModule {}
freehidehide/IMA_client
src/app/home/home.module.ts
TypeScript
ClassDeclaration
@Component({ selector: 'add-group-dialog', templateUrl: 'add-group-dialog.html', }) export class AddGroupDialogComponent { public GroupName: FormControl; @ViewChild(MatCheckbox, { static: true }) public IsPublic: MatCheckbox; constructor( public dialogRef: MatDialogRef<ChatComponent>) { this.GroupName = new FormControl('', Validators.compose( [Validators.required, Validators.minLength(ChatsService.MinGroupNameLength)])); } onNoClick(): void { this.dialogRef.close(); } public CreateGroup() { if (!this.GroupName.valid) { return; } this.dialogRef.close({ name: this.GroupName.value, isPublic: this.IsPublic.checked }); } }
ActualDennis/Vibechat.Web
Vibechat.Web/Vibechat.Web/ClientApp/src/app/Dialogs/AddGroupDialog.ts
TypeScript
MethodDeclaration
public CreateGroup() { if (!this.GroupName.valid) { return; } this.dialogRef.close({ name: this.GroupName.value, isPublic: this.IsPublic.checked }); }
ActualDennis/Vibechat.Web
Vibechat.Web/Vibechat.Web/ClientApp/src/app/Dialogs/AddGroupDialog.ts
TypeScript
FunctionDeclaration
/// Returns an extension that installs the Java language and /// support features. export function java(): Extension { return [javaLanguage] }
twop/codemirror.next
lang-java/src/java.ts
TypeScript
ArrowFunction
context => { let after = context.textAfter, closed = /^\s*\}/.test(after), isCase = /^\s*(case|default)\b/.test(after) return context.baseIndent + (closed ? 0 : isCase ? 1 : 2) * context.unit }
twop/codemirror.next
lang-java/src/java.ts
TypeScript
ArrowFunction
() => -1
twop/codemirror.next
lang-java/src/java.ts
TypeScript
MethodDeclaration
"Block SwitchBlock ClassBody ElementValueArrayInitializer ModuleBody EnumBody ConstructorBody InterfaceBody ArrayInitializer" (tree) { return {from: tree.from + 1, to: tree.to - 1} }
twop/codemirror.next
lang-java/src/java.ts
TypeScript
MethodDeclaration
BlockComment(tree) { return {from: tree.from + 2, to: tree.to - 2} }
twop/codemirror.next
lang-java/src/java.ts
TypeScript
ClassDeclaration
export class Rule extends Lint.Rules.AbstractRule { static readonly metadata: Lint.IRuleMetadata = { description: 'Disallows explicit calls to life cycle hooks.', options: null, optionsDescription: 'Not configurable.', rationale: 'Explicit calls to life cycle hooks could be confusing. Invoke life cycle hooks is the responsability of Angular.', ruleName: 'no-life-cycle-call', type: 'maintainability', typescriptOnly: true }; static readonly FAILURE_STRING = 'Avoid explicit calls to life cycle hooks.'; apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { return this.applyWithWalker(new ExpressionCallMetadataWalker(sourceFile, this.getOptions())); } }
AngularJS-NG2-NG4-NG5/codelyzer
src/noLifeCycleCallRule.ts
TypeScript
ClassDeclaration
export class ExpressionCallMetadataWalker extends NgWalker { visitCallExpression(node: ts.CallExpression): void { this.validateCallExpression(node); super.visitCallExpression(node); } private validateCallExpression(node: ts.CallExpression): void { const name = ts.isPropertyAccessExpression(node.expression) ? node.expression.name : undefined; const expression = ts.isPropertyAccessExpression(node.expression) ? node.expression.expression : undefined; const isSuperCall = expression && expression.kind === ts.SyntaxKind.SuperKeyword; const isLifecycleCall = name && ts.isIdentifier(name) && lifecycleHooksMethods.has(name.text as LifecycleHooksMethods); if (isLifecycleCall && !isSuperCall) { this.addFailureAtNode(node, Rule.FAILURE_STRING); } } }
AngularJS-NG2-NG4-NG5/codelyzer
src/noLifeCycleCallRule.ts
TypeScript
TypeAliasDeclaration
export type LifecycleHooksMethods = | 'ngAfterContentChecked' | 'ngAfterContentInit' | 'ngAfterViewChecked' | 'ngAfterViewInit' | 'ngDoCheck' | 'ngOnChanges' | 'ngOnDestroy' | 'ngOnInit';
AngularJS-NG2-NG4-NG5/codelyzer
src/noLifeCycleCallRule.ts
TypeScript
MethodDeclaration
apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { return this.applyWithWalker(new ExpressionCallMetadataWalker(sourceFile, this.getOptions())); }
AngularJS-NG2-NG4-NG5/codelyzer
src/noLifeCycleCallRule.ts
TypeScript
MethodDeclaration
visitCallExpression(node: ts.CallExpression): void { this.validateCallExpression(node); super.visitCallExpression(node); }
AngularJS-NG2-NG4-NG5/codelyzer
src/noLifeCycleCallRule.ts
TypeScript
MethodDeclaration
private validateCallExpression(node: ts.CallExpression): void { const name = ts.isPropertyAccessExpression(node.expression) ? node.expression.name : undefined; const expression = ts.isPropertyAccessExpression(node.expression) ? node.expression.expression : undefined; const isSuperCall = expression && expression.kind === ts.SyntaxKind.SuperKeyword; const isLifecycleCall = name && ts.isIdentifier(name) && lifecycleHooksMethods.has(name.text as LifecycleHooksMethods); if (isLifecycleCall && !isSuperCall) { this.addFailureAtNode(node, Rule.FAILURE_STRING); } }
AngularJS-NG2-NG4-NG5/codelyzer
src/noLifeCycleCallRule.ts
TypeScript
ClassDeclaration
@NgModule({ declarations: [ AddonMessagesConversationInfoPage, ], imports: [ CoreComponentsModule, CoreDirectivesModule, IonicPageModule.forChild(AddonMessagesConversationInfoPage), TranslateModule.forChild() ], }) export class AddonMessagesConversationInfoPageModule {}
interactivegroup/almsmobileapp
src/addon/messages/pages/conversation-info/conversation-info.module.ts
TypeScript
InterfaceDeclaration
interface MinutesDoc extends App.Minutes, Document {}
jsrois/sll-seguiment-casos
backend/server/minutes/minutes.model.ts
TypeScript
ArrowFunction
token => { // -->Set: token this.token = token; // -->Is: ok? this.tokenInfo = { hasToken: true }; // -->Return: token return token; }
devantennae786/idexy_custom_webapp
src/app/providers/http/http-client.service.ts
TypeScript
ClassDeclaration
@Injectable() export class HttpClientService extends HttpClient { @JsonLocalStorage private token: UserInterface.Token; @JsonLocalStorage private tokenInfo: UserInterface.TokenInfo; get getTokenInfo(): UserInterface.TokenInfo { return this.tokenInfo; } get hasToken(): boolean { return this.tokenInfo.hasToken; } get getToken(): UserInterface.Token { return this.token; } constructor( handler: HttpHandler, @Inject('APIConfig') private APIConfig ) { super(handler); } /** -------------------------------- * Standard HTTP requests * -------------------------------- */ public getJson<T>(uri: string): Observable<T> { return super.get<T>(this.getUrl(uri), <HttpOptions>this.getOptions()); } public postJSON<T>(uri: string, data: Object): Observable<T> { return super.post<T>(this.getUrl(uri), data, <HttpOptions>this.getOptions()); } public putJson<T>(uri: string, data: Object): Observable<T> { return super.put<T>(this.getUrl(uri), data, <HttpOptions>this.getOptions()); } public patchJson<T>(uri: string, data: any): Observable<T> { return super.patch<T>(this.getUrl(uri), data, <HttpOptions>this.getOptions()); } public headJson<T>(uri: string): Observable<T> { return super.head<T>(this.getUrl(uri), <HttpOptions>this.getOptions()); } public deleteJson<T>(uri: string): Observable<T> { return super.delete<T>(this.getUrl(uri), <HttpOptions>this.getOptions()); } public optionsJson<T>(uri: string): Observable<T> { return super.options<T>(this.getUrl(uri), <HttpOptions>this.getOptions()); } /** -------------------------------- * Custom HTTP requests * -------------------------------- */ /** * Submit the token form and recover the auth * * @param {UserInterface.Login} data * @returns {Observable<UserInterface.User>} */ public login(data: UserInterface.Login): Observable<UserInterface.Token> { // -->Set: headers let params = new HttpParams(); params = params.append('username', data.username); params = params.append('password', data.password); let headers = new HttpHeaders(); headers = headers.append('Content-Type', 'application/x-www-form-urlencoded'); const options = { headers: headers, params: {}, observe: 'body', reportProgress: true, responseType: 'json', withCredentials: true, }; return super.post<UserInterface.Token>( this.APIConfig.AUTH_API, params, <HttpOptions>options ) .map(token => { // -->Set: token this.token = token; // -->Is: ok? this.tokenInfo = { hasToken: true }; // -->Return: token return token; }); } /** * Prepare request url * * @param {string} uri * @returns {string} */ private getUrl(uri: string): string { return this.APIConfig.API + uri; } /** * Get the HTTP options for the requests * * @returns {HttpOptions} */ private getOptions(data?) { let headers = new HttpHeaders(); headers = headers.append('Authorization', `Bearer ${this.token.access_token}`); const options = { headers: headers, observe: 'body', params: (data) ? new HttpParams({ fromObject: data }) : new HttpParams(), reportProgress: true, responseType: 'json', withCredentials: true }; return options; } }
devantennae786/idexy_custom_webapp
src/app/providers/http/http-client.service.ts
TypeScript
InterfaceDeclaration
export interface HttpOptions { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: 'body'; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }
devantennae786/idexy_custom_webapp
src/app/providers/http/http-client.service.ts
TypeScript
MethodDeclaration
/** -------------------------------- * Standard HTTP requests * -------------------------------- */ public getJson<T>(uri: string): Observable<T> { return super.get<T>(this.getUrl(uri), <HttpOptions>this.getOptions()); }
devantennae786/idexy_custom_webapp
src/app/providers/http/http-client.service.ts
TypeScript
MethodDeclaration
public postJSON<T>(uri: string, data: Object): Observable<T> { return super.post<T>(this.getUrl(uri), data, <HttpOptions>this.getOptions()); }
devantennae786/idexy_custom_webapp
src/app/providers/http/http-client.service.ts
TypeScript
MethodDeclaration
public putJson<T>(uri: string, data: Object): Observable<T> { return super.put<T>(this.getUrl(uri), data, <HttpOptions>this.getOptions()); }
devantennae786/idexy_custom_webapp
src/app/providers/http/http-client.service.ts
TypeScript
MethodDeclaration
public patchJson<T>(uri: string, data: any): Observable<T> { return super.patch<T>(this.getUrl(uri), data, <HttpOptions>this.getOptions()); }
devantennae786/idexy_custom_webapp
src/app/providers/http/http-client.service.ts
TypeScript
MethodDeclaration
public headJson<T>(uri: string): Observable<T> { return super.head<T>(this.getUrl(uri), <HttpOptions>this.getOptions()); }
devantennae786/idexy_custom_webapp
src/app/providers/http/http-client.service.ts
TypeScript
MethodDeclaration
public deleteJson<T>(uri: string): Observable<T> { return super.delete<T>(this.getUrl(uri), <HttpOptions>this.getOptions()); }
devantennae786/idexy_custom_webapp
src/app/providers/http/http-client.service.ts
TypeScript
MethodDeclaration
public optionsJson<T>(uri: string): Observable<T> { return super.options<T>(this.getUrl(uri), <HttpOptions>this.getOptions()); }
devantennae786/idexy_custom_webapp
src/app/providers/http/http-client.service.ts
TypeScript
MethodDeclaration
/** -------------------------------- * Custom HTTP requests * -------------------------------- */ /** * Submit the token form and recover the auth * * @param {UserInterface.Login} data * @returns {Observable<UserInterface.User>} */ public login(data: UserInterface.Login): Observable<UserInterface.Token> { // -->Set: headers let params = new HttpParams(); params = params.append('username', data.username); params = params.append('password', data.password); let headers = new HttpHeaders(); headers = headers.append('Content-Type', 'application/x-www-form-urlencoded'); const options = { headers: headers, params: {}, observe: 'body', reportProgress: true, responseType: 'json', withCredentials: true, }; return super.post<UserInterface.Token>( this.APIConfig.AUTH_API, params, <HttpOptions>options ) .map(token => { // -->Set: token this.token = token; // -->Is: ok? this.tokenInfo = { hasToken: true }; // -->Return: token return token; }); }
devantennae786/idexy_custom_webapp
src/app/providers/http/http-client.service.ts
TypeScript
MethodDeclaration
/** * Prepare request url * * @param {string} uri * @returns {string} */ private getUrl(uri: string): string { return this.APIConfig.API + uri; }
devantennae786/idexy_custom_webapp
src/app/providers/http/http-client.service.ts
TypeScript
MethodDeclaration
/** * Get the HTTP options for the requests * * @returns {HttpOptions} */ private getOptions(data?) { let headers = new HttpHeaders(); headers = headers.append('Authorization', `Bearer ${this.token.access_token}`); const options = { headers: headers, observe: 'body', params: (data) ? new HttpParams({ fromObject: data }) : new HttpParams(), reportProgress: true, responseType: 'json', withCredentials: true }; return options; }
devantennae786/idexy_custom_webapp
src/app/providers/http/http-client.service.ts
TypeScript
ArrowFunction
(id: number): IncrementAction => { return { type: Types.INCREMENT_PROGRESS, payload: id }; }
negibokken/okra
src/store/store.ts
TypeScript
ArrowFunction
(id: number): DecrementAction => { return { type: Types.DECREMENT_PROGRESS, payload: id }; }
negibokken/okra
src/store/store.ts
TypeScript
ArrowFunction
(state: AppState = initialState, action: AppActions) => { console.log(`[#${action.type}]`); switch (action.type) { case Types.INCREMENT_PROGRESS: { const okr = { ...state.okr }; const keyResults = [...okr.keyResults]; const idx = keyResults.findIndex((i) => i.id === action.payload); if (idx !== -1) { if (keyResults[idx].completedTasks < keyResults[idx].totalTasks) keyResults[idx].completedTasks++; } okr.keyResults = keyResults; return { ...state, okr }; } case Types.DECREMENT_PROGRESS: { const okr = { ...state.okr }; const keyResults = [...okr.keyResults]; const idx = keyResults.findIndex((i) => i.id === action.payload); if (idx !== -1) { if (keyResults[idx].completedTasks > 0) keyResults[idx].completedTasks--; } okr.keyResults = keyResults; return { ...state, okr }; } default: { return state; } } }
negibokken/okra
src/store/store.ts
TypeScript
ArrowFunction
(i) => i.id === action.payload
negibokken/okra
src/store/store.ts
TypeScript
InterfaceDeclaration
export interface KeyResult { id: number; title: string; totalTasks: number; completedTasks: number; }
negibokken/okra
src/store/store.ts
TypeScript
InterfaceDeclaration
export interface AtomicOKR { id: number; objective: string; description: string; keyResults: KeyResult[]; }
negibokken/okra
src/store/store.ts
TypeScript
InterfaceDeclaration
export interface AppState { okr: AtomicOKR; }
negibokken/okra
src/store/store.ts
TypeScript
EnumDeclaration
export enum Types { INCREMENT_PROGRESS = 'INCREMENT_PROGRESS', DECREMENT_PROGRESS = 'DECREMENT_PROGRESS', }
negibokken/okra
src/store/store.ts
TypeScript
TypeAliasDeclaration
type IncrementAction = { type: Types.INCREMENT_PROGRESS; payload: number };
negibokken/okra
src/store/store.ts
TypeScript
TypeAliasDeclaration
type DecrementAction = { type: Types.DECREMENT_PROGRESS; payload: number };
negibokken/okra
src/store/store.ts
TypeScript
TypeAliasDeclaration
type AppActions = IncrementAction | DecrementAction;
negibokken/okra
src/store/store.ts
TypeScript
ArrowFunction
() => { const ShowStat = () => { return ( <> <Column> <Row>Stat</Row> </Column> </> ) } return ( <Page> <ShowcaseHeader title="Stat" description={` Show data in a number or a graphical visual. `}
atelier-saulx/aviato
apps/docs/pages/data-display/stat.tsx
TypeScript
ArrowFunction
() => { return ( <> <Column> <Row>Stat</Row> </Column> </> ) }
atelier-saulx/aviato
apps/docs/pages/data-display/stat.tsx
TypeScript
ArrowFunction
(transformType) => { if (transformType === 'trim') { value = value.trim(); } else if (transformType === 'toLowerCase') { value = value.toLowerCase(); } else if (transformType === 'toUpperCase') { value = value.toUpperCase(); } }
Too-Tao/drip-table
packages/drip-table-generator/src/components/CustomForm/components/input/index.tsx
TypeScript
ArrowFunction
(msg) => { this.props.onValidate?.(msg); return msg; }
Too-Tao/drip-table
packages/drip-table-generator/src/components/CustomForm/components/input/index.tsx
TypeScript
ArrowFunction
(error) => { throw error; }
Too-Tao/drip-table
packages/drip-table-generator/src/components/CustomForm/components/input/index.tsx
TypeScript
ClassDeclaration
export default class InputComponent extends React.PureComponent<Props> { public static componentName = 'input'; private transform(value: string) { const transform = (this.props.schema as StringDataSchema).transform; if (transform) { transform.forEach((transformType) => { if (transformType === 'trim') { value = value.trim(); } else if (transformType === 'toLowerCase') { value = value.toLowerCase(); } else if (transformType === 'toUpperCase') { value = value.toUpperCase(); } }); } return value; } public render() { const config = this.props.schema; const uiProps = this.props.schema['ui:props'] || {}; return ( <Input {...uiProps} value={this.props.value as string} placeholder={uiProps.placeholder as string} disabled={uiProps.disabled as boolean} style={{ width: 420, ...uiProps.style }} onChange={(e) =>
Too-Tao/drip-table
packages/drip-table-generator/src/components/CustomForm/components/input/index.tsx
TypeScript
InterfaceDeclaration
interface Props { schema: DTGComponentPropertySchema; value?: string; onChange?: (value: string) => void; onValidate?: (errorMessage: string) => void; }
Too-Tao/drip-table
packages/drip-table-generator/src/components/CustomForm/components/input/index.tsx
TypeScript
MethodDeclaration
private transform(value: string) { const transform = (this.props.schema as StringDataSchema).transform; if (transform) { transform.forEach((transformType) => { if (transformType === 'trim') { value = value.trim(); } else if (transformType === 'toLowerCase') { value = value.toLowerCase(); } else if (transformType === 'toUpperCase') { value = value.toUpperCase(); } }); } return value; }
Too-Tao/drip-table
packages/drip-table-generator/src/components/CustomForm/components/input/index.tsx
TypeScript
MethodDeclaration
public render() { const config = this.props.schema; const uiProps = this.props.schema['ui:props'] || {}; return ( <Input {...uiProps} value={this.props.value as string} placeholder={uiProps.placeholder as string} disabled={uiProps.disabled as boolean} style={{ width: 420, ...uiProps.style }}
Too-Tao/drip-table
packages/drip-table-generator/src/components/CustomForm/components/input/index.tsx
TypeScript
ArrowFunction
(_testName, C, domTarget) => { const Component = C as InteractiveType const prefix = domTarget ? 'dom-' : '' const { getByTestId, rerender } = render(<Component gestures={['Hover']} />) const element = getByTestId(`${prefix}hover-el`) test('mouseEnter should initiate hover', () => { fireEvent.mouseEnter(element, { clientX: 10, clientY: 20 }) expect(getByTestId(`${prefix}hover-hovering`)).toHaveTextContent('true') expect(getByTestId(`${prefix}hover-xy`)).toHaveTextContent('10,20') }) test('mouseLeave should terminate hover', () => { fireEvent.mouseLeave(element, { clientX: 20, clientY: 40 }) expect(getByTestId(`${prefix}hover-hovering`)).toHaveTextContent('false') expect(getByTestId(`${prefix}hover-xy`)).toHaveTextContent('20,40') }) test('disabling all gestures should prevent state from updating', () => { rerender(<Component gestures={['Hover']} config={{ enabled: false }} />) fireEvent.mouseEnter(element) expect(getByTestId(`${prefix}hover-hovering`)).toHaveTextContent('false') }
Ding-Fan/react-use-gesture
test/Hover.test.tsx
TypeScript
ArrowFunction
() => { fireEvent.mouseEnter(element, { clientX: 10, clientY: 20 }) expect(getByTestId(`${prefix}hover-hovering`)).toHaveTextContent('true') expect(getByTestId(`${prefix}hover-xy`)).toHaveTextContent('10,20') }
Ding-Fan/react-use-gesture
test/Hover.test.tsx
TypeScript
ArrowFunction
() => { fireEvent.mouseLeave(element, { clientX: 20, clientY: 40 }) expect(getByTestId(`${prefix}hover-hovering`)).toHaveTextContent('false') expect(getByTestId(`${prefix}hover-xy`)).toHaveTextContent('20,40') }
Ding-Fan/react-use-gesture
test/Hover.test.tsx
TypeScript
ArrowFunction
() => { rerender(<Component gestures={['Hover']} config={{ enabled: false }}
Ding-Fan/react-use-gesture
test/Hover.test.tsx
TypeScript
ArrowFunction
() => { rerender(<Component gestures={['Hover']} config={{ hover: { enabled: false } }}
Ding-Fan/react-use-gesture
test/Hover.test.tsx
TypeScript
ArrowFunction
() => { // registerでバリデーション // errorsでバリデーションエラーのハンドリング // handleSubmitで送信 const { register, errors, handleSubmit, watch } = useForm<Inputs>({ // 初回バリデーションのタイミング(mode)をonBlurに設定 mode: "onBlur" }); // 投稿画像のstateを設定 const [photos, setPhotos] = useState<File[]>([]); const [address, setAddress] = useState(""); const [show, setShow] = useState(false); // const modalOn = () => setShow(true); const onSubmit = async (data: Inputs): Promise<void> => { console.log(data); const { name, comment, tags} = data; if ( name === "" && comment === "" && tags === "" && photos.length === 0 ) { // アンケートフォームが空の場合はPOSTしない return; } // 画像を送信できるようにFormDataに変換する const formData = new FormData(); // appendでformDataにキーと値を追加 formData.append("name", name); formData.append("comment", comment); formData.append("address", address); formData.append("tags", tags); const compressOptions = { // 3MB以下に圧縮する maxSizeMB: 3, }; // Promise.all で 非同期処理を実行し値を代入 const compressedPhotoData = await Promise.all( // 一枚一枚の順番を変えないため改めてasyncで処理をハンドリング photos.map(async (photo) => { return { blob: await imageCompression(photo, compressOptions) }; }) ); // console.log(compressedPhotoData); for (let i = 0; i < compressedPhotoData.length; i++){ formData.append("place_image_" + i, compressedPhotoData[i].blob, ); } // 以下 一枚の写真しか送れなかったもの // forEachで圧縮した写真データphotoDataとして渡し一つずつformDataに入れる // compressedPhotoData.forEach((photoData) => { // formData.append("place_image", photoData.blob, photoData.name); // }); console.log(...formData.entries()); // axiosの記述方法 postメソッドを使わないやり方で記述 axios({ // php側のstoreメソッドのルートのurl url: "/place", method: "post", data: formData, // formの送信時のenctype headers: { "content-type": "multipart/form-data", }, }) .then(() => { // ここにモーダルコンポーネント setShow(true); }) .catch(() => { alert("エラーが発生しました。"); }); }; // スタイル const useStyles = makeStyles(() => createStyles({ "dataContainer": { borderColor: 'red' }, "photoUpload": { }, "AddressUpload": {}, "tagsUpload": {}, "button": { } })) const classes = useStyles(); // html return ( <> <form onSubmit={handleSubmit(onSubmit)}> <div className={classes.dataContainer}> <label>場所の名前</label> <input name="name" // refのなかにバリデーションルールを記述 ref={register({required : true, maxLength: 30 })} // error={errors.name !== undefined} /> {errors.address && <span>文字数は最大30文字です</span>} <label>コメント</label> <input name="comment" ref={register({ required: true, maxLength: 200 })} /> {errors.comment && <span>文字数は最大200文字です</span>} </div> <div className={classes.AddressUpload}> {/* PostalCodeで値を紐付ける必要がある */} <PostalCode name="address" address={address} setAddress={setAddress} /> </div> <div className={classes.photoUpload}> {/* propsでphotosのstateをわたす */} <PhotosUpload name="photos" photos={photos} setPhotos={setPhotos} /> </div> <div className={classes.tagsUpload}> <label>タグ</label> <input name="tags" ref={register()} /> </div> <div> <input type="submit" /> </div> <div className={classes.button}> {/* <button disabled={ } /> */} </div> </form> <NewModal show={show} /> </>
mxxxnxxx/laravel.pressplace
.history/resources/ts/components/PlaceForm_20210320134537.tsx
TypeScript
ArrowFunction
async (data: Inputs): Promise<void> => { console.log(data); const { name, comment, tags} = data; if ( name === "" && comment === "" && tags === "" && photos.length === 0 ) { // アンケートフォームが空の場合はPOSTしない return; } // 画像を送信できるようにFormDataに変換する const formData = new FormData(); // appendでformDataにキーと値を追加 formData.append("name", name); formData.append("comment", comment); formData.append("address", address); formData.append("tags", tags); const compressOptions = { // 3MB以下に圧縮する maxSizeMB: 3, }; // Promise.all で 非同期処理を実行し値を代入 const compressedPhotoData = await Promise.all( // 一枚一枚の順番を変えないため改めてasyncで処理をハンドリング photos.map(async (photo) => { return { blob: await imageCompression(photo, compressOptions) }; }) ); // console.log(compressedPhotoData); for (let i = 0; i < compressedPhotoData.length; i++){ formData.append("place_image_" + i, compressedPhotoData[i].blob, ); } // 以下 一枚の写真しか送れなかったもの // forEachで圧縮した写真データphotoDataとして渡し一つずつformDataに入れる // compressedPhotoData.forEach((photoData) => { // formData.append("place_image", photoData.blob, photoData.name); // }); console.log(...formData.entries()); // axiosの記述方法 postメソッドを使わないやり方で記述 axios({ // php側のstoreメソッドのルートのurl url: "/place", method: "post", data: formData, // formの送信時のenctype headers: { "content-type": "multipart/form-data", }, }) .then(() => { // ここにモーダルコンポーネント setShow(true); }) .catch(() => { alert("エラーが発生しました。"); }); }
mxxxnxxx/laravel.pressplace
.history/resources/ts/components/PlaceForm_20210320134537.tsx
TypeScript
ArrowFunction
async (photo) => { return { blob: await imageCompression(photo, compressOptions) }; }
mxxxnxxx/laravel.pressplace
.history/resources/ts/components/PlaceForm_20210320134537.tsx
TypeScript
ArrowFunction
() => { // ここにモーダルコンポーネント setShow(true); }
mxxxnxxx/laravel.pressplace
.history/resources/ts/components/PlaceForm_20210320134537.tsx
TypeScript
ArrowFunction
() => { alert("エラーが発生しました。"); }
mxxxnxxx/laravel.pressplace
.history/resources/ts/components/PlaceForm_20210320134537.tsx
TypeScript
ArrowFunction
() => createStyles({ "dataContainer": { borderColor: 'red' }, "photoUpload": { }, "AddressUpload": {}, "tagsUpload": {}, "button": { } })
mxxxnxxx/laravel.pressplace
.history/resources/ts/components/PlaceForm_20210320134537.tsx
TypeScript
InterfaceDeclaration
// 型定義 interface Inputs { name: string; comment: string; address: string; tags: string; }
mxxxnxxx/laravel.pressplace
.history/resources/ts/components/PlaceForm_20210320134537.tsx
TypeScript
MethodDeclaration
register({required : true, maxLength: 30 })
mxxxnxxx/laravel.pressplace
.history/resources/ts/components/PlaceForm_20210320134537.tsx
TypeScript
MethodDeclaration
register({ required: true, maxLength: 200 })
mxxxnxxx/laravel.pressplace
.history/resources/ts/components/PlaceForm_20210320134537.tsx
TypeScript
MethodDeclaration
register()
mxxxnxxx/laravel.pressplace
.history/resources/ts/components/PlaceForm_20210320134537.tsx
TypeScript
InterfaceDeclaration
// Extend the generic Workflow interface to check that Example is a valid workflow interface // Workflow interfaces are useful for generating type safe workflow clients export interface Example extends Workflow { main(name: string): Promise<string>; }
gdw2/sdk-node
packages/create-project/samples/interface.ts
TypeScript
FunctionDeclaration
async function timeOut(message: string, timeout: number): Promise<void> { return new Promise((resolve, reject) => { const timer = setTimeout(() => reject(`${message} Timeout after ${timeout}ms`), timeout); timer.unref(); }); }
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
FunctionDeclaration
function getJson<T>(s: string): T | null { try { return JSON.parse(s); } catch (e) { return null; } }
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
ArrowFunction
(resolve, reject) => { const timer = setTimeout(() => reject(`${message} Timeout after ${timeout}ms`), timeout); timer.unref(); }
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
ArrowFunction
() => reject(`${message} Timeout after ${timeout}ms`)
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
ArrowFunction
async (resolve) => { const process = spawn(WineCommand, args, { cwd }); if (process == null || process.stdout == null) throw new Error('Failed to start command'); this.process = process; process.stderr.on('data', (data) => { Log.debug({ data: data.toString().trim() }, 'MapProcess:stderr'); }); process.on('error', (error) => { log.fatal({ error }, 'ProcessDied'); inter.close(); this.process = null; }); process.on('close', (exitCode) => { inter.close(); this.process = null; if (exitCode == null) return; if (exitCode > 0) log.fatal({ exitCode }, 'ProcessClosed'); }); log.info({ pid: process.pid }, 'MapProcessStarted'); const inter = createInterface(process.stdout).on('line', (line) => { const json = getJson<Diablo2MapGenMessage | LogMessage>(line); if (json == null) return; if ('time' in json) { if (json.level < 30) return; Log.info({ ...json, log: json.msg }, 'SubProcess'); } else if (json.type) this.events.emit(json.type, json); }); await this.once('init'); resolve(); }
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
ArrowFunction
(data) => { Log.debug({ data: data.toString().trim() }, 'MapProcess:stderr'); }
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
ArrowFunction
(error) => { log.fatal({ error }, 'ProcessDied'); inter.close(); this.process = null; }
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
ArrowFunction
(exitCode) => { inter.close(); this.process = null; if (exitCode == null) return; if (exitCode > 0) log.fatal({ exitCode }, 'ProcessClosed'); }
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
ArrowFunction
(line) => { const json = getJson<Diablo2MapGenMessage | LogMessage>(line); if (json == null) return; if ('time' in json) { if (json.level < 30) return; Log.info({ ...json, log: json.msg }, 'SubProcess'); } else if (json.type) this.events.emit(json.type, json); }
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
ArrowFunction
(resolve) => { this.events.once(e, (data) => resolve(data)); cb?.(); }
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
ArrowFunction
(data) => resolve(data)
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
ArrowFunction
() => this.process?.stdin?.write(command)
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
ArrowFunction
async () => { const mapResult = await this.getMaps(seed, difficulty, log); this.cache.set(mapKey, mapResult); return mapResult; }
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
ArrowFunction
(msg: MapGenMessageMap): void => { log.trace({ mapId: msg.id }, 'GotMap'); maps[msg.id] = msg; }
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
ArrowFunction
(resolve, reject) => { const failedTimer = setTimeout(() => { this.events.off('map', newMap); reject(); }, ProcessTimeout); this.events.on('map', newMap); this.events.on('done', () => { this.events.off('map', newMap); clearTimeout(failedTimer); log.trace({ count: Object.keys(maps).length }, 'MapsGenerated'); resolve(maps); }); this.process?.stdin?.write(`$map\n`); }
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
ArrowFunction
() => { this.events.off('map', newMap); reject(); }
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
ArrowFunction
() => { this.events.off('map', newMap); clearTimeout(failedTimer); log.trace({ count: Object.keys(maps).length }, 'MapsGenerated'); resolve(maps); }
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
ClassDeclaration
export class Diablo2MapProcess { cache: LruCache<Diablo2MapResponse> = new LruCache(100); process: ChildProcess | null; /** Number of maps generated by this process */ generatedCount = 0; events: EventEmitter = new EventEmitter(); /** * Limit the map generation to a single thread * TODO having a pool of these map processes would be quite nice */ q = PLimit(1); /** Get the version of WINE that is being used */ async version(log: LogType): Promise<string> { const versionResponse = spawnSync(WineCommand, ['--version']); const version = versionResponse.stdout.toString().trim(); log.info({ version, command: WineCommand }, 'WineVersion'); return version; } /** Start the map process waiting for the `init` event before allowing anything to continue */ async start(log: LogType): Promise<void> { if (this.process != null) { Log.warn({ pid: this.process.pid }, 'MapProcess already started'); return; } this.generatedCount = 0; const res = spawnSync(WineCommand, ['regedit', RegistryPath]); log.info({ data: res.stdout.toString() }, 'RegistryUpdate'); // const gamePath = await this.getGamePath(); const args = [MapCommand, Diablo2Path]; log.info({ wineArgs: args }, 'Starting MapProcess'); return new Promise(async (resolve) => { const process = spawn(WineCommand, args, { cwd }); if (process == null || process.stdout == null) throw new Error('Failed to start command'); this.process = process; process.stderr.on('data', (data) => { Log.debug({ data: data.toString().trim() }, 'MapProcess:stderr'); }); process.on('error', (error) => { log.fatal({ error }, 'ProcessDied'); inter.close(); this.process = null; }); process.on('close', (exitCode) => { inter.close(); this.process = null; if (exitCode == null) return; if (exitCode > 0) log.fatal({ exitCode }, 'ProcessClosed'); }); log.info({ pid: process.pid }, 'MapProcessStarted'); const inter = createInterface(process.stdout).on('line', (line) => { const json = getJson<Diablo2MapGenMessage | LogMessage>(line); if (json == null) return; if ('time' in json) { if (json.level < 30) return; Log.info({ ...json, log: json.msg }, 'SubProcess'); } else if (json.type) this.events.emit(json.type, json); }); await this.once('init'); resolve(); }); } async once<T extends Diablo2MapGenMessage>(e: T['type'], cb?: () => void): Promise<T> { return Promise.race([ new Promise((resolve) => { this.events.once(e, (data) => resolve(data)); cb?.(); }), timeOut(`Event: ${e}`, ProcessTimeout), ]) as Promise<T>; } async stop(log: LogType): Promise<void> { if (this.process == null) return; log.info({ pid: this.process.pid }, 'StoppingProcess'); this.process.kill('SIGKILL'); this.process = null; } async command(cmd: 'seed' | 'difficulty', value: number, log: LogType): Promise<void> { if (this.process == null) await this.start(log); log.info({ cmd, value }, 'Command'); const command = `$${cmd} ${value}\n`; const res = await this.once<MapGenMessageInfo>('info', () => this.process?.stdin?.write(command)); if (res[cmd] !== value) throw new Error(`Failed to set ${cmd}=${value} (output: ${JSON.stringify(res)}: ${command})`); } map(seed: number, difficulty: number, log: LogType): Promise<Diablo2MapResponse> { const mapKey = `${seed}_${difficulty}`; const cacheData = this.cache.get(mapKey); if (cacheData != null) return Promise.resolve(cacheData); return this.q(async () => { const mapResult = await this.getMaps(seed, difficulty, log); this.cache.set(mapKey, mapResult); return mapResult; }); } private async getMaps(seed: number, difficulty: number, log: LogType): Promise<Diablo2MapResponse> { if (this.generatedCount > MaxMapsToGenerate) { this.generatedCount = 0; await this.stop(log); await this.start(log); } await this.command('seed', seed, log); await this.command('difficulty', difficulty, log); this.generatedCount++; log.info({ seed, difficulty, generated: this.generatedCount }, 'GenerateMap'); const maps: Record<string, Diablo2Map> = {}; const newMap = (msg: MapGenMessageMap): void => { log.trace({ mapId: msg.id }, 'GotMap'); maps[msg.id] = msg; }; return await new Promise((resolve, reject) => { const failedTimer = setTimeout(() => { this.events.off('map', newMap); reject(); }, ProcessTimeout); this.events.on('map', newMap); this.events.on('done', () => { this.events.off('map', newMap); clearTimeout(failedTimer); log.trace({ count: Object.keys(maps).length }, 'MapsGenerated'); resolve(maps); }); this.process?.stdin?.write(`$map\n`); }); } }
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
InterfaceDeclaration
interface LogMessage { time: number; level: number; msg: string; }
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
TypeAliasDeclaration
export type Diablo2MapResponse = { [key: string]: Diablo2Map };
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
MethodDeclaration
/** Get the version of WINE that is being used */ async version(log: LogType): Promise<string> { const versionResponse = spawnSync(WineCommand, ['--version']); const version = versionResponse.stdout.toString().trim(); log.info({ version, command: WineCommand }, 'WineVersion'); return version; }
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
MethodDeclaration
/** Start the map process waiting for the `init` event before allowing anything to continue */ async start(log: LogType): Promise<void> { if (this.process != null) { Log.warn({ pid: this.process.pid }, 'MapProcess already started'); return; } this.generatedCount = 0; const res = spawnSync(WineCommand, ['regedit', RegistryPath]); log.info({ data: res.stdout.toString() }, 'RegistryUpdate'); // const gamePath = await this.getGamePath(); const args = [MapCommand, Diablo2Path]; log.info({ wineArgs: args }, 'Starting MapProcess'); return new Promise(async (resolve) => { const process = spawn(WineCommand, args, { cwd }); if (process == null || process.stdout == null) throw new Error('Failed to start command'); this.process = process; process.stderr.on('data', (data) => { Log.debug({ data: data.toString().trim() }, 'MapProcess:stderr'); }); process.on('error', (error) => { log.fatal({ error }, 'ProcessDied'); inter.close(); this.process = null; }); process.on('close', (exitCode) => { inter.close(); this.process = null; if (exitCode == null) return; if (exitCode > 0) log.fatal({ exitCode }, 'ProcessClosed'); }); log.info({ pid: process.pid }, 'MapProcessStarted'); const inter = createInterface(process.stdout).on('line', (line) => { const json = getJson<Diablo2MapGenMessage | LogMessage>(line); if (json == null) return; if ('time' in json) { if (json.level < 30) return; Log.info({ ...json, log: json.msg }, 'SubProcess'); } else if (json.type) this.events.emit(json.type, json); }); await this.once('init'); resolve(); }); }
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
MethodDeclaration
async once<T extends Diablo2MapGenMessage>(e: T['type'], cb?: () => void): Promise<T> { return Promise.race([ new Promise((resolve) => { this.events.once(e, (data) => resolve(data)); cb?.(); }), timeOut(`Event: ${e}`, ProcessTimeout), ]) as Promise<T>; }
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
MethodDeclaration
async stop(log: LogType): Promise<void> { if (this.process == null) return; log.info({ pid: this.process.pid }, 'StoppingProcess'); this.process.kill('SIGKILL'); this.process = null; }
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
MethodDeclaration
async command(cmd: 'seed' | 'difficulty', value: number, log: LogType): Promise<void> { if (this.process == null) await this.start(log); log.info({ cmd, value }, 'Command'); const command = `$${cmd} ${value}\n`; const res = await this.once<MapGenMessageInfo>('info', () => this.process?.stdin?.write(command)); if (res[cmd] !== value) throw new Error(`Failed to set ${cmd}=${value} (output: ${JSON.stringify(res)}: ${command})`); }
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
MethodDeclaration
map(seed: number, difficulty: number, log: LogType): Promise<Diablo2MapResponse> { const mapKey = `${seed}_${difficulty}`; const cacheData = this.cache.get(mapKey); if (cacheData != null) return Promise.resolve(cacheData); return this.q(async () => { const mapResult = await this.getMaps(seed, difficulty, log); this.cache.set(mapKey, mapResult); return mapResult; }); }
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
MethodDeclaration
private async getMaps(seed: number, difficulty: number, log: LogType): Promise<Diablo2MapResponse> { if (this.generatedCount > MaxMapsToGenerate) { this.generatedCount = 0; await this.stop(log); await this.start(log); } await this.command('seed', seed, log); await this.command('difficulty', difficulty, log); this.generatedCount++; log.info({ seed, difficulty, generated: this.generatedCount }, 'GenerateMap'); const maps: Record<string, Diablo2Map> = {}; const newMap = (msg: MapGenMessageMap): void => { log.trace({ mapId: msg.id }, 'GotMap'); maps[msg.id] = msg; }; return await new Promise((resolve, reject) => { const failedTimer = setTimeout(() => { this.events.off('map', newMap); reject(); }, ProcessTimeout); this.events.on('map', newMap); this.events.on('done', () => { this.events.off('map', newMap); clearTimeout(failedTimer); log.trace({ count: Object.keys(maps).length }, 'MapsGenerated'); resolve(maps); }); this.process?.stdin?.write(`$map\n`); }); }
deeean/diablo2
packages/map/src/map/map.process.ts
TypeScript
FunctionDeclaration
export default function PostIframe(value: any) { console.error('PostIframe', value) return <iframe width={680} src={value.src} frameBorder="0" allowFullScreen/> }
BaryshevRS/ubuntunews.ru
components/post/post-iframe.tsx
TypeScript
InterfaceDeclaration
export interface IProps { children: React.ReactChild href: string; }
BaryshevRS/ubuntunews.ru
components/post/post-iframe.tsx
TypeScript
ArrowFunction
() => { let component: GettingStartedComponent; let fixture: ComponentFixture<GettingStartedComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [GettingStartedComponent] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(GettingStartedComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }
AnthonyNahas/ngx-storage-firebaseui
src/app/getting-started/getting-started.component.spec.ts
TypeScript
ArrowFunction
() => { TestBed.configureTestingModule({ declarations: [GettingStartedComponent] }) .compileComponents(); }
AnthonyNahas/ngx-storage-firebaseui
src/app/getting-started/getting-started.component.spec.ts
TypeScript
ArrowFunction
() => { fixture = TestBed.createComponent(GettingStartedComponent); component = fixture.componentInstance; fixture.detectChanges(); }
AnthonyNahas/ngx-storage-firebaseui
src/app/getting-started/getting-started.component.spec.ts
TypeScript
FunctionDeclaration
/** * TODO: Implement this component */ function AppBarSection({ item }: { item: LandingBarItem }): JSX.Element { return <div className="inline-block p-4 font-bold">{item}</div>; }
UTDNebula/planner
components/landing/AppBar.tsx
TypeScript