text:
from PLC.Method import Method
from PLC.Parameter import Parameter, Mixed
from PLC.Auth import Auth
from PLC.sendmail import sendmail

class NotifySupport(Method):
    """
    Sends an e-mail message to the configured support address.

    Returns 1 if successful.
    """

    roles = ['admin']

    accepts = [
        Auth(),
        Parameter(str, "E-mail subject"),
        Parameter(str, "E-mail body")
        ]

    returns = Parameter(int, '1 if successful')

    def call(self, auth, subject, body):
        to_name="%s Support"%self.api.config.PLC_NAME
        to_address=self.api.config.PLC_MAIL_SUPPORT_ADDRESS

        # Send email
        sendmail(self.api, To=(to_name,to_address),
                 Subject = subject,
                 Body = body)

        # Logging variables
        #self.event_objects = {'Person': [person['person_id'] for person in persons]}
        self.message = subject

        return 1

redpajama_set_name: RedPajamaGithub


text:
define([
    "./Message",
    "../Path",
    "../events/BaseEvent",
    "../events/ChangeEvent",
    "../events/ActionEvent"
], function(Message, Path, BaseEvent, ChangeEvent, ActionEvent) {
    var BaseTransport = function() {
        this.outgoingMessages = [];
        this.connected = false;
    };

    BaseTransport.prototype.onConnectionChange = function(connected) {};

    BaseTransport.prototype.init = function(ankorSystem) {
        this.ankorSystem = ankorSystem;
        this.utils = ankorSystem.utils;

        if (this.onConnectionChange) this.onConnectionChange(this.connected);
    };

    BaseTransport.prototype.sendEvent = function(event) {
        var message = new Message(event);
        this.sendMessage(message);
    };

    BaseTransport.prototype.sendMessage = function(message) {

        var stateProps = this.ankorSystem.stateProps;
        if (stateProps) {
            message.stateValues = {};
            for (var i = 0, stateProp; (stateProp = stateProps[i]); i++) {
                message.stateValues[stateProp] = this.ankorSystem.model.getValue(new Path(stateProp));
            }
        }

        this.outgoingMessages.push(message);
        if (this.ankorSystem.debug) {
            message.event.pathString = message.event.path.toString();
            console.log("OUT", message);
        }
    };

    BaseTransport.prototype.receiveMessage = function(message) {
        if (this.ankorSystem.debug) {
            message.event.pathString = message.event.path.toString();
            console.log("IN", message);
        }
        this.ankorSystem.onIncomingEvent(message.event);
    };

    BaseTransport.prototype.decodeMessage = function(parsedJson) {
        var event = null;
        var path = new Path(parsedJson.property);

        if (parsedJson.change) {
            event = new ChangeEvent(path, "ankorRemoteEvent", parsedJson.change.type, parsedJson.change.key, parsedJson.change.value);
        }
        else if (parsedJson.action) {
            if (parsedJson.action instanceof Object) {
                event = new ActionEvent(path, "ankorRemoteEvent", parsedJson.action.name, parsedJson.action.params);
            }
            else {
                event = new ActionEvent(path, "ankorRemoteEvent", parsedJson.action, null);
            }
        }
        else {
            event = new BaseEvent(path, "ankorRemoteEvent");
        }

        var message = new Message(event);

        // unexpected side effects
        if (parsedJson.stateProps && true /* TODO: Check if message is newer */ ) {
            this.ankorSystem.stateProps = message.stateProps = parsedJson.stateProps;
        }

        return message;
    };

    BaseTransport.prototype.encodeMessage = function(message) {
        var event = message.event;
        var jsonMessage = {
            property: event.path.toString()
        };

        if (message.stateValues) {
            jsonMessage.stateValues = message.stateValues;
        }

        if (event instanceof ActionEvent) {
            jsonMessage.action = {
                name: event.actionName,
                params: event.params
            };
        }
        else if (event instanceof ChangeEvent) {
            jsonMessage.change = {
                type: event.type,
                key: event.key,
                value: event.value
            };
        }
        else if (message.connectParams) {
            jsonMessage.connectParams = message.connectParams;
        }
        return jsonMessage;
    };

    return BaseTransport;
});


text:
package io.cdap.delta.test.mock;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import io.cdap.cdap.api.annotation.Name;
import io.cdap.cdap.api.data.format.StructuredRecord;
import io.cdap.cdap.api.data.schema.Schema;
import io.cdap.cdap.api.plugin.PluginClass;
import io.cdap.cdap.api.plugin.PluginConfig;
import io.cdap.cdap.api.plugin.PluginPropertyField;
import io.cdap.cdap.internal.io.SchemaTypeAdapter;
import io.cdap.delta.api.ChangeEvent;
import io.cdap.delta.api.Configurer;
import io.cdap.delta.api.DeltaSource;
import io.cdap.delta.api.DeltaSourceContext;
import io.cdap.delta.api.EventEmitter;
import io.cdap.delta.api.EventReader;
import io.cdap.delta.api.EventReaderDefinition;
import io.cdap.delta.api.SourceConfigurer;
import io.cdap.delta.api.assessment.StandardizedTableDetail;
import io.cdap.delta.api.assessment.TableAssessor;
import io.cdap.delta.api.assessment.TableDetail;
import io.cdap.delta.api.assessment.TableList;
import io.cdap.delta.api.assessment.TableRegistry;
import io.cdap.delta.proto.Artifact;
import io.cdap.delta.proto.Plugin;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;

/**
 * Mock DeltaSource used in unit tests. Emits a pre-configured set of events.
 */
@io.cdap.cdap.api.annotation.Plugin(type = DeltaSource.PLUGIN_TYPE)
@Name(MockSource.NAME)
public class MockSource implements DeltaSource {
  public static final String NAME = "mock";
  public static final PluginClass PLUGIN_CLASS = getPluginClass();
  private static final Gson GSON = new GsonBuilder()
    .registerTypeAdapter(StructuredRecord.class, new StructuredRecordSerde())
    .registerTypeAdapter(Schema.class, new SchemaTypeAdapter())
    .registerTypeAdapter(ChangeEvent.class, new ChangeEventDeserializer())
    .create();
  private final Conf conf;

  public MockSource(Conf conf) {
    this.conf = conf;
  }

  @Override
  public void configure(SourceConfigurer configurer) {
    // no-op
  }

  @Override
  public EventReader createReader(EventReaderDefinition definition, DeltaSourceContext context, EventEmitter emitter) {
    if (conf.proceedFile != null) {
      File proceedFile = new File(conf.proceedFile);
      if (!proceedFile.exists()) {
        return new FailureEventReader(context);
      }
    }
    try {
      context.setOK();
    } catch (IOException e) {
      // shouldn't happen in unit tests
    }
    return new MockEventReader(GSON.fromJson(conf.events, new TypeToken<List<? extends ChangeEvent>>() { }.getType()),
                               emitter, conf.maxEvents);
  }

  @Override
  public TableRegistry createTableRegistry(Configurer configurer) {
    // fake table registry returns null for everything.
    // this doesn't cause errors because TableRegistry is not used at runtime, only for creating pipelines
    return new TableRegistry() {
      @Override
      public TableList listTables() {
        return null;
      }

      @Override
      public TableDetail describeTable(String database, String table) {
        return null;
      }

      @Override
      public TableDetail describeTable(String database, String schema, String table) {
        return null;
      }

      @Override
      public StandardizedTableDetail standardize(TableDetail tableDetail) {
        return null;
      }

      @Override
      public void close() {

      }
    };
  }

  @Override
  public TableAssessor<TableDetail> createTableAssessor(Configurer configurer) {
    return tableDescriptor -> null;
  }

  /**
   * Config for the plugin
   */
  private static class Conf extends PluginConfig {
    private String events;

    private int maxEvents;

    @Nullable
    private String proceedFile;
  }

  /**
   * Get the plugin configuration for a mock source that should emit the given events in order.
   *
   * @param events events to emit in order
   * @return plugin configuration for the mock source
   */
  public static Plugin getPlugin(List<? extends ChangeEvent> events) {
    return getPlugin(events, events.size());
  }

  /**
   * Get the plugin configuration for a mock source that should emit the given events in order, up to the maximum
   * number of events given. When maxEvents is less than the size of the event list, the pipeline will have to be
   * restarted multiple times in order to emit all the events. This is used to test that the pipeline starts
   * from the correct offset.
   *
   * @param events events to emit in order
   * @param maxEvents maximum number of events to emit for a single run of the pipeline
   * @return plugin configuration for the mock source
   */
  public static Plugin getPlugin(List<? extends ChangeEvent> events, int maxEvents) {
    Map<String, String> properties = new HashMap<>();
    properties.put("events", GSON.toJson(events));
    properties.put("maxEvents", String.valueOf(maxEvents));
    return new Plugin(NAME, DeltaSource.PLUGIN_TYPE, properties, Artifact.EMPTY);
  }

  /**
   * Get the plugin configuration for a mock source that should throw exceptions until the specified proceed file
   * exists. After that point, it should emit the specified events.
   *
   * @param events events to emit in order
   * @param proceedFile file that must exist before events are emitted
   * @return plugin configuration for the mock source
   */
  public static Plugin getPlugin(List<? extends ChangeEvent> events, File proceedFile) {
    Map<String, String> properties = new HashMap<>();
    properties.put("events", GSON.toJson(events));
    properties.put("maxEvents", String.valueOf(Integer.MAX_VALUE));
    properties.put("proceedFile", proceedFile.getAbsolutePath());
    return new Plugin(NAME, DeltaSource.PLUGIN_TYPE, properties, Artifact.EMPTY);
  }

