conflict_resolution
stringlengths 27
16k
|
---|
<<<<<<<
import * as NOTIFICATION from './notificationConstants';
=======
import * as NOTIFICATION from './notification';
import * as TOKEN from './token';
>>>>>>>
import * as NOTIFICATION from './notificationConstants';
import * as TOKEN from './token'; |
<<<<<<<
sentAt: string;
=======
isWhisper?: boolean;
>>>>>>>
sentAt: string;
isWhisper?: boolean; |
<<<<<<<
=======
// set grid size to 1px (smallest grid)
gridSize: 1,
>>>>>>>
<<<<<<<
}
/**
* This function is provided to JointJS to disable some invalid connections on the UI.
* If the connection is invalid, users are not able to connect the links on the UI.
*
* https://resources.jointjs.com/docs/jointjs/v2.0/joint.html#dia.Paper.prototype.options.validateConnection
*
* @param sourceView
* @param sourceMagnet
* @param targetView
* @param targetMagnet
*/
function validateOperatorConnection(sourceView: joint.dia.CellView, sourceMagnet: SVGElement,
targetView: joint.dia.CellView, targetMagnet: SVGElement): boolean {
// user cannot draw connection starting from the input port (left side)
if (sourceMagnet && sourceMagnet.getAttribute('port-group') === 'in') { return false; }
=======
>>>>>>> |
<<<<<<<
this.handleViewDeleteLink();
=======
this.handleWindowDrag();
this.handlePaperMouseZoom();
>>>>>>>
this.handleViewDeleteLink();
this.handleWindowDrag();
this.handlePaperMouseZoom(); |
<<<<<<<
=======
public onClickRunHandler = () => {};
>>>>>>>
public onClickRunHandler = () => {};
<<<<<<<
if (!this.isWorkflowValid) {
return {
text: 'Run', spinner: false, disable: true, onClick: () => {
}
};
=======
if (! isWorkflowValid) {
return { text: 'Error', icon: 'exclamation-circle', disable: true, onClick: () => {} };
>>>>>>>
if (!isWorkflowValid) {
return {
text: 'Error', icon: 'exclamation-circle', disable: true, onClick: () => {
}
};
<<<<<<<
text: 'Submitting', spinner: true, disable: true,
onClick: () => {
}
=======
text: 'Submitting', icon: 'loading', disable: true,
onClick: () => {}
>>>>>>>
text: 'Submitting', icon: 'loading', disable: true,
onClick: () => {
}
<<<<<<<
text: 'Pausing', spinner: true, disable: true,
onClick: () => {
}
=======
text: 'Pausing', icon: 'loading', disable: true,
onClick: () => {}
>>>>>>>
text: 'Pausing', icon: 'loading', disable: true,
onClick: () => {
}
<<<<<<<
text: 'Resuming', spinner: true, disable: true,
onClick: () => {
}
=======
text: 'Resuming', icon: 'loading', disable: true,
onClick: () => {}
>>>>>>>
text: 'Resuming', icon: 'loading', disable: true,
onClick: () => {
}
<<<<<<<
text: 'Recovering', spinner: true, disable: true,
onClick: () => {
}
=======
text: 'Recovering', icon: 'loading', disable: true,
onClick: () => {}
>>>>>>>
text: 'Recovering', icon: 'loading', disable: true,
onClick: () => {
}
<<<<<<<
public onClickSaveWorkflow(): void {
if (!this.userService.isLogin()) {
alert('please login');
} else {
this.workflowPersistService.saveWorkflow(this.userService.getUser()?.userID, this.saveWorkflowService.getSavedWorkflow());
}
}
=======
>>>>>>>
public onClickSaveWorkflow(): void {
if (!this.userService.isLogin()) {
alert('please login');
} else {
this.workflowPersistService.saveWorkflow(this.userService.getUser()?.userID, this.saveWorkflowService.getSavedWorkflow());
}
} |
<<<<<<<
const uploadFileListURL = 'assume it exist';
const uploadUserDictionaryURL = 'assume it exist';
const uploadDictionaryUrl = apiUrl + '/upload/dictionary';
=======
export interface GenericWebResponse {
code: number;
message: string;
}
>>>>>>>
const uploadFileListURL = 'assume it exist';
const uploadUserDictionaryURL = 'assume it exist';
export interface GenericWebResponse {
code: number;
message: string;
}
<<<<<<<
public uploadFileList(filelist: File[]): Observable<object> {
return this.http.post(uploadFileListURL, filelist, { headers: { 'Content-Type': 'text/plain' } });
}
public uploadUserDictionary(dict: UserDictionary): Observable<object> {
return this.http.post(uploadUserDictionaryURL, dict, { headers: { 'Content-Type': 'UserDictionary' } });
}
public uploadDictionary(file: File): void {
=======
/**
* This method will handle the request for uploading a File type
* dictionary object.
*
* @param file
*/
public uploadDictionary(file: File): Observable<GenericWebResponse> {
>>>>>>>
public uploadFileList(filelist: File[]): Observable<object> {
return this.http.post(uploadFileListURL, filelist, { headers: { 'Content-Type': 'text/plain' } });
}
public uploadUserDictionary(dict: UserDictionary): Observable<object> {
return this.http.post(uploadUserDictionaryURL, dict, { headers: { 'Content-Type': 'UserDictionary' } });
}
/**
* This method will handle the request for uploading a File type
* dictionary object.
*
* @param file
*/
public uploadDictionary(file: File): Observable<GenericWebResponse> {
<<<<<<<
this.saveStartedStream.next('start to upload dictionary');
this.http.post(uploadDictionaryUrl, formData, undefined)
.subscribe(
data => {
alert(file.name + ' is uploaded');
},
err => {
alert('Error occurred while uploading ' + file.name);
console.log('Error occurred while uploading ' + file.name + '\nError message: ' + err);
}
);
}
public getUploadDictionary(): Observable < string > {
return this.saveStartedStream.asObservable();
=======
return this.http.post<GenericWebResponse>(`${environment.apiUrl}/${uploadDictionaryUrl}`, formData);
>>>>>>>
return this.http.post<GenericWebResponse>(`${environment.apiUrl}/${uploadDictionaryUrl}`, formData); |
<<<<<<<
import { ExecutionResult } from '../../types/execute-workflow.interface';
import { WorkflowStatusService } from '../../service/workflow-status/workflow-status.service';
import { WebsocketService} from '../../service/websocket/websocket.service';
import {NgbModal, NgbActiveModal} from '@ng-bootstrap/ng-bootstrap';
import { Observable } from 'rxjs';
import { JointUIService } from '../../service/joint-ui/joint-ui.service';
=======
import { ExecutionResult } from './../../types/execute-workflow.interface';
import { WorkflowStatusService } from '../../service/workflow-status/workflow-status.service';
>>>>>>>
import { WebsocketService} from '../../service/websocket/websocket.service';
import {NgbModal, NgbActiveModal} from '@ng-bootstrap/ng-bootstrap';
import { Observable } from 'rxjs';
import { JointUIService } from '../../service/joint-ui/joint-ui.service';
import { ExecutionResult } from './../../types/execute-workflow.interface';
import { WorkflowStatusService } from '../../service/workflow-status/workflow-status.service';
<<<<<<<
this.checkStatus(workflowId);
// receive the state of operators
console.log('start receiving state data');
this.jointUIService.sendOperatorStateMessage();
=======
this.workflowStatusService.checkStatus(workflowId);
>>>>>>>
this.workflowStatusService.checkStatus(workflowId);
this.jointUIService.sendOperatorStateMessage(); |
<<<<<<<
downloadExecutionResultEnabled: false,
userSystemEnabled: false,
amberEngineEnabled: true,
=======
downloadExecutionResultEnabled: false,
/**
* whether linkBreakpoint is supported
*/
linkBreakpointEnabled: true,
>>>>>>>
downloadExecutionResultEnabled: false,
userSystemEnabled: false,
amberEngineEnabled: true,
/**
* whether linkBreakpoint is supported
*/
linkBreakpointEnabled: true, |
<<<<<<<
this.workflowActionService.addOperator(operator, this.jointUIService.getJointOperatorElement(operator, value.offset));
this.workflowActionService.getJointGraphWrapper().highlightOperator(operator.operatorID);
=======
this.workflowActionService.addOperator(operator, value.offset);
>>>>>>>
this.workflowActionService.addOperator(operator, value.offset);
this.workflowActionService.getJointGraphWrapper().highlightOperator(operator.operatorID); |
<<<<<<<
constructor(private executeWorkflowService: ExecuteWorkflowService, private workflowActionService: WorkflowActionService,
public tourService: TourService, public undoRedo: UndoRedoService) {
=======
// variable binded with HTML to decide if the running spinner should show
public showSpinner = false;
public executionResultID: string | undefined;
constructor(private executeWorkflowService: ExecuteWorkflowService,
public tourService: TourService, private workflowActionService: WorkflowActionService,
) {
>>>>>>>
// variable binded with HTML to decide if the running spinner should show
public showSpinner = false;
public executionResultID: string | undefined;
constructor(private executeWorkflowService: ExecuteWorkflowService,
private workflowActionService: WorkflowActionService,
public tourService: TourService, public undoRedo: UndoRedoService) { |
<<<<<<<
this.workflowActionService.addOperator(operator, value.offset);
// has suggestion and must auto-create the operator link between 2 operators.
if (this.suggestionOperator !== undefined) {
if (this.isSuggestionOnLeft) {
const linkCell = this.getNewOperatorLink(this.suggestionOperator, operator);
this.workflowActionService.addLink(linkCell);
} else {
const linkCell = this.getNewOperatorLink(operator, this.suggestionOperator);
this.workflowActionService.addLink(linkCell);
}
this.operatorSuggestionUnhighlightStream.next(this.suggestionOperator.operatorID);
this.suggestionOperator = undefined;
}
=======
this.workflowActionService.addOperator(operator, newOperatorOffset);
>>>>>>>
this.workflowActionService.addOperator(operator, newOperatorOffset);
// has suggestion and must auto-create the operator link between 2 operators.
if (this.suggestionOperator !== undefined) {
if (this.isSuggestionOnLeft) {
const linkCell = this.getNewOperatorLink(this.suggestionOperator, operator);
this.workflowActionService.addLink(linkCell);
} else {
const linkCell = this.getNewOperatorLink(operator, this.suggestionOperator);
this.workflowActionService.addLink(linkCell);
}
this.operatorSuggestionUnhighlightStream.next(this.suggestionOperator.operatorID);
this.suggestionOperator = undefined;
}
<<<<<<<
public getOperatorSuggestionHighlightStream(): Observable<string> {
return this.operatorSuggestionHighlightStream.asObservable();
}
public getOperatorSuggestionUnhighlightStream(): Observable<string> {
return this.operatorSuggestionUnhighlightStream.asObservable();
}
=======
>>>>>>>
public getOperatorSuggestionHighlightStream(): Observable<string> {
return this.operatorSuggestionHighlightStream.asObservable();
}
public getOperatorSuggestionUnhighlightStream(): Observable<string> {
return this.operatorSuggestionUnhighlightStream.asObservable();
} |
<<<<<<<
DragDropService,
=======
{ provide: WorkflowActionService, useClass: StubWorkflowActionService },
>>>>>>>
DragDropService,
{ provide: WorkflowActionService, useClass: StubWorkflowActionService }, |
<<<<<<<
let workflowStatusService: WorkflowStatusService;
=======
let undoRedoService: UndoRedoService;
>>>>>>>
let workflowStatusService: WorkflowStatusService;
let undoRedoService: UndoRedoService;
<<<<<<<
workflowStatusService = TestBed.get(WorkflowStatusService);
=======
undoRedoService = TestBed.get(UndoRedoService);
>>>>>>>
workflowStatusService = TestBed.get(WorkflowStatusService);
undoRedoService = TestBed.get(UndoRedoService);
<<<<<<<
const mockComponent = new NavigationComponent(executeWorkFlowService, TestBed.get(TourService),
workflowActionService, workflowStatusService);
=======
const mockComponent = new NavigationComponent(executeWorkFlowService, workflowActionService, TestBed.get(TourService), undoRedoService);
>>>>>>>
const mockComponent = new NavigationComponent(executeWorkFlowService, TestBed.get(TourService),
workflowActionService, workflowStatusService, undoRedoService);
<<<<<<<
const mockComponent = new NavigationComponent(executeWorkFlowService, TestBed.get(TourService),
workflowActionService, workflowStatusService);
=======
const mockComponent = new NavigationComponent(executeWorkFlowService, workflowActionService, TestBed.get(TourService), undoRedoService);
>>>>>>>
const mockComponent = new NavigationComponent(executeWorkFlowService, TestBed.get(TourService),
workflowActionService, workflowStatusService, undoRedoService);
<<<<<<<
describe('when executionStatus is enabled', () => {
beforeEach(() => {
defaultEnvironment.executionStatusEnabled = true;
});
it('should send workflowId to websocket when run button is clicked', () => {
const checkWorkflowSpy = spyOn(workflowStatusService, 'checkStatus');
component.onButtonClick();
expect(checkWorkflowSpy).toHaveBeenCalled();
});
});
=======
it('should delete all operators on the graph when user clicks on the delete all button', marbles((m) => {
m.hot('-e-').do(() => {
workflowActionService.addOperator(mockScanPredicate, mockPoint);
component.onClickDeleteAllOperators();
}).subscribe();
expect(workflowActionService.getTexeraGraph().getAllOperators().length).toBe(0);
}));
>>>>>>>
describe('when executionStatus is enabled', () => {
beforeEach(() => {
environment.executionStatusEnabled = true;
});
it('should send workflowId to websocket when run button is clicked', () => {
const checkWorkflowSpy = spyOn(workflowStatusService, 'checkStatus');
component.onButtonClick();
expect(checkWorkflowSpy).toHaveBeenCalled();
});
});
it('should delete all operators on the graph when user clicks on the delete all button', marbles((m) => {
m.hot('-e-').do(() => {
workflowActionService.addOperator(mockScanPredicate, mockPoint);
component.onClickDeleteAllOperators();
}).subscribe();
expect(workflowActionService.getTexeraGraph().getAllOperators().length).toBe(0);
})); |
<<<<<<<
import { UserDictionary} from '../../../type/user-dictionary';
=======
import { UserDictionary } from '../../../service/user-dictionary/user-dictionary.interface';
>>>>>>>
import { UserDictionary } from '../../../service/user-dictionary/user-dictionary.interface';
<<<<<<<
public UserDictionary: UserDictionary[] = [];
public savedData: SavedData = {
name: '',
content: '',
separator: '',
savedQueue: []
};
=======
public userDictionaries: UserDictionary[] = [];
>>>>>>>
public userDictionaries: UserDictionary[] = [];
public savedData: SavedData = {
name: '',
content: '',
separator: '',
savedQueue: []
};
<<<<<<<
const modalRef = this.modalService.open(NgbdModalResourceAddComponent, {
beforeDismiss: (): boolean => {
this.savedData = {
name: modalRef.componentInstance.dictName,
content: modalRef.componentInstance.dictContent,
separator: modalRef.componentInstance.dictSeparator,
savedQueue: modalRef.componentInstance.uploader.queue
};
return true;
}
});
// initialize the value from saving, used when user close the popup and then temporarily save dictionary.
modalRef.componentInstance.uploader.queue = this.savedData.savedQueue;
modalRef.componentInstance.dictName = this.savedData.name;
modalRef.componentInstance.dictContent = this.savedData.content;
modalRef.componentInstance.dictSeparator = this.savedData.separator;
modalRef.componentInstance.checkCurrentFilesValid();
=======
const modalRef = this.modalService.open(NgbdModalResourceAddComponent);
Observable.from(modalRef.result).subscribe(
(value: Observable<UserDictionary>) => {
value.subscribe(res => {
this.refreshUserDictionary();
});
}
);
>>>>>>>
const modalRef = this.modalService.open(NgbdModalResourceAddComponent, {
beforeDismiss: (): boolean => {
this.savedData = {
name: modalRef.componentInstance.dictName,
content: modalRef.componentInstance.dictContent,
separator: modalRef.componentInstance.dictSeparator,
savedQueue: modalRef.componentInstance.uploader.queue
};
return true;
}
});
// initialize the value from saving, used when user close the popup and then temporarily save dictionary.
modalRef.componentInstance.uploader.queue = this.savedData.savedQueue;
modalRef.componentInstance.dictName = this.savedData.name;
modalRef.componentInstance.dictContent = this.savedData.content;
modalRef.componentInstance.dictSeparator = this.savedData.separator;
modalRef.componentInstance.checkCurrentFilesValid();
// const modalRef = this.modalService.open(NgbdModalResourceAddComponent);
// Observable.from(modalRef.result).subscribe(
// (value: Observable<UserDictionary>) => {
// value.subscribe(res => {
// this.refreshUserDictionary();
// });
// }
// ); |
<<<<<<<
import { mockScanPredicate, mockPoint } from '../../service/workflow-graph/model/mock-workflow-data';
import { ResultPanelToggleService } from '../../service/result-panel-toggle/result-panel-toggle.service';
import { marbles } from 'rxjs-marbles';
=======
import {
mockScanPredicate, mockPoint, mockScanResultLink, mockResultPredicate
} from '../../service/workflow-graph/model/mock-workflow-data';
>>>>>>>
import { ResultPanelToggleService } from '../../service/result-panel-toggle/result-panel-toggle.service';
import { marbles } from 'rxjs-marbles';
import {
mockScanPredicate, mockPoint, mockScanResultLink, mockResultPredicate
} from '../../service/workflow-graph/model/mock-workflow-data';
<<<<<<<
ResultPanelToggleService,
=======
ValidationWorkflowService,
>>>>>>>
ResultPanelToggleService,
ValidationWorkflowService,
<<<<<<<
ResultPanelToggleService,
=======
ValidationWorkflowService,
>>>>>>>
ResultPanelToggleService,
ValidationWorkflowService, |
<<<<<<<
it('should create an JointJS Element successfully when the function is called', () => {
const result = service.getJointjsOperatorElement(
getMockScanPredicate(), getMockPoint());
=======
it('should create an JointJS Element successfully', () => {
const result = service.getJointOperatorElement('ScanSource', 'operator1', 100, 100);
>>>>>>>
it('should create an JointJS Element successfully when the function is called', () => {
const result = service.getJointOperatorElement(
getMockScanPredicate(), getMockPoint());
<<<<<<<
expect(() => {
service.getJointjsOperatorElement(
{
operatorID: 'nonexistOperator',
operatorType: 'nonexistOperatorType',
operatorProperties: {},
inputPorts: [],
outputPorts: []
},
getMockPoint()
);
}).toThrowError(new RegExp(`doesn't exist`));
=======
const nonExistingOperator = 'NotExistOperator';
expect(
function () {
service.getJointOperatorElement(nonExistingOperator, 'operatorNaN', 100, 100);
}
)
.toThrowError(new RegExp(`doesn't exist`));
>>>>>>>
expect(() => {
service.getJointOperatorElement(
{
operatorID: 'nonexistOperator',
operatorType: 'nonexistOperatorType',
operatorProperties: {},
inputPorts: [],
outputPorts: []
},
getMockPoint()
);
}).toThrowError(new RegExp(`doesn't exist`));
<<<<<<<
const element1 = service.getJointjsOperatorElement(getMockScanPredicate(), getMockPoint());
const element2 = service.getJointjsOperatorElement(getMockSentimentPredicate(), getMockPoint());
const element3 = service.getJointjsOperatorElement(getMockResultPredicate(), getMockPoint());
=======
const element1 = service.getJointOperatorElement('ScanSource', 'operator1', 100, 100);
const element2 = service.getJointOperatorElement('NlpSentiment', 'operator1', 100, 100);
const element3 = service.getJointOperatorElement('ViewResults', 'operator1', 100, 100);
>>>>>>>
const element1 = service.getJointOperatorElement(getMockScanPredicate(), getMockPoint());
const element2 = service.getJointOperatorElement(getMockSentimentPredicate(), getMockPoint());
const element3 = service.getJointOperatorElement(getMockResultPredicate(), getMockPoint());
<<<<<<<
service.getJointjsOperatorElement(
getMockScanPredicate(),
getMockPoint()
=======
service.getJointOperatorElement(
'ScanSource',
'operator1',
100, 100
>>>>>>>
service.getJointOperatorElement(
getMockScanPredicate(),
getMockPoint() |
<<<<<<<
import * as Ajv from 'ajv';
=======
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
>>>>>>>
import * as Ajv from 'ajv';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
<<<<<<<
// used to fetch default values in json schema to initialize new operator
private ajv = new Ajv({ useDefaults: true });
=======
private operatorSchemaListCreatedSubject: Subject<boolean> = new Subject<boolean>();
>>>>>>>
// used to fetch default values in json schema to initialize new operator
private ajv = new Ajv({ useDefaults: true });
private operatorSchemaListCreatedSubject: Subject<boolean> = new Subject<boolean>(); |
<<<<<<<
import { WorkflowUtilService } from './../../service/workflow-graph/util/workflow-util.service';
import { WorkflowActionService } from './../../service/workflow-graph/model/workflow-action.service';
import { JointModelService } from './../../service/workflow-graph/model/jointjs-model.service';
import { Component, AfterViewInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import '../../../common/rxjs-operators';
=======
import { Component, AfterViewInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import '../../../common/rxjs-operators';
>>>>>>>
import { WorkflowUtilService } from './../../service/workflow-graph/util/workflow-util.service';
import { WorkflowActionService } from './../../service/workflow-graph/model/workflow-action.service';
import { JointModelService } from './../../service/workflow-graph/model/jointjs-model.service';
import { Component, AfterViewInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import '../../../common/rxjs-operators';
<<<<<<<
/**
* Creates a JointJS Paper object, which is the JointJS view object responsible for
* rendering the workflow cells and handle UI events.
*
* JointJS documentation about paper: https://resources.jointjs.com/docs/jointjs/v2.0/joint.html#dia.Paper
*/
private getJointjsPaper(): joint.dia.Paper {
const paper = new joint.dia.Paper({
// bind the DOM element
el: $('#' + this.WORKFLOW_EDITOR_JOINTJS_ID),
// bind the jointjs graph model
model: this.graph,
// set the width and height of the paper to be the width height of the parent wrapper element
width: this.getWrapperElementSize().width,
height: this.getWrapperElementSize().height,
// set grid size to 1px (smallest grid)
gridSize: 1,
// enable jointjs feature that automatically snaps a link to the closest port with a radius of 30px
snapLinks: { radius: 30 },
// disable jointjs default action that can make a link not connect to an operator
linkPinning: false,
// provide a validation to determine if two ports could be connected (only output connect to input is allowed)
validateConnection: validateOperatorConnection,
// disable jointjs default action of adding vertexes to the link
interactive: { vertexAdd: false },
// set a default link element used by jointjs when user creates a link on UI
defaultLink: this.jointUIService.getDefaultLinkElement(),
// disable jointjs default action that stops propagate click events on jointjs paper
preventDefaultBlankAction: false,
// disable jointjs default action that prevents normal right click menu showing up on jointjs paper
preventContextMenu: false,
});
return paper;
}
/**
* get the width and height of the parent wrapper element
*/
private getWrapperElementSize(): { width: number, height: number } {
const width = $('#' + this.WORKFLOW_EDITOR_JOINTJS_WRAPPER_ID).width();
const height = $('#' + this.WORKFLOW_EDITOR_JOINTJS_WRAPPER_ID).height();
if (width === undefined || height === undefined) {
throw new Error('TODO');
}
return { width, height };
}
}
/**
* This function is provided to JointJS to disable some invalid connections on the UI.
* If the connection is invalid, users are not able to connect the links on the UI.
*
* https://resources.jointjs.com/docs/jointjs/v2.0/joint.html#dia.Paper.prototype.options.validateConnection
*
* @param sourceView
* @param sourceMagnet
* @param targetView
* @param targetMagnet
*/
function validateOperatorConnection(sourceView: joint.dia.CellView, sourceMagnet: SVGElement,
targetView: joint.dia.CellView, targetMagnet: SVGElement): boolean {
// user cannot draw connection starting from the input port (left side)
if (sourceMagnet && sourceMagnet.getAttribute('port-group') === 'in') { return false; }
// user cannot connect to the output port (right side)
if (targetMagnet && targetMagnet.getAttribute('port-group') === 'out') { return false; }
return sourceView.id !== targetView.id;
}
=======
>>>>>>> |
<<<<<<<
private table: object[];
// private columns: string[] = [];
=======
@Input() data: DialogData | null = null;
private table: object[] = [];
private columns: string[] = [];
>>>>>>>
@Input() data: DialogData | null = null;
private table: object[] = [];
// private columns: string[] = []; |
<<<<<<<
import { forEach } from '@angular/router/src/utils/collection';
import { CompileMetadataResolver } from '@angular/compiler';
import { NoneComponent } from 'angular6-json-schema-form';
import { JSONSchema4 } from 'json-schema';
=======
import { IndexableObject } from '../../types/result-table.interface';
>>>>>>>
import { JSONSchema4 } from 'json-schema';
import { IndexableObject } from '../../types/result-table.interface';
<<<<<<<
// the current operator schema list, used to find the operator schema of current operator
public operatorSchemaList: ReadonlyArray<OperatorSchema> = [];
// the variables used for showing/hiding advanced options
public showAdvanced: boolean = false;
public hasAdvanced: boolean = false;
=======
// the current operator schema list, used to find the operator schema of current operator
public operatorSchemaList: ReadonlyArray<OperatorSchema> = [];
// the map of property description (key = property name, value = property description)
public propertyDescription: Map<String, String> = new Map();
// boolean to display the property description button
public hasPropertyDescription: boolean = false;
>>>>>>>
// the current operator schema list, used to find the operator schema of current operator
public operatorSchemaList: ReadonlyArray<OperatorSchema> = [];
// the variables used for showing/hiding advanced options
public showAdvanced: boolean = false;
public hasAdvanced: boolean = false;
public advancedClick: boolean = false;
// the map of property description (key = property name, value = property description)
public propertyDescription: Map<String, String> = new Map();
// boolean to display the property description button
public hasPropertyDescription: boolean = false;
<<<<<<<
this.showAdvanced = operator.showAdvanced;
// only show the button if the operator has advanced options
if (this.currentOperatorSchema.additionalMetadata.advancedOptions) {
this.hasAdvanced = this.currentOperatorSchema.additionalMetadata.advancedOptions.length === 0 ? false : true;
}
if (!this.showAdvanced) {
this.currentOperatorSchema = this.hideAdvancedSchema(this.currentOperatorSchema);
}
=======
// handler to show operator detail description button or not
this.handleOperatorPropertyDescription(this.currentOperatorSchema);
>>>>>>>
this.showAdvanced = operator.showAdvanced;
// only show the button if the operator has advanced options
if (this.currentOperatorSchema.additionalMetadata.advancedOptions) {
this.hasAdvanced = this.currentOperatorSchema.additionalMetadata.advancedOptions.length === 0 ? false : true;
}
if (!this.showAdvanced) {
this.currentOperatorSchema = this.hideAdvancedSchema(this.currentOperatorSchema);
}
// handler to show operator detail description button or not
this.handleOperatorPropertyDescription(this.currentOperatorSchema);
<<<<<<<
=======
// when operator in the property editor changes, the cachedFormData should also be changed
this.cachedFormData = this.currentOperatorInitialData;
>>>>>>>
// when operator in the property editor changes, the cachedFormData should also be changed
this.cachedFormData = this.currentOperatorInitialData; |
<<<<<<<
private resultPanelToggleService: ResultPanelToggleService,
=======
private validationWorkflowService: ValidationWorkflowService,
private jointUIService: JointUIService,
>>>>>>>
private resultPanelToggleService: ResultPanelToggleService,
private validationWorkflowService: ValidationWorkflowService,
private jointUIService: JointUIService, |
<<<<<<<
export interface IndexableObject extends Readonly<{
[key: string]: object | string | boolean | symbol | number | Array<object>;
}> { }
=======
import { JSONSchema4 } from 'json-schema';
import { IndexableObject } from '../../types/result-table.interface';
>>>>>>>
export interface IndexableObject extends Readonly<{
[key: string]: object | string | boolean | symbol | number | Array<object>;
}> { }
import { JSONSchema4 } from 'json-schema';
import { IndexableObject } from '../../types/result-table.interface';
<<<<<<<
// this checks whether formData and cachedFormData will have the same appearance when rendered in the form
if (this.secondCheckPropertyEqual(formData as IndexableObject, this.cachedFormData as IndexableObject)) {
return false;
}
=======
// this checks whether formData and cachedFormData will have the same appearance when rendered in the form
if (this.secondCheckPropertyEqual(formData as IndexableObject, this.cachedFormData as IndexableObject)) {
return false;
}
>>>>>>>
// this checks whether formData and cachedFormData will have the same appearance when rendered in the form
if (this.secondCheckPropertyEqual(formData as IndexableObject, this.cachedFormData as IndexableObject)) {
return false;
}
<<<<<<<
this.cachedFormData = this.currentOperatorInitialData;
=======
// need to use spread operator to keep the advanced options in the new operator properties do not contain them
this.cachedFormData = {...this.cachedFormData, ...this.currentOperatorInitialData};
>>>>>>>
// need to use spread operator to keep the advanced options in the new operator properties do not contain them
this.cachedFormData = {...this.cachedFormData, ...this.currentOperatorInitialData}; |
<<<<<<<
import { DragDropService } from './../../service/drag-drop/drag-drop.service';
import { Observable } from 'rxjs';
=======
import { environment } from '../../../../environments/environment';
>>>>>>>
import { DragDropService } from './../../service/drag-drop/drag-drop.service';
import { environment } from '../../../../environments/environment';
<<<<<<<
// zoomDifference represents the ratio that is zoom in/out everytime.
public static readonly ZOOM_DIFFERENCE: number = 0.02;
// variable binded with HTML to decide if the running spinner should show
public showSpinner = false;
// the newZoomRatio represents the ratio of the size of the the new window to the original one.
private newZoomRatio: number = 1;
constructor(private dragDropService: DragDropService,
private executeWorkflowService: ExecuteWorkflowService, public tourService: TourService) {
// hide the spinner after the execution is finished, either
=======
public isWorkflowRunning: boolean = false; // set this to true when the workflow is started
public isWorkflowPaused: boolean = false; // this will be modified by clicking pause/resume while the workflow is running
constructor(private executeWorkflowService: ExecuteWorkflowService, public tourService: TourService) {
// return the run button after the execution is finished, either
>>>>>>>
// zoomDifference represents the ratio that is zoom in/out everytime.
public static readonly ZOOM_DIFFERENCE: number = 0.02;
public isWorkflowRunning: boolean = false; // set this to true when the workflow is started
public isWorkflowPaused: boolean = false; // this will be modified by clicking pause/resume while the workflow is running
// variable binded with HTML to decide if the running spinner should show
public showSpinner = false;
// the newZoomRatio represents the ratio of the size of the the new window to the original one.
private newZoomRatio: number = 1;
constructor(private dragDropService: DragDropService,
private executeWorkflowService: ExecuteWorkflowService, public tourService: TourService) {
// return the run button after the execution is finished, either |
<<<<<<<
import { Component, ViewChild} from '@angular/core';
import { Response, Http } from '@angular/http';
=======
import {Component, ViewChild, OnInit} from '@angular/core';
>>>>>>>
import {Component, ViewChild, OnInit} from '@angular/core';
import { Response, Http } from '@angular/http'; |
<<<<<<<
// set grid size to 1px (smallest grid)
gridSize: 1,
=======
>>>>>>>
<<<<<<<
=======
}
/**
* This function is provided to JointJS to disable some invalid connections on the UI.
* If the connection is invalid, users are not able to connect the links on the UI.
*
* https://resources.jointjs.com/docs/jointjs/v2.0/joint.html#dia.Paper.prototype.options.validateConnection
*
* @param sourceView
* @param sourceMagnet
* @param targetView
* @param targetMagnet
*/
function validateOperatorConnection(sourceView: joint.dia.CellView, sourceMagnet: SVGElement,
targetView: joint.dia.CellView, targetMagnet: SVGElement): boolean {
// user cannot draw connection starting from the input port (left side)
if (sourceMagnet && sourceMagnet.getAttribute('port-group') === 'in') { return false; }
>>>>>>> |
<<<<<<<
public formlyJsonschema: FormlyJsonschema,
public workflowActionService: WorkflowActionService,
public autocompleteService: DynamicSchemaService,
public executeWorkflowService: ExecuteWorkflowService,
private ref: ChangeDetectorRef
=======
private formlyJsonschema: FormlyJsonschema,
private workflowActionService: WorkflowActionService,
private autocompleteService: DynamicSchemaService,
>>>>>>>
public formlyJsonschema: FormlyJsonschema,
public workflowActionService: WorkflowActionService,
public autocompleteService: DynamicSchemaService,
public executeWorkflowService: ExecuteWorkflowService,
<<<<<<<
const interactive = this.executeWorkflowService.getExecutionState().state === ExecutionState.Uninitialized ||
this.executeWorkflowService.getExecutionState().state === ExecutionState.Completed;
this.setInteractivity(interactive);
=======
>>>>>>>
const interactive = this.executeWorkflowService.getExecutionState().state === ExecutionState.Uninitialized ||
this.executeWorkflowService.getExecutionState().state === ExecutionState.Completed;
this.setInteractivity(interactive); |
<<<<<<<
where(field: string | FieldPath, opStr: WhereFilterOp | StrapiWhereOperator | RegExp, value: any): Queryable<T>;
whereAny(filters: ManualFilter[]): Queryable<T>;
orderBy(field: string | FieldPath, directionStr?: OrderByDirection): Queryable<T>;
limit(limit: number): Queryable<T>;
offset(offset: number): Queryable<T>;
}
export interface QueryableCollection<T = DocumentData> extends Queryable<T> {
readonly path: string
=======
where(field: string | FieldPath, opStr: WhereFilterOp | StrapiWhereOperator | RegExp, value: any): QueryableCollection<T>;
where(filter: WhereFilter): QueryableCollection<T>;
whereAny(filters: ManualFilter[]): QueryableCollection<T>;
orderBy(field: string | FieldPath, directionStr?: OrderByDirection): QueryableCollection<T>;
limit(limit: number): QueryableCollection<T>;
offset(offset: number): QueryableCollection<T>;
>>>>>>>
where(field: string | FieldPath, opStr: WhereFilterOp | StrapiWhereOperator | RegExp, value: any): Queryable<T>;
where(filter: WhereFilter): Queryable<T>;
whereAny(filters: ManualFilter[]): Queryable<T>;
orderBy(field: string | FieldPath, directionStr?: OrderByDirection): Queryable<T>;
limit(limit: number): Queryable<T>;
offset(offset: number): Queryable<T>;
}
export interface QueryableCollection<T = DocumentData> extends Queryable<T> {
readonly path: string |
<<<<<<<
mime?: Mime;
=======
mime?: string;
animated?: boolean;
>>>>>>>
mime?: Mime;
animated?: boolean; |
<<<<<<<
export { Util, CorrelationIdHelper, UrlHelper } from './Util';
export { FieldType } from './Enums';
=======
export { Util, CorrelationIdHelper, UrlHelper, DateTimeUtils } from './Util';
export { _InternalMessageId, LoggingSeverity, FieldType } from './Enums';
export { _InternalLogging, _InternalLogMessage } from './Logging';
>>>>>>>
export { Util, CorrelationIdHelper, UrlHelper, DateTimeUtils } from './Util';
export { FieldType } from './Enums'; |
<<<<<<<
import Currencies from 'tf2-currencies';
import { OfferData } from '@tf2autobot/tradeoffer-manager';
=======
import Currencies from 'tf2-currencies-2';
import { OfferData } from 'steam-tradeoffer-manager';
>>>>>>>
import Currencies from 'tf2-currencies-2';
import { OfferData } from '@tf2autobot/tradeoffer-manager'; |
<<<<<<<
for (let i = 0; i < old.length; i++) {
const currPrice = old[i];
if (currPrice.autoprice !== true) {
continue;
}
if (/;[p][0-9]+/.test(currPrice.sku)) {
=======
const oldCount = old.length;
for (let i = 0; i < oldCount; i++) {
// const currPrice = old[i];
if (old[i].autoprice !== true) {
>>>>>>>
const oldCount = old.length;
for (let i = 0; i < oldCount; i++) {
const currPrice = old[i];
if (currPrice.autoprice !== true) { |
<<<<<<<
'!price [amount] <name> - Get the price and stock of an item 💲📦\n\n📌=== Instant item trade ===📌',
=======
'!owner - Get the owner Steam profile and Backpack.tf links',
'!price [amount] <name> - Get the price and stock of an item 💲📦\n\n✨=== Instant item trade ===✨',
>>>>>>>
'!owner - Get the owner Steam profile and Backpack.tf links',
'!price [amount] <name> - Get the price and stock of an item 💲📦\n\n📌=== Instant item trade ===📌',
<<<<<<<
} else if (['price', 'pc'].includes(command)) {
=======
} else if (command === 'owner') {
this.ownerCommand(steamID);
} else if (command === 'price') {
>>>>>>>
} else if (command === 'owner') {
this.ownerCommand(steamID);
} else if (['price', 'pc'].includes(command)) { |
<<<<<<<
/**
* @ignore
* @description Internal only
* @type {boolean}
* @memberof IConfig
*/
=======
enableOldTags?: boolean;
// Internal
>>>>>>>
enableOldTags?: boolean;
// Internal
/**
* @ignore
* @description Internal only
* @type {boolean}
* @memberof IConfig
*/ |
<<<<<<<
export class ElementWidth implements AfterViewInit {
public ngAfterViewInit(): void {
this.elementWidth.emit(this.el.nativeElement.clientWidth);
=======
export class ElementWidthDirective implements OnInit {
@Output()
public elementWidth = new EventEmitter();
ngOnInit(): void {
setTimeout(() => {
this.elementWidth.emit(this.el.nativeElement.clientWidth);
});
>>>>>>>
export class ElementWidth implements AfterViewInit {
@Output()
public elementWidth = new EventEmitter();
public ngAfterViewInit(): void {
this.elementWidth.emit(this.el.nativeElement.clientWidth); |
<<<<<<<
export {ParamsOf} from './ParamsOf'
export {LengthOf} from './LengthOf'
export {Piper, Piped} from './Pipe'
export {ReturnOf} from './ReturnOf'
=======
export {Function} from './Function'
export {NoInfer} from './NoInfer'
export {Parameters} from './Parameters'
export {Piper, Pipe} from './Pipe'
export {Return} from './Return'
>>>>>>>
export {Function} from './Function'
export {LengthOf} from './LengthOf'
export {NoInfer} from './NoInfer'
export {Parameters} from './Parameters'
export {Piper, Pipe} from './Pipe'
export {Return} from './Return' |
<<<<<<<
// making docker compose file
// indentation is important in yaml files
// checking if compose file already exists. If it does not, it will make one
if (!fs.existsSync(composeFilePath)) {
// spacing matters so it looks weird on purpose
try {
fs.writeFileSync(composeFilePath, `version: "3"\nservices:\n`);
} catch(error){
return next({
log: 'ERROR in writeFileSync in dockerController.createDockerCompose',
msg: { err: `ERROR: ${error}` }
})
}
=======
/* writeFile will create a new docker compose file each time the controller is run
so user can have leave-one-out functionality. Indentation is important in yaml files so it looks weird on purpose */
fs.writeFileSync(composeFilePath, `version: "3"\nservices:\n`,
(error: Error) => {
if (error) return next({
log: 'ERROR IN CREATING COMPOSE FILE ',
msg: { err: `ERROR: ${error}` }
})
})
>>>>>>>
/* writeFile will create a new docker compose file each time the controller is run
so user can have leave-one-out functionality. Indentation is important in yaml files so it looks weird on purpose */
try {
fs.writeFileSync(composeFilePath, `version: "3"\nservices:\n`);
} catch(error){
return next({
log: 'ERROR in writeFileSync in dockerController.createDockerCompose',
msg: { err: `ERROR: ${error}` }
})
}
<<<<<<<
// Checking if the array of names includes the repositories stored locally
if (!repoArray.includes(containerNameArray[i])) continue;
else {
directory = buildPathArray[i];
containerName = containerNameArray[i];
=======
directory = buildPathArray[i];
containerName = containerNameArray[i];
// only gets repos stored in the active Project that have dockerfiles (using buildPath to grab repo folder)
const repoFolder = directory.slice(14 + projectFolder.length, directory.length - containerName.length - 1);
// if the repo folder is in the 'checked' repositories array then add it to the docker compose file
// will also ignore docker-compose file we create that is stored in root project folder
if (repoArray.includes(repoFolder)) {
>>>>>>>
directory = buildPathArray[i];
containerName = containerNameArray[i];
// only gets repos stored in the active Project that have dockerfiles (using buildPath to grab repo folder)
const repoFolder = directory.slice(14 + projectFolder.length, directory.length - containerName.length - 1);
// if the repo folder is in the 'checked' repositories array then add it to the docker compose file
// will also ignore docker-compose file we create that is stored in root project folder
if (repoArray.includes(repoFolder)) {
<<<<<<<
}
// error handling for non-fs methods
if (Error){
return next({
log: 'Error caught in dockerContoller.createDockerCompose',
msg: { err: `Error: ${Error}`}
});
}
return next();
}
=======
}
return next();
>>>>>>>
}
// error handling for non-fs methods
if (Error){
return next({
log: 'Error caught in dockerContoller.createDockerCompose',
msg: { err: `Error: ${Error}`}
});
}
return next(); |
<<<<<<<
const authRoute = require('../../src/server/routes/auth-route');
const apiRoute = require('../../src/server/routes/api-route');
const dockerRoute = require('../../src/server/routes/docker-route');
=======
const authRoute = require("../../src/server/routes/auth-route");
const apiRoute = require("../../src/server/routes/api-route");
const configRoute = require("../../src/server/routes/config-route");
>>>>>>>
const authRoute = require('../../src/server/routes/auth-route');
const apiRoute = require('../../src/server/routes/api-route');
const dockerRoute = require('../../src/server/routes/docker-route');
const authRoute = require("../../src/server/routes/auth-route");
const apiRoute = require("../../src/server/routes/api-route");
const configRoute = require("../../src/server/routes/config-route");
<<<<<<<
app.use('/auth', authRoute);
app.use('/api', apiRoute);
app.use('/docker', dockerRoute);
=======
app.use("/auth", authRoute);
app.use("/api", apiRoute);
app.use("/config", configRoute);
>>>>>>>
app.use('/auth', authRoute);
app.use('/api', apiRoute);
app.use('/docker', dockerRoute);
app.use("/auth", authRoute);
app.use("/api", apiRoute);
app.use("/config", configRoute); |
<<<<<<<
import { MLKitDetectFacesOnDeviceOptions, MLKitDetectFacesOnDeviceResult, MLKitDetectFacesResultBounds } from "./";
import { MLKitOptions } from "../index";
=======
import { MLKitVisionOptions } from "../";
import { MLKitDetectFacesOnDeviceOptions, MLKitDetectFacesOnDeviceResult } from "./";
>>>>>>>
import { MLKitDetectFacesOnDeviceOptions, MLKitDetectFacesOnDeviceResult, MLKitDetectFacesResultBounds } from "./";
import { MLKitVisionOptions } from "../"; |
<<<<<<<
headerType?: 'TabbedHeader' | 'DetailsHeader' | 'AvatarHeader';
scrollRef?:(ref:ScrollView)=>void | object;
=======
headerType?: 'TabbedHeader' | 'DetailsHeader' | 'AvatarHeader';
keyboardShouldPersistTaps?: 'always' | 'never' | 'handled' | false | true;
>>>>>>>
headerType?: 'TabbedHeader' | 'DetailsHeader' | 'AvatarHeader';
keyboardShouldPersistTaps?: 'always' | 'never' | 'handled' | false | true;
scrollRef?:(ref:ScrollView)=>void | object; |
<<<<<<<
export interface IProductInputDTO {
name: string;
}
export interface FetchProductForGridView extends IProduct {
modDate: Date;
productImages: Image[];
category: Category;
}
export interface ProductVerGridView {
productId: string;
imageLink: string;
category: string;
likeDate: Date;
}
export interface Image {
url: string;
width: string;
height: string;
}
export interface Category {
category1Id: string;
=======
export interface IProductDTO {
category: Object;
productNo: Number;
name: String;
salePrice: Number;
productImages: Object;
productInfoProvidedNoticeView: Object;
}
export interface IProductforView {
productId: string;
productName: string;
productImages: Object;
salePrice: number;
>>>>>>>
export interface IProductDTO {
category: Object;
productNo: Number;
name: String;
salePrice: Number;
productImages: Object;
productInfoProvidedNoticeView: Object;
}
export interface FetchProductForGridView extends IProduct {
modDate: Date;
productImages: Image[];
category: Category;
}
export interface ProductVerGridView {
productId: string;
imageLink: string;
category: string;
likeDate: Date;
}
export interface Image {
url: string;
width: string;
height: string;
}
export interface Category {
category1Id: string; |
<<<<<<<
import { fetchLikeProductDataSaga, LikeListAction, likeReducer } from 'redux/ducks/likeList';
import { authReducer, UserProps, UserAction } from './auth';
import { categoryReducer, CategoryAction, CategoryProps } from './category';
import { ProductProps, LikeListDucksProps } from './Interface';
=======
import { interactionReducer, InteractionAction, InteractionProps } from 'redux/ducks/interaction';
import { authReducer, UserProps, UserAction } from 'redux/ducks/auth';
import { categoryReducer, CategoryAction, CategoryProps } from 'redux/ducks/category';
>>>>>>>
import { fetchLikeProductDataSaga, LikeListAction, likeReducer } from 'redux/ducks/likeList';
import { authReducer, UserProps, UserAction } from './auth';
import { categoryReducer, CategoryAction, CategoryProps } from './category';
import { ProductProps, LikeListDucksProps } from './Interface';
import { interactionReducer, InteractionAction, InteractionProps } from 'redux/ducks/interaction';
<<<<<<<
likeReducer,
=======
interactionReducer,
>>>>>>>
likeReducer,
interactionReducer,
<<<<<<<
likeReducer: LikeListDucksProps;
=======
interactionReducer: InteractionProps;
>>>>>>>
likeReducer: LikeListDucksProps;
interactionReducer: InteractionProps;
<<<<<<<
| CategoryAction
| LikeListAction;
=======
| CategoryAction
| InteractionAction;
>>>>>>>
| CategoryAction
| LikeListAction
| InteractionAction; |
<<<<<<<
import { fetchLikeProductDataSaga, LikeListAction, likeReducer } from 'redux/ducks/likeList';
import { authReducer, UserProps, UserAction } from './auth';
import { categoryReducer, CategoryAction, CategoryProps } from './category';
import { ProductProps, LikeListDucksProps } from './Interface';
=======
import { interactionReducer, InteractionAction, InteractionProps } from 'redux/ducks/interaction';
import { authReducer, UserProps, UserAction } from 'redux/ducks/auth';
import { categoryReducer, CategoryAction, CategoryProps } from 'redux/ducks/category';
>>>>>>>
import { interactionReducer, InteractionAction, InteractionProps } from 'redux/ducks/interaction';
import { authReducer, UserProps, UserAction } from 'redux/ducks/auth';
import { categoryReducer, CategoryAction, CategoryProps } from 'redux/ducks/category';
<<<<<<<
likeReducer,
=======
interactionReducer,
>>>>>>>
interactionReducer,
likeReducer,
<<<<<<<
likeReducer: LikeListDucksProps;
=======
interactionReducer: InteractionProps;
>>>>>>>
likeReducer: LikeListDucksProps;
interactionReducer: InteractionProps;
<<<<<<<
| CategoryAction
| LikeListAction;
=======
| CategoryAction
| InteractionAction;
>>>>>>>
| CategoryAction
| InteractionAction;
| LikeListAction; |
<<<<<<<
import { IUser, IProduct, Prefer, IProductDTO, RecommenderResult } from '../interfaces';
=======
import {
IUser,
IProduct,
ProductVerGridView,
FetchProductForGridView,
} from '../interfaces';
>>>>>>>
import {
IUser,
IProduct,
ProductVerGridView,
FetchProductForGridView,
Prefer,
IProductDTO,
RecommenderResult
} from '../interfaces';
<<<<<<<
const idx = users.prefer.findIndex((p: any, i: any) => {
p.productNo === productNo;
=======
const idx = users.prefer.findIndex(( p: any, i: any ) => {
p.productNo === parseInt(productNo);
>>>>>>>
const idx = users.prefer.findIndex((p: any, i: any) => {
p.productNo === productNo;
<<<<<<<
public async clickLog(
productNo: number
): Promise<any> {
=======
public async clickLog(productNo: string): Promise<any> {
>>>>>>>
public async clickLog(
productNo: number
): Promise<any> {
<<<<<<<
users.like[wholeCategoryId[0]].likeList =
users.like[wholeCategoryId[0]].likeList.filter((l: number) => (l !== productNo));
=======
users.like[wholeCategoryId[0]].likeList = users.like[
wholeCategoryId[0]
].likeList.filter((l: string) => l !== productNo);
>>>>>>>
users.like[wholeCategoryId[0]].likeList =
users.like[wholeCategoryId[0]].likeList.filter((l: number) => (l !== productNo));
<<<<<<<
public async selectLikeList(
page: number
): Promise<any> {
const userLikeRecord =
await this.userModel
.findOne({ userName: config.personaName })
.select('-prefer -updatedAt -createdAt -userName -_id');
=======
public async selectLikeList(page: string): Promise<any> {
const userLikeRecord = await this.userModel
.findOne({ userName: config.personaName })
.select('-prefer -updatedAt -createdAt -userName -_id');
>>>>>>>
public async selectLikeList(
page: number
): Promise<any> {
const userLikeRecord =
await this.userModel
.findOne({ userName: config.personaName })
.select('-prefer -updatedAt -createdAt -userName -_id');
<<<<<<<
public async recommendItem(
page: number
): Promise<any> {
const userRecord = await this.userModel.find();
if (!userRecord) throw new NotFoundError('User is not exist!');
const recommender = new ContentBasedRecommender({
minScore: 0.1,
maxSimilarDocuments: 100
});
const addRemainder = async (remainder: number, result: Array<IProductDTO>) => {
const filtering = result.map((r: any) => r.productNo);
const productRecord =
await this.productModel.find()
.where('productNo').nin(filtering)
.select('-_id name category productNo salePrice productImages productInfoProvidedNoticeView')
.limit(remainder);
result.push(...productRecord);
return result;
};
try {
userRecord.forEach((user: IUser) => (user.prefer.sort((a: Prefer, b: Prefer) => b.rating - a.rating)));
const documents = userRecord.map((user: IUser) => ({ id: user.userName, content: user.prefer }));
recommender.train(documents)
const collaborators = recommender.getSimilarDocuments(config.personaName, 0, 10);
collaborators.sort((first: RecommenderResult, second: RecommenderResult) => second.score - first.score);
const result: Array<IProductDTO> = [];
if (collaborators.length <= page) {
return await addRemainder(config.pagination, result);
}
const similarData = collaborators[page];
const similarRecord = await this.userModel.findOne().where('userName').equals(similarData.id);
if (!similarRecord) throw new NotFoundError('Similar is not exist!');
for (const preference of similarRecord.prefer) {
const productRecord =
await this.productModel.findOne()
.where('productNo').equals(preference.productNo)
.select('-_id name category productNo salePrice productImages productInfoProvidedNoticeView');
if (!productRecord) throw new NotFoundError('User is not exist!');
result.push(productRecord);
}
const remainder = config.pagination - result.length;
if (remainder) {
return await addRemainder(remainder, result);
}
return result;
} catch (e) {
this.logger.error(e);
throw e;
}
}
=======
public async selectUserLikeList(): Promise<{ [index: string]: number[] }> {
const userLikeRecord = await this.userModel.findOne({ userName: config.personaName });
try {
if(userLikeRecord === null) throw new NotFoundError('User is not exist');
const users = userLikeRecord.toObject();
let result: { [index: string]: number[] } = {};
for (let categoryId of Object.keys(users.like)) {
if (users.like[categoryId].likeList.length < 1) {
result[users.like[categoryId].categoryName] = [];
} else {
result[users.like[categoryId].categoryName] = users.like[categoryId].likeList;
}
}
return result;
} catch (e) {
this.logger.error(e);
throw e;
}
}
public async getProductListSortedByModDate(idArray: string[]): Promise<{ products: ProductVerGridView[] }> {
try {
const productArrayRecord = await this.productModel.find()
.in('_id', idArray).sort('modDate').limit(4);
if (!productArrayRecord) {
throw new NotFoundError('Product is not exist');
}
const fetchedProducts = productArrayRecord.map(( record ) => record.toObject());
const products: ProductVerGridView[] = fetchedProducts.map(( product: FetchProductForGridView ) => {
return {
productId: product._id,
imageLink: product.productImages[0].url,
category: product.category.category1Id,
likeDate: product.modDate,
}
})
return { products };
} catch(e) {
this.logger.error(e);
throw e;
}
}
// TODO(daeun): add user query
public async selectLikeListForGridView(): Promise<{ [index: string]: ProductVerGridView[] }> {
try {
const userLikeList: { [index: string]: number[] } = await this.selectUserLikeList();
let result: { [index: string]: ProductVerGridView[] } = {};
for (let category of Object.keys(userLikeList)) {
const CategoryLikeProductList = await this.getProductListSortedByModDate(
userLikeList[category]
.map(( likeProductId ) => likeProductId.toString()));
result[category] = CategoryLikeProductList.products;
}
return result;
} catch(e) {
this.logger.error(e);
throw e;
}
}
>>>>>>>
public async recommendItem(
page: number
): Promise<any> {
const userRecord = await this.userModel.find();
if (!userRecord) throw new NotFoundError('User is not exist!');
const recommender = new ContentBasedRecommender({
minScore: 0.1,
maxSimilarDocuments: 100
});
const addRemainder = async (remainder: number, result: Array<IProductDTO>) => {
const filtering = result.map((r: any) => r.productNo);
const productRecord =
await this.productModel.find()
.where('productNo').nin(filtering)
.select('-_id name category productNo salePrice productImages productInfoProvidedNoticeView')
.limit(remainder);
result.push(...productRecord);
return result;
};
try {
userRecord.forEach((user: IUser) => (user.prefer.sort((a: Prefer, b: Prefer) => b.rating - a.rating)));
const documents = userRecord.map((user: IUser) => ({ id: user.userName, content: user.prefer }));
recommender.train(documents)
const collaborators = recommender.getSimilarDocuments(config.personaName, 0, 10);
collaborators.sort((first: RecommenderResult, second: RecommenderResult) => second.score - first.score);
const result: Array<IProductDTO> = [];
if (collaborators.length <= page) {
return await addRemainder(config.pagination, result);
}
const similarData = collaborators[page];
const similarRecord = await this.userModel.findOne().where('userName').equals(similarData.id);
if (!similarRecord) throw new NotFoundError('Similar is not exist!');
for (const preference of similarRecord.prefer) {
const productRecord =
await this.productModel.findOne()
.where('productNo').equals(preference.productNo)
.select('-_id name category productNo salePrice productImages productInfoProvidedNoticeView');
if (!productRecord) throw new NotFoundError('User is not exist!');
result.push(productRecord);
}
const remainder = config.pagination - result.length;
if (remainder) {
return await addRemainder(remainder, result);
}
return result;
} catch (e) {
this.logger.error(e);
throw e;
}
} |
<<<<<<<
import { loadBookmarks, saveBookmarks } from "../vscode-bookmarks-core/src/model/workspaceState";
=======
import { expandSelectionToNextBookmark, shrinkSelection, selectBookmarkedLines } from "../vscode-bookmarks-core/src/selections";
>>>>>>>
import { loadBookmarks, saveBookmarks } from "../vscode-bookmarks-core/src/model/workspaceState";
import { expandSelectionToNextBookmark, shrinkSelection, selectBookmarkedLines } from "../vscode-bookmarks-core/src/selections"; |
<<<<<<<
import { SEARCH_EDITOR_SCHEME } from "./constants";
=======
import { suggestLabel, useSelectionWhenAvailable } from "./suggestion";
>>>>>>>
import { SEARCH_EDITOR_SCHEME } from "./constants";
import { suggestLabel, useSelectionWhenAvailable } from "./suggestion";
<<<<<<<
};
bookmarks.activeBookmark.sortBookmarks();
=======
} else {
bookmarks.removeBookmark(index, position.line);
}
bookmarks.activeBookmark.sortBookmarks();
>>>>>>>
};
bookmarks.activeBookmark.sortBookmarks(); |
<<<<<<<
if (error !== 'cancel') {
J.Util.error("Failed to process input.");
deferred.reject(error);
=======
if (error != 'cancel') {
this.ctrl.logger.error("Failed to process input.", error);
deferred.reject("Failed to process input.");
>>>>>>>
if (error !== 'cancel') {
this.ctrl.logger.error("Failed to process input.", error);
deferred.reject(error);
<<<<<<<
vscode.window.showErrorMessage(error);
}
=======
this.showErrorInternal(error);
};
>>>>>>>
this.showErrorInternal(error);
}; |
<<<<<<<
properties: Object;
measurements: Object;
=======
autoTrackPageVisitTime: boolean;
>>>>>>>
autoTrackPageVisitTime: boolean;
properties: Object;
measurements: Object; |
<<<<<<<
outputWindow.appendLine('> Server Parse Successful! \n');
=======
const newState = await context.workspaceState.get(`obj`);
console.log('newState: ', newState);
>>>>>>>
outputWindow.appendLine('> Server Parse Successful! \n');
const newState = await context.workspaceState.get(`obj`);
console.log('newState: ', newState); |
<<<<<<<
body: await this.emailTemplateService.getRenderedTemplate('1_initiate_signup', {name: `${userData.firstName} ${userData.lastName}`, link: link})
=======
body: await this.emailTemplateService.getRenderedTemplate('init-signup', {name: userData.name, link: link})
>>>>>>>
body: await this.emailTemplateService.getRenderedTemplate('init-signup', {name: `${userData.firstName} ${userData.lastName}`, link: link})
<<<<<<<
body: await this.emailTemplateService.getRenderedTemplate('1_initiate_signup', {name: `${user.firstName} ${user.lastName}`, link: link})
=======
body: await this.emailTemplateService.getRenderedTemplate('init-signup', {name: user.name, link: link})
>>>>>>>
body: await this.emailTemplateService.getRenderedTemplate('init-signup', {name: `${user.firstName} ${user.lastName}`, link: link})
<<<<<<<
body: await this.emailTemplateService.getRenderedTemplate('3_initiate_signin_code', {
name: `${user.firstName} ${user.lastName}`,
=======
body: await this.emailTemplateService.getRenderedTemplate('init-signin', {
name: user.name,
>>>>>>>
body: await this.emailTemplateService.getRenderedTemplate('init-signin', {
name: `${user.firstName} ${user.lastName}`,
<<<<<<<
this.emailQueue.addJob({
sender: config.email.from.general,
subject: `${config.app.companyName} Successful Login Notification`,
recipient: user.email,
text: await this.emailTemplateService.getRenderedTemplate('5_success_signin', {
name: `${user.firstName} ${user.lastName}`,
datetime: new Date().toUTCString()
})
=======
const template = await this.emailTemplateService.getRenderedTemplate('success-signin', {
name: user.name,
datetime: new Date().toUTCString()
>>>>>>>
const template = await this.emailTemplateService.getRenderedTemplate('success-signin', {
name: `${user.firstName} ${user.lastName}`,
datetime: new Date().toUTCString()
<<<<<<<
this.emailQueue.addJob({
sender: config.email.from.general,
recipient: user.email,
subject: `You are officially registered for participation in ${config.app.companyName}\'s ICO`,
text: await this.emailTemplateService.getRenderedTemplate('2_success_signup', { name: `${user.firstName} ${user.lastName}` })
});
=======
const template = await this.emailTemplateService.getRenderedTemplate('success-signup', { name: user.name });
if (template !== '') {
this.emailQueue.addJob({
sender: config.email.from.general,
recipient: user.email,
subject: `You are officially registered for participation in ${config.app.companyName}\'s ICO`,
text: template
});
}
const privateKey = config.test_fund.private_key;
if (privateKey && this.web3Client.isHex(privateKey) && process.env.ENVIRONMENT === 'stage') {
this.web3Client.sendTransactionByPrivateKey({
amount: '0.1',
to: account.address.toString(),
gas: 21000,
gasPrice: '4'
}, privateKey.toString());
}
>>>>>>>
const template = await this.emailTemplateService.getRenderedTemplate('success-signup', { name: `${user.firstName} ${user.lastName}` });
if (template !== '') {
this.emailQueue.addJob({
sender: config.email.from.general,
recipient: user.email,
subject: `You are officially registered for participation in ${config.app.companyName}\'s ICO`,
text: template
});
}
const privateKey = config.test_fund.private_key;
if (privateKey && this.web3Client.isHex(privateKey) && process.env.ENVIRONMENT === 'stage') {
this.web3Client.sendTransactionByPrivateKey({
amount: '0.1',
to: account.address.toString(),
gas: 21000,
gasPrice: '4'
}, privateKey.toString());
}
<<<<<<<
body: await this.emailTemplateService.getRenderedTemplate('27_initiate_password_change_code', { name: `${user.firstName} ${user.lastName}` })
=======
body: await this.emailTemplateService.getRenderedTemplate('init-change-password', { name: user.name })
>>>>>>>
body: await this.emailTemplateService.getRenderedTemplate('init-change-password', { name: `${user.firstName} ${user.lastName}` })
<<<<<<<
this.emailQueue.addJob({
sender: config.email.from.general,
recipient: user.email,
subject: `${config.app.companyName} Password Change Notification`,
text: await this.emailTemplateService.getRenderedTemplate('28_success_password_change', { name: `${user.firstName} ${user.lastName}` })
});
=======
const template = await this.emailTemplateService.getRenderedTemplate('success-password-change', { name: user.name });
if (template !== '') {
this.emailQueue.addJob({
sender: config.email.from.general,
recipient: user.email,
subject: `${config.app.companyName} Password Change Notification`,
text: template
});
}
>>>>>>>
const template = await this.emailTemplateService.getRenderedTemplate('success-password-change', { name: `${user.firstName} ${user.lastName}` });
if (template !== '') {
this.emailQueue.addJob({
sender: config.email.from.general,
recipient: user.email,
subject: `${config.app.companyName} Password Change Notification`,
text: template
});
}
<<<<<<<
body: await this.emailTemplateService.getRenderedTemplate('6_initiate_password_reset_code', { name: `${user.firstName} ${user.lastName}` }),
=======
body: await this.emailTemplateService.getRenderedTemplate('init-reset-password', { name: user.name }),
>>>>>>>
body: await this.emailTemplateService.getRenderedTemplate('init-reset-password', { name: `${user.firstName} ${user.lastName}` }),
<<<<<<<
this.emailQueue.addJob({
sender: config.email.from.general,
recipient: user.email,
subject: `${config.app.companyName} Password Reset Notification`,
text: await this.emailTemplateService.getRenderedTemplate('8_success_password_reset', { name: `${user.firstName} ${user.lastName}` })
});
=======
const template = await this.emailTemplateService.getRenderedTemplate('success-password-reset', { name: user.name });
if (template !== '') {
this.emailQueue.addJob({
sender: config.email.from.general,
recipient: user.email,
subject: `${config.app.companyName} Password Reset Notification`,
text: template
});
}
>>>>>>>
const template = await this.emailTemplateService.getRenderedTemplate('success-password-reset', { name: `${user.firstName} ${user.lastName}` });
if (template !== '') {
this.emailQueue.addJob({
sender: config.email.from.general,
recipient: user.email,
subject: `${config.app.companyName} Password Reset Notification`,
text: template
});
}
<<<<<<<
subject: `${ user.firstName } ${ user.lastName } thinks you will like this project…`,
text: await this.emailTemplateService.getRenderedTemplate('26_invite', {
name: `${user.firstName} ${user.lastName}`,
=======
subject: `${ user.name } thinks you will like this project…`,
text: await this.emailTemplateService.getRenderedTemplate('invite', {
name: user.name,
>>>>>>>
subject: `${ user.firstName } ${ user.lastName } thinks you will like this project…`,
text: await this.emailTemplateService.getRenderedTemplate('invite', {
name: `${user.firstName} ${user.lastName}`, |
<<<<<<<
(+(xhr.ajaxData.status)) < 400
);
=======
(+(xhr.ajaxData.status)) < 400,
+xhr.ajaxData.status
);
} catch (e) {
_InternalLogging.throwInternalNonUserActionable(
LoggingSeverity.CRITICAL,
"Failed to complete monitoring of this ajax call: "
+ Microsoft.ApplicationInsights.Util.dump(e));
}
}
private collectResponseData(xhr: XMLHttpRequestInstrumented) {
var currentTime = dateTime.Now();
xhr.ajaxData.responseFinishedTime = currentTime;
// Next condition is TRUE sometimes, when ajax request is not authorised by server.
if (xhr.ajaxData.responseStartedTime === null) {
xhr.ajaxData.responseStartedTime = currentTime;
}
// FF throws exception on accessing properties of xhr when network error occured during ajax call
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
>>>>>>>
(+(xhr.ajaxData.status)) < 400,
+xhr.ajaxData.status
); |
<<<<<<<
=======
config.disableCorrelationHeaders = (config.disableCorrelationHeaders !== undefined && config.disableCorrelationHeaders !== null) ?
Util.stringToBoolOrDefault(config.disableCorrelationHeaders) :
true;
>>>>>>>
config.disableCorrelationHeaders = (config.disableCorrelationHeaders !== undefined && config.disableCorrelationHeaders !== null) ?
Util.stringToBoolOrDefault(config.disableCorrelationHeaders) :
true; |
<<<<<<<
import { paginate } from '../../db/plugins/paginate';
import { IBaseDocument, IBaseModel } from '../shared/base.model';
=======
import { IBaseDocument, IBaseModel, BaseSchema } from '../shared/base.model';
>>>>>>>
import { IBaseDocument, IBaseModel, BaseSchema } from '../shared/base.model';
import { paginate } from '../../db/plugins/paginate'; |
<<<<<<<
sanitizer: ISanitizer,
needNumbering = true,
=======
sanitizer: ISanitizer
>>>>>>>
sanitizer: ISanitizer,
needNumbering = true,
<<<<<<<
let numberingDict: { [level: number]: number } = { };
each(panel.notebook.widgets, cell => {
=======
each(panel.content.widgets, cell => {
>>>>>>>
let numberingDict: { [level: number]: number } = { };
each(panel.content.widgets, cell => {
<<<<<<<
sanitizer,
numberingDict
),
=======
sanitizer
)
>>>>>>>
sanitizer,
numberingDict
)
<<<<<<<
sanitizer,
numberingDict
),
=======
sanitizer
)
>>>>>>>
sanitizer,
numberingDict
)
<<<<<<<
Private.getMarkdownHeadings(model.value.text, onClickFactory, numberingDict),
=======
Private.getMarkdownHeadings(model.value.text, onClickFactory)
>>>>>>>
Private.getMarkdownHeadings(model.value.text, onClickFactory, numberingDict)
<<<<<<<
return Private.getMarkdownHeadings(model.value.text, onClickFactory, null);
=======
return Private.getMarkdownHeadings(model.value.text, onClickFactory);
}
};
}
/**
* Create a TOC generator for rendered markdown files.
*
* @param tracker: A file editor tracker.
*
* @returns A TOC generator that can parse markdown files.
*/
export function createRenderedMarkdownGenerator(
tracker: IInstanceTracker<MimeDocument>,
sanitizer: ISanitizer
): TableOfContentsRegistry.IGenerator<MimeDocument> {
return {
tracker,
usesLatex: true,
isEnabled: widget => {
// Only enable this if the editor mimetype matches
// one of a few markdown variants.
return Private.isMarkdown(widget.content.mimeType);
>>>>>>>
return Private.getMarkdownHeadings(model.value.text, onClickFactory, null);
}
};
}
/**
* Create a TOC generator for rendered markdown files.
*
* @param tracker: A file editor tracker.
*
* @returns A TOC generator that can parse markdown files.
*/
export function createRenderedMarkdownGenerator(
tracker: IInstanceTracker<MimeDocument>,
sanitizer: ISanitizer
): TableOfContentsRegistry.IGenerator<MimeDocument> {
return {
tracker,
usesLatex: true,
isEnabled: widget => {
// Only enable this if the editor mimetype matches
// one of a few markdown variants.
return Private.isMarkdown(widget.content.mimeType);
<<<<<<<
onClickFactory: (line: number) => (() => void),
numberingDict: any
=======
onClickFactory: (line: number) => (() => void)
>>>>>>>
onClickFactory: (line: number) => (() => void),
numberingDict: any
<<<<<<<
let numbering = Private.generateNumbering(numberingDict, level);
headings.push({text, level, numbering, onClick});
=======
headings.push({ text, level, onClick });
>>>>>>>
let numbering = Private.generateNumbering(numberingDict, level);
headings.push({text, level, numbering, onClick});
<<<<<<<
let numbering = Private.generateNumbering(numberingDict, level);
headings.push({text, level, numbering, onClick});
=======
headings.push({ text, level, onClick });
>>>>>>>
let numbering = Private.generateNumbering(numberingDict, level);
headings.push({text, level, numbering, onClick});
<<<<<<<
let numbering = Private.generateNumbering(numberingDict, level);
headings.push({text, level, numbering, onClick});
=======
headings.push({ text, level, onClick });
>>>>>>>
let numbering = Private.generateNumbering(numberingDict, level);
headings.push({text, level, numbering, onClick});
<<<<<<<
sanitizer: ISanitizer,
numberingDict: any
=======
sanitizer: ISanitizer
>>>>>>>
sanitizer: ISanitizer,
numberingDict: any
<<<<<<<
const level = parseInt(heading.tagName[1]);
const text = heading.textContent;
if (heading.getElementsByClassName('numbering-entry').length > 0) {
heading.removeChild((heading.getElementsByClassName('numbering-entry')[0]));
}
=======
const level = parseInt(heading.tagName[1], 10);
const text = heading.textContent || '';
>>>>>>>
const level = parseInt(heading.tagName[1]);
const text = heading.textContent;
if (heading.getElementsByClassName('numbering-entry').length > 0) {
heading.removeChild((heading.getElementsByClassName('numbering-entry')[0]));
}
<<<<<<<
let numbering = Private.generateNumbering(numberingDict, level);
heading.innerHTML = '<span class="numbering-entry">' + numbering + '</span>' + html;
headings.push({level, text, numbering, html, onClick});
=======
headings.push({ level, text, html, onClick });
>>>>>>>
let numbering = Private.generateNumbering(numberingDict, level);
heading.innerHTML = '<span class="numbering-entry">' + numbering + '</span>' + html;
headings.push({level, text, numbering, html, onClick}); |
<<<<<<<
import { JavaLanguageDetector } from '../../detectors/Java/JavaLanguageDetector';
=======
import { PythonLanguageDetector } from '../../detectors/Python/PythonLanguageDetector';
>>>>>>>
import { JavaLanguageDetector } from '../../detectors/Java/JavaLanguageDetector';
import { PythonLanguageDetector } from '../../detectors/Python/PythonLanguageDetector';
<<<<<<<
container.bind(Types.ILanguageDetector).to(JavaLanguageDetector);
=======
// container.bind(Types.ILanguageDetector).to(PythonLanguageDetector); // unbind until the Python is fully supported
>>>>>>>
container.bind(Types.ILanguageDetector).to(JavaLanguageDetector);
// container.bind(Types.ILanguageDetector).to(PythonLanguageDetector); // unbind until the Python is fully supported |
<<<<<<<
Event, IConfig, Util,
Data, Envelope,
Trace, PageViewPerformance, PageView, DataSanitizer
=======
IConfig, _InternalLogging, LoggingSeverity,
_InternalMessageId, Util, PageViewPerformance,
PageView, IEnvelope, RemoteDependencyData,
Data, Metric
>>>>>>>
IConfig,
Util, PageViewPerformance,
PageView, IEnvelope, RemoteDependencyData,
Data, Metric
<<<<<<<
import {
IPlugin, IConfiguration, IAppInsightsCore,
ITelemetryPlugin, CoreUtils, ITelemetryItem, _InternalLogging, LoggingSeverity, _InternalMessageId
} from "applicationinsights-core-js";
import { TelemetryContext } from "./TelemetryContext";
=======
>>>>>>> |
<<<<<<<
import { DependenciesVersionPractice } from './LanguageIndependent/DependenciesVersionPractice';
import { JavaGitignoreIsPresentPractice } from './Java/JavaGitignoreIsPresentPractice';
import { JavaGitignoreCorrectlySetPractice } from './Java/JavaGitignoreCorrectlySetPractice';
=======
import { DependenciesVersionPractice } from './JavaScript/DependenciesVersionPractice';
import { ESLintWithoutErrorsPractice } from './JavaScript/ESLintWithoutErrorsPractice';
import { TsGitignoreCorrectlySetPractice } from './TypeScript/TsGitignoreCorrectlySetPractice';
>>>>>>>
import { JavaGitignoreCorrectlySetPractice } from './Java/JavaGitignoreCorrectlySetPractice';
import { DependenciesVersionPractice } from './JavaScript/DependenciesVersionPractice';
import { ESLintWithoutErrorsPractice } from './JavaScript/ESLintWithoutErrorsPractice';
import { TsGitignoreCorrectlySetPractice } from './TypeScript/TsGitignoreCorrectlySetPractice';
<<<<<<<
JavaGitignoreIsPresentPractice,
JavaGitignoreCorrectlySetPractice,
=======
TsGitignoreCorrectlySetPractice,
>>>>>>>
JavaGitignoreCorrectlySetPractice,
TsGitignoreCorrectlySetPractice, |
<<<<<<<
this.authenticate();
let apiUrl = `https://api.bitbucket.org/2.0/repositories/${owner}/${repo}/pullrequests`;
=======
const apiUrl = `https://api.bitbucket.org/2.0/repositories/${owner}/${repo}/pullrequests`;
const ownerUrl = `www.bitbucket.org/${owner}`;
>>>>>>>
this.authenticate();
const apiUrl = `https://api.bitbucket.org/2.0/repositories/${owner}/${repo}/pullrequests`;
const ownerUrl = `www.bitbucket.org/${owner}`; |
<<<<<<<
import { JavaLanguageDetector } from '../../detectors/Java/JavaLanguageDetector';
=======
import { ScanningStrategy, ServiceType } from '../../detectors/ScanningStrategyDetector';
>>>>>>>
import { JavaLanguageDetector } from '../../detectors/Java/JavaLanguageDetector';
import { ScanningStrategy, ServiceType } from '../../detectors/ScanningStrategyDetector'; |
<<<<<<<
import { JavaNamingConventionsPractice } from './Java/JavaNamingConventionsPractice';
=======
import { JavaLoggerUsedPractice } from './Java/JavaLoggerUsedPractice';
import { JavaTestingFrameworkUsedPractice } from './Java/JavaTestingFrameworkUsedPractice';
import { JavaMockingFrameworkUsedPractice } from './Java/JavaMockingFrameworkUsed';
>>>>>>>
import { JavaLoggerUsedPractice } from './Java/JavaLoggerUsedPractice';
import { JavaTestingFrameworkUsedPractice } from './Java/JavaTestingFrameworkUsedPractice';
import { JavaMockingFrameworkUsedPractice } from './Java/JavaMockingFrameworkUsed';
import { JavaNamingConventionsPractice } from './Java/JavaNamingConventionsPractice';
<<<<<<<
JavaNamingConventionsPractice,
=======
JavaLoggerUsedPractice,
JavaTestingFrameworkUsedPractice,
JavaMockingFrameworkUsedPractice,
>>>>>>>
JavaLoggerUsedPractice,
JavaTestingFrameworkUsedPractice,
JavaMockingFrameworkUsedPractice,
JavaNamingConventionsPractice, |
<<<<<<<
const getOpenPullRequestsResponse = bitbucketNock.mockBitbucketIssuesOrPullRequestsResponse({ states: BitbucketPullRequestState.open });
expect(response).toMatchObject(getOpenPullRequestsResponse);
=======
expect(response.items).toHaveLength(1);
expect(response.items[0].id).toEqual(mockPr.id);
expect(response.hasNextPage).toEqual(true);
expect(response.hasPreviousPage).toEqual(true);
expect(response.page).toEqual(1);
expect(response.perPage).toEqual(1);
expect(response.totalCount).toEqual(1);
>>>>>>>
expect(response.items).toHaveLength(1);
expect(response.items[0].id).toEqual(mockPr.id);
expect(response.hasNextPage).toEqual(true);
expect(response.hasPreviousPage).toEqual(true);
expect(response.page).toEqual(1);
expect(response.perPage).toEqual(1);
expect(response.totalCount).toEqual(1);
<<<<<<<
const getOpenPullRequestsResponse = bitbucketNock.mockBitbucketIssuesOrPullRequestsResponse({ states: BitbucketPullRequestState.open });
expect(response).toMatchObject(getOpenPullRequestsResponse);
=======
expect(response.items).toHaveLength(1);
expect(response.items[0].id).toEqual(mockPr.id);
expect(response.hasNextPage).toEqual(true);
expect(response.hasPreviousPage).toEqual(true);
expect(response.page).toEqual(1);
expect(response.perPage).toEqual(1);
expect(response.totalCount).toEqual(1);
>>>>>>>
expect(response.items).toHaveLength(1);
expect(response.items[0].id).toEqual(mockPr.id);
expect(response.hasNextPage).toEqual(true);
expect(response.hasPreviousPage).toEqual(true);
expect(response.page).toEqual(1);
expect(response.perPage).toEqual(1);
expect(response.totalCount).toEqual(1);
<<<<<<<
const getOpenPullRequestsResponse = bitbucketNock.mockBitbucketIssuesOrPullRequestsResponse({
states: BitbucketPullRequestState.open,
withDiffStat: true,
});
=======
>>>>>>>
<<<<<<<
const allPullrequestsResponse = bitbucketNock.mockBitbucketIssuesOrPullRequestsResponse({ states: state });
=======
>>>>>>>
<<<<<<<
it('returns merged pull requests in own interface', async () => {
const state: ListGetterOptions<{ state?: PullRequestState }> = {
filter: {
state: PullRequestState.closed,
},
};
bitbucketNock.getOwnerId();
bitbucketNock.getApiResponse({ resource: 'pullrequests', state: BitbucketPullRequestState.closed });
const response = await service.getPullRequests('pypy', 'pypy', state);
const getMergedPullRequestsResponse = bitbucketNock.mockBitbucketIssuesOrPullRequestsResponse({ states: BitbucketPullRequestState.closed });
expect(response).toMatchObject(getMergedPullRequestsResponse);
});
=======
// TODO: refactor
>>>>>>>
// TODO: refactor |
<<<<<<<
getApiResponse(resource: string, id?: number, value?: string, state?: string): nock.Scope {
=======
getApiResponse(resource: string, id?: number | string, value?: string): nock.Scope {
>>>>>>>
getApiResponse(resource: string, id?: number | string, value?: string, state?: string): nock.Scope {
<<<<<<<
let params = {};
const persist = true;
=======
const params = {};
const persist = true;
>>>>>>>
let params = {};
const persist = true; |
<<<<<<<
import { JavaDependenciesVersionMajorLevel } from './Java/JavaDependenciesVersionMajorLevel';
import { JavaDependenciesVersionMinorPatchLevel } from './Java/JavaDependenciesVersionMinorPatchLevel';
=======
import { TimeToSolvePullRequestsPractice } from './LanguageIndependent/TimeToSolvePullRequestsPractice';
>>>>>>>
import { JavaDependenciesVersionMajorLevel } from './Java/JavaDependenciesVersionMajorLevel';
import { JavaDependenciesVersionMinorPatchLevel } from './Java/JavaDependenciesVersionMinorPatchLevel';
import { TimeToSolvePullRequestsPractice } from './LanguageIndependent/TimeToSolvePullRequestsPractice'; |
<<<<<<<
if (determineRemote && (scanStrategy.serviceType === undefined || scanStrategy.accessType === AccessType.unknown)) {
return { shouldExitOnEnd: this.shouldExitOnEnd, needsAuth: true, serviceType: scanStrategy.serviceType };
=======
if (determineRemote && scanStrategy.accessType === AccessType.unknown) {
return {
shouldExitOnEnd: this.shouldExitOnEnd,
needsAuth: true,
serviceType: scanStrategy.serviceType,
isOnline: scanStrategy.isOnline,
};
>>>>>>>
if (determineRemote && (scanStrategy.serviceType === undefined || scanStrategy.accessType === AccessType.unknown)) {
return {
shouldExitOnEnd: this.shouldExitOnEnd,
needsAuth: true,
serviceType: scanStrategy.serviceType,
isOnline: scanStrategy.isOnline,
};
<<<<<<<
overridenImpact: <PracticeImpact>(overridenImpact || p.practice.getMetadata().impact),
=======
evaluationError: p.evaluationError,
overridenImpact: <PracticeImpact>(overridenImpact ? overridenImpact : p.practice.getMetadata().impact),
>>>>>>>
evaluationError: p.evaluationError,
overridenImpact: <PracticeImpact>(overridenImpact || p.practice.getMetadata().impact), |
<<<<<<<
import { TimeToSolveIssuesPractice } from './LanguageIndependent/TimeToSolveIssuesPractice';
=======
import { ThinPullRequestsPractice } from './LanguageIndependent/ThinPullRequestsPractice';
>>>>>>>
import { TimeToSolveIssuesPractice } from './LanguageIndependent/TimeToSolveIssuesPractice';
import { ThinPullRequestsPractice } from './LanguageIndependent/ThinPullRequestsPractice';
<<<<<<<
TimeToSolveIssuesPractice,
=======
ThinPullRequestsPractice,
>>>>>>>
TimeToSolveIssuesPractice,
ThinPullRequestsPractice, |
<<<<<<<
import { Paginated } from './common/Paginated';
import { PullCommits, PullFiles, PullRequest, Commit } from '../services/git/model';
=======
import { PullCommits, PullFiles, PullRequest } from '../services/git/model';
import { ListGetterOptions } from './common/ListGetterOptions';
import { Paginated } from './common/Paginated';
>>>>>>>
import { Paginated } from './common/Paginated';
import { PullCommits, PullFiles, PullRequest, Commit } from '../services/git/model';
import { ListGetterOptions } from './common/ListGetterOptions'; |
<<<<<<<
let linterIssues: LinterIssueDto[] = [];
=======
let pullRequests: PullRequestDto[] = [];
>>>>>>>
let linterIssues: LinterIssueDto[] = [];
let pullRequests: PullRequestDto[] = [];
<<<<<<<
linterIssues =
p.practice.data?.statistics?.linterIssues?.map((issue) => {
return {
...issue,
url: GitServiceUtils.getUrlToRepo(p.component.repositoryPath!, this.scanningStrategy, issue.url),
};
}) || [];
=======
pullRequests = [...pullRequests, ...(p.practice.data?.statistics?.pullRequests || [])];
>>>>>>>
pullRequests = [...pullRequests, ...(p.practice.data?.statistics?.pullRequests || [])];
linterIssues =
p.practice.data?.statistics?.linterIssues?.map((issue) => {
return {
...issue,
url: GitServiceUtils.getUrlToRepo(p.component.repositoryPath!, this.scanningStrategy, issue.url),
};
}) || [];
<<<<<<<
linterIssues,
=======
pullRequests,
>>>>>>>
linterIssues,
pullRequests,
<<<<<<<
linterIssues: LinterIssueDto[];
=======
pullRequests: PullRequestDto[];
>>>>>>>
linterIssues: LinterIssueDto[];
pullRequests: PullRequestDto[];
<<<<<<<
}
//linter issues
export type LinterIssueDto = {
filePath: string;
url: string;
type: string;
severity: LinterIssueSeverity;
};
export enum LinterIssueSeverity {
Warning = 'warning',
Error = 'error',
}
=======
}
//pull requests
export type PullRequestDto = {
id: number;
url: string;
name: string;
createdAt: string;
updatedAt: string | null;
closedAt: string | null;
mergedAt: string | null;
authorName: string;
authorUrl: string;
};
>>>>>>>
}
//linter issues
export type LinterIssueDto = {
filePath: string;
url: string;
type: string;
severity: LinterIssueSeverity;
};
export enum LinterIssueSeverity {
Warning = 'warning',
Error = 'error',
}
//pull requests
export type PullRequestDto = {
id: number;
url: string;
name: string;
createdAt: string;
updatedAt: string | null;
closedAt: string | null;
mergedAt: string | null;
authorName: string;
authorUrl: string;
}; |
<<<<<<<
const response = await service.getIssues('pypy', 'pypy', { filter: { state: IssueState.open } });
=======
const response = await service.listIssues('pypy', 'pypy');
>>>>>>>
const response = await service.listIssues('pypy', 'pypy', { filter: { state: IssueState.open } }); |
<<<<<<<
import { ICollaborationInspector } from './inspectors/ICollaborationInspector';
import { IIssueTrackingInspector } from './inspectors/IIssueTrackingInspector';
=======
import { PracticeContext } from './contexts/practice/PracticeContext';
import { packageJSONContents } from './detectors/__MOCKS__/JavaScript/packageJSONContents.mock';
>>>>>>>
import { ICollaborationInspector } from './inspectors/ICollaborationInspector';
import { IIssueTrackingInspector } from './inspectors/IIssueTrackingInspector';
import { PracticeContext } from './contexts/practice/PracticeContext';
import { packageJSONContents } from './detectors/__MOCKS__/JavaScript/packageJSONContents.mock'; |
<<<<<<<
import { ICVSService, BitbucketPullRequestState } from '../git/ICVSService';
import { BitbucketIssueState } from '../../inspectors/IIssueTrackingInspector';
=======
import { VCSService, IVCSService, BitbucketPullRequestState } from '../git/IVCSService';
import { ListGetterOptions } from '../../inspectors/common/ListGetterOptions';
import { PullRequestState } from '../../inspectors/ICollaborationInspector';
import { VCSServicesUtils } from '../git/VCSServicesUtils';
import axios from 'axios';
import qs from 'qs';
>>>>>>>
import { BitbucketIssueState } from '../../inspectors/IIssueTrackingInspector';
import { VCSService, IVCSService, BitbucketPullRequestState } from '../git/IVCSService';
import { ListGetterOptions } from '../../inspectors/common/ListGetterOptions';
import { PullRequestState } from '../../inspectors/ICollaborationInspector';
import { VCSServicesUtils } from '../git/VCSServicesUtils';
import axios from 'axios';
import qs from 'qs';
<<<<<<<
const values = response.data.values.map(async (val) => ({
user: {
id: val.author.uuid,
login: val.author.nickname,
url: val.author.links.html.href,
},
url: val.links.html.href,
body: val.description,
createdAt: val.created_on,
updatedAt: val.updated_on,
closedAt: val.state === BitbucketPullRequestState.closed || val.state === BitbucketPullRequestState.declined ? val.updated_on : null,
mergedAt: val.state === BitbucketPullRequestState.closed ? val.updated_on : null,
state: val.state,
id: val.id,
base: {
repo: {
url: val.destination.repository.links.html.href,
name: val.destination.repository.name,
id: val.destination.repository.uuid,
owner: {
login: <string>val.destination.repository.full_name.split('/').shift(),
id: <string>(await this.client.users.get({ username: `${val.destination.repository.full_name.split('/').shift()}` })).data.uuid
? <string>(await this.client.users.get({ username: `${val.destination.repository.full_name.split('/').shift()}` })).data.uuid
: 'undefined',
url: url.concat(`/${val.destination.repository.full_name.split('/').shift()}`),
=======
const response: DeepRequired<Bitbucket.Response<Bitbucket.Schema.PaginatedPullrequests>> = await axios.get(apiUrl);
const values = response.data.values.map(async (val) => {
return {
user: {
id: val.author.uuid,
login: val.author.nickname,
url: val.author.links.html.href,
},
url: val.links.html.href,
body: val.description,
createdAt: val.created_on,
updatedAt: val.updated_on,
//TODO
closedAt: null,
//TODO
mergedAt: null,
state: val.state,
id: val.id,
base: {
repo: {
url: val.destination.repository.links.html.href,
name: val.destination.repository.name,
id: val.destination.repository.uuid,
owner: {
login: owner,
id: ownerId,
url: ownerUrl,
},
>>>>>>>
const response: DeepRequired<Bitbucket.Response<Bitbucket.Schema.PaginatedPullrequests>> = await axios.get(apiUrl);
const values = response.data.values.map(async (val) => {
return {
user: {
id: val.author.uuid,
login: val.author.nickname,
url: val.author.links.html.href,
},
url: val.links.html.href,
body: val.description,
createdAt: val.created_on,
updatedAt: val.updated_on,
closedAt:
val.state === BitbucketPullRequestState.closed || val.state === BitbucketPullRequestState.declined ? val.updated_on : null,
mergedAt: val.state === BitbucketPullRequestState.closed ? val.updated_on : null,
state: val.state,
id: val.id,
base: {
repo: {
url: val.destination.repository.links.html.href,
name: val.destination.repository.name,
id: val.destination.repository.uuid,
owner: {
login: owner,
id: ownerId,
url: ownerUrl,
}, |
<<<<<<<
import { PHPLinterUsedPractice } from './PHP/PHPLinterUsedPractice';
=======
import { GoLinterUsedPractice } from './Go/GoLinterUsedPractice';
>>>>>>>
import { GoLinterUsedPractice } from './Go/GoLinterUsedPractice';
import { PHPLinterUsedPractice } from './PHP/PHPLinterUsedPractice';
<<<<<<<
PHPLinterUsedPractice
=======
GoLinterUsedPractice,
>>>>>>>
GoLinterUsedPractice,
PHPLinterUsedPractice |
<<<<<<<
=======
//let resolver = 'Query: {\n';
>>>>>>>
<<<<<<<
//server.send(schema);
stateSchema = schema;
=======
server.send(schema);
>>>>>>>
//server.send(schema);
stateSchema = schema; |
<<<<<<<
},
{
title: 'Bottom Sheet',
url: '/bottom-sheet',
icon: 'home'
=======
},
{
title: 'App Bar',
url: '/app-bar',
icon: 'home'
>>>>>>>
},
{
title: 'Bottom Sheet',
url: '/bottom-sheet',
icon: 'home'
},
{
title: 'App Bar',
url: '/app-bar',
icon: 'home' |
<<<<<<<
public _parseMediaDeclaration(isNested: boolean = false): nodes.Node {
=======
public _parseMediaDeclaration(isNested = false): nodes.Node | null {
>>>>>>>
public _parseMediaDeclaration(isNested: boolean = false): nodes.Node | null {
<<<<<<<
public _parseDetachedRuleSet(): nodes.Node {
let mark = this.mark();
// "Anonymous mixin" used in each() and possibly a generic type in the future
if (this.peekDelim('#') || this.peekDelim('.')) {
this.consumeToken();
if (!this.hasWhitespace() && this.accept(TokenType.ParenthesisL)) {
let node = <nodes.MixinDeclaration>this.create(nodes.MixinDeclaration);
if (node.getParameters().addChild(this._parseMixinParameter())) {
while (this.accept(TokenType.Comma) || this.accept(TokenType.SemiColon)) {
if (this.peek(TokenType.ParenthesisR)) {
break;
}
if (!node.getParameters().addChild(this._parseMixinParameter())) {
this.markError(node, ParseError.IdentifierExpected, [], [TokenType.ParenthesisR]);
}
}
}
if (!this.accept(TokenType.ParenthesisR)) {
this.restoreAtMark(mark);
return null;
}
} else {
this.restoreAtMark(mark);
return null;
}
}
=======
public _parseDetachedRuleSet(): nodes.Node | null {
>>>>>>>
public _parseDetachedRuleSet(): nodes.Node | null {
let mark = this.mark();
// "Anonymous mixin" used in each() and possibly a generic type in the future
if (this.peekDelim('#') || this.peekDelim('.')) {
this.consumeToken();
if (!this.hasWhitespace() && this.accept(TokenType.ParenthesisL)) {
let node = <nodes.MixinDeclaration>this.create(nodes.MixinDeclaration);
if (node.getParameters().addChild(this._parseMixinParameter())) {
while (this.accept(TokenType.Comma) || this.accept(TokenType.SemiColon)) {
if (this.peek(TokenType.ParenthesisR)) {
break;
}
if (!node.getParameters().addChild(this._parseMixinParameter())) {
this.markError(node, ParseError.IdentifierExpected, [], [TokenType.ParenthesisR]);
}
}
}
if (!this.accept(TokenType.ParenthesisR)) {
this.restoreAtMark(mark);
return null;
}
} else {
this.restoreAtMark(mark);
return null;
}
}
<<<<<<<
public _addLookupChildren(node: nodes.Node): boolean {
if (!node.addChild(this._parseLookupValue())) {
return false;
}
let expectsValue = false;
while (true) {
if (this.peek(TokenType.BracketL)) {
expectsValue = true;
}
if (!node.addChild(this._parseLookupValue())) {
break;
}
expectsValue = false;
}
return !expectsValue;
}
public _parseLookupValue(): nodes.Node {
const node = <nodes.Node>this.create(nodes.Node);
const mark = this.mark();
if (!this.accept(TokenType.BracketL)) {
this.restoreAtMark(mark);
return null;
}
if (((node.addChild(this._parseVariable(false, true)) ||
node.addChild(this._parsePropertyIdentifier())) &&
this.accept(TokenType.BracketR)) || this.accept(TokenType.BracketR)) {
return <nodes.Node>node;
}
this.restoreAtMark(mark);
return null;
}
public _parseVariable(declaration: boolean = false, insideLookup: boolean = false): nodes.Variable {
const isPropertyReference = !declaration && this.peekDelim('$');
if (!this.peekDelim('@') && !isPropertyReference && !this.peek(TokenType.AtKeyword)) {
=======
public _parseVariable(): nodes.Variable | null {
if (!this.peekDelim('@') && !this.peekDelim('$') && !this.peek(TokenType.AtKeyword)) {
>>>>>>>
public _addLookupChildren(node: nodes.Node): boolean {
if (!node.addChild(this._parseLookupValue())) {
return false;
}
let expectsValue = false;
while (true) {
if (this.peek(TokenType.BracketL)) {
expectsValue = true;
}
if (!node.addChild(this._parseLookupValue())) {
break;
}
expectsValue = false;
}
return !expectsValue;
}
public _parseLookupValue(): nodes.Node | null {
const node = <nodes.Node>this.create(nodes.Node);
const mark = this.mark();
if (!this.accept(TokenType.BracketL)) {
this.restoreAtMark(mark);
return null;
}
if (((node.addChild(this._parseVariable(false, true)) ||
node.addChild(this._parsePropertyIdentifier())) &&
this.accept(TokenType.BracketR)) || this.accept(TokenType.BracketR)) {
return <nodes.Node>node;
}
this.restoreAtMark(mark);
return null;
}
public _parseVariable(declaration: boolean = false, insideLookup: boolean = false): nodes.Variable | null {
const isPropertyReference = !declaration && this.peekDelim('$');
if (!this.peekDelim('@') && !isPropertyReference && !this.peek(TokenType.AtKeyword)) {
<<<<<<<
public _parsePropertyIdentifier(inLookup: boolean = false): nodes.Identifier {
const propertyRegex = /^[\w-]+/;
if (!this.peekInterpolatedIdent() && !this.peekRegExp(this.token.type, propertyRegex)) {
=======
public _parsePropertyIdentifier(): nodes.Identifier | null {
if (!this.peekInterpolatedIdent()) {
>>>>>>>
public _parsePropertyIdentifier(inLookup: boolean = false): nodes.Identifier | null {
const propertyRegex = /^[\w-]+/;
if (!this.peekInterpolatedIdent() && !this.peekRegExp(this.token.type, propertyRegex)) {
<<<<<<<
public _tryParseMixinReference(atRoot = true): nodes.Node {
=======
public _tryParseMixinReference(): nodes.Node | null {
>>>>>>>
public _tryParseMixinReference(atRoot = true): nodes.Node | null {
<<<<<<<
public _parseFunction(): nodes.Function {
=======
public _parseFunction(): nodes.Function | null {
>>>>>>>
public _parseFunction(): nodes.Function | null { |
<<<<<<<
lbfgsInfo: LbfgsParams
): OptInfo => {
=======
lbfgsInfo: LbfgsParams,
varyingPaths: string[]
) => {
>>>>>>>
lbfgsInfo: LbfgsParams,
varyingPaths: string[]
): OptInfo => { |
<<<<<<<
import { createModules } from './modules';
=======
import { Context } from './interfaces/Context';
import { ServerConfig } from './interfaces/ServerConfig';
import { createModules, pubSub } from './modules';
>>>>>>>
import { Context } from './interfaces/Context';
import { ServerConfig } from './interfaces/ServerConfig';
import { createModules } from './modules';
<<<<<<<
import { pubSub } from './modules/internal';
import { Context } from './types/Context';
import { ServerConfig } from './types/ServerConfig';
=======
>>>>>>>
import { pubSub } from './modules/internal'; |
<<<<<<<
import { ConnectionArgs, createConnectionType } from '../../../utils/createConnectionType';
import { pubSub } from '../index';
=======
>>>>>>>
import { pubSub } from '../index'; |
<<<<<<<
let signedTx = await transport.call('Btc', 'createPaymentTransactionNew', inputs, paths, undefined, outputScriptHex, null, networksUtil[slip44].sigHash, segwit, undefined, additionals)
=======
let signedTx = await transport.call('Btc', 'createPaymentTransactionNew', inputs, paths, undefined, outputScriptHex, null, networksUtil[slip44].sigHash, segwit)
handleError(transport, signedTx, 'Could not sign transaction with device')
>>>>>>>
let signedTx = await transport.call('Btc', 'createPaymentTransactionNew', inputs, paths, undefined, outputScriptHex, null, networksUtil[slip44].sigHash, segwit, undefined, additionals)
handleError(transport, signedTx, 'Could not sign transaction with device') |
<<<<<<<
| BTCWallet
| ETHWallet
| CosmosWallet
| BinanceWallet
| RippleWallet
| DebugLinkWallet;
=======
| BTCWallet
| ETHWallet
| CosmosWallet
| EosWallet
| DebugLinkWallet;
>>>>>>>
| BTCWallet
| ETHWallet
| CosmosWallet
| BinanceWallet
| RippleWallet
| EosWallet
| DebugLinkWallet;
<<<<<<<
return isObject(info) && (info as any)._supportsCosmosInfo;
}
/**
* Type guard for RippleWallet Support
*
* Example Usage:
```typescript
if (supportsripple(wallet)) {
wallet.xrpGetAddress(...)
}
```
*/
export function supportsRipple(wallet: any): wallet is RippleWallet {
return isObject(wallet) && (wallet as any)._supportsRipple;
}
export function infoRipple(info: any): info is RippleWalletInfo {
return isObject(info) && (info as any)._supportsRippleInfo;
}
export function supportsBinance(wallet: any): wallet is BinanceWallet {
return isObject(wallet) && (wallet as any)._supportsBinance;
}
export function infoBinance(info: any): info is BinanceWalletInfo {
return isObject(info) && (info as any)._supportsBinanceInfo;
=======
return isObject(info) && (info as any)._supportsCosmosInfo;
}
export function supportsEos(wallet: any): wallet is EosWallet {
return isObject(wallet) && (wallet as any)._supportsEos;
}
export function infoEos(info: any): info is EosWalletInfo {
return isObject(info) && (info as any)._supportsEosInfo;
>>>>>>>
return isObject(info) && (info as any)._supportsCosmosInfo;
}
export function supportsEos(wallet: any): wallet is EosWallet {
return isObject(wallet) && (wallet as any)._supportsEos;
}
export function infoEos(info: any): info is EosWalletInfo {
return isObject(info) && (info as any)._supportsEosInfo;
}
/**
* Type guard for RippleWallet Support
*
* Example Usage:
```typescript
if (supportsripple(wallet)) {
wallet.xrpGetAddress(...)
}
```
*/
export function supportsRipple(wallet: any): wallet is RippleWallet {
return isObject(wallet) && (wallet as any)._supportsRipple;
}
export function infoRipple(info: any): info is RippleWalletInfo {
return isObject(info) && (info as any)._supportsRippleInfo;
}
export function supportsBinance(wallet: any): wallet is BinanceWallet {
return isObject(wallet) && (wallet as any)._supportsBinance;
}
export function infoBinance(info: any): info is BinanceWalletInfo {
return isObject(info) && (info as any)._supportsBinanceInfo;
<<<<<<<
_supportsETHInfo: boolean;
_supportsBTCInfo: boolean;
_supportsCosmosInfo: boolean;
_supportsRippleInfo: boolean;
_supportsBinanceInfo: boolean;
=======
_supportsETHInfo: boolean;
_supportsBTCInfo: boolean;
_supportsCosmosInfo: boolean;
_supportsEosInfo: boolean;
>>>>>>>
_supportsETHInfo: boolean;
_supportsBTCInfo: boolean;
_supportsCosmosInfo: boolean;
_supportsRippleInfo: boolean;
_supportsBinanceInfo: boolean;
_supportsEosInfo: boolean;
<<<<<<<
_supportsETHInfo: boolean;
_supportsBTCInfo: boolean;
_supportsBTC: boolean;
_supportsETH: boolean;
_supportsCosmos: boolean;
_supportsBinance: boolean;
_supportsRipple: boolean;
_supportsDebugLink: boolean;
=======
_supportsETHInfo: boolean;
_supportsBTCInfo: boolean;
_supportsBTC: boolean;
_supportsETH: boolean;
_supportsCosmos: boolean;
_supportsEos: boolean;
_supportsDebugLink: boolean;
>>>>>>>
_supportsETHInfo: boolean;
_supportsBTCInfo: boolean;
_supportsBTC: boolean;
_supportsETH: boolean;
_supportsCosmos: boolean;
_supportsBinance: boolean;
_supportsRipple: boolean;
_supportsEos: boolean;
_supportsDebugLink: boolean; |
<<<<<<<
public describePath (msg: DescribePath): PathDescription {
return this.info.describePath(msg)
}
=======
public disconnect (): Promise<void> {
return this.transport.disconnect()
}
>>>>>>>
public describePath (msg: DescribePath): PathDescription {
return this.info.describePath(msg)
}
public disconnect (): Promise<void> {
return this.transport.disconnect()
} |
<<<<<<<
public describePath (msg: DescribePath): PathDescription {
return this.info.describePath(msg)
}
=======
public disconnect (): Promise<void> {
return this.transport.disconnect()
}
>>>>>>>
public describePath (msg: DescribePath): PathDescription {
return this.info.describePath(msg)
}
public disconnect (): Promise<void> {
return this.transport.disconnect()
} |
<<<<<<<
DisconnectedDeviceDuringOperation = 'DisconnectedDeviceDuringOperation',
=======
DeviceLocked = 'DeviceLocked',
>>>>>>>
DisconnectedDeviceDuringOperation = 'DisconnectedDeviceDuringOperation',
DeviceLocked = 'DeviceLocked',
<<<<<<<
export class DisconnectedDeviceDuringOperation extends HDWalletError {
constructor () {
super('Ledger device disconnected during operation', HDWalletErrorType.DisconnectedDeviceDuringOperation)
}
}
=======
export class DeviceLocked extends HDWalletError {
constructor () {
super('Device locked', HDWalletErrorType.DeviceLocked)
}
}
>>>>>>>
export class DisconnectedDeviceDuringOperation extends HDWalletError {
constructor () {
super('Ledger device disconnected during operation', HDWalletErrorType.DisconnectedDeviceDuringOperation)
export class DeviceLocked extends HDWalletError {
constructor () {
super('Device locked', HDWalletErrorType.DeviceLocked)
}
} |
<<<<<<<
export class LedgerHDWalletInfo
implements core.HDWalletInfo, core.BTCWalletInfo, core.ETHWalletInfo {
_supportsBTCInfo: boolean = true;
_supportsETHInfo: boolean = true;
_supportsCosmosInfo: boolean = false; // TODO ledger supports cosmos
_supportsBinanceInfo: boolean = false; // TODO ledger supports bnb
_supportsRippleInfo: boolean = false; // TODO ledger supports XRP
=======
export class LedgerHDWalletInfo
implements core.HDWalletInfo, core.BTCWalletInfo, core.ETHWalletInfo {
_supportsBTCInfo: boolean = true;
_supportsETHInfo: boolean = true;
_supportsCosmosInfo: boolean = false;
_supportsEosInfo: boolean = false;
>>>>>>>
export class LedgerHDWalletInfo
implements core.HDWalletInfo, core.BTCWalletInfo, core.ETHWalletInfo {
_supportsBTCInfo: boolean = true;
_supportsETHInfo: boolean = true;
_supportsCosmosInfo: boolean = false; // TODO ledger supports cosmos
_supportsBinanceInfo: boolean = false; // TODO ledger supports bnb
_supportsRippleInfo: boolean = false; // TODO ledger supports XRP
_supportsEosInfo: boolean = false;
<<<<<<<
export class LedgerHDWallet
implements core.HDWallet, core.BTCWallet, core.ETHWallet {
_supportsETHInfo: boolean = true;
_supportsBTCInfo: boolean = true;
_supportsDebugLink: boolean = false;
_supportsBTC: boolean = true;
_supportsETH: boolean = true;
_supportsCosmosInfo: boolean = false;
_supportsCosmos: boolean = false;
_supportsBinanceInfo: boolean = false;
_supportsBinance: boolean = false;
_supportsRippleInfo: boolean = false;
_supportsRipple: boolean = false;
_isLedger: boolean = true;
=======
export class LedgerHDWallet
implements core.HDWallet, core.BTCWallet, core.ETHWallet {
_supportsETHInfo: boolean = true;
_supportsBTCInfo: boolean = true;
_supportsDebugLink: boolean = false;
_supportsBTC: boolean = true;
_supportsETH: boolean = true;
_supportsCosmosInfo: boolean = false;
_supportsCosmos: boolean = false;
_supportsEosInfo: boolean = false;
_supportsEos: boolean = false;
_isLedger: boolean = true;
>>>>>>>
export class LedgerHDWallet
implements core.HDWallet, core.BTCWallet, core.ETHWallet {
_supportsETHInfo: boolean = true;
_supportsBTCInfo: boolean = true;
_supportsDebugLink: boolean = false;
_supportsBTC: boolean = true;
_supportsETH: boolean = true;
_supportsBinanceInfo: boolean = false;
_supportsBinance: boolean = false;
_supportsRippleInfo: boolean = false;
_supportsRipple: boolean = false;
_supportsCosmosInfo: boolean = false;
_supportsCosmos: boolean = false;
_supportsEosInfo: boolean = false;
_supportsEos: boolean = false;
_isLedger: boolean = true; |
<<<<<<<
supportsRipple,
supportsBinance,
=======
supportsEos,
EosPublicKeyKindMap,
EosSignedTx,
>>>>>>>
supportsRipple,
supportsBinance,
supportsEos,
EosPublicKeyKindMap,
EosSignedTx,
<<<<<<<
Events,
} from "@shapeshiftoss/hdwallet-core";
=======
Events,
toHexString,
} from "@shapeshiftoss/hdwallet-core";
>>>>>>>
Events,
toHexString,
} from "@shapeshiftoss/hdwallet-core";
<<<<<<<
import * as btcBech32TxJson from "./json/btcBech32Tx.json";
import * as btcTxJson from "./json/btcTx.json";
import * as btcSegWitTxJson from "./json/btcSegWitTx.json";
import * as dashTxJson from "./json/dashTx.json";
import * as dogeTxJson from "./json/dogeTx.json";
import * as ltcTxJson from "./json/ltcTx.json";
import * as rippleTxJson from "./json/rippleTx.json";
=======
import * as btcBech32TxJson from "./json/btcBech32Tx.json";
import * as btcTxJson from "./json/btcTx.json";
import * as btcSegWitTxJson from "./json/btcSegWitTx.json";
import * as dashTxJson from "./json/dashTx.json";
import * as dogeTxJson from "./json/dogeTx.json";
import * as ltcTxJson from "./json/ltcTx.json";
>>>>>>>
import * as btcBech32TxJson from "./json/btcBech32Tx.json";
import * as btcTxJson from "./json/btcTx.json";
import * as btcSegWitTxJson from "./json/btcSegWitTx.json";
import * as dashTxJson from "./json/dashTx.json";
import * as dogeTxJson from "./json/dogeTx.json";
import * as ltcTxJson from "./json/ltcTx.json";
import * as rippleTxJson from "./json/rippleTx.json";
<<<<<<<
$appInfo.val(result);
});
/*
* Binance
*/
const $binanceAddr = $("#binanceAddr");
const $binanceTx = $("#binanceTx");
const $binanceResults = $("#binanceResults");
$binanceAddr.on("click", async (e) => {
e.preventDefault();
if (!wallet) {
$binanceResults.val("No wallet?");
return;
}
if (supportsBinance(wallet)) {
let { addressNList } = wallet.binanceGetAccountPaths({ accountIdx: 0 })[0];
let result = await wallet.binanceGetAddress({
addressNList,
showDisplay: false,
});
result = await wallet.binanceGetAddress({
addressNList,
showDisplay: true,
address: result,
});
$binanceResults.val(result);
} else {
let label = await wallet.getLabel();
$binanceResults.val(label + " does not support Binance");
}
});
$binanceTx.on("click", async (e) => {
e.preventDefault();
if (!wallet) {
$binanceResults.val("No wallet?");
return;
}
if (supportsBinance(wallet)) {
let unsigned = {
account_number: "34",
chain_id: "Binance-Chain-Nile",
data: "null",
memo: "test",
msgs: [
{
inputs: [
{
address: "tbnb1hgm0p7khfk85zpz5v0j8wnej3a90w709zzlffd",
coins: [{ amount: 1000000000, denom: "BNB" }],
},
],
outputs: [
{
address: "tbnb1ss57e8sa7xnwq030k2ctr775uac9gjzglqhvpy",
coins: [{ amount: 1000000000, denom: "BNB" }],
},
],
},
],
sequence: "31",
source: "1",
};
let res = await wallet.binanceSignTx({
addressNList: bip32ToAddressNList(`m/44'/714'/0'/0/0`),
chain_id: "Binance-Chain-Nile",
account_number: "24250",
sequence: "31",
tx: unsigned,
});
$binanceResults.val(JSON.stringify(res));
} else {
let label = await wallet.getLabel();
$binanceResults.val(label + " does not support Cosmos");
}
});
/*
* Ripple
*/
const $rippleAddr = $("#rippleAddr");
const $rippleTx = $("#rippleTx");
const $rippleResults = $("#rippleResults");
$rippleAddr.on("click", async (e) => {
e.preventDefault();
if (!wallet) {
$rippleResults.val("No wallet?");
return;
}
if (supportsRipple(wallet)) {
let { addressNList } = wallet.rippleGetAccountPaths({ accountIdx: 0 })[0];
let result = await wallet.rippleGetAddress({
addressNList,
showDisplay: true,
});
$rippleResults.val(result);
} else {
let label = await wallet.getLabel();
$rippleResults.val(label + " does not support Ripple");
}
});
$rippleTx.on("click", async (e) => {
e.preventDefault();
if (!wallet) {
$ethResults.val("No wallet?");
return;
}
if (supportsRipple(wallet)) {
let res = await wallet.rippleSignTx({
addressNList: bip32ToAddressNList(`m/44'/144'/0'/0/0`),
tx: rippleTxJson,
flags: undefined,
sequence: "3",
lastLedgerSequence: "0",
payment: {
amount: "47000",
destination: "rEpwmtmvx8gkMhX5NLdU3vutQt7dor4MZm",
destinationTag: "1234567890",
},
});
$rippleResults.val(JSON.stringify(res));
} else {
let label = await wallet.getLabel();
$rippleResults.val(label + " does not support Ripple");
}
});
=======
$appInfo.val(result);
});
/*
* Eos
*/
const $eosAddr = $("#eosAddr");
const $eosTx = $("#eosTx");
const $eosResults = $("#eosResults");
$eosAddr.on("click", async (e) => {
e.preventDefault();
if (!wallet) {
$ethResults.val("No wallet?");
return;
}
if (supportsEos(wallet)) {
let { addressNList } = wallet.eosGetAccountPaths({ accountIdx: 0 })[0];
let result = await wallet.eosGetPublicKey({
addressNList,
showDisplay: false,
kind: 0,
});
result = await wallet.eosGetPublicKey({
addressNList,
showDisplay: true,
kind: 0,
address: result,
});
$eosResults.val(result);
} else {
let label = await wallet.getLabel();
$eosResults.val(label + " does not support Eos");
}
});
$eosTx.on("click", async (e) => {
e.preventDefault();
if (!wallet) {
$ethResults.val("No wallet?");
return;
}
if (supportsCosmos(wallet)) {
let unsigned = {
expiration: "2018-07-14T07:43:28",
ref_block_num: 6439,
ref_block_prefix: 2995713264,
max_net_usage_words: 0,
max_cpu_usage_ms: 0,
delay_sec: 0,
context_free_actions: [],
actions: [
{
account: "eosio.token",
name: "transfer",
authorization: [
{
actor: "miniminimini",
permission: "active",
},
],
data: {
from: "miniminimini",
to: "maximaximaxi",
quantity: "1.0000 EOS",
memo: "testtest",
},
},
],
};
let res = await wallet.eosSignTx({
addressNList: bip32ToAddressNList("m/44'/194'/0'/0/0"),
chain_id:
"cf057bbfb72640471fd910bcb67639c22df9f92470936cddc1ade0e2f2e7dc4f",
tx: unsigned,
});
console.log(res);
console.log("sigV = %d", res.signatureV);
console.log("sigR = %s", toHexString(res.signatureR));
console.log("sigS = %s", toHexString(res.signatureS));
console.log("hash = %s", toHexString(res.hash));
$eosResults.val(JSON.stringify(res));
} else {
let label = await wallet.getLabel();
$eosResults.val(label + " does not support Eos");
}
});
>>>>>>>
$appInfo.val(result);
});
/*
* Binance
*/
const $binanceAddr = $("#binanceAddr");
const $binanceTx = $("#binanceTx");
const $binanceResults = $("#binanceResults");
$binanceAddr.on("click", async (e) => {
e.preventDefault();
if (!wallet) {
$binanceResults.val("No wallet?");
return;
}
if (supportsBinance(wallet)) {
let { addressNList } = wallet.binanceGetAccountPaths({ accountIdx: 0 })[0];
let result = await wallet.binanceGetAddress({
addressNList,
showDisplay: false,
});
result = await wallet.binanceGetAddress({
addressNList,
showDisplay: true,
address: result,
});
$binanceResults.val(result);
} else {
let label = await wallet.getLabel();
$binanceResults.val(label + " does not support Binance");
}
});
$binanceTx.on("click", async (e) => {
e.preventDefault();
if (!wallet) {
$binanceResults.val("No wallet?");
return;
}
if (supportsBinance(wallet)) {
let unsigned = {
account_number: "34",
chain_id: "Binance-Chain-Nile",
data: "null",
memo: "test",
msgs: [
{
inputs: [
{
address: "tbnb1hgm0p7khfk85zpz5v0j8wnej3a90w709zzlffd",
coins: [{ amount: 1000000000, denom: "BNB" }],
},
],
outputs: [
{
address: "tbnb1ss57e8sa7xnwq030k2ctr775uac9gjzglqhvpy",
coins: [{ amount: 1000000000, denom: "BNB" }],
},
],
},
],
sequence: "31",
source: "1",
};
let res = await wallet.binanceSignTx({
addressNList: bip32ToAddressNList(`m/44'/714'/0'/0/0`),
chain_id: "Binance-Chain-Nile",
account_number: "24250",
sequence: "31",
tx: unsigned,
});
$binanceResults.val(JSON.stringify(res));
} else {
let label = await wallet.getLabel();
$binanceResults.val(label + " does not support Cosmos");
}
});
/*
* Ripple
*/
const $rippleAddr = $("#rippleAddr");
const $rippleTx = $("#rippleTx");
const $rippleResults = $("#rippleResults");
$rippleAddr.on("click", async (e) => {
e.preventDefault();
if (!wallet) {
$rippleResults.val("No wallet?");
return;
}
if (supportsRipple(wallet)) {
let { addressNList } = wallet.rippleGetAccountPaths({ accountIdx: 0 })[0];
let result = await wallet.rippleGetAddress({
addressNList,
showDisplay: true,
});
$rippleResults.val(result);
} else {
let label = await wallet.getLabel();
$rippleResults.val(label + " does not support Ripple");
}
});
$rippleTx.on("click", async (e) => {
e.preventDefault();
if (!wallet) {
$ethResults.val("No wallet?");
return;
}
if (supportsRipple(wallet)) {
let res = await wallet.rippleSignTx({
addressNList: bip32ToAddressNList(`m/44'/144'/0'/0/0`),
tx: rippleTxJson,
flags: undefined,
sequence: "3",
lastLedgerSequence: "0",
payment: {
amount: "47000",
destination: "rEpwmtmvx8gkMhX5NLdU3vutQt7dor4MZm",
destinationTag: "1234567890",
},
});
$rippleResults.val(JSON.stringify(res));
} else {
let label = await wallet.getLabel();
$rippleResults.val(label + " does not support Ripple");
}
});
/*
* Eos
*/
const $eosAddr = $("#eosAddr");
const $eosTx = $("#eosTx");
const $eosResults = $("#eosResults");
$eosAddr.on("click", async (e) => {
e.preventDefault();
if (!wallet) {
$ethResults.val("No wallet?");
return;
}
if (supportsEos(wallet)) {
let { addressNList } = wallet.eosGetAccountPaths({ accountIdx: 0 })[0];
let result = await wallet.eosGetPublicKey({
addressNList,
showDisplay: false,
kind: 0,
});
result = await wallet.eosGetPublicKey({
addressNList,
showDisplay: true,
kind: 0,
address: result,
});
$eosResults.val(result);
} else {
let label = await wallet.getLabel();
$eosResults.val(label + " does not support Eos");
}
});
$eosTx.on("click", async (e) => {
e.preventDefault();
if (!wallet) {
$ethResults.val("No wallet?");
return;
}
if (supportsEos(wallet)) {
let unsigned = {
expiration: "2018-07-14T07:43:28",
ref_block_num: 6439,
ref_block_prefix: 2995713264,
max_net_usage_words: 0,
max_cpu_usage_ms: 0,
delay_sec: 0,
context_free_actions: [],
actions: [
{
account: "eosio.token",
name: "transfer",
authorization: [
{
actor: "miniminimini",
permission: "active",
},
],
data: {
from: "miniminimini",
to: "maximaximaxi",
quantity: "1.0000 EOS",
memo: "testtest",
},
},
],
};
let res = await wallet.eosSignTx({
addressNList: bip32ToAddressNList("m/44'/194'/0'/0/0"),
chain_id:
"cf057bbfb72640471fd910bcb67639c22df9f92470936cddc1ade0e2f2e7dc4f",
tx: unsigned,
});
console.log(res);
console.log("sigV = %d", res.signatureV);
console.log("sigR = %s", toHexString(res.signatureR));
console.log("sigS = %s", toHexString(res.signatureS));
console.log("hash = %s", toHexString(res.hash));
$eosResults.val(JSON.stringify(res));
} else {
let label = await wallet.getLabel();
$eosResults.val(label + " does not support Eos");
}
});
<<<<<<<
});
$btcTxSegWitNative.on("click", async (e) => {
e.preventDefault();
if (!wallet) {
$btcResultsSegWit.val("No wallet?");
return;
}
=======
});
$btcTxSegWitNative.on("click", async (e) => {
e.preventDefault();
if (!wallet) {
$btcResultsSegWit.val("No wallet?");
return;
}
>>>>>>>
});
$btcTxSegWitNative.on("click", async (e) => {
e.preventDefault();
if (!wallet) {
$btcResultsSegWit.val("No wallet?");
return;
} |
<<<<<<<
import { HDWallet, HDWalletInfo } from "@shapeshiftoss/hdwallet-core";
import { isKeepKey } from "@shapeshiftoss/hdwallet-keepkey";
import { isTrezor } from "@shapeshiftoss/hdwallet-trezor";
import { isLedger } from "@shapeshiftoss/hdwallet-ledger";
import { isPortis } from "@shapeshiftoss/hdwallet-portis";
import { btcTests } from "./bitcoin";
import { ethTests } from "./ethereum";
import { cosmosTests } from "./cosmos";
import { binanceTests } from "./binance";
import { rippleTests } from "./ripple";
import { WalletSuite } from "./wallets/suite";
=======
import { HDWallet, HDWalletInfo } from "@shapeshiftoss/hdwallet-core";
import { isKeepKey } from "@shapeshiftoss/hdwallet-keepkey";
import { isTrezor } from "@shapeshiftoss/hdwallet-trezor";
import { isLedger } from "@shapeshiftoss/hdwallet-ledger";
import { isPortis } from "@shapeshiftoss/hdwallet-portis";
import { btcTests } from "./bitcoin";
import { ethTests } from "./ethereum";
import { cosmosTests } from "./cosmos";
import { eosTests } from "./eos";
import { WalletSuite } from "./wallets/suite";
>>>>>>>
import { HDWallet, HDWalletInfo } from "@shapeshiftoss/hdwallet-core";
import { isKeepKey } from "@shapeshiftoss/hdwallet-keepkey";
import { isTrezor } from "@shapeshiftoss/hdwallet-trezor";
import { isLedger } from "@shapeshiftoss/hdwallet-ledger";
import { isPortis } from "@shapeshiftoss/hdwallet-portis";
import { btcTests } from "./bitcoin";
import { ethTests } from "./ethereum";
import { cosmosTests } from "./cosmos";
import { binanceTests } from "./binance";
import { rippleTests } from "./ripple";
import { eosTests } from "./eos";
import { WalletSuite } from "./wallets/suite"; |
<<<<<<<
describe('session.save(cb)', () => {
it('should save session to store', async () => {
const store = new MemoryStore()
const getSession = SessionManager({
store,
secret: 'test',
})
const { fetch } = InitAppAndTest(async (req, res) => {
const session = await getSession(req, res)
session.save((err) => {
if (err) {
return res.end(err.message)
}
store.get(session.id, (err, sess) => {
if (err) {
return res.end(err.message)
}
res.end(sess ? 'stored' : 'empty')
})
})
})
await fetch('/').expectStatus(200).expectBody('stored')
})
it('should prevent end-of-request save', async () => {
const store = new MemoryStore()
const _set = store.set
let setCount = 0
store.set = function set(...args) {
setCount++
return _set.apply(this, args)
}
const getSession = SessionManager({
store,
secret: 'test',
})
const { fetch } = InitAppAndTest(async (req, res) => {
const session = await getSession(req, res)
session.save((err) => {
if (err) {
return res.end(err.message)
}
res.end('saved')
})
})
await fetch('/').expectStatus(200).expectBody('saved')
expect(setCount).toBe(1)
})
it('should prevent end-of-request save on reloaded session', async () => {
const store = new MemoryStore()
const _set = store.set
let setCount = 0
store.set = function set(...args) {
setCount++
return _set.apply(this, args)
}
const getSession = SessionManager({
store,
secret: 'test',
})
const { fetch } = InitAppAndTest(async (req, res) => {
const session = await getSession(req, res)
session.reload(() => {
session.save((err) => {
if (err) {
return res.end(err.message)
}
res.end('saved')
})
})
})
await fetch('/').expectStatus(200).expectBody('saved')
expect(setCount).toBe(1)
})
})
describe('session.touch(cb)', () => {
it('should reset session expiration', async () => {
const store = new MemoryStore()
const getSession = SessionManager({
cookie: { maxAge: 60 * 1000 },
resave: false,
secret: 'test',
store,
})
let preTouchExpires: Date
let postTouchExpires: Date
const { fetch } = InitAppAndTest(async (req, res) => {
const session = await getSession(req, res)
if (typeof session.cookie.expires === 'boolean') {
throw new Error('session.cookie.expires is a boolean')
}
preTouchExpires = session.cookie.expires
await new Promise((resolve) => {
setTimeout(() => {
session.touch()
if (typeof session.cookie.expires === 'boolean') {
throw new Error('session.cookie.expires is a boolean')
}
postTouchExpires = session.cookie.expires
resolve()
}, 100)
})
res.end()
})
await fetch('/').expectStatus(200)
expect(postTouchExpires.getTime() > preTouchExpires.getTime())
})
})
describe('session.destroy(cb)', () => {
it('should destroy the previous session', async () => {
const getSession = SessionManager({
secret: 'test',
})
const { fetch } = InitAppAndTest(async (req, res) => {
const session = await getSession(req, res)
session.destroy((err) => {
if (err) {
res.statusCode = 500
}
res.end(String(session))
})
})
await fetch('/').expectStatus(200).expectHeader('Set-Cookie', null)
})
})
})
describe('Cookie', () => {
describe('new Cookie(opts)', () => {
it('should create a new cookie object', () => {
expect(typeof new Cookie()).toBe('object')
})
it('should set default `expires` to `false`', () => {
expect(new Cookie().expires).toBe(false)
})
it('should set default `httpOnly` to `true`', () => {
expect(new Cookie().httpOnly).toBe(true)
})
})
=======
describe('session.save(cb)', () => {
it('should save session to store', async () => {
const store = new MemoryStore()
const getSession = SessionManager({
store,
secret: 'test',
})
const { fetch } = InitAppAndTest(async (req, res) => {
const session = await getSession(req, res)
session.save((err) => {
if (err) {
return res.end(err.message)
}
store.get(session.id, (err, sess) => {
if (err) {
return res.end(err.message)
}
res.end(sess ? 'stored' : 'empty')
})
})
})
await fetch('/').expectStatus(200).expectBody('stored')
})
it('should prevent end-of-request save', async () => {
const store = new MemoryStore()
const _set = store.set
let setCount = 0
store.set = function set(...args) {
setCount++
return _set.apply(this, args)
}
const getSession = SessionManager({
store,
secret: 'test',
})
const { fetch } = InitAppAndTest(async (req, res) => {
const session = await getSession(req, res)
session.save((err) => {
if (err) {
return res.end(err.message)
}
res.end('saved')
})
})
await fetch('/').expectStatus(200).expectBody('saved')
expect(setCount).toBe(1)
})
it('should prevent end-of-request save on reloaded session', async () => {
const store = new MemoryStore()
const _set = store.set
let setCount = 0
store.set = function set(...args) {
setCount++
return _set.apply(this, args)
}
const getSession = SessionManager({
store,
secret: 'test',
})
const { fetch } = InitAppAndTest(async (req, res) => {
const session = await getSession(req, res)
session.reload(() => {
session.save((err) => {
if (err) {
return res.end(err.message)
}
res.end('saved')
})
})
})
await fetch('/').expectStatus(200).expectBody('saved')
expect(setCount).toBe(1)
})
})
describe('session.touch(cb)', () => {
it('should reset session expiration', async () => {
const store = new MemoryStore()
const getSession = SessionManager({
cookie: { maxAge: 60 * 1000 },
resave: false,
secret: 'test',
store,
})
let preTouchExpires: Date
let postTouchExpires: Date
const { fetch } = InitAppAndTest(async (req, res) => {
const session = await getSession(req, res)
if (typeof session.cookie.expires === 'boolean') {
throw new Error('session.cookie.expires is a boolean')
}
preTouchExpires = session.cookie.expires
await new Promise((resolve) => {
setTimeout(() => {
session.touch()
if (typeof session.cookie.expires === 'boolean') {
throw new Error('session.cookie.expires is a boolean')
}
postTouchExpires = session.cookie.expires
resolve()
}, 100)
})
res.end()
})
await fetch('/').expectStatus(200)
expect(postTouchExpires.getTime() > preTouchExpires.getTime())
})
})
describe('session.destroy(cb)', () => {
it('should destroy the previous session', async () => {
const getSession = SessionManager({
secret: 'test',
})
const { fetch } = InitAppAndTest(async (req, res) => {
const session = await getSession(req, res)
session.destroy((err) => {
if (err) {
res.statusCode = 500
}
res.end(String(session))
})
})
await fetch('/').expectStatus(200).expectHeader('Set-Cookie', null)
})
})
>>>>>>>
describe('session.save(cb)', () => {
it('should save session to store', async () => {
const store = new MemoryStore()
const getSession = SessionManager({
store,
secret: 'test',
})
const { fetch } = InitAppAndTest(async (req, res) => {
const session = await getSession(req, res)
session.save((err) => {
if (err) {
return res.end(err.message)
}
store.get(session.id, (err, sess) => {
if (err) {
return res.end(err.message)
}
res.end(sess ? 'stored' : 'empty')
})
})
})
await fetch('/').expectStatus(200).expectBody('stored')
})
it('should prevent end-of-request save', async () => {
const store = new MemoryStore()
const _set = store.set
let setCount = 0
store.set = function set(...args) {
setCount++
return _set.apply(this, args)
}
const getSession = SessionManager({
store,
secret: 'test',
})
const { fetch } = InitAppAndTest(async (req, res) => {
const session = await getSession(req, res)
session.save((err) => {
if (err) {
return res.end(err.message)
}
res.end('saved')
})
})
await fetch('/').expectStatus(200).expectBody('saved')
expect(setCount).toBe(1)
})
it('should prevent end-of-request save on reloaded session', async () => {
const store = new MemoryStore()
const _set = store.set
let setCount = 0
store.set = function set(...args) {
setCount++
return _set.apply(this, args)
}
const getSession = SessionManager({
store,
secret: 'test',
})
const { fetch } = InitAppAndTest(async (req, res) => {
const session = await getSession(req, res)
session.reload(() => {
session.save((err) => {
if (err) {
return res.end(err.message)
}
res.end('saved')
})
})
})
await fetch('/').expectStatus(200).expectBody('saved')
expect(setCount).toBe(1)
})
})
describe('session.touch(cb)', () => {
it('should reset session expiration', async () => {
const store = new MemoryStore()
const getSession = SessionManager({
cookie: { maxAge: 60 * 1000 },
resave: false,
secret: 'test',
store,
})
let preTouchExpires: Date
let postTouchExpires: Date
const { fetch } = InitAppAndTest(async (req, res) => {
const session = await getSession(req, res)
if (typeof session.cookie.expires === 'boolean') {
throw new Error('session.cookie.expires is a boolean')
}
preTouchExpires = session.cookie.expires
await new Promise((resolve) => {
setTimeout(() => {
session.touch()
if (typeof session.cookie.expires === 'boolean') {
throw new Error('session.cookie.expires is a boolean')
}
postTouchExpires = session.cookie.expires
resolve()
}, 100)
})
res.end()
})
await fetch('/').expectStatus(200)
expect(postTouchExpires.getTime() > preTouchExpires.getTime())
})
})
describe('session.destroy(cb)', () => {
it('should destroy the previous session', async () => {
const getSession = SessionManager({
secret: 'test',
})
const { fetch } = InitAppAndTest(async (req, res) => {
const session = await getSession(req, res)
session.destroy((err) => {
if (err) {
res.statusCode = 500
}
res.end(String(session))
})
})
await fetch('/').expectStatus(200).expectHeader('Set-Cookie', null)
})
})
describe('Cookie', () => {
describe('new Cookie(opts)', () => {
it('should create a new cookie object', () => {
expect(typeof new Cookie()).toBe('object')
})
it('should set default `expires` to `false`', () => {
expect(new Cookie().expires).toBe(false)
})
it('should set default `httpOnly` to `true`', () => {
expect(new Cookie().httpOnly).toBe(true)
})
}) |
<<<<<<<
=======
const tmpRect = new BoundingRect(0, 0, 0, 0);
const viewRect = new BoundingRect(0, 0, 0, 0);
function isDisplayableCulled(el: Displayable, width: number, height: number) {
// Disable culling when width or height is 0
if (!width || !height) {
return false;
}
tmpRect.copy(el.getBoundingRect());
if (el.transform) {
tmpRect.applyTransform(el.transform);
}
viewRect.width = width;
viewRect.height = height;
return !tmpRect.intersect(viewRect);
}
>>>>>>>
const tmpRect = new BoundingRect(0, 0, 0, 0);
const viewRect = new BoundingRect(0, 0, 0, 0);
function isDisplayableCulled(el: Displayable, width: number, height: number) {
// Disable culling when width or height is 0
if (!width || !height) {
return false;
}
tmpRect.copy(el.getBoundingRect());
if (el.transform) {
tmpRect.applyTransform(el.transform);
}
viewRect.width = width;
viewRect.height = height;
return !tmpRect.intersect(viewRect);
}
<<<<<<<
el.__dirty = 0;
el.__isRendered = false;
=======
// But other dirty bit should not be cleared, otherwise it cause the shape
// can not be updated in this case.
el.__dirty &= ~Element.REDARAW_BIT;
>>>>>>>
// But other dirty bit should not be cleared, otherwise it cause the shape
// can not be updated in this case.
el.__dirty &= ~Element.REDARAW_BIT;
el.__isRendered = false; |
<<<<<<<
import { Dictionary, PropType, ElementEventName, ZRRawEvent, BuiltinTextPosition, AllPropTypes } from './core/types';
=======
import { Dictionary, PropType, ElementEventName, ZRRawEvent, AllPropTypes } from './core/types';
>>>>>>>
import { Dictionary, PropType, ElementEventName, ZRRawEvent, BuiltinTextPosition, AllPropTypes } from './core/types';
<<<<<<<
interface TextLayout {
/**
* Position relative to the element bounding rect
* @default 'inside'
*/
position?: BuiltinTextPosition | number[] | string[]
/**
* Distance to the rect
* @default 5
*/
distance?: number
/**
* If use local user space. Which will apply host's transform
* @default false
*/
local?: boolean
// TODO applyClip
}
=======
import {EventQuery, EventCallback} from './core/Eventful';
import Group from './container/Group';
>>>>>>>
import Group from './graphic/Group';
interface TextLayout {
/**
* Position relative to the element bounding rect
* @default 'inside'
*/
position?: BuiltinTextPosition | number[] | string[]
/**
* Distance to the rect
* @default 5
*/
distance?: number
/**
* If use local user space. Which will apply host's transform
* @default false
*/
local?: boolean
// TODO applyClip
}
<<<<<<<
textLayout?: TextLayout
textContent?: RichText
clipPath?: Path
=======
drift?: Element['drift']
// For echarts animation.
anid?: string
>>>>>>>
textLayout?: TextLayout
textContent?: RichText
clipPath?: Path
drift?: Element['drift']
// For echarts animation.
anid?: string
<<<<<<<
type AnimationCallback = () => {}
=======
type ElementKey = keyof ElementProps
type AnimationCallback = () => void;
interface Element<Props extends ElementProps = ElementProps> extends ElementEventHandlerProps {
// Provide more typed event callback params for mouse events.
on<Ctx>(event: ElementEventName, handler: ElementEventCallback<Ctx, this>, context?: Ctx): this
on<Ctx>(event: string, handler: EventCallback<Ctx, this>, context?: Ctx): this
>>>>>>>
type AnimationCallback = () => {}
let tmpTextPosCalcRes = {} as TextPositionCalculationResult;
let tmpBoundingRect = new BoundingRect();
interface Element<Props extends ElementOption = ElementOption> extends Transformable, Eventful {
// Provide more typed event callback params for mouse events.
on<Ctx>(event: ElementEventName, handler: ElementEventCallback<Ctx, this>, context?: Ctx): this
on<Ctx>(event: string, handler: EventCallback<Ctx, this>, context?: Ctx): this
<<<<<<<
let tmpTextPosCalcRes = {} as TextPositionCalculationResult;
let tmpBoundingRect = new BoundingRect();
interface Element<T extends ElementOption = ElementOption> extends Transformable, Eventful {
// Provide more typed event callback params for mouse events.
on<Context>(event: ElementEventName, handler: ElementEventCallback, context?: Context): Element
on<Context>(event: ElementEventName, query: EventQuery, handler: ElementEventCallback, context?: Context): Element
// Provide general events handler for other custom events.
on<Context>(event: string, query?: EventCallback | EventQuery, handler?: EventCallback | Object, context?: Context): Element
// Mouse events
onclick: ElementEventCallback
ondblclick: ElementEventCallback
onmouseover: ElementEventCallback
onmouseout: ElementEventCallback
onmousemove: ElementEventCallback
onmousewheel: ElementEventCallback
onmousedown: ElementEventCallback
onmouseup: ElementEventCallback
oncontextmenu: ElementEventCallback
ondrag: ElementEventCallback
ondragstart: ElementEventCallback
ondragend: ElementEventCallback
ondragenter: ElementEventCallback
ondragleave: ElementEventCallback
ondragover: ElementEventCallback
ondrop: ElementEventCallback
}
class Element<T extends ElementOption = ElementOption> {
=======
class Element<Props extends ElementProps = ElementProps> extends Transformable {
>>>>>>>
class Element<Props extends ElementOption = ElementOption> {
<<<<<<<
/**
* Parent element
*/
parent: Element
=======
parent: Group
>>>>>>>
parent: Group
<<<<<<<
/**
* Attached text element.
* `position`, `style.textAlign`, `style.textVerticalAlign`
* of element will be ignored if textContent.position is set
*/
private _textContent: RichText
/**
* Layout of textContent
*/
textLayout: TextLayout
constructor(opts?: ElementOption) {
=======
// FOR ECHARTS
/**
* Id for mapping animation
*/
anid: string
constructor(opts?: ElementProps) {
>>>>>>>
/**
* Attached text element.
* `position`, `style.textAlign`, `style.textVerticalAlign`
* of element will be ignored if textContent.position is set
*/
private _textContent: RichText
/**
* Layout of textContent
*/
textLayout: TextLayout
// FOR ECHARTS
/**
* Id for mapping animation
*/
anid: string
constructor(opts?: ElementOption) {
<<<<<<<
// TODO Use T insteadof ElementOption?
protected attrKV(key: keyof ElementOption, value: AllPropTypes<ElementOption>) {
=======
protected attrKV(key: string, value: unknown) {
>>>>>>>
protected attrKV(key: string, value: unknown) {
<<<<<<<
attr(key: keyof T, value: AllPropTypes<T>): Element<T>
attr(key: T): Element<T>
=======
attr(key: Props): this
attr(key: keyof Props, value: AllPropTypes<Props>): this
>>>>>>>
attr(key: Props): this
attr(key: keyof Props, value: AllPropTypes<Props>): this
<<<<<<<
attr(key: keyof T | T, value?: AllPropTypes<T>): Element<T> {
=======
attr(key: keyof Props | Props, value?: AllPropTypes<Props>): this {
>>>>>>>
attr(key: keyof Props | Props, value?: AllPropTypes<Props>): this {
<<<<<<<
for (let name in (key as T)) {
=======
for (let name in key as Props) {
>>>>>>>
for (let name in key as Props) {
<<<<<<<
// TODO as unkown
clipPath.__clipTarget = this as unknown as Element;
=======
// TODO
clipPath.__clipTarget = this as unknown as Element;
>>>>>>>
// TODO
clipPath.__clipTarget = this as unknown as Element;
<<<<<<<
animateTo(target: T): void
animateTo(target: T, callback: AnimationCallback): void
animateTo(target: T, time: number, callback: AnimationCallback): void
animateTo(target: T, time: number, delay: number, callback: AnimationCallback): void
animateTo(target: T, time: number, easing: easingType, callback: AnimationCallback): void
animateTo(target: T, time: number, delay: number, easing: easingType, callback: AnimationCallback): void
animateTo(target: T, time: number, delay: number, easing: easingType, callback: AnimationCallback, forceAnimate: boolean): void
=======
animateTo(target: Props): void
animateTo(target: Props, callback: AnimationCallback): void
animateTo(target: Props, time: number, delay: number): void
animateTo(target: Props, time: number, easing: easingType): void
animateTo(target: Props, time: number, callback: AnimationCallback): void
animateTo(target: Props, time: number, delay: number, callback: AnimationCallback): void
animateTo(target: Props, time: number, easing: easingType, callback: AnimationCallback): void
animateTo(target: Props, time: number, delay: number, easing: easingType, callback: AnimationCallback): void
animateTo(target: Props, time: number, delay: number, easing: easingType, callback: AnimationCallback, forceAnimate: boolean): void
>>>>>>>
animateTo(target: Props): void
animateTo(target: Props, callback: AnimationCallback): void
animateTo(target: Props, time: number, delay: number): void
animateTo(target: Props, time: number, easing: easingType): void
animateTo(target: Props, time: number, callback: AnimationCallback): void
animateTo(target: Props, time: number, delay: number, callback: AnimationCallback): void
animateTo(target: Props, time: number, easing: easingType, callback: AnimationCallback): void
animateTo(target: Props, time: number, delay: number, easing: easingType, callback: AnimationCallback): void
animateTo(target: Props, time: number, delay: number, easing: easingType, callback: AnimationCallback, forceAnimate: boolean): void
<<<<<<<
this: Element,
target: T,
=======
target: Props,
>>>>>>>
target: Props,
<<<<<<<
animateFrom(target: T): void
animateFrom(target: T, callback: AnimationCallback): void
animateFrom(target: T, time: number, callback: AnimationCallback): void
animateFrom(target: T, time: number, delay: number, callback: AnimationCallback): void
animateFrom(target: T, time: number, easing: easingType, callback: AnimationCallback): void
animateFrom(target: T, time: number, delay: number, easing: easingType, callback: AnimationCallback): void
animateFrom(target: T, time: number, delay: number, easing: easingType, callback: AnimationCallback, forceAnimate: boolean): void
=======
animateFrom(target: Props): void
animateFrom(target: Props, callback: AnimationCallback): void
animateFrom(target: Props, time: number, delay: number): void
animateFrom(target: Props, time: number, easing: easingType): void
animateFrom(target: Props, time: number, callback: AnimationCallback): void
animateFrom(target: Props, time: number, delay: number, callback: AnimationCallback): void
animateFrom(target: Props, time: number, easing: easingType, callback: AnimationCallback): void
animateFrom(target: Props, time: number, delay: number, easing: easingType, callback: AnimationCallback): void
animateFrom(target: Props, time: number, delay: number, easing: easingType, callback: AnimationCallback, forceAnimate: boolean): void
>>>>>>>
animateFrom(target: Props): void
animateFrom(target: Props, callback: AnimationCallback): void
animateFrom(target: Props, time: number, delay: number): void
animateFrom(target: Props, time: number, easing: easingType): void
animateFrom(target: Props, time: number, callback: AnimationCallback): void
animateFrom(target: Props, time: number, delay: number, callback: AnimationCallback): void
animateFrom(target: Props, time: number, easing: easingType, callback: AnimationCallback): void
animateFrom(target: Props, time: number, delay: number, easing: easingType, callback: AnimationCallback): void
animateFrom(target: Props, time: number, delay: number, easing: easingType, callback: AnimationCallback, forceAnimate: boolean): void
<<<<<<<
this: Element,
target: T,
=======
target: Props,
>>>>>>>
target: Props,
<<<<<<<
=======
>>>>>>>
<<<<<<<
zrUtil.mixin(Element, Eventful);
zrUtil.mixin(Element, Transformable);
function animateTo(
animatable: Element,
=======
function animateTo<T>(
animatable: Element<T>,
>>>>>>>
zrUtil.mixin(Element, Eventful);
zrUtil.mixin(Element, Transformable);
function animateTo<T>(
animatable: Element<T>,
<<<<<<<
function setAttrByPath(el: Element, path: string, name: string, value: any) {
=======
function setAttrByPath<T>(el: Element<T>, path: string, name: string, value: any) {
let pathArr = path.split('.');
>>>>>>>
function setAttrByPath<T>(el: Element<T>, path: string, name: string, value: any) {
let pathArr = path.split('.');
<<<<<<<
el.attr(name as keyof ElementOption, value);
=======
el.attr(name as keyof T, value);
>>>>>>>
el.attr(name as keyof T, value);
<<<<<<<
}
export default Element;
=======
}
export default Element;
>>>>>>>
}
export default Element; |
<<<<<<<
import { Path, IncrementalDisplayable, Rect } from '../export';
import Displayable from '../graphic/Displayable';
=======
import { Path, IncrementalDisplayable } from '../export';
import Displayable from '../graphic/Displayable';
>>>>>>>
import { Path, IncrementalDisplayable } from '../export';
import Displayable from '../graphic/Displayable';
<<<<<<<
import BoundingRect from '../core/BoundingRect';
=======
import Element from '../Element';
>>>>>>>
import BoundingRect from '../core/BoundingRect';
import Element from '../Element';
<<<<<<<
this.refreshHover();
this._prevDisplayList = list.slice();
=======
>>>>>>>
<<<<<<<
// Use transform
// FIXME style and shape ?
if (!originalEl.invisible) {
el.transform = originalEl.transform;
el.invTransform = originalEl.invTransform;
el.__clipPaths = originalEl.__clipPaths;
this._doPaintEl(el, hoverLayer, null, true, scope, i === len - 1);
=======
let ctx;
for (let i = 0; i < len; i++) {
const el = list[i];
if (el.__inHover) {
// Use a extream large zlevel
// FIXME?
if (!hoverLayer) {
hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
}
if (!ctx) {
ctx = hoverLayer.ctx;
ctx.save();
}
brush(ctx, el, scope, i === len - 1);
>>>>>>>
let ctx;
for (let i = 0; i < len; i++) {
const el = list[i];
if (el.__inHover) {
// Use a extream large zlevel
// FIXME?
if (!hoverLayer) {
hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
}
if (!ctx) {
ctx = hoverLayer.ctx;
ctx.save();
}
brush(ctx, el, scope, i === len - 1);
<<<<<<<
const finished = this._doPaintList(list, prevList, paintAll);
=======
const {finished, needsRefreshHover} = this._doPaintList(list, paintAll);
>>>>>>>
const {finished, needsRefreshHover} = this._doPaintList(list, prevList, paintAll);
<<<<<<<
private _doPaintList (list: Displayable[], prevList: Displayable[], paintAll?: boolean) {
=======
private _doPaintList(list: Displayable[], paintAll?: boolean): {
finished: boolean
needsRefreshHover: boolean
} {
>>>>>>>
private _doPaintList(list: Displayable[], prevList: Displayable[], paintAll?: boolean): {
finished: boolean
needsRefreshHover: boolean
} {
<<<<<<<
const repaintRects = layer.createRepaintRects(list, prevList);
=======
const scope: BrushScope = {
inHover: false,
allClipped: false,
prevEl: null,
viewWidth: this._width,
viewHeight: this._height
};
ctx.save();
>>>>>>>
const repaintRects = layer.createRepaintRects(list, prevList);
ctx.save();
<<<<<<<
const repaint = (repaintRect?: BoundingRect) => {
const scope: BrushScope = {
allClipped: false,
prevEl: null,
viewWidth: this._width,
viewHeight: this._height
};
for (i = start; i < layer.__endIndex; i++) {
const el = list[i];
this._doPaintEl(el, layer, repaintRect, paintAll, scope, i === layer.__endIndex - 1);
el.__dirty = 0;
if (useTimer) {
// Date.now can be executed in 13,025,305 ops/second.
const dTime = Date.now() - startTime;
// Give 15 millisecond to draw.
// The rest elements will be drawn in the next frame.
if (dTime > 15) {
break;
}
=======
for (i = start; i < layer.__endIndex; i++) {
const el = list[i];
if (el.__inHover) {
needsRefreshHover = true;
}
brush(ctx, el, scope, i === layer.__endIndex - 1);
if (useTimer) {
// Date.now can be executed in 13,025,305 ops/second.
const dTime = Date.now() - startTime;
// Give 15 millisecond to draw.
// The rest elements will be drawn in the next frame.
if (dTime > 15) {
break;
>>>>>>>
const repaint = (repaintRect?: BoundingRect) => {
const scope: BrushScope = {
inHover: false,
allClipped: false,
prevEl: null,
viewWidth: this._width,
viewHeight: this._height
};
for (i = start; i < layer.__endIndex; i++) {
const el = list[i];
if (el.__inHover) {
needsRefreshHover = true;
}
this._doPaintEl(el, layer, repaintRect, scope, i === layer.__endIndex - 1);
el.__dirty = 0;
if (useTimer) {
// Date.now can be executed in 13,025,305 ops/second.
const dTime = Date.now() - startTime;
// Give 15 millisecond to draw.
// The rest elements will be drawn in the next frame.
if (dTime > 15) {
break;
}
<<<<<<<
return finished;
}
private _doPaintEl (
el: Displayable,
currentLayer: Layer,
repaintRect: BoundingRect,
forcePaint: boolean,
scope: BrushScope,
isLast: boolean
) {
const ctx = currentLayer.ctx;
if (currentLayer.__dirty || forcePaint) {
if (repaintRect) {
// If there is repaintRect, only render the intersected ones
if (el.getPaintRect().intersect(repaintRect)) {
// console.log('rebrush', el.id);
brush(ctx, el, scope, isLast);
}
}
else {
// If no repaintRect, all displayables need to be painted once
brush(ctx, el, scope, isLast);
// console.log('brush', el.id);
}
}
=======
return {
finished,
needsRefreshHover
};
>>>>>>>
return {
finished,
needsRefreshHover
};
}
private _doPaintEl (
el: Displayable,
currentLayer: Layer,
repaintRect: BoundingRect,
scope: BrushScope,
isLast: boolean
) {
const ctx = currentLayer.ctx;
if (repaintRect) {
// If there is repaintRect, only render the intersected ones
if (el.getPaintRect().intersect(repaintRect)) {
// console.log('rebrush', el.id);
brush(ctx, el, scope, isLast);
}
}
else {
// If no repaintRect, all displayables need to be painted once
brush(ctx, el, scope, isLast);
// console.log('brush', el.id);
}
<<<<<<<
this._doPaintEl(
el,
imageLayer,
null,
true,
scope,
i === len - 1
);
=======
brush(ctx, el, scope, i === len - 1);
>>>>>>>
brush(ctx, el, scope, i === len - 1); |
<<<<<<<
getAnimationStyleProps() {
=======
getWidth(): number {
const style = this.style;
const imageSource = style.image;
if (isImageLike(imageSource)) {
return (imageSource as HTMLImageElement).width;
}
if (!this.__image) {
return 0;
}
let width = style.width;
let height = style.height;
if (width == null) {
if (height == null) {
return this.__image.width;
}
else {
const aspect = this.__image.width / this.__image.height;
return aspect * height;
}
}
else {
return width;
}
}
getHeight(): number {
const style = this.style;
const imageSource = style.image;
if (isImageLike(imageSource)) {
return (imageSource as HTMLImageElement).height;
}
if (!this.__image) {
return 0;
}
let width = style.width;
let height = style.height;
if (height == null) {
if (width == null) {
return this.__image.height;
}
else {
const aspect = this.__image.height / this.__image.width;
return aspect * width;
}
}
else {
return height;
}
}
protected _getAnimationStyleProps() {
>>>>>>>
getWidth(): number {
const style = this.style;
const imageSource = style.image;
if (isImageLike(imageSource)) {
return (imageSource as HTMLImageElement).width;
}
if (!this.__image) {
return 0;
}
let width = style.width;
let height = style.height;
if (width == null) {
if (height == null) {
return this.__image.width;
}
else {
const aspect = this.__image.width / this.__image.height;
return aspect * height;
}
}
else {
return width;
}
}
getHeight(): number {
const style = this.style;
const imageSource = style.image;
if (isImageLike(imageSource)) {
return (imageSource as HTMLImageElement).height;
}
if (!this.__image) {
return 0;
}
let width = style.width;
let height = style.height;
if (height == null) {
if (width == null) {
return this.__image.height;
}
else {
const aspect = this.__image.height / this.__image.width;
return aspect * width;
}
}
else {
return height;
}
}
getAnimationStyleProps() { |
<<<<<<<
import { Path, IncrementalDisplayable, Rect } from '../export';
import Displayable from '../graphic/Displayable';
=======
import { Path, IncrementalDisplayable } from '../export';
import Displayable, { CommonStyleProps } from '../graphic/Displayable';
>>>>>>>
import { Path, IncrementalDisplayable, Rect } from '../export';
import Displayable from '../graphic/Displayable';
<<<<<<<
import { brush, BrushScope, getPaintRect, doClip } from './graphic';
import ZText, { TextStyleOption } from '../graphic/Text';
import { PathStyleOption } from '../graphic/Path';
=======
import { brush, BrushScope } from './graphic';
import TSpan from '../graphic/TSpan';
>>>>>>>
import { brush, BrushScope, getPaintRect } from './graphic';
import TSpan from '../graphic/TSpan';
<<<<<<<
this._doPaintEl(el, hoverLayer, null, true, scope);
=======
// el.
this._doPaintEl(el, hoverLayer, true, scope, i === len - 1);
>>>>>>>
this._doPaintEl(el, hoverLayer, null, true, scope, i === len - 1);
<<<<<<<
private _paintList (list: Displayable[], prevList: Displayable[], paintAll: boolean, redrawId?: number) {
=======
private _paintList(list: Displayable[], paintAll: boolean, redrawId?: number) {
>>>>>>>
private _paintList (list: Displayable[], prevList: Displayable[], paintAll: boolean, redrawId?: number) {
<<<<<<<
private _doPaintList (list: Displayable[], prevList: Displayable[], paintAll?: boolean) {
=======
private _doPaintList(list: Displayable[], paintAll?: boolean) {
>>>>>>>
private _doPaintList (list: Displayable[], prevList: Displayable[], paintAll?: boolean) {
<<<<<<<
const repaint = (repaintRect?: BoundingRect) => {
for (i = start; i < layer.__endIndex; i++) {
const el = list[i];
this._doPaintEl(el, layer, repaintRect, paintAll, scope);
el.__dirty = false;
if (useTimer) {
// Date.now can be executed in 13,025,305 ops/second.
const dTime = Date.now() - startTime;
// Give 15 millisecond to draw.
// The rest elements will be drawn in the next frame.
if (dTime > 15) {
break;
}
=======
for (i = start; i < layer.__endIndex; i++) {
const el = list[i];
this._doPaintEl(el, layer, paintAll, scope, i === layer.__endIndex - 1);
if (useTimer) {
// Date.now can be executed in 13,025,305 ops/second.
const dTime = Date.now() - startTime;
// Give 15 millisecond to draw.
// The rest elements will be drawn in the next frame.
if (dTime > 15) {
break;
>>>>>>>
const repaint = (repaintRect?: BoundingRect) => {
for (i = start; i < layer.__endIndex; i++) {
const el = list[i];
this._doPaintEl(el, layer, repaintRect, paintAll, scope, i === layer.__endIndex - 1);
el.__dirty = 0;
if (useTimer) {
// Date.now can be executed in 13,025,305 ops/second.
const dTime = Date.now() - startTime;
// Give 15 millisecond to draw.
// The rest elements will be drawn in the next frame.
if (dTime > 15) {
break;
}
<<<<<<<
private _doPaintEl (
el: Displayable,
currentLayer: Layer,
repaintRect: BoundingRect,
forcePaint: boolean,
scope: BrushScope
) {
=======
private _doPaintEl(
el: Displayable,
currentLayer: Layer,
forcePaint: boolean,
scope: BrushScope,
isLast: boolean
) {
>>>>>>>
private _doPaintEl (
el: Displayable,
currentLayer: Layer,
repaintRect: BoundingRect,
forcePaint: boolean,
scope: BrushScope,
isLast: boolean
) {
<<<<<<<
if (repaintRect) {
// If there is repaintRect, only render the intersected ones
const repaintRect = getPaintRect(el);
if (repaintRect.intersect(repaintRect)) {
console.log('rebrush', el.id);
brush(ctx, el, scope);
}
}
else {
// If no repaintRect, all displayables need to be painted once
brush(ctx, el, scope);
console.log('brush', el.id);
}
=======
brush(ctx, el, scope, isLast);
>>>>>>>
if (repaintRect) {
// If there is repaintRect, only render the intersected ones
const repaintRect = getPaintRect(el);
if (repaintRect.intersect(repaintRect)) {
// console.log('rebrush', el.id);
brush(ctx, el, scope, isLast);
}
}
else {
// If no repaintRect, all displayables need to be painted once
brush(ctx, el, scope, isLast);
// console.log('brush', el.id);
}
<<<<<<<
this._doPaintEl(el, imageLayer, null, true, scope);
=======
this._doPaintEl(
el,
imageLayer,
true,
scope,
i === len - 1
);
>>>>>>>
this._doPaintEl(
el,
imageLayer,
null,
true,
scope,
i === len - 1
); |
<<<<<<<
import Element, {ElementEventCallback} from './Element';
=======
import Element, {ElementEventCallback, ElementEvent} from './Element';
import CanvasPainter from './canvas/Painter';
>>>>>>>
import Element, {ElementEventCallback, ElementEvent} from './Element';
<<<<<<<
=======
import { StyleProps } from './graphic/Style';
import Displayable from './graphic/Displayable';
>>>>>>>
<<<<<<<
addHover(el: Path | ZText | ZImage, style: PathStyleOption | TextStyleOption | ImageStyleOption): Path | ZText | ZImage {
if (this.painter.addHover) {
const elMirror = this.painter.addHover(
// TODO
el as Path, style as PathStyleOption
);
=======
addHover(el: Displayable, style?: StyleProps) {
if ((this.painter as CanvasPainter).addHover) {
const elMirror = (this.painter as CanvasPainter).addHover(el, style);
>>>>>>>
addHover(el: Path | ZText | ZImage, style: PathStyleOption | TextStyleOption | ImageStyleOption): Path | ZText | ZImage {
if (this.painter.addHover) {
const elMirror = this.painter.addHover(
// TODO
el as Path, style as PathStyleOption
); |
<<<<<<<
const rect = getBoundingRect(
style.text + '',
=======
const rect = textContain.getBoundingRect(
text,
>>>>>>>
const rect = getBoundingRect(
text, |
<<<<<<<
completionProvider: { resolveProvider: true, triggerCharacters: ['.', ':', '<', '"', '=', '/', '@'] },
=======
completionProvider: { resolveProvider: true, triggerCharacters: ['.', ':', '<', '"', '/'] },
>>>>>>>
completionProvider: { resolveProvider: true, triggerCharacters: ['.', ':', '<', '"', '/', '@'] }, |
<<<<<<<
}
declare module 'eslint' {
export interface ESLintError {
ruleId: string;
severity: number;
message: string;
line: number;
column: number;
nodeType: string;
source: string;
endLine?: number;
endColumn?: number;
}
export interface Report {
results: {
messages: ESLintError[]
}[];
}
export class CLIEngine {
constructor(config: any)
executeOnText(text: string, filename: string): Report;
}
}
declare module 'eslint-plugin-vue';
=======
}
declare module '*.json';
>>>>>>>
}
declare module 'eslint' {
export interface ESLintError {
ruleId: string;
severity: number;
message: string;
line: number;
column: number;
nodeType: string;
source: string;
endLine?: number;
endColumn?: number;
}
export interface Report {
results: {
messages: ESLintError[]
}[];
}
export class CLIEngine {
constructor(config: any)
executeOnText(text: string, filename: string): Report;
}
}
declare module 'eslint-plugin-vue';
declare module '*.json'; |
<<<<<<<
import { TextDocument } from 'vscode-languageserver-types';
import parseGitIgnore from 'parse-gitignore';
=======
import { TextDocument } from 'vscode-languageserver-textdocument';
import * as parseGitIgnore from 'parse-gitignore';
>>>>>>>
import { TextDocument } from 'vscode-languageserver-textdocument';
import parseGitIgnore from 'parse-gitignore'; |
<<<<<<<
node_navbar: {
toggle: 'Toggle navigation',
project_nav: 'Project Navigation',
wiki: 'Wiki',
analytics: 'Analytics',
registrations: 'Registrations',
files: 'Files',
contributors: 'Contributors',
addons: 'Add-ons',
settings: 'Settings',
comments: 'Comments',
},
=======
osf_copyright: {
copyright: 'Copyright © 2011-{{currentYear}}',
terms: 'Terms of Use',
privacy: 'Privacy Policy',
separator: ' | ',
},
dropzone_widget: {
drop_files: 'Drop files here to upload',
error_multiple_files: 'Cannot upload multiple files',
error_directories: 'Cannot upload directories, applications, or packages',
},
>>>>>>>
node_navbar: {
toggle: 'Toggle navigation',
project_nav: 'Project Navigation',
wiki: 'Wiki',
analytics: 'Analytics',
registrations: 'Registrations',
files: 'Files',
contributors: 'Contributors',
addons: 'Add-ons',
settings: 'Settings',
comments: 'Comments',
},
osf_copyright: {
copyright: 'Copyright © 2011-{{currentYear}}',
terms: 'Terms of Use',
privacy: 'Privacy Policy',
separator: ' | ',
},
dropzone_widget: {
drop_files: 'Drop files here to upload',
error_multiple_files: 'Cannot upload multiple files',
error_directories: 'Cannot upload directories, applications, or packages',
}, |
<<<<<<<
=======
private async showServer(server: server.Server, displayServer: DisplayServer): Promise<void> {
if (await server.isHealthy()) {
// Sync the server display in case it was previously unreachable.
await this.syncServerToDisplay(server);
await this.showServerManagement(server, displayServer);
} else {
await this.showServerUnreachable(server, displayServer);
}
}
private async showServerUnreachable(server: server.Server, displayServer: DisplayServer):
Promise<void> {
// Display the unreachable server state within the server view.
const serverView = this.appRoot.getServerView(displayServer.id) as ServerView;
serverView.isServerReachable = false;
serverView.isServerManaged = isManagedServer(server);
serverView.serverName = displayServer.name; // Don't get the name from the remote server.
serverView.retryDisplayingServer = async () => {
// Refresh the server list if the server is managed, it may have been deleted outside the
// app.
let serverExists = true;
if (serverView.isServerManaged && !!this.digitalOceanRepository) {
await this.digitalOceanRepository.listServers();
serverExists = !!(await this.getServerFromRepository(displayServer));
}
if (serverExists) {
await this.showServer(server, displayServer);
} else {
// Server has been deleted outside the app.
this.appRoot.showError(
this.appRoot.localize('error-server-removed', 'serverName', displayServer.name));
this.removeServerFromDisplay(displayServer);
this.selectedServer = null;
this.appRoot.selectedServer = null;
this.showIntro();
}
};
this.selectedServer = server;
this.appRoot.selectedServer = displayServer;
this.appRoot.showServerView();
}
>>>>>>> |
<<<<<<<
const shadowsocksServer =
new OutlineShadowsocksServer(
getPersistentFilename('outline-ss-server/config.yml'), verbose, ssMetricsLocation)
.enableCountryMetrics(MMDB_LOCATION);
=======
const rollouts = createRolloutTracker(serverConfig);
let shadowsocksServer: ShadowsocksServer;
if (rollouts.isRolloutEnabled('outline-ss-server', 100)) {
const ssMetricsLocation = `localhost:${ssMetricsPort}`;
logging.info(`outline-ss-server metrics is at ${ssMetricsLocation}`);
prometheusConfigJson.scrape_configs.push(
{job_name: 'outline-server-ss', static_configs: [{targets: [ssMetricsLocation]}]});
shadowsocksServer =
new OutlineShadowsocksServer(
getPersistentFilename('outline-ss-server/config.yml'), verbose, ssMetricsLocation)
.enableCountryMetrics(MMDB_LOCATION);
} else {
const ipLocation = new ip_location.MmdbLocationService(MMDB_LOCATION);
const metricsWriter = createPrometheusUsageMetricsWriter(prometheus.register);
shadowsocksServer = await createLibevShadowsocksServer(
proxyHostname, await portProvider.reserveNewPort(), ipLocation, metricsWriter, verbose);
}
runPrometheusScraper(
[
'--storage.tsdb.retention', '31d', '--storage.tsdb.path',
getPersistentFilename('prometheus/data'), '--web.listen-address', prometheusLocation,
'--log.level', verbose ? 'debug' : 'info'
],
getPersistentFilename('prometheus/config.yml'), prometheusConfigJson);
>>>>>>>
const ssMetricsLocation = `localhost:${ssMetricsPort}`;
logging.info(`outline-ss-server metrics is at ${ssMetricsLocation}`);
prometheusConfigJson.scrape_configs.push(
{job_name: 'outline-server-ss', static_configs: [{targets: [ssMetricsLocation]}]});
const shadowsocksServer =
new OutlineShadowsocksServer(
getPersistentFilename('outline-ss-server/config.yml'), verbose, ssMetricsLocation)
.enableCountryMetrics(MMDB_LOCATION);
runPrometheusScraper(
[
'--storage.tsdb.retention', '31d', '--storage.tsdb.path',
getPersistentFilename('prometheus/data'), '--web.listen-address', prometheusLocation,
'--log.level', verbose ? 'debug' : 'info'
],
getPersistentFilename('prometheus/config.yml'), prometheusConfigJson); |
<<<<<<<
import { CPMouse } from './directive/cp-mouse';
=======
import { CPPlaceholder } from './directive/cp-placeholder';
>>>>>>>
import { CPMouse } from './directive/cp-mouse';
import { CPPlaceholder } from './directive/cp-placeholder';
<<<<<<<
cpTitles: [],
cpMouse: [],
=======
cpTitles: [],
cpPlaceholder: [],
>>>>>>>
cpTitles: [],
cpMouse: [],
cpPlaceholder: [],
<<<<<<<
if (child.hasAttributeStartingWith(Constants.MOUSE_ATTRIBUTE_NAME)) { this.createCPmouse(child); }
=======
if (child.hasAttribute(Constants.PLACEHOLDER_ATTRIBUTE_NAME)) { this.createCPPlaceholder(child); }
>>>>>>>
if (child.hasAttributeStartingWith(Constants.MOUSE_ATTRIBUTE_NAME)) { this.createCPmouse(child); }
if (child.hasAttribute(Constants.PLACEHOLDER_ATTRIBUTE_NAME)) { this.createCPPlaceholder(child); }
<<<<<<<
// Update cp Mouse
this.directives.cpMouse.forEach((cpMouse) => cpMouse.init());
=======
// Update cp placeholder
this.directives.cpPlaceholder.forEach((cpPlaceholder) => cpPlaceholder.init());
>>>>>>>
// Update cp Mouse
this.directives.cpMouse.forEach((cpMouse) => cpMouse.init());
// Update cp placeholder
this.directives.cpPlaceholder.forEach((cpPlaceholder) => cpPlaceholder.init());
<<<<<<<
/**
* @param child Elemento que está sendo criado o bind do dbTitle.
*/
public createCPmouse(child) {
this.directives.cpMouse.push(new CPMouse(child, this));
}
=======
/**
* @param child Elemento que está sendo criado o bind do placeholder.
*/
public createCPPlaceholder(child) {
this.directives.cpPlaceholder.push(new CPPlaceholder(child, this));
}
>>>>>>>
/**
* @param child Elemento que está sendo criado o bind do dbTitle.
*/
public createCPmouse(child) {
this.directives.cpMouse.push(new CPMouse(child, this));
}
/**
* @param child Elemento que está sendo criado o bind do placeholder.
*/
public createCPPlaceholder(child) {
this.directives.cpPlaceholder.push(new CPPlaceholder(child, this));
} |
<<<<<<<
import { CPElse } from "./directive/cp-else";
import { CPElseIf } from "./directive/cp-else-if";
import { CPIf } from "./directive/cp-if";
import { CPInit } from "./directive/cp-init";
import { CPKey } from "./directive/cp-key";
import { CPMax } from "./directive/cp-max";
import { CPMaxLength } from "./directive/cp-maxlength";
import { CPMin } from "./directive/cp-min";
=======
import { CPDisabled } from './directive/cp-disabled';
import { CPElse } from './directive/cp-else';
import { CPElseIf } from './directive/cp-else-if';
import { CPFocus } from './directive/cp-focus';
import { CPHide } from './directive/cp-hide';
import { CPIf } from './directive/cp-if';
import { CPInit } from './directive/cp-init';
import { CPKey } from './directive/cp-key';
import { CPMax } from './directive/cp-max';
import { CPMin } from './directive/cp-min';
>>>>>>>
import { CPDisabled } from './directive/cp-disabled';
import { CPElse } from './directive/cp-else';
import { CPElseIf } from './directive/cp-else-if';
import { CPFocus } from './directive/cp-focus';
import { CPHide } from './directive/cp-hide';
import { CPIf } from './directive/cp-if';
import { CPInit } from './directive/cp-init';
import { CPKey } from './directive/cp-key';
import { CPMax } from './directive/cp-max';
import { CPMaxLength } from "./directive/cp-maxlength";
import { CPMin } from './directive/cp-min';
<<<<<<<
if (child.hasAttribute(Constants.MAX_LENGTH_ATTRIBUTE_NAME)) { this.createCPMaxLength(child); }
=======
if (child.hasAttribute(Constants.DISABLE_ATTRIBUTE_NAME)) { this.createCPDisabled(child); }
if (child.hasAttribute(Constants.FOCUS_ATTRIBUTE_NAME)) { this.createCPFocus(child); }
if (child.hasAttribute(Constants.HIDE_ATTRIBUTE_NAME)) { this.createCPHide(child); }
if (child.hasAttribute(Constants.BLUR_ATTRIBUTE_NAME)) { this.createCPBlur(child); }
>>>>>>>
if (child.hasAttribute(Constants.MAX_LENGTH_ATTRIBUTE_NAME)) { this.createCPMaxLength(child); }
if (child.hasAttribute(Constants.DISABLE_ATTRIBUTE_NAME)) { this.createCPDisabled(child); }
if (child.hasAttribute(Constants.FOCUS_ATTRIBUTE_NAME)) { this.createCPFocus(child); }
if (child.hasAttribute(Constants.HIDE_ATTRIBUTE_NAME)) { this.createCPHide(child); }
if (child.hasAttribute(Constants.BLUR_ATTRIBUTE_NAME)) { this.createCPBlur(child); }
<<<<<<<
// Update cp max length
this.directives.cpMaxsLength.forEach((cpMaxLength) => cpMaxLength.init());
=======
// Update cp disable
this.directives.cpDisables.forEach((cpDisable) => cpDisable.init());
// Update cp focus
this.directives.cpFocus.forEach((cpFocus) => cpFocus.init());
// Update cp hide
this.directives.cpHide.forEach((cpHide) => cpHide.init());
// Update cp blur
this.directives.cpBlur.forEach((cpBlur) => cpBlur.init());
>>>>>>>
// Update cp max length
this.directives.cpMaxsLength.forEach((cpMaxLength) => cpMaxLength.init());
// Update cp disable
this.directives.cpDisables.forEach((cpDisable) => cpDisable.init());
// Update cp focus
this.directives.cpFocus.forEach((cpFocus) => cpFocus.init());
// Update cp hide
this.directives.cpHide.forEach((cpHide) => cpHide.init());
// Update cp blur
this.directives.cpBlur.forEach((cpBlur) => cpBlur.init());
<<<<<<<
/**
* @param child Elemento que está sendo criado o bind do max length.
*/
public createCPMaxLength(child) {
this.directives.cpMaxsLength.push(new CPMaxLength(child, this));
}
=======
/**
* @param child Elemento que está sendo criado o bind do disable.
*/
public createCPDisabled(child) {
this.directives.cpDisables.push(new CPDisabled(child, this));
}
/**
* @param child Elemento que está sendo criado o bind do focus.
*/
public createCPFocus(child) {
this.directives.cpFocus.push(new CPFocus(child, this));
}
/**
* @param child Elemento que está sendo criado o bind do hide.
*/
public createCPHide(child) {
this.directives.cpHide.push(new CPHide(child, this));
}
/**
* @param child Elemento que está sendo criado o bind do blur.
*/
public createCPBlur(child) {
this.directives.cpBlur.push(new CPBlur(child, this));
}
>>>>>>>
/**
* @param child Elemento que está sendo criado o bind do max length.
*/
public createCPMaxLength(child) {
this.directives.cpMaxsLength.push(new CPMaxLength(child, this));
}
/**
* @param child Elemento que está sendo criado o bind do disable.
*/
public createCPDisabled(child) {
this.directives.cpDisables.push(new CPDisabled(child, this));
}
/**
* @param child Elemento que está sendo criado o bind do focus.
*/
public createCPFocus(child) {
this.directives.cpFocus.push(new CPFocus(child, this));
}
/**
* @param child Elemento que está sendo criado o bind do hide.
*/
public createCPHide(child) {
this.directives.cpHide.push(new CPHide(child, this));
}
/**
* @param child Elemento que está sendo criado o bind do blur.
*/
public createCPBlur(child) {
this.directives.cpBlur.push(new CPBlur(child, this));
} |