Best Python code snippet using avocado_python
repeater-admin.js
Source:repeater-admin.js  
1jQuery(document).ready(function($){2    var online_portfolio_upload;3    var online_portfolio_selector;4    function online_portfolio_add_file(event, selector) {5        var upload = $(".uploaded-file"), frame;6        var $el = $(this);7        online_portfolio_selector = selector;8        event.preventDefault();9        // If the media frame already exists, reopen it.10        if ( online_portfolio_upload ) {11            online_portfolio_upload.open();12        } else {13            // Create the media frame.14            online_portfolio_upload = wp.media.frames.online_portfolio_upload =  wp.media({15                // Set the title of the modal.16                title: $el.data('choose'),17                // Customize the submit button.18                button: {19                    // Set the text of the button.20                    text: $el.data('update'),21                    // Tell the button not to close the modal, since we're22                    // going to refresh the page when the image is selected.23                    close: false24                }25            });26            // When an image is selected, run a callback.27            online_portfolio_upload.on( 'select', function() {28                // Grab the selected attachment.29                var attachment = online_portfolio_upload.state().get('selection').first();30                online_portfolio_upload.close();31                online_portfolio_selector.find('.upload').val(attachment.attributes.url);32                if ( attachment.attributes.type == 'image' ) {33                    online_portfolio_selector.find('.screenshot').empty().hide().append('<img src="' + attachment.attributes.url + '"><a class="remove-image">'+ online_portfolio_remove.remove +'</a>').slideDown('fast');34                }35                online_portfolio_selector.find('.upload-button-wdgt').unbind().addClass('remove-file').removeClass('upload-button-wdgt').val(online_portfolio_remove.remove);36                online_portfolio_selector.find('.of-background-properties').slideDown();37                online_portfolio_selector.find('.remove-image, .remove-file').on('click', function() {38                    online_portfolio_remove_file( $(this).parents('.section') );39                });40            });41        }42        // Finally, open the modal.43        online_portfolio_upload.open();44    }45    function online_portfolio_remove_file(selector) {46        selector.find('.remove-image').hide();47        selector.find('.upload').val('');48        selector.find('.of-background-properties').hide();49        selector.find('.screenshot').slideUp();50        selector.find('.remove-file').unbind().addClass('upload-button-wdgt').removeClass('remove-file').val(online_portfolio_remove.upload);51        if ( $('.section-upload .upload-notice').length > 0 ) {52            $('.upload-button-wdgt').remove();53        }54        selector.find('.upload-button-wdgt').on('click', function(event) {55            online_portfolio_add_file(event, $(this).parents('.section'));56        });57    }58    $('body').on('click','.remove-image, .remove-file', function() {59        online_portfolio_remove_file( $(this).parents('.section') );60    });61    $(document).on('click', '.upload-button-wdgt', function( event ) {62        online_portfolio_add_file(event, $(this).parents('.section'));63    });64    /**65     * Repeater Fields66     */67    function online_portfolio_refresh_repeater_values(){68        $(".online_portfolio-repeater-field-control-wrap").each(function(){69            var values = [];70            var $this = $(this);71            $this.find(".online_portfolio-repeater-field-control").each(function(){72                var valueToPush = {};73                $(this).find('[data-name]').each(function(){74                    var dataName = $(this).attr('data-name');75                    var dataValue = $(this).val();76                    valueToPush[dataName] = dataValue;77                });78                values.push(valueToPush);79            });80            $this.next('.online_portfolio-repeater-collector').val(JSON.stringify(values)).trigger('change');81        });82    }83    $('#customize-theme-controls').on('click','.online_portfolio-repeater-field-title',function(){84        $(this).next().slideToggle();85        $(this).closest('.online_portfolio-repeater-field-control').toggleClass('expanded');86    });87    $('#customize-theme-controls').on('click', '.online_portfolio-repeater-field-close', function(){88        $(this).closest('.online_portfolio-repeater-fields').slideUp();;89        $(this).closest('.online_portfolio-repeater-field-control').toggleClass('expanded');90    });91    $("body").on("click",'.online_portfolio-add-control-field', function(){92        var $this = $(this).parent();93        if(typeof $this != 'undefined') {94            var field = $this.find(".online_portfolio-repeater-field-control:first").clone();95            if(typeof field != 'undefined'){96                field.find("input[type='text'][data-name]").each(function(){97                    var defaultValue = $(this).attr('data-default');98                    $(this).val(defaultValue);99                });100                field.find("textarea[data-name]").each(function(){101                    var defaultValue = $(this).attr('data-default');102                    $(this).val(defaultValue);103                });104                field.find("select[data-name]").each(function(){105                    var defaultValue = $(this).attr('data-default');106                    $(this).val(defaultValue);107                });108                field.find(".radio-labels input[type='radio']").each(function(){109                    var defaultValue = $(this).closest('.radio-labels').next('input[data-name]').attr('data-default');110                    $(this).closest('.radio-labels').next('input[data-name]').val(defaultValue);111                    if($(this).val() == defaultValue){112                        $(this).prop('checked',true);113                    }else{114                        $(this).prop('checked',false);115                    }116                });117                field.find(".selector-labels label").each(function(){118                    var defaultValue = $(this).closest('.selector-labels').next('input[data-name]').attr('data-default');119                    var dataVal = $(this).attr('data-val');120                    $(this).closest('.selector-labels').next('input[data-name]').val(defaultValue);121                    if(defaultValue == dataVal){122                        $(this).addClass('selector-selected');123                    }else{124                        $(this).removeClass('selector-selected');125                    }126                });127                field.find('.range-input').each(function(){128                    var $dis = $(this);129                    $dis.removeClass('ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all').empty();130                    var defaultValue = parseFloat($dis.attr('data-defaultvalue'));131                    $dis.siblings(".range-input-selector").val(defaultValue);132                    $dis.slider({133                        range: "min",134                        value: parseFloat($dis.attr('data-defaultvalue')),135                        min: parseFloat($dis.attr('data-min')),136                        max: parseFloat($dis.attr('data-max')),137                        step: parseFloat($dis.attr('data-step')),138                        slide: function( event, ui ) {139                            $dis.siblings(".range-input-selector").val(ui.value );140                            online_portfolio_refresh_repeater_values();141                        }142                    });143                });144                field.find('.onoffswitch').each(function(){145                    var defaultValue = $(this).next('input[data-name]').attr('data-default');146                    $(this).next('input[data-name]').val(defaultValue);147                    if(defaultValue == 'on'){148                        $(this).addClass('switch-on');149                    }else{150                        $(this).removeClass('switch-on');151                    }152                });153                field.find(".attachment-media-view").each(function(){154                    var defaultValue = $(this).find('input[data-name]').attr('data-default');155                    $(this).find('input[data-name]').val(defaultValue);156                    if(defaultValue){157                        $(this).find(".thumbnail-image").html('<img src="'+defaultValue+'"/>').prev('.placeholder').addClass('hidden');158                    }else{159                        $(this).find(".thumbnail-image").html('').prev('.placeholder').removeClass('hidden');160                    }161                });162                field.find(".online_portfolio-icon-list").each(function(){163                    var defaultValue = $(this).next('input[data-name]').attr('data-default');164                    $(this).next('input[data-name]').val(defaultValue);165                    $(this).prev('.online_portfolio-selected-icon').children('i').attr('class','').addClass(defaultValue);166                    $(this).find('li').each(function(){167                        var icon_class = $(this).find('i').attr('class');168                        if(defaultValue == icon_class ){169                            $(this).addClass('icon-active');170                        }else{171                            $(this).removeClass('icon-active');172                        }173                    });174                });175                field.find(".online_portfolio-multi-category-list").each(function(){176                    var defaultValue = $(this).next('input[data-name]').attr('data-default');177                    $(this).next('input[data-name]').val(defaultValue);178                    $(this).find('input[type="checkbox"]').each(function(){179                        if($(this).val() == defaultValue){180                            $(this).prop('checked',true);181                        }else{182                            $(this).prop('checked',false);183                        }184                    });185                });186                field.find('.online_portfolio-fields').show();187                $this.find('.online_portfolio-repeater-field-control-wrap').append(field);188                field.addClass('expanded').find('.online_portfolio-repeater-fields').show();189                $('.accordion-section-content').animate({ scrollTop: $this.height() }, 1000);190                online_portfolio_refresh_repeater_values();191            }192        }193        return false;194    });195    $("#customize-theme-controls").on("click", ".online_portfolio-repeater-field-remove",function(){196        if( typeof	$(this).parent() != 'undefined'){197            $(this).closest('.online_portfolio-repeater-field-control').slideUp('normal', function(){198                $(this).remove();199                online_portfolio_refresh_repeater_values();200            });201        }202        return false;203    });204    $("#customize-theme-controls").on('keyup change', '[data-name]',function(){205        online_portfolio_refresh_repeater_values();206        return false;207    });208    $("#customize-theme-controls").on('change', 'input[type="checkbox"][data-name]',function(){209        if($(this).is(":checked")){210            $(this).val('yes');211        }else{212            $(this).val('no');213        }214        online_portfolio_refresh_repeater_values();215        return false;216    });217    /*Drag and drop to change order*/218    $(".online_portfolio-repeater-field-control-wrap").sortable({219        orientation: "vertical",220        update: function( event, ui ) {221            online_portfolio_refresh_repeater_values();222        }223    });224    // Set all variables to be used in scope225    var frame;226    // ADD IMAGE LINK227    $('.customize-control-repeater').on( 'click', '.online_portfolio-upload-button', function( event ){228        event.preventDefault();229        var imgContainer = $(this).closest('.online_portfolio-fields-wrap').find( '.thumbnail-image'),230            placeholder = $(this).closest('.online_portfolio-fields-wrap').find( '.placeholder'),231            imgIdInput = $(this).siblings('.upload-id');232        // Create a new media frame233        frame = wp.media({234            title: 'Select or Upload Image',235            button: {236                text: 'Use Image'237            },238            multiple: false  // Set to true to allow multiple files to be selected239        });240        // When an image is selected in the media frame...241        frame.on( 'select', function() {242            // Get media attachment details from the frame state243            var attachment = frame.state().get('selection').first().toJSON();244            // Send the attachment URL to our custom image input field.245            imgContainer.html( '<img src="'+attachment.url+'" style="max-width:100%;"/>' );246            placeholder.addClass('hidden');247            // Send the attachment id to our hidden input248            imgIdInput.val( attachment.url ).trigger('change');249        });250        // Finally, open the modal on click251        frame.open();252    });253    // DELETE IMAGE LINK254    $('.customize-control-repeater').on( 'click', '.online_portfolio-delete-button', function( event ){255        event.preventDefault();256        var imgContainer = $(this).closest('.online_portfolio-fields-wrap').find( '.thumbnail-image'),257            placeholder = $(this).closest('.online_portfolio-fields-wrap').find( '.placeholder'),258            imgIdInput = $(this).siblings('.upload-id');259        // Clear out the preview image260        imgContainer.find('img').remove();261        placeholder.removeClass('hidden');262        // Delete the image id from the hidden input263        imgIdInput.val( '' ).trigger('change');264    });265    $('body').on('click','.selector-labels label', function(){266        var $this = $(this);267        var value = $this.attr('data-val');268        $this.siblings().removeClass('selector-selected');269        $this.addClass('selector-selected');270        $this.closest('.selector-labels').next('input').val(value).trigger('change');271    });272    $('body').on('change','.online_portfolio-type-radio input[type="radio"]', function(){273        var $this = $(this);274        $this.parent('label').siblings('label').find('input[type="radio"]').prop('checked',false);275        var value = $this.closest('.radio-labels').find('input[type="radio"]:checked').val();276        $this.closest('.radio-labels').next('input').val(value).trigger('change');277    });278    $('body').on('click', '.onoffswitch', function(){279        var $this = $(this);280        if($this.hasClass('switch-on')){281            $(this).removeClass('switch-on');282            $this.next('input').val('off').trigger('change')283        }else{284            $(this).addClass('switch-on');285            $this.next('input').val('on').trigger('change')286        }287    });288    $('.range-input').each(function(){289        var $this = $(this);290        $this.slider({291            range: "min",292            value: parseFloat($this.attr('data-value')),293            min: parseFloat($this.attr('data-min')),294            max: parseFloat($this.attr('data-max')),295            step: parseFloat($this.attr('data-step')),296            slide: function( event, ui ) {297                $this.siblings(".range-input-selector").val(ui.value );298                online_portfolio_refresh_repeater_values();299            }300        });301    });302    $('body').on('click', '.online_portfolio-icon-list li', function(){303        var icon_class = $(this).find('i').attr('class');304        $(this).addClass('icon-active').siblings().removeClass('icon-active');305        $(this).parent('.online_portfolio-icon-list').prev('.online_portfolio-selected-icon').children('i').attr('class','').addClass(icon_class);306        $(this).parent('.online_portfolio-icon-list').next('input').val(icon_class).trigger('change');307        online_portfolio_refresh_repeater_values();308    });309    $('body').on('click', '.online_portfolio-selected-icon', function(){310        $(this).next().slideToggle();311    });312    //MultiCheck box Control JS313    $( 'body' ).on( 'change', '.online_portfolio-type-multicategory input[type="checkbox"]' , function() {314        var checkbox_values = $( this ).parents( '.online_portfolio-type-multicategory' ).find( 'input[type="checkbox"]:checked' ).map(function(){315            return $( this ).val();316        }).get().join( ',' );317        $( this ).parents( '.online_portfolio-type-multicategory' ).find( 'input[type="hidden"]' ).val( checkbox_values ).trigger( 'change' );318        online_portfolio_refresh_repeater_values();319    });320    $('body').on( 'click', '.vl-bottom-block-layout label[data-val]', function(){321        if( $(this).attr('data-val') == 'style2' ){322            $(this).closest('.online_portfolio-repeater-fields').find('.vl-bottom-block-cat2, .vl-bottom-block-cat3').fadeOut();323        }else{324            $(this).closest('.online_portfolio-repeater-fields').find('.vl-bottom-block-cat1, .vl-bottom-block-cat2, .vl-bottom-block-cat3').fadeIn();325        }326    });327    $('.vl-bottom-block-layout').each(function(){328        if( $(this).find('input[type="hidden"]').val() == 'style2' ){329            $(this).closest('.online_portfolio-repeater-fields').find('.vl-bottom-block-cat2, .vl-bottom-block-cat3').fadeOut();330        }else{331            $(this).closest('.online_portfolio-repeater-fields').find('.vl-bottom-block-cat1, .vl-bottom-block-cat2, .vl-bottom-block-cat2').fadeIn();332        }333    });334    /******for pulling multiple categories ***/335// Holds the status of whether or not the rest of the code should be run336    /**337     * Multiple checkboxes338     */339    $( '.customize-control-checkbox-multiple input[type="checkbox"]' ).on( 'change', function() {340        checkbox_values = $( this ).parents( '.customize-control' ).find( 'input[type="checkbox"]:checked' ).map(341            function() {342                return this.value;343            }344        ).get().join( ',' );345        $( this ).parents( '.customize-control' ).find( 'input[type="hidden"]' ).val( checkbox_values ).trigger( 'change' );346    });...background.js
Source:background.js  
1'use strict'2import { app, protocol, BrowserWindow, ipcMain, Menu} from 'electron'3import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'4import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'5const dgram = require('dgram');6const isDevelopment = process.env.NODE_ENV !== 'production'7const serialport = require("serialport").SerialPort8let port9const Datastore = require('nedb-promises')10let db = Datastore.create('/path/to/db.db')11const net = require('net')12const connectedSocketClient = new Set()13let win14let moment = require('moment')15let udpSenderStatus = {16  ip:'',17  port:'',18  status:false19}20let viewSetup = {21  showHex:false,22  sendHex:false,23  sendCrLf:false24}25let onlineState = {26  serial:false,27  tcpserver:false,28  tcpclient:false,29  udpserver:false,30  udpsender:false31}32// Scheme must be registered before the app is ready33protocol.registerSchemesAsPrivileged([34  { scheme: 'app', privileges: { secure: true, standard: true } }35])36function createWindow() {37  win = new BrowserWindow({38    width: 1280,39    height: 600,40    webPreferences: {41      nodeIntegration: true42    }43  })44  // Menu.setApplicationMenu(null)45  if (process.env.WEBPACK_DEV_SERVER_URL) {46    win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)47    if (!process.env.IS_TEST) win.webContents.openDevTools()48  } else {49    createProtocol('app')50    win.loadURL('app://./index.html')51  }52  win.on('closed', () => {53    win = null54  })55  //Remove Menu Tab56  Menu.setApplicationMenu(null)57}58app.on('window-all-closed', () => {59  if (process.platform !== 'darwin') {60    app.quit()61  }62})63app.on('activate', () => {64  if (win === null) {65    createWindow()66  }67})68app.on('ready', async () => {69  if (isDevelopment && !process.env.IS_TEST) {70    try {71      await installExtension(VUEJS_DEVTOOLS)72    } catch (e) {73      console.error('Vue Devtools failed to install:', e.toString())74    }75  }76  createWindow()77})78if (isDevelopment) {79  if (process.platform === 'win32') {80    process.on('message', (data) => {81      if (data === 'graceful-exit') {82        app.quit()83      }84    })85  } else {86    process.on('SIGTERM', () => {87      app.quit()88    })89  }90}91async function writedb(protocol, from, data) {92  const returnMsg = {93    createAt: moment().format("YYYY-MM-DD HH:mm:ss"),94    protocol: protocol,95    from: from,96    msg : dataDecode(data)97  }98  const wd = await db.insert(returnMsg)99  readdb()100}101async function readdb() {102  const rd = await db.find()103  win.webContents.send('rtMsg', rd)104  // console.log(rd)105}106function removeAll () {107  db.remove({}, {multi:true}) 108}109function dataDecode (data) {110  if (viewSetup.showHex === true) {111    let msg = data.toString('hex').replace(/(.{2})/g,"$1,")112    return msg = 'hex '+msg.slice(0,-1)113  } else {114    return data.toString()115  }116}117function serialPortConnent(com, baud) {118  try {119    port = new serialport(com, {120      buadrate: baud,121      // parser: serialport.parsers.readline('\n')122    })123    onlineState.serial = true124    win.webContents.send('onlineStatus', onlineState)125    port.on('data', data => {126      console.log(data)127      writedb("Serial",com,data)128    })129    port.on('close', function(err) {130      console.log('serialport Close', err)131      onlineState.serial = false132      win.webContents.send('onlineStatus', onlineState)133    })134  } catch(err) {135    win.webContents.send('alert', JSON.stringify(err));136    onlineState.serial = false137    win.webContents.send('onlineStatus', onlineState)138  }139}140serialPortConnent.disconnect = () => {141  try {142    port.close()143    onlineState.serial = false144    win.webContents.send('onlineStatus', onlineState)145  } catch(err) {146    win.webContents.send('alert', JSON.stringify(err));147    onlineState.serial = false148    win.webContents.send('onlineStatus', onlineState)149  }150  151}152function serialWrite(data) {153  port.write(data)154  writedb("Serial",'This',data)155}156// TCP Server to Client Broadcast Message157connectedSocketClient.broadcast = function (text, except) {158  for (let Client of this) {159    if (Client !== except) {160      Client.write(text)161    }162  }163  writedb("TcpServer",'This',text)164}165// TCP Server166const server = net.createServer (function (Client) {167  connectedSocketClient.add(Client)168  169  Client.on('data', function (data) {170    // console.log('Tcp Server Recv Data %d: %s', Client.remotePort,data.toString());171    if (!data) return172    let address = (`${Client.remoteAddress}:${Client.remotePort}`)173    writedb("TcpServer",address,data)174  })175  Client.on('close', function() {176    connectedSocketClient.delete(Client)177  })178})179server.on('error', function(err) {180  // Tcp server Error Report181  win.webContents.send('alert', JSON.stringify(err));182})183function tcpServerConnect(ip, port) {184  try {185    server.listen(port, function() {186      console.log('Server listening: '+ JSON.stringify(server.address()));187      onlineState.tcpserver = true188      win.webContents.send('onlineStatus', onlineState)189  190      server.on('close', function(){191        console.log("Server Close");192        onlineState.tcpserver = false193        win.webContents.send('onlineStatus', onlineState)194      })195    })196  } catch (err) {197    win.webContents.send('alert', JSON.stringify(err));198    onlineState.tcpserver = false199    win.webContents.send('onlineStatus', onlineState)200  }  201}202tcpServerConnect.disconnect = () => {203  for (let Clinet of connectedSocketClient) {Clinet.destroy()}204  server.close(function() {server.unref()})205}206// TcpClient Module207let TcpClient208const tcpClientConnect = (ip, port) => {209  try {210    TcpClient = net.connect({port:port, host:ip}, ()=>{211      console.log('connected tcp clinet : '+ ip + ',' + port)212      onlineState.tcpclient = true213      win.webContents.send('onlineStatus', onlineState)214    })215    TcpClient.on('close', function() {216      console.log('tcpclinet disconnected')217      onlineState.tcpclient = false218      win.webContents.send('onlineStatus', onlineState)219    })220    TcpClient.on('data', function(data) {221      const address = ip+':'+port222      writedb("TcpClient",address,data)223    })224    TcpClient.on('end', function() {225      console.log('client end')226      onlineState.tcpclient = false227      win.webContents.send('onlineStatus', onlineState)228    })229    TcpClient.on('error', function(err) {230      win.webContents.send('alert', JSON.stringify(err));231      onlineState.tcpclient = false232      win.webContents.send('onlineStatus', onlineState)233    })234    return TcpClient235  } catch (err) {236    win.webContents.send('alert', JSON.stringify(err));237    onlineState.tcpclient = false238    win.webContents.send('onlineStatus', onlineState)239  }240}241tcpClientConnect.disconnect = () => {242  TcpClient.end()243}244function tcpClientWrite (data) {245  TcpClient.write(data)246  writedb("TcpClient",'This',data)247}248let UdpServer = dgram.createSocket('udp4')249//UDP Server250function udpServerConnect(ip,port) {251  try {252    UdpServer.on('error',(err) =>{253      win.webContents.send('alert', JSON.stringify(err));254    });255  256    UdpServer.on('message', (data, rinfo) =>{257      const address = (`${rinfo.address}:${rinfo.port}`);258      writedb("UdpServer",address,data)259    });260  261    UdpServer.on('listening', () => {262      const address = UdpServer.address();263      console.log(`server listening ${address.address}:${address.port}`);264      onlineState.udpserver = true265      win.webContents.send('onlineStatus', onlineState)266  267    });268  269    UdpServer.on('close', () => {270      console.log('UdpServer Close')271      onlineState.udpserver = false272      win.webContents.send('onlineStatus', onlineState)273      UdpServer = null274      UdpServer = dgram.createSocket('udp4')275    })276  277    UdpServer.bind(port,ip)278    // UdpServer.close()279  } catch (err) {280    win.webContents.send('alert', JSON.stringify(err));281    onlineState.udpserver = false282    win.webContents.send('onlineStatus', onlineState)283  }284}285udpServerConnect.disconnect = function() {286  UdpServer.close()287}288let UdpClinet = dgram.createSocket('udp4');289function udpSenderWrite (msg) {290  // let message = new Buffer(msg);291  UdpClinet.send(msg, 0, msg.length, udpSenderStatus.port, udpSenderStatus.ip, function(err){292    if (err) {293      win.webContents.send('alert', JSON.stringify(err));294    }295    writedb("UdpBroad",'This',msg)296  })297}298function udpSenderConnect(ip, port) {299  udpSenderStatus.ip = ip;300  udpSenderStatus.port = port;301  onlineState.udpsender = true302  win.webContents.send('onlineStatus', onlineState)303}304udpSenderConnect.disconnect = () => {305  udpSenderStatus.ip = null;306  udpSenderStatus.port = null;307  onlineState.udpsender = false;308  win.webContents.send('onlineStatus', onlineState);309}310const connections = [serialPortConnent, tcpServerConnect, tcpClientConnect, udpServerConnect, udpSenderConnect]311ipcMain.on('OnConnect', (e, connect) => {312  if (connect.state === true){313    connections[connect.protocol](connect.ip,Number(connect.port))314  }315  else {316    connections[connect.protocol].disconnect()317  }318})319ipcMain.on('sendMsg', (event, msg) => {320  if (viewSetup.sendHex === true) {321    msg = msg.replace(",","")322    if(msg.length % 2 !== 0) {323      win.webContents.send('alert', "Byte ì를 íì¸ í´ì£¼ì¸ì")     324    } else {325      let procMsg = hexToBytes(msg)326      let message = Buffer.from(procMsg)327      sendMsg(message)328    }329  } else {330    if (viewSetup.sendCrLf === true) {331      msg = msg+"\n"332    }333    let message = Buffer.from(msg)334    sendMsg(message)335  }336  337})338function hexToBytes(hex) {  339  for (var bytes = [], c = 0; c < hex.length; c += 2)340  bytes.push(parseInt(hex.substr(c, 2), 16));341  if (viewSetup.sendCrLf === true){342    bytes.push(0x0d,0x0a)343  }344  return bytes;345}346function sendMsg (msg) {347  if (onlineState.serial === true) {348    serialWrite(msg)349  }350  if (onlineState.tcpserver === true) {351    connectedSocketClient.broadcast(msg)352  }353  if (onlineState.tcpclient === true) {354    tcpClientWrite(msg)355  }356  if (onlineState.udpsender === true) {357    udpSenderWrite(msg)358  }359}360ipcMain.on('viewSetup',(e,value) => {361  viewSetup = value362  console.log(value)363} )364removeAll()365// sendHex:false,...onlinehandler.js
Source:onlinehandler.js  
1// Copyright 2008 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7//      http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14/**15 * @fileoverview This event handler will dispatch events when16 * {@code navigator.onLine} changes.  HTML5 defines two events, online and17 * offline that is fired on the window.  As of today 3 browsers support these18 * events: Firefox 3 (Gecko 1.9), Opera 9.5, and IE8.  If we have any of these19 * we listen to the 'online' and 'offline' events on the current window20 * object.  Otherwise we poll the navigator.onLine property to detect changes.21 *22 * Note that this class only reflects what the browser tells us and this usually23 * only reflects changes to the File -> Work Offline menu item.24 *25 * @author arv@google.com (Erik Arvidsson)26 * @see ../demos/onlinehandler.html27 */28// TODO(arv): We should probably implement some kind of polling service and/or29// a poll for changes event handler that can be used to fire events when a state30// changes.31goog.provide('goog.events.OnlineHandler');32goog.provide('goog.events.OnlineHandler.EventType');33goog.require('goog.Timer');34goog.require('goog.events.BrowserFeature');35goog.require('goog.events.EventHandler');36goog.require('goog.events.EventTarget');37goog.require('goog.events.EventType');38goog.require('goog.net.NetworkStatusMonitor');39/**40 * Basic object for detecting whether the online state changes.41 * @constructor42 * @extends {goog.events.EventTarget}43 * @implements {goog.net.NetworkStatusMonitor}44 */45goog.events.OnlineHandler = function() {46  goog.events.OnlineHandler.base(this, 'constructor');47  /**48   * @private {goog.events.EventHandler<!goog.events.OnlineHandler>}49   */50  this.eventHandler_ = new goog.events.EventHandler(this);51  // Some browsers do not support navigator.onLine and therefore we don't52  // bother setting up events or timers.53  if (!goog.events.BrowserFeature.HAS_NAVIGATOR_ONLINE_PROPERTY) {54    return;55  }56  if (goog.events.BrowserFeature.HAS_HTML5_NETWORK_EVENT_SUPPORT) {57    var target = goog.events.BrowserFeature.HTML5_NETWORK_EVENTS_FIRE_ON_BODY ?58        document.body :59        window;60    this.eventHandler_.listen(61        target, [goog.events.EventType.ONLINE, goog.events.EventType.OFFLINE],62        this.handleChange_);63  } else {64    this.online_ = this.isOnline();65    this.timer_ = new goog.Timer(goog.events.OnlineHandler.POLL_INTERVAL_);66    this.eventHandler_.listen(this.timer_, goog.Timer.TICK, this.handleTick_);67    this.timer_.start();68  }69};70goog.inherits(goog.events.OnlineHandler, goog.events.EventTarget);71/**72 * Enum for the events dispatched by the OnlineHandler.73 * @enum {string}74 * @deprecated Use goog.net.NetworkStatusMonitor.EventType instead.75 */76goog.events.OnlineHandler.EventType = goog.net.NetworkStatusMonitor.EventType;77/**78 * The time to wait before checking the {@code navigator.onLine} again.79 * @type {number}80 * @private81 */82goog.events.OnlineHandler.POLL_INTERVAL_ = 250;83/**84 * Stores the last value of the online state so we can detect if this has85 * changed.86 * @type {boolean}87 * @private88 */89goog.events.OnlineHandler.prototype.online_;90/**91 * The timer object used to poll the online state.92 * @type {goog.Timer}93 * @private94 */95goog.events.OnlineHandler.prototype.timer_;96/** @override */97goog.events.OnlineHandler.prototype.isOnline = function() {98  return goog.events.BrowserFeature.HAS_NAVIGATOR_ONLINE_PROPERTY ?99      navigator.onLine :100      true;101};102/**103 * Called every time the timer ticks to see if the state has changed and when104 * the online state changes the method handleChange_ is called.105 * @private106 */107goog.events.OnlineHandler.prototype.handleTick_ = function() {108  var online = this.isOnline();109  if (online != this.online_) {110    this.online_ = online;111    this.handleChange_();112  }113};114/**115 * Called when the online state changes.  This dispatches the116 * {@code ONLINE} and {@code OFFLINE} events respectively.117 * @private118 */119goog.events.OnlineHandler.prototype.handleChange_ = function() {120  var type = this.isOnline() ? goog.net.NetworkStatusMonitor.EventType.ONLINE :121                               goog.net.NetworkStatusMonitor.EventType.OFFLINE;122  this.dispatchEvent(type);123};124/** @override */125goog.events.OnlineHandler.prototype.disposeInternal = function() {126  goog.events.OnlineHandler.base(this, 'disposeInternal');127  this.eventHandler_.dispose();128  this.eventHandler_ = null;129  if (this.timer_) {130    this.timer_.dispose();131    this.timer_ = null;132  }...onlinelistener_test.js
Source:onlinelistener_test.js  
1// Copyright 2008 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7//      http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14goog.provide('goog.events.OnlineHandlerTest');15goog.setTestOnly('goog.events.OnlineHandlerTest');16goog.require('goog.events');17goog.require('goog.events.BrowserFeature');18goog.require('goog.events.Event');19goog.require('goog.events.EventHandler');20goog.require('goog.events.OnlineHandler');21goog.require('goog.net.NetworkStatusMonitor');22goog.require('goog.testing.MockClock');23goog.require('goog.testing.PropertyReplacer');24goog.require('goog.testing.jsunit');25goog.require('goog.testing.recordFunction');26var stubs = new goog.testing.PropertyReplacer();27var clock = new goog.testing.MockClock();28var online = true;29var onlineCount;30var offlineCount;31function listenToEvents(oh) {32  onlineCount = 0;33  offlineCount = 0;34  goog.events.listen(35      oh, goog.net.NetworkStatusMonitor.EventType.ONLINE, function(e) {36        assertTrue(oh.isOnline());37        onlineCount++;38      });39  goog.events.listen(40      oh, goog.net.NetworkStatusMonitor.EventType.OFFLINE, function(e) {41        assertFalse(oh.isOnline());42        offlineCount++;43      });44}45function setUp() {46  stubs.set(goog.events.OnlineHandler.prototype, 'isOnline', function() {47    return online;48  });49}50function tearDown() {51  stubs.reset();52  clock.uninstall();53}54function testConstructAndDispose() {55  var oh = new goog.events.OnlineHandler();56  oh.dispose();57}58function testNoOnlineProperty() {59  stubs.set(goog.events.BrowserFeature, 'HAS_NAVIGATOR_ONLINE_PROPERTY', false);60  stubs.set(61      goog.events.EventHandler.prototype, 'listen',62      goog.testing.recordFunction());63  var oh = new goog.events.OnlineHandler();64  assertEquals(0, oh.eventHandler_.listen.getCallCount());65  oh.dispose();66}67function testNonHtml5() {68  clock.install();69  stubs.set(70      goog.events.BrowserFeature, 'HAS_HTML5_NETWORK_EVENT_SUPPORT', false);71  var oh = new goog.events.OnlineHandler();72  listenToEvents(oh);73  clock.tick(500);74  online = false;75  clock.tick(500);76  assertEquals(0, onlineCount);77  assertEquals(1, offlineCount);78  online = true;79  clock.tick(500);80  assertEquals(1, onlineCount);81  assertEquals(1, offlineCount);82  oh.dispose();83  clock.dispose();84}85function testHtml5() {86  stubs.set(87      goog.events.BrowserFeature, 'HAS_HTML5_NETWORK_EVENT_SUPPORT', true);88  // Test for browsers that fire network events on document.body.89  stubs.set(90      goog.events.BrowserFeature, 'HTML5_NETWORK_EVENTS_FIRE_ON_BODY', true);91  var oh = new goog.events.OnlineHandler();92  listenToEvents(oh);93  online = false;94  var e = new goog.events.Event('offline');95  goog.events.fireListeners(document.body, e.type, false, e);96  assertEquals(0, onlineCount);97  assertEquals(1, offlineCount);98  online = true;99  e = new goog.events.Event('online');100  goog.events.fireListeners(document.body, e.type, false, e);101  assertEquals(1, onlineCount);102  assertEquals(1, offlineCount);103  oh.dispose();104  // Test for browsers that fire network events on window.105  stubs.set(106      goog.events.BrowserFeature, 'HTML5_NETWORK_EVENTS_FIRE_ON_BODY', false);107  oh = new goog.events.OnlineHandler();108  listenToEvents(oh);109  online = false;110  e = new goog.events.Event('offline');111  goog.events.fireListeners(window, e.type, false, e);112  assertEquals(0, onlineCount);113  assertEquals(1, offlineCount);114  online = true;115  e = new goog.events.Event('online');116  goog.events.fireListeners(window, e.type, false, e);117  assertEquals(1, onlineCount);118  assertEquals(1, offlineCount);119  oh.dispose();...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!!