  private static PluginClass getPluginClass() {
    Map<String, PluginPropertyField> properties = new HashMap<>();
    properties.put("events", new PluginPropertyField("events", "", "string", true, false));
    properties.put("maxEvents", new PluginPropertyField("maxEvents", "", "int", true, false));
    properties.put("proceedFile", new PluginPropertyField("proceedFile", "", "string", false, false));
    return new PluginClass(DeltaSource.PLUGIN_TYPE, NAME, "", MockSource.class.getName(), "conf", properties);
  }
}


text:
/*! HTML5 Boilerplate v5.2.0 | MIT License | https://html5boilerplate.com/ */

/*
 * What follows is the result of much research on cross-browser styling.
 * Credit left inline and big thanks to Nicolas Gallagher, Jonathan Neal,
 * Kroc Camen, and the H5BP dev community and team.
 */

/* ==========================================================================
   Base styles: opinionated defaults
   ========================================================================== */

html {
    color: #222;
    font-size: 1em;
    line-height: 1.4;
}

/*
 * Remove text-shadow in selection highlight:
 * https://twitter.com/miketaylr/status/12228805301
 *
 * These selection rule sets have to be separate.
 * Customize the background color to match your design.
 */

::-moz-selection {
    background: #b3d4fc;
    text-shadow: none;
}

::selection {
    background: #b3d4fc;
    text-shadow: none;
}

/*
 * A better looking default horizontal rule
 */

hr {
    display: block;
    height: 1px;
    border: 0;
    border-top: 1px solid #ccc;
    margin: 1em 0;
    padding: 0;
}

/*
 * Remove the gap between audio, canvas, iframes,
 * images, videos and the bottom of their containers:
 * https://github.com/h5bp/html5-boilerplate/issues/440
 */

audio,
canvas,
iframe,
img,
svg,
video {
    vertical-align: middle;
}

/*
 * Remove default fieldset styles.
 */

fieldset {
    border: 0;
    margin: 0;
    padding: 0;
}

/*
 * Allow only vertical resizing of textareas.
 */

textarea {
    resize: vertical;
}

/* ==========================================================================
   Browser Upgrade Prompt
   ========================================================================== */

.browserupgrade {
    margin: 0.2em 0;
    background: #ccc;
    color: #000;
    padding: 0.2em 0;
}

/* ==========================================================================
   Author's custom styles
   ========================================================================== */
a.feed-url {
    text-decoration: none;
    color: #f8f8f8;
    font-weight: 400;
    line-height: 22px;
}

a.feed-url:hover {
    text-decoration: none;
    color: inherit;
}
/* ==========================================================================
    Grid layout system
   ========================================================================== */
.grid {
    max-width: 69em;
    list-style: none;
    margin: 30px auto;
    padding: 0;
}

.grid li {
    display: block;
    float: left;
    padding: 7px;
    width: 33%;
    opacity: 0;
}

.grid li.shown,
.no-js .grid li,
.no-cssanimations .grid li {
    opacity: 1;
}

.grid li a,
.grid li img {
    outline: none;
    border: none;
    display: block;
    max-width: 100%;
}

/* Effect 1: opacity */
.grid.effect-1 li.animate {
    -webkit-animation: fadeIn 0.65s ease forwards;
    animation: fadeIn 0.65s ease forwards;
}

@-webkit-keyframes fadeIn {
    0% { }
    100% { opacity: 1; }
}

@keyframes fadeIn {
    0% { }
    100% { opacity: 1; }
}

/* Effect 2: Move Up */
.grid.effect-2 li.animate {
    -webkit-transform: translateY(200px);
    transform: translateY(200px);
    -webkit-animation: moveUp 0.65s ease forwards;
    animation: moveUp 0.65s ease forwards;
}

@-webkit-keyframes moveUp {
    0% { }
    100% { -webkit-transform: translateY(0); opacity: 1; }
}

@keyframes moveUp {
    0% { }
    100% { -webkit-transform: translateY(0); transform: translateY(0); opacity: 1; }
}

/* Effect 3: Scale up */
.grid.effect-3 li.animate {
    -webkit-transform: scale(0.6);
    transform: scale(0.6);
    -webkit-animation: scaleUp 0.65s ease-in-out forwards;
    animation: scaleUp 0.65s ease-in-out forwards;
}

@-webkit-keyframes scaleUp {
    0% { }
    100% { -webkit-transform: scale(1); opacity: 1; }
}

@keyframes scaleUp {
    0% { }
    100% { -webkit-transform: scale(1); transform: scale(1); opacity: 1; }
}

/* Effect 4: fall perspective */
.grid.effect-4 {
    -webkit-perspective: 1300px;
    perspective: 1300px;
}

.grid.effect-4 li.animate {
    -webkit-transform-style: preserve-3d;
    transform-style: preserve-3d;
    -webkit-transform: translateZ(400px) translateY(300px) rotateX(-90deg);
    transform: translateZ(400px) translateY(300px) rotateX(-90deg);
    -webkit-animation: fallPerspective .8s ease-in-out forwards;
    animation: fallPerspective .8s ease-in-out forwards;
}

@-webkit-keyframes fallPerspective {
    0% { }
    100% { -webkit-transform: translateZ(0px) translateY(0px) rotateX(0deg); opacity: 1; }
}

@keyframes fallPerspective {
    0% { }
    100% { -webkit-transform: translateZ(0px) translateY(0px) rotateX(0deg); transform: translateZ(0px) translateY(0px) rotateX(0deg); opacity: 1; }
}

/* Effect 5: fly (based on http://lab.hakim.se/scroll-effects/ by @hakimel) */
.grid.effect-5 {
    -webkit-perspective: 1300px;
    perspective: 1300px;
}

.grid.effect-5 li.animate {
    -webkit-transform-style: preserve-3d;
    transform-style: preserve-3d;
    -webkit-transform-origin: 50% 50% -300px;
    transform-origin: 50% 50% -300px;
    -webkit-transform: rotateX(-180deg);
    transform: rotateX(-180deg);
    -webkit-animation: fly .8s ease-in-out forwards;
    animation: fly .8s ease-in-out forwards;
}

@-webkit-keyframes fly {
    0% { }
    100% { -webkit-transform: rotateX(0deg); opacity: 1; }
}

@keyframes fly {
    0% { }
    100% { -webkit-transform: rotateX(0deg); transform: rotateX(0deg); opacity: 1; }
}

/* Effect 6: flip (based on http://lab.hakim.se/scroll-effects/ by @hakimel) */
.grid.effect-6 {
    -webkit-perspective: 1300px;
    perspective: 1300px;
}

.grid.effect-6 li.animate {
    -webkit-transform-style: preserve-3d;
    transform-style: preserve-3d;
    -webkit-transform-origin: 0% 0%;
    transform-origin: 0% 0%;
    -webkit-transform: rotateX(-80deg);
    transform: rotateX(-80deg);
    -webkit-animation: flip .8s ease-in-out forwards;
    animation: flip .8s ease-in-out forwards;
}

@-webkit-keyframes flip {
    0% { }
    100% { -webkit-transform: rotateX(0deg); opacity: 1; }
}

@keyframes flip {
    0% { }
    100% { -webkit-transform: rotateX(0deg); transform: rotateX(0deg); opacity: 1; }
}

/* Effect 7: helix (based on http://lab.hakim.se/scroll-effects/ by @hakimel) */
.grid.effect-7 {
    -webkit-perspective: 1300px;
    perspective: 1300px;
}

.grid.effect-7 li.animate {
    -webkit-transform-style: preserve-3d;
    transform-style: preserve-3d;
    -webkit-transform: rotateY(-180deg);
    transform: rotateY(-180deg);
    -webkit-animation: helix .8s ease-in-out forwards;
    animation: helix .8s ease-in-out forwards;
}

@-webkit-keyframes helix {
    0% { }
    100% { -webkit-transform: rotateY(0deg); opacity: 1; }
}

@keyframes helix {
    0% { }
    100% { -webkit-transform: rotateY(0deg); transform: rotateY(0deg); opacity: 1; }
}

/* Effect 8:  */
.grid.effect-8 {
    -webkit-perspective: 1300px;
    perspective: 1300px;
}

.grid.effect-8 li.animate {
    -webkit-transform-style: preserve-3d;
    transform-style: preserve-3d;
    -webkit-transform: scale(0.4);
    transform: scale(0.4);
    -webkit-animation: popUp .8s ease-in forwards;
    animation: popUp .8s ease-in forwards;
}

@-webkit-keyframes popUp {
    0% { }
    70% { -webkit-transform: scale(1.1); opacity: .8; -webkit-animation-timing-function: ease-out; }
    100% { -webkit-transform: scale(1); opacity: 1; }
}

@keyframes popUp {
    0% { }
    70% { -webkit-transform: scale(1.1); transform: scale(1.1); opacity: .8; -webkit-animation-timing-function: ease-out; animation-timing-function: ease-out; }
    100% { -webkit-transform: scale(1); transform: scale(1); opacity: 1; }
}

@media screen and (max-width: 900px) {
    .grid li {
        width: 50%;
    }
}

@media screen and (max-width: 400px) {
    .grid li {
        width: 100%;
    }
}

/* ==========================================================================
   Helper classes
   ========================================================================== */

/*
 * Hide visually and from screen readers:
 */

.hidden {
    display: none !important;
}

/*
 * Hide only visually, but have it available for screen readers:
 * http://snook.ca/archives/html_and_css/hiding-content-for-accessibility
 */

