How to use Identity method in Cypress

Best JavaScript code snippet using cypress

createIdentityPool.js

Source:createIdentityPool.js Github

copy

Full Screen

1#!/usr/bin/env node2const path = require('path');3const awscommon = require(path.join(__dirname, 'awscommonutils'));4const fs = require('fs');5const YAML = require('yamljs');6const AwsRequest = require(path.join(__dirname, 'AwsRequest'));7const argv = require('yargs')8.usage('Create the identity pools required for the project.\nIf identity pools with the same name already exist a new pool will not be created and the existing pool infomation will be used.\nUsage: $0 [options]')9.alias('s','baseDefinitionsFile')10.describe('s','yaml file that contains information about your API')11.default('s','./base.definitions.yaml')12.help('h')13.alias('h', 'help')14.argv;15if (!fs.existsSync(argv.baseDefinitionsFile)) {16 throw new Error("Base definitions file \"" + argv.baseDefinitionsFile + "\" not found.");17}18var baseDefinitions = YAML.load(argv.baseDefinitionsFile);19var AWSCLIUserProfile = "default";20if (!awscommon.verifyPath(baseDefinitions,['environment', 'AWSCLIUserProfile'],'s').isVerifyError) {21 AWSCLIUserProfile = baseDefinitions.environment.AWSCLIUserProfile;22} else {23 console.log("using \"default\" AWSCLIUserProfile");24}25console.log("## Creating Identity Pools ##");26awscommon.verifyPath(baseDefinitions, ['cognitoIdentityPoolInfo', 'identityPools'], 'o', "definitions file \""+argv.baseDefinitionsFile+"\"").exitOnError();27var numIdentityPools = Object.keys(baseDefinitions.cognitoIdentityPoolInfo.identityPools).length;28var successDecCount = numIdentityPools;29// first lets get the identity pools to see if one with our name exists already30getIdentityPools(function (serverIdentityPools) {31 // now see which ones are valid and which ones need to be created32 var poolCreateRequests = [];33 Object.keys(baseDefinitions.cognitoIdentityPoolInfo.identityPools).forEach(function (identityPoolKey) {34 var identityPoolName;35 if (awscommon.isValidAWSResourceNamePrefix(baseDefinitions, argv.baseDefinitionsFile)) {36 identityPoolName = baseDefinitions.environment.AWSResourceNamePrefix + identityPoolKey;37 } else {38 throw new Error("Please assign a AWSResourceNamePrefix at 'environment.AWSResourceNamePrefix' in base definitions file '" + argv.baseDefinitionsFile + "'.");39 }40 var poolDef = baseDefinitions.cognitoIdentityPoolInfo.identityPools[identityPoolKey];41 if (serverIdentityPools) {42 for (var index = 0; index < serverIdentityPools.IdentityPools.length; index ++) {43 if (identityPoolName === serverIdentityPools.IdentityPools[index].IdentityPoolName) {44 baseDefinitions.cognitoIdentityPoolInfo.identityPools[identityPoolKey].identityPoolId = serverIdentityPools.IdentityPools[index].IdentityPoolId;45 console.log("Found identity pool \"" + identityPoolName + "\" on aws.");46 setRoles(identityPoolKey);47 updateRolePolicyDocumentStatementConditions(identityPoolKey);48 numIdentityPools --;49 successDecCount --;50 if (numIdentityPools === 0) {51 writeout();52 return;53 } else {54 break;55 }56 }57 }58 }59 // validate to make sure we have everything60 awscommon.verifyPath(poolDef, ['allowUnauthedIdentities'], 'b', "identity pool definition \"" + identityPoolKey + "\"").exitOnError();61 awscommon.verifyPath(poolDef, ['authProviders'], 'o', "identity pool definition \"" + identityPoolKey + "\"").exitOnError();62 var params={63 'identity-pool-name': {type: 'string', value: identityPoolName},64 'profile': {type: 'string', value:AWSCLIUserProfile}65 };66 params[(poolDef.allowUnauthedIdentities ? 'allow-unauthenticated-identities': 'no-allow-unauthenticated-identities')] = {type: 'none'};67 Object.keys(poolDef.authProviders).forEach(function(authProvider) {68 switch (authProvider) {69 case 'custom':70 awscommon.verifyPath(poolDef.authProviders,['custom', 'developerProvider'],'s','custom developer provider for pool "' + identityPoolKey + '""').exitOnError();71 params['developer-provider-name'] = {type: 'string', value:poolDef.authProviders.custom.developerProvider};72 break;73 default:74 }75 });76 poolCreateRequests.push(77 AwsRequest.createRequest({78 serviceName:'cognito-identity',79 functionName:'create-identity-pool',80 context: {poolName: identityPoolName, poolKey: identityPoolKey},81 returnSchema:'json',82 returnValidation:[{path:['IdentityPoolId'], type:'s'}],83 parameters:params84 })85 );86 });87 AwsRequest.createBatch(poolCreateRequests, function (batch) {88 batch.requestArray.forEach(function (request) {89 if (request.response.error) {90 console.log(request.response.error);91 console.log("Failed to create pool " + request.context.poolName + ".");92 } else {93 console.log("Successfully created pool " + request.context.poolName + ".");94 successDecCount --;95 baseDefinitions.cognitoIdentityPoolInfo.identityPools[request.context.poolKey].identityPoolId = request.response.parsedJSON.IdentityPoolId;96 setRoles(request.context.poolKey);97 updateRolePolicyDocumentStatementConditions(request.context.poolKey);98 }99 });100 writeout();101 }).startRequest();102});103function writeout() {104 // now delete role105 awscommon.updateFile(argv.baseDefinitionsFile, function () {106 return YAML.stringify(baseDefinitions, 15);107 }, function (backupErr, writeErr) {108 if (backupErr) {109 console.log("Could not create backup of \"" + argv.baseDefinitionsFile + "\". pool id was not updated.");110 throw backupErr;111 }112 if (writeErr) {113 console.log("Unable to write updated definitions file.");114 throw writeErr;115 }116 if (successDecCount !== 0) {117 console.log("Some creation operations failed.");118 }119 });120}121function getIdentityPools (doneCallback) {122 AwsRequest.createRequest({123 serviceName:'cognito-identity',124 functionName:'list-identity-pools',125 returnSchema:'json',126 returnValidation:[{path:['IdentityPools','IdentityPoolId'], type:'s'},127 {path:['IdentityPools','IdentityPoolName'], type:'s'}],128 parameters:{129 'max-results': {type: 'string', value:'15'},130 'profile': {type: 'string', value:AWSCLIUserProfile}131 }132 }, function(request) {133 if (request.response.error) {134 console.log(request.response.error);135 doneCallback(null);136 return;137 }138 doneCallback(request.response.parsedJSON);139 }).startRequest();140}141function setRoles(identityPoolKey){142 if (!awscommon.verifyPath(baseDefinitions, ['cognitoIdentityPoolInfo', 'identityPools', identityPoolKey, 'roles'], 'o',"").isVerifyError) {143 var roles = {};144 // TODO GET ROLE ARN!!!145 roles = baseDefinitions.cognitoIdentityPoolInfo.identityPools[identityPoolKey].roles;146 var identityPoolRoles = {};147 Object.keys(roles).forEach(function (roleType) {148 identityPoolRoles[roleType] = baseDefinitions.cognitoIdentityPoolInfo.roleDefinitions[roles[roleType]].arnRole;149 });150 AwsRequest.createRequest({151 serviceName: 'cognito-identity',152 functionName: 'set-identity-pool-roles',153 context: {poolKey: identityPoolKey},154 returnSchema:'none',155 parameters: {156 'identity-pool-id' : {type:'string', value:baseDefinitions.cognitoIdentityPoolInfo.identityPools[identityPoolKey].identityPoolId},157 'roles' : {type: 'JSONObject', value:identityPoolRoles},158 'profile': {type: 'string', value:AWSCLIUserProfile}159 }160 },161 function (roleReq) {162 if (roleReq.response.error) {163 throw roleReq.response.error;164 } else {165 console.log("Set Roles for \"" + roleReq.context.poolKey + "\"");166 }167 }).startRequest();168 }169}170function updateRolePolicyDocumentStatementConditions(identityPoolKey) {171 // first get the role172 var roles = baseDefinitions.cognitoIdentityPoolInfo.identityPools[identityPoolKey].roles;173 Object.keys(roles).forEach(function (roleType) {174 var role = roles[roleType];175 if (!awscommon.verifyPath(baseDefinitions,['cognitoIdentityPoolInfo','identityPools',identityPoolKey,'rolePolicyDocumentStatementConditions',role],'a').isVerifyError) {176 // get the role177 var roleName;178 if (awscommon.isValidAWSResourceNamePrefix(baseDefinitions, argv.baseDefinitionsFile)) {179 roleName = baseDefinitions.environment.AWSResourceNamePrefix + role;180 }181 AwsRequest.createRequest({182 serviceName: 'iam',183 functionName: 'get-role',184 context: {poolKey: identityPoolKey, roleKey:role, roleName: roleName},185 returnSchema:'json',186 parameters: {187 'role-name' : {type:'string', value:roleName},188 'profile': {type: 'string', value:AWSCLIUserProfile}189 }190 },191 function (roleReq) {192 if (roleReq.response.error) {193 console.log("no policy document statemets for role \"" + roleReq.context.roleKey + "to update. Is the role created?");194 console.log(roleReq.response.error);195 } else {196 if (!awscommon.verifyPath(roleReq.response.parsedJSON,['Role','AssumeRolePolicyDocument','Statement'],'a').isVerifyError) {197 // for each matching policy action add the conditions198 var statementArray = roleReq.response.parsedJSON.Role.AssumeRolePolicyDocument.Statement;199 var conditionArray = baseDefinitions.cognitoIdentityPoolInfo.identityPools[roleReq.context.poolKey].rolePolicyDocumentStatementConditions[role];200 for (var conditionIndex = 0; conditionIndex < conditionArray.length; conditionIndex ++) {201 for (var statementIndex = 0; statementIndex < statementArray.length; statementIndex ++) {202 if (statementArray[statementIndex].Action === conditionArray[conditionIndex].Action) {203 statementArray[statementIndex].Condition = conditionArray[conditionIndex].Condition;204 // we may want to replace the identity pool ID in some of the conditions205 Object.keys(statementArray[statementIndex].Condition).forEach(function(conditionType) {206 var theCondition = statementArray[statementIndex].Condition[conditionType];207 Object.keys(theCondition).forEach(function(conditionTypeParam) {208 var val = theCondition[conditionTypeParam];209 if (val === '$identityPoolId') {210 theCondition[conditionTypeParam] = baseDefinitions.cognitoIdentityPoolInfo.identityPools[roleReq.context.poolKey].identityPoolId;211 }212 });213 });214 }215 }216 }217 // UPDATE THE MODIFIED POLICY218 AwsRequest.createRequest({219 serviceName: 'iam',220 functionName: 'update-assume-role-policy',221 context: {poolKey: roleReq.context.poolKey, roleName:roleReq.context.roleName},222 returnSchema:'none',223 parameters: {224 'role-name': {type:'string', value:roleReq.context.roleName},225 'policy-document': {type: 'JSONObject', value:roleReq.response.parsedJSON.Role.AssumeRolePolicyDocument},226 'profile': {type: 'string', value:AWSCLIUserProfile},227 }228 },229 function (putPolReq) {230 if (putPolReq.response.error) {231 console.log("Error updating policy doc for role \"" + putPolReq.context.roleName + "\"");232 console.log(putPolReq.response.error);233 } else {234 console.log("Updated policy doc for role \"" + putPolReq.context.roleName + "\"");235 }236 }).startRequest();237 }238 }239 }).startRequest();240 }241 });...

