type
stringclasses 7
values | content
stringlengths 4
9.55k
| repo
stringlengths 7
96
| path
stringlengths 4
178
| language
stringclasses 1
value |
|---|---|---|---|---|
ClassDeclaration
|
@Component({
selector: 'datatable-row-wrapper',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div *ngIf="groupHeader && groupHeader.template" class="datatable-group-header" [ngStyle]="getGroupHeaderStyle()">
<ng-template
*ngIf="groupHeader && groupHeader.template"
[ngTemplateOutlet]="groupHeader.template"
[ngTemplateOutletContext]="groupContext"
>
</ng-template>
</div>
<ng-content *ngIf="(groupHeader && groupHeader.template && expanded) || (!groupHeader || !groupHeader.template)">
</ng-content>
<div
*ngIf="rowDetail && rowDetail.template && expanded"
[style.height.px]="detailRowHeight"
class="datatable-row-detail"
>
<ng-template
*ngIf="rowDetail && rowDetail.template"
[ngTemplateOutlet]="rowDetail.template"
[ngTemplateOutletContext]="rowContext"
>
</ng-template>
</div>
`,
host: {
class: 'datatable-row-wrapper'
}
})
export class DataTableRowWrapperComponent implements OnChanges {
@Input() innerWidth: number;
@Input() rowDetail: any;
@Input() groupHeader: any;
@Input() offsetX: number;
@Input() detailRowHeight: any;
@Input() row: any;
@Input() groupedRows: any;
@Output() rowContextmenu = new EventEmitter<{ event: MouseEvent; row: any }>(false);
@Input() set rowIndex(val: number) {
this._rowIndex = val;
this.rowContext.rowIndex = val;
this.groupContext.rowIndex = val;
this.cd.markForCheck();
}
get rowIndex(): number {
return this._rowIndex;
}
@Input() set expanded(val: boolean) {
this._expanded = val;
this.groupContext.expanded = val;
this.rowContext.expanded = val;
this.cd.markForCheck();
}
get expanded(): boolean {
return this._expanded;
}
groupContext: any = {
group: this.row,
expanded: this.expanded,
rowIndex: this.rowIndex
};
rowContext: any = {
row: this.row,
expanded: this.expanded,
rowIndex: this.rowIndex
};
private _expanded: boolean = false;
private _rowIndex: number;
constructor(private cd: ChangeDetectorRef) {
}
ngOnChanges({ row: rowChange }: SimpleChanges): void {
if (rowChange) {
this.rowContext.row = this.row;
this.groupContext.group = this.row;
this.cd.markForCheck();
}
}
@HostListener('contextmenu', ['$event'])
onContextmenu($event: MouseEvent): void {
this.rowContextmenu.emit({ event: $event, row: this.row });
}
getGroupHeaderStyle(): any {
const styles = {};
styles['transform'] = 'translate3d(' + this.offsetX + 'px, 0px, 0px)';
styles['backface-visibility'] = 'hidden';
styles['width'] = this.innerWidth;
return styles;
}
}
|
sst-lending/ngx-datatable
|
projects/swimlane/ngx-datatable/src/lib/components/body/body-row-wrapper.component.ts
|
TypeScript
|
MethodDeclaration
|
ngOnChanges({ row: rowChange }: SimpleChanges): void {
if (rowChange) {
this.rowContext.row = this.row;
this.groupContext.group = this.row;
this.cd.markForCheck();
}
}
|
sst-lending/ngx-datatable
|
projects/swimlane/ngx-datatable/src/lib/components/body/body-row-wrapper.component.ts
|
TypeScript
|
MethodDeclaration
|
@HostListener('contextmenu', ['$event'])
onContextmenu($event: MouseEvent): void {
this.rowContextmenu.emit({ event: $event, row: this.row });
}
|
sst-lending/ngx-datatable
|
projects/swimlane/ngx-datatable/src/lib/components/body/body-row-wrapper.component.ts
|
TypeScript
|
MethodDeclaration
|
getGroupHeaderStyle(): any {
const styles = {};
styles['transform'] = 'translate3d(' + this.offsetX + 'px, 0px, 0px)';
styles['backface-visibility'] = 'hidden';
styles['width'] = this.innerWidth;
return styles;
}
|
sst-lending/ngx-datatable
|
projects/swimlane/ngx-datatable/src/lib/components/body/body-row-wrapper.component.ts
|
TypeScript
|
ArrowFunction
|
() => {
actions.operators = {
...actions.operators,
getCSV: jest.fn(),
getResource: jest.fn(),
};
const mockDispatch = jest.fn(res => res);
spyOnUseDispatch = jest.spyOn(ReactRedux, "useDispatch").mockReturnValue(mockDispatch);
}
|
faraz891/kubeapps
|
dashboard/src/components/OperatorInstanceUpdateForm/OperatorInstanceUpdateForm.v2.test.tsx
|
TypeScript
|
ArrowFunction
|
res => res
|
faraz891/kubeapps
|
dashboard/src/components/OperatorInstanceUpdateForm/OperatorInstanceUpdateForm.v2.test.tsx
|
TypeScript
|
ArrowFunction
|
() => {
actions.operators = { ...kubeaActions };
spyOnUseDispatch.mockRestore();
}
|
faraz891/kubeapps
|
dashboard/src/components/OperatorInstanceUpdateForm/OperatorInstanceUpdateForm.v2.test.tsx
|
TypeScript
|
ArrowFunction
|
() => {
const props = { ...defaultProps, cluster: "other-cluster" };
const wrapper = mountWrapper(defaultStore, <OperatorInstanceUpdateForm {...props} />);
expect(wrapper.find(OperatorNotSupported)).toExist();
}
|
faraz891/kubeapps
|
dashboard/src/components/OperatorInstanceUpdateForm/OperatorInstanceUpdateForm.v2.test.tsx
|
TypeScript
|
ArrowFunction
|
() => {
const getResource = jest.fn();
const getCSV = jest.fn();
actions.operators.getResource = getResource;
actions.operators.getCSV = getCSV;
mountWrapper(defaultStore, <OperatorInstanceUpdateForm {...defaultProps} />);
expect(getCSV).toHaveBeenCalledWith(
defaultProps.cluster,
defaultProps.namespace,
defaultProps.csvName,
);
expect(getResource).toHaveBeenCalledWith(
defaultProps.cluster,
defaultProps.namespace,
defaultProps.csvName,
defaultProps.crdName,
defaultProps.resourceName,
);
}
|
faraz891/kubeapps
|
dashboard/src/components/OperatorInstanceUpdateForm/OperatorInstanceUpdateForm.v2.test.tsx
|
TypeScript
|
ArrowFunction
|
() => {
const wrapper = mountWrapper(
getStore({
operators: {
resource: defaultResource,
csv: defaultCSV,
},
}),
<OperatorInstanceUpdateForm {...defaultProps} />,
);
expect(wrapper.find(OperatorInstanceFormBody).props()).toMatchObject({
defaultValues: "kind: Foo\napiVersion: v1\n",
deployedValues: "kind: Foo\napiVersion: v1\nmetadata:\n name: my-foo\n",
});
}
|
faraz891/kubeapps
|
dashboard/src/components/OperatorInstanceUpdateForm/OperatorInstanceUpdateForm.v2.test.tsx
|
TypeScript
|
ArrowFunction
|
() => {
const wrapper = mountWrapper(defaultStore, <OperatorInstanceUpdateForm {...defaultProps} />);
expect(wrapper.find(Alert)).toIncludeText("Resource my-foo not found");
}
|
faraz891/kubeapps
|
dashboard/src/components/OperatorInstanceUpdateForm/OperatorInstanceUpdateForm.v2.test.tsx
|
TypeScript
|
ArrowFunction
|
() => {
const updateResource = jest.fn();
actions.operators.updateResource = updateResource;
const wrapper = mountWrapper(
getStore({
operators: {
resource: defaultResource,
csv: defaultCSV,
},
}),
<OperatorInstanceUpdateForm {...defaultProps} />,
);
const form = wrapper.find("form");
form.simulate("submit", { preventDefault: jest.fn() });
expect(updateResource).toHaveBeenCalledWith(
defaultProps.cluster,
defaultProps.namespace,
defaultResource.apiVersion,
defaultProps.crdName,
defaultProps.resourceName,
defaultResource,
);
}
|
faraz891/kubeapps
|
dashboard/src/components/OperatorInstanceUpdateForm/OperatorInstanceUpdateForm.v2.test.tsx
|
TypeScript
|
ArrowFunction
|
(howMany: number, word: string) => {
return `${howMany} ${pluralize(word, howMany)}`;
}
|
ceres23/api-oas-checker-action
|
src/utils.ts
|
TypeScript
|
ClassDeclaration
|
@Injectable()
export class AuthService {
constructor(private readonly configService: ConfigService) {
const mongoConStr = this.configService.get<string>('MONGODB_WRITE_CONNECTHION_STRING')
console.log(mongoConStr)
}
}
|
artyrkozel/nest
|
src/auth/auth.service.ts
|
TypeScript
|
ClassDeclaration
|
@Injectable()
export class StudentService {
products = [
{ id: 1, name: 'One Plus 7', price: 48000 },
{ id: 2, name: 'I Phone X', price: 64999 },
];
constructor(@InjectModel('Student') private studentRepository:Model<student>){}
getData()
{
return this.products;
}
async addCustomer(createCustomerDTO): Promise<student> {
const newCustomer = await this.studentRepository.create(createCustomerDTO)
return newCustomer;
}
}
|
wizba/training
|
src/student/student/student.service.ts
|
TypeScript
|
MethodDeclaration
|
getData()
{
return this.products;
}
|
wizba/training
|
src/student/student/student.service.ts
|
TypeScript
|
MethodDeclaration
|
async addCustomer(createCustomerDTO): Promise<student> {
const newCustomer = await this.studentRepository.create(createCustomerDTO)
return newCustomer;
}
|
wizba/training
|
src/student/student/student.service.ts
|
TypeScript
|
ClassDeclaration
|
/**
* <p>Creates an application, optionally including an AWS SAM file to create the first application version in the same call.</p>
* @example
* Use a bare-bones client and the command you need to make an API call.
* ```javascript
* import { ServerlessApplicationRepositoryClient, CreateApplicationCommand } from "@aws-sdk/client-serverlessapplicationrepository"; // ES Modules import
* // const { ServerlessApplicationRepositoryClient, CreateApplicationCommand } = require("@aws-sdk/client-serverlessapplicationrepository"); // CommonJS import
* const client = new ServerlessApplicationRepositoryClient(config);
* const command = new CreateApplicationCommand(input);
* const response = await client.send(command);
* ```
*
* @see {@link CreateApplicationCommandInput} for command's `input` shape.
* @see {@link CreateApplicationCommandOutput} for command's `response` shape.
* @see {@link ServerlessApplicationRepositoryClientResolvedConfig | config} for ServerlessApplicationRepositoryClient's `config` shape.
*
*/
export class CreateApplicationCommand extends $Command<
CreateApplicationCommandInput,
CreateApplicationCommandOutput,
ServerlessApplicationRepositoryClientResolvedConfig
> {
// Start section: command_properties
// End section: command_properties
constructor(readonly input: CreateApplicationCommandInput) {
// Start section: command_constructor
super();
// End section: command_constructor
}
/**
* @internal
*/
resolveMiddleware(
clientStack: MiddlewareStack<ServiceInputTypes, ServiceOutputTypes>,
configuration: ServerlessApplicationRepositoryClientResolvedConfig,
options?: __HttpHandlerOptions
): Handler<CreateApplicationCommandInput, CreateApplicationCommandOutput> {
this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize));
const stack = clientStack.concat(this.middlewareStack);
const { logger } = configuration;
const clientName = "ServerlessApplicationRepositoryClient";
const commandName = "CreateApplicationCommand";
const handlerExecutionContext: HandlerExecutionContext = {
logger,
clientName,
commandName,
inputFilterSensitiveLog: CreateApplicationRequest.filterSensitiveLog,
outputFilterSensitiveLog: CreateApplicationResponse.filterSensitiveLog,
};
const { requestHandler } = configuration;
return stack.resolve(
(request: FinalizeHandlerArguments<any>) =>
requestHandler.handle(request.request as __HttpRequest, options || {}),
handlerExecutionContext
);
}
private serialize(input: CreateApplicationCommandInput, context: __SerdeContext): Promise<__HttpRequest> {
return serializeAws_restJson1CreateApplicationCommand(input, context);
}
private deserialize(output: __HttpResponse, context: __SerdeContext): Promise<CreateApplicationCommandOutput> {
return deserializeAws_restJson1CreateApplicationCommand(output, context);
}
// Start section: command_body_extra
// End section: command_body_extra
}
|
AllanZhengYP/aws-sdk-js-v3
|
clients/client-serverlessapplicationrepository/src/commands/CreateApplicationCommand.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface CreateApplicationCommandInput extends CreateApplicationRequest {}
|
AllanZhengYP/aws-sdk-js-v3
|
clients/client-serverlessapplicationrepository/src/commands/CreateApplicationCommand.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface CreateApplicationCommandOutput extends CreateApplicationResponse, __MetadataBearer {}
|
AllanZhengYP/aws-sdk-js-v3
|
clients/client-serverlessapplicationrepository/src/commands/CreateApplicationCommand.ts
|
TypeScript
|
MethodDeclaration
|
/**
* @internal
*/
resolveMiddleware(
clientStack: MiddlewareStack<ServiceInputTypes, ServiceOutputTypes>,
configuration: ServerlessApplicationRepositoryClientResolvedConfig,
options?: __HttpHandlerOptions
): Handler<CreateApplicationCommandInput, CreateApplicationCommandOutput> {
this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize));
const stack = clientStack.concat(this.middlewareStack);
const { logger } = configuration;
const clientName = "ServerlessApplicationRepositoryClient";
const commandName = "CreateApplicationCommand";
const handlerExecutionContext: HandlerExecutionContext = {
logger,
clientName,
commandName,
inputFilterSensitiveLog: CreateApplicationRequest.filterSensitiveLog,
outputFilterSensitiveLog: CreateApplicationResponse.filterSensitiveLog,
};
const { requestHandler } = configuration;
return stack.resolve(
(request: FinalizeHandlerArguments<any>) =>
requestHandler.handle(request.request as __HttpRequest, options || {}),
handlerExecutionContext
);
}
|
AllanZhengYP/aws-sdk-js-v3
|
clients/client-serverlessapplicationrepository/src/commands/CreateApplicationCommand.ts
|
TypeScript
|
MethodDeclaration
|
private serialize(input: CreateApplicationCommandInput, context: __SerdeContext): Promise<__HttpRequest> {
return serializeAws_restJson1CreateApplicationCommand(input, context);
}
|
AllanZhengYP/aws-sdk-js-v3
|
clients/client-serverlessapplicationrepository/src/commands/CreateApplicationCommand.ts
|
TypeScript
|
MethodDeclaration
|
private deserialize(output: __HttpResponse, context: __SerdeContext): Promise<CreateApplicationCommandOutput> {
return deserializeAws_restJson1CreateApplicationCommand(output, context);
}
|
AllanZhengYP/aws-sdk-js-v3
|
clients/client-serverlessapplicationrepository/src/commands/CreateApplicationCommand.ts
|
TypeScript
|
ClassDeclaration
|
export class AnnouncementsMongoDbPersistence
extends IdentifiableMongoDbPersistence<AnnouncementV1, string>
implements IAnnouncementsPersistence {
constructor() {
super('announcements');
}
private composeFilter(filter: FilterParams): any {
filter = filter || new FilterParams();
let criteria = [];
let search = filter.getAsNullableString('search');
if (search != null) {
let searchRegex = new RegExp(search, "i");
let searchCriteria = [];
searchCriteria.push({ 'title.en': { $regex: searchRegex } });
searchCriteria.push({ 'title.sp': { $regex: searchRegex } });
searchCriteria.push({ 'title.fr': { $regex: searchRegex } });
searchCriteria.push({ 'title.de': { $regex: searchRegex } });
searchCriteria.push({ 'title.ru': { $regex: searchRegex } });
searchCriteria.push({ 'content.en': { $regex: searchRegex } });
searchCriteria.push({ 'content.sp': { $regex: searchRegex } });
searchCriteria.push({ 'content.fr': { $regex: searchRegex } });
searchCriteria.push({ 'content.de': { $regex: searchRegex } });
searchCriteria.push({ 'content.ru': { $regex: searchRegex } });
searchCriteria.push({ 'location.name': { $regex: searchRegex } });
searchCriteria.push({ 'creator.name': { $regex: searchRegex } });
criteria.push({ $or: searchCriteria });
}
let id = filter.getAsNullableString('id');
if (id != null)
criteria.push({ _id: id });
let category = filter.getAsNullableString('category');
if (category != null)
criteria.push({ category: category });
let app = filter.getAsNullableString('app');
if (app != null)
criteria.push({ app: app });
let status = filter.getAsNullableString('status');
if (status != null)
criteria.push({ status: status });
// Search by tags
let tags = filter.getAsObject('tags');
if (tags) {
let searchTags = TagsProcessor.compressTags([tags]);
criteria.push({ all_tags: { $in: searchTags } });
}
let fromCreateTime = filter.getAsNullableDateTime('from_create_time');
if (fromCreateTime != null)
criteria.push({ create_time: { $gte: fromCreateTime } });
let toCreateTime = filter.getAsNullableDateTime('to_create_time');
if (toCreateTime != null)
criteria.push({ create_time: { $lt: toCreateTime } });
return criteria.length > 0 ? { $and: criteria } : {};
}
public getPageByFilter(correlationId: string, filter: FilterParams, paging: PagingParams, callback: any) {
super.getPageByFilter(correlationId, this.composeFilter(filter), paging, '-create_time', null, callback);
}
public getOneRandom(correlationId: string, filter: FilterParams,
callback: (err: any, item: AnnouncementV1) => void): void {
super.getOneRandom(correlationId, this.composeFilter(filter), callback);
}
}
|
pip-services-support/pip-services-announcements-node
|
src/persistence/AnnouncementsMongoDbPersistence.ts
|
TypeScript
|
MethodDeclaration
|
private composeFilter(filter: FilterParams): any {
filter = filter || new FilterParams();
let criteria = [];
let search = filter.getAsNullableString('search');
if (search != null) {
let searchRegex = new RegExp(search, "i");
let searchCriteria = [];
searchCriteria.push({ 'title.en': { $regex: searchRegex } });
searchCriteria.push({ 'title.sp': { $regex: searchRegex } });
searchCriteria.push({ 'title.fr': { $regex: searchRegex } });
searchCriteria.push({ 'title.de': { $regex: searchRegex } });
searchCriteria.push({ 'title.ru': { $regex: searchRegex } });
searchCriteria.push({ 'content.en': { $regex: searchRegex } });
searchCriteria.push({ 'content.sp': { $regex: searchRegex } });
searchCriteria.push({ 'content.fr': { $regex: searchRegex } });
searchCriteria.push({ 'content.de': { $regex: searchRegex } });
searchCriteria.push({ 'content.ru': { $regex: searchRegex } });
searchCriteria.push({ 'location.name': { $regex: searchRegex } });
searchCriteria.push({ 'creator.name': { $regex: searchRegex } });
criteria.push({ $or: searchCriteria });
}
let id = filter.getAsNullableString('id');
if (id != null)
criteria.push({ _id: id });
let category = filter.getAsNullableString('category');
if (category != null)
criteria.push({ category: category });
let app = filter.getAsNullableString('app');
if (app != null)
criteria.push({ app: app });
let status = filter.getAsNullableString('status');
if (status != null)
criteria.push({ status: status });
// Search by tags
let tags = filter.getAsObject('tags');
if (tags) {
let searchTags = TagsProcessor.compressTags([tags]);
criteria.push({ all_tags: { $in: searchTags } });
}
let fromCreateTime = filter.getAsNullableDateTime('from_create_time');
if (fromCreateTime != null)
criteria.push({ create_time: { $gte: fromCreateTime } });
let toCreateTime = filter.getAsNullableDateTime('to_create_time');
if (toCreateTime != null)
criteria.push({ create_time: { $lt: toCreateTime } });
return criteria.length > 0 ? { $and: criteria } : {};
}
|
pip-services-support/pip-services-announcements-node
|
src/persistence/AnnouncementsMongoDbPersistence.ts
|
TypeScript
|
MethodDeclaration
|
public getPageByFilter(correlationId: string, filter: FilterParams, paging: PagingParams, callback: any) {
super.getPageByFilter(correlationId, this.composeFilter(filter), paging, '-create_time', null, callback);
}
|
pip-services-support/pip-services-announcements-node
|
src/persistence/AnnouncementsMongoDbPersistence.ts
|
TypeScript
|
MethodDeclaration
|
public getOneRandom(correlationId: string, filter: FilterParams,
callback: (err: any, item: AnnouncementV1) => void): void {
super.getOneRandom(correlationId, this.composeFilter(filter), callback);
}
|
pip-services-support/pip-services-announcements-node
|
src/persistence/AnnouncementsMongoDbPersistence.ts
|
TypeScript
|
ClassDeclaration
|
@Component({
template: `<div
style.color="a{{one}}b"
style.border="a{{one}}b"
[class.apple]="yesToApple"
[style.transition]="transition"
[class.orange]="yesToOrange"
[style.width]="width"
style.height="a{{one}}b"
style.top="a{{one}}b"></div>`
})
export class MyComponent {
one = '';
transition = 'all 1337ms ease';
width = '42px';
yesToApple = true;
yesToOrange = true;
}
|
017-Ddas/angular
|
packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_styling/chaining/break_different_instructions.ts
|
TypeScript
|
ClassDeclaration
|
export default class Shell extends Component<ShellProps, any> {
static Branding: ComponentType<ShellCommonProps>;
static Action: ComponentType<ShellCommonProps>;
static MultiTask: ComponentType<ShellCommonProps>;
static AppBar: ComponentType<ShellCommonProps>;
static Content: ComponentType<ShellCommonProps>;
static Footer: ComponentType<ShellCommonProps>;
static ToolDockItem: ComponentType<ShellCommonProps>;
static Navigation: ComponentType<ShellNavigationProps>;
static LocalNavigation: ComponentType<ShellLocalNavigationProps>;
static Ancillary: ComponentType<ShellAncillaryProps>;
static ToolDock: ComponentType<ShellToolDockProps>;
}
|
Mavericker-1996/next
|
types/shell/index.d.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface ShellProps extends HTMLAttributes<HTMLElement>, CommonProps {
/**
* 设备类型,针对不同的设备类型组件做出对应的响应式变化
*/
device?: 'tablet' | 'desktop' | 'phone';
type?: 'light' | 'dark' | 'brand';
fixedHeader?: boolean;
}
|
Mavericker-1996/next
|
types/shell/index.d.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface ShellCommonProps extends HTMLAttributes<HTMLElement>, CommonProps {
}
|
Mavericker-1996/next
|
types/shell/index.d.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface ShellNavigationProps extends ShellCommonProps {
collapse?: boolean;
direction?: 'hoz' | 'ver';
align?: 'left' | 'right' | 'center';
fixed?: boolean;
onCollapseChange?: (collapse?: boolean) => {};
}
|
Mavericker-1996/next
|
types/shell/index.d.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface ShellLocalNavigationProps extends ShellCommonProps {
collapse?: boolean;
onCollapseChange?: (collapse?: boolean) => {};
}
|
Mavericker-1996/next
|
types/shell/index.d.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface ShellToolDockProps extends ShellCommonProps {
collapse?: boolean;
fixed?: boolean;
onCollapseChange?: (collapse?: boolean) => {};
}
|
Mavericker-1996/next
|
types/shell/index.d.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface ShellAncillaryProps extends ShellCommonProps {
collapse?: boolean;
onCollapseChange?: (collapse?: boolean) => {};
}
|
Mavericker-1996/next
|
types/shell/index.d.ts
|
TypeScript
|
ArrowFunction
|
(filename: string) =>
sqlBase.__dangerous__rawValue(readFileSync(filename, 'utf8'))
|
AmitMY/atdatabases
|
packages/sql/src/index.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface SQL extends SQLBase {
file(filename: string): SQLQuery;
}
|
AmitMY/atdatabases
|
packages/sql/src/index.ts
|
TypeScript
|
ClassDeclaration
|
/**
* Acquires an item for the specified type and ignites it
*/
export default class AcquireItemAndIgnite extends Objective {
constructor(private readonly itemType: ItemType) {
super();
}
public getIdentifier(): string {
return `AcquireItemAndIgnite:${ItemType[this.itemType]}`;
}
public getStatus(): string | undefined {
return `Acquiring ${Translation.nameOf(Dictionary.Item, this.itemType).getString()} and igniting it`;
}
public override canIncludeContextHashCode(): boolean {
return true;
}
public override shouldIncludeContextHashCode(context: Context): boolean {
return context.isReservedItemType(this.itemType);
}
public async execute(context: Context): Promise<ObjectiveExecutionResult> {
const objectives: IObjective[] = [];
const itemToIgnite = itemUtilities.getItemInInventory(context, this.itemType);
if (itemToIgnite === undefined) {
objectives.push(new AcquireItem(this.itemType).setContextDataKey(this.getHashCode()));
}
objectives.push(new IgniteItem(itemToIgnite));
return objectives;
}
}
|
WaywardGame/tars
|
src/Objectives/Acquire/Item/AcquireItemAndIgnite.ts
|
TypeScript
|
MethodDeclaration
|
public getIdentifier(): string {
return `AcquireItemAndIgnite:${ItemType[this.itemType]}`;
}
|
WaywardGame/tars
|
src/Objectives/Acquire/Item/AcquireItemAndIgnite.ts
|
TypeScript
|
MethodDeclaration
|
public getStatus(): string | undefined {
return `Acquiring ${Translation.nameOf(Dictionary.Item, this.itemType).getString()} and igniting it`;
}
|
WaywardGame/tars
|
src/Objectives/Acquire/Item/AcquireItemAndIgnite.ts
|
TypeScript
|
MethodDeclaration
|
public override canIncludeContextHashCode(): boolean {
return true;
}
|
WaywardGame/tars
|
src/Objectives/Acquire/Item/AcquireItemAndIgnite.ts
|
TypeScript
|
MethodDeclaration
|
public override shouldIncludeContextHashCode(context: Context): boolean {
return context.isReservedItemType(this.itemType);
}
|
WaywardGame/tars
|
src/Objectives/Acquire/Item/AcquireItemAndIgnite.ts
|
TypeScript
|
MethodDeclaration
|
public async execute(context: Context): Promise<ObjectiveExecutionResult> {
const objectives: IObjective[] = [];
const itemToIgnite = itemUtilities.getItemInInventory(context, this.itemType);
if (itemToIgnite === undefined) {
objectives.push(new AcquireItem(this.itemType).setContextDataKey(this.getHashCode()));
}
objectives.push(new IgniteItem(itemToIgnite));
return objectives;
}
|
WaywardGame/tars
|
src/Objectives/Acquire/Item/AcquireItemAndIgnite.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface IScatterPlotProps {
index: number;
data: ILine[];
axesScaleType?: IAxesScaleState;
chartTitle?: IChartTitle;
displayOutliers?: boolean;
highlightMode?: HighlightEnum;
zoom?: IChartZoom;
onZoomChange?: (zoom: Partial<IChartZoom>) => void;
syncHoverState: (args: ISyncHoverStateArgs) => void;
}
|
SSamDav/aim
|
aim/web/ui/src/components/ScatterPlot/types.d.ts
|
TypeScript
|
MethodDeclaration
|
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "notification" ("id" SERIAL NOT NULL, "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "userId" integer NOT NULL, "isRead" boolean, "data" jsonb NOT NULL, CONSTRAINT "PK_705b6c7cdf9b2c2ff7ac7872cb7" PRIMARY KEY ("id"))`,
)
await queryRunner.query(
`CREATE TABLE "token" ("id" SERIAL NOT NULL, "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "lastActiveAt" TIMESTAMP WITH TIME ZONE NOT NULL, "type" character varying NOT NULL, "value" character varying NOT NULL, "maxAge" character varying NOT NULL, "userId" integer NOT NULL, CONSTRAINT "UQ_1096f931c2f2d9bf9c3c858d630" UNIQUE ("value"), CONSTRAINT "PK_82fae97f905930df5d62a702fc9" PRIMARY KEY ("id"))`,
)
await queryRunner.query(
`CREATE TABLE "node" ("id" SERIAL NOT NULL, "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "slug" character varying NOT NULL, "name" character varying NOT NULL, "description" character varying NOT NULL, "image" character varying, CONSTRAINT "UQ_e9c89f1e059861b0c4f897008d5" UNIQUE ("slug"), CONSTRAINT "PK_8c8caf5f29d25264abe9eaf94dd" PRIMARY KEY ("id"))`,
)
await queryRunner.query(
`CREATE TABLE "topic" ("id" SERIAL NOT NULL, "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "title" character varying NOT NULL, "content" character varying NOT NULL, "authorId" integer NOT NULL, "nodeId" integer NOT NULL, CONSTRAINT "PK_33aa4ecb4e4f20aa0157ea7ef61" PRIMARY KEY ("id"))`,
)
await queryRunner.query(
`CREATE TABLE "user_topic_like" ("id" SERIAL NOT NULL, "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "userId" integer NOT NULL, "topicId" integer NOT NULL, CONSTRAINT "PK_0151dd46f30684c6fe1d0d01061" PRIMARY KEY ("id"))`,
)
await queryRunner.query(
`CREATE TABLE "user" ("id" SERIAL NOT NULL, "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "username" character varying NOT NULL, "email" character varying, "avatar" character varying, "bio" character varying, "github" character varying, "twitter" character varying, "website" character varying, "githubUserId" character varying, "googleUserId" character varying, CONSTRAINT "UQ_78a916df40e02a9deb1c4b75edb" UNIQUE ("username"), CONSTRAINT "UQ_e12875dfb3b1d92d7d7c5377e22" UNIQUE ("email"), CONSTRAINT "UQ_c445acb0ecd41969b8a0955e13a" UNIQUE ("githubUserId"), CONSTRAINT "UQ_3a6d6e65d5678fd41783302bbb2" UNIQUE ("googleUserId"), CONSTRAINT "PK_cace4a159ff9f2512dd42373760" PRIMARY KEY ("id"))`,
)
await queryRunner.query(
`CREATE TABLE "comment" ("id" SERIAL NOT NULL, "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "content" character varying NOT NULL, "topicId" integer NOT NULL, "authorId" integer NOT NULL, "parentId" integer, CONSTRAINT "PK_0b0e4bbc8415ec426f87f3a88e2" PRIMARY KEY ("id"))`,
)
await queryRunner.query(
`ALTER TABLE "notification" ADD CONSTRAINT "FK_1ced25315eb974b73391fb1c81b" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
)
await queryRunner.query(
`ALTER TABLE "token" ADD CONSTRAINT "FK_94f168faad896c0786646fa3d4a" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
)
await queryRunner.query(
`ALTER TABLE "topic" ADD CONSTRAINT "FK_5bc4974a5ec06dd10c348bdb5ec" FOREIGN KEY ("authorId") REFERENCES "user"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
)
await queryRunner.query(
`ALTER TABLE "topic" ADD CONSTRAINT "FK_b6f2a8821db533df60c26491470" FOREIGN KEY ("nodeId") REFERENCES "node"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
)
await queryRunner.query(
`ALTER TABLE "user_topic_like" ADD CONSTRAINT "FK_d4a2527fbbba34e21b1079de424" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
)
await queryRunner.query(
`ALTER TABLE "user_topic_like" ADD CONSTRAINT "FK_bee938ba73f54fe875fa83573d2" FOREIGN KEY ("topicId") REFERENCES "topic"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
)
await queryRunner.query(
`ALTER TABLE "comment" ADD CONSTRAINT "FK_b57a5333a16e092c662bd8ff5fe" FOREIGN KEY ("topicId") REFERENCES "topic"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
)
await queryRunner.query(
`ALTER TABLE "comment" ADD CONSTRAINT "FK_276779da446413a0d79598d4fbd" FOREIGN KEY ("authorId") REFERENCES "user"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
)
await queryRunner.query(
`ALTER TABLE "comment" ADD CONSTRAINT "FK_e3aebe2bd1c53467a07109be596" FOREIGN KEY ("parentId") REFERENCES "comment"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
)
}
|
gozeon/hakka
|
server/migrations/1608889243136-init.ts
|
TypeScript
|
MethodDeclaration
|
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "comment" DROP CONSTRAINT "FK_e3aebe2bd1c53467a07109be596"`,
)
await queryRunner.query(
`ALTER TABLE "comment" DROP CONSTRAINT "FK_276779da446413a0d79598d4fbd"`,
)
await queryRunner.query(
`ALTER TABLE "comment" DROP CONSTRAINT "FK_b57a5333a16e092c662bd8ff5fe"`,
)
await queryRunner.query(
`ALTER TABLE "user_topic_like" DROP CONSTRAINT "FK_bee938ba73f54fe875fa83573d2"`,
)
await queryRunner.query(
`ALTER TABLE "user_topic_like" DROP CONSTRAINT "FK_d4a2527fbbba34e21b1079de424"`,
)
await queryRunner.query(
`ALTER TABLE "topic" DROP CONSTRAINT "FK_b6f2a8821db533df60c26491470"`,
)
await queryRunner.query(
`ALTER TABLE "topic" DROP CONSTRAINT "FK_5bc4974a5ec06dd10c348bdb5ec"`,
)
await queryRunner.query(
`ALTER TABLE "token" DROP CONSTRAINT "FK_94f168faad896c0786646fa3d4a"`,
)
await queryRunner.query(
`ALTER TABLE "notification" DROP CONSTRAINT "FK_1ced25315eb974b73391fb1c81b"`,
)
await queryRunner.query(`DROP TABLE "comment"`)
await queryRunner.query(`DROP TABLE "user"`)
await queryRunner.query(`DROP TABLE "user_topic_like"`)
await queryRunner.query(`DROP TABLE "topic"`)
await queryRunner.query(`DROP TABLE "node"`)
await queryRunner.query(`DROP TABLE "token"`)
await queryRunner.query(`DROP TABLE "notification"`)
}
|
gozeon/hakka
|
server/migrations/1608889243136-init.ts
|
TypeScript
|
ArrowFunction
|
() => {
this.inputEventWasTriggered = true;
}
|
acrolinx/sidebar-sdk-js
|
test/spec/adapter-test-setups/content-editable.ts
|
TypeScript
|
ClassDeclaration
|
export class ContentEditableTestSetup implements AdapterTestSetup {
name = 'ContentEditableAdapter';
inputFormat = 'HTML';
editorElement = `<div id="editorId" style="height: ${EDITOR_HEIGHT}px; overflow-x: scroll; position: relative; font-size: 10px">initial text</div>`;
inputEventWasTriggered?: boolean;
init() {
return Promise.resolve(new ContentEditableAdapter({editorId: 'editorId'}));
}
setEditorContent(html: string, done: DoneCallback) {
$('#editorId').html(html).on('input', () => {
this.inputEventWasTriggered = true;
});
done();
}
remove() {
$('#editorId').remove();
}
getSelectedText(): string {
return window.getSelection()!.toString();
}
}
|
acrolinx/sidebar-sdk-js
|
test/spec/adapter-test-setups/content-editable.ts
|
TypeScript
|
MethodDeclaration
|
init() {
return Promise.resolve(new ContentEditableAdapter({editorId: 'editorId'}));
}
|
acrolinx/sidebar-sdk-js
|
test/spec/adapter-test-setups/content-editable.ts
|
TypeScript
|
MethodDeclaration
|
setEditorContent(html: string, done: DoneCallback) {
$('#editorId').html(html).on('input', () => {
this.inputEventWasTriggered = true;
});
done();
}
|
acrolinx/sidebar-sdk-js
|
test/spec/adapter-test-setups/content-editable.ts
|
TypeScript
|
MethodDeclaration
|
remove() {
$('#editorId').remove();
}
|
acrolinx/sidebar-sdk-js
|
test/spec/adapter-test-setups/content-editable.ts
|
TypeScript
|
MethodDeclaration
|
getSelectedText(): string {
return window.getSelection()!.toString();
}
|
acrolinx/sidebar-sdk-js
|
test/spec/adapter-test-setups/content-editable.ts
|
TypeScript
|
FunctionDeclaration
|
/**
* This turns a node path into a valid state machine name, to try and improve
* the StepFunction's AWS console experience while minimizing the risk for
* collisons.
*/
function stateMachineNameFrom(nodePath: string): string {
// Poor man's replace all...
return nodePath.split(/[^a-z0-9+!@.()=_'-]+/i).join('.');
}
|
cdklabs/construct-hub
|
src/backend/ingestion/index.ts
|
TypeScript
|
ClassDeclaration
|
/**
* A StepFunctions State Machine to reprocess every currently indexed package
* through the ingestion function. This should not be frequently required, but
* can come in handy at times.
*
* For more information, refer to the runbook at
* https://github.com/cdklabs/construct-hub/blob/main/docs/operator-runbook.md
*/
class ReprocessIngestionWorkflow extends Construct {
public readonly stateMachine: StateMachine;
public constructor(scope: Construct, id: string, props: ReprocessIngestionWorkflowProps) {
super(scope, id);
const lambdaFunction = new ReIngest(this, 'Function', {
architecture: gravitonLambdaIfAvailable(this),
description: '[ConstructHub/Ingestion/ReIngest] The function used to reprocess packages through ingestion',
environment: { BUCKET_NAME: props.bucket.bucketName, QUEUE_URL: props.queue.queueUrl },
memorySize: 10_240,
tracing: Tracing.ACTIVE,
timeout: Duration.minutes(3),
});
props.queue.grantSendMessages(lambdaFunction);
props.bucket.grantRead(lambdaFunction, `${STORAGE_KEY_PREFIX}*${METADATA_KEY_SUFFIX}`);
props.bucket.grantRead(lambdaFunction, `${STORAGE_KEY_PREFIX}*${PACKAGE_KEY_SUFFIX}`);
// Need to physical-name the state machine so it can self-invoke.
const stateMachineName = stateMachineNameFrom(this.node.path);
const listBucket = new Choice(this, 'Has a ContinuationToken?')
.when(Condition.isPresent('$.ContinuationToken'),
new CallAwsService(this, 'S3.ListObjectsV2(NextPage)', {
service: 's3',
action: 'listObjectsV2',
iamAction: 's3:ListBucket',
iamResources: [props.bucket.bucketArn],
parameters: {
Bucket: props.bucket.bucketName,
ContinuationToken: JsonPath.stringAt('$.ContinuationToken'),
Prefix: STORAGE_KEY_PREFIX,
},
resultPath: '$.response',
}).addRetry({ errors: ['S3.SdkClientException'] }))
.otherwise(new CallAwsService(this, 'S3.ListObjectsV2(FirstPage)', {
service: 's3',
action: 'listObjectsV2',
iamAction: 's3:ListBucket',
iamResources: [props.bucket.bucketArn],
parameters: {
Bucket: props.bucket.bucketName,
Prefix: STORAGE_KEY_PREFIX,
},
resultPath: '$.response',
}).addRetry({ errors: ['S3.SdkClientException'] })).afterwards();
const process = new Map(this, 'Process Result', {
itemsPath: '$.response.Contents',
resultPath: JsonPath.DISCARD,
}).iterator(
new Choice(this, 'Is metadata object?')
.when(
Condition.stringMatches('$.Key', `*${METADATA_KEY_SUFFIX}`),
new LambdaInvoke(this, 'Send for reprocessing', { lambdaFunction })
// Ample retries here... We should never fail because of throttling....
.addRetry({ errors: ['Lambda.TooManyRequestsException'], backoffRate: 1.1, interval: Duration.minutes(1), maxAttempts: 30 }),
)
.otherwise(new Succeed(this, 'Nothing to do')),
);
listBucket.next(
new Choice(this, 'Is there more?')
.when(
Condition.isPresent('$.response.NextContinuationToken'),
new StepFunctionsStartExecution(this, 'Continue as new', {
associateWithParent: true,
stateMachine: StateMachine.fromStateMachineArn(this, 'ThisStateMachine', Stack.of(this).formatArn({
arnFormat: ArnFormat.COLON_RESOURCE_NAME,
service: 'states',
resource: 'stateMachine',
resourceName: stateMachineName,
})),
input: TaskInput.fromObject({ ContinuationToken: JsonPath.stringAt('$.response.NextContinuationToken') }),
integrationPattern: IntegrationPattern.REQUEST_RESPONSE,
resultPath: JsonPath.DISCARD,
}).addRetry({ errors: ['StepFunctions.ExecutionLimitExceeded'] }),
).afterwards({ includeOtherwise: true })
.next(process),
);
this.stateMachine = new StateMachine(this, 'StateMachine', {
definition: listBucket,
stateMachineName,
timeout: Duration.hours(1),
});
props.bucket.grantRead(this.stateMachine);
props.queue.grantSendMessages(this.stateMachine);
}
}
|
cdklabs/construct-hub
|
src/backend/ingestion/index.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface IngestionProps {
/**
* The bucket in which ingested objects are due to be inserted.
*/
readonly bucket: IBucket;
/**
* The CodeArtifact repository to which packages should be published. This is
* the ConstructHub internal CodeArtifact repository, if one exists.
*/
readonly codeArtifact?: Repository;
/**
* The monitoring handler to register alarms with.
*/
readonly monitoring: Monitoring;
/**
* The backend orchestration to invoke once the package metadata has been
* successfully registered.
*/
readonly orchestration: Orchestration;
/**
* How long to retain the CloudWatch logs.
*
* @default RetentionDays.TEN_YEARS
*/
readonly logRetention?: RetentionDays;
/**
* Configuration for custom package page links.
*/
readonly packageLinks?: PackageLinkConfig[];
/**
* Serialized configuration for custom package tags.
*/
readonly packageTags?: PackageTagConfig[];
/**
* How frequently all packages should get fully reprocessed.
*
* See the operator runbook for more information about reprocessing.
* @see https://github.com/cdklabs/construct-hub/blob/main/docs/operator-runbook.md
*
* @default - never
*/
readonly reprocessFrequency?: Duration;
}
|
cdklabs/construct-hub
|
src/backend/ingestion/index.ts
|
TypeScript
|
InterfaceDeclaration
|
interface ReprocessIngestionWorkflowProps {
readonly bucket: IBucket;
readonly queue: IQueue;
}
|
cdklabs/construct-hub
|
src/backend/ingestion/index.ts
|
TypeScript
|
MethodDeclaration
|
public metricFoundLicenseFile(opts?: MetricOptions): Metric {
return new Metric({
period: Duration.minutes(5),
statistic: Statistic.SUM,
...opts,
metricName: MetricName.FOUND_LICENSE_FILE,
namespace: METRICS_NAMESPACE,
});
}
|
cdklabs/construct-hub
|
src/backend/ingestion/index.ts
|
TypeScript
|
MethodDeclaration
|
public metricIneligibleLicense(opts?: MetricOptions): Metric {
return new Metric({
period: Duration.minutes(5),
statistic: Statistic.SUM,
...opts,
metricName: MetricName.INELIGIBLE_LICENSE,
namespace: METRICS_NAMESPACE,
});
}
|
cdklabs/construct-hub
|
src/backend/ingestion/index.ts
|
TypeScript
|
MethodDeclaration
|
public metricInvalidAssembly(opts?: MetricOptions): Metric {
return new Metric({
period: Duration.minutes(5),
statistic: Statistic.SUM,
...opts,
metricName: MetricName.INVALID_ASSEMBLY,
namespace: METRICS_NAMESPACE,
});
}
|
cdklabs/construct-hub
|
src/backend/ingestion/index.ts
|
TypeScript
|
MethodDeclaration
|
public metricInvalidTarball(opts?: MetricOptions): Metric {
return new Metric({
period: Duration.minutes(5),
statistic: Statistic.SUM,
...opts,
metricName: MetricName.INVALID_TARBALL,
namespace: METRICS_NAMESPACE,
});
}
|
cdklabs/construct-hub
|
src/backend/ingestion/index.ts
|
TypeScript
|
MethodDeclaration
|
/**
* This metrics is the total count of packages that were rejected due to
* mismatched identity (name, version, license) between the `package.json`
* file and te `.jsii` attribute.
*/
public metricMismatchedIdentityRejections(opts?: MetricOptions): Metric {
return new Metric({
period: Duration.minutes(5),
statistic: Statistic.SUM,
...opts,
metricName: MetricName.MISMATCHED_IDENTITY_REJECTIONS,
namespace: METRICS_NAMESPACE,
});
}
|
cdklabs/construct-hub
|
src/backend/ingestion/index.ts
|
TypeScript
|
ArrowFunction
|
() => {
test('click on closed', () => {
const mockToggle = jest.fn();
const view = mount(
<SelectToggle id="Select Toggle" onToggle={mockToggle} parentRef={{ current: document.createElement('div') }}>
Select
</SelectToggle>
);
view
.find('button')
.first()
.simulate('click');
expect(mockToggle.mock.calls[0][0]).toBe(true);
}
|
CooperRedhat/patternfly-react
|
packages/react-core/src/components/Select/__tests__/SelectToggle.test.tsx
|
TypeScript
|
ArrowFunction
|
() => {
const mockToggle = jest.fn();
const view = mount(
<SelectToggle id="Select Toggle" onToggle={mockToggle} parentRef={{ current: document.createElement('div') }}
|
CooperRedhat/patternfly-react
|
packages/react-core/src/components/Select/__tests__/SelectToggle.test.tsx
|
TypeScript
|
ArrowFunction
|
() => {
const mockToggle = jest.fn();
const view = mount(
<SelectToggle
id="Select Toggle"
onToggle={mockToggle}
isOpen
parentRef={{ current: document.createElement('div') }}
|
CooperRedhat/patternfly-react
|
packages/react-core/src/components/Select/__tests__/SelectToggle.test.tsx
|
TypeScript
|
ArrowFunction
|
() => {
const map = {} as any;
document.addEventListener = jest.fn((event, cb) => {
map[event] = cb;
});
const mockToggle = jest.fn();
mount(
<SelectToggle
id="Select Toggle"
onToggle={mockToggle}
isOpen
parentRef={{ current: document.createElement('div') }}
|
CooperRedhat/patternfly-react
|
packages/react-core/src/components/Select/__tests__/SelectToggle.test.tsx
|
TypeScript
|
ArrowFunction
|
(event, cb) => {
map[event] = cb;
}
|
CooperRedhat/patternfly-react
|
packages/react-core/src/components/Select/__tests__/SelectToggle.test.tsx
|
TypeScript
|
ArrowFunction
|
() => {
const map = {} as any;
document.addEventListener = jest.fn((event, cb) => {
map[event] = cb;
});
document.removeEventListener = jest.fn((event, cb) => {
if (map[event] === cb) {
map[event] = () => {};
}
});
const mockToggle = jest.fn();
const view = mount(
<SelectToggle
id="Select Toggle"
onToggle={mockToggle}
isOpen
parentRef={{ current: document.createElement('div') }}
|
CooperRedhat/patternfly-react
|
packages/react-core/src/components/Select/__tests__/SelectToggle.test.tsx
|
TypeScript
|
ArrowFunction
|
(event, cb) => {
if (map[event] === cb) {
map[event] = () => {};
}
}
|
CooperRedhat/patternfly-react
|
packages/react-core/src/components/Select/__tests__/SelectToggle.test.tsx
|
TypeScript
|
ArrowFunction
|
() => {
test('active', () => {
const view = mount(
<SelectToggle id="Select Toggle" isActive parentRef={{ current: document.createElement('div') }}>
Select
</SelectToggle>
);
expect(view).toMatchSnapshot();
}
|
CooperRedhat/patternfly-react
|
packages/react-core/src/components/Select/__tests__/SelectToggle.test.tsx
|
TypeScript
|
ArrowFunction
|
() => {
const view = mount(
<SelectToggle id="Select Toggle" isActive parentRef={{ current: document.createElement('div') }}
|
CooperRedhat/patternfly-react
|
packages/react-core/src/components/Select/__tests__/SelectToggle.test.tsx
|
TypeScript
|
TypeAliasDeclaration
|
export type CacheValue = number | Record<string, any>;
|
HcwXd/bottender
|
packages/bottender/src/cache/CacheStore.ts
|
TypeScript
|
TypeAliasDeclaration
|
type CacheStore = {
get(key: string): Promise<CacheValue | null>;
all(): Promise<CacheValue[]>;
put(key: string, value: CacheValue, minutes: number): Promise<void>;
forget(key: string): Promise<void>;
flush(): Promise<void>;
getPrefix(): string;
};
|
HcwXd/bottender
|
packages/bottender/src/cache/CacheStore.ts
|
TypeScript
|
ClassDeclaration
|
@Controller('/api/v1')
export class ApiV1PaymentController {
constructor (
private readonly accountsService: AccountsService
) {}
@UseGuards(UserRequiredAuthGuard)
@Post('add-payment-token')
async handleAddPaymentToken (@Request() req, @Res() res: Response): Promise<any> {
const account = await this.accountsService.findByOwnerEmail(req.user.email)
if (account == null) {
return res.json({
statusCode: 400,
error: 'Account not found'
})
}
const methods = await this.accountsService.addPaymentsMethods(account.id, req.body)
return res.json({
statusCode: 200,
message: methods
})
}
}
|
kompotkot/saasform
|
src/webapp/src/api/controllers/v1/api.payment.controller.ts
|
TypeScript
|
MethodDeclaration
|
@UseGuards(UserRequiredAuthGuard)
@Post('add-payment-token')
async handleAddPaymentToken (@Request() req, @Res() res: Response): Promise<any> {
const account = await this.accountsService.findByOwnerEmail(req.user.email)
if (account == null) {
return res.json({
statusCode: 400,
error: 'Account not found'
})
}
const methods = await this.accountsService.addPaymentsMethods(account.id, req.body)
return res.json({
statusCode: 200,
message: methods
})
}
|
kompotkot/saasform
|
src/webapp/src/api/controllers/v1/api.payment.controller.ts
|
TypeScript
|
ArrowFunction
|
() => {
it('should render text when not wrapped with provider', () => {
let App = () => (
<>
<Text>Foobar 3000</Text>
</>
);
let { getByText } = render(<App />);
expect(getByText('Foobar 3000')).toBeTruthy();
}
|
RuneXa/infra
|
packages/exoflex/src/components/__tests__/Text.test.web.tsx
|
TypeScript
|
ArrowFunction
|
() => {
let App = () => (
<>
<Text>Foobar 3000</Text>
</>
|
RuneXa/infra
|
packages/exoflex/src/components/__tests__/Text.test.web.tsx
|
TypeScript
|
ArrowFunction
|
() => (
<>
<Text>Foobar
|
RuneXa/infra
|
packages/exoflex/src/components/__tests__/Text.test.web.tsx
|
TypeScript
|
ArrowFunction
|
() => {
let App = () => (
<Provider skipFontsLoading>
<Text>Foobar 3000</Text>
</Provider>
|
RuneXa/infra
|
packages/exoflex/src/components/__tests__/Text.test.web.tsx
|
TypeScript
|
ArrowFunction
|
() => (
<Provider skipFontsLoading>
<Text>Foobar
|
RuneXa/infra
|
packages/exoflex/src/components/__tests__/Text.test.web.tsx
|
TypeScript
|
ArrowFunction
|
(err: Error, raw: Buffer) => {
if (err) return cb(err)
var account = new Account(raw)
cb(null, account)
}
|
Aminadav/ethereumjs-vm
|
lib/state/cache.ts
|
TypeScript
|
ArrowFunction
|
(err: Error, account: Account) => {
if (err) return cb(err)
this._update(key, account, false, false)
cb(null, account)
}
|
Aminadav/ethereumjs-vm
|
lib/state/cache.ts
|
TypeScript
|
ArrowFunction
|
val => {
if (val) accountArr.push(val)
}
|
Aminadav/ethereumjs-vm
|
lib/state/cache.ts
|
TypeScript
|
ArrowFunction
|
(addressHex: string, done: any) => {
var address = Buffer.from(addressHex, 'hex')
this._lookupAccount(address, (err: Error, account: Account) => {
if (err) return done(err)
this._update(address, account, false, false)
done()
})
}
|
Aminadav/ethereumjs-vm
|
lib/state/cache.ts
|
TypeScript
|
ArrowFunction
|
(err: Error, account: Account) => {
if (err) return done(err)
this._update(address, account, false, false)
done()
}
|
Aminadav/ethereumjs-vm
|
lib/state/cache.ts
|
TypeScript
|
ArrowFunction
|
() => next
|
Aminadav/ethereumjs-vm
|
lib/state/cache.ts
|
TypeScript
|
ArrowFunction
|
(done: any) => {
if (it.value && it.value.modified) {
it.value.modified = false
it.value.val = it.value.val.serialize()
this._trie.put(Buffer.from(it.key, 'hex'), it.value.val, (err: Error) => {
if (err) return done(err)
next = it.hasNext
it.next()
done()
})
} else if (it.value && it.value.deleted) {
it.value.modified = false
it.value.deleted = false
it.value.val = new Account().serialize()
this._trie.del(Buffer.from(it.key, 'hex'), (err: Error) => {
if (err) return done(err)
next = it.hasNext
it.next()
done()
})
} else {
next = it.hasNext
it.next()
asyncLib.nextTick(done)
}
}
|
Aminadav/ethereumjs-vm
|
lib/state/cache.ts
|
TypeScript
|
ArrowFunction
|
(err: Error) => {
if (err) return done(err)
next = it.hasNext
it.next()
done()
}
|
Aminadav/ethereumjs-vm
|
lib/state/cache.ts
|
TypeScript
|
ClassDeclaration
|
/**
* @ignore
*/
export default class Cache {
_cache: any
_checkpoints: any[]
_trie: any
constructor(trie: any) {
this._cache = Tree()
this._checkpoints = []
this._trie = trie
}
/**
* Puts account to cache under its address.
* @param key - Address of account
* @param val - Account
*/
put(key: Buffer, val: Account, fromTrie: boolean = false): void {
const modified = !fromTrie
this._update(key, val, modified, false)
}
/**
* Returns the queried account or an empty account.
* @param key - Address of account
*/
get(key: Buffer): Account {
let account = this.lookup(key)
if (!account) {
account = new Account()
}
return account
}
/**
* Returns the queried account or undefined.
* @param key - Address of account
*/
lookup(key: Buffer): Account | undefined {
const keyStr = key.toString('hex')
const it = this._cache.find(keyStr)
if (it.node) {
const account = new Account(it.value.val)
return account
}
}
/**
* Looks up address in underlying trie.
* @param address - Address of account
* @param cb - Callback with params (err, account)
*/
_lookupAccount(address: Buffer, cb: any): void {
this._trie.get(address, (err: Error, raw: Buffer) => {
if (err) return cb(err)
var account = new Account(raw)
cb(null, account)
})
}
/**
* Looks up address in cache, if not found, looks it up
* in the underlying trie.
* @param key - Address of account
* @param cb - Callback with params (err, account)
*/
getOrLoad(key: Buffer, cb: any): void {
const account = this.lookup(key)
if (account) {
asyncLib.nextTick(cb, null, account)
} else {
this._lookupAccount(key, (err: Error, account: Account) => {
if (err) return cb(err)
this._update(key, account, false, false)
cb(null, account)
})
}
}
/**
* Warms cache by loading their respective account from trie
* and putting them in cache.
* @param addresses - Array of addresses
* @param cb - Callback
*/
warm(addresses: string[], cb: any): void {
// shim till async supports iterators
const accountArr: string[] = []
addresses.forEach(val => {
if (val) accountArr.push(val)
})
asyncLib.eachSeries(
accountArr,
(addressHex: string, done: any) => {
var address = Buffer.from(addressHex, 'hex')
this._lookupAccount(address, (err: Error, account: Account) => {
if (err) return done(err)
this._update(address, account, false, false)
done()
})
},
cb,
)
}
/**
* Flushes cache by updating accounts that have been modified
* and removing accounts that have been deleted.
* @param cb - Callback
*/
flush(cb: any): void {
const it = this._cache.begin
let next = true
asyncLib.whilst(
() => next,
(done: any) => {
if (it.value && it.value.modified) {
it.value.modified = false
it.value.val = it.value.val.serialize()
this._trie.put(Buffer.from(it.key, 'hex'), it.value.val, (err: Error) => {
if (err) return done(err)
next = it.hasNext
it.next()
done()
})
} else if (it.value && it.value.deleted) {
it.value.modified = false
it.value.deleted = false
it.value.val = new Account().serialize()
this._trie.del(Buffer.from(it.key, 'hex'), (err: Error) => {
if (err) return done(err)
next = it.hasNext
it.next()
done()
})
} else {
next = it.hasNext
it.next()
asyncLib.nextTick(done)
}
},
cb,
)
}
/**
* Marks current state of cache as checkpoint, which can
* later on be reverted or commited.
*/
checkpoint(): void {
this._checkpoints.push(this._cache)
}
/**
* Revert changes to cache last checkpoint (no effect on trie).
*/
revert(): void {
this._cache = this._checkpoints.pop()
}
/**
* Commits to current state of cache (no effect on trie).
*/
commit(): void {
this._checkpoints.pop()
}
/**
* Clears cache.
*/
clear(): void {
this._cache = Tree()
}
/**
* Marks address as deleted in cache.
* @param key - Address
*/
del(key: Buffer): void {
this._update(key, new Account(), false, true)
}
_update(key: Buffer, val: Account, modified: boolean, deleted: boolean): void {
const keyHex = key.toString('hex')
const it = this._cache.find(keyHex)
if (it.node) {
this._cache = it.update({
val: val,
modified: modified,
deleted: deleted,
})
} else {
this._cache = this._cache.insert(keyHex, {
val: val,
modified: modified,
deleted: deleted,
})
}
}
}
|
Aminadav/ethereumjs-vm
|
lib/state/cache.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Puts account to cache under its address.
* @param key - Address of account
* @param val - Account
*/
put(key: Buffer, val: Account, fromTrie: boolean = false): void {
const modified = !fromTrie
this._update(key, val, modified, false)
}
|
Aminadav/ethereumjs-vm
|
lib/state/cache.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Returns the queried account or an empty account.
* @param key - Address of account
*/
get(key: Buffer): Account {
let account = this.lookup(key)
if (!account) {
account = new Account()
}
return account
}
|
Aminadav/ethereumjs-vm
|
lib/state/cache.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Returns the queried account or undefined.
* @param key - Address of account
*/
lookup(key: Buffer): Account | undefined {
const keyStr = key.toString('hex')
const it = this._cache.find(keyStr)
if (it.node) {
const account = new Account(it.value.val)
return account
}
}
|
Aminadav/ethereumjs-vm
|
lib/state/cache.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Looks up address in underlying trie.
* @param address - Address of account
* @param cb - Callback with params (err, account)
*/
_lookupAccount(address: Buffer, cb: any): void {
this._trie.get(address, (err: Error, raw: Buffer) => {
if (err) return cb(err)
var account = new Account(raw)
cb(null, account)
})
}
|
Aminadav/ethereumjs-vm
|
lib/state/cache.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Looks up address in cache, if not found, looks it up
* in the underlying trie.
* @param key - Address of account
* @param cb - Callback with params (err, account)
*/
getOrLoad(key: Buffer, cb: any): void {
const account = this.lookup(key)
if (account) {
asyncLib.nextTick(cb, null, account)
} else {
this._lookupAccount(key, (err: Error, account: Account) => {
if (err) return cb(err)
this._update(key, account, false, false)
cb(null, account)
})
}
}
|
Aminadav/ethereumjs-vm
|
lib/state/cache.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Warms cache by loading their respective account from trie
* and putting them in cache.
* @param addresses - Array of addresses
* @param cb - Callback
*/
warm(addresses: string[], cb: any): void {
// shim till async supports iterators
const accountArr: string[] = []
addresses.forEach(val => {
if (val) accountArr.push(val)
})
asyncLib.eachSeries(
accountArr,
(addressHex: string, done: any) => {
var address = Buffer.from(addressHex, 'hex')
this._lookupAccount(address, (err: Error, account: Account) => {
if (err) return done(err)
this._update(address, account, false, false)
done()
})
},
cb,
)
}
|
Aminadav/ethereumjs-vm
|
lib/state/cache.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Flushes cache by updating accounts that have been modified
* and removing accounts that have been deleted.
* @param cb - Callback
*/
flush(cb: any): void {
const it = this._cache.begin
let next = true
asyncLib.whilst(
() => next,
(done: any) => {
if (it.value && it.value.modified) {
it.value.modified = false
it.value.val = it.value.val.serialize()
this._trie.put(Buffer.from(it.key, 'hex'), it.value.val, (err: Error) => {
if (err) return done(err)
next = it.hasNext
it.next()
done()
})
} else if (it.value && it.value.deleted) {
it.value.modified = false
it.value.deleted = false
it.value.val = new Account().serialize()
this._trie.del(Buffer.from(it.key, 'hex'), (err: Error) => {
if (err) return done(err)
next = it.hasNext
it.next()
done()
})
} else {
next = it.hasNext
it.next()
asyncLib.nextTick(done)
}
},
cb,
)
}
|
Aminadav/ethereumjs-vm
|
lib/state/cache.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Marks current state of cache as checkpoint, which can
* later on be reverted or commited.
*/
checkpoint(): void {
this._checkpoints.push(this._cache)
}
|
Aminadav/ethereumjs-vm
|
lib/state/cache.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Revert changes to cache last checkpoint (no effect on trie).
*/
revert(): void {
this._cache = this._checkpoints.pop()
}
|
Aminadav/ethereumjs-vm
|
lib/state/cache.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Commits to current state of cache (no effect on trie).
*/
commit(): void {
this._checkpoints.pop()
}
|
Aminadav/ethereumjs-vm
|
lib/state/cache.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Clears cache.
*/
clear(): void {
this._cache = Tree()
}
|
Aminadav/ethereumjs-vm
|
lib/state/cache.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Marks address as deleted in cache.
* @param key - Address
*/
del(key: Buffer): void {
this._update(key, new Account(), false, true)
}
|
Aminadav/ethereumjs-vm
|
lib/state/cache.ts
|
TypeScript
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.