.visuallyhidden {
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}

/*
 * Extends the .visuallyhidden class to allow the element
 * to be focusable when navigated to via the keyboard:
 * https://www.drupal.org/node/897638
 */

.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus {
    clip: auto;
    height: auto;
    margin: 0;
    overflow: visible;
    position: static;
    width: auto;
}

/*
 * Hide visually and from screen readers, but maintain layout
 */

.invisible {
    visibility: hidden;
}

/*
 * Clearfix: contain floats
 *
 * For modern browsers
 * 1. The space content is one way to avoid an Opera bug when the
 *    `contenteditable` attribute is included anywhere else in the document.
 *    Otherwise it causes space to appear at the top and bottom of elements
 *    that receive the `clearfix` class.
 * 2. The use of `table` rather than `block` is only necessary if using
 *    `:before` to contain the top-margins of child elements.
 */

.clearfix:before,
.clearfix:after {
    content: " ";
    /* 1 */
    display: table;
    /* 2 */
}

.clearfix:after {
    clear: both;
}

/* ==========================================================================
   EXAMPLE Media Queries for Responsive Design.
   These examples override the primary ('mobile first') styles.
   Modify as content requires.
   ========================================================================== */

@media only screen and (min-width: 35em) {
    /* Style adjustments for viewports that meet the condition */
}

@media print,
(-webkit-min-device-pixel-ratio: 1.25),
(min-resolution: 1.25dppx),
(min-resolution: 120dpi) {
    /* Style adjustments for high resolution devices */
}

/* ==========================================================================
   Print styles.
   Inlined to avoid the additional HTTP request:
   http://www.phpied.com/delay-loading-your-print-css/
   ========================================================================== */

@media print {
    *,
    *:before,
    *:after {
        background: transparent !important;
        color: #000 !important;
        /* Black prints faster:
                                   http://www.sanbeiji.com/archives/953 */
        box-shadow: none !important;
        text-shadow: none !important;
    }
    a,
    a:visited {
        text-decoration: underline;
    }
    a[href]:after {
        content: " (" attr(href) ")";
    }
    abbr[title]:after {
        content: " (" attr(title) ")";
    }
    /*
     * Don't show links that are fragment identifiers,
     * or use the `javascript:` pseudo protocol
     */
    a[href^="#"]:after,
    a[href^="javascript:"]:after {
        content: "";
    }
    pre,
    blockquote {
        border: 1px solid #999;
        page-break-inside: avoid;
    }
    /*
     * Printing Tables:
     * http://css-discuss.incutio.com/wiki/Printing_Tables
     */
    thead {
        display: table-header-group;
    }
    tr,
    img {
        page-break-inside: avoid;
    }
    img {
        max-width: 100% !important;
    }
    p,
    h2,
    h3 {
        orphans: 3;
        widows: 3;
    }
    h2,
    h3 {
        page-break-after: avoid;
    }
}


text:
__author__ = 'zach.mott@gmail.com'

from django.db import models
from django.utils.translation import ugettext_lazy as _

class AbstractBase(models.Model):
    created_by = models.ForeignKey('auth.User', verbose_name=_('Created by'))

    created = models.DateTimeField(_('Created on'), auto_now_add=True)
    last_modified = models.DateTimeField(_('Last modified'), auto_now=True)

    class Meta:
        app_label = 'quizard'
        abstract = True


text:
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.openqa.selenium.htmlunit;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import net.sourceforge.htmlunit.corejs.javascript.Function;
import net.sourceforge.htmlunit.corejs.javascript.NativeJavaObject;

import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriverException;

import com.gargoylesoftware.htmlunit.ScriptException;
import com.gargoylesoftware.htmlunit.ScriptResult;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

/**
 * Injects an asynchronous script into the current page for execution. The script should signal that
 * it is finished by invoking the callback function, which will always be the last argument passed
 * to the injected script.
 */
class AsyncScriptExecutor {

  private final HtmlPage page;
  private final long timeoutMillis;

  /**
   * Prepares a new asynchronous script for execution.
   *
   * @param page The page to inject the script into.
   * @param timeoutMillis How long to wait for the script to complete, in milliseconds.
   */
  AsyncScriptExecutor(HtmlPage page, long timeoutMillis) {
    this.page = page;
    this.timeoutMillis = timeoutMillis;
  }

  /**
   * Injects an asynchronous script for execution and waits for its result.
   *
   * @param scriptBody The script body.
   * @param parameters The script parameters, which can be referenced using the {@code arguments}
   *        JavaScript object.
   * @return The script result.
   */
  public Object execute(String scriptBody, Object[] parameters) {
    AsyncScriptResult asyncResult = new AsyncScriptResult();
    Function function = createInjectedScriptFunction(scriptBody, asyncResult);

    try {
      page.executeJavaScriptFunctionIfPossible(function, function, parameters,
          page.getDocumentElement());
    } catch (ScriptException e) {
      throw new WebDriverException(e);
    }

    try {
      return asyncResult.waitForResult();
    } catch (InterruptedException e) {
      throw new WebDriverException(e);
    }
  }

  private Function createInjectedScriptFunction(String userScript, AsyncScriptResult asyncResult) {
    String script =
        "function() {" +
            "  var self = this, timeoutId;" +
            "  var cleanUp = function() {" +
            "    window.clearTimeout(timeoutId);" +
            "    if (window.detachEvent) {" +
            "      window.detachEvent('onunload', catchUnload);" +
            "    } else {" +
            "      window.removeEventListener('unload', catchUnload, false);" +
            "    }" +
            "  };" +
            "  var self = this, timeoutId, catchUnload = function() {" +
            "    cleanUp();" +
            "    self.host.unload();" +
            "  };" +
            // Convert arguments into an actual array, then add the callback object.
            "  arguments = Array.prototype.slice.call(arguments, 0);" +
            "  arguments.push(function(value) {" +
            "    cleanUp();" +
            "    self.host.callback(typeof value == 'undefined' ? null : value);" +
            "  });" +
            // Add an event listener to trap unload events; page loads are not supported with async
            // script execution.
            "  if (window.attachEvent) {" +
            "    window.attachEvent('onunload', catchUnload);" +
            "  } else {" +
            "    window.addEventListener('unload', catchUnload, false);" +
            "  }" +
            // Execute the user's script
            "  (function() {" + userScript + "}).apply(null, arguments);" +
            // Register our timeout for the script. If the script invokes the callback immediately
            // (e.g. it's not really async), then this will still fire. That's OK because the host
            // object should ignore the extra timeout.
            "  timeoutId = window.setTimeout(function() {" +
            "    self.host.timeout();" +
            "  }, " + timeoutMillis + ");" +
            "}";

    // Compile our script.
    ScriptResult result = page.executeJavaScript(script);
    Function function = (Function) result.getJavaScriptResult();

    // Finally, update the script with the callback host object.
    function.put("host", function, new NativeJavaObject(function, asyncResult, null));

    return function;
  }

  /**
   * Host object used to capture the result of an asynchronous script.
   *
   *

   * This class has public visibility so it can be correctly wrapped in a {@link NativeJavaObject}.
   *
   * @see AsyncScriptExecutor
   */
  public static class AsyncScriptResult {

    private final CountDownLatch latch = new CountDownLatch(1);

    private volatile Object value = null;
    private volatile boolean isTimeout = false;
    private volatile boolean unloadDetected = false;

    /**
     * Waits for the script to signal it is done by calling {@link #callback(Object) callback}.
     *
     * @return The script result.
     * @throws InterruptedException If this thread is interrupted before a result is ready.
     */
    Object waitForResult() throws InterruptedException {
      long startTimeNanos = System.nanoTime();
      latch.await();
      if (isTimeout) {
        long elapsedTimeNanos = System.nanoTime() - startTimeNanos;
        long elapsedTimeMillis = TimeUnit.NANOSECONDS.toMillis(elapsedTimeNanos);
        throw new TimeoutException(
            "Timed out waiting for async script result after " + elapsedTimeMillis + "ms");
      }

      if (unloadDetected) {
        throw new WebDriverException(
            "Detected a page unload event; executeAsyncScript does not work across page loads");
      }
      return value;
    }

    /**
     * Callback function to be exposed in JavaScript.
     *
     *

     * This method has public visibility for Rhino and should never be called by code outside of
     * Rhino.
     *
     * @param value The asynchronous script result.
     */
    public void callback(Object value) {
      if (latch.getCount() > 0) {
        this.value = value;
        latch.countDown();
      }
    }

    /**
     * Function exposed in JavaScript to signal a timeout. Has no effect if called after the
     * {@link #callback(Object) callback} function.
     *
     *

     * This method has public visibility for Rhino and should never be called by code outside of
     * Rhino.
     */
    public void timeout() {
      if (latch.getCount() > 0) {
        isTimeout = true;
        latch.countDown();
      }
    }

    /**
     * Function exposed to JavaScript to signal that a page unload event was fired. WebDriver's
     * asynchronous script execution model does not permit new page loads.
     *
     *

     * This method has public visibility for Rhino and should never be called by code outside of
     * Rhino.
     */
    public void unload() {
      if (latch.getCount() > 0) {
        unloadDetected = true;
        latch.countDown();
      }
    }
  }
}


text:
#include "networking/lowlevel/vsnet_debug.h"
#include "cmd/unit_generic.h"
#include "vs_globals.h"
#include "vsfilesystem.h"
#include "networking/netclient.h"
#include "savegame.h"
#include "main_loop.h"
#include "networking/lowlevel/netbuffer.h"
#include "networking/lowlevel/packet.h"
#include "lin_time.h"
#include "networking/lowlevel/vsnet_notify.h"
#include "networking/lowlevel/vsnet_sockethttp.h"
#include "networking/lowlevel/vsnet_dloadmgr.h"
#include "networking/lowlevel/netui.h"
#include "networking/client.h"
#include "networking/fileutil.h"

std::string global_username;
std::string global_password;
/*
 ************************************************************
 **** Authenticate the client                             ***
 ************************************************************
 */

int NetClient::authenticate()
{
    COUT<<" enter "<<__PRETTY_FUNCTION__<<endl;

    Packet    packet2;
    string    str_callsign, str_passwd;
    NetBuffer netbuf;

    //Get the name and password from vegastrike.config
    //Maybe someday use a default Guest account if no callsign or password is provided thus allowing
    //Player to wander but not interact with the universe
    this->callsign = str_callsign = vs_config->getVariable( "player", "callsign", "" );
    this->password = str_passwd = vs_config->getVariable( "player", "password", "" );
    if ( global_username.length() )
        this->callsign = global_username;
    if ( global_password.length() )
        this->password = global_password;
    if ( str_callsign.length() && str_passwd.length() ) {
        netbuf.addString( str_callsign );
        netbuf.addString( str_passwd );

        packet2.send( CMD_LOGIN, 0,
                     netbuf.getData(), netbuf.getDataLength(),
                     SENDRELIABLE, NULL, *this->clt_tcp_sock,
                     __FILE__, PSEUDO__LINE__( 165 ) );
        COUT<<"Send login for player <"<<str_callsign<<">:<*******"
        "> - buffer length : "<<packet2.getDataLength()
            <<" (+"<<packet2.getHeaderLength()<<" header len"<<endl;
    } else {
        cerr<<"Callsign and/or password not specified in vegastrike.config, please check this."<<endl<<endl;
        return -1;
    }
    return 0;
}

/*
 ************************************************************
 **** Login loop : waiting for game server to respond     ***
 ************************************************************
 */

int NetClient::loginAuth( string str_callsign, string str_passwd, string &error )
{
    COUT<<"enter "<<"NetClient::loginLoop"<<endl;
    lastsave.clear();
    ship_select_list.clear();

    Packet    packet2;
    NetBuffer netbuf;

    //memset( buffer, 0, tmplen+1);
    netbuf.addString( str_callsign );
    netbuf.addString( str_passwd );

    packet2.send( CMD_LOGIN, 0,
                 netbuf.getData(), netbuf.getDataLength(),
                 SENDRELIABLE, NULL, *this->clt_tcp_sock,
                 __FILE__, PSEUDO__LINE__( 316 ) );
    COUT<<"Sent login for player <"<<str_callsign<<">:<*******"
        <<">"<<endl
        <<"   - buffer length : "<<packet2.getDataLength()<<endl;
    this->callsign = str_callsign;
    this->password = str_passwd;
    //Now the loop
    return loginLoop( error );
}

int NetClient::loginLoop( string &error )
{
    int     timeout = 0, recv = 0;
    //int ret=0;

    Packet  packet;

    string  login_tostr = vs_config->getVariable( "network", "logintimeout", "100" );
    timeval tv = {atoi( login_tostr.c_str() ), 0};
    while (!timeout) {
        recv = this->recvMsg( &packet, &tv );
        if (recv == 0) {
            error   = "NETWORK ERROR : Login procedeure timed out.";
            timeout = 1;
        } else if (recv < 0) {
            char str[127];
            sprintf( str, "NETWORK ERROR in recieving login data (error number %d)!!!",
#ifdef _WIN32
                     WSAGetLastError()
#else
                     errno
#endif
                   );
            error   = (str);
            timeout = 1;
        } else {
            break;
        }
    }
    COUT<<"End of login loop"<<endl;
    if (lastsave.empty() || lastsave[0] == "") {
        if ( ship_select_list.empty() )
            error = "Login failure!";
        return ship_select_list.size();
    }
    //cout<<"GLOBALSAVES[0] : "
    //cout<<"GLOBALSAVES[1] : "<<globalsaves[1]<<endl;
    return 1;
}

/*
 ************************************************************
 **** Login loop : waiting for account server to respond  ***
 ************************************************************
 */

vector< string >& NetClient::loginAcctLoop( string str_callsign, string str_passwd )
{
    COUT<<"enter "<<"NetClient::loginAcctLoop"<<endl;

    this->error_message = string();

    std::string netbuf;
    addSimpleChar( netbuf, ACCT_LOGIN_DATA );
    //memset( buffer, 0, tmplen+1);
    addSimpleString( netbuf, str_callsign );
    addSimpleString( netbuf, str_passwd );

    COUT<<"Buffering to send with LOGIN_DATA for "<<str_callsign<<endl;
    //PacketMem m( netbuf.getData(), netbuf.getDataLength(), PacketMem::LeaveOwnership );
    //m.dump( cerr, 3 );
    acct_sock->sendstr( netbuf );
    /*
     *  packet2.send( LOGIN_DATA, 0,
     *         netbuf.getData(), netbuf.getDataLength(),
     *         SENDRELIABLE, NULL, this->acct_sock,
     *         __FILE__, PSEUDO__LINE__(378) );
     */
    //Now the loop
    int    timeout = 0, recv = 0;
    //int ret=0;

    Packet packet;

    double initial     = queryTime();
    double newtime     = 0;
    double elapsed     = 0;
    string login_tostr = vs_config->getVariable( "network", "logintimeout", "20" );
    int    login_to    = atoi( login_tostr.c_str() );
    while (!timeout && !recv) {
        //If we have no response in "login_to" seconds -> fails
        newtime = queryTime();
        elapsed = newtime-initial;
        //COUT<<elapsed<<" seconds since login request"<<endl;
        if (elapsed > login_to) {
            //lastsave.push_back( "");
            COUT<<"!!! NETWORK ERROR : Connection to account server timed out !!!"<<endl;
            timeout = 1;
            break;
        }
        recv = checkAcctMsg();
        _sock_set.waste_time( 0, 40000 );
    }
    COUT<<"End of loginAcct loop"<<endl;
    //globalsaves should be empty otherwise we filled it with an empty string followed by the error message
    if (lastsave.empty() || lastsave[0] != "") {
        //this->callsign = str_callsign;
        //savefiles = globalsaves;
        COUT<<"Trying to connect to game server..."<<endl
            <<"\tIP="<<_serverip<<":"<<_serverport<<endl;
    }
    return lastsave;
}

void NetClient::loginChooseShip( Packet &p1 )
{
    NetBuffer netbuf( p1.getData(), p1.getDataLength() );
    ship_select_list.clear();
    unsigned short numShips = netbuf.getShort();
    ship_select_list.reserve( numShips );
    for (int i = 0; i < numShips; i++)
        ship_select_list.push_back( netbuf.getString() );
}

void NetClient::loginAccept( Packet &p1 )
{
    using namespace VSFileSystem;
    NetBuffer netbuf( p1.getData(), p1.getDataLength() );

    Packet    pckt;
    this->serial = p1.getSerial();
    COUT<<">>> LOGIN ACCEPTED =( serial #"<<serial<<" )= --------------------------------------"<<endl;
    {
        char msg[100];
        sprintf( msg, "#cc66ffNETWORK: Login Accepted.  Serial number is %d.  Downloading system file...", serial );
        bootstrap_draw( msg, NULL );
    }
    //Should receive player's data (savegame) from server if there is a save
    localSerials.push_back( serial );

    string datestr = netbuf.getString();
    _Universe->current_stardate.InitTrek( datestr );
    cerr<<"Stardate initialized"<<endl;
    cerr<<"WE ARE ON STARDATE "<<datestr<<" - converted : "
        <<_Universe->current_stardate.GetFullTrekDate()<<endl;
    lastsave.push_back( netbuf.getString() );
    lastsave.push_back( netbuf.getString() );
    unsigned char *digest = 0;
    unsigned short digest_length;

    /*
     *  // Get universe file... not too useful.
     *  // But this is a good example of using VsnetDownload download manager.
     *
     *  // Get the galaxy file from buffer with relative path to datadir !
     *  digest_length = netbuf.getShort();
     *  string univfile = netbuf.getString();
     *  if (digest_length) {
     *       digest = netbuf.getBuffer( digest_length );
     * #ifdef CRYPTO
     *       cerr<<"Initial system = "<<VSFileSystem::datadir+univfile<<" - File Hash = "<<digest<<endl;
     *       // Compare to local hash and ask for the good file if we don't have it or bad version
     *       if( !FileUtil::HashCompare( univfile, digest, UniverseFile))
     *       {
     *               VsnetDownload::Client::NoteFile f( this->clt_tcp_sock, univfile, VSFileSystem::UniverseFile);
     *               _downloadManagerClient->addItem( &f);
     *               timeval timeout={10,0};
     *               while( !f.done())
     *               {
     *                       if (recvMsg( NULL, &timeout )<=0) {
     *  //NETFIXME: What to do if the download times out?
     *                               break;
     *                       }
     *               }
     *       }
     * #endif
     *  }
     */

    //Get the initial system file...
    string sysfile = netbuf.getString();
    bool   downloadsystem = true;
    bool   autogen;
    string fullsys = VSFileSystem::GetCorrectStarSysPath( sysfile, autogen );
    if ( fullsys.empty() ) fullsys = sysfile;
    digest_length = netbuf.getShort();
    COUT<<"Initial system = "<<fullsys;
    if (digest_length) {
        digest = netbuf.getBuffer( digest_length );
#ifdef CRYPTO
        cerr<<" - File Hash = "<<digest;
        if ( FileUtil::HashCompare( fullsys, digest, SystemFile ) )
            downloadsystem = false;
#endif
    }
    //Set the zone number
    this->zone = netbuf.getShort();
    //Did the hash compare fail?
    if (downloadsystem) {
        cerr<<": Downloading system from server..."<<endl;
        VsnetDownload::Client::NoteFile f( fullsys, *this->clt_tcp_sock, sysfile, VSFileSystem::SystemFile );
        _downloadManagerClient->addItem( &f );
        timeval timeout = {10, 0};
        while ( !f.done() )
            if (recvMsg( NULL, &timeout ) <= 0)
                //NETFIXME: what to do if timeout elapses...
                break;
    }
    cout<<endl;
}

void NetClient::respawnRequest()
{
    Packet    packet2;
    NetBuffer netbuf;
    //No data.
    packet2.send( CMD_RESPAWN, 0,
                 netbuf.getData(), netbuf.getDataLength(),
                 SENDRELIABLE, NULL, *this->clt_tcp_sock,
                 __FILE__, PSEUDO__LINE__( 165 ) );
}
void NetClient::textMessage( const std::string &data )
{
    Packet    packet2;
    NetBuffer netbuf;
    netbuf.addString( data );
    //No data.
    packet2.send( CMD_TXTMESSAGE, 0,
                 netbuf.getData(), netbuf.getDataLength(),
                 SENDRELIABLE, NULL, *this->clt_tcp_sock,
                 __FILE__, PSEUDO__LINE__( 165 ) );
}

void NetClient::GetCurrentServerAddress( string &addr, unsigned short &port )
{
    addr = this->_serverip;
    port = this->_serverport;
}

void NetClient::SetCurrentServerAddress( string addr, unsigned short port )
{
    this->_serverip   = addr;
    this->_serverport = port;
}

void NetClient::SetConfigServerAddress( string &addr, unsigned short &port )
{
    bool use_acctserver = XMLSupport::parse_bool( vs_config->getVariable( "network", "use_account_server", "false" ) );
    if (use_acctserver) {
        this->_serverport = port = 0;
        this->_serverip   = addr = vs_config->getVariable( "network", "account_server_url",
                                                           "http://localhost/cgi-bin/accountserver.py" );
        cout<<endl<<"Account Server URL : "<<addr<<endl<<endl;
        return;
    }
    int    port_tmp;
    string srvport = vs_config->getVariable( "network", "server_port", "6777" );
    port_tmp = atoi( srvport.c_str() );
    if (port_tmp > 65535 || port_tmp < 0)
        port_tmp = 0;
    port     = (unsigned short) port_tmp;

    addr     = vs_config->getVariable( "network", "server_ip", "" );
    this->_serverip   = addr;
    this->_serverport = port;
    cout<<endl<<"Server IP : "<<addr<<" - port : "<<srvport<<endl<<endl;
}

/*
 ************************************************************
 **** Initialize the client network to account server     ***
 ************************************************************
 */
VsnetHTTPSocket* NetClient::init_acct( const std::string &addr )
{
    COUT<<" enter "<<__PRETTY_FUNCTION__
        <<" with "<<addr<<endl;

    _sock_set.start();

    cout<<"Initializing connection to account server..."<<endl;
    acct_sock = new VsnetHTTPSocket( addr, _sock_set );
    COUT<<"accountserver on socket "<<acct_sock<<" done."<<endl;

    return acct_sock;
}

/*
 ************************************************************
 **** Initialize the client network                       ***
 ************************************************************
 */

SOCKETALT NetClient::init( const char *addr, unsigned short port, std::string &error )
{
    if ( clt_tcp_sock && clt_tcp_sock->valid() ) clt_tcp_sock->disconnect( "NC_init_tcp" );
    if ( clt_udp_sock && clt_udp_sock->valid() ) NetUIUDP::disconnectSaveUDP( *clt_udp_sock );
    lastsave.clear();
    netversion = 0;
    if (addr == NULL) {
        addr = _serverip.c_str();
        port = _serverport;
    }
    COUT<<" enter "<<__PRETTY_FUNCTION__
        <<" with "<<addr<<":"<<port<<endl;

    _sock_set.start();

    string strnetatom;
    strnetatom = vs_config->getVariable( "network", "network_atom", "" );
    if (strnetatom == "")
        NETWORK_ATOM = 0.2;
    else
        NETWORK_ATOM = (double) atof( strnetatom.c_str() );
    *this->clt_tcp_sock = NetUITCP::createSocket( addr, port, _sock_set );
    this->lossy_socket  = this->clt_tcp_sock;
    if ( !clt_tcp_sock->valid() )
        return *this->clt_tcp_sock;
    COUT<<"created TCP socket ("<<addr<<","<<port<<") -> "<<this->clt_tcp_sock<<endl;

    /*
     *  if( this->authenticate() == -1)
     *  {
     *       perror( "Error login in ");
     *       return -1;
     *  }
     */
    Packet join;
    join.send( CMD_CONNECT, CLIENT_NETVERSION, "", 0, SENDRELIABLE, NULL,
              *this->clt_tcp_sock, __FILE__, PSEUDO__LINE__( 407 ) );
    this->enabled = 1;

    string  login_tostr = vs_config->getVariable( "network", "connecttimeout", "10" );
    timeval tv = {atoi( login_tostr.c_str() ), 0};
    int     timeout     = 0;
    Packet  packet;
    while (!timeout) {
        int recvd = this->recvMsg( &packet, &tv );
        if (recvd == 0) {
            error   = "Connection to game server timed out!";
            timeout = 1;
        } else if (recvd < 0) {
            char str[127];
            sprintf( str, "NETWORK ERROR in recieving socket (error number %d)!!!",
#ifdef _WIN32
                     WSAGetLastError()
#else
                     errno
#endif
                   );
            error   = str;
            timeout = 1;
        } else if (this->netversion) {
            break;
        }
    }
    if (!this->netversion) {
        if ( error.empty() )
            error = "Unable to receive a valid version from this server.";
        timeout = 1;
    }
    if (timeout)
        clt_tcp_sock->disconnect( "NCinit_timedout" );
    return *this->clt_tcp_sock;
}

/*
 ************************************************************
 **** Synchronize server time and client time             ***
 ************************************************************
 **** This function creates the UDP socket and determines ***
 **** whether to use the UDP or the TCP socket for lossy  ***
 **** packet data.                                        ***
 ************************************************************
 */

//NETFIXME: Correctly obtain ping time.
#include "vs_random.h" //For random ping time.

void NetClient::synchronizeTime( SOCKETALT *udpsock )
{
    int            i  = 0;
    int            timeout = 0;
    int            recv;
    timeval        tv = {1, 0};   //Timeout after 1 second, request send again.
    double         ping; //use deltaTime?
    double         pingavg           = 0.;
    double         timeavg           = 0.;
    std::map< double, double >times;     //sorted container.
    double         initialTime       = queryTime();
    static int     NUM_TIMES         = XMLSupport::parse_int( vs_config->getVariable( "network", "servertime_calibration", "10" ) );
    static int     UDP_TIMEOUT       = XMLSupport::parse_int( vs_config->getVariable( "network", "udp_timeout", "1" ) );
    static int     clt_port_read     = XMLSupport::parse_int( vs_config->getVariable( "network", "udp_listen_port", "6778" ) );
    if (clt_port_read > 65535 || clt_port_read <= 0)
        clt_port_read = 0;
    static int     clt_port_read_max = XMLSupport::parse_int( vs_config->getVariable( "network", "udp_listen_port_max", "6778" ) );
    if (clt_port_read_max > 65535 || clt_port_read_max <= 0)
        clt_port_read_max = clt_port_read;
    unsigned short clt_port          = (unsigned short) clt_port_read;
    unsigned short clt_port_max      = (unsigned short) clt_port_read_max;
    if (clt_port_max < clt_port)
        clt_port_max = clt_port;
    static string  nettransport      = vs_config->getVariable( "network", "transport", "udp" );

    //std::string addr;
    unsigned short port = this->_serverport;
    //getConfigServerAddress(addr, port);
    if ( !( udpsock != NULL && udpsock->setRemoteAddress( NetUIBase::lookupHost( this->_serverip.c_str(), port ) ) ) ) {
        do
            *this->clt_udp_sock = NetUIUDP::createSocket( this->_serverip.c_str(), port, clt_port, _sock_set );
        while ( ( !this->clt_udp_sock->valid() ) && (clt_port++) );
    } else {
        this->clt_udp_sock = udpsock;
    }
    COUT<<"created UDP socket ("<<this->_serverip<<","<<port<<", listen on "<<clt_port<<") -> "<<this->clt_udp_sock<<endl;
    if (nettransport == "udp") {
        //NETFIXME:  Keep trying ports until a connection is established.
        COUT<<"Default lossy transport configured to UDP."<<endl;
        this->lossy_socket = clt_udp_sock;
    } else {
        COUT<<"Default lossy transport configured to TCP (behind firewall)."<<endl;
        this->lossy_socket = clt_tcp_sock;
        clt_port = 0;
    }
    this->clt_tcp_sock->set_block();
    this->clt_udp_sock->set_block();
    //Wait for NUM_TIMES (10) successful tries, or 10 consecutive 1-second timeouts
    //(we use UDP on the response (SENDANDFORGET) to improve timing accuracy).
    while (i < NUM_TIMES && timeout < UDP_TIMEOUT) {
        Packet    packet;
        NetBuffer outData;
        outData.addShort( clt_port );
        packet.send( CMD_SERVERTIME, 0,
                    outData.getData(), outData.getDataLength(),                      //No data.
                    SENDRELIABLE, NULL, *this->clt_tcp_sock,
                    __FILE__, PSEUDO__LINE__( 343 ) );
        recv = this->recvMsg( &packet, &tv );
        //If we have no response.
        if (recv <= 0) {
            COUT<<"synchronizeTime() Timed out"<<endl;
            ++timeout;
            if (timeout >= UDP_TIMEOUT) {
                if (this->lossy_socket->isTcp() == false) {
                    if (clt_port < clt_port_max && !udpsock) {
                        NetUIUDP::disconnectSaveUDP( *this->clt_udp_sock );
                        *this->clt_udp_sock = NetUIUDP::createSocket( this->_serverip.c_str(), port, clt_port, _sock_set );
                        clt_port++;
                        COUT<<"Trying UDP port "<<clt_port<<"."<<endl;
                    } else {
                        //no UDP requests made it, fallback to TCP.
                        this->lossy_socket = this->clt_tcp_sock;
                        clt_port = 0;
                        COUT<<"Setting default lossy transport to TCP (UDP timeout)."<<endl;
                    }
                    timeout = 0;
                }
            }
        } else if (packet.getCommand() == CMD_SERVERTIME) {
            //NETFIXME: obtain actual ping time
            //ping = getPingTime( &tv );
            ping = exp( vsrandom.uniformInc( -10, 0 ) );
            if (ping > 0 && ping < 1.) {
                ++i;
                NetBuffer data( packet.getData(), packet.getDataLength() );
                double    serverTime  = data.getDouble();
                double    currentTime = queryTime();
                serverTime += initialTime-currentTime;
                times.insert( std::multimap< double, double >::value_type( ping, serverTime-ping ) );
                timeout     = 0;
            } else {
                ++timeout;
            }
        }
    }
    this->clt_tcp_sock->set_nonblock();
    this->clt_udp_sock->set_nonblock();
//std::sort(times[0], times[i]);
    if (i >= NUM_TIMES) {
        int    mid      = i/2;
        double median   = 0.;
        double tot      = 0.;
        int    location = 0;
        std::map< double, double >::const_iterator iter;
        for (iter = times.begin(); iter != times.end(); ++iter) {
            if (location == mid) {
                median = iter->first;
                if (i%2 == 1) {
                    ++iter;
                    median += iter->first;
                }
                break;
            }
            ++location;
        }
        if (i%2 == 1)
            median /= 2;
        for (iter = times.begin(); iter != times.end(); ++iter) {
            double wdiff = exp( -10*(median-iter->first)*(median-iter->first) );
            pingavg += wdiff*iter->first;
            timeavg += wdiff*iter->second;
            tot     += wdiff;
        }
        pingavg /= tot;
        timeavg /= tot;
    } else {
        COUT<<"Error in time synchronization: connection ended or timed out.";
    }
    this->deltatime = pingavg;
    double newTime = timeavg+queryTime()-initialTime;
    COUT<<"Setting time to: New time: "<<newTime<<endl;
    setNewTime( newTime );
    for (unsigned int cpnum = 0; cpnum < _Universe->numPlayers(); cpnum++)
        //Seems like a bad idea... shouldn't this rely on SIMULATION_ATOM?
        _Universe->AccessCockpit( cpnum )->TimeOfLastCollision = -200;
    cur_time = newTime;
}

/*
 ************************************************************
 **** Receive that start locations                        ***
 ************************************************************
 */

//Receives possible start locations (first a short representing number of locations)
//Then for each number, a desc

void NetClient::receiveLocations( const Packet* )
{
    unsigned char cmd;

#ifdef __DEBUG__
    COUT<<"Nb start locations : "<<nblocs<<endl;
#endif
    //Choose starting location here

    //Send the chosen location to the server
    cmd = CMD_ADDCLIENT;
}

/*
 ************************************************************
 **** Create a new character                              ***
 ************************************************************
 */
bool NetClient::selectShip( unsigned int ship )
{
    if (lastsave.empty() || lastsave[0] == "") {
        NetBuffer netbuf;
        string    shipname;
        netbuf.addShort( (unsigned short) ship );
        if ( ship < ship_select_list.size() )
            shipname = ship_select_list[ship];
        netbuf.addString( shipname );
        Packet p;
        p.send( CMD_CHOOSESHIP, 0, netbuf.getData(), netbuf.getDataLength(), SENDRELIABLE,
               NULL, *clt_tcp_sock, __FILE__, PSEUDO__LINE__( 628 ) );
        string err;
        int    ret = loginLoop( err );
        if (ret != 1 || lastsave.size() < 2 || lastsave[0] == "") {
            cout<<"Error in CHOOSEHIP: "<<err
                <<"choice="<<ship<<"("<<shipname<<"), max="<<ret<<endl;
            return false;
        }
    }
    return true;
}

void NetClient::createChar()
{}

int NetClient::connectLoad( string username, string passwd, string &error )
{
    localSerials.resize( 0 );
    bootstrap_draw( "#cc66ffNETWORK: Initializing...", NULL );
    cout<<"NETWORK: Initializing..."<<endl;
    string srvipadr;
    unsigned short port;
    bool   ret = false;
    //Are we using the directly account server to identify us ?
    GetCurrentServerAddress( srvipadr, port );
    if (!port) {
        //using account server.
        string srvipadr = vs_config->getVariable( "network", "account_server_url", "http://localhost/cgi-bin/accountserver.py" );
        bootstrap_draw( "#cc66ffNETWORK: Connecting to account server.", NULL );
        cout<<"NETWORK: Connecting to account server."<<endl;
        init_acct( srvipadr );
        vector< string > &savetmp = loginAcctLoop( username, passwd );
        //We don't expect a saved game...
        if ( savetmp.size() >= 2 && savetmp[0].empty() ) {
            //But this is the way the acctserver code indicates an error.
            error = savetmp[1];
            return 0;
        }
        bootstrap_draw( "#cc66ffNETWORK: Connecting to VegaServer.", NULL );
        cout<<"NETWORK: Connecting to VegaServer."<<endl;
        ret = init( NULL, 0, error ).valid();
    } else {
        //Or are we going through a game server to do so ?
        bootstrap_draw( "#cc66ffNETWORK: Connecting to VegaServer.", NULL );
        cout<<"NETWORK: Connecting to VegaServer."<<endl;
        ret = init( srvipadr.c_str(), port, error ).valid();
    }
    if (ret == false) {
        //If network initialization fails, exit
        if ( error.empty() ) error = "Network connection error";
        if ( !this->error_message.empty() )
            error += "\n"+this->error_message;
        cout<<"Error: "<<error<<endl;
        return 0;
    }
    cout<<"Successfully connected!";
    //sleep( 3);
    cout<<"Waiting for player "<<username<<": login response..."<<endl;
    bootstrap_draw( "#cc66ffNETWORK: Successful connection! Waiting to log in.", NULL );
    int loggedin = loginAuth( username, passwd, error );
    if ( !this->error_message.empty() ) {
        cout<<"Warning: "<<this->error_message<<endl;
        if ( !error.empty() )
            error += "\n";
        error += this->error_message;
    }
    return loggedin;
}
vector< string >* NetClient::loginSavedGame( int ship )
{
    if ( !selectShip( ship ) )
        return NULL;
    /************* NETWORK PART ***************/

    return &lastsave;
}

void NetClient::startGame()
{
    vector< string >savedships;
    QVector pos;
    //useless.
    string  mysystem;
    string  savefiles;
    bool    setplayerXloc = false;
    float   credits = 0.0;
    vector< StarSystem* >ss;
    vector< QVector >    playerNloc;
    vector< string >playersaveunit;
    vector< vector< string > >vecstr;

    bootstrap_draw( "#cc66ffNETWORK: Checking for UDP connection.", NULL );
    cout<<"NETWORK: Checking for UDP connection."<<endl;
    synchronizeTime( NULL );
    cout<<" logged in !"<<endl;

    bootstrap_draw( "#cc66ffNETWORK: Loading player ship.", NULL );
    cout<<"NETWORK: Loading player ship."<<endl;
    if (_Universe->numPlayers() == 0)
        _Universe->createCockpit( callsign );
    _Universe->clearAllSystems();
    _Universe->AccessCockpit( 0 )->savegame->SetStarSystem( string() );
    _Universe->AccessCockpit( 0 )->savegame->ParseSaveGame( "",
                                                            mysystem,
                                                            "",
                                                            pos,
                                                            setplayerXloc,
                                                            credits,
                                                            savedships,
                                                            0,
                                                            lastsave[0],
                                                            false );

    ss.push_back( _Universe->Init( mysystem, Vector( 0, 0, 0 ), string() ) );

    CopySavedShips( callsign, 0, savedships, true );
    playersaveunit.push_back( savedships[0] );
    if (setplayerXloc)
        playerNloc.push_back( pos );
    else
        playerNloc.push_back( QVector( FLT_MAX, FLT_MAX, FLT_MAX ) );
    vecstr.push_back( lastsave );
    createObjects( playersaveunit, ss, playerNloc, vecstr );
    bootstrap_draw( "#cc66ffNETWORK: Loading system.", NULL );
    cout<<"NETWORK: Loading system."<<endl;
    inGame();
    //PacketLoop(CMD_ADDEDYOU); // Wait for the command before stopping.
}


text:
class User < ActiveRecord::Base

  validates_presence_of :email, :name

  has_many :posts

end

class Post < ActiveRecord::Base

  validates_presence_of :title, :content

  belongs_to :user
  has_many :comments

end

class Comment < ActiveRecord::Base

  validates_presence_of :body

  belongs_to :post
  belongs_to :user

end


text:
use selenium_rs::webdriver::{Browser, Selector, WebDriver};
use std::fs;
use std::io::{self, Read, Write};
use std::net::TcpStream;
use std::path::Path;
use std::process::{Command, Output, Stdio};
use std::thread;
use std::time::{Duration, Instant};

const LOCAL_AUTH_BASE_URL: &str = "http://localhost:12731/";

const USERNAME_SELECTOR: &str = ".auth0-lock-input-email .auth0-lock-input";
const PASSWORD_SELECTOR: &str = ".auth0-lock-input-password .auth0-lock-input";
const LOGIN_SELECTOR: &str = ".auth0-lock-submit";

const BROWSER_RETRY_WAIT: Duration = Duration::from_secs(1);
const BROWSER_MAX_WAIT: Duration = Duration::from_secs(10);

// The configuration below is for the sccache-test tenant under aidanhs' auth0 account. There
// is one user, one api and two applications. There is a rule ensuring that oauth access is
// never granted to the built-in auth0 tenant management API (though the worst that could happen
// is tests start failing because someone deliberately messes up the configuration).

const TEST_USERNAME: &str = "test@example.com";
const TEST_PASSWORD: &str = "test1234";

fn generate_code_grant_pkce_auth_config() -> sccache::config::DistAuth {
    sccache::config::DistAuth::Oauth2CodeGrantPKCE {
        client_id: "Xmbl6zRW1o1tJ5LQOz0p65NwY47aMO7A".to_owned(),
        auth_url:
            "https://sccache-test.auth0.com/authorize?audience=https://sccache-dist-test-api/"
                .to_owned(),
        token_url: "https://sccache-test.auth0.com/oauth/token".to_owned(),
    }
}
fn generate_implicit_auth_config() -> sccache::config::DistAuth {
    sccache::config::DistAuth::Oauth2Implicit {
        client_id: "TTborSAyjBnSi1W11201ZzNu9gSg63bq".to_owned(),
        auth_url:
            "https://sccache-test.auth0.com/authorize?audience=https://sccache-dist-test-api/"
                .to_owned(),
    }
}

fn config_with_dist_auth(
    tmpdir: &Path,
    auth_config: sccache::config::DistAuth,
) -> sccache::config::FileConfig {
    sccache::config::FileConfig {
        cache: Default::default(),
        dist: sccache::config::DistConfig {
            auth: auth_config,
            scheduler_url: None,
            cache_dir: tmpdir.join("unused-cache"),
            toolchains: vec![],
            toolchain_cache_size: 0,
            rewrite_includes_only: true,
        },
    }
}

fn sccache_command() -> Command {
    Command::new(assert_cmd::cargo::cargo_bin("sccache"))
}

fn retry<F: FnMut() -> Option<T>, T>(interval: Duration, until: Duration, mut f: F) -> Option<T> {
    let start = Instant::now();
    while start.elapsed() < until {
        if let Some(res) = f() {
            return Some(res);
        } else {
            thread::sleep(interval)
        }
    }
    None
}

trait DriverExt {
    fn wait_for_element(&self, selector: &str) -> Result<(), ()>;
    fn wait_on_url<F: Fn(&str) -> bool>(&self, condition: F) -> Result<(), ()>;
}
impl DriverExt for WebDriver {
    fn wait_for_element(&self, selector: &str) -> Result<(), ()> {
        retry(BROWSER_RETRY_WAIT, BROWSER_MAX_WAIT, || {
            self.find_element(Selector::CSS, selector).ok()
        })
        .map(|_| ())
        .ok_or(())
    }
    fn wait_on_url<F: Fn(&str) -> bool>(&self, condition: F) -> Result<(), ()> {
        let start = Instant::now();
        while start.elapsed() < BROWSER_MAX_WAIT {
            match self.get_current_url() {
                Ok(ref url) if condition(&url) => return Ok(()),
                Ok(_) | Err(_) => thread::sleep(BROWSER_RETRY_WAIT),
            }
        }
        Err(())
    }
}

// With reference to https://github.com/mozilla-iam/cis_tests/blob/ef7740b/pages/auth0.py
fn auth0_login(driver: &WebDriver, email: &str, password: &str) {
    driver.wait_for_element(USERNAME_SELECTOR).unwrap();
    thread::sleep(Duration::from_secs(1)); // Give the element time to get ready
    driver
        .find_element(Selector::CSS, USERNAME_SELECTOR)
        .unwrap()
        .type_text(email)
        .unwrap();
    driver
        .find_element(Selector::CSS, PASSWORD_SELECTOR)
        .unwrap()
        .type_text(password)
        .unwrap();
    driver
        .find_element(Selector::CSS, LOGIN_SELECTOR)
        .unwrap()
        .click()
        .unwrap();
}

struct SeleniumContainer {
    cid: String,
}

fn check_output(output: &Output) {
    if !output.status.success() {
        println!(
            "===========\n{}\n==========\n\n\n\n=========\n{}\n===============\n\n\n",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        panic!()
    }
}

impl SeleniumContainer {
    fn new() -> Self {
        // https://github.com/SeleniumHQ/docker-selenium#running-the-images
        let cid = {
            // It's important to use net=host so that selenium can see pages hosted on localhost
            let args = &[
                "run",
                "--rm",
                "-d",
                "-v",
                "/dev/shm:/dev/shm",
                "--net",
                "host",
                "-e",
                "SE_OPTS=-debug",
                "selenium/standalone-chrome-debug:3.14.0",
            ];
            let output = Command::new("docker").args(args).output().unwrap();
            check_output(&output);
            let stdout = String::from_utf8(output.stdout).unwrap();
            stdout.trim().to_owned()
        };
        SeleniumContainer { cid }
    }
}

impl Drop for SeleniumContainer {
    fn drop(&mut self) {
        let Output { stdout, stderr, .. } = Command::new("docker")
            .args(&["logs", &self.cid])
            .output()
            .unwrap();
        let output = Command::new("docker")
            .args(&["kill", &self.cid])
            .output()
            .unwrap();

        println!(
            "====\n> selenium container <:\n## STDOUT\n{}\n\n## STDERR\n{}\n====",
            String::from_utf8_lossy(&stdout),
            String::from_utf8_lossy(&stderr)
        );
        check_output(&output)
    }
}

#[test]
#[cfg_attr(
    not(all(target_os = "linux", target_arch = "x86_64", feature = "dist-tests")),
    ignore
)]
fn test_auth() {
    // Make sure the client auth port isn't in use, as sccache will gracefully fall back
    let client_auth_port = sccache::dist::client_auth::VALID_PORTS[0];
    assert_eq!(
        TcpStream::connect(("localhost", client_auth_port))
            .unwrap_err()
            .kind(),
        io::ErrorKind::ConnectionRefused
    );

    // NOTE: if you want to debug selenium, you can comment out the three lines below and just use a local
    // selenium instance (download the standalone server and the chrome driver, running the former and putting the
    // latter on the PATH). Alternatively, because we use the '-debug' image you can use vnc with the password 'secret'.
    assert_eq!(
        TcpStream::connect(("localhost", 4444)).unwrap_err().kind(),
        io::ErrorKind::ConnectionRefused
    );
    let _selenium = SeleniumContainer::new();
    thread::sleep(Duration::from_secs(3));

    // Code grant PKCE
    println!("Testing code grant pkce auth");
    test_auth_with_config(generate_code_grant_pkce_auth_config());

    // Implicit
    println!("Testing implicit auth");
    test_auth_with_config(generate_implicit_auth_config());
}

fn test_auth_with_config(dist_auth: sccache::config::DistAuth) {
    let conf_dir = tempfile::Builder::new()
        .prefix("sccache-test-conf")
        .tempdir()
        .unwrap();
    let sccache_config = config_with_dist_auth(conf_dir.path(), dist_auth);
    let sccache_config_path = conf_dir.path().join("sccache-config.json");
    fs::File::create(&sccache_config_path)
        .unwrap()
        .write_all(&serde_json::to_vec(&sccache_config).unwrap())
        .unwrap();
    let sccache_cached_config_path = conf_dir.path().join("sccache-cached-config");
    let envs = vec![
        ("RUST_LOG", "sccache=trace".into()),
        ("SCCACHE_CONF", sccache_config_path.into_os_string()),
        (
            "SCCACHE_CACHED_CONF",
            sccache_cached_config_path.clone().into_os_string(),
        ),
    ];

    println!("Starting sccache --dist-auth");
    let mut sccache_process = sccache_command()
        .arg("--dist-auth")
        .envs(envs)
        .stdin(Stdio::null())
        .spawn()
        .unwrap();
    thread::sleep(Duration::from_secs(1)); // let the http server start up
    println!("Beginning in-browser auth");
    login();
    let status = retry(Duration::from_secs(1), Duration::from_secs(10), || {
        sccache_process.try_wait().unwrap()
    });
    match status {
        Some(s) => assert!(s.success()),
        None => {
            sccache_process.kill().unwrap();
            panic!("Waited too long for process to exit")
        }
    }
    println!("Validating cached config");
    let mut cached_config_bytes = vec![];
    fs::File::open(sccache_cached_config_path)
        .unwrap()
        .read_to_end(&mut cached_config_bytes)
        .unwrap();
    let cached_config: sccache::config::CachedFileConfig =
        toml::from_slice(&cached_config_bytes).unwrap();
    assert_eq!(cached_config.dist.auth_tokens.len(), 1);
}

