Best Python code snippet using green
basic-popup-and-iframe-tests.https.js
Source:basic-popup-and-iframe-tests.https.js  
1/**2 * This test checks the Secure Context state of documents for various3 * permutations of document URI types and loading methods.4 *5 * The hierarchy that is tested is:6 *7 *   creator-doc > createe-doc8 *9 * The creator-doc is one of:10 *11 *   http:12 *   https:13 *14 * The createe-doc is loaded as either a:15 *16 *   popup17 *   iframe18 *   sandboxed-iframe19 *20 * into which we load and test:21 *22 *   http:23 *   https:24 *   blob:25 *   javascript:26 *   about:blank27 *   initial about:blank28 *   srcdoc29 *30 * TODO once web-platform-tests supports it:31 *   - test http://localhost32 *   - test file:33 *34 * TODO once https://github.com/w3c/webappsec-secure-contexts/issues/26 is resolved35 *   - test data:36 */37setup({explicit_done:true});38const host_and_dirname = location.host +39                         location.pathname.substr(0, location.pathname.lastIndexOf("/") + 1);40// Flags to indicate where document types should be loaded for testing:41const eLoadInPopup             = (1 << 0);42const eLoadInUnsandboxedIframe = (1 << 1);43const eLoadInSandboxedIframe   = (1 << 2);44const eLoadInEverything        = eLoadInPopup | eLoadInUnsandboxedIframe | eLoadInSandboxedIframe;45// Flags indicating if a document type is expected to be a Secure Context:46const eSecureNo              = 1;47const eSecureIfCreatorSecure = 2;48// Flags indicating how the result of a test is obtained:49const eResultFromPostMessage       = 1;50const eResultFromExaminationOnLoad = 2;51const eResultFromExaminationSync   = 3;52const loadTypes = [53  new LoadType("an http: URI",54               eLoadInEverything,55               http_dir + "postMessage-helper.html",56               eSecureNo,57               eResultFromPostMessage),58  new LoadType("an https: URI",59               eLoadInEverything,60               https_dir + "postMessage-helper.https.html",61               eSecureIfCreatorSecure,62               eResultFromPostMessage),63  new LoadType("a blob: URI",64               eLoadInEverything,65               URL.createObjectURL(new Blob(["<script>(opener||parent).postMessage(isSecureContext, '*')</script>"])),66               eSecureIfCreatorSecure,67               eResultFromPostMessage),68  new LoadType("a srcdoc",69               // popup not relevant:70               eLoadInUnsandboxedIframe | eLoadInSandboxedIframe,71               "<script>(opener||parent).postMessage(isSecureContext, '*')</script>",72               eSecureIfCreatorSecure,73               eResultFromPostMessage),74  new LoadType("a javascript: URI",75               // can't load in sandbox:76               eLoadInUnsandboxedIframe | eLoadInPopup,77               "javascript:(opener||parent).postMessage(isSecureContext, '*')",78               eSecureIfCreatorSecure,79               eResultFromPostMessage),80  new LoadType("about:blank",81               // can't obtain state if sandboxed:82               eLoadInUnsandboxedIframe | eLoadInPopup,83               "about:blank",84               eSecureIfCreatorSecure,85               eResultFromExaminationOnLoad),86  new LoadType("initial about:blank",87               // can't obtain state if sandboxed:88               eLoadInUnsandboxedIframe | eLoadInPopup,89               "about:blank", // we don't wait for this to load, so whatever90               eSecureIfCreatorSecure,91               eResultFromExaminationSync),92];93const loadTargets = [94  new LoadTarget("an iframe",          eLoadInUnsandboxedIframe),95  new LoadTarget("a sandboxed iframe", eLoadInSandboxedIframe),96  new LoadTarget("a popup",            eLoadInPopup),97];98function LoadType(description, loadInFlags, uri, expectedSecureFlag, resultFrom) {99  this.desc = description;100  this.loadInFlags = loadInFlags;101  this.uri = uri;102  this.expectedSecureFlag = expectedSecureFlag;103  this.resultFrom = resultFrom;104}105function LoadTarget(description, loadInFlag) {106  this.desc = description;107  this.loadInFlag = loadInFlag;108}109LoadTarget.prototype.open = function(loadType) {110  let loadTarget = this;111  this.currentTest.step(function() {112    assert_true((loadTarget.loadInFlag & loadType.loadInFlags) != 0,113                loadType.desc + " cannot be tested in " + loadTarget.desc);114  });115  if (this.loadInFlag == eLoadInUnsandboxedIframe) {116    let iframe = document.createElement("iframe");117    document.body.appendChild(iframe);118    iframe[loadType.desc == "a srcdoc" ? "srcdoc" : "src"] = loadType.uri;119    return iframe;120  }121  if (this.loadInFlag == eLoadInSandboxedIframe) {122    let iframe = document.body.appendChild(document.createElement("iframe"));123    iframe.setAttribute("sandbox", "allow-scripts");124    iframe[loadType.desc == "a srcdoc" ? "srcdoc" : "src"] = loadType.uri;125    return iframe;126  }127  if (this.loadInFlag == eLoadInPopup) {128    return window.open(loadType.uri);129  }130  this.currentTest.step(function() {131    assert_unreached("Unknown load type flag: " + loadInFlags);132  });133  return null;134}135LoadTarget.prototype.close = function(domTarget) {136  if (this.loadInFlag == eLoadInUnsandboxedIframe ||137      this.loadInFlag == eLoadInSandboxedIframe) {138    domTarget.remove();139    return;140  }141  if (this.loadInFlag == eLoadInPopup) {142    domTarget.close();143    return;144  }145  this.currentTest.step(function() {146    assert_unreached("Unknown load type flag: " + loadInFlags);147  });148}149LoadTarget.prototype.load_and_get_result_for = function(loadType) {150  if (!(loadType.loadInFlags & this.loadInFlag)) {151    return Promise.reject("not applicable");152  }153  if (!(this.loadInFlag & eLoadInPopup) &&154      location.protocol == "https:" &&155      loadType.uri.substr(0,5) == "http:") {156    // Mixed content blocker will prevent this load157    return Promise.reject("not applicable");158  }159  this.currentTest = async_test("Test Window.isSecureContext in " + this.desc +160                                " loading " + loadType.desc)161  if (loadType.resultFrom == eResultFromExaminationSync) {162    let domTarget = this.open(loadType);163    let result = domTarget instanceof Window ?164          domTarget.isSecureContext : domTarget.contentWindow.isSecureContext;165    this.close(domTarget);166    return Promise.resolve(result);167  }168  let target = this;169  if (loadType.resultFrom == eResultFromExaminationOnLoad) {170    return new Promise(function(resolve, reject) {171      function handleLoad(event) {172        let result = domTarget instanceof Window ?173              domTarget.isSecureContext : domTarget.contentWindow.isSecureContext;174        domTarget.removeEventListener("load", handleLoad);175        target.close(domTarget);176        resolve(result);177      }178      let domTarget = target.open(loadType);179      domTarget.addEventListener("load", handleLoad, false);180    });181  }182  if (loadType.resultFrom == eResultFromPostMessage) {183    return new Promise(function(resolve, reject) {184      function handleMessage(event) {185        window.removeEventListener("message", handleMessage);186        target.close(domTarget);187        resolve(event.data);188      }189      window.addEventListener("message", handleMessage, false);190      let domTarget = target.open(loadType);191   });192  }193  return Promise.reject("unexpected 'result from' type");194}195let current_type_index = -1;196let current_target_index = 0;197function run_next_test() {198  current_type_index++;199  if (current_type_index >= loadTypes.length) {200    current_type_index = 0;201    current_target_index++;202    if (current_target_index >= loadTargets.length) {203      done();204      return; // all test permutations complete205    }206  }207  let loadTarget = loadTargets[current_target_index];208  let loadType = loadTypes[current_type_index];209  loadTarget.load_and_get_result_for(loadType).then(210    function(value) {211      run_next_test_soon();212      loadTarget.currentTest.step(function() {213        if (loadType.expectedSecureFlag == eSecureNo) {214          assert_false(value, loadType.desc + " in " + loadTarget.desc + " should not create a Secure Context");215        } else if (loadType.expectedSecureFlag == eSecureIfCreatorSecure) {216          if (!window.isSecureContext) {217            assert_false(value, loadType.desc + " in " + loadTarget.desc + " should not create a Secure Context when its creator is not a Secure Context.");218          } else {219            assert_true(value, loadType.desc + " in " + loadTarget.desc + " should create a Secure Context when its creator is a Secure Context");220          }221        } else {222          assert_unreached(loadType.desc + " - unknown expected secure flag: " + expectedSecureFlag);223        }224        loadTarget.currentTest.done();225      });226    },227    function(failReason) {228      run_next_test_soon();229      if (failReason == "not applicable") {230        return;231      }232      loadTarget.currentTest.step(function() {233        assert_unreached(loadType.desc + " - got unexpected rejected promise");234      });235    }236  );237}238function run_next_test_soon() {239  setTimeout(run_next_test, 0);240}241function begin() {242  test(function() {243    if (location.protocol == "http:") {244      assert_false(isSecureContext,245                   "http: creator should not be a Secure Context");246    } else if (location.protocol == "https:") {247      assert_true(isSecureContext,248                  "https: creator should be a Secure Context");249    } else {250      assert_unreached("Unknown location.protocol");251    }252  });253  run_next_test();...agent_models.py
Source:agent_models.py  
1# !/usr/bin/env python2# -*- coding:utf-8 _*-3# @Author: swang4# @Contact: wang00sheng@gmail.com5# @Project Name: D3QN6# @File: A2C.py7# @Time: 2021/10/29/22:548# @Software: PyCharm9import os10import numpy as np11import tensorflow as tf12import tensorflow.keras as keras13from tensorflow.keras.models import Model, Sequential14from tensorflow.keras.layers import Dense, Activation, Input, Conv2D, Flatten, Lambda, Add, BatchNormalization, Reshape15import tensorflow_probability as tfp16def FeatureExtractor(model_dir='../model/base_model/'):17    '''18    initialize a feature extractor for a d3qn RL agent.19    '''20    ckpt_dir = os.path.join(model_dir, 'feature_extractor', 'ckpt')21    fe = tf.keras.models.load_model(ckpt_dir)22    fe.trainable = False23    fe.compile()24    25    print('-' * 20, 'ResCNN_feature_extractor', '-' * 20, )26    fe.summary()27    28    return fe29def D3QN_Classifier(dueling=True, base_model_dir='../model/base_model/', loadTarget=False,30                    load_d3qn_model=False, d3qn_model_dir='../model/d3qn_model/', based_on_base_model=True):31    def __init_d3qn_model__():32        print('-' * 20, 'Initializing a new D3QN model...', '-' * 20, )33        if based_on_base_model:34            print('-' * 20, 'Based on base_model\'s classifier...', '-' * 20, )35            base_classifier = tf.keras.models.load_model(base_ckpt_dir)36            conv, reshape = base_classifier.layers37            # input = base_classifier.input38            # base_classifier = Model(inputs=input, outputs=reshape(conv(input)))39        40        else:41            print('-' * 20, 'Even the classifier is initialized randomly...', '-' * 20, )42            base_classifier = Sequential([43                Input(shape=(30, 8, 82), name='feature_input'),44                Conv2D(1, kernel_size=(30, 1), strides=(1, 1), padding='valid', use_bias=True),45                Reshape((-1,)), ],46                name='output_conv')47        48        if dueling:49            # ------------------------------------- value network -------------------------------------------------#50            state_value = Conv2D(1, kernel_size=(30, 1), strides=(1, 1), padding='valid', use_bias=True,51                                 name='value_conv')(base_classifier.input)52            # state_value = BatchNormalization(axis=-1)(state_value)53            state_value = Reshape((-1,), name='value_reshape')(state_value)54            state_value = Dense(1, name='value_dense')(state_value)55            56            # ------------------------------------- advantage network -------------------------------------------------#57            action_advantage = base_classifier.output58            # kernel_constraint=max_norm(norm_rate))(feature_extraction.output)59            60            # ------------------------------------- add -------------------------------------------------#61            output = Add()([state_value, action_advantage])62        else:63            output = base_classifier.output64        # outputs = tf.keras.layers.Multiply()([output, [1, 1. / 2460]])65        output = Lambda(lambda x: x / 2460.)(output)66        return Model(inputs=base_classifier.input, outputs=output)67    68    def __load_d3qn_model__():69        try:70            print('-' * 20, 'Loading pre-trained D3QN classifier...', '-' * 20, )71            return tf.keras.models.load_model(d3qn_ckpt_dir)72        except Exception as e:73            print('Warning:', e)74            print('-' * 20, 'Fail to load the pre-trained D3QN model! An initialized model will be used!',75                  '-' * 20, )76            return __init_d3qn_model__()77    78    # ------------------------------------- main procedure -------------------------------------------------#79    base_ckpt_dir = os.path.join(base_model_dir, 'classifier', 'ckpt')80    if loadTarget:81        d3qn_ckpt_dir = os.path.join(d3qn_model_dir, 'classifier', 'target_ckpt')82    else:83        d3qn_ckpt_dir = os.path.join(d3qn_model_dir, 'classifier', 'ckpt')84    85    if load_d3qn_model:86        d3qn_model = __load_d3qn_model__()87    else:88        d3qn_model = __init_d3qn_model__()89    90    if loadTarget:91        print('-' * 20, 'd3qn_target_classifier', '-' * 20, )92    else:93        print('-' * 20, 'd3qn_classifier', '-' * 20, )94    d3qn_model.summary()95    96    return d3qn_model97def SAC_actor(base_model_dir='../model/base_model/',98              load_sac_model=False, sac_model_dir='../model/sac_model/', based_on_base_model=True):99    def __init_sac_actor__():100        print('-' * 20, 'Initializing a new SAC_actor...', '-' * 20, )101        if based_on_base_model:102            print('-' * 20, 'Based on base_model\'s classifier...', '-' * 20, )103            base_classifier = tf.keras.models.load_model(base_ckpt_dir)104        else:105            print('-' * 20, 'Even the classifier is initialized randomly...', '-' * 20, )106            base_classifier = Sequential([107                Input(shape=(30, 8, 82), name='feature_input'),108                Conv2D(1, kernel_size=(30, 1), strides=(1, 1), padding='valid', use_bias=True),109                BatchNormalization(axis=-1), Reshape((-1,)), ],110                name='output_conv')111        112        output = Activation('softmax', name='softmax')(base_classifier.output)113        114        return Model(inputs=base_classifier.input, outputs=output)115    116    def __load_sac_actor__():117        try:118            print('-' * 20, 'Loading pre-trained sac_actor...', '-' * 20, )119            return tf.keras.models.load_model(sac_ckpt_dir)120        except Exception as e:121            print('Warning:', e)122            print('-' * 20, 'Fail to load the pre-trained sac_actor! An initialized model will be used!',123                  '-' * 20, )124            return __init_sac_actor__()125    126    # ------------------------------------- main procedure -------------------------------------------------#127    base_ckpt_dir = os.path.join(base_model_dir, 'classifier', 'ckpt')128    sac_ckpt_dir = os.path.join(sac_model_dir, 'actor', 'ckpt')129    130    if load_sac_model:131        sac_actor = __load_sac_actor__()132    else:133        sac_actor = __init_sac_actor__()134    135    print('-' * 20, 'sac_actor', '-' * 20, )136    sac_actor.summary()137    138    return sac_actor139def SAC_critic(base_model_dir='../model/base_model/', load_sac_model=False, sac_model_dir='../model/sac_model/',140               based_on_base_model=True, index=None, loadTarget=False):141    def __init_sac_critic__():142        print('-' * 20, 'Initializing a new SAC_critic...', '-' * 20, )143        if based_on_base_model:144            print('-' * 20, 'Based on base_model\'s classifier...', '-' * 20, )145            base_classifier = tf.keras.models.load_model(base_ckpt_dir)146        else:147            print('-' * 20, 'Even the classifier is initialized randomly...', '-' * 20, )148            base_classifier = Sequential([149                Input(shape=(30, 8, 82), name='feature_input'),150                Conv2D(1, kernel_size=(30, 1), strides=(1, 1), padding='valid', use_bias=True),151                Reshape((-1,)), ],152                name='output_conv')153        154        return Model(inputs=base_classifier.input, outputs=base_classifier.output)155    156    def __load_sac_critic__():157        try:158            if loadTarget:159                print('-' * 20, 'Loading pre-trained target sac_critic...', '-' * 20, )160            else:161                print('-' * 20, 'Loading pre-trained sac_critic...', '-' * 20, )162            return tf.keras.models.load_model(sac_ckpt_dir)163        except Exception as e:164            print('Warning:', e)165            print('-' * 20, 'Fail to load the pre-trained sac_critic! An initialized model will be used!',166                  '-' * 20, )167            return __init_sac_critic__()168    169    # ------------------------------------- main procedure -------------------------------------------------#170    base_ckpt_dir = os.path.join(base_model_dir, 'classifier', 'ckpt')171    if loadTarget:172        if index is None:173            sac_ckpt_dir = os.path.join(sac_model_dir, 'critic', 'target_ckpt')174        else:175            sac_ckpt_dir = os.path.join(sac_model_dir, 'critic', 'target_ckpt_' + str(index))176    else:177        if index is None:178            sac_ckpt_dir = os.path.join(sac_model_dir, 'critic', 'ckpt')179        else:180            sac_ckpt_dir = os.path.join(sac_model_dir, 'critic', 'ckpt_' + str(index))181    182    if load_sac_model:183        sac_critic = __load_sac_critic__()184    else:185        sac_critic = __init_sac_critic__()186    187    print('-' * 20, 'sac_critic', '-' * 20, )188    sac_critic.summary()189    190    return sac_critic191if __name__ == '__main__':192    print('Hello World!')193    os.environ['CUDA_VISIBLE_DEVICES'] = '-1'194    195    fe = FeatureExtractor()196    cls = D3QN_Classifier(based_on_base_model=True)197    cls = SAC_actor(based_on_base_model=True)198    cls = SAC_critic(based_on_base_model=True)199    ...Add_Data.py
Source:Add_Data.py  
1'''2Created on Oct 12, 20153@author: kyleg4'''5if __name__ == '__main__':6    pass7def main():8    pass9    #LoadARegion()10    LoadAliasTables()11def LoadARegion():12    from arcpy import Append_management, ListFeatureClasses, ListDatasets, env, ListTables13    #importGDB = r"//gisdata/planning/Cart/projects/Conflation/GIS_DATA/GEO_COMM/REGION3_20151002/REGION3_20151002.gdb"14    #importGDB = r"\\gisdata\planning\Cart\projects\Conflation\GIS_DATA\GEO_COMM\REGION4_20151021\REGION4_20151021\REGION4_20151021.gdb"15    importGDB = r"\\gisdata\planning\Cart\projects\Conflation\GIS_DATA\GEO_COMM\REGION5_20151211\REGION5_20151211.gdb"16    LoadTarget = r"\\gisdata\planning\Cart\projects\Conflation\Workflow\conflation_sqlgis_geo.sde\Conflation.GEO."17    env.workspace = importGDB18    ### There are no tables in the conflated dataset products - handle similarly and separately19    skiplist = ['Stitch_Lines', 'RoadCenterlines', 'Overlaps_Gaps_MunicipalBoundary', 'Overlaps_Gaps_FIRE', 'Overlaps_Gaps_LAW', 'Overlaps_Gaps_PSAP', 'Overlaps_Gaps_ESZ', 'Overlaps_Gaps_EMS', 'Overlaps_Gaps_CountyBoundary', 'Overlaps_Gaps_AuthoritativeBoundary']20    tables = ListTables()21    for table in tables:22        print table23        target = LoadTarget+table24        print target25        26    datasets = ListDatasets("*")27    for fd in datasets:28        print fd29        featureClasses = ListFeatureClasses("*", "All", fd)30        for fc in featureClasses:31            print fc32            if fc in skiplist:33                print 'skipping'34            else:35                target = LoadTarget+fd+"/"+fc36                print "loading to "+target37                Append_management(fc, target, schema_type="NO_TEST")38                39def LoadAliasTables():40    from arcpy import Append_management, env, ListTables, ListWorkspaces, CalculateField_management41    importFolder = r"\\gisdata\planning\Cart\projects\Conflation\GIS_DATA\R1\Alias3"42    LoadTarget = r"Database Connections\Conflation2012_sde.sde\Conflation.SDE.RoadAlias"43    env.workspace = importFolder44    GDBList = []45    for gdb in ListWorkspaces("*", "FileGDB"):46        GDBList.append(gdb)47    48    for geodatabase in GDBList:49        env.workspace = geodatabase50        tables = ListTables("RoadAlias")51        for table in tables:52            print table53            CalculateField_management(table, "SEGID", expression="""[STEWARD]&" "& [SEGID]""", expression_type="VB", code_block="")54            Append_management(table, LoadTarget, schema_type="NO_TEST")55        print geodatabase56        57        58        59'''        60        61    ### There are no tables in the conflated dataset products62    tables = ListTables()63    for table in tables:64        print table65        target = LoadTarget+table66        print target67        68    datasets = ListDatasets("*")69    for fd in datasets:70        print fd71        featureClasses = ListFeatureClasses("*", "All", fd)72        for fc in featureClasses:73            print fc74            if fc in skiplist:75                print 'skipping'76            else:77                target = LoadTarget+fd+"/"+fc78                print "loading to "+target79                Append_management(fc, target, schema_type="NO_TEST")80'''...script_DashPart_Detail.js
Source:script_DashPart_Detail.js  
1let loadTarget = document.querySelector(".loading")23function show_loading(){4    loadTarget.style.display = "block";5    loadTarget.style.opacity = 1;6}7function hide_loading(){8    //loadTarget.style.display = "none";9    let loadEffect = setInterval(() => {10        if(!loadTarget.style.opacity) {11            loadTarget.style.opacity = 1;12        }13        if (loadTarget.style.opacity > 0){14            loadTarget.style.opacity -= 0.1;15        } else {16            clearInterval(loadEffect)17            loadTarget.style.display = "none"18        }19    },100)20}21function tampil_data(){22    show_loading()23    fetch("http://192.168.18.68:8055/items/order?fields=customer_id.customer_id,customer_id.customer_name,ticket_id.ticket_id,ticket_id.ticket_type&filter[customer_id]=2")24        .then((response) => response.json())25        .then((response) => {26            response.map(data => {27                //var textNode = document.createTextNode(response.)28            })29        })
...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
