First steps with Flask (Edition... Getting started with Flask (Creating a Hello World Python Flask app)
The following examples show how to use itlodashYou can upvote the ones you like or downvote the ones you don't and go to the original project or source file by following the links above each example. You can check the usage of the related API in the sidebar.
Example 1
source file:Range Selection.tsFrom S2 licensed by MIT | 6You | ![]() ![]() |
PrivatehandleSeriesNumberRowSelected( startIndex:Number, final index:Number, Cell: S2CellType<ViewMeta>, ) {// Serial number header in table mode untilcellIdSufFix =He.spreadsheet.facet.layoutResult.colLeafNodes[0].ID;go backrange(startIndex, endIndex +1).Map((line) =>{untilprefixIdCelda =line(Fila);go back{ ID: cellId prefix +'-'+ cellIdSuffix, colIndex:0, row index: row,type: cell.cell type, }; }); }
Example #2
source file:padlock-limits.test.tsFrom airnode under MIT license | 6You | ![]() ![]() |
createRequests = (apiCallsCount:Number, Payment count:Number):bundled requests=>{// We want the generated requests to be sorted by order of execution permissionblock number =12345;go back{ apiCalls: range(apiCallsCount).map(()=>{go backFixtures.requests.buildApiCall({ Metadatos: Fixtures.requests.buildMetadata({ BlockNumber: BlockNumber++ }), }); }), Auszahlungen: range(withdrawalCount).map(()=>{go backFixtures.requests.buildApiCall({ Metadatos: Fixtures.requests.buildMetadata({ BlockNumber: BlockNumber++ }), }); }), };}
Example #3
source file:LogCompression.test.tsFrom balancer-v2-monorepo with GNU General Public License v3 | 6You | ![]() ![]() |
// 0.05% or ~e^0.00005describe('log compression',function(){permissionsimulacrum: contract; Before(asynchronous function(){simulacrum =waitinsert('MockLogCompression'); });function ValoresEnMagnitud(Performance:Number){go back[0,4,1.2,2.9,3.3,4.8,5.3,6.1,7.4,8.5,9.4].Map((x) =>Sr. (X *10** Performance)); }function itRecoversOriginalValueWithError(Minimum performance:Number, maximum power:Number, maxRelativeError:Number){for(untilpower range(minPower, maxPower)) { is(encodes and decodes powers of${power}`,asynchronous() => {for(untiloriginal values in magnitude(power)) {untilactually =waitsimulacro.fromLowResLog(waitmaqueta.toLowResLog(Original)); ExpectEqualWithError(real, original, maxRelativeError); } }); } } describe('small values',()=>{ GetOriginalValueWithError(1,5,0,1);// Smaller values have greater error due to lack of resolution}); describe('medium and large values',()=>{ GetOriginalValueWithError(5,35, MAX_RELATIVE_ERROR); });});
Example #4
source file:container-list.editor.tsxDe next-basics con GNU General Public License v3.0 | 6You | ![]() ![]() |
Export function List Container Editor({NodeUid,}: EditorComponentProps):React.reactelement {untilnode = useBuilderNode<ListContainerProperties>({ nodeUid });/** * Note: Use the widget's property settings to expose the main functionality of the widget's user interface. * For example: for button widgets, display the appropriate background color according to `buttonType`. */ // const { someProps } = node.$$parsedProperties; go back( <EditorContainer nodeUid={nodeUid}> <div className={styles.listContainer}> {range(0, 3).map((_, index) => ( <div key={index} className={styles.content }></div> ))} </div> </EditorContainer> );}
Example #5
source file:usePollPredictions.tsVom Glide-Frontend con GNU General Public License v3.0 | 6You | ![]() ![]() |
usePollPredictions =()=>{untiltimer = useRef<JSNode.Timeout>(Null)untilDispatch = useAppDispatch()until{ Konto } = useWeb3React()untilépocaActual = useGetCurrentEpoch()untilearliest epoch = useGetEarliestEpoch()untilestado = useGetPredictionsStatus() useEffect(()=>{// Delete old timer And(timer.current) { clearInterval(timer.current) }And(Status === PredictionStatus.LIVE) {timer.current = setInterval(asynchronous() => {untilliveAndCurrent = [epocaactual, epocaactual -1] Despacho(fetchRounds(liveAndCurrent)) Despacho(fetchMarketData())And(Account) {untilepochRange = range(earliestEpoch, currentEpoch +1) dispatch(fetchLedgerData({ count, epochs: epochRange })) dispatch(fetchClaimableStatuses({ count, epochs: epochRange })) } }, POLL_TIME_IN_SECONDS *1000) }go back ()=>{And(timer.current) { clearInterval(timer.current) } } }, [timer, count, state, current epoch, earliest epoch, dispatch])}
Example #6
source file:GeneMapAxis.tsxBy nextclade under MIT license | 6You | ![]() ![]() |
Export function GeneMapAxis(){untilgenome size = useRecoilValue(genome size)untilgeneMap = useRecoilValue(geneMapAtom)untilvistoGen = useRecoilValue(viewedGenAtom)until{ Brands, Domain } = useMemo(()=>{untillength = getAxisLength(genome size, gene seen, genetic map)untiltickSize = getTickSize(longitud)untildomain: [number, number] = [0, Largo]untilmarks = range (0, length, mark size)go back{ marcas, dominio } }, [GeneMap, GenomSize, ViewedGene])go back( <ResponsiveContainer width="100%" height={30}> <ComposedChart margin={MARGIN}> <XAxis dataKey={'ticks'} type="number" ticks={ticks} domain={domain} axisLine={ false} /> </ComposedChart> </ResponsiveContainer> )}
Example #7
source file:usePollPredictions.tsFrom vvs-ui with GNU General Public License v3.0 | 6You | ![]() ![]() |
usePollPredictions =()=>{untiltimer = useRef<JSNode.Timeout>(Null)untilDispatch = useAppDispatch()until{ Konto } = useWeb3React()untilépocaActual = useGetCurrentEpoch()untilearliest epoch = useGetEarliestEpoch()untilestado = useGetPredictionsStatus() useEffect(()=>{// Delete old timer And(timer.current) { clearInterval(timer.current) }And(estado !== PredictionStatus.INITIAL) { timer.current = setInterval(asynchronous() => {untilliveCurrentAndRecent = [epocaactual, epocaactual -1, current season -2] Despacho(fetchRounds(liveCurrentAndRecent)) Despacho(fetchMarketData())And(Account) {untilepochRange = range(earliestEpoch, currentEpoch +1) dispatch(fetchLedgerData({ count, epochs: epochRange })) dispatch(fetchClaimableStatuses({ count, epochs: epochRange })) } }, POLL_TIME_IN_SECONDS *1000) }go back ()=>{And(timer.current) { clearInterval(timer.current) } } }, [timer, count, state, current epoch, earliest epoch, dispatch])}
Example #8
source file:Range Selection.tsFrom S2 licensed by MIT | 5You | ![]() ![]() |
PrivatebindDataCellClick() {He.spreadsheet.on(S2Event.DATA_CELL_CLICK,(Event: Event) =>{ event. stop propagation();untilCelda: DataCell =He.spreadsheet.getCell(event.ziel);untilmeta = cell.getMeta();until{interaction} =He.spreadsheet;And(!Meta) {go back; }untillast cell clicked =He.spreadsheet.store.get('last cell clicked');untilisShiftSelect =He.isRangeSelection && lastClickedCell?.cellType === cell.cellType;And(!isShiftSelect) {He.spreadsheet.store.set('last cell clicked', whole);go back; }until{ Inicio, Fin } = getRangeIndex (lastClickedCell.getMeta()andViewMeta, cell.getMeta(), );untilceldas = range(start.colIndex, end.colIndex +1).flatmap((column) =>{untilsuffixIdCelda =He.spreadsheet.facet.layoutResult.colLeafNodes[col].id;go backrange(start.rowindex, end.rowindex +1).Map((line) =>{untilprefixIdCelda =He.spreadsheet.facet.getSeriesNumberWidth() ||He.spreadsheet.isTableMode() ?line(Fila) :He.spreadsheet.facet.layoutResult.rowLeafNodes[fila].id;go back{ ID: cellId prefix +'-'+ cellIdSuffix, colIndex: Spalte, rowIndex: Zeile,type: cell.cell type, }; }); }); Interaction.addIntercepts([InterceptType.CLICK, InterceptType.HOVER]); interaction.ChangeState({ cells, state name: interaction state name. SELECTED, });He.spreadsheet.showTooltipWithInfo( Ereignis, getActiveCellsTooltipData(He.spreadsheet), );He.spreadsheet.emit (S2Event.GLOBAL_SELECTED, Interaktion.getActiveCells(), ); }); }
Example #9
source file:Actions.test.tsFrom airnode under MIT license | 5You | ![]() ![]() |
describe('procesarSolicitudes',()=>{ test.each(['Legacy','eip1559']and until)('process requests for each EVM provider - txType: %s',asynchronous(txTipo) => {until{blockSpy, gasPriceSpy} = createAndMockGasTarget(txType); schätzenGasWithdrawalMock.mockResolvedValueOnce(ethers.BigNumber.from(50_000)); staticFulfillMock.mockResolvedValue({ callSuccess:TRUE}); FulfillMock.mockResolvedValue({Hash:'0xad33fe94de7294c6ab461325828276185dff6fed92c54b15ac039c6160d2bac3', });untilSponsor Address ='0x641eeb15B15d8E2CFB5f9d6480B175d93c14e6B6';untilapiCall = Fixtures.requests.buildSuccessfulApiCall ({ ID:'0x67caaa2862cf971502d5c5b3d94d09d15c770f3313e76aa95c296b6587e7e5f1', Sponsor address, });untilSolicitudes: GroupedRequests = { apiCalls: [apiCall], Pagos: [] };untiltransactionCountsBySponsorAddress = { [Sponsor Address]:5};untilall providers = range(2) .Map(()=>Fixtures.buildEVMProviderSponsorState({ Anfragen, TransactionCountsBySponsorAddress, SponsorAddress })) .map((initial state) =>({ ... initial state, configuration: { ... initial state. configuration, string options: { txType, FulfillmentGasLimit:500_000 }, }, }));untilWorkerOpts = Fixtures.buildWorkerOptions();until[registers, resolution] =waitproveedor.processRequests(allProviders, workerOpts); Expect(registros).toEqual([]); expected (txType ==='Legacy'? blockSpy : gasPriceSpy).not.toHaveBeenCalled(); erwartet (txTyp ==='eip1559'? blockSpy : gasPriceSpy).toHaveBeenCalled(); erwarten(res.evm.map((evm) =>evm.requests.apiCalls[0])).toEqual( range(allProviders.length).map(()=>({ ...apiCall, Compliance: { Hash:'0xad33fe94de7294c6ab461325828276185dff6fed92c54b15ac039c6160d2bac3'}, once:5, })) ); });});
Example #10
source file:LunrSearchEngineIndexer.test.tsBackstage licensed Apache 2.0 | 5You | ![]() ![]() |
describe('LunrSearchEngineIndexer',()=>{permissionIndexer: LunrSearchEngineIndexer; vorjedem(()=>{broma.clearAllMocks(); indexer =nuevoLunrSearchEngineIndexer(); }); Él('should index documents',asynchronous() => {untilDocuments = [ { Title:'trial term', Text:'test text', Location:'Test/Location', }, ];waitTestPipeline.withSubject(indexador).withDocuments(documents).execute(); erwartet (lunrBuilderAddSpy).toHaveBeenCalledWith(Dokumente[0]); }); Es('should index documents in bulk',asynchronous() => {untildocuments = area (350).Map(I=>({ title:"Hello World${yo}`, Text:'Lorem Ipsum', Location:`Lage-${yo}`, }));waitTestPipeline.withSubject(indexador).withDocuments(documents).execute(); Expect(lunrBuilderAddSpy).toHaveBeenCalledTimes(350); }); Es('should initialize schema',asynchronous() => {untilDocuments = [ { Title:'trial term', Text:'test text', Location:'Test/Location', extra:'Feld', }, ];waitTestPipeline.withSubject(indexador).withDocuments(documents).execute();// The constructor reference must be set to location (and only once).Expect(lunrBuilderRefSpy).toHaveBeenCalledTimes(1); erwartet(lunrBuilderRefSpy).to have been last called with('Location');// The constructor fields must be based on the document fields.Expect(lunrBuilderFieldSpy).toHaveBeenCalledTimes(4); erwartet (lunrBuilderFieldSpy).toHaveBeenCalledWith('Title'); erwartet (lunrBuilderFieldSpy).toHaveBeenCalledWith('Text'); erwartet (lunrBuilderFieldSpy).toHaveBeenCalledWith('Location'); erwartet (lunrBuilderFieldSpy).toHaveBeenCalledWith('extra'); }); Es('should configure lunr pipe',asynchronous() => { expect(lunrBuilderSearchPipelineAddSpy).toHaveBeenLastCalledWith(lunr.votes, ); esperado (lunrBuilderPipelineAddSpy).toHaveBeenCalledWith( ...[lunr.trimmer, lunr.stopWordFilter, lunr.votes], ); });});
Example #11
source file:PonderadoPool.test.tsFrom balancer-v2-monorepo with GNU General Public License v3 | 5You | ![]() ![]() |
describe('Weighted pool',function(){permissionall tokens: list of tokens;untilMAX_TOKEN =20;untilPOOL_SWAP_FEE_PERCENTAGE = fp(0,01);untilWEIGHTS = range (1000,1000+ MAX_FICHA);// These are normalized to weights that are similar but differentshared before each ('provide tokens',asynchronous() => { all tiles =waitTokenList.create(MAX_TOKENS, {ordenado:TRUE, different decimals:TRUE}); }); itPaysProtocolFeesFromInvariantGrowth(WeightedPoolType.WEIGHTED_POOL); beschreiben('Weights and scale factors',()=>{for(untilnumTokens of range (2, MAX_TOKEN +1)) { context ("con${numTokens}Symbolic',()=>{permissionGroup: Weighted Group;permissionToken: List of Tokens; shared before each one ('implementation group',asynchronous() => {tokens = allTokens.subset(numTokens); Becken =waitWeightedPool.create({ PoolType: WeightedPoolType.WEIGHTED_POOL, Token, Gewichte: WEIGHTS.slice(0, numTokens), SwapFeePercentage: POOL_SWAP_FEE_PERCENTAGE, }); }); Es('set token weights',asynchronous() => {untilnormalized weights =waitpool.getNormalizedWeights(); Expect(normalizedWeights).to.deep.equal(pool.normalizedWeights); }); Es('set scale factors',asynchronous() => {untilpoolScalingFactors =waitpool.getScalingFactors();untiltokenScalingFactors = tokens.map((characters) =>fp(10** (18- token.decimales))); erwartet (poolScalingFactors).to.deep.equal(tokenScalingFactors); }); }); } });});
Example #12
source file:getFunctionStep.tsDe next-basics con GNU General Public License v3.0 | 5You | ![]() ![]() |
function getStageNodesAndEdges(functionLinksEdges: GraphEdge[], firstStepId:line, root id:line): [stageNodes:CollectNode[],stage edges:chart border[],stepDescendantsMap:Map<line,Prayer<line>>]{untilstepLevelMap =nuevocard<line,Number>();permissionnivelmax =0;untilstepDescendantsMap =nuevocard<line, set<line>>();untila pie = (ID:line, eben:Number, have offspring?: Set<Set<line>> ):Empty=>{And(Nivel > (stepLevelMap.get(id) ??-1)) {// Take the maximum level at each step.stepLevelMap.set(id, nivel); }And(nivel > maxLevel) {maxLevel = nivel; }permissionselfDesc = stepDescendantsMap.get(id);And(! autoDesc) { autoDesc =nuevoSatz(); stepDescendantsMap.set(id, selfDesc); }untilnewDescendantsCarry =nuevoSet (giving birth); newDescendantsCarry.add(selfDesc);for(untilat the edgefunctionLinksEdges){And(edge.font === id) {for(untildesc of newDescendantsCarry) { desc.add(edge.target); } walk(edge.target, Ebene +1, newDescendantsCarry); } } }; walk(firstStepId,0,nuevoPrayer());untilstageNodes: CollectNode[] = range(0, maxLevel +1).Map((level) =>({type:"Scenery", IDENTIFICATION:`Scenario.${level}`, }andCollectNode) );untilStageEdges: GraphEdge[] = stageNodes.map((nodes) =>( { source: rootId , destination: node.id ,type:"Capa", }));for(until[id, nivel] de stepLevelMap.entries()) {stageEdges.push({ fuente:`Scenario.${level}`, Target:ID,type:"Scenery", }); }go back[stageNodes, stageEdges, stepDescendantsMap];}
Example #13
source file:useBuilderGroupedChildNodes.spec.tsxCon next-core mit GNU General Public License v3.0 | 5You | ![]() ![]() |
// Given the tree:// - 1:// - toolbar:// - 2// - Content:// - 3// - Content// - 5// - <internal-template>// - 6// - Article// - 7// - 4(use BuilderDataandFun.MockedFunction<Kind ofuseBuilderData>).mockReturnValue({ rootId:1, node: area (1,8).Map(($$uid) =>({ $$uid, }andParcial<BuilderRuntimeNode>andBuilderRuntimeNode) ), borders: [ { parent:1, Gentle:2, mount point:"Toolbar", Sort by:0, }, {padre:1, Gentle:3, mount point:"Content", Sort by:1, }, {padre:1, Gentle:4, mount point:"Content", Sort by:2, }, {padre:3, Gentle:5, mount point:"Content", Sort by:0, }, {padre:5, Gentle:6, mount point:"<external>", Sort by:0, $$esTemplateInternal:TRUE, }, {padre:5, Gentle:7, mount point:"Article", Sort by:1, $$esTemplateDelegado:TRUE, }, ], wrapperNode: { $$uid:3, }andBuilderRuntimeNode,});
Example #14
source file:testUtils.tsFrom excalideck under MIT license | 5You | ![]() ![]() |
Export function hacerRandomExcalidrawElements(length = 10):ExcalidrawElemento[]{go backArea(0, Longitud).map(makeRandomExcalidrawElement);}
Example #15
source file:generate-auto-extractors.spec.tsBy js-client under MIT license | 5You | ![]() ![]() |
describe('generarAutoExtractores()',()=>{untilgenerarAutoExtractores = hacerGenerarAutoExtractores(TEST_BASE_API_CONTEXT);// Use a randomly generated tag so we know exactly what to queryuntilLabel = uuidv4();// The number of entries to generateuntilcount =1000;// The start date of the generated queriesuntilbeginning =nuevo Given(2010,0,0);// The end date of the generated queries; one minute between each entryuntilend = addMinutes(start, count -1);above all(asynchronous() => {// Generate and log some inputsuntilingestJSONEntries = makeIngestJSONEntries(TEST_BASE_API_CONTEXT);untilValues:Training<CreableJSONEntry> = Area(0, count).map(I=>{untiltimestamp = addMinutes(start, i).toISOString();go back{timestamp, day, dates:JSON.stringify({ timestamp, value: i },Null,2),// Add vertical spaces so that JSON is recommended over CSV};});waitingestJSONEntries(values);// Check the list of tags until our new tag appearsuntilgetAllTags = makeGetAllTags(TEST_BASE_API_CONTEXT);while(!(waitgetAllTags()).includes(tag)) {// Give the backend a moment to catch upwaitsleep(1000);}},25000);Es('Should generate automatic extractors',integration test(asynchronous() => {untilSubscribeToOneSearch = makeSubscribeToOneSearch(TEST_BASE_API_CONTEXT);untilquery =`label=${tag}limit 10';untilsearch =waitSubscribeToOneSearch(query, {filter: {date range: {start, end} } });untilentries =waitlastValueFrom(find.inputs$.pipe(map(mi=>miandRawSearchEntries),takeWhile(mi=>!e.done,TRUE),),);untilBrowseResults =waitgenerateAutoExtractors({label, entries});wait(Object.keys(browse results).length).withContext('we should get >0 AX suggestions').toBeMayorThan(0);wait(exploreResults['json']).conContexto('We should have a JSON AX proposal').toBeDefined();wait(exploreResults['json'].Long).withContext('We should have >0 JSON AX suggestions').toBeMayorThan(0);Explore results['json'].for each(Axe=>{esperar(ax.autoExtractor.tag).withContext('the suggested AX label must match the supplied label').toEqual(label);wait(ax.autoExtractor.module).withContext('suggested AX module should be json').equal('json');wait(ax.trust).withContext('json is the correct module, so its confidence should be 10').equal(10);wait(ax.autoExtractor.parameters).withContext('the proposed AX module should break down the fields in the inputs').equal('timestamp value');esperar(ax.explorerEntries.length).withContext('Explore should have >0 items').toBeMayorThan(0);ax.explorerEntries.forEach(explore entrance=>{wait(scanInput.elements.length).withContext('Explore should have two elements: one for each field (timestamp and value)').equal(2);exploreEntry.elements.forEach(elt=>{ expect (the.filter.length).withContext("We should have filters for browse items").toBeMayorThan(0);});});});// We can't really tell what the other AX generators will do by looking at the JSON data}),25000,);});
Example #16
source file:DebugEvents.tsxBy Jitsu under MIT license | 5You | ![]() ![]() |
debug events =({ handleClick }: Accessories) =>{untilDienste = ApplicationServices.get()until{Data: eventData, isLoading } = useLoaderAsObject(asynchronous() =>waitservicios.backendApiClient.get(`/events/cache?project_id=${services.activeproject.id}&limit=10`, {Attorney:TRUE, }) )untilallEvents = useMemo(()=>{untilevents = event data?.events ?? []And(Events.Duration >100) events.length =100 go backEvents .map(Fall=>({Data: Fall,Time: time(event.original._timestamp), })) .sort((e1: evento, e2: evento) =>{And(e1.time.isAfter(e2.time)) {go back -1}Anders And(e2.time.isAfter(e1.time)) {go back 1}go back 0}) }, [event data?.events])go back( <Card bordered={false} className={`${styles.events}`}> {isLoading ? ( <List dataSource={range(0, 25)} renderItem={() => ( <Skeleton active title= {falso} párrafo = {{ filas: 2, ancho: ["100%", "70%"] }} className="mb-2" /> )} /> ): ( <List className={`h- full w-full overflow-y-auto overflow-x-hidden ${styles.withSmallScrollbar}`} dataSource={allEvents} renderItem={(item: any) => { return ( <div className={`flex flex-col items-stretch ${styles.eventItem}`} onClick={handleClick(item?.data.original)} > <p className="truncate mb-0">{item?.time?.utc?.()?. formato?.()}</p> {elemento?.datos?.original?.tipo_evento? ( <p className="truncate mb-0">{elemento?.datos?.original?.tipo_evento}</p> ) : ( "" )} </div> ) }} /> )} </Carta> )}
Example #17
source file:max-por.spec.tsFrom s-libs under the MIT license | 5You | ![]() ![]() |
describe('maxBy()',()=>{Es('can sort by any primitive',()=>{ wait (maxBy([0,1,-1], identity)).toBe(1); wait(maxBy([INCORRECT,TRUE,INCORRECT], identity)).toBe(TRUE); wait(maxBy(['B','C','A'], identity)).toBe('C'); });// // Stolen from https://github.com/lodash/lodash //Es('should return correct iterated arguments',()=>{untilSpy = jasmine.createSpy(); maxPor([1,2,3], spy); expected(spy.calls.first().args).toEqual([1]); }); Es('should treat sparse matrices as dense',()=>{untilmatrix = [1]; Training[2] =3;untilspy = jasmine.createSpy().and.returnValue(TRUE); maxBy (matriz, spion); ExpectCallsAndReset(Spion, [1], [not defined], [3]); }); Es('must not iterate custom properties of arrays',()=>{untilmatrix = [1]; (Filaand any).a =1;untilSpion = jazmín.createSpy(); maxBy (matriz, spion); ExpectCallsAndReset(Spion, [1]); }); Es('should ignore changes to `length`',()=>{untilmatrix = [1];untilspy = jasmine.createSpy().and.callFake(()=>{ array.push(2);go back TRUE; }); maxBy(array, spy); Expected(spy).toHaveBeenCalledTimes(1); }); Es('should work with extremely large arrays',()=>{ wait(maxBy(range(0,5e5), identity)).toBe(499999); }); Es('should work with a 'repeat infringer',()=>{ wait (maxBy([1,2,3],(n) =>-n)).toBe(1); }); Es('should work if 'iteratee' returns +/-Infinity',()=>{untilWert = -plenty;untilobject = {a: value};untilcurrent = maxBy([object, {a: value}],(obj: { a:Number}) =>obj.a); wait (actually). be (object); });});
Example #18
source file:blackboard.tsBy panvala with Apache 2.0 license | 4You | ![]() ![]() |
/** * Read information from blockchain whiteboard, IPFS and local database */asynchronous function getAllSlates(){// Get an interface to Gatekeeper, ParameterStore contracts until{ Provider, Keeper, Parameter Store } =waitgetContracts();// Get the slate staking requirement untilparticipation required =waitstoreparameter.functions.get('amountshareboard');// Get the number of panels available untilblackboardCount =waitporter.functions.slateCount();console.Protocol(`search${blackboard counter}Board');untilcurrent season =waitgatekeeper.functions.currentEpochNumber();console.Protocol('current season:', current season);permissionIncumbent Grants, Incumbent Governance:line|not defined;And(keeper.functions.hasOwnProperty('Official')) { [Incumbent Grants, Incumbent Governance] =wait Promise.all([gatekeeper.functions.incumbent(tokenCapacitorAddress), gatekeeper.functions.incumbent(parameterStore.address), ]); }// 0..blackboardcounter untilslateIDs = range (0, slateCount.toNumber());console.Protocol('Board ID', Board ID);// TEMPORARY HACK permissionslateIDsToQuery = slateIDs;untilred =waitprovider.getNetwork();And(red.chainId ===4&& porter.address ==='0xe944C83D35B404610a82166c23B17F33d6399343') {untiltrash = [0,1,2,3,5];untilfiltering = slateIDs.filter(ID=>!garbage.includes(id)); slateIDsToQuery = gefiltert; }untilblackboard =waitBluebird.map( slateIDsToQuery,asynchronous(board id, index) => {And(Index! ==0)waitbluebird.delay(1000);// console.log('IDPizarra:', IDPizarra); untilblackboard =waitgatekeeper.slates (slateID);// const dbSlate = wait Request.findOrCreate({ where: {} }); // decrypt hash untildecodificador = toUtf8String (slate.metadataHash);// console.log('hash decodificado', decodificado); permissiontitular =INCORRECT;And(slate.recommender === GrantsIncumbent && slate.resource === tokenCapacitorAddress) { Titular =TRUE; }Anders And( slate.recommender === GovernanceIncumbent && slate.resource === ParameterStore.address ) { Titular =TRUE; }// Manual rejection criteria: // (1) from the previous time, (2) not accepted, (3) without contest || the competition ended And(BN(slate.epochNumber).lt(época actual)) {// No stacking And(blackboard.state ===0) { whiteboard.state =3; }// staked And(blackboard.state ===1) {untilCompetitive state =waitgatekeeper.contestStatus(slate.epochNumber, slate.resource);untilcompetition board =waitgatekeeper.contestSlates(slate.epochNumber, slate.resource);// No competition || the competition ended And(competition status! ==2&& contestBoards.length >1) { whiteboard.state =3; } } }go backgetSlateWithMetadata(slateID, slate, decoded, holder, participation required); }, { concurrency:5});go backBoard;}
Example #19
source file:index.tsxFrom the Prism frontend under the MIT license | 4You | ![]() ![]() |
function Analyzer({ Scope, Classes }: AnalyzerProps){untilDispatch = useDispatch();untilmap = useSelector(mapSelector);untilcapasSeleccionadas = useSelector(capasSelector);until{ updateHistory, removeKeyFromUrl, resetAnalysisParams, updateAnalysisParams, getAnalysisParams,} = useUrlHistory();untilavailable dates = useSelector(available dates selector);untilanalysisResult = useSelector(analysisResultSelector);untilisAnalysisLoading = useSelector(isAnalysisLoadingSelector);untilisMapLayerActive = useSelector(isAnalysisLayerActiveSelector);until{AnalyseHazardLayerId: HazardLayerIdFromUrl,analysisBaselineLayerId: baselineLayerIdFromUrl,Date of analysis: dateSelectedFromUrl,Analytics Statistics:SelectedStatisticOfUrl,UmbralArriba analysis: above the URL threshold,below threshold analysis: below the URL threshold,Analyze administrator level: adminLevelFromUrl,Analysis start date: start date selected from URL,Analysis end date: fechaFinalSeleccionadaDeUrl, } = getAnalysisParams();// form elements until[hazardLayerId, setHazardLayerId] = useState<LayerKey |not defined>( peligroLayerIdFromUrl, );until[Statistik, setStatistic] = useState( (s selectedStatisticFromUrlandAggregation Operationsen) || Aggregation operations. Half, );until[baselineLayerId, setBaselineLayerId] = useState<LayerKey |not defined>(base de referenciaLayerIdFromUrl,);until[SelectedDate, setSelectedDate] = useState<number |Null>(Null);until[below threshold, set below threshold] = useState(below threshold url ||'', );until[aboveThreshold, setAboveThreshold] = useState( aboveThresholdFromUrl ||'', );until[thresholdError, setThresholdError] = useState<cadena |Null>(Null);until[isAnalyserFormOpen, setIsAnalyserFormOpen] = useState<booleano>(hazardLayerIdFromUrl!==not defined, );until[istTableViewOpen, setIsTableViewOpen] = useState(TRUE);// for polygon intersection analysis until[AdminLevel, setAdminLevel] = useState<AdminLevelType>(Number(adminLevelFromUrl ||'1')andAdminLevelType, );until[startDate, setStartDate] = useState<number |Null>(Null);until[endDate, setEndDate] = useState<número |Null>(Null);// Find the layer for the given adminLevel untilAdminLevelLayer = getAdminLevelLayer(AdminLevel);untiladminLevelLayerData = useSelector(// If we couldn't find a management layer, just return undefinedAdminLevelLayer? capaDataSelector(adminLevelLayer.id) :()=> not defined, )andLayerData<BoundaryLayerProps> |not defined;// get variables derived from state untilseleccionadoHazardLayer = HazardLayerId ? (LayerDefinitions[hazardLayerId]andWMSLayerProps):Null;untilHazard Data Type: Hazard Data Type |Null= hazard layer selected? selectedHazardLayer.geometry || RasterType.Raster :Null;untilavailableHazardDates = selectedHazardLayer ? getPossibleDatesForLayer(selected hazard layer, available dates)?.map(D=> nuevo Given(d), ) || [] :not defined;untilBASELINE_URL_LAYER_KEY ='baselineLayerId';untilpreSelectedBaselineLayer = capasseleccionadas.find(yo=>l.type ==='admin_level_data', );until[vorherigeBaselineId, setPreviousBaselineId] = useState< LayerKey |not defined>(preselected base layer?.id);until{ t } = useSecureTranslation();// Check if there is a date available in the URL; otherwise, use the latest available date for the selected danger level untillastAvailableHazardDate = availableHazardDates ? getDateFromList(seleccionadoDateFromUrl?nuevo Given(SelectedDateFromUrl) :Null, danger dates available, )?.getTime() ||Null:Null;untillastAvailableHazardStartDate = availableHazardDates ? getDateFromList(seleccionadoStartDateFromUrl?nuevo Given(selected StartDateFromUrl):Null, danger dates available, )?.getTime() ||Null:Null;untillastAvailableHazardEndDate = availableHazardDates ? getDateFromList(seleccionadoEndDateFromUrl?nuevo Given(selectedEndDateFromUrl) :Null, danger dates available, )?.getTime() ||Null:Null;until{ translateColumns } = useAnalysisTableColumns(analysisResult);// Set the default date after the data is loaded and when the hazard layer changesuseEffect(()=>{And(isNil(last available danger date)) { setSelectedDate(Null); }Anders{ setSelectedDate(últimoAvailableHazardDate); }And(isNil(ultimate date of start of danger available)) { setStartDate(Null); }Anders{setStartDate(ultimate date of the beginning of the danger available); }And(isNil(last available danger end date)) { set end date (Null); }Anders{setEndDate(últimoAvailableHazardEndDate); } }, [ availableDates, hazardLayerId, lastAvailableHazardDate, lastAvailableHazardStartDate, lastAvailableHazardEndDate, ]);untilonOptionChange = <T erweitert string>( setterFunc: Dispatch<SetStateAction<T>>, ) => (event: React.ChangeEvent<HTMLInputElement>) => {const value = event.target.value as T; setterFunc(Wert); Rückgabewert; }; // führt speziell für Schwellenwerte auch eine Fehlerprüfung durch const onThresholdOptionChange = (thresholdType: 'above' | 'below') => ( event: React.ChangeEvent<HTMLInputElement>, ) => { const setterFunc = thresholdType === 'above ' ? setAboveThreshold : setBelowThreshold; const changeOption = onOptionChange(setterFunc)(event); // Das Setzen eines Wertes aktualisiert den vorhandenen Wert bis zum nächsten Rendern nicht, daher müssen wir hier entscheiden, ob wir auf den alten oder den neu geänderten Wert zugreifen. const aboveThresholdValue = parseFloat( Schwellentyp === 'oben' ? geänderteOption : aboveThreshold, ); const belowThresholdValue = parseFloat( Schwellentyp === 'unten' ? geänderteOption : belowThreshold, ); if (belowThresholdValue > aboveThresholdValue) { setThresholdError('Der untere Schwellenwert ist größer als der obere Schwellenwert!'); } sonst { setThresholdError (null); } }; const statisticOptions = Object.entries(AggregationOperations) .filter(([, value]) => value !== AggregationOperations.Sum) // Die Summe wird nur für die Expositionsanalyse verwendet. .map(([Schlüssel, Wert]) => ( <FormControlLabel key={key} value={value} control={ <Radio className={classes.radioOptions} color="default" size="small" /> } label={t(key)} /> )); const activateUniqueBoundary = (forceAdminLevel?: BoundaryLayerProps) => { if (forceAdminLevel) { // Angezeigte Grenzen entfernen getDisplayBoundaryLayers().forEach(l => { if (l.id !== forceAdminLevel.id) { safeDispatchRemoveLayer(map, l , versenden); } }); safeDispatchAddLayer( map, { ...forceAdminLevel, isPrimary: true }, dispatch, ); zurückkehren; } if (!baselineLayerId) { throw new Error('Layer sollte ausgewählt werden, um die Analyse auszuführen'); } const baselineLayer = LayerDefinitions[ baselineLayerId ] as AdminLevelDataLayerProps; if (baselineLayer.boundary) {const borderLayer = LayerDefinitions[baselineLayer.boundary] as BoundaryLayerProps; // Angezeigte Grenzen entfernen getDisplayBoundaryLayers().forEach(l => { if (l.id !== borderLayer.id) { safeDispatchRemoveLayer(map, l, dispatch); } }); safeDispatchAddLayer( map, { ...boundaryLayer, isPrimary: true }, dispatch, ); } else { getDisplayBoundaryLayers().forEach(l => { safeDispatchAddLayer(map, l, dispatch); }); } }; const deactivateUniqueBoundary = () => { if (!baselineLayerId) { throw new Error('Layer must be selected to run analysis'); } const baselineLayer = LayerDefinitions[ baselineLayerId ] as AdminLevelDataLayerProps; if (baselineLayer.boundary) {const borderLayer = LayerDefinitions[baselineLayer.boundary] as BoundaryLayerProps; if (!getDisplayBoundaryLayers().includes(boundaryLayer)) { safeDispatchRemoveLayer(Karte, BoundaryLayer, Dispatch); } } getDisplayBoundaryLayers().forEach(l => { safeDispatchAddLayer(map, l, dispatch); }); }; const clearAnalysis = () => {dispatch(clearAnalysisResult()); resetAnalysisParams(); if (vorherigeBaselineId) { const previousBaseline = LayerDefinitions[ previousBaselineId ] as AdminLevelDataLayerProps; updateHistory(BASELINE_URL_LAYER_KEY, previousBaselineId); safeDispatchAddLayer(Karte, vorherigeBaseline, Versand); // isMapLayerActive bei Analyse prüfen clear // um Fehlerverhalten bei Grenzschichten zu vermeiden dispatch(setIsMapLayerActive(true)); } }; const shareAnalysis = () => { copyTextToClipboard(window.location.href).then(() => { dispatch( addNotification({ message: 'Link to this analysis copyed to clipboard!', type: 'success', }) , ); }); }; const onMapSwitchChange = (e: ChangeEvent<HTMLInputElement>) => {dispatch(setIsMapLayerActive(e.target.checked)); // Die Gefahrenebene benötigt keine Anzeigegrenze, // da sie bereits ein Vektor ist if (hazardDataType === GeometryType.Polygon) { return; } if (isMapLayerActive) {deactivateUniqueBoundary(); // Auf vorherige Baseline prüfen und zurückbringen if ( previousBaselineId ) { const previousBaseline = LayerDefinitions[ previousBaselineId ] as AdminLevelDataLayerProps; updateHistory(BASELINE_URL_LAYER_KEY, previousBaselineId); safeDispatchAddLayer(Karte, vorherigeBaseline, Versand); } } else { // auf vorherige Baseline prüfen und diese entfernen, bevor... if ( previousBaselineId ) { const previousBaseline = LayerDefinitions[ previousBaselineId ] as AdminLevelDataLayerProps; removeKeyFromUrl(BASELINE_URL_LAYER_KEY); safeDispatchRemoveLayer(Karte, vorherigeBaseline, Versand); } // Aktivieren der eindeutigen Grenzschicht activateUniqueBoundary(); } }; const runAnalyser = async () => {if (preSelectedBaselineLayer) {setPreviousBaselineId(preSelectedBaselineLayer.id); removeKeyFromUrl(BASELINE_URL_LAYER_KEY); // Kein sicheres Versenden erforderlich remove Wir sind sicher, dass dispatch(removeLayer(preSelectedBaselineLayer)); } if (analysisResult) {clearAnalysis(); } if (! Umfang) { return; } // wurde noch nicht berechnet if (!s selectedHazardLayer) { throw new Error('Hazard layer should be selected to run analysis'); } if (hazardDataType === GeometryType.Polygon) { if (!startDate) { throw new Error('Datumsbereich muss angegeben werden, um Analyse auszuführen'); } if (!endDate) { throw new Error('Datumsbereich muss angegeben werden, um Analyse auszuführen'); } if (!adminLevelLayer || !adminLevelLayerData) { // technisch können wir hier nicht hinkommen, weil die Schaltfläche "Analyse ausführen" // deaktiviert ist, während die Daten auf Admin-Ebene geladen werden // aber wir müssen dies einfügen, damit der Typescript-Compiler // löst keinen Fehler aus, wenn wir versuchen, auf die Daten // Eigenschaft von adminLevelLayerData zuzugreifen throw new Error('Daten auf Admin-Ebene werden noch geladen'); } const params: PolygonAnalysisDispatchParams = { hazardLayer: selectedHazardLayer, adminLevel, adminLevelLayer, adminLevelData: adminLevelLayerData.data, startDate, endDate, expansion, }; activateUniqueBoundary(adminLevelLayer); // Verlauf aktualisieren updateAnalysisParams({ analysisHazardLayerId: hazardLayerId, analysisAdminLevel: adminLevel.toString(), analysisStartDate: moment(startDate).format(DEFAULT_DATE_FORMAT), analysisEndDate: moment(endDate).format(DEFAULT_DATE_FORMAT), analysisStatistic: statistic, }); Dispatch (requestAndStorePolygonAnalysis(params)); } else { if (!s selectedDate) { throw new Error('Datum muss angegeben werden, um Analyse auszuführen'); } if (!baselineLayerId) { throw new Error('Baseline-Layer sollte zum Ausführen der Analyse ausgewählt werden'); } const selectedBaselineLayer = LayerDefinitions[ baselineLayerId ] as AdminLevelDataLayerProps; activateUniqueBoundary(); const params: AnalysisDispatchParams = { hazardLayer: selectedHazardLayer, baselineLayer: selectedBaselineLayer, date: selectedDate, statistic, expansion, threshold: { above: parseFloat(aboveThreshold) || undefiniert, darunter: parseFloat(belowThreshold) || nicht definiert, }, }; // Verlauf aktualisieren updateAnalysisParams({ analysisHazardLayerId: hazardLayerId, analysisBaselineLayerId: baselineLayerId, analysisDate: moment(s selectedDate).format(DEFAULT_DATE_FORMAT), analysisStatistic: statistic, analysisThresholdAbove: aboveThreshold || undefined, analysisThresholdBelow: belowThreshold || undefined, }); Dispatch (requestAndStoreAnalysis(params)); } }; return ( <div className={classes.analyser}> <Button variation="contained" color="primary" onClick={() => { setIsAnalyserFormOpen(!isAnalyserFormOpen); }} > <BarChart fontSize="small" /> <Typografievariante="body2" className={classes.analyserLabel}> {t('Run Analysis')} </Typography> <ArrowDropDown fontSize="small" /> </Button> <Box className={classes.analyserMenu} width={isAnalyserFormOpen ? 'min-content' : 0} padding={isAnalyserFormOpen ? '10px' : 0} > {isAnalyserFormOpen ? ( <div> <div className={classes.newAnalyserContainer}> <div className={classes.analyserOptions }> <Typografievariante="body2">{t('Hazard Layer')}</Typografie> <LayerDropdown type="wms" value={hazardLayerId} setValue={setHazardLayerId} className={classes.selector} placeholder=" Gefahrenebene wählen" /> </div> {hazardDataType === GeometryType.Polygon && ( <> <div className={classes.analyserOptions}> <Typography Variante="body2">Admin Level</Typography> <SimpleDropdown value= {adminLevel} options={range(getAdminLevelCount()).map(i => [ (i + 1) as AdminLevelType, `Admin ${i + 1}`, ])} onChange={setAdminLevel} /> </div > <div className={classes.analyserOptions}> <Typografievariante="body2">{t('Date Range')}</Typography> <div className={classes.dateRangePicker}> <Typografievariante="body2"> {t('Start')}</Typography> <DatePicker selected={startDate ? new Date(startDate) : null} onChange={date => setStartDate(date?.getTime() || startDate) } maxDate={new Date()} todayButton="Today" peekNextMonth showMonthDropdown showYearDropdown dropdownMode="select" customInput= {<Input />} popperClassName={classes.calendarPopper} includeDates={availableHazardDates} /> </div> <div className={classes.dateRangePicker}> <Typografievariante="body2">{t('End')} </Typografie> <DatePicker selected={endDate ? neues Datum(endDate) : null} onChange={date => setEndDate(date?.getTime() || endDate) } maxDate={new Date()} todayButton="Today" peekNextMonth showMonthDropdown showYearDropdown dropdownMode="select" customInput= {<Input />} popperClassName={classes.calendarPopper} includeDates={availableHazardDates} /> </div> </div> </> )} {hazardDataType === RasterType.Raster && ( <> <div className={ classes.analyserOptions}> <Typografievariante="body2">{t('Statistic')}</Typography> <FormControl component="div"> <RadioGroup name="statistics" value={statistic} onChange={onOptionChange( setStatistic)} row > {statisticOptions} </RadioGroup> </FormControl> </div> <div className={classes.analyserOptions}> <Typography Variante="body2"> {t('Baseline Layer')} </Typography > <LayerDropdown type="admin_level_data" value={baselineLayerId || undefined} setValue={setBaselineLayerId} className={classes.selector} placeholder="Choose baseline layer" /> </div> <div className={classes.analyserOptions} > <Typografievariante="body2">{t('Threshold')}</Typografie> <TextField id="filled-number" error={!!thresholdError} helperText={thresholdError} className={classes.numberField} label ={t('Below')} type="number" value={belowThreshold} onChange={onThresholdOptionChange('below')}variante="filled" /> <TextField id="filled-number" label={t( 'Above')} className={classes.numberField} value={aboveThreshold} onChange={onThresholdOptionChange('above')} type="number" variation="filled" /> </div> <div className={classes. analyserOptions}> <Typografievariante="body2">{t('Date')}</Typografie> <DatePicker locale={t('date_locale')} dateFormat="PP" selected={s selectedDate ? neues Datum(ausgewähltesDatum) : null} onChange={date => setSelectedDate(date?.getTime() || selectedDate) } maxDate={neues Datum()} todayButton={t('Today')} peekNextMonth showMonthDropdown showYearDropdown dropdownMode= "select" customInput={<Input />} popperClassName={classes.calendarPopper} includeDates={availableHazardDates} /> </div> </> )} </div> {!isAnalysisLoading && analysisResult && (analysisResult instanceof BaselineLayerResult || analysisResult instanceof PolygonAnalysisResult) && ( <> <FormGroup> <FormControlLabel control={ <Switch color="default" selected={isMapLayerActive} onChange={onMapSwitchChange} /> } label={t('Map View')} /> < FormControlLabel control={ <Switch color="default" selected={isTableViewOpen} onChange={e => setIsTableViewOpen(e.target.checked)} /> } label={t('Table View')} /> </FormGroup > {isTableViewOpen && ( <AnalysisTable tableData={analysisResult.tableData} column={translatedColumns} /> )} <Button className={classes.innerAnalysisButton} onClick={() => downloadCSVFromTableData( analysisResult, translateColumns, selectedDate, ) } > <Typografievariante="body2">{t('Download')}</Typografie> </Button> <Button className={classes.innerAnalysisButton} onClick={clearAnalysis} > <Typografievariante="body2"> {t( 'Clear Analysis')} </Typography> </Button> <Button className={classes.innerAnalysisButton} onClick={shareAnalysis} > <Typography Variante="body2"> {t('Share Analysis')} </Typography> </Button> </> )} {(!analysisResult || analysisResult instanceof ExposedPopulationResult) && ( <Button className={classes.innerAnalysisButton} onClick={runAnalyser} disabled={ !!thresholdError || // wenn ein Schwellenwertfehler vorliegt isAnalysisLoading || // oder die Analyse lädt gerade !hazardLayerId || // oder Gefahrenebene wurde nicht ausgewählt (hazardDataType === GeometryType.Polygon ? !startDate || !endDate || !adminLevelLayerData : !s selectedDate || !baselineLayerId) // oder Datum wurde nicht ausgewählt // oder Baseline Ebene wurde nicht ausgewählt } > <Typografievariante="body2">{t('Run Analysis')}</Typography> </Button> )} {isAnalysisLoading ? <LinearProgress /> : null} </div> ) : null} </Box> </div> );}
Example #20
source file:Brush Selection SpecificationsFrom S2 licensed by MIT | 4You | ![]() ![]() |
describe('Interactive brush selection tests',()=>{permissionbrushSelectionInstance: BrushSelection;permissionmock spreadsheet instance: spreadsheet;permissionmockRootInteraction: RootInteraktion;untilstartBrushDataCellMeta: Parcial<ViewMeta> = { colIndex:0, line index:1, };untilendBrushDataCellMeta: Parcial<ViewMeta> = {colIndex:4, line index:3, };untilstartBrushDataCell =nuevoMockDataCell(); startBrushDataCell.getMeta =()=>startBrushDataCellMetaandVerMeta;untilendBrushDataCell =nuevoMockDataCell(); endBrushDataCell.getMeta =()=>endBrushDataCellMetaandVerMeta;untilpanelGroupAllDataCells =Training.von<Number[]>({ Length:4}) .fill(range(10)) .reduce<data cell[]>((arr, v, i) =>{ v.forEach((_,j) =>{untilcell = { cell type: cell types.DATA_CELL, getMeta() {go back{colIndex:j,row index:I, }and See Goal; }, }and data cell;Arr.press(Cellular); });go back Arr; }, []);until emitEvent= (type: S2Event, Evento: Parcial<OriginalEvent>) =>{ brushSelectionInstance.spreadsheet.emit (type, { Original Event: Event, PreventDefault() {}, }and any); };until emitGlobalEvent= (type: S2Event, Evento: Parcial<MouseEvent>) =>{ brushSelectionInstance.spreadsheet.emit (type, { ...Event, PreventDefault() {}, }and any); }; I like it(()=>{MockRootInteraction.mockClear(); mockSpreadSheetInstance =nuevodynamic sheet(document.createElement('div'),Null,Null, ); simulacroRootInteraction =nuevoMockRootInteraction (mockSpreadSheetInstance); mockSpreadSheetInstance.getCell = broma.fn(()=>startBrushDataCell)and any; mockSpreadSheetInstance.foregroundGroup =nuevoGroup(''); mockSpreadSheetInstance.showTooltipWithInfo = jest.fn(); mockRootInteraction.getPanelGroupAllDataCells =()=>PanelGroupAllDataCells; mockSpreadSheetInstance.interaction = mockRootInteraction; mockSpreadSheetInstance.render(); mockSpreadSheetInstance.facet.layoutResult.colLeafNodes =Training.outside(nuevo Training(10), ).Map((_,idx) =>{go back{ colIndex: idx, id: idx, x: idx *100, Broad:100, }; })andA stranger[]andNudo[]; mockSpreadSheetInstance.facet.layoutResult.rowLeafNodes =Training.outside(nuevo Training(10), ).Map((_,idx) =>{go back{ queue index: idx, id: idx, y: idx *100, Height:100, }; })andA stranger[]andNodo[]; mockSpreadSheetInstance.facet.getCellRange=()=>{go back{ Begin:0, Fin:9, }; }; brushSelectionInstance =nuevoBrushSelection(mockSpreadSheetInstance); brushSelectionInstance.brushSelectionStage = InteracciónBrushSelectionStage.UN_DRAGGED; brushSelectionInstance.hidePrepareSelectMaskShape = jest.fn(); }); prüfen('should log events',()=>{ esperar (brushSelectionInstance.bindEvents).toBeDefined(); }); prueba('prepare mask shape should not be made invisible after rendering',()=>{ expect (brushSelectionInstance.prepareSelectMaskShape).not.toBeDefined(); }); prueba('the brush selection phase should start',()=>{ esperar (brushSelectionInstance.brushSelectionStage).toEqual( InteractionBrushSelectionStage.UN_DRAGGED, ); }); prueba('should make the selection mask shape invisible after mouse click on the data cell',()=>{ emitEvent(S2Event.DATA_CELL_MOUSE_DOWN, {layerX:10, CapaY:20, }); expect (brushSelectionInstance.prepareSelectMaskShape).toBeDefined(); expect( brushSelectionInstance.prepareSelectMaskShape.attr('visible'), ).toBeFalsy(); }); proof('should get initial brush point when mouse button is down',()=>{ emitEvent(S2Event.DATA_CELL_MOUSE_DOWN, {layerX:10, CapaY:20, }); erwarten (brushSelectionInstance.spreadsheet.getCell).toHaveBeenCalled(); erwartet(brushSelectionInstance.startBrushPoint).toStrictEqual({ x:10, y:20, scrollX:0, scroll Y:0, line index:1, col index:0, }); Expect(brushSelectionInstance.displayedDataCells).toEqual(panelGroupAllDataCells, ); }); prueba('should ignore brush selection when mouse is not dragged',()=>{ emitEvent(S2Event.DATA_CELL_MOUSE_DOWN, {layerX:10, CapaY:20, }); emitGlobalEvent(S2Event.GLOBAL_MOUSE_MOVE, { clienteX:12, client Y:22, }); emitEvent(S2Event.GLOBAL_MOUSE_UP, {}); Expect(brushSelectionInstance.brushSelectionStage).toEqual( InteractionBrushSelectionStage.UN_DRAGGED, ); erwarten (brushSelectionInstance.spreadsheet.interaction.hasIntercepts([InterceptType.BRUSH_SELECTION, ]),).toBeFalsy();// If the brush selection distance is too short, follow the single selection logic and you should hide the brush selection prompt boxerwarten (brushSelectionInstance.hidePrepareSelectMaskShape,).toHaveBeenCalled(); });// https://github.com/antvis/S2/issues/852proof('should clear the brush selection state when the mouse button is pressed and the context menu is clicked',()=>{untilglobalMouseUp = broma.fn(); mockSpreadSheetInstance.on(S2Event.GLOBAL_MOUSE_UP, globalMouseUp); emitEvent(S2Event.DATA_CELL_MOUSE_DOWN, {layerX:10, CapaY:20, }); emitGlobalEvent(S2Event.GLOBAL_MOUSE_MOVE, { clienteX:12, client Y:22, }); Expect(instanciaSelecciónBrocha.EtapaSelecciónBrocha).toEqual( InteracciónEtapaSelecciónBrocha.ARRASTRADA, ); emitEvent(S2Event.GLOBAL_CONTEXT_MENU, {}); Expect(globalMouseUp).not.toHaveBeenCalled(); Expect(brushSelectionInstance.brushSelectionStage).toEqual( InteractionBrushSelectionStage.UN_DRAGGED, ); erwarten (brushSelectionInstance.spreadsheet.interaction.hasIntercepts([InterceptType.HOVER, ]),).toBeFalsy(); erwarten (brushSelectionInstance.spreadsheet.interaction.hasIntercepts([InterceptType.BRUSH_SELECTION, ]),).toBeFalsy(); erwartet (brushSelectionInstance.hidePrepareSelectMaskShape, ).toHaveReturnedTimes(1); }); proof('should ignore brush selection if mouse moves less than valid',()=>{ emitEvent(S2Event.GLOBAL_MOUSE_MOVE, {}); Expect(brushSelectionInstance.brushSelectionStage).toEqual( InteractionBrushSelectionStage.UN_DRAGGED, ); Expect(brushSelectionInstance.endBrushPoint).not.toBeDefined(); erwartet (brushSelectionInstance.brushRangeDataCells).toHaveLength(0); expect (brushSelectionInstance.spreadsheet.interaction.hasIntercepts([InterceptType.HOVER, ]),).toBeFalsy(); }); prueba('should get brush selection area cells',()=>{untilselectedFn = is.fn();untilbrushSelectionFn = is.fn(); mockSpreadSheetInstance.getCell = is.fn(()=>startBrushDataCell)and any; mockSpreadSheetInstance.on (S2Event.GLOBAL_SELECTED, selectedFn); mockSpreadSheetInstance.on (S2Event.DATE_CELL_BRUSH_SELECTION, brushSelectionFn, );// ================== Mouse Down ==================emitEvent(S2Event.DATA_CELL_MOUSE_DOWN, {layerX:10, CapaY:20}); mockSpreadSheetInstance.getCell = broma.fn(()=>endBrushDataCell)and any;// =================== Mouse movement ===================emitGlobalEvent(S2Event.GLOBAL_MOUSE_MOVE, { clienteX:100, client Y:200, }); Expect(BrushSelectioninstance.BrushSelectionStage).toEqual(BrushSelectionStageInteraction.DRAG, );// Get the end point of the brushesperado(brushSelectionInstance.endBrushPoint).toEqual({ ...endBrushDataCellMeta, x:100, y:200, });// Show preliminary brush selection maskerwartet (brushSelectionInstance.prepareSelectMaskShape.attr()).toMatchObject({ x:10, y:20, Broad:90, Height:180, });// ================== Mouse Up ==================emitEvent(S2Event.GLOBAL_MOUSE_UP, {});// Hide preparation maskerwarten ( brushSelectionInstance.prepareSelectMaskShape.attr ('visible'), ).toBeFalsy();// Show tooltiperwartet (mockSpreadSheetInstance.showTooltipWithInfo).toHaveBeenCalled();// Reset brush levelExpect(brushSelectionInstance.brushSelectionStage).toEqual( InteractionBrushSelectionStage.UN_DRAGGED, );// Get selected cells from the brush areaesperado (brushSelectionInstance.brushRangeDataCells).toHaveLength(15); brushSelectionInstance.brushRangeDataCells.forEach((cell) =>{until{rowIndex, colIndex} = celda.getMeta(); Expect(rowIndex).toBeLessThanOrEqual(endBrushDataCellMeta.rowIndex); Expect(rowIndex).toBeGreaterThanOrEqual(startBrushDataCellMeta.rowIndex); Expect(colIndex).toBeLessThanOrEqual(endBrushDataCellMeta.colIndex); Expect(colIndex).toBeGreaterThanOrEqual(startBrushDataCellMeta.colIndex); });// exit eventexpect(selectedFn).toHaveBeenCalledTimes(1); expect(brushSelectionFn).toHaveBeenCalledTimes(1); }); proof('should get the correctly formatted brush point',()=>{untilEXTRA_PIXEL =2;untilVSCROLLBAR_WIDTH =5;until{ancho, alto} = mockSpreadSheetInstance.facet.getCanvasHW();untilminX =10;untilminY =10;untilmaxY = height +10;untilmaxX = ancho +10; mockSpreadSheetInstance.facet.panelBBox = { minX, minY, maxY, maxX, }and any; brushSelectionInstance.endBrushPoint = { x: maxX -10, y: maxY -10, scrollX:0, col index:0, line index:0, }; mockSpreadSheetInstance.facet.vScrollBar = {getBBox:()=>({ ancho: VSCROLLBAR_WIDTH, }and any), }and any;permissionresultado = brushSelectionInstance.formatBrushPointForScroll({ x:20, y:20, }); expected(Result).toStrictEqual({ x: { needScroll:TRUE, Wert: maxX - VSCROLLBAR_WIDTH - EXTRA_PIXEL, }, y: {needScroll:TRUE, Wert: maxY - EXTRA_PIXEL, }, }); brushSelectionInstance.endBrushPoint = { x: maxX -10, y: maxY -10, scrollX:0, col index:0, line index:0, }; resultado = brushSelectionInstance.formatBrushPointForScroll({ x:1, y:1, }); expected(Result).toStrictEqual({ x: { needScroll:INCORRECT, Valor: maxX -10+1, }, y: {needsOffset:INCORRECT, Value: maxY -10+1, }, }); brushSelectionInstance.endBrushPoint = { x: minX +10, y: minY +10, scrollX:0, col index:0, line index:0, }; resultado = brushSelectionInstance.formatBrushPointForScroll({ x:-20, y:-20, }); expected(Result).toStrictEqual({ x: { needScroll:TRUE, Wert: minX + EXTRA_PIXEL, }, y: {needScroll:TRUE, value: minY + EXTRA_PIXEL, }, }); }); proof('should get correct selected cell goals',()=>{ erwarten ( brushSelectionInstance.getSelectedCellMetas ({ inicio: { colIndex:0, line index:0, }, End: { colIndex:9, line index:9, }, }and any).largo, ).toBe(100); }); proof('should get the frozen row index and column index correctly set',()=>{until{ajustarNextColIndexWithFrozen, ajustarNextRowIndexWithFrozen} = brushSelectionInstance; mockSpreadSheetInstance.setOptions({frozenColCount:1, number of frozen rows:1, congeladoTrailingColCount:1, congeladoTrailingRowCount:1, }); mockSpreadSheetInstance.dataSet.getDisplayDataSet =()=>{go back Training.outside(nuevo Training(10)).Map(()=>{go back{}; }); }; (mockSpreadSheetInstance.facetandTableFacet).panelScrollGroupIndexes = [1,8,1,8, ]; expected (setNextColIndexWithFrozen(9, ScrollDirection.TRAILING)).toBe(8); expected (setNextColIndexWithFrozen(0, ScrollDirection.LEADING)).toBe(1); expected (setNextColIndexWithFrozen(7, ScrollDirection.TRAILING)).toBe(7); expected (setNextRowIndexWithFrozen(9, ScrollDirection.TRAILING)).toBe(8); expected (setNextRowIndexWithFrozen(0, ScrollDirection.LEADING)).toBe(1); expected (setNextRowIndexWithFrozen(7, ScrollDirection.TRAILING)).toBe(7); }); proof('should get the correct scroll offset for the row and column',()=>{until{ faceta } = mockSpreadSheetInstance; esperar ( getScrollOffsetForCol (7, ScrollDirection.LEADING, mockSpreadSheetInstance, ), ).toBe(700); wait( getScrollOffsetForCol(7, ScrollDirection.TRAILING, mockSpreadSheetInstance, ), ).toBe(200); (FacetandTableFacet).frozenGroupInfo = { [FrozenGroup.FROZEN_COL]: { Breite:100, }, [FrozenGroup.FROZEN_TRAILING_COL]: { Breite:100, }, [FrozenGroup.FROZEN_ROW]: { Aquí:0, }, [FrozenGroup.FROZEN_TRAILING_ROW]: { Aquí:0, }, }; wait( getScrollOffsetForCol(7, ScrollDirection.LEADING, mockSpreadSheetInstance, ), ).toBe(600); wait( getScrollOffsetForCol(7, ScrollDirection.TRAILING, mockSpreadSheetInstance, ), ).toBe(300); facet.panelBBox = { height: facet.getCanvasHW().height, }and any; faceta.viewCellHeights = faceta.getViewCellHeights (faceta.layoutResult); esperar ( getScrollOffsetForRow (7, ScrollDirection.LEADING, mockSpreadSheetInstance, ), ).toBe(700); esperar ( getScrollOffsetForRow (7, ScrollDirection.TRAILING, mockSpreadSheetInstance, ), ).toBe(320); (FacetandTableFacet).frozenGroupInfo = { [FrozenGroup.FROZEN_COL]: { Breite:0, }, [FrozenGroup.FROZEN_TRAILING_COL]: { Breite:0, }, [FrozenGroup.FROZEN_ROW]: { Aquí:100, }, [FrozenGroup.FROZEN_TRAILING_ROW]: { Aquí:100, }, }; esperar ( getScrollOffsetForRow (7, ScrollDirection.LEADING, mockSpreadSheetInstance, ), ).toBe(600); esperar ( getScrollOffsetForRow (7, ScrollDirection.TRAILING, mockSpreadSheetInstance, ), ).toBe(420); }); proof('should get a valid x and y index',()=>{until{ validarXIndex, validarYIndex } = brushSelectionInstance; esperar(validarXIndex(-1)).to be(Null); wait(validateXIndex(1)).to be(1); wait(validateXIndex(10)).to be(Null); wait(validateXIndex(9)).to be(9); wait(validateIndexY(-1)).to be(Null); wait(validateIndexY(1)).to be(1); wait(validateIndexY(10)).to be(Null); wait(validateIndexY(9)).to be(9); (mockSpreadSheetInstance.facetandTableFacet).frozenGroupInfo = { [FrozenGroup.FROZEN_COL]: { Área: [0,1], }, [FrozenGroup.FROZEN_TRAILING_COL]: { Rango: [8,9], }, [FrozenGroup.FROZEN_ROW]: { rango: [0,1], }, [FrozenGroup.FROZEN_TRAILING_ROW]: { Tipo: [8,9], }, }; wait(validateXIndex(1)).to be(Null); wait(validateXIndex(2)).to be(2); wait(validateXIndex(8)).to be(Null); wait(validateXIndex(7)).to be(7); wait(validateXIndex(1)).to be(Null); wait(validateXIndex(2)).to be(2); wait(validateXIndex(8)).to be(Null); wait(validateXIndex(7)).to be(7); });});
Example #21
source file:ElasticSearchSearchEngineIndexer.test.tsBackstage licensed Apache 2.0 | 4You | ![]() ![]() |
describe('ElasticSearchSearchEngineIndexer',()=>{permissionIndexador: ElasticSearchSearchEngineIndexer;permissionbulkSpy: es.Mock;permissioncatSpy: es.Mock;permissioncreateSpy: es.Mock;permissionaliasSpy: is.Mock;permissiondeleteSpy: es.Mock; vorjeed(()=>{// Create an instance of the indexer to test.indexer =nuevoElasticSearchSearchEngineIndexer({type:'some boy', index prefix:'', index separator:'-Index__', alias:'some-kind-index__search', Registrador: getVoidLogger(), elasticSearchClient: cliente, });// Set up the required Elastic simulations.simulacro.clearAll(); bulkSpy = broma.fn().mockReturnValue({ nahm:9, Error:INCORRECT, Article: [] }); mock.add({ Method:'CORREO', Far:'/_bulk products', }, BulkSpy, ); mock.add ({ Method:'RECEIVE', Far:'/:index/_update', }, es.fn().mockReturnValue({}), ); catSpy = is.fn().mockReturnValue([ { Alias:'some-kind-index__search', Index:'some-type-index__123tobedelete', filter:'-','routing.index':'-','routing.lookup':'-', is_write_index:'-', }, { alias:'some-kind-index__search_removable', Index:'some-type-index__456tobedelete', filter:'-','routing.index':'-','routing.lookup':'-', is_write_index:'-', }, ]); mock.add ({ Method:'RECEIVE', Far:'/_cat/aliases/some-type-index__search%2Csome-type-index__search_removable', }, spy cat, ); createSpy = jest.fn().mockReturnValue({ confirmed:TRUE, Fragments_Recognized:TRUE, Index:'unique_index', }); mock.add ({ Method:'TO PLACE', Far:'/:Index', }, create spy, ); aliasSpy = joke.fn().mockReturnValue({}); mock.add({ Method:'CORREO', Far:'*', }, aliasSpy, ); deleteSpy = broma.fn().mockReturnValue({}); mock.add ({ Método:'EXTINGUISH', Far:'/some-index-of-type__123toremove%2Some-index-of-type__456toremove', }, deleteSpy, ); }); Is('index documents',asynchronous() => {untilDocuments = [ { Title:'trial term', Text:'test text', Location:'Test/Location', }, { Title:"Another test", Text:'Some more text', Location:'test/location/2', }, ];waitTestPipeline.withSubject(indexador).withDocuments(documents).execute();// Older indices should have been queried.erwartet (gatSpy).toHaveBeenCalled();// A new index should have been created. untilcreatedIndex = createSpy.mock.calls[0][0].path.segment(1); expected(createdindex).toContain('some-kind-of-index__');// The bulk helper should have been called with docs. untilbulkBody = bulkSpy.mock.calls[0][0].Body; wait(mass body[0]).toStrictEqual({index: { _index: createdindex } }); wait(mass body[1]).toStrictEqual(Dokumente[0]); wait(mass body[2]).toStrictEqual({index: { _index: createdindex } }); wait(mass body[3]).toStrictEqual(Dokumente[1]);// Alias should have been rotated.erwarten (aliasesSpy).toHaveBeenCalled();untilaliasActions = aliasSpy.mock.calls[0][0].body.actions; expect(aliasActions[0]).toStrictEqual({ delete: { index:'some-type-index__*', alias:'some-kind-index__search'}, }); expect(aliasActions[1]).toStrictEqual({ add: { indices: ['some-type-index__123tobedelete','some-type-index__456tobedelete', ], alias:'some-kind-index__search_removable', }, }); expect(aliasActions[2]).toStrictEqual({ add: { index: index created, alias:'some-kind-index__search'}, });// The old index should be cleaned up.Expect(deleteSpy).toHaveBeenCalled(); }); Es('handles bulk and batch during indexing',asynchronous() => {untildocuments = area (550).Map(I=>({ title:"Hello World${yo}`, Location:`Lage-${yo}`,// Generate large documents to trigger ES bulk flush.text: area (2000).to connect(', '), }));waitTestPipeline.withSubject(indexador).withDocuments(documents).execute();// Make sure multiple bulk requests have been made.erwarten(bulkSpy).toHaveBeenCalledTimes(2);// Make sure that the first and last documents have been included in the payloads. untildocLocations:line[] = [ ...bulkSpy.mock.calls[0][0].body.map((l:any) =>l.location), ...bulkSpy.mock.calls[1][0].body.map((l:any) =>l.position), ]; expected(doclocations).toContain('location-0'); expected(doclocations).toContain('location-549'); }); Es('ignore cleanup if no existing indexes',asynchronous() => {untilDocuments = [ { Title:'trial term', Text:'test text', Location:'Test/Location', }, ];// update the initial cat alias so that it returns nothing.spycat = joke.fn().mockReturnValue([]); mock.clear({ Method:'RECEIVE', Far:'/_cat/aliases/some-type-index__search%2Csome-type-index__search_removable', }); mock.add ({ Method:'RECEIVE', Far:'/_cat/aliases/some-type-index__search%2Csome-type-index__search_removable', }, spy cat, );waitTestPipeline.withSubject(indexador).withDocuments(documents).execute();// Do not call purge.Expect(deleteSpy).not.toHaveBeenCalled(); });});
Example #22
source file:tarea.fork.tsFrom balancer-v2-monorepo with GNU General Public License v3 | 4You | ![]() ![]() |
describe('ArbitrumRootGaugeFactory',function(){permissionveBALHolder: SignerWithAddress, admin: SignerWithAddress, Empfänger: SignerWithAddress;permissionfactory: contract, apprenticeship: contract;permissionvault:Contract, authorizer:Contract, authorization adapter:Contract, BAL:Contract, BALTokenAdmin:Contract, gauge controller:Contract, gauge adder:Contract;untiltask =nuevoTask('20220413-arbitrum-root-gauge-factory', TaskMode.TEST, getForkedNetwork(hre));untilTITULAR_VEBAL ='0xCB3593C7c0dFe13129Ff2B6add9bA402f76c797e';untilGOV_MULTISIG ='0x10A19e7eE7d7F8a52822f6817de8ea18204F2e4f'; Before('run task',asynchronous() => {waittask.run({ force:TRUE}); Bodies =waittask.deployed instance('ArbitrumRootGaugeFactory'); }); Before('wait time',asynchronous() => {// This expires all voting cooldowns and allows the veBAL owner to vote again waitDelivery period (DAY *12); }); Before('Set up accounts',asynchronous() => { Administrator =waitgetSigner(0); receptor =waitgetSigner(1); veBALHolder =waitimitieren (VEBAL_HOLDER, fp(100)); }); Before("Construction Contracts",asynchronous() => {untilvault task =nuevoTask('20210418-Tesoro', TaskMode.READ_ONLY, getForkedNetwork(hre)); Tesoro =waitVaultTask.instanceIn('boveda','0xBA12222222228d8Ba445958a75a0704d566BF2C8');// TaskVault.output({ network: 'mainnet' }).Vaultagent =waitVaultTask.instanceIn('Authorized representative',waitvault.getAuthorizer());untilAuthorizerAdaptorTask =nuevoTask('20220325-Authorizer-Adapter', TaskMode.READ_ONLY, getForkedNetwork(hre)); adaptadorautor =waitAuthorizerAdaptorTask.instanceAt('AuthorizerAdaptor','0x8f42adbba1b16eaae3bb5754915e0d06059add75' // AuthorizerAdaptorTask.output({ red: 'mainnet' }).AuthorizerAdaptor);untiltaskAddmeter =nuevoTask('caliber adder 20220325', TaskMode.READ_ONLY, getForkedNetwork(hre)); sumador de calibre =waitcalibreAdderTask.instanceAt('Caliber aggregator','0xEd5ba579bB5D516263ff6E1C10fcAc1040075Fe2' // gaugeAdderTask.output({ red: 'mainnet' }).GaugeAdder);untilbalancerTokenAdminTask =nuevoTask('20220325-balancer-token-admin', TaskMode.READ_ONLY, getForkedNetwork(hre)); BALTokenAdmin =waitbalancerTokenAdminTask.instanceAt('BalancerTokenAdmin','0xf302f9F50958c5593770FDf4d4812309fF77414f' // balancerTokenAdminTask.output({ red: 'mainnet' }).BalancerTokenAdmin);// We reuse this task because it contains an ABI similar to the actual BAL token untiltestBALTokenTask =nuevoTask('20220325-test-balancer-token', TaskMode.READ_ONLY, getForkedNetwork(hre)); BA =waittestBALTokenTask.instanceIn('TestBalancerToken',waitBALTokenAdmin.getBalancerToken());untilgauge controller task =nuevoTask('20220325 - gauge controller', TaskMode.READ_ONLY, getForkedNetwork(hre)); controlador de calibre =waitcalibreControllerTask.instanceAt('gauge controller','0xC128468b7Ce63eA702C1f104D55A2566b13D3ABD' // gaugeControllerTask.output({ red: 'mainnet' }).GaugeController); }); Es('Create indicator',asynchronous() => {untiltx =waitfactory.create(recipient.address);untilevent = eventosesperado.enRecibo(waittx.wait(),'ArbitrumRootGaugeCreated'); calibre =waittask.instanceIn('Arbitrage Root Meter', event.args.gauge); Expect(event.args.recipient).to.equal(recipient.address); erwarten(waitfactory.isGaugeFromFactory(gauge.address)).to.be.true; erwarten(waitfactory.getRecipientGauge(Recipient.Address)).to.equal(Gauge.Address); esperar(waitfactory.getGaugeRecipient(gauge.address)).to.equal(recipient.address); }); He('Grant permissions',asynchronous() => {// We need to give the admin permission to add the Arbitrum factory to the GaugeAdder and then add it // Gauges from that factory to the GaugeController. untilgovMultisig =waitlimitar (GOV_MULTISIG, fp(100));untilselectors = ['addGaugeFactory','addArbitrumGauge'].Map((Method) =>gaugeAdder.interface.getSighash (Método));wait Promise.all( Select.map(asynchronous(Selector) =>waitauthorizer.connect(govMultisig).grantRole(waitgaugeAdder.getActionId(selector), admin.address) ) );// We also need to grant permissions to emboss on indicators, which is done via the Authorizing Adapter waitAutorizar .connect(govMultisig) .grantRole(waitAuthorizerAdaptor.getActionId(gauge.interface.getSighash('Control')), address.administrator); }); Is('Add indicator to indicator controller',asynchronous() => {waitgaugeAdder.addGaugeFactory(factory.adder,4);// Select the meter type 4 waitgaugeAdder.addArbitrumGauge(gauge.address); esperar(waitgaugeController.gauge_exists(gauge.address)).to.be.true; }); Es('Voice for caliber',asynchronous() => { wait (waitgaugeController.get_gauge_weight(gauge.dirección)).to.equal(0);waitgaugeController.connect(veBALHolder).vote_for_gauge_weights(gauge.address,10000);// The maximum voting power is 10,000 points // Now we need to go through a time for the voices to be blocked waitDelivery period (DAY *8);waitgauge controller.checkpoint(); wait(waitIndicator Handler['gauge_relative_weight(Direction)'](indicator.direction)).to.be.gt(0); }); Es('Coin and Bridge Token',asynchronous() => {// The indicator has votes for this week and will issue the first batch of tokens. We save the current caliber // relative weight as it changes over time due to declining votes. untilfirstMintWeekTimestamp =waitcurrent week timestamp();untilrelative weight of the indicator =waitIndicator Handler['gauge_relative_weight(Direction)'](gauge.direction);untilcalldata = calibre.interfaz.encodeFunctionData('Control');// Although the announcement has relative weight, it cannot be coined yet because the epoch must end untilBrückeETH =waitcaliber.getTotalBridgeCost();untilzeroMintTx =waitAuthorizerAdaptor .connect(admin) .performAction(gauge.address, calldata, { value: bridgeETH }); ExpectEvent.inReceiptIndirecto(waitzeroMintTx.wait(), caliber.interfaz,'Control', { periodTime: firstMintWeekTimestamp.sub(SEMANA),// Expiration of the last week that had zero votesPeriodEmissions:0, });// No token transfers when emissions are zero, but we can't prove their absence waitadvanceTime(WEEK);// The screen should now mint and send all minted tokens to the arbitrage bridge untilmentaTx =waitAuthorizerAdaptor.connect(admin).performAction(gauge.address, calldata, { value: bridgeETH });untilevent = expected event. in Indirect Receipt (waitmintTx.wait(), gauge.interface,'Control', { periodTime: firstMintWeekTimestamp, });untilcurrent emissions = event.args.periodEmissions;// The amount of minted tokens must be equal to the weekly issuance rate multiplied by the relative weight of the meter untilweekly price = (waitBALTokenAdmin.getInflationRate()).mul(SEMANA);untilexpected emissions = caliberRelativeWeight.mul(weeklyRate).div(FP_SCALING_FACTOR); ExpectEqualWithError(actual emissions, expected emissions,0,001);// Mint tokens for the meterExpectEvent.inReceiptIndirecto(waitmintTx.wait(), BAL.interface,'Transfer', {outside: ZERO_ADDRESS, to: gauge.address, value: realEmissions, });// And the meter stores them in the predicate via the bridging mechanism untilbridge interface =nuevoeteres.utils.Interface(['event DepositInitiated(address l1Token, address indexed by, address indexed to, sequence number indexed uint256, amount uint256)', ]); ExpectEvent.inReceiptIndirecto(waitmintTx.wait(), interfazpuente,'Deposit started', {outside: gauge.address, to: recipient.address, l1Token: BAL.address, amount: current issues, }); }); He('Mint several weeks',asynchronous() => {untilnumber of weeks =5;waitadvanceTime(WEEK * numberOfWeeks);waitgaugeController.checkpoint_gauge (indicator.direction);untilWocheZeitstempel =waitcurrent week timestamp();// We can check the relative weight of the indicator for each of the last weeks untilrelative weights: BigNumber[] =wait Promise.all(area(1, number of weeks +1).Map(asynchronous(weekindex) => indicator handler['gauge_relative_weight (Direction, uint256)'](indicator.direction, weekTimestamp.sub(WEEK * weekindex)) ) );// The amount of minted tokens must be equal to the sum of the weekly issuance rate multiplied by the relative weight of the // Indicator (this assumes that we do not exceed a time of the emission rate so that inflation remains constant). untilweekly price = (waitBALTokenAdmin.getInflationRate()).mul(SEMANA);untilexpected emissions = relative weights .map((weight) =>weight.mul(weekly rate).div(FP_SCALING_FACTOR)) .reduce((sum, value) =>suma.add(value));untilcalldata = calibre.interfaz.encodeFunctionData('Control');untiltx =waitAuthorizerAdaptor .connect(admin) .performAction(gauge.address, calldata, { value:waitcaliber.getTotalBridgeCost() });wait Promise.all(area(1, number of weeks +1).Map(asynchronous(weekIndex) => expected event.inReceiptIndirect(waittx.wait(), caliber.interface,'Control', { periodTime: weekTimestamp.sub(WEEK * weekindex), }) ) );// Mint tokens for the meterExpectEvent.inReceiptIndirecto(waittx.wait(), BAL.interface,'Transfer', {outside: ADDRESS_ZERO, a: address.indicator, value: expected emissions, });// And the meter stores them in the predicate via the bridging mechanism untilbridge interface =nuevoeteres.utils.Interface(['event DepositInitiated(address l1Token, address indexed by, address indexed to, sequence number indexed uint256, amount uint256)', ]); ExpectEvent.inReceiptIndirecto(waittx.wait(), bridge interface,'Deposit started', {outside: gauge.address, to: receiver.address, l1Token: BAL.address, quantity: expected emission, }); });});
Example #23
source file:usePagination.tsBy gio-design licensed under the Apache 2.0 license | 4You | ![]() ![]() |
usePagination = ( Props: Omit<PaginationProps,'page size'> & Required<Choose<PaginationProps,'page size'>>): {maxPages:Number; go to page: (value:Number, Ereignis: React.MouseEvent<HTMLButtonElement> | React.KeyboardEvent<HTMLInputElement> |Null) =>Empty; Article: PaginationItemProps[];} => {until{ onChange, defaultCurrent =1, hideFirstButton =INCORRECT, hideLastButton =INCORRECT, totals =0, actual: currentProp, pagesize, } = props;until[aktuelleSeite, setCurrentPage] = useControlledState(currentProp, defaultCurrent);until[startPage, endPage, maxPages] = usePage(currentPage, pageSize, total);untilgo to page: return type <Kind ofuse pagination>['go to page'] = use Callback(( page , event ) =>{And(page >0) { setCurrentPage(mathematics.min(Page, maxPages));And(isFunction(onChange)) { onChange(page, pagesize, event); } } }, [maxPages, onChange, pageSize, setCurrentPage] ); useEffect(()=>{And( current page > maxPages && maxPages >0) { go to page (maximum pages,Null); } }, [maxPages, currentPage, setCurrentPage, goToPage]);untilcalcularPágina = (type: Type of pagination element):Number=>{change(type) {FallPaginationItemType.First:go back 1;FallPaginationItemType.Anterior:go backcurrent page -1;FallPaginationItemType.Next:go backcurrent page +1;FallPaginationItemType.Last:go backmaxPages;Standard:go back 0; } };/** * Rendering type of child paging elements * p. untilItem Types:Training<Number| pagination element type >= [// Jump to the home page...(hideFirstButton ? [] : [PaginationItemType.First]),// return to the last pagePaginationItemType.Anterior,// page number... range ( startpage , endpage +1),// Go to the next pagePaginationItemType.Next,// jump to the last page...(hideLastButton ? [] : [PaginationItemType.Last]), ];untilitems = itemTypes.map<PaginationItemProps>((type) =>{untildisabledByStringType =(()=>{change(type) {Fall PaginationItemTypePaginationItemType.First:Fall PaginationItemTypePaginationItemType.anterior:go back current page<= 1;Fall PaginationItemTypePaginationItemType.Next:Fall PaginationItemTypePaginationItemType.Last:go back current page>=maxpages;Standard:go back INCORRECT; } })();And(Kind of type=== 'line') {go back{type,Disabled person:disabledByStringType,page of book:calculate page(type),on click: (event) =>go to page (calculation page (type),Fall), }; }until page of book=type;go back{type:PaginationItemTypePaginationItemType.page of book,page of book, 'Silver-actual':page of book===current page,asset:page of book===current page,on click: (event) =>goToPage(page, event), }; });go back{ maxPages, gotoPage, Element, };}
Example #24
source file:ExperimentList.test.tsxFor kfp-tekton-backend with Apache 2.0 license | 4You | ![]() ![]() |
describe('List of experiments',()=>{permissionBaum: Shallow Wrapping | ReactWrapper;untilonErrorSpy = es.fn();untillistExperimentsSpy = jest.spyOn(Apis.experimentServiceApi,'experimentlist');untilgetExperimentSpy = jest.spyOn(Apis.experimentServiceApi,'getExperiment');// We mock this because it uses toLocaleDateString which causes mismatches between local and CI // test environments untilformatDateStringSpy = jest.spyOn(Utils,'format date string');untillistRunsSpy = jest.spyOn(Apis.runServiceApi,'listRuns');function GenerateAccessories():ExperimentoListaAccesorios {go back{ History: {}and any, Location: { Search:''}and any, fit:'' and any, onError: onErrorSpy, }; }function MockNExperimente(NORTE:Number):Empty { getExperimentSpy.mockImplementation(ID=> Promise.resolve({ ID:'test experiment'+ ID, Name:'Experiment with ID: Testexperiment'+ id, }), ); listExperimentsSpy.mockImplementation(()=> Promise.resolve({ Experiments: Rank(1, n+1).Map(I=>{go back{ IDENTIFICATION:'test experiment'+ me, name:'Experiment with ID: Testexperiment'+ i, }; }), }), ); } before each (()=>{formatDateStringSpy.mockImplementation((Given?:Given) =>{go backGiven?'02.01.2019, 12:34:56':'-'; }); onErrorSpy.mockClear(); listaExperimentosEspía.mockClear(); getExperimentSpy.mockClear(); }); nach jedem(asynchronous() => {// unmount() should be called before resetAllMocks() if it is part of the unmount lifecycle // depends on mocks/spies And(Baum) {waittree.unmount(); } joke.resetAllMocks(); }); Is('make the experience empty',()=>{expect(flat(<ExperimentList {...generateProps()} />)).toMatchSnapshot(); }); Él('Render empty experience in ARCHIVED state',()=>{untilRequisito = GenerateProps (); props.storageState = ExperimentStorageState.ARCHIVIERT; Expect(shallow(<ExperimentList {...props} />)).toMatchSnapshot(); }); Es('load experiments whose storage state is not ARCHIVED if the storage state is AVAILABLE',asynchronous() => { MockNExperimente (1);untilRequisito = GenerateProps (); props.storageState = ExperimentStorageState.VERFÜGBAR; árbol = superficial (<ExperimentList {...props} />);wait(Tree.Instance()andExperimentListTest)._loadExperiments({}); esperado (Apis.experimentServiceApi.listExperiment).toHaveBeenLastCalledWith(not defined,not defined,not defined,encodeURIComponent(JSON.stringify({ predicates: [ { keys:'memory state', op: PredicateOp.NOTEQUALS, string_value: ExperimentStorageState.ARCHIVED.toString(), }, ], }andAPI filter), ),not defined,not defined, ); }); Es('load experiments whose storage state is ARCHIVED if the storage state is equal to ARCHIVED',asynchronous() => { MockNExperimente (1);untilRequisito = GenerateProps (); props.storageState = ExperimentStorageState.ARCHIVIERT; árbol = superficial (<ExperimentList {...props} />);wait(Tree.Instance()andExperimentListTest)._loadExperiments({}); esperado (Apis.experimentServiceApi.listExperiment).toHaveBeenLastCalledWith(not defined,not defined,not defined,encodeURIComponent(JSON.stringify({ predicates: [ { keys:'memory state', op: PredicateOp.EQUALS, string_value: ExperimentStorageState.ARCHIVED.toString(), }, ], }andAPI filter), ),not defined,not defined, ); }); Es('Extend request filters with memory state predicates',asynchronous() => { MockNExperimente (1);untilRequisito = GenerateProps (); props.storageState = ExperimentStorageState.ARCHIVIERT; árbol = superficial (<ExperimentList {...props} />);wait(Tree.Instance()andExperimentListTest)._loadExperiments({ Filtro:encodeURIComponent(JSON.stringify({ predicates: [{ keys:'k', op:'op', string value:'wert'}], }), ), }); esperado (Apis.experimentServiceApi.listExperiment).toHaveBeenLastCalledWith(not defined,not defined,not defined,encodeURIComponent(JSON.stringify({ predicates: [ { keys:'k', op:'op', string value:'wert', }, { Gusto:'memory state', op: PredicateOp.EQUALS, string_value: ExperimentStorageState.ARCHIVED.toString(), }, ], }andAPI filter), ),not defined,not defined, ); }); Es('load an experiment',asynchronous() => { MockNExperimente (1);untilRequisito = GenerateProps (); árbol = superficial (<ExperimentList {...props} />);wait(Tree.Instance()andExperimentListTest)._loadExperiments({}); esperado (Apis.experimentServiceApi.listExperiment).toHaveBeenLastCalledWith(not defined,not defined,not defined,not defined,not defined,not defined, ); Expect(props.onError).not.toHaveBeenCalled(); erwarten(baum).toMatchSnapshot(); }); Es('reloads experiment when update is invoked',asynchronous() => { MockNExperimente (0);untilRequisito = GenerateProps (); árbol = TestUtils.mountWithRouter(<ExperimentList {...props} />);wait(Tree.Instance()andListaExperimentos).refresh(); Baum.update(); Expect(Apis.experimentServiceApi.listExperiment).toHaveBeenCalledTimes(2); esperado (Apis.experimentServiceApi.listExperiment).toHaveBeenLastCalledWith('',10, ExperimentSortKeys.CREATED_AT +'downward','',not defined,not defined, ); Expect(props.onError).not.toHaveBeenCalled(); erwarten(baum).toMatchSnapshot(); }); Es('load multiple experiments',asynchronous() => { MockNExperimente (5);untilRequisito = GenerateProps (); árbol = superficial (<ExperimentList {...props} />);wait(Tree.Instance()andExperimentListTest)._loadExperiments({}); Expect(props.onError).not.toHaveBeenCalled(); erwarten(baum).toMatchSnapshot(); }); Es('call error callback if loading experiment fails',asynchronous() => { TestUtils.makeErrorResponseOnce( jest.spyOn(Apis.experimentServiceApi,'experimentlist'),'Something bad happened', );untilRequisito = GenerateProps (); árbol = superficial (<ExperimentList {...props} />);wait(Tree.Instance()andExperimentListTest)._loadExperiments({}); erwartet(props.onError).to have been last called with('Error: Could not enumerate experiments: ',nuevo Error('Something bad happened'), ); }); Es('load runs for a specific experiment id when expanded',asynchronous() => { listRunsSpy.mockImplementation (()=>{}); MockNExperimente (1);untilRequisito = GenerateProps (); árbol = TestUtils.mountWithRouter(<ExperimentList {...props} />);wait(Tree.Instance()andExperimentListTest)._loadExperiments({}); Tree.update(); Expect(props.onError).not.toHaveBeenCalled(); expected(tree.state()).toHaveProperty('displayExperimente', [ { expandState: ExpandState.COLLAPSED, ID:'testexperiment1', Name:'Experiment with ID: Testexperiment1', }, ]);// Expand the first experimentBaum .find('button[aria-label="Expand"]') .in(0).simulate('click');waitSpyRunList; Tree.update(); expected(tree.state()).toHaveProperty('displayExperimente', [ { expandState: ExpandState.EXPANDED, ID:'testexperiment1', Name:'Experiment with ID: Testexperiment1', }, ]); Expect(Apis.runServiceApi.listRuns).toHaveBeenCalledTimes(1); esperado (Apis.runServiceApi.listRuns).toHaveBeenLastCalledWith('',10,'created_on download','EXPERIMENT','testexperiment1',encodeURIComponent(JSON.stringify({ predicates: [ { keys:'memory state', op: PredicateOp.NOTEQUALS, string_value: RunStorageState.ARCHIVED.toString(), }, ], }andApiFilter), ), ); }); Is('load runs for a specific experiment id with expanded memory state when expanded',asynchronous() => { listRunsSpy.mockImplementation (()=>{}); MockNExperimente (1);untilAccesorios = GenerarAccesorios(); props.storageState = ExperimentStorageState.ARCHIVED; árbol = TestUtils.mountWithRouter(<ExperimentList {...props} />);wait(Tree.Instance()andExperimentListTest)._loadExperiments({}); Tree.update(); Expect(props.onError).not.toHaveBeenCalled(); expected(tree.state()).toHaveProperty('displayExperimente', [ { expandState: ExpandState.COLLAPSED, ID:'testexperiment1', Name:'Experiment with ID: Testexperiment1', }, ]);// Expand the first experimentBaum .find('button[aria-label="Expand"]') .in(0).simulate('click');waitSpyRunList; Tree.update(); expected(tree.state()).toHaveProperty('displayExperimente', [ { expandState: ExpandState.EXPANDED, ID:'testexperiment1', Name:'Experiment with ID: Testexperiment1', }, ]); Expect(Apis.runServiceApi.listRuns).toHaveBeenCalledTimes(1); esperado (Apis.runServiceApi.listRuns).toHaveBeenLastCalledWith('',10,'created_on download','EXPERIMENT','testexperiment1',encodeURIComponent(JSON.stringify({ predicates: [ { keys:'memory state', op: PredicateOp.EQUALS, string_value: RunStorageState.ARCHIVED.toString(), }, ], }andAPIFilter), ), ); });});
Example #25
source file:DataDocChartComposer.tsxBy Apache License 2.0 Sourcebook | 4You | ![]() ![]() |
DataDocChartComposerComponent: React.FunctionComponent< IProps & FormikProps<IChartFormValues>> = ({ meta, dataDocId, cellAboveId, valores, sucio, handleSubmit, setFieldValue, setFieldTouched, isEditable,}) => {until[formTab, setFormTab] = React.useState<'Data'|'Diagram'|'Images'>('Data');until[showTable, setShowTable] = React.useState(TRUE);// const [showSeriesAggTypes, setShowSeriesAggTypes] = React.useState<boolean>( // !values.aggType || !Object.keys(values.aggSeries).length //); until[tableTab, setTableTab] = React.useState<'Original'|'transformed'>( added.values || values.change ?'transformed':'Original');until[displayExecutionId, setDisplayExecutionId] = React.useState (valores.executionId);until[displayStatementId, setDisplayStatementId] = React.useState(not defined);until{ statement result data, query executions, statement executions, } = useChartSource( values.cellId, displayExecutionId, displayStatementId, setFieldValue.bind(Null,'cellId'), establecerValorCampo.bind(Null,'run id'), setDisplayStatementId, valores.limit );untilchartData = React.useMemo(()=>AussageResultData ? transformData(statementResultData, values.aggregate, values.switch, values.formatAggCol, values.formatSeriesCol, values.formatValueCols, values.aggSeries, values.sortIndex, values.sortAsc, values.xIndex) :Null, [statementResultData, aggregate.values, switch.values, formatAggCol.values, formatSeriesCol.values, formatValueCols.values, aggSeries.values, sortIndex.values, sortAsc.values, xIndex.values, ]);// Get Redux status untilqueryCellOptions = useSelector((State: IStoreState) =>queryCellSelector(status, dataDocId) ); Reagieren.useEffect(()=>{And(Values.FontType ==='cell_oben'&& Werte.cellId !== cellAboveId ) { setFieldValue('cellId', cellAboveId); }Anders And((Values.FontType ==='cell'|| Valores.SourceType ==='Execution') && valores.cellId ==Null) { setFieldValue('cellId', celdaAboveId ?? queryCellOptions?.[0].ID); } }, [values.sourcetype]); React.useEffect(()=>{And(chartData && values.aggType) { handleAggTypeChange(values.aggType); } }, [(datagraphics || [])[0]?.Length]); React.useEffect(()=>{setDisplayExecutionId(valores.executionId); }, [valores.executionId]);// ------------- Choose options --------------------------------- --------------------------------- untilcell execution options = React.useMemo(()=>{And(query runs) {go backconsultaEjecuciones.map((query execution) =>({Wert: queryExecution.id,label:"Execution${queryExecution.id}`, })); }Anders And(DisplayExecutionId) {go back[ {Wert: show run id,label:"Execution${displayExecutionId}`, }, ]; }Anders{go back[ {Wert:-1,label:`Loading runs`, }, ]; } }, [displayExecutionId, queryExecutions]);untilxAxisOptions = React.useMemo(()=>{And(! chart data) {go back[]; }go backchart data[0].Map((columna, idx) =>({Wert: idx,label: Split, })); }, [chart data]);untilformatAggByOptions = React.useMemo(()=>{And(!DataResultStatement) {go back[]; }go backDeclarationResultData[0].reduce<Training<ISelectOption<Number>>>((optionsAcc, label, idx) =>{And(idx !== values.formatSeriesCol) { optionsAcc.push({Wert:idx, label, }); }go backOptionenAcc; }, []); }, [statementResultData, valores.formatSeriesCol]);untilmakeFormatSeriesOptions = React.useMemo(()=>{And(!DataResultStatement) {go back[]; }untilcolumns = DataResultDeclaration[0];untilOptions:Training<ISelectOption<Number>> = [];for(permissionyo =0; in <Column.Length; i++) {And(i !== values.formatAggCol) { options.push({Wert: I,label: columnas[i], }); } }go backOptions; }, [statementResultData, values.formatAggCol]);untilmakeFormatValueOptions = React.useMemo(()=>{And(!DataResultStatement) {go back[]; }untilcolumns = DataResultDeclaration[0];untilOptions:Training<ISelectOption<Number>> = [];for(permissionyo =0; in <Column.Length; i++) {And(i !== values.xIndex && i !== values.formatSeriesCol) { options.push({Wert: I,label: columnas[i], }); } }go backOptions; }, [statementResultData, values.formatSeriesCol, values.xIndex]);untilmakeSeriesValsAndOptions = React.useCallback((selected values: boolesch) =>{And(!ChartData || !ChartData.Long) {go back[{Wert:0,label:'Loading series'}]; }untilvalsArray = chartData[0];untiloptionIdxs = selected values? range(valsArray.length).filter((Wert) =>!values.hiddenSeries.includes(val) && val !== values.xIndex ) : values.hiddenSeries;untilOptions = OptionIdxs.map((I) =>({Wert: I,label: valsArray[i],Color: ColorPalette[Werte.ColoredSeries[i] ?? i % ColorPalette.length .color, }));go backOptions; }, [chartData, values.xIndex, values.hiddenSeries, values.coloredSeries]);untilgetAxesScaleType = React.useCallback((ColIndex: Number) =>{for(permissionline =1; row < chart data?.length; row++) {untilcell = chartData?.[row]?.[colIndex];And(cell !=Null) {go backgetDefaultScaleType(chartData?.[row]?.[colIndex]); } }// Unknown type, use linear as default go back 'lineal'; }, [chart data]);untilseriesColorOptions = ColorPalette.map((color, idx) =>({Wert: idx,label: Farbe.Name,Color: color.color, }));untilseriesAggOptions =Object.entries(aggTypes).mapa(([value, key]) =>({Wert: WertandChartDataAggType,label: Gusto, }));// ------------- Event handler -------------------------------- - --------------------------------- untilhandleHiddenSeriesChange = (ValoresSeleccionados:Training<ISelectOption<Number>> ) => {untilhidden string = [];untilselectedstring = selectedvalues.map((object) =>object value);for(permissionyo =0; i < chart data [0].Largo; i++) {And(i !== valores.xIndex && !s selectedSeries.includes(i)) { hiddenSeries.push(i); } } establecerValorCampo('hidden series', hidden string); };untilhandleAggTypeChange =(aggType: ChartDataAggType) =>{ setFieldValue('kind of grudge', aggType);untilnewAggString = {};for(permissionyo =0; i < chart data [0].Long; i++) { newAggString[i] = aggType; } setFieldValue('aggSerie', newSeriesAgg); };// ------------- DOM Elements --------------------------------- --------------------------------- until tabsDOM = ( <Tabs selectedTabKey={formTab} onSelect={(selectedTab: 'data' | 'chart' | 'visuals') => setFormTab(selectedTab) } items={formTabs} wide /> ); const renderPickerDOM = () => { if (values.sourceType === 'custom') { return null; // Custom data is sourced from internal context } const showQueryExecution = values.sourceType !== 'execution' && queryExecutions.length; const showStatementExecution = displayExecutionId != null && statementExecutions.length; const queryExecutionPicker = showQueryExecution || showStatementExecution ? ( <FormField label={`${ showQueryExecution ? 'Query Execution' : 'Statement' } (Display Only)`} stacked help="Not Saved. Defaults to latest." > {showQueryExecution && ( <QueryExecutionPicker queryExecutionId={displayExecutionId} onSelection={setDisplayExecutionId} queryExecutions={queryExecutions} autoSelect shortVersion /> )} {showStatementExecution && ( <StatementExecutionPicker statementExecutionId={displayStatementId} onSelection={setDisplayStatementId} statementExecutions={statementExecutions} total={statementExecutions.length} autoSelect /> )} </FormField> ) : null; return ( <div className="DataDocChartComposer-exec-picker"> {queryExecutionPicker} </div> ); }; const dataSourceDOM = ( <> <FormSectionHeader>Source</FormSectionHeader> <FormField stacked label="Type"> <SimpleReactSelect value={values.sourceType} onChange={(val) => { if ( values.sourceType === 'execution' && val !== 'execution' ) { setFieldValue('executionId', null); } setFieldValue('sourceType', val); }} options={Object.entries(sourceTypes).map(([key, val]) => ({ value: key, label: val, }))} /> </FormField> {values.sourceType !== 'cell_above' ? ( <FormField stacked label="Cell"> <ReactSelectField name="cellId" options={queryCellOptions.map((val) => ({ value: val.id, label: val.title, }))} /> </FormField> ) : null} {values.sourceType === 'execution' ? ( <SimpleField stacked type="react-select" options={cellExecutionOptions} name="executionId" label="Execution" /> ) : null} {renderPickerDOM()} <SimpleField stacked type="react-select" options={StatementExecutionResultSizes.map((size) => ({ value: size, label: formatNumber(size, 'Row'), }))} name="limit" label="Row Limit" help="Max number of rows to fetch from the result" /> </> ); const dataTransformationDOM = ( <> <FormSectionHeader>Transformation</FormSectionHeader> <SimpleField type="checkbox" name="aggregate" label="Aggregate" onChange={(val) => { setFieldValue('aggregate', val); setFieldValue('hiddenSeries', []); if (val) { handleAggTypeChange('sum'); setTableTab('transformed'); } else { setFieldValue('aggType', undefined); setFieldValue('aggSeries', {}); } }} help="By default, all rows will be aggregated" /> {values.aggregate ? ( <> <FormField stacked label="Aggregate By"> <SimpleReactSelect value={values.aggType} onChange={(val) => handleAggTypeChange(val)} options={seriesAggOptions} /> </FormField> <div className="DataDocChartComposer-info m8"> Value must be selected for aggregation by row/column. </div> <SimpleField stacked type="react-select" label="Row" name="formatAggCol" options={formatAggByOptions} isDisabled={!statementResultData} withDeselect /> <SimpleField stacked label="Column" type="react-select" name="formatSeriesCol" options={makeFormatSeriesOptions} isDisabled={!statementResultData} withDeselect /> <SimpleField stacked label="Value" type="react-select" name="formatValueCols" value={values.formatValueCols[0]} options={makeFormatValueOptions} isDisabled={!statementResultData} onChange={(val) => { if (val == null) { setFieldValue('formatValueCols', []); } else { setFieldValue('formatValueCols', [val]); } }} withDeselect /> </> ) : null} <SimpleField type="checkbox" label="Switch Rows/Columns" name="switch" help="Switch is applied after aggregation" /> </> ); const dataTabDOM = ( <> {dataSourceDOM} {dataTransformationDOM} </> ); const chartOptionsDOM = ( <> <FormField stacked label="Type"> <SimpleReactSelect value={values.chartType} onChange={(val) => { setFieldValue('chartType', val); // area defaults to true if (val === 'area') { setFieldValue('stack', true); } else if ( [ 'line', 'pie', 'doughnut', 'scatter', 'bubble', ].includes(val) ) { // these charts cannot be stacked setFieldValue('stack', false); if (val === 'bubble' && !values.zIndex) { setFieldValue('zIndex', 2); } } }} options={Object.entries(chartTypes).map(([key, val]) => ({ value: key, label: val, }))} /> </FormField> {['bar', 'histogram'].includes(values.chartType) ? ( <SimpleField type="checkbox" label="Stack Chart" name="stack" /> ) : null} </> ); let axesDOM: React.ReactChild = null; if (values.chartType !== 'table') { const noAxesConfig = ['pie', 'doughnut'].includes(values.chartType); const getAxisDOM = ( prefix: string, axisMeta: IChartAxisMeta, scaleType: ChartScaleType, scaleOptions: ChartScaleType[] = ChartScaleOptions ) => { if (noAxesConfig) { return null; } scaleType = getAutoDetectedScaleType(scaleOptions, scaleType); const allScaleOptions = [ { label: `auto detect (${scaleType})`, value: null, }, ].concat( scaleOptions.map((value) => ({ label: value, value, })) ); let axisRangeDOM: React.ReactNode; const assumedScale = axisMeta.scale ?? scaleType; if (assumedScale === 'linear' || assumedScale === 'logarithmic') { axisRangeDOM = ( <FormField stacked label="Range"> <Level margin="8px"> <NumberField name={`${prefix}.min`} placeholder="Min" /> <NumberField name={`${prefix}.max`} placeholder="Max" /> </Level> </FormField> ); } return ( <> <SimpleField stacked type="react-select" name={`${prefix}.scale`} options={allScaleOptions} /> {axisRangeDOM} </> ); }; const detectedXAxisScale = getAxesScaleType(values.xIndex); const xAxisDOM = ( <> <FormSectionHeader>X Axis</FormSectionHeader> <FormField stacked label="X Axis"> <ReactSelectField name={`xIndex`} options={xAxisOptions} isDisabled={!statementResultData} /> </FormField> {getAxisDOM( 'xAxis', values.xAxis, detectedXAxisScale === 'linear' ? 'category' : detectedXAxisScale, chartTypeToAllowedAxisType[values.chartType].x )} </> ); let yAxisDOM: React.ReactChild; if (!noAxesConfig) { const yAxisSeries = makeSeriesValsAndOptions(true); const defaultYAxisScaleType = yAxisSeries.length ? getAxesScaleType(yAxisSeries[0].value) : null; yAxisDOM = ( <> <FormSectionHeader>Y Axis</FormSectionHeader> <FormField stacked label="Series"> <Select styles={defaultReactSelectStyles} value={yAxisSeries} onChange={(val: any[]) => handleHiddenSeriesChange(val) } options={makeSeriesValsAndOptions(false)} isMulti /> </FormField> {getAxisDOM( 'yAxis', values.yAxis, defaultYAxisScaleType, chartTypeToAllowedAxisType[values.chartType].y )} </> ); } const zAxisDOM = values.chartType === 'bubble' ? ( <> <FormSectionHeader>Z Axis</FormSectionHeader> <FormField stacked label="Z Axis"> <ReactSelectField name={`zIndex`} options={xAxisOptions} isDisabled={!statementResultData} /> </FormField> </> ) : null; axesDOM = ( <> {xAxisDOM} {yAxisDOM} {zAxisDOM} </> ); } const sortDOM = ( <> <FormSectionHeader>Sort</FormSectionHeader> <SimpleField stacked type="react-select" options={xAxisOptions} name="sortIndex" label="Sort Index" withDeselect onChange={(val) => { setFieldValue('sortIndex', val); if (val != null) { setTableTab('transformed'); } }} /> <SimpleField stacked type="react-select" options={[ { value: true, label: 'Ascending' }, { value: false, label: 'Descending' }, ]} name="sortAsc" label="Sort Direction" /> </> ); const chartTabDOM = ( <> {chartOptionsDOM} {axesDOM} {sortDOM} </> ); const seriesColorDOM = chartData ? chartData[0].map((col, seriesIdx) => { if (seriesIdx === 0 || values.hiddenSeries.includes(seriesIdx)) { return null; } const colorIdx = seriesIdx in values.coloredSeries ? values.coloredSeries[seriesIdx] : seriesIdx % ColorPalette.length; return ( <FormField stacked key={col} label={() => ( <> <b>{col}</b> Color </> )} > <ReactSelectField value={colorIdx} name={`coloredSeries[${seriesIdx}]`} options={seriesColorOptions} /> </FormField> ); }) : null; const visualsTabDOM = values.chartType === 'table' ? ( <FormField stacked label="Title"> <Field name="title" /> </FormField> ) : ( <> <FormField stacked label="Title"> <Field name="title" /> </FormField> {['pie', 'doughnut'].includes(values.chartType) ? null : ( <> <SimpleField stacked label="X Axis Label" name="xAxis.label" type="input" /> <SimpleField stacked label="Y Axis Label" name="yAxis.label" type="input" /> </> )} <SimpleField stacked label="Chart Height" name="size" type="react-select" help="If set from not auto to auto height, refresh the page to see change." options={[ { value: ChartSize.SMALL, label: 'Small (1/3 height)', }, { value: ChartSize.MEDIUM, label: 'Medium (1/2 height)', }, { value: ChartSize.LARGE, label: 'Large (full height)', }, { value: ChartSize.AUTO, label: 'Auto height', }, ]} /> <FormSectionHeader>Legend</FormSectionHeader> <SimpleField label="Visible" name="legendDisplay" type="checkbox" /> <SimpleField stacked label="Position" name="legendPosition" type="react-select" options={['top', 'bottom', 'left', 'right']} /> <FormSectionHeader>Values</FormSectionHeader> <SimpleField stacked label="Display" name="valueDisplay" type="react-select" options={[ { value: ChartValueDisplayType.FALSE, label: 'Hide Values', }, { value: ChartValueDisplayType.TRUE, label: 'Show Values', }, { value: ChartValueDisplayType.AUTO, label: 'Show Values without Overlap', }, ]} onChange={(val) => { setFieldValue('valueDisplay', val); if (val) { if (values.valuePosition == null) { setFieldValue('valuePosition', 'center'); } if (values.valueAlignment == null) { setFieldValue('valueAlignment', 'center'); } } }} /> {values.valueDisplay ? ( <> <SimpleField stacked label="Position" name="valuePosition" type="react-select" options={['center', 'start', 'end']} /> <SimpleField stacked label="Alignment" name="valueAlignment" type="react-select" options={[ 'center', 'start', 'end', 'right', 'left', 'top', 'bottom', ]} /> </> ) : null} {['pie', 'doughnut', 'table'].includes( values.chartType ) ? null : ( <> <FormSectionHeader>Colors</FormSectionHeader> {seriesColorDOM} </> )} {['line', 'area'].includes(values.chartType) ? ( <> <FormSectionHeader>Line Formatting</FormSectionHeader> <SimpleField label="Connect missing data" name="connectMissing" type="checkbox" /> </> ) : null} </> ); const formDOM = ( <FormWrapper size={7} className="DataDocChartComposer-form"> <DisabledSection disabled={!isEditable}> {formTab === 'data' && dataTabDOM} {formTab === 'chart' && chartTabDOM} {formTab === 'visuals' && visualsTabDOM} </DisabledSection> </FormWrapper> ); const hideTableButtonDOM = ( <IconButton icon={showTable ? 'ChevronDown' : 'ChevronUp'} onClick={() => setShowTable(!showTable)} noPadding /> ); let dataDOM: JSX.Element; let dataSwitch: JSX.Element; if (chartData && showTable) { if (values.aggregate || values.switch || values.sortIndex != null) { dataSwitch = ( <div className="toggleTableDataSwitch"> <Tabs selectedTabKey={tableTab} onSelect={(key: 'original' | 'transformed') => setTableTab(key) } items={tableTabs} /> </div> ); } dataDOM = ( <div className="DataDocChartComposer-data"> <StatementResultTable data={ tableTab === 'original' ? statementResultData : chartData } paginate={true} maxNumberOfRowsToShow={5} /> </div> ); } const tableDOM = ( <div className="DataDocChartComposer-bottom"> <Level> <LevelItem>{dataSwitch}</LevelItem> <LevelItem>{hideTableButtonDOM}</LevelItem> </Level> {dataDOM} </div> ); const chartDOM = values.chartType === 'table' ? ( <DataDocChartCellTable data={chartData} title={values.title} /> ) : ( <DataDocChart data={chartData} meta={formValsToMeta(values, meta)} chartJSOptions={{ maintainAspectRatio: false }} /> ); const makeLeftDOM = () => ( <div className="DataDocChartComposer-left mr16"> <div className="DataDocChartComposer-chart mt8"> <div className="DataDocChartComposer-chart-sizer"> {chartData ? chartDOM : null} </div> </div> {tableDOM} </div> ); return ( <div className="DataDocChartComposer mh16 pb16"> {makeLeftDOM()} <div className="DataDocChartComposer-right"> {tabsDOM} {formDOM} {isEditable ? ( <div className="DataDocChartComposer-button"> <SoftButton onClick={() => handleSubmit()} title="Save" fullWidth pushable={false} /> </div> ) : null} </div> </div> );}
Example #26
source file:Time Chart.tsxFrom office hours with GNU General Public License v3.0 | 4You | ![]() ![]() |
Export Standard function time chart({values, maxTime, firstHour, lastHour, width, height,}: {values: number[]; maxTime: number; firstHour: number; lasttime: number; width: number; height: number;}):reactelement {until{ tooltipOpen, tooltipLeft, tooltipTop, tooltipData, hideTooltip, showTooltip, } = useTooltip<número>();until{ containerRef, TooltipInPortal } = useTooltipInPortal();// borders untilxMax = Breite - RIGHT_MARGIN - LEFT_MARGIN;untilyMax = Höhe - TOP_MARGIN - BOTTOM_MARGIN;// Scales, remember for performance untilxScale = useMemo(()=>scaleBand<Number>({Area: [0, xmax],redondo:TRUE,Domain: Area(mathematics.max(0, first hour),mathematics.min(last hour +1,24) +1),upholstery: BAR_PADDING, }), [xMax, firstHour, lastHour] );// number of minutes between each row of the grid row untilgridRowInterval = maxTime >=60?60:30;untilmaxTickVal =mathematics.max(MaxTime, GridRowInterval);untilyScale = useMemo(()=>linearScale<number>({Area: [yMáx,0],redondo:TRUE,Domain: [0, maxTickVal +5], }), [yMax, maxTickVal] );untilbar width = xScale.bandwidth();// the tick values for the y axis untilyAxisTickValues = range( gridRowInterval, maxTickVal +1, gridRowInterval );go backancho <10?Null: (// The relative position is necessary for the correct positioning of the tooltip<GraphContainer> <svg ref={containerRef} ancho={ancho} alto={alto}> <rect x={0} y={0} ancho={ancho} alto={alto} fill="rgba(0, 0,0,0)" rx={14} /> <GridRows top={TOP_MARGIN} left={LEFT_MARGIN} width={ancho - RIGHT_MARGIN - LEFT_MARGIN} scale={yScale} tickValues={yAxisTickValues} stroke="#cccccc " /> <Grupo izquierda={LEFT_MARGIN} top={TOP_MARGIN}> {values.map((value, i) => { const barHeight = yMax - yScale(value); const barX = xScale(i) + (barWidth * (1 + BAR_PADDING)) / 2; const barY = yMax - barHeight; const interactiveWithBar = () => { if (tooltipTimeout) clearTimeout(tooltipTimeout); const top = yMax - barHeight - TOP_MARGIN; // - VERTICAL_MARGIN - barHeight; const izquierda = barX + barWidth; showTooltip({ tooltipData: value, tooltipTop: top, tooltipLeft: left, }); }; return ( <BarRounded key={`bar-${formatDateHour(i)}`} className="popularTimes__bar" x={barX} y={barY} ancho={barAncho} altura={barAltura} radio={10} top fill="#40a9ff" onMouseLeave={() => { tooltipTimeout = window.setTimeout(() => { versteckeTooltip(); }, 300); }} onMouseOver={interactWithBar} onMouseDown={interactWithBar} /> ); })} </Group> <Group left={LEFT_MARGIN}> <AxisBottom top={yMax + TOP_MARGIN} scale={xScale} tickFormat={(hora: número) => (hora - primerahora) % 3 == 0 ? formatDateHour(hora) : "" } tickLabelProps={() => ({ fill: "", fontSize: 11, textAnchor: "middle", })} /> </Group> <Group top={TOP_MARGIN} left= {LEFT_MARGIN}> <AxisLeft scale={yScale} hideTicks={true} tickValues={yAxisTickValues} tickFormat={(hora: número) => formatWaitTime(hora)} tickLabelProps={() => ({ fill: "", fontSize: 11, textAnchor: "end", })} /> </Group> </svg> {tooltipOpen && tooltipData && ( <TooltipInPortal key={Math.random()} // Aktualisierung der Tooltip-Grenzen bei jedem Rendern top={ tooltipTop} left={tooltipLeft} style={tooltipStyles} > {formatWaitTime(tooltipData)} </TooltipInPortal> )} </GraphContainer> );}
Example #27
source file:index.test.tsBy analytics-next licensed by MIT | 4You | ![]() ![]() |
describe('event factory',()=>{permissionuser: userpermissionFactory: EventFactoryuntilshoes = {product:'Shoes', total:'$35', Category:'Category'}untilBuyer = { total spend:100} before each (()=>{ user =nuevouser() user.reset() factory =nuevoEventFactory (user) }) describe ('alias',()=>{ proof('generate alias events',()=>{untilalias = fabric.alias('Red','Neto Farah') Expect(alias.type).toEqual('alias') expected (alias.event).toBeUndefined() expected(alias.userId).toEqual('Red') expected(alias.previousId).toEqual('Neto Farah') }) Es('does not accept traits or properties',()=>{untilalias = fabric.alias('Red','Neto Farah') expected(alias.traits).toBeUndefined() expected(alias.properties).toBeUndefined() }) }) describe('Group',()=>{ proof('create group events',()=>{untilgroup = factory.group('Benutzer ID', { cool kids:TRUE}) Expect(group.traits).toEqual({ coolkids:TRUE}) expected(Group.Type).toEqual('Group') Expect(group.event).toBeUndefined() }) it('accept properties',()=>{untilgroup = factory.group('Red', Comprador) Expect(Group.Features).toEqual(Buyer) }) it('set the group ID in the message',()=>{untilgroup = factory.group('coolKidsId', { cool kids:TRUE}) expected (group.groupId).toEqual('coolKidsId') }) }) describe('book page',()=>{ proof('create page events',()=>{untilpage = factory.page ('Category','Name') Wait(page.features).toBeUndefined() Wait(page.type).toEqual('book page') expected(Page.Event).toBeUndefined() expected(Page.Name).toEqual('Name') expected(Page.Category).toEqual('Category') }) Es('accept properties',()=>{untilpage = factory.page ('Category','Name', zapatos) Expect(page.properties).toEqual(shoes) }) it('ignore category and page if not approved',()=>{untilpage = factory.page (Null,Null) expected(Page.Category).toBeUndefined() expected(Page.Name).toBeUndefined() }) }) describe('identify',()=>{ proof('identify created events',()=>{untilidentify = factory.identify ('Red', Käufer) Expect(identify.traits).toEqual(Käufer) Expect(identify.properties).toBeUndefined() Expect(identify.type).toEqual('identify') Expect(identify.event).toBeUndefined() }) }) describe('Lane',()=>{ proof('Create trace events',()=>{untiltrack = factory.track('Order completed', shoes) expected(track.event).toEqual('Order completed') Wait(Track.Features).toEqual(Shoes) Wait(Track.Features).ToBeUndefined() Wait(Track.Type).toEqual('Lane') }) proof('add a message ID',()=>{untiltrack = factory.track('Order completed', zapatos) expected(track.messageId).toContain('ajs-next') }) proof('add random message id even when randomly mocked',()=>{ es.useFakeTimers() es.spyOn(uuid,'v4').mock implementation(()=> 'abc-123')// fake timer and fake uuid => samewait(factory.track('Order completed', zapatos).messageId).toEqual( factory.track('Order completed', shoes).messageId )// restore function UUID => not equaljest.restoreAllMocks() esperado (factory.track('Order completed', Schuhe).messageId).not.toEqual( factory.track('Order completed', shoes).messageId )// restore timer function => raggedjest.useRealTimers() esperado (factory.track('Order completed', Schuhe).messageId).not.toEqual( factory.track('Order completed', shoes).messageId ) }) test('Message IDs are random',()=>{untilidentifiers = area (0,200).Map(()=>Factory.Track ('Order completed', Schuhe).messageId ) Expect(uniq(ids)).toHaveLength(200) }) proof('set a user ID',()=>{ user.identify ('007')untiltrack = factory.track('Order completed', shoes) expected (track.userId).toEqual('007') }) proof('set an anonymous ID',()=>{untiltrack = factory.track('Order completed', Schuhe) Expect(track.userId).toBeUndefined() Expect(track.anonymousId).toEqual(user.anonymousId()) }) test('Set options in context',()=>{untiltrack = factory.track('Order completed', shoes, {opt1:TRUE, }) expected(clue.context).toEqual({ opt1:TRUE}) }) proof('integration sets',()=>{untiltrack = factory.track('Order completed', shoes, {}, { amplitude:INCORRECT, } ) Expect(track.integrations).toEqual({ Amplitude:INCORRECT}) }) proof('join `options` and `integrations`' integrations,()=>{untiltrack = factory.track('Order completed', shoes, {opt1:TRUE, integration: { Breadth:INCORRECT, }, }, { Google analytics:TRUE, Amplitude:TRUE, } ) Expect(track.integrations).toEqual({ googleAnalytics:TRUE, Amplitude:INCORRECT, }) }) proof('Do not send integration configuration overrides from initialization',()=>{untiltrack = factory.track('Order completed', shoes, { integrations: { breadth: { sessionId:'sesion_123', }, }, }, {'Segmento.io': { apiHost:'habit', }, Google analytics:INCORRECT,'Kunde.io': {}, } ) Expect(track.integrations).toEqual({// Do not pass the global configuration of Segment.io 'Segmento.io':TRUE,// Accept amplitude event level settingsbreadth: { session id:'sesion_123', },// Pass the Google Analytics preferenceAnalytical Google:INCORRECT,// empty objects are still valid 'Kunde.io':TRUE, }) }) proof('should put foreign options in 'context',()=>{untiltrack = factory.track('Order completed', shoes, {opt1:TRUE, opt2:'?', integration: { Breadth:INCORRECT, }, }) expected(hint.context).toEqual({ opt1:TRUE, opt2:'?'}) }) proof('shouldn't move known options to 'context',()=>{untiltrack = factory.track('Order completed', shoes, {opt1:TRUE, opt2:'?', integration: { Breadth:INCORRECT, }, anonymous ID:'anon-1', Timestamp:nuevo Given(), }) Expect(track.context).toEqual({ opt1:TRUE, opt2:'?'}) }) proof('accept anonymous identification',()=>{untiltrack = factory.track('Order completed', zapatos, { Anonymous ID:'anon-1', }) expected(hint.context).toEqual({}) expected(hint.anonymousId).toEqual('anon-1') }) proof('accept a timestamp',()=>{untiltimestamp =nuevo Given()untiltrack = factory.track('Order completed', Schuhe, { Zeitstempel, }) Expect(track.context).toEqual({}) Expect(track.timestamp).toEqual(timestamp) }) test('accept properties',()=>{untiltrack = factory.track('Order completed', shoes, { properties: { cell:'?', }, }) expected(hint.context?.characteristics).toEqual({ cell:'?', }) }) proof('accepts a context object',()=>{untiltrack = factory.track('Order completed', shoes, { context: { library: { name:'ajs-next', Execution:'0.1.0', }, }, }) Expect(track.context).toEqual({ Bibliothek: { Name:'ajs-next', Execution:'0.1.0', }, }) }) proof('connect a context object',()=>{untiltrack = factory.track('Order completed', shoes, {foreign property:'??', context: { interiorProp:'?', library: { name:'ajs-next', Execution:'0.1.0', }, }, }) Expect(track.context).toEqual({ Bibliothek: { Name:'ajs-next', Execution:'0.1.0', }, foreignproperty:'??', interiorProp:'?', }) }) }) describe('normalize',function(){untilMessage: SegmentEvent = {type:'Lane'}untiloptions: options = (message.options = {}) describe ('News',function(){Es('should merge original with normalized',function(){ msg.userId ='Benutzer ID'opts.integrations = {Segmento:TRUE}untilnormalized = factory['normalize'](message) expected(normalized.messageId?.length).toBeGreaterThanOrEqual(41)// 'ajs-next-md5(Inhalt + [UUID])' extinguishnormalized.messageId Expect(normalized).toStrictEqual({ Integrationen: { Segment:TRUE},type:'Lane', Benutzer identification:'Benutzer ID', context: {}, }) }) }) })})
Example #28
source file:LogRows.test.tsxFrom grafana-Chinese under the Apache License 2.0 | 4You | ![]() ![]() |
describe('Record Rows',()=>{Es('Render the sails',()=>{untilZeilen: LogRowModel[] = [makeLog({ uid:'1' }), makeLog({ uid: '2' }), makeLog({ uid: '3'})];untilwrapper = mount( <LogRows logRows={filas} dedupStrategy={LogsDedupStrategy.none} highlighterExpressions={[]} showLabels={INCORRECT} showTime={INCORRECT} involveMensajeRegistro={TRUE} timezone={'coordinated world time'}/>); expected(Wrapper.find(LogRow).Length).toBe(3); expect( wrapper.contains('Log message 1')).toBeTruthy(); expect( wrapper.contains('log message 2')).toBeTruthy(); expect( wrapper.contains('log message 3')).toBeTruthy(); }); Él('Render lines only a limited number of lines at the beginning',()=>{untilZeilen: LogRowModel[] = [makeLog({ uid:'1' }), makeLog({ uid: '2' }), makeLog({ uid: '3'})]; broma.useFakeTimers();untilwrapper = mount( <LogRows logRows={filas} dedupStrategy={LogsDedupStrategy.none} highlighterExpressions={[]} showLabels={INCORRECT} showTime={INCORRECT} involveMensajeRegistro={TRUE} timezone={'coordinated world time'} PreviewLimit={1}/>); expected(Wrapper.find(LogRow).Length).toBe(1); expect( wrapper.contains('Log message 1')).toBeTruthy(); is.runAllTimers(); container.update(); expected(Wrapper.find(LogRow).Length).toBe(3); expect( wrapper.contains('Log message 1')).toBeTruthy(); expect( wrapper.contains('log message 2')).toBeTruthy(); expect( wrapper.contains('log message 3')).toBeTruthy(); is.useRealTimes(); }); Is('process deduplicated rows if any',()=>{untilZeilen: LogRowModel[] = [makeLog({ uid:'1' }), makeLog({ uid: '2' }), makeLog({ uid: '3'})];until dedupedRows: LogRowModel[] = [makeLog({ uid: '4' }), makeLog({ uid: '5'})];untilwrapper = mount( <LogRows logRows={filas} deduplicatedRows={dedupedRows} dedupStrategy={LogsDedupStrategy.none} highlighterExpressions={[]} showLabels={INCORRECT} showTime={INCORRECT} involveMensajeRegistro={TRUE} timezone={'coordinated world time'}/>); expected(Wrapper.find(LogRow).Length).toBe(2); expect( wrapper.contains('Log message 4')).toBeTruthy(); expect( wrapper.contains('log message 5')).toBeTruthy(); }); Él('Default preview limit renders',()=>{// PREVIEW_LIMIT * 2 is there because otherwise we just render all rows untilRows: LogRowModel[] = range(PREVIEW_LIMIT *2+1).Map(Number=> makeLog({ uid: num.toString() })); untilwrapper = mount( <LogRows logRows={filas} dedupStrategy={LogsDedupStrategy.none} highlighterExpressions={[]} showLabels={INCORRECT} showTime={INCORRECT} involveMensajeRegistro={TRUE} timezone={'coordinated world time'}/>); expected(Wrapper.find(LogRow).Length).toBe(100); });});
Example #29
source file:barra lateral.tsxBy project-papua with Apache License 2.0 | 4You | ![]() ![]() |
Sidebar: React.FC<Accessories> =(accessories) =>{until{sides} = accessoriesuntil{ translateByID, form, pageIndex, setPage, finalization } = useContext(FormContext)until{ language, setLanguage } = useContext(LanguageContext)untiltamaño = useContext (ResponsiveContext)untilpageCurrent = Pages[PageIndex]untilpercentage =mathematics.floor((pagesIndex / (pages.length -1)) *100)untilcanClickPage =(me: number) =>{go backArea(0, i).each((Index) =>completion[index]) }go back( <Box flex={{ Schrumpfen: 0 }} margin={size === 'small' ? { top: 'small' } : { left: 'small' }} direction="column" width={size == = 'klein' ? '100%' : '350px'} > <Kartenrand={{ unten: 'klein' }} pad={{ horizontal: Größe === 'klein' ? '24px' : 'mittel', vertical : 'klein' }}> <Markdown>{translateByID('demo-warning')}</Markdown> </Card> <Card pad="medium"> {form.seal && ( <Box margin={{ bottom : 'medio' }}> <Image src={form.seal} style={{ maxHeight: '175px', maxWidth: '100%', objectFit: 'contain' }} /> </Box> )} <Box > <Heading level={4} margin="none"> {translateByID('language')} </Heading> <StyledSelect a11yTitle="seleccionar idioma" margin={{ top: 'xsmall' }} options={idiomas} labelKey ="title" valueKey={{ key: 'value', Reduce: true }} value={language} onChange={({ value }) => setLanguage(value)} /> </Box> <Box margin= { { arriba: 'medio' }}> <Dirección del cuadro="fila" justificar="entre"> <Nivel de encabezado={4} margen="ninguno"> {translateByID('progreso')} </Título> <Margen del párrafo ="ninguno">{percent}%</Paragraph> </Box> <Box margin={{ top: 'xsmall' }} style={{ width: '100%', height: '12px', borderRadius: ' 12px', Hintergrund: '#F2F2F2' }} > <Box style={{ width: '${percent}%`, height: '100%', borderRadius: '12px', background: '#3A80C2' }} / > </Box> </Box> <Box margin={{ top: 'mediano' }}> {tamaño === 'pequeño' && páginas.longitud > 2 ? ( <> {/* Auf kleinen Bildschirmen reduzieren wir die Abschnittstitel auf ein Select */} <Heading level={4} margin="none"> {translateByID('section')} </Heading> <StyledSelect a11yTitle= "Bereich auswählen" margin={{ top: 'xsmall' }} options={pages.map((page, i) => ({ page, i, disabled: !canClickPage(i) }))} labelKey="page " valueKey ={{ key: 'i', Reduce: true }} disabledKey="disabled" value={pageIndex as any} /* Diese Typdefinitionen unterstützen keine Werte als Zahlen */ // TODO: In der Produktion hinzufügen ein `canClickPage(i ) && ` unten, um zu verhindern, dass Leute nach vorne springen. onChange={({ value: i }) => setPage(i)} /> </> ) : ( /* Auf größeren Bildschirmen zeigen wir alle Abschnittstitel als Liste */ pages.map((page, i) => { return ( <Text style={{ cursor: canClickPage(i) ? 'pointer' : 'not-allowed', opacity: currentPage === page ? '100 %' : canClickPage(i) ? '50%' : '20%', }} // TODO: Fügen Sie in der Produktion unten ein `canClickPage(i) && ` hinzu, um zu verhindern, dass Leute nach vorne springen { () => setPage(i)} margin={{ bottom: 'xsmall' }} key={page} > {page} </Text> ) }) )} </Box> </Card> </Box > )}