fn login() {
    let mut driver = WebDriver::new(Browser::Chrome);
    driver.start_session().unwrap();
    println!("Started browser session");

    driver.navigate(LOCAL_AUTH_BASE_URL).unwrap();
    driver
        .wait_on_url(|url| url != LOCAL_AUTH_BASE_URL)
        .unwrap();
    auth0_login(&driver, TEST_USERNAME, TEST_PASSWORD);
    driver
        .wait_on_url(|url| url.starts_with(LOCAL_AUTH_BASE_URL))
        .unwrap();
    // Let any final JS complete
    thread::sleep(Duration::from_secs(1));
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.resourcemover.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Security Rule data model for Network Security Groups. */
@Fluent
public final class NsgSecurityRule {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(NsgSecurityRule.class);

    /*
     * Gets or sets the Security rule name.
     */
    @JsonProperty(value = "name")
    private String name;

    /*
     * Gets or sets whether network traffic is allowed or denied.
     * Possible values are "Allow" and "Deny".
     */
    @JsonProperty(value = "access")
    private String access;

    /*
     * Gets or sets a description for this rule. Restricted to 140 chars.
     */
    @JsonProperty(value = "description")
    private String description;

    /*
     * Gets or sets destination address prefix. CIDR or source IP range.
     * A "*" can also be used to match all source IPs. Default tags such
     * as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be
     * used.
     */
    @JsonProperty(value = "destinationAddressPrefix")
    private String destinationAddressPrefix;

    /*
     * Gets or sets Destination Port or Range. Integer or range between
     * 0 and 65535. A "*" can also be used to match all ports.
     */
    @JsonProperty(value = "destinationPortRange")
    private String destinationPortRange;

    /*
     * Gets or sets the direction of the rule.InBound or Outbound. The
     * direction specifies if rule will be evaluated on incoming or outgoing
     * traffic.
     */
    @JsonProperty(value = "direction")
    private String direction;

    /*
     * Gets or sets the priority of the rule. The value can be between
     * 100 and 4096. The priority number must be unique for each rule in the
     * collection.
     * The lower the priority number, the higher the priority of the rule.
     */
    @JsonProperty(value = "priority")
    private Integer priority;

    /*
     * Gets or sets Network protocol this rule applies to. Can be Tcp, Udp or
     * All(*).
     */
    @JsonProperty(value = "protocol")
    private String protocol;

    /*
     * Gets or sets source address prefix. CIDR or source IP range. A
     * "*" can also be used to match all source IPs.  Default tags such as
     * 'VirtualNetwork',
     * 'AzureLoadBalancer' and 'Internet' can also be used. If this is an
     * ingress
     * rule, specifies where network traffic originates from.
     */
    @JsonProperty(value = "sourceAddressPrefix")
    private String sourceAddressPrefix;

    /*
     * Gets or sets Source Port or Range. Integer or range between 0 and
     * 65535. A "*" can also be used to match all ports.
     */
    @JsonProperty(value = "sourcePortRange")
    private String sourcePortRange;

    /**
     * Get the name property: Gets or sets the Security rule name.
     *
     * @return the name value.
     */
    public String name() {
        return this.name;
    }

    /**
     * Set the name property: Gets or sets the Security rule name.
     *
     * @param name the name value to set.
     * @return the NsgSecurityRule object itself.
     */
    public NsgSecurityRule withName(String name) {
        this.name = name;
        return this;
    }

    /**
     * Get the access property: Gets or sets whether network traffic is allowed or denied. Possible values are "Allow"
     * and "Deny".
     *
     * @return the access value.
     */
    public String access() {
        return this.access;
    }

    /**
     * Set the access property: Gets or sets whether network traffic is allowed or denied. Possible values are "Allow"
     * and "Deny".
     *
     * @param access the access value to set.
     * @return the NsgSecurityRule object itself.
     */
    public NsgSecurityRule withAccess(String access) {
        this.access = access;
        return this;
    }

    /**
     * Get the description property: Gets or sets a description for this rule. Restricted to 140 chars.
     *
     * @return the description value.
     */
    public String description() {
        return this.description;
    }

    /**
     * Set the description property: Gets or sets a description for this rule. Restricted to 140 chars.
     *
     * @param description the description value to set.
     * @return the NsgSecurityRule object itself.
     */
    public NsgSecurityRule withDescription(String description) {
        this.description = description;
        return this;
    }

    /**
     * Get the destinationAddressPrefix property: Gets or sets destination address prefix. CIDR or source IP range. A
     * "*" can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and
     * 'Internet' can also be used.
     *
     * @return the destinationAddressPrefix value.
     */
    public String destinationAddressPrefix() {
        return this.destinationAddressPrefix;
    }

    /**
     * Set the destinationAddressPrefix property: Gets or sets destination address prefix. CIDR or source IP range. A
     * "*" can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and
     * 'Internet' can also be used.
     *
     * @param destinationAddressPrefix the destinationAddressPrefix value to set.
     * @return the NsgSecurityRule object itself.
     */
    public NsgSecurityRule withDestinationAddressPrefix(String destinationAddressPrefix) {
        this.destinationAddressPrefix = destinationAddressPrefix;
        return this;
    }

    /**
     * Get the destinationPortRange property: Gets or sets Destination Port or Range. Integer or range between 0 and
     * 65535. A "*" can also be used to match all ports.
     *
     * @return the destinationPortRange value.
     */
    public String destinationPortRange() {
        return this.destinationPortRange;
    }

    /**
     * Set the destinationPortRange property: Gets or sets Destination Port or Range. Integer or range between 0 and
     * 65535. A "*" can also be used to match all ports.
     *
     * @param destinationPortRange the destinationPortRange value to set.
     * @return the NsgSecurityRule object itself.
     */
    public NsgSecurityRule withDestinationPortRange(String destinationPortRange) {
        this.destinationPortRange = destinationPortRange;
        return this;
    }

    /**
     * Get the direction property: Gets or sets the direction of the rule.InBound or Outbound. The direction specifies
     * if rule will be evaluated on incoming or outgoing traffic.
     *
     * @return the direction value.
     */
    public String direction() {
        return this.direction;
    }

    /**
     * Set the direction property: Gets or sets the direction of the rule.InBound or Outbound. The direction specifies
     * if rule will be evaluated on incoming or outgoing traffic.
     *
     * @param direction the direction value to set.
     * @return the NsgSecurityRule object itself.
     */
    public NsgSecurityRule withDirection(String direction) {
        this.direction = direction;
        return this;
    }

    /**
     * Get the priority property: Gets or sets the priority of the rule. The value can be between 100 and 4096. The
     * priority number must be unique for each rule in the collection. The lower the priority number, the higher the
     * priority of the rule.
     *
     * @return the priority value.
     */
    public Integer priority() {
        return this.priority;
    }

    /**
     * Set the priority property: Gets or sets the priority of the rule. The value can be between 100 and 4096. The
     * priority number must be unique for each rule in the collection. The lower the priority number, the higher the
     * priority of the rule.
     *
     * @param priority the priority value to set.
     * @return the NsgSecurityRule object itself.
     */
    public NsgSecurityRule withPriority(Integer priority) {
        this.priority = priority;
        return this;
    }

    /**
     * Get the protocol property: Gets or sets Network protocol this rule applies to. Can be Tcp, Udp or All(*).
     *
     * @return the protocol value.
     */
    public String protocol() {
        return this.protocol;
    }

    /**
     * Set the protocol property: Gets or sets Network protocol this rule applies to. Can be Tcp, Udp or All(*).
     *
     * @param protocol the protocol value to set.
     * @return the NsgSecurityRule object itself.
     */
    public NsgSecurityRule withProtocol(String protocol) {
        this.protocol = protocol;
        return this;
    }

    /**
     * Get the sourceAddressPrefix property: Gets or sets source address prefix. CIDR or source IP range. A "*" can also
     * be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can
     * also be used. If this is an ingress rule, specifies where network traffic originates from.
     *
     * @return the sourceAddressPrefix value.
     */
    public String sourceAddressPrefix() {
        return this.sourceAddressPrefix;
    }

    /**
     * Set the sourceAddressPrefix property: Gets or sets source address prefix. CIDR or source IP range. A "*" can also
     * be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can
     * also be used. If this is an ingress rule, specifies where network traffic originates from.
     *
     * @param sourceAddressPrefix the sourceAddressPrefix value to set.
     * @return the NsgSecurityRule object itself.
     */
    public NsgSecurityRule withSourceAddressPrefix(String sourceAddressPrefix) {
        this.sourceAddressPrefix = sourceAddressPrefix;
        return this;
    }

    /**
     * Get the sourcePortRange property: Gets or sets Source Port or Range. Integer or range between 0 and 65535. A "*"
     * can also be used to match all ports.
     *
     * @return the sourcePortRange value.
     */
    public String sourcePortRange() {
        return this.sourcePortRange;
    }

    /**
     * Set the sourcePortRange property: Gets or sets Source Port or Range. Integer or range between 0 and 65535. A "*"
     * can also be used to match all ports.
     *
     * @param sourcePortRange the sourcePortRange value to set.
     * @return the NsgSecurityRule object itself.
     */
    public NsgSecurityRule withSourcePortRange(String sourcePortRange) {
        this.sourcePortRange = sourcePortRange;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}