Full Screen

Full Screen

IdentityHashMap.js

Source:IdentityHashMap.js Github

copy

Full Screen

1$_L(["java.util.AbstractMap","$.AbstractSet","$.Iterator","$.Map","$.MapEntry"],"java.util.IdentityHashMap",["java.lang.IllegalArgumentException","$.IllegalStateException","java.util.AbstractCollection","$.ConcurrentModificationException","java.util.MapEntry.Type","java.util.NoSuchElementException"],function(){2c$=$_C(function(){3this.elementData=null;4this.$size=0;5this.threshold=0;6this.modCount=0;7$_Z(this,arguments);8},java.util,"IdentityHashMap",java.util.AbstractMap,[java.util.Map,java.io.Serializable,Cloneable]);9$_K(c$,10function(){11this.construct(21);12});13$_K(c$,14function(maxSize){15$_R(this,java.util.IdentityHashMap,[]);16if(maxSize>=0){17this.$size=0;18this.threshold=this.getThreshold(maxSize);19this.elementData=this.newElementArray(this.computeElementArraySize());20}else{21throw new IllegalArgumentException();22}},"~N");23$_M(c$,"getThreshold",24($fz=function(maxSize){25return maxSize>3?maxSize:3;26},$fz.isPrivate=true,$fz),"~N");27$_M(c$,"computeElementArraySize",28($fz=function(){29return(Math.floor((this.threshold*10000)/7500))*2;30},$fz.isPrivate=true,$fz));31$_M(c$,"newElementArray",32($fz=function(s){33return new Array(s);34},$fz.isPrivate=true,$fz),"~N");35$_K(c$,36function(map){37this.construct(map.size()<6?11:map.size()*2);38this.putAllImpl(map);39},"java.util.Map");40$_M(c$,"massageValue",41($fz=function(value){42return((value===java.util.IdentityHashMap.NULL_OBJECT)?null:value);43},$fz.isPrivate=true,$fz),"~O");44$_V(c$,"clear",45function(){46this.$size=0;47for(var i=0;i<this.elementData.length;i++){48this.elementData[i]=null;49}50this.modCount++;51});52$_V(c$,"containsKey",53function(key){54if(key==null){55key=java.util.IdentityHashMap.NULL_OBJECT;56}var index=this.findIndex(key,this.elementData);57return this.elementData[index]===key;58},"~O");59$_V(c$,"containsValue",60function(value){61if(value==null){62value=java.util.IdentityHashMap.NULL_OBJECT;63}for(var i=1;i<this.elementData.length;i=i+2){64if(this.elementData[i]===value){65return true;66}}67return false;68},"~O");69$_V(c$,"get",70function(key){71if(key==null){72key=java.util.IdentityHashMap.NULL_OBJECT;73}var index=this.findIndex(key,this.elementData);74if(this.elementData[index]===key){75var result=this.elementData[index+1];76return this.massageValue(result);77}return null;78},"~O");79$_M(c$,"getEntry",80($fz=function(key){81if(key==null){82key=java.util.IdentityHashMap.NULL_OBJECT;83}var index=this.findIndex(key,this.elementData);84if(this.elementData[index]===key){85return this.getEntry(index);86}return null;87},$fz.isPrivate=true,$fz),"~O");88$_M(c$,"getEntry",89($fz=function(index){90var key=this.elementData[index];91var value=this.elementData[index+1];92if(key===java.util.IdentityHashMap.NULL_OBJECT){93key=null;94}if(value===java.util.IdentityHashMap.NULL_OBJECT){95value=null;96}return new java.util.IdentityHashMap.IdentityHashMapEntry(key,value);97},$fz.isPrivate=true,$fz),"~N");98$_M(c$,"findIndex",99($fz=function(key,array){100var length=array.length;101var index=this.getModuloHash(key,length);102var last=(index+length-2)%length;103while(index!=last){104if(array[index]===key||(array[index]==null)){105break;106}index=(index+2)%length;107}108return index;109},$fz.isPrivate=true,$fz),"~O,~A");110$_M(c$,"getModuloHash",111($fz=function(key,length){112return((System.identityHashCode(key)&0x7FFFFFFF)%(Math.floor(length/2)))*2;113},$fz.isPrivate=true,$fz),"~O,~N");114$_V(c$,"put",115function(key,value){116var _key=key;117var _value=value;118if(_key==null){119_key=java.util.IdentityHashMap.NULL_OBJECT;120}if(_value==null){121_value=java.util.IdentityHashMap.NULL_OBJECT;122}var index=this.findIndex(_key,this.elementData);123if(this.elementData[index]!==_key){124this.modCount++;125if(++this.$size>this.threshold){126this.rehash();127index=this.findIndex(_key,this.elementData);128}this.elementData[index]=_key;129this.elementData[index+1]=null;130}var result=this.elementData[index+1];131this.elementData[index+1]=_value;132return this.massageValue(result);133},"~O,~O");134$_V(c$,"putAll",135function(map){136this.putAllImpl(map);137},"java.util.Map");138$_M(c$,"rehash",139($fz=function(){140var newlength=this.elementData.length<<1;141if(newlength==0){142newlength=1;143}var newData=this.newElementArray(newlength);144for(var i=0;i<this.elementData.length;i=i+2){145var key=this.elementData[i];146if(key!=null){147var index=this.findIndex(key,newData);148newData[index]=key;149newData[index+1]=this.elementData[i+1];150}}151this.elementData=newData;152this.computeMaxSize();153},$fz.isPrivate=true,$fz));154$_M(c$,"computeMaxSize",155($fz=function(){156this.threshold=(Math.floor((Math.floor(this.elementData.length/ 2)) * 7500 /10000));157},$fz.isPrivate=true,$fz));158$_V(c$,"remove",159function(key){160if(key==null){161key=java.util.IdentityHashMap.NULL_OBJECT;162}var hashedOk;163var index;164var next;165var hash;166var result;167var object;168index=next=this.findIndex(key,this.elementData);169if(this.elementData[index]!==key){170return null;171}result=this.elementData[index+1];172var length=this.elementData.length;173while(true){174next=(next+2)%length;175object=this.elementData[next];176if(object==null){177break;178}hash=this.getModuloHash(object,length);179hashedOk=hash>index;180if(next<index){181hashedOk=hashedOk||(hash<=next);182}else{183hashedOk=hashedOk&&(hash<=next);184}if(!hashedOk){185this.elementData[index]=object;186this.elementData[index+1]=this.elementData[next+1];187index=next;188}}189this.$size--;190this.modCount++;191this.elementData[index]=null;192this.elementData[index+1]=null;193return this.massageValue(result);194},"~O");195$_V(c$,"entrySet",196function(){197return new java.util.IdentityHashMap.IdentityHashMapEntrySet(this);198});199$_V(c$,"keySet",200function(){201if(this.$keySet==null){202this.$keySet=(($_D("java.util.IdentityHashMap$1")?0:java.util.IdentityHashMap.$IdentityHashMap$1$()),$_N(java.util.IdentityHashMap$1,this,null));203}return this.$keySet;204});205$_V(c$,"values",206function(){207if(this.valuesCollection==null){208this.valuesCollection=(($_D("java.util.IdentityHashMap$2")?0:java.util.IdentityHashMap.$IdentityHashMap$2$()),$_N(java.util.IdentityHashMap$2,this,null));209}return this.valuesCollection;210});211$_V(c$,"equals",212function(object){213if(this===object){214return true;215}if($_O(object,java.util.Map)){216var map=object;217if(this.size()!=map.size()){218return false;219}var set=this.entrySet();220return set.equals(map.entrySet());221}return false;222},"~O");223$_M(c$,"clone",224function(){225try{226return $_U(this,java.util.IdentityHashMap,"clone",[]);227}catch(e){228if($_O(e,CloneNotSupportedException)){229return null;230}else{231throw e;232}233}234});235$_V(c$,"isEmpty",236function(){237return this.$size==0;238});239$_V(c$,"size",240function(){241return this.$size;242});243$_M(c$,"putAllImpl",244($fz=function(map){245if(map.entrySet()!=null){246$_U(this,java.util.IdentityHashMap,"putAll",[map]);247}},$fz.isPrivate=true,$fz),"java.util.Map");248c$.$IdentityHashMap$1$=function(){249$_H();250c$=$_W(java.util,"IdentityHashMap$1",java.util.AbstractSet);251$_V(c$,"contains",252function(object){253return this.b$["java.util.IdentityHashMap"].containsKey(object);254},"~O");255$_V(c$,"size",256function(){257return this.b$["java.util.IdentityHashMap"].size();258});259$_V(c$,"clear",260function(){261this.b$["java.util.IdentityHashMap"].clear();262});263$_V(c$,"remove",264function(key){265if(this.b$["java.util.IdentityHashMap"].containsKey(key)){266this.b$["java.util.IdentityHashMap"].remove(key);267return true;268}return false;269},"~O");270$_V(c$,"iterator",271function(){272return new java.util.IdentityHashMap.IdentityHashMapIterator((($_D("java.util.IdentityHashMap$1$1")?0:java.util.IdentityHashMap.$IdentityHashMap$1$1$()),$_N(java.util.IdentityHashMap$1$1,this,null)),this.b$["java.util.IdentityHashMap"]);273});274c$=$_P();275};276c$.$IdentityHashMap$1$1$=function(){277$_H();278c$=$_W(java.util,"IdentityHashMap$1$1",null,java.util.MapEntry.Type);279$_V(c$,"get",280function(entry){281return entry.key;282},"java.util.MapEntry");283c$=$_P();284};285c$.$IdentityHashMap$2$=function(){286$_H();287c$=$_W(java.util,"IdentityHashMap$2",java.util.AbstractCollection);288$_V(c$,"contains",289function(object){290return this.b$["java.util.IdentityHashMap"].containsValue(object);291},"~O");292$_V(c$,"size",293function(){294return this.b$["java.util.IdentityHashMap"].size();295});296$_V(c$,"clear",297function(){298this.b$["java.util.IdentityHashMap"].clear();299});300$_V(c$,"iterator",301function(){302return new java.util.IdentityHashMap.IdentityHashMapIterator((($_D("java.util.IdentityHashMap$2$1")?0:java.util.IdentityHashMap.$IdentityHashMap$2$1$()),$_N(java.util.IdentityHashMap$2$1,this,null)),this.b$["java.util.IdentityHashMap"]);303});304$_V(c$,"remove",305function(object){306var it=this.iterator();307while(it.hasNext()){308if(object===it.next()){309it.remove();310return true;311}}312return false;313},"~O");314c$=$_P();315};316c$.$IdentityHashMap$2$1$=function(){317$_H();318c$=$_W(java.util,"IdentityHashMap$2$1",null,java.util.MapEntry.Type);319$_V(c$,"get",320function(entry){321return entry.value;322},"java.util.MapEntry");323c$=$_P();324};325$_H();326c$=$_T(java.util.IdentityHashMap,"IdentityHashMapEntry",java.util.MapEntry);327$_V(c$,"equals",328function(a){329if(this===a){330return true;331}if($_O(a,java.util.Map.Entry)){332var b=a;333return(this.key===b.getKey())&&(this.value===b.getValue());334}return false;335},"~O");336$_V(c$,"hashCode",337function(){338return System.identityHashCode(this.key)^System.identityHashCode(this.value);339});340$_V(c$,"toString",341function(){342return this.key+"="+this.value;343});344c$=$_P();345$_H();346c$=$_C(function(){347this.position=0;348this.lastPosition=0;349this.associatedMap=null;350this.expectedModCount=0;351this.type=null;352this.canRemove=false;353$_Z(this,arguments);354},java.util.IdentityHashMap,"IdentityHashMapIterator",null,java.util.Iterator);355$_K(c$,356function(a,b){357this.associatedMap=b;358this.type=a;359this.expectedModCount=b.modCount;360},"java.util.MapEntry.Type,java.util.IdentityHashMap");361$_V(c$,"hasNext",362function(){363while(this.position<this.associatedMap.elementData.length){364if(this.associatedMap.elementData[this.position]==null){365this.position+=2;366}else{367return true;368}}369return false;370});371$_M(c$,"checkConcurrentMod",372function(){373if(this.expectedModCount!=this.associatedMap.modCount){374throw new java.util.ConcurrentModificationException();375}});376$_V(c$,"next",377function(){378this.checkConcurrentMod();379if(!this.hasNext()){380throw new java.util.NoSuchElementException();381}var a=this.associatedMap.getEntry(this.position);382this.lastPosition=this.position;383this.position+=2;384this.canRemove=true;385return this.type.get(a);386});387$_V(c$,"remove",388function(){389this.checkConcurrentMod();390if(!this.canRemove){391throw new IllegalStateException();392}this.canRemove=false;393this.associatedMap.remove(this.associatedMap.elementData[this.lastPosition]);394this.position=this.lastPosition;395this.expectedModCount++;396});397c$=$_P();398$_H();399c$=$_C(function(){400this.associatedMap=null;401$_Z(this,arguments);402},java.util.IdentityHashMap,"IdentityHashMapEntrySet",java.util.AbstractSet);403$_K(c$,404function(a){405$_R(this,java.util.IdentityHashMap.IdentityHashMapEntrySet,[]);406this.associatedMap=a;407},"java.util.IdentityHashMap");408$_M(c$,"hashMap",409function(){410return this.associatedMap;411});412$_V(c$,"size",413function(){414return this.associatedMap.$size;415});416$_V(c$,"clear",417function(){418this.associatedMap.clear();419});420$_V(c$,"remove",421function(a){422if(this.contains(a)){423this.associatedMap.remove((a).getKey());424return true;425}return false;426},"~O");427$_V(c$,"contains",428function(a){429if($_O(a,java.util.Map.Entry)){430var b=this.associatedMap.getEntry((a).getKey());431return b!=null&&b.equals(a);432}return false;433},"~O");434$_V(c$,"iterator",435function(){436return new java.util.IdentityHashMap.IdentityHashMapIterator((($_D("java.util.IdentityHashMap$IdentityHashMapEntrySet$1")?0:java.util.IdentityHashMap.IdentityHashMapEntrySet.$IdentityHashMap$IdentityHashMapEntrySet$1$()),$_N(java.util.IdentityHashMap$IdentityHashMapEntrySet$1,this,null)),this.associatedMap);437});438c$.$IdentityHashMap$IdentityHashMapEntrySet$1$=function(){439$_H();440c$=$_W(java.util,"IdentityHashMap$IdentityHashMapEntrySet$1",null,java.util.MapEntry.Type);441$_V(c$,"get",442function(a){443return a;444},"java.util.MapEntry");445c$=$_P();446};447c$=$_P();448$_S(c$,449"DEFAULT_MAX_SIZE",21,450"loadFactor",7500);451c$.NULL_OBJECT=c$.prototype.NULL_OBJECT=new JavaObject();...

Full Screen

Full Screen

core.js

Source:core.js Github

copy

Full Screen

1var systemObject = {2 defaultMax : 10,3 buttonsMax : 5,4 tableMax : [], 5 currentPage : [],6 tableData : [],7 tableDataIndex : [],8 tableDataText : [], 9 tableDataFiltered : [],10 pagesAll : [],11 recordsAll : [],12 blocksAll : [],13 blockCurrent : [],14 indexStart : [],15 indexEnd : [],16 indexPrevious : [],17 indexNext : [],18 isEmpty : function(thisValue) {19 "use strict";20 if ($.isArray(thisValue)) {21 return thisValue.length > 0 ? false : true;22 } else {23 return thisValue !== '' && typeof thisValue !== 'undefined' ? false : true;24 }25 },26 outerHtml : function(obj) {27 "use strict";28 return obj.wrap('<div>').parent().html(); 29 },30 setCurrentPage : function(thisIdentity, thisPage) {31 "use strict";32 thisPage = !this.isEmpty(thisPage) ? thisPage : 1;33 this.currentPage[thisIdentity] = thisPage;34 $('#' + thisIdentity).attr('data-page', thisPage);35 },36 pagingTemplate : function(thisIdentity, thisButtons) {37 "use strict";38 if (!this.isEmpty(thisButtons)) {39 var thisPaging = '<ul class="paging" data-form="' + thisIdentity + '">';40 thisPaging += thisButtons;41 thisPaging += '</ul>';42 return thisPaging;43 }44 },45 feedPaging : function(thisIdentity, thisButtons) {46 "use strict";47 // replace pagination48 $('#' + thisIdentity + 'Paging').html(this.pagingTemplate(thisIdentity, thisButtons));49 // replace number of records50 $('#' + thisIdentity + 'Count').html(this.recordsAll[thisIdentity]);51 // replace page52 $('#' + thisIdentity + 'Page').html(this.currentPage[thisIdentity]);53 // replace page of54 $('#' + thisIdentity + 'PageOf').html(this.pagesAll[thisIdentity]);55 },56 pagingLoad : function(thisIdentity, thisArray) {57 "use strict";58 if (!this.isEmpty(thisIdentity)) {59 var thisButtons = [];60 if (!this.isEmpty(thisArray)) {61 62 if ($('#' + thisIdentity + 'Paging').length > 0) {63 64 // first / previous buttons65 if (this.currentPage[thisIdentity] > 1) {66 67 thisButtons.push('<li><span data-index="1">&lt;&lt;</span></li>');68 thisButtons.push('<li><span data-index="' + parseInt((this.currentPage[thisIdentity] - 1), 10) + '">&lt;</span></li>');69 70 } else {71 72 thisButtons.push('<li class="inactive">&lt;&lt;</li>');73 thisButtons.push('<li class="inactive">&lt;</li>');74 75 }76 77 // previous block button78 if (this.blockCurrent[thisIdentity] > 1) {79 thisButtons.push('<li><span data-index="' + this.indexPrevious[thisIdentity] + '">...</span></li>');80 } 81 82 // middle buttons83 for (var i = this.indexStart[thisIdentity]; i <= this.indexEnd[thisIdentity]; i++) {84 var thisButton;85 if (i == this.currentPage[thisIdentity]) {86 thisButton = '<li><span class="active">' + i + '</span></li>';87 } else {88 thisButton = '<li><span data-index="' + i + '">' + i + '</span></li>';89 }90 thisButtons.push(thisButton);91 }92 93 // next block button94 if (this.blockCurrent[thisIdentity] < this.blocksAll[thisIdentity]) {95 thisButtons.push('<li><span data-index="' + this.indexNext[thisIdentity] + '">...</span></li>');96 }97 98 // next / last buttons99 if (this.currentPage[thisIdentity] < this.pagesAll[thisIdentity]) {100 101 thisButtons.push('<li><span data-index="' + (parseInt(this.currentPage[thisIdentity], 10) + 1) + '">&gt;</span></li>'); 102 thisButtons.push('<li><span data-index="' + this.pagesAll[thisIdentity] + '">&gt;&gt;</span></li>');103 104 } else {105 106 thisButtons.push('<li class="inactive">&gt;</li>'); 107 thisButtons.push('<li class="inactive">&gt;&gt;</li>');108 109 }110 111 this.feedPaging(thisIdentity, thisButtons.join(''));112 113 }114 115 } else {116 117 // if array is empty118 thisButtons.push('<li class="inactive">&lt;&lt;</li>'); 119 thisButtons.push('<li class="inactive">&lt;</li>');120 thisButtons.push('<li class="inactive">1</li>');121 thisButtons.push('<li class="inactive">&gt;</li>'); 122 thisButtons.push('<li class="inactive">&gt;&gt;</li>');123 124 this.feedPaging(thisIdentity, thisButtons.join(''));125 126 }127 }128 },129 calculate : function(thisIdentity, thisArray) {130 "use strict";131 // all records132 this.recordsAll[thisIdentity] = thisArray.length;133 // rounding up the number of pages134 this.pagesAll[thisIdentity] = Math.ceil(this.recordsAll[thisIdentity] / this.tableMax[thisIdentity]);135 // correct current page if necessary136 this.currentPage[thisIdentity] = this.currentPage[thisIdentity] < this.pagesAll[thisIdentity] ?137 this.currentPage[thisIdentity] : this.pagesAll[thisIdentity];138 // setting current page number139 this.setCurrentPage(thisIdentity, this.currentPage[thisIdentity]);140 // calculate blocks141 this.blocksAll[thisIdentity] = Math.ceil(this.pagesAll[thisIdentity] / this.buttonsMax);142 this.blockCurrent[thisIdentity] = Math.ceil(this.currentPage[thisIdentity] / this.buttonsMax);143 // start index144 this.indexStart[thisIdentity] = Math.ceil( 145 ( 146 (this.blockCurrent[thisIdentity] - 1) * this.buttonsMax 147 ) + 1 148 );149 // if there is only one block150 // or it's the last block151 // get the right number of buttons152 var thisButtonsMaxEnd = this.buttonsMax;153 if (this.blockCurrent[thisIdentity] == this.blocksAll[thisIdentity]) {154 // if there's only one block of buttons155 if (this.blocksAll[thisIdentity] == 1) {156 thisButtonsMaxEnd = this.pagesAll[thisIdentity];157 } else {158 thisButtonsMaxEnd = Math.ceil(159 parseInt( (this.pagesAll[thisIdentity] - this.indexStart[thisIdentity]), 10) + 1160 );161 }162 }163 this.indexEnd[thisIdentity] = parseInt(164 ( (this.indexStart[thisIdentity] - 1) + thisButtonsMaxEnd ), 10165 );166 this.indexPrevious[thisIdentity] = parseInt(167 (this.indexStart[thisIdentity] - this.buttonsMax), 10168 );169 this.indexNext[thisIdentity] = parseInt(170 (this.indexEnd[thisIdentity] + 1), 10171 );172 },173 paging : function(obj) {174 "use strict";175 obj.live('click', function(e) {176 e.preventDefault();177 var thisIdentity = $(this).closest('ul').attr('data-form');178 var thisIndex = $(this).attr('data-index');179 if (!systemObject.isEmpty(thisIdentity)) {180 // update current page number181 systemObject.setCurrentPage(thisIdentity, thisIndex);182 if (!systemObject.isEmpty(systemObject.tableDataFiltered[thisIdentity])) {183 systemObject.limit(thisIdentity, systemObject.tableDataFiltered[thisIdentity]);184 } else {185 systemObject.limit(thisIdentity, systemObject.tableData[thisIdentity]);186 }187 }188 });189 },190 limit : function(thisIdentity, thisArray) {191 "use strict";192 if (!this.isEmpty(thisIdentity)) {193 this.calculate(thisIdentity, thisArray);194 if (!this.isEmpty(thisArray)) {195 var thisFiltered = [];196 if (this.pagesAll[thisIdentity] > 1) {197 var thisStartIndex = ( 198 parseInt((this.currentPage[thisIdentity] - 1), 10) * 199 this.tableMax[thisIdentity]200 );201 var thisEndIndex = (202 parseInt(thisStartIndex, 10) + this.tableMax[thisIdentity]203 );204 thisFiltered = thisArray.slice(thisStartIndex, thisEndIndex);205 } else {206 thisFiltered = thisArray.slice(0, this.tableMax[thisIdentity]);207 }208 $('#' + thisIdentity + 'Table tbody').html(thisFiltered.join(''));209 } else {210 var thisSpan = $('#' + thisIdentity + 'Table th').length;211 var thisNoRecords = '<tr><td colspan="' + thisSpan + '"';212 thisNoRecords += ' class="bgOrange">';213 thisNoRecords += 'There are no records matching your search criteria.';214 thisNoRecords += '</td></tr>'; 215 $('#' + thisIdentity + 'Table tbody').html($(thisNoRecords).show());216 }217 this.pagingLoad(thisIdentity, thisArray);218 } 219 },220 loadTable : function(obj) {221 "use strict";222 if (obj.length > 0) {223 $.each(obj, function() {224 var thisObj = $(this);225 var thisUrl = thisObj.attr('data-url');226 var thisIdentity = thisObj.attr('id');227 var thisMax = thisObj.attr('data-max');228 systemObject.tableMax[thisIdentity] = !systemObject.isEmpty(thisMax) ? 229 parseInt(thisMax, 10) : systemObject.defaultMax;230 var thisCurrentPage = thisObj.attr('data-page');231 systemObject.currentPage[thisIdentity] = !systemObject.isEmpty(thisCurrentPage) ? 232 parseInt(thisCurrentPage, 10) : 1;233 $.ajax({234 type : 'GET',235 url : thisUrl,236 dataType : 'json',237 success : function(data) {238 if (data && data.rows && data.rowsIndex && data.text) {239 systemObject.tableData[thisIdentity] = data.rows;240 systemObject.tableDataIndex[thisIdentity] = data.rowsIndex;241 systemObject.tableDataText[thisIdentity] = data.text;242 systemObject.limit(thisIdentity, systemObject.tableData[thisIdentity]);243 }244 }245 });246 });247 }248 },249 search : function(obj) {250 "use strict";251 $.each(obj, function() {252 var thisObj = $(this);253 var thisIdentity = thisObj.attr('data-form');254 thisObj.live('keyup keypress', function(e) {255 var thisCode = (e.keyCode ? e.keyCode : e.which);256 if (thisCode === 13) {257 e.preventDefault();258 } else {259 if (!systemObject.isEmpty(systemObject.tableData[thisIdentity])) {260 if (e.type === 'keyup') {261 systemObject.setCurrentPage(thisIdentity);262 systemObject.tableDataFiltered[thisIdentity] = [];263 var thisValue = $(this).val().toLowerCase();264 if (!systemObject.isEmpty(thisValue)) {265 var thisValues = thisValue.split(' ');266 for (var tIndex in systemObject.tableDataText[thisIdentity]) {267 $.each(thisValues, function(k, v) {268 if (systemObject.tableDataText[thisIdentity][tIndex].indexOf(v) !== -1) {269 var thisItem = systemObject.outerHtml($(systemObject.tableDataIndex[thisIdentity][tIndex]));270 systemObject.tableDataFiltered[thisIdentity].push(thisItem);271 return false;272 }273 });274 }275 systemObject.limit(thisIdentity, systemObject.tableDataFiltered[thisIdentity]);276 } else {277 systemObject.limit(thisIdentity, systemObject.tableData[thisIdentity]);278 }279 }280 }281 }282 });283 });284 }285};286$(function() {287 "use strict";288 systemObject.loadTable($('.loadTable'));289 systemObject.paging($('.paging li span'));290 systemObject.search($('.search'));...

Full Screen

Full Screen

custom_oauth_server.js

Source:custom_oauth_server.js Github

copy

Full Screen

...99 } else {100 return data.access_token;101 }102 }103 getIdentity(accessToken) {104 const params = {};105 const headers = {106 'User-Agent': this.userAgent // http://doc.gitlab.com/ce/api/users.html#Current-user107 };108 if (this.identityTokenSentVia === 'header') {109 headers['Authorization'] = `Bearer ${ accessToken }`;110 } else {111 params['access_token'] = accessToken;112 }113 try {114 const response = HTTP.get(this.identityPath, {115 headers,116 params117 });118 let data;119 if (response.data) {120 data = response.data;121 } else {122 data = JSON.parse(response.content);123 }124 logger.debug('Identity response', JSON.stringify(data, null, 2));125 return data;126 } catch (err) {127 const error = new Error(`Failed to fetch identity from ${ this.name } at ${ this.identityPath }. ${ err.message }`);128 throw _.extend(error, {response: err.response});129 }130 }131 registerService() {132 const self = this;133 OAuth.registerService(this.name, 2, null, (query) => {134 const accessToken = self.getAccessToken(query);135 // console.log 'at:', accessToken136 let identity = self.getIdentity(accessToken);137 if (identity) {138 // Set 'id' to '_id' for any sources that provide it139 if (identity._id && !identity.id) {140 identity.id = identity._id;141 }142 // Fix for Reddit143 if (identity.result) {144 identity = identity.result;145 }146 // Fix WordPress-like identities having 'ID' instead of 'id'147 if (identity.ID && !identity.id) {148 identity.id = identity.ID;149 }150 // Fix Auth0-like identities having 'user_id' instead of 'id'...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1import signal from 'pico-signals';2import { assertApp } from '../identities';3import { UnknownSessionError, IdentityRevokedError } from '../utils/errors';4import { loadSessions, createSession, removeSession, assertSessionOptions } from './session';5class Sessions {6 #sessions;7 #storage;8 #identities;9 #identityListeners = new Map();10 #onDestroy = signal();11 constructor(sessions, storage, identities) {12 this.#sessions = sessions;13 this.#storage = storage;14 this.#identities = identities;15 this.#identities.onLoad(this.#handleIdentitiesLoad);16 this.#identities.onChange(this.#handleIdentitiesChange);17 }18 get(sessionId) {19 const session = this.#sessions[sessionId];20 if (!session || !session.isValid(sessionId)) {21 throw new UnknownSessionError(sessionId);22 }23 return session;24 }25 isValid(sessionId) {26 const session = this.#sessions[sessionId];27 return Boolean(session && session.isValid());28 }29 async create(identityId, app, options) {30 assertApp(app);31 assertSessionOptions(options);32 const identity = this.#identities.get(identityId);33 if (identity.isRevoked()) {34 throw new IdentityRevokedError(`Unable to create session for revoked identity: ${identityId}`);35 }36 const session = this.#getSessionByIdentityAndAppId(identityId, app.id);37 if (session) {38 if (session.isValid()) {39 return session;40 }41 await this.destroy(session.getId());42 }43 const newSession = await createSession(identity, app, options, this.#storage, this.#identities);44 const newSessionId = newSession.getId();45 this.#sessions[newSessionId] = newSession;46 try {47 await identity.apps.add(app);48 await identity.apps.linkCurrentDevice(app.id);49 } catch (err) {50 delete this.#sessions[newSessionId];51 try {52 await removeSession(newSessionId, this.#storage).catch(() => {});53 } catch (err) {54 console.warn(`Unable to remove session "${newSessionId}" after failed attempt to create app "${app.id}" or link it to "${identityId}". Will cleanup on when identities got loaded again.`, err);55 }56 throw err;57 }58 return newSession;59 }60 async destroy(sessionId) {61 const session = this.#sessions[sessionId];62 if (!session) {63 return;64 }65 await removeSession(sessionId, this.#storage);66 delete this.#sessions[sessionId];67 const appId = session.getAppId();68 const identityId = session.getIdentityId();69 if (this.#identities.isLoaded() && this.#identities.has(identityId)) {70 const identity = this.#identities.get(identityId);71 try {72 await identity.apps.unlinkCurrentDevice(appId);73 } catch (err) {74 console.warn(`Something went wrong unlinking current device with app "${appId}" for identity "${identityId}". Will retry on reload.`, err);75 }76 }77 this.#onDestroy.dispatch(sessionId, session.getMeta());78 }79 onDestroy(fn) {80 return this.#onDestroy.add(fn);81 }82 #getSessionByIdentityAndAppId = (identityId, appId, sessions = this.#sessions) =>83 Object.values(sessions).find((session) => session.getAppId() === appId && session.getIdentityId() === identityId);84 #getSessionsByIdentityId = (identityId, sessions = this.#sessions) =>85 Object.values(sessions).filter((session) => session.getIdentityId() === identityId);86 #destroySessionsByIdentityId = async (identityId) => {87 const identitySessions = this.#getSessionsByIdentityId(identityId);88 await Promise.all(identitySessions.map((session) => this.destroy(session.getId())));89 }90 #addIdentityListeners = (identityId) => {91 if (this.#identityListeners.has(identityId)) {92 return;93 }94 const identity = this.#identities.get(identityId);95 const removeRevokeListener = identity.onRevoke((...args) => this.#handleIdentityRevoke(identityId, ...args));96 const removeLinkChangeListener = identity.apps.onLinkCurrentChange((...args) => this.#handleLinkCurrentChange(identityId, ...args));97 this.#identityListeners.set(identityId, { removeRevokeListener, removeLinkChangeListener });98 }99 #removeIdentityListeners = (identityId) => {100 if (!this.#identityListeners.has(identityId)) {101 return;102 }103 const listeners = this.#identityListeners.get(identityId);104 listeners.removeRevokeListener();105 listeners.removeLinkChangeListener();106 this.#identityListeners.delete(identityId);107 }108 #handleIdentitiesLoad = () => {109 Object.values(this.#identities.list()).forEach((identity) => {110 const apps = identity.apps.list();111 const identityId = identity.getId();112 apps.forEach((app) => {113 const session = this.#getSessionByIdentityAndAppId(identityId, app.id);114 if (!session) {115 identity.apps.unlinkCurrentDevice(app.id)116 .catch((err) => console.warn(`Something went wrong unlinking current device with app "${app.id}" for identity "${identityId}". Will retry on reload.`, err));117 }118 });119 this.#addIdentityListeners(identity.getId());120 });121 Object.values(this.#sessions).forEach((session) => {122 const sessionId = session.getId();123 const identityId = session.getIdentityId();124 if (!this.#identities.has(identityId) || this.#identities.get(identityId).isRevoked()) {125 this.destroy(sessionId)126 .catch((err) => console.warn(`Something went wrong destroying session "${sessionId}" for identity "${identityId}". Will retry on reload.`, err));127 }128 });129 }130 #handleIdentitiesChange = async (identities, operation) => {131 const { type, id: identityId } = operation;132 if (type !== 'remove') {133 this.#addIdentityListeners(identityId);134 return;135 }136 try {137 await this.#destroySessionsByIdentityId(identityId);138 this.#removeIdentityListeners(identityId);139 } catch (err) {140 console.warn(`Something went wrong destroying sessions for removed identity "${identityId}". Will retry on reload.`);141 }142 }143 #handleIdentityRevoke = async (identityId) => {144 try {145 await this.#destroySessionsByIdentityId(identityId);146 } catch (err) {147 console.warn(`Something went wrong destroying sessions for revoked identity "${identityId}". Will retry on reload.`);148 }149 }150 #handleLinkCurrentChange = async (identityId, { appId, isLinked }) => {151 const session = this.#getSessionByIdentityAndAppId(identityId, appId);152 if (session && !isLinked) {153 const sessionId = session.getId();154 try {155 await this.destroy(session.getId());156 } catch (err) {157 console.warn(`Something went wrong destroying session "${sessionId}" for app "${appId}" of identity "${identityId}" . Will retry on reload.`);158 }159 } else if (!session && isLinked) {160 console.warn(`App "${appId}" of identity "${identityId}" is linked but there's no session. Will fix on reload.`);161 }162 }163}164const createSessions = async (storage, identities) => {165 const sessions = await loadSessions(storage);166 return new Sessions(sessions, storage, identities);167};...

Full Screen

Full Screen

identity-test.js

Source:identity-test.js Github

copy

Full Screen

1var vows = require("vows"),2 load = require("../load"),3 assert = require("../assert");4var suite = vows.describe("d3.scale.identity");5suite.addBatch({6 "identity": {7 topic: load("scale/identity").expression("d3.scale.identity"),8 "domain and range": {9 "are identical": function(identity) {10 var x = identity();11 assert.strictEqual(x.domain, x.range);12 assert.strictEqual(x.domain(), x.range());13 var x = identity().domain([-10, 0, 100]);14 assert.deepEqual(x.range(), [-10, 0, 100]);15 var x = identity().range([-10, 0, 100]);16 assert.deepEqual(x.domain(), [-10, 0, 100]);17 },18 "default to [0, 1]": function(identity) {19 var x = identity();20 assert.deepEqual(x.domain(), [0, 1]);21 assert.deepEqual(x.range(), [0, 1]);22 assert.strictEqual(x(.5), .5);23 },24 "coerce values to numbers": function(identity) {25 var x = identity().domain([new Date(1990, 0, 1), new Date(1991, 0, 1)]);26 assert.typeOf(x.domain()[0], "number");27 assert.typeOf(x.domain()[1], "number");28 assert.strictEqual(x.domain()[0], +new Date(1990, 0, 1));29 assert.strictEqual(x.domain()[1], +new Date(1991, 0, 1));30 assert.typeOf(x(new Date(1989, 09, 20)), "number");31 assert.strictEqual(x(new Date(1989, 09, 20)), +new Date(1989, 09, 20));32 var x = identity().domain(["0", "1"]);33 assert.typeOf(x.domain()[0], "number");34 assert.typeOf(x.domain()[1], "number");35 assert.strictEqual(x(.5), .5);36 var x = identity().domain([new Number(0), new Number(1)]);37 assert.typeOf(x.domain()[0], "number");38 assert.typeOf(x.domain()[1], "number");39 assert.strictEqual(x(.5), .5);40 var x = identity().range([new Date(1990, 0, 1), new Date(1991, 0, 1)]);41 assert.typeOf(x.range()[0], "number");42 assert.typeOf(x.range()[1], "number");43 assert.strictEqual(x.range()[0], +new Date(1990, 0, 1));44 assert.strictEqual(x.range()[1], +new Date(1991, 0, 1));45 assert.typeOf(x(new Date(1989, 09, 20)), "number");46 assert.strictEqual(x(new Date(1989, 09, 20)), +new Date(1989, 09, 20));47 var x = identity().range(["0", "1"]);48 assert.typeOf(x.range()[0], "number");49 assert.typeOf(x.range()[1], "number");50 assert.strictEqual(x(.5), .5);51 var x = identity().range([new Number(0), new Number(1)]);52 assert.typeOf(x.range()[0], "number");53 assert.typeOf(x.range()[1], "number");54 assert.strictEqual(x(.5), .5);55 },56 "can specify a polyidentity domain and range": function(identity) {57 var x = identity().domain([-10, 0, 100]);58 assert.deepEqual(x.domain(), [-10, 0, 100]);59 assert.strictEqual(x(-5), -5);60 assert.strictEqual(x(50), 50);61 assert.strictEqual(x(75), 75);62 var x = identity().range([-10, 0, 100]);63 assert.deepEqual(x.range(), [-10, 0, 100]);64 assert.strictEqual(x(-5), -5);65 assert.strictEqual(x(50), 50);66 assert.strictEqual(x(75), 75);67 },68 "do not affect the identity function": function(identity) {69 var x = identity().domain([Infinity, NaN]);70 assert.strictEqual(x(42), 42);71 assert.strictEqual(x.invert(-42), -42);72 }73 },74 "is the identity function": function(identity) {75 var x = identity().domain([1, 2]);76 assert.strictEqual(x(.5), .5);77 assert.strictEqual(x(1), 1);78 assert.strictEqual(x(1.5), 1.5);79 assert.strictEqual(x(2), 2);80 assert.strictEqual(x(2.5), 2.5);81 },82 "coerces input to a number": function(identity) {83 var x = identity().domain([1, 2]);84 assert.strictEqual(x("2"), 2);85 },86 "invert": {87 "is the identity function": function(identity) {88 var x = identity().domain([1, 2]);89 assert.strictEqual(x.invert(.5), .5);90 assert.strictEqual(x.invert(1), 1);91 assert.strictEqual(x.invert(1.5), 1.5);92 assert.strictEqual(x.invert(2), 2);93 assert.strictEqual(x.invert(2.5), 2.5);94 },95 "coerces range value to numbers": function(identity) {96 var x = identity().range(["0", "2"]);97 assert.strictEqual(x.invert("1"), 1);98 var x = identity().range([new Date(1990, 0, 1), new Date(1991, 0, 1)]);99 assert.strictEqual(x.invert(new Date(1990, 6, 2, 13)), +new Date(1990, 6, 2, 13));100 var x = identity().range(["#000", "#fff"]);101 assert.isNaN(x.invert("#999"));102 },103 "coerces input to a number": function(identity) {104 var x = identity().domain([1, 2]);105 assert.strictEqual(x.invert("2"), 2);106 }107 },108 "ticks": {109 "generates ticks of varying degree": function(identity) {110 var x = identity();111 assert.deepEqual(x.ticks(1).map(x.tickFormat(1)), [0, 1]);112 assert.deepEqual(x.ticks(2).map(x.tickFormat(2)), [0, .5, 1]);113 assert.deepEqual(x.ticks(5).map(x.tickFormat(5)), [0, .2, .4, .6, .8, 1]);114 assert.deepEqual(x.ticks(10).map(x.tickFormat(10)), [0, .1, .2, .3, .4, .5, .6, .7, .8, .9, 1]);115 var x = identity().domain([1, 0]);116 assert.deepEqual(x.ticks(1).map(x.tickFormat(1)), [0, 1]);117 assert.deepEqual(x.ticks(2).map(x.tickFormat(2)), [0, .5, 1]);118 assert.deepEqual(x.ticks(5).map(x.tickFormat(5)), [0, .2, .4, .6, .8, 1]);119 assert.deepEqual(x.ticks(10).map(x.tickFormat(10)), [0, .1, .2, .3, .4, .5, .6, .7, .8, .9, 1]);120 },121 "formats ticks with the appropriate precision": function(identity) {122 var x = identity().domain([.123456789, 1.23456789]);123 assert.strictEqual(x.tickFormat(1)(x.ticks(1)[0]), "1");124 assert.strictEqual(x.tickFormat(2)(x.ticks(2)[0]), "0.5");125 assert.strictEqual(x.tickFormat(4)(x.ticks(4)[0]), "0.2");126 assert.strictEqual(x.tickFormat(8)(x.ticks(8)[0]), "0.2");127 assert.strictEqual(x.tickFormat(16)(x.ticks(16)[0]), "0.2");128 assert.strictEqual(x.tickFormat(32)(x.ticks(32)[0]), "0.15");129 assert.strictEqual(x.tickFormat(64)(x.ticks(64)[0]), "0.14");130 assert.strictEqual(x.tickFormat(128)(x.ticks(128)[0]), "0.13");131 assert.strictEqual(x.tickFormat(256)(x.ticks(256)[0]), "0.125");132 }133 },134 "copy": {135 "changes to the domain or range are isolated": function(identity) {136 var x = identity(), y = x.copy();137 x.domain([1, 2]);138 assert.deepEqual(y.domain(), [0, 1]);139 y.domain([2, 3]);140 assert.deepEqual(x.domain(), [1, 2]);141 assert.deepEqual(y.domain(), [2, 3]);142 var x = identity(), y = x.copy();143 x.range([1, 2]);144 assert.deepEqual(y.range(), [0, 1]);145 y.range([2, 3]);146 assert.deepEqual(x.range(), [1, 2]);147 assert.deepEqual(y.range(), [2, 3]);148 }149 }150 }151});...

Full Screen

Full Screen

numerical-integration.js

Source:numerical-integration.js Github

copy

Full Screen

1function integrateRectagle(func, a, b, n, k) {2 var h = (b-a)/n;3 var sum = 0;4 for (var i = a, j=a; i < b; i+=(b/n), ++j) {5 if (func == "cube") {6 sum += cube(i-h*(1-k));7 }8 9 if (func == "reciprocal") {10 sum += reciprocal(i-h*(1-k));11 }12 if (func == "identity") {13 sum += identity(i-h*(1-k));14 } 15 }16 sum *= h;17}18function integrateTrapezoid(func, a, b, n) {19 var h = (b-a)/n;20 var sum = 0;21 for (var i = a, j=a; i < b; i+=(b/n), ++j) {22 if (func == "cube") {23 if (i < b-1) {24 sum += cube(i) + cube(i+1); 25 } else {26 sum += cube(i) + cube(i+1-b);27 }28 } 29 if (func == "reciprocal") {30 if (i < b-1) {31 sum += reciprocal(i) + reciprocal(i+1); 32 } else {33 sum += reciprocal(i) + reciprocal(i+1-b);34 }35 } 36 if (func == "identity") {37 if (i < b-1) {38 sum += identity(i) + identity(i+1); 39 } else {40 sum += identity(i) + identity(i+1-b);41 }42 } 43 }44 sum *= h/2;45}46function integrateSimpsons(func, a, b, n) {47 var h = (b-a)/h;48 var sum = 0;49 for (var i = a, j=a; i < b; i+=(b/n), ++j) {50 if (func == "cube") {51 if (i < b -1) {52 sum += cube(i) + (4 * cube(i - (h / 2))) + cube(i + 1);53 } else {54 sum += cube(i) + (4 * cube(i - (h / 2))) + cube(i + 1 - b);55 }56 }57 if (func == "reciprocal") {58 if (i < b -1) {59 sum += reciprocal(i) + (4 * reciprocal(i - (h / 2))) + reciprocal(i + 1);60 } else {61 sum += reciprocal(i) + (4 * reciprocal(i - (h / 2))) + reciprocal(i + 1 - b);62 }63 }64 if (func == "identity") {65 if (i < b -1) {66 sum += identity(i) + (4 * identity(i - (h / 2))) + identity(i + 1);67 } else {68 sum += identity(i) + (4 * identity(i - (h / 2))) + identity(i + 1 - b);69 }70 }71 }72 sum *= h/6;73}74function cube(x) {75 return (x*x*x+aVar);76}77function reciprocal(x) {78 return 1/(x+aVar);79}80function identity(x) {81 return x+aVar;82}83function executeTask(i) {84integrateRectagle("cube",0,1,100,0);85integrateRectagle("cube",0,1,100,0.5);86integrateRectagle("cube",0,1,100,1);87integrateTrapezoid("cube",0,1,100);88integrateSimpsons("cube",0,1,100);89integrateRectagle("reciprocal",1,100,1000,0);90integrateRectagle("reciprocal",1,100,1000,0.5);91integrateRectagle("reciprocal",1,100,1000,1);92integrateTrapezoid("reciprocal",1,100,1000);93integrateSimpsons("reciprocal",1,100,1000);94integrateRectagle("identity",0,5000,5000000,0);95integrateRectagle("identity",0,5000,5000000,0.5);96integrateRectagle("identity",0,5000,5000000,1);97integrateTrapezoid("identity",0,5000,5000000);98integrateSimpsons("identity",0,5000,5000000);99integrateRectagle("identity",0,6000,6000000,0);100integrateRectagle("identity",0,6000,6000000,0.5);101integrateRectagle("identity",0,6000,6000000,1);102integrateTrapezoid("identity",0,6000,6000000);103integrateSimpsons("identity",0,6000,6000000);104 return i;105}106var r = 1;107var aVar = 0;108for ( aVar = 0; aVar < 100; ++aVar) {109 r = executeTask(aVar);...

Full Screen

Full Screen

principal.service.js

Source:principal.service.js Github

copy

Full Screen

1(function() {2 'use strict';3 angular4 .module('angular1JavaApp')5 .factory('Principal', Principal);6 Principal.$inject = ['$q', 'Account'];7 function Principal ($q, Account) {8 var _identity,9 _authenticated = false;10 var service = {11 authenticate: authenticate,12 hasAnyAuthority: hasAnyAuthority,13 hasAuthority: hasAuthority,14 identity: identity,15 isAuthenticated: isAuthenticated,16 isIdentityResolved: isIdentityResolved17 };18 return service;19 function authenticate (identity) {20 _identity = identity;21 _authenticated = identity !== null;22 }23 function hasAnyAuthority (authorities) {24 if (!_authenticated || !_identity || !_identity.authorities) {25 return false;26 }27 for (var i = 0; i < authorities.length; i++) {28 if (_identity.authorities.indexOf(authorities[i]) !== -1) {29 return true;30 }31 }32 return false;33 }34 function hasAuthority (authority) {35 if (!_authenticated) {36 return $q.when(false);37 }38 return this.identity().then(function(_id) {39 return _id.authorities && _id.authorities.indexOf(authority) !== -1;40 }, function(){41 return false;42 });43 }44 function identity (force) {45 var deferred = $q.defer();46 if (force === true) {47 _identity = undefined;48 }49 // check and see if we have retrieved the identity data from the server.50 // if we have, reuse it by immediately resolving51 if (angular.isDefined(_identity)) {52 deferred.resolve(_identity);53 return deferred.promise;54 }55 // retrieve the identity data from the server, update the identity object, and then resolve.56 Account.get().$promise57 .then(getAccountThen)58 .catch(getAccountCatch);59 return deferred.promise;60 function getAccountThen (account) {61 _identity = account.data;62 _authenticated = true;63 deferred.resolve(_identity);64 }65 function getAccountCatch () {66 _identity = null;67 _authenticated = false;68 deferred.resolve(_identity);69 }70 }71 function isAuthenticated () {72 return _authenticated;73 }74 function isIdentityResolved () {75 return angular.isDefined(_identity);76 }77 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.contains('type').click()4 cy.url().should('include', '/commands/actions')5 cy.get('.action-email')6 .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test Suite', function () {2 it('Test Case', function () {3 cy.get('.search-keyword').type('ca')4 cy.wait(2000)5 cy.get('.products').as('productLocator')6 cy.get('@productLocator').find('.product').should('have.length', 5)7 cy.get(':nth-child(3) > .product-action > button').click()8 cy.get('@productLocator').find('.product').should('have.length', 4)9 cy.get('@productLocator').find('.product').eq(2).contains('ADD TO CART').click().then(function () {10 console.log('sf')11 })12 })13})

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My Test Suite', function() {2 it('My Test Case', function() {3 cy.viewport(320, 480)4 cy.screenshot()5 })6})

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.get('input[type="text"]').type('Hello World');2cy.get('input[type="text"]').should('have.value', 'Hello World');3cy.get('input[type="text"]').type('Hello World');4cy.get('input[type="text"]').should('have.value', 'Hello World');5cy.get('input[type="text"]').type('Hello World');6cy.get('input[type="text"]').should('have.value', 'Hello World');7cy.get('input[type="text"]').type('Hello World');8cy.get('input[type="text"]').should('have.value', 'Hello World');9cy.get('input[type="text"]').type('Hello World');10cy.get('input[type="text"]').should('have.value', 'Hello World');11cy.get('input[type="text"]').type('Hello World');12cy.get('input[type="text"]').should('have.value', 'Hello World');13cy.get('input[type="text"]').type('Hello World');14cy.get('input[type="text"]').should('have.value', 'Hello World');15cy.get('input[type="text"]').type('Hello World');16cy.get('input[type="text"]').should('have.value', 'Hello World');17cy.get('input[type="text"]').type('Hello World');18cy.get('input[type="text"]').should('have.value', 'Hello World');19cy.get('input[type="text"]').type('Hello World');20cy.get('input[type="text"]').should('have.value', 'Hello World');21cy.get('input[type="text"]').type('Hello World');22cy.get('input[type="text"]').should('have.value', 'Hello World');23cy.get('input[type="text"]').type('Hello World');24cy.get('input[type="text"]').should('have.value', 'Hello World');25cy.get('input[type="text"]').type('Hello World');26cy.get('input[type="text"]').should('have.value', 'Hello World');

Full Screen

Using AI Code Generation

copy

Full Screen

1it('should login to the application', () => {2 cy.visit('localhost:4200/login');3 cy.get('[formcontrolname="username"]').type('admin');4 cy.get('[formcontrolname="password"]').type('admin');5 cy.get('.btn').click();6 cy.url().should('include', 'dashboard');7 cy.get('.nav-link').should('have.text', 'admin');8});9{10 "env": {11 }12}13module.exports = (on, config) => {14}15import './commands'16Cypress.Commands.add('login', (username, password) => {17 cy.visit('/login');18 cy.get('[formcontrolname="username"]').type(username);19 cy.get('[formcontrolname="password"]').type(password);20 cy.get('.btn').click();21 cy.url().should('include', 'dashboard');22 cy.get('.nav-link').should('have.text', username);23});24describe('Login', () => {25 it('should login to the application', () => {26 cy.login('admin', 'admin');27 });28});29describe('Login', () => {30 it('should login to the application', () => {31 cy.login('admin', 'admin');32 cy.get('.nav-link').click();33 cy.get('.dropdown-item').contains('Logout').click();34 cy.url().should('include', '